1
0
Fork 0

Merge remote-tracking branch 'origin/next' into next

This commit is contained in:
James.Hester 2019-02-07 22:10:13 +11:00
commit b718d909a4
105 changed files with 1513 additions and 1693 deletions

View file

@ -18,9 +18,9 @@ include (CheckCXXSourceCompiles)
include (CheckIncludeFile) include (CheckIncludeFile)
include (CPack) include (CPack)
# let's use & require C++11 - note these are only functional with CMake 3.1 # let's use & require C++14 - note these are only functional with CMake 3.1
# we do manual fallbacks for CMake 3.0 in the compilers section # we do manual fallbacks for CMake 3.0 in the compilers section
set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED YES) set(CMAKE_CXX_STANDARD_REQUIRED YES)
project(TerraGear) project(TerraGear)
@ -58,8 +58,6 @@ if (MSVC)
else (EXISTS ${TEST_3RDPARTY_DIR}) else (EXISTS ${TEST_3RDPARTY_DIR})
set(MSVC_3RDPARTY_ROOT NOT_FOUND CACHE PATH "Location where the third-party dependencies are extracted") set(MSVC_3RDPARTY_ROOT NOT_FOUND CACHE PATH "Location where the third-party dependencies are extracted")
endif (EXISTS ${TEST_3RDPARTY_DIR}) endif (EXISTS ${TEST_3RDPARTY_DIR})
set( RT_LIBRARY "winmm.lib" )
else (MSVC) else (MSVC)
set(MSVC_3RDPARTY_ROOT) set(MSVC_3RDPARTY_ROOT)
endif (MSVC) endif (MSVC)
@ -153,9 +151,11 @@ if(CMAKE_COMPILER_IS_GNUCXX)
set(WARNING_FLAGS -Wall) set(WARNING_FLAGS -Wall)
if (CMAKE_VERSION VERSION_LESS 3.1) if (CMAKE_VERSION VERSION_LESS 3.1)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14")
endif() endif()
endif(CMAKE_COMPILER_IS_GNUCXX) elseif (MSVC AND CMAKE_VERSION VERSION_LESS 3.1)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /std=c++14")
endif()
if (WIN32) if (WIN32)
if (MSVC) if (MSVC)

View file

@ -157,7 +157,7 @@ else(SIMGEAR_SHARED)
${ZLIB_LIBRARY}) ${ZLIB_LIBRARY})
if(WIN32) if(WIN32)
list(APPEND SIMGEAR_CORE_LIBRARY_DEPENDENCIES ws2_32.lib Shlwapi.lib ) list(APPEND SIMGEAR_CORE_LIBRARY_DEPENDENCIES ws2_32.lib Shlwapi.lib Winmm.lib)
endif(WIN32) endif(WIN32)
if(NOT MSVC) if(NOT MSVC)
@ -188,9 +188,16 @@ unset(SIMGEAR_COMPILE_TEST CACHE)
# disable OSG dependencies for test-compiling # disable OSG dependencies for test-compiling
set(CMAKE_REQUIRED_DEFINITIONS "-DNO_OPENSCENEGRAPH_INTERFACE") set(CMAKE_REQUIRED_DEFINITIONS "-DNO_OPENSCENEGRAPH_INTERFACE")
set(CMAKE_CXX_STANDARD 11) if ((NOT CMAKE_CXX_STANDARD) OR (${CMAKE_CXX_STANDARD} LESS 11))
set(CMAKE_CXX_STANDARD_REQUIRED YES) set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") set(CMAKE_CXX_STANDARD_REQUIRED YES)
if(CMAKE_COMPILER_IS_GNUCXX AND CMAKE_VERSION VERSION_LESS 3.1)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif (MSVC AND CMAKE_VERSION VERSION_LESS 3.1)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /std=c++11")
endif()
endif()
check_cxx_source_runs( check_cxx_source_runs(
"#include <cstdio> "#include <cstdio>

48
README
View file

@ -46,56 +46,26 @@ Preprocessing Terrain
TerraGear supports several terrain data sources: TerraGear supports several terrain data sources:
1. 30-arcsec SRTM based terrain data covering the world (recommended 1. [Preferred] SRTM (version 3):
over other 30-arcsec data sources): Void filled, 1-arc-sec and 3-arc-sec, near worldwide coverage.
ftp://edcsgs9.cr.usgs.gov/pub/data/srtm/SRTM30/ https://e4ftl01.cr.usgs.gov/MEASURES/SRTMGL1.003/
I don't recall the details at the moment for processing this data. a) Chop up each .zip files using "Prep/DemChop/hgtchop"
Probably similar to the processing of the GLOBE data.
2. 30-arcsec world wide data: GLOBE project:
http://www.ngdc.noaa.gov/seg/topo/globe.shtml
a) First convert the "bin" DEM format to "ascii" DEM format using
"Prep/DemRaw2ascii/raw2ascii"
b) Then process the resulting files with "Prep/DemChop/demchop"
3. 30-arcsec world wide data: GTOPO30 data: 2. SRTM (version 1 & 2):
May contain voids, 1-arc-sec and 3-arc-sec, near worldwide coverage.
http://edcwww.cr.usgs.gov/landdaac/gtopo30/gtopo30.html
a) First convert the "bin" DEM format to "ascii" DEM format using
"Prep/DemRaw2ascii/raw2ascii"
b) Then process the resulting files with "Prep/DemChop/demchop"
4. SRTM (version 1 & 2) (1 and 3-arcsec nearly world wide coverage):
ftp://edcsgs9.cr.usgs.gov/pub/data/srtm/ ftp://edcsgs9.cr.usgs.gov/pub/data/srtm/
a) Chop up each .zip files using "Prep/DemChop/hgtchop" a) Chop up each .zip files using "Prep/DemChop/hgtchop"
5. 3-arcsec ASCII DEM files:
Generally, I recommend using the SRTM data over this older data
set, however in places like Alaska, there is no SRTM coverage so
this data is better than the 30 arcsec data.
http://edcwww.cr.usgs.gov/doc/edchome/ndcdb/ndcdb.html
a) Create the .arr.gz files using the "Prep/DemChop/demchop" utility.
The result for any of these terrain sources should be a "work" tree The result for any of these terrain sources should be a "work" tree
with a .arr.gz file for each FG tile. with a .arr.gz file for each FG tile.
6. SRTM data comes with 'voids'. These are areas where their 3. SRTM versions 1 & 2 come with 'voids'. These are areas where their
automated data processing system could not reliably determine the automated data processing system could not reliably determine the
elevation. Often this happens over water, or over mountain peaks. elevation. Often this happens over water, or over mountain peaks.
There is a big chunk of the Grand Canyon missing, a big chunk of There is a big chunk of the Grand Canyon missing, a big chunk of
@ -106,13 +76,13 @@ with a .arr.gz file for each FG tile.
I half trust is the USGS 3 arcsec DEM data for the USA. So we I half trust is the USGS 3 arcsec DEM data for the USA. So we
can't fix voids outside the USA right now. can't fix voids outside the USA right now.
In the same directory as DemChop and HgtChop there is a "fillvoids" In the same directory as HgtChop there is a "fillvoids"
program. You might wish to run it with something like the program. You might wish to run it with something like the
following command line: following command line:
find /export/fgfs05/curt/Work/SRTM2-North_America3 -name '*.arr.gz' -exec ./fillvoids {} /stage/fgfs05/curt/Work/USGS-DEM-USA-3 \; find /export/fgfs05/curt/Work/SRTM2-North_America3 -name '*.arr.gz' -exec ./fillvoids {} /stage/fgfs05/curt/Work/USGS-DEM-USA-3 \;
7. After you create the .arr.gz files you have to create a 4. After you create the .arr.gz files you have to create a
corresponding .fit.gz file for each of these. This is a data corresponding .fit.gz file for each of these. This is a data
reduction step which fits a set of polygons to the raw terrain with reduction step which fits a set of polygons to the raw terrain with
a set of constraints on the maximum error allowed relative to the a set of constraints on the maximum error allowed relative to the

View file

@ -23,7 +23,6 @@ under Windows. If running the tools from the standard Win32 command
prompt a lot of the tools have problems with directory creation - with prompt a lot of the tools have problems with directory creation - with
the tools that try to create many subdirectories this can be a major the tools that try to create many subdirectories this can be a major
problem. It is much better to run the tools from a Cygwin bash shell problem. It is much better to run the tools from a Cygwin bash shell
- in this case only raw2ascii has a directory creation problem - the - the output directory specified on the command line needs to be
output directory specified on the command line needs to be manually manually created.
created.

View file

@ -21,24 +21,18 @@ Preparation and Preprocessing
1) DEM data. 1) DEM data.
As the first step you have to download DEM for the area you need. (You As the first step you have to download DEM for the area you need. (You
can get them from USGS site). If this is a 30 arc sec DEM (which is most can get them from USGS site).
probable) you need to transfer this file into ASCII format using
raw2ascii
Usage: ./raw2ascii <input_file_basename> <output_dir>
Here output dir is quite arbitrary as we will remove all the files from
it later.
Then you have to chop files that we got into the tiles used for the Then you have to chop files that we got into the tiles used for the
scenery generation. You should use demchop for this. As we already have scenery generation. You should use hgtchop for this. As we already have
a number of files I'm using the following Perl script a number of files I'm using the following Perl script
#-------------------------------------------------------------------------- #--------------------------------------------------------------------------
#!/usr/bin/perl #!/usr/bin/perl
my @files=glob("./*.dem"); my @files=glob("./*.hgt");
my $size=@files; my $size=@files;
for (my $i=0;$i<$size;$i++) { for (my $i=0;$i<$size;$i++) {
system("demchop $files[$i] /home/anovikov/w020n90/Work/DEM-30"); system("hgtchop $files[$i] /home/anovikov/w020n90/Work/SRTM-3");
} }
#-------------------------------------------------------------------------- #--------------------------------------------------------------------------

View file

