It is mandatory that the system be initialized before any other library routines are called.
int G_gisinit() initialize gis library This routine reads the user's GRASS environment file into memory and makes sure that the user has selected a valid database and mapset. It also initializes hidden variables used by other routines. If the user's database information is invalid, an error message is printed and the module exits. The program_name is stored for later recall by G_program_name. It is recommended that argv[0] be used for the program_name: \verbatim int main (int argc, char **argv) { G_gisinit(argv[0]); } \endverbatim \subsection diag Diagnostic Messages The following routines are used by other routines in the library to report warning and error messages. They may also be used directly by GRASS programs.
int G_fatal_error() print error message and exit
int G_debug() print debug message
int G_warning() print warning message and continue These routines report errors to the user. The normal mode is to write the message to the screen (on the standard error output) and wait a few seconds. G_warning() will return and G_fatal_error() will exit.
If the standard error output is not a tty device, then the message is mailed to the user instead.
If the file GIS_ERROR_LOG exists (with write permission), in either the user's home directory or in the $GISBASE directory, the messages will also be logged to this file.
While most applications will find the normal error reporting quite adequate, there will be times when different handling is needed. For example, graphics modules may want the messages displayed graphically instead of on the standard error output. If the programmer wants to handle the error messages differently, the following routines can be used to modify the error handling:
int G_set_error_routine() change error handling This routine provides a different error handler for G_fatal_error() and G_warning(). The handler routine must be defined as follows: \verbatim int handler (char *message, int fatal) \endverbatim
where message is the message to be handled and fatal indicates the type of error: 1 (fatal error) or 0 (warning).
Note. The handler only provides a way to send the message somewhere other than to the error output. If the error is fatal, the module will exit after the handler returns.
int G_unset_error_routine() reset normal error handling This routine resets the error handling for G_fatal_error() and G_warning() back to the default action.
int G_sleep_on_error() sleep on error? If flag is 0, then no pause will occur after printing an error or warning message. Otherwise the pause will occur.
int G_suppress_warnings() suppress warnings? If flag is 0, then G_warning() will no longer print warning messages. If flag is 1, then G_warning() will print warning messages.
Note. This routine has no effect on G_fatal_error(). \subsection envir Environment and Database Information
The following routines return information about the current database selected by the user. Some of this information is retrieved from the user's GRASS environment file. Some of it comes from files in the database itself. See \ref Environment_Variables for a discussion of the GRASS environment.
The following four routines can be used freely by the programmer:
char * G_location() current location name Returns the name of the current database location. This routine should be used by modules that need to display the current location to the user. See \ref Locations for an explanation of locations.
char * G_mapset() current mapset name Returns the name of the current mapset in the current location. This routine is often used when accessing files in the current mapset. See Mapsets for an explanation of mapsets.
char * G_myname() location title Returns a one line title for the database location. This title is read from the file MYNAME in the PERMANENT mapset. See also \ref Permanent_Mapset for a discussion of the PERMANENT mapset.
char * G_gisbase() top level module directory Returns the full path name of the top level directory for GRASS programs. This directory will have subdirectories which will contain modules and files required for the running of the system. Some of these directories are: \verbatim bin commands run by the user etc modules and data files used by GRASS commands html help files \endverbatim
The use of G_gisbase() to find these subdirectories enables GRASS modules to be written independently of where the GRASS system is actually installed on the machine. For example, to run the module sroff in the GRASS etc directory: \verbatim char command[200]; sprintf (command, "%s/etc/sroff", G_gisbase() ); system (command); \endverbatim
The following two routines return full path UNIX directory names. They should be used only in special cases. They are used by other routines in the library to build full UNIX file names for database files. The programmer should not use the next two routines to bypass the normal database access routines.
char * G_gisdbase() top level database directory Returns the full UNIX path name of the directory which holds the database locations. See \ref GISDBASE for a full explanation of this directory.
char * G_location_path() current location directory Returns the full UNIX path name of the current database location. For example, if the user is working in location spearfish in the /home/user/grassdata database directory, this routine will return a string which looks like
/home/user/grassdata/spearfish.
These next routines provide the low-level management of the information in the user's GRASS environment file. They should not be used in place of the higher level interface routines described above.
int G_getenv() query GRASS environment variable
int G__getenv() query GRASS environment variable These routines look up the variable name in the GRASS environment and return its value (which is a character string). If name is not set, G_getenv() issues an error message and calls exit(). G__setenv() just returns the NULL pointer.
int G_setenv () set GRASS environment variable
int G__setenv() set GRASS environment variable These routines set the the GRASS environment variable name to value. If value is NULL, the name is unset.
Both routines set the value in module memory, but only G_setenv() writes the new value to the user's GRASS environment file. \subsection dbaseaccess Fundamental Database Access Routines
The routines described in this section provide the low-level interface to the GRASS database. They search the database for files, prompt the user for file names, open files for reading or writing, etc. The programmer should never bypass this level of database interface. These routines must be used to access the GRASS database unless there are other higher level library routines which perform the same function. For example, routines to process raster files (Raster_File_Processing), vector files (Vector_File_Processing), etc., should be used instead.
In the descriptions below, the term database element is used. Elements are subdirectories within a mapset and are associated with a specific GRASS data type. For example, raster files live in the "cell" and "fcell" element. See \ref Elements for more details. \subsection prompt Prompting for Database Files
The following routines interactively prompt the user for a file name from a specific database element. (See \ref Elements for an explanation of elements.) In each, the prompt string will be printed as the first line of the full prompt which asks the user to enter a file name. If prompt is the empty string "" then an appropriate prompt will be substituted. The name that the user enters is copied into the name buffer. The size of name should be large enough to hold any GRASS file name. Most systems allow file names to be quite long. It is recommended that name be declared char name[GNAME_MAX]. The short (one or two word) label describing the element is used as part of a title when listing the files in element.
The user is required to enter a valid file name, or else hit the RETURN key to cancel the request. If the user enters an invalid response, a message is printed, and the user is prompted again. If the user cancels the request, the NULL pointer is returned. Otherwise the mapset where the file lives or is to be created is returned. Both the name and the mapset are used in other routines to refer to the file.
An example will be given here. The G_ask_old() routine used in the example is described a bit later. The user is asked to enter a file from the "paint/labels" element: \verbatim char name[GNAME_MAX]; char *mapset; mapset = G_ask_old("", name, "paint/labels", "labels"); if (mapset == NULL) exit(EXIT_SUCCESS); /* user canceled the request */ \endverbatim
The user will see the following: \verbatim Enter the name of an existing labels file Enter 'list' for a list of existing labels files Hit RETURN to cancel request \endverbatim The last line of the prompt can be modified using G_set_ask_return_msg().
char * G_ask_old() prompt for existing database file The user is asked to enter the name of an existing database file.
Note. This routine looks for the file in the current mapset as well as other mapsets. The mapsets that are searched are determined from the user's mapset search path. See \ref Mapset_Search_Path for some more details about the search path.
char * G_ask_new() prompt for new database file The user is asked to enter the name of a new file which does not exist in the current mapset.
Note. The file chosen by the user may exist in other mapsets. This routine does not look in other mapsets, since the assumption is that name will be used to create a new file. New files are always created in the current mapset.
char * G_ask_in_mapset() prompt for existing database file The user is asked to enter the name of an file which exists in the current mapset.
Note. The file chosen by the user may or may not exist in other mapsets. This routine does not look in other mapsets, since the assumption is that name will be used to modify a file. GRASS only permits users to modify files in the current mapset.
char * G_ask_any() prompt for any valid file name The user is asked to enter any legal file name. If warn is 1 and the file chosen exists in the current mapset, then the user is asked if it is ok to overwrite the file. If warn is 0, then any leg al name is accepted and no warning is issued to the user if the file exists.
int G_set_ask_return_msg() set Hit RETURN msg The "Hit RETURN to cancel request" part of the prompt in the prompting routines described above, is modified to "Hit RETURN msg."
char * G_get_ask_return_msg() get Hit RETURN msg The current msg (as set by G_set_ask_return_msg()) is returned. \subsection Fully_Qualified_File_Names Fully Qualified File Names All GRASS routines which access database files must be given both the file name and the mapset where the file resides. Often the name and the mapset are 2 distinct character strings. However, there is a need for a single character string which contains both the name and the mapset (e.g., for interactive interfacing to command-line programs). This form of the name is known as the fully qualified file name and is built by the following routine:
char * G_fully_qualified_name() fully qualified file name Returns a fully qualified name for the file name in mapset. Currently this string is in the form name@mapset, but the programmer should pretend not to know this and always call this routine to get the fully qualified name.
The following example shows how an interactive version of d.rast
interfaces with the command-line version of d.rast:
\verbatim
#include
The following routines search the database for files:
char * G_find_file() find a
database file
Look for the file name under the specified element in
the database. The mapset parameter can either be the empty
string "", which means search all the mapsets in the user's current
mapset search path, or it can be a specific mapset, which means
. look for the file only in this one mapset (for example, in
the current mapset).
If found, the mapset where the file lives is returned. If not found,
the NULL pointer is returned.
If the user specifies a fully qualified file name, (i.e, a name that also
contains the mapset; see \ref Fully_Qualified_File_Names) then
G_find_file() modifies name by eliminating the mapset
from the name
For example, to find a "paint/labels" file anywhere in the database:
\verbatim
char name[GNAME_MAX];
char *mapset;
if ((mapset = G_find_file("paint/labels",name,"")) == NULL)
/* not found */
\endverbatim
To check that the file exists in the current mapset:
\verbatim
char name[GNAME_MAX];
if (G_find_file("paint/labels",name,G_mapset()) == NULL)
/* not found */
\endverbatim
\subsection Legal_File_Names Legal File Names
Not all names that a user may enter will be legal files for the GRASS
databases. The routines which create new files require that the new
file have a legal name. The routines which prompt the user for file
names (e.g., G_ask_new()) guarantee that the name entered by
the user will be legal. If the name is obtained from the command
line, for example, the programmer must check that the name is
legal. The following routine checks for legal file names:
int G_legal_filename() check for legal database file
names
Returns 1 if name is ok, -1 otherwise.
\subsection Opening_an_Existing_Database_File_for_Reading Opening an Existing Database File for Reading
The following routines open the file name in mapset from
the specified database element for reading (but not for
writing). The file name and mapset can be obtained
interactively using G_ask_old(), and noninteractively using
G_find_file().
int G_open_old() open a database file for reading
The database file name under the
element in the specified mapset is opened for reading (but
not for writing).
The UNIX open() routine is used to open the file. If the file does not exist,
-1 is returned. Otherwise the file descriptor from the open() is returned.
FILE * G_fopen_old() open a database file for reading
The database file name under the
element in the specified mapset is opened for reading (but
not for writing).
The UNIX fopen() routine, with "r" read mode, is used to open the
file. If the file does not exist, the NULL pointer is
returned. Otherwise the file descriptor from the fopen() is returned.
\subsection Opening_an_Existing_Database_File_for_Update Opening an Existing Database File for Update
The following routines open the file name in the current mapset
from the specified database element for writing. The file must
exist. Its name can be obtained interactively using
G_ask_in_mapset(), and noninteractively using G_find_file().
int G_open_update() open a database file for update
The database file name under the element in the
current mapset is opened for reading and writing.
The UNIX open() routine is used to open the file. If the file does not exist,
-1 is returned. Otherwise the file is positioned at the end of the file and
the file descriptor from the open() is returned.
int G_fopen_append() open a database file for update
The database file name under the element in the current
mapset is opened for appending (but not for reading).
The UNIX fopen() routine, with "a" append mode, is used to open the
file. If the file does not exist, the NULL pointer is
returned. Otherwise the file is positioned at the end of the file and
the file descriptor from the fopen() is returned.
\subsection Creating_and_Opening_a_New_Database_File Creating and Opening a New Database File
The following routines create the new file name in the current
mapset (GRASS does not allow files to be created outside the current
mapset; see \ref Database_Access_Rules) under the specified database
element and open it for writing. The database element is
created, if it does not already exist.
The file name should be obtained interactively using
G_ask_new(). If obtained noninteractively (e.g., from the
command line), G_legal_filename() should be called first to
make sure that name is a valid GRASS file name. Warning.
It is not an error for name to already exist. However, the file
will be removed and recreated empty. The interactive routine
G_ask_new() guarantees that name will not exist, but if
name is obtained from the command line, name may
exist. In this case G_find_file() could be used to see if
name exists.
int G_open_new() open a new database file
The database file name under the element in the current
mapset is created and opened for writing (but not reading).
The UNIX open() routine is used to open the file. If the file does not
exist, -1 is returned. Otherwise the file is positioned at the end of
the file and the file descriptor from the open() is returned.
FILE * G_fopen_new() open a new database file
The database file name under the element in the current
mapset is created and opened for writing (but not reading).
The UNIX fopen() routine, with "w" write mode, is used to open the
file. If the file does not exist, the NULL pointer is
returned. Otherwise the file is positioned at the end of the file and
the file descriptor from the fopen() is returned.
\subsection Database_File_Management Database File Management
The following routines allow the renaming and removal of database
files in the current mapset (These functions only apply to the current
mapset since GRASS does permit users to modify things in mapsets other
than the current mapset; see \ref Database_Access_Rules).
int G_rename() rename a database
file
The file or directory old under the database element
directory in the current mapset is renamed to new.
Returns 1 if successful, 0 if old does not exist, and -1 if
there was an error.
Bug. This routine does not check to see if the new name is a
valid database file name.
int G_remove() remove a database file
The file or directory name under the database element directory
in the current mapset is removed.
Returns 1 if successful, 0 if name does not exist, and -1 if
there was an error.
Note. If name is a directory, everything within the
directory is removed as well.
Note. These functions only apply to the specific element
and not to other "related" elements. For example, if element is
"cell", then the specified raster file will be removed (or renamed),
but the other support files, such as "cellhd" or "cats", will not. To
remove these other files as well, specific calls must be made for each
related element.
\subsection Memory_Allocation Memory Allocation
The following routines provide memory allocation capability. They are
simply calls to the UNIX suite of memory allocation routines malloc(),
realloc() and calloc(), except that if there is not enough memory,
they print a diagnostic message to that effect and then call exit().
Note. Use the G_free() routine to release memory allocated by these
routines.
int G_free() free the memory allocated
Free the memory allocated by the GRASS malloc routines.
void * G_malloc () memory allocation
Allocates a block of memory at least size bytes which is
aligned properly for all data types. A pointer to the aligned block is
returned.
void * G_realloc() memory allocation
Changes the size of a previously allocated block of memory at
ptr and returns a pointer to the new block of memory. The
size may be larger or smaller than the original size. If the
original block cannot be extended "in place", then a new block is
allocated and the original block copied to the new block.
Note. If ptr is NULL, then this routine simply allocates
a block of size bytes. This routine works around broken
realloc() routines, which do not handle a NULL ptr.
void * G_calloc() memory allocation
Allocates a properly aligned block of memory n*size
bytes in length, initializes the allocated memory to zero, and returns
a pointer to the allocated block of memory.
Note. Allocating memory for reading and writing raster files is
discussed in Allocating_Raster_I_O_Buffers.
double * G_alloc_vector() memory allocation
Allocate a vector (array) of n doubles initialized to zero.
float * G_alloc_fvector() memory allocation
Allocate a vector (array) of n floats initialized to zero.
double ** G_alloc_matrix() memory allocation
Allocate a matrix of rows by cols doubles initialized to
zero.
float ** G_alloc_fmatrix() memory allocation
Allocate a matrix of rows by cols floats initialized to
zero.
int G_free_vector() memory deallocation
Deallocate a vector (array) of doubles or floats.
int G_free_matrix() memory deallocation
Deallocate a matrix of doubles.
int G_free_fmatrix() memory deallocation
Deallocate a matrix of floats.
\subsection The_Region The Region
The region concept is explained in Region. It can be thought of as a
two-dimensional matrix with known boundaries and rectangular cells.
There are logically two different regions. The first is the database
region that the user has set in the current mapset. The other is the
region that is active in the module. This active module region is what
controls reading and writing of raster file data. The
vector map export does not take care for the active region settings.
The routines described below use a GRASS data structure
Cell_head to hold region information. This structure is defined
in the "gis.h" header file. It is discussed in detail under
GIS_Library_Data_Structures .
\subsection The_Database_Region The Database Region
Reading and writing the user's database region are done by the
following routines:
[Note: Previous versions of GRASS called this the "window". Due to
overuse of this term (database window, graphics window, etc.), the
term was changed to "region". However, to maintain compatibility with
existing programs, library routine names were not changed - hence the
term "window" is used in the routine name (where "region" should
probably be used instead.)]
int G_get_window() read the database region
Reads the database region as stored in the WIND file in the user's
current mapset into region.
An error message is printed and exit() is called if there is a problem
reading the region.
Note. GRASS applications that read or write raster files should
not use this routine since its use implies that the active module
region will not be used. Programs that read or write raster file data
(or vector data) can query the active module region using
G_window_rows() and G_window_cols().
int G_put_window() write the database region
Writes the database region file (WIND) in the user's current mapset
from region. Returns 1 if the region is written ok. Returns -1
if not (no diagnostic message is printed).
Warning. Since this routine actually changes the database
region, it should only be called by modules which the user knows will
change the region. It is probably fair to say that under GRASS 3.0
only the g.region, and d.zoom modules should call this
routine.
There is another database region. This region is the default region
for the location. The default region provides the user with a
"starting" region, i.e., a region to begin with and return to as a
reference point. The GRASS modules g.region allow the user to
set their database region from the default region. (See
Permanent_Mapset for a discussion of the default region.) The
following routine reads this region:
int G_get_default_window() read the default
region
Reads the default region for the location into region.
An error message is printed and exit() is called if there is a problem
reading the default region.
\subsection The_Active_Module_Region The Active Module Region
The active module region is the one that is used when reading and
writing raster file data. This region determines the resampling when
reading raster data. It also determines the extent and resolution of
new raster files.
Initially the active module region and the user's database region are
the same, but the programmer can make them different. The following
routines manage the active module region.
int G_window_rows() number of rows in active region
int G_window_cols() number of columns in active region
These routines return the number of rows and columns (respectively) in
the active module region. Before raster files can be read or written,
it is necessary to known how many rows and columns are in the active
region. For example:
\verbatim
int nrows, cols;
int row, col;
nrows = G_window_rows();
ncols = G_window_cols();
for (row = 0; row < nrows; row++){
read row ...
for (col = 0; col < ncols; col++){
process col ...
}
}
\endverbatim
int G_set_window() set the active region
This routine sets the active region from region. Setting the
active region does not change the WIND file in the database. It simply
changes the region for the duration of the module.
However, the new region setting is not retained across the UNIX exec()
call. This implies that G_set_window() cannot be used to set the
region for a module to be executed using the system() or popen()
routines.
A warning message is printed and -1 returned if region is not
valid. Otherwise 1 is returned.
Note. This routine overrides the region as set by the user. Its
use should be very limited since it changes what the user normally
expects to happen. If this routine is not called, then the active
region will be the same as what is in the user's WIND file.
Warning. Calling this routine with already opened raster files
has some side effects. If there are raster files which are open for
reading, they will be read into the newly set region, not the region
that was active when they were opened. However, CELL buffers allocated
for reading the raster files are not automatically reallocated. The
module must reallocate them explicitly. Also, this routine does not
change the region for raster files which are open for writing. The
region that was active when the open occurred still applies to these
files.
int G_get_set_window() get the active region
Gets the values of the currently active region into region. If
G_set_window() has been called, then the values set by that call
are retrieved. Otherwise the user's database region is retrieved.
Note. For modules that read or write raster data, and really
need the full region information, this routine is preferred over
G_get_window(). However, since G_window_rows() and G_window_cols()
return the number of rows and columns in the active region, the
programmer should consider whether or not the full region information
is really needed before using this routine.
char * G_align_window() align two regions
Modifies the input region to align to the ref
region. The resolutions in region are set to match those in
ref and the region edges (north, south, east, west) are
modified to align with the grid of the ref region.
The region may be enlarged if necessary to achieve the
alignment. The north is rounded northward, the south southward, the
east eastward and the west westward.
This routine returns NULL if ok, otherwise it returns an error message.
double G_col_to_easting() column to easting
Converts a column relative to a region to an easting;
Note. col is a double: col+0.5 will return the easting for the
center of the column; col+0.0 will return the easting for the western
edge of the column; and col+1.0 will return the easting for the
eastern edge of the column.
double G_row_to_northing() row to northing
Converts a row relative to a region to a northing;
Note. row is a double: row+0.5 will return the northing for the
center of the row; row+0.0 will return the northing for the northern
edge of the row; and row+1.0 will return the northing for the southern
edge of the row.
double G_easting_to_col() easting to column
Converts an easting relative to a region to a column.
Note. The result is a double. Casting it to an integer will
give the column number.
double G_northing_to_row() northing to row
Converts a northing relative to a region to a row.
Note. the result is a double. Casting it to an integer will
give the row number.
\subsection Projection_Information Projection Information
The following routines return information about the cartographic
projection and zone. See \ref Region for more information about these
values.
int G_projection() query cartographic projection
This routine returns a code indicating the projection for the active
region. The current values are:
0 unreferenced x,y (imagery data)
char * G_database_projection_name() query cartographic projection
Returns a pointer to a string which is a printable name for projection
code proj (as returned by G_projection()). Returns NULL if
proj is not a valid projection.
char * G_database_unit_name() database units
Returns a string describing the database grid units. It returns a
plural form (eg. feet) if plural is true. Otherwise it returns
a singular form (eg. foot).
double G_database_units_to_meters_factor() conversion to
meters
Returns a factor which converts the grid unit to meters (by
multiplication). If the database is not metric (eg. imagery) then 0.0
is returned.
int G_zone() query cartographic zone
This routine returns the zone for the active region. The meaning for
the zone depends on the projection. For example zone 18 for projection
type 1 would be UTM zone 18.
\subsection Latitude_Longitude_Databases Latitude-Longitude Databases
GRASS supports databases in a longitude-latitude grid using a
projection where the x coordinate is the longitude and the y
coordinate is the latitude. This projection is called the Equidistant
Cylindrical Projection (also known as Plate Carree). ECP has the
property that where am I and row-column calculations are
identical to those in planimetric grids (like UTM, Universal
Transverse Mercator Projection). This implies that normal GRASS
registration and overlay functions will work without any special
considerations or modifications to existing code. However, the
projection is not planimetric. This means that distance and area
calculations are no longed Euclidean.
Also, since the world is round, maps may not have edges in the
east-west direction, especially for global databases. Maps may have
the same longitude at both the east and west edges of the
display. This feature, called global wraparound, must be accounted for
by GRASS modules (particularly vector based functions, like plotting.)
What follows is a description of the GISLIB library routines that are
available to support latitude-longitude databases.
\subsection Coordinates Coordinates
Latitudes and longitudes are specified in degrees. Northern latitudes
range from 0 to 90 degrees, and southern latitudes from 0 to
-90. Longitudes have no limits since longitudes ±360 degrees are
equivalent.
Coordinates are represented in ASCII using the format dd:mm:ssN
or dd:mm:ssS for latitudes, ddd:mm:ssE or
ddd.mm.ssW for longitudes, and dd.mm.ss for grid
resolution. For example, 80:30:24N represents a northern latitude of
80 degrees, 30 minutes, and 24 seconds. 120:15W represents a
longitude 120 degrees and 15 minutes west of the prime meridian. 30:15
represents a resolution of 30 degrees and 15 minutes. These next
routines convert between ASCII representations and the machine
representation for a coordinate. They work both with
latitude-longitude projections and planimetric projections.
Note. In each subroutine, the programmer must specify the
projection number. If the projection number is PROJECTION_LL (defined
in "gis.h"), then latitude-longitude ASCII format is invoked.
Otherwise, a standard floating-point to ASCII conversion is made.
int G_format_easting() easting to ASCII
Converts the double representation of the east coordinate to
its ASCII representation (into buf).
int G_format_northing() northing to ASCII
Converts the double representation of the north coordinate to
its ASCII representation (into buf).
int G_format_resolution() resolution to ASCII
Converts the double representation of the resolution to its
ASCII representation (into buf).
int G_scan_easting() ASCII easting to double
Converts the ASCII "easting" coordinate string in buf to its
double representation (into easting).
int G_scan_northing() ASCII northing to double
Converts the ASCII "northing" coordinate string in buf to its
double representation (into northing).
int G_scan_resolution() ASCII resolution to double
Converts the ASCII "resolution" string in buf to its double
representation (into resolution).
The following are examples of how these routines are used.
\verbatim
double north;
char buf[50];
G_scan_northing(buf, north, G_projection()); /* ASCII to double */
G_format_northing(north, buf, G_projection()); /* double to ASCII */
G_format_northing(north, buf, -1); /* double to ASCII */
/* This last example forces floating-point ASCII format */
\endverbatim
\subsection Raster_Area_Calculations Raster Area Calculations
The following routines perform area calculations for raster maps.,
They are based on the fact that while the latitude-longitude grid is
not planimetric, the size of the grid cell at a given latitude is
constant. The first routines work in any projection.
int G_begin_cell_area_calculations() begin cell area calculations
This routine must be called once before any call to
G_area_of_cell_at_row(). It can be used in either planimetric
projections or the latitude-longitude projection. It returns 2 if the
projection is latitude-longitude, 1 if the projection is planimetric,
and 0 of the projection doesn't hav e a metric (e.g. imagery.) If the
return value is 1 or 0, all the grid cells in the map have the same
area. Otherwise the area of a grid cell varies with the row.
double G_area_of_cell_at_row() cell area in specified row
This routine returns the area in square meters of a cell in the
specified row. This value is constant for planimetric grids and
varies with the row if the projection is latitude-longitude.
int G_begin_zone_area_on_ellipsoid() begin area calculations for ellipsoid
Initializes raster area calculations for an ellipsoid, where a
is the semi-major axis of the ellipse (in meters), e2 is the
ellipsoid eccentricity squared, and s is a scale factor to
allow for calculations of part of the zone (s=1.0 is full zone,
s=0.5 is half the zone, and s=360/ew_res is for a single
grid cell).
Note. e2 must be positive. A negative value makes no sense, and
zero implies a sphere.
double G_area_for_zone_on_ellipsoid() area between latitudes
Returns the area between latitudes north and south
scaled by the factor s passed to
G_begin_zone_area_on_ellipsoid().
int G_begin_zone_area_on_sphere() initialize
calculations for sphere
Initializes raster area calculations for a sphere. The radius of the
sphere is r and s is a scale factor to allow for
calculations of a part of the zone (see
G_begin_zone_area_on_ellipsoid()).
double G_area_for_zone_on_sphere() area between latitudes
Returns the area between latitudes north and south
scaled by the factor s passed to
G_begin_zone_area_on_sphere()
\subsection Polygonal_Area_Calculations Polygonal Area Calculations
These next routines provide area calculations for polygons. Some of
the routines are specifically for latitude-longitude, while others
will function for all projections.
However, there is an issue for latitude-longitude that does not occur
with planimetric grids. Vector/polygon data is described as a series
of x,y coordinates. The lines connecting the points are not stored but
are inferred. This is a simple, straight-forward process for
planimetric grids, but it is not simple for latitude-longitude. What
is the shape of the line that connects two points on the surface of a
globe?
One choice (among many) is the shortest path from x1,y1 to
x2,y2, known as the geodesic. Another is a straight line on the
grid. The area routines described below assume the latter. Routines
to work with the former have not yet been developed.
int G_begin_polygon_area_calculations() begin polygon area
calculations
This initializes the polygon area calculation routines. It is used
both for planimetric and latitude-longitude projections.
It returns 2 if the projection is latitude-longitude, 1 if the
projection is planimetric, and 0 if the projection doesn't have a
metric (e.g. imagery.)
double G_area_of_polygon() area in square meters of polygon
Returns the area in square meters of the polygon described by the
n pairs of x,y coordinate vertices. It is used both for
planimetric and latitude-longitude projections.
Note. If the database is planimetric with the non-meter grid,
this routine performs the required unit conversion to produce square
meters. double G_planimetric_polygon_area() (x, y, n) area in
coordinate units double *x, *y ; int n ;
Returns the area in coordinate units of the polygon described by the
n pairs of x,y coordinate vertices for planimetric
grids. If the units for x,y are meters, then the area is in
square meters. If the units are feet, then the area is in square
feet, and so on.
int G_begin_ellipsoid_polygon_area () begin area calculations
This initializes the polygon area calculations for the ellipsoid with
semi-major axis a (in meters) and ellipsoid eccentricity
squared e2.
double G_ellipsoid_polygon_area() area of lat-long polygon
Returns the area in square meters of the polygon described by the
n pairs of lat,long vertices for latitude-longitude
grids.
Note. This routine assumes grid lines on the connecting the
vertices (as opposed to geodesics).
\subsection Distance Calculations Distance Calculations
Two routines perform distance calculations for any projection.
int G_begin_distance_calculations() begin distance calculations
Initializes the distance calculations. It is used both for the
planimetric and latitude-longitude projections.
It returns 2 if the projection is latitude-longitude, 1 if the
projection is planimetric, and 0 if the projection doesn't hav e a
metric (e.g. imagery).
double G_distance() distance in meters
This routine computes the distance, in meters, from x1,y1 to
x2,y2. If the projection is latitude-longitude, this distance
is measured along the geodesic. Two routines perform geodesic distance
calculations.
int G_begin_geodesic_distance() begin geodesic distance
Initializes the distance calculations for the ellipsoid with
semi-major axis a (in meters) and ellipsoid eccentricity
squared e2. It is used only for the latitude-longitude
projection.
double G_geodesic_distance() geodesic distance
Calculates the geodesic distance from lon1,lat1 to
lon2,lat2 in meters.
The calculation of the geodesic distance is fairly costly. These next
three routines provide a mechanism for calculating distance with two
fixed latitudes and varying longitude separation.
int G_set_geodesic_distance_lat1() set geodesic distance lat1
Set the first latitude.
int G_set_geodesic_distance_lat2() set geodesic distance lat2
Set the second latitude.
double G_geodesic_distance_lon_to_lon() geodesic distance
Calculates the geodesic distance from lon1,lat1 to
lon2,lat2 in meters, where lat1 was the latitude passed
to G_set_geodesic_distance_latl() and lat2 was the
latitude passed to G_set_geodesic_distance_lat2().
\subsection Global_Wraparound Global Wraparound
These next routines provide a mechanism for determining the relative
position of a pair of longitudes. Since longitudes of ±360 are
equivalent, but GRASS requires the east to be bigger than the west,
some adjustment of coordinates is necessary.
double G_adjust_easting() returns east larger than west
If the region projection is PROJECTION_LL, then this routine returns
an equivalent east that is larger, but no more than 360 degrees
larger, than the coordinate for the western edge of the
region. Otherwise no adjustment is made and the original east
is returned.
double G_adjust_east_longitude() adjust east
longitude
This routine returns an equivalent east that is larger, but no
more than 360 larger than the west coordinate.
This routine should be used only with latitude-longitude coordinates.
int G_shortest_way() shortest way between eastings
If the database projection is PROJECTION_LL, then east1,east2
are changed so that they are no more than 180 degrees apart. Their
true locations are not changed. If the database projection is not
PROJECTION_LL, then east1,east2 are not changed.
\subsection Miscellaneous Miscellaneous
char * G_ellipsoid_name() return ellipsoid name
This routine returns a pointer to a string containing the name for the
nth ellipsoid in the GRASS ellipsoid table; NULL when
n is too large. It can be used as follows:
\verbatim
int n;
char *name;
for (n=0; name=G_ellipsoid_name(n); n++)
fprintf(stdout, "%s\n", name);
\endverbatim
int G_get_ellipsoid_by_name() get ellipsoid by name
This routine returns the semi-major axis a (in meters) and
eccentricity squared e2 for the named ellipsoid. Returns 1 if
name is a known ellipsoid, 0 otherwise.
int G_get_ellipsoid_parameters() get ellipsoid parameters
This routine returns the semi-major axis a (in meters) and the
eccentricity squared e2 for the ellipsoid associated with the
database. If there is no ellipsoid explicitly associated with the
database, it returns the values for the WGS 84 ellipsoid.
double G_meridional_radius_of_curvature() meridional radius of curvature
Returns the meridional radius of curvature at a given longitude:
\f$
\rho = \frac{a (1-e^2)}{(1-e^2\sin^2 lon)^{3/2}}
\f$
double G_transverse_radius_of_curvature() transverse radius of curvature
Returns the transverse radius of curvature at a given longitude:
\f$
\nu = \frac{a}{(1-e^2\sin^2 lon)^{1/2}}
\f$
double G_radius_of_conformal_tangent_sphere() radius of conformal tangent sphere
Returns the radius of the conformal sphere tangent to ellipsoid at a
given longitude:
\f$
r = \frac{a (1-e^2)^{1/2}}{(1-e^2\sin^2 lon)}
\f$
int G_pole_in_polygon() pole in polygon
For latitude-longitude coordinates, this routine determines if the
polygon defined by the n coordinate vertices x,y
contains one of the poles.
Returns -1 if it contains the south pole; 1 if it contains the north
pole; 0 if it contains neither pole.
Note. Use this routine only if the projection is PROJECTION_LL.
\section Raster_File_Processing GRASS Raster File Processing
Please refer to GRASS Raster File Processing in Chapter \ref gisrastintro .
\section Vector_File_Processing GRASS Vector File Processing
Please refer to GRASS Vector File Processing in Chapter \ref gisvectintro .
Note, that the old "sites" are stored as vector points in GRASS 6.
\section General_Plotting_Routines General Plotting Routines
The following routines form the foundation of a general purpose line
and polygon plotting capability.
int G_bresenham_line() Bresenham line algorithm
Draws a line from x1,y1 to x2,y2 using Bresenham's
algorithm. A routine to plot points must be provided, as is defined
as:
point(x, y) plot a point at x,y
This routine does not require a previous call to G_setup_plot() to
function correctly, and is independent of all following routines.
int G_setup_plot() initialize plotting routines
Initializes the plotting capability. This routine must be called once
before calling the G_plot_*() routines described below.
The parameters t, b, l, r are the top, bottom, left, and right
of the output x,y coordinate space. They are not integers, but doubles
to allow for subpixel registration of the input and output coordinate
spaces. The input coordinate space is assumed to be the current GRASS
region, and the routines supports both planimetric and
latitude-longitude coordinate systems.
Move and Cont are subroutines that will draw lines in
x,y space. They will be called as follows:
Move(x, y) move to x,y (no draw)
Cont(x, y) draw from previous position
to x,y. Cont() is responsible for clipping
int G_plot_line() plot line between latlon coordinates
A line from east1,north1 to east2,north2 is plotted in
output x,y coordinates (e.g. pixels for graphics.) This routine
handles global wrap-around for latitude-longitude databases.
See G_setup_plot() for the required coordinate initialization
procedure.
int G_plot_polygon() plot filled
polygon with n vertices
The polygon, described by the n vertices east,north, is
plotted in the output x,y space as a filled polygon.
See G_setup_plot() for the required coordinate initialization
procedure.
int G_plot_area() plot multiple polygons
Like G_plot_polygon(), except it takes a set of polygons, each with
npts[i] vertices, where the number of polygons is
specified with the rings argument. It is especially useful for
plotting vector areas with interior islands.
int G_plot_where_en() x,y to east,north
The pixel coordinates x,y are converted to map coordinates
east,north.
See G_setup_plot() for the required coordinate initialization
procedure.
int G_plot_where_xy() east,north to x,y
The map coordinates east,north are converted to pixel
coordinates x,y.
See G_setup_plot() for the required coordinate initialization
procedure.
int G_plot_fx() plot f(east1) to f(east2)
The function f(east) is plotted from east1 to
east2. The function f(east) must return the map northing
coordinate associated with east.
See G_setup_plot() for the required coordinate initialization
procedure.
\section Temporary_Files Temporary Files
Often it is necessary for modules to use temporary files to store
information that is only useful during the module run. After the
module finishes, the information in the temporary file is no longer
needed and the file is removed. Commonly it is required that
temporary file names be unique from invocation to invocation of the
module. It would not be good for a fixed name like "/tmp/mytempfile"
to be used. If the module were run by two users at the same time, they
would use the same temporary file. In addition systematic use of the
/tmp directory could leave the system vulnerable to symlink attacks.
The following routine generates temporary file names which are unique
within the module and across all GRASS programs.
char * G_tempfile() returns a temporary file name
This routine returns a pointer to a string containing a unique file
name that can be used as a temporary file within the
module. Successive calls to G_tempfile() will generate new names.
Only the file name is generated. The file itself is not created. To
create the file, the module must use standard UNIX functions which
create and open files, e.g., creat() or fopen().
The programmer should take reasonable care to remove (unlink) the file
before the module exits. However, GRASS database management will
eventually remove all temporary files created by G_tempfile() that
have been left behind by the modules which created them.
Note. The temporary files are created in the GRASS database
rather than under /tmp. This is done for two reasons. The first is to
increase the likelihood that enough disk is available for large
temporary files since /tmp may be a very small file system. The second
is so that abandoned temporary files can be automatically removed (but
see the warning below).
Warning. The temporary files are named, in part, using the
process id of the module. GRASS database management will remove these
files only if the module which created them is no longer
running. However, this feature has a subtle trap. Programs which
create child processes (using the UNIX fork(), see also G_fork()
routine) should let the child call G_tempfile(). If the parent does it
and then exits, the child may find that GRASS has removed the
temporary file since the process which created it is no longer
running.
\section Command_Line_Parsing Command Line Parsing
The following routines provide a standard mechanism for command line
parsing. Use of the provided set of routines will standardize GRASS
commands that expect command line arguments, creating a family of
GRASS modules that is easy for users to learn. As soon as a GRASS user
familiarizes himself with the general form of command line input as
defined by the parser, it will greatly simplify the necessity of
remembering or at least guessing the required command line arguments
for any GRASS command. It is strongly recommended that GRASS
programmers use this set of routines for all command line
parsing. With their use, the programmer is freed from the burden of
generating user interface code for every command. The parser will
limit the programmer to a pre-defined look and feel, but limiting the
interface is well worth the shortened user learning curve.
\subsection Description Description
The GRASS parser is a collection of five subroutines which use two
structures that are defined in the GRASS "gis.h" header file. These
structures allow the programmer to define the options and flags that
make up the valid command line input of a GRASS command.
The parser routines behave in one of three ways:
(1) If no command line arguments are entered by the user, the parser
searches for a completely interactive version of the command. If the
interactive version is found, control is passed over to this
version. If not, the parser will prompt the user for all
programmer-defined options and flags. This prompting conforms to the
same standard for every GRASS command that uses the parser routines.
(2) If command line arguments are entered but they are a subset of the
options and flags that the programmer has defined as required
arguments, three things happen. The parser will pass an error message
to the user indicating which required options and/or flags were
missing from the command line, the parser will then display a complete
usage message for that command, and finally the parser cancels
execution of the command.
(3) If all necessary options and flags are entered on the command line
by the user, the parser executes the command with the given options
and flags.
\subsection Structures Structures
The parser routines described below use two structures as defined in
the GRASS "gis.h" header file.
This is a basic list of members of the Option and Flag structures. A
comprehensive description of all elements of these two structures and
their possible values can be found in
Full_Structure_Members_Description.
\subsection Option_structure Option structure
These are the basic members of the Option structure.
\verbatim
struct Option *opt; /* to declare a command line option */
\endverbatim
Structure Member Description of Member
\verbatim
opt->key Option name that user will use
opt->description Option description that is shown to the user
opt->type Variable type of the user's answer to the option
opt->required Is this option required on the command line? (Boolean)
\endverbatim
\subsection Flag_structure Flag structure
These are the basic members of the Flag structure.
\verbatim
struct Flag *flag; /* to declare a command line flag */
\endverbatim
Structure Member Description of Member
\verbatim
flag->key Single letter used for flag name
flag->description Flag description that is shown to the user
\endverbatim
\subsection Parser_Routines Parser Routines
Associated with the parser are five routines that are automatically
included in the GRASS Makefile process. The Makefile process is
documented in \ref Compiling_and_Installing_GRASS_Modules.
struct Option * G_define_option() returns Option structure
Allocates memory for the Option structure and returns a pointer to
this memory (of type struct Option *).
struct Flag * G_define_flag() return Flag structure
Allocates memory for the Flag structure and returns a pointer to this
memory (of type struct Flag *).
int G_parser() parse command line
The command line parameters argv and the number of parameters
argc from the main() routine are passed directly to
G_parser(). G_parser() accepts the command line input
entered by the user, and parses this input according to the input
options and/or flags that were defined by the programmer.
G_parser() returns 0 if successful. If not successful, a usage
statement is displayed that describes the expected and/or required
options and flags and a non-zero value is returned.
int G_usage() command line help/usage message
Calls to G_usage() allow the programmer to print the usage
message at any time. This will explain the allowed and required
command line input to the user. This description is given according to
the programmer's definitions for options and flags. This function
becomes useful when the user enters options and/or flags on the
command line that are syntactically valid to the parser, but
functionally invalid for the command (e.g. an invalid file name.)
For example, the parser logic doesn't directly support grouping
options. If two options be specified together or not at all, the
parser must be told that these options are not required and the
programmer must check that if one is specified the other must be as
well. If this additional check fails, then G_parser() will
succeed, but the programmer can then call G_usage() to print
the standard usage message and print additional information about how
the two options work together.
int G_disable_interactive() turns off interactive capability
When a user calls a command with no arguments on the command line, the
parser will enter its own standardized interactive session in which
all flags and options are presented to the user for input. A call to
G_disable_interactive() disables the parser's interactive
prompting.
Note: Displaying multiple answers default values (new in GRASS
5, see d.zoom for example).
\verbatim
char *def[] = {"One", "Two", "Last", NULL};
opt->multiple = YES;
opt->answers = def;
if (G_parser(argc, argv))
exit(EXIT_FAILURE);
\endverbatim
The programmer may not forget last NULL value.
\subsection Parser_Programming_Examples Parser Programming Examples
The use of the parser in the programming process is demonstrated
here. Both a basic step by step example and full code example are
presented.
\subsection Step_by_Step_Use_of_the_Parser Step by Step Use of the Parser
These are the four basic steps to follow to implement the use of the
GRASS parser in a GRASS command:
(1) Allocate memory for Flags and Options:
Flags and Options are pointers to structures allocated through the
parser routines G_define_option() and G_define_flag() as
defined in Parser_Routines.
\verbatim
#include
(2) Define members of Flag and Option structures:
The programmer should define the characteristics of each option and
flag desired as outlined by the following example:
\verbatim
opt->key = "option"; /* The name of this option is "option". */
opt->description = _("Option test"); /* The option description is "Option test" */
opt->type = TYPE_STRING; /* The data type of the answer to the option */
opt->required = YES; /* This option *is* required from the user */
flag->key = "t"; /* Single letter name for flag */
flag->description = _("Flag test"); /* The flag description is "Flag test" */
\endverbatim
Note.There are more options defined later in
Complete_Structure_Members_Table.
(3) Call the parser:
\verbatim
int
main(int argc, char *argv[]); /* command line args passed into main() */
if (G_parser(argc, argv)) /* Returns 0 if successful, non-zero otherwise */
exit(EXIT_FAILURE);
\endverbatim
(4) Extracting information from the parser structures:
\verbatim
fprintf(stdout, "For the option "%s" you chose: <%s>\n", opt->description, opt->answer );
fprintf(stdout, "The flag "-%s" is %s set.\n", flag->key, flag->answer ? "" : "not" );
\endverbatim
(5) Running the example program
Once such a module has been compiled (for example to the default
executable file a.out , execution will result in the following
user interface scenarios. Lines that begin with # imply user entered
commands on the command line.
\verbatim
# a.out help
\endverbatim
This is a standard user call for basic help information on the
module. The command line options (in this case, "help") are sent to
the parser via G_parser(). The parser recognizes the "help"
command line option and returns a list of options and/or flags that
are applicable for the specific command. Note how the programmer
provided option and flag information is captured in the output.
\verbatim
a.out [-t] option=name
Flags:
-t Flag test
Parameters:
option Option test
\endverbatim
Now the following command is executed:
\verbatim
# a.out -t
\endverbatim
This command line does not contain the required option. Note that the
output provides this information along with the standard usage message
(as already shown above):
\verbatim
Required parameter
1 UTM
2 State Plane
3 Latitude-Longitude
99 Other (more than 121 projections are supported)