@ -33,6 +33,7 @@
#include "triangle.h" #include "triangle.h"
void build_segments(struct triangulateio* tri, struct Map_info* map) void build_segments(struct triangulateio* tri, struct Map_info* map)
{ {
plus_t node_idx, line_idx; plus_t node_idx, line_idx;

View file

@ -24,7 +24,8 @@
#include <grass/dbmi.h> #include <grass/dbmi.h>
#include <grass/vector.h> #include <grass/vector.h>
void apply_setz_operator( struct Map_info* map, double z, int* cats, int ncats, int layer)
void apply_setz_operator(struct Map_info* map, double z, int* cats, int ncats, int layer)
{ {
const plus_t area_count = Vect_get_num_areas( map ); const plus_t area_count = Vect_get_num_areas( map );
plus_t area_idx; plus_t area_idx;
@ -42,7 +43,7 @@ void apply_setz_operator( struct Map_info* map, double z, int* cats, int ncats,
} }
} }
void apply_mean_operator( struct Map_info* map, int* cats, int ncats, int layer ) void apply_mean_operator(struct Map_info* map, int* cats, int ncats, int layer)
{ {
if (ncats > 0) { if (ncats > 0) {
/* We have to greedily collect adjacent selected areas */ /* We have to greedily collect adjacent selected areas */
@ -53,7 +54,7 @@ void apply_mean_operator( struct Map_info* map, int* cats, int ncats, int layer
} }
} }
void apply_slope_operator( struct Map_info* map, double slope, int* cats, int ncats, int layer) void apply_slope_operator(struct Map_info* map, double slope, int* cats, int ncats, int layer)
{ {
if (ncats > 0) { if (ncats > 0) {
/* We apply slope to individual areas */ /* We apply slope to individual areas */
@ -73,9 +74,7 @@ int main(int argc, char *argv[])
struct Option *fieldopt; struct Option *fieldopt;
int field; int field;
struct Map_info oldmap, newmap; struct Map_info oldmap, newmap;
struct field_info* fieldinfo; int ncats, *cats;
dbDriver* driver;
int i, ncats, *cats;
G_gisinit(argv[0]); G_gisinit(argv[0]);
@ -131,36 +130,36 @@ int main(int argc, char *argv[])
Vect_close(&oldmap); Vect_close(&oldmap);
if (whereopt->answer!=NULL) { if (whereopt->answer!=NULL) {
field = Vect_get_field_number( &newmap, fieldopt->answer ); field = Vect_get_field_number( &newmap, fieldopt->answer );
fieldinfo = Vect_get_field( &newmap, field ); struct field_info* fieldinfo = Vect_get_field( &newmap, field );
if (!fieldinfo) { if (!fieldinfo) {
G_fatal_error(_("Database connection not defined for layer <%s>"), G_fatal_error(_("Database connection not defined for layer <%s>"),
fieldopt->answer); fieldopt->answer);
} }
G_debug(1, "Loading categories from table <%s>", fieldinfo->table); G_debug(1, "Loading categories from table <%s>", fieldinfo->table);
driver = db_start_driver_open_database(fieldinfo->driver, fieldinfo->database); dbDriver* driver = db_start_driver_open_database(fieldinfo->driver, fieldinfo->database);
if (driver == NULL) { if (driver == NULL) {
G_fatal_error(_("Unable to open database <%s> by driver <%s>"), G_fatal_error(_("Unable to open database <%s> by driver <%s>"),
fieldinfo->database, fieldinfo->driver); fieldinfo->database, fieldinfo->driver);
} }
ncats = db_select_int(driver, fieldinfo->table, fieldinfo->key, whereopt->answer, ncats = db_select_int(driver, fieldinfo->table, fieldinfo->key, whereopt->answer,
&cats); &cats);
if (ncats == -1) { if (ncats == -1) {
G_fatal_error(_("Unable select records from table <%s>"), fieldinfo->table); G_fatal_error(_("Unable select records from table <%s>"), fieldinfo->table);
} }
G_message(_("%d categories loaded from table <%s>"), ncats, G_message(_("%d categories loaded from table <%s>"), ncats,
fieldinfo->table); fieldinfo->table);
db_close_database(driver); db_close_database(driver);
db_shutdown_driver(driver); db_shutdown_driver(driver);
} else { } else {
field = -1; field = -1;
cats = NULL; cats = NULL;
ncats = -1; ncats = -1;
} }
if (!strcmp(operator->answer, "setz")) { if (!strcmp(operator->answer, "setz")) {
apply_setz_operator( &newmap, atof(value->answer), cats, ncats, field ); apply_setz_operator( &newmap, atof(value->answer), cats, ncats, field );
@ -172,9 +171,10 @@ int main(int argc, char *argv[])
Vect_build(&newmap); Vect_build(&newmap);
if (cats != NULL) { if (cats != NULL) {
G_free(cats); G_free(cats);
} }
Vect_close(&newmap); Vect_close(&newmap);
/* Don't forget to report to caller sucessful end of data processing :) */ /* Don't forget to report to caller sucessful end of data processing :) */

View file

@ -21,10 +21,11 @@
#include <grass/glocale.h> #include <grass/glocale.h>
#include <grass/vector.h> #include <grass/vector.h>
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
struct GModule *module; /* GRASS module for parsing arguments */ struct GModule *module; /* GRASS module for parsing arguments */
struct Option *old, *new; struct Option *old;
struct Map_info oldmap; struct Map_info oldmap;
G_gisinit(argv[0]); G_gisinit(argv[0]);
@ -36,7 +37,7 @@ int main(int argc, char *argv[])
/* Define the different options as defined in gis.h */ /* Define the different options as defined in gis.h */
old = G_define_standard_option(G_OPT_V_INPUT); old = G_define_standard_option(G_OPT_V_INPUT);
new = G_define_standard_option(G_OPT_F_OUTPUT); G_define_standard_option(G_OPT_F_OUTPUT);
/* options and flags parser */ /* options and flags parser */
if (G_parser(argc, argv)) if (G_parser(argc, argv))

View file

@ -39,13 +39,6 @@ MODE="testing" # production, testing
InitCutoutTable () { InitCutoutTable () {
${PSQL} "DROP TABLE ${CUTLAYER}" ${PSQL} "DROP TABLE ${CUTLAYER}"
# ${PSQL} "CREATE TABLE ${CUTLAYER} (ogc_fid serial NOT NULL, \
# wkb_geometry geometry, \
# CONSTRAINT enforce_dims_wkb_geometry CHECK (ST_NDims(wkb_geometry) = 2), \
# CONSTRAINT enforce_geotype_wkb_geometry CHECK ((ST_GeometryType(wkb_geometry) = 'ST_Polygon'::text) \
# OR (ST_GeometryType(wkb_geometry) = 'ST_MultiPolygon'::text)), \
# CONSTRAINT enforce_srid_wkb_geometry CHECK (ST_SRID(wkb_geometry) = 4326) \
# )"
${PSQL} "CREATE TABLE ${CUTLAYER} (ogc_fid serial NOT NULL, \ ${PSQL} "CREATE TABLE ${CUTLAYER} (ogc_fid serial NOT NULL, \
wkb_geometry geometry, \ wkb_geometry geometry, \
CONSTRAINT enforce_dims_wkb_geometry CHECK (ST_NDims(wkb_geometry) = 2), \ CONSTRAINT enforce_dims_wkb_geometry CHECK (ST_NDims(wkb_geometry) = 2), \

View file

@ -25,10 +25,11 @@ date
DUMPDIR=${HOME}/shp DUMPDIR=${HOME}/shp
mkdir -p ${DUMPDIR} mkdir -p ${DUMPDIR}
RUNDIR=`pwd` RUNDIR=`pwd`
cd `dirname ${0}` && export BASEDIR=`pwd` cd `dirname ${0}` && export BASEDIR=`pwd`
cd ${RUNDIR} cd ${RUNDIR}
CALLNAME=`basename ${0}` CALLNAME=`basename ${0}`
#
MAPPINGFILE=${BASEDIR}/CORINEtoCS.txt MAPPINGFILE=${BASEDIR}/CORINEtoCS.txt
if [ ${CALLNAME} = "grassVMap.sh" ]; then if [ ${CALLNAME} = "grassVMap.sh" ]; then
@ -50,33 +51,24 @@ elif [ ${CALLNAME} = "grassCLC06.sh" ]; then
else else
SRCID=0 SRCID=0
fi fi
PREFIX=${TYPE}${YEAR} PREFIX=${TYPE}${YEAR}
#PREFIX=nl
#PREFIX=clc${YEAR}_nl
CLEANMAP=cleanmap CLEANMAP=cleanmap
if [ ${TYPE} = "v0" ]; then if [ ${TYPE} = "v0" ]; then
SRCKBS=nad83 SRCKBS=nad83
#SNAP=0.00001
SNAP=0.000001 SNAP=0.000001
#MIN_AREA1=1
MIN_AREA1=0.0000001 MIN_AREA1=0.0000001
MIN_AREA=100 MIN_AREA=100
#MIN_AREA=0.000000001
elif [ ${TYPE} = "cs" ]; then elif [ ${TYPE} = "cs" ]; then
SRCKBS=wgs84 SRCKBS=wgs84
SNAP=0.000001 SNAP=0.000001
#MIN_AREA1=1
MIN_AREA1=0.0000001 MIN_AREA1=0.0000001
MIN_AREA=1 MIN_AREA=1
elif [ ${TYPE} = "clc" ]; then elif [ ${TYPE} = "clc" ]; then
SRCKBS=laea SRCKBS=laea
SNAP=0.01 SNAP=0.01
#SNAP=0.001
#SNAP=0.0001
#SNAP=0.000001
MIN_AREA=1 MIN_AREA=1
#MIN_AREA=0.000000001
fi fi
######################################################################## ########################################################################
@ -148,7 +140,6 @@ fn_importVMap() {
LAYER=`basename ${SHAPEFILE} | cut -f 1 -d \.` LAYER=`basename ${SHAPEFILE} | cut -f 1 -d \.`
MAP=`echo ${LAYER} | sed -e 's/-/_/g'` MAP=`echo ${LAYER} | sed -e 's/-/_/g'`
g.remove vect=${MAP} g.remove vect=${MAP}
# v.in.ogr dsn="${LOADDIR}" layer=${LAYER} output=${MAP} snap=${SNAP} --verbose
v.in.ogr dsn="${LOADDIR}" layer=${LAYER} output=${MAP} --verbose v.in.ogr dsn="${LOADDIR}" layer=${LAYER} output=${MAP} --verbose
done done
} }
@ -238,11 +229,9 @@ fn_split() {
v.extract -t input=${LAYER} type=area output=${PREFIX}_mixedcrop_${ZONE} where="f_code NOT LIKE 'BH135' and veg = 0" v.extract -t input=${LAYER} type=area output=${PREFIX}_mixedcrop_${ZONE} where="f_code NOT LIKE 'BH135' and veg = 0"
v.extract -t input=${LAYER} type=area output=${PREFIX}_drycrop_${ZONE} where="f_code NOT LIKE 'BH135' and veg = 1" v.extract -t input=${LAYER} type=area output=${PREFIX}_drycrop_${ZONE} where="f_code NOT LIKE 'BH135' and veg = 1"
v.extract -t input=${LAYER} type=area output=${PREFIX}_irrcrop_${ZONE} where="f_code NOT LIKE 'BH135' and veg > 1" v.extract -t input=${LAYER} type=area output=${PREFIX}_irrcrop_${ZONE} where="f_code NOT LIKE 'BH135' and veg > 1"
# v.extract -t input=${LAYER} type=area output=${PREFIX}_rice_${ZONE} where="f_code LIKE 'BH135'"
;; ;;
"grassa@veg(*)_area") "grassa@veg(*)_area")
v.extract -t input=${LAYER} type=area output=${PREFIX}_grassland_${ZONE} where="f_code LIKE 'EB010'" v.extract -t input=${LAYER} type=area output=${PREFIX}_grassland_${ZONE} where="f_code LIKE 'EB010'"
# v.extract -t input=${LAYER} type=area output=${PREFIX}_bamboo_${ZONE} where="f_code LIKE 'EC010'"
v.extract -t input=${LAYER} type=area output=${PREFIX}_scrub_${ZONE} where="f_code NOT LIKE 'EB010' AND f_code NOT LIKE 'EC010'" v.extract -t input=${LAYER} type=area output=${PREFIX}_scrub_${ZONE} where="f_code NOT LIKE 'EB010' AND f_code NOT LIKE 'EC010'"
;; ;;
"oasisa@veg(*)_area") "oasisa@veg(*)_area")
@ -257,7 +246,6 @@ fn_split() {
v.extract -t input=${LAYER} type=area output=${PREFIX}_marsh_${ZONE} where="f_code NOT LIKE 'BH015'" v.extract -t input=${LAYER} type=area output=${PREFIX}_marsh_${ZONE} where="f_code NOT LIKE 'BH015'"
;; ;;
"treesa@veg(*)_area") "treesa@veg(*)_area")
# v.extract -t input=${LAYER} type=area output=${PREFIX}_mangrove_${ZONE} where="veg = 19"
v.extract -t input=${LAYER} type=area output=${PREFIX}_deciduousforest_${ZONE} where="veg = 24" v.extract -t input=${LAYER} type=area output=${PREFIX}_deciduousforest_${ZONE} where="veg = 24"
v.extract -t input=${LAYER} type=area output=${PREFIX}_evergreenforest_${ZONE} where="veg = 25" v.extract -t input=${LAYER} type=area output=${PREFIX}_evergreenforest_${ZONE} where="veg = 25"
v.extract -t input=${LAYER} type=area output=${PREFIX}_mixedforest_${ZONE} where="veg != 19 AND veg != 24 AND veg != 25" v.extract -t input=${LAYER} type=area output=${PREFIX}_mixedforest_${ZONE} where="veg != 19 AND veg != 24 AND veg != 25"
@ -292,7 +280,6 @@ fn_reclass() {
done done
g.remove vect=${OUTPUT}_patched g.remove vect=${OUTPUT}_patched
v.patch input=`g.mlist type=vect pattern="${OUTPUT}_[a-z][a-z][a-z]_lcclass" separator=,` output=${OUTPUT}_patched v.patch input=`g.mlist type=vect pattern="${OUTPUT}_[a-z][a-z][a-z]_lcclass" separator=,` output=${OUTPUT}_patched
# v.patch input=`g.mlist type=vect pattern="${OUTPUT}_[a-z][a-z][a-z]_lcclass" separator=,` output=${INTMAP}
g.remove vect=${OUTPUT}_bpol,${OUTPUT}_snap,${OUTPUT}_split,${OUTPUT}_rmsa,${OUTPUT}_rmdangle,${OUTPUT}_rmarea,${OUTPUT}_prune g.remove vect=${OUTPUT}_bpol,${OUTPUT}_snap,${OUTPUT}_split,${OUTPUT}_rmsa,${OUTPUT}_rmdangle,${OUTPUT}_rmarea,${OUTPUT}_prune
v.clean input=${OUTPUT}_patched output=${OUTPUT}_bpol -c tool=bpol type=boundary --verbose v.clean input=${OUTPUT}_patched output=${OUTPUT}_bpol -c tool=bpol type=boundary --verbose
@ -451,7 +438,6 @@ fn_export() {
# #
SELECTION=`v.category input=${CLEANMAP} type=centroid option=print | sort -n | uniq` SELECTION=`v.category input=${CLEANMAP} type=centroid option=print | sort -n | uniq`
for CATEGORY in ${SELECTION}; do for CATEGORY in ${SELECTION}; do
# LAYER=${PREFIX}_${CATEGORY}
LAYER=`grep \^${CATEGORY} ${MAPPINGFILE} | awk '{print $2}' | sed -e "s/^cs_/${PREFIX}_/g"` LAYER=`grep \^${CATEGORY} ${MAPPINGFILE} | awk '{print $2}' | sed -e "s/^cs_/${PREFIX}_/g"`
g.remove vect=${LAYER} g.remove vect=${LAYER}
v.extract cats=${CATEGORY} input=${CLEANMAP} output=${LAYER} type=area v.extract cats=${CATEGORY} input=${CLEANMAP} output=${LAYER} type=area
@ -461,7 +447,6 @@ fn_export() {
g.rename vect=${LAYER},${NEWLAYER} g.rename vect=${LAYER},${NEWLAYER}
LAYER=${NEWLAYER} LAYER=${NEWLAYER}
fi fi
# v.out.ogr input=${LAYER} type=area dsn=${DUMPDIR}/${PREFIX}_c${CATEGORY}.shp # For CLC
v.out.ogr input=${LAYER} type=area dsn=${DUMPDIR}/${LAYER}.shp # For VMap0/CS v.out.ogr input=${LAYER} type=area dsn=${DUMPDIR}/${LAYER}.shp # For VMap0/CS
fn_topostgis ${LAYER} fn_topostgis ${LAYER}
done done

View file

@ -28,8 +28,6 @@ mkdir -p ${DUMPDIR}
export LD_LIBRARY_PATH=/opt/GRASS.32/lib export LD_LIBRARY_PATH=/opt/GRASS.32/lib
OGR2OGR=/opt/GRASS.32/bin/ogr2ogr OGR2OGR=/opt/GRASS.32/bin/ogr2ogr
OGRINFO=/opt/GRASS.32/bin/ogrinfo OGRINFO=/opt/GRASS.32/bin/ogrinfo
#OGR2OGR=/usr/local/bin/ogr2ogr
#OGRINFO=/usr/local/bin/ogrinfo
AREAS="v0eur_5/vmaplv0/eurnasia v0noa_5/vmaplv0/noamer v0sas_5/vmaplv0/sasaus v0soa_5/vmaplv0/soamafr" AREAS="v0eur_5/vmaplv0/eurnasia v0noa_5/vmaplv0/noamer v0sas_5/vmaplv0/sasaus v0soa_5/vmaplv0/soamafr"
@ -46,7 +44,6 @@ GetFeatureNames () {
ConvertToSHapefiles () { ConvertToSHapefiles () {
for VMAP_URL in ${AREAS}; do for VMAP_URL in ${AREAS}; do
ZONE=`echo ${VMAP_URL} | cut -f 1 -d \/ | sed -e 's/^v0//g' -e 's/_5\$//g'` ZONE=`echo ${VMAP_URL} | cut -f 1 -d \/ | sed -e 's/^v0//g' -e 's/_5\$//g'`
# for FEATURE in `GetFeatureNames`; do
for FEATURE in `${OGRINFO} gltp:/vrf/home/martin/live/vmap0/${VMAP_URL} 2>&1 | egrep \^"[0-9].*@" | awk '{print $2}' | sort | uniq`; do for FEATURE in `${OGRINFO} gltp:/vrf/home/martin/live/vmap0/${VMAP_URL} 2>&1 | egrep \^"[0-9].*@" | awk '{print $2}' | sort | uniq`; do
CATEGORY=`echo ${FEATURE} | cut -f 1 -d \@` CATEGORY=`echo ${FEATURE} | cut -f 1 -d \@`
DIR=`echo ${FEATURE} | cut -f 1 -d \( | cut -f 2 -d \@` DIR=`echo ${FEATURE} | cut -f 1 -d \( | cut -f 2 -d \@`

View file

@ -33,7 +33,6 @@ target_link_libraries(genapts850
${CMAKE_THREAD_LIBS_INIT} ${CMAKE_THREAD_LIBS_INIT}
${SIMGEAR_CORE_LIBRARIES} ${SIMGEAR_CORE_LIBRARIES}
${SIMGEAR_CORE_LIBRARY_DEPENDENCIES} ${SIMGEAR_CORE_LIBRARY_DEPENDENCIES}
${Boost_LIBRARIES} ${Boost_LIBRARIES})
${RT_LIBRARY})
install(TARGETS genapts850 RUNTIME DESTINATION bin) install(TARGETS genapts850 RUNTIME DESTINATION bin)

View file

@ -93,60 +93,17 @@ Airport::Airport( int c, char* def)
Airport::~Airport() Airport::~Airport()
{ {
for (unsigned int i=0; i<features.size(); i++) std::fill(features.begin(), features.end(), nullptr);
{ std::fill(helipads.begin(), helipads.end(), nullptr);
delete features[i]; std::fill(runways.begin(), runways.end(), nullptr);
} std::fill(waterrunways.begin(), waterrunways.end(), nullptr);
std::fill(pavements.begin(), pavements.end(), nullptr);
for (unsigned int i=0; i<helipads.size(); i++) std::fill(taxiways.begin(), taxiways.end(), nullptr);
{ std::fill(lightobjects.begin(), lightobjects.end(), nullptr);
delete helipads[i]; std::fill(windsocks.begin(), windsocks.end(), nullptr);
} std::fill(beacons.begin(), beacons.end(), nullptr);
std::fill(signs.begin(), signs.end(), nullptr);
for (unsigned int i=0; i<runways.size(); i++) std::fill(boundary.begin(), boundary.end(), nullptr);
{
delete runways[i];
}
for (unsigned int i=0; i<waterrunways.size(); i++)
{
delete waterrunways[i];
}
for (unsigned int i=0; i<pavements.size(); i++)
{
delete pavements[i];
}
for (unsigned int i=0; i<taxiways.size(); i++)
{
delete taxiways[i];
}
for (unsigned int i=0; i<lightobjects.size(); i++)
{
delete lightobjects[i];
}
for (unsigned int i=0; i<windsocks.size(); i++)
{
delete windsocks[i];
}
for (unsigned int i=0; i<beacons.size(); i++)
{
delete beacons[i];
}
for (unsigned int i=0; i<signs.size(); i++)
{
delete signs[i];
}
for (unsigned int i=0; i<boundary.size(); i++)
{
delete boundary[i];
}
} }
bool Airport::isDebugRunway( int rwy ) bool Airport::isDebugRunway( int rwy )
@ -243,7 +200,6 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
// runway lights // runway lights
tglightcontour_list rwy_lights; tglightcontour_list rwy_lights;
bool make_shapefiles = false;
char debug_root[32]; char debug_root[32];
sprintf(debug_root, "./airport_dbg/%s/", icao.c_str() ); sprintf(debug_root, "./airport_dbg/%s/", icao.c_str() );
@ -305,6 +261,7 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
{ {
TG_LOG(SG_GENERAL, SG_DEBUG, "Build Feature Poly " << i + 1 << " of " << features.size() << " : " << features[i]->GetDescription() ); TG_LOG(SG_GENERAL, SG_DEBUG, "Build Feature Poly " << i + 1 << " of " << features.size() << " : " << features[i]->GetDescription() );
bool make_shapefiles = false;
features[i]->BuildBtg( line_polys, rwy_lights, lf_accum, make_shapefiles ); features[i]->BuildBtg( line_polys, rwy_lights, lf_accum, make_shapefiles );
} }
@ -327,7 +284,7 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
//slivers.clear(); //slivers.clear();
if ( isDebugRunway(i) ) { if ( isDebugRunway(i) ) {
sprintf( shapefile_name, "runway_%d", i ); sprintf( shapefile_name, "runway_%u", i );
} else { } else {
strcpy( shapefile_name, "" ); strcpy( shapefile_name, "" );
} }
@ -393,7 +350,7 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
//slivers.clear(); //slivers.clear();
if ( isDebugPavement(i) ) { if ( isDebugPavement(i) ) {
sprintf( shapefile_name, "pvmnt_%d", i ); sprintf( shapefile_name, "pvmnt_%u", i );
} else { } else {
strcpy( shapefile_name, "" ); strcpy( shapefile_name, "" );
} }
@ -427,7 +384,7 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
//slivers.clear(); //slivers.clear();
if ( isDebugTaxiway(i) ) { if ( isDebugTaxiway(i) ) {
sprintf( shapefile_name, "taxiway_%d", i ); sprintf( shapefile_name, "taxiway_%u", i );
} else { } else {
strcpy( shapefile_name, "" ); strcpy( shapefile_name, "" );
} }
@ -813,7 +770,6 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
group_list strips_tc; strips_tc.clear(); group_list strips_tc; strips_tc.clear();
string_list strip_materials; strip_materials.clear(); string_list strip_materials; strip_materials.clear();
int index;
int_list pt_v, tri_v, strip_v; int_list pt_v, tri_v, strip_v;
int_list pt_n, tri_n, strip_n; int_list pt_n, tri_n, strip_n;
int_list tri_tc, strip_tc; int_list tri_tc, strip_tc;
@ -837,9 +793,7 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
sgboTri.material = material; sgboTri.material = material;
for (int l = 0; l < 3; ++l) { for (int l = 0; l < 3; ++l) {
int index; int index = nodes.add( poly.GetTriNode( i, l ) );
index = nodes.add( poly.GetTriNode( i, l ) );
sgboTri.v_list.push_back( index ); sgboTri.v_list.push_back( index );
// use 'the' normal // use 'the' normal
@ -868,9 +822,7 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
sgboTri.material = material; sgboTri.material = material;
for (int l = 0; l < 3; ++l) { for (int l = 0; l < 3; ++l) {
int index; int index = nodes.add( poly.GetTriNode( i, l ) );
index = nodes.add( poly.GetTriNode( i, l ) );
sgboTri.v_list.push_back( index ); sgboTri.v_list.push_back( index );
// use 'the' normal // use 'the' normal
@ -899,9 +851,7 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
sgboTri.material = material; sgboTri.material = material;
for (int l = 0; l < 3; ++l) { for (int l = 0; l < 3; ++l) {
int index; int index = nodes.add( poly.GetTriNode( i, l ) );
index = nodes.add( poly.GetTriNode( i, l ) );
sgboTri.v_list.push_back( index ); sgboTri.v_list.push_back( index );
// use 'the' normal // use 'the' normal
@ -924,9 +874,7 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
sgboTri.material = material; sgboTri.material = material;
for (int l = 0; l < 3; ++l) { for (int l = 0; l < 3; ++l) {
int index; int index = nodes.add( base_poly.GetTriNode( k, l ) );
index = nodes.add( base_poly.GetTriNode( k, l ) );
sgboTri.v_list.push_back( index ); sgboTri.v_list.push_back( index );
// use 'the' normal // use 'the' normal
@ -947,7 +895,7 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
{ {
for ( unsigned int j = 0; j < divided_base.ContourSize( i ); ++j ) for ( unsigned int j = 0; j < divided_base.ContourSize( i ); ++j )
{ {
index = nodes.add( divided_base.GetNode(i, j) ); int index = nodes.add( divided_base.GetNode(i, j) );
TG_LOG(SG_GENERAL, SG_DEBUG, "added base point " << divided_base.GetNode(i, j) << " at " << index ); TG_LOG(SG_GENERAL, SG_DEBUG, "added base point " << divided_base.GetNode(i, j) << " at " << index );
} }
} }
@ -1080,9 +1028,7 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
for ( unsigned int j = 0; j < rwy_lights[i].ContourSize(); ++j ) for ( unsigned int j = 0; j < rwy_lights[i].ContourSize(); ++j )
{ {
int index; int index = nodes.add( rwy_lights[i].GetPosition(j) );
index = nodes.add( rwy_lights[i].GetPosition(j) );
sgboPt.v_list.push_back( index ); sgboPt.v_list.push_back( index );
index = normals.add( rwy_lights[i].GetNormal(j) ); index = normals.add( rwy_lights[i].GetNormal(j) );
@ -1106,10 +1052,10 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
} }
SGVec3d gbs_center = SGVec3d::fromGeod( b.get_center() ); SGVec3d gbs_center = SGVec3d::fromGeod( b.get_center() );
double dist_squared, radius_squared = 0; double radius_squared = 0;
for ( unsigned int i = 0; i < wgs84_nodes.size(); ++i ) for ( unsigned int i = 0; i < wgs84_nodes.size(); ++i )
{ {
dist_squared = distSqr(gbs_center, wgs84_nodes[i]); double dist_squared = distSqr(gbs_center, wgs84_nodes[i]);
if ( dist_squared > radius_squared ) { if ( dist_squared > radius_squared ) {
radius_squared = dist_squared; radius_squared = dist_squared;
} }
@ -1157,7 +1103,6 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
} }
#endif #endif
SGGeod ref_geod;
// calc elevations and write out windsock references // calc elevations and write out windsock references
TG_LOG(SG_GENERAL, SG_DEBUG, "Computing windsock node elevations"); TG_LOG(SG_GENERAL, SG_DEBUG, "Computing windsock node elevations");
@ -1181,7 +1126,7 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
// write out beacon references // write out beacon references
for ( unsigned int i = 0; i < beacons.size(); ++i ) for ( unsigned int i = 0; i < beacons.size(); ++i )
{ {
ref_geod = beacons[i]->GetLoc(); SGGeod ref_geod = beacons[i]->GetLoc();
ref_geod.setElevationM( apt_surf.calc_elevation( ref_geod, 0.0 ) ); ref_geod.setElevationM( apt_surf.calc_elevation( ref_geod, 0.0 ) );
write_index_object_shared( objpath, b, ref_geod, write_index_object_shared( objpath, b, ref_geod,
@ -1192,7 +1137,7 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
// write out taxiway signs references // write out taxiway signs references
for ( unsigned int i = 0; i < signs.size(); ++i ) for ( unsigned int i = 0; i < signs.size(); ++i )
{ {
ref_geod = signs[i]->GetLoc(); SGGeod ref_geod = signs[i]->GetLoc();
ref_geod.setElevationM( apt_surf.calc_elevation( ref_geod, 0.0 ) ); ref_geod.setElevationM( apt_surf.calc_elevation( ref_geod, 0.0 ) );
write_index_object_sign( objpath, b, ref_geod, write_index_object_sign( objpath, b, ref_geod,
signs[i]->GetDefinition(), signs[i]->GetDefinition(),
@ -1207,7 +1152,7 @@ void Airport::BuildBtg(const std::string& root, const string_list& elev_src )
for ( unsigned int j = 0; j < buoys.GetSize(); ++j ) for ( unsigned int j = 0; j < buoys.GetSize(); ++j )
{ {
ref_geod = buoys.GetNode(j); SGGeod ref_geod = buoys.GetNode(j);
ref_geod.setElevationM( apt_surf.calc_elevation( ref_geod, 0.0 ) ); ref_geod.setElevationM( apt_surf.calc_elevation( ref_geod, 0.0 ) );
write_index_object_shared( objpath, b, ref_geod, write_index_object_shared( objpath, b, ref_geod,
"Models/Airport/water_rw_buoy.xml", "Models/Airport/water_rw_buoy.xml",
@ -1258,7 +1203,7 @@ bool Airport::CheckZFightingTriangles( const char* prefix, const char* debug_roo
tgContour intContour = intersection.GetContour( m ); tgContour intContour = intersection.GetContour( m );
if ( (intContour.GetSize() > 2) && (intContour.GetArea() > min_area_thresh) ) { if ( (intContour.GetSize() > 2) && (intContour.GetArea() > min_area_thresh) ) {
TG_LOG( SG_GENERAL, SG_ALERT, prefix << "Z-FIGHTING between runway poly " << i << " and pavement poly " << k << " contour has " << intContour.GetSize() << " nodes " << " area is " << intContour.GetArea() ); TG_LOG( SG_GENERAL, SG_ALERT, prefix << "Z-FIGHTING between runway poly " << i << " and pavement poly " << k << " contour has " << intContour.GetSize() << " nodes " << " area is " << intContour.GetArea() );
sprintf( desc, "rwy_%06d_pvmt_%06d", i, j ); sprintf( desc, "rwy_%06u_pvmt_%06u", i, j );
tgShapefile::FromContour( intContour, debug_root, layer, desc ); tgShapefile::FromContour( intContour, debug_root, layer, desc );
zfighting = true; zfighting = true;
} }
@ -1292,7 +1237,7 @@ bool Airport::CheckZFightingTriangles( const char* prefix, const char* debug_roo
tgContour intContour = intersection.GetContour( m ); tgContour intContour = intersection.GetContour( m );
if ( (intContour.GetSize() > 2) && (intContour.GetArea() > min_area_thresh) ) { if ( (intContour.GetSize() > 2) && (intContour.GetArea() > min_area_thresh) ) {
TG_LOG( SG_GENERAL, SG_ALERT, prefix << "Z-FIGHTING between pavement poly " << i << " and runway poly " << k << " contour has " << intContour.GetSize() << " nodes " << " area is " << intContour.GetArea() ); TG_LOG( SG_GENERAL, SG_ALERT, prefix << "Z-FIGHTING between pavement poly " << i << " and runway poly " << k << " contour has " << intContour.GetSize() << " nodes " << " area is " << intContour.GetArea() );
sprintf( desc, "pvmt_%06d_rwy_%06d", i, j ); sprintf( desc, "pvmt_%06u_rwy_%06u", i, j );
tgShapefile::FromContour( intContour, debug_root, layer, desc ); tgShapefile::FromContour( intContour, debug_root, layer, desc );
zfighting = true; zfighting = true;
} }
@ -1325,7 +1270,7 @@ bool Airport::CheckZFightingTriangles( const char* prefix, const char* debug_roo
tgContour intContour = intersection.GetContour( m ); tgContour intContour = intersection.GetContour( m );
if ( (intContour.GetSize() > 2) && (intContour.GetArea() > min_area_thresh) ) { if ( (intContour.GetSize() > 2) && (intContour.GetArea() > min_area_thresh) ) {
TG_LOG( SG_GENERAL, SG_ALERT, prefix << "Z-FIGHTING between base poly and runway poly " << j << " contour has " << intContour.GetSize() << " nodes " << " area is " << intContour.GetArea() ); TG_LOG( SG_GENERAL, SG_ALERT, prefix << "Z-FIGHTING between base poly and runway poly " << j << " contour has " << intContour.GetSize() << " nodes " << " area is " << intContour.GetArea() );
sprintf( desc, "base_rwy_%06d", j ); sprintf( desc, "base_rwy_%06u", j );
tgShapefile::FromContour( intContour, debug_root, layer, desc ); tgShapefile::FromContour( intContour, debug_root, layer, desc );
zfighting = true; zfighting = true;
} }
@ -1353,7 +1298,7 @@ bool Airport::CheckZFightingTriangles( const char* prefix, const char* debug_roo
tgContour intContour = intersection.GetContour( m ); tgContour intContour = intersection.GetContour( m );
if ( (intContour.GetSize() > 2) && (intContour.GetArea() > min_area_thresh) ) { if ( (intContour.GetSize() > 2) && (intContour.GetArea() > min_area_thresh) ) {
TG_LOG( SG_GENERAL, SG_ALERT, prefix << "Z-FIGHTING between base poly and pavement poly " << j << " contour has " << intContour.GetSize() << " nodes " << " area is " << intContour.GetArea() ); TG_LOG( SG_GENERAL, SG_ALERT, prefix << "Z-FIGHTING between base poly and pavement poly " << j << " contour has " << intContour.GetSize() << " nodes " << " area is " << intContour.GetArea() );
sprintf( desc, "base_pvmt_%06d", j ); sprintf( desc, "base_pvmt_%06u", j );
tgShapefile::FromContour( intContour, debug_root, layer, desc ); tgShapefile::FromContour( intContour, debug_root, layer, desc );
zfighting = true; zfighting = true;
} }

View file

@ -1,6 +1,8 @@
#ifndef _AIRPORT_H_ #ifndef _AIRPORT_H_
#define _AIRPORT_H_ #define _AIRPORT_H_
#include <memory>
#include <simgear/timing/timestamp.hxx> #include <simgear/timing/timestamp.hxx>
#include <simgear/math/sg_types.hxx> #include <simgear/math/sg_types.hxx>
#include <simgear/threads/SGThread.hxx> #include <simgear/threads/SGThread.hxx>
@ -20,46 +22,46 @@ public:
Airport( int c, char* def); Airport( int c, char* def);
~Airport(); ~Airport();
void AddRunway( Runway* runway ) void AddRunway( std::shared_ptr<Runway> runway )
{ {
runways.push_back( runway ); runways.push_back( runway );
} }
void AddWaterRunway( WaterRunway* waterrunway ) void AddWaterRunway( std::shared_ptr<WaterRunway> waterrunway )
{ {
waterrunways.push_back( waterrunway ); waterrunways.push_back( waterrunway );
} }
void AddObj( LightingObj* lightobj ) void AddObj( std::shared_ptr<LightingObj> lightobj )
{ {
lightobjects.push_back( lightobj ); lightobjects.push_back( lightobj );
} }
void AddHelipad( Helipad* helipad ) void AddHelipad( std::shared_ptr<Helipad> helipad )
{ {
helipads.push_back( helipad ); helipads.push_back( helipad );
} }
void AddTaxiway( Taxiway* taxiway ) void AddTaxiway( std::shared_ptr<Taxiway> taxiway )
{ {
taxiways.push_back( taxiway ); taxiways.push_back( taxiway );
} }
void AddPavement( ClosedPoly* pavement ) void AddPavement( std::shared_ptr<ClosedPoly> pavement )
{ {
pavements.push_back( pavement ); pavements.push_back( pavement );
} }
void AddFeature( LinearFeature* feature ) void AddFeature( std::shared_ptr<LinearFeature> feature )
{ {
features.push_back( feature ); features.push_back( feature );
} }
void AddFeatures( FeatureList* feature_list ) void AddFeatures( FeatureList feature_list )
{ {
for (unsigned int i=0; i<feature_list->size(); i++) for (auto feature : feature_list)
{ {
features.push_back( feature_list->at(i) ); features.push_back( feature );
} }
} }
@ -68,22 +70,22 @@ public:
return features.size(); return features.size();
} }
void AddBoundary( ClosedPoly* bndry ) void AddBoundary( std::shared_ptr<ClosedPoly> bndry )
{ {
boundary.push_back( bndry ); boundary.push_back( bndry );
} }
void AddWindsock( Windsock* windsock ) void AddWindsock( std::shared_ptr<Windsock> windsock )
{ {
windsocks.push_back( windsock ); windsocks.push_back( windsock );
} }
void AddBeacon( Beacon* beacon ) void AddBeacon( std::shared_ptr<Beacon> beacon )
{ {
beacons.push_back( beacon ); beacons.push_back( beacon );
} }
void AddSign( Sign* sign ) void AddSign( std::shared_ptr<Sign> sign )
{ {
signs.push_back( sign ); signs.push_back( sign );
} }
@ -163,6 +165,6 @@ private:
debug_map debug_features; debug_map debug_features;
}; };
typedef std::vector <Airport *> AirportList; typedef std::vector<std::shared_ptr<Airport>> AirportList;
#endif #endif

View file

@ -4,6 +4,7 @@
#include <vector> #include <vector>
#include <string.h> #include <string.h>
#include <float.h> #include <float.h>
#include <memory>
#include <simgear/debug/logstream.hxx> #include <simgear/debug/logstream.hxx>
#include <simgear/math/SGMath.hxx> #include <simgear/math/SGMath.hxx>
@ -119,10 +120,9 @@ inline double CalculateTheta( const SGVec3d& dirCur, const SGVec3d& dirNext, con
class BezNode class BezNode
{ {
public: public:
BezNode( SGGeod l ) explicit BezNode( SGGeod l ) :
loc(l)
{ {
loc = l;
has_prev_cp = false; has_prev_cp = false;
has_next_cp = false; has_next_cp = false;
@ -132,28 +132,18 @@ public:
close = false; close = false;
} }
BezNode( double lat, double lon ) BezNode( double lat, double lon ) :
BezNode(SGGeod::fromDeg(lon, lat))
{ {
loc = SGGeod::fromDeg( lon, lat );
has_prev_cp = false;
has_next_cp = false;
mark = 0;
light = 0;
term = false;
close = false;
} }
BezNode( SGGeod l, SGGeod cp ) BezNode( SGGeod l, SGGeod cp ) :
loc(l),
prev_cp(Mirror(cp)),
next_cp(cp)
{ {
loc = l;
next_cp = cp;
has_next_cp = true;
prev_cp = Mirror(cp);
has_prev_cp = true; has_prev_cp = true;
has_next_cp = true;
mark = 0; mark = 0;
light = 0; light = 0;
@ -161,20 +151,9 @@ public:
close = false; close = false;
} }
BezNode( double lat, double lon, double cp_lat, double cp_lon ) BezNode( double lat, double lon, double cp_lat, double cp_lon ) :
BezNode(SGGeod::fromDeg(lon, lat), SGGeod::fromDeg(cp_lon, cp_lat))
{ {
loc = SGGeod::fromDeg( lon, lat );
next_cp = SGGeod::fromDeg( cp_lon, cp_lat );
has_next_cp = true;
prev_cp = Mirror( next_cp );
has_prev_cp = true;
mark = 0;
light = 0;
term = false;
close = false;
} }
SGGeod Mirror( const SGGeod& pt ) SGGeod Mirror( const SGGeod& pt )
@ -282,8 +261,8 @@ private:
// array of BezNodes make a contour // array of BezNodes make a contour
typedef std::vector <BezNode *> BezContour; typedef std::vector<std::shared_ptr<BezNode>> BezContour;
typedef std::vector <BezContour *> BezContourArray; typedef std::vector<BezContour> BezContourArray;
#endif #endif

View file

@ -21,50 +21,33 @@ static void stringPurifier( std::string& s )
} }
} }
ClosedPoly::ClosedPoly( char* desc ) ClosedPoly::ClosedPoly( char* desc ) :
is_pavement(false),
is_border(false),
has_feature(false),
surface_type(0),
smoothness(0.0),
texture_heading(0.0),
description(std::string(desc ? desc : "none"))
{ {
is_pavement = false; is_border = true;
is_border = true;
has_feature = false;
if ( desc )
{
description = desc;
stringPurifier(description);
}
else
{
description = "none";
}
boundary = NULL; stringPurifier(description);
cur_contour = NULL;
cur_feature = NULL; boundary.clear();
cur_contour.clear();
} }
ClosedPoly::ClosedPoly( int st, float s, float th, char* desc ) ClosedPoly::ClosedPoly( int st, float s, float th, char* desc ) :
ClosedPoly( desc )
{ {
surface_type = st; surface_type = st;
smoothness = s; smoothness = s;
texture_heading = th; texture_heading = th;
is_pavement = (surface_type != 15) ? true : false; // wrong?? is_pavement = (surface_type != 15) ? true : false; // wrong??
is_border = false; is_border = false;
has_feature = true; has_feature = true;
if ( desc )
{
description = desc;
stringPurifier(description);
}
else
{
description = "none";
}
boundary = NULL;
cur_contour = NULL;
cur_feature = NULL;
} }
ClosedPoly::~ClosedPoly() ClosedPoly::~ClosedPoly()
@ -72,14 +55,9 @@ ClosedPoly::~ClosedPoly()
TG_LOG( SG_GENERAL, SG_DEBUG, "Deleting ClosedPoly " << description ); TG_LOG( SG_GENERAL, SG_DEBUG, "Deleting ClosedPoly " << description );
} }
void ClosedPoly::AddNode( BezNode* node ) void ClosedPoly::AddNode( std::shared_ptr<BezNode> node )
{ {
// if this is the first node of the contour - create a new contour cur_contour.push_back( node );
if (!cur_contour)
{
cur_contour = new BezContour;
}
cur_contour->push_back( node );
TG_LOG(SG_GENERAL, SG_DEBUG, "CLOSEDPOLY::ADDNODE : " << node->GetLoc() ); TG_LOG(SG_GENERAL, SG_DEBUG, "CLOSEDPOLY::ADDNODE : " << node->GetLoc() );
@ -89,7 +67,7 @@ void ClosedPoly::AddNode( BezNode* node )
if (!cur_feature) if (!cur_feature)
{ {
std::string feature_desc = description + " - "; std::string feature_desc = description + " - ";
if (boundary) if (boundary.size() == 0)
{ {
feature_desc += "hole"; feature_desc += "hole";
} }
@ -99,7 +77,7 @@ void ClosedPoly::AddNode( BezNode* node )
} }
TG_LOG(SG_GENERAL, SG_DEBUG, " Adding node " << node->GetLoc() << " to current linear feature " << cur_feature); TG_LOG(SG_GENERAL, SG_DEBUG, " Adding node " << node->GetLoc() << " to current linear feature " << cur_feature);
cur_feature = new LinearFeature(feature_desc, 1.0f ); cur_feature = std::make_shared<LinearFeature>(feature_desc, 1.0f);
} }
cur_feature->AddNode( node ); cur_feature->AddNode( node );
} }
@ -122,55 +100,55 @@ void ClosedPoly::CloseCurContour()
// add the contour to the poly - first one is the outer boundary // add the contour to the poly - first one is the outer boundary
// subsequent contours are holes // subsequent contours are holes
if ( boundary == NULL ) if ( boundary.size() == 0 )
{ {
boundary = cur_contour; boundary = cur_contour;
// generate the convex hull from the bezcontour node locations // generate the convex hull from the bezcontour node locations
// CreateConvexHull(); // CreateConvexHull();
cur_contour = NULL; cur_contour.clear();
} }
else else
{ {
holes.push_back( cur_contour ); holes.push_back( cur_contour );
cur_contour = NULL; cur_contour.clear();
} }
} }
void ClosedPoly::ConvertContour( BezContour* src, tgContour& dst ) void ClosedPoly::ConvertContour( const BezContour& src, tgContour& dst )
{ {
BezNode* curNode; std::shared_ptr<BezNode> curNode;
BezNode* nextNode; std::shared_ptr<BezNode> nextNode;
SGGeod curLoc; SGGeod curLoc;
SGGeod nextLoc; SGGeod nextLoc;
SGGeod cp1; SGGeod cp1;
SGGeod cp2; SGGeod cp2;
int curve_type = CURVE_LINEAR; int curve_type;
double total_dist; double total_dist;
int num_segs = BEZIER_DETAIL; int num_segs;
TG_LOG(SG_GENERAL, SG_DEBUG, "Creating a contour with " << src->size() << " nodes"); TG_LOG(SG_GENERAL, SG_DEBUG, "Creating a contour with " << src.size() << " nodes");
// clear anything in this point list // clear anything in this point list
dst.Erase(); dst.Erase();
// iterate through each bezier node in the contour // iterate through each bezier node in the contour
for (unsigned int i = 0; i <= src->size()-1; i++) for (unsigned int i = 0; i < src.size(); ++i)
{ {
TG_LOG(SG_GENERAL, SG_DEBUG, "\nHandling Node " << i << "\n\n"); TG_LOG(SG_GENERAL, SG_DEBUG, "\nHandling Node " << i << "\n\n");
curNode = src->at(i); curNode = src.at(i);
if (i < src->size() - 1) if (i < src.size() - 1)
{ {
nextNode = src->at(i+1); nextNode = src.at(i + 1);
} }
else else
{ {
// for the last node, next is the first. as all contours are closed // for the last node, next is the first node, as all contours are closed
nextNode = src->at(0); nextNode = src.at(0);
} }
// now determine how we will iterate from current node to next node // now determine how we will iterate from current node to next node
@ -337,14 +315,14 @@ void ClosedPoly::Finish()
tgContour dst_contour; tgContour dst_contour;
// error handling // error handling
if (boundary == NULL) if (boundary.size() == 0)
{ {
TG_LOG(SG_GENERAL, SG_ALERT, "no boundary"); TG_LOG(SG_GENERAL, SG_ALERT, "no boundary");
} }
TG_LOG(SG_GENERAL, SG_DEBUG, "Converting a poly with " << holes.size() << " holes"); TG_LOG(SG_GENERAL, SG_DEBUG, "Converting a poly with " << holes.size() << " holes");
if (boundary != NULL) if (boundary.size() != 0)
{ {
// create the boundary // create the boundary
ConvertContour( boundary, dst_contour ); ConvertContour( boundary, dst_contour );
@ -367,22 +345,9 @@ void ClosedPoly::Finish()
} }
// save memory by deleting unneeded resources // save memory by deleting unneeded resources
for (unsigned int i=0; i<boundary->size(); i++) boundary.clear();
{
delete boundary->at(i);
}
delete boundary;
boundary = NULL;
// and the hole contours // and the hole contours
for (unsigned int i=0; i<holes.size(); i++)
{
for (unsigned int j=0; j<holes[i]->size(); j++)
{
delete holes[i]->at(j);
}
}
holes.clear(); holes.clear();
} }
@ -458,10 +423,10 @@ int ClosedPoly::BuildBtg( tgpolygon_list& rwy_polys, tgcontour_list& slivers, tg
int ClosedPoly::BuildBtg( tgpolygon_list& rwy_polys, tgcontour_list& slivers, tgAccumulator& accum, std::string& shapefile_name ) int ClosedPoly::BuildBtg( tgpolygon_list& rwy_polys, tgcontour_list& slivers, tgAccumulator& accum, std::string& shapefile_name )
{ {
char layer[128];
if ( is_pavement && pre_tess.Contours() ) if ( is_pavement && pre_tess.Contours() )
{ {
char layer[128];
if( shapefile_name.size() ) { if( shapefile_name.size() ) {
sprintf( layer, "%s_preclip", shapefile_name.c_str() ); sprintf( layer, "%s_preclip", shapefile_name.c_str() );
tgShapefile::FromPolygon( pre_tess, "./airport_dbg", layer, std::string("preclip") ); tgShapefile::FromPolygon( pre_tess, "./airport_dbg", layer, std::string("preclip") );

View file

@ -1,6 +1,8 @@
#ifndef _BEZPOLY_H_ #ifndef _BEZPOLY_H_
#define _BEZPOLY_H_ #define _BEZPOLY_H_
#include <memory>
#include <terragear/tg_polygon.hxx> #include <terragear/tg_polygon.hxx>
#include "beznode.hxx" #include "beznode.hxx"
@ -9,12 +11,12 @@
class ClosedPoly class ClosedPoly
{ {
public: public:
ClosedPoly( char* desc ); explicit ClosedPoly( char* desc );
ClosedPoly( int st, float s, float th, char* desc ); ClosedPoly( int st, float s, float th, char* desc );
~ClosedPoly(); ~ClosedPoly();
inline std::string GetDescription() { return description; } inline std::string GetDescription() { return description; }
void AddNode( BezNode* node ); void AddNode( std::shared_ptr<BezNode> node );
void CloseCurContour(); void CloseCurContour();
void Finish(); void Finish();
@ -36,15 +38,15 @@ public:
tgAccumulator& accum, tgAccumulator& accum,
std::string& shapefile_name ); std::string& shapefile_name );
FeatureList* GetFeatures() FeatureList& GetFeatures()
{ {
return &features; return features;
} }
private: private:
// convert the BezierPoly to a normal Poly (adding nodes for the curves) // convert the BezierPoly to a normal Poly (adding nodes for the curves)
void CreateConvexHull( void ); void CreateConvexHull( void );
void ConvertContour( BezContour* src, tgContour& dst ); void ConvertContour( const BezContour& src, tgContour& dst );
std::string GetMaterial( int surface ); std::string GetMaterial( int surface );
@ -58,13 +60,13 @@ private:
std::string description; std::string description;
// outer boundary definition as bezier nodes // outer boundary definition as bezier nodes
BezContour* boundary; BezContour boundary;
// holes // holes
BezContourArray holes; BezContourArray holes;
// contour that nodes will be added until done // contour that nodes will be added until done
BezContour* cur_contour; BezContour cur_contour;
// Converted polygon after parsing complete // Converted polygon after parsing complete
tgPolygon pre_tess; tgPolygon pre_tess;
@ -73,10 +75,10 @@ private:
tgpolygon_list shoulder_polys; tgpolygon_list shoulder_polys;
// pavement definitions have multiple linear features (markings and lights for each contour) // pavement definitions have multiple linear features (markings and lights for each contour)
LinearFeature* cur_feature; std::shared_ptr<LinearFeature> cur_feature;
FeatureList features; FeatureList features;
}; };
typedef std::vector <ClosedPoly *> PavementList; typedef std::vector<std::shared_ptr<ClosedPoly>> PavementList;
#endif #endif

View file

@ -37,7 +37,7 @@
// lookup node elevations for each point in the SGGeod list. Returns // lookup node elevations for each point in the SGGeod list. Returns
// average of all points. Doesn't modify the original list. // average of all points. Doesn't modify the original list.
double tgAverageElevation( const std::string &root, const string_list elev_src, double tgAverageElevation( const std::string &root, const string_list elev_src,
const std::vector<SGGeod> points_source ) const std::vector<SGGeod>& points_source )
{ {
bool done = false; bool done = false;
unsigned int i; unsigned int i;
@ -109,7 +109,7 @@ double tgAverageElevation( const std::string &root, const string_list elev_src,
} }
} }
array.close(); array.unload();
} else { } else {
done = true; done = true;
} }

View file

@ -25,7 +25,7 @@
// lookup node elevations for each point in the SGGeod list. Returns // lookup node elevations for each point in the SGGeod list. Returns
// average of all points. Doesn't modify the original list. // average of all points. Doesn't modify the original list.
double tgAverageElevation( const std::string &root, const string_list elev_src, double tgAverageElevation( const std::string &root, const string_list elev_src,
const std::vector<SGGeod> points_source ); const std::vector<SGGeod>& points_source );
// lookup node elevations for each point in the specified nurbs++ // lookup node elevations for each point in the specified nurbs++
// matrix. // matrix.

View file

@ -23,19 +23,26 @@
#include "runway.hxx" #include "runway.hxx"
#include "debug.hxx" #include "debug.hxx"
#include <cstdio>
#include <stdlib.h>
Helipad::Helipad(char* definition) Helipad::Helipad(char* definition)
{ {
// helipad format:
// designator lat lon heading length width surface markings shoulder smoothness edge-lighting
// example:
// "H1 21.30433555 -157.85586778 0.00 10.70 10.70 2 0 0 0.25 0\r"
// format: std::istringstream ss(definition);
// helipad designator lat lon heading length width surface markings shoulder smoothness edge lighting ss >> heli.designator
>> heli.lat
// int fscanf(FILE *stream, const char *format, ...); >> heli.lon
sscanf(definition, "%s %lf %lf %lf %lf %lf %d %d %d %lf %d", >> heli.heading
heli.designator, &heli.lat, &heli.lon, &heli.heading, &heli.length, &heli.width, &heli.surface, >> heli.length
&heli.marking, &heli.shoulder, &heli.smoothness, &heli.edge_lights); >> heli.width
>> heli.surface
>> heli.marking
>> heli.shoulder
>> heli.smoothness
>> heli.edge_lights;
TG_LOG(SG_GENERAL, SG_DEBUG, "Read helipad: (" << heli.lon << "," << heli.lat << ") heading: " << heli.heading << " length: " << heli.length << " width: " << heli.width ); TG_LOG(SG_GENERAL, SG_DEBUG, "Read helipad: (" << heli.lon << "," << heli.lat << ") heading: " << heli.heading << " length: " << heli.length << " width: " << heli.width );
} }

View file

@ -16,6 +16,8 @@
#ifndef _HELIPAD_HXX #ifndef _HELIPAD_HXX
#define _HELIPAD_HXX #define _HELIPAD_HXX
#include <memory>
#include <terragear/tg_polygon.hxx> #include <terragear/tg_polygon.hxx>
#include <terragear/tg_accumulator.hxx> #include <terragear/tg_accumulator.hxx>
#include <terragear/tg_light.hxx> #include <terragear/tg_light.hxx>
@ -23,7 +25,7 @@
class Helipad class Helipad
{ {
public: public:
Helipad(char* def); explicit Helipad(char* def);
void BuildBtg( tgpolygon_list& heli_polys, void BuildBtg( tgpolygon_list& heli_polys,
tglightcontour_list& heli_lights, tglightcontour_list& heli_lights,
@ -54,18 +56,18 @@ public:
private: private:
struct TGRunway { struct TGRunway {
// data for helipad // data for helipad
char designator[16]; char designator[16];
double lat; double lat;
double lon; double lon;
double heading; double heading;
double length; double length;
double width; double width;
int surface; int surface;
int marking; int marking;
int shoulder; int shoulder;
double smoothness; double smoothness;
int edge_lights; int edge_lights;
}; };
TGRunway heli; TGRunway heli;
@ -91,6 +93,6 @@ private:
}; };
typedef std::vector <Helipad *> HelipadList; typedef std::vector<std::shared_ptr<Helipad>> HelipadList;
#endif #endif

View file

@ -402,7 +402,6 @@ tglightcontour_list Runway::gen_calvert( const string &kind, bool recip )
{ {
tgLightContour w_lights; tgLightContour w_lights;
tgLightContour r_lights; tgLightContour r_lights;
int i, j;
string flag; string flag;
SGVec3f normal = gen_runway_light_vector( 3.0, recip ); SGVec3f normal = gen_runway_light_vector( 3.0, recip );
@ -438,9 +437,7 @@ tglightcontour_list Runway::gen_calvert( const string &kind, bool recip )
// first set of single lights // first set of single lights
pt = ref; pt = ref;
for ( i = 0; i < count; ++i ) { for ( int i = 0; i < count; ++i ) {
// centre lights // centre lights
pt = SGGeodesy::direct(pt, length_hdg, -vert_space); pt = SGGeodesy::direct(pt, length_hdg, -vert_space);
@ -529,7 +526,7 @@ tglightcontour_list Runway::gen_calvert( const string &kind, bool recip )
int num_lights = 0; int num_lights = 0;
// draw nice crossbars // draw nice crossbars
for ( i = 0; i < 5; i++ ) { for ( int i = 0; i < 5; ++i ) {
switch ( i ) { switch ( i ) {
case 0: case 0:
num_lights = 4; num_lights = 4;
@ -549,14 +546,14 @@ tglightcontour_list Runway::gen_calvert( const string &kind, bool recip )
} }
pt = crossbar[i]; pt = crossbar[i];
for ( j = 0 ; j < num_lights; j++ ) { for ( int j = 0 ; j < num_lights; ++j ) {
// left side lights // left side lights
pt = SGGeodesy::direct(pt, left_hdg, horiz_space); pt = SGGeodesy::direct(pt, left_hdg, horiz_space);
w_lights.AddLight(pt, normal); w_lights.AddLight(pt, normal);
} }
pt = crossbar[i]; pt = crossbar[i];
for ( j = 0; j < num_lights; j++ ) { for ( int j = 0; j < num_lights; ++j ) {
// right side lights // right side lights
pt = SGGeodesy::direct(pt, left_hdg, -horiz_space); pt = SGGeodesy::direct(pt, left_hdg, -horiz_space);
w_lights.AddLight(pt, normal); w_lights.AddLight(pt, normal);

View file

@ -4,42 +4,42 @@
#include "beznode.hxx" #include "beznode.hxx"
#include "linearfeature.hxx" #include "linearfeature.hxx"
void LinearFeature::ConvertContour( BezContour* src, bool closed ) void LinearFeature::ConvertContour( const BezContour& src, bool closed )
{ {
BezNode* curNode; std::shared_ptr<BezNode> curNode;
BezNode* nextNode; std::shared_ptr<BezNode> nextNode;
SGGeod curLoc; SGGeod curLoc;
SGGeod nextLoc; SGGeod nextLoc;
SGGeod cp1; SGGeod cp1;
SGGeod cp2; SGGeod cp2;
int curve_type = CURVE_LINEAR; int curve_type;
double total_dist; double total_dist;
double theta1, theta2; double theta1, theta2;
int num_segs = BEZIER_DETAIL; int num_segs;
Marking* cur_mark = NULL; Marking* cur_mark = NULL;
Lighting* cur_light = NULL; Lighting* cur_light = NULL;
TG_LOG(SG_GENERAL, SG_DEBUG, " LinearFeature::ConvertContour - Creating a contour with " << src->size() << " nodes"); TG_LOG(SG_GENERAL, SG_DEBUG, " LinearFeature::ConvertContour - Creating a contour with " << src.size() << " nodes");
// clear anything in the point list // clear anything in the point list
points.Erase(); points.Erase();
// iterate through each bezier node in the contour // iterate through each bezier node in the contour
for (unsigned int i=0; i <= src->size()-1; i++) for (unsigned int i = 0; i < src.size(); ++i)
{ {
curNode = src->at(i); curNode = src.at(i);
if (i < src->size() - 1) if (i < src.size() - 1)
{ {
nextNode = src->at(i+1); nextNode = src.at(i + 1);
} }
else else
{ {
// for the last node, next is the first. as all contours are closed // for the last node, next is the first node, as all contours are closed
nextNode = src->at(0); nextNode = src.at(0);
} }
//////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////
@ -161,7 +161,7 @@ void LinearFeature::ConvertContour( BezContour* src, bool closed )
// Sometimes, the control point lies just beyond the final point. We try to make a 'hook' at the end, which makes some really bad polys // Sometimes, the control point lies just beyond the final point. We try to make a 'hook' at the end, which makes some really bad polys
// Just convert the entire segment to linear // Just convert the entire segment to linear
// this can be detected in quadratic curves (current issue in LFKJ) when the contol point lies within the line generated from point 1 to point 2 // this can be detected in quadratic curves (current issue in LFKJ) when the contol point lies within the line generated from point 1 to point 2
// theat close to 180 at the control point to the cur node and next node // at close to 180 at the control point to the cur node and next node
if ( curve_type == CURVE_QUADRATIC ) if ( curve_type == CURVE_QUADRATIC )
{ {
if ( (std::abs(theta1 - 180.0) < 5.0 ) || (std::abs(theta1) < 5.0 ) || (std::isnan(theta1)) ) if ( (std::abs(theta1 - 180.0) < 5.0 ) || (std::abs(theta1) < 5.0 ) || (std::isnan(theta1)) )
@ -370,23 +370,21 @@ int LinearFeature::Finish( bool closed, unsigned int idx )
double heading; double heading;
double dist; double dist;
double az2; double az2;
double last_end_v;
double width = 0; double width = 0;
std::string material; std::string material;
double cur_light_dist = 0.0f;
double light_delta = 0; double light_delta = 0;
bool markStarted; bool markStarted;
// create the inner and outer boundaries to generate polys // create the inner and outer boundaries to generate polys
// this generates 2 point lists for the contours, and remembers // this generates 2 point lists for the contours, and remembers
// the start stop points for markings and lights // the start stop points for markings and lights
ConvertContour( &contour, closed ); ConvertContour( contour, closed );
// now generate the supoerpoly and texparams lists for markings // now generate the supoerpoly and texparams lists for markings
for (unsigned int i=0; i<marks.size(); i++) for (unsigned int i=0; i<marks.size(); i++)
{ {
markStarted = false; markStarted = false;
last_end_v = 0.0f; double last_end_v = 0.0;
// which material for this mark? // which material for this mark?
switch( marks[i]->type ) switch( marks[i]->type )
@ -568,7 +566,7 @@ int LinearFeature::Finish( bool closed, unsigned int idx )
for (unsigned int i=0; i<lights.size(); i++) for (unsigned int i=0; i<lights.size(); i++)
{ {
markStarted = false; markStarted = false;
cur_light_dist = 0.0f; double cur_light_dist = 0.0;
int light_direction = lights[i]->LightDirection(); int light_direction = lights[i]->LightDirection();
bool alternate = false; bool alternate = false;
@ -637,7 +635,7 @@ int LinearFeature::Finish( bool closed, unsigned int idx )
while (cur_light_dist < dist) while (cur_light_dist < dist)
{ {
if (cur_light_dist == 0.0f) if (cur_light_dist == 0.0)
{ {
tmp = prev_outer; tmp = prev_outer;
} }

View file

@ -1,6 +1,8 @@
#ifndef _LINEARFEATURE_H_ #ifndef _LINEARFEATURE_H_
#define _LINEARFEATURE_H_ #define _LINEARFEATURE_H_
#include <memory>
#include <terragear/tg_polygon.hxx> #include <terragear/tg_polygon.hxx>
#include <terragear/tg_accumulator.hxx> #include <terragear/tg_accumulator.hxx>
#include <terragear/tg_light.hxx> #include <terragear/tg_light.hxx>
@ -46,7 +48,7 @@ public:
unsigned int start_idx; unsigned int start_idx;
unsigned int end_idx; unsigned int end_idx;
}; };
typedef std::vector <Marking*> MarkingList; typedef std::vector<Marking*> MarkingList;
struct Lighting struct Lighting
{ {
@ -65,35 +67,30 @@ public:
return 0; return 0;
} }
}; };
typedef std::vector <Lighting*> LightingList; typedef std::vector<Lighting*> LightingList;
class LinearFeature class LinearFeature
{ {
public: public:
LinearFeature( char* desc, double o ) LinearFeature( char* desc, double o ) :
LinearFeature(std::string(desc ? desc : "none"), o)
{ {
if ( desc )
{
description = desc;
}
else
{
description = "none";
}
offset = o;
} }
LinearFeature( std::string desc, double o ) LinearFeature( const std::string& desc, double o ) :
cur_mark(nullptr),
cur_light(nullptr),
description(desc)
{ {
description = desc;
offset = o; offset = o;
width = 0;
} }
~LinearFeature(); ~LinearFeature();
inline std::string GetDescription() { return description; } inline std::string GetDescription() { return description; }
void AddNode( BezNode* b ) void AddNode( std::shared_ptr<BezNode> b )
{ {
contour.push_back( b ); contour.push_back( b );
} }
@ -111,7 +108,7 @@ private:
LightingList lights; LightingList lights;
Lighting* cur_light; Lighting* cur_light;
void ConvertContour( BezContour* src, bool closed ); void ConvertContour( const BezContour& src, bool closed );
// text description // text description
std::string description; std::string description;
@ -126,6 +123,6 @@ private:
tglightcontour_list lighting_polys; tglightcontour_list lighting_polys;
}; };
typedef std::vector <LinearFeature *> FeatureList; typedef std::vector<std::shared_ptr<LinearFeature>> FeatureList;
#endif #endif

View file

@ -1,35 +1,50 @@
#include <simgear/debug/logstream.hxx> #include <simgear/debug/logstream.hxx>
#include "linked_objects.hxx" #include "linked_objects.hxx"
#include "debug.hxx" #include "debug.hxx"
#include <cstdio>
Windsock::Windsock( char* definition ) Windsock::Windsock(char* definition)
{ {
sscanf(definition, "%lf %lf %d", &lat, &lon, &lit); std::istringstream ss(definition);
ss >> lat
>> lon
>> lit;
TG_LOG(SG_GENERAL, SG_DEBUG, "Read Windsock: (" << lon << "," << lat << ") lit: " << lit ); TG_LOG(SG_GENERAL, SG_DEBUG, "Read Windsock: (" << lon << "," << lat << ") lit: " << lit );
} }
Beacon::Beacon( char* definition ) Beacon::Beacon(char* definition)
{ {
sscanf(definition, "%lf %lf %d", &lat, &lon, &code); std::istringstream ss(definition);
ss >> lat
>> lon
>> code;
TG_LOG(SG_GENERAL, SG_DEBUG, "Read Beacon: (" << lon << "," << lat << ") code: " << code ); TG_LOG(SG_GENERAL, SG_DEBUG, "Read Beacon: (" << lon << "," << lat << ") code: " << code );
} }
Sign::Sign( char* definition ) Sign::Sign(char* definition)
{ {
char sgdef[256]; char sgdef[256];
double def_heading; double def_heading;
sscanf(definition, "%lf %lf %lf %d %d %s", &lat, &lon, &def_heading, &reserved, &size, sgdef ); std::istringstream ss(definition);
ss >> lat
>> lon
>> def_heading
>> reserved
>> size
>> sgdef;
// 850 format sign heading is the heading which points away from the visible numbers // 850 format sign heading is the heading which points away from the visible numbers
// Flightgear wants the heading to be the heading in which the sign is read // Flightgear wants the heading to be the heading in which the sign is read
heading = -def_heading + 360.0; heading = -def_heading + 360.0;
TG_LOG(SG_GENERAL, SG_DEBUG, "Read Sign: (" << lon << "," << lat << ") heading " << def_heading << " size " << size << " definition: " << sgdef << " calc view heading: " << heading ); TG_LOG(SG_GENERAL, SG_DEBUG, "Read Sign: (" << lon << "," << lat <<
") heading " << def_heading <<
" size " << size <<
" definition: " << sgdef <<
" calc view heading: " << heading );
sgn_def = sgdef; sgn_def = sgdef;
} }

View file

@ -1,12 +1,14 @@
#ifndef _LINKED_OBJECTS_H_ #ifndef _LINKED_OBJECTS_H_
#define _LINKED_OBJECTS_H_ #define _LINKED_OBJECTS_H_
#include <memory>
#include <terragear/tg_polygon.hxx> #include <terragear/tg_polygon.hxx>
class Windsock class Windsock
{ {
public: public:
Windsock(char* def); explicit Windsock(char* def);
double lat; double lat;
double lon; double lon;
@ -23,13 +25,13 @@ public:
} }
}; };
typedef std::vector <Windsock *> WindsockList; typedef std::vector<std::shared_ptr<Windsock>> WindsockList;
class Beacon class Beacon
{ {
public: public:
Beacon(char* def); explicit Beacon(char* def);
double lat; double lat;
double lon; double lon;
@ -46,12 +48,12 @@ public:
} }
}; };
typedef std::vector <Beacon *> BeaconList; typedef std::vector<std::shared_ptr<Beacon>> BeaconList;
class Sign class Sign
{ {
public: public:
Sign(char* def); explicit Sign(char* def);
double lat; double lat;
double lon; double lon;
@ -81,6 +83,6 @@ public:
} }
}; };
typedef std::vector <Sign *> SignList; typedef std::vector<std::shared_ptr<Sign>> SignList;
#endif #endif

View file

@ -39,10 +39,10 @@ using namespace std;
// Display usage // Display usage
static void usage( int argc, char **argv ) { static void usage( int argc, char **argv ) {
TG_LOG(SG_GENERAL, SG_ALERT, "Usage: " << argv[0] << "\n--input=<apt_file>" TG_LOG(SG_GENERAL, SG_ALERT, "Usage: " << argv[0] << "\n--input=<apt_file>"
<< "\n--work=<work_dir>\n[ --start-id=abcd ] [ --restart-id=abcd ] [ --nudge=n ] " << "\n--work=<work_dir>\n[ --start-id=abcd ] [ --nudge=n ] "
<< "[--min-lon=<deg>] [--max-lon=<deg>] [--min-lat=<deg>] [--max-lat=<deg>] " << "[--min-lon=<deg>] [--max-lon=<deg>] [--min-lat=<deg>] [--max-lat=<deg>] "
<< "[ --airport=abcd ] [--max-slope=<decimal>] [--tile=<tile>] [--threads] [--threads=x]" << "[ --airport=abcd ] [--max-slope=<decimal>] [--threads] [--threads=x]"
<< "[--chunk=<chunk>] [--clear-dem-path] [--dem-path=<path>] [--verbose] [--help] [--log-level=bulk|info|debug|warn|alert]"); << "[--clear-dem-path] [--dem-path=<path>] [--verbose] [--help] [--log-level=bulk|info|debug|warn|alert]");
} }
@ -57,6 +57,8 @@ void setup_default_elevation_sources(string_list& elev_src) {
elev_src.push_back( "SRTM-1" ); elev_src.push_back( "SRTM-1" );
elev_src.push_back( "SRTM-3" ); elev_src.push_back( "SRTM-3" );
elev_src.push_back( "SRTM-30" ); elev_src.push_back( "SRTM-30" );
elev_src.push_back( "SRTMGL1" );
elev_src.push_back( "SRTMGL3" );
} }
// Display help and usage // Display help and usage
@ -79,11 +81,7 @@ static void help( int argc, char **argv, const string_list& elev_src ) {
cout << "a valid airport code eg. --airport-id=KORD, or a starting airport can be specified using --start-id=abcd \n"; cout << "a valid airport code eg. --airport-id=KORD, or a starting airport can be specified using --start-id=abcd \n";
cout << "where once again abcd is a valid airport code. In this case, all airports in the file subsequent to the \n"; cout << "where once again abcd is a valid airport code. In this case, all airports in the file subsequent to the \n";
cout << "start-id are done. This is convenient when re-starting after a previous error. \n"; cout << "start-id are done. This is convenient when re-starting after a previous error. \n";
cout << "If you want to restart with the airport after a problem icao, use --restart-id=abcd, as this works the same as\n";
cout << " with the exception that the airport abcd is skipped \n";
cout << "\nAn input area may be specified by lat and lon extent using min and max lat and lon. \n"; cout << "\nAn input area may be specified by lat and lon extent using min and max lat and lon. \n";
//cout << "Alternatively, you may specify a chunk (10 x 10 degrees) or tile (1 x 1 degree) using a string \n";
//cout << "such as eg. w080n40, e000s27. \n";
cout << "\nAn input file containing only a subset of the world's \n"; cout << "\nAn input file containing only a subset of the world's \n";
cout << "airports may of course be used.\n"; cout << "airports may of course be used.\n";
cout << "\n\n"; cout << "\n\n";
@ -92,7 +90,7 @@ static void help( int argc, char **argv, const string_list& elev_src ) {
cout << "The following subdirectories of the work-dir will be searched for elevation files:\n\n"; cout << "The following subdirectories of the work-dir will be searched for elevation files:\n\n";
string_list::const_iterator elev_src_it; string_list::const_iterator elev_src_it;
for (elev_src_it = elev_src.begin(); elev_src_it != elev_src.end(); elev_src_it++) { for (elev_src_it = elev_src.begin(); elev_src_it != elev_src.end(); ++elev_src_it) {
cout << *elev_src_it << "\n"; cout << *elev_src_it << "\n";
} }
cout << "\n"; cout << "\n";
@ -131,7 +129,6 @@ int main(int argc, char **argv)
SGGeod min = SGGeod::fromDeg( -180, -90 ); SGGeod min = SGGeod::fromDeg( -180, -90 );
SGGeod max = SGGeod::fromDeg( 180, 90 ); SGGeod max = SGGeod::fromDeg( 180, 90 );
long position = 0;
// Setup elevation directories // Setup elevation directories
string_list elev_src; string_list elev_src;
@ -152,127 +149,103 @@ int main(int argc, char **argv)
std::string input_file = ""; std::string input_file = "";
std::string summary_file = "./genapt850.csv"; std::string summary_file = "./genapt850.csv";
std::string start_id = ""; std::string start_id = "";
std::string restart_id = "";
std::string airport_id = ""; std::string airport_id = "";
std::string last_apt_file = "./last_apt.txt";
int num_threads = 1; int num_threads = 1;
int arg_pos; int arg_pos;
for (arg_pos = 1; arg_pos < argc; arg_pos++) for (arg_pos = 1; arg_pos < argc; arg_pos++)
{ {
string arg = argv[arg_pos]; string arg = argv[arg_pos];
if ( arg.find("--log-level=") == 0 ) if (arg.compare(0, 12, "--log-level=") == 0)
{ {
setLoggingPriority(arg.substr(12)); setLoggingPriority(arg.substr(12));
} }
else if ( arg.find("--work=") == 0 ) else if (arg.compare(0, 7, "--work=") == 0)
{ {
work_dir = arg.substr(7); work_dir = arg.substr(7);
} }
else if ( arg.find("--input=") == 0 ) else if (arg.compare(0, 8, "--input=") == 0)
{ {
input_file = arg.substr(8); input_file = arg.substr(8);
} }
else if ( arg.find("--start-id=") == 0 ) else if (arg.compare(0, 11, "--start-id=") == 0)
{ {
start_id = arg.substr(11); start_id = arg.substr(11);
} }
else if ( arg.find("--restart-id=") == 0 ) else if (arg.compare(0, 8, "--nudge=") == 0)
{
restart_id = arg.substr(13);
}
else if ( arg.find("--nudge=") == 0 )
{ {
nudge = atoi( arg.substr(8).c_str() ); nudge = atoi( arg.substr(8).c_str() );
} }
else if ( arg.find("--snap=") == 0 ) else if (arg.compare(0, 7, "--snap=") == 0)
{ {
gSnap = atof( arg.substr(7).c_str() ); gSnap = atof( arg.substr(7).c_str() );
} }
else if ( arg.find("--last_apt_file=") == 0 ) else if (arg.compare(0, 10, "--min-lon=") == 0)
{
last_apt_file = arg.substr(16);
}
else if ( arg.find("--min-lon=") == 0 )
{ {
min.setLongitudeDeg(atof( arg.substr(10).c_str() )); min.setLongitudeDeg(atof( arg.substr(10).c_str() ));
} }
else if ( arg.find("--max-lon=") == 0 ) else if (arg.compare(0, 10, "--max-lon=") == 0)
{ {
max.setLongitudeDeg(atof( arg.substr(10).c_str() )); max.setLongitudeDeg(atof( arg.substr(10).c_str() ));
} }
else if ( arg.find("--min-lat=") == 0 ) else if (arg.compare(0, 10, "--min-lat=") == 0)
{ {
min.setLatitudeDeg(atof( arg.substr(10).c_str() )); min.setLatitudeDeg(atof( arg.substr(10).c_str() ));
} }
else if ( arg.find("--max-lat=") == 0 ) else if (arg.compare(0, 10, "--max-lat=") == 0)
{ {
max.setLatitudeDeg(atof( arg.substr(10).c_str() )); max.setLatitudeDeg(atof( arg.substr(10).c_str() ));
} }
#if 0 // relly? - do we need this? else if (arg.compare(0, 10, "--airport=") == 0)
else if ( arg.find("--chunk=") == 0 )
{
tg::Rectangle rectangle = tg::parseChunk(arg.substr(8).c_str(), 10.0);
min = rectangle.getMin();
max = rectangle.getMax();
}
else if ( arg.find("--tile=") == 0 )
{
tg::Rectangle rectangle = tg::parseTile(arg.substr(7).c_str());
min = rectangle.getMin();
max = rectangle.getMax();
}
#endif
else if ( arg.find("--airport=") == 0 )
{ {
airport_id = simgear::strutils::uppercase( arg.substr(10).c_str() ); airport_id = simgear::strutils::uppercase( arg.substr(10).c_str() );
} }
else if ( arg == "--clear-dem-path" ) else if (arg.compare(0, 16, "--clear-dem-path") == 0)
{ {
elev_src.clear(); elev_src.clear();
} }
else if ( arg.find("--dem-path=") == 0 ) else if (arg.compare(0, 11, "--dem-path=") == 0)
{ {
elev_src.push_back( arg.substr(11) ); elev_src.push_back( arg.substr(11) );
} }
else if ( (arg.find("--verbose") == 0) || (arg.find("-v") == 0) ) else if (arg.compare(0, 9, "--verbose") == 0 || arg.compare(0, 2, "-v") == 0)
{ {
sglog().setLogLevels( SG_GENERAL, SG_BULK ); sglog().setLogLevels( SG_GENERAL, SG_BULK );
} }
else if ( (arg.find("--max-slope=") == 0) ) else if (arg.compare(0, 12, "--max-slope=") == 0)
{ {
slope_max = atof( arg.substr(12).c_str() ); slope_max = atof( arg.substr(12).c_str() );
} }
else if ( (arg.find("--threads=") == 0) ) else if (arg.compare(0, 10, "--threads=") == 0)
{ {
num_threads = atoi( arg.substr(10).c_str() ); num_threads = atoi( arg.substr(10).c_str() );
} }
else if ( (arg.find("--threads") == 0) ) else if (arg.compare(0, 9, "--threads") == 0)
{ {
num_threads = boost::thread::hardware_concurrency(); num_threads = boost::thread::hardware_concurrency();
} }
else if (arg.find("--debug-dir=") == 0) else if (arg.compare(0, 12, "--debug-dir=") == 0)
{ {
debug_dir = arg.substr(12); debug_dir = arg.substr(12);
} }
else if (arg.find("--debug-runways=") == 0) else if (arg.compare(0, 16, "--debug-runways=") == 0)
{ {
debug_runway_defs.push_back( arg.substr(16) ); debug_runway_defs.push_back( arg.substr(16) );
} }
else if (arg.find("--debug-pavements=") == 0) else if (arg.compare(0, 18, "--debug-pavements=") == 0)
{ {
debug_pavement_defs.push_back( arg.substr(18) ); debug_pavement_defs.push_back( arg.substr(18) );
} }
else if (arg.find("--debug-taxiways=") == 0) else if (arg.compare(0, 17, "--debug-taxiways=") == 0)
{ {
TG_LOG(SG_GENERAL, SG_INFO, "add debug taxiway " << arg.substr(17) ); TG_LOG(SG_GENERAL, SG_INFO, "add debug taxiway " << arg.substr(17) );
debug_taxiway_defs.push_back( arg.substr(17) ); debug_taxiway_defs.push_back( arg.substr(17) );
} }
else if (arg.find("--debug-features=") == 0) else if (arg.compare(0, 17, "--debug-features=") == 0)
{ {
debug_feature_defs.push_back( arg.substr(17) ); debug_feature_defs.push_back( arg.substr(17) );
} }
else if ( (arg.find("--help") == 0) || (arg.find("-h") == 0) ) else if (arg.compare(0, 6, "--help") == 0 || arg.compare(0, 2, "-h") == 0)
{ {
help( argc, argv, elev_src ); help( argc, argv, elev_src );
exit(-1); exit(-1);
@ -312,8 +285,6 @@ int main(int argc, char **argv)
sgp.append( "dummy" ); sgp.append( "dummy" );
sgp.create_dir( 0755 ); sgp.create_dir( 0755 );
std::string lastaptfile = work_dir+"/last_apt";
tgRectangle boundingBox(min, max); tgRectangle boundingBox(min, max);
boundingBox.sanify(); boundingBox.sanify();
@ -349,7 +320,7 @@ int main(int argc, char **argv)
} }
// Create the scheduler // Create the scheduler
Scheduler* scheduler = new Scheduler(input_file, work_dir, elev_src); auto scheduler = std::make_unique<Scheduler>(input_file, work_dir, elev_src);
// auto scheduler = std::unique_ptr<Scheduler>(new Scheduler(input_file, work_dir, elev_src)); // auto scheduler = std::unique_ptr<Scheduler>(new Scheduler(input_file, work_dir, elev_src));
// Add any debug // Add any debug
@ -372,7 +343,7 @@ int main(int argc, char **argv)
TG_LOG(SG_GENERAL, SG_INFO, "move forward to " << start_id ); TG_LOG(SG_GENERAL, SG_INFO, "move forward to " << start_id );
// scroll forward in datafile // scroll forward in datafile
position = scheduler->FindAirport( start_id ); long position = scheduler->FindAirport( start_id );
// add remaining airports within boundary // add remaining airports within boundary
if ( scheduler->AddAirports( position, &boundingBox ) ) if ( scheduler->AddAirports( position, &boundingBox ) )

View file

@ -1,12 +1,18 @@
#include <simgear/math/SGMathFwd.hxx> #include <simgear/math/SGMathFwd.hxx>
#include <simgear/debug/logstream.hxx> #include <simgear/debug/logstream.hxx>
#include "object.hxx" #include "object.hxx"
#include "debug.hxx" #include "debug.hxx"
#include <cstdio>
LightingObj::LightingObj( char* definition ) LightingObj::LightingObj( char* definition )
{ {
sscanf(definition, "%lf %lf %d %lf %lf %s", &lat, &lon, &type, &heading, &glideslope, &assoc_rw); std::istringstream ss(definition);
ss >> lat
>> lon
>> type
>> heading
>> glideslope
>> assoc_rw;
TG_LOG(SG_GENERAL, SG_DEBUG, "Read lighting object: (" << lon << "," << lat << ") heading: " << heading << " type: " << type ); TG_LOG(SG_GENERAL, SG_DEBUG, "Read lighting object: (" << lon << "," << lat << ") heading: " << heading << " type: " << type );
} }

View file

@ -1,13 +1,15 @@
#ifndef _OBJECT_H_ #ifndef _OBJECT_H_
#define _OBJECT_H_ #define _OBJECT_H_
#include <memory>
#include <terragear/tg_light.hxx> #include <terragear/tg_light.hxx>
#include <terragear/tg_polygon.hxx> #include <terragear/tg_polygon.hxx>
class LightingObj class LightingObj
{ {
public: public:
LightingObj(char* def); explicit LightingObj(char* def);
double lat; double lat;
double lon; double lon;
@ -20,6 +22,6 @@ public:
void BuildBtg( tglightcontour_list& lights ); void BuildBtg( tglightcontour_list& lights );
}; };
typedef std::vector <LightingObj *> LightingObjList; typedef std::vector<std::shared_ptr<LightingObj>> LightingObjList;
#endif #endif

View file

@ -24,7 +24,6 @@
#include <config.h> #include <config.h>
#endif #endif
#include <cstdio>
#include <cstdlib> #include <cstdlib>
#include <fstream> #include <fstream>
#include <set> #include <set>
@ -102,7 +101,7 @@ void write_index_object_sign( const string &base, const SGBucket &b,
exit(-1); exit(-1);
} }
fprintf( fp, "OBJECT_SIGN %s %.6f %.6f %.1f %.2f %u\n", sign.c_str(), fprintf( fp, "OBJECT_SIGN %s %.6f %.6f %.1f %.2f %d\n", sign.c_str(),
p.getLongitudeDeg(), p.getLatitudeDeg(), p.getElevationM(), heading, size ); p.getLongitudeDeg(), p.getLatitudeDeg(), p.getElevationM(), heading, size );
fclose( fp ); fclose( fp );
} }

View file

@ -8,17 +8,15 @@
bool Parser::GetAirportDefinition( char* line, std::string& icao ) bool Parser::GetAirportDefinition( char* line, std::string& icao )
{ {
char* tok; bool match = false;
int code;
bool match = false;
// Get the number code // Get the number code
tok = strtok(line, " \t\r\n"); char* tok = strtok(line, " \t\r\n");
if (tok) if (tok)
{ {
line += strlen(tok)+1; line += strlen(tok)+1;
code = atoi(tok); int code = atoi(tok);
switch(code) switch(code)
{ {
@ -40,7 +38,7 @@ bool Parser::GetAirportDefinition( char* line, std::string& icao )
return match; return match;
} }
void Parser::set_debug( std::string path, std::vector<std::string> runway_defs, void Parser::set_debug( const std::string& path, std::vector<std::string> runway_defs,
std::vector<std::string> pavement_defs, std::vector<std::string> pavement_defs,
std::vector<std::string> taxiway_defs, std::vector<std::string> taxiway_defs,
std::vector<std::string> feature_defs ) std::vector<std::string> feature_defs )
@ -64,13 +62,12 @@ void Parser::set_debug( std::string path, std::vector<std::string> runway_defs,
shapes.push_back( std::numeric_limits<int>::max() ); shapes.push_back( std::numeric_limits<int>::max() );
} else { } else {
std::stringstream ss(dsd); std::stringstream ss(dsd);
int i; int idx;
while (ss >> idx)
while (ss >> i)
{ {
TG_LOG(SG_GENERAL, SG_ALERT, "Adding debug runway " << i); TG_LOG(SG_GENERAL, SG_ALERT, "Adding debug runway " << idx);
shapes.push_back(i); shapes.push_back(idx);
if (ss.peek() == ',') if (ss.peek() == ',')
ss.ignore(); ss.ignore();
@ -93,13 +90,12 @@ void Parser::set_debug( std::string path, std::vector<std::string> runway_defs,
shapes.push_back( std::numeric_limits<int>::max() ); shapes.push_back( std::numeric_limits<int>::max() );
} else { } else {
std::stringstream ss(dsd); std::stringstream ss(dsd);
int i; int idx;
while (ss >> idx)
while (ss >> i)
{ {
TG_LOG(SG_GENERAL, SG_ALERT, "Adding debug pavement " << i); TG_LOG(SG_GENERAL, SG_ALERT, "Adding debug pavement " << idx);
shapes.push_back(i); shapes.push_back(idx);
if (ss.peek() == ',') if (ss.peek() == ',')
ss.ignore(); ss.ignore();
@ -122,13 +118,12 @@ void Parser::set_debug( std::string path, std::vector<std::string> runway_defs,
shapes.push_back( std::numeric_limits<int>::max() ); shapes.push_back( std::numeric_limits<int>::max() );
} else { } else {
std::stringstream ss(dsd); std::stringstream ss(dsd);
int i; int idx;
while (ss >> idx)
while (ss >> i)
{ {
TG_LOG(SG_GENERAL, SG_ALERT, "Adding debug taxiway " << i); TG_LOG(SG_GENERAL, SG_ALERT, "Adding debug taxiway " << idx);
shapes.push_back(i); shapes.push_back(idx);
if (ss.peek() == ',') if (ss.peek() == ',')
ss.ignore(); ss.ignore();
@ -151,13 +146,12 @@ void Parser::set_debug( std::string path, std::vector<std::string> runway_defs,
shapes.push_back( std::numeric_limits<int>::max() ); shapes.push_back( std::numeric_limits<int>::max() );
} else { } else {
std::stringstream ss(dsd); std::stringstream ss(dsd);
int i; int idx;
while (ss >> idx)
while (ss >> i)
{ {
TG_LOG(SG_GENERAL, SG_ALERT, "Adding debug feature " << i); TG_LOG(SG_GENERAL, SG_ALERT, "Adding debug feature " << idx);
shapes.push_back(i); shapes.push_back(idx);
if (ss.peek() == ',') if (ss.peek() == ',')
ss.ignore(); ss.ignore();
@ -236,8 +230,7 @@ void Parser::run()
cur_airport->GetCleanupTime( clean_time ); cur_airport->GetCleanupTime( clean_time );
cur_airport->GetTriangulationTime( triangulation_time ); cur_airport->GetTriangulationTime( triangulation_time );
delete cur_airport; cur_airport = nullptr;
cur_airport = NULL;
} }
log_time = time(0); log_time = time(0);
@ -250,12 +243,12 @@ void Parser::run()
} }
} }
BezNode* Parser::ParseNode( int type, char* line, BezNode* prevNode ) std::shared_ptr<BezNode> Parser::ParseNode( int type, char* line, std::shared_ptr<BezNode> prevNode )
{ {
double lat, lon; double lat, lon;
double ctrl_lat, ctrl_lon; double ctrl_lat, ctrl_lon;
int feat_type1, feat_type2; int feat_type1, feat_type2;
BezNode *curNode = NULL; std::shared_ptr<BezNode> curNode = nullptr;
bool hasCtrl = false; bool hasCtrl = false;
bool close = false; bool close = false;
@ -347,15 +340,15 @@ BezNode* Parser::ParseNode( int type, char* line, BezNode* prevNode )
} }
// if this is a new node, add it - as first part never has prev cp // if this is a new node, add it - as first part never has prev cp
if (curNode == NULL) if (curNode == nullptr)
{ {
if (hasCtrl) if (hasCtrl)
{ {
curNode = new BezNode(lat, lon, ctrl_lat, ctrl_lon); curNode = std::make_shared<BezNode>(lat, lon, ctrl_lat, ctrl_lon);
} }
else else
{ {
curNode = new BezNode(lat, lon); curNode = std::make_shared<BezNode>(lat, lon);
} }
} }
@ -386,38 +379,38 @@ BezNode* Parser::ParseNode( int type, char* line, BezNode* prevNode )
curNode->SetTerm( term ); curNode->SetTerm( term );
curNode->SetClose( close ); curNode->SetClose( close );
return curNode; return std::move(curNode);
} }
LinearFeature* Parser::ParseFeature( char* line ) std::shared_ptr<LinearFeature> Parser::ParseFeature( char* line )
{ {
LinearFeature* feature; std::shared_ptr<LinearFeature> feature;
if (strlen( line )) if (strlen( line ))
{ {
feature = new LinearFeature(line, 0.0f); feature = std::make_shared<LinearFeature>(line, 0.0f);
} }
else else
{ {
feature = new LinearFeature(NULL, 0.0f); feature = std::make_shared<LinearFeature>(nullptr, 0.0f);
} }
TG_LOG(SG_GENERAL, SG_DEBUG, "Creating Linear Feature with description \"" << line << "\""); TG_LOG(SG_GENERAL, SG_DEBUG, "Creating Linear Feature with description \"" << line << "\"");
return feature; return std::move(feature);
} }
ClosedPoly* Parser::ParsePavement( char* line ) std::shared_ptr<ClosedPoly> Parser::ParsePavement( char* line )
{ {
ClosedPoly* poly; std::shared_ptr<ClosedPoly> poly;
int st = 0; // surface type int st = 0; // surface type
float s = 0.0f; // smoothness float s = 0.0f; // smoothness
float th = 0.0f; // texture heading float th = 0.0f; // texture heading
char desc[256]; // description char desc[256]; // description
char *d = NULL; char *d = nullptr;
int numParams; int numParams;
numParams = sscanf(line, "%d %f %f %s", &st, &s, &th, desc); numParams = sscanf(line, "%d %f %f %255s", &st, &s, &th, desc);
if (numParams == 4) if (numParams == 4)
{ {
@ -429,19 +422,19 @@ ClosedPoly* Parser::ParsePavement( char* line )
TG_LOG(SG_GENERAL, SG_DEBUG, "Creating Closed Poly with st " << st << " smoothness " << s << " texture heading " << th); TG_LOG(SG_GENERAL, SG_DEBUG, "Creating Closed Poly with st " << st << " smoothness " << s << " texture heading " << th);
} }
poly = new ClosedPoly(st, s, th, d); poly = std::make_shared<ClosedPoly>(st, s, th, d);
return poly; return std::move(poly);
} }
ClosedPoly* Parser::ParseBoundary( char* line ) std::shared_ptr<ClosedPoly> Parser::ParseBoundary( char* line )
{ {
ClosedPoly* poly; std::shared_ptr<ClosedPoly> poly;
char desc[256]; char desc[256];
char *d = NULL; char *d = nullptr;
int numParams; int numParams;
numParams = sscanf(line, "%s", desc); numParams = sscanf(line, "%255s", desc);
if (numParams == 1) if (numParams == 1)
{ {
@ -453,9 +446,9 @@ ClosedPoly* Parser::ParseBoundary( char* line )
} }
TG_LOG(SG_GENERAL, SG_DEBUG, "Creating Closed Poly for airport boundary : " << d); TG_LOG(SG_GENERAL, SG_DEBUG, "Creating Closed Poly for airport boundary : " << d);
poly = new ClosedPoly(d); poly = std::make_shared<ClosedPoly>(d);
return poly; return std::move(poly);
} }
int Parser::SetState( int state ) int Parser::SetState( int state )
@ -467,7 +460,7 @@ int Parser::SetState( int state )
TG_LOG(SG_GENERAL, SG_DEBUG, "Closing and Adding pavement"); TG_LOG(SG_GENERAL, SG_DEBUG, "Closing and Adding pavement");
cur_pavement->Finish(); cur_pavement->Finish();
cur_airport->AddPavement( cur_pavement ); cur_airport->AddPavement( cur_pavement );
cur_pavement = NULL; cur_pavement = nullptr;
} }
if ( cur_airport && cur_state == STATE_PARSE_BOUNDARY ) if ( cur_airport && cur_state == STATE_PARSE_BOUNDARY )
@ -475,7 +468,7 @@ int Parser::SetState( int state )
TG_LOG(SG_GENERAL, SG_DEBUG, "Closing and Adding boundary"); TG_LOG(SG_GENERAL, SG_DEBUG, "Closing and Adding boundary");
cur_boundary->Finish(); cur_boundary->Finish();
cur_airport->AddBoundary( cur_boundary ); cur_airport->AddBoundary( cur_boundary );
cur_boundary = NULL; cur_boundary = nullptr;
} }
cur_state = state; cur_state = state;
@ -486,164 +479,196 @@ int Parser::SetState( int state )
// TODO: This should be a loop here, and main should just pass the file name and airport code... // TODO: This should be a loop here, and main should just pass the file name and airport code...
int Parser::ParseLine(char* line) int Parser::ParseLine(char* line)
{ {
char* tok; std::shared_ptr<BezNode> cur_node = nullptr;
int code;
BezNode* cur_node = NULL; if (*line == '#')
return cur_state;
// Get the number code
char* tok = strtok(line, " \t\r\n");
if (*line != '#') if (tok)
{ {
// Get the number code line += strlen(tok)+1;
tok = strtok(line, " \t\r\n"); int code = atoi(tok);
if (tok) switch(code)
{ {
line += strlen(tok)+1; case LAND_AIRPORT_CODE:
code = atoi(tok); case SEA_AIRPORT_CODE:
if (cur_state == STATE_NONE)
{
SetState( STATE_PARSE_SIMPLE );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing land airport: " << line);
cur_airport = std::make_shared<Airport>( code, line );
}
else
{
SetState( STATE_DONE );
}
break;
case HELIPORT_CODE:
if (cur_state == STATE_NONE)
{
SetState( STATE_PARSE_SIMPLE );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing heliport: " << line);
cur_airport = std::make_shared<Airport>( code, line );
}
else
{
SetState( STATE_DONE );
}
break;
switch(code) case LAND_RUNWAY_CODE:
{ SetState( STATE_PARSE_SIMPLE );
case LAND_AIRPORT_CODE: TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing runway: " << line);
case SEA_AIRPORT_CODE: cur_runway = std::make_shared<Runway>(line);
if (cur_state == STATE_NONE) if (cur_airport)
{ {
SetState( STATE_PARSE_SIMPLE ); cur_airport->AddRunway( cur_runway );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing land airport: " << line); }
cur_airport = new Airport( code, line ); break;
}
else
{
SetState( STATE_DONE );
}
break;
case HELIPORT_CODE:
if (cur_state == STATE_NONE)
{
SetState( STATE_PARSE_SIMPLE );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing heliport: " << line);
cur_airport = new Airport( code, line );
}
else
{
SetState( STATE_DONE );
}
break;
case LAND_RUNWAY_CODE:
SetState( STATE_PARSE_SIMPLE );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing runway: " << line);
cur_runway = new Runway(line);
if (cur_airport)
{
cur_airport->AddRunway( cur_runway );
}
break;
case WATER_RUNWAY_CODE:
SetState( STATE_PARSE_SIMPLE );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing water runway: " << line);
cur_waterrunway = new WaterRunway(line);
if (cur_airport)
{
cur_airport->AddWaterRunway( cur_waterrunway );
}
break;
case HELIPAD_CODE:
SetState( STATE_PARSE_SIMPLE );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing helipad: " << line);
cur_helipad = new Helipad(line);
if (cur_airport)
{
cur_airport->AddHelipad( cur_helipad );
}
break;
case TAXIWAY_CODE:
SetState( STATE_PARSE_SIMPLE );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing taxiway: " << line);
cur_taxiway = new Taxiway(line);
if (cur_airport)
{
cur_airport->AddTaxiway( cur_taxiway );
}
break;
case PAVEMENT_CODE:
SetState( STATE_PARSE_PAVEMENT );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing pavement: " << line);
cur_pavement = ParsePavement( line );
break;
case LINEAR_FEATURE_CODE:
SetState( STATE_PARSE_FEATURE );
TG_LOG(SG_GENERAL, SG_DEBUG, "Linear Feature: " << line);
cur_feat = ParseFeature( line );
break;
case BOUNDARY_CODE:
SetState( STATE_PARSE_BOUNDARY );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing Boundary: " << line);
cur_boundary = ParseBoundary( line );
break;
case NODE_CODE:
case BEZIER_NODE_CODE:
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing node: " << line);
cur_node = ParseNode( code, line, prev_node );
if ( prev_node && (cur_node != prev_node) )
{
// prev node is done - process it
if ( cur_state == STATE_PARSE_PAVEMENT )
{
cur_pavement->AddNode( prev_node );
}
else if ( cur_state == STATE_PARSE_FEATURE )
{
cur_feat->AddNode( prev_node );
}
else if ( cur_state == STATE_PARSE_BOUNDARY )
{
cur_boundary->AddNode( prev_node );
}
}
prev_node = cur_node; case WATER_RUNWAY_CODE:
break; SetState( STATE_PARSE_SIMPLE );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing water runway: " << line);
case CLOSE_NODE_CODE: cur_waterrunway = std::make_shared<WaterRunway>(line);
case CLOSE_BEZIER_NODE_CODE: if (cur_airport)
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing close loop node: " << line); {
cur_node = ParseNode( code, line, prev_node ); cur_airport->AddWaterRunway( cur_waterrunway );
}
break;
case HELIPAD_CODE:
SetState( STATE_PARSE_SIMPLE );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing helipad: " << line);
cur_helipad = std::make_shared<Helipad>(line);
if (cur_airport)
{
cur_airport->AddHelipad( cur_helipad );
}
break;
if ( cur_state == STATE_PARSE_PAVEMENT && prev_node ) case TAXIWAY_CODE:
SetState( STATE_PARSE_SIMPLE );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing taxiway: " << line);
cur_taxiway = std::make_shared<Taxiway>(line);
if (cur_airport)
{
cur_airport->AddTaxiway( cur_taxiway );
}
break;
case PAVEMENT_CODE:
SetState( STATE_PARSE_PAVEMENT );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing pavement: " << line);
cur_pavement = ParsePavement( line );
break;
case LINEAR_FEATURE_CODE:
SetState( STATE_PARSE_FEATURE );
TG_LOG(SG_GENERAL, SG_DEBUG, "Linear Feature: " << line);
cur_feat = ParseFeature( line );
break;
case BOUNDARY_CODE:
SetState( STATE_PARSE_BOUNDARY );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing Boundary: " << line);
cur_boundary = ParseBoundary( line );
break;
case NODE_CODE:
case BEZIER_NODE_CODE:
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing node: " << line);
cur_node = ParseNode( code, line, prev_node );
if ( prev_node && (cur_node != prev_node) )
{
// prev node is done - process it
if ( cur_state == STATE_PARSE_PAVEMENT )
{ {
if (cur_node != prev_node) cur_pavement->AddNode( prev_node );
{
cur_pavement->AddNode( prev_node );
cur_pavement->AddNode( cur_node );
}
else
{
cur_pavement->AddNode( cur_node );
}
cur_pavement->CloseCurContour();
}
else if ( cur_state == STATE_PARSE_BOUNDARY )
{
if (cur_node != prev_node)
{
cur_boundary->AddNode( prev_node );
cur_boundary->AddNode( cur_node );
}
else
{
cur_boundary->AddNode( cur_node );
}
cur_boundary->CloseCurContour();
} }
else if ( cur_state == STATE_PARSE_FEATURE ) else if ( cur_state == STATE_PARSE_FEATURE )
{ {
cur_feat->AddNode( prev_node );
}
else if ( cur_state == STATE_PARSE_BOUNDARY )
{
cur_boundary->AddNode( prev_node );
}
}
prev_node = cur_node;
break;
case CLOSE_NODE_CODE:
case CLOSE_BEZIER_NODE_CODE:
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing close loop node: " << line);
cur_node = ParseNode( code, line, prev_node );
if ( cur_state == STATE_PARSE_PAVEMENT && prev_node )
{
if (cur_node != prev_node)
{
cur_pavement->AddNode( prev_node );
cur_pavement->AddNode( cur_node );
}
else
{
cur_pavement->AddNode( cur_node );
}
cur_pavement->CloseCurContour();
}
else if ( cur_state == STATE_PARSE_BOUNDARY )
{
if (cur_node != prev_node)
{
cur_boundary->AddNode( prev_node );
cur_boundary->AddNode( cur_node );
}
else
{
cur_boundary->AddNode( cur_node );
}
cur_boundary->CloseCurContour();
}
else if ( cur_state == STATE_PARSE_FEATURE )
{
if (cur_node != prev_node)
{
cur_feat->AddNode( prev_node );
cur_feat->AddNode( cur_node );
}
else
{
cur_feat->AddNode( cur_node );
}
if (cur_airport)
{
cur_feat->Finish( true, cur_airport->NumFeatures() );
cur_airport->AddFeature( cur_feat );
}
cur_feat = nullptr;
SetState( STATE_PARSE_SIMPLE );
}
prev_node = nullptr;
cur_node = nullptr;
break;
case TERM_NODE_CODE:
case TERM_BEZIER_NODE_CODE:
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing termination node: " << line);
if ( cur_state == STATE_PARSE_FEATURE )
{
// we have some bad data - termination nodes right after the
// linear feature declaration - can't do anything with a
// single point - detect and delete.
if ( prev_node )
{
cur_node = ParseNode( code, line, prev_node );
if (cur_node != prev_node) if (cur_node != prev_node)
{ {
cur_feat->AddNode( prev_node ); cur_feat->AddNode( prev_node );
@ -655,123 +680,86 @@ int Parser::ParseLine(char* line)
} }
if (cur_airport) if (cur_airport)
{ {
cur_feat->Finish( true, cur_airport->NumFeatures() ); cur_feat->Finish( false, cur_airport->NumFeatures() );
cur_airport->AddFeature( cur_feat ); cur_airport->AddFeature( cur_feat );
} }
cur_feat = NULL;
SetState( STATE_PARSE_SIMPLE );
} }
prev_node = NULL; else
cur_node = NULL;
break;
case TERM_NODE_CODE:
case TERM_BEZIER_NODE_CODE:
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing termination node: " << line);
if ( cur_state == STATE_PARSE_FEATURE )
{ {
// we have some bad data - termination nodes right after the TG_LOG(SG_GENERAL, SG_ALERT, "Parsing termination node with no previous nodes!!!" );
// linear feature declaration - can't do anything with a
// single point - detect and delete.
if ( prev_node )
{
cur_node = ParseNode( code, line, prev_node );
if (cur_node != prev_node)
{
cur_feat->AddNode( prev_node );
cur_feat->AddNode( cur_node );
}
else
{
cur_feat->AddNode( cur_node );
}
if (cur_airport)
{
cur_feat->Finish( false, cur_airport->NumFeatures() );
cur_airport->AddFeature( cur_feat );
}
}
else
{
TG_LOG(SG_GENERAL, SG_ALERT, "Parsing termination node with no previous nodes!!!" );
// this feature is bogus...
delete cur_feat;
}
cur_feat = NULL;
SetState( STATE_PARSE_SIMPLE );
} }
prev_node = NULL;
cur_node = NULL; cur_feat = nullptr;
break;
case AIRPORT_VIEWPOINT_CODE:
SetState( STATE_PARSE_SIMPLE ); SetState( STATE_PARSE_SIMPLE );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing viewpoint: " << line); }
break; prev_node = nullptr;
case AIRPLANE_STARTUP_LOCATION_CODE: cur_node = nullptr;
SetState( STATE_PARSE_SIMPLE ); break;
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing airplane startup location: " << line);
break; case AIRPORT_VIEWPOINT_CODE:
case LIGHT_BEACON_CODE: SetState( STATE_PARSE_SIMPLE );
SetState( STATE_PARSE_SIMPLE ); TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing viewpoint: " << line);
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing light beacon: " << line); break;
cur_beacon = new Beacon(line); case AIRPLANE_STARTUP_LOCATION_CODE:
cur_airport->AddBeacon( cur_beacon ); SetState( STATE_PARSE_SIMPLE );
break; TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing airplane startup location: " << line);
case WINDSOCK_CODE: break;
SetState( STATE_PARSE_SIMPLE ); case LIGHT_BEACON_CODE:
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing windsock: " << line); SetState( STATE_PARSE_SIMPLE );
cur_windsock = new Windsock(line); TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing light beacon: " << line);
cur_airport->AddWindsock( cur_windsock ); cur_beacon = std::make_shared<Beacon>(line);
break; cur_airport->AddBeacon( cur_beacon );
case TAXIWAY_SIGN: break;
SetState( STATE_PARSE_SIMPLE ); case WINDSOCK_CODE:
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing taxiway sign: " << line); SetState( STATE_PARSE_SIMPLE );
cur_sign = new Sign(line); TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing windsock: " << line);
cur_airport->AddSign( cur_sign ); cur_windsock = std::make_shared<Windsock>(line);
break; cur_airport->AddWindsock( cur_windsock );
case LIGHTING_OBJECT: break;
SetState( STATE_PARSE_SIMPLE ); case TAXIWAY_SIGN:
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing lighting object: " << line); SetState( STATE_PARSE_SIMPLE );
cur_object = new LightingObj(line); TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing taxiway sign: " << line);
cur_airport->AddObj( cur_object ); cur_sign = std::make_shared<Sign>(line);
break; cur_airport->AddSign( cur_sign );
case COMM_FREQ1_CODE: break;
SetState( STATE_PARSE_SIMPLE ); case LIGHTING_OBJECT:
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing commfreq 1: " << line); SetState( STATE_PARSE_SIMPLE );
break; TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing lighting object: " << line);
case COMM_FREQ2_CODE: cur_object = std::make_shared<LightingObj>(line);
SetState( STATE_PARSE_SIMPLE ); cur_airport->AddObj( cur_object );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing commfreq 2: " << line); break;
break; case COMM_FREQ1_CODE:
case COMM_FREQ3_CODE: SetState( STATE_PARSE_SIMPLE );
SetState( STATE_PARSE_SIMPLE ); TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing commfreq 1: " << line);
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing commfreq 3: " << line); break;
break; case COMM_FREQ2_CODE:
case COMM_FREQ4_CODE: SetState( STATE_PARSE_SIMPLE );
SetState( STATE_PARSE_SIMPLE ); TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing commfreq 2: " << line);
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing commfreq 4: " << line); break;
break; case COMM_FREQ3_CODE:
case COMM_FREQ5_CODE: SetState( STATE_PARSE_SIMPLE );
SetState( STATE_PARSE_SIMPLE ); TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing commfreq 3: " << line);
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing commfreq 5: " << line); break;
break; case COMM_FREQ4_CODE:
case COMM_FREQ6_CODE: SetState( STATE_PARSE_SIMPLE );
SetState( STATE_PARSE_SIMPLE ); TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing commfreq 4: " << line);
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing commfreq 6: " << line); break;
break; case COMM_FREQ5_CODE:
case COMM_FREQ7_CODE: SetState( STATE_PARSE_SIMPLE );
SetState( STATE_PARSE_SIMPLE ); TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing commfreq 5: " << line);
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing commfreq 7: " << line); break;
break; case COMM_FREQ6_CODE:
case END_OF_FILE : SetState( STATE_PARSE_SIMPLE );
TG_LOG(SG_GENERAL, SG_DEBUG, "Reached end of file"); TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing commfreq 6: " << line);
SetState( STATE_DONE ); break;
break; case COMM_FREQ7_CODE:
} SetState( STATE_PARSE_SIMPLE );
TG_LOG(SG_GENERAL, SG_DEBUG, "Parsing commfreq 7: " << line);
break;
case END_OF_FILE :
TG_LOG(SG_GENERAL, SG_DEBUG, "Reached end of file");
SetState( STATE_DONE );
break;
} }
} }

View file

@ -3,6 +3,7 @@
#include <iostream> #include <iostream>
#include <fstream> #include <fstream>
#include <memory>
#include <simgear/threads/SGThread.hxx> #include <simgear/threads/SGThread.hxx>
@ -88,30 +89,29 @@
class Parser : public SGThread class Parser : public SGThread
{ {
public: public:
Parser(const std::string& datafile, const std::string& root, const string_list& elev_src ) Parser(const std::string& datafile, const std::string& root, const string_list& elev_src ) :
prev_node(nullptr),
filename(datafile),
elevation(elev_src),
work_dir(root),
cur_airport(nullptr),
cur_taxiway(nullptr),
cur_runway(nullptr),
cur_waterrunway(nullptr),
cur_helipad(nullptr),
cur_pavement(nullptr),
cur_boundary(nullptr),
cur_feat(nullptr),
cur_object(nullptr),
cur_windsock(nullptr),
cur_beacon(nullptr),
cur_sign(nullptr)
{ {
filename = datafile; cur_state = STATE_NONE;
work_dir = root;
elevation = elev_src;
cur_airport = NULL;
cur_runway = NULL;
cur_waterrunway = NULL;
cur_helipad = NULL;
cur_taxiway = NULL;
cur_pavement = NULL;
cur_boundary = NULL;
cur_feat = NULL;
cur_object = NULL;
cur_windsock = NULL;
cur_beacon = NULL;
cur_sign = NULL;
prev_node = NULL;
cur_state = STATE_NONE;
} }
// Debug // Debug
void set_debug( std::string path, std::vector<std::string> runway_defs, void set_debug( const std::string& path, std::vector<std::string> runway_defs,
std::vector<std::string> pavement_defs, std::vector<std::string> pavement_defs,
std::vector<std::string> taxiway_defs, std::vector<std::string> taxiway_defs,
std::vector<std::string> feature_defs ); std::vector<std::string> feature_defs );
@ -124,14 +124,14 @@ private:
int SetState( int state ); int SetState( int state );
BezNode* ParseNode( int type, char* line, BezNode* prevNode ); std::shared_ptr<BezNode> ParseNode( int type, char* line, std::shared_ptr<BezNode> prevNode );
LinearFeature* ParseFeature( char* line ); std::shared_ptr<LinearFeature> ParseFeature( char* line );
ClosedPoly* ParsePavement( char* line ); std::shared_ptr<ClosedPoly> ParsePavement( char* line );
ClosedPoly* ParseBoundary( char* line ); std::shared_ptr<ClosedPoly> ParseBoundary( char* line );
int ParseLine( char* line ); int ParseLine( char* line );
BezNode* prev_node; std::shared_ptr<BezNode> prev_node;
int cur_state; int cur_state;
std::string filename; std::string filename;
string_list elevation; string_list elevation;
@ -139,18 +139,18 @@ private:
// a polygon conists of an array of contours // a polygon conists of an array of contours
// (first is outside boundry, remaining are holes) // (first is outside boundry, remaining are holes)
Airport* cur_airport; std::shared_ptr<Airport> cur_airport;
Taxiway* cur_taxiway; std::shared_ptr<Taxiway> cur_taxiway;
Runway* cur_runway; std::shared_ptr<Runway> cur_runway;
WaterRunway* cur_waterrunway; std::shared_ptr<WaterRunway> cur_waterrunway;
Helipad* cur_helipad; std::shared_ptr<Helipad> cur_helipad;
ClosedPoly* cur_pavement; std::shared_ptr<ClosedPoly> cur_pavement;
ClosedPoly* cur_boundary; std::shared_ptr<ClosedPoly> cur_boundary;
LinearFeature* cur_feat; std::shared_ptr<LinearFeature> cur_feat;
LightingObj* cur_object; std::shared_ptr<LightingObj> cur_object;
Windsock* cur_windsock; std::shared_ptr<Windsock> cur_windsock;
Beacon* cur_beacon; std::shared_ptr<Beacon> cur_beacon;
Sign* cur_sign; std::shared_ptr<Sign> cur_sign;
// debug // debug
std::string debug_path; std::string debug_path;

View file

@ -7,8 +7,6 @@
#include <terragear/tg_polygon.hxx> #include <terragear/tg_polygon.hxx>
#include <cstdio>
#include "global.hxx" #include "global.hxx"
#include "apt_math.hxx" #include "apt_math.hxx"
#include "beznode.hxx" #include "beznode.hxx"
@ -20,43 +18,74 @@ Runway::Runway(char* definition)
{ {
double az2; double az2;
// format: // runway format:
// runway width surface shoulder smoothness centerline lights edge lighting distance remaining signs // width surface shoulder smoothness centerline lights edge lighting distance remaining signs
// 100 46.02 2 1 0.00 1 2 1 // 46.02 2 1 0.00 1 2 1
// //
// runway number runway end lat runway end long threshold overrun markings approach lighting // runway number runway end lat runway end long threshold overrun markings approach lighting
// 09L 33.63470475 -084.44798671 0.00 120.09 3 7 // 09L 33.63470475 -084.44798671 0.00 120.09 3 7
// //
// touchdown zone lighting runway end identifier lights // touchdown zone lighting runway end identifier lights
// 0 1 // 0 1
// //
// runway number runway end lat runway end long threshold overrun markings approach lighting // runway number runway end lat runway end long threshold overrun markings approach lighting
// 27R 33.63469907 -084.40893004 0.00 120.09 3 6 // 27R 33.63469907 -084.40893004 0.00 120.09 3 6
// //
// touchdown zone lighting runway end identifier lights // touchdown zone lighting runway end identifier lights
// 0 1 // 0 1
// Parse the line // Parse the line
// 46.02 2 1 0.00 1 2 1 09L 33.63470475 -084.44798671 0.00 120.09 3 7 0 1 27R 33.63469907 -084.40893004 0.00 120.09 3 6 0 1 // 46.02 2 1 0.00 1 2 1 09L 33.63470475 -084.44798671 0.00 120.09 3 7 0 1 27R 33.63469907 -084.40893004 0.00 120.09 3 6 0 1
// int fscanf(FILE *stream, const char *format, ...); std::istringstream ss(definition);
sscanf(definition, "%lf %d %d %lf %d %d %d %s %lf %lf %lf %lf %d %d %d %d %s %lf %lf %lf %lf %d %d %d %d", ss >> rwy.width
&rwy.width, &rwy.surface, &rwy.shoulder, &rwy.smoothness, &rwy.centerline_lights, &rwy.edge_lights, &rwy.dist_remain_signs, >> rwy.surface
rwy.rwnum[0], &rwy.lat[0], &rwy.lon[0], &rwy.threshold[0], &rwy.overrun[0], &rwy.marking[0], &rwy.approach_lights[0], &rwy.tz_lights[0], &rwy.reil[0], >> rwy.shoulder
rwy.rwnum[1], &rwy.lat[1], &rwy.lon[1], &rwy.threshold[1], &rwy.overrun[1], &rwy.marking[1], &rwy.approach_lights[1], &rwy.tz_lights[1], &rwy.reil[1] >> rwy.smoothness
); >> rwy.centerline_lights
>> rwy.edge_lights
>> rwy.dist_remain_signs
>> rwy.rwnum[0]
>> rwy.lat[0]
>> rwy.lon[0]
>> rwy.threshold[0]
>> rwy.overrun[0]
>> rwy.marking[0]
>> rwy.approach_lights[0]
>> rwy.tz_lights[0]
>> rwy.reil[0]
>> rwy.rwnum[1]
>> rwy.lat[1]
>> rwy.lon[1]
>> rwy.threshold[1]
>> rwy.overrun[1]
>> rwy.marking[1]
>> rwy.approach_lights[1]
>> rwy.tz_lights[1]
>> rwy.reil[1];
// calculate runway heading and length (used a lot) // calculate runway heading and length (used a lot)
SGGeodesy::inverse( GetStart(), GetEnd(), rwy.heading, az2, rwy.length ); SGGeodesy::inverse( GetStart(), GetEnd(), rwy.heading, az2, rwy.length );
TG_LOG(SG_GENERAL, SG_DEBUG, "Read runway: (" << rwy.lon[0] << "," << rwy.lat[0] << ") to (" << rwy.lon[1] << "," << rwy.lat[1] << ") heading: " << rwy.heading << " length: " << rwy.length << " width: " << rwy.width ); TG_LOG(SG_GENERAL, SG_DEBUG, "Read runway: (" << rwy.lon[0] << "," << rwy.lat[0] <<
") to (" << rwy.lon[1] << "," << rwy.lat[1] <<
") heading: " << rwy.heading <<
" length: " << rwy.length <<
" width: " << rwy.width );
} }
WaterRunway::WaterRunway(char* definition) WaterRunway::WaterRunway(char* definition)
{ {
sscanf(definition, "%lf %d %s %lf %lf %s %lf %lf", &width, &buoys, rwnum[0], &lat[0], &lon[0], rwnum[1], &lat[1], &lon[1]); std::istringstream ss(definition);
ss >> width
>> buoys
>> rwnum[0]
>> lat[0]
>> lon[0]
>> rwnum[1]
>> lat[1]
>> lon[1];
TG_LOG(SG_GENERAL, SG_DEBUG, "Read water runway: (" << lon[0] << "," << lat[0] << ") to (" << lon[1] << "," << lat[1] << ") width: " << width << " buoys = " << buoys ); TG_LOG(SG_GENERAL, SG_DEBUG, "Read water runway: (" << lon[0] << "," << lat[0] << ") to (" << lon[1] << "," << lat[1] << ") width: " << width << " buoys = " << buoys );
} }
@ -85,6 +114,7 @@ tgContour WaterRunway::GetBuoys()
} }
} }
} }
return buoys_nodes; return buoys_nodes;
} }

View file

@ -1,6 +1,8 @@
#ifndef _RUNWAY_H_ #ifndef _RUNWAY_H_
#define _RUNWAY_H_ #define _RUNWAY_H_
#include <memory>
#include <terragear/tg_polygon.hxx> #include <terragear/tg_polygon.hxx>
#include <terragear/tg_accumulator.hxx> #include <terragear/tg_accumulator.hxx>
#include <terragear/tg_light.hxx> #include <terragear/tg_light.hxx>
@ -11,7 +13,7 @@ class Runway
{ {
public: public:
Runway(char* def); explicit Runway(char* def);
SGGeod GetStart() SGGeod GetStart()
{ {
@ -53,7 +55,7 @@ public:
private: private:
struct TGRunway { struct TGRunway {
// data for whole runway // data for whole runway
int surface; int surface;
int shoulder; int shoulder;
int centerline_lights; int centerline_lights;
@ -176,13 +178,13 @@ private:
tglightcontour_list gen_malsx( const std::string& kind, bool recip ); tglightcontour_list gen_malsx( const std::string& kind, bool recip );
}; };
typedef std::vector <Runway *> RunwayList; typedef std::vector <std::shared_ptr<Runway>> RunwayList;
class WaterRunway class WaterRunway
{ {
public: public:
WaterRunway(char* def); explicit WaterRunway(char* def);
tgContour GetBuoys(); tgContour GetBuoys();
@ -203,6 +205,6 @@ private:
double lat[2]; double lat[2];
double lon[2]; double lon[2];
}; };
typedef std::vector <WaterRunway *> WaterRunwayList; typedef std::vector <std::shared_ptr<WaterRunway>> WaterRunwayList;
#endif #endif

View file

@ -832,19 +832,16 @@ void Runway::gen_rwy( tgpolygon_list& rwy_polys,
start1_pct = 0.0; start1_pct = 0.0;
end1_pct = 0.0; end1_pct = 0.0;
double part_len = 0.0;
int count=0;
if (rwy.overrun[rwhalf] > 0.0) { if (rwy.overrun[rwhalf] > 0.0) {
/* Generate approach end overrun */ /* Generate approach end overrun */
count = (int) (rwy.overrun[rwhalf] * 2.0/ rwy.width); int count = (int) (rwy.overrun[rwhalf] * 2.0/ rwy.width);
if(count < 1) { if (count < 1) {
count = 1; count = 1;
} }
part_len = rwy.overrun[rwhalf] / (double)count; double part_len = rwy.overrun[rwhalf] / (double)count;
for(int i=0; i<count; i++) { for (int i = 0; i < count; ++i) {
start1_pct=end1_pct; start1_pct = end1_pct;
end1_pct = start1_pct + ( part_len / length ); end1_pct = start1_pct + ( part_len / length );
if ( debug ) { section_name = shapefile_name + "stopway"; } if ( debug ) { section_name = shapefile_name + "stopway"; }
gen_runway_section( runway_half, gen_runway_section( runway_half,

View file

@ -22,6 +22,7 @@
#include <simgear/compiler.h> #include <simgear/compiler.h>
#include <simgear/debug/logstream.hxx> #include <simgear/debug/logstream.hxx>
#include "runway.hxx" #include "runway.hxx"
#include "debug.hxx" #include "debug.hxx"
@ -37,9 +38,7 @@ void Runway::gen_simple_rwy( tgpolygon_list& rwy_polys,
std::string empty = ""; std::string empty = "";
for ( int rwhalf=0; rwhalf<2; ++rwhalf ) { for ( int rwhalf=0; rwhalf<2; ++rwhalf ) {
double length = rwy.length / 2.0; double length = rwy.length / 2.0;
double start_pct = 0.0;
double end_pct = 0.0; double end_pct = 0.0;
double heading = 0.0; double heading = 0.0;
@ -53,7 +52,6 @@ void Runway::gen_simple_rwy( tgpolygon_list& rwy_polys,
runway_half.AddNode( 0, runway.GetNode(5) ); runway_half.AddNode( 0, runway.GetNode(5) );
runway_half.AddNode( 0, runway.GetNode(2) ); runway_half.AddNode( 0, runway.GetNode(2) );
} }
else { else {
heading = rwy.heading; heading = rwy.heading;
@ -71,7 +69,7 @@ void Runway::gen_simple_rwy( tgpolygon_list& rwy_polys,
if ( rwy.threshold[rwhalf] > 0.0 ) { if ( rwy.threshold[rwhalf] > 0.0 ) {
TG_LOG( SG_GENERAL, SG_DEBUG, "Displaced threshold for RW side " << rwhalf << " is " << rwy.threshold[rwhalf] ); TG_LOG( SG_GENERAL, SG_DEBUG, "Displaced threshold for RW side " << rwhalf << " is " << rwy.threshold[rwhalf] );
start_pct = end_pct; double start_pct = end_pct;
end_pct = start_pct + ( rwy.threshold[rwhalf] / length ); end_pct = start_pct + ( rwy.threshold[rwhalf] / length );
Runway::gen_runway_section( runway_half, Runway::gen_runway_section( runway_half,
start_pct, end_pct, start_pct, end_pct,

View file

@ -4,6 +4,7 @@
#endif #endif
#include <cstring> #include <cstring>
#include <memory>
#include <simgear/debug/logstream.hxx> #include <simgear/debug/logstream.hxx>
#include <simgear/io/iostreams/sgstream.hxx> #include <simgear/io/iostreams/sgstream.hxx>
@ -48,7 +49,7 @@ std::ostream& operator<< (std::ostream &out, const AirportInfo &ai)
return out; // MSVC return out; // MSVC
} }
void Scheduler::set_debug( std::string path, std::vector<std::string> runway_defs, void Scheduler::set_debug( const std::string& path, std::vector<std::string> runway_defs,
std::vector<std::string> pavement_defs, std::vector<std::string> pavement_defs,
std::vector<std::string> taxiway_defs, std::vector<std::string> taxiway_defs,
std::vector<std::string> feature_defs ) std::vector<std::string> feature_defs )
@ -72,13 +73,12 @@ void Scheduler::set_debug( std::string path, std::vector<std::string> runway_def
shapes.push_back( std::numeric_limits<int>::max() ); shapes.push_back( std::numeric_limits<int>::max() );
} else { } else {
std::stringstream ss(dsd); std::stringstream ss(dsd);
int i; int idx;
while (ss >> idx)
while (ss >> i)
{ {
TG_LOG(SG_GENERAL, SG_ALERT, "Adding debug runway " << i << " for " << icao ); TG_LOG(SG_GENERAL, SG_ALERT, "Adding debug runway " << idx << " for " << icao );
shapes.push_back(i); shapes.push_back(idx);
if (ss.peek() == ',') if (ss.peek() == ',')
ss.ignore(); ss.ignore();
@ -101,13 +101,12 @@ void Scheduler::set_debug( std::string path, std::vector<std::string> runway_def
shapes.push_back( std::numeric_limits<int>::max() ); shapes.push_back( std::numeric_limits<int>::max() );
} else { } else {
std::stringstream ss(dsd); std::stringstream ss(dsd);
int i; int idx;
while (ss >> idx)
while (ss >> i)
{ {
TG_LOG(SG_GENERAL, SG_ALERT, "Adding debug pavement " << i << " for " << icao ); TG_LOG(SG_GENERAL, SG_ALERT, "Adding debug pavement " << idx << " for " << icao );
shapes.push_back(i); shapes.push_back(idx);
if (ss.peek() == ',') if (ss.peek() == ',')
ss.ignore(); ss.ignore();
@ -130,13 +129,12 @@ void Scheduler::set_debug( std::string path, std::vector<std::string> runway_def
shapes.push_back( std::numeric_limits<int>::max() ); shapes.push_back( std::numeric_limits<int>::max() );
} else { } else {
std::stringstream ss(dsd); std::stringstream ss(dsd);
int i; int idx;
while (ss >> idx)
while (ss >> i)
{ {
TG_LOG(SG_GENERAL, SG_ALERT, "Adding debug taxiway " << i << " for " << icao ); TG_LOG(SG_GENERAL, SG_ALERT, "Adding debug taxiway " << idx << " for " << icao );
shapes.push_back(i); shapes.push_back(idx);
if (ss.peek() == ',') if (ss.peek() == ',')
ss.ignore(); ss.ignore();
@ -159,13 +157,12 @@ void Scheduler::set_debug( std::string path, std::vector<std::string> runway_def
shapes.push_back( std::numeric_limits<int>::max() ); shapes.push_back( std::numeric_limits<int>::max() );
} else { } else {
std::stringstream ss(dsd); std::stringstream ss(dsd);
int i; int idx;
while (ss >> idx)
while (ss >> i)
{ {
TG_LOG(SG_GENERAL, SG_ALERT, "Adding debug feature " << i << " for " << icao ); TG_LOG(SG_GENERAL, SG_ALERT, "Adding debug feature " << idx << " for " << icao );
shapes.push_back(i); shapes.push_back(idx);
if (ss.peek() == ',') if (ss.peek() == ',')
ss.ignore(); ss.ignore();
@ -175,32 +172,31 @@ void Scheduler::set_debug( std::string path, std::vector<std::string> runway_def
} }
} }
bool Scheduler::IsAirportDefinition( char* line, std::string icao ) bool Scheduler::IsAirportDefinition( char* line, const std::string& icao )
{ {
char* tok; bool match = false;
int code;
bool match = false;
// Get the number code // Get the number code
tok = strtok(line, " \t\r\n"); char* tok = strtok(line, " \t\r\n");
if (tok) if (tok)
{ {
line += strlen(tok)+1; line += strlen(tok)+1;
code = atoi(tok); int code = atoi(tok);
switch(code) switch(code)
{ {
case LAND_AIRPORT_CODE: case LAND_AIRPORT_CODE:
case SEA_AIRPORT_CODE: case SEA_AIRPORT_CODE:
case HELIPORT_CODE: case HELIPORT_CODE:
{
Airport ap( code, line );
if ( ap.GetIcao() == icao )
{ {
match = true; Airport ap( code, line );
if ( ap.GetIcao() == icao )
{
match = true;
}
} }
}
break; break;
case LAND_RUNWAY_CODE: case LAND_RUNWAY_CODE:
@ -239,7 +235,6 @@ bool Scheduler::IsAirportDefinition( char* line, std::string icao )
void Scheduler::AddAirport( std::string icao ) void Scheduler::AddAirport( std::string icao )
{ {
char line[2048]; char line[2048];
long cur_pos;
bool found = false; bool found = false;
AirportInfo ai; AirportInfo ai;
@ -254,7 +249,7 @@ void Scheduler::AddAirport( std::string icao )
while ( !in.eof() && !found ) while ( !in.eof() && !found )
{ {
// remember the position of this line // remember the position of this line
cur_pos = in.tellg(); long cur_pos = in.tellg();
// get a line // get a line
in.getline(line, 2048); in.getline(line, 2048);
@ -272,7 +267,7 @@ void Scheduler::AddAirport( std::string icao )
} }
} }
long Scheduler::FindAirport( std::string icao ) long Scheduler::FindAirport( const std::string& icao )
{ {
char line[2048]; char line[2048];
long cur_pos = 0; long cur_pos = 0;
@ -320,11 +315,8 @@ void Scheduler::RetryAirport( AirportInfo* pai )
bool Scheduler::AddAirports( long start_pos, tgRectangle* boundingBox ) bool Scheduler::AddAirports( long start_pos, tgRectangle* boundingBox )
{ {
char line[2048]; char line[2048];
char* def;
long cur_pos;
long cur_apt_pos = 0; long cur_apt_pos = 0;
std::string cur_apt_name; std::string cur_apt_name;
char* tok;
int code; int code;
bool match; bool match;
bool done; bool done;
@ -350,14 +342,14 @@ bool Scheduler::AddAirports( long start_pos, tgRectangle* boundingBox )
while (!done) while (!done)
{ {
// remember the position of this line // remember the position of this line
cur_pos = in.tellg(); long cur_pos = in.tellg();
// get a line // get a line
in.getline(line, 2048); in.getline(line, 2048);
def = &line[0]; char* def = &line[0];
// Get the number code // Get the number code
tok = strtok(def, " \t\r\n"); char* tok = strtok(def, " \t\r\n");
if (tok) if (tok)
{ {
@ -370,7 +362,7 @@ bool Scheduler::AddAirports( long start_pos, tgRectangle* boundingBox )
case SEA_AIRPORT_CODE: case SEA_AIRPORT_CODE:
case HELIPORT_CODE: case HELIPORT_CODE:
{ {
Airport* airport = new Airport( code, def ); auto airport = std::make_unique<Airport>( code, def );
if (match) if (match)
{ {
// Start off with given snap value // Start off with given snap value
@ -380,7 +372,6 @@ bool Scheduler::AddAirports( long start_pos, tgRectangle* boundingBox )
// remember this new apt pos and name, and clear match // remember this new apt pos and name, and clear match
cur_apt_pos = cur_pos; cur_apt_pos = cur_pos;
cur_apt_name = airport->GetIcao(); cur_apt_name = airport->GetIcao();
delete airport;
match = false; match = false;
} }
@ -400,14 +391,13 @@ bool Scheduler::AddAirports( long start_pos, tgRectangle* boundingBox )
// if the the runway start / end coords are within the rect, // if the the runway start / end coords are within the rect,
// we have a winner // we have a winner
{ {
Runway* runway = new Runway(def); auto runway = std::make_unique<Runway>(def);
if ( boundingBox->isInside(runway->GetStart()) ) { if ( boundingBox->isInside(runway->GetStart()) ) {
match = true; match = true;
} }
else if ( boundingBox->isInside(runway->GetEnd()) ) { else if ( boundingBox->isInside(runway->GetEnd()) ) {
match = true; match = true;
} }
delete runway;
} }
break; break;
@ -415,14 +405,13 @@ bool Scheduler::AddAirports( long start_pos, tgRectangle* boundingBox )
// if the the runway start / end coords are within the rect, // if the the runway start / end coords are within the rect,
// we have a winner // we have a winner
{ {
WaterRunway* runway = new WaterRunway(def); auto runway = std::make_unique<WaterRunway>(def);
if ( boundingBox->isInside(runway->GetStart()) ) { if ( boundingBox->isInside(runway->GetStart()) ) {
match = true; match = true;
} }
else if ( boundingBox->isInside(runway->GetEnd()) ) { else if ( boundingBox->isInside(runway->GetEnd()) ) {
match = true; match = true;
} }
delete runway;
} }
break; break;
@ -430,11 +419,10 @@ bool Scheduler::AddAirports( long start_pos, tgRectangle* boundingBox )
// if the heliport coords are within the rect, we have // if the heliport coords are within the rect, we have
// a winner // a winner
{ {
Helipad* helipad = new Helipad(def); auto helipad = std::make_unique<Helipad>(def);
if ( boundingBox->isInside(helipad->GetLoc()) ) { if ( boundingBox->isInside(helipad->GetLoc()) ) {
match = true; match = true;
} }
delete helipad;
} }
break; break;
@ -474,12 +462,11 @@ bool Scheduler::AddAirports( long start_pos, tgRectangle* boundingBox )
} }
} }
Scheduler::Scheduler(std::string& datafile, const std::string& root, const string_list& elev_src) Scheduler::Scheduler(std::string& datafile, const std::string& root, const string_list& elev_src) :
filename(datafile),
elevation(elev_src),
work_dir(root)
{ {
filename = datafile;
work_dir = root;
elevation = elev_src;
std::ifstream in( filename.c_str() ); std::ifstream in( filename.c_str() );
if ( !in.is_open() ) if ( !in.is_open() )
{ {
@ -490,16 +477,9 @@ Scheduler::Scheduler(std::string& datafile, const std::string& root, const strin
void Scheduler::Schedule( int num_threads, std::string& summaryfile ) void Scheduler::Schedule( int num_threads, std::string& summaryfile )
{ {
// std::ofstream csvfile; std::vector<std::shared_ptr<Parser>> parsers;
// open and truncate the summary file : monitor only appends
// csvfile.open( summaryfile.c_str(), std::ios_base::out | std::ios_base::trunc );
// csvfile.close();
std::vector<Parser *> parsers;
for (int i=0; i<num_threads; i++) { for (int i=0; i<num_threads; i++) {
Parser* parser = new Parser( filename, work_dir, elevation ); auto parser = std::make_shared<Parser>( filename, work_dir, elevation );
// parser->set_debug();
parser->start(); parser->start();
parsers.push_back( parser ); parsers.push_back( parser );
} }
@ -511,6 +491,6 @@ void Scheduler::Schedule( int num_threads, std::string& summaryfile )
// Then wait until they are finished // Then wait until they are finished
for (unsigned int i=0; i<parsers.size(); i++) { for (unsigned int i=0; i<parsers.size(); i++) {
parsers[i]->join(); parsers[i]->join();
delete parsers[i]; parsers[i] = nullptr;
} }
} }

View file

@ -44,9 +44,9 @@ public:
{ {
} }
AirportInfo( std::string id, long p, double s ) AirportInfo( const std::string& id, long p, double s ) :
icao(id)
{ {
icao = id;
pos = p; pos = p;
snap = s; snap = s;
@ -99,7 +99,7 @@ class Scheduler
public: public:
Scheduler(std::string& datafile, const std::string& root, const string_list& elev_src); Scheduler(std::string& datafile, const std::string& root, const string_list& elev_src);
long FindAirport( std::string icao ); long FindAirport( const std::string& icao );
void AddAirport( std::string icao ); void AddAirport( std::string icao );
bool AddAirports( long start_pos, tgRectangle* boundingBox ); bool AddAirports( long start_pos, tgRectangle* boundingBox );
void RetryAirport( AirportInfo* pInfo ); void RetryAirport( AirportInfo* pInfo );
@ -107,13 +107,13 @@ public:
void Schedule( int num_threads, std::string& summaryfile ); void Schedule( int num_threads, std::string& summaryfile );
// Debug // Debug
void set_debug( std::string path, std::vector<std::string> runway_defs, void set_debug( const std::string& path, std::vector<std::string> runway_defs,
std::vector<std::string> pavement_defs, std::vector<std::string> pavement_defs,
std::vector<std::string> taxiway_defs, std::vector<std::string> taxiway_defs,
std::vector<std::string> feature_defs ); std::vector<std::string> feature_defs );
private: private:
bool IsAirportDefinition( char* line, std::string icao ); bool IsAirportDefinition( char* line, const std::string& icao );
std::string filename; std::string filename;
string_list elevation; string_list elevation;

View file

@ -6,8 +6,6 @@
#include <terragear/tg_shapefile.hxx> #include <terragear/tg_shapefile.hxx>
#include <cstdio>
#include "global.hxx" #include "global.hxx"
#include "apt_math.hxx" #include "apt_math.hxx"
#include "beznode.hxx" #include "beznode.hxx"
@ -29,20 +27,31 @@ Taxiway::Taxiway(char* definition)
double smoothness; double smoothness;
int signs; int signs;
// format: // taxiway format:
// taxiway lat lon designation heading length threshold overrun // lat lon designation heading length threshold overrun
// 10 44.38085600 -074.20606200 xxx 79.29 3384 0.0 0.0 // 44.38085600 -074.20606200 xxx 79.29 3384 0.0 0.0
// //
// width lighting surface shoulder markings smoothness dist remain // width lighting surface shoulder markings smoothness dist remain
// 60 161161 1 0 0 0.35 0 // 60 161161 1 0 0 0.35 0
// Parse the line // Parse the line
// 44.38085600 -074.20606200 xxx 79.29 3384 0.0 0.0 60 161161 1 0 0 0.35 0 // 44.38085600 -074.20606200 xxx 79.29 3384 0.0 0.0 60 161161 1 0 0 0.35 0
// int fscanf(FILE *stream, const char *format, ...); std::istringstream ss(definition);
sscanf(definition, "%lf %lf %s %lf %lf %lf %lf %lf %s %d %d %d %lf %d", ss >> lat
&lat, &lon, designation, &heading, &length, &threshold, &overrun, >> lon
&width, lighting, &surface, &shoulder, &markings, &smoothness, &signs); >> designation
>> heading
>> length
>> threshold
>> overrun
>> width
>> lighting
>> surface
>> shoulder
>> markings
>> smoothness
>> signs;
TG_LOG(SG_GENERAL, SG_DEBUG, "Read taxiway: (" << lon << "," << lat << ") heading: " << heading << " length: " << length << " width: " << width ); TG_LOG(SG_GENERAL, SG_DEBUG, "Read taxiway: (" << lon << "," << lat << ") heading: " << heading << " length: " << length << " width: " << width );

View file

@ -1,6 +1,8 @@
#ifndef _TAXIWAY_H_ #ifndef _TAXIWAY_H_
#define _TAXIWAY_H_ #define _TAXIWAY_H_
#include <memory>
#include <terragear/tg_light.hxx> #include <terragear/tg_light.hxx>
#include <terragear/tg_polygon.hxx> #include <terragear/tg_polygon.hxx>
#include <terragear/tg_accumulator.hxx> #include <terragear/tg_accumulator.hxx>
@ -11,7 +13,7 @@ class Taxiway
{ {
public: public:
Taxiway(char* def); explicit Taxiway(char* def);
int BuildBtg( tgpolygon_list& taxi_polys, int BuildBtg( tgpolygon_list& taxi_polys,
tglightcontour_list& taxi_lights, tglightcontour_list& taxi_lights,
@ -39,6 +41,6 @@ private:
void GenLights(tglightcontour_list& rwy_lights); void GenLights(tglightcontour_list& rwy_lights);
}; };
typedef std::vector <Taxiway *> TaxiwayList; typedef std::vector<std::shared_ptr<Taxiway>> TaxiwayList;
#endif #endif

View file

@ -35,9 +35,22 @@ int PrecisionFirstValue(const char * filename)
char line[80]; char line[80];
FILE *f = fopen(filename, "r"); FILE *f = fopen(filename, "r");
if (!f) return 0; if (!f) return 0;
if (fgets(line, 80, f) == 0) return 0; //skip poly count
if (fgets(line, 80, f) == 0) return 0; //skip length first polygon if (fgets(line, 80, f) == 0) {
if (fgets(line, 80, f) == 0) return 0; //get coords first vertex fclose(f);
return 0; //skip poly count
}
if (fgets(line, 80, f) == 0) {
fclose(f);
return 0; //skip length first polygon
}
if (fgets(line, 80, f) == 0) {
fclose(f);
return 0; //get coords first vertex
}
fclose(f); fclose(f);
int i = 0; int i = 0;
@ -66,7 +79,6 @@ bool LoadFromFile(Polygons &ppg, char * filename, double scale)
FILE *f = fopen(filename, "r"); FILE *f = fopen(filename, "r");
if (!f) return false; if (!f) return false;
int polyCnt, vertCnt; int polyCnt, vertCnt;
char junk [80];
double X, Y; double X, Y;
if (fscanf(f, "%d", &polyCnt) == 1 && polyCnt > 0) if (fscanf(f, "%d", &polyCnt) == 1 && polyCnt > 0)
@ -79,6 +91,8 @@ bool LoadFromFile(Polygons &ppg, char * filename, double scale)
if (fscanf(f, "%lf%*[, ]%lf", &X, &Y) != 2) break; if (fscanf(f, "%lf%*[, ]%lf", &X, &Y) != 2) break;
ppg[i][j].X = Round(X * scale); ppg[i][j].X = Round(X * scale);
ppg[i][j].Y = Round(Y * scale); ppg[i][j].Y = Round(Y * scale);
char junk [80];
fgets(junk, 80, f); fgets(junk, 80, f);
} }
} }

View file

@ -51,7 +51,7 @@ static void usage( const string name ) {
SG_LOG(SG_GENERAL, SG_ALERT, " --work-dir=<directory>"); SG_LOG(SG_GENERAL, SG_ALERT, " --work-dir=<directory>");
SG_LOG(SG_GENERAL, SG_ALERT, " --share-dir=<directory>"); SG_LOG(SG_GENERAL, SG_ALERT, " --share-dir=<directory>");
SG_LOG(SG_GENERAL, SG_ALERT, " --match-dir=<directory>"); SG_LOG(SG_GENERAL, SG_ALERT, " --match-dir=<directory>");
SG_LOG(SG_GENERAL, SG_ALERT, " --cover=<path to land-cover raster>"); // unused: SG_LOG(SG_GENERAL, SG_ALERT, " --cover=<path to land-cover raster>");
SG_LOG(SG_GENERAL, SG_ALERT, " --tile-id=<id>"); SG_LOG(SG_GENERAL, SG_ALERT, " --tile-id=<id>");
SG_LOG(SG_GENERAL, SG_ALERT, " --min-lon=<degrees>"); SG_LOG(SG_GENERAL, SG_ALERT, " --min-lon=<degrees>");
SG_LOG(SG_GENERAL, SG_ALERT, " --max-lon=<degrees>"); SG_LOG(SG_GENERAL, SG_ALERT, " --max-lon=<degrees>");
@ -59,7 +59,7 @@ static void usage( const string name ) {
SG_LOG(SG_GENERAL, SG_ALERT, " --max-lat=<degrees>"); SG_LOG(SG_GENERAL, SG_ALERT, " --max-lat=<degrees>");
SG_LOG(SG_GENERAL, SG_ALERT, " --nudge=<float>"); SG_LOG(SG_GENERAL, SG_ALERT, " --nudge=<float>");
SG_LOG(SG_GENERAL, SG_ALERT, " --priorities=<filename>"); SG_LOG(SG_GENERAL, SG_ALERT, " --priorities=<filename>");
SG_LOG(SG_GENERAL, SG_ALERT, " --usgs-map=<filename>"); // unused: SG_LOG(SG_GENERAL, SG_ALERT, " --usgs-map=<filename>");
SG_LOG(SG_GENERAL, SG_ALERT, " --ignore-landmass"); SG_LOG(SG_GENERAL, SG_ALERT, " --ignore-landmass");
SG_LOG(SG_GENERAL, SG_ALERT, " --threads"); SG_LOG(SG_GENERAL, SG_ALERT, " --threads");
SG_LOG(SG_GENERAL, SG_ALERT, " --threads=<numthreads>"); SG_LOG(SG_GENERAL, SG_ALERT, " --threads=<numthreads>");
@ -84,9 +84,9 @@ int main(int argc, char **argv) {
string work_dir = "."; string work_dir = ".";
string share_dir = ""; string share_dir = "";
string match_dir = ""; string match_dir = "";
string cover = ""; // unused: string cover = "";
string priorities_file = DEFAULT_PRIORITIES_FILE; string priorities_file = DEFAULT_PRIORITIES_FILE;
string usgs_map_file = DEFAULT_USGS_MAPFILE; // unused: string usgs_map_file = DEFAULT_USGS_MAPFILE;
SGGeod min, max; SGGeod min, max;
long tile_id = -1; long tile_id = -1;
int num_threads = 1; int num_threads = 1;
@ -130,12 +130,12 @@ int main(int argc, char **argv) {
max.setLatitudeDeg(atof( arg.substr(10).c_str() )); max.setLatitudeDeg(atof( arg.substr(10).c_str() ));
} else if (arg.find("--nudge=") == 0) { } else if (arg.find("--nudge=") == 0) {
nudge = atof(arg.substr(8).c_str())*SG_EPSILON; nudge = atof(arg.substr(8).c_str())*SG_EPSILON;
} else if (arg.find("--cover=") == 0) { // } else if (arg.find("--cover=") == 0) {
cover = arg.substr(8); // unused: cover = arg.substr(8);
} else if (arg.find("--priorities=") == 0) { } else if (arg.find("--priorities=") == 0) {
priorities_file = arg.substr(13); priorities_file = arg.substr(13);
} else if (arg.find("--usgs-map=") == 0) { // } else if (arg.find("--usgs-map=") == 0) {
usgs_map_file = arg.substr(11); // unused: usgs_map_file = arg.substr(11);
} else if (arg.find("--ignore-landmass") == 0) { } else if (arg.find("--ignore-landmass") == 0) {
ignoreLandmass = true; ignoreLandmass = true;
} else if (arg.find("--threads=") == 0) { } else if (arg.find("--threads=") == 0) {

View file

@ -33,10 +33,14 @@
class TGAreaDefinition { class TGAreaDefinition {
public: public:
TGAreaDefinition( const std::string& n, const std::string& c, unsigned int p ) { TGAreaDefinition( const std::string& n, const std::string& c, unsigned int p ) :
name = n; name(n),
category = c; category(c)
{
priority = p; priority = p;
smooth_method = 0;
layered = false;
default_layer = 0;
}; };
std::string const& GetName() const { std::string const& GetName() const {
@ -68,7 +72,12 @@ typedef area_definition_list::const_iterator area_definition_iterator;
class TGAreaDefinitions { class TGAreaDefinitions {
public: public:
TGAreaDefinitions() {}; TGAreaDefinitions() :
sliver_area_name("<unnamed>")
{
sliver_area_priority = 0;
};
int init( const std::string& filename ); int init( const std::string& filename );
unsigned int size() const { unsigned int size() const {
return area_defs.size(); return area_defs.size();

View file

@ -36,15 +36,20 @@ const double TGConstruct::gSnap = 0.00000001; // approx 1 mm
TGConstruct::TGConstruct( const TGAreaDefinitions& areas, unsigned int s, SGLockedQueue<SGBucket>& q, SGMutex* l) : TGConstruct::TGConstruct( const TGAreaDefinitions& areas, unsigned int s, SGLockedQueue<SGBucket>& q, SGMutex* l) :
area_defs(areas), area_defs(areas),
workQueue(q), workQueue(q),
stage(s),
ignoreLandmass(false),
debug_all(false),
ds_id((void*)-1), ds_id((void*)-1),
isOcean(false) l_id(nullptr),
ds_name(""),
layer_name(""),
feature_name(""),
lock(l)
{ {
total_tiles = q.size(); total_tiles = q.size();
stage = s;
ignoreLandmass = false;
nudge = 0.0;
debug_all = false;
isOcean = false;
num_areas = areas.size(); num_areas = areas.size();
lock = l;
} }
@ -55,9 +60,9 @@ TGConstruct::~TGConstruct() {
} }
// TGConstruct: Setup // TGConstruct: Setup
void TGConstruct::set_paths( const std::string work, const std::string share, void TGConstruct::set_paths( const std::string& work, const std::string& share,
const std::string match, const std::string output, const std::string& match, const std::string& output,
const std::vector<std::string> load ) { const std::vector<std::string>& load ) {
work_base = work; work_base = work;
share_base = share; share_base = share;
match_base = match; match_base = match;
@ -72,12 +77,10 @@ void TGConstruct::set_options( bool ignore_lm, double n ) {
void TGConstruct::run() void TGConstruct::run()
{ {
unsigned int tiles_complete;
// as long as we have feometry to parse, do so // as long as we have feometry to parse, do so
while ( !workQueue.empty() ) { while ( !workQueue.empty() ) {
bucket = workQueue.pop(); bucket = workQueue.pop();
tiles_complete = total_tiles - workQueue.size(); unsigned int tiles_complete = total_tiles - workQueue.size();
// assume non ocean tile until proven otherwise // assume non ocean tile until proven otherwise
isOcean = false; isOcean = false;

View file

@ -83,8 +83,8 @@ public:
#endif #endif
// paths // paths
void set_paths( const std::string work, const std::string share, const std::string match, void set_paths( const std::string& work, const std::string& share, const std::string& match,
const std::string output, const std::vector<std::string> load_dirs ); const std::string& output, const std::vector<std::string>& load_dirs );
void set_options( bool ignore_lm, double n ); void set_options( bool ignore_lm, double n );
// TODO : REMOVE // TODO : REMOVE

View file

@ -39,13 +39,12 @@ bool TGConstruct::ClipLandclassPolys( void ) {
tgPolygon remains; tgPolygon remains;
tgPolygon safety_base; tgPolygon safety_base;
tgcontour_list slivers; tgcontour_list slivers;
SGGeod p; bool debug_shape;
bool debug_area, debug_shape;
tgAccumulator accum(bucket.gen_index_str()); tgAccumulator accum(bucket.gen_index_str());
unsigned int accum_idx = 0; unsigned int accum_idx = 0;
// set up clipping tile : and remember to add the nodes! // set up clipping tile : and remember to add the nodes!
p = bucket.get_corner( SG_BUCKET_SW ); SGGeod p = bucket.get_corner( SG_BUCKET_SW );
p.setElevationM( -9999.0 ); p.setElevationM( -9999.0 );
safety_base.AddNode( 0, p ); safety_base.AddNode( 0, p );
nodes.unique_add( p ); nodes.unique_add( p );
@ -102,7 +101,7 @@ bool TGConstruct::ClipLandclassPolys( void ) {
// process polygons in priority order // process polygons in priority order
for ( unsigned int i = 0; i < area_defs.size(); i++ ) { for ( unsigned int i = 0; i < area_defs.size(); i++ ) {
debug_area = IsDebugArea( i ); bool debug_area = IsDebugArea( i );
for( unsigned int j = 0; j < polys_in.area_size(i); ++j ) { for( unsigned int j = 0; j < polys_in.area_size(i); ++j ) {
tgPolygon& current = polys_in.get_poly(i, j); tgPolygon& current = polys_in.get_poly(i, j);
debug_shape = IsDebugShape( polys_in.get_poly( i, j ).GetId() ); debug_shape = IsDebugShape( polys_in.get_poly( i, j ).GetId() );
@ -127,7 +126,7 @@ bool TGConstruct::ClipLandclassPolys( void ) {
char name[32]; char name[32];
sprintf(layer, "pre_clip_%d", polys_in.get_poly( i, j ).GetId() ); sprintf(layer, "pre_clip_%d", polys_in.get_poly( i, j ).GetId() );
sprintf(name, "shape %d,%d", i,j); sprintf(name, "shape %u,%u", i,j);
tgShapefile::FromPolygon( tmp, ds_name, layer, name ); tgShapefile::FromPolygon( tmp, ds_name, layer, name );
tgPolygon::ToClipperFile( tmp, ds_name, layer ); tgPolygon::ToClipperFile( tmp, ds_name, layer );
@ -159,7 +158,7 @@ bool TGConstruct::ClipLandclassPolys( void ) {
char name[32]; char name[32];
sprintf(layer, "post_clip_%d", polys_in.get_poly( i, j ).GetId() ); sprintf(layer, "post_clip_%d", polys_in.get_poly( i, j ).GetId() );
sprintf(name, "shape %d,%d", i,j); sprintf(name, "shape %u,%u", i,j);
tgShapefile::FromPolygon( clipped, ds_name, layer, name ); tgShapefile::FromPolygon( clipped, ds_name, layer, name );
} }
@ -175,7 +174,7 @@ bool TGConstruct::ClipLandclassPolys( void ) {
accum.Add( tmp ); accum.Add( tmp );
if ( debug_area || debug_shape ) { if ( debug_area || debug_shape ) {
char layer[32]; char layer[32];
sprintf(layer, "post_clip_accum_%d_%d", accum_idx++, polys_in.get_poly( i, j ).GetId() ); sprintf(layer, "post_clip_accum_%u_%u", accum_idx++, polys_in.get_poly( i, j ).GetId() );
accum.ToShapefiles( ds_name, layer, false ); accum.ToShapefiles( ds_name, layer, false );
accum.ToClipperfiles( ds_name, layer, false ); accum.ToClipperfiles( ds_name, layer, false );
@ -281,10 +280,10 @@ bool TGConstruct::ClipLandclassPolys( void ) {
// Now make sure any newly added intersection nodes are added to the tgnodes // Now make sure any newly added intersection nodes are added to the tgnodes
for (unsigned int area = 0; area < area_defs.size(); area++) { for (unsigned int area = 0; area < area_defs.size(); area++) {
bool isRoad = area_defs.is_road_area( area ); bool isRoad = area_defs.is_road_area( area );
for (unsigned int p = 0; p < polys_clipped.area_size(area); p++ ) { for (unsigned int idxPoly = 0; idxPoly < polys_clipped.area_size(area); ++idxPoly ) {
tgPolygon& poly = polys_clipped.get_poly( area, p ); tgPolygon& poly = polys_clipped.get_poly( area, idxPoly );
SG_LOG( SG_CLIPPER, SG_DEBUG, "Collecting nodes for " << area_defs.get_area_name(area) << ":" << p+1 << " of " << polys_clipped.area_size(area) ); SG_LOG( SG_CLIPPER, SG_DEBUG, "Collecting nodes for " << area_defs.get_area_name(area) << ":" << idxPoly + 1 << " of " << polys_clipped.area_size(area) );
for (unsigned int con=0; con < poly.Contours(); con++) { for (unsigned int con=0; con < poly.Contours(); con++) {
for (unsigned int n = 0; n < poly.ContourSize( con ); n++) { for (unsigned int n = 0; n < poly.ContourSize( con ); n++) {

View file

@ -47,25 +47,24 @@ void TGConstruct::get_debug( void )
debug_shapes.clear(); debug_shapes.clear();
/* Find any ids for our tile */ /* Find any ids for our tile */
for (unsigned int i=0; i< debug_area_defs.size(); i++) { for (unsigned int i = 0; i < debug_area_defs.size(); ++i) {
string dsd = debug_area_defs[i]; string dsd = debug_area_defs[i];
size_t d_pos = dsd.find(":"); size_t d_pos = dsd.find(":");
string tile = dsd.substr(0, d_pos); string tile = dsd.substr(0, d_pos);
if( tile == bucket.gen_index_str() ) { if ( tile == bucket.gen_index_str() ) {
dsd.erase(0, d_pos+1); dsd.erase(0, d_pos + 1);
if ( dsd == "all" ) { if ( dsd == "all" ) {
debug_all = true; debug_all = true;
} else { } else {
std::stringstream ss(dsd); std::stringstream ss(dsd);
int i; int idx;
while (ss >> idx)
while (ss >> i)
{ {
SG_LOG(SG_GENERAL, SG_ALERT, "Adding debug area " << i); SG_LOG(SG_GENERAL, SG_ALERT, "Adding debug area " << idx);
debug_areas.push_back(i); debug_areas.push_back(idx);
if (ss.peek() == ',') if (ss.peek() == ',')
ss.ignore(); ss.ignore();
@ -74,25 +73,24 @@ void TGConstruct::get_debug( void )
} }
} }
for (unsigned int i=0; i< debug_shape_defs.size(); i++) { for (unsigned int i = 0; i < debug_shape_defs.size(); ++i) {
string dsd = debug_shape_defs[i]; string dsd = debug_shape_defs[i];
size_t d_pos = dsd.find(":"); size_t d_pos = dsd.find(":");
string tile = dsd.substr(0, d_pos); string tile = dsd.substr(0, d_pos);
if( tile == bucket.gen_index_str() ) { if ( tile == bucket.gen_index_str() ) {
dsd.erase(0, d_pos+1); dsd.erase(0, d_pos + 1);
if ( dsd == "all" ) { if ( dsd == "all" ) {
debug_all = true; debug_all = true;
} else { } else {
std::stringstream ss(dsd); std::stringstream ss(dsd);
int i; int idx;
while (ss >> idx)
while (ss >> i)
{ {
SG_LOG(SG_GENERAL, SG_ALERT, "Adding debug shape " << i); SG_LOG(SG_GENERAL, SG_ALERT, "Adding debug shape " << idx);
debug_shapes.push_back(i); debug_shapes.push_back(idx);
if (ss.peek() == ',') if (ss.peek() == ',')
ss.ignore(); ss.ignore();

View file

@ -34,9 +34,8 @@ using std::string;
// and return list of fitted nodes. // and return list of fitted nodes.
void TGConstruct::LoadElevationArray( bool add_nodes ) { void TGConstruct::LoadElevationArray( bool add_nodes ) {
string base = bucket.gen_base_path(); string base = bucket.gen_base_path();
int i;
for ( i = 0; i < (int)load_dirs.size(); ++i ) { for ( int i = 0; i < (int)load_dirs.size(); ++i ) {
string array_path = work_base + "/" + load_dirs[i] + "/" + base + "/" + bucket.gen_index_str(); string array_path = work_base + "/" + load_dirs[i] + "/" + base + "/" + bucket.gen_index_str();
if ( array.open(array_path) ) { if ( array.open(array_path) ) {
@ -48,14 +47,15 @@ void TGConstruct::LoadElevationArray( bool add_nodes ) {
array.parse( bucket ); array.parse( bucket );
array.remove_voids( ); array.remove_voids( );
if ( add_nodes ) { if ( add_nodes ) {
std::vector<SGGeod> const& corner_list = array.get_corner_list(); std::vector<SGGeod> const& corner_list = array.get_corner_list();
for (unsigned int i=0; i<corner_list.size(); i++) { for (unsigned int i = 0; i < corner_list.size(); ++i) {
nodes.unique_add( corner_list[i] ); nodes.unique_add( corner_list[i] );
} }
std::vector<SGGeod> const& fit_list = array.get_fitted_list(); std::vector<SGGeod> const& fit_list = array.get_fitted_list();
for (unsigned int i=0; i<fit_list.size(); i++) { for (unsigned int i = 0; i < fit_list.size(); ++i) {
SGGeod node = fit_list[i]; SGGeod node = fit_list[i];
if ( CheckMatchingNode( node, false, false ) ) { if ( CheckMatchingNode( node, false, false ) ) {
nodes.unique_add( node ); nodes.unique_add( node );

View file

@ -68,8 +68,7 @@ SGVec3f TGConstruct::calc_normal( double area, const SGVec3d& p1, const SGVec3d&
void TGConstruct::calc_normals( std::vector<SGGeod>& geod_nodes, std::vector<SGVec3d>& wgs84_nodes, tgPolygon& poly ) { void TGConstruct::calc_normals( std::vector<SGGeod>& geod_nodes, std::vector<SGVec3d>& wgs84_nodes, tgPolygon& poly ) {
// for each face in the superpoly, calculate a face normal // for each face in the superpoly, calculate a face normal
SGVec3f normal; SGVec3f normal;
double area;
for (unsigned int tri = 0; tri < poly.Triangles(); tri++) { for (unsigned int tri = 0; tri < poly.Triangles(); tri++) {
SGGeod g1 = geod_nodes[ poly.GetTriIdx( tri, 0 ) ]; SGGeod g1 = geod_nodes[ poly.GetTriIdx( tri, 0 ) ];
@ -80,7 +79,7 @@ void TGConstruct::calc_normals( std::vector<SGGeod>& geod_nodes, std::vector<SGV
SGVec3d v2 = wgs84_nodes[ poly.GetTriIdx( tri, 1 ) ]; SGVec3d v2 = wgs84_nodes[ poly.GetTriIdx( tri, 1 ) ];
SGVec3d v3 = wgs84_nodes[ poly.GetTriIdx( tri, 2 ) ]; SGVec3d v3 = wgs84_nodes[ poly.GetTriIdx( tri, 2 ) ];
area = tgTriangle::area( g1, g2, g3 ); double area = tgTriangle::area( g1, g2, g3 );
normal = calc_normal( area, v1, v2, v3 ); normal = calc_normal( area, v1, v2, v3 );
poly.SetTriFaceArea( tri, area ); poly.SetTriFaceArea( tri, area );

View file

@ -87,7 +87,7 @@ void TGConstruct::AddCustomObjects( void ) {
in.getline(line, 2048); in.getline(line, 2048);
SG_LOG( SG_GENERAL, SG_DEBUG, "line = " << line ); SG_LOG( SG_GENERAL, SG_DEBUG, "line = " << line );
int result = sscanf( line, "%s %s", token, name ); int result = sscanf( line, "%255s %255s", token, name );
SG_LOG( SG_GENERAL, SG_DEBUG, "scanf scanned " << result << " tokens" ); SG_LOG( SG_GENERAL, SG_DEBUG, "scanf scanned " << result << " tokens" );
if ( result > 0 ) { if ( result > 0 ) {
@ -133,10 +133,10 @@ void TGConstruct::WriteBtgFile( void )
nodes.get_wgs84_nodes( wgs84_nodes ); nodes.get_wgs84_nodes( wgs84_nodes );
SGVec3d gbs_center = SGVec3d::fromGeod( bucket.get_center() ); SGVec3d gbs_center = SGVec3d::fromGeod( bucket.get_center() );
double dist_squared, radius_squared = 0; double radius_squared = 0;
for (int i = 0; i < (int)wgs84_nodes.size(); ++i) for (int i = 0; i < (int)wgs84_nodes.size(); ++i)
{ {
dist_squared = distSqr(gbs_center, wgs84_nodes[i]); double dist_squared = distSqr(gbs_center, wgs84_nodes[i]);
if ( dist_squared > radius_squared ) { if ( dist_squared > radius_squared ) {
radius_squared = dist_squared; radius_squared = dist_squared;
} }

View file

@ -38,15 +38,13 @@ static unsigned int cur_poly_id = 0;
// load all 2d polygons from the specified load disk directories and // load all 2d polygons from the specified load disk directories and
// clip against each other to resolve any overlaps // clip against each other to resolve any overlaps
int TGConstruct::LoadLandclassPolys( void ) { int TGConstruct::LoadLandclassPolys( void ) {
int i;
string base = bucket.gen_base_path(); string base = bucket.gen_base_path();
string poly_path; string poly_path;
int total_polys_read = 0; int total_polys_read = 0;
tgPolygon poly; tgPolygon poly;
// load 2D polygons from all directories provided // load 2D polygons from all directories provided
for ( i = 0; i < (int)load_dirs.size(); ++i ) { for ( int i = 0; i < (int)load_dirs.size(); ++i ) {
poly_path = work_base + "/" + load_dirs[i] + '/' + base; poly_path = work_base + "/" + load_dirs[i] + '/' + base;
string tile_str = bucket.gen_index_str(); string tile_str = bucket.gen_index_str();
@ -72,7 +70,6 @@ int TGConstruct::LoadLandclassPolys( void ) {
{ {
// skipped! // skipped!
} else { } else {
int area;
std::string material; std::string material;
gzFile fp = gzopen( p.c_str(), "rb" ); gzFile fp = gzopen( p.c_str(), "rb" );
unsigned int count; unsigned int count;
@ -80,9 +77,9 @@ int TGConstruct::LoadLandclassPolys( void ) {
sgReadUInt( fp, &count ); sgReadUInt( fp, &count );
SG_LOG( SG_GENERAL, SG_DEBUG, " Load " << count << " polys from " << p.realpath() ); SG_LOG( SG_GENERAL, SG_DEBUG, " Load " << count << " polys from " << p.realpath() );
for ( unsigned int i=0; i<count; i++ ) { for ( unsigned int idx = 0; idx < count; ++idx ) {
poly.LoadFromGzFile( fp ); poly.LoadFromGzFile( fp );
area = area_defs.get_area_priority( poly.GetFlag() ); int area = area_defs.get_area_priority( poly.GetFlag() );
material = area_defs.get_area_name( area ); material = area_defs.get_area_name( area );
bool isRoad = area_defs.is_road_area( area ); bool isRoad = area_defs.is_road_area( area );
@ -212,11 +209,10 @@ bool TGConstruct::CheckMatchingNode( SGGeod& node, bool road, bool fixed )
SGGeod TGConstruct::GetNearestNodeLongitude( const SGGeod& node, const std::vector<SGGeod>& selection ) SGGeod TGConstruct::GetNearestNodeLongitude( const SGGeod& node, const std::vector<SGGeod>& selection )
{ {
double min_dist = std::numeric_limits<double>::infinity(); double min_dist = std::numeric_limits<double>::infinity();
double cur_dist;
unsigned int min_idx = 0; unsigned int min_idx = 0;
for ( unsigned int i=0; i<selection.size(); i++ ) { for ( unsigned int i = 0; i < selection.size(); ++i ) {
cur_dist = fabs( node.getLongitudeDeg() - selection[i].getLongitudeDeg() ); double cur_dist = fabs( node.getLongitudeDeg() - selection[i].getLongitudeDeg() );
if ( cur_dist < min_dist ) { if ( cur_dist < min_dist ) {
min_dist = cur_dist; min_dist = cur_dist;
min_idx = i; min_idx = i;
@ -229,11 +225,10 @@ SGGeod TGConstruct::GetNearestNodeLongitude( const SGGeod& node, const std::vect
SGGeod TGConstruct::GetNearestNodeLatitude( const SGGeod& node, const std::vector<SGGeod>& selection ) SGGeod TGConstruct::GetNearestNodeLatitude( const SGGeod& node, const std::vector<SGGeod>& selection )
{ {
double min_dist = std::numeric_limits<double>::infinity(); double min_dist = std::numeric_limits<double>::infinity();
double cur_dist;
unsigned int min_idx = 0; unsigned int min_idx = 0;
for ( unsigned int i=0; i<selection.size(); i++ ) { for ( unsigned int i = 0; i < selection.size(); ++i ) {
cur_dist = fabs( node.getLatitudeDeg() - selection[i].getLatitudeDeg() ); double cur_dist = fabs( node.getLatitudeDeg() - selection[i].getLatitudeDeg() );
if ( cur_dist < min_dist ) { if ( cur_dist < min_dist ) {
min_dist = cur_dist; min_dist = cur_dist;
min_idx = i; min_idx = i;

View file

@ -38,7 +38,7 @@ using std::string;
void TGConstruct::CreateMatchedEdgeFiles( std::vector<SGBucket>& bucketList ) void TGConstruct::CreateMatchedEdgeFiles( std::vector<SGBucket>& bucketList )
{ {
// todo - add to work queue // todo - add to work queue
for ( unsigned int i=0; i<bucketList.size(); i++ ) { for ( unsigned int i = 0; i < bucketList.size(); ++i ) {
SGBucket b = bucketList[i]; SGBucket b = bucketList[i];
nodes.clear(); nodes.clear();
@ -54,7 +54,7 @@ void TGConstruct::CreateMatchedEdgeFiles( std::vector<SGBucket>& bucketList )
int nCount; int nCount;
// read in all of the .btg nodes // read in all of the .btg nodes
for ( unsigned int j=0; j<wgs84_nodes.size(); j++ ) { for ( unsigned int j = 0; j < wgs84_nodes.size(); ++j ) {
SGGeod pos = SGGeod::fromCart( wgs84_nodes[j] + obj.get_gbs_center() ); SGGeod pos = SGGeod::fromCart( wgs84_nodes[j] + obj.get_gbs_center() );
nodes.unique_add( pos ); nodes.unique_add( pos );
} }
@ -83,32 +83,32 @@ void TGConstruct::CreateMatchedEdgeFiles( std::vector<SGBucket>& bucketList )
nCount = north.size(); nCount = north.size();
SG_LOG( SG_GENERAL, SG_DEBUG, "write " << north.size() << " northern nodes to file " << filepath.c_str() ); SG_LOG( SG_GENERAL, SG_DEBUG, "write " << north.size() << " northern nodes to file " << filepath.c_str() );
sgWriteInt( fp, nCount ); sgWriteInt( fp, nCount );
for (int i=0; i<nCount; i++) { for (int j = 0; j < nCount; ++j) {
sgWriteGeod( fp, north[i] ); sgWriteGeod( fp, north[j] );
} }
// south // south
nCount = south.size(); nCount = south.size();
SG_LOG( SG_GENERAL, SG_DEBUG, "write " << south.size() << " southern nodes to file " << filepath.c_str() ); SG_LOG( SG_GENERAL, SG_DEBUG, "write " << south.size() << " southern nodes to file " << filepath.c_str() );
sgWriteInt( fp, nCount ); sgWriteInt( fp, nCount );
for (int i=0; i<nCount; i++) { for (int j = 0; j < nCount; ++j) {
sgWriteGeod( fp, south[i] ); sgWriteGeod( fp, south[j] );
} }
// east // east
nCount = east.size(); nCount = east.size();
SG_LOG( SG_GENERAL, SG_DEBUG, "write " << east.size() << " eastern nodes to file " << filepath.c_str() ); SG_LOG( SG_GENERAL, SG_DEBUG, "write " << east.size() << " eastern nodes to file " << filepath.c_str() );
sgWriteInt( fp, nCount ); sgWriteInt( fp, nCount );
for (int i=0; i<nCount; i++) { for (int j = 0; j < nCount; ++j) {
sgWriteGeod( fp, east[i] ); sgWriteGeod( fp, east[j] );
} }
// west // west
nCount = west.size(); nCount = west.size();
SG_LOG( SG_GENERAL, SG_DEBUG, "write " << west.size() << " western nodes to file " << filepath.c_str() ); SG_LOG( SG_GENERAL, SG_DEBUG, "write " << west.size() << " western nodes to file " << filepath.c_str() );
sgWriteInt( fp, nCount ); sgWriteInt( fp, nCount );
for (int i=0; i<nCount; i++) { for (int j = 0; j < nCount; ++j) {
sgWriteGeod( fp, west[i] ); sgWriteGeod( fp, west[j] );
} }
gzclose(fp); gzclose(fp);

View file

@ -43,7 +43,7 @@ void TGConstruct::TesselatePolys( void )
if ( IsDebugShape( poly.GetId() ) ) { if ( IsDebugShape( poly.GetId() ) ) {
char layer[32]; char layer[32];
sprintf(layer, "pretess_%d_%d", area, p ); sprintf(layer, "pretess_%u_%u", area, p );
tgShapefile::FromPolygon( poly, ds_name, layer, "poly" ); tgShapefile::FromPolygon( poly, ds_name, layer, "poly" );
} }

View file

@ -66,12 +66,11 @@ void TGLandclass::LoadFromGzFile(gzFile& fp)
std::ostream& operator<< ( std::ostream& out, const TGLandclass& lc ) std::ostream& operator<< ( std::ostream& out, const TGLandclass& lc )
{ {
unsigned int count;
tgPolygon poly; tgPolygon poly;
// Save all landclass shapes // Save all landclass shapes
for (unsigned int i=0; i<lc.polys.size(); i++) { for (unsigned int i=0; i<lc.polys.size(); i++) {
count = lc.polys[i].size(); unsigned int count = lc.polys[i].size();
out << count << "\n"; out << count << "\n";
for (unsigned int j=0; j<count; j++) { for (unsigned int j=0; j<count; j++) {
out << lc.polys[i][j] << " "; out << lc.polys[i][j] << " ";
@ -84,14 +83,14 @@ std::ostream& operator<< ( std::ostream& out, const TGLandclass& lc )
void TGLandclass::SaveToGzFile(gzFile& fp) void TGLandclass::SaveToGzFile(gzFile& fp)
{ {
int i, j, num_layers, num_polys; int i, j, num_layers;
tgPolygon shape; tgPolygon shape;
// Save all landclass shapes // Save all landclass shapes
num_layers = polys.size(); num_layers = polys.size();
sgWriteInt( fp, num_layers ); sgWriteInt( fp, num_layers );
for (i=0; i<num_layers; i++) { for (i=0; i<num_layers; i++) {
num_polys = polys[i].size(); int num_polys = polys[i].size();
sgWriteInt( fp, num_polys ); sgWriteInt( fp, num_polys );
for (j=0; j<num_polys; j++) { for (j=0; j<num_polys; j++) {

View file

@ -140,8 +140,7 @@ int make_socket (char *host, unsigned short int port) {
// connect to the server and get the next task // connect to the server and get the next task
long int get_next_task( const string& host, int port, long int last_tile ) { long int get_next_task( const string& host, int port, long int last_tile ) {
long int tile; int sock;
int sock, len;
fd_set ready; fd_set ready;
char message[MAXBUF]; char message[MAXBUF];
@ -172,17 +171,17 @@ long int get_next_task( const string& host, int port, long int last_tile ) {
cout << " received reply" << endl; cout << " received reply" << endl;
if ( FD_ISSET(sock, &ready) ) { if ( FD_ISSET(sock, &ready) ) {
/* input coming from socket */ /* input coming from socket */
if ( (len = read(sock, message, MAXBUF)) > 0 ) { if ( (int len = read(sock, message, MAXBUF)) > 0 ) {
message[len] = '\0'; message[len] = '\0';
tile = atoi(message); long int tile = atoi(message);
cout << " tile to construct = " << tile << endl; cout << " tile to construct = " << tile << endl;
close(sock); close(sock);
return tile; return tile;
} else { } else {
close(sock); close(sock);
return -1; return -1;
} }
} }
close(sock); close(sock);

View file

@ -76,7 +76,6 @@ int make_socket (unsigned short int* port) {
// Give the socket a name. // Give the socket a name.
name.sin_family = AF_INET; name.sin_family = AF_INET;
name.sin_addr.s_addr = INADDR_ANY;
name.sin_port = 0 /* htons (port) */; name.sin_port = 0 /* htons (port) */;
name.sin_addr.s_addr = htonl (INADDR_ANY); name.sin_addr.s_addr = htonl (INADDR_ANY);
if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) { if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
@ -171,56 +170,56 @@ long int get_next_tile() {
// first time this routine is called, init counters // first time this routine is called, init counters
if ( first_time ) { if ( first_time ) {
first_time = false; first_time = false;
start_seconds = seconds = time(NULL); start_seconds = seconds = time(NULL);
counter = global_counter = 0; counter = global_counter = 0;
} }
// cout << "lon = " << lon << " lat = " << lat << endl; // cout << "lon = " << lon << " lat = " << lat << endl;
// cout << "start_lat = " << start_lat << endl; // cout << "start_lat = " << start_lat << endl;
if ( lon > start_lon + area_width ) { if ( lon > start_lon + area_width ) {
// increment to next row // increment to next row
// skip every other row (to avoid two clients working on // skip every other row (to avoid two clients working on
// adjacent tiles) // adjacent tiles)
lat += 2.0 * dy; lat += 2.0 * dy;
SGBucket tmp( SGGeod::fromDeg(0.0, lat) ); SGBucket tmp( SGGeod::fromDeg(0.0, lat) );
double dx = tmp.get_width(); double dx = tmp.get_width();
lon = start_lon + (shift_over*dx) + (dx*0.5); lon = start_lon + (shift_over*dx) + (dx*0.5);
} }
if ( lat > start_lat + area_height ) { if ( lat > start_lat + area_height ) {
++pass; ++pass;
if ( pass == 1 ) { if ( pass == 1 ) {
shift_over = 0.0; shift_over = 0.0;
shift_up = 0.0; shift_up = 0.0;
} else if ( pass == 2 ) { } else if ( pass == 2 ) {
shift_over = 1.0; shift_over = 1.0;
shift_up = 0.0; shift_up = 0.0;
} else if ( pass == 3 ) { } else if ( pass == 3 ) {
shift_over = 0.0; shift_over = 0.0;
shift_up = 1.0; shift_up = 1.0;
} else if ( pass == 4 ) { } else if ( pass == 4 ) {
shift_over = 1.0; shift_over = 1.0;
shift_up = 1.0; shift_up = 1.0;
} else { } else {
return -1; return -1;
} }
// reset lat // reset lat
// lat = -89.0 + (shift_up*dy) - (dy*0.5); // lat = -89.0 + (shift_up*dy) - (dy*0.5);
// lat = 27.0 + (0*dy) + (dy*0.5); // lat = 27.0 + (0*dy) + (dy*0.5);
lat = start_lat + (shift_up*dy) + (dy*0.5); lat = start_lat + (shift_up*dy) + (dy*0.5);
// reset lon // reset lon
SGBucket tmp( SGGeod::fromDeg(0.0, lat) ); SGBucket tmp( SGGeod::fromDeg(0.0, lat) );
double dx = tmp.get_width(); double dx = tmp.get_width();
// lon = -82 + (shift_over*dx) + (dx*0.5); // lon = -82 + (shift_over*dx) + (dx*0.5);
lon = start_lon + (shift_over*dx) + (dx*0.5); lon = start_lon + (shift_over*dx) + (dx*0.5);
cout << "starting pass = " << pass cout << "starting pass = " << pass
<< " with lat = " << lat << " lon = " << lon << endl; << " with lat = " << lat << " lon = " << lon << endl;
} }
// if ( ! start_lon ) { // if ( ! start_lon ) {

View file

@ -38,19 +38,20 @@
using std::string; using std::string;
TGArray::TGArray( void ): TGArray::TGArray() :
array_in(NULL), array_in(NULL),
fitted_in(NULL), fitted_in(NULL),
in_data(NULL) originx(0.0), originy(0.0),
cols(0), rows(0),
rectified(false),
col_step(0.0), row_step(0.0),
in_data(NULL)
{ {
} }
TGArray::TGArray( const string &file ): TGArray::TGArray( const string &file ) :
array_in(NULL), TGArray()
fitted_in(NULL),
in_data(NULL)
{ {
TGArray::open(file); TGArray::open(file);
} }
@ -123,7 +124,6 @@ void TGArray::load_cliffs(const string & height_base)
{ {
//Get the directory so we can list the children //Get the directory so we can list the children
tgPolygon poly; //actually a contour but whatever... tgPolygon poly; //actually a contour but whatever...
int total_contours_read = 0;
SGPath b(height_base); SGPath b(height_base);
simgear::Dir d(b.dir()); simgear::Dir d(b.dir());
simgear::PathList files = d.children(simgear::Dir::TYPE_FILE); simgear::PathList files = d.children(simgear::Dir::TYPE_FILE);
@ -199,7 +199,6 @@ TGArray::parse( SGBucket& b ) {
SG_LOG(SG_GENERAL, SG_DEBUG, " cols = " << cols << " rows = " << rows ); SG_LOG(SG_GENERAL, SG_DEBUG, " cols = " << cols << " rows = " << rows );
SG_LOG(SG_GENERAL, SG_DEBUG, " col_step = " << col_step << " row_step = " << row_step ); SG_LOG(SG_GENERAL, SG_DEBUG, " col_step = " << col_step << " row_step = " << row_step );
in_data = new short[cols * rows]; in_data = new short[cols * rows];
memset(in_data, 0, sizeof(short) * cols * rows); memset(in_data, 0, sizeof(short) * cols * rows);
SG_LOG(SG_GENERAL, SG_DEBUG, " File not open, so using zero'd data" ); SG_LOG(SG_GENERAL, SG_DEBUG, " File not open, so using zero'd data" );
@ -250,40 +249,41 @@ void TGArray::parse_bin()
// Write out an array. If rectified is true, the heights have been adjusted // Write out an array. If rectified is true, the heights have been adjusted
// for discontinuities. // for discontinuities.
void TGArray::write_bin(const string root_dir, bool rectified, SGBucket& b) { void TGArray::write_bin(const string& root_dir, bool rectified, SGBucket& b) {
// generate output file name // generate output file name
string base = b.gen_base_path(); string base = b.gen_base_path();
string path = root_dir + "/" + base; string path = root_dir + "/" + base;
string extension = ".arr.new.gz"; string extension = ".arr.new.gz";
if (rectified) extension = ".arr.rectified.gz"; if (rectified)
SGPath sgp( path ); extension = ".arr.rectified.gz";
sgp.append( "dummy" ); SGPath sgp( path );
sgp.create_dir( 0755 ); sgp.append( "dummy" );
sgp.create_dir( 0755 );
string array_file = path + "/" + b.gen_index_str() + extension;
SG_LOG(SG_GENERAL, SG_DEBUG, "array_file = " << array_file );
// write the file
gzFile fp;
if ( (fp = gzopen( array_file.c_str(), "wb9" )) == NULL ) {
SG_LOG(SG_GENERAL, SG_ALERT, "ERROR: cannot open " << array_file << " for writing!" );
return;
}
int32_t header = 0x54474152; //'TGAR' string array_file = path + "/" + b.gen_index_str() + extension;
sgWriteLong(fp,header); SG_LOG(SG_GENERAL, SG_DEBUG, "array_file = " << array_file );
sgWriteInt(fp,originx);
sgWriteInt(fp,originy); // write the file
sgWriteInt(fp,cols); gzFile fp;
sgWriteInt(fp,col_step); if ( (fp = gzopen( array_file.c_str(), "wb9" )) == NULL ) {
sgWriteInt(fp,rows); SG_LOG(SG_GENERAL, SG_ALERT, "ERROR: cannot open " << array_file << " for writing!" );
sgWriteInt(fp,row_step); return;
sgWriteShort(fp, rows*cols, in_data); }
gzclose(fp);
int32_t header = 0x54474152; //'TGAR'
sgWriteLong(fp,header);
sgWriteInt(fp,originx);
sgWriteInt(fp,originy);
sgWriteInt(fp,cols);
sgWriteInt(fp,col_step);
sgWriteInt(fp,rows);
sgWriteInt(fp,row_step);
sgWriteShort(fp, rows*cols, in_data);
gzclose(fp);
} }
// write an Array file // write an Array file
bool TGArray::write( const string root_dir, SGBucket& b ) { bool TGArray::write( const string& root_dir, SGBucket& b ) {
// generate output file name // generate output file name
string base = b.gen_base_path(); string base = b.gen_base_path();
string path = root_dir + "/" + base; string path = root_dir + "/" + base;
@ -297,18 +297,18 @@ bool TGArray::write( const string root_dir, SGBucket& b ) {
// write the file // write the file
gzFile fp; gzFile fp;
if ( (fp = gzopen( array_file.c_str(), "wb9" )) == NULL ) { if ( (fp = gzopen( array_file.c_str(), "wb9" )) == NULL ) {
SG_LOG(SG_GENERAL, SG_ALERT, "ERROR: cannot open " << array_file << " for writing!" ); SG_LOG(SG_GENERAL, SG_ALERT, "ERROR: cannot open " << array_file << " for writing!" );
return false; return false;
} }
SG_LOG(SG_GENERAL, SG_DEBUG, "origin = " << originx << ", " << originy ); SG_LOG(SG_GENERAL, SG_DEBUG, "origin = " << originx << ", " << originy );
gzprintf( fp, "%d %d\n", (int)originx, (int)originy ); gzprintf( fp, "%d %d\n", (int)originx, (int)originy );
gzprintf( fp, "%d %d %d %d\n", cols, (int)col_step, rows, (int)row_step ); gzprintf( fp, "%d %d %d %d\n", cols, (int)col_step, rows, (int)row_step );
for ( int i = 0; i < cols; ++i ) { for ( int i = 0; i < cols; ++i ) {
for ( int j = 0; j < rows; ++j ) { for ( int j = 0; j < rows; ++j ) {
gzprintf( fp, "%d ", get_array_elev(i, j) ); gzprintf( fp, "%d ", get_array_elev(i, j) );
} }
gzprintf( fp, "\n" ); gzprintf( fp, "\n" );
} }
gzclose(fp); gzclose(fp);
@ -445,7 +445,7 @@ std::vector<int> TGArray::collect_bad_points(const double bad_zone) {
} }
// Check to see if the specified grid point is bad // Check to see if the specified grid point is bad
bool TGArray::is_bad_point(const int xgrid, const int ygrid, const std::vector<int> bad_points) const { bool TGArray::is_bad_point(const int xgrid, const int ygrid, const std::vector<int>& bad_points) const {
int grididx; int grididx;
grididx = xgrid+ygrid*cols; grididx = xgrid+ygrid*cols;
auto result = std::find( std::begin(bad_points),std::end(bad_points),grididx ); auto result = std::find( std::begin(bad_points),std::end(bad_points),grididx );
@ -504,15 +504,13 @@ through the three known points.
TODO: Handle points on the boundaries. */ TODO: Handle points on the boundaries. */
double TGArray::rectify_point(const int xgrid, const int ygrid, const std::vector<int> bad_points) const { double TGArray::rectify_point(const int xgrid, const int ygrid, const std::vector<int>& bad_points) const {
//xgrid: grid units horizontally //xgrid: grid units horizontally
//ygrid: grid units vertically //ygrid: grid units vertically
//Loop over corner points, if no points available, give up //Loop over corner points, if no points available, give up
int corners[4][2]; //possible corners int corners[4][2]; //possible corners
int final_pts[3][2]; // rectangle corners
int pt_cnt = 0; int pt_cnt = 0;
double centre_long, centre_lat; double centre_long, centre_lat;
double cliff_error = col_step; //Assume row step, col step the same
int original_height = get_array_elev(xgrid,ygrid); int original_height = get_array_elev(xgrid,ygrid);
centre_long = (originx + col_step*xgrid)/3600; centre_long = (originx + col_step*xgrid)/3600;
centre_lat = (originy + row_step*ygrid)/3600; centre_lat = (originy + row_step*ygrid)/3600;
@ -587,7 +585,8 @@ double TGArray::altitude_from_grid( double lon, double lat ) const {
// we expect incoming (lon,lat) to be in arcsec for now // we expect incoming (lon,lat) to be in arcsec for now
double xlocal, ylocal, dx, dy, zA, zB, elev; double xlocal, ylocal, dx, dy, zA, zB, elev;
int x1, x2, x3, y1, y2, y3; int x1 = 0, x2 = 0, x3 = 0;
int y1 = 0, y2 = 0, y3 = 0;
float z1, z2, z3; float z1, z2, z3;
int xindex, yindex; int xindex, yindex;
@ -612,19 +611,19 @@ double TGArray::altitude_from_grid( double lon, double lat ) const {
yindex = (int)(ylocal); yindex = (int)(ylocal);
if ( xindex + 1 == cols ) { if ( xindex + 1 == cols ) {
xindex--; xindex--;
} }
if ( yindex + 1 == rows ) { if ( yindex + 1 == rows ) {
yindex--; yindex--;
} }
if ( (xindex < 0) || (xindex + 1 >= cols) || if ( (xindex < 0) || (xindex + 1 >= cols) ||
(yindex < 0) || (yindex + 1 >= rows) ) { (yindex < 0) || (yindex + 1 >= rows) ) {
SG_LOG(SG_GENERAL, SG_DEBUG, "WARNING: Attempt to interpolate value outside of array!!!" ); SG_LOG(SG_GENERAL, SG_DEBUG, "WARNING: Attempt to interpolate value outside of array!!!" );
return -9999; return -9999;
} }
// Now check if we are on the same side of any cliffs // Now check if we are on the same side of any cliffs
@ -858,10 +857,10 @@ bool TGArray::check_points( const double lon1, const double lat1, const double l
SGGeod pt2 = SGGeod::fromDeg( lon2,lat2 ); SGGeod pt2 = SGGeod::fromDeg( lon2,lat2 );
bool same_side = true; bool same_side = true;
for ( int i=0;i<cliffs_list.size();i++ ) { for ( int i = 0; i < static_cast<int>(cliffs_list.size()); ++i ) {
bool check_result = cliffs_list[i].AreSameSide( pt1,pt2 ); bool check_result = cliffs_list[i].AreSameSide( pt1,pt2 );
if(!check_result) { if (!check_result) {
SG_LOG(SG_GENERAL, SG_DEBUG, "Cliff " << i <<":" <<pt1 << " and " << pt2 << " on opposite sides"); SG_LOG(SG_GENERAL, SG_DEBUG, "Cliff " << i <<":" <<pt1 << " and " << pt2 << " on opposite sides");
@ -881,7 +880,7 @@ bool TGArray::is_near_cliff( const double lon1, const double lat1, const double
SGGeod pt1 = SGGeod::fromDeg(lon1,lat1); SGGeod pt1 = SGGeod::fromDeg(lon1,lat1);
for ( int i=0;i<cliffs_list.size();i++ ) { for ( int i = 0; i < static_cast<int>(cliffs_list.size()); ++i ) {
double dist = cliffs_list[i].MinDist(pt1); double dist = cliffs_list[i].MinDist(pt1);
if (dist < bad_zone) return true; if (dist < bad_zone) return true;
} }
@ -926,4 +925,3 @@ bool TGArray::is_open() const
return false; return false;
} }
} }

View file

@ -47,8 +47,9 @@ private:
// number of columns and rows // number of columns and rows
int cols, rows; int cols, rows;
// Whether or not the input data have been rectified // Whether or not the input data have been rectified
bool rectified; bool rectified;
// Distance between column and row data points (in arc seconds) // Distance between column and row data points (in arc seconds)
double col_step, row_step; double col_step, row_step;
@ -59,20 +60,22 @@ private:
std::vector<SGGeod> corner_list; std::vector<SGGeod> corner_list;
std::vector<SGGeod> fitted_list; std::vector<SGGeod> fitted_list;
// list of cliff contours // list of cliff contours
tgcontour_list cliffs_list; tgcontour_list cliffs_list;
void parse_bin(); void parse_bin();
// Routines for height rectification // Routines for height rectification
std::vector<int> collect_bad_points(const double bad_zone); std::vector<int> collect_bad_points(const double bad_zone);
bool is_bad_point(const int xgrid, const int ygrid, const std::vector<int> bad_points) const; bool is_bad_point(const int xgrid, const int ygrid, const std::vector<int>& bad_points) const;
double rectify_point(const int xgrid, const int ygrid, const std::vector<int> bad_points) const; double rectify_point(const int xgrid, const int ygrid, const std::vector<int>& bad_points) const;
bool is_near_cliff(const double lon1,const double lon2, const double bad_zone) const; bool is_near_cliff(const double lon1,const double lon2, const double bad_zone) const;
public: public:
// Constructor // Constructor
TGArray( void ); TGArray( void );
TGArray( const std::string& file ); explicit TGArray( const std::string& file );
// Destructor // Destructor
~TGArray( void ); ~TGArray( void );
@ -80,8 +83,8 @@ public:
// open an Array file (use "-" if input is coming from stdin) // open an Array file (use "-" if input is coming from stdin)
bool open ( const std::string& file_base ); bool open ( const std::string& file_base );
// Load contours from polygon files delineating height discontinuities // Load contours from polygon files delineating height discontinuities
void load_cliffs(const std::string & height_base); void load_cliffs(const std::string & height_base);
// return if array was successfully opened or not // return if array was successfully opened or not
bool is_open() const; bool is_open() const;
@ -93,11 +96,11 @@ public:
bool parse( SGBucket& b ); bool parse( SGBucket& b );
// write an Array file // write an Array file
bool write( const std::string root_dir, SGBucket& b ); bool write( const std::string& root_dir, SGBucket& b );
// write an Array file in binary format. If ht_rect is true, // write an Array file in binary format. If ht_rect is true,
// the file will have extension 'arr.rectified.gz' // the file will have extension 'arr.rectified.gz'
void write_bin(const std::string root_dir, bool ht_rect, SGBucket& b); void write_bin(const std::string& root_dir, bool ht_rect, SGBucket& b);
// do our best to remove voids by picking data from the nearest // do our best to remove voids by picking data from the nearest
// neighbor. // neighbor.
@ -127,8 +130,9 @@ public:
int get_array_elev( int col, int row ) const; int get_array_elev( int col, int row ) const;
void set_array_elev( int col, int row, int val ); void set_array_elev( int col, int row, int val );
// Check whether or not two points are on the same side of contour // Check whether or not two points are on the same side of contour
bool check_points (const double a,const double b, const double c, const double d) const; bool check_points (const double a,const double b, const double c, const double d) const;
// reset Array to initial state - ready to load another elevation file // reset Array to initial state - ready to load another elevation file
void unload( void ); void unload( void );
}; };

View file

@ -40,7 +40,7 @@ and if they have an associated cliff file, will adjust and then output
the heights. */ the heights. */
// display usage and exit // display usage and exit
static void usage( const std::string name ) { static void usage( const std::string& name ) {
SG_LOG(SG_GENERAL, SG_ALERT, "Usage: " << name); SG_LOG(SG_GENERAL, SG_ALERT, "Usage: " << name);
SG_LOG(SG_GENERAL, SG_ALERT, " --work-dir=<directory>"); SG_LOG(SG_GENERAL, SG_ALERT, " --work-dir=<directory>");
SG_LOG(SG_GENERAL, SG_ALERT, " --height-dir=<directory>"); SG_LOG(SG_GENERAL, SG_ALERT, " --height-dir=<directory>");
@ -69,26 +69,26 @@ int main( int argc, char **argv) {
// //
int arg_pos; int arg_pos;
for (arg_pos = 1; arg_pos < argc; arg_pos++) { for (arg_pos = 1; arg_pos < argc; arg_pos++) {
std::string arg = argv[arg_pos]; std::string arg = argv[arg_pos];
if (arg.find("--work-dir=") == 0) { if (arg.compare(0, 11, "--work-dir=") == 0) {
work_dir = arg.substr(11); work_dir = arg.substr(11);
} else if (arg.find("--height-dir=") == 0) { } else if (arg.compare(0, 13, "--height-dir=") == 0) {
height_dir = arg.substr(13); height_dir = arg.substr(13);
} else if (arg.find("--tile-id=") == 0) { } else if (arg.compare(0, 10, "--tile-id=") == 0) {
tile_id = atol(arg.substr(10).c_str()); tile_id = atol(arg.substr(10).c_str());
} else if ( arg.find("--min-lon=") == 0 ) { } else if ( arg.compare(0, 10, "--min-lon=") == 0 ) {
min.setLongitudeDeg(atof( arg.substr(10).c_str() )); min.setLongitudeDeg(atof( arg.substr(10).c_str() ));
} else if ( arg.find("--max-lon=") == 0 ) { } else if ( arg.compare(0, 10, "--max-lon=") == 0 ) {
max.setLongitudeDeg(atof( arg.substr(10).c_str() )); max.setLongitudeDeg(atof( arg.substr(10).c_str() ));
} else if ( arg.find("--min-lat=") == 0 ) { } else if ( arg.compare(0, 10, "--min-lat=") == 0 ) {
min.setLatitudeDeg(atof( arg.substr(10).c_str() )); min.setLatitudeDeg(atof( arg.substr(10).c_str() ));
} else if ( arg.find("--max-lat=") == 0 ) { } else if ( arg.compare(0, 10, "--max-lat=") == 0 ) {
max.setLatitudeDeg(atof( arg.substr(10).c_str() )); max.setLatitudeDeg(atof( arg.substr(10).c_str() ));
} else if ( arg.find("--min-dist=") == 0) { } else if ( arg.compare(0, 11, "--min-dist=") == 0) {
bad_zone = atof(arg.substr(11).c_str()); bad_zone = atof(arg.substr(11).c_str());
} else if (arg.find("--") == 0) { } else if (arg.compare(0, 2, "--") == 0) {
usage(argv[0]); usage(argv[0]);
} else { } else {
break; break;
} }

View file

@ -38,23 +38,51 @@ using std::string;
TGDem::TGDem() : TGDem::TGDem() :
z_units(2) // meters in(nullptr),
dem_data(new float[DEM_SIZE_1][DEM_SIZE_1]),
output_data(new float[DEM_SIZE_1][DEM_SIZE_1]),
dem_description(""),
dem_quadrangle(""),
option_name("")
{ {
// cout << "class TGDem CONstructor called." << endl; originx = originy = 0.0;
dem_data = new float[DEM_SIZE_1][DEM_SIZE_1]; cols =rows = 0;
output_data = new float[DEM_SIZE_1][DEM_SIZE_1]; col_step = row_step = 0.0;
dem_x1 = dem_x2 = dem_x3 = dem_x4 = 0.0;
dem_y1 = dem_y2 = dem_y3 = dem_y4 = 0.0;
dem_z1 = dem_z2 = 0.0;
dem_resolution = dem_num_profiles = 0;
prof_col = prof_row = 0;
prof_num_cols = prof_num_rows = 0;
prof_x1 = prof_y1 = 0.0;
prof_data = 0.0;
do_data = 0;
cur_col = cur_row = 0;
z_units = 2; // meters
for (int x = 0; x < DEM_SIZE_1; ++x) {
for (int y = 0; y < DEM_SIZE_1; ++y) {
dem_data[x][y] = 0.0;
output_data[x][y] = 0.0;
}
}
} }
TGDem::TGDem( const string &file ) { TGDem::TGDem( const string &file ) :
// cout << "class TGDem CONstructor called." << endl; TGDem::TGDem()
dem_data = new float[DEM_SIZE_1][DEM_SIZE_1]; {
output_data = new float[DEM_SIZE_1][DEM_SIZE_1];
TGDem::open(file); TGDem::open(file);
} }
TGDem::~TGDem() {
// printf("class TGDem DEstructor called.\n");
delete [] dem_data;
delete [] output_data;
}
// open a DEM file // open a DEM file
bool bool
TGDem::open ( const string& file ) { TGDem::open ( const string& file ) {
@ -150,7 +178,6 @@ TGDem::next_exp() {
bool bool
TGDem::read_a_record() { TGDem::read_a_record() {
int i, inum; int i, inum;
double dnum;
string name, token, buf; string name, token, buf;
char c; char c;
@ -187,7 +214,7 @@ TGDem::read_a_record() {
// Map projection parameters (ignored) // Map projection parameters (ignored)
for ( i = 0; i < 15; i++ ) { for ( i = 0; i < 15; i++ ) {
dnum = next_exp(); double dnum = next_exp();
SG_LOG(SG_GENERAL, SG_DEBUG, i << ": " << dnum); SG_LOG(SG_GENERAL, SG_DEBUG, i << ": " << dnum);
} }
@ -446,8 +473,8 @@ TGDem::write_area( const string& root, SGBucket& b ) {
} }
gzprintf( fp, "%d %d\n", (int)min_x, (int)min_y ); gzprintf( fp, "%d %d\n", (int)min_x, (int)min_y );
gzprintf( fp, "%d %f %d %f\n", span_x + 1, (int)col_step, gzprintf( fp, "%d %f %d %f\n", span_x + 1, col_step,
span_y + 1, (int)row_step ); span_y + 1, row_step );
for ( int i = start_x; i <= start_x + span_x; ++i ) { for ( int i = start_x; i <= start_x + span_x; ++i ) {
for ( int j = start_y; j <= start_y + span_y; ++j ) { for ( int j = start_y; j <= start_y + span_y; ++j ) {
gzprintf( fp, "%d ", (int)dem_data[i][j] ); gzprintf( fp, "%d ", (int)dem_data[i][j] );
@ -459,12 +486,6 @@ TGDem::write_area( const string& root, SGBucket& b ) {
return true; return true;
} }
TGDem::~TGDem() {
// printf("class TGDem DEstructor called.\n");
delete [] dem_data;
delete [] output_data;
}
bool bool
TGDem::has_non_zero_elev (int start_x, int span_x, TGDem::has_non_zero_elev (int start_x, int span_x,

View file

@ -95,7 +95,7 @@ public:
// Constructor // Constructor
TGDem(); TGDem();
TGDem( const std::string& file ); explicit TGDem( const std::string& file );
// Destructor // Destructor
~TGDem(); ~TGDem();

View file

@ -47,7 +47,6 @@
#include <simgear/misc/sg_dir.hxx> #include <simgear/misc/sg_dir.hxx>
#include <simgear/debug/logstream.hxx> #include <simgear/debug/logstream.hxx>
#include "dted.hxx" #include "dted.hxx"
using std::cout; using std::cout;
@ -61,16 +60,30 @@ TGDted::TGDted( int _res )
data = new short int[MAX_DTED_SIZE][MAX_DTED_SIZE]; data = new short int[MAX_DTED_SIZE][MAX_DTED_SIZE];
output_data = new short int[MAX_DTED_SIZE][MAX_DTED_SIZE]; output_data = new short int[MAX_DTED_SIZE][MAX_DTED_SIZE];
for (int x = 0; x < MAX_DTED_SIZE; ++x) {
for (int y = 0; y < MAX_DTED_SIZE; ++y) {
data[x][y] = 0;
output_data[x][y] = 0;
}
}
} }
TGDted::TGDted( int _res, const SGPath &file ):TGDted(_res) TGDted::TGDted( int _res, const SGPath &file ) :
TGDted(_res)
{ {
TGDted::open( file ); TGDted::open( file );
} }
TGDted::~TGDted() {
// printf("class TGSrtmBase DEstructor called.\n");
delete [] data;
delete [] output_data;
}
// open an DTED file // open an DTED file
bool bool
TGDted::open ( const SGPath &f ) { TGDted::open ( const SGPath &f ) {
@ -222,11 +235,3 @@ TGDted::load( ) {
return true; return true;
} }
TGDted::~TGDted() {
// printf("class TGSrtmBase DEstructor called.\n");
delete [] data;
delete [] output_data;
}

View file

@ -60,7 +60,7 @@ public:
// Constructor, _res must be either "1" for the 1arcsec data or // Constructor, _res must be either "1" for the 1arcsec data or
// "3" for the 3arcsec data. // "3" for the 3arcsec data.
TGDted( int _res ); explicit TGDted( int _res );
TGDted( int _res, const SGPath &file ); TGDted( int _res, const SGPath &file );
// Destructor // Destructor
@ -75,7 +75,7 @@ public:
// load an dted file // load an dted file
bool load(); bool load();
virtual short height( int x, int y ) const { return data[x][y]; } virtual short height( int x, int y ) const override { return data[x][y]; }
}; };

View file

@ -58,20 +58,32 @@ TGHgt::TGHgt( int _res )
hgt_resolution = _res; hgt_resolution = _res;
data = new short int[MAX_HGT_SIZE][MAX_HGT_SIZE]; data = new short int[MAX_HGT_SIZE][MAX_HGT_SIZE];
output_data = new short int[MAX_HGT_SIZE][MAX_HGT_SIZE]; read_buffer = new short int[MAX_HGT_SIZE];
for (int x = 0; x < MAX_HGT_SIZE; ++x) {
for (int y = 0; y < MAX_HGT_SIZE; ++y) {
data[x][y] = 0;
}
read_buffer[x] = 0;
}
} }
TGHgt::TGHgt( int _res, const SGPath &file ) TGHgt::TGHgt( int _res, const SGPath &file ) :
TGHgt( _res )
{ {
hgt_resolution = _res;
data = new short int[MAX_HGT_SIZE][MAX_HGT_SIZE];
output_data = new short int[MAX_HGT_SIZE][MAX_HGT_SIZE];
TGHgt::open( file ); TGHgt::open( file );
} }
TGHgt::~TGHgt() {
// printf("class TGSrtmBase DEstructor called.\n");
delete [] data;
delete [] read_buffer;
}
// open an HGT file // open an HGT file
bool bool
TGHgt::open ( const SGPath &f ) { TGHgt::open ( const SGPath &f ) {
@ -164,26 +176,22 @@ TGHgt::load( ) {
return false; return false;
} }
short int *var;
for ( int row = size - 1; row >= 0; --row ) { for ( int row = size - 1; row >= 0; --row ) {
for ( int col = 0; col < size; ++col ) { if ( gzfread( (voidp)read_buffer, 2, size, fd ) != (unsigned)size ) {
var = &data[col][row]; return false;
if ( gzread ( fd, var, sizeof(short) ) != sizeof(short) ) { }
return false;
} // convert to column-major
if ( sgIsLittleEndian() ) { for ( int col = 0; col < size; ++col )
sgEndianSwap( (unsigned short int*)var); data[col][row] = *(read_buffer + col);
} }
if (sgIsLittleEndian()) {
auto pData = (unsigned short *)data;
for (int i = 0; i < rows * cols; ++i) {
sgEndianSwap(pData++);
} }
} }
return true; return true;
} }
TGHgt::~TGHgt() {
// printf("class TGSrtmBase DEstructor called.\n");
delete [] data;
delete [] output_data;
}

View file

@ -53,13 +53,13 @@ private:
// pointers to the actual grid data allocated here // pointers to the actual grid data allocated here
short int (*data)[MAX_HGT_SIZE]; short int (*data)[MAX_HGT_SIZE];
short int (*output_data)[MAX_HGT_SIZE]; short int *read_buffer;
public: public:
// Constructor, _res must be either "1" for the 1arcsec data or // Constructor, _res must be either "1" for the 1arcsec data or
// "3" for the 3arcsec data. // "3" for the 3arcsec data.
TGHgt( int _res ); explicit TGHgt( int _res );
TGHgt( int _res, const SGPath &file ); TGHgt( int _res, const SGPath &file );
// Destructor // Destructor
@ -74,7 +74,7 @@ public:
// load an hgt file // load an hgt file
bool load(); bool load();
virtual short height( int x, int y ) const { return data[x][y]; } virtual short height( int x, int y ) const override { return data[x][y]; }
}; };

View file

@ -21,10 +21,6 @@
// $Id: hgt.cxx,v 1.7 2005-12-19 16:06:45 curt Exp $ // $Id: hgt.cxx,v 1.7 2005-12-19 16:06:45 curt Exp $
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <iostream> #include <iostream>
#include <stdlib.h> #include <stdlib.h>
#include <zlib.h> #include <zlib.h>

View file

@ -24,10 +24,6 @@
#ifndef _SRTMBASE_HXX #ifndef _SRTMBASE_HXX
#define _SRTMBASE_HXX #define _SRTMBASE_HXX
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <simgear/compiler.h> #include <simgear/compiler.h>
#include <simgear/bucket/newbucket.hxx> #include <simgear/bucket/newbucket.hxx>
@ -36,8 +32,13 @@
class TGSrtmBase { class TGSrtmBase {
protected: protected:
TGSrtmBase() : remove_tmp_file(false) TGSrtmBase() :
{} remove_tmp_file(false)
{
originx = originy = 0.0;
cols = rows = 0;
col_step = row_step = 0.0;
}
~TGSrtmBase(); ~TGSrtmBase();
@ -83,5 +84,3 @@ public:
#endif // _SRTMBASE_HXX #endif // _SRTMBASE_HXX

View file

@ -61,7 +61,7 @@ class LandCover {
public: public:
LandCover( const std::string &filename ); explicit LandCover( const std::string &filename );
virtual ~LandCover (); virtual ~LandCover ();
virtual int getValue (long x, long y) const; virtual int getValue (long x, long y) const;

View file

@ -40,7 +40,7 @@ main (int ac, const char * av[])
int value = lu.getValue(lon, lat); int value = lu.getValue(lon, lat);
cout << "Value is " << value cout << "Value is " << value
<< " \"" << lu.getDescUSGS(value) << '"' << endl; << " \"" << lu.getDescUSGS(value) << '"' << endl;
} catch (string e) { } catch (const string& e) {
cerr << "Died with exception: " << e << endl; cerr << "Died with exception: " << e << endl;
return 1; return 1;
} }

View file

@ -60,13 +60,13 @@ public:
@param A rectangular (m>=n) matrix. @param A rectangular (m>=n) matrix.
*/ */
QR(const TNT::Array2D<Real> &A) /* constructor */ explicit QR(const TNT::Array2D<Real> &A) : /* constructor */
{ QR_(A.copy())
QR_ = A.copy(); {
m = A.dim1(); m = A.dim1();
n = A.dim2(); n = A.dim2();
Rdiag = TNT::Array1D<Real>(n); Rdiag = TNT::Array1D<Real>(n);
int i=0, j=0, k=0; int i, j, k;
// Main loop. // Main loop.
for (k = 0; k < n; k++) { for (k = 0; k < n; k++) {
@ -182,7 +182,7 @@ public:
TNT::Array2D<Real> getQ() const TNT::Array2D<Real> getQ() const
{ {
int i=0, j=0, k=0; int i, j, k;
TNT::Array2D<Real> Q(m,n); TNT::Array2D<Real> Q(m,n);
for (k = n-1; k >= 0; k--) { for (k = n-1; k >= 0; k--) {
@ -277,7 +277,7 @@ public:
int nx = B.dim2(); int nx = B.dim2();
TNT::Array2D<Real> X = B.copy(); TNT::Array2D<Real> X = B.copy();
int i=0, j=0, k=0; int i, j, k;
// Compute Y = transpose(Q)*B // Compute Y = transpose(Q)*B
for (k = 0; k < n; k++) { for (k = 0; k < n; k++) {

View file

@ -181,6 +181,8 @@ int PolyTree::Total() const
PolyNode::PolyNode(): Parent(0), Index(0), m_IsOpen(false) PolyNode::PolyNode(): Parent(0), Index(0), m_IsOpen(false)
{ {
m_jointype = JoinType::Square;
m_endtype = EndType::ClosedPolygon;
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
@ -256,7 +258,7 @@ class Int128
Int128(long64 _lo = 0) Int128(long64 _lo = 0)
{ {
lo = (ulong64)_lo; lo = (ulong64)_lo;
if (_lo < 0) hi = -1; else hi = 0; if (_lo < 0) hi = -1; else hi = 0;
} }
@ -551,8 +553,8 @@ bool SlopesEqual(const TEdge &e1, const TEdge &e2, bool UseFullInt64Range)
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
bool SlopesEqual(const IntPoint pt1, const IntPoint pt2, bool SlopesEqual(const IntPoint& pt1, const IntPoint& pt2,
const IntPoint pt3, bool UseFullInt64Range) const IntPoint& pt3, bool UseFullInt64Range)
{ {
#ifndef use_int32 #ifndef use_int32
if (UseFullInt64Range) if (UseFullInt64Range)
@ -563,8 +565,8 @@ bool SlopesEqual(const IntPoint pt1, const IntPoint pt2,
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
bool SlopesEqual(const IntPoint pt1, const IntPoint pt2, bool SlopesEqual(const IntPoint& pt1, const IntPoint& pt2,
const IntPoint pt3, const IntPoint pt4, bool UseFullInt64Range) const IntPoint& pt3, const IntPoint& pt4, bool UseFullInt64Range)
{ {
#ifndef use_int32 #ifndef use_int32
if (UseFullInt64Range) if (UseFullInt64Range)
@ -581,7 +583,7 @@ inline bool IsHorizontal(TEdge &e)
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
inline double GetDx(const IntPoint pt1, const IntPoint pt2) inline double GetDx(const IntPoint& pt1, const IntPoint& pt2)
{ {
return (pt1.Y == pt2.Y) ? return (pt1.Y == pt2.Y) ?
HORIZONTAL : (double)(pt2.X - pt1.X) / (pt2.Y - pt1.Y); HORIZONTAL : (double)(pt2.X - pt1.X) / (pt2.Y - pt1.Y);
@ -718,7 +720,10 @@ void DisposeOutPts(OutPt*& pp)
inline void InitEdge(TEdge* e, TEdge* eNext, TEdge* ePrev, const IntPoint& Pt) inline void InitEdge(TEdge* e, TEdge* eNext, TEdge* ePrev, const IntPoint& Pt)
{ {
// Dx is explicitly being set due to memset not being portable for floating-point values
std::memset(e, 0, sizeof(TEdge)); std::memset(e, 0, sizeof(TEdge));
e->Dx = 0.0;
e->Next = eNext; e->Next = eNext;
e->Prev = ePrev; e->Prev = ePrev;
e->Curr = Pt; e->Curr = Pt;
@ -857,8 +862,8 @@ OutPt* GetBottomPt(OutPt *pp)
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
bool Pt2IsBetweenPt1AndPt3(const IntPoint pt1, bool Pt2IsBetweenPt1AndPt3(const IntPoint& pt1,
const IntPoint pt2, const IntPoint pt3) const IntPoint& pt2, const IntPoint& pt3)
{ {
if ((pt1 == pt3) || (pt1 == pt2) || (pt3 == pt2)) if ((pt1 == pt3) || (pt1 == pt2) || (pt3 == pt2))
return false; return false;
@ -880,10 +885,13 @@ bool HorzSegmentsOverlap(cInt seg1a, cInt seg1b, cInt seg2a, cInt seg2b)
// ClipperBase class methods ... // ClipperBase class methods ...
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
ClipperBase::ClipperBase() //constructor ClipperBase::ClipperBase() :
m_ActiveEdges(nullptr)
{ {
m_CurrentLM = m_MinimaList.begin(); //begin() == end() here m_CurrentLM = m_MinimaList.begin(); //begin() == end() here
m_UseFullRange = false; m_UseFullRange = false;
m_PreserveCollinear = false;
m_HasOpenPaths = false;
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
@ -928,7 +936,6 @@ TEdge* FindNextLocMin(TEdge* E)
TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward) TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward)
{ {
TEdge *Result = E; TEdge *Result = E;
TEdge *Horz = 0;
if (E->OutIdx == Skip) if (E->OutIdx == Skip)
{ {
@ -1000,7 +1007,7 @@ TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward)
//nb: at the top of a bound, horizontals are added to the bound //nb: at the top of a bound, horizontals are added to the bound
//only when the preceding edge attaches to the horizontal's left vertex //only when the preceding edge attaches to the horizontal's left vertex
//unless a Skip edge is encountered when that becomes the top divide //unless a Skip edge is encountered when that becomes the top divide
Horz = Result; TEdge *Horz = Result;
while (IsHorizontal(*Horz->Prev)) Horz = Horz->Prev; while (IsHorizontal(*Horz->Prev)) Horz = Horz->Prev;
if (Horz->Prev->Top.X > Result->Next->Top.X) Result = Horz->Prev; if (Horz->Prev->Top.X > Result->Next->Top.X) Result = Horz->Prev;
} }
@ -1020,7 +1027,7 @@ TEdge* ClipperBase::ProcessBound(TEdge* E, bool NextIsForward)
Result = Result->Prev; Result = Result->Prev;
if (IsHorizontal(*Result) && Result->Prev->OutIdx != Skip) if (IsHorizontal(*Result) && Result->Prev->OutIdx != Skip)
{ {
Horz = Result; TEdge *Horz = Result;
while (IsHorizontal(*Horz->Next)) Horz = Horz->Next; while (IsHorizontal(*Horz->Next)) Horz = Horz->Next;
if (Horz->Next->Top.X == Result->Prev->Top.X || if (Horz->Next->Top.X == Result->Prev->Top.X ||
Horz->Next->Top.X > Result->Prev->Top.X) Result = Horz->Next; Horz->Next->Top.X > Result->Prev->Top.X) Result = Horz->Next;
@ -1473,6 +1480,11 @@ bool ClipperBase::LocalMinimaPending()
Clipper::Clipper(int initOptions) : ClipperBase() //constructor Clipper::Clipper(int initOptions) : ClipperBase() //constructor
{ {
m_ClipType = ClipType::Intersection;
m_SortedEdges = 0;
m_ClipFillType = PolyFillType::EvenOdd;
m_SubjFillType = PolyFillType::EvenOdd;
m_UsingPolyTree = false;
m_ExecuteLocked = false; m_ExecuteLocked = false;
m_UseFullRange = false; m_UseFullRange = false;
m_ReverseOutput = ((initOptions & static_cast<int>(InitOptions::ReverseSolution)) != 0); m_ReverseOutput = ((initOptions & static_cast<int>(InitOptions::ReverseSolution)) != 0);
@ -1939,7 +1951,7 @@ void Clipper::CopyAELToSEL()
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
void Clipper::AddJoin(OutPt *op1, OutPt *op2, const IntPoint OffPt) void Clipper::AddJoin(OutPt *op1, OutPt *op2, const IntPoint& OffPt)
{ {
Join* j = new Join; Join* j = new Join;
j->OutPt1 = op1; j->OutPt1 = op1;
@ -1965,7 +1977,7 @@ void Clipper::ClearGhostJoins()
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
void Clipper::AddGhostJoin(OutPt *op, const IntPoint OffPt) void Clipper::AddGhostJoin(OutPt *op, const IntPoint& OffPt)
{ {
Join* j = new Join; Join* j = new Join;
j->OutPt1 = op; j->OutPt1 = op;
@ -2655,14 +2667,14 @@ void Clipper::ProcessHorizontal(TEdge *horzEdge)
if (dir == Direction::LeftToRight) if (dir == Direction::LeftToRight)
{ {
maxIt = m_Maxima.begin(); maxIt = m_Maxima.begin();
while (maxIt != m_Maxima.end() && *maxIt <= horzEdge->Bot.X) maxIt++; while (maxIt != m_Maxima.end() && *maxIt <= horzEdge->Bot.X) ++maxIt;
if (maxIt != m_Maxima.end() && *maxIt >= eLastHorz->Top.X) if (maxIt != m_Maxima.end() && *maxIt >= eLastHorz->Top.X)
maxIt = m_Maxima.end(); maxIt = m_Maxima.end();
} }
else else
{ {
maxRit = m_Maxima.rbegin(); maxRit = m_Maxima.rbegin();
while (maxRit != m_Maxima.rend() && *maxRit > horzEdge->Bot.X) maxRit++; while (maxRit != m_Maxima.rend() && *maxRit > horzEdge->Bot.X) ++maxRit;
if (maxRit != m_Maxima.rend() && *maxRit <= eLastHorz->Top.X) if (maxRit != m_Maxima.rend() && *maxRit <= eLastHorz->Top.X)
maxRit = m_Maxima.rend(); maxRit = m_Maxima.rend();
} }
@ -2689,7 +2701,7 @@ void Clipper::ProcessHorizontal(TEdge *horzEdge)
{ {
if (horzEdge->OutIdx >= 0 && !IsOpen) if (horzEdge->OutIdx >= 0 && !IsOpen)
AddOutPt(horzEdge, IntPoint(*maxIt, horzEdge->Bot.Y)); AddOutPt(horzEdge, IntPoint(*maxIt, horzEdge->Bot.Y));
maxIt++; ++maxIt;
} }
} }
else else
@ -2698,7 +2710,7 @@ void Clipper::ProcessHorizontal(TEdge *horzEdge)
{ {
if (horzEdge->OutIdx >= 0 && !IsOpen) if (horzEdge->OutIdx >= 0 && !IsOpen)
AddOutPt(horzEdge, IntPoint(*maxRit, horzEdge->Bot.Y)); AddOutPt(horzEdge, IntPoint(*maxRit, horzEdge->Bot.Y));
maxRit++; ++maxRit;
} }
} }
}; };
@ -2980,7 +2992,7 @@ void Clipper::DoMaxima(TEdge *e)
} }
else if( e->OutIdx >= 0 && eMaxPair->OutIdx >= 0 ) else if( e->OutIdx >= 0 && eMaxPair->OutIdx >= 0 )
{ {
if (e->OutIdx >= 0) AddLocalMaxPoly(e, eMaxPair, e->Top); AddLocalMaxPoly(e, eMaxPair, e->Top);
DeleteFromAEL(e); DeleteFromAEL(e);
DeleteFromAEL(eMaxPair); DeleteFromAEL(eMaxPair);
} }
@ -3199,19 +3211,26 @@ int PointCount(OutPt *Pts)
void Clipper::BuildResult(Paths &polys) void Clipper::BuildResult(Paths &polys)
{ {
polys.reserve(m_PolyOuts.size()); polys.reserve(m_PolyOuts.size());
for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i) for (PolyOutList::size_type i = 0; i < m_PolyOuts.size(); ++i)
{ {
if (!m_PolyOuts[i]->Pts) continue; if (!m_PolyOuts[i]->Pts)
Path pg; continue;
OutPt* p = m_PolyOuts[i]->Pts->Prev; OutPt* p = m_PolyOuts[i]->Pts->Prev;
int cnt = PointCount(p); int cnt = PointCount(p);
if (cnt < 2) continue; if (cnt < 2)
continue;
Path pg;
pg.reserve(cnt); pg.reserve(cnt);
for (int i = 0; i < cnt; ++i) for (int j = 0; j < cnt; ++j)
{ {
pg.push_back(p->Pt); pg.push_back(p->Pt);
p = p->Prev; p = p->Prev;
} }
polys.push_back(pg); polys.push_back(pg);
} }
} }
@ -3369,7 +3388,7 @@ OutPt* DupOutPt(OutPt* outPt, bool InsertAfter)
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
bool JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b, bool JoinHorz(OutPt* op1, OutPt* op1b, OutPt* op2, OutPt* op2b,
const IntPoint Pt, bool DiscardLeft) const IntPoint& Pt, bool DiscardLeft)
{ {
Direction Dir1 = (op1->Pt.X > op1b->Pt.X ? Direction::RightToLeft : Direction::LeftToRight); Direction Dir1 = (op1->Pt.X > op1b->Pt.X ? Direction::RightToLeft : Direction::LeftToRight);
Direction Dir2 = (op2->Pt.X > op2b->Pt.X ? Direction::RightToLeft : Direction::LeftToRight); Direction Dir2 = (op2->Pt.X > op2b->Pt.X ? Direction::RightToLeft : Direction::LeftToRight);
@ -3788,6 +3807,8 @@ ClipperOffset::ClipperOffset(double miterLimit, double arcTolerance)
this->MiterLimit = miterLimit; this->MiterLimit = miterLimit;
this->ArcTolerance = arcTolerance; this->ArcTolerance = arcTolerance;
m_lowest.X = -1; m_lowest.X = -1;
m_delta = m_sinA = m_sin = m_cos = 0.0;
m_miterLim = m_StepsPerRad = 0.0;
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
@ -4199,13 +4220,13 @@ void ClipperOffset::DoRound(int j, int k)
m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y); m_normals[k].X * m_normals[j].X + m_normals[k].Y * m_normals[j].Y);
int steps = std::max((int)Round(m_StepsPerRad * std::fabs(a)), 1); int steps = std::max((int)Round(m_StepsPerRad * std::fabs(a)), 1);
double X = m_normals[k].X, Y = m_normals[k].Y, X2; double X = m_normals[k].X, Y = m_normals[k].Y;
for (int i = 0; i < steps; ++i) for (int i = 0; i < steps; ++i)
{ {
m_destPoly.push_back(IntPoint( m_destPoly.push_back(IntPoint(
Round(m_srcPoly[j].X + X * m_delta), Round(m_srcPoly[j].X + X * m_delta),
Round(m_srcPoly[j].Y + Y * m_delta))); Round(m_srcPoly[j].Y + Y * m_delta)));
X2 = X; double X2 = X;
X = X * m_cos - m_sin * Y; X = X * m_cos - m_sin * Y;
Y = X2 * m_sin + Y * m_cos; Y = X2 * m_sin + Y * m_cos;
} }
@ -4520,7 +4541,7 @@ void MinkowskiSum(const Path& pattern, const Path& path, Paths& solution, bool p
} }
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
void TranslatePath(const Path& input, Path& output, const IntPoint delta) void TranslatePath(const Path& input, Path& output, const IntPoint& delta)
{ {
//precondition: input != output //precondition: input != output
output.resize(input.size()); output.resize(input.size());

View file

@ -118,7 +118,7 @@ struct DoublePoint
double X; double X;
double Y; double Y;
DoublePoint(double x = 0, double y = 0) : X(x), Y(y) {} DoublePoint(double x = 0, double y = 0) : X(x), Y(y) {}
DoublePoint(IntPoint ip) : X((double)ip.X), Y((double)ip.Y) {} explicit DoublePoint(const IntPoint& ip) : X(ip.X), Y(ip.Y) {}
}; };
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
@ -263,7 +263,7 @@ protected:
class Clipper : public virtual ClipperBase class Clipper : public virtual ClipperBase
{ {
public: public:
Clipper(int initOptions = 0); explicit Clipper(int initOptions = 0);
bool Execute(ClipType clipType, bool Execute(ClipType clipType,
Paths &solution, Paths &solution,
PolyFillType fillType = PolyFillType::EvenOdd); PolyFillType fillType = PolyFillType::EvenOdd);
@ -341,10 +341,10 @@ private:
bool IsHole(TEdge *e); bool IsHole(TEdge *e);
bool FindOwnerFromSplitRecs(OutRec &outRec, OutRec *&currOrfl); bool FindOwnerFromSplitRecs(OutRec &outRec, OutRec *&currOrfl);
void FixHoleLinkage(OutRec &outrec); void FixHoleLinkage(OutRec &outrec);
void AddJoin(OutPt *op1, OutPt *op2, const IntPoint offPt); void AddJoin(OutPt *op1, OutPt *op2, const IntPoint& offPt);
void ClearJoins(); void ClearJoins();
void ClearGhostJoins(); void ClearGhostJoins();
void AddGhostJoin(OutPt *op, const IntPoint offPt); void AddGhostJoin(OutPt *op, const IntPoint& offPt);
bool JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2); bool JoinPoints(Join *j, OutRec* outRec1, OutRec* outRec2);
void JoinCommonEdges(); void JoinCommonEdges();
void DoSimplePolygons(); void DoSimplePolygons();
@ -391,7 +391,7 @@ private:
class clipperException : public std::exception class clipperException : public std::exception
{ {
public: public:
clipperException(const char* description): m_descr(description) {} explicit clipperException(const char* description): m_descr(description) {}
virtual ~clipperException() throw() {} virtual ~clipperException() throw() {}
virtual const char* what() const throw() {return m_descr.c_str();} virtual const char* what() const throw() {return m_descr.c_str();}
private: private:

View file

@ -56,7 +56,7 @@ tgPolygon tgAccumulator::Diff( const tgContour& subject )
max_hits = num_hits-1; max_hits = num_hits-1;
FILE* fp = fopen( "./accumulator_fail.log", "a" ); FILE* fp = fopen( "./accumulator_fail.log", "a" );
fprintf( fp, "%s : reduce from %d to %d\n", debugstr.c_str(), num_hits, max_hits ); fprintf( fp, "%s : reduce from %u to %u\n", debugstr.c_str(), num_hits, max_hits );
fclose(fp); fclose(fp);
} else { } else {
result = tgPolygon::FromClipper( clipper_result ); result = tgPolygon::FromClipper( clipper_result );
@ -119,7 +119,7 @@ tgPolygon tgAccumulator::Diff( const tgPolygon& subject )
max_hits = num_hits-1; max_hits = num_hits-1;
FILE* fp = fopen( "./accumulator_fail.log", "a" ); FILE* fp = fopen( "./accumulator_fail.log", "a" );
fprintf( fp, "%s : reduce from %d to %d\n", debugstr.c_str(), num_hits, max_hits ); fprintf( fp, "%s : reduce from %u to %u\n", debugstr.c_str(), num_hits, max_hits );
fclose(fp); fclose(fp);
} else { } else {
result = tgPolygon::FromClipper( clipper_result ); result = tgPolygon::FromClipper( clipper_result );
@ -173,14 +173,14 @@ void tgAccumulator::Add( const tgPolygon& subject )
void tgAccumulator::ToShapefiles( const std::string& path, const std::string& layer_prefix, bool individual ) void tgAccumulator::ToShapefiles( const std::string& path, const std::string& layer_prefix, bool individual )
{ {
char shapefile[32];
char layer[32];
if ( accum.size() ) { if ( accum.size() ) {
if ( individual ) { if ( individual ) {
for (unsigned int i=0; i < accum.size(); i++) { for (unsigned int i=0; i < accum.size(); i++) {
sprintf( layer, "%s_%d", layer_prefix.c_str(), i ); char layer[32];
sprintf( shapefile, "accum_%d", i ); sprintf( layer, "%s_%u", layer_prefix.c_str(), i );
char shapefile[32];
sprintf( shapefile, "accum_%u", i );
tgShapefile::FromClipper( accum[i], path, layer, std::string(shapefile) ); tgShapefile::FromClipper( accum[i], path, layer, std::string(shapefile) );
} }
} else { } else {
@ -204,13 +204,13 @@ void tgAccumulator::ToShapefiles( const std::string& path, const std::string& la
void tgAccumulator::ToClipperfiles( const std::string& path, const std::string& layer_prefix, bool individual ) void tgAccumulator::ToClipperfiles( const std::string& path, const std::string& layer_prefix, bool individual )
{ {
std::ofstream file; std::ofstream file;
char filename[256];
if ( accum.size() ) { if ( accum.size() ) {
if ( individual ) { if ( individual ) {
char filename[256];
for (unsigned int i=0; i < accum.size(); i++) { for (unsigned int i=0; i < accum.size(); i++) {
sprintf( filename, "%s/%s_%d", path.c_str(), layer_prefix.c_str(), i ); sprintf( filename, "%s/%s_%u", path.c_str(), layer_prefix.c_str(), i );
file.open (filename); file.open (filename);
file << accum[i]; file << accum[i];
file.close(); file.close();
@ -225,6 +225,7 @@ void tgAccumulator::ToClipperfiles( const std::string& path, const std::string&
} }
if ( c.Execute( ClipperLib::ClipType::Union, clipper_result, ClipperLib::PolyFillType::NonZero, ClipperLib::PolyFillType::NonZero) ) { if ( c.Execute( ClipperLib::ClipType::Union, clipper_result, ClipperLib::PolyFillType::NonZero, ClipperLib::PolyFillType::NonZero) ) {
char filename[256];
sprintf( filename, "%s/%s", path.c_str(), layer_prefix.c_str() ); sprintf( filename, "%s/%s", path.c_str(), layer_prefix.c_str() );
file.open (filename); file.open (filename);

View file

@ -8,7 +8,7 @@
class tgAccumulator class tgAccumulator
{ {
public: public:
tgAccumulator( const std::string& d ) : debugstr(d) {} explicit tgAccumulator( const std::string& d ) : debugstr(d) {}
tgPolygon Diff( const tgContour& subject ); tgPolygon Diff( const tgContour& subject );
tgPolygon Diff( const tgPolygon& subject ); tgPolygon Diff( const tgPolygon& subject );

View file

@ -141,40 +141,43 @@ void tgChopper::Add( const tgPolygon& subject, const std::string& type )
} }
} }
long int tgChopper::GenerateIndex( std::string path ) uint32_t tgChopper::GenerateIndex(const std::string& path)
{ {
std::string index_file = path + "/chop.idx"; std::string index_file = path + "/chop.idx";
long int index = 0; uint32_t index = 0;
//Open or create the named mutex //Open or create the named mutex
boost::interprocess::named_mutex mutex(boost::interprocess::open_or_create, "tgChopper_index2"); boost::interprocess::named_mutex mutex(boost::interprocess::open_or_create, "tgChopper_index2");
{ {
boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(mutex); boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(mutex);
/* first try to read the file */ // first, read the current index
FILE *fp = fopen( index_file.c_str(), "r+" ); FILE* fp = fopen(index_file.c_str(), "rb");
if ( fp == NULL ) { if (fp != NULL) {
/* doesn't exist - create it */ if (fread((void*)&index, sizeof(uint32_t), 1, fp) != 1) {
fp = fopen( index_file.c_str(), "w" );
if ( fp == NULL ) {
SG_LOG(SG_GENERAL, SG_ALERT, "Error cannot open Index file " << index_file << " for writing");
boost::interprocess::named_mutex::remove("tgChopper_index2");
exit( 0 );
}
} else {
if ( fread( (void*)&index, sizeof(long int), 1, fp ) != 1 )
{
SG_LOG(SG_GENERAL, SG_ALERT, "Error reading Index file " << index_file << " abort"); SG_LOG(SG_GENERAL, SG_ALERT, "Error reading Index file " << index_file << " abort");
fclose(fp);
boost::interprocess::named_mutex::remove("tgChopper_index2"); boost::interprocess::named_mutex::remove("tgChopper_index2");
exit(0); exit(0);
} }
fclose(fp);
} }
index++; // overwrite the existing file - or create if it doesn't already exist
fp = fopen(index_file.c_str(), "wb");
if (fp == NULL) {
SG_LOG(SG_GENERAL, SG_ALERT, "Error cannot open Index file " << index_file << " for writing");
rewind( fp ); boost::interprocess::named_mutex::remove("tgChopper_index2");
fwrite( (void*)&index, sizeof(long int), 1, fp ); exit(0);
fclose( fp ); }
++index;
fwrite((void*)&index, sizeof(uint32_t), 1, fp);
fclose(fp);
} }
boost::interprocess::named_mutex::remove("tgChopper_index2"); boost::interprocess::named_mutex::remove("tgChopper_index2");
@ -182,53 +185,51 @@ long int tgChopper::GenerateIndex( std::string path )
return index; return index;
} }
void tgChopper::Save( bool DebugShapefiles ) void tgChopper::Save(bool DebugShapefiles)
{ {
// traverse the bucket list // traverse the bucket list
bucket_polys_map_interator it; bucket_polys_map_interator it;
char tile_name[16]; char tile_name[16];
char poly_ext[16];
char layer[32]; char layer[32];
char ds_name[64]; char ds_name[64];
for (it=bp_map.begin(); it != bp_map.end(); it++) { for (it = bp_map.begin(); it != bp_map.end(); ++it) {
SGBucket b( (*it).first ); SGBucket b((*it).first);
tgpolygon_list const& polys = (*it).second; tgpolygon_list const& polys = (*it).second;
sprintf(ds_name, "./bucket_%s", b.gen_index_str().c_str() ); sprintf(ds_name, "./bucket_%s", b.gen_index_str().c_str());
std::string path = root_path + "/" + b.gen_base_path(); std::string path = root_path + "/" + b.gen_base_path();
sprintf( tile_name, "%ld", b.gen_index() ); sprintf(tile_name, "%ld", b.gen_index());
std::string polyfile = path + "/" + tile_name; std::string polyfile = path + "/" + tile_name;
SGPath sgp( polyfile ); SGPath sgp(polyfile);
sgp.create_dir( 0755 ); sgp.create_dir(0755);
long int poly_index = GenerateIndex( path ); uint32_t poly_index = GenerateIndex(path);
char poly_ext[32];
sprintf( poly_ext, "%ld", poly_index ); sprintf(poly_ext, "%u%.25s", poly_index, extra_extension.c_str());
polyfile = polyfile + "." + poly_ext + "." + extra_extension; polyfile = polyfile + "." + poly_ext;
gzFile fp; gzFile fp;
if ( (fp = gzopen( polyfile.c_str(), "wb9" )) == NULL ) { if ((fp = gzopen(polyfile.c_str(), "wb9")) == NULL) {
SG_LOG( SG_GENERAL, SG_INFO, "ERROR: opening " << polyfile.c_str() << " for writing!" ); SG_LOG(SG_GENERAL, SG_INFO, "ERROR: opening " << polyfile.c_str() << " for writing!");
return; return;
} }
/* Write polys to the file */ /* Write polys to the file */
sgWriteUInt( fp, polys.size() ); sgWriteUInt(fp, polys.size());
for ( unsigned int i=0; i<polys.size(); i++ ) { for (unsigned int i = 0; i < polys.size(); i++) {
polys[i].SaveToGzFile( fp ); polys[i].SaveToGzFile(fp);
if ( DebugShapefiles ) if (DebugShapefiles) {
{ sprintf(layer, "poly_%s-%u", b.gen_index_str().c_str(), i);
sprintf(layer, "poly_%s-%d", b.gen_index_str().c_str(), i ); tgShapefile::FromPolygon(polys[i], ds_name, layer, "poly");
tgShapefile::FromPolygon( polys[i], ds_name, layer, "poly" );
} }
} }
gzclose( fp ); gzclose(fp);
} }
} }

View file

@ -9,9 +9,10 @@ typedef bucket_polys_map::iterator bucket_polys_map_interator;
class tgChopper class tgChopper
{ {
public: public:
tgChopper( const std::string& path ) { explicit tgChopper( const std::string& path ) :
root_path = path; root_path(path),
extra_extension = ""; extra_extension("")
{
} }
void Add( const tgPolygon& poly, const std::string& type ); void Add( const tgPolygon& poly, const std::string& type );
@ -21,7 +22,7 @@ public:
} }
private: private:
long int GenerateIndex( std::string path ); uint32_t GenerateIndex( const std::string& path );
void ClipRow( const tgPolygon& subject, const double& center_lat, const std::string& type ); void ClipRow( const tgPolygon& subject, const double& center_lat, const std::string& type );
tgPolygon Clip( const tgPolygon& subject, const std::string& type, SGBucket& b ); tgPolygon Clip( const tgPolygon& subject, const std::string& type, SGBucket& b );
void Chop( const tgPolygon& subject, const std::string& type ); void Chop( const tgPolygon& subject, const std::string& type );

View file

@ -25,8 +25,8 @@ tgContour tgContour::Snap( const tgContour& subject, double snap )
double tgContour::GetMinimumAngle( void ) const double tgContour::GetMinimumAngle( void ) const
{ {
unsigned int p1_index, p2_index, p3_index; unsigned int p1_index, p3_index;
double angle, min_angle = 2.0 * SGD_PI; double min_angle = 2.0 * SGD_PI;
unsigned int size = node_list.size(); unsigned int size = node_list.size();
SG_LOG(SG_GENERAL, SG_DEBUG, " tgContour::GetMinimumAngle() : contour size is " << size ); SG_LOG(SG_GENERAL, SG_DEBUG, " tgContour::GetMinimumAngle() : contour size is " << size );
@ -38,7 +38,7 @@ double tgContour::GetMinimumAngle( void ) const
p1_index = i - 1; p1_index = i - 1;
} }
p2_index = i; unsigned p2_index = i;
if ( i == size - 1 ) { if ( i == size - 1 ) {
p3_index = 0; p3_index = 0;
@ -46,7 +46,7 @@ double tgContour::GetMinimumAngle( void ) const
p3_index = i + 1; p3_index = i + 1;
} }
angle = SGGeod_CalculateTheta( node_list[p1_index], node_list[p2_index], node_list[p3_index] ); double angle = SGGeod_CalculateTheta( node_list[p1_index], node_list[p2_index], node_list[p3_index] );
if ( angle < min_angle ) { if ( angle < min_angle ) {
min_angle = angle; min_angle = angle;
} }
@ -58,16 +58,14 @@ double tgContour::GetMinimumAngle( void ) const
double tgContour::GetArea( void ) const double tgContour::GetArea( void ) const
{ {
double area = 0.0; double area = 0.0;
SGVec2d a, b;
unsigned int i, j;
if ( node_list.size() ) { if ( node_list.size() ) {
j = node_list.size() - 1; unsigned j = node_list.size() - 1;
for (i=0; i<node_list.size(); i++) { for (unsigned i = 0; i < node_list.size(); ++i) {
a = SGGeod_ToSGVec2d( node_list[i] ); SGVec2d a = SGGeod_ToSGVec2d( node_list[i] );
b = SGGeod_ToSGVec2d( node_list[j] ); SGVec2d b = SGGeod_ToSGVec2d( node_list[j] );
area += (b.x() + a.x()) * (b.y() - a.y()); area += (b.x() + a.x()) * (b.y() - a.y());
j=i; j = i;
} }
} }
@ -111,8 +109,7 @@ bool tgContour::AreSameSide( const SGGeod& firstpt, const SGGeod& secondpt) cons
//Now cycle over all nodes and count how many times we intersect //Now cycle over all nodes and count how many times we intersect
int intersect_ct = 0; int intersect_ct = 0;
if (node_list.size()) { if (node_list.size()) {
int j = node_list.size() - 1; for (int i = 0; i < static_cast<int>(node_list.size()) - 1; ++i) {
for (int i=0;i<node_list.size()-1;i++) {
double nx1 = node_list[i].getLatitudeDeg(); double nx1 = node_list[i].getLatitudeDeg();
double ny1 = node_list[i].getLongitudeDeg(); double ny1 = node_list[i].getLongitudeDeg();
double nx2 = node_list[i+1].getLatitudeDeg(); double nx2 = node_list[i+1].getLatitudeDeg();
@ -140,20 +137,18 @@ bool tgContour::AreSameSide( const SGGeod& firstpt, const SGGeod& secondpt) cons
double tgContour::MinDist(const SGGeod& probe) const { double tgContour::MinDist(const SGGeod& probe) const {
SGVec3d probexyz; SGVec3d probexyz;
SGGeodesy::SGGeodToCart( probe,probexyz ); SGGeodesy::SGGeodToCart( probe, probexyz );
double mindist = 100000.0; double mindist = 100000.0;
double dist;
if ( node_list.size() ) { if ( node_list.size() ) {
int j = node_list.size() - 1; int j = node_list.size() - 1;
for (int i=0;i<j;i++) { for (int i = 0; i < j; ++i) {
SGVec3d start,end; SGVec3d start,end;
SGGeodesy::SGGeodToCart( node_list[i],start ); SGGeodesy::SGGeodToCart( node_list[i],start );
SGGeodesy::SGGeodToCart( node_list[i+1],end ); SGGeodesy::SGGeodToCart( node_list[i+1],end );
SGLineSegment<double> piece = SGLineSegment<double>(start,end); SGLineSegment<double> piece = SGLineSegment<double>(start,end);
dist = distSqr( piece,probexyz ); double dist = distSqr( piece,probexyz );
if (dist < mindist) mindist = dist; if (dist < mindist) mindist = dist;
} }
} }
@ -634,7 +629,6 @@ static bool FindIntermediateNode( const SGGeod& start, const SGGeod& end,
double bbEpsilon, double errEpsilon ) double bbEpsilon, double errEpsilon )
{ {
bool found_node = false; bool found_node = false;
double m, m1, b, b1, y_err, x_err, y_err_min, x_err_min;
SGGeod p0 = start; SGGeod p0 = start;
SGGeod p1 = end; SGGeod p1 = end;
@ -642,8 +636,8 @@ static bool FindIntermediateNode( const SGGeod& start, const SGGeod& end,
double xdist = fabs(p0.getLongitudeDeg() - p1.getLongitudeDeg()); double xdist = fabs(p0.getLongitudeDeg() - p1.getLongitudeDeg());
double ydist = fabs(p0.getLatitudeDeg() - p1.getLatitudeDeg()); double ydist = fabs(p0.getLatitudeDeg() - p1.getLatitudeDeg());
x_err_min = xdist + 1.0; double x_err_min = xdist + 1.0;
y_err_min = ydist + 1.0; double y_err_min = ydist + 1.0;
if ( xdist > ydist ) { if ( xdist > ydist ) {
// sort these in a sensible order // sort these in a sensible order
@ -656,15 +650,15 @@ static bool FindIntermediateNode( const SGGeod& start, const SGGeod& end,
p_max = p0; p_max = p0;
} }
m = (p_min.getLatitudeDeg() - p_max.getLatitudeDeg()) / (p_min.getLongitudeDeg() - p_max.getLongitudeDeg()); double m = (p_min.getLatitudeDeg() - p_max.getLatitudeDeg()) / (p_min.getLongitudeDeg() - p_max.getLongitudeDeg());
b = p_max.getLatitudeDeg() - m * p_max.getLongitudeDeg(); double b = p_max.getLatitudeDeg() - m * p_max.getLongitudeDeg();
for ( int i = 0; i < (int)nodes.size(); ++i ) { for ( int i = 0; i < (int)nodes.size(); ++i ) {
// cout << i << endl; // cout << i << endl;
SGGeod current = nodes[i]; SGGeod current = nodes[i];
if ( (current.getLongitudeDeg() > (p_min.getLongitudeDeg() + (bbEpsilon))) && (current.getLongitudeDeg() < (p_max.getLongitudeDeg() - (bbEpsilon))) ) { if ( (current.getLongitudeDeg() > (p_min.getLongitudeDeg() + (bbEpsilon))) && (current.getLongitudeDeg() < (p_max.getLongitudeDeg() - (bbEpsilon))) ) {
y_err = fabs(current.getLatitudeDeg() - (m * current.getLongitudeDeg() + b)); double y_err = fabs(current.getLatitudeDeg() - (m * current.getLongitudeDeg() + b));
if ( y_err < errEpsilon ) { if ( y_err < errEpsilon ) {
found_node = true; found_node = true;
@ -686,15 +680,15 @@ static bool FindIntermediateNode( const SGGeod& start, const SGGeod& end,
p_max = p0; p_max = p0;
} }
m1 = (p_min.getLongitudeDeg() - p_max.getLongitudeDeg()) / (p_min.getLatitudeDeg() - p_max.getLatitudeDeg()); double m1 = (p_min.getLongitudeDeg() - p_max.getLongitudeDeg()) / (p_min.getLatitudeDeg() - p_max.getLatitudeDeg());
b1 = p_max.getLongitudeDeg() - m1 * p_max.getLatitudeDeg(); double b1 = p_max.getLongitudeDeg() - m1 * p_max.getLatitudeDeg();
for ( int i = 0; i < (int)nodes.size(); ++i ) { for ( int i = 0; i < (int)nodes.size(); ++i ) {
SGGeod current = nodes[i]; SGGeod current = nodes[i];
if ( (current.getLatitudeDeg() > (p_min.getLatitudeDeg() + (bbEpsilon))) && (current.getLatitudeDeg() < (p_max.getLatitudeDeg() - (bbEpsilon))) ) { if ( (current.getLatitudeDeg() > (p_min.getLatitudeDeg() + (bbEpsilon))) && (current.getLatitudeDeg() < (p_max.getLatitudeDeg() - (bbEpsilon))) ) {
x_err = fabs(current.getLongitudeDeg() - (m1 * current.getLatitudeDeg() + b1)); double x_err = fabs(current.getLongitudeDeg() - (m1 * current.getLatitudeDeg() + b1));
if ( x_err < errEpsilon ) { if ( x_err < errEpsilon ) {
found_node = true; found_node = true;
@ -715,7 +709,6 @@ static bool FindIntermediateNode( const SGGeod& start, const SGGeod& end,
double bbEpsilon, double errEpsilon ) double bbEpsilon, double errEpsilon )
{ {
bool found_node = false; bool found_node = false;
double m, m1, b, b1, y_err, x_err, y_err_min, x_err_min;
SGGeod p0 = start; SGGeod p0 = start;
SGGeod p1 = end; SGGeod p1 = end;
@ -723,8 +716,8 @@ static bool FindIntermediateNode( const SGGeod& start, const SGGeod& end,
double xdist = fabs(p0.getLongitudeDeg() - p1.getLongitudeDeg()); double xdist = fabs(p0.getLongitudeDeg() - p1.getLongitudeDeg());
double ydist = fabs(p0.getLatitudeDeg() - p1.getLatitudeDeg()); double ydist = fabs(p0.getLatitudeDeg() - p1.getLatitudeDeg());
x_err_min = xdist + 1.0; double x_err_min = xdist + 1.0;
y_err_min = ydist + 1.0; double y_err_min = ydist + 1.0;
if ( xdist > ydist ) { if ( xdist > ydist ) {
// sort these in a sensible order // sort these in a sensible order
@ -737,15 +730,15 @@ static bool FindIntermediateNode( const SGGeod& start, const SGGeod& end,
p_max = p0; p_max = p0;
} }
m = (p_min.getLatitudeDeg() - p_max.getLatitudeDeg()) / (p_min.getLongitudeDeg() - p_max.getLongitudeDeg()); double m = (p_min.getLatitudeDeg() - p_max.getLatitudeDeg()) / (p_min.getLongitudeDeg() - p_max.getLongitudeDeg());
b = p_max.getLatitudeDeg() - m * p_max.getLongitudeDeg(); double b = p_max.getLatitudeDeg() - m * p_max.getLongitudeDeg();
for ( int i = 0; i < (int)nodes.size(); ++i ) { for ( int i = 0; i < (int)nodes.size(); ++i ) {
// cout << i << endl; // cout << i << endl;
SGGeod current = nodes[i]->GetPosition(); SGGeod current = nodes[i]->GetPosition();
if ( (current.getLongitudeDeg() > (p_min.getLongitudeDeg() + (bbEpsilon))) && (current.getLongitudeDeg() < (p_max.getLongitudeDeg() - (bbEpsilon))) ) { if ( (current.getLongitudeDeg() > (p_min.getLongitudeDeg() + (bbEpsilon))) && (current.getLongitudeDeg() < (p_max.getLongitudeDeg() - (bbEpsilon))) ) {
y_err = fabs(current.getLatitudeDeg() - (m * current.getLongitudeDeg() + b)); double y_err = fabs(current.getLatitudeDeg() - (m * current.getLongitudeDeg() + b));
if ( y_err < errEpsilon ) { if ( y_err < errEpsilon ) {
found_node = true; found_node = true;
@ -767,15 +760,15 @@ static bool FindIntermediateNode( const SGGeod& start, const SGGeod& end,
p_max = p0; p_max = p0;
} }
m1 = (p_min.getLongitudeDeg() - p_max.getLongitudeDeg()) / (p_min.getLatitudeDeg() - p_max.getLatitudeDeg()); double m1 = (p_min.getLongitudeDeg() - p_max.getLongitudeDeg()) / (p_min.getLatitudeDeg() - p_max.getLatitudeDeg());
b1 = p_max.getLongitudeDeg() - m1 * p_max.getLatitudeDeg(); double b1 = p_max.getLongitudeDeg() - m1 * p_max.getLatitudeDeg();
for ( int i = 0; i < (int)nodes.size(); ++i ) { for ( int i = 0; i < (int)nodes.size(); ++i ) {
SGGeod current = nodes[i]->GetPosition(); SGGeod current = nodes[i]->GetPosition();
if ( (current.getLatitudeDeg() > (p_min.getLatitudeDeg() + (bbEpsilon))) && (current.getLatitudeDeg() < (p_max.getLatitudeDeg() - (bbEpsilon))) ) { if ( (current.getLatitudeDeg() > (p_min.getLatitudeDeg() + (bbEpsilon))) && (current.getLatitudeDeg() < (p_max.getLatitudeDeg() - (bbEpsilon))) ) {
x_err = fabs(current.getLongitudeDeg() - (m1 * current.getLatitudeDeg() + b1)); double x_err = fabs(current.getLongitudeDeg() - (m1 * current.getLatitudeDeg() + b1));
if ( x_err < errEpsilon ) { if ( x_err < errEpsilon ) {
found_node = true; found_node = true;
@ -813,7 +806,7 @@ extern SGGeod InterpolateElevation( const SGGeod& dst_node, const SGGeod& start,
static void AddIntermediateNodes( const SGGeod& p0, const SGGeod& p1, bool preserve3d, std::vector<TGNode*>& nodes, tgContour& result, double bbEpsilon, double errEpsilon ) static void AddIntermediateNodes( const SGGeod& p0, const SGGeod& p1, bool preserve3d, std::vector<TGNode*>& nodes, tgContour& result, double bbEpsilon, double errEpsilon )
{ {
TGNode* new_pt; TGNode* new_pt = nullptr;
SGGeod new_geode; SGGeod new_geode;
SG_LOG(SG_GENERAL, SG_BULK, " " << p0 << " <==> " << p1 ); SG_LOG(SG_GENERAL, SG_BULK, " " << p0 << " <==> " << p1 );
@ -1003,8 +996,6 @@ tgContour tgContour::Expand( const tgContour& subject, double offset )
tgpolygon_list tgContour::ExpandToPolygons( const tgContour& subject, double width ) tgpolygon_list tgContour::ExpandToPolygons( const tgContour& subject, double width )
{ {
int turn_dir;
SGGeod cur_inner; SGGeod cur_inner;
SGGeod cur_outer; SGGeod cur_outer;
SGGeod prev_inner; SGGeod prev_inner;
@ -1012,8 +1003,6 @@ tgpolygon_list tgContour::ExpandToPolygons( const tgContour& subject, double wid
SGGeod calc_inner; SGGeod calc_inner;
SGGeod calc_outer; SGGeod calc_outer;
double last_end_v = 0.0f;
tgContour expanded; tgContour expanded;
tgPolygon segment; tgPolygon segment;
tgAccumulator accum("ExpandToPolygons"); tgAccumulator accum("ExpandToPolygons");
@ -1022,8 +1011,7 @@ tgpolygon_list tgContour::ExpandToPolygons( const tgContour& subject, double wid
// generate poly and texparam lists for each line segment // generate poly and texparam lists for each line segment
for (unsigned int i = 0; i < subject.GetSize(); i++) for (unsigned int i = 0; i < subject.GetSize(); i++)
{ {
last_end_v = 0.0f; int turn_dir = 0;
turn_dir = 0;
sglog().setLogLevels( SG_ALL, SG_INFO ); sglog().setLogLevels( SG_ALL, SG_INFO );
@ -1034,8 +1022,8 @@ tgpolygon_list tgContour::ExpandToPolygons( const tgContour& subject, double wid
if (i == 0) if (i == 0)
{ {
// first point on the list - offset heading is 90deg // first point on the list - offset heading is 90deg
cur_outer = OffsetPointFirst( subject.GetNode(i), subject.GetNode(i+1), -width/2.0f ); cur_outer = OffsetPointFirst( subject.GetNode(i), subject.GetNode(1), -width/2.0f );
cur_inner = OffsetPointFirst( subject.GetNode(i), subject.GetNode(i+1), width/2.0f ); cur_inner = OffsetPointFirst( subject.GetNode(i), subject.GetNode(1), width/2.0f );
} }
else if (i == subject.GetSize()-1) else if (i == subject.GetSize()-1)
{ {
@ -1099,6 +1087,8 @@ tgpolygon_list tgContour::ExpandToPolygons( const tgContour& subject, double wid
} }
} }
double last_end_v = 0.0;
expanded.SetHole(false); expanded.SetHole(false);
segment.AddContour(expanded); segment.AddContour(expanded);
segment.SetTexParams( prev_inner, width, 20.0f, heading ); segment.SetTexParams( prev_inner, width, 20.0f, heading );
@ -1106,6 +1096,7 @@ tgpolygon_list tgContour::ExpandToPolygons( const tgContour& subject, double wid
segment.SetTexMethod( TG_TEX_BY_TPS_CLIPU, -1.0, 0.0, 1.0, 0.0 ); segment.SetTexMethod( TG_TEX_BY_TPS_CLIPU, -1.0, 0.0, 1.0, 0.0 );
result.push_back( segment ); result.push_back( segment );
// BUG??: value will never be utilized
last_end_v = 1.0f - (fmod( (double)(dist - last_end_v), (double)1.0f )); last_end_v = 1.0f - (fmod( (double)(dist - last_end_v), (double)1.0f ));
} }

View file

@ -148,7 +148,7 @@ bool TGNodes::get_geod_inside( const SGGeod& min, const SGGeod& max, std::vector
tg_kd_tree.search(std::back_inserter( result ), exact_bb); tg_kd_tree.search(std::back_inserter( result ), exact_bb);
// and convert the tuples back into SGGeod // and convert the tuples back into SGGeod
for ( it = result.begin(); it != result.end(); it++ ) { for ( it = result.begin(); it != result.end(); ++it ) {
points.push_back( SGGeod::fromDegM( boost::get<0>(*it).x(), boost::get<0>(*it).y(), boost::get<1>(*it) ) ); points.push_back( SGGeod::fromDegM( boost::get<0>(*it).x(), boost::get<0>(*it).y(), boost::get<1>(*it) ) );
} }
@ -178,7 +178,7 @@ bool TGNodes::get_nodes_inside( const SGGeod& min, const SGGeod& max, std::vecto
tg_kd_tree.search(std::back_inserter( result ), exact_bb); tg_kd_tree.search(std::back_inserter( result ), exact_bb);
// and convert the tuples back into SGGeod // and convert the tuples back into SGGeod
for ( it = result.begin(); it != result.end(); it++ ) { for ( it = result.begin(); it != result.end(); ++it ) {
points.push_back( boost::get<2>(*it) ); points.push_back( boost::get<2>(*it) );
} }
@ -217,7 +217,7 @@ bool TGNodes::get_geod_edge( const SGBucket& b, std::vector<SGGeod>& north, std:
exact_bb = Fuzzy_bb(ll, ur); exact_bb = Fuzzy_bb(ll, ur);
result.clear(); result.clear();
tg_kd_tree.search(std::back_inserter( result ), exact_bb); tg_kd_tree.search(std::back_inserter( result ), exact_bb);
for ( it = result.begin(); it != result.end(); it++ ) { for ( it = result.begin(); it != result.end(); ++it ) {
north.push_back( SGGeod::fromDegM( boost::get<0>(*it).x(), boost::get<0>(*it).y(), boost::get<1>(*it) ) ); north.push_back( SGGeod::fromDegM( boost::get<0>(*it).x(), boost::get<0>(*it).y(), boost::get<1>(*it) ) );
} }
@ -228,7 +228,7 @@ bool TGNodes::get_geod_edge( const SGBucket& b, std::vector<SGGeod>& north, std:
result.clear(); result.clear();
tg_kd_tree.search(std::back_inserter( result ), exact_bb); tg_kd_tree.search(std::back_inserter( result ), exact_bb);
for ( it = result.begin(); it != result.end(); it++ ) { for ( it = result.begin(); it != result.end(); ++it ) {
south.push_back( SGGeod::fromDegM( boost::get<0>(*it).x(), boost::get<0>(*it).y(), boost::get<1>(*it) ) ); south.push_back( SGGeod::fromDegM( boost::get<0>(*it).x(), boost::get<0>(*it).y(), boost::get<1>(*it) ) );
} }
@ -239,7 +239,7 @@ bool TGNodes::get_geod_edge( const SGBucket& b, std::vector<SGGeod>& north, std:
result.clear(); result.clear();
tg_kd_tree.search(std::back_inserter( result ), exact_bb); tg_kd_tree.search(std::back_inserter( result ), exact_bb);
for ( it = result.begin(); it != result.end(); it++ ) { for ( it = result.begin(); it != result.end(); ++it ) {
east.push_back( SGGeod::fromDegM( boost::get<0>(*it).x(), boost::get<0>(*it).y(), boost::get<1>(*it) ) ); east.push_back( SGGeod::fromDegM( boost::get<0>(*it).x(), boost::get<0>(*it).y(), boost::get<1>(*it) ) );
} }
@ -250,7 +250,7 @@ bool TGNodes::get_geod_edge( const SGBucket& b, std::vector<SGGeod>& north, std:
result.clear(); result.clear();
tg_kd_tree.search(std::back_inserter( result ), exact_bb); tg_kd_tree.search(std::back_inserter( result ), exact_bb);
for ( it = result.begin(); it != result.end(); it++ ) { for ( it = result.begin(); it != result.end(); ++it ) {
west.push_back( SGGeod::fromDegM( boost::get<0>(*it).x(), boost::get<0>(*it).y(), boost::get<1>(*it) ) ); west.push_back( SGGeod::fromDegM( boost::get<0>(*it).x(), boost::get<0>(*it).y(), boost::get<1>(*it) ) );
} }

View file

@ -211,8 +211,6 @@ void tgPolygon::Texture( void )
{ {
SGGeod p; SGGeod p;
SGVec2f t; SGVec2f t;
double x, y;
float tx, ty;
SG_LOG(SG_GENERAL, SG_DEBUG, "Texture Poly with material " << material << " method " << tp.method << " tpref " << tp.ref << " heading " << tp.heading ); SG_LOG(SG_GENERAL, SG_DEBUG, "Texture Poly with material " << material << " method " << tp.method << " tpref " << tp.ref << " heading " << tp.heading );
@ -272,8 +270,8 @@ void tgPolygon::Texture( void )
// 3. Convert from polar to cartesian coordinates // 3. Convert from polar to cartesian coordinates
// //
x = sin( course * SGD_DEGREES_TO_RADIANS ) * dist; double x = sin( course * SGD_DEGREES_TO_RADIANS ) * dist;
y = cos( course * SGD_DEGREES_TO_RADIANS ) * dist; double y = cos( course * SGD_DEGREES_TO_RADIANS ) * dist;
SG_LOG(SG_GENERAL, SG_DEBUG, " x = " << x << " y = " << y); SG_LOG(SG_GENERAL, SG_DEBUG, " x = " << x << " y = " << y);
// //
@ -282,7 +280,7 @@ void tgPolygon::Texture( void )
float tmp; float tmp;
tmp = (float)x / (float)tp.width; tmp = (float)x / (float)tp.width;
tx = tmp * (float)(tp.maxu - tp.minu) + (float)tp.minu; float tx = tmp * (float)(tp.maxu - tp.minu) + (float)tp.minu;
SG_LOG(SG_GENERAL, SG_DEBUG, " (" << tx << ")"); SG_LOG(SG_GENERAL, SG_DEBUG, " (" << tx << ")");
// clip u? // clip u?
@ -292,7 +290,7 @@ void tgPolygon::Texture( void )
} }
tmp = (float)y / (float)tp.length; tmp = (float)y / (float)tp.length;
ty = tmp * (float)(tp.maxv - tp.minv) + (float)tp.minv; float ty = tmp * (float)(tp.maxv - tp.minv) + (float)tp.minv;
SG_LOG(SG_GENERAL, SG_DEBUG, " (" << ty << ")"); SG_LOG(SG_GENERAL, SG_DEBUG, " (" << ty << ")");
// clip v? // clip v?

View file

@ -244,7 +244,9 @@ public:
tgPolygon() { tgPolygon() {
preserve3d = false; preserve3d = false;
closed = true; closed = true;
id = 0;
} }
~tgPolygon() { ~tgPolygon() {
contours.clear(); contours.clear();
triangles.clear(); triangles.clear();

View file

@ -213,21 +213,19 @@ void tgPolygon::RemoveSlivers( tgPolygon& subject, tgcontour_list& slivers )
double angle_cutoff = 10.0 * SGD_DEGREES_TO_RADIANS; double angle_cutoff = 10.0 * SGD_DEGREES_TO_RADIANS;
double area_cutoff = 0.000000001; double area_cutoff = 0.000000001;
double min_angle;
double area;
// process contours in reverse order so deleting a contour doesn't // process contours in reverse order so deleting a contour doesn't
// foul up our sequence // foul up our sequence
for ( i = subject.Contours() - 1; i >= 0; --i ) { for ( i = subject.Contours() - 1; i >= 0; --i ) {
SG_LOG(SG_GENERAL, SG_DEBUG, "contour " << i ); SG_LOG(SG_GENERAL, SG_DEBUG, "contour " << i );
contour = subject.GetContour(i); contour = subject.GetContour(i);
SG_LOG(SG_GENERAL, SG_DEBUG, " calc min angle for contour " << i); SG_LOG(SG_GENERAL, SG_DEBUG, " calc min angle for contour " << i);
min_angle = contour.GetMinimumAngle(); double min_angle = contour.GetMinimumAngle();
SG_LOG(SG_GENERAL, SG_DEBUG, " min_angle (rad) = " << min_angle ); SG_LOG(SG_GENERAL, SG_DEBUG, " min_angle (rad) = " << min_angle );
area = contour.GetArea(); double area = contour.GetArea();
SG_LOG(SG_GENERAL, SG_DEBUG, " area = " << area ); SG_LOG(SG_GENERAL, SG_DEBUG, " area = " << area );
if ( ((min_angle < angle_cutoff) && (area < area_cutoff)) || if ( ((min_angle < angle_cutoff) && (area < area_cutoff)) ||
@ -262,7 +260,6 @@ tgcontour_list tgPolygon::MergeSlivers( tgpolygon_list& polys, tgcontour_list& s
tgContour contour; tgContour contour;
tgcontour_list unmerged; tgcontour_list unmerged;
unsigned int original_contours, result_contours; unsigned int original_contours, result_contours;
bool done;
for ( unsigned int i = 0; i < sliver_list.size(); i++ ) { for ( unsigned int i = 0; i < sliver_list.size(); i++ ) {
sliver = sliver_list[i]; sliver = sliver_list[i];
@ -270,7 +267,7 @@ tgcontour_list tgPolygon::MergeSlivers( tgpolygon_list& polys, tgcontour_list& s
sliver.SetHole( false ); sliver.SetHole( false );
done = false; bool done = false;
// try to merge the slivers with the list of clipped polys // try to merge the slivers with the list of clipped polys
for ( unsigned int j = 0; j < polys.size() && !done; j++ ) { for ( unsigned int j = 0; j < polys.size() && !done; j++ ) {

View file

@ -13,15 +13,18 @@
#include "tg_polygon.hxx" #include "tg_polygon.hxx"
#include "tg_misc.hxx" #include "tg_misc.hxx"
/* determining if a face is within the reulting poly */ /* determining if a face is within the resulting poly */
struct FaceInfo2 struct FaceInfo2
{ {
FaceInfo2() {} FaceInfo2() {
int nesting_level; nesting_level = 0;
}
bool in_domain(){ int nesting_level;
return nesting_level%2 == 1;
} bool in_domain() {
return nesting_level % 2 == 1;
}
}; };
typedef CGAL::Exact_predicates_exact_constructions_kernel K; typedef CGAL::Exact_predicates_exact_constructions_kernel K;

View file

@ -98,6 +98,10 @@ void* tgShapefile::CloseDatasource( void* ds_id )
{ {
GDALDataset* datasource = ( GDALDataset * )ds_id; GDALDataset* datasource = ( GDALDataset * )ds_id;
GDALClose((GDALDatasetH) datasource ); GDALClose((GDALDatasetH) datasource );
GDALDestroyDriverManager();
tgShapefile::initialized = false;
return (void *)-1; return (void *)-1;
} }
@ -112,7 +116,7 @@ void tgShapefile::FromClipper( const ClipperLib::Paths& subject, const std::stri
OGRPolygon* polygon = new OGRPolygon(); OGRPolygon* polygon = new OGRPolygon();
SG_LOG(SG_GENERAL, SG_DEBUG, "subject has " << subject.size() << " contours "); SG_LOG(SG_GENERAL, SG_DEBUG, "subject has " << subject.size() << " contours ");
for ( unsigned int i = 0; i < subject.size(); i++ ) { for ( unsigned int i = 0; i < subject.size(); ++i ) {
ClipperLib::Path const& contour = subject[i]; ClipperLib::Path const& contour = subject[i];
if (contour.size() < 3) { if (contour.size() < 3) {
@ -142,7 +146,8 @@ void tgShapefile::FromClipper( const ClipperLib::Paths& subject, const std::stri
feature->SetField("ID", description.c_str()); feature->SetField("ID", description.c_str());
feature->SetGeometry(polygon); feature->SetGeometry(polygon);
if( l_id->CreateFeature( feature ) != OGRERR_NONE )
if ( l_id->CreateFeature( feature ) != OGRERR_NONE )
{ {
SG_LOG(SG_GENERAL, SG_ALERT, "Failed to create feature in shapefile"); SG_LOG(SG_GENERAL, SG_ALERT, "Failed to create feature in shapefile");
} }
@ -151,9 +156,7 @@ void tgShapefile::FromClipper( const ClipperLib::Paths& subject, const std::stri
} }
// close after each write // close after each write
if ( ds_id >= 0 ) { tgShapefile::CloseDatasource( ds_id );
ds_id = tgShapefile::CloseDatasource( ds_id );
}
} }
void tgShapefile::FromContour( const tgContour& subject, const std::string& datasource, const std::string& layer, const std::string& description ) void tgShapefile::FromContour( const tgContour& subject, const std::string& datasource, const std::string& layer, const std::string& description )
@ -197,7 +200,7 @@ void tgShapefile::FromContour( const tgContour& subject, const std::string& data
} }
// close after each write // close after each write
ds_id = tgShapefile::CloseDatasource( ds_id ); tgShapefile::CloseDatasource( ds_id );
} }
void tgShapefile::FromTriangles( const tgPolygon& subject, const std::string& datasource, const std::string& layer, const std::string& description ) void tgShapefile::FromTriangles( const tgPolygon& subject, const std::string& datasource, const std::string& layer, const std::string& description )
@ -237,7 +240,7 @@ void tgShapefile::FromTriangles( const tgPolygon& subject, const std::string& da
} }
// close after each write // close after each write
ds_id = tgShapefile::CloseDatasource( ds_id ); tgShapefile::CloseDatasource( ds_id );
} }
void tgShapefile::FromPolygon( const tgPolygon& subject, const std::string& datasource, const std::string& layer, const std::string& description ) void tgShapefile::FromPolygon( const tgPolygon& subject, const std::string& datasource, const std::string& layer, const std::string& description )
@ -291,7 +294,7 @@ void tgShapefile::FromPolygon( const tgPolygon& subject, const std::string& data
} }
// close after each write // close after each write
ds_id = tgShapefile::CloseDatasource( ds_id ); tgShapefile::CloseDatasource( ds_id );
} }
tgPolygon tgShapefile::ToPolygon( const void* subject ) tgPolygon tgShapefile::ToPolygon( const void* subject )

View file

@ -168,7 +168,7 @@ static void tgCalcElevations( const std::string &root, const string_list elev_sr
} }
} }
array.close(); array.unload();
} else { } else {
done = true; done = true;
@ -226,10 +226,10 @@ tgSurface::tgSurface( const std::string& path,
double average_elev_m, double average_elev_m,
double slope_max, double slope_max,
double slope_eps double slope_eps
) ) :
_aptBounds(aptBounds)
{ {
// Calculate desired size of grid // Calculate desired size of grid
_aptBounds = aptBounds;
_min_deg = _aptBounds.getMin(); _min_deg = _aptBounds.getMin();
_max_deg = _aptBounds.getMax(); _max_deg = _aptBounds.getMax();
_average_elev_m = average_elev_m; _average_elev_m = average_elev_m;

View file

@ -53,10 +53,11 @@ public:
//int index = ( row * _cols ) + col; //int index = ( row * _cols ) + col;
if ( col < 0 || col >= _cols ) { if ( col < 0 || col >= _cols ) {
SG_LOG(SG_GENERAL, SG_WARN, "column out of bounds on read (" << col << " >= " << _cols << ")"); SG_LOG(SG_GENERAL, SG_WARN, "column out of bounds on read (" << col << " >= " << _cols << ")");
int *p = 0; *p = 1; // force crash col = col < 0 ? 0 : _cols - 1;
} else if ( row < 0 || row >= _rows ) { }
else if ( row < 0 || row >= _rows ) {
SG_LOG(SG_GENERAL, SG_WARN, "row out of bounds on read (" << row << " >= " << _rows << ")"); SG_LOG(SG_GENERAL, SG_WARN, "row out of bounds on read (" << row << " >= " << _rows << ")");
int *p = 0; *p = 1; // force crash row = row < 0 ? 0 : _rows - 1;
} }
return m[row][col]; return m[row][col];
@ -66,10 +67,11 @@ public:
//int index = ( row * _cols ) + col; //int index = ( row * _cols ) + col;
if ( col < 0 || col >= _cols ) { if ( col < 0 || col >= _cols ) {
SG_LOG(SG_GENERAL, SG_WARN,"column out of bounds on set (" << col << " >= " << _cols << ")"); SG_LOG(SG_GENERAL, SG_WARN,"column out of bounds on set (" << col << " >= " << _cols << ")");
int *p = 0; *p = 1; // force crash col = col < 0 ? 0 : _cols - 1;
} else if ( row < 0 || row >= _rows ) { }
else if ( row < 0 || row >= _rows ) {
SG_LOG(SG_GENERAL, SG_WARN,"row out of bounds on set (" << row << " >= " << _rows << ")"); SG_LOG(SG_GENERAL, SG_WARN,"row out of bounds on set (" << row << " >= " << _rows << ")");
int *p = 0; *p = 1; // force crash row = row < 0 ? 0 : _rows - 1;
} }
m[row][col] = p; m[row][col] = p;
} }

View file

@ -27,9 +27,9 @@
class SGGeodIndex { class SGGeodIndex {
public: public:
SGGeodIndex( SGGeod g ) { explicit SGGeodIndex( SGGeod g ) :
geod = g; geod(g)
{
std::size_t FNV_prime; std::size_t FNV_prime;
std::size_t offset_basis; std::size_t offset_basis;

View file

@ -39,8 +39,9 @@ public:
// constructor for serialization only // constructor for serialization only
} }
TGNode( SGGeod p ) { explicit TGNode( SGGeod p ) :
position = p; position(p)
{
CalcWgs84(); CalcWgs84();
fixed_position = false; // no matter what - don't move x, y, or z (likely a hole around an airport generated ny genapts) fixed_position = false; // no matter what - don't move x, y, or z (likely a hole around an airport generated ny genapts)
@ -131,9 +132,9 @@ private:
class TGNodeIndex { class TGNodeIndex {
public: public:
TGNodeIndex( SGGeod g ) { explicit TGNodeIndex( SGGeod g ) :
geod = g; geod(g)
{
std::size_t FNV_prime; std::size_t FNV_prime;
std::size_t offset_basis; std::size_t offset_basis;

View file

@ -80,9 +80,7 @@ void Decoder::processLineString(OGRLineString* poGeometry)
tgContour line; tgContour line;
SGGeod p0, p1; SGGeod p0, p1;
double heading, dist, az2; int i, numPoints;
int i, j, numPoints, numSegs;
double max_dist;
numPoints = poGeometry->getNumPoints(); numPoints = poGeometry->getNumPoints();
if (numPoints < 2) { if (numPoints < 2) {
@ -90,7 +88,7 @@ void Decoder::processLineString(OGRLineString* poGeometry)
return; return;
} }
heading = SGGeodesy::courseDeg( p1, p0 ); SGGeodesy::courseDeg( p1, p0 );
// now add the middle points : if they are too far apart, add intermediate nodes // now add the middle points : if they are too far apart, add intermediate nodes
for ( i=0;i<numPoints;i++) { for ( i=0;i<numPoints;i++) {
@ -187,7 +185,7 @@ void processLayer(OGRLayer* poLayer, tgChopper& results )
char* srsWkt; char* srsWkt;
oSourceSRS->exportToWkt(&srsWkt); oSourceSRS->exportToWkt(&srsWkt);
SG_LOG( SG_GENERAL, SG_DEBUG, "Source spatial reference system: " << srsWkt ); SG_LOG( SG_GENERAL, SG_DEBUG, "Source spatial reference system: " << srsWkt );
OGRFree(srsWkt); CPLFree(srsWkt);
oTargetSRS.SetWellKnownGeogCS( "WGS84" ); oTargetSRS.SetWellKnownGeogCS( "WGS84" );
@ -419,9 +417,10 @@ int main( int argc, char **argv ) {
} }
GDALClose(poDS); GDALClose(poDS);
GDALDestroyDriverManager();
SG_LOG(SG_GENERAL, SG_ALERT, "Saving to buckets"); SG_LOG(SG_GENERAL, SG_ALERT, "Saving to buckets");
results.Add_Extension("cliffs"); results.Add_Extension(".cliffs");
results.Save( save_shapefiles ); results.Save( save_shapefiles );
auto finish_time = std::chrono::high_resolution_clock::now(); auto finish_time = std::chrono::high_resolution_clock::now();

View file

@ -1,15 +1,5 @@
include_directories(${PROJECT_SOURCE_DIR}/src/Lib/terragear) include_directories(${PROJECT_SOURCE_DIR}/src/Lib/terragear)
add_executable(demchop demchop.cxx)
target_link_libraries(demchop
DEM
${ZLIB_LIBRARY}
${SIMGEAR_CORE_LIBRARIES}
${SIMGEAR_CORE_LIBRARY_DEPENDENCIES})
install(TARGETS demchop RUNTIME DESTINATION bin)
add_executable(hgtchop hgtchop.cxx) add_executable(hgtchop hgtchop.cxx)
target_link_libraries(hgtchop target_link_libraries(hgtchop

View file

@ -1,104 +0,0 @@
// demchop.cxx -- chop up a dem file into it's corresponding pieces and stuff
// them into the workspace directory
//
// Written by Curtis Olson, started March 1999.
//
// Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
//
// $Id: demchop.cxx,v 1.13 2004-11-19 22:25:51 curt Exp $
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <simgear/compiler.h>
#include <chrono>
#include <iostream>
#include <string>
#include <stdlib.h>
#include <simgear/bucket/newbucket.hxx>
#include <simgear/debug/logstream.hxx>
#include <simgear/misc/sg_path.hxx>
#include <DEM/dem.hxx>
using std::endl;
using std::cout;
using std::string;
int main(int argc, char **argv) {
sglog().setLogLevels( SG_ALL, SG_WARN );
if ( argc != 3 ) {
SG_LOG( SG_GENERAL, SG_ALERT, "Usage " << argv[0] << " <dem_file> <work_dir>" );
return EXIT_FAILURE;
}
auto start_time = std::chrono::high_resolution_clock::now();
string dem_name = argv[1];
string work_dir = argv[2];
SGPath sgp( work_dir );
sgp.append( "dummy" );
sgp.create_dir( 0755 );
TGDem dem(dem_name);
dem.parse();
dem.close();
SGGeod min = SGGeod::fromDeg(dem.get_originx() / 3600.0 + SG_HALF_BUCKET_SPAN,
dem.get_originy() / 3600.0 + SG_HALF_BUCKET_SPAN);
SGGeod max = SGGeod::fromDeg( (dem.get_originx() + dem.get_cols() * dem.get_col_step()) / 3600.0 - SG_HALF_BUCKET_SPAN,
(dem.get_originy() + dem.get_rows() * dem.get_row_step()) / 3600.0 - SG_HALF_BUCKET_SPAN );
SGBucket b_min( min );
SGBucket b_max( max );
if ( b_min == b_max ) {
dem.write_area( work_dir, b_min );
} else {
SGBucket b_cur;
int dx, dy, i, j;
sgBucketDiff(b_min, b_max, &dx, &dy);
cout << "DEM file spans tile boundaries" << endl;
cout << " dx = " << dx << " dy = " << dy << endl;
if ( (dx > 20) || (dy > 20) ) {
cout << "somethings really wrong!!!!" << endl;
return EXIT_FAILURE;
}
for ( j = 0; j <= dy; j++ ) {
for ( i = 0; i <= dx; i++ ) {
b_cur = b_min.sibling(i, j);
dem.write_area( work_dir, b_cur );
}
}
}
auto finish_time = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish_time - start_time;
std::cout << std::endl << "Elapsed time: " << elapsed.count() << " seconds" << std::endl << std::endl;
return EXIT_SUCCESS;
}

View file

@ -1,7 +0,0 @@
#! /bin/bash
WORKDIR=$HOME/workdirs/world_scenery
for f in $WORKDIR/SRTM-30-ASCII/*/*.dem; do
demchop $f $WORKDIR/SRTM-30
done

View file

@ -59,7 +59,7 @@ using std::ios;
#define MAX_HGT_SIZE 6001 #define MAX_HGT_SIZE 6001
class TGSrtmTiff : public TGSrtmBase { class TGSrtmTiff : public TGSrtmBase {
public: public:
TGSrtmTiff( const SGPath &file ); explicit TGSrtmTiff( const SGPath &file );
~TGSrtmTiff(); ~TGSrtmTiff();
bool open( const SGPath &f ); bool open( const SGPath &f );
bool close(); bool close();
@ -181,8 +181,7 @@ bool TGSrtmTiff::open( const SGPath &f ) {
} }
bool TGSrtmTiff::load() { bool TGSrtmTiff::load() {
int size; cols = rows = 6000;
cols = rows = size = 6000;
col_step = row_step = 3; col_step = row_step = 3;
uint32 w, h, d; uint32 w, h, d;

View file

@ -76,7 +76,7 @@ int SimpleRasterTransformer(void *pTransformerArg,
int bDstToSrc, int nPointCount, int bDstToSrc, int nPointCount,
double *x, double *y, double *z, int *panSuccess ) double *x, double *y, double *z, int *panSuccess )
{ {
SimpleRasterTransformerInfo* info = (SimpleRasterTransformerInfo*)pTransformerArg; SimpleRasterTransformerInfo* info = static_cast<SimpleRasterTransformerInfo*>(pTransformerArg);
int success; int success;
if (bDstToSrc) { if (bDstToSrc) {
@ -105,7 +105,7 @@ int SimpleRasterTransformer(void *pTransformerArg,
class ImageInfo { class ImageInfo {
public: public:
ImageInfo(GDALDataset *dataset); explicit ImageInfo(GDALDataset *dataset);
void GetBounds(double &n, double &s, double &e, double &w) const { void GetBounds(double &n, double &s, double &e, double &w) const {
n = north; n = north;
@ -532,6 +532,8 @@ int main(int argc, const char **argv)
} }
} }
GDALDestroyDriverManager();
auto finish_time = std::chrono::high_resolution_clock::now(); auto finish_time = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = finish_time - start_time; std::chrono::duration<double> elapsed = finish_time - start_time;
std::cout << std::endl << "Elapsed time: " << elapsed.count() << " seconds" << std::endl << std::endl; std::cout << std::endl << "Elapsed time: " << elapsed.count() << " seconds" << std::endl << std::endl;

View file

@ -135,7 +135,7 @@ void Decoder::processLineString(OGRLineString* poGeometry, const string& area_ty
SGGeod p0, p1; SGGeod p0, p1;
double heading, dist, az2; double heading, dist, az2;
int i, j, numPoints, numSegs; int j, numPoints, numSegs;
double max_dist; double max_dist;
numPoints = poGeometry->getNumPoints(); numPoints = poGeometry->getNumPoints();
@ -154,7 +154,7 @@ void Decoder::processLineString(OGRLineString* poGeometry, const string& area_ty
line.AddNode( SGGeodesy::direct( p0, heading, EP_STRETCH ) ); line.AddNode( SGGeodesy::direct( p0, heading, EP_STRETCH ) );
// now add the middle points : if they are too far apart, add intermediate nodes // now add the middle points : if they are too far apart, add intermediate nodes
for ( i=1;i<numPoints-1;i++) { for ( int i = 1; i < numPoints - 1; ++i) {
p0 = SGGeod::fromDeg( poGeometry->getX(i-1), poGeometry->getY(i-1) ); p0 = SGGeod::fromDeg( poGeometry->getX(i-1), poGeometry->getY(i-1) );
p1 = SGGeod::fromDeg( poGeometry->getX(i ), poGeometry->getY(i ) ); p1 = SGGeod::fromDeg( poGeometry->getX(i ), poGeometry->getY(i ) );
SGGeodesy::inverse( p0, p1, heading, az2, dist ); SGGeodesy::inverse( p0, p1, heading, az2, dist );
@ -185,7 +185,7 @@ void Decoder::processLineString(OGRLineString* poGeometry, const string& area_ty
// make a plygons from the line segments // make a plygons from the line segments
segments = tgContour::ExpandToPolygons( line, width ); segments = tgContour::ExpandToPolygons( line, width );
for ( unsigned int i=0; i<segments.size(); i++ ) { for ( unsigned int i = 0; i < segments.size(); ++i ) {
segments[i].SetPreserve3D( false ); segments[i].SetPreserve3D( false );
if (with_texture) { if (with_texture) {
segments[i].SetTexMethod( TG_TEX_BY_TPS_CLIPU ); segments[i].SetTexMethod( TG_TEX_BY_TPS_CLIPU );
@ -296,7 +296,7 @@ void Decoder::run()
} }
} }
OGRMultiPoint* multipt=(OGRMultiPoint*)poGeometry; OGRMultiPoint* multipt=(OGRMultiPoint*)poGeometry;
for (int i=0;i<multipt->getNumGeometries();i++) { for (int i = 0; i < multipt->getNumGeometries(); ++i) {
processPoint((OGRPoint*)(multipt->getGeometryRef(i)), area_type_name, width); processPoint((OGRPoint*)(multipt->getGeometryRef(i)), area_type_name, width);
} }
break; break;
@ -325,7 +325,7 @@ void Decoder::run()
} }
OGRMultiLineString* multilines=(OGRMultiLineString*)poGeometry; OGRMultiLineString* multilines=(OGRMultiLineString*)poGeometry;
for (int i=0;i<multilines->getNumGeometries();i++) { for (int i = 0; i < multilines->getNumGeometries(); ++i) {
processLineString((OGRLineString*)(multilines->getGeometryRef(i)), area_type_name, width, texture_lines); processLineString((OGRLineString*)(multilines->getGeometryRef(i)), area_type_name, width, texture_lines);
} }
break; break;
@ -338,7 +338,7 @@ void Decoder::run()
case wkbMultiPolygon: { case wkbMultiPolygon: {
SG_LOG( SG_GENERAL, SG_DEBUG, "MultiPolygon feature" ); SG_LOG( SG_GENERAL, SG_DEBUG, "MultiPolygon feature" );
OGRMultiPolygon* multipoly=(OGRMultiPolygon*)poGeometry; OGRMultiPolygon* multipoly=(OGRMultiPolygon*)poGeometry;
for (int i=0;i<multipoly->getNumGeometries();i++) { for (int i = 0; i < multipoly->getNumGeometries(); ++i) {
processPolygon((OGRPolygon*)(multipoly->getGeometryRef(i)), area_type_name); processPolygon((OGRPolygon*)(multipoly->getGeometryRef(i)), area_type_name);
} }
break; break;
@ -356,11 +356,16 @@ void Decoder::run()
// Main Thread // Main Thread
void processLayer(OGRLayer* poLayer, tgChopper& results ) void processLayer(OGRLayer* poLayer, tgChopper& results )
{ {
int feature_count=poLayer->GetFeatureCount(); int feature_count = poLayer->GetFeatureCount();
if (feature_count!=-1 && start_record>0 && start_record>=feature_count) { if (feature_count != -1 && start_record > 0 && start_record >= feature_count) {
SG_LOG( SG_GENERAL, SG_ALERT, "Layer has only " << feature_count << " records, but start record is set to " << start_record ); SG_LOG( SG_GENERAL, SG_ALERT, "Layer has only " << feature_count << " records, but start record is set to " << start_record );
exit( 1 ); if (!continue_on_errors) {
SG_LOG( SG_GENERAL, SG_ALERT, "Aborting!" );
exit( 1 );
}
else
return;
} }
/* determine the indices of the required columns */ /* determine the indices of the required columns */
@ -372,8 +377,12 @@ void processLayer(OGRLayer* poLayer, tgChopper& results )
point_width_field=poFDefn->GetFieldIndex(point_width_col.c_str()); point_width_field=poFDefn->GetFieldIndex(point_width_col.c_str());
if (point_width_field==-1) { if (point_width_field==-1) {
SG_LOG( SG_GENERAL, SG_ALERT, "Field " << point_width_col << " for point-width not found in layer" ); SG_LOG( SG_GENERAL, SG_ALERT, "Field " << point_width_col << " for point-width not found in layer" );
if (!continue_on_errors) if (!continue_on_errors) {
exit( 1 ); SG_LOG( SG_GENERAL, SG_ALERT, "Aborting!" );
exit( 1 );
}
else
return;
} }
} }
@ -381,8 +390,12 @@ void processLayer(OGRLayer* poLayer, tgChopper& results )
line_width_field=poFDefn->GetFieldIndex(line_width_col.c_str()); line_width_field=poFDefn->GetFieldIndex(line_width_col.c_str());
if (line_width_field==-1) { if (line_width_field==-1) {
SG_LOG( SG_GENERAL, SG_ALERT, "Field " << line_width_col << " for line-width not found in layer" ); SG_LOG( SG_GENERAL, SG_ALERT, "Field " << line_width_col << " for line-width not found in layer" );
if (!continue_on_errors) if (!continue_on_errors) {
exit( 1 ); SG_LOG( SG_GENERAL, SG_ALERT, "Aborting!" );
exit( 1 );
}
else
return;
} }
} }
@ -390,8 +403,12 @@ void processLayer(OGRLayer* poLayer, tgChopper& results )
area_type_field=poFDefn->GetFieldIndex(area_type_col.c_str()); area_type_field=poFDefn->GetFieldIndex(area_type_col.c_str());
if (area_type_field==-1) { if (area_type_field==-1) {
SG_LOG( SG_GENERAL, SG_ALERT, "Field " << area_type_col << " for area type not found in layer" ); SG_LOG( SG_GENERAL, SG_ALERT, "Field " << area_type_col << " for area type not found in layer" );
if (!continue_on_errors) if (!continue_on_errors) {
exit( 1 ); SG_LOG( SG_GENERAL, SG_ALERT, "Aborting!" );
exit( 1 );
}
else
return;
} }
} }
@ -400,42 +417,53 @@ void processLayer(OGRLayer* poLayer, tgChopper& results )
oSourceSRS=poLayer->GetSpatialRef(); oSourceSRS=poLayer->GetSpatialRef();
if (oSourceSRS == NULL) { if (oSourceSRS == NULL) {
SG_LOG( SG_GENERAL, SG_ALERT, "Layer " << layername << " has no defined spatial reference system" ); SG_LOG( SG_GENERAL, SG_ALERT, "Layer " << layername << " has no defined spatial reference system" );
exit( 1 ); if (!continue_on_errors) {
SG_LOG( SG_GENERAL, SG_ALERT, "Aborting!" );
exit( 1 );
}
else
return;
} }
char* srsWkt; char* srsWkt;
oSourceSRS->exportToWkt(&srsWkt); oSourceSRS->exportToWkt(&srsWkt);
SG_LOG( SG_GENERAL, SG_DEBUG, "Source spatial reference system: " << srsWkt ); SG_LOG( SG_GENERAL, SG_DEBUG, "Source spatial reference system: " << srsWkt );
OGRFree(srsWkt); CPLFree(srsWkt);
oTargetSRS.SetWellKnownGeogCS( "WGS84" ); oTargetSRS.SetWellKnownGeogCS( "WGS84" );
OGRCoordinateTransformation *poCT = OGRCreateCoordinateTransformation(oSourceSRS, &oTargetSRS); auto poCT = OGRCreateCoordinateTransformation(oSourceSRS, &oTargetSRS);
/* setup attribute and spatial queries */ /* setup attribute and spatial queries */
if (use_spatial_query) { if (use_spatial_query) {
double trans_min_x,trans_min_y,trans_max_x,trans_max_y; double trans_min_x, trans_min_y, trans_max_x, trans_max_y;
/* do a simple reprojection of the source SRS */ /* do a simple reprojection of the source SRS */
OGRCoordinateTransformation *poCTinverse; auto poCTinverse = OGRCreateCoordinateTransformation(&oTargetSRS, oSourceSRS);
poCTinverse = OGRCreateCoordinateTransformation(&oTargetSRS, oSourceSRS); trans_min_x = spat_min_x;
trans_min_y = spat_min_y;
trans_max_x = spat_max_x;
trans_max_y = spat_max_y;
trans_min_x=spat_min_x; poCTinverse->Transform(1, &trans_min_x, &trans_min_y);
trans_min_y=spat_min_y; poCTinverse->Transform(1, &trans_max_x, &trans_max_y);
trans_max_x=spat_max_x;
trans_max_y=spat_max_y;
poCTinverse->Transform(1,&trans_min_x,&trans_min_y);
poCTinverse->Transform(1,&trans_max_x,&trans_max_y);
poLayer->SetSpatialFilterRect(trans_min_x, trans_min_y, poLayer->SetSpatialFilterRect(trans_min_x, trans_min_y,
trans_max_x, trans_max_y); trans_max_x, trans_max_y);
OCTDestroyCoordinateTransformation ( poCTinverse );
} }
if (use_attribute_query) { if (use_attribute_query) {
if (poLayer->SetAttributeFilter(attribute_query.c_str()) != OGRERR_NONE) { if (poLayer->SetAttributeFilter(attribute_query.c_str()) != OGRERR_NONE) {
SG_LOG( SG_GENERAL, SG_ALERT, "Error in query expression '" << attribute_query << "'" ); SG_LOG( SG_GENERAL, SG_ALERT, "Error in query expression '" << attribute_query << "'" );
exit( 1 ); if (!continue_on_errors) {
SG_LOG( SG_GENERAL, SG_ALERT, "Aborting!" );
OCTDestroyCoordinateTransformation ( poCT );
exit( 1 );
}
else
return;
} }
} }
@ -449,16 +477,16 @@ void processLayer(OGRLayer* poLayer, tgChopper& results )
// Now process the workqueue with threads // Now process the workqueue with threads
// this just generates all the tgPolygons // this just generates all the tgPolygons
std::vector<Decoder *> decoders; std::vector<std::shared_ptr<Decoder>> decoders;
for (int i=0; i<num_threads; i++) { for (int i = 0; i < num_threads; ++i) {
Decoder* decoder = new Decoder( poCT, area_type_field, point_width_field, line_width_field, results ); auto decoder = std::make_shared<Decoder>( poCT, area_type_field, point_width_field, line_width_field, results );
decoder->start(); decoder->start();
decoders.push_back( decoder ); decoders.push_back( decoder );
} }
// Then wait until they are finished // Then wait until they are finished
for (unsigned int i=0; i<decoders.size(); i++) { for (auto decoder : decoders) {
decoders[i]->join(); decoder->join();
} }
OCTDestroyCoordinateTransformation ( poCT ); OCTDestroyCoordinateTransformation ( poCT );
@ -683,31 +711,34 @@ int main( int argc, char **argv ) {
SG_LOG( SG_GENERAL, SG_DEBUG, "Opening datasource " << datasource << " for reading." ); SG_LOG( SG_GENERAL, SG_DEBUG, "Opening datasource " << datasource << " for reading." );
GDALAllRegister(); GDALAllRegister();
GDALDataset *poDS; GDALDataset *poDS;
poDS = (GDALDataset*) GDALOpenEx( datasource.c_str(), GDAL_OF_VECTOR, NULL, NULL, NULL ); poDS = (GDALDataset*) GDALOpenEx( datasource.c_str(), GDAL_OF_VECTOR, NULL, NULL, NULL );
if( poDS == NULL ) if ( poDS == NULL )
{ {
SG_LOG( SG_GENERAL, SG_ALERT, "Failed opening datasource " << datasource ); SG_LOG( SG_GENERAL, SG_ALERT, "Failed opening datasource " << datasource );
exit( 1 );
GDALDestroyDriverManager();
return EXIT_FAILURE;
} }
SG_LOG( SG_GENERAL, SG_ALERT, "Processing datasource " << datasource ); SG_LOG( SG_GENERAL, SG_ALERT, "Processing datasource " << datasource );
OGRLayer *poLayer; OGRLayer *poLayer;
if (argc>3) { if (argc > 3) {
for (int i=3;i<argc;i++) { for (int i = 3; i < argc; ++i) {
poLayer = poDS->GetLayerByName( argv[i] ); poLayer = poDS->GetLayerByName( argv[i] );
if (poLayer == NULL ) if (poLayer == NULL )
{ {
SG_LOG( SG_GENERAL, SG_ALERT, "Failed opening layer " << argv[i] << " from datasource " << datasource ); SG_LOG( SG_GENERAL, SG_ALERT, "Failed opening layer " << argv[i] << " from datasource " << datasource );
exit( 1 ); return EXIT_FAILURE;
} }
processLayer(poLayer, results ); processLayer(poLayer, results );
} }
} else { } else {
for (int i=0;i<poDS->GetLayerCount();i++) { for (int i = 0; i < poDS->GetLayerCount(); ++i) {
poLayer = poDS->GetLayer(i); poLayer = poDS->GetLayer(i);
assert(poLayer != NULL); assert(poLayer != NULL);
@ -717,6 +748,7 @@ int main( int argc, char **argv ) {
} }
GDALClose(poDS); GDALClose(poDS);
GDALDestroyDriverManager();
SG_LOG(SG_GENERAL, SG_ALERT, "Saving to buckets"); SG_LOG(SG_GENERAL, SG_ALERT, "Saving to buckets");
results.Save( save_shapefiles ); results.Save( save_shapefiles );

View file

@ -24,7 +24,7 @@ void TrackedTriangle::update(Subdivision& s)
GreedySubdivision::GreedySubdivision(Map *map) GreedySubdivision::GreedySubdivision(Map *map)
{ {
H = map; H = map;
heap = new Heap(128); heap = new Heap(16384);
int w = H->width; int w = H->width;
int h = H->height; int h = H->height;

View file

@ -63,6 +63,7 @@ Edge::~Edge()
e2->qnext = NULL; e2->qnext = NULL;
e3->qnext = NULL; e3->qnext = NULL;
//FIXME: who deletes the edges allocated in ctor? (Torsten Dreyer 01/2019)
//delete e1; //delete e1;
//delete e2; //delete e2;
//delete e3; //delete e3;

View file

@ -15,8 +15,8 @@ private:
Edge(Edge *prev); Edge(Edge *prev);
protected: //protected:
Vec2 *data; Vec2 data;
Edge *next; Edge *next;
Triangle *lface; Triangle *lface;
@ -47,16 +47,16 @@ public:
Edge *Rprev() const { return Sym()->Onext(); } Edge *Rprev() const { return Sym()->Onext(); }
Vec2& Org() const { return *data; } const Vec2& Org() const { return data; }
Vec2& Dest() const { return *Sym()->data; } const Vec2& Dest() const { return Sym()->data; }
Triangle *Lface() const { return lface; } Triangle *Lface() const { return lface; }
void set_Lface(Triangle *t) { lface = t; } void set_Lface(Triangle *t) { lface = t; }
void EndPoints(Vec2& org, Vec2& dest) void EndPoints(const Vec2& org, const Vec2& dest)
{ {
data = &org; data = org;
Sym()->data = &dest; Sym()->data = dest;
} }
// //

View file

@ -28,7 +28,7 @@ Subdivision::~Subdivision()
} }
} }
Edge *Subdivision::makeEdge(Vec2& org, Vec2& dest) Edge *Subdivision::makeEdge(const Vec2& org, const Vec2& dest)
{ {
Edge *e = new Edge(); Edge *e = new Edge();
edges.push_back(e); edges.push_back(e);
@ -54,31 +54,26 @@ Edge *Subdivision::makeEdge()
void Subdivision::initMesh(const Vec2& A,const Vec2& B, void Subdivision::initMesh(const Vec2& A,const Vec2& B,
const Vec2& C,const Vec2& D) const Vec2& C,const Vec2& D)
{ {
Vec2& a = A.clone();
Vec2& b = B.clone();
Vec2& c = C.clone();
Vec2& d = D.clone();
Edge *ea = makeEdge(); Edge *ea = makeEdge();
ea->EndPoints(a, b); ea->EndPoints(A, B);
Edge *eb = makeEdge(); Edge *eb = makeEdge();
splice(ea->Sym(), eb); splice(ea->Sym(), eb);
eb->EndPoints(b, c); eb->EndPoints(B, C);
Edge *ec = makeEdge(); Edge *ec = makeEdge();
splice(eb->Sym(), ec); splice(eb->Sym(), ec);
ec->EndPoints(c, d); ec->EndPoints(C, D);
Edge *ed = makeEdge(); Edge *ed = makeEdge();
splice(ec->Sym(), ed); splice(ec->Sym(), ed);
ed->EndPoints(d, a); ed->EndPoints(D, A);
splice(ed->Sym(), ea); splice(ed->Sym(), ea);
Edge *diag = makeEdge(); Edge *diag = makeEdge();
splice(ed->Sym(),diag); splice(ed->Sym(),diag);
splice(eb->Sym(),diag->Sym()); splice(eb->Sym(),diag->Sym());
diag->EndPoints(a,c); diag->EndPoints(A,C);
startingEdge = ea; startingEdge = ea;
@ -334,7 +329,7 @@ Edge *Subdivision::spoke(Vec2& x, Edge *e)
// x lies within the Lface of e // x lies within the Lface of e
} }
Edge *base = makeEdge(e->Org(), x.clone()); Edge *base = makeEdge(e->Org(), x );
splice(base, e); splice(base, e);

View file

@ -66,7 +66,7 @@ protected:
~Subdivision(); ~Subdivision();
Edge *makeEdge(); Edge *makeEdge();
Edge *makeEdge(Vec2& org, Vec2& dest); Edge *makeEdge(const Vec2& org, const Vec2& dest);
virtual Triangle *allocFace(Edge *e); virtual Triangle *allocFace(Edge *e);
Triangle& makeFace(Edge *e); Triangle& makeFace(Edge *e);

View file

@ -16,7 +16,6 @@ public:
Vec2(real x=0, real y=0) { elt[0]=x; elt[1]=y; } Vec2(real x=0, real y=0) { elt[0]=x; elt[1]=y; }
Vec2(const Vec2& v) { copy(v); } Vec2(const Vec2& v) { copy(v); }
Vec2(const real *v) { elt[0]=v[0]; elt[1]=v[1]; } Vec2(const real *v) { elt[0]=v[0]; elt[1]=v[1]; }
Vec2& clone() const { return *(new Vec2(elt[0], elt[1])); }
// Access methods // Access methods
real& operator()(int i) { return elt[i]; } real& operator()(int i) { return elt[i]; }
@ -164,7 +163,7 @@ inline std::ostream& operator<<(std::ostream& out, const Vec2& v)
inline std::istream& operator>>(std::istream& in, Vec2& v) inline std::istream& operator>>(std::istream& in, Vec2& v)
{ {
char c; char c = '\0';
return in >> c >> v[0] >> v[1] >> c; return in >> c >> v[0] >> v[1] >> c;
} }

Some files were not shown because too many files have changed in this diff Show more