[saga] 03/04: Imported Upstream version 2.2.2
Johan Van de Wauw
johanvdw-guest at moszumanska.debian.org
Sun Oct 18 20:06:19 UTC 2015
This is an automated email from the git hooks/post-receive script.
johanvdw-guest pushed a commit to branch master
in repository saga.
commit 45e0b2410f6c8f4b2a4205c0ac7495ac86a0b16a
Author: Johan Van de Wauw <johan at vandewauw.be>
Date: Sun Oct 18 21:24:41 2015 +0200
Imported Upstream version 2.2.2
---
Makefile.am | 5 +
Makefile.in | 39 +-
README | 2 +-
configure | 20 +-
configure.ac | 4 +-
.../climate/climate_tools/MLB_Interface.cpp | 3 +
src/modules/climate/climate_tools/Makefile.am | 2 +
src/modules/climate/climate_tools/Makefile.in | 5 +-
.../climate_tools/daily_sun.cpp} | 513 +-
.../Filter.h => climate/climate_tools/daily_sun.h} | 39 +-
.../climate/climate_tools/etp_hargreave.cpp | 34 +-
src/modules/db/db_odbc/odbc.cpp | 31 +-
src/modules/db/db_pgsql/MLB_Interface.cpp | 4 +
src/modules/db/db_pgsql/db_pgsql.cpp | 330 +-
src/modules/db/db_pgsql/db_pgsql.h | 29 +-
src/modules/db/db_pgsql/get_connection.cpp | 175 +
src/modules/db/db_pgsql/get_connection.h | 40 +
src/modules/db/db_pgsql/pgis_raster.cpp | 252 +-
src/modules/db/db_pgsql/pgis_raster.h | 29 +
src/modules/db/db_pgsql/pgis_shapes.cpp | 24 +-
.../garden_3d_viewer/3d_viewer_pointcloud.cpp | 7 -
src/modules/grid/grid_filter/Filter.cpp | 145 +-
src/modules/grid/grid_filter/Filter.h | 10 +-
src/modules/grid/grid_filter/MLB_Interface.cpp | 5 +-
src/modules/grid/grid_filter/wombling.cpp | 633 +-
src/modules/grid/grid_filter/wombling.h | 59 +-
src/modules/grid/grid_gridding/nn/triangle.c | 16012 +++++++++++++++++++
src/modules/grid/grid_gridding/nn/triangle.h | 296 +
.../grid/grid_spline/Gridding_Spline_MBA.cpp | 7 +-
src/modules/grid/grid_tools/Grid_Gaps.cpp | 50 +-
.../imagery_classification/MLB_Interface.cpp | 4 +-
.../imagery/imagery_classification/Makefile.am | 2 +
.../imagery/imagery_classification/Makefile.in | 9 +-
.../imagery_classification/change_detection.cpp | 274 +-
.../imagery_classification/change_detection.h | 2 +
.../classification_quality.cpp | 429 +
...change_detection.h => classification_quality.h} | 27 +-
src/modules/imagery/imagery_svm/svm.cpp | 3089 ++++
src/modules/imagery/imagery_svm/svm.h | 101 +
src/modules/io/io_gdal/gdal_import.cpp | 13 +-
.../pointcloud_tools/pc_attribute_calculator.cpp | 25 +-
.../pointcloud_tools/pc_attribute_calculator.h | 3 +-
.../pointcloud_tools/pc_drop_attribute.cpp | 130 +-
.../pointcloud_tools/pc_drop_attribute.h | 3 +-
.../pointcloud/pointcloud_tools/pc_merge.cpp | 30 +-
src/modules/pointcloud/pointcloud_tools/pc_merge.h | 3 +-
.../shapes/shapes_tools/shapes_split_randomly.cpp | 74 +-
.../shapes/shapes_tools/shapes_split_randomly.h | 11 +-
.../simulation/sim_fire_spreading/Forecasting.cpp | 666 +
.../simulation/sim_fire_spreading/Forecasting.h | 84 +
.../sim_fire_spreading}/MLB_Interface.cpp | 88 +-
.../sim_fire_spreading/MLB_Interface.h} | 49 +-
.../simulation/sim_fire_spreading/Makefile.am | 26 +
.../sim_fire_spreading}/Makefile.in | 115 +-
.../simulation/sim_fire_spreading/Simulate.cpp | 363 +
.../simulation/sim_fire_spreading/Simulate.h | 81 +
.../simulation/sim_fire_spreading/fireLib.c | 1817 +++
.../simulation/sim_fire_spreading/fireLib.h | 551 +
.../statistics/statistics_kriging/kriging_base.cpp | 48 +-
.../statistics_kriging/kriging_regression.cpp | 49 +-
.../statistics_kriging/semivariogram.cpp | 49 +-
.../ta_lighting/SolarRadiation.cpp | 1131 +-
.../terrain_analysis/ta_lighting/SolarRadiation.h | 35 +-
.../ta_morphometry/MLB_Interface.cpp | 1 +
.../ta_morphometry/wind_effect.cpp | 195 +-
.../terrain_analysis/ta_morphometry/wind_effect.h | 27 +-
src/modules/tin/tin_viewer/tin_view_module.cpp | 7 -
src/saga_core/saga_api/api_callback.cpp | 16 +-
src/saga_core/saga_api/api_core.h | 4 +-
src/saga_core/saga_api/api_memory.cpp | 6 +-
src/saga_core/saga_api/datetime.cpp | 175 +-
src/saga_core/saga_api/datetime.h | 28 +-
src/saga_core/saga_api/grid.cpp | 95 +-
src/saga_core/saga_api/grid_io.cpp | 66 +-
src/saga_core/saga_api/grid_operation.cpp | 72 +-
src/saga_core/saga_api/module.cpp | 16 +-
src/saga_core/saga_api/module_chain.cpp | 70 +-
src/saga_core/saga_api/module_library.h | 9 +-
src/saga_core/saga_api/parameter.cpp | 66 +-
src/saga_core/saga_api/parameter_data.cpp | 11 +-
src/saga_core/saga_api/parameters.cpp | 26 +-
src/saga_core/saga_api/parameters.h | 12 +-
src/saga_core/saga_api/saga_api.h | 4 +-
src/saga_core/saga_api/shapes.cpp | 93 +-
src/saga_core/saga_api/table.cpp | 86 +-
src/saga_core/saga_api/table_io.cpp | 49 +-
src/saga_core/saga_cmd/module_library.cpp | 7 +-
src/saga_core/saga_gui/active.cpp | 4 +-
src/saga_core/saga_gui/data_source.cpp | 6 +
src/saga_core/saga_gui/data_source.h | 2 +
src/saga_core/saga_gui/data_source_odbc.cpp | 22 +-
src/saga_core/saga_gui/data_source_pgsql.cpp | 748 +-
src/saga_core/saga_gui/data_source_pgsql.h | 26 +
src/saga_core/saga_gui/info_messages.cpp | 25 +-
src/saga_core/saga_gui/parameters_control.cpp | 21 +-
src/saga_core/saga_gui/project.cpp | 94 +-
src/saga_core/saga_gui/res/saga_tip.txt | 37 +-
src/saga_core/saga_gui/res_commands.cpp | 21 +-
src/saga_core/saga_gui/res_commands.h | 18 +-
src/saga_core/saga_gui/saga_frame.cpp | 5 +-
src/saga_core/saga_gui/wksp_data_item.cpp | 66 +-
src/saga_core/saga_gui/wksp_data_manager.cpp | 11 +-
src/saga_core/saga_gui/wksp_grid.cpp | 84 +-
src/saga_core/saga_gui/wksp_pointcloud.cpp | 6 +-
src/saga_core/saga_gui/wksp_shapes.cpp | 60 +-
src/saga_core/saga_gui/wksp_table.cpp | 36 +-
.../python/examples/00_grid_create_dummy.py | 70 +
.../python/examples/01_grid_asc_to_saga.py | 57 +
.../python/examples/02_grid_morphometry.py | 90 +
.../python/examples/03_grid_difference.py | 66 +
src/scripting/python/examples/04_grid_contour.py | 57 +
src/scripting/python/examples/05_shp2xyz.py | 48 +
src/scripting/python/examples/06_xyz2shp.py | 69 +
src/scripting/python/helpers/print_version.py | 13 +
.../saga_cmd_param_interface/environment.py | 31 +
.../saga_cmd_param_interface/param_interface.py | 64 +
.../helpers/saga_cmd_param_interface/tools.py | 638 +
src/scripting/python/test_data/test.mgrd | 24 +
src/scripting/python/test_data/test.sdat | 1 +
src/scripting/python/test_data/test.sgrd | 14 +
src/scripting/python/test_data/test_ascii.asc | 16 +
src/scripting/python/test_data/test_pts.dbf | Bin 0 -> 6081 bytes
src/scripting/python/test_data/test_pts.mshp | 31 +
src/scripting/python/test_data/test_pts.shp | Bin 0 -> 2340 bytes
src/scripting/python/test_data/test_pts.shx | Bin 0 -> 740 bytes
src/scripting/python/test_data/test_pts_xyz.xyz | 81 +
src/scripting/toolchains/cluster_terrain.xml | 63 +
src/scripting/toolchains/gridding.xml | 36 +
src/scripting/toolchains/imagery_lczc.xml | 134 +
src/scripting/toolchains/obia.xml | 113 +
src/scripting/toolchains/points_to_contour.xml | 48 +
src/scripting/toolchains/sieve_and_clump.xml | 45 +
.../toolchains/temperature_downscaling.xml | 92 +
src/scripting/toolchains/terrain_analysis.xml | 8 +
src/scripting/toolchains/terrain_segmentation.xml | 148 +
src/scripting/toolchains/twi.xml | 54 +
src/scripting/toolchains/upslope_height.xml | 104 +
137 files changed, 30285 insertions(+), 2548 deletions(-)
diff --git a/Makefile.am b/Makefile.am
index c435550..a2f7fec 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -4,3 +4,8 @@ AM_CFLAGS = -g -DDEBUG
AM_CXXFLAGS = -g -DDEBUG $(GOMPFLAGS)
endif
ACLOCAL_AMFLAGS = -I m4
+
+# additional directories to package
+EXTRA_DIST = ./src/scripting
+dist-hook:
+ rm -rf `find $(distdir)/src/scripting -type d -name .svn`
diff --git a/Makefile.in b/Makefile.in
index e71f187..0d9f735 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -81,7 +81,8 @@ subdir = .
DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
$(top_srcdir)/configure $(am__configure_deps) \
$(srcdir)/config.h.in AUTHORS COPYING ChangeLog NEWS README \
- compile config.guess config.sub install-sh missing ltmain.sh
+ compile config.guess config.sub depcomp install-sh missing \
+ py-compile ltmain.sh
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/m4/ax_lib_postgresql.m4 \
$(top_srcdir)/m4/ax_pkg_swig.m4 \
@@ -349,6 +350,9 @@ SUBDIRS = . src
@DEBUG_TRUE at AM_CFLAGS = -g -DDEBUG
@DEBUG_TRUE at AM_CXXFLAGS = -g -DDEBUG $(GOMPFLAGS)
ACLOCAL_AMFLAGS = -I m4
+
+# additional directories to package
+EXTRA_DIST = ./src/scripting
all: config.h
$(MAKE) $(AM_MAKEFLAGS) all-recursive
@@ -575,6 +579,9 @@ distdir: $(DISTFILES)
|| exit 1; \
fi; \
done
+ $(MAKE) $(AM_MAKEFLAGS) \
+ top_distdir="$(top_distdir)" distdir="$(distdir)" \
+ dist-hook
-test -n "$(am__skip_mode_fix)" \
|| find "$(distdir)" -type d ! -perm -755 \
-exec chmod u+rwx,go+rx {} \; -o \
@@ -816,20 +823,22 @@ uninstall-am:
.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \
am--refresh check check-am clean clean-cscope clean-generic \
clean-libtool cscope cscopelist-am ctags ctags-am dist \
- dist-all dist-bzip2 dist-gzip dist-lzip dist-shar dist-tarZ \
- dist-xz dist-zip distcheck distclean distclean-generic \
- distclean-hdr distclean-libtool distclean-tags distcleancheck \
- distdir distuninstallcheck dvi dvi-am html html-am info \
- info-am install install-am install-data install-data-am \
- install-dvi install-dvi-am install-exec install-exec-am \
- install-html install-html-am install-info install-info-am \
- install-man install-pdf install-pdf-am install-ps \
- install-ps-am install-strip installcheck installcheck-am \
- installdirs installdirs-am maintainer-clean \
- maintainer-clean-generic mostlyclean mostlyclean-generic \
- mostlyclean-libtool pdf pdf-am ps ps-am tags tags-am uninstall \
- uninstall-am
-
+ dist-all dist-bzip2 dist-gzip dist-hook dist-lzip dist-shar \
+ dist-tarZ dist-xz dist-zip distcheck distclean \
+ distclean-generic distclean-hdr distclean-libtool \
+ distclean-tags distcleancheck distdir distuninstallcheck dvi \
+ dvi-am html html-am info info-am install install-am \
+ install-data install-data-am install-dvi install-dvi-am \
+ install-exec install-exec-am install-html install-html-am \
+ install-info install-info-am install-man install-pdf \
+ install-pdf-am install-ps install-ps-am install-strip \
+ installcheck installcheck-am installdirs installdirs-am \
+ maintainer-clean maintainer-clean-generic mostlyclean \
+ mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
+ tags tags-am uninstall uninstall-am
+
+dist-hook:
+ rm -rf `find $(distdir)/src/scripting -type d -name .svn`
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
diff --git a/README b/README
index 21371d7..2b38889 100644
--- a/README
+++ b/README
@@ -1,6 +1,6 @@
_______________________________________________________________________________
- SAGA 2.2.1 - System for Automated Geoscientific Analyses
+ SAGA 2.2.2 - System for Automated Geoscientific Analyses
_______________________________________________________________________________
* Introduction
diff --git a/configure b/configure
index 9f94184..174542e 100755
--- a/configure
+++ b/configure
@@ -1,6 +1,6 @@
#! /bin/sh
# Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.69 for saga 2.2.1.
+# Generated by GNU Autoconf 2.69 for saga 2.2.2.
#
# Report bugs to <BUG-REPORT-ADDRESS>.
#
@@ -590,8 +590,8 @@ MAKEFLAGS=
# Identity of this package.
PACKAGE_NAME='saga'
PACKAGE_TARNAME='saga'
-PACKAGE_VERSION='2.2.1'
-PACKAGE_STRING='saga 2.2.1'
+PACKAGE_VERSION='2.2.2'
+PACKAGE_STRING='saga 2.2.2'
PACKAGE_BUGREPORT='BUG-REPORT-ADDRESS'
PACKAGE_URL=''
@@ -1380,7 +1380,7 @@ if test "$ac_init_help" = "long"; then
# Omit some internal or obsolete options to make the list less imposing.
# This message is too long to be a string in the A/UX 3.1 sh.
cat <<_ACEOF
-\`configure' configures saga 2.2.1 to adapt to many kinds of systems.
+\`configure' configures saga 2.2.2 to adapt to many kinds of systems.
Usage: $0 [OPTION]... [VAR=VALUE]...
@@ -1450,7 +1450,7 @@ fi
if test -n "$ac_init_help"; then
case $ac_init_help in
- short | recursive ) echo "Configuration of saga 2.2.1:";;
+ short | recursive ) echo "Configuration of saga 2.2.2:";;
esac
cat <<\_ACEOF
@@ -1571,7 +1571,7 @@ fi
test -n "$ac_init_help" && exit $ac_status
if $ac_init_version; then
cat <<\_ACEOF
-saga configure 2.2.1
+saga configure 2.2.2
generated by GNU Autoconf 2.69
Copyright (C) 2012 Free Software Foundation, Inc.
@@ -2115,7 +2115,7 @@ cat >config.log <<_ACEOF
This file contains any messages produced by compilers while
running configure, to aid debugging if configure makes a mistake.
-It was created by saga $as_me 2.2.1, which was
+It was created by saga $as_me 2.2.2, which was
generated by GNU Autoconf 2.69. Invocation command line was
$ $0 $@
@@ -2982,7 +2982,7 @@ fi
# Define the identity of the package.
PACKAGE='saga'
- VERSION='2.2.1'
+ VERSION='2.2.2'
cat >>confdefs.h <<_ACEOF
@@ -18590,7 +18590,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
# report actual input values of CONFIG_FILES etc. instead of their
# values after options handling.
ac_log="
-This file was extended by saga $as_me 2.2.1, which was
+This file was extended by saga $as_me 2.2.2, which was
generated by GNU Autoconf 2.69. Invocation command line was
CONFIG_FILES = $CONFIG_FILES
@@ -18656,7 +18656,7 @@ _ACEOF
cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
ac_cs_version="\\
-saga config.status 2.2.1
+saga config.status 2.2.2
configured by $0, generated by GNU Autoconf 2.69,
with options \\"\$ac_cs_config\\"
diff --git a/configure.ac b/configure.ac
index 5bb0a9a..5a7a618 100755
--- a/configure.ac
+++ b/configure.ac
@@ -1,9 +1,9 @@
-# $Id: configure.ac 2536 2015-07-02 14:57:02Z oconrad $
+# $Id: configure.ac 2601 2015-09-23 15:11:23Z oconrad $
# -*- Autoconf -*-
# Process this file with autoconf to produce a configure script.
AC_PREREQ(2.59)
-AC_INIT(saga, 2.2.1, BUG-REPORT-ADDRESS)
+AC_INIT(saga, 2.2.2, BUG-REPORT-ADDRESS)
AC_CONFIG_SRCDIR([src/saga_core/saga_gui/wksp_data_menu_files.cpp])
AC_CONFIG_HEADER([config.h])
AC_CONFIG_MACRO_DIR([m4])
diff --git a/src/modules/climate/climate_tools/MLB_Interface.cpp b/src/modules/climate/climate_tools/MLB_Interface.cpp
index 6645aa3..d0b699e 100644
--- a/src/modules/climate/climate_tools/MLB_Interface.cpp
+++ b/src/modules/climate/climate_tools/MLB_Interface.cpp
@@ -98,6 +98,7 @@ CSG_String Get_Info(int i)
#include "grid_levels_interpolation.h"
#include "milankovic.h"
#include "etp_hargreave.h"
+#include "daily_sun.h"
//---------------------------------------------------------
@@ -119,6 +120,8 @@ CSG_Module * Create_Module(int i)
case 6: return( new CPET_Hargreave_Table );
case 7: return( new CPET_Day_To_Hour );
+ case 9: return( new CDaily_Sun );
+
//-----------------------------------------------------
case 10: return( NULL );
default: return( MLB_INTERFACE_SKIP_MODULE );
diff --git a/src/modules/climate/climate_tools/Makefile.am b/src/modules/climate/climate_tools/Makefile.am
index 42d73e5..be16d24 100644
--- a/src/modules/climate/climate_tools/Makefile.am
+++ b/src/modules/climate/climate_tools/Makefile.am
@@ -13,10 +13,12 @@ AM_CXXFLAGS = -fPIC $(CXX_INCS) $(DEF_SAGA) $(UC_DEFS) $(DBGFLAGS) $(GOMP
AM_LDFLAGS = -fPIC -shared -avoid-version
pkglib_LTLIBRARIES = libclimate_tools.la
libclimate_tools_la_SOURCES =\
+daily_sun.cpp\
etp_hargreave.cpp\
grid_levels_interpolation.cpp\
milankovic.cpp\
MLB_Interface.cpp\
+daily_sun.h\
etp_hargreave.h\
grid_levels_interpolation.h\
milankovic.h\
diff --git a/src/modules/climate/climate_tools/Makefile.in b/src/modules/climate/climate_tools/Makefile.in
index 5c278c1..47d3ce5 100644
--- a/src/modules/climate/climate_tools/Makefile.in
+++ b/src/modules/climate/climate_tools/Makefile.in
@@ -127,7 +127,7 @@ am__installdirs = "$(DESTDIR)$(pkglibdir)"
LTLIBRARIES = $(pkglib_LTLIBRARIES)
libclimate_tools_la_DEPENDENCIES = \
$(top_srcdir)/src/saga_core/saga_api/libsaga_api.la
-am_libclimate_tools_la_OBJECTS = etp_hargreave.lo \
+am_libclimate_tools_la_OBJECTS = daily_sun.lo etp_hargreave.lo \
grid_levels_interpolation.lo milankovic.lo MLB_Interface.lo
libclimate_tools_la_OBJECTS = $(am_libclimate_tools_la_OBJECTS)
AM_V_lt = $(am__v_lt_ at AM_V@)
@@ -372,10 +372,12 @@ AM_CXXFLAGS = -fPIC $(CXX_INCS) $(DEF_SAGA) $(UC_DEFS) $(DBGFLAGS) $(GOMPFLAGS)
AM_LDFLAGS = -fPIC -shared -avoid-version
pkglib_LTLIBRARIES = libclimate_tools.la
libclimate_tools_la_SOURCES = \
+daily_sun.cpp\
etp_hargreave.cpp\
grid_levels_interpolation.cpp\
milankovic.cpp\
MLB_Interface.cpp\
+daily_sun.h\
etp_hargreave.h\
grid_levels_interpolation.h\
milankovic.h\
@@ -462,6 +464,7 @@ distclean-compile:
-rm -f *.tab.c
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/MLB_Interface.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/daily_sun.Plo at am__quote@
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/etp_hargreave.Plo at am__quote@
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/grid_levels_interpolation.Plo at am__quote@
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/milankovic.Plo at am__quote@
diff --git a/src/modules/grid/grid_filter/Filter.cpp b/src/modules/climate/climate_tools/daily_sun.cpp
similarity index 50%
copy from src/modules/grid/grid_filter/Filter.cpp
copy to src/modules/climate/climate_tools/daily_sun.cpp
index 2edfd4d..a1b375f 100644
--- a/src/modules/grid/grid_filter/Filter.cpp
+++ b/src/modules/climate/climate_tools/daily_sun.cpp
@@ -1,273 +1,260 @@
-/**********************************************************
- * Version $Id: Filter.cpp 1921 2014-01-09 10:24:11Z oconrad $
- *********************************************************/
-
-///////////////////////////////////////////////////////////
-// //
-// SAGA //
-// //
-// System for Automated Geoscientific Analyses //
-// //
-// Module Library: //
-// Grid_Filter //
-// //
-//-------------------------------------------------------//
-// //
-// Filter.cpp //
-// //
-// Copyright (C) 2003 by //
-// Olaf Conrad //
-// //
-//-------------------------------------------------------//
-// //
-// This file is part of 'SAGA - System for Automated //
-// Geoscientific Analyses'. SAGA 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; version 2 of the License. //
-// //
-// SAGA 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 Street, 5th Floor, Boston, MA 02110-1301, //
-// USA. //
-// //
-//-------------------------------------------------------//
-// //
-// e-mail: oconrad at saga-gis.org //
-// //
-// contact: Olaf Conrad //
-// Institute of Geography //
-// University of Goettingen //
-// Goldschmidtstr. 5 //
-// 37077 Goettingen //
-// Germany //
-// //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-
-
-///////////////////////////////////////////////////////////
-// //
-// //
-// //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-#include "Filter.h"
-
-
-///////////////////////////////////////////////////////////
-// //
-// //
-// //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-CFilter::CFilter(void)
-{
- //-----------------------------------------------------
- // 1. Info...
-
- Set_Name (_TL("Simple Filter"));
-
- Set_Author (SG_T("O.Conrad (c) 2003"));
-
- Set_Description (_TW(
- "Simple standard filters for grids."
- ));
-
-
- //-----------------------------------------------------
- // 2. Parameters...
-
- Parameters.Add_Grid(
- NULL, "INPUT" , _TL("Grid"),
- _TL(""),
- PARAMETER_INPUT
- );
-
- Parameters.Add_Grid(
- NULL, "RESULT" , _TL("Filtered Grid"),
- _TL(""),
- PARAMETER_OUTPUT_OPTIONAL
- );
-
+/**********************************************************
+ * Version $Id: daily_sun.cpp 911 2011-11-11 11:11:11Z oconrad $
+ *********************************************************/
+
+///////////////////////////////////////////////////////////
+// //
+// SAGA //
+// //
+// System for Automated Geoscientific Analyses //
+// //
+// Module Library: //
+// climate_tools //
+// //
+//-------------------------------------------------------//
+// //
+// daily_sun.cpp //
+// //
+// Copyright (C) 2015 by //
+// Olaf Conrad //
+// //
+//-------------------------------------------------------//
+// //
+// This file is part of 'SAGA - System for Automated //
+// Geoscientific Analyses'. SAGA 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; version 2 of the License. //
+// //
+// SAGA 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 Street, 5th Floor, Boston, MA 02110-1301, //
+// USA. //
+// //
+//-------------------------------------------------------//
+// //
+// e-mail: oconrad at saga-gis.de //
+// //
+// contact: Olaf Conrad //
+// Institute of Geography //
+// University of Hamburg //
+// Germany //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+#include "daily_sun.h"
+
+#include <saga_api/datetime.h>
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+CDaily_Sun::CDaily_Sun(void)
+{
+ //-----------------------------------------------------
+ Set_Name (_TL("Sunrise and Sunset"));
+
+ Set_Author ("O.Conrad (c) 2015");
+
+ Set_Description (_TW(
+ ""
+ ));
+
+ //-----------------------------------------------------
+ Parameters.Add_Grid(NULL, "TARGET" , _TL("Target System"), _TL(""), PARAMETER_INPUT);
+ Parameters.Add_Grid(NULL, "SUNRISE", _TL("Sunrise" ), _TL(""), PARAMETER_OUTPUT);
+ Parameters.Add_Grid(NULL, "SUNSET" , _TL("Sunset" ), _TL(""), PARAMETER_OUTPUT);
+ Parameters.Add_Grid(NULL, "LENGTH" , _TL("Day Length" ), _TL(""), PARAMETER_OUTPUT);
+
+ //-----------------------------------------------------
+ Parameters.Add_Value(
+ NULL , "YEAR" , _TL("Year"),
+ _TL(""),
+ PARAMETER_TYPE_Int, CSG_DateTime::Get_Current_Year()
+ );
+
Parameters.Add_Choice(
- NULL, "MODE" , _TL("Search Mode"),
- _TL(""),
- CSG_String::Format(SG_T("%s|%s|"),
- _TL("Square"),
- _TL("Circle")
- ), 1
- );
-
- Parameters.Add_Choice(
- NULL, "METHOD" , _TL("Filter"),
- _TL(""),
- CSG_String::Format(SG_T("%s|%s|%s|"),
- _TL("Smooth"),
- _TL("Sharpen"),
- _TL("Edge")
- ), 0
- );
-
- Parameters.Add_Value(
- NULL, "RADIUS" , _TL("Radius"),
+ NULL , "MONTH" , _TL("Month"),
_TL(""),
- PARAMETER_TYPE_Int, 1, 1, true
+ CSG_DateTime::Get_Month_Choices(), CSG_DateTime::Get_Current_Month()
);
-}
-
-
-///////////////////////////////////////////////////////////
-// //
-// //
-// //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-bool CFilter::On_Execute(void)
-{
- int Mode, Radius, Method;
- double Mean;
- CSG_Grid *pResult;
-
- //-----------------------------------------------------
- m_pInput = Parameters("INPUT") ->asGrid();
- pResult = Parameters("RESULT") ->asGrid();
- Radius = Parameters("RADIUS") ->asInt();
- Mode = Parameters("MODE") ->asInt();
- Method = Parameters("METHOD") ->asInt();
-
- switch( Mode )
- {
- case 0: break;
- case 1: m_Radius.Create(Radius); break;
- }
-
- //-----------------------------------------------------
- if( !pResult || pResult == m_pInput )
- {
- pResult = SG_Create_Grid(m_pInput);
- }
- else
- {
- pResult->Set_Name(CSG_String::Format(SG_T("%s [%s]"), m_pInput->Get_Name(), _TL("Filter")));
-
- pResult->Set_NoData_Value(m_pInput->Get_NoData_Value());
- }
-
- //-----------------------------------------------------
- for(int y=0; y<Get_NY() && Set_Progress(y); y++)
- {
- for(int x=0; x<Get_NX(); x++)
- {
- if( m_pInput->is_InGrid(x, y) )
- {
- switch( Mode )
- {
- case 0: Mean = Get_Mean_Square(x, y, Radius); break;
- case 1: Mean = Get_Mean_Circle(x, y); break;
- }
-
- switch( Method )
- {
- case 0: default: // Smooth...
- pResult->Set_Value(x, y, Mean);
- break;
-
- case 1: // Sharpen...
- pResult->Set_Value(x, y, m_pInput->asDouble(x, y) + (m_pInput->asDouble(x, y) - Mean));
- break;
-
- case 2: // Edge...
- pResult->Set_Value(x, y, m_pInput->asDouble(x, y) - Mean);
- break;
- }
- }
- else
- {
- pResult->Set_NoData(x, y);
- }
- }
- }
-
- //-----------------------------------------------------
- if( !Parameters("RESULT")->asGrid() || Parameters("RESULT")->asGrid() == m_pInput )
- {
- m_pInput->Assign(pResult);
- delete(pResult);
-
- DataObject_Update(m_pInput);
- }
-
- m_Radius.Destroy();
-
- return( true );
-}
-
-
-///////////////////////////////////////////////////////////
-// //
-// //
-// //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-double CFilter::Get_Mean_Square(int x, int y, int Radius)
+ Parameters.Add_Value(
+ NULL , "DAY" , _TL("Day of Month"),
+ _TL(""),
+ PARAMETER_TYPE_Int, CSG_DateTime::Get_Current_Day(), 1, true, 31, true
+ );
+
+ Parameters.Add_Choice(
+ NULL , "TIME" , _TL("Time"),
+ _TL(""),
+ CSG_String::Format("%s|%s|",
+ _TL("local"),
+ _TL("world")
+ )
+ );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+int CDaily_Sun::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
{
- int ix, iy, n;
- double s;
-
- for(n=0, s=0.0, iy=y-Radius; iy<=y+Radius; iy++)
- {
- for(ix=x-Radius; ix<=x+Radius; ix++)
- {
- if( m_pInput->is_InGrid(ix, iy) )
- {
- s += m_pInput->asDouble(ix, iy);
- n ++;
- }
- }
- }
-
- return( n > 0 ? s / n : m_pInput->Get_NoData_Value() );
+ return( CSG_Module::On_Parameters_Enable(pParameters, pParameter) );
}
-//---------------------------------------------------------
-double CFilter::Get_Mean_Circle(int x, int y)
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+double SG_Range_Set_0_to_24(double Value)
{
- int i, ix, iy, n;
- double s;
-
- for(n=0, s=0.0, i=0; i<m_Radius.Get_nPoints(); i++)
- {
- m_Radius.Get_Point(i, x, y, ix, iy);
-
- if( m_pInput->is_InGrid(ix, iy) )
- {
- s += m_pInput->asDouble(ix, iy);
- n ++;
- }
- }
+ Value = fmod(Value, 24.0);
- return( n > 0 ? s / n : m_pInput->Get_NoData_Value() );
+ return( Value < 0.0 ? Value + 24.0 : Value );
}
-
-
-///////////////////////////////////////////////////////////
-// //
-// //
-// //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CDaily_Sun::On_Execute(void)
+{
+ //-----------------------------------------------------
+ CSG_Grid *pTarget = Parameters("TARGET")->asGrid();
+
+ if( !pTarget->Get_Projection().is_Okay() )
+ {
+ Error_Set(_TL("target's spatial reference system is undefined"));
+
+ return( false );
+ }
+
+ CSG_Grid Lon(*Get_System()), Lat(*Get_System());
+
+ SG_RUN_MODULE_ExitOnError("pj_proj4", 17, // geographic coordinate grids
+ SG_MODULE_PARAMETER_SET("GRID", pTarget)
+ && SG_MODULE_PARAMETER_SET("LON" , &Lon)
+ && SG_MODULE_PARAMETER_SET("LAT" , &Lat)
+ )
+
+ Lon *= M_DEG_TO_RAD;
+ Lat *= M_DEG_TO_RAD;
+
+ //-----------------------------------------------------
+ CSG_Grid *pSunset = Parameters("SUNSET" )->asGrid();
+ CSG_Grid *pSunrise = Parameters("SUNRISE")->asGrid();
+ CSG_Grid *pDuration = Parameters("LENGTH" )->asGrid();
+
+ bool bWorld = Parameters("TIME")->asInt() == 1;
+
+ //-----------------------------------------------------
+ CSG_DateTime Time((CSG_DateTime::TSG_DateTime)Parameters("DAY")->asInt(), (CSG_DateTime::Month)Parameters("MONTH")->asInt(), Parameters("YEAR")->asInt());
+
+ Time.Reset_Time();
+
+ Message_Add(Time.Format("\n%A, %d. %B %Y"), false);
+
+ //-----------------------------------------------------
+ double Dec, RA, RAm, T;
+
+ SG_Get_Sun_Position(Time, RA, Dec);
+
+ T = ((int)Time.Get_JDN() - 2451545.0 ) / 36525.0; // Number of Julian centuries since 2000/01/01 at 12 UT (JDN = 2451545.0)
+
+ RAm = fmod(18.71506921 + 2400.0513369 * T + (2.5862e-5 - 1.72e-9 * T) * T*T, 24.0);
+ RA = fmod(RA * 12.0 / M_PI, 24.0); if( RA < 0.0 ) RA += 24.0;
+
+ T = 1.0027379 * (RAm - RA);
+
+ //-----------------------------------------------------
+ for(int y=0; y<Get_NY() && Set_Progress(y); y++)
+ {
+ // #pragma omp parallel for
+ for(int x=0; x<Get_NX(); x++)
+ {
+ if( pTarget->is_NoData(x, y) )
+ {
+ pSunrise ->Set_NoData(x, y);
+ pSunset ->Set_NoData(x, y);
+ pDuration->Set_NoData(x, y);
+ }
+ else
+ {
+ double dT = (sin(-Lat.asDouble(x, y) / 60.0) - sin(Lat.asDouble(x, y)) * sin(Dec)) / (cos(Lat.asDouble(x, y)) * cos(Dec));
+
+ if( dT > 1.0 )
+ {
+ pSunrise ->Set_NoData(x, y);
+ pSunset ->Set_NoData(x, y);
+ pDuration->Set_Value (x, y, 0.0);
+ }
+ else if( dT < -1.0 )
+ {
+ pSunrise ->Set_NoData(x, y);
+ pSunset ->Set_NoData(x, y);
+ pDuration->Set_Value (x, y, 24.0);
+ }
+ else
+ {
+ dT = acos(dT) * 12.0 / M_PI;
+
+ double Sunrise = SG_Range_Set_0_to_24(12.0 - dT - T);
+ double Sunset = SG_Range_Set_0_to_24(12.0 + dT - T);
+
+ pDuration->Set_Value(x, y, Sunset - Sunrise);
+
+ if( bWorld )
+ {
+ Sunrise = SG_Range_Set_0_to_24(Sunrise - M_RAD_TO_DEG * Lon.asDouble(x, y) / 15.0);
+ Sunset = SG_Range_Set_0_to_24(Sunset - M_RAD_TO_DEG * Lon.asDouble(x, y) / 15.0);
+ }
+
+ pSunrise ->Set_Value(x, y, Sunrise);
+ pSunset ->Set_Value(x, y, Sunset );
+ }
+ }
+ }
+ }
+
+ //-----------------------------------------------------
+ return( true );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
diff --git a/src/modules/grid/grid_filter/Filter.h b/src/modules/climate/climate_tools/daily_sun.h
similarity index 81%
copy from src/modules/grid/grid_filter/Filter.h
copy to src/modules/climate/climate_tools/daily_sun.h
index e95357a..e700015 100644
--- a/src/modules/grid/grid_filter/Filter.h
+++ b/src/modules/climate/climate_tools/daily_sun.h
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: Filter.h 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: daily_sun.h 911 2011-02-14 16:38:15Z reklov_w $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -9,13 +9,13 @@
// System for Automated Geoscientific Analyses //
// //
// Module Library: //
-// Grid_Filter //
+// climate_tools //
// //
//-------------------------------------------------------//
// //
-// Filter.h //
+// daily_sun.h //
// //
-// Copyright (C) 2003 by //
+// Copyright (C) 2015 by //
// Olaf Conrad //
// //
//-------------------------------------------------------//
@@ -40,13 +40,11 @@
// //
//-------------------------------------------------------//
// //
-// e-mail: oconrad at saga-gis.org //
+// e-mail: oconrad at saga-gis.de //
// //
// contact: Olaf Conrad //
// Institute of Geography //
-// University of Goettingen //
-// Goldschmidtstr. 5 //
-// 37077 Goettingen //
+// University of Hamburg //
// Germany //
// //
///////////////////////////////////////////////////////////
@@ -61,8 +59,8 @@
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-#ifndef HEADER_INCLUDED__Filter_H
-#define HEADER_INCLUDED__Filter_H
+#ifndef HEADER_INCLUDED__daily_sun_H
+#define HEADER_INCLUDED__daily_sun_H
///////////////////////////////////////////////////////////
@@ -82,26 +80,19 @@
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-class CFilter : public CSG_Module_Grid
+class CDaily_Sun : public CSG_Module_Grid
{
public:
- CFilter(void);
+ CDaily_Sun(void);
-
-protected:
-
- virtual bool On_Execute (void);
+ virtual CSG_String Get_MenuPath (void) { return( _TL("Tools") ); }
-private:
-
- CSG_Grid_Radius m_Radius;
-
- CSG_Grid *m_pInput;
+protected:
+ virtual int On_Parameters_Enable (CSG_Parameters *pParameters, CSG_Parameter *pParameter);
- double Get_Mean_Square (int x, int y, int Radius);
- double Get_Mean_Circle (int x, int y);
+ virtual bool On_Execute (void);
};
@@ -113,4 +104,4 @@ private:
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-#endif // #ifndef HEADER_INCLUDED__Filter_H
+#endif // #ifndef HEADER_INCLUDED__daily_sun_H
diff --git a/src/modules/climate/climate_tools/etp_hargreave.cpp b/src/modules/climate/climate_tools/etp_hargreave.cpp
index 5579adc..5e25bb6 100644
--- a/src/modules/climate/climate_tools/etp_hargreave.cpp
+++ b/src/modules/climate/climate_tools/etp_hargreave.cpp
@@ -61,6 +61,8 @@
//---------------------------------------------------------
#include "etp_hargreave.h"
+#include <saga_api/datetime.h>
+
///////////////////////////////////////////////////////////
// //
@@ -107,8 +109,6 @@ CPET_Hargreave_Grid::CPET_Hargreave_Grid(void)
CSG_Parameter *pNode;
//-----------------------------------------------------
- // 1. Info...
-
Set_Name (_TL("PET (after Hargreaves, Grid)"));
Set_Author ("O.Conrad (c) 2015");
@@ -131,8 +131,6 @@ CPET_Hargreave_Grid::CPET_Hargreave_Grid(void)
//-----------------------------------------------------
- // 2. Parameters...
-
Parameters.Add_Grid(NULL, "T" , _TL("Mean Temperature" ), _TL(""), PARAMETER_INPUT);
Parameters.Add_Grid(NULL, "T_MIN", _TL("Minimum Temperature" ), _TL(""), PARAMETER_INPUT);
Parameters.Add_Grid(NULL, "T_MAX", _TL("Maximum Temperature" ), _TL(""), PARAMETER_INPUT);
@@ -156,16 +154,13 @@ CPET_Hargreave_Grid::CPET_Hargreave_Grid(void)
Parameters.Add_Choice(
pNode , "MONTH" , _TL("Month"),
_TL(""),
- CSG_String::Format(SG_T("%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|"),
- _TL("January"), _TL("February"), _TL("March" ), _TL("April" ), _TL("May" ), _TL("June" ),
- _TL("July" ), _TL("August" ), _TL("September"), _TL("October"), _TL("November"), _TL("December")
- ), 2
+ CSG_DateTime::Get_Month_Choices(), CSG_DateTime::Get_Current_Month()
);
Parameters.Add_Value(
pNode , "DAY" , _TL("Day of Month"),
_TL(""),
- PARAMETER_TYPE_Int, 21, 1, true, 31, true
+ PARAMETER_TYPE_Int, CSG_DateTime::Get_Current_Day(), 1, true, 31, true
);
}
@@ -229,8 +224,15 @@ bool CPET_Hargreave_Grid::On_Execute(void)
}
//-----------------------------------------------------
- int Mon = Parameters("TIME")->asInt() == 0 ? -1 : DaysCount[Parameters("MONTH")->asInt()];
- int Day = DaysBefore[Parameters("MONTH")->asInt()] + Mon < 0 ? Parameters("DAY")->asInt() : Mon / 2;
+ int bDaily = Parameters("TIME")->asInt() == 0;
+
+ CSG_DateTime Date(
+ (CSG_DateTime::TSG_DateTime)(bDaily ? Parameters("DAY")->asInt() : 15),
+ (CSG_DateTime::Month)Parameters("MONTH")->asInt()
+ );
+
+ int Day = Date.Get_DayOfYear();
+ int nDays = Date.Get_NumberOfDays(Parameters("MONTH")->asInt());
double R0_const = Get_Radiation_TopOfAtmosphere(Day, Parameters("LAT")->asDouble() * M_DEG_TO_RAD);
@@ -252,7 +254,7 @@ bool CPET_Hargreave_Grid::On_Execute(void)
pTmax->asDouble(x, y)
);
- pPET->Set_Value(x, y, Mon < 0 ? PET : PET * Mon);
+ pPET->Set_Value(x, y, bDaily ? PET : PET * nDays);
}
}
}
@@ -274,8 +276,6 @@ CPET_Hargreave_Table::CPET_Hargreave_Table(void)
CSG_Parameter *pNode;
//-----------------------------------------------------
- // 1. Info...
-
Set_Name (_TL("PET (after Hargreaves, Table)"));
Set_Author ("O.Conrad (c) 2011");
@@ -297,8 +297,6 @@ CPET_Hargreave_Table::CPET_Hargreave_Table(void)
//-----------------------------------------------------
- // 2. Parameters...
-
pNode = Parameters.Add_Table(
NULL , "TABLE" , _TL("Data"),
_TL(""),
@@ -394,8 +392,6 @@ CPET_Day_To_Hour::CPET_Day_To_Hour(void)
CSG_Parameter *pNode;
//-----------------------------------------------------
- // 1. Info...
-
Set_Name (_TL("Daily to Hourly PET"));
Set_Author ("O.Conrad (c) 2011");
@@ -410,8 +406,6 @@ CPET_Day_To_Hour::CPET_Day_To_Hour(void)
//-----------------------------------------------------
- // 2. Parameters...
-
pNode = Parameters.Add_Table(
NULL , "DAYS" , _TL("Daily Data"),
_TL(""),
diff --git a/src/modules/db/db_odbc/odbc.cpp b/src/modules/db/db_odbc/odbc.cpp
index f2f66d2..36c979d 100644
--- a/src/modules/db/db_odbc/odbc.cpp
+++ b/src/modules/db/db_odbc/odbc.cpp
@@ -1457,34 +1457,11 @@ int CSG_ODBC_Connections::Get_Connections(CSG_String &Connections)
//---------------------------------------------------------
CSG_ODBC_Module::CSG_ODBC_Module(void)
{
- if( !SG_UI_Get_Window_Main() )
- {
- Parameters.Add_String(
- NULL , "ODBC_DSN" , _TL("DSN"),
- _TL("Data Source Name"),
- SG_T("")
- );
+ Parameters.Add_String(NULL, "ODBC_DSN" , _TL("DSN" ), _TL("Data Source Name" ), "")->Set_UseInGUI(false);
+ Parameters.Add_String(NULL, "ODBC_USR" , _TL("User" ), _TL("User Name" ), "")->Set_UseInGUI(false);
+ Parameters.Add_String(NULL, "ODBC_PWD" , _TL("Password" ), _TL("Password" ), "")->Set_UseInGUI(false);
- Parameters.Add_String(
- NULL , "ODBC_USR" , _TL("User"),
- _TL("User Name"),
- SG_T("")
- );
-
- Parameters.Add_String(
- NULL , "ODBC_PWD" , _TL("Password"),
- _TL("Password"),
- SG_T("")
- );
- }
- else
- {
- Parameters.Add_Choice(
- NULL , "CONNECTION" , _TL("Server Connection"),
- _TL(""),
- ""
- );
- }
+ Parameters.Add_Choice(NULL, "CONNECTION", _TL("Server Connection"), _TL("Server Connection"), "")->Set_UseInCMD(false);
m_pConnection = NULL;
}
diff --git a/src/modules/db/db_pgsql/MLB_Interface.cpp b/src/modules/db/db_pgsql/MLB_Interface.cpp
index 75ace8b..6be9990 100644
--- a/src/modules/db/db_pgsql/MLB_Interface.cpp
+++ b/src/modules/db/db_pgsql/MLB_Interface.cpp
@@ -128,9 +128,13 @@ CSG_Module * Create_Module(int i)
case 22: return( new CShapes_SRID_Update );
case 30: return( new CRaster_Load );
+ case 33: return( new CRaster_Load_Band );
case 31: return( new CRaster_Save );
case 32: return( new CRaster_SRID_Update );
+ case 35: return( new CDatabase_Create );
+ case 36: return( new CDatabase_Destroy );
+
case 40: return( NULL );
default: return( MLB_INTERFACE_SKIP_MODULE );
}
diff --git a/src/modules/db/db_pgsql/db_pgsql.cpp b/src/modules/db/db_pgsql/db_pgsql.cpp
index 6c3d9d2..d805574 100644
--- a/src/modules/db/db_pgsql/db_pgsql.cpp
+++ b/src/modules/db/db_pgsql/db_pgsql.cpp
@@ -133,6 +133,14 @@ void _Error_Message(PGconn *pConnection)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
+CSG_PG_Connection::CSG_PG_Connection(void)
+{
+ m_bTransaction = false;
+
+ m_pConnection = NULL;
+}
+
+//---------------------------------------------------------
CSG_PG_Connection::CSG_PG_Connection(const CSG_String &Host, int Port, const CSG_String &Name, const CSG_String &User, const CSG_String &Password, bool bAutoCommit)
{
Create(Host, Port, Name, User, Password, bAutoCommit);
@@ -142,7 +150,9 @@ bool CSG_PG_Connection::Create(const CSG_String &Host, int Port, const CSG_Strin
{
m_bTransaction = false;
- m_pConnection = PQsetdbLogin(Host, CSG_String::Format(SG_T("%d"), Port), NULL, NULL, Name, User, Password);
+ m_pConnection = Name.is_Empty()
+ ? PQsetdbLogin(Host, CSG_String::Format("%d", Port), NULL, NULL, NULL, User, Password)
+ : PQsetdbLogin(Host, CSG_String::Format("%d", Port), NULL, NULL, Name, User, Password);
if( PQstatus(m_pgConnection) != CONNECTION_OK )
{
@@ -271,9 +281,16 @@ void CSG_PG_Connection::GUI_Update(void) const
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-CSG_String CSG_PG_Connection::Get_Connection(void) const
+CSG_String CSG_PG_Connection::Get_Connection(int Style) const
{
- return( Get_DBName() + " [" + Get_Host() + ":" + Get_Port() + "]" );
+ switch( Style )
+ {
+ default: return( Get_DBName() + " [" + Get_Host() + ":" + Get_Port() + "]" );
+
+ case 1: return( Get_DBName() );
+
+ case 2: return( "PGSQL:" + Get_Host() + ":" + Get_Port() + ":" + Get_DBName() );
+ }
}
//---------------------------------------------------------
@@ -344,7 +361,7 @@ bool CSG_PG_Connection::has_PostGIS(double minVersion)
CSG_Table t;
return( _Table_Load(t, "SELECT PostGIS_Lib_Version()", "") && t.Get_Count() == 1 && t.Get_Field_Count() == 1
- && 0.0001 * t[0][0].asDouble() >= minVersion
+ && t[0][0].asDouble() >= minVersion
);
}
@@ -354,6 +371,37 @@ bool CSG_PG_Connection::has_PostGIS(double minVersion)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
+CSG_MetaData & CSG_PG_Connection::Add_MetaData(CSG_Data_Object &Object, const CSG_String &Table, const CSG_String &Select)
+{
+ CSG_String Name(Object.Get_Name());
+ Object.Set_File_Name(Get_Connection(2) + ":" + Table);
+ Object.Set_Name(Name);
+
+ CSG_MetaData &DB = Object.Get_MetaData_DB();
+
+ DB.Del_Children();
+
+ DB.Add_Child("DBMS" , "PostgreSQL");
+ DB.Add_Child("HOST" , Get_Host ());
+ DB.Add_Child("PORT" , Get_Port ());
+ DB.Add_Child("USER" , Get_User ());
+ DB.Add_Child("NAME" , Get_DBName ());
+ DB.Add_Child("TABLE", Table);
+
+ if( !Select.is_Empty() )
+ {
+ DB.Add_Child("SELECT", Select);
+ }
+
+ return( DB );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
int CSG_PG_Connection::Get_Tables(CSG_Strings &Tables) const
{
Tables.Clear();
@@ -801,7 +849,20 @@ bool CSG_PG_Connection::Table_Insert(const CSG_String &Table_Name, const CSG_Tab
}
else
{
- sprintf(Values[iField], "%s", CSG_String(pRecord->asString(iField)).b_str());
+ CSG_String Value = pRecord->asString(iField);
+
+ if( 0 && Table.Get_Field_Type(iField) == SG_DATATYPE_String )
+ {
+ char *s = NULL; Value.to_ASCII(&s);
+
+ sprintf(Values[iField], "%s", s ? s : '\0');
+
+ SG_FREE_SAFE(s);
+ }
+ else
+ {
+ sprintf(Values[iField], "%s", Value.b_str());
+ }
paramValues [iField] = Values[iField];
}
@@ -860,6 +921,8 @@ bool CSG_PG_Connection::Table_Save(const CSG_String &Table_Name, const CSG_Table
}
//-----------------------------------------------------
+ Add_MetaData(*((CSG_Table *)&Table), Table_Name);
+
return( true );
}
@@ -955,7 +1018,14 @@ bool CSG_PG_Connection::_Table_Load(CSG_Table &Table, void *_pResult) const
//---------------------------------------------------------
bool CSG_PG_Connection::Table_Load(CSG_Table &Table, const CSG_String &Table_Name)
{
- return( _Table_Load(Table, CSG_String::Format(SG_T("SELECT * FROM \"%s\""), Table_Name.c_str()), Table_Name) );
+ if( _Table_Load(Table, CSG_String::Format(SG_T("SELECT * FROM \"%s\""), Table_Name.c_str()), Table_Name) )
+ {
+ Add_MetaData(Table, Table_Name);
+
+ return( true );
+ }
+
+ return( false );
}
//---------------------------------------------------------
@@ -985,7 +1055,14 @@ bool CSG_PG_Connection::Table_Load(CSG_Table &Table, const CSG_String &Tables, c
Select += SG_T(" ORDER BY ") + Order;
}
- return( _Table_Load(Table, Select, Table.Get_Name()) );
+ if( _Table_Load(Table, Select, Table.Get_Name()) )
+ {
+ Add_MetaData(Table, Table.Get_Name(), Select);
+
+ return( true );
+ }
+
+ return( false );
}
@@ -1028,7 +1105,14 @@ bool CSG_PG_Connection::Shapes_Load(CSG_Shapes *pShapes, const CSG_String &Name)
Fields += (bBinary ? "ST_AsBinary(" : "ST_AsText(") + Geometry + ") AS __geometry__";
- return( Shapes_Load(pShapes, Name, "SELECT " + Fields + " FROM \"" + Name + "\"", "__geometry__", bBinary, SRID) );
+ if( Shapes_Load(pShapes, Name, "SELECT " + Fields + " FROM \"" + Name + "\"", "__geometry__", bBinary, SRID) )
+ {
+ Add_MetaData(*pShapes, Name);
+
+ return( true );
+ }
+
+ return( false );
}
//---------------------------------------------------------
@@ -1168,6 +1252,8 @@ bool CSG_PG_Connection::Shapes_Load(CSG_Shapes *pShapes, const CSG_String &Name,
//-----------------------------------------------------
PQclear(pResult);
+ Add_MetaData(*pShapes, Name, Select);
+
return( true );
}
@@ -1177,30 +1263,31 @@ bool CSG_PG_Connection::Shapes_Load(CSG_Shapes *pShapes, const CSG_String &Name,
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-bool CSG_PG_Connection::Raster_Load(const CSG_String &Table, const CSG_String &Where, const CSG_String &Order, const CSG_String &Names, CSG_Parameter_Grid_List *pList)
+bool CSG_PG_Connection::_Raster_Open(CSG_Table &Info, const CSG_String &Table, const CSG_String &Where, const CSG_String &Order, bool bBinary)
{
- CSG_Table Info;
-
+ //-----------------------------------------------------
if( !Table_Load(Info, "raster_columns", "*", CSG_String("r_table_name = '") + Table + "'") || Info.Get_Count() != 1 )
{
+ SG_UI_Msg_Add_Error(CSG_String::Format("[PostGIS] %s (%s)", _TL("could not access table"), SG_T("raster_columns")));
+
return( false );
}
- CSG_String Geometry = Info[0].asString("r_raster_column");
+ CSG_String Field = Info[0].asString("r_raster_column");
//-----------------------------------------------------
- if( Names.is_Empty() || !Table_Load(Info, Table, Names, Where, "", "", Order) )
+ if( !Table_Load(Info, Table, "rid, name", Where, "", "", Order) )
{
- Info.Destroy();
+ SG_UI_Msg_Add_Error(CSG_String::Format("[PostGIS] %s (%s)", _TL("could not access raster table"), Table.c_str()));
+
+ return( false );
}
//-----------------------------------------------------
- bool bBinary = true;
+ CSG_String Select = "COPY (SELECT ST_AsBinary(\"" + Field + "\") AS rastbin FROM \"" + Table + "\"";
- CSG_String Select = "COPY (SELECT ST_AsBinary(\"" + Geometry + "\") AS rastbin FROM \"" + Table + "\"";
-
- if( Where.Length() ) Select += SG_T(" WHERE ") + Where;
- if( Order.Length() ) Select += SG_T(" ORDER BY ") + Order;
+ if( Where.Length() ) Select += " WHERE " + Where;
+ if( Order.Length() ) Select += " ORDER BY " + Order;
Select += ") TO STDOUT"; if( bBinary ) Select += " WITH (FORMAT 'binary')";
@@ -1216,72 +1303,116 @@ bool CSG_PG_Connection::Raster_Load(const CSG_String &Table, const CSG_String &W
return( false );
}
+ PQclear(pResult);
+
+ return( true );
+}
+
+//---------------------------------------------------------
+bool CSG_PG_Connection::_Raster_Load(CSG_Grid *pGrid, bool bFirst, bool bBinary)
+{
//-----------------------------------------------------
char *Bytes;
- int nBytes, nOkay, iBand;
+ int nBytes;
- for(iBand=0, nOkay=0; SG_UI_Process_Get_Okay() && (nBytes = PQgetCopyData(m_pgConnection, &Bytes, 0)) > 0; iBand++)
+ if( (nBytes = PQgetCopyData(m_pgConnection, &Bytes, 0)) <= 0 )
{
- CSG_Bytes Band;
+ return( false );
+ }
- if( bBinary )
- {
- int Offset = iBand == 0 ? 25 : 6;
+ //-----------------------------------------------------
+ CSG_Bytes Band;
- if( *((short *)Bytes) > 0 && nBytes > Offset )
- {
- Band.Create((BYTE *)(Bytes + Offset), nBytes - Offset);
- }
- }
- else if( nBytes > 3 )
+ if( bBinary )
+ {
+ int Offset = bFirst ? 25 : 6;
+
+ if( *((short *)Bytes) > 0 && nBytes > Offset )
{
- Band.fromHexString(Bytes + 3);
+ Band.Create((BYTE *)(Bytes + Offset), nBytes - Offset);
}
+ }
+ else if( nBytes > 3 )
+ {
+ Band.fromHexString(Bytes + 3);
+ }
- PQfreemem(Bytes);
+ PQfreemem(Bytes);
- //-------------------------------------------------
+ return( Band.Get_Count() > 0 && CSG_Grid_OGIS_Converter::from_WKBinary(Band, pGrid) );
+}
+
+//---------------------------------------------------------
+bool CSG_PG_Connection::Raster_Load(CSG_Parameter_Grid_List *pGrids, const CSG_String &Table, const CSG_String &Where, const CSG_String &Order)
+{
+ //-----------------------------------------------------
+ bool bBinary = true;
+
+ CSG_Table Info;
+
+ if( !_Raster_Open(Info, Table, Where, Order, bBinary) )
+ {
+ return( false );
+ }
+
+ //-----------------------------------------------------
+ for(int iBand=0; iBand<Info.Get_Count() && SG_UI_Process_Get_Okay(); iBand++)
+ {
CSG_Grid *pGrid = SG_Create_Grid();
- if( Band.Get_Count() > 0 && CSG_Grid_OGIS_Converter::from_WKBinary(Band, pGrid) )
+ if( !_Raster_Load(pGrid, iBand == 0, bBinary) )
{
- if( iBand < Info.Get_Count() )
- {
- pGrid->Set_Name(CSG_String::Format(SG_T("%s [%s]" ), Table.c_str(), Info[iBand].asString(0)));
- }
- else
- {
- pGrid->Set_Name(CSG_String::Format(SG_T("%s [%02d]"), Table.c_str(), iBand + 1));
- }
+ delete(pGrid);
+
+ return( false );
+ }
+ else
+ {
+ pGrid->Set_Name(Table + " [" + Info[iBand].asString(1) + "]");
+
+ Add_MetaData(*pGrid, Table + CSG_String::Format(":rid=%d", Info[iBand].asInt(0)));
SG_Get_Data_Manager().Add(pGrid);
- if( pList )
+ if( pGrids )
{
- pList->Add_Item(pGrid);
+ pGrids->Add_Item(pGrid);
}
-
- nOkay++;
- }
- else
- {
- delete(pGrid);
}
}
//-----------------------------------------------------
- PQclear(pResult);
+ return( true );
+}
- return( nOkay > 0 );
+//---------------------------------------------------------
+bool CSG_PG_Connection::Raster_Load(CSG_Grid *pGrid, const CSG_String &Table, const CSG_String &Where)
+{
+ CSG_Table Info;
+
+ if( _Raster_Open(Info, Table, Where) && _Raster_Load(pGrid, true) )
+ {
+ pGrid->Set_Name(Table + " [" + Info[0].asString(1) + "]");
+
+ Add_MetaData(*pGrid, Table + CSG_String::Format(":rid=%d", Info[0].asInt(0)));
+
+ SG_Get_Data_Manager().Add(pGrid);
+
+ return( true );
+ }
+
+ return( false );
}
//---------------------------------------------------------
-bool CSG_PG_Connection::Raster_Save(CSG_Grid *pGrid, int SRID, const CSG_String &Table, const CSG_String &Field)
+bool CSG_PG_Connection::Raster_Save(CSG_Grid *pGrid, int SRID, const CSG_String &Table, const CSG_String &Name)
{
CSG_Table Info;
- if( !Table_Load(Info, "raster_columns", "*", CSG_String("r_table_name = '") + Table + "'") || Info.Get_Count() != 1 )
+ if( !pGrid || !Table_Load(Info, "raster_columns", "*", CSG_String("r_table_name = '") + Table + "'") || Info.Get_Count() != 1 )
{
+ SG_UI_Msg_Add_Error(CSG_String::Format("[PostGIS] %s (%s)", _TL("could not access table"), SG_T("raster_columns")));
+
return( false );
}
@@ -1304,6 +1435,8 @@ bool CSG_PG_Connection::Raster_Save(CSG_Grid *pGrid, int SRID, const CSG_String
return( false );
}
+ PQclear(pResult);
+
//-----------------------------------------------------
CSG_Bytes Band;
@@ -1324,7 +1457,19 @@ bool CSG_PG_Connection::Raster_Save(CSG_Grid *pGrid, int SRID, const CSG_String
}
//-----------------------------------------------------
- PQclear(pResult);
+ Table_Load(Info, Table, "rid"); // CSG_String::Format("SELECT currval('%s_rid_seq')", Table.c_str()));
+
+ int rid = Info[Info.Get_Count() - 1].asInt(0);
+
+ //-----------------------------------------------------
+ Info = Get_Field_Desc(Table);
+
+ if( !Name.is_Empty() && Info.Get_Count() > 2 && !SG_STR_CMP("varchar", Info[2].asString(1)) )
+ {
+ Execute(CSG_String::Format("UPDATE %s SET %s='%s' WHERE rid=%d", Table.c_str(), Info[2].asString(0), Name.c_str(), rid));
+ }
+
+ Add_MetaData(*pGrid, Table + CSG_String::Format(":rid=%d", rid));
return( true );
}
@@ -1551,46 +1696,41 @@ int CSG_PG_Connections::Get_Connections(CSG_String &Connections)
//---------------------------------------------------------
CSG_PG_Module::CSG_PG_Module(void)
{
- if( !SG_UI_Get_Window_Main() )
- {
- Parameters.Add_String(
- NULL , "PG_HOST" , _TL("Host"),
- _TL("Password"),
- SG_T("")
- );
-
- Parameters.Add_Value(
- NULL , "PG_PORT" , _TL("Port"),
- _TL(""),
- PARAMETER_TYPE_Int, 5432, 0, true
- );
-
- Parameters.Add_String(
- NULL , "PG_NAME" , _TL("Database"),
- _TL("Database Name"),
- SG_T("")
- );
-
- Parameters.Add_String(
- NULL , "PG_USER" , _TL("User"),
- _TL("User Name"),
- SG_T("")
- );
+ Parameters.Add_String(
+ NULL , "PG_HOST" , _TL("Host"),
+ _TL("Password"),
+ ""
+ )->Set_UseInGUI(false);
- Parameters.Add_String(
- NULL , "PG_PWD" , _TL("Password"),
- _TL("Password"),
- SG_T("")
- );
- }
- else
- {
- Parameters.Add_Choice(
- NULL , "CONNECTION", _TL("Available Connections"),
- _TL(""),
- ""
- );
- }
+ Parameters.Add_Value(
+ NULL , "PG_PORT" , _TL("Port"),
+ _TL(""),
+ PARAMETER_TYPE_Int, 5432, 0, true
+ )->Set_UseInGUI(false);
+
+ Parameters.Add_String(
+ NULL , "PG_NAME" , _TL("Database"),
+ _TL("Database Name"),
+ ""
+ )->Set_UseInGUI(false);
+
+ Parameters.Add_String(
+ NULL , "PG_USER" , _TL("User"),
+ _TL("User Name"),
+ ""
+ )->Set_UseInGUI(false);
+
+ Parameters.Add_String(
+ NULL , "PG_PWD" , _TL("Password"),
+ _TL("Password"),
+ ""
+ )->Set_UseInGUI(false);
+
+ Parameters.Add_Choice(
+ NULL , "CONNECTION" , _TL("Available Connections"),
+ _TL(""),
+ ""
+ )->Set_UseInCMD(false);
m_pConnection = NULL;
}
diff --git a/src/modules/db/db_pgsql/db_pgsql.h b/src/modules/db/db_pgsql/db_pgsql.h
index 1f2c90f..dbf1c35 100644
--- a/src/modules/db/db_pgsql/db_pgsql.h
+++ b/src/modules/db/db_pgsql/db_pgsql.h
@@ -91,6 +91,15 @@ class db_pgsql_EXPORT CSG_PG_Connection
public:
+ CSG_PG_Connection (void);
+
+ CSG_PG_Connection (const CSG_String &Host, int Port, const CSG_String &Name, const CSG_String &User, const CSG_String &Password, bool bAutoCommit = false);
+ bool Create (const CSG_String &Host, int Port, const CSG_String &Name, const CSG_String &User, const CSG_String &Password, bool bAutoCommit = false);
+
+ virtual ~CSG_PG_Connection(void);
+
+ bool Destroy (void);
+
static CSG_String Get_Type_To_SQL (TSG_Data_Type Type, int Size = 0);
static TSG_Data_Type Get_Type_From_SQL (int Type);
static CSG_String Get_Raster_Type_To_SQL (TSG_Data_Type Type);
@@ -99,7 +108,7 @@ public:
bool is_Connected (void) const { return( m_pConnection != NULL ); }
- CSG_String Get_Connection (void) const;
+ CSG_String Get_Connection (int Style = 0) const;
CSG_String Get_Host (void) const;
CSG_String Get_Port (void) const;
@@ -123,6 +132,8 @@ public:
bool Commit (const CSG_String &SavePoint = "");
bool is_Transaction (void) const { return( is_Connected() && m_bTransaction ); }
+ CSG_MetaData & Add_MetaData (CSG_Data_Object &Object, const CSG_String &Table, const CSG_String &Select = "");
+
bool Table_Exists (const CSG_String &Table_Name) const;
bool Table_Create (const CSG_String &Table_Name, const CSG_Table &Table, const CSG_Buffer &Flags = 0, bool bCommit = true);
@@ -136,22 +147,13 @@ public:
bool Shapes_Load (CSG_Shapes *pShapes, const CSG_String &Table);
bool Shapes_Load (CSG_Shapes *pShapes, const CSG_String &Name, const CSG_String &Select, const CSG_String &Geometry_Field, bool bBinary, int SRID = -1);
- bool Raster_Load (const CSG_String &Table, const CSG_String &Where = "", const CSG_String &Order = "", const CSG_String &Names = "", CSG_Parameter_Grid_List *pList = NULL);
+ bool Raster_Load (CSG_Parameter_Grid_List *pGrids , const CSG_String &Table, const CSG_String &Where = "", const CSG_String &Order = "");
+ bool Raster_Load (CSG_Grid *pGrid , const CSG_String &Table, const CSG_String &Where = "");
bool Raster_Save (CSG_Grid *pGrid, int SRID, const CSG_String &Table, const CSG_String &Field);
private:
- CSG_PG_Connection (const CSG_String &Host, int Port, const CSG_String &Name, const CSG_String &User, const CSG_String &Password, bool bAutoCommit = false);
- bool Create (const CSG_String &Host, int Port, const CSG_String &Name, const CSG_String &User, const CSG_String &Password, bool bAutoCommit = false);
-
- virtual ~CSG_PG_Connection(void);
-
- bool Destroy (void);
-
-
-private:
-
void *m_pConnection;
bool m_bTransaction;
@@ -160,6 +162,9 @@ private:
bool _Table_Load (CSG_Table &Data, const CSG_String &Select, const CSG_String &Name = "") const;
bool _Table_Load (CSG_Table &Data, void *pResult) const;
+ bool _Raster_Open (CSG_Table &Info, const CSG_String &Table, const CSG_String &Where = "", const CSG_String &Order = "", bool bBinary = true);
+ bool _Raster_Load (CSG_Grid *pGrid, bool bFirst, bool bBinary = true);
+
};
diff --git a/src/modules/db/db_pgsql/get_connection.cpp b/src/modules/db/db_pgsql/get_connection.cpp
index ebca6dc..86d2c4d 100644
--- a/src/modules/db/db_pgsql/get_connection.cpp
+++ b/src/modules/db/db_pgsql/get_connection.cpp
@@ -581,3 +581,178 @@ bool CExecute_SQL::On_Execute(void)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
+CDatabase_Create::CDatabase_Create(void)
+{
+ Set_Name (_TL("Create Database"));
+
+ Set_Author (SG_T("O.Conrad (c) 2015"));
+
+ Set_Description (_TW(
+ "Creates a new PostgreSQL Database."
+ ));
+
+ Parameters.Add_String(
+ NULL , "PG_HOST" , _TL("Host"),
+ _TL("Password"),
+ "localhost"
+ );
+
+ Parameters.Add_Value(
+ NULL , "PG_PORT" , _TL("Port"),
+ _TL(""),
+ PARAMETER_TYPE_Int, 5432, 0, true
+ );
+
+ Parameters.Add_String(
+ NULL , "PG_NAME" , _TL("Database"),
+ _TL("Database Name"),
+ "geo_test"
+ );
+
+ Parameters.Add_String(
+ NULL , "PG_USER" , _TL("User"),
+ _TL("User Name"),
+ "postgres"
+ );
+
+ Parameters.Add_String(
+ NULL , "PG_PWD" , _TL("Password"),
+ _TL("Password"),
+ "postgres", false, true
+ );
+}
+
+//---------------------------------------------------------
+bool CDatabase_Create::On_Execute(void)
+{
+ const SG_Char *Host, *Name, *User, *Password;
+
+ Host = Parameters("PG_HOST")->asString();
+ int Port = Parameters("PG_PORT")->asInt();
+ Name = Parameters("PG_NAME")->asString(),
+ User = Parameters("PG_USER")->asString();
+ Password = Parameters("PG_PWD" )->asString();
+
+ if( SG_PG_Get_Connection_Manager().Get_Connection(CSG_String::Format("%s [%s:%d]", Name, Host, Port)) )
+ {
+ Message_Add(CSG_String::Format("%s [%s:%d]: %s", Name, Host, Port, _TL("PostgreSQL database is already connected")));
+
+ return( false );
+ }
+
+ CSG_PG_Connection Connection;
+
+ if( Connection.Create(Host, Port, "", User, Password) && Connection.Execute(CSG_String::Format("CREATE DATABASE %s", Name)) )
+ {
+ CSG_PG_Connection *pConnection = SG_PG_Get_Connection_Manager().Add_Connection(Name, User, Password, Host, Port);
+
+ if( pConnection )
+ {
+ if( pConnection->Execute("CREATE EXTENSION postgis") )
+ {
+ Message_Add(CSG_String::Format("%s [%s:%d]: %s", Name, Host, Port, _TL("PostGIS extension added")));
+ }
+
+ pConnection->GUI_Update();
+
+ return( true );
+ }
+ }
+
+ Message_Add(CSG_String::Format("%s [%s:%d]: %s", Name, Host, Port, _TL("could not create new PostgreSQL database")));
+
+ return( false );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+CDatabase_Destroy::CDatabase_Destroy(void)
+{
+ Set_Name (_TL("Drop Database"));
+
+ Set_Author (SG_T("O.Conrad (c) 2015"));
+
+ Set_Description (_TW(
+ "Deletes a PostgreSQL Database."
+ ));
+
+ Parameters.Add_String(
+ NULL , "PG_HOST" , _TL("Host"),
+ _TL("Password"),
+ "localhost"
+ );
+
+ Parameters.Add_Value(
+ NULL , "PG_PORT" , _TL("Port"),
+ _TL(""),
+ PARAMETER_TYPE_Int, 5432, 0, true
+ );
+
+ Parameters.Add_String(
+ NULL , "PG_NAME" , _TL("Database"),
+ _TL("Database Name"),
+ "geo_test"
+ );
+
+ Parameters.Add_String(
+ NULL , "PG_USER" , _TL("User"),
+ _TL("User Name"),
+ "postgres"
+ );
+
+ Parameters.Add_String(
+ NULL , "PG_PWD" , _TL("Password"),
+ _TL("Password"),
+ "postgres", false, true
+ );
+}
+
+//---------------------------------------------------------
+bool CDatabase_Destroy::On_Execute(void)
+{
+ const SG_Char *Host, *Name, *User, *Password;
+
+ Host = Parameters("PG_HOST")->asString();
+ int Port = Parameters("PG_PORT")->asInt();
+ Name = Parameters("PG_NAME")->asString(),
+ User = Parameters("PG_USER")->asString();
+ Password = Parameters("PG_PWD" )->asString();
+
+ if( SG_PG_Get_Connection_Manager().Get_Connection(CSG_String::Format("%s [%s:%d]", Name, Host, Port)) )
+ {
+ if( !SG_PG_Get_Connection_Manager().Del_Connection(CSG_String::Format("%s [%s:%d]", Name, Host, Port), false) )
+ {
+ Message_Add(CSG_String::Format("%s [%s:%d]: %s", Name, Host, Port, _TL("could not disconnect and drop PostgreSQL database")));
+
+ return( false );
+ }
+ }
+
+ CSG_PG_Connection Connection;
+
+ if( Connection.Create(Host, Port, "", User, Password) && Connection.Execute(CSG_String::Format("DROP DATABASE IF EXISTS %s", Name)) )
+ {
+ SG_UI_ODBC_Update("");
+
+ return( true );
+ }
+
+ Message_Add(CSG_String::Format("%s [%s:%d]: %s", Name, Host, Port, _TL("could not drop PostgreSQL database")));
+
+ return( false );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
diff --git a/src/modules/db/db_pgsql/get_connection.h b/src/modules/db/db_pgsql/get_connection.h
index 1d38953..fbfe637 100644
--- a/src/modules/db/db_pgsql/get_connection.h
+++ b/src/modules/db/db_pgsql/get_connection.h
@@ -217,6 +217,46 @@ protected:
///////////////////////////////////////////////////////////
// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+class CDatabase_Create : public CSG_Module
+{
+public:
+ CDatabase_Create(void);
+
+ virtual CSG_String Get_MenuPath (void) { return( SG_T("R:Tools") ); }
+
+
+protected:
+
+ virtual bool On_Execute (void);
+
+};
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+class CDatabase_Destroy : public CSG_Module
+{
+public:
+ CDatabase_Destroy(void);
+
+ virtual CSG_String Get_MenuPath (void) { return( SG_T("R:Tools") ); }
+
+
+protected:
+
+ virtual bool On_Execute (void);
+
+};
+
+
+///////////////////////////////////////////////////////////
+// //
// //
// //
///////////////////////////////////////////////////////////
diff --git a/src/modules/db/db_pgsql/pgis_raster.cpp b/src/modules/db/db_pgsql/pgis_raster.cpp
index 972de58..127caba 100644
--- a/src/modules/db/db_pgsql/pgis_raster.cpp
+++ b/src/modules/db/db_pgsql/pgis_raster.cpp
@@ -90,6 +90,12 @@ CRaster_Load::CRaster_Load(void)
_TL(""),
""
);
+
+ Parameters.Add_String(
+ NULL , "WHERE" , _TL("Where"),
+ _TL(""),
+ ""
+ );
}
//---------------------------------------------------------
@@ -118,7 +124,7 @@ bool CRaster_Load::On_Execute(void)
pGrids->Del_Items();
- if( !Get_Connection()->Raster_Load(Table, "", "", "", pGrids) )//, "rid=4") )
+ if( !Get_Connection()->Raster_Load(pGrids, Table, Parameters("WHERE")->asString()) )
{
return( false );
}
@@ -134,6 +140,127 @@ bool CRaster_Load::On_Execute(void)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
+CRaster_Load_Band::CRaster_Load_Band(void)
+{
+ Set_Name (_TL("Import Single Raster Band from PostGIS"));
+
+ Set_Author ("O.Conrad (c) 2015");
+
+ Set_Description (_TW(
+ "Imports grids from a PostGIS database."
+ ));
+
+ Parameters.Add_Grid_Output(
+ NULL , "GRID" , _TL("Grid"),
+ _TL("")
+ );
+
+ Parameters.Add_Choice(
+ NULL , "TABLES" , _TL("Tables"),
+ _TL(""),
+ ""
+ );
+
+ Parameters.Add_Choice(
+ NULL , "BANDS" , _TL("Bands"),
+ _TL(""),
+ ""
+ )->Set_UseInCMD(false);
+
+ Parameters.Add_String(
+ NULL , "RID" , _TL("Raster Band Identifier"),
+ _TL(""),
+ ""
+ )->Set_UseInGUI(false);
+}
+
+//---------------------------------------------------------
+void CRaster_Load_Band::On_Connection_Changed(CSG_Parameters *pParameters)
+{
+ CSG_String s;
+ CSG_Table t;
+
+ SG_UI_Progress_Lock(true); SG_UI_Msg_Lock(true);
+
+ if( Get_Connection()->Table_Load(t, "raster_columns") )
+ {
+ for(int i=0; i<t.Get_Count(); i++)
+ {
+ s += t[i].asString("r_table_name") + CSG_String("|");
+ }
+ }
+
+ SG_UI_Progress_Lock(false); SG_UI_Msg_Lock(false);
+
+ pParameters->Get_Parameter("TABLES")->asChoice()->Set_Items(s);
+
+ On_Parameter_Changed(pParameters, pParameters->Get_Parameter("TABLES"));
+}
+
+//---------------------------------------------------------
+int CRaster_Load_Band::On_Parameter_Changed(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
+{
+ if( !SG_STR_CMP(pParameter->Get_Identifier(), "TABLES") )
+ {
+ CSG_String s;
+ CSG_Table t;
+
+ SG_UI_Progress_Lock(true); SG_UI_Msg_Lock(true);
+
+ if( Get_Connection()->Table_Load(t, pParameter->asString(), "rid, name") )
+ {
+ for(int i=0; i<t.Get_Count(); i++)
+ {
+ s += CSG_String::Format("{%d}%s|", t[i].asInt(0), t[i].asString(1));
+ }
+ }
+
+ SG_UI_Progress_Lock(false); SG_UI_Msg_Lock(false);
+
+ pParameters->Get_Parameter("BANDS")->asChoice()->Set_Items(s);
+ }
+
+ return( CSG_PG_Module::On_Parameter_Changed(pParameters, pParameter) );
+}
+
+//---------------------------------------------------------
+bool CRaster_Load_Band::On_Execute(void)
+{
+ CSG_String Table = Parameters("TABLES")->asString(), Where;
+
+ CSG_Grid *pGrid = SG_Create_Grid();
+
+ if( !SG_UI_Get_Window_Main() || *Parameters("RID")->asString() )
+ {
+ Where.Printf("rid=%s", Parameters("RID")->asString());
+ }
+ else
+ {
+ Where.Printf("rid=%s", Parameters("BANDS")->asChoice()->Get_Item_Data(Parameters("BANDS")->asInt()).c_str());
+ }
+
+ if( !Get_Connection()->Raster_Load(pGrid, Table, Where) )
+ {
+ Error_Fmt("%s: %s (%s)", _TL("could not load raster"), Table.c_str(), Where.c_str());
+
+ delete(pGrid);
+
+ return( false );
+ }
+
+ Parameters("GRID")->Set_Value(pGrid);
+
+ return( true );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
CRaster_Save::CRaster_Save(void)
{
CSG_Parameter *pNode;
@@ -141,7 +268,7 @@ CRaster_Save::CRaster_Save(void)
//-----------------------------------------------------
Set_Name (_TL("Export Raster to PostGIS"));
- Set_Author (SG_T("O.Conrad (c) 2013"));
+ Set_Author ("O.Conrad (c) 2013");
Set_Description (_TW(
"Exports grids to a PostGIS database."
@@ -159,6 +286,12 @@ CRaster_Save::CRaster_Save(void)
PARAMETER_INPUT
);
+ Parameters.Add_Choice(
+ NULL , "TABLE" , _TL("Table"),
+ _TL(""),
+ ""
+ );
+
Parameters.Add_String(
NULL , "NAME" , _TL("Table Name"),
_TL(""),
@@ -175,11 +308,60 @@ CRaster_Save::CRaster_Save(void)
}
//---------------------------------------------------------
+void CRaster_Save::On_Connection_Changed(CSG_Parameters *pParameters)
+{
+ CSG_String s;
+ CSG_Table t;
+
+ if( Get_Connection()->Table_Load(t, "raster_columns") )
+ {
+ for(int i=0; i<t.Get_Count(); i++)
+ {
+ s += t[i].asString("r_table_name") + CSG_String("|");
+ }
+ }
+
+ s += _TL("<not set>") + CSG_String("|");
+
+ pParameters->Get_Parameter("TABLE")->asChoice()->Set_Items(s);
+ pParameters->Get_Parameter("TABLE")->Set_Value(t.Get_Count());
+}
+
+//---------------------------------------------------------
+int CRaster_Save::On_Parameter_Changed(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
+{
+ if( !SG_STR_CMP(pParameter->Get_Identifier(), "TABLE") )
+ {
+ bool bCreate = pParameter->asInt() >= pParameter->asChoice()->Get_Count() - 1;
+
+ pParameters->Set_Enabled("NAME" , bCreate);
+ pParameters->Set_Enabled("GRID_NAME", bCreate);
+ }
+
+ if( !SG_STR_CMP(pParameter->Get_Identifier(), "GRIDS") )
+ {
+ for(int i=0; i<pParameter->asList()->Get_Count(); i++)
+ {
+ CSG_Projection p = pParameter->asGridList()->asGrid(i)->Get_Projection();
+
+ if( p.is_Okay() && p.Get_EPSG() > 0 )
+ {
+ Set_SRID(pParameters, p.Get_EPSG());
+
+ break;
+ }
+ }
+ }
+
+ return( CSG_PG_Module::On_Parameter_Changed(pParameters, pParameter) );
+}
+
+//---------------------------------------------------------
bool CRaster_Save::On_Execute(void)
{
- if( !Get_Connection()->Table_Exists(SG_T("spatial_ref_sys")) || !Get_Connection()->Table_Exists(SG_T("geometry_columns")) )
+ if( !Get_Connection()->has_PostGIS(2.0) )
{
- SG_UI_Dlg_Message(_TL("Not a valid PostGIS database!"), _TL("Database Connection Error"));
+ Error_Set(_TL("PostGIS extension missing or too old"));
return( false );
}
@@ -187,21 +369,27 @@ bool CRaster_Save::On_Execute(void)
//-----------------------------------------------------
CSG_Parameter_Grid_List *pGrids = Parameters("GRIDS")->asGridList();
- CSG_String SavePoint, Name = Parameters("NAME")->asString();
+ CSG_String SavePoint, Table;
- if( Name.Length() == 0 )
- return( false );
+ Table = Parameters("TABLE")->asInt() < Parameters("TABLE")->asChoice()->Get_Count() - 1
+ ? Parameters("TABLE")->asString()
+ : Parameters("NAME" )->asString();
- bool bGridName = Parameters("GRID_NAME")->asBool();
+ if( Table.Length() == 0 )
+ {
+ Error_Set(_TL("no name has been specified for new raster table"));
+
+ return( false );
+ }
//-----------------------------------------------------
Get_Connection()->Begin(SavePoint = Get_Connection()->is_Transaction() ? "RASTER_SAVE" : "");
//-----------------------------------------------------
- if( !Get_Connection()->Table_Exists(Name) )
+ if( !Get_Connection()->Table_Exists(Table) )
{
- CSG_String SQL = "CREATE TABLE \"" + Name + "\" (\"rid\" serial PRIMARY KEY, \"raster\" raster"
- + (bGridName ? ", \"name\" varchar(64))" : ")");
+ CSG_String SQL = "CREATE TABLE \"" + Table + "\" (\"rid\" serial PRIMARY KEY, \"raster\" raster"
+ + (Parameters("GRID_NAME")->asBool() ? ", \"name\" varchar(64))" : ")");
if( !Get_Connection()->Execute(SQL) )
{
@@ -214,33 +402,33 @@ bool CRaster_Save::On_Execute(void)
//-----------------------------------------------------
for(int i=0; i<pGrids->Get_Count(); i++)
{
- CSG_Bytes WKB;
-
- Process_Set_Text(CSG_String::Format(SG_T("%s: %s [%d/%d]"), _TL("export grid"), pGrids->asGrid(i)->Get_Name(), i + 1, pGrids->Get_Count()));
+ Process_Set_Text(CSG_String::Format("%s: %s [%d/%d]", _TL("export grid"), pGrids->asGrid(i)->Get_Name(), i + 1, pGrids->Get_Count()));
- if( !bGridName )
+ if( !Get_Connection()->Raster_Save(pGrids->asGrid(i), Get_SRID(), Table, pGrids->asGrid(i)->Get_Name()) )
{
- if( !Get_Connection()->Raster_Save(pGrids->asGrid(i), Get_SRID(), Name, "") )
- {
- Get_Connection()->Rollback(SavePoint);
+ Get_Connection()->Rollback(SavePoint);
- return( false );
- }
+ return( false );
}
- else if( CSG_Grid_OGIS_Converter::to_WKBinary(WKB, pGrids->asGrid(i), Get_SRID()) )
- {
- CSG_String SQL = "INSERT INTO \"" + Name + "\" (\"raster\", \"name\") VALUES("
- + "ST_AddBand('" + WKB.toHexString() + "'::raster, '"
- + CSG_PG_Connection::Get_Raster_Type_To_SQL(pGrids->asGrid(i)->Get_Type()) + "'::text, 0, NULL), '"
- + pGrids->asGrid(i)->Get_Name() + "')";
- if( !Get_Connection()->Execute(SQL) )
- {
- Get_Connection()->Rollback(SavePoint);
+ //{
+ // CSG_Bytes WKB;
- return( false );
- }
- }
+ // if( CSG_Grid_OGIS_Converter::to_WKBinary(WKB, pGrids->asGrid(i), Get_SRID()) )
+ // {
+ // CSG_String SQL = "INSERT INTO \"" + Table + "\" (\"raster\", \"name\") VALUES("
+ // + "ST_AddBand('" + WKB.toHexString() + "'::raster, '"
+ // + CSG_PG_Connection::Get_Raster_Type_To_SQL(pGrids->asGrid(i)->Get_Type()) + "'::text, 0, NULL), '"
+ // + pGrids->asGrid(i)->Get_Name() + "')";
+
+ // if( !Get_Connection()->Execute(SQL) )
+ // {
+ // Get_Connection()->Rollback(SavePoint);
+
+ // return( false );
+ // }
+ // }
+ //}
}
//-----------------------------------------------------
diff --git a/src/modules/db/db_pgsql/pgis_raster.h b/src/modules/db/db_pgsql/pgis_raster.h
index 49c444a..cad1509 100644
--- a/src/modules/db/db_pgsql/pgis_raster.h
+++ b/src/modules/db/db_pgsql/pgis_raster.h
@@ -101,6 +101,31 @@ protected:
// //
///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+class CRaster_Load_Band : public CSG_PG_Module
+{
+public:
+ CRaster_Load_Band(void);
+
+ virtual CSG_String Get_MenuPath (void) { return( SG_T("R:Raster") ); }
+
+
+protected:
+
+ virtual void On_Connection_Changed (CSG_Parameters *pParameters);
+
+ virtual int On_Parameter_Changed (CSG_Parameters *pParameters, CSG_Parameter *pParameter);
+
+ virtual bool On_Execute (void);
+
+};
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
//---------------------------------------------------------
class CRaster_Save : public CSG_PG_Module
{
@@ -112,6 +137,10 @@ public:
protected:
+ virtual void On_Connection_Changed (CSG_Parameters *pParameters);
+
+ virtual int On_Parameter_Changed (CSG_Parameters *pParameters, CSG_Parameter *pParameter);
+
virtual bool On_Execute (void);
};
diff --git a/src/modules/db/db_pgsql/pgis_shapes.cpp b/src/modules/db/db_pgsql/pgis_shapes.cpp
index 859ad77..061ad40 100644
--- a/src/modules/db/db_pgsql/pgis_shapes.cpp
+++ b/src/modules/db/db_pgsql/pgis_shapes.cpp
@@ -309,7 +309,7 @@ bool CShapes_Save::On_Execute(void)
CSG_Shapes_OGIS_Converter::to_WKBinary(pShape, WKB);
- SQL += "ST_GeomFromWKB(E'\\\\x" + WKB.toHexString() + CSG_String::Format(SG_T("', %d)"), SRID);
+ SQL += "ST_GeomFromWKB(E'\\\\x" + WKB.toHexString() + CSG_String::Format("', %d)", SRID);
}
else
{
@@ -317,7 +317,7 @@ bool CShapes_Save::On_Execute(void)
CSG_Shapes_OGIS_Converter::to_WKText(pShape, WKT);
- SQL += "ST_GeomFromText('" + WKT + CSG_String::Format(SG_T("', %d)"), SRID);
+ SQL += "ST_GeomFromText('" + WKT + CSG_String::Format("', %d)", SRID);
}
for(iField=0; iField<pShapes->Get_Field_Count(); iField++)
@@ -326,14 +326,20 @@ bool CShapes_Save::On_Execute(void)
if( pShapes->Get_Field_Type(iField) == SG_DATATYPE_String )
{
- s.Replace(SG_T("'"), SG_T("\""));
- s = SG_T("'") + s + SG_T("'");
+ if( 1 )
+ {
+ char *_s = NULL; if( s.to_ASCII(&_s) ) s = _s; SG_FREE_SAFE(_s);
+ }
+
+ s.Replace("'", "\"");
+
+ s = "'" + s + "'";
}
- SQL += SG_T(", ") + s;
+ SQL += ", " + s;
}
- SQL += SG_T(")");
+ SQL += ")";
if( Get_Connection()->Execute(SQL) )
{
@@ -341,7 +347,7 @@ bool CShapes_Save::On_Execute(void)
}
else
{
- Message_Add(CSG_String::Format(SG_T("%s [%d/%d]"), _TL("could not save shape"), 1 + iShape, pShapes->Get_Count()));
+ Message_Add(CSG_String::Format("%s [%d/%d]", _TL("could not save shape"), 1 + iShape, pShapes->Get_Count()));
}
}
}
@@ -360,6 +366,10 @@ bool CShapes_Save::On_Execute(void)
Get_Connection()->GUI_Update();
+ Get_Connection()->Add_MetaData(*pShapes, Name);
+
+ pShapes->Set_Modified(false);
+
return( true );
}
diff --git a/src/modules/garden/garden_3d_viewer/3d_viewer_pointcloud.cpp b/src/modules/garden/garden_3d_viewer/3d_viewer_pointcloud.cpp
index 37ba705..2f73c8a 100644
--- a/src/modules/garden/garden_3d_viewer/3d_viewer_pointcloud.cpp
+++ b/src/modules/garden/garden_3d_viewer/3d_viewer_pointcloud.cpp
@@ -923,13 +923,6 @@ C3D_Viewer_PointCloud::C3D_Viewer_PointCloud(void)
//---------------------------------------------------------
bool C3D_Viewer_PointCloud::On_Execute(void)
{
- if( !SG_UI_Get_Window_Main() )
- {
- Message_Add(_TL("point cloud viewer can only be run from graphical user interface"));
-
- return( false );
- }
-
CSG_PointCloud *pPoints = Parameters("POINTS")->asPointCloud();
if( pPoints->Get_Count() <= 0 )
diff --git a/src/modules/grid/grid_filter/Filter.cpp b/src/modules/grid/grid_filter/Filter.cpp
index 2edfd4d..1a99154 100644
--- a/src/modules/grid/grid_filter/Filter.cpp
+++ b/src/modules/grid/grid_filter/Filter.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: Filter.cpp 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: Filter.cpp 2629 2015-10-01 09:40:40Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -74,53 +74,48 @@
CFilter::CFilter(void)
{
//-----------------------------------------------------
- // 1. Info...
-
Set_Name (_TL("Simple Filter"));
- Set_Author (SG_T("O.Conrad (c) 2003"));
+ Set_Author ("O.Conrad (c) 2003");
Set_Description (_TW(
"Simple standard filters for grids."
));
-
//-----------------------------------------------------
- // 2. Parameters...
-
Parameters.Add_Grid(
- NULL, "INPUT" , _TL("Grid"),
+ NULL , "INPUT" , _TL("Grid"),
_TL(""),
PARAMETER_INPUT
);
Parameters.Add_Grid(
- NULL, "RESULT" , _TL("Filtered Grid"),
+ NULL , "RESULT" , _TL("Filtered Grid"),
_TL(""),
PARAMETER_OUTPUT_OPTIONAL
);
Parameters.Add_Choice(
- NULL, "MODE" , _TL("Search Mode"),
- _TL(""),
- CSG_String::Format(SG_T("%s|%s|"),
- _TL("Square"),
- _TL("Circle")
- ), 1
- );
-
- Parameters.Add_Choice(
- NULL, "METHOD" , _TL("Filter"),
+ NULL , "METHOD" , _TL("Filter"),
_TL(""),
- CSG_String::Format(SG_T("%s|%s|%s|"),
+ CSG_String::Format("%s|%s|%s|",
_TL("Smooth"),
_TL("Sharpen"),
_TL("Edge")
), 0
);
+ Parameters.Add_Choice(
+ NULL , "MODE" , _TL("Search Mode"),
+ _TL(""),
+ CSG_String::Format("%s|%s|",
+ _TL("Square"),
+ _TL("Circle")
+ ), 1
+ );
+
Parameters.Add_Value(
- NULL, "RADIUS" , _TL("Radius"),
+ NULL , "RADIUS" , _TL("Radius"),
_TL(""),
PARAMETER_TYPE_Int, 1, 1, true
);
@@ -129,66 +124,69 @@ CFilter::CFilter(void)
///////////////////////////////////////////////////////////
// //
-// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CFilter::On_Before_Execution(void)
+{
+ if( Parameters("RESULT")->asGrid() == Parameters("INPUT")->asGrid() )
+ {
+ Parameters("RESULT")->Set_Value(DATAOBJECT_NOTSET);
+ }
+
+ return( true );
+}
+
+
+///////////////////////////////////////////////////////////
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
bool CFilter::On_Execute(void)
{
- int Mode, Radius, Method;
- double Mean;
- CSG_Grid *pResult;
-
//-----------------------------------------------------
- m_pInput = Parameters("INPUT") ->asGrid();
- pResult = Parameters("RESULT") ->asGrid();
- Radius = Parameters("RADIUS") ->asInt();
- Mode = Parameters("MODE") ->asInt();
- Method = Parameters("METHOD") ->asInt();
+ m_pInput = Parameters("INPUT")->asGrid();
- switch( Mode )
- {
- case 0: break;
- case 1: m_Radius.Create(Radius); break;
- }
+ CSG_Grid Input, *pResult = Parameters("RESULT")->asGrid();
- //-----------------------------------------------------
if( !pResult || pResult == m_pInput )
{
- pResult = SG_Create_Grid(m_pInput);
+ Parameters("RESULT")->Set_Value(pResult = m_pInput);
+ Input.Create(*m_pInput);
+ m_pInput = &Input;
}
else
{
- pResult->Set_Name(CSG_String::Format(SG_T("%s [%s]"), m_pInput->Get_Name(), _TL("Filter")));
-
+ pResult->Set_Name(CSG_String::Format("%s [%s]", m_pInput->Get_Name(), _TL("Filter")));
pResult->Set_NoData_Value(m_pInput->Get_NoData_Value());
}
//-----------------------------------------------------
+ int Method = Parameters("METHOD")->asInt();
+
+ m_Kernel.Set_Radius(Parameters("RADIUS")->asInt(), Parameters("MODE")->asInt() == 0);
+
for(int y=0; y<Get_NY() && Set_Progress(y); y++)
{
+ #pragma omp parallel for
for(int x=0; x<Get_NX(); x++)
{
- if( m_pInput->is_InGrid(x, y) )
- {
- switch( Mode )
- {
- case 0: Mean = Get_Mean_Square(x, y, Radius); break;
- case 1: Mean = Get_Mean_Circle(x, y); break;
- }
+ double Mean;
+ if( Get_Mean(x, y, Mean) )
+ {
switch( Method )
{
- case 0: default: // Smooth...
+ default: // Smooth...
pResult->Set_Value(x, y, Mean);
break;
- case 1: // Sharpen...
+ case 1: // Sharpen...
pResult->Set_Value(x, y, m_pInput->asDouble(x, y) + (m_pInput->asDouble(x, y) - Mean));
break;
- case 2: // Edge...
+ case 2: // Edge...
pResult->Set_Value(x, y, m_pInput->asDouble(x, y) - Mean);
break;
}
@@ -200,18 +198,9 @@ bool CFilter::On_Execute(void)
}
}
- //-----------------------------------------------------
- if( !Parameters("RESULT")->asGrid() || Parameters("RESULT")->asGrid() == m_pInput )
- {
- m_pInput->Assign(pResult);
-
- delete(pResult);
-
- DataObject_Update(m_pInput);
- }
-
- m_Radius.Destroy();
+ m_Kernel.Destroy();
+ //-----------------------------------------------------
return( true );
}
@@ -223,44 +212,32 @@ bool CFilter::On_Execute(void)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-double CFilter::Get_Mean_Square(int x, int y, int Radius)
+bool CFilter::Get_Mean(int x, int y, double &Value)
{
- int ix, iy, n;
- double s;
+ CSG_Simple_Statistics s;
- for(n=0, s=0.0, iy=y-Radius; iy<=y+Radius; iy++)
+ if( m_pInput->is_InGrid(x, y) )
{
- for(ix=x-Radius; ix<=x+Radius; ix++)
+ for(int i=0; i<m_Kernel.Get_Count(); i++)
{
+ int ix = m_Kernel.Get_X(i, x);
+ int iy = m_Kernel.Get_Y(i, y);
+
if( m_pInput->is_InGrid(ix, iy) )
{
s += m_pInput->asDouble(ix, iy);
- n ++;
}
}
}
- return( n > 0 ? s / n : m_pInput->Get_NoData_Value() );
-}
-
-//---------------------------------------------------------
-double CFilter::Get_Mean_Circle(int x, int y)
-{
- int i, ix, iy, n;
- double s;
-
- for(n=0, s=0.0, i=0; i<m_Radius.Get_nPoints(); i++)
+ if( s.Get_Count() > 0 )
{
- m_Radius.Get_Point(i, x, y, ix, iy);
+ Value = s.Get_Mean();
- if( m_pInput->is_InGrid(ix, iy) )
- {
- s += m_pInput->asDouble(ix, iy);
- n ++;
- }
+ return( true );
}
- return( n > 0 ? s / n : m_pInput->Get_NoData_Value() );
+ return( false );
}
diff --git a/src/modules/grid/grid_filter/Filter.h b/src/modules/grid/grid_filter/Filter.h
index e95357a..bc0f582 100644
--- a/src/modules/grid/grid_filter/Filter.h
+++ b/src/modules/grid/grid_filter/Filter.h
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: Filter.h 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: Filter.h 2629 2015-10-01 09:40:40Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -90,18 +90,18 @@ public:
protected:
- virtual bool On_Execute (void);
+ virtual bool On_Before_Execution (void);
+ virtual bool On_Execute (void);
private:
- CSG_Grid_Radius m_Radius;
+ CSG_Grid_Cell_Addressor m_Kernel;
CSG_Grid *m_pInput;
- double Get_Mean_Square (int x, int y, int Radius);
- double Get_Mean_Circle (int x, int y);
+ bool Get_Mean (int x, int y, double &Value);
};
diff --git a/src/modules/grid/grid_filter/MLB_Interface.cpp b/src/modules/grid/grid_filter/MLB_Interface.cpp
index a19509d..1436651 100644
--- a/src/modules/grid/grid_filter/MLB_Interface.cpp
+++ b/src/modules/grid/grid_filter/MLB_Interface.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: MLB_Interface.cpp 2579 2015-09-16 18:48:35Z oconrad $
+ * Version $Id: MLB_Interface.cpp 2622 2015-09-30 13:17:47Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -140,8 +140,9 @@ CSG_Module * Create_Module(int i)
case 14: return( new Cconnectivity_analysis );
case 15: return( new CFilter_Sieve );
case 16: return( new CWombling );
+ case 17: return( new CWombling_MultiFeature );
- case 17: return( NULL );
+ case 18: return( NULL );
default: return( MLB_INTERFACE_SKIP_MODULE );
}
}
diff --git a/src/modules/grid/grid_filter/wombling.cpp b/src/modules/grid/grid_filter/wombling.cpp
index f21f3e2..94142e6 100644
--- a/src/modules/grid/grid_filter/wombling.cpp
+++ b/src/modules/grid/grid_filter/wombling.cpp
@@ -69,76 +69,61 @@
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-CWombling::CWombling(void)
+double SG_Get_Angle_Diff(double a, double b)
{
- //-----------------------------------------------------
- Set_Name (_TL("Wombling (Edge Detection)"));
+ double d = fmod(b - a, M_PI_360);
- Set_Author ("O.Conrad (c) 2015");
+ if( d < 0.0 ) d += M_PI_360;
- Set_Description (_TW(
- "Continuous Wombling for edge detection. Uses magnitude of gradient "
- "to detect edges between adjacent cells. Edge segments connect such "
- "edges, when the difference of their gradient directions is below given threshold.\n"
- "\n"
- "References:\n"
- "- Fitzpatrick, M.C., Preisser, E.L., Porter, A., Elkinton, J., Waller, L.A., Carlin, B.P., Ellison, A.M. (2010):"
- " Ecological boundary detection using Bayesian areal wombling. Ecology 91(12): 3448-3455. doi:10.1890/10-0807.1\n"
- "- Fortin, M.-J. and Dale, M.R.T (2005):"
- " Spatial Analysis - A Guide for Ecologists. Cambridge University Press.\n"
- ));
-
- //-----------------------------------------------------
- Parameters.Add_Grid(
- NULL , "GRID" , _TL("Grid"),
- _TL(""),
- PARAMETER_INPUT
- );
+ return( d > M_PI_180 ? d - M_PI_180 : d );
+}
- Parameters.Add_Shapes(
- NULL , "EDGE_POINTS" , _TL("Edge Points"),
- _TL(""),
- PARAMETER_OUTPUT, SHAPE_TYPE_Point
- );
- Parameters.Add_Shapes(
- NULL , "EDGE_LINES" , _TL("Edge Segments"),
- _TL(""),
- PARAMETER_OUTPUT, SHAPE_TYPE_Line
- );
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+//---------------------------------------------------------
+CWombling_Base::CWombling_Base(void)
+{
+ //-----------------------------------------------------
Parameters.Add_Value(
- NULL , "TMAGNITUDE" , _TL("Minimum Magnitude"),
+ NULL , "TMAGNITUDE" , _TL("Minimum Magnitude"),
_TL("Minimum magnitude as percentile."),
PARAMETER_TYPE_Double, 90.0, 0.0, true, 100.0, true
);
Parameters.Add_Value(
- NULL , "TDIRECTION" , _TL("Maximum Angle"),
+ NULL , "TDIRECTION" , _TL("Maximum Angle"),
_TL("Maximum angular difference as degree between adjacent segment points."),
- PARAMETER_TYPE_Double, 10.0, 0.0, true, 180.0, true
+ PARAMETER_TYPE_Double, 30.0, 0.0, true, 180.0, true
);
Parameters.Add_Value(
- NULL , "GRIDS_SHOW" , _TL("Output of Grids"),
- _TL(""),
- PARAMETER_TYPE_Bool, false
+ NULL , "TNEIGHBOUR" , _TL("Minimum Neighbours"),
+ _TL("Minimum number of neighbouring potential edge cells with similar direction."),
+ PARAMETER_TYPE_Int, 1.0, 0.0, true
);
- Parameters.Add_Grid_List(
- NULL , "GRIDS" , _TL("Grids"),
+ Parameters.Add_Choice(
+ NULL , "ALIGNMENT" , _TL("Alignment"),
_TL(""),
- PARAMETER_OUTPUT_OPTIONAL, false
+ CSG_String::Format(SG_T("%s|%s|"),
+ _TL("between cells"),
+ _TL("on cell")
+ ), 1
);
-// Parameters.Add_Choice(
-// NULL , "NEIGHBOUR" , _TL("Segment Connection"),
-// _TL(""),
-// CSG_String::Format(SG_T("%s|%s|"),
-// _TL("Rooke"),
-// _TL("Queen")
-// ), 1
-// );
+ Parameters.Add_Choice(
+ NULL , "NEIGHBOUR" , _TL("Edge Connectivity"),
+ _TL(""),
+ CSG_String::Format("%s|%s|",
+ _TL("Rooke's case"),
+ _TL("Queen's case")
+ ), 1
+ );
}
@@ -147,7 +132,7 @@ CWombling::CWombling(void)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-int CWombling::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
+int CWombling_Base::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
{
return( CSG_Module_Grid::On_Parameters_Enable(pParameters, pParameter) );
}
@@ -158,107 +143,330 @@ int CWombling::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-bool CWombling::On_Execute(void)
+bool CWombling_Base::Initialize(CSG_Grid Gradient[2], CSG_Grid *pEdges)
{
- //-----------------------------------------------------
- CSG_Grid_System System(Get_Cellsize(),
- Get_XMin() + 0.5 * Get_Cellsize(),
- Get_YMin() + 0.5 * Get_Cellsize(),
- Get_NX() - 1, Get_NY() - 1
- );
+ m_Neighbour = Parameters( "NEIGHBOUR")->asInt() == 0 ? 2 : 1;
+ m_minNeighbours = Parameters("TNEIGHBOUR")->asInt();
+ m_maxAngle = Parameters("TDIRECTION")->asDouble() * M_DEG_TO_RAD;
- CSG_Grid *pSlope, *pAspect, Slope, Aspect;
+ //-----------------------------------------------------
+ CSG_Grid_System System;
- if( Parameters("GRIDS_SHOW")->asBool() )
+ if( Parameters("ALIGNMENT")->asInt() == 1 )
{
- CSG_Parameter_Grid_List *pGrids = Parameters("GRIDS")->asGridList();
+ System = *Get_System();
+ }
+ else
+ {
+ System.Assign(Get_Cellsize(),
+ Get_XMin() + 0.5 * Get_Cellsize(),
+ Get_YMin() + 0.5 * Get_Cellsize(),
+ Get_NX() - 1, Get_NY() - 1
+ );
+ }
- if( pGrids->asGrid(0) && pGrids->asGrid(0)->Get_System().is_Equal(System)
- && pGrids->asGrid(1) && pGrids->asGrid(1)->Get_System().is_Equal(System) )
- {
- pSlope = pGrids->asGrid(0);
- pAspect = pGrids->asGrid(1);
- }
- else
+ //-----------------------------------------------------
+ Gradient[0].Create(System); Gradient[0].Set_NoData_Value(-1.0);
+ Gradient[1].Create(System); Gradient[1].Set_NoData_Value(-1.0);
+
+ pEdges->Create(System, SG_DATATYPE_Char); pEdges->Set_NoData(0.0);
+
+ //-----------------------------------------------------
+ return( true );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CWombling_Base::Get_Gradient(CSG_Grid Gradient[2], CSG_Grid *pFeature, bool bOrientation)
+{
+ int Alignment = Parameters("ALIGNMENT")->asInt() == 1;
+
+ Gradient[0].Set_Name(CSG_String::Format("%s [%s]", pFeature->Get_Name(), _TL("Magnitude")));
+ Gradient[1].Set_Name(CSG_String::Format("%s [%s]", pFeature->Get_Name(), _TL("Direction")));
+
+ //-----------------------------------------------------
+ for(int y=0; y<Gradient[0].Get_NY() && Set_Progress(y, Gradient[0].Get_NY()); y++)
+ {
+ #pragma omp parallel for
+ for(int x=0; x<Gradient[0].Get_NX(); x++)
{
- pGrids->Del_Items();
+ double Slope, Aspect, z[4];
+
+ if( Alignment == 1 )
+ {
+ if( !pFeature->Get_Gradient(x, y, Slope, Aspect) )
+ {
+ Slope = -1.0;
+ }
+ }
+ else if( pFeature->is_NoData(x , y )
+ || pFeature->is_NoData(x + 1, y )
+ || pFeature->is_NoData(x , y + 1)
+ || pFeature->is_NoData(x + 1, y + 1) )
+ {
+ Slope = -1.0;
+ }
+ else
+ {
+ z[0] = pFeature->asDouble(x , y );
+ z[1] = pFeature->asDouble(x + 1, y );
+ z[2] = pFeature->asDouble(x , y + 1);
+ z[3] = pFeature->asDouble(x + 1, y + 1);
+
+ _Get_Gradient_2x2(z, Slope, Aspect);
+ }
- pGrids->Add_Item(pSlope = SG_Create_Grid());
- pGrids->Add_Item(pAspect = SG_Create_Grid());
+ //---------------------------------------------
+ if( Slope < 0.0 )
+ {
+ Gradient[0].Set_NoData(x, y);
+ }
+ else
+ {
+ Gradient[0].Set_Value(x, y, Slope);
+ }
+
+ if( Aspect < 0.0 )
+ {
+ Gradient[1].Set_NoData(x, y);
+ }
+ else
+ {
+ Gradient[1].Set_Value(x, y, bOrientation && Aspect > M_PI_180 ? Aspect - M_PI_180 : Aspect);
+ }
}
}
- else
+
+ return( true );
+}
+
+//---------------------------------------------------------
+inline void CWombling_Base::_Get_Gradient_2x2(double z[4], double &Slope, double &Aspect)
+{
+ double a = (-z[2] + z[3] + z[0] - z[1]) * 0.5 / Get_Cellsize();
+ double b = ( z[2] + z[3] - z[0] - z[1]) * 0.5 / Get_Cellsize();
+
+ Slope = sqrt(a*a + b*b);
+ Aspect = a != 0.0 ? M_PI_180 + atan2(b, a)
+ : b > 0.0 ? M_PI_270
+ : b < 0.0 ? M_PI_090 : -1;
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CWombling_Base::Get_Edge_Cells(CSG_Grid *Gradient, CSG_Grid *pEdges)
+{
+ CSG_Shapes *pPoints = Parameters("EDGE_POINTS") ? Parameters("EDGE_POINTS")->asShapes() : NULL;
+
+ if( pPoints )
{
- pSlope = &Slope;
- pAspect = &Aspect;
+ pPoints->Create(SHAPE_TYPE_Point, CSG_String::Format("%s.%s", Parameters("FEATURE")->asGrid()->Get_Name(), _TL("Edges")));
+
+ pPoints->Add_Field("ID" , SG_DATATYPE_Int );
+ pPoints->Add_Field("MAGNITUDE" , SG_DATATYPE_Double);
+ pPoints->Add_Field("DIRECTION" , SG_DATATYPE_Double);
+ pPoints->Add_Field("NEIGHBOURS", SG_DATATYPE_Int );
}
- pSlope ->Create(System);
- pAspect->Create(System);
+ //-----------------------------------------------------
+ int y;
- pAspect->Set_NoData_Value(-1.0);
+ Lock_Create();
//-----------------------------------------------------
- Lock_Create();
+ // 1. magnitude
- Get_Gradient (pSlope, pAspect);
- Get_Edge_Points(pSlope, pAspect);
- Get_Edge_Lines (pSlope, pAspect);
+ double Threshold = Gradient[0].Get_Percentile(Parameters("TMAGNITUDE")->asDouble());
- Lock_Destroy();
+ for(y=0; y<Gradient[0].Get_NY() && Set_Progress(y, Gradient[0].Get_NY()); y++)
+ {
+ #pragma omp parallel for
+ for(int x=0; x<Gradient[0].Get_NX(); x++)
+ {
+ if( !Gradient[1].is_NoData(x, y) && !Gradient[0].is_NoData(x, y) && Gradient[0].asDouble(x, y) >= Threshold )
+ {
+ Lock_Set(x, y);
+ }
+ }
+ }
+
+ //-----------------------------------------------------
+ // 2. neighbours and direction
+
+ for(y=0; y<Gradient[0].Get_NY() && Set_Progress(y, Gradient[0].Get_NY()); y++)
+ {
+ for(int x=0; x<Gradient[0].Get_NX(); x++)
+ {
+ int n = _is_Edge_Cell(Gradient, x, y);
+
+ if( n >= m_minNeighbours )
+ {
+ pEdges->Set_Value(x, y, n);
+
+ if( pPoints )
+ {
+ CSG_Shape *pPoint = pPoints->Add_Shape();
+
+ pPoint->Set_Point(Gradient[0].Get_System().Get_Grid_to_World(x, y), 0);
+ pPoint->Set_Value(0, pPoints->Get_Count());
+ pPoint->Set_Value(1, Gradient[0].asDouble(x, y));
+ pPoint->Set_Value(2, Gradient[1].asDouble(x, y) * M_RAD_TO_DEG);
+ pPoint->Set_Value(3, n);
+ }
+ }
+ else
+ {
+ pEdges->Set_NoData(x, y);
+ }
+ }
+ }
//-----------------------------------------------------
+ Lock_Destroy();
+
return( true );
}
+//---------------------------------------------------------
+int CWombling_Base::_is_Edge_Cell(CSG_Grid Gradient[2], int x, int y)
+{
+ int n = 0;
+
+ if( Lock_Get(x, y) )
+ {
+ for(int i=0; i<8; i+=m_Neighbour)
+ {
+ int ix = Get_xTo(i, x);
+ int iy = Get_yTo(i, y);
+
+ if( Gradient[0].is_InGrid(ix, iy) && Lock_Get(ix, iy) && SG_Get_Angle_Diff(Gradient[1].asDouble(x, y), Gradient[1].asDouble(ix, iy)) <= m_maxAngle )
+ {
+ n++;
+ }
+ }
+ }
+
+ return( n );
+}
+
///////////////////////////////////////////////////////////
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-bool CWombling::Get_Edge_Lines(CSG_Grid *pSlope, CSG_Grid *pAspect)
+bool CWombling_Base::Get_Edge_Lines(CSG_Grid Gradient[2], CSG_Grid *pEdge)
{
-// int Neighbour = Parameters("NEIGHBOUR" )->asInt();
- double Threshold = Parameters("TDIRECTION")->asDouble() * M_DEG_TO_RAD;
+ CSG_Shapes *pLines = Parameters("EDGE_LINES") ? Parameters("EDGE_LINES")->asShapes() : NULL;
- CSG_Shapes *pLines = Parameters("EDGE_LINES")->asShapes();
+ if( !pLines )
+ {
+ return( false );
+ }
+
+ pLines->Create(SHAPE_TYPE_Line, CSG_String::Format("%s %s", Parameters("FEATURE")->asGrid()->Get_Name(), _TL("Edges")));
- pLines->Create(SHAPE_TYPE_Line, CSG_String::Format("%s %s", Parameters("GRID")->asGrid()->Get_Name(), _TL("Edges")));
pLines->Add_Field("ID" , SG_DATATYPE_Int);
pLines->Add_Field("ANGLE", SG_DATATYPE_Double);
- for(int y=0; y<Get_NY()-2 && Set_Progress(y); y++)
+ for(int y=0; y<Gradient[0].Get_NY() && Set_Progress(y); y++)
{
- for(int x=0; x<Get_NX()-2; x++)
+ for(int x=0; x<Gradient[0].Get_NX(); x++)
{
- Get_Edge_Lines(x, y, x + 1, y , pSlope, pAspect, pLines, Threshold);
- Get_Edge_Lines(x, y, x , y + 1, pSlope, pAspect, pLines, Threshold);
+ if( !pEdge->is_NoData(x, y) )
+ {
+ for(int i=0; i<4; i+=2)
+ {
+ int ix = Get_xTo(i, x);
+ int iy = Get_yTo(i, y);
+
+ if( pEdge->is_InGrid(ix, iy) )
+ {
+ double diff = SG_Get_Angle_Diff(Gradient[1].asDouble(x, y), Gradient[1].asDouble(ix, iy));
+
+ if( diff <= m_maxAngle )
+ {
+ CSG_Shape *pLine = pLines->Add_Shape();
+
+ pLine->Add_Point(Gradient[0].Get_System().Get_Grid_to_World( x, y));
+ pLine->Add_Point(Gradient[0].Get_System().Get_Grid_to_World(ix, iy));
+ pLine->Set_Value(0, pLines->Get_Count());
+ pLine->Set_Value(1, diff * M_RAD_TO_DEG);
+ }
+ }
+ }
+ }
}
}
return( true );
}
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
//---------------------------------------------------------
-inline void CWombling::Get_Edge_Lines(int ix, int iy, int jx, int jy, CSG_Grid *pSlope, CSG_Grid *pAspect, CSG_Shapes *pLines, double Threshold)
+CWombling::CWombling(void)
{
- if( !Lock_Get(ix, iy) && !Lock_Get(jx, jy) )
- {
- double i = pAspect->asDouble(ix, iy); if( i < 0.0 ) i += M_PI_360; i = fmod(i, M_PI_360);
- double j = pAspect->asDouble(jx, jy); if( j < 0.0 ) j += M_PI_360; j = fmod(j, M_PI_360);
+ //-----------------------------------------------------
+ Set_Name (_TL("Wombling (Edge Detection)"));
- double diff = i > j ? i - j : j - i;
+ Set_Author ("O.Conrad (c) 2015");
- if( Threshold == 0.0 || diff <= Threshold )
- {
- CSG_Shape *pLine = pLines->Add_Shape();
- pLine->Add_Point(pSlope->Get_System().Get_Grid_to_World(ix, iy));
- pLine->Add_Point(pSlope->Get_System().Get_Grid_to_World(jx, jy));
- pLine->Set_Value(0, pLines->Get_Count());
- pLine->Set_Value(1, diff * M_RAD_TO_DEG);
- }
- }
+ Set_Description (_TW(
+ "Continuous Wombling for edge detection. Uses magnitude of gradient "
+ "to detect edges between adjacent cells. Edge segments connect such "
+ "edges, when the difference of their gradient directions is below given threshold.\n"
+ "\n"
+ "References:\n"
+ "- Fitzpatrick, M.C., Preisser, E.L., Porter, A., Elkinton, J., Waller, L.A., Carlin, B.P., Ellison, A.M. (2010):"
+ " Ecological boundary detection using Bayesian areal wombling. Ecology 91(12): 3448-3455. doi:10.1890/10-0807.1\n"
+ "- Fortin, M.-J. and Dale, M.R.T (2005):"
+ " Spatial Analysis - A Guide for Ecologists. Cambridge University Press.\n"
+ ));
+
+ //-----------------------------------------------------
+ Parameters.Add_Grid(
+ NULL , "FEATURE" , _TL("Feature"),
+ _TL(""),
+ PARAMETER_INPUT
+ );
+
+ Parameters.Add_Shapes(
+ NULL , "EDGE_POINTS" , _TL("Edge Points"),
+ _TL(""),
+ PARAMETER_OUTPUT_OPTIONAL, SHAPE_TYPE_Point
+ );
+
+ Parameters.Add_Shapes(
+ NULL , "EDGE_LINES" , _TL("Edge Segments"),
+ _TL(""),
+ PARAMETER_OUTPUT_OPTIONAL, SHAPE_TYPE_Line
+ );
+
+ Parameters.Add_Value(
+ NULL , "GRADIENTS_OUT" , _TL("Output of Gradients"),
+ _TL(""),
+ PARAMETER_TYPE_Bool, false
+ );
+
+ Parameters.Add_Grid_List(
+ NULL , "GRADIENTS" , _TL("Gradients"),
+ _TL(""),
+ PARAMETER_OUTPUT_OPTIONAL, false
+ );
}
@@ -267,95 +475,196 @@ inline void CWombling::Get_Edge_Lines(int ix, int iy, int jx, int jy, CSG_Grid *
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-bool CWombling::Get_Edge_Points(CSG_Grid *pSlope, CSG_Grid *pAspect)
+bool CWombling::On_Execute(void)
{
- double Threshold = pSlope->Get_Percentile(Parameters("TMAGNITUDE")->asDouble());
+ //-----------------------------------------------------
+ CSG_Grid Gradient[2], Edges;
+
+ if( !Initialize(Gradient, &Edges) )
+ {
+ return( false );
+ }
- CSG_Shapes *pPoints = Parameters("EDGE_POINTS")->asShapes();
+ //-----------------------------------------------------
+ CSG_Grid *pFeature = Parameters("FEATURE")->asGrid();
+
+ Edges.Set_Name(CSG_String::Format("%s [%s]", pFeature->Get_Name(), _TL("Edges")));
+
+ Get_Gradient (Gradient, pFeature, false);
- pPoints->Create(SHAPE_TYPE_Point, CSG_String::Format("%s %s", Parameters("GRID")->asGrid()->Get_Name(), _TL("Edges")));
- pPoints->Add_Field("ID" , SG_DATATYPE_Int);
- pPoints->Add_Field("MAGNITUDE", SG_DATATYPE_Double);
- pPoints->Add_Field("DIRECTION", SG_DATATYPE_Double);
+ Get_Edge_Cells (Gradient, &Edges);
+ Get_Edge_Lines (Gradient, &Edges);
- for(int y=0; y<Get_NY()-1 && Set_Progress(y); y++)
+ //-----------------------------------------------------
+ if( Parameters("GRADIENTS_OUT")->asBool() )
{
- for(int x=0; x<Get_NX()-1; x++)
+ CSG_Parameter_Grid_List *pGrids = Parameters("GRADIENTS")->asGridList();
+
+ if( pGrids->asGrid(0) && pGrids->asGrid(0)->Get_System().is_Equal(Gradient[0].Get_System())
+ && pGrids->asGrid(1) && pGrids->asGrid(1)->Get_System().is_Equal(Gradient[1].Get_System()) )
{
- if( pAspect->is_NoData(x, y) || pSlope->is_NoData(x, y) || pSlope->asDouble(x, y) < Threshold )
- {
- Lock_Set(x, y);
- }
- else
- {
- CSG_Shape *pPoint = pPoints->Add_Shape();
- pPoint->Set_Point(pSlope->Get_System().Get_Grid_to_World(x, y), 0);
- pPoint->Set_Value(0, pPoints->Get_Count());
- pPoint->Set_Value(1, pSlope ->asDouble(x, y));
- pPoint->Set_Value(2, pAspect->asDouble(x, y) * M_RAD_TO_DEG);
- }
+ pGrids->asGrid(0)->Assign(&Gradient[0]);
+ pGrids->asGrid(1)->Assign(&Gradient[1]);
+ }
+ else
+ {
+ pGrids->Del_Items();
+
+ pGrids->Add_Item(SG_Create_Grid(Gradient[0]));
+ pGrids->Add_Item(SG_Create_Grid(Gradient[1]));
}
}
- return( pPoints->Get_Count() > 0 );
+ //-----------------------------------------------------
+ return( true );
}
///////////////////////////////////////////////////////////
// //
+// //
+// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-bool CWombling::Get_Gradient(CSG_Grid *pSlope, CSG_Grid *pAspect)
+CWombling_MultiFeature::CWombling_MultiFeature(void)
{
- CSG_Grid *pGrid = Parameters("GRID")->asGrid();
+ //-----------------------------------------------------
+ Set_Name (_TL("Wombling for Multiple Features (Edge Detection)"));
- pSlope ->Set_Name(CSG_String::Format("%s [%s]", pGrid->Get_Name(), _TL("Wombling Magnitude")));
- pAspect->Set_Name(CSG_String::Format("%s [%s]", pGrid->Get_Name(), _TL("Wombling Direction")));
+ Set_Author ("O.Conrad (c) 2015");
- for(int y=0; y<Get_NY()-1 && Set_Progress(y); y++)
+ Set_Description (_TW(
+ "Continuous Wombling for edge detection. Uses magnitude of gradient "
+ "to detect edges between adjacent cells. Edge segments connect such "
+ "edges, when the difference of their gradient directions is below given threshold.\n"
+ "\n"
+ "References:\n"
+ "- Fitzpatrick, M.C., Preisser, E.L., Porter, A., Elkinton, J., Waller, L.A., Carlin, B.P., Ellison, A.M. (2010):"
+ " Ecological boundary detection using Bayesian areal wombling. Ecology 91(12): 3448-3455. doi:10.1890/10-0807.1\n"
+ "- Fortin, M.-J. and Dale, M.R.T (2005):"
+ " Spatial Analysis - A Guide for Ecologists. Cambridge University Press.\n"
+ ));
+
+ //-----------------------------------------------------
+ Parameters.Add_Grid_List(
+ NULL , "FEATURES" , _TL("Features"),
+ _TL(""),
+ PARAMETER_INPUT
+ );
+
+ Parameters.Add_Grid_List(
+ NULL , "EDGE_CELLS" , _TL("Edges"),
+ _TL(""),
+ PARAMETER_OUTPUT, false
+ );
+
+ //Parameters.Add_Choice(
+ // NULL , "ASPECT_CMP" , _TL("Direction Difference"),
+ // _TL(""),
+ // CSG_String::Format("%s|%s|",
+ // _TL("direction"),
+ // _TL("orientation")
+ // ), 0
+ //);
+
+ Parameters.Add_Choice(
+ NULL , "OUTPUT_ADD" , _TL("Additional Output"),
+ _TL(""),
+ CSG_String::Format("%s|%s|%s|",
+ _TL("none"),
+ _TL("gradients"),
+ _TL("edge cells")
+ ), 0
+ );
+
+ Parameters.Add_Grid_List(
+ NULL , "OUTPUT" , _TL("Output"),
+ _TL(""),
+ PARAMETER_OUTPUT_OPTIONAL, false
+ );
+
+ Parameters.Add_Value(
+ NULL , "ZERO_AS_NODATA" , _TL("Zero as No-Data"),
+ _TL(""),
+ PARAMETER_TYPE_Bool, true
+ );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CWombling_MultiFeature::On_Execute(void)
+{
+ CSG_Parameter_Grid_List *pFeatures = Parameters("FEATURES")->asGridList(), *pOutput = NULL;
+
+ //-----------------------------------------------------
+ CSG_Grid Gradient[2], Edges;
+
+ if( !Initialize(Gradient, &Edges) )
{
- #pragma omp parallel for
- for(int x=0; x<Get_NX()-1; x++)
+ return( false );
+ }
+
+ //-----------------------------------------------------
+ if( Parameters("OUTPUT_ADD")->asInt() )
+ {
+ pOutput = Parameters("OUTPUT")->asGridList();
+
+ for(int i=pOutput->Get_Count()-1; i>=0; i--)
{
- if( pGrid->is_NoData(x , y )
- || pGrid->is_NoData(x + 1, y )
- || pGrid->is_NoData(x , y + 1)
- || pGrid->is_NoData(x + 1, y + 1) )
+ if( !pOutput->asGrid(i)->Get_System().is_Equal(Gradient[0].Get_System()) )
{
- pSlope ->Set_NoData(x, y);
- pAspect->Set_NoData(x, y);
+ pOutput->Del_Item(i);
}
- else
- {
- double Slope, Aspect, z[4];
+ }
+ }
+
+ //-----------------------------------------------------
+ CSG_Grid Count, *pCount = Parameters("EDGE_CELLS")->asGridList()->asGrid(0);
+
+ if( !pCount || !pCount->Get_System().is_Equal(Gradient[0].Get_System()) )
+ {
+ Parameters("EDGE_CELLS")->asGridList()->Del_Items();
+ Parameters("EDGE_CELLS")->asGridList()->Add_Item(pCount = SG_Create_Grid(Gradient[0].Get_System(), SG_DATATYPE_Char));
+ }
+
+ pCount->Set_Name(_TL("Edge Cells"));
+ pCount->Assign(0.0);
+ pCount->Set_NoData_Value(-1.0);
+
+ //-----------------------------------------------------
+ for(int i=0; i<pFeatures->Get_Count() && Process_Get_Okay(); i++)
+ {
+ Edges.Set_Name(CSG_String::Format("%s [%s]", pFeatures->asGrid(i)->Get_Name(), _TL("Edges")));
+
+ Get_Gradient(Gradient, pFeatures->asGrid(i), false);
- z[0] = pGrid->asDouble(x , y );
- z[1] = pGrid->asDouble(x + 1, y );
- z[2] = pGrid->asDouble(x , y + 1);
- z[3] = pGrid->asDouble(x + 1, y + 1);
+ Get_Edge_Cells(Gradient, &Edges);
- Get_Gradient(z, Slope, Aspect);
+ pCount->Add(Edges);
- pSlope ->Set_Value(x, y, Slope );
- pAspect->Set_Value(x, y, Aspect);
+ if( pOutput )
+ {
+ if( !pOutput->asGrid(i) )
+ {
+ pOutput->Add_Item(SG_Create_Grid());
}
+
+ pOutput->asGrid(i)->Create(Parameters("OUTPUT_ADD")->asInt() == 1 ? Gradient[0] : Edges);
}
}
- return( true );
-}
+ if( Parameters("ZERO_AS_NODATA")->asBool() )
+ {
+ pCount->Set_NoData_Value(0.0);
+ }
-//---------------------------------------------------------
-inline void CWombling::Get_Gradient(double z[4], double &Slope, double &Aspect)
-{
- double a = (-z[2] + z[3] + z[0] - z[1]) * 0.5 / Get_Cellsize();
- double b = ( z[2] + z[3] - z[0] - z[1]) * 0.5 / Get_Cellsize();
-
- Slope = sqrt(a*a + b*b);
- Aspect = a != 0.0 ? M_PI_180 + atan2(b, a)
- : b > 0.0 ? M_PI_270
- : b < 0.0 ? M_PI_090 : -1;
+ //-----------------------------------------------------
+ return( true );
}
diff --git a/src/modules/grid/grid_filter/wombling.h b/src/modules/grid/grid_filter/wombling.h
index f86187b..7590afb 100644
--- a/src/modules/grid/grid_filter/wombling.h
+++ b/src/modules/grid/grid_filter/wombling.h
@@ -80,31 +80,72 @@
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-class CWombling : public CSG_Module_Grid
+class CWombling_Base : public CSG_Module_Grid
{
public:
- CWombling(void);
+ CWombling_Base(void);
protected:
virtual int On_Parameters_Enable (CSG_Parameters *pParameters, CSG_Parameter *pParameter);
- virtual bool On_Execute (void);
+ bool Initialize (CSG_Grid Gradient[2], CSG_Grid *pEdges);
+
+ bool Get_Gradient (CSG_Grid Gradient[2], CSG_Grid *pFeature, bool bOrientation);
+
+ bool Get_Edge_Cells (CSG_Grid Gradient[2], CSG_Grid *pEdges);
+ bool Get_Edge_Lines (CSG_Grid Gradient[2], CSG_Grid *pEdges);
private:
- double m_TMagnitude, m_TDirection;
+ int m_Neighbour, m_minNeighbours;
+
+ double m_maxAngle;
+
+
+ void _Get_Gradient_2x2 (double z[4], double &Slope, double &Aspect);
+
+ int _is_Edge_Cell (CSG_Grid Gradient[2], int x, int y);
+
+};
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+//---------------------------------------------------------
+class CWombling : public CWombling_Base
+{
+public:
+ CWombling(void);
- void Get_Gradient (double z[4], double &Slope, double &Aspect);
- bool Get_Gradient (CSG_Grid *pSlope, CSG_Grid *pAspect);
- bool Get_Edge_Points (CSG_Grid *pSlope, CSG_Grid *pAspect);
+protected:
+
+ virtual bool On_Execute (void);
+
+
+};
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+class CWombling_MultiFeature : public CWombling_Base
+{
+public:
+ CWombling_MultiFeature(void);
+
+
+protected:
+
+ virtual bool On_Execute (void);
- void Get_Edge_Lines (int ix, int iy, int jx, int jy, CSG_Grid *pSlope, CSG_Grid *pAspect, CSG_Shapes *pLines, double Threshold);
- bool Get_Edge_Lines (CSG_Grid *pSlope, CSG_Grid *pAspect);
};
diff --git a/src/modules/grid/grid_gridding/nn/triangle.c b/src/modules/grid/grid_gridding/nn/triangle.c
new file mode 100644
index 0000000..5676f82
--- /dev/null
+++ b/src/modules/grid/grid_gridding/nn/triangle.c
@@ -0,0 +1,16012 @@
+/**********************************************************
+ * Version $Id: triangle.c 911 2011-02-14 16:38:15Z reklov_w $
+ *********************************************************/
+/*****************************************************************************/
+/* */
+/* 888888888 ,o, / 888 */
+/* 888 88o88o " o8888o 88o8888o o88888o 888 o88888o */
+/* 888 888 888 88b 888 888 888 888 888 d888 88b */
+/* 888 888 888 o88^o888 888 888 "88888" 888 8888oo888 */
+/* 888 888 888 C888 888 888 888 / 888 q888 */
+/* 888 888 888 "88o^888 888 888 Cb 888 "88oooo" */
+/* "8oo8D */
+/* */
+/* A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator. */
+/* (triangle.c) */
+/* */
+/* Version 1.6 */
+/* July 28, 2005 */
+/* */
+/* Copyright 1993, 1995, 1997, 1998, 2002, 2005 */
+/* Jonathan Richard Shewchuk */
+/* 2360 Woolsey #H */
+/* Berkeley, California 94705-1927 */
+/* jrs at cs.berkeley.edu */
+/* */
+/* This program may be freely redistributed under the condition that the */
+/* copyright notices (including this entire header and the copyright */
+/* notice printed when the `-h' switch is selected) are not removed, and */
+/* no compensation is received. Private, research, and institutional */
+/* use is free. You may distribute modified versions of this code UNDER */
+/* THE CONDITION THAT THIS CODE AND ANY MODIFICATIONS MADE TO IT IN THE */
+/* SAME FILE REMAIN UNDER COPYRIGHT OF THE ORIGINAL AUTHOR, BOTH SOURCE */
+/* AND OBJECT CODE ARE MADE FREELY AVAILABLE WITHOUT CHARGE, AND CLEAR */
+/* NOTICE IS GIVEN OF THE MODIFICATIONS. Distribution of this code as */
+/* part of a commercial system is permissible ONLY BY DIRECT ARRANGEMENT */
+/* WITH THE AUTHOR. (If you are not directly supplying this code to a */
+/* customer, and you are instead telling them how they can obtain it for */
+/* free, then you are not required to make any arrangement with me.) */
+/* */
+/* Hypertext instructions for Triangle are available on the Web at */
+/* */
+/* http://www.cs.cmu.edu/~quake/triangle.html */
+/* */
+/* Disclaimer: Neither I nor Carnegie Mellon warrant this code in any way */
+/* whatsoever. This code is provided "as-is". Use at your own risk. */
+/* */
+/* Some of the references listed below are marked with an asterisk. [*] */
+/* These references are available for downloading from the Web page */
+/* */
+/* http://www.cs.cmu.edu/~quake/triangle.research.html */
+/* */
+/* Three papers discussing aspects of Triangle are available. A short */
+/* overview appears in "Triangle: Engineering a 2D Quality Mesh */
+/* Generator and Delaunay Triangulator," in Applied Computational */
+/* Geometry: Towards Geometric Engineering, Ming C. Lin and Dinesh */
+/* Manocha, editors, Lecture Notes in Computer Science volume 1148, */
+/* pages 203-222, Springer-Verlag, Berlin, May 1996 (from the First ACM */
+/* Workshop on Applied Computational Geometry). [*] */
+/* */
+/* The algorithms are discussed in the greatest detail in "Delaunay */
+/* Refinement Algorithms for Triangular Mesh Generation," Computational */
+/* Geometry: Theory and Applications 22(1-3):21-74, May 2002. [*] */
+/* */
+/* More detail about the data structures may be found in my dissertation: */
+/* "Delaunay Refinement Mesh Generation," Ph.D. thesis, Technical Report */
+/* CMU-CS-97-137, School of Computer Science, Carnegie Mellon University, */
+/* Pittsburgh, Pennsylvania, 18 May 1997. [*] */
+/* */
+/* Triangle was created as part of the Quake Project in the School of */
+/* Computer Science at Carnegie Mellon University. For further */
+/* information, see Hesheng Bao, Jacobo Bielak, Omar Ghattas, Loukas F. */
+/* Kallivokas, David R. O'Hallaron, Jonathan R. Shewchuk, and Jifeng Xu, */
+/* "Large-scale Simulation of Elastic Wave Propagation in Heterogeneous */
+/* Media on Parallel Computers," Computer Methods in Applied Mechanics */
+/* and Engineering 152(1-2):85-102, 22 January 1998. */
+/* */
+/* Triangle's Delaunay refinement algorithm for quality mesh generation is */
+/* a hybrid of one due to Jim Ruppert, "A Delaunay Refinement Algorithm */
+/* for Quality 2-Dimensional Mesh Generation," Journal of Algorithms */
+/* 18(3):548-585, May 1995 [*], and one due to L. Paul Chew, "Guaranteed- */
+/* Quality Mesh Generation for Curved Surfaces," Proceedings of the Ninth */
+/* Annual Symposium on Computational Geometry (San Diego, California), */
+/* pages 274-280, Association for Computing Machinery, May 1993, */
+/* http://portal.acm.org/citation.cfm?id=161150 . */
+/* */
+/* The Delaunay refinement algorithm has been modified so that it meshes */
+/* domains with small input angles well, as described in Gary L. Miller, */
+/* Steven E. Pav, and Noel J. Walkington, "When and Why Ruppert's */
+/* Algorithm Works," Twelfth International Meshing Roundtable, pages */
+/* 91-102, Sandia National Laboratories, September 2003. [*] */
+/* */
+/* My implementation of the divide-and-conquer and incremental Delaunay */
+/* triangulation algorithms follows closely the presentation of Guibas */
+/* and Stolfi, even though I use a triangle-based data structure instead */
+/* of their quad-edge data structure. (In fact, I originally implemented */
+/* Triangle using the quad-edge data structure, but the switch to a */
+/* triangle-based data structure sped Triangle by a factor of two.) The */
+/* mesh manipulation primitives and the two aforementioned Delaunay */
+/* triangulation algorithms are described by Leonidas J. Guibas and Jorge */
+/* Stolfi, "Primitives for the Manipulation of General Subdivisions and */
+/* the Computation of Voronoi Diagrams," ACM Transactions on Graphics */
+/* 4(2):74-123, April 1985, http://portal.acm.org/citation.cfm?id=282923 .*/
+/* */
+/* Their O(n log n) divide-and-conquer algorithm is adapted from Der-Tsai */
+/* Lee and Bruce J. Schachter, "Two Algorithms for Constructing the */
+/* Delaunay Triangulation," International Journal of Computer and */
+/* Information Science 9(3):219-242, 1980. Triangle's improvement of the */
+/* divide-and-conquer algorithm by alternating between vertical and */
+/* horizontal cuts was introduced by Rex A. Dwyer, "A Faster Divide-and- */
+/* Conquer Algorithm for Constructing Delaunay Triangulations," */
+/* Algorithmica 2(2):137-151, 1987. */
+/* */
+/* The incremental insertion algorithm was first proposed by C. L. Lawson, */
+/* "Software for C1 Surface Interpolation," in Mathematical Software III, */
+/* John R. Rice, editor, Academic Press, New York, pp. 161-194, 1977. */
+/* For point location, I use the algorithm of Ernst P. Mucke, Isaac */
+/* Saias, and Binhai Zhu, "Fast Randomized Point Location Without */
+/* Preprocessing in Two- and Three-Dimensional Delaunay Triangulations," */
+/* Proceedings of the Twelfth Annual Symposium on Computational Geometry, */
+/* ACM, May 1996. [*] If I were to randomize the order of vertex */
+/* insertion (I currently don't bother), their result combined with the */
+/* result of Kenneth L. Clarkson and Peter W. Shor, "Applications of */
+/* Random Sampling in Computational Geometry II," Discrete & */
+/* Computational Geometry 4(1):387-421, 1989, would yield an expected */
+/* O(n^{4/3}) bound on running time. */
+/* */
+/* The O(n log n) sweepline Delaunay triangulation algorithm is taken from */
+/* Steven Fortune, "A Sweepline Algorithm for Voronoi Diagrams", */
+/* Algorithmica 2(2):153-174, 1987. A random sample of edges on the */
+/* boundary of the triangulation are maintained in a splay tree for the */
+/* purpose of point location. Splay trees are described by Daniel */
+/* Dominic Sleator and Robert Endre Tarjan, "Self-Adjusting Binary Search */
+/* Trees," Journal of the ACM 32(3):652-686, July 1985, */
+/* http://portal.acm.org/citation.cfm?id=3835 . */
+/* */
+/* The algorithms for exact computation of the signs of determinants are */
+/* described in Jonathan Richard Shewchuk, "Adaptive Precision Floating- */
+/* Point Arithmetic and Fast Robust Geometric Predicates," Discrete & */
+/* Computational Geometry 18(3):305-363, October 1997. (Also available */
+/* as Technical Report CMU-CS-96-140, School of Computer Science, */
+/* Carnegie Mellon University, Pittsburgh, Pennsylvania, May 1996.) [*] */
+/* An abbreviated version appears as Jonathan Richard Shewchuk, "Robust */
+/* Adaptive Floating-Point Geometric Predicates," Proceedings of the */
+/* Twelfth Annual Symposium on Computational Geometry, ACM, May 1996. [*] */
+/* Many of the ideas for my exact arithmetic routines originate with */
+/* Douglas M. Priest, "Algorithms for Arbitrary Precision Floating Point */
+/* Arithmetic," Tenth Symposium on Computer Arithmetic, pp. 132-143, IEEE */
+/* Computer Society Press, 1991. [*] Many of the ideas for the correct */
+/* evaluation of the signs of determinants are taken from Steven Fortune */
+/* and Christopher J. Van Wyk, "Efficient Exact Arithmetic for Computa- */
+/* tional Geometry," Proceedings of the Ninth Annual Symposium on */
+/* Computational Geometry, ACM, pp. 163-172, May 1993, and from Steven */
+/* Fortune, "Numerical Stability of Algorithms for 2D Delaunay Triangu- */
+/* lations," International Journal of Computational Geometry & Applica- */
+/* tions 5(1-2):193-213, March-June 1995. */
+/* */
+/* The method of inserting new vertices off-center (not precisely at the */
+/* circumcenter of every poor-quality triangle) is from Alper Ungor, */
+/* "Off-centers: A New Type of Steiner Points for Computing Size-Optimal */
+/* Quality-Guaranteed Delaunay Triangulations," Proceedings of LATIN */
+/* 2004 (Buenos Aires, Argentina), April 2004. */
+/* */
+/* For definitions of and results involving Delaunay triangulations, */
+/* constrained and conforming versions thereof, and other aspects of */
+/* triangular mesh generation, see the excellent survey by Marshall Bern */
+/* and David Eppstein, "Mesh Generation and Optimal Triangulation," in */
+/* Computing and Euclidean Geometry, Ding-Zhu Du and Frank Hwang, */
+/* editors, World Scientific, Singapore, pp. 23-90, 1992. [*] */
+/* */
+/* The time for incrementally adding PSLG (planar straight line graph) */
+/* segments to create a constrained Delaunay triangulation is probably */
+/* O(t^2) per segment in the worst case and O(t) per segment in the */
+/* common case, where t is the number of triangles that intersect the */
+/* segment before it is inserted. This doesn't count point location, */
+/* which can be much more expensive. I could improve this to O(d log d) */
+/* time, but d is usually quite small, so it's not worth the bother. */
+/* (This note does not apply when the -s switch is used, invoking a */
+/* different method is used to insert segments.) */
+/* */
+/* The time for deleting a vertex from a Delaunay triangulation is O(d^2) */
+/* in the worst case and O(d) in the common case, where d is the degree */
+/* of the vertex being deleted. I could improve this to O(d log d) time, */
+/* but d is usually quite small, so it's not worth the bother. */
+/* */
+/* Ruppert's Delaunay refinement algorithm typically generates triangles */
+/* at a linear rate (constant time per triangle) after the initial */
+/* triangulation is formed. There may be pathological cases where */
+/* quadratic time is required, but these never arise in practice. */
+/* */
+/* The geometric predicates (circumcenter calculations, segment */
+/* intersection formulae, etc.) appear in my "Lecture Notes on Geometric */
+/* Robustness" at http://www.cs.berkeley.edu/~jrs/mesh . */
+/* */
+/* If you make any improvements to this code, please please please let me */
+/* know, so that I may obtain the improvements. Even if you don't change */
+/* the code, I'd still love to hear what it's being used for. */
+/* */
+/*****************************************************************************/
+
+/* For single precision (which will save some memory and reduce paging), */
+/* define the symbol SINGLE by using the -DSINGLE compiler switch or by */
+/* writing "#define SINGLE" below. */
+/* */
+/* For double precision (which will allow you to refine meshes to a smaller */
+/* edge length), leave SINGLE undefined. */
+/* */
+/* Double precision uses more memory, but improves the resolution of the */
+/* meshes you can generate with Triangle. It also reduces the likelihood */
+/* of a floating exception due to overflow. Finally, it is much faster */
+/* than single precision on 64-bit architectures like the DEC Alpha. I */
+/* recommend double precision unless you want to generate a mesh for which */
+/* you do not have enough memory. */
+
+/* #define SINGLE */
+
+#ifdef SINGLE
+#define REAL float
+#else /* not SINGLE */
+#define REAL double
+#endif /* not SINGLE */
+
+/* If yours is not a Unix system, define the NO_TIMER compiler switch to */
+/* remove the Unix-specific timing code. */
+
+#define NO_TIMER
+
+/* To insert lots of self-checks for internal errors, define the SELF_CHECK */
+/* symbol. This will slow down the program significantly. It is best to */
+/* define the symbol using the -DSELF_CHECK compiler switch, but you could */
+/* write "#define SELF_CHECK" below. If you are modifying this code, I */
+/* recommend you turn self-checks on until your work is debugged. */
+
+/* #define SELF_CHECK */
+
+/* To compile Triangle as a callable object library (triangle.o), define the */
+/* TRILIBRARY symbol. Read the file triangle.h for details on how to call */
+/* the procedure triangulate() that results. */
+
+#define TRILIBRARY
+
+/* It is possible to generate a smaller version of Triangle using one or */
+/* both of the following symbols. Define the REDUCED symbol to eliminate */
+/* all features that are primarily of research interest; specifically, the */
+/* -i, -F, -s, and -C switches. Define the CDT_ONLY symbol to eliminate */
+/* all meshing algorithms above and beyond constrained Delaunay */
+/* triangulation; specifically, the -r, -q, -a, -u, -D, -S, and -s */
+/* switches. These reductions are most likely to be useful when */
+/* generating an object library (triangle.o) by defining the TRILIBRARY */
+/* symbol. */
+
+/* #define REDUCED */
+/* #define CDT_ONLY */
+
+/* On some machines, my exact arithmetic routines might be defeated by the */
+/* use of internal extended precision floating-point registers. The best */
+/* way to solve this problem is to set the floating-point registers to use */
+/* single or double precision internally. On 80x86 processors, this may */
+/* be accomplished by setting the CPU86 symbol for the Microsoft C */
+/* compiler, or the LINUX symbol for the gcc compiler running on Linux. */
+/* */
+/* An inferior solution is to declare certain values as `volatile', thus */
+/* forcing them to be stored to memory and rounded off. Unfortunately, */
+/* this solution might slow Triangle down quite a bit. To use volatile */
+/* values, write "#define INEXACT volatile" below. Normally, however, */
+/* INEXACT should be defined to be nothing. ("#define INEXACT".) */
+/* */
+/* For more discussion, see http://www.cs.cmu.edu/~quake/robust.pc.html . */
+/* For yet more discussion, see Section 5 of my paper, "Adaptive Precision */
+/* Floating-Point Arithmetic and Fast Robust Geometric Predicates" (also */
+/* available as Section 6.6 of my dissertation). */
+
+/* #define CPU86 */
+/* #define LINUX */
+
+#define INEXACT /* Nothing */
+/* #define INEXACT volatile */
+
+/* Maximum number of characters in a file name (including the null). */
+
+#define FILENAMESIZE 2048
+
+/* Maximum number of characters in a line read from a file (including the */
+/* null). */
+
+#define INPUTLINESIZE 1024
+
+/* For efficiency, a variety of data structures are allocated in bulk. The */
+/* following constants determine how many of each structure is allocated */
+/* at once. */
+
+#define TRIPERBLOCK 4092 /* Number of triangles allocated at once. */
+#define SUBSEGPERBLOCK 508 /* Number of subsegments allocated at once. */
+#define VERTEXPERBLOCK 4092 /* Number of vertices allocated at once. */
+#define VIRUSPERBLOCK 1020 /* Number of virus triangles allocated at once. */
+/* Number of encroached subsegments allocated at once. */
+#define BADSUBSEGPERBLOCK 252
+/* Number of skinny triangles allocated at once. */
+#define BADTRIPERBLOCK 4092
+/* Number of flipped triangles allocated at once. */
+#define FLIPSTACKERPERBLOCK 252
+/* Number of splay tree nodes allocated at once. */
+#define SPLAYNODEPERBLOCK 508
+
+/* The vertex types. A DEADVERTEX has been deleted entirely. An */
+/* UNDEADVERTEX is not part of the mesh, but is written to the output */
+/* .node file and affects the node indexing in the other output files. */
+
+#define INPUTVERTEX 0
+#define SEGMENTVERTEX 1
+#define FREEVERTEX 2
+#define DEADVERTEX -32768
+#define UNDEADVERTEX -32767
+
+/* The next line is used to outsmart some very stupid compilers. If your */
+/* compiler is smarter, feel free to replace the "int" with "void". */
+/* Not that it matters. */
+
+#define VOID void
+
+/* Two constants for algorithms based on random sampling. Both constants */
+/* have been chosen empirically to optimize their respective algorithms. */
+
+/* Used for the point location scheme of Mucke, Saias, and Zhu, to decide */
+/* how large a random sample of triangles to inspect. */
+
+#define SAMPLEFACTOR 11
+
+/* Used in Fortune's sweepline Delaunay algorithm to determine what fraction */
+/* of boundary edges should be maintained in the splay tree for point */
+/* location on the front. */
+
+#define SAMPLERATE 10
+
+/* A number that speaks for itself, every kissable digit. */
+
+#define PI 3.141592653589793238462643383279502884197169399375105820974944592308
+
+/* Another fave. */
+
+#define SQUAREROOTTWO 1.4142135623730950488016887242096980785696718753769480732
+
+/* And here's one for those of you who are intimidated by math. */
+
+#define ONETHIRD 0.333333333333333333333333333333333333333333333333333333333333
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+#ifndef NO_TIMER
+#include <sys/time.h>
+#endif /* not NO_TIMER */
+#ifdef CPU86
+#include <float.h>
+#endif /* CPU86 */
+#ifdef LINUX
+#include <fpu_control.h>
+#endif /* LINUX */
+#ifdef TRILIBRARY
+#include "triangle.h"
+#endif /* TRILIBRARY */
+
+/* A few forward declarations. */
+
+#ifndef TRILIBRARY
+char *readline();
+char *findfield();
+#endif /* not TRILIBRARY */
+
+/* Labels that signify the result of point location. The result of a */
+/* search indicates that the point falls in the interior of a triangle, on */
+/* an edge, on a vertex, or outside the mesh. */
+
+enum locateresult {INTRIANGLE, ONEDGE, ONVERTEX, OUTSIDE};
+
+/* Labels that signify the result of vertex insertion. The result indicates */
+/* that the vertex was inserted with complete success, was inserted but */
+/* encroaches upon a subsegment, was not inserted because it lies on a */
+/* segment, or was not inserted because another vertex occupies the same */
+/* location. */
+
+enum insertvertexresult {SUCCESSFULVERTEX, ENCROACHINGVERTEX, VIOLATINGVERTEX,
+ DUPLICATEVERTEX};
+
+/* Labels that signify the result of direction finding. The result */
+/* indicates that a segment connecting the two query points falls within */
+/* the direction triangle, along the left edge of the direction triangle, */
+/* or along the right edge of the direction triangle. */
+
+enum finddirectionresult {WITHIN, LEFTCOLLINEAR, RIGHTCOLLINEAR};
+
+/*****************************************************************************/
+/* */
+/* The basic mesh data structures */
+/* */
+/* There are three: vertices, triangles, and subsegments (abbreviated */
+/* `subseg'). These three data structures, linked by pointers, comprise */
+/* the mesh. A vertex simply represents a mesh vertex and its properties. */
+/* A triangle is a triangle. A subsegment is a special data structure used */
+/* to represent an impenetrable edge of the mesh (perhaps on the outer */
+/* boundary, on the boundary of a hole, or part of an internal boundary */
+/* separating two triangulated regions). Subsegments represent boundaries, */
+/* defined by the user, that triangles may not lie across. */
+/* */
+/* A triangle consists of a list of three vertices, a list of three */
+/* adjoining triangles, a list of three adjoining subsegments (when */
+/* segments exist), an arbitrary number of optional user-defined */
+/* floating-point attributes, and an optional area constraint. The latter */
+/* is an upper bound on the permissible area of each triangle in a region, */
+/* used for mesh refinement. */
+/* */
+/* For a triangle on a boundary of the mesh, some or all of the neighboring */
+/* triangles may not be present. For a triangle in the interior of the */
+/* mesh, often no neighboring subsegments are present. Such absent */
+/* triangles and subsegments are never represented by NULL pointers; they */
+/* are represented by two special records: `dummytri', the triangle that */
+/* fills "outer space", and `dummysub', the omnipresent subsegment. */
+/* `dummytri' and `dummysub' are used for several reasons; for instance, */
+/* they can be dereferenced and their contents examined without violating */
+/* protected memory. */
+/* */
+/* However, it is important to understand that a triangle includes other */
+/* information as well. The pointers to adjoining vertices, triangles, and */
+/* subsegments are ordered in a way that indicates their geometric relation */
+/* to each other. Furthermore, each of these pointers contains orientation */
+/* information. Each pointer to an adjoining triangle indicates which face */
+/* of that triangle is contacted. Similarly, each pointer to an adjoining */
+/* subsegment indicates which side of that subsegment is contacted, and how */
+/* the subsegment is oriented relative to the triangle. */
+/* */
+/* The data structure representing a subsegment may be thought to be */
+/* abutting the edge of one or two triangle data structures: either */
+/* sandwiched between two triangles, or resting against one triangle on an */
+/* exterior boundary or hole boundary. */
+/* */
+/* A subsegment consists of a list of four vertices--the vertices of the */
+/* subsegment, and the vertices of the segment it is a part of--a list of */
+/* two adjoining subsegments, and a list of two adjoining triangles. One */
+/* of the two adjoining triangles may not be present (though there should */
+/* always be one), and neighboring subsegments might not be present. */
+/* Subsegments also store a user-defined integer "boundary marker". */
+/* Typically, this integer is used to indicate what boundary conditions are */
+/* to be applied at that location in a finite element simulation. */
+/* */
+/* Like triangles, subsegments maintain information about the relative */
+/* orientation of neighboring objects. */
+/* */
+/* Vertices are relatively simple. A vertex is a list of floating-point */
+/* numbers, starting with the x, and y coordinates, followed by an */
+/* arbitrary number of optional user-defined floating-point attributes, */
+/* followed by an integer boundary marker. During the segment insertion */
+/* phase, there is also a pointer from each vertex to a triangle that may */
+/* contain it. Each pointer is not always correct, but when one is, it */
+/* speeds up segment insertion. These pointers are assigned values once */
+/* at the beginning of the segment insertion phase, and are not used or */
+/* updated except during this phase. Edge flipping during segment */
+/* insertion will render some of them incorrect. Hence, don't rely upon */
+/* them for anything. */
+/* */
+/* Other than the exception mentioned above, vertices have no information */
+/* about what triangles, subfacets, or subsegments they are linked to. */
+/* */
+/*****************************************************************************/
+
+/*****************************************************************************/
+/* */
+/* Handles */
+/* */
+/* The oriented triangle (`otri') and oriented subsegment (`osub') data */
+/* structures defined below do not themselves store any part of the mesh. */
+/* The mesh itself is made of `triangle's, `subseg's, and `vertex's. */
+/* */
+/* Oriented triangles and oriented subsegments will usually be referred to */
+/* as "handles." A handle is essentially a pointer into the mesh; it */
+/* allows you to "hold" one particular part of the mesh. Handles are used */
+/* to specify the regions in which one is traversing and modifying the mesh.*/
+/* A single `triangle' may be held by many handles, or none at all. (The */
+/* latter case is not a memory leak, because the triangle is still */
+/* connected to other triangles in the mesh.) */
+/* */
+/* An `otri' is a handle that holds a triangle. It holds a specific edge */
+/* of the triangle. An `osub' is a handle that holds a subsegment. It */
+/* holds either the left or right side of the subsegment. */
+/* */
+/* Navigation about the mesh is accomplished through a set of mesh */
+/* manipulation primitives, further below. Many of these primitives take */
+/* a handle and produce a new handle that holds the mesh near the first */
+/* handle. Other primitives take two handles and glue the corresponding */
+/* parts of the mesh together. The orientation of the handles is */
+/* important. For instance, when two triangles are glued together by the */
+/* bond() primitive, they are glued at the edges on which the handles lie. */
+/* */
+/* Because vertices have no information about which triangles they are */
+/* attached to, I commonly represent a vertex by use of a handle whose */
+/* origin is the vertex. A single handle can simultaneously represent a */
+/* triangle, an edge, and a vertex. */
+/* */
+/*****************************************************************************/
+
+/* The triangle data structure. Each triangle contains three pointers to */
+/* adjoining triangles, plus three pointers to vertices, plus three */
+/* pointers to subsegments (declared below; these pointers are usually */
+/* `dummysub'). It may or may not also contain user-defined attributes */
+/* and/or a floating-point "area constraint." It may also contain extra */
+/* pointers for nodes, when the user asks for high-order elements. */
+/* Because the size and structure of a `triangle' is not decided until */
+/* runtime, I haven't simply declared the type `triangle' as a struct. */
+
+typedef REAL **triangle; /* Really: typedef triangle *triangle */
+
+/* An oriented triangle: includes a pointer to a triangle and orientation. */
+/* The orientation denotes an edge of the triangle. Hence, there are */
+/* three possible orientations. By convention, each edge always points */
+/* counterclockwise about the corresponding triangle. */
+
+struct otri {
+ triangle *tri;
+ int orient; /* Ranges from 0 to 2. */
+};
+
+/* The subsegment data structure. Each subsegment contains two pointers to */
+/* adjoining subsegments, plus four pointers to vertices, plus two */
+/* pointers to adjoining triangles, plus one boundary marker, plus one */
+/* segment number. */
+
+typedef REAL **subseg; /* Really: typedef subseg *subseg */
+
+/* An oriented subsegment: includes a pointer to a subsegment and an */
+/* orientation. The orientation denotes a side of the edge. Hence, there */
+/* are two possible orientations. By convention, the edge is always */
+/* directed so that the "side" denoted is the right side of the edge. */
+
+struct osub {
+ subseg *ss;
+ int ssorient; /* Ranges from 0 to 1. */
+};
+
+/* The vertex data structure. Each vertex is actually an array of REALs. */
+/* The number of REALs is unknown until runtime. An integer boundary */
+/* marker, and sometimes a pointer to a triangle, is appended after the */
+/* REALs. */
+
+typedef REAL *vertex;
+
+/* A queue used to store encroached subsegments. Each subsegment's vertices */
+/* are stored so that we can check whether a subsegment is still the same. */
+
+struct badsubseg {
+ subseg encsubseg; /* An encroached subsegment. */
+ vertex subsegorg, subsegdest; /* Its two vertices. */
+};
+
+/* A queue used to store bad triangles. The key is the square of the cosine */
+/* of the smallest angle of the triangle. Each triangle's vertices are */
+/* stored so that one can check whether a triangle is still the same. */
+
+struct badtriang {
+ triangle poortri; /* A skinny or too-large triangle. */
+ REAL key; /* cos^2 of smallest (apical) angle. */
+ vertex triangorg, triangdest, triangapex; /* Its three vertices. */
+ struct badtriang *nexttriang; /* Pointer to next bad triangle. */
+};
+
+/* A stack of triangles flipped during the most recent vertex insertion. */
+/* The stack is used to undo the vertex insertion if the vertex encroaches */
+/* upon a subsegment. */
+
+struct flipstacker {
+ triangle flippedtri; /* A recently flipped triangle. */
+ struct flipstacker *prevflip; /* Previous flip in the stack. */
+};
+
+/* A node in a heap used to store events for the sweepline Delaunay */
+/* algorithm. Nodes do not point directly to their parents or children in */
+/* the heap. Instead, each node knows its position in the heap, and can */
+/* look up its parent and children in a separate array. The `eventptr' */
+/* points either to a `vertex' or to a triangle (in encoded format, so */
+/* that an orientation is included). In the latter case, the origin of */
+/* the oriented triangle is the apex of a "circle event" of the sweepline */
+/* algorithm. To distinguish site events from circle events, all circle */
+/* events are given an invalid (smaller than `xmin') x-coordinate `xkey'. */
+
+struct event {
+ REAL xkey, ykey; /* Coordinates of the event. */
+ VOID *eventptr; /* Can be a vertex or the location of a circle event. */
+ int heapposition; /* Marks this event's position in the heap. */
+};
+
+/* A node in the splay tree. Each node holds an oriented ghost triangle */
+/* that represents a boundary edge of the growing triangulation. When a */
+/* circle event covers two boundary edges with a triangle, so that they */
+/* are no longer boundary edges, those edges are not immediately deleted */
+/* from the tree; rather, they are lazily deleted when they are next */
+/* encountered. (Since only a random sample of boundary edges are kept */
+/* in the tree, lazy deletion is faster.) `keydest' is used to verify */
+/* that a triangle is still the same as when it entered the splay tree; if */
+/* it has been rotated (due to a circle event), it no longer represents a */
+/* boundary edge and should be deleted. */
+
+struct splaynode {
+ struct otri keyedge; /* Lprev of an edge on the front. */
+ vertex keydest; /* Used to verify that splay node is still live. */
+ struct splaynode *lchild, *rchild; /* Children in splay tree. */
+};
+
+/* A type used to allocate memory. firstblock is the first block of items. */
+/* nowblock is the block from which items are currently being allocated. */
+/* nextitem points to the next slab of free memory for an item. */
+/* deaditemstack is the head of a linked list (stack) of deallocated items */
+/* that can be recycled. unallocateditems is the number of items that */
+/* remain to be allocated from nowblock. */
+/* */
+/* Traversal is the process of walking through the entire list of items, and */
+/* is separate from allocation. Note that a traversal will visit items on */
+/* the "deaditemstack" stack as well as live items. pathblock points to */
+/* the block currently being traversed. pathitem points to the next item */
+/* to be traversed. pathitemsleft is the number of items that remain to */
+/* be traversed in pathblock. */
+/* */
+/* alignbytes determines how new records should be aligned in memory. */
+/* itembytes is the length of a record in bytes (after rounding up). */
+/* itemsperblock is the number of items allocated at once in a single */
+/* block. itemsfirstblock is the number of items in the first block, */
+/* which can vary from the others. items is the number of currently */
+/* allocated items. maxitems is the maximum number of items that have */
+/* been allocated at once; it is the current number of items plus the */
+/* number of records kept on deaditemstack. */
+
+struct memorypool {
+ VOID **firstblock, **nowblock;
+ VOID *nextitem;
+ VOID *deaditemstack;
+ VOID **pathblock;
+ VOID *pathitem;
+ int alignbytes;
+ int itembytes;
+ int itemsperblock;
+ int itemsfirstblock;
+ long items, maxitems;
+ int unallocateditems;
+ int pathitemsleft;
+};
+
+
+/* Global constants. */
+
+REAL splitter; /* Used to split REAL factors for exact multiplication. */
+REAL epsilon; /* Floating-point machine epsilon. */
+REAL resulterrbound;
+REAL ccwerrboundA, ccwerrboundB, ccwerrboundC;
+REAL iccerrboundA, iccerrboundB, iccerrboundC;
+REAL o3derrboundA, o3derrboundB, o3derrboundC;
+
+/* Random number seed is not constant, but I've made it global anyway. */
+
+unsigned long randomseed; /* Current random number seed. */
+
+
+/* Mesh data structure. Triangle operates on only one mesh, but the mesh */
+/* structure is used (instead of global variables) to allow reentrancy. */
+
+struct mesh {
+
+/* Variables used to allocate memory for triangles, subsegments, vertices, */
+/* viri (triangles being eaten), encroached segments, bad (skinny or too */
+/* large) triangles, and splay tree nodes. */
+
+ struct memorypool triangles;
+ struct memorypool subsegs;
+ struct memorypool vertices;
+ struct memorypool viri;
+ struct memorypool badsubsegs;
+ struct memorypool badtriangles;
+ struct memorypool flipstackers;
+ struct memorypool splaynodes;
+
+/* Variables that maintain the bad triangle queues. The queues are */
+/* ordered from 4095 (highest priority) to 0 (lowest priority). */
+
+ struct badtriang *queuefront[4096];
+ struct badtriang *queuetail[4096];
+ int nextnonemptyq[4096];
+ int firstnonemptyq;
+
+/* Variable that maintains the stack of recently flipped triangles. */
+
+ struct flipstacker *lastflip;
+
+/* Other variables. */
+
+ REAL xmin, xmax, ymin, ymax; /* x and y bounds. */
+ REAL xminextreme; /* Nonexistent x value used as a flag in sweepline. */
+ int invertices; /* Number of input vertices. */
+ int inelements; /* Number of input triangles. */
+ int insegments; /* Number of input segments. */
+ int holes; /* Number of input holes. */
+ int regions; /* Number of input regions. */
+ int undeads; /* Number of input vertices that don't appear in the mesh. */
+ long edges; /* Number of output edges. */
+ int mesh_dim; /* Dimension (ought to be 2). */
+ int nextras; /* Number of attributes per vertex. */
+ int eextras; /* Number of attributes per triangle. */
+ long hullsize; /* Number of edges in convex hull. */
+ int steinerleft; /* Number of Steiner points not yet used. */
+ int vertexmarkindex; /* Index to find boundary marker of a vertex. */
+ int vertex2triindex; /* Index to find a triangle adjacent to a vertex. */
+ int highorderindex; /* Index to find extra nodes for high-order elements. */
+ int elemattribindex; /* Index to find attributes of a triangle. */
+ int areaboundindex; /* Index to find area bound of a triangle. */
+ int checksegments; /* Are there segments in the triangulation yet? */
+ int checkquality; /* Has quality triangulation begun yet? */
+ int readnodefile; /* Has a .node file been read? */
+ long samples; /* Number of random samples for point location. */
+
+ long incirclecount; /* Number of incircle tests performed. */
+ long counterclockcount; /* Number of counterclockwise tests performed. */
+ long orient3dcount; /* Number of 3D orientation tests performed. */
+ long hyperbolacount; /* Number of right-of-hyperbola tests performed. */
+ long circumcentercount; /* Number of circumcenter calculations performed. */
+ long circletopcount; /* Number of circle top calculations performed. */
+
+/* Triangular bounding box vertices. */
+
+ vertex infvertex1, infvertex2, infvertex3;
+
+/* Pointer to the `triangle' that occupies all of "outer space." */
+
+ triangle *dummytri;
+ triangle *dummytribase; /* Keep base address so we can free() it later. */
+
+/* Pointer to the omnipresent subsegment. Referenced by any triangle or */
+/* subsegment that isn't really connected to a subsegment at that */
+/* location. */
+
+ subseg *dummysub;
+ subseg *dummysubbase; /* Keep base address so we can free() it later. */
+
+/* Pointer to a recently visited triangle. Improves point location if */
+/* proximate vertices are inserted sequentially. */
+
+ struct otri recenttri;
+
+}; /* End of `struct mesh'. */
+
+
+/* Data structure for command line switches and file names. This structure */
+/* is used (instead of global variables) to allow reentrancy. */
+
+struct behavior {
+
+/* Switches for the triangulator. */
+/* poly: -p switch. refine: -r switch. */
+/* quality: -q switch. */
+/* minangle: minimum angle bound, specified after -q switch. */
+/* goodangle: cosine squared of minangle. */
+/* offconstant: constant used to place off-center Steiner points. */
+/* vararea: -a switch without number. */
+/* fixedarea: -a switch with number. */
+/* maxarea: maximum area bound, specified after -a switch. */
+/* usertest: -u switch. */
+/* regionattrib: -A switch. convex: -c switch. */
+/* weighted: 1 for -w switch, 2 for -W switch. jettison: -j switch */
+/* firstnumber: inverse of -z switch. All items are numbered starting */
+/* from `firstnumber'. */
+/* edgesout: -e switch. voronoi: -v switch. */
+/* neighbors: -n switch. geomview: -g switch. */
+/* nobound: -B switch. nopolywritten: -P switch. */
+/* nonodewritten: -N switch. noelewritten: -E switch. */
+/* noiterationnum: -I switch. noholes: -O switch. */
+/* noexact: -X switch. */
+/* order: element order, specified after -o switch. */
+/* nobisect: count of how often -Y switch is selected. */
+/* steiner: maximum number of Steiner points, specified after -S switch. */
+/* incremental: -i switch. sweepline: -F switch. */
+/* dwyer: inverse of -l switch. */
+/* splitseg: -s switch. */
+/* conformdel: -D switch. docheck: -C switch. */
+/* quiet: -Q switch. verbose: count of how often -V switch is selected. */
+/* usesegments: -p, -r, -q, or -c switch; determines whether segments are */
+/* used at all. */
+/* */
+/* Read the instructions to find out the meaning of these switches. */
+
+ int poly, refine, quality, vararea, fixedarea, usertest;
+ int regionattrib, convex, weighted, jettison;
+ int firstnumber;
+ int edgesout, voronoi, neighbors, geomview;
+ int nobound, nopolywritten, nonodewritten, noelewritten, noiterationnum;
+ int noholes, noexact, conformdel;
+ int incremental, sweepline, dwyer;
+ int splitseg;
+ int docheck;
+ int quiet, verbose;
+ int usesegments;
+ int order;
+ int nobisect;
+ int steiner;
+ REAL minangle, goodangle, offconstant;
+ REAL maxarea;
+
+/* Variables for file names. */
+
+#ifndef TRILIBRARY
+ char innodefilename[FILENAMESIZE];
+ char inelefilename[FILENAMESIZE];
+ char inpolyfilename[FILENAMESIZE];
+ char areafilename[FILENAMESIZE];
+ char outnodefilename[FILENAMESIZE];
+ char outelefilename[FILENAMESIZE];
+ char outpolyfilename[FILENAMESIZE];
+ char edgefilename[FILENAMESIZE];
+ char vnodefilename[FILENAMESIZE];
+ char vedgefilename[FILENAMESIZE];
+ char neighborfilename[FILENAMESIZE];
+ char offfilename[FILENAMESIZE];
+#endif /* not TRILIBRARY */
+
+}; /* End of `struct behavior'. */
+
+
+/*****************************************************************************/
+/* */
+/* Mesh manipulation primitives. Each triangle contains three pointers to */
+/* other triangles, with orientations. Each pointer points not to the */
+/* first byte of a triangle, but to one of the first three bytes of a */
+/* triangle. It is necessary to extract both the triangle itself and the */
+/* orientation. To save memory, I keep both pieces of information in one */
+/* pointer. To make this possible, I assume that all triangles are aligned */
+/* to four-byte boundaries. The decode() routine below decodes a pointer, */
+/* extracting an orientation (in the range 0 to 2) and a pointer to the */
+/* beginning of a triangle. The encode() routine compresses a pointer to a */
+/* triangle and an orientation into a single pointer. My assumptions that */
+/* triangles are four-byte-aligned and that the `unsigned long' type is */
+/* long enough to hold a pointer are two of the few kludges in this program.*/
+/* */
+/* Subsegments are manipulated similarly. A pointer to a subsegment */
+/* carries both an address and an orientation in the range 0 to 1. */
+/* */
+/* The other primitives take an oriented triangle or oriented subsegment, */
+/* and return an oriented triangle or oriented subsegment or vertex; or */
+/* they change the connections in the data structure. */
+/* */
+/* Below, triangles and subsegments are denoted by their vertices. The */
+/* triangle abc has origin (org) a, destination (dest) b, and apex (apex) */
+/* c. These vertices occur in counterclockwise order about the triangle. */
+/* The handle abc may simultaneously denote vertex a, edge ab, and triangle */
+/* abc. */
+/* */
+/* Similarly, the subsegment ab has origin (sorg) a and destination (sdest) */
+/* b. If ab is thought to be directed upward (with b directly above a), */
+/* then the handle ab is thought to grasp the right side of ab, and may */
+/* simultaneously denote vertex a and edge ab. */
+/* */
+/* An asterisk (*) denotes a vertex whose identity is unknown. */
+/* */
+/* Given this notation, a partial list of mesh manipulation primitives */
+/* follows. */
+/* */
+/* */
+/* For triangles: */
+/* */
+/* sym: Find the abutting triangle; same edge. */
+/* sym(abc) -> ba* */
+/* */
+/* lnext: Find the next edge (counterclockwise) of a triangle. */
+/* lnext(abc) -> bca */
+/* */
+/* lprev: Find the previous edge (clockwise) of a triangle. */
+/* lprev(abc) -> cab */
+/* */
+/* onext: Find the next edge counterclockwise with the same origin. */
+/* onext(abc) -> ac* */
+/* */
+/* oprev: Find the next edge clockwise with the same origin. */
+/* oprev(abc) -> a*b */
+/* */
+/* dnext: Find the next edge counterclockwise with the same destination. */
+/* dnext(abc) -> *ba */
+/* */
+/* dprev: Find the next edge clockwise with the same destination. */
+/* dprev(abc) -> cb* */
+/* */
+/* rnext: Find the next edge (counterclockwise) of the adjacent triangle. */
+/* rnext(abc) -> *a* */
+/* */
+/* rprev: Find the previous edge (clockwise) of the adjacent triangle. */
+/* rprev(abc) -> b** */
+/* */
+/* org: Origin dest: Destination apex: Apex */
+/* org(abc) -> a dest(abc) -> b apex(abc) -> c */
+/* */
+/* bond: Bond two triangles together at the resepective handles. */
+/* bond(abc, bad) */
+/* */
+/* */
+/* For subsegments: */
+/* */
+/* ssym: Reverse the orientation of a subsegment. */
+/* ssym(ab) -> ba */
+/* */
+/* spivot: Find adjoining subsegment with the same origin. */
+/* spivot(ab) -> a* */
+/* */
+/* snext: Find next subsegment in sequence. */
+/* snext(ab) -> b* */
+/* */
+/* sorg: Origin sdest: Destination */
+/* sorg(ab) -> a sdest(ab) -> b */
+/* */
+/* sbond: Bond two subsegments together at the respective origins. */
+/* sbond(ab, ac) */
+/* */
+/* */
+/* For interacting tetrahedra and subfacets: */
+/* */
+/* tspivot: Find a subsegment abutting a triangle. */
+/* tspivot(abc) -> ba */
+/* */
+/* stpivot: Find a triangle abutting a subsegment. */
+/* stpivot(ab) -> ba* */
+/* */
+/* tsbond: Bond a triangle to a subsegment. */
+/* tsbond(abc, ba) */
+/* */
+/*****************************************************************************/
+
+/********* Mesh manipulation primitives begin here *********/
+/** **/
+/** **/
+
+/* Fast lookup arrays to speed some of the mesh manipulation primitives. */
+
+int plus1mod3[3] = {1, 2, 0};
+int minus1mod3[3] = {2, 0, 1};
+
+/********* Primitives for triangles *********/
+/* */
+/* */
+
+/* decode() converts a pointer to an oriented triangle. The orientation is */
+/* extracted from the two least significant bits of the pointer. */
+
+#define decode(ptr, otri) \
+ (otri).orient = (int) ((unsigned long) (ptr) & (unsigned long) 3l); \
+ (otri).tri = (triangle *) \
+ ((unsigned long) (ptr) ^ (unsigned long) (otri).orient)
+
+/* encode() compresses an oriented triangle into a single pointer. It */
+/* relies on the assumption that all triangles are aligned to four-byte */
+/* boundaries, so the two least significant bits of (otri).tri are zero. */
+
+#define encode(otri) \
+ (triangle) ((unsigned long) (otri).tri | (unsigned long) (otri).orient)
+
+/* The following handle manipulation primitives are all described by Guibas */
+/* and Stolfi. However, Guibas and Stolfi use an edge-based data */
+/* structure, whereas I use a triangle-based data structure. */
+
+/* sym() finds the abutting triangle, on the same edge. Note that the edge */
+/* direction is necessarily reversed, because the handle specified by an */
+/* oriented triangle is directed counterclockwise around the triangle. */
+
+#define sym(otri1, otri2) \
+ ptr = (otri1).tri[(otri1).orient]; \
+ decode(ptr, otri2);
+
+#define symself(otri) \
+ ptr = (otri).tri[(otri).orient]; \
+ decode(ptr, otri);
+
+/* lnext() finds the next edge (counterclockwise) of a triangle. */
+
+#define lnext(otri1, otri2) \
+ (otri2).tri = (otri1).tri; \
+ (otri2).orient = plus1mod3[(otri1).orient]
+
+#define lnextself(otri) \
+ (otri).orient = plus1mod3[(otri).orient]
+
+/* lprev() finds the previous edge (clockwise) of a triangle. */
+
+#define lprev(otri1, otri2) \
+ (otri2).tri = (otri1).tri; \
+ (otri2).orient = minus1mod3[(otri1).orient]
+
+#define lprevself(otri) \
+ (otri).orient = minus1mod3[(otri).orient]
+
+/* onext() spins counterclockwise around a vertex; that is, it finds the */
+/* next edge with the same origin in the counterclockwise direction. This */
+/* edge is part of a different triangle. */
+
+#define onext(otri1, otri2) \
+ lprev(otri1, otri2); \
+ symself(otri2);
+
+#define onextself(otri) \
+ lprevself(otri); \
+ symself(otri);
+
+/* oprev() spins clockwise around a vertex; that is, it finds the next edge */
+/* with the same origin in the clockwise direction. This edge is part of */
+/* a different triangle. */
+
+#define oprev(otri1, otri2) \
+ sym(otri1, otri2); \
+ lnextself(otri2);
+
+#define oprevself(otri) \
+ symself(otri); \
+ lnextself(otri);
+
+/* dnext() spins counterclockwise around a vertex; that is, it finds the */
+/* next edge with the same destination in the counterclockwise direction. */
+/* This edge is part of a different triangle. */
+
+#define dnext(otri1, otri2) \
+ sym(otri1, otri2); \
+ lprevself(otri2);
+
+#define dnextself(otri) \
+ symself(otri); \
+ lprevself(otri);
+
+/* dprev() spins clockwise around a vertex; that is, it finds the next edge */
+/* with the same destination in the clockwise direction. This edge is */
+/* part of a different triangle. */
+
+#define dprev(otri1, otri2) \
+ lnext(otri1, otri2); \
+ symself(otri2);
+
+#define dprevself(otri) \
+ lnextself(otri); \
+ symself(otri);
+
+/* rnext() moves one edge counterclockwise about the adjacent triangle. */
+/* (It's best understood by reading Guibas and Stolfi. It involves */
+/* changing triangles twice.) */
+
+#define rnext(otri1, otri2) \
+ sym(otri1, otri2); \
+ lnextself(otri2); \
+ symself(otri2);
+
+#define rnextself(otri) \
+ symself(otri); \
+ lnextself(otri); \
+ symself(otri);
+
+/* rprev() moves one edge clockwise about the adjacent triangle. */
+/* (It's best understood by reading Guibas and Stolfi. It involves */
+/* changing triangles twice.) */
+
+#define rprev(otri1, otri2) \
+ sym(otri1, otri2); \
+ lprevself(otri2); \
+ symself(otri2);
+
+#define rprevself(otri) \
+ symself(otri); \
+ lprevself(otri); \
+ symself(otri);
+
+/* These primitives determine or set the origin, destination, or apex of a */
+/* triangle. */
+
+#define org(otri, vertexptr) \
+ vertexptr = (vertex) (otri).tri[plus1mod3[(otri).orient] + 3]
+
+#define dest(otri, vertexptr) \
+ vertexptr = (vertex) (otri).tri[minus1mod3[(otri).orient] + 3]
+
+#define apex(otri, vertexptr) \
+ vertexptr = (vertex) (otri).tri[(otri).orient + 3]
+
+#define setorg(otri, vertexptr) \
+ (otri).tri[plus1mod3[(otri).orient] + 3] = (triangle) vertexptr
+
+#define setdest(otri, vertexptr) \
+ (otri).tri[minus1mod3[(otri).orient] + 3] = (triangle) vertexptr
+
+#define setapex(otri, vertexptr) \
+ (otri).tri[(otri).orient + 3] = (triangle) vertexptr
+
+/* Bond two triangles together. */
+
+#define bond(otri1, otri2) \
+ (otri1).tri[(otri1).orient] = encode(otri2); \
+ (otri2).tri[(otri2).orient] = encode(otri1)
+
+/* Dissolve a bond (from one side). Note that the other triangle will still */
+/* think it's connected to this triangle. Usually, however, the other */
+/* triangle is being deleted entirely, or bonded to another triangle, so */
+/* it doesn't matter. */
+
+#define dissolve(otri) \
+ (otri).tri[(otri).orient] = (triangle) m->dummytri
+
+/* Copy an oriented triangle. */
+
+#define otricopy(otri1, otri2) \
+ (otri2).tri = (otri1).tri; \
+ (otri2).orient = (otri1).orient
+
+/* Test for equality of oriented triangles. */
+
+#define otriequal(otri1, otri2) \
+ (((otri1).tri == (otri2).tri) && \
+ ((otri1).orient == (otri2).orient))
+
+/* Primitives to infect or cure a triangle with the virus. These rely on */
+/* the assumption that all subsegments are aligned to four-byte boundaries.*/
+
+#define infect(otri) \
+ (otri).tri[6] = (triangle) \
+ ((unsigned long) (otri).tri[6] | (unsigned long) 2l)
+
+#define uninfect(otri) \
+ (otri).tri[6] = (triangle) \
+ ((unsigned long) (otri).tri[6] & ~ (unsigned long) 2l)
+
+/* Test a triangle for viral infection. */
+
+#define infected(otri) \
+ (((unsigned long) (otri).tri[6] & (unsigned long) 2l) != 0l)
+
+/* Check or set a triangle's attributes. */
+
+#define elemattribute(otri, attnum) \
+ ((REAL *) (otri).tri)[m->elemattribindex + (attnum)]
+
+#define setelemattribute(otri, attnum, value) \
+ ((REAL *) (otri).tri)[m->elemattribindex + (attnum)] = value
+
+/* Check or set a triangle's maximum area bound. */
+
+#define areabound(otri) ((REAL *) (otri).tri)[m->areaboundindex]
+
+#define setareabound(otri, value) \
+ ((REAL *) (otri).tri)[m->areaboundindex] = value
+
+/* Check or set a triangle's deallocation. Its second pointer is set to */
+/* NULL to indicate that it is not allocated. (Its first pointer is used */
+/* for the stack of dead items.) Its fourth pointer (its first vertex) */
+/* is set to NULL in case a `badtriang' structure points to it. */
+
+#define deadtri(tria) ((tria)[1] == (triangle) NULL)
+
+#define killtri(tria) \
+ (tria)[1] = (triangle) NULL; \
+ (tria)[3] = (triangle) NULL
+
+/********* Primitives for subsegments *********/
+/* */
+/* */
+
+/* sdecode() converts a pointer to an oriented subsegment. The orientation */
+/* is extracted from the least significant bit of the pointer. The two */
+/* least significant bits (one for orientation, one for viral infection) */
+/* are masked out to produce the real pointer. */
+
+#define sdecode(sptr, osub) \
+ (osub).ssorient = (int) ((unsigned long) (sptr) & (unsigned long) 1l); \
+ (osub).ss = (subseg *) \
+ ((unsigned long) (sptr) & ~ (unsigned long) 3l)
+
+/* sencode() compresses an oriented subsegment into a single pointer. It */
+/* relies on the assumption that all subsegments are aligned to two-byte */
+/* boundaries, so the least significant bit of (osub).ss is zero. */
+
+#define sencode(osub) \
+ (subseg) ((unsigned long) (osub).ss | (unsigned long) (osub).ssorient)
+
+/* ssym() toggles the orientation of a subsegment. */
+
+#define ssym(osub1, osub2) \
+ (osub2).ss = (osub1).ss; \
+ (osub2).ssorient = 1 - (osub1).ssorient
+
+#define ssymself(osub) \
+ (osub).ssorient = 1 - (osub).ssorient
+
+/* spivot() finds the other subsegment (from the same segment) that shares */
+/* the same origin. */
+
+#define spivot(osub1, osub2) \
+ sptr = (osub1).ss[(osub1).ssorient]; \
+ sdecode(sptr, osub2)
+
+#define spivotself(osub) \
+ sptr = (osub).ss[(osub).ssorient]; \
+ sdecode(sptr, osub)
+
+/* snext() finds the next subsegment (from the same segment) in sequence; */
+/* one whose origin is the input subsegment's destination. */
+
+#define snext(osub1, osub2) \
+ sptr = (osub1).ss[1 - (osub1).ssorient]; \
+ sdecode(sptr, osub2)
+
+#define snextself(osub) \
+ sptr = (osub).ss[1 - (osub).ssorient]; \
+ sdecode(sptr, osub)
+
+/* These primitives determine or set the origin or destination of a */
+/* subsegment or the segment that includes it. */
+
+#define sorg(osub, vertexptr) \
+ vertexptr = (vertex) (osub).ss[2 + (osub).ssorient]
+
+#define sdest(osub, vertexptr) \
+ vertexptr = (vertex) (osub).ss[3 - (osub).ssorient]
+
+#define setsorg(osub, vertexptr) \
+ (osub).ss[2 + (osub).ssorient] = (subseg) vertexptr
+
+#define setsdest(osub, vertexptr) \
+ (osub).ss[3 - (osub).ssorient] = (subseg) vertexptr
+
+#define segorg(osub, vertexptr) \
+ vertexptr = (vertex) (osub).ss[4 + (osub).ssorient]
+
+#define segdest(osub, vertexptr) \
+ vertexptr = (vertex) (osub).ss[5 - (osub).ssorient]
+
+#define setsegorg(osub, vertexptr) \
+ (osub).ss[4 + (osub).ssorient] = (subseg) vertexptr
+
+#define setsegdest(osub, vertexptr) \
+ (osub).ss[5 - (osub).ssorient] = (subseg) vertexptr
+
+/* These primitives read or set a boundary marker. Boundary markers are */
+/* used to hold user-defined tags for setting boundary conditions in */
+/* finite element solvers. */
+
+#define mark(osub) (* (int *) ((osub).ss + 8))
+
+#define setmark(osub, value) \
+ * (int *) ((osub).ss + 8) = value
+
+/* Bond two subsegments together. */
+
+#define sbond(osub1, osub2) \
+ (osub1).ss[(osub1).ssorient] = sencode(osub2); \
+ (osub2).ss[(osub2).ssorient] = sencode(osub1)
+
+/* Dissolve a subsegment bond (from one side). Note that the other */
+/* subsegment will still think it's connected to this subsegment. */
+
+#define sdissolve(osub) \
+ (osub).ss[(osub).ssorient] = (subseg) m->dummysub
+
+/* Copy a subsegment. */
+
+#define subsegcopy(osub1, osub2) \
+ (osub2).ss = (osub1).ss; \
+ (osub2).ssorient = (osub1).ssorient
+
+/* Test for equality of subsegments. */
+
+#define subsegequal(osub1, osub2) \
+ (((osub1).ss == (osub2).ss) && \
+ ((osub1).ssorient == (osub2).ssorient))
+
+/* Check or set a subsegment's deallocation. Its second pointer is set to */
+/* NULL to indicate that it is not allocated. (Its first pointer is used */
+/* for the stack of dead items.) Its third pointer (its first vertex) */
+/* is set to NULL in case a `badsubseg' structure points to it. */
+
+#define deadsubseg(sub) ((sub)[1] == (subseg) NULL)
+
+#define killsubseg(sub) \
+ (sub)[1] = (subseg) NULL; \
+ (sub)[2] = (subseg) NULL
+
+/********* Primitives for interacting triangles and subsegments *********/
+/* */
+/* */
+
+/* tspivot() finds a subsegment abutting a triangle. */
+
+#define tspivot(otri, osub) \
+ sptr = (subseg) (otri).tri[6 + (otri).orient]; \
+ sdecode(sptr, osub)
+
+/* stpivot() finds a triangle abutting a subsegment. It requires that the */
+/* variable `ptr' of type `triangle' be defined. */
+
+#define stpivot(osub, otri) \
+ ptr = (triangle) (osub).ss[6 + (osub).ssorient]; \
+ decode(ptr, otri)
+
+/* Bond a triangle to a subsegment. */
+
+#define tsbond(otri, osub) \
+ (otri).tri[6 + (otri).orient] = (triangle) sencode(osub); \
+ (osub).ss[6 + (osub).ssorient] = (subseg) encode(otri)
+
+/* Dissolve a bond (from the triangle side). */
+
+#define tsdissolve(otri) \
+ (otri).tri[6 + (otri).orient] = (triangle) m->dummysub
+
+/* Dissolve a bond (from the subsegment side). */
+
+#define stdissolve(osub) \
+ (osub).ss[6 + (osub).ssorient] = (subseg) m->dummytri
+
+/********* Primitives for vertices *********/
+/* */
+/* */
+
+#define vertexmark(vx) ((int *) (vx))[m->vertexmarkindex]
+
+#define setvertexmark(vx, value) \
+ ((int *) (vx))[m->vertexmarkindex] = value
+
+#define vertextype(vx) ((int *) (vx))[m->vertexmarkindex + 1]
+
+#define setvertextype(vx, value) \
+ ((int *) (vx))[m->vertexmarkindex + 1] = value
+
+#define vertex2tri(vx) ((triangle *) (vx))[m->vertex2triindex]
+
+#define setvertex2tri(vx, value) \
+ ((triangle *) (vx))[m->vertex2triindex] = value
+
+/** **/
+/** **/
+/********* Mesh manipulation primitives end here *********/
+
+/********* User-defined triangle evaluation routine begins here *********/
+/** **/
+/** **/
+
+/*****************************************************************************/
+/* */
+/* triunsuitable() Determine if a triangle is unsuitable, and thus must */
+/* be further refined. */
+/* */
+/* You may write your own procedure that decides whether or not a selected */
+/* triangle is too big (and needs to be refined). There are two ways to do */
+/* this. */
+/* */
+/* (1) Modify the procedure `triunsuitable' below, then recompile */
+/* Triangle. */
+/* */
+/* (2) Define the symbol EXTERNAL_TEST (either by adding the definition */
+/* to this file, or by using the appropriate compiler switch). This way, */
+/* you can compile triangle.c separately from your test. Write your own */
+/* `triunsuitable' procedure in a separate C file (using the same prototype */
+/* as below). Compile it and link the object code with triangle.o. */
+/* */
+/* This procedure returns 1 if the triangle is too large and should be */
+/* refined; 0 otherwise. */
+/* */
+/*****************************************************************************/
+
+#ifdef EXTERNAL_TEST
+
+int triunsuitable();
+
+#else /* not EXTERNAL_TEST */
+
+#ifdef ANSI_DECLARATORS
+int triunsuitable(vertex triorg, vertex tridest, vertex triapex, REAL area)
+#else /* not ANSI_DECLARATORS */
+int triunsuitable(triorg, tridest, triapex, area)
+vertex triorg; /* The triangle's origin vertex. */
+vertex tridest; /* The triangle's destination vertex. */
+vertex triapex; /* The triangle's apex vertex. */
+REAL area; /* The area of the triangle. */
+#endif /* not ANSI_DECLARATORS */
+
+{
+ REAL dxoa, dxda, dxod;
+ REAL dyoa, dyda, dyod;
+ REAL oalen, dalen, odlen;
+ REAL maxlen;
+
+ dxoa = triorg[0] - triapex[0];
+ dyoa = triorg[1] - triapex[1];
+ dxda = tridest[0] - triapex[0];
+ dyda = tridest[1] - triapex[1];
+ dxod = triorg[0] - tridest[0];
+ dyod = triorg[1] - tridest[1];
+ /* Find the squares of the lengths of the triangle's three edges. */
+ oalen = dxoa * dxoa + dyoa * dyoa;
+ dalen = dxda * dxda + dyda * dyda;
+ odlen = dxod * dxod + dyod * dyod;
+ /* Find the square of the length of the longest edge. */
+ maxlen = (dalen > oalen) ? dalen : oalen;
+ maxlen = (odlen > maxlen) ? odlen : maxlen;
+
+ if (maxlen > 0.05 * (triorg[0] * triorg[0] + triorg[1] * triorg[1]) + 0.02) {
+ return 1;
+ } else {
+ return 0;
+ }
+}
+
+#endif /* not EXTERNAL_TEST */
+
+/** **/
+/** **/
+/********* User-defined triangle evaluation routine ends here *********/
+
+/********* Memory allocation and program exit wrappers begin here *********/
+/** **/
+/** **/
+
+#ifdef ANSI_DECLARATORS
+void triexit(int status)
+#else /* not ANSI_DECLARATORS */
+void triexit(status)
+int status;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ exit(status);
+}
+
+#ifdef ANSI_DECLARATORS
+VOID *trimalloc(int size)
+#else /* not ANSI_DECLARATORS */
+VOID *trimalloc(size)
+int size;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ VOID *memptr;
+
+ memptr = (VOID *) malloc((unsigned int) size);
+ if (memptr == (VOID *) NULL) {
+ printf("Error: Out of memory.\n");
+ triexit(1);
+ }
+ return(memptr);
+}
+
+#ifdef ANSI_DECLARATORS
+void trifree(VOID *memptr)
+#else /* not ANSI_DECLARATORS */
+void trifree(memptr)
+VOID *memptr;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ free(memptr);
+}
+
+/** **/
+/** **/
+/********* Memory allocation and program exit wrappers end here *********/
+
+/********* User interaction routines begin here *********/
+/** **/
+/** **/
+
+/*****************************************************************************/
+/* */
+/* syntax() Print list of command line switches. */
+/* */
+/*****************************************************************************/
+
+#ifndef TRILIBRARY
+
+void syntax()
+{
+#ifdef CDT_ONLY
+#ifdef REDUCED
+ printf("triangle [-pAcjevngBPNEIOXzo_lQVh] input_file\n");
+#else /* not REDUCED */
+ printf("triangle [-pAcjevngBPNEIOXzo_iFlCQVh] input_file\n");
+#endif /* not REDUCED */
+#else /* not CDT_ONLY */
+#ifdef REDUCED
+ printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__lQVh] input_file\n");
+#else /* not REDUCED */
+ printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__iFlsCQVh] input_file\n");
+#endif /* not REDUCED */
+#endif /* not CDT_ONLY */
+
+ printf(" -p Triangulates a Planar Straight Line Graph (.poly file).\n");
+#ifndef CDT_ONLY
+ printf(" -r Refines a previously generated mesh.\n");
+ printf(
+ " -q Quality mesh generation. A minimum angle may be specified.\n");
+ printf(" -a Applies a maximum triangle area constraint.\n");
+ printf(" -u Applies a user-defined triangle constraint.\n");
+#endif /* not CDT_ONLY */
+ printf(
+ " -A Applies attributes to identify triangles in certain regions.\n");
+ printf(" -c Encloses the convex hull with segments.\n");
+#ifndef CDT_ONLY
+ printf(" -D Conforming Delaunay: all triangles are truly Delaunay.\n");
+#endif /* not CDT_ONLY */
+/*
+ printf(" -w Weighted Delaunay triangulation.\n");
+ printf(" -W Regular triangulation (lower hull of a height field).\n");
+*/
+ printf(" -j Jettison unused vertices from output .node file.\n");
+ printf(" -e Generates an edge list.\n");
+ printf(" -v Generates a Voronoi diagram.\n");
+ printf(" -n Generates a list of triangle neighbors.\n");
+ printf(" -g Generates an .off file for Geomview.\n");
+ printf(" -B Suppresses output of boundary information.\n");
+ printf(" -P Suppresses output of .poly file.\n");
+ printf(" -N Suppresses output of .node file.\n");
+ printf(" -E Suppresses output of .ele file.\n");
+ printf(" -I Suppresses mesh iteration numbers.\n");
+ printf(" -O Ignores holes in .poly file.\n");
+ printf(" -X Suppresses use of exact arithmetic.\n");
+ printf(" -z Numbers all items starting from zero (rather than one).\n");
+ printf(" -o2 Generates second-order subparametric elements.\n");
+#ifndef CDT_ONLY
+ printf(" -Y Suppresses boundary segment splitting.\n");
+ printf(" -S Specifies maximum number of added Steiner points.\n");
+#endif /* not CDT_ONLY */
+#ifndef REDUCED
+ printf(" -i Uses incremental method, rather than divide-and-conquer.\n");
+ printf(" -F Uses Fortune's sweepline algorithm, rather than d-and-c.\n");
+#endif /* not REDUCED */
+ printf(" -l Uses vertical cuts only, rather than alternating cuts.\n");
+#ifndef REDUCED
+#ifndef CDT_ONLY
+ printf(
+ " -s Force segments into mesh by splitting (instead of using CDT).\n");
+#endif /* not CDT_ONLY */
+ printf(" -C Check consistency of final mesh.\n");
+#endif /* not REDUCED */
+ printf(" -Q Quiet: No terminal output except errors.\n");
+ printf(" -V Verbose: Detailed information on what I'm doing.\n");
+ printf(" -h Help: Detailed instructions for Triangle.\n");
+ triexit(0);
+}
+
+#endif /* not TRILIBRARY */
+
+/*****************************************************************************/
+/* */
+/* info() Print out complete instructions. */
+/* */
+/*****************************************************************************/
+
+#ifndef TRILIBRARY
+
+void info()
+{
+ printf("Triangle\n");
+ printf(
+"A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.\n");
+ printf("Version 1.6\n\n");
+ printf(
+"Copyright 1993, 1995, 1997, 1998, 2002, 2005 Jonathan Richard Shewchuk\n");
+ printf("2360 Woolsey #H / Berkeley, California 94705-1927\n");
+ printf("Bugs/comments to jrs at cs.berkeley.edu\n");
+ printf(
+"Created as part of the Quake project (tools for earthquake simulation).\n");
+ printf(
+"Supported in part by NSF Grant CMS-9318163 and an NSERC 1967 Scholarship.\n");
+ printf("There is no warranty whatsoever. Use at your own risk.\n");
+#ifdef SINGLE
+ printf("This executable is compiled for single precision arithmetic.\n\n\n");
+#else /* not SINGLE */
+ printf("This executable is compiled for double precision arithmetic.\n\n\n");
+#endif /* not SINGLE */
+ printf(
+"Triangle generates exact Delaunay triangulations, constrained Delaunay\n");
+ printf(
+"triangulations, conforming Delaunay triangulations, Voronoi diagrams, and\n");
+ printf(
+"high-quality triangular meshes. The latter can be generated with no small\n"
+);
+ printf(
+"or large angles, and are thus suitable for finite element analysis. If no\n"
+);
+ printf(
+"command line switch is specified, your .node input file is read, and the\n");
+ printf(
+"Delaunay triangulation is returned in .node and .ele output files. The\n");
+ printf("command syntax is:\n\n");
+ printf("triangle [-prq__a__uAcDjevngBPNEIOXzo_YS__iFlsCQVh] input_file\n\n");
+ printf(
+"Underscores indicate that numbers may optionally follow certain switches.\n");
+ printf(
+"Do not leave any space between a switch and its numeric parameter.\n");
+ printf(
+"input_file must be a file with extension .node, or extension .poly if the\n");
+ printf(
+"-p switch is used. If -r is used, you must supply .node and .ele files,\n");
+ printf(
+"and possibly a .poly file and an .area file as well. The formats of these\n"
+);
+ printf("files are described below.\n\n");
+ printf("Command Line Switches:\n\n");
+ printf(
+" -p Reads a Planar Straight Line Graph (.poly file), which can specify\n"
+);
+ printf(
+" vertices, segments, holes, regional attributes, and regional area\n");
+ printf(
+" constraints. Generates a constrained Delaunay triangulation (CDT)\n"
+);
+ printf(
+" fitting the input; or, if -s, -q, -a, or -u is used, a conforming\n");
+ printf(
+" constrained Delaunay triangulation (CCDT). If you want a truly\n");
+ printf(
+" Delaunay (not just constrained Delaunay) triangulation, use -D as\n");
+ printf(
+" well. When -p is not used, Triangle reads a .node file by default.\n"
+);
+ printf(
+" -r Refines a previously generated mesh. The mesh is read from a .node\n"
+);
+ printf(
+" file and an .ele file. If -p is also used, a .poly file is read\n");
+ printf(
+" and used to constrain segments in the mesh. If -a is also used\n");
+ printf(
+" (with no number following), an .area file is read and used to\n");
+ printf(
+" impose area constraints on the mesh. Further details on refinement\n"
+);
+ printf(" appear below.\n");
+ printf(
+" -q Quality mesh generation by Delaunay refinement (a hybrid of Paul\n");
+ printf(
+" Chew's and Jim Ruppert's algorithms). Adds vertices to the mesh to\n"
+);
+ printf(
+" ensure that all angles are between 20 and 140 degrees. An\n");
+ printf(
+" alternative bound on the minimum angle, replacing 20 degrees, may\n");
+ printf(
+" be specified after the `q'. The specified angle may include a\n");
+ printf(
+" decimal point, but not exponential notation. Note that a bound of\n"
+);
+ printf(
+" theta degrees on the smallest angle also implies a bound of\n");
+ printf(
+" (180 - 2 theta) on the largest angle. If the minimum angle is 28.6\n"
+);
+ printf(
+" degrees or smaller, Triangle is mathematically guaranteed to\n");
+ printf(
+" terminate (assuming infinite precision arithmetic--Triangle may\n");
+ printf(
+" fail to terminate if you run out of precision). In practice,\n");
+ printf(
+" Triangle often succeeds for minimum angles up to 34 degrees. For\n");
+ printf(
+" some meshes, however, you might need to reduce the minimum angle to\n"
+);
+ printf(
+" avoid problems associated with insufficient floating-point\n");
+ printf(" precision.\n");
+ printf(
+" -a Imposes a maximum triangle area. If a number follows the `a', no\n");
+ printf(
+" triangle is generated whose area is larger than that number. If no\n"
+);
+ printf(
+" number is specified, an .area file (if -r is used) or .poly file\n");
+ printf(
+" (if -r is not used) specifies a set of maximum area constraints.\n");
+ printf(
+" An .area file contains a separate area constraint for each\n");
+ printf(
+" triangle, and is useful for refining a finite element mesh based on\n"
+);
+ printf(
+" a posteriori error estimates. A .poly file can optionally contain\n"
+);
+ printf(
+" an area constraint for each segment-bounded region, thereby\n");
+ printf(
+" controlling triangle densities in a first triangulation of a PSLG.\n"
+);
+ printf(
+" You can impose both a fixed area constraint and a varying area\n");
+ printf(
+" constraint by invoking the -a switch twice, once with and once\n");
+ printf(
+" without a number following. Each area specified may include a\n");
+ printf(" decimal point.\n");
+ printf(
+" -u Imposes a user-defined constraint on triangle size. There are two\n"
+);
+ printf(
+" ways to use this feature. One is to edit the triunsuitable()\n");
+ printf(
+" procedure in triangle.c to encode any constraint you like, then\n");
+ printf(
+" recompile Triangle. The other is to compile triangle.c with the\n");
+ printf(
+" EXTERNAL_TEST symbol set (compiler switch -DEXTERNAL_TEST), then\n");
+ printf(
+" link Triangle with a separate object file that implements\n");
+ printf(
+" triunsuitable(). In either case, the -u switch causes the user-\n");
+ printf(" defined test to be applied to every triangle.\n");
+ printf(
+" -A Assigns an additional floating-point attribute to each triangle\n");
+ printf(
+" that identifies what segment-bounded region each triangle belongs\n");
+ printf(
+" to. Attributes are assigned to regions by the .poly file. If a\n");
+ printf(
+" region is not explicitly marked by the .poly file, triangles in\n");
+ printf(
+" that region are assigned an attribute of zero. The -A switch has\n");
+ printf(
+" an effect only when the -p switch is used and the -r switch is not.\n"
+);
+ printf(
+" -c Creates segments on the convex hull of the triangulation. If you\n");
+ printf(
+" are triangulating a vertex set, this switch causes a .poly file to\n"
+);
+ printf(
+" be written, containing all edges of the convex hull. If you are\n");
+ printf(
+" triangulating a PSLG, this switch specifies that the whole convex\n");
+ printf(
+" hull of the PSLG should be triangulated, regardless of what\n");
+ printf(
+" segments the PSLG has. If you do not use this switch when\n");
+ printf(
+" triangulating a PSLG, Triangle assumes that you have identified the\n"
+);
+ printf(
+" region to be triangulated by surrounding it with segments of the\n");
+ printf(
+" input PSLG. Beware: if you are not careful, this switch can cause\n"
+);
+ printf(
+" the introduction of an extremely thin angle between a PSLG segment\n"
+);
+ printf(
+" and a convex hull segment, which can cause overrefinement (and\n");
+ printf(
+" possibly failure if Triangle runs out of precision). If you are\n");
+ printf(
+" refining a mesh, the -c switch works differently: it causes a\n");
+ printf(
+" .poly file to be written containing the boundary edges of the mesh\n"
+);
+ printf(" (useful if no .poly file was read).\n");
+ printf(
+" -D Conforming Delaunay triangulation: use this switch if you want to\n"
+);
+ printf(
+" ensure that all the triangles in the mesh are Delaunay, and not\n");
+ printf(
+" merely constrained Delaunay; or if you want to ensure that all the\n"
+);
+ printf(
+" Voronoi vertices lie within the triangulation. (Some finite volume\n"
+);
+ printf(
+" methods have this requirement.) This switch invokes Ruppert's\n");
+ printf(
+" original algorithm, which splits every subsegment whose diametral\n");
+ printf(
+" circle is encroached. It usually increases the number of vertices\n"
+);
+ printf(" and triangles.\n");
+ printf(
+" -j Jettisons vertices that are not part of the final triangulation\n");
+ printf(
+" from the output .node file. By default, Triangle copies all\n");
+ printf(
+" vertices in the input .node file to the output .node file, in the\n");
+ printf(
+" same order, so their indices do not change. The -j switch prevents\n"
+);
+ printf(
+" duplicated input vertices, or vertices `eaten' by holes, from\n");
+ printf(
+" appearing in the output .node file. Thus, if two input vertices\n");
+ printf(
+" have exactly the same coordinates, only the first appears in the\n");
+ printf(
+" output. If any vertices are jettisoned, the vertex numbering in\n");
+ printf(
+" the output .node file differs from that of the input .node file.\n");
+ printf(
+" -e Outputs (to an .edge file) a list of edges of the triangulation.\n");
+ printf(
+" -v Outputs the Voronoi diagram associated with the triangulation.\n");
+ printf(
+" Does not attempt to detect degeneracies, so some Voronoi vertices\n");
+ printf(
+" may be duplicated. See the discussion of Voronoi diagrams below.\n");
+ printf(
+" -n Outputs (to a .neigh file) a list of triangles neighboring each\n");
+ printf(" triangle.\n");
+ printf(
+" -g Outputs the mesh to an Object File Format (.off) file, suitable for\n"
+);
+ printf(" viewing with the Geometry Center's Geomview package.\n");
+ printf(
+" -B No boundary markers in the output .node, .poly, and .edge output\n");
+ printf(
+" files. See the detailed discussion of boundary markers below.\n");
+ printf(
+" -P No output .poly file. Saves disk space, but you lose the ability\n");
+ printf(
+" to maintain constraining segments on later refinements of the mesh.\n"
+);
+ printf(" -N No output .node file.\n");
+ printf(" -E No output .ele file.\n");
+ printf(
+" -I No iteration numbers. Suppresses the output of .node and .poly\n");
+ printf(
+" files, so your input files won't be overwritten. (If your input is\n"
+);
+ printf(
+" a .poly file only, a .node file is written.) Cannot be used with\n");
+ printf(
+" the -r switch, because that would overwrite your input .ele file.\n");
+ printf(
+" Shouldn't be used with the -q, -a, -u, or -s switch if you are\n");
+ printf(
+" using a .node file for input, because no .node file is written, so\n"
+);
+ printf(" there is no record of any added Steiner points.\n");
+ printf(" -O No holes. Ignores the holes in the .poly file.\n");
+ printf(
+" -X No exact arithmetic. Normally, Triangle uses exact floating-point\n"
+);
+ printf(
+" arithmetic for certain tests if it thinks the inexact tests are not\n"
+);
+ printf(
+" accurate enough. Exact arithmetic ensures the robustness of the\n");
+ printf(
+" triangulation algorithms, despite floating-point roundoff error.\n");
+ printf(
+" Disabling exact arithmetic with the -X switch causes a small\n");
+ printf(
+" improvement in speed and creates the possibility that Triangle will\n"
+);
+ printf(" fail to produce a valid mesh. Not recommended.\n");
+ printf(
+" -z Numbers all items starting from zero (rather than one). Note that\n"
+);
+ printf(
+" this switch is normally overridden by the value used to number the\n"
+);
+ printf(
+" first vertex of the input .node or .poly file. However, this\n");
+ printf(
+" switch is useful when calling Triangle from another program.\n");
+ printf(
+" -o2 Generates second-order subparametric elements with six nodes each.\n"
+);
+ printf(
+" -Y No new vertices on the boundary. This switch is useful when the\n");
+ printf(
+" mesh boundary must be preserved so that it conforms to some\n");
+ printf(
+" adjacent mesh. Be forewarned that you will probably sacrifice much\n"
+);
+ printf(
+" of the quality of the mesh; Triangle will try, but the resulting\n");
+ printf(
+" mesh may contain poorly shaped triangles. Works well if all the\n");
+ printf(
+" boundary vertices are closely spaced. Specify this switch twice\n");
+ printf(
+" (`-YY') to prevent all segment splitting, including internal\n");
+ printf(" boundaries.\n");
+ printf(
+" -S Specifies the maximum number of Steiner points (vertices that are\n");
+ printf(
+" not in the input, but are added to meet the constraints on minimum\n"
+);
+ printf(
+" angle and maximum area). The default is to allow an unlimited\n");
+ printf(
+" number. If you specify this switch with no number after it,\n");
+ printf(
+" the limit is set to zero. Triangle always adds vertices at segment\n"
+);
+ printf(
+" intersections, even if it needs to use more vertices than the limit\n"
+);
+ printf(
+" you set. When Triangle inserts segments by splitting (-s), it\n");
+ printf(
+" always adds enough vertices to ensure that all the segments of the\n"
+);
+ printf(" PLSG are recovered, ignoring the limit if necessary.\n");
+ printf(
+" -i Uses an incremental rather than a divide-and-conquer algorithm to\n");
+ printf(
+" construct a Delaunay triangulation. Try it if the divide-and-\n");
+ printf(" conquer algorithm fails.\n");
+ printf(
+" -F Uses Steven Fortune's sweepline algorithm to construct a Delaunay\n");
+ printf(
+" triangulation. Warning: does not use exact arithmetic for all\n");
+ printf(" calculations. An exact result is not guaranteed.\n");
+ printf(
+" -l Uses only vertical cuts in the divide-and-conquer algorithm. By\n");
+ printf(
+" default, Triangle alternates between vertical and horizontal cuts,\n"
+);
+ printf(
+" which usually improve the speed except with vertex sets that are\n");
+ printf(
+" small or short and wide. This switch is primarily of theoretical\n");
+ printf(" interest.\n");
+ printf(
+" -s Specifies that segments should be forced into the triangulation by\n"
+);
+ printf(
+" recursively splitting them at their midpoints, rather than by\n");
+ printf(
+" generating a constrained Delaunay triangulation. Segment splitting\n"
+);
+ printf(
+" is true to Ruppert's original algorithm, but can create needlessly\n"
+);
+ printf(
+" small triangles. This switch is primarily of theoretical interest.\n"
+);
+ printf(
+" -C Check the consistency of the final mesh. Uses exact arithmetic for\n"
+);
+ printf(
+" checking, even if the -X switch is used. Useful if you suspect\n");
+ printf(" Triangle is buggy.\n");
+ printf(
+" -Q Quiet: Suppresses all explanation of what Triangle is doing,\n");
+ printf(" unless an error occurs.\n");
+ printf(
+" -V Verbose: Gives detailed information about what Triangle is doing.\n"
+);
+ printf(
+" Add more `V's for increasing amount of detail. `-V' is most\n");
+ printf(
+" useful; itgives information on algorithmic progress and much more\n");
+ printf(
+" detailed statistics. `-VV' gives vertex-by-vertex details, and\n");
+ printf(
+" prints so much that Triangle runs much more slowly. `-VVVV' gives\n"
+);
+ printf(" information only a debugger could love.\n");
+ printf(" -h Help: Displays these instructions.\n");
+ printf("\n");
+ printf("Definitions:\n");
+ printf("\n");
+ printf(
+" A Delaunay triangulation of a vertex set is a triangulation whose\n");
+ printf(
+" vertices are the vertex set, that covers the convex hull of the vertex\n");
+ printf(
+" set. A Delaunay triangulation has the property that no vertex lies\n");
+ printf(
+" inside the circumscribing circle (circle that passes through all three\n");
+ printf(" vertices) of any triangle in the triangulation.\n\n");
+ printf(
+" A Voronoi diagram of a vertex set is a subdivision of the plane into\n");
+ printf(
+" polygonal cells (some of which may be unbounded, meaning infinitely\n");
+ printf(
+" large), where each cell is the set of points in the plane that are closer\n"
+);
+ printf(
+" to some input vertex than to any other input vertex. The Voronoi diagram\n"
+);
+ printf(" is a geometric dual of the Delaunay triangulation.\n\n");
+ printf(
+" A Planar Straight Line Graph (PSLG) is a set of vertices and segments.\n");
+ printf(
+" Segments are simply edges, whose endpoints are all vertices in the PSLG.\n"
+);
+ printf(
+" Segments may intersect each other only at their endpoints. The file\n");
+ printf(" format for PSLGs (.poly files) is described below.\n\n");
+ printf(
+" A constrained Delaunay triangulation (CDT) of a PSLG is similar to a\n");
+ printf(
+" Delaunay triangulation, but each PSLG segment is present as a single edge\n"
+);
+ printf(
+" of the CDT. (A constrained Delaunay triangulation is not truly a\n");
+ printf(
+" Delaunay triangulation, because some of its triangles might not be\n");
+ printf(
+" Delaunay.) By definition, a CDT does not have any vertices other than\n");
+ printf(
+" those specified in the input PSLG. Depending on context, a CDT might\n");
+ printf(
+" cover the convex hull of the PSLG, or it might cover only a segment-\n");
+ printf(" bounded region (e.g. a polygon).\n\n");
+ printf(
+" A conforming Delaunay triangulation of a PSLG is a triangulation in which\n"
+);
+ printf(
+" each triangle is truly Delaunay, and each PSLG segment is represented by\n"
+);
+ printf(
+" a linear contiguous sequence of edges of the triangulation. New vertices\n"
+);
+ printf(
+" (not part of the PSLG) may appear, and each input segment may have been\n");
+ printf(
+" subdivided into shorter edges (subsegments) by these additional vertices.\n"
+);
+ printf(
+" The new vertices are frequently necessary to maintain the Delaunay\n");
+ printf(" property while ensuring that every segment is represented.\n\n");
+ printf(
+" A conforming constrained Delaunay triangulation (CCDT) of a PSLG is a\n");
+ printf(
+" triangulation of a PSLG whose triangles are constrained Delaunay. New\n");
+ printf(" vertices may appear, and input segments may be subdivided into\n");
+ printf(
+" subsegments, but not to guarantee that segments are respected; rather, to\n"
+);
+ printf(
+" improve the quality of the triangles. The high-quality meshes produced\n");
+ printf(
+" by the -q switch are usually CCDTs, but can be made conforming Delaunay\n");
+ printf(" with the -D switch.\n\n");
+ printf("File Formats:\n\n");
+ printf(
+" All files may contain comments prefixed by the character '#'. Vertices,\n"
+);
+ printf(
+" triangles, edges, holes, and maximum area constraints must be numbered\n");
+ printf(
+" consecutively, starting from either 1 or 0. Whichever you choose, all\n");
+ printf(
+" input files must be consistent; if the vertices are numbered from 1, so\n");
+ printf(
+" must be all other objects. Triangle automatically detects your choice\n");
+ printf(
+" while reading the .node (or .poly) file. (When calling Triangle from\n");
+ printf(
+" another program, use the -z switch if you wish to number objects from\n");
+ printf(" zero.) Examples of these file formats are given below.\n\n");
+ printf(" .node files:\n");
+ printf(
+" First line: <# of vertices> <dimension (must be 2)> <# of attributes>\n"
+);
+ printf(
+" <# of boundary markers (0 or 1)>\n"
+);
+ printf(
+" Remaining lines: <vertex #> <x> <y> [attributes] [boundary marker]\n");
+ printf("\n");
+ printf(
+" The attributes, which are typically floating-point values of physical\n");
+ printf(
+" quantities (such as mass or conductivity) associated with the nodes of\n"
+);
+ printf(
+" a finite element mesh, are copied unchanged to the output mesh. If -q,\n"
+);
+ printf(
+" -a, -u, -D, or -s is selected, each new Steiner point added to the mesh\n"
+);
+ printf(" has attributes assigned to it by linear interpolation.\n\n");
+ printf(
+" If the fourth entry of the first line is `1', the last column of the\n");
+ printf(
+" remainder of the file is assumed to contain boundary markers. Boundary\n"
+);
+ printf(
+" markers are used to identify boundary vertices and vertices resting on\n"
+);
+ printf(
+" PSLG segments; a complete description appears in a section below. The\n"
+);
+ printf(
+" .node file produced by Triangle contains boundary markers in the last\n");
+ printf(" column unless they are suppressed by the -B switch.\n\n");
+ printf(" .ele files:\n");
+ printf(
+" First line: <# of triangles> <nodes per triangle> <# of attributes>\n");
+ printf(
+" Remaining lines: <triangle #> <node> <node> <node> ... [attributes]\n");
+ printf("\n");
+ printf(
+" Nodes are indices into the corresponding .node file. The first three\n");
+ printf(
+" nodes are the corner vertices, and are listed in counterclockwise order\n"
+);
+ printf(
+" around each triangle. (The remaining nodes, if any, depend on the type\n"
+);
+ printf(" of finite element used.)\n\n");
+ printf(
+" The attributes are just like those of .node files. Because there is no\n"
+);
+ printf(
+" simple mapping from input to output triangles, Triangle attempts to\n");
+ printf(
+" interpolate attributes, and may cause a lot of diffusion of attributes\n"
+);
+ printf(
+" among nearby triangles as the triangulation is refined. Attributes do\n"
+);
+ printf(" not diffuse across segments, so attributes used to identify\n");
+ printf(" segment-bounded regions remain intact.\n\n");
+ printf(
+" In .ele files produced by Triangle, each triangular element has three\n");
+ printf(
+" nodes (vertices) unless the -o2 switch is used, in which case\n");
+ printf(
+" subparametric quadratic elements with six nodes each are generated.\n");
+ printf(
+" The first three nodes are the corners in counterclockwise order, and\n");
+ printf(
+" the fourth, fifth, and sixth nodes lie on the midpoints of the edges\n");
+ printf(
+" opposite the first, second, and third vertices, respectively.\n");
+ printf("\n");
+ printf(" .poly files:\n");
+ printf(
+" First line: <# of vertices> <dimension (must be 2)> <# of attributes>\n"
+);
+ printf(
+" <# of boundary markers (0 or 1)>\n"
+);
+ printf(
+" Following lines: <vertex #> <x> <y> [attributes] [boundary marker]\n");
+ printf(" One line: <# of segments> <# of boundary markers (0 or 1)>\n");
+ printf(
+" Following lines: <segment #> <endpoint> <endpoint> [boundary marker]\n");
+ printf(" One line: <# of holes>\n");
+ printf(" Following lines: <hole #> <x> <y>\n");
+ printf(
+" Optional line: <# of regional attributes and/or area constraints>\n");
+ printf(
+" Optional following lines: <region #> <x> <y> <attribute> <max area>\n");
+ printf("\n");
+ printf(
+" A .poly file represents a PSLG, as well as some additional information.\n"
+);
+ printf(
+" The first section lists all the vertices, and is identical to the\n");
+ printf(
+" format of .node files. <# of vertices> may be set to zero to indicate\n"
+);
+ printf(
+" that the vertices are listed in a separate .node file; .poly files\n");
+ printf(
+" produced by Triangle always have this format. A vertex set represented\n"
+);
+ printf(
+" this way has the advantage that it may easily be triangulated with or\n");
+ printf(
+" without segments (depending on whether the -p switch is invoked).\n");
+ printf("\n");
+ printf(
+" The second section lists the segments. Segments are edges whose\n");
+ printf(
+" presence in the triangulation is enforced. (Depending on the choice of\n"
+);
+ printf(
+" switches, segment might be subdivided into smaller edges). Each\n");
+ printf(
+" segment is specified by listing the indices of its two endpoints. This\n"
+);
+ printf(
+" means that you must include its endpoints in the vertex list. Each\n");
+ printf(" segment, like each point, may have a boundary marker.\n\n");
+ printf(
+" If -q, -a, -u, and -s are not selected, Triangle produces a constrained\n"
+);
+ printf(
+" Delaunay triangulation (CDT), in which each segment appears as a single\n"
+);
+ printf(
+" edge in the triangulation. If -q, -a, -u, or -s is selected, Triangle\n"
+);
+ printf(
+" produces a conforming constrained Delaunay triangulation (CCDT), in\n");
+ printf(
+" which segments may be subdivided into smaller edges. If -D is\n");
+ printf(
+" selected, Triangle produces a conforming Delaunay triangulation, so\n");
+ printf(
+" that every triangle is Delaunay, and not just constrained Delaunay.\n");
+ printf("\n");
+ printf(
+" The third section lists holes (and concavities, if -c is selected) in\n");
+ printf(
+" the triangulation. Holes are specified by identifying a point inside\n");
+ printf(
+" each hole. After the triangulation is formed, Triangle creates holes\n");
+ printf(
+" by eating triangles, spreading out from each hole point until its\n");
+ printf(
+" progress is blocked by segments in the PSLG. You must be careful to\n");
+ printf(
+" enclose each hole in segments, or your whole triangulation might be\n");
+ printf(
+" eaten away. If the two triangles abutting a segment are eaten, the\n");
+ printf(
+" segment itself is also eaten. Do not place a hole directly on a\n");
+ printf(" segment; if you do, Triangle chooses one side of the segment\n");
+ printf(" arbitrarily.\n\n");
+ printf(
+" The optional fourth section lists regional attributes (to be assigned\n");
+ printf(
+" to all triangles in a region) and regional constraints on the maximum\n");
+ printf(
+" triangle area. Triangle reads this section only if the -A switch is\n");
+ printf(
+" used or the -a switch is used without a number following it, and the -r\n"
+);
+ printf(
+" switch is not used. Regional attributes and area constraints are\n");
+ printf(
+" propagated in the same manner as holes: you specify a point for each\n");
+ printf(
+" attribute and/or constraint, and the attribute and/or constraint\n");
+ printf(
+" affects the whole region (bounded by segments) containing the point.\n");
+ printf(
+" If two values are written on a line after the x and y coordinate, the\n");
+ printf(
+" first such value is assumed to be a regional attribute (but is only\n");
+ printf(
+" applied if the -A switch is selected), and the second value is assumed\n"
+);
+ printf(
+" to be a regional area constraint (but is only applied if the -a switch\n"
+);
+ printf(
+" is selected). You may specify just one value after the coordinates,\n");
+ printf(
+" which can serve as both an attribute and an area constraint, depending\n"
+);
+ printf(
+" on the choice of switches. If you are using the -A and -a switches\n");
+ printf(
+" simultaneously and wish to assign an attribute to some region without\n");
+ printf(" imposing an area constraint, use a negative maximum area.\n\n");
+ printf(
+" When a triangulation is created from a .poly file, you must either\n");
+ printf(
+" enclose the entire region to be triangulated in PSLG segments, or\n");
+ printf(
+" use the -c switch, which automatically creates extra segments that\n");
+ printf(
+" enclose the convex hull of the PSLG. If you do not use the -c switch,\n"
+);
+ printf(
+" Triangle eats all triangles that are not enclosed by segments; if you\n");
+ printf(
+" are not careful, your whole triangulation may be eaten away. If you do\n"
+);
+ printf(
+" use the -c switch, you can still produce concavities by the appropriate\n"
+);
+ printf(
+" placement of holes just inside the boundary of the convex hull.\n");
+ printf("\n");
+ printf(
+" An ideal PSLG has no intersecting segments, nor any vertices that lie\n");
+ printf(
+" upon segments (except, of course, the endpoints of each segment). You\n"
+);
+ printf(
+" aren't required to make your .poly files ideal, but you should be aware\n"
+);
+ printf(
+" of what can go wrong. Segment intersections are relatively safe--\n");
+ printf(
+" Triangle calculates the intersection points for you and adds them to\n");
+ printf(
+" the triangulation--as long as your machine's floating-point precision\n");
+ printf(
+" doesn't become a problem. You are tempting the fates if you have three\n"
+);
+ printf(
+" segments that cross at the same location, and expect Triangle to figure\n"
+);
+ printf(
+" out where the intersection point is. Thanks to floating-point roundoff\n"
+);
+ printf(
+" error, Triangle will probably decide that the three segments intersect\n"
+);
+ printf(
+" at three different points, and you will find a minuscule triangle in\n");
+ printf(
+" your output--unless Triangle tries to refine the tiny triangle, uses\n");
+ printf(
+" up the last bit of machine precision, and fails to terminate at all.\n");
+ printf(
+" You're better off putting the intersection point in the input files,\n");
+ printf(
+" and manually breaking up each segment into two. Similarly, if you\n");
+ printf(
+" place a vertex at the middle of a segment, and hope that Triangle will\n"
+);
+ printf(
+" break up the segment at that vertex, you might get lucky. On the other\n"
+);
+ printf(
+" hand, Triangle might decide that the vertex doesn't lie precisely on\n");
+ printf(
+" the segment, and you'll have a needle-sharp triangle in your output--or\n"
+);
+ printf(" a lot of tiny triangles if you're generating a quality mesh.\n");
+ printf("\n");
+ printf(
+" When Triangle reads a .poly file, it also writes a .poly file, which\n");
+ printf(
+" includes all the subsegments--the edges that are parts of input\n");
+ printf(
+" segments. If the -c switch is used, the output .poly file also\n");
+ printf(
+" includes all of the edges on the convex hull. Hence, the output .poly\n"
+);
+ printf(
+" file is useful for finding edges associated with input segments and for\n"
+);
+ printf(
+" setting boundary conditions in finite element simulations. Moreover,\n");
+ printf(
+" you will need the output .poly file if you plan to refine the output\n");
+ printf(
+" mesh, and don't want segments to be missing in later triangulations.\n");
+ printf("\n");
+ printf(" .area files:\n");
+ printf(" First line: <# of triangles>\n");
+ printf(" Following lines: <triangle #> <maximum area>\n");
+ printf("\n");
+ printf(
+" An .area file associates with each triangle a maximum area that is used\n"
+);
+ printf(
+" for mesh refinement. As with other file formats, every triangle must\n");
+ printf(
+" be represented, and the triangles must be numbered consecutively. A\n");
+ printf(
+" triangle may be left unconstrained by assigning it a negative maximum\n");
+ printf(" area.\n\n");
+ printf(" .edge files:\n");
+ printf(" First line: <# of edges> <# of boundary markers (0 or 1)>\n");
+ printf(
+" Following lines: <edge #> <endpoint> <endpoint> [boundary marker]\n");
+ printf("\n");
+ printf(
+" Endpoints are indices into the corresponding .node file. Triangle can\n"
+);
+ printf(
+" produce .edge files (use the -e switch), but cannot read them. The\n");
+ printf(
+" optional column of boundary markers is suppressed by the -B switch.\n");
+ printf("\n");
+ printf(
+" In Voronoi diagrams, one also finds a special kind of edge that is an\n");
+ printf(
+" infinite ray with only one endpoint. For these edges, a different\n");
+ printf(" format is used:\n\n");
+ printf(" <edge #> <endpoint> -1 <direction x> <direction y>\n\n");
+ printf(
+" The `direction' is a floating-point vector that indicates the direction\n"
+);
+ printf(" of the infinite ray.\n\n");
+ printf(" .neigh files:\n");
+ printf(
+" First line: <# of triangles> <# of neighbors per triangle (always 3)>\n"
+);
+ printf(
+" Following lines: <triangle #> <neighbor> <neighbor> <neighbor>\n");
+ printf("\n");
+ printf(
+" Neighbors are indices into the corresponding .ele file. An index of -1\n"
+);
+ printf(
+" indicates no neighbor (because the triangle is on an exterior\n");
+ printf(
+" boundary). The first neighbor of triangle i is opposite the first\n");
+ printf(" corner of triangle i, and so on.\n\n");
+ printf(
+" Triangle can produce .neigh files (use the -n switch), but cannot read\n"
+);
+ printf(" them.\n\n");
+ printf("Boundary Markers:\n\n");
+ printf(
+" Boundary markers are tags used mainly to identify which output vertices\n");
+ printf(
+" and edges are associated with which PSLG segment, and to identify which\n");
+ printf(
+" vertices and edges occur on a boundary of the triangulation. A common\n");
+ printf(
+" use is to determine where boundary conditions should be applied to a\n");
+ printf(
+" finite element mesh. You can prevent boundary markers from being written\n"
+);
+ printf(" into files produced by Triangle by using the -B switch.\n\n");
+ printf(
+" The boundary marker associated with each segment in an output .poly file\n"
+);
+ printf(" and each edge in an output .edge file is chosen as follows:\n");
+ printf(
+" - If an output edge is part or all of a PSLG segment with a nonzero\n");
+ printf(
+" boundary marker, then the edge is assigned the same marker.\n");
+ printf(
+" - Otherwise, if the edge lies on a boundary of the triangulation\n");
+ printf(
+" (even the boundary of a hole), then the edge is assigned the marker\n");
+ printf(" one (1).\n");
+ printf(" - Otherwise, the edge is assigned the marker zero (0).\n");
+ printf(
+" The boundary marker associated with each vertex in an output .node file\n");
+ printf(" is chosen as follows:\n");
+ printf(
+" - If a vertex is assigned a nonzero boundary marker in the input file,\n"
+);
+ printf(
+" then it is assigned the same marker in the output .node file.\n");
+ printf(
+" - Otherwise, if the vertex lies on a PSLG segment (even if it is an\n");
+ printf(
+" endpoint of the segment) with a nonzero boundary marker, then the\n");
+ printf(
+" vertex is assigned the same marker. If the vertex lies on several\n");
+ printf(" such segments, one of the markers is chosen arbitrarily.\n");
+ printf(
+" - Otherwise, if the vertex occurs on a boundary of the triangulation,\n");
+ printf(" then the vertex is assigned the marker one (1).\n");
+ printf(" - Otherwise, the vertex is assigned the marker zero (0).\n");
+ printf("\n");
+ printf(
+" If you want Triangle to determine for you which vertices and edges are on\n"
+);
+ printf(
+" the boundary, assign them the boundary marker zero (or use no markers at\n"
+);
+ printf(
+" all) in your input files. In the output files, all boundary vertices,\n");
+ printf(" edges, and segments will be assigned the value one.\n\n");
+ printf("Triangulation Iteration Numbers:\n\n");
+ printf(
+" Because Triangle can read and refine its own triangulations, input\n");
+ printf(
+" and output files have iteration numbers. For instance, Triangle might\n");
+ printf(
+" read the files mesh.3.node, mesh.3.ele, and mesh.3.poly, refine the\n");
+ printf(
+" triangulation, and output the files mesh.4.node, mesh.4.ele, and\n");
+ printf(" mesh.4.poly. Files with no iteration number are treated as if\n");
+ printf(
+" their iteration number is zero; hence, Triangle might read the file\n");
+ printf(
+" points.node, triangulate it, and produce the files points.1.node and\n");
+ printf(" points.1.ele.\n\n");
+ printf(
+" Iteration numbers allow you to create a sequence of successively finer\n");
+ printf(
+" meshes suitable for multigrid methods. They also allow you to produce a\n"
+);
+ printf(
+" sequence of meshes using error estimate-driven mesh refinement.\n");
+ printf("\n");
+ printf(
+" If you're not using refinement or quality meshing, and you don't like\n");
+ printf(
+" iteration numbers, use the -I switch to disable them. This switch also\n");
+ printf(
+" disables output of .node and .poly files to prevent your input files from\n"
+);
+ printf(
+" being overwritten. (If the input is a .poly file that contains its own\n");
+ printf(
+" points, a .node file is written. This can be quite convenient for\n");
+ printf(" computing CDTs or quality meshes.)\n\n");
+ printf("Examples of How to Use Triangle:\n\n");
+ printf(
+" `triangle dots' reads vertices from dots.node, and writes their Delaunay\n"
+);
+ printf(
+" triangulation to dots.1.node and dots.1.ele. (dots.1.node is identical\n");
+ printf(
+" to dots.node.) `triangle -I dots' writes the triangulation to dots.ele\n");
+ printf(
+" instead. (No additional .node file is needed, so none is written.)\n");
+ printf("\n");
+ printf(
+" `triangle -pe object.1' reads a PSLG from object.1.poly (and possibly\n");
+ printf(
+" object.1.node, if the vertices are omitted from object.1.poly) and writes\n"
+);
+ printf(
+" its constrained Delaunay triangulation to object.2.node and object.2.ele.\n"
+);
+ printf(
+" The segments are copied to object.2.poly, and all edges are written to\n");
+ printf(" object.2.edge.\n\n");
+ printf(
+" `triangle -pq31.5a.1 object' reads a PSLG from object.poly (and possibly\n"
+);
+ printf(
+" object.node), generates a mesh whose angles are all between 31.5 and 117\n"
+);
+ printf(
+" degrees and whose triangles all have areas of 0.1 or less, and writes the\n"
+);
+ printf(
+" mesh to object.1.node and object.1.ele. Each segment may be broken up\n");
+ printf(" into multiple subsegments; these are written to object.1.poly.\n");
+ printf("\n");
+ printf(
+" Here is a sample file `box.poly' describing a square with a square hole:\n"
+);
+ printf("\n");
+ printf(
+" # A box with eight vertices in 2D, no attributes, one boundary marker.\n"
+);
+ printf(" 8 2 0 1\n");
+ printf(" # Outer box has these vertices:\n");
+ printf(" 1 0 0 0\n");
+ printf(" 2 0 3 0\n");
+ printf(" 3 3 0 0\n");
+ printf(" 4 3 3 33 # A special marker for this vertex.\n");
+ printf(" # Inner square has these vertices:\n");
+ printf(" 5 1 1 0\n");
+ printf(" 6 1 2 0\n");
+ printf(" 7 2 1 0\n");
+ printf(" 8 2 2 0\n");
+ printf(" # Five segments with boundary markers.\n");
+ printf(" 5 1\n");
+ printf(" 1 1 2 5 # Left side of outer box.\n");
+ printf(" # Square hole has these segments:\n");
+ printf(" 2 5 7 0\n");
+ printf(" 3 7 8 0\n");
+ printf(" 4 8 6 10\n");
+ printf(" 5 6 5 0\n");
+ printf(" # One hole in the middle of the inner square.\n");
+ printf(" 1\n");
+ printf(" 1 1.5 1.5\n");
+ printf("\n");
+ printf(
+" Note that some segments are missing from the outer square, so you must\n");
+ printf(
+" use the `-c' switch. After `triangle -pqc box.poly', here is the output\n"
+);
+ printf(
+" file `box.1.node', with twelve vertices. The last four vertices were\n");
+ printf(
+" added to meet the angle constraint. Vertices 1, 2, and 9 have markers\n");
+ printf(
+" from segment 1. Vertices 6 and 8 have markers from segment 4. All the\n");
+ printf(
+" other vertices but 4 have been marked to indicate that they lie on a\n");
+ printf(" boundary.\n\n");
+ printf(" 12 2 0 1\n");
+ printf(" 1 0 0 5\n");
+ printf(" 2 0 3 5\n");
+ printf(" 3 3 0 1\n");
+ printf(" 4 3 3 33\n");
+ printf(" 5 1 1 1\n");
+ printf(" 6 1 2 10\n");
+ printf(" 7 2 1 1\n");
+ printf(" 8 2 2 10\n");
+ printf(" 9 0 1.5 5\n");
+ printf(" 10 1.5 0 1\n");
+ printf(" 11 3 1.5 1\n");
+ printf(" 12 1.5 3 1\n");
+ printf(" # Generated by triangle -pqc box.poly\n");
+ printf("\n");
+ printf(" Here is the output file `box.1.ele', with twelve triangles.\n");
+ printf("\n");
+ printf(" 12 3 0\n");
+ printf(" 1 5 6 9\n");
+ printf(" 2 10 3 7\n");
+ printf(" 3 6 8 12\n");
+ printf(" 4 9 1 5\n");
+ printf(" 5 6 2 9\n");
+ printf(" 6 7 3 11\n");
+ printf(" 7 11 4 8\n");
+ printf(" 8 7 5 10\n");
+ printf(" 9 12 2 6\n");
+ printf(" 10 8 7 11\n");
+ printf(" 11 5 1 10\n");
+ printf(" 12 8 4 12\n");
+ printf(" # Generated by triangle -pqc box.poly\n\n");
+ printf(
+" Here is the output file `box.1.poly'. Note that segments have been added\n"
+);
+ printf(
+" to represent the convex hull, and some segments have been subdivided by\n");
+ printf(
+" newly added vertices. Note also that <# of vertices> is set to zero to\n");
+ printf(" indicate that the vertices should be read from the .node file.\n");
+ printf("\n");
+ printf(" 0 2 0 1\n");
+ printf(" 12 1\n");
+ printf(" 1 1 9 5\n");
+ printf(" 2 5 7 1\n");
+ printf(" 3 8 7 1\n");
+ printf(" 4 6 8 10\n");
+ printf(" 5 5 6 1\n");
+ printf(" 6 3 10 1\n");
+ printf(" 7 4 11 1\n");
+ printf(" 8 2 12 1\n");
+ printf(" 9 9 2 5\n");
+ printf(" 10 10 1 1\n");
+ printf(" 11 11 3 1\n");
+ printf(" 12 12 4 1\n");
+ printf(" 1\n");
+ printf(" 1 1.5 1.5\n");
+ printf(" # Generated by triangle -pqc box.poly\n");
+ printf("\n");
+ printf("Refinement and Area Constraints:\n");
+ printf("\n");
+ printf(
+" The -r switch causes a mesh (.node and .ele files) to be read and\n");
+ printf(
+" refined. If the -p switch is also used, a .poly file is read and used to\n"
+);
+ printf(
+" specify edges that are constrained and cannot be eliminated (although\n");
+ printf(
+" they can be subdivided into smaller edges) by the refinement process.\n");
+ printf("\n");
+ printf(
+" When you refine a mesh, you generally want to impose tighter constraints.\n"
+);
+ printf(
+" One way to accomplish this is to use -q with a larger angle, or -a\n");
+ printf(
+" followed by a smaller area than you used to generate the mesh you are\n");
+ printf(
+" refining. Another way to do this is to create an .area file, which\n");
+ printf(
+" specifies a maximum area for each triangle, and use the -a switch\n");
+ printf(
+" (without a number following). Each triangle's area constraint is applied\n"
+);
+ printf(
+" to that triangle. Area constraints tend to diffuse as the mesh is\n");
+ printf(
+" refined, so if there are large variations in area constraint between\n");
+ printf(
+" adjacent triangles, you may not get the results you want. In that case,\n"
+);
+ printf(
+" consider instead using the -u switch and writing a C procedure that\n");
+ printf(" determines which triangles are too large.\n\n");
+ printf(
+" If you are refining a mesh composed of linear (three-node) elements, the\n"
+);
+ printf(
+" output mesh contains all the nodes present in the input mesh, in the same\n"
+);
+ printf(
+" order, with new nodes added at the end of the .node file. However, the\n");
+ printf(
+" refinement is not hierarchical: there is no guarantee that each output\n");
+ printf(
+" element is contained in a single input element. Often, an output element\n"
+);
+ printf(
+" can overlap two or three input elements, and some input edges are not\n");
+ printf(
+" present in the output mesh. Hence, a sequence of refined meshes forms a\n"
+);
+ printf(
+" hierarchy of nodes, but not a hierarchy of elements. If you refine a\n");
+ printf(
+" mesh of higher-order elements, the hierarchical property applies only to\n"
+);
+ printf(
+" the nodes at the corners of an element; the midpoint nodes on each edge\n");
+ printf(" are discarded before the mesh is refined.\n\n");
+ printf(
+" Maximum area constraints in .poly files operate differently from those in\n"
+);
+ printf(
+" .area files. A maximum area in a .poly file applies to the whole\n");
+ printf(
+" (segment-bounded) region in which a point falls, whereas a maximum area\n");
+ printf(
+" in an .area file applies to only one triangle. Area constraints in .poly\n"
+);
+ printf(
+" files are used only when a mesh is first generated, whereas area\n");
+ printf(
+" constraints in .area files are used only to refine an existing mesh, and\n"
+);
+ printf(
+" are typically based on a posteriori error estimates resulting from a\n");
+ printf(" finite element simulation on that mesh.\n\n");
+ printf(
+" `triangle -rq25 object.1' reads object.1.node and object.1.ele, then\n");
+ printf(
+" refines the triangulation to enforce a 25 degree minimum angle, and then\n"
+);
+ printf(
+" writes the refined triangulation to object.2.node and object.2.ele.\n");
+ printf("\n");
+ printf(
+" `triangle -rpaa6.2 z.3' reads z.3.node, z.3.ele, z.3.poly, and z.3.area.\n"
+);
+ printf(
+" After reconstructing the mesh and its subsegments, Triangle refines the\n");
+ printf(
+" mesh so that no triangle has area greater than 6.2, and furthermore the\n");
+ printf(
+" triangles satisfy the maximum area constraints in z.3.area. No angle\n");
+ printf(
+" bound is imposed at all. The output is written to z.4.node, z.4.ele, and\n"
+);
+ printf(" z.4.poly.\n\n");
+ printf(
+" The sequence `triangle -qa1 x', `triangle -rqa.3 x.1', `triangle -rqa.1\n");
+ printf(
+" x.2' creates a sequence of successively finer meshes x.1, x.2, and x.3,\n");
+ printf(" suitable for multigrid.\n\n");
+ printf("Convex Hulls and Mesh Boundaries:\n\n");
+ printf(
+" If the input is a vertex set (not a PSLG), Triangle produces its convex\n");
+ printf(
+" hull as a by-product in the output .poly file if you use the -c switch.\n");
+ printf(
+" There are faster algorithms for finding a two-dimensional convex hull\n");
+ printf(" than triangulation, of course, but this one comes for free.\n\n");
+ printf(
+" If the input is an unconstrained mesh (you are using the -r switch but\n");
+ printf(
+" not the -p switch), Triangle produces a list of its boundary edges\n");
+ printf(
+" (including hole boundaries) as a by-product when you use the -c switch.\n");
+ printf(
+" If you also use the -p switch, the output .poly file contains all the\n");
+ printf(" segments from the input .poly file as well.\n\n");
+ printf("Voronoi Diagrams:\n\n");
+ printf(
+" The -v switch produces a Voronoi diagram, in files suffixed .v.node and\n");
+ printf(
+" .v.edge. For example, `triangle -v points' reads points.node, produces\n");
+ printf(
+" its Delaunay triangulation in points.1.node and points.1.ele, and\n");
+ printf(
+" produces its Voronoi diagram in points.1.v.node and points.1.v.edge. The\n"
+);
+ printf(
+" .v.node file contains a list of all Voronoi vertices, and the .v.edge\n");
+ printf(
+" file contains a list of all Voronoi edges, some of which may be infinite\n"
+);
+ printf(
+" rays. (The choice of filenames makes it easy to run the set of Voronoi\n");
+ printf(" vertices through Triangle, if so desired.)\n\n");
+ printf(
+" This implementation does not use exact arithmetic to compute the Voronoi\n"
+);
+ printf(
+" vertices, and does not check whether neighboring vertices are identical.\n"
+);
+ printf(
+" Be forewarned that if the Delaunay triangulation is degenerate or\n");
+ printf(
+" near-degenerate, the Voronoi diagram may have duplicate vertices or\n");
+ printf(" crossing edges.\n\n");
+ printf(
+" The result is a valid Voronoi diagram only if Triangle's output is a true\n"
+);
+ printf(
+" Delaunay triangulation. The Voronoi output is usually meaningless (and\n");
+ printf(
+" may contain crossing edges and other pathology) if the output is a CDT or\n"
+);
+ printf(
+" CCDT, or if it has holes or concavities. If the triangulated domain is\n");
+ printf(
+" convex and has no holes, you can use -D switch to force Triangle to\n");
+ printf(
+" construct a conforming Delaunay triangulation instead of a CCDT, so the\n");
+ printf(" Voronoi diagram will be valid.\n\n");
+ printf("Mesh Topology:\n\n");
+ printf(
+" You may wish to know which triangles are adjacent to a certain Delaunay\n");
+ printf(
+" edge in an .edge file, which Voronoi cells are adjacent to a certain\n");
+ printf(
+" Voronoi edge in a .v.edge file, or which Voronoi cells are adjacent to\n");
+ printf(
+" each other. All of this information can be found by cross-referencing\n");
+ printf(
+" output files with the recollection that the Delaunay triangulation and\n");
+ printf(" the Voronoi diagram are planar duals.\n\n");
+ printf(
+" Specifically, edge i of an .edge file is the dual of Voronoi edge i of\n");
+ printf(
+" the corresponding .v.edge file, and is rotated 90 degrees counterclock-\n");
+ printf(
+" wise from the Voronoi edge. Triangle j of an .ele file is the dual of\n");
+ printf(
+" vertex j of the corresponding .v.node file. Voronoi cell k is the dual\n");
+ printf(" of vertex k of the corresponding .node file.\n\n");
+ printf(
+" Hence, to find the triangles adjacent to a Delaunay edge, look at the\n");
+ printf(
+" vertices of the corresponding Voronoi edge. If the endpoints of a\n");
+ printf(
+" Voronoi edge are Voronoi vertices 2 and 6 respectively, then triangles 2\n"
+);
+ printf(
+" and 6 adjoin the left and right sides of the corresponding Delaunay edge,\n"
+);
+ printf(
+" respectively. To find the Voronoi cells adjacent to a Voronoi edge, look\n"
+);
+ printf(
+" at the endpoints of the corresponding Delaunay edge. If the endpoints of\n"
+);
+ printf(
+" a Delaunay edge are input vertices 7 and 12, then Voronoi cells 7 and 12\n"
+);
+ printf(
+" adjoin the right and left sides of the corresponding Voronoi edge,\n");
+ printf(
+" respectively. To find which Voronoi cells are adjacent to each other,\n");
+ printf(" just read the list of Delaunay edges.\n\n");
+ printf(
+" Triangle does not write a list of the edges adjoining each Voronoi cell,\n"
+);
+ printf(
+" but you can reconstructed it straightforwardly. For instance, to find\n");
+ printf(
+" all the edges of Voronoi cell 1, search the output .edge file for every\n");
+ printf(
+" edge that has input vertex 1 as an endpoint. The corresponding dual\n");
+ printf(
+" edges in the output .v.edge file form the boundary of Voronoi cell 1.\n");
+ printf("\n");
+ printf(
+" For each Voronoi vertex, the .neigh file gives a list of the three\n");
+ printf(
+" Voronoi vertices attached to it. You might find this more convenient\n");
+ printf(" than the .v.edge file.\n\n");
+ printf("Quadratic Elements:\n\n");
+ printf(
+" Triangle generates meshes with subparametric quadratic elements if the\n");
+ printf(
+" -o2 switch is specified. Quadratic elements have six nodes per element,\n"
+);
+ printf(
+" rather than three. `Subparametric' means that the edges of the triangles\n"
+);
+ printf(
+" are always straight, so that subparametric quadratic elements are\n");
+ printf(
+" geometrically identical to linear elements, even though they can be used\n"
+);
+ printf(
+" with quadratic interpolating functions. The three extra nodes of an\n");
+ printf(
+" element fall at the midpoints of the three edges, with the fourth, fifth,\n"
+);
+ printf(
+" and sixth nodes appearing opposite the first, second, and third corners\n");
+ printf(" respectively.\n\n");
+ printf("Domains with Small Angles:\n\n");
+ printf(
+" If two input segments adjoin each other at a small angle, clearly the -q\n"
+);
+ printf(
+" switch cannot remove the small angle. Moreover, Triangle may have no\n");
+ printf(
+" choice but to generate additional triangles whose smallest angles are\n");
+ printf(
+" smaller than the specified bound. However, these triangles only appear\n");
+ printf(
+" between input segments separated by small angles. Moreover, if you\n");
+ printf(
+" request a minimum angle of theta degrees, Triangle will generally produce\n"
+);
+ printf(
+" no angle larger than 180 - 2 theta, even if it is forced to compromise on\n"
+);
+ printf(" the minimum angle.\n\n");
+ printf("Statistics:\n\n");
+ printf(
+" After generating a mesh, Triangle prints a count of entities in the\n");
+ printf(
+" output mesh, including the number of vertices, triangles, edges, exterior\n"
+);
+ printf(
+" boundary edges (i.e. subsegments on the boundary of the triangulation,\n");
+ printf(
+" including hole boundaries), interior boundary edges (i.e. subsegments of\n"
+);
+ printf(
+" input segments not on the boundary), and total subsegments. If you've\n");
+ printf(
+" forgotten the statistics for an existing mesh, run Triangle on that mesh\n"
+);
+ printf(
+" with the -rNEP switches to read the mesh and print the statistics without\n"
+);
+ printf(
+" writing any files. Use -rpNEP if you've got a .poly file for the mesh.\n");
+ printf("\n");
+ printf(
+" The -V switch produces extended statistics, including a rough estimate\n");
+ printf(
+" of memory use, the number of calls to geometric predicates, and\n");
+ printf(
+" histograms of the angles and the aspect ratios of the triangles in the\n");
+ printf(" mesh.\n\n");
+ printf("Exact Arithmetic:\n\n");
+ printf(
+" Triangle uses adaptive exact arithmetic to perform what computational\n");
+ printf(
+" geometers call the `orientation' and `incircle' tests. If the floating-\n"
+);
+ printf(
+" point arithmetic of your machine conforms to the IEEE 754 standard (as\n");
+ printf(
+" most workstations do), and does not use extended precision internal\n");
+ printf(
+" floating-point registers, then your output is guaranteed to be an\n");
+ printf(
+" absolutely true Delaunay or constrained Delaunay triangulation, roundoff\n"
+);
+ printf(
+" error notwithstanding. The word `adaptive' implies that these arithmetic\n"
+);
+ printf(
+" routines compute the result only to the precision necessary to guarantee\n"
+);
+ printf(
+" correctness, so they are usually nearly as fast as their approximate\n");
+ printf(" counterparts.\n\n");
+ printf(
+" May CPUs, including Intel x86 processors, have extended precision\n");
+ printf(
+" floating-point registers. These must be reconfigured so their precision\n"
+);
+ printf(
+" is reduced to memory precision. Triangle does this if it is compiled\n");
+ printf(" correctly. See the makefile for details.\n\n");
+ printf(
+" The exact tests can be disabled with the -X switch. On most inputs, this\n"
+);
+ printf(
+" switch reduces the computation time by about eight percent--it's not\n");
+ printf(
+" worth the risk. There are rare difficult inputs (having many collinear\n");
+ printf(
+" and cocircular vertices), however, for which the difference in speed\n");
+ printf(
+" could be a factor of two. Be forewarned that these are precisely the\n");
+ printf(
+" inputs most likely to cause errors if you use the -X switch. Hence, the\n"
+);
+ printf(" -X switch is not recommended.\n\n");
+ printf(
+" Unfortunately, the exact tests don't solve every numerical problem.\n");
+ printf(
+" Exact arithmetic is not used to compute the positions of new vertices,\n");
+ printf(
+" because the bit complexity of vertex coordinates would grow without\n");
+ printf(
+" bound. Hence, segment intersections aren't computed exactly; in very\n");
+ printf(
+" unusual cases, roundoff error in computing an intersection point might\n");
+ printf(
+" actually lead to an inverted triangle and an invalid triangulation.\n");
+ printf(
+" (This is one reason to specify your own intersection points in your .poly\n"
+);
+ printf(
+" files.) Similarly, exact arithmetic is not used to compute the vertices\n"
+);
+ printf(" of the Voronoi diagram.\n\n");
+ printf(
+" Another pair of problems not solved by the exact arithmetic routines is\n");
+ printf(
+" underflow and overflow. If Triangle is compiled for double precision\n");
+ printf(
+" arithmetic, I believe that Triangle's geometric predicates work correctly\n"
+);
+ printf(
+" if the exponent of every input coordinate falls in the range [-148, 201].\n"
+);
+ printf(
+" Underflow can silently prevent the orientation and incircle tests from\n");
+ printf(
+" being performed exactly, while overflow typically causes a floating\n");
+ printf(" exception.\n\n");
+ printf("Calling Triangle from Another Program:\n\n");
+ printf(" Read the file triangle.h for details.\n\n");
+ printf("Troubleshooting:\n\n");
+ printf(" Please read this section before mailing me bugs.\n\n");
+ printf(" `My output mesh has no triangles!'\n\n");
+ printf(
+" If you're using a PSLG, you've probably failed to specify a proper set\n"
+);
+ printf(
+" of bounding segments, or forgotten to use the -c switch. Or you may\n");
+ printf(
+" have placed a hole badly, thereby eating all your triangles. To test\n");
+ printf(" these possibilities, try again with the -c and -O switches.\n");
+ printf(
+" Alternatively, all your input vertices may be collinear, in which case\n"
+);
+ printf(" you can hardly expect to triangulate them.\n\n");
+ printf(" `Triangle doesn't terminate, or just crashes.'\n\n");
+ printf(
+" Bad things can happen when triangles get so small that the distance\n");
+ printf(
+" between their vertices isn't much larger than the precision of your\n");
+ printf(
+" machine's arithmetic. If you've compiled Triangle for single-precision\n"
+);
+ printf(
+" arithmetic, you might do better by recompiling it for double-precision.\n"
+);
+ printf(
+" Then again, you might just have to settle for more lenient constraints\n"
+);
+ printf(
+" on the minimum angle and the maximum area than you had planned.\n");
+ printf("\n");
+ printf(
+" You can minimize precision problems by ensuring that the origin lies\n");
+ printf(
+" inside your vertex set, or even inside the densest part of your\n");
+ printf(
+" mesh. If you're triangulating an object whose x-coordinates all fall\n");
+ printf(
+" between 6247133 and 6247134, you're not leaving much floating-point\n");
+ printf(" precision for Triangle to work with.\n\n");
+ printf(
+" Precision problems can occur covertly if the input PSLG contains two\n");
+ printf(
+" segments that meet (or intersect) at an extremely small angle, or if\n");
+ printf(
+" such an angle is introduced by the -c switch. If you don't realize\n");
+ printf(
+" that a tiny angle is being formed, you might never discover why\n");
+ printf(
+" Triangle is crashing. To check for this possibility, use the -S switch\n"
+);
+ printf(
+" (with an appropriate limit on the number of Steiner points, found by\n");
+ printf(
+" trial-and-error) to stop Triangle early, and view the output .poly file\n"
+);
+ printf(
+" with Show Me (described below). Look carefully for regions where dense\n"
+);
+ printf(
+" clusters of vertices are forming and for small angles between segments.\n"
+);
+ printf(
+" Zoom in closely, as such segments might look like a single segment from\n"
+);
+ printf(" a distance.\n\n");
+ printf(
+" If some of the input values are too large, Triangle may suffer a\n");
+ printf(
+" floating exception due to overflow when attempting to perform an\n");
+ printf(
+" orientation or incircle test. (Read the section on exact arithmetic\n");
+ printf(
+" above.) Again, I recommend compiling Triangle for double (rather\n");
+ printf(" than single) precision arithmetic.\n\n");
+ printf(
+" Unexpected problems can arise if you use quality meshing (-q, -a, or\n");
+ printf(
+" -u) with an input that is not segment-bounded--that is, if your input\n");
+ printf(
+" is a vertex set, or you're using the -c switch. If the convex hull of\n"
+);
+ printf(
+" your input vertices has collinear vertices on its boundary, an input\n");
+ printf(
+" vertex that you think lies on the convex hull might actually lie just\n");
+ printf(
+" inside the convex hull. If so, the vertex and the nearby convex hull\n");
+ printf(
+" edge form an extremely thin triangle. When Triangle tries to refine\n");
+ printf(
+" the mesh to enforce angle and area constraints, Triangle might generate\n"
+);
+ printf(
+" extremely tiny triangles, or it might fail because of insufficient\n");
+ printf(" floating-point precision.\n\n");
+ printf(
+" `The numbering of the output vertices doesn't match the input vertices.'\n"
+);
+ printf("\n");
+ printf(
+" You may have had duplicate input vertices, or you may have eaten some\n");
+ printf(
+" of your input vertices with a hole, or by placing them outside the area\n"
+);
+ printf(
+" enclosed by segments. In any case, you can solve the problem by not\n");
+ printf(" using the -j switch.\n\n");
+ printf(
+" `Triangle executes without incident, but when I look at the resulting\n");
+ printf(
+" mesh, it has overlapping triangles or other geometric inconsistencies.'\n");
+ printf("\n");
+ printf(
+" If you select the -X switch, Triangle occasionally makes mistakes due\n");
+ printf(
+" to floating-point roundoff error. Although these errors are rare,\n");
+ printf(
+" don't use the -X switch. If you still have problems, please report the\n"
+);
+ printf(" bug.\n\n");
+ printf(
+" `Triangle executes without incident, but when I look at the resulting\n");
+ printf(" Voronoi diagram, it has overlapping edges or other geometric\n");
+ printf(" inconsistencies.'\n");
+ printf("\n");
+ printf(
+" If your input is a PSLG (-p), you can only expect a meaningful Voronoi\n"
+);
+ printf(
+" diagram if the domain you are triangulating is convex and free of\n");
+ printf(
+" holes, and you use the -D switch to construct a conforming Delaunay\n");
+ printf(" triangulation (instead of a CDT or CCDT).\n\n");
+ printf(
+" Strange things can happen if you've taken liberties with your PSLG. Do\n");
+ printf(
+" you have a vertex lying in the middle of a segment? Triangle sometimes\n");
+ printf(
+" copes poorly with that sort of thing. Do you want to lay out a collinear\n"
+);
+ printf(
+" row of evenly spaced, segment-connected vertices? Have you simply\n");
+ printf(
+" defined one long segment connecting the leftmost vertex to the rightmost\n"
+);
+ printf(
+" vertex, and a bunch of vertices lying along it? This method occasionally\n"
+);
+ printf(
+" works, especially with horizontal and vertical lines, but often it\n");
+ printf(
+" doesn't, and you'll have to connect each adjacent pair of vertices with a\n"
+);
+ printf(" separate segment. If you don't like it, tough.\n\n");
+ printf(
+" Furthermore, if you have segments that intersect other than at their\n");
+ printf(
+" endpoints, try not to let the intersections fall extremely close to PSLG\n"
+);
+ printf(" vertices or each other.\n\n");
+ printf(
+" If you have problems refining a triangulation not produced by Triangle:\n");
+ printf(
+" Are you sure the triangulation is geometrically valid? Is it formatted\n");
+ printf(
+" correctly for Triangle? Are the triangles all listed so the first three\n"
+);
+ printf(
+" vertices are their corners in counterclockwise order? Are all of the\n");
+ printf(
+" triangles constrained Delaunay? Triangle's Delaunay refinement algorithm\n"
+);
+ printf(" assumes that it starts with a CDT.\n\n");
+ printf("Show Me:\n\n");
+ printf(
+" Triangle comes with a separate program named `Show Me', whose primary\n");
+ printf(
+" purpose is to draw meshes on your screen or in PostScript. Its secondary\n"
+);
+ printf(
+" purpose is to check the validity of your input files, and do so more\n");
+ printf(
+" thoroughly than Triangle does. Unlike Triangle, Show Me requires that\n");
+ printf(
+" you have the X Windows system. Sorry, Microsoft Windows users.\n");
+ printf("\n");
+ printf("Triangle on the Web:\n");
+ printf("\n");
+ printf(" To see an illustrated version of these instructions, check out\n");
+ printf("\n");
+ printf(" http://www.cs.cmu.edu/~quake/triangle.html\n");
+ printf("\n");
+ printf("A Brief Plea:\n");
+ printf("\n");
+ printf(
+" If you use Triangle, and especially if you use it to accomplish real\n");
+ printf(
+" work, I would like very much to hear from you. A short letter or email\n");
+ printf(
+" (to jrs at cs.berkeley.edu) describing how you use Triangle will mean a lot\n"
+);
+ printf(
+" to me. The more people I know are using this program, the more easily I\n"
+);
+ printf(
+" can justify spending time on improvements, which in turn will benefit\n");
+ printf(
+" you. Also, I can put you on a list to receive email whenever a new\n");
+ printf(" version of Triangle is available.\n\n");
+ printf(
+" If you use a mesh generated by Triangle in a publication, please include\n"
+);
+ printf(
+" an acknowledgment as well. And please spell Triangle with a capital `T'!\n"
+);
+ printf(
+" If you want to include a citation, use `Jonathan Richard Shewchuk,\n");
+ printf(
+" ``Triangle: Engineering a 2D Quality Mesh Generator and Delaunay\n");
+ printf(
+" Triangulator,'' in Applied Computational Geometry: Towards Geometric\n");
+ printf(
+" Engineering (Ming C. Lin and Dinesh Manocha, editors), volume 1148 of\n");
+ printf(
+" Lecture Notes in Computer Science, pages 203-222, Springer-Verlag,\n");
+ printf(
+" Berlin, May 1996. (From the First ACM Workshop on Applied Computational\n"
+);
+ printf(" Geometry.)'\n\n");
+ printf("Research credit:\n\n");
+ printf(
+" Of course, I can take credit for only a fraction of the ideas that made\n");
+ printf(
+" this mesh generator possible. Triangle owes its existence to the efforts\n"
+);
+ printf(
+" of many fine computational geometers and other researchers, including\n");
+ printf(
+" Marshall Bern, L. Paul Chew, Kenneth L. Clarkson, Boris Delaunay, Rex A.\n"
+);
+ printf(
+" Dwyer, David Eppstein, Steven Fortune, Leonidas J. Guibas, Donald E.\n");
+ printf(
+" Knuth, Charles L. Lawson, Der-Tsai Lee, Gary L. Miller, Ernst P. Mucke,\n");
+ printf(
+" Steven E. Pav, Douglas M. Priest, Jim Ruppert, Isaac Saias, Bruce J.\n");
+ printf(
+" Schachter, Micha Sharir, Peter W. Shor, Daniel D. Sleator, Jorge Stolfi,\n"
+);
+ printf(" Robert E. Tarjan, Alper Ungor, Christopher J. Van Wyk, Noel J.\n");
+ printf(
+" Walkington, and Binhai Zhu. See the comments at the beginning of the\n");
+ printf(" source code for references.\n\n");
+ triexit(0);
+}
+
+#endif /* not TRILIBRARY */
+
+/*****************************************************************************/
+/* */
+/* internalerror() Ask the user to send me the defective product. Exit. */
+/* */
+/*****************************************************************************/
+
+void internalerror()
+{
+ printf(" Please report this bug to jrs at cs.berkeley.edu\n");
+ printf(" Include the message above, your input data set, and the exact\n");
+ printf(" command line you used to run Triangle.\n");
+ triexit(1);
+}
+
+/*****************************************************************************/
+/* */
+/* parsecommandline() Read the command line, identify switches, and set */
+/* up options and file names. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void parsecommandline(int argc, char **argv, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void parsecommandline(argc, argv, b)
+int argc;
+char **argv;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+#ifdef TRILIBRARY
+#define STARTINDEX 0
+#else /* not TRILIBRARY */
+#define STARTINDEX 1
+ int increment;
+ int meshnumber;
+#endif /* not TRILIBRARY */
+#ifndef CDT_ONLY
+ int k;
+ char workstring[FILENAMESIZE];
+#endif
+ int i, j;
+
+ b->poly = b->refine = b->quality = 0;
+ b->vararea = b->fixedarea = b->usertest = 0;
+ b->regionattrib = b->convex = b->weighted = b->jettison = 0;
+ b->firstnumber = 1;
+ b->edgesout = b->voronoi = b->neighbors = b->geomview = 0;
+ b->nobound = b->nopolywritten = b->nonodewritten = b->noelewritten = 0;
+ b->noiterationnum = 0;
+ b->noholes = b->noexact = 0;
+ b->incremental = b->sweepline = 0;
+ b->dwyer = 1;
+ b->splitseg = 0;
+ b->docheck = 0;
+ b->nobisect = 0;
+ b->conformdel = 0;
+ b->steiner = -1;
+ b->order = 1;
+ b->minangle = 0.0;
+ b->maxarea = -1.0;
+ b->quiet = b->verbose = 0;
+#ifndef TRILIBRARY
+ b->innodefilename[0] = '\0';
+#endif /* not TRILIBRARY */
+
+ for (i = STARTINDEX; i < argc; i++) {
+#ifndef TRILIBRARY
+ if (argv[i][0] == '-') {
+#endif /* not TRILIBRARY */
+ for (j = STARTINDEX; argv[i][j] != '\0'; j++) {
+ if (argv[i][j] == 'p') {
+ b->poly = 1;
+ }
+#ifndef CDT_ONLY
+ if (argv[i][j] == 'r') {
+ b->refine = 1;
+ }
+ if (argv[i][j] == 'q') {
+ b->quality = 1;
+ if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
+ (argv[i][j + 1] == '.')) {
+ k = 0;
+ while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
+ (argv[i][j + 1] == '.')) {
+ j++;
+ workstring[k] = argv[i][j];
+ k++;
+ }
+ workstring[k] = '\0';
+ b->minangle = (REAL) strtod(workstring, (char **) NULL);
+ } else {
+ b->minangle = 20.0;
+ }
+ }
+ if (argv[i][j] == 'a') {
+ b->quality = 1;
+ if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
+ (argv[i][j + 1] == '.')) {
+ b->fixedarea = 1;
+ k = 0;
+ while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) ||
+ (argv[i][j + 1] == '.')) {
+ j++;
+ workstring[k] = argv[i][j];
+ k++;
+ }
+ workstring[k] = '\0';
+ b->maxarea = (REAL) strtod(workstring, (char **) NULL);
+ if (b->maxarea <= 0.0) {
+ printf("Error: Maximum area must be greater than zero.\n");
+ triexit(1);
+ }
+ } else {
+ b->vararea = 1;
+ }
+ }
+ if (argv[i][j] == 'u') {
+ b->quality = 1;
+ b->usertest = 1;
+ }
+#endif /* not CDT_ONLY */
+ if (argv[i][j] == 'A') {
+ b->regionattrib = 1;
+ }
+ if (argv[i][j] == 'c') {
+ b->convex = 1;
+ }
+ if (argv[i][j] == 'w') {
+ b->weighted = 1;
+ }
+ if (argv[i][j] == 'W') {
+ b->weighted = 2;
+ }
+ if (argv[i][j] == 'j') {
+ b->jettison = 1;
+ }
+ if (argv[i][j] == 'z') {
+ b->firstnumber = 0;
+ }
+ if (argv[i][j] == 'e') {
+ b->edgesout = 1;
+ }
+ if (argv[i][j] == 'v') {
+ b->voronoi = 1;
+ }
+ if (argv[i][j] == 'n') {
+ b->neighbors = 1;
+ }
+ if (argv[i][j] == 'g') {
+ b->geomview = 1;
+ }
+ if (argv[i][j] == 'B') {
+ b->nobound = 1;
+ }
+ if (argv[i][j] == 'P') {
+ b->nopolywritten = 1;
+ }
+ if (argv[i][j] == 'N') {
+ b->nonodewritten = 1;
+ }
+ if (argv[i][j] == 'E') {
+ b->noelewritten = 1;
+ }
+#ifndef TRILIBRARY
+ if (argv[i][j] == 'I') {
+ b->noiterationnum = 1;
+ }
+#endif /* not TRILIBRARY */
+ if (argv[i][j] == 'O') {
+ b->noholes = 1;
+ }
+ if (argv[i][j] == 'X') {
+ b->noexact = 1;
+ }
+ if (argv[i][j] == 'o') {
+ if (argv[i][j + 1] == '2') {
+ j++;
+ b->order = 2;
+ }
+ }
+#ifndef CDT_ONLY
+ if (argv[i][j] == 'Y') {
+ b->nobisect++;
+ }
+ if (argv[i][j] == 'S') {
+ b->steiner = 0;
+ while ((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) {
+ j++;
+ b->steiner = b->steiner * 10 + (int) (argv[i][j] - '0');
+ }
+ }
+#endif /* not CDT_ONLY */
+#ifndef REDUCED
+ if (argv[i][j] == 'i') {
+ b->incremental = 1;
+ }
+ if (argv[i][j] == 'F') {
+ b->sweepline = 1;
+ }
+#endif /* not REDUCED */
+ if (argv[i][j] == 'l') {
+ b->dwyer = 0;
+ }
+#ifndef REDUCED
+#ifndef CDT_ONLY
+ if (argv[i][j] == 's') {
+ b->splitseg = 1;
+ }
+ if ((argv[i][j] == 'D') || (argv[i][j] == 'L')) {
+ b->quality = 1;
+ b->conformdel = 1;
+ }
+#endif /* not CDT_ONLY */
+ if (argv[i][j] == 'C') {
+ b->docheck = 1;
+ }
+#endif /* not REDUCED */
+ if (argv[i][j] == 'Q') {
+ b->quiet = 1;
+ }
+ if (argv[i][j] == 'V') {
+ b->verbose++;
+ }
+#ifndef TRILIBRARY
+ if ((argv[i][j] == 'h') || (argv[i][j] == 'H') ||
+ (argv[i][j] == '?')) {
+ info();
+ }
+#endif /* not TRILIBRARY */
+ }
+#ifndef TRILIBRARY
+ } else {
+ strncpy(b->innodefilename, argv[i], FILENAMESIZE - 1);
+ b->innodefilename[FILENAMESIZE - 1] = '\0';
+ }
+#endif /* not TRILIBRARY */
+ }
+#ifndef TRILIBRARY
+ if (b->innodefilename[0] == '\0') {
+ syntax();
+ }
+ if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".node")) {
+ b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
+ }
+ if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".poly")) {
+ b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
+ b->poly = 1;
+ }
+#ifndef CDT_ONLY
+ if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 4], ".ele")) {
+ b->innodefilename[strlen(b->innodefilename) - 4] = '\0';
+ b->refine = 1;
+ }
+ if (!strcmp(&b->innodefilename[strlen(b->innodefilename) - 5], ".area")) {
+ b->innodefilename[strlen(b->innodefilename) - 5] = '\0';
+ b->refine = 1;
+ b->quality = 1;
+ b->vararea = 1;
+ }
+#endif /* not CDT_ONLY */
+#endif /* not TRILIBRARY */
+ b->usesegments = b->poly || b->refine || b->quality || b->convex;
+ b->goodangle = cos(b->minangle * PI / 180.0);
+ if (b->goodangle == 1.0) {
+ b->offconstant = 0.0;
+ } else {
+ b->offconstant = 0.475 * sqrt((1.0 + b->goodangle) / (1.0 - b->goodangle));
+ }
+ b->goodangle *= b->goodangle;
+ if (b->refine && b->noiterationnum) {
+ printf(
+ "Error: You cannot use the -I switch when refining a triangulation.\n");
+ triexit(1);
+ }
+ /* Be careful not to allocate space for element area constraints that */
+ /* will never be assigned any value (other than the default -1.0). */
+ if (!b->refine && !b->poly) {
+ b->vararea = 0;
+ }
+ /* Be careful not to add an extra attribute to each element unless the */
+ /* input supports it (PSLG in, but not refining a preexisting mesh). */
+ if (b->refine || !b->poly) {
+ b->regionattrib = 0;
+ }
+ /* Regular/weighted triangulations are incompatible with PSLGs */
+ /* and meshing. */
+ if (b->weighted && (b->poly || b->quality)) {
+ b->weighted = 0;
+ if (!b->quiet) {
+ printf("Warning: weighted triangulations (-w, -W) are incompatible\n");
+ printf(" with PSLGs (-p) and meshing (-q, -a, -u). Weights ignored.\n"
+ );
+ }
+ }
+ if (b->jettison && b->nonodewritten && !b->quiet) {
+ printf("Warning: -j and -N switches are somewhat incompatible.\n");
+ printf(" If any vertices are jettisoned, you will need the output\n");
+ printf(" .node file to reconstruct the new node indices.");
+ }
+
+#ifndef TRILIBRARY
+ strcpy(b->inpolyfilename, b->innodefilename);
+ strcpy(b->inelefilename, b->innodefilename);
+ strcpy(b->areafilename, b->innodefilename);
+ increment = 0;
+ strcpy(workstring, b->innodefilename);
+ j = 1;
+ while (workstring[j] != '\0') {
+ if ((workstring[j] == '.') && (workstring[j + 1] != '\0')) {
+ increment = j + 1;
+ }
+ j++;
+ }
+ meshnumber = 0;
+ if (increment > 0) {
+ j = increment;
+ do {
+ if ((workstring[j] >= '0') && (workstring[j] <= '9')) {
+ meshnumber = meshnumber * 10 + (int) (workstring[j] - '0');
+ } else {
+ increment = 0;
+ }
+ j++;
+ } while (workstring[j] != '\0');
+ }
+ if (b->noiterationnum) {
+ strcpy(b->outnodefilename, b->innodefilename);
+ strcpy(b->outelefilename, b->innodefilename);
+ strcpy(b->edgefilename, b->innodefilename);
+ strcpy(b->vnodefilename, b->innodefilename);
+ strcpy(b->vedgefilename, b->innodefilename);
+ strcpy(b->neighborfilename, b->innodefilename);
+ strcpy(b->offfilename, b->innodefilename);
+ strcat(b->outnodefilename, ".node");
+ strcat(b->outelefilename, ".ele");
+ strcat(b->edgefilename, ".edge");
+ strcat(b->vnodefilename, ".v.node");
+ strcat(b->vedgefilename, ".v.edge");
+ strcat(b->neighborfilename, ".neigh");
+ strcat(b->offfilename, ".off");
+ } else if (increment == 0) {
+ strcpy(b->outnodefilename, b->innodefilename);
+ strcpy(b->outpolyfilename, b->innodefilename);
+ strcpy(b->outelefilename, b->innodefilename);
+ strcpy(b->edgefilename, b->innodefilename);
+ strcpy(b->vnodefilename, b->innodefilename);
+ strcpy(b->vedgefilename, b->innodefilename);
+ strcpy(b->neighborfilename, b->innodefilename);
+ strcpy(b->offfilename, b->innodefilename);
+ strcat(b->outnodefilename, ".1.node");
+ strcat(b->outpolyfilename, ".1.poly");
+ strcat(b->outelefilename, ".1.ele");
+ strcat(b->edgefilename, ".1.edge");
+ strcat(b->vnodefilename, ".1.v.node");
+ strcat(b->vedgefilename, ".1.v.edge");
+ strcat(b->neighborfilename, ".1.neigh");
+ strcat(b->offfilename, ".1.off");
+ } else {
+ workstring[increment] = '%';
+ workstring[increment + 1] = 'd';
+ workstring[increment + 2] = '\0';
+ sprintf(b->outnodefilename, workstring, meshnumber + 1);
+ strcpy(b->outpolyfilename, b->outnodefilename);
+ strcpy(b->outelefilename, b->outnodefilename);
+ strcpy(b->edgefilename, b->outnodefilename);
+ strcpy(b->vnodefilename, b->outnodefilename);
+ strcpy(b->vedgefilename, b->outnodefilename);
+ strcpy(b->neighborfilename, b->outnodefilename);
+ strcpy(b->offfilename, b->outnodefilename);
+ strcat(b->outnodefilename, ".node");
+ strcat(b->outpolyfilename, ".poly");
+ strcat(b->outelefilename, ".ele");
+ strcat(b->edgefilename, ".edge");
+ strcat(b->vnodefilename, ".v.node");
+ strcat(b->vedgefilename, ".v.edge");
+ strcat(b->neighborfilename, ".neigh");
+ strcat(b->offfilename, ".off");
+ }
+ strcat(b->innodefilename, ".node");
+ strcat(b->inpolyfilename, ".poly");
+ strcat(b->inelefilename, ".ele");
+ strcat(b->areafilename, ".area");
+#endif /* not TRILIBRARY */
+}
+
+/** **/
+/** **/
+/********* User interaction routines begin here *********/
+
+/********* Debugging routines begin here *********/
+/** **/
+/** **/
+
+/*****************************************************************************/
+/* */
+/* printtriangle() Print out the details of an oriented triangle. */
+/* */
+/* I originally wrote this procedure to simplify debugging; it can be */
+/* called directly from the debugger, and presents information about an */
+/* oriented triangle in digestible form. It's also used when the */
+/* highest level of verbosity (`-VVV') is specified. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void printtriangle(struct mesh *m, struct behavior *b, struct otri *t)
+#else /* not ANSI_DECLARATORS */
+void printtriangle(m, b, t)
+struct mesh *m;
+struct behavior *b;
+struct otri *t;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri printtri;
+ struct osub printsh;
+ vertex printvertex;
+
+ printf("triangle x%lx with orientation %d:\n", (unsigned long) t->tri,
+ t->orient);
+ decode(t->tri[0], printtri);
+ if (printtri.tri == m->dummytri) {
+ printf(" [0] = Outer space\n");
+ } else {
+ printf(" [0] = x%lx %d\n", (unsigned long) printtri.tri,
+ printtri.orient);
+ }
+ decode(t->tri[1], printtri);
+ if (printtri.tri == m->dummytri) {
+ printf(" [1] = Outer space\n");
+ } else {
+ printf(" [1] = x%lx %d\n", (unsigned long) printtri.tri,
+ printtri.orient);
+ }
+ decode(t->tri[2], printtri);
+ if (printtri.tri == m->dummytri) {
+ printf(" [2] = Outer space\n");
+ } else {
+ printf(" [2] = x%lx %d\n", (unsigned long) printtri.tri,
+ printtri.orient);
+ }
+
+ org(*t, printvertex);
+ if (printvertex == (vertex) NULL)
+ printf(" Origin[%d] = NULL\n", (t->orient + 1) % 3 + 3);
+ else
+ printf(" Origin[%d] = x%lx (%.12g, %.12g)\n",
+ (t->orient + 1) % 3 + 3, (unsigned long) printvertex,
+ printvertex[0], printvertex[1]);
+ dest(*t, printvertex);
+ if (printvertex == (vertex) NULL)
+ printf(" Dest [%d] = NULL\n", (t->orient + 2) % 3 + 3);
+ else
+ printf(" Dest [%d] = x%lx (%.12g, %.12g)\n",
+ (t->orient + 2) % 3 + 3, (unsigned long) printvertex,
+ printvertex[0], printvertex[1]);
+ apex(*t, printvertex);
+ if (printvertex == (vertex) NULL)
+ printf(" Apex [%d] = NULL\n", t->orient + 3);
+ else
+ printf(" Apex [%d] = x%lx (%.12g, %.12g)\n",
+ t->orient + 3, (unsigned long) printvertex,
+ printvertex[0], printvertex[1]);
+
+ if (b->usesegments) {
+ sdecode(t->tri[6], printsh);
+ if (printsh.ss != m->dummysub) {
+ printf(" [6] = x%lx %d\n", (unsigned long) printsh.ss,
+ printsh.ssorient);
+ }
+ sdecode(t->tri[7], printsh);
+ if (printsh.ss != m->dummysub) {
+ printf(" [7] = x%lx %d\n", (unsigned long) printsh.ss,
+ printsh.ssorient);
+ }
+ sdecode(t->tri[8], printsh);
+ if (printsh.ss != m->dummysub) {
+ printf(" [8] = x%lx %d\n", (unsigned long) printsh.ss,
+ printsh.ssorient);
+ }
+ }
+
+ if (b->vararea) {
+ printf(" Area constraint: %.4g\n", areabound(*t));
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* printsubseg() Print out the details of an oriented subsegment. */
+/* */
+/* I originally wrote this procedure to simplify debugging; it can be */
+/* called directly from the debugger, and presents information about an */
+/* oriented subsegment in digestible form. It's also used when the highest */
+/* level of verbosity (`-VVV') is specified. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void printsubseg(struct mesh *m, struct behavior *b, struct osub *s)
+#else /* not ANSI_DECLARATORS */
+void printsubseg(m, b, s)
+struct mesh *m;
+struct behavior *b;
+struct osub *s;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct osub printsh;
+ struct otri printtri;
+ vertex printvertex;
+
+ printf("subsegment x%lx with orientation %d and mark %d:\n",
+ (unsigned long) s->ss, s->ssorient, mark(*s));
+ sdecode(s->ss[0], printsh);
+ if (printsh.ss == m->dummysub) {
+ printf(" [0] = No subsegment\n");
+ } else {
+ printf(" [0] = x%lx %d\n", (unsigned long) printsh.ss,
+ printsh.ssorient);
+ }
+ sdecode(s->ss[1], printsh);
+ if (printsh.ss == m->dummysub) {
+ printf(" [1] = No subsegment\n");
+ } else {
+ printf(" [1] = x%lx %d\n", (unsigned long) printsh.ss,
+ printsh.ssorient);
+ }
+
+ sorg(*s, printvertex);
+ if (printvertex == (vertex) NULL)
+ printf(" Origin[%d] = NULL\n", 2 + s->ssorient);
+ else
+ printf(" Origin[%d] = x%lx (%.12g, %.12g)\n",
+ 2 + s->ssorient, (unsigned long) printvertex,
+ printvertex[0], printvertex[1]);
+ sdest(*s, printvertex);
+ if (printvertex == (vertex) NULL)
+ printf(" Dest [%d] = NULL\n", 3 - s->ssorient);
+ else
+ printf(" Dest [%d] = x%lx (%.12g, %.12g)\n",
+ 3 - s->ssorient, (unsigned long) printvertex,
+ printvertex[0], printvertex[1]);
+
+ decode(s->ss[6], printtri);
+ if (printtri.tri == m->dummytri) {
+ printf(" [6] = Outer space\n");
+ } else {
+ printf(" [6] = x%lx %d\n", (unsigned long) printtri.tri,
+ printtri.orient);
+ }
+ decode(s->ss[7], printtri);
+ if (printtri.tri == m->dummytri) {
+ printf(" [7] = Outer space\n");
+ } else {
+ printf(" [7] = x%lx %d\n", (unsigned long) printtri.tri,
+ printtri.orient);
+ }
+
+ segorg(*s, printvertex);
+ if (printvertex == (vertex) NULL)
+ printf(" Segment origin[%d] = NULL\n", 4 + s->ssorient);
+ else
+ printf(" Segment origin[%d] = x%lx (%.12g, %.12g)\n",
+ 4 + s->ssorient, (unsigned long) printvertex,
+ printvertex[0], printvertex[1]);
+ segdest(*s, printvertex);
+ if (printvertex == (vertex) NULL)
+ printf(" Segment dest [%d] = NULL\n", 5 - s->ssorient);
+ else
+ printf(" Segment dest [%d] = x%lx (%.12g, %.12g)\n",
+ 5 - s->ssorient, (unsigned long) printvertex,
+ printvertex[0], printvertex[1]);
+}
+
+/** **/
+/** **/
+/********* Debugging routines end here *********/
+
+/********* Memory management routines begin here *********/
+/** **/
+/** **/
+
+/*****************************************************************************/
+/* */
+/* poolzero() Set all of a pool's fields to zero. */
+/* */
+/* This procedure should never be called on a pool that has any memory */
+/* allocated to it, as that memory would leak. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void poolzero(struct memorypool *pool)
+#else /* not ANSI_DECLARATORS */
+void poolzero(pool)
+struct memorypool *pool;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ pool->firstblock = (VOID **) NULL;
+ pool->nowblock = (VOID **) NULL;
+ pool->nextitem = (VOID *) NULL;
+ pool->deaditemstack = (VOID *) NULL;
+ pool->pathblock = (VOID **) NULL;
+ pool->pathitem = (VOID *) NULL;
+ pool->alignbytes = 0;
+ pool->itembytes = 0;
+ pool->itemsperblock = 0;
+ pool->itemsfirstblock = 0;
+ pool->items = 0;
+ pool->maxitems = 0;
+ pool->unallocateditems = 0;
+ pool->pathitemsleft = 0;
+}
+
+/*****************************************************************************/
+/* */
+/* poolrestart() Deallocate all items in a pool. */
+/* */
+/* The pool is returned to its starting state, except that no memory is */
+/* freed to the operating system. Rather, the previously allocated blocks */
+/* are ready to be reused. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void poolrestart(struct memorypool *pool)
+#else /* not ANSI_DECLARATORS */
+void poolrestart(pool)
+struct memorypool *pool;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ unsigned long alignptr;
+
+ pool->items = 0;
+ pool->maxitems = 0;
+
+ /* Set the currently active block. */
+ pool->nowblock = pool->firstblock;
+ /* Find the first item in the pool. Increment by the size of (VOID *). */
+ alignptr = (unsigned long) (pool->nowblock + 1);
+ /* Align the item on an `alignbytes'-byte boundary. */
+ pool->nextitem = (VOID *)
+ (alignptr + (unsigned long) pool->alignbytes -
+ (alignptr % (unsigned long) pool->alignbytes));
+ /* There are lots of unallocated items left in this block. */
+ pool->unallocateditems = pool->itemsfirstblock;
+ /* The stack of deallocated items is empty. */
+ pool->deaditemstack = (VOID *) NULL;
+}
+
+/*****************************************************************************/
+/* */
+/* poolinit() Initialize a pool of memory for allocation of items. */
+/* */
+/* This routine initializes the machinery for allocating items. A `pool' */
+/* is created whose records have size at least `bytecount'. Items will be */
+/* allocated in `itemcount'-item blocks. Each item is assumed to be a */
+/* collection of words, and either pointers or floating-point values are */
+/* assumed to be the "primary" word type. (The "primary" word type is used */
+/* to determine alignment of items.) If `alignment' isn't zero, all items */
+/* will be `alignment'-byte aligned in memory. `alignment' must be either */
+/* a multiple or a factor of the primary word size; powers of two are safe. */
+/* `alignment' is normally used to create a few unused bits at the bottom */
+/* of each item's pointer, in which information may be stored. */
+/* */
+/* Don't change this routine unless you understand it. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void poolinit(struct memorypool *pool, int bytecount, int itemcount,
+ int firstitemcount, int alignment)
+#else /* not ANSI_DECLARATORS */
+void poolinit(pool, bytecount, itemcount, firstitemcount, alignment)
+struct memorypool *pool;
+int bytecount;
+int itemcount;
+int firstitemcount;
+int alignment;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ /* Find the proper alignment, which must be at least as large as: */
+ /* - The parameter `alignment'. */
+ /* - sizeof(VOID *), so the stack of dead items can be maintained */
+ /* without unaligned accesses. */
+ if (alignment > sizeof(VOID *)) {
+ pool->alignbytes = alignment;
+ } else {
+ pool->alignbytes = sizeof(VOID *);
+ }
+ pool->itembytes = ((bytecount - 1) / pool->alignbytes + 1) *
+ pool->alignbytes;
+ pool->itemsperblock = itemcount;
+ if (firstitemcount == 0) {
+ pool->itemsfirstblock = itemcount;
+ } else {
+ pool->itemsfirstblock = firstitemcount;
+ }
+
+ /* Allocate a block of items. Space for `itemsfirstblock' items and one */
+ /* pointer (to point to the next block) are allocated, as well as space */
+ /* to ensure alignment of the items. */
+ pool->firstblock = (VOID **)
+ trimalloc(pool->itemsfirstblock * pool->itembytes + (int) sizeof(VOID *) +
+ pool->alignbytes);
+ /* Set the next block pointer to NULL. */
+ *(pool->firstblock) = (VOID *) NULL;
+ poolrestart(pool);
+}
+
+/*****************************************************************************/
+/* */
+/* pooldeinit() Free to the operating system all memory taken by a pool. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void pooldeinit(struct memorypool *pool)
+#else /* not ANSI_DECLARATORS */
+void pooldeinit(pool)
+struct memorypool *pool;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ while (pool->firstblock != (VOID **) NULL) {
+ pool->nowblock = (VOID **) *(pool->firstblock);
+ trifree((VOID *) pool->firstblock);
+ pool->firstblock = pool->nowblock;
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* poolalloc() Allocate space for an item. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+VOID *poolalloc(struct memorypool *pool)
+#else /* not ANSI_DECLARATORS */
+VOID *poolalloc(pool)
+struct memorypool *pool;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ VOID *newitem;
+ VOID **newblock;
+ unsigned long alignptr;
+
+ /* First check the linked list of dead items. If the list is not */
+ /* empty, allocate an item from the list rather than a fresh one. */
+ if (pool->deaditemstack != (VOID *) NULL) {
+ newitem = pool->deaditemstack; /* Take first item in list. */
+ pool->deaditemstack = * (VOID **) pool->deaditemstack;
+ } else {
+ /* Check if there are any free items left in the current block. */
+ if (pool->unallocateditems == 0) {
+ /* Check if another block must be allocated. */
+ if (*(pool->nowblock) == (VOID *) NULL) {
+ /* Allocate a new block of items, pointed to by the previous block. */
+ newblock = (VOID **) trimalloc(pool->itemsperblock * pool->itembytes +
+ (int) sizeof(VOID *) +
+ pool->alignbytes);
+ *(pool->nowblock) = (VOID *) newblock;
+ /* The next block pointer is NULL. */
+ *newblock = (VOID *) NULL;
+ }
+
+ /* Move to the new block. */
+ pool->nowblock = (VOID **) *(pool->nowblock);
+ /* Find the first item in the block. */
+ /* Increment by the size of (VOID *). */
+ alignptr = (unsigned long) (pool->nowblock + 1);
+ /* Align the item on an `alignbytes'-byte boundary. */
+ pool->nextitem = (VOID *)
+ (alignptr + (unsigned long) pool->alignbytes -
+ (alignptr % (unsigned long) pool->alignbytes));
+ /* There are lots of unallocated items left in this block. */
+ pool->unallocateditems = pool->itemsperblock;
+ }
+
+ /* Allocate a new item. */
+ newitem = pool->nextitem;
+ /* Advance `nextitem' pointer to next free item in block. */
+ pool->nextitem = (VOID *) ((char *) pool->nextitem + pool->itembytes);
+ pool->unallocateditems--;
+ pool->maxitems++;
+ }
+ pool->items++;
+ return newitem;
+}
+
+/*****************************************************************************/
+/* */
+/* pooldealloc() Deallocate space for an item. */
+/* */
+/* The deallocated space is stored in a queue for later reuse. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void pooldealloc(struct memorypool *pool, VOID *dyingitem)
+#else /* not ANSI_DECLARATORS */
+void pooldealloc(pool, dyingitem)
+struct memorypool *pool;
+VOID *dyingitem;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ /* Push freshly killed item onto stack. */
+ *((VOID **) dyingitem) = pool->deaditemstack;
+ pool->deaditemstack = dyingitem;
+ pool->items--;
+}
+
+/*****************************************************************************/
+/* */
+/* traversalinit() Prepare to traverse the entire list of items. */
+/* */
+/* This routine is used in conjunction with traverse(). */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void traversalinit(struct memorypool *pool)
+#else /* not ANSI_DECLARATORS */
+void traversalinit(pool)
+struct memorypool *pool;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ unsigned long alignptr;
+
+ /* Begin the traversal in the first block. */
+ pool->pathblock = pool->firstblock;
+ /* Find the first item in the block. Increment by the size of (VOID *). */
+ alignptr = (unsigned long) (pool->pathblock + 1);
+ /* Align with item on an `alignbytes'-byte boundary. */
+ pool->pathitem = (VOID *)
+ (alignptr + (unsigned long) pool->alignbytes -
+ (alignptr % (unsigned long) pool->alignbytes));
+ /* Set the number of items left in the current block. */
+ pool->pathitemsleft = pool->itemsfirstblock;
+}
+
+/*****************************************************************************/
+/* */
+/* traverse() Find the next item in the list. */
+/* */
+/* This routine is used in conjunction with traversalinit(). Be forewarned */
+/* that this routine successively returns all items in the list, including */
+/* deallocated ones on the deaditemqueue. It's up to you to figure out */
+/* which ones are actually dead. Why? I don't want to allocate extra */
+/* space just to demarcate dead items. It can usually be done more */
+/* space-efficiently by a routine that knows something about the structure */
+/* of the item. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+VOID *traverse(struct memorypool *pool)
+#else /* not ANSI_DECLARATORS */
+VOID *traverse(pool)
+struct memorypool *pool;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ VOID *newitem;
+ unsigned long alignptr;
+
+ /* Stop upon exhausting the list of items. */
+ if (pool->pathitem == pool->nextitem) {
+ return (VOID *) NULL;
+ }
+
+ /* Check whether any untraversed items remain in the current block. */
+ if (pool->pathitemsleft == 0) {
+ /* Find the next block. */
+ pool->pathblock = (VOID **) *(pool->pathblock);
+ /* Find the first item in the block. Increment by the size of (VOID *). */
+ alignptr = (unsigned long) (pool->pathblock + 1);
+ /* Align with item on an `alignbytes'-byte boundary. */
+ pool->pathitem = (VOID *)
+ (alignptr + (unsigned long) pool->alignbytes -
+ (alignptr % (unsigned long) pool->alignbytes));
+ /* Set the number of items left in the current block. */
+ pool->pathitemsleft = pool->itemsperblock;
+ }
+
+ newitem = pool->pathitem;
+ /* Find the next item in the block. */
+ pool->pathitem = (VOID *) ((char *) pool->pathitem + pool->itembytes);
+ pool->pathitemsleft--;
+ return newitem;
+}
+
+/*****************************************************************************/
+/* */
+/* dummyinit() Initialize the triangle that fills "outer space" and the */
+/* omnipresent subsegment. */
+/* */
+/* The triangle that fills "outer space," called `dummytri', is pointed to */
+/* by every triangle and subsegment on a boundary (be it outer or inner) of */
+/* the triangulation. Also, `dummytri' points to one of the triangles on */
+/* the convex hull (until the holes and concavities are carved), making it */
+/* possible to find a starting triangle for point location. */
+/* */
+/* The omnipresent subsegment, `dummysub', is pointed to by every triangle */
+/* or subsegment that doesn't have a full complement of real subsegments */
+/* to point to. */
+/* */
+/* `dummytri' and `dummysub' are generally required to fulfill only a few */
+/* invariants: their vertices must remain NULL and `dummytri' must always */
+/* be bonded (at offset zero) to some triangle on the convex hull of the */
+/* mesh, via a boundary edge. Otherwise, the connections of `dummytri' and */
+/* `dummysub' may change willy-nilly. This makes it possible to avoid */
+/* writing a good deal of special-case code (in the edge flip, for example) */
+/* for dealing with the boundary of the mesh, places where no subsegment is */
+/* present, and so forth. Other entities are frequently bonded to */
+/* `dummytri' and `dummysub' as if they were real mesh entities, with no */
+/* harm done. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void dummyinit(struct mesh *m, struct behavior *b, int trianglebytes,
+ int subsegbytes)
+#else /* not ANSI_DECLARATORS */
+void dummyinit(m, b, trianglebytes, subsegbytes)
+struct mesh *m;
+struct behavior *b;
+int trianglebytes;
+int subsegbytes;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ unsigned long alignptr;
+
+ /* Set up `dummytri', the `triangle' that occupies "outer space." */
+ m->dummytribase = (triangle *) trimalloc(trianglebytes +
+ m->triangles.alignbytes);
+ /* Align `dummytri' on a `triangles.alignbytes'-byte boundary. */
+ alignptr = (unsigned long) m->dummytribase;
+ m->dummytri = (triangle *)
+ (alignptr + (unsigned long) m->triangles.alignbytes -
+ (alignptr % (unsigned long) m->triangles.alignbytes));
+ /* Initialize the three adjoining triangles to be "outer space." These */
+ /* will eventually be changed by various bonding operations, but their */
+ /* values don't really matter, as long as they can legally be */
+ /* dereferenced. */
+ m->dummytri[0] = (triangle) m->dummytri;
+ m->dummytri[1] = (triangle) m->dummytri;
+ m->dummytri[2] = (triangle) m->dummytri;
+ /* Three NULL vertices. */
+ m->dummytri[3] = (triangle) NULL;
+ m->dummytri[4] = (triangle) NULL;
+ m->dummytri[5] = (triangle) NULL;
+
+ if (b->usesegments) {
+ /* Set up `dummysub', the omnipresent subsegment pointed to by any */
+ /* triangle side or subsegment end that isn't attached to a real */
+ /* subsegment. */
+ m->dummysubbase = (subseg *) trimalloc(subsegbytes +
+ m->subsegs.alignbytes);
+ /* Align `dummysub' on a `subsegs.alignbytes'-byte boundary. */
+ alignptr = (unsigned long) m->dummysubbase;
+ m->dummysub = (subseg *)
+ (alignptr + (unsigned long) m->subsegs.alignbytes -
+ (alignptr % (unsigned long) m->subsegs.alignbytes));
+ /* Initialize the two adjoining subsegments to be the omnipresent */
+ /* subsegment. These will eventually be changed by various bonding */
+ /* operations, but their values don't really matter, as long as they */
+ /* can legally be dereferenced. */
+ m->dummysub[0] = (subseg) m->dummysub;
+ m->dummysub[1] = (subseg) m->dummysub;
+ /* Four NULL vertices. */
+ m->dummysub[2] = (subseg) NULL;
+ m->dummysub[3] = (subseg) NULL;
+ m->dummysub[4] = (subseg) NULL;
+ m->dummysub[5] = (subseg) NULL;
+ /* Initialize the two adjoining triangles to be "outer space." */
+ m->dummysub[6] = (subseg) m->dummytri;
+ m->dummysub[7] = (subseg) m->dummytri;
+ /* Set the boundary marker to zero. */
+ * (int *) (m->dummysub + 8) = 0;
+
+ /* Initialize the three adjoining subsegments of `dummytri' to be */
+ /* the omnipresent subsegment. */
+ m->dummytri[6] = (triangle) m->dummysub;
+ m->dummytri[7] = (triangle) m->dummysub;
+ m->dummytri[8] = (triangle) m->dummysub;
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* initializevertexpool() Calculate the size of the vertex data structure */
+/* and initialize its memory pool. */
+/* */
+/* This routine also computes the `vertexmarkindex' and `vertex2triindex' */
+/* indices used to find values within each vertex. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void initializevertexpool(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void initializevertexpool(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ int vertexsize;
+
+ /* The index within each vertex at which the boundary marker is found, */
+ /* followed by the vertex type. Ensure the vertex marker is aligned to */
+ /* a sizeof(int)-byte address. */
+ m->vertexmarkindex = ((m->mesh_dim + m->nextras) * sizeof(REAL) +
+ sizeof(int) - 1) /
+ sizeof(int);
+ vertexsize = (m->vertexmarkindex + 2) * sizeof(int);
+ if (b->poly) {
+ /* The index within each vertex at which a triangle pointer is found. */
+ /* Ensure the pointer is aligned to a sizeof(triangle)-byte address. */
+ m->vertex2triindex = (vertexsize + sizeof(triangle) - 1) /
+ sizeof(triangle);
+ vertexsize = (m->vertex2triindex + 1) * sizeof(triangle);
+ }
+
+ /* Initialize the pool of vertices. */
+ poolinit(&m->vertices, vertexsize, VERTEXPERBLOCK,
+ m->invertices > VERTEXPERBLOCK ? m->invertices : VERTEXPERBLOCK,
+ sizeof(REAL));
+}
+
+/*****************************************************************************/
+/* */
+/* initializetrisubpools() Calculate the sizes of the triangle and */
+/* subsegment data structures and initialize */
+/* their memory pools. */
+/* */
+/* This routine also computes the `highorderindex', `elemattribindex', and */
+/* `areaboundindex' indices used to find values within each triangle. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void initializetrisubpools(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void initializetrisubpools(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ int trisize;
+
+ /* The index within each triangle at which the extra nodes (above three) */
+ /* associated with high order elements are found. There are three */
+ /* pointers to other triangles, three pointers to corners, and possibly */
+ /* three pointers to subsegments before the extra nodes. */
+ m->highorderindex = 6 + (b->usesegments * 3);
+ /* The number of bytes occupied by a triangle. */
+ trisize = ((b->order + 1) * (b->order + 2) / 2 + (m->highorderindex - 3)) *
+ sizeof(triangle);
+ /* The index within each triangle at which its attributes are found, */
+ /* where the index is measured in REALs. */
+ m->elemattribindex = (trisize + sizeof(REAL) - 1) / sizeof(REAL);
+ /* The index within each triangle at which the maximum area constraint */
+ /* is found, where the index is measured in REALs. Note that if the */
+ /* `regionattrib' flag is set, an additional attribute will be added. */
+ m->areaboundindex = m->elemattribindex + m->eextras + b->regionattrib;
+ /* If triangle attributes or an area bound are needed, increase the number */
+ /* of bytes occupied by a triangle. */
+ if (b->vararea) {
+ trisize = (m->areaboundindex + 1) * sizeof(REAL);
+ } else if (m->eextras + b->regionattrib > 0) {
+ trisize = m->areaboundindex * sizeof(REAL);
+ }
+ /* If a Voronoi diagram or triangle neighbor graph is requested, make */
+ /* sure there's room to store an integer index in each triangle. This */
+ /* integer index can occupy the same space as the subsegment pointers */
+ /* or attributes or area constraint or extra nodes. */
+ if ((b->voronoi || b->neighbors) &&
+ (trisize < 6 * sizeof(triangle) + sizeof(int))) {
+ trisize = 6 * sizeof(triangle) + sizeof(int);
+ }
+
+ /* Having determined the memory size of a triangle, initialize the pool. */
+ poolinit(&m->triangles, trisize, TRIPERBLOCK,
+ (2 * m->invertices - 2) > TRIPERBLOCK ? (2 * m->invertices - 2) :
+ TRIPERBLOCK, 4);
+
+ if (b->usesegments) {
+ /* Initialize the pool of subsegments. Take into account all eight */
+ /* pointers and one boundary marker. */
+ poolinit(&m->subsegs, 8 * sizeof(triangle) + sizeof(int),
+ SUBSEGPERBLOCK, SUBSEGPERBLOCK, 4);
+
+ /* Initialize the "outer space" triangle and omnipresent subsegment. */
+ dummyinit(m, b, m->triangles.itembytes, m->subsegs.itembytes);
+ } else {
+ /* Initialize the "outer space" triangle. */
+ dummyinit(m, b, m->triangles.itembytes, 0);
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* triangledealloc() Deallocate space for a triangle, marking it dead. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void triangledealloc(struct mesh *m, triangle *dyingtriangle)
+#else /* not ANSI_DECLARATORS */
+void triangledealloc(m, dyingtriangle)
+struct mesh *m;
+triangle *dyingtriangle;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ /* Mark the triangle as dead. This makes it possible to detect dead */
+ /* triangles when traversing the list of all triangles. */
+ killtri(dyingtriangle);
+ pooldealloc(&m->triangles, (VOID *) dyingtriangle);
+}
+
+/*****************************************************************************/
+/* */
+/* triangletraverse() Traverse the triangles, skipping dead ones. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+triangle *triangletraverse(struct mesh *m)
+#else /* not ANSI_DECLARATORS */
+triangle *triangletraverse(m)
+struct mesh *m;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ triangle *newtriangle;
+
+ do {
+ newtriangle = (triangle *) traverse(&m->triangles);
+ if (newtriangle == (triangle *) NULL) {
+ return (triangle *) NULL;
+ }
+ } while (deadtri(newtriangle)); /* Skip dead ones. */
+ return newtriangle;
+}
+
+/*****************************************************************************/
+/* */
+/* subsegdealloc() Deallocate space for a subsegment, marking it dead. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void subsegdealloc(struct mesh *m, subseg *dyingsubseg)
+#else /* not ANSI_DECLARATORS */
+void subsegdealloc(m, dyingsubseg)
+struct mesh *m;
+subseg *dyingsubseg;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ /* Mark the subsegment as dead. This makes it possible to detect dead */
+ /* subsegments when traversing the list of all subsegments. */
+ killsubseg(dyingsubseg);
+ pooldealloc(&m->subsegs, (VOID *) dyingsubseg);
+}
+
+/*****************************************************************************/
+/* */
+/* subsegtraverse() Traverse the subsegments, skipping dead ones. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+subseg *subsegtraverse(struct mesh *m)
+#else /* not ANSI_DECLARATORS */
+subseg *subsegtraverse(m)
+struct mesh *m;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ subseg *newsubseg;
+
+ do {
+ newsubseg = (subseg *) traverse(&m->subsegs);
+ if (newsubseg == (subseg *) NULL) {
+ return (subseg *) NULL;
+ }
+ } while (deadsubseg(newsubseg)); /* Skip dead ones. */
+ return newsubseg;
+}
+
+/*****************************************************************************/
+/* */
+/* vertexdealloc() Deallocate space for a vertex, marking it dead. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void vertexdealloc(struct mesh *m, vertex dyingvertex)
+#else /* not ANSI_DECLARATORS */
+void vertexdealloc(m, dyingvertex)
+struct mesh *m;
+vertex dyingvertex;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ /* Mark the vertex as dead. This makes it possible to detect dead */
+ /* vertices when traversing the list of all vertices. */
+ setvertextype(dyingvertex, DEADVERTEX);
+ pooldealloc(&m->vertices, (VOID *) dyingvertex);
+}
+
+/*****************************************************************************/
+/* */
+/* vertextraverse() Traverse the vertices, skipping dead ones. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+vertex vertextraverse(struct mesh *m)
+#else /* not ANSI_DECLARATORS */
+vertex vertextraverse(m)
+struct mesh *m;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ vertex newvertex;
+
+ do {
+ newvertex = (vertex) traverse(&m->vertices);
+ if (newvertex == (vertex) NULL) {
+ return (vertex) NULL;
+ }
+ } while (vertextype(newvertex) == DEADVERTEX); /* Skip dead ones. */
+ return newvertex;
+}
+
+/*****************************************************************************/
+/* */
+/* badsubsegdealloc() Deallocate space for a bad subsegment, marking it */
+/* dead. */
+/* */
+/*****************************************************************************/
+
+#ifndef CDT_ONLY
+
+#ifdef ANSI_DECLARATORS
+void badsubsegdealloc(struct mesh *m, struct badsubseg *dyingseg)
+#else /* not ANSI_DECLARATORS */
+void badsubsegdealloc(m, dyingseg)
+struct mesh *m;
+struct badsubseg *dyingseg;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ /* Set subsegment's origin to NULL. This makes it possible to detect dead */
+ /* badsubsegs when traversing the list of all badsubsegs . */
+ dyingseg->subsegorg = (vertex) NULL;
+ pooldealloc(&m->badsubsegs, (VOID *) dyingseg);
+}
+
+#endif /* not CDT_ONLY */
+
+/*****************************************************************************/
+/* */
+/* badsubsegtraverse() Traverse the bad subsegments, skipping dead ones. */
+/* */
+/*****************************************************************************/
+
+#ifndef CDT_ONLY
+
+#ifdef ANSI_DECLARATORS
+struct badsubseg *badsubsegtraverse(struct mesh *m)
+#else /* not ANSI_DECLARATORS */
+struct badsubseg *badsubsegtraverse(m)
+struct mesh *m;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct badsubseg *newseg;
+
+ do {
+ newseg = (struct badsubseg *) traverse(&m->badsubsegs);
+ if (newseg == (struct badsubseg *) NULL) {
+ return (struct badsubseg *) NULL;
+ }
+ } while (newseg->subsegorg == (vertex) NULL); /* Skip dead ones. */
+ return newseg;
+}
+
+#endif /* not CDT_ONLY */
+
+/*****************************************************************************/
+/* */
+/* getvertex() Get a specific vertex, by number, from the list. */
+/* */
+/* The first vertex is number 'firstnumber'. */
+/* */
+/* Note that this takes O(n) time (with a small constant, if VERTEXPERBLOCK */
+/* is large). I don't care to take the trouble to make it work in constant */
+/* time. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+vertex getvertex(struct mesh *m, struct behavior *b, int number)
+#else /* not ANSI_DECLARATORS */
+vertex getvertex(m, b, number)
+struct mesh *m;
+struct behavior *b;
+int number;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ VOID **getblock;
+ char *foundvertex;
+ unsigned long alignptr;
+ int current;
+
+ getblock = m->vertices.firstblock;
+ current = b->firstnumber;
+
+ /* Find the right block. */
+ if (current + m->vertices.itemsfirstblock <= number) {
+ getblock = (VOID **) *getblock;
+ current += m->vertices.itemsfirstblock;
+ while (current + m->vertices.itemsperblock <= number) {
+ getblock = (VOID **) *getblock;
+ current += m->vertices.itemsperblock;
+ }
+ }
+
+ /* Now find the right vertex. */
+ alignptr = (unsigned long) (getblock + 1);
+ foundvertex = (char *) (alignptr + (unsigned long) m->vertices.alignbytes -
+ (alignptr % (unsigned long) m->vertices.alignbytes));
+ return (vertex) (foundvertex + m->vertices.itembytes * (number - current));
+}
+
+/*****************************************************************************/
+/* */
+/* triangledeinit() Free all remaining allocated memory. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void triangledeinit(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void triangledeinit(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ pooldeinit(&m->triangles);
+ trifree((VOID *) m->dummytribase);
+ if (b->usesegments) {
+ pooldeinit(&m->subsegs);
+ trifree((VOID *) m->dummysubbase);
+ }
+ pooldeinit(&m->vertices);
+#ifndef CDT_ONLY
+ if (b->quality) {
+ pooldeinit(&m->badsubsegs);
+ if ((b->minangle > 0.0) || b->vararea || b->fixedarea || b->usertest) {
+ pooldeinit(&m->badtriangles);
+ pooldeinit(&m->flipstackers);
+ }
+ }
+#endif /* not CDT_ONLY */
+}
+
+/** **/
+/** **/
+/********* Memory management routines end here *********/
+
+/********* Constructors begin here *********/
+/** **/
+/** **/
+
+/*****************************************************************************/
+/* */
+/* maketriangle() Create a new triangle with orientation zero. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void maketriangle(struct mesh *m, struct behavior *b, struct otri *newotri)
+#else /* not ANSI_DECLARATORS */
+void maketriangle(m, b, newotri)
+struct mesh *m;
+struct behavior *b;
+struct otri *newotri;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ int i;
+
+ newotri->tri = (triangle *) poolalloc(&m->triangles);
+ /* Initialize the three adjoining triangles to be "outer space". */
+ newotri->tri[0] = (triangle) m->dummytri;
+ newotri->tri[1] = (triangle) m->dummytri;
+ newotri->tri[2] = (triangle) m->dummytri;
+ /* Three NULL vertices. */
+ newotri->tri[3] = (triangle) NULL;
+ newotri->tri[4] = (triangle) NULL;
+ newotri->tri[5] = (triangle) NULL;
+ if (b->usesegments) {
+ /* Initialize the three adjoining subsegments to be the omnipresent */
+ /* subsegment. */
+ newotri->tri[6] = (triangle) m->dummysub;
+ newotri->tri[7] = (triangle) m->dummysub;
+ newotri->tri[8] = (triangle) m->dummysub;
+ }
+ for (i = 0; i < m->eextras; i++) {
+ setelemattribute(*newotri, i, 0.0);
+ }
+ if (b->vararea) {
+ setareabound(*newotri, -1.0);
+ }
+
+ newotri->orient = 0;
+}
+
+/*****************************************************************************/
+/* */
+/* makesubseg() Create a new subsegment with orientation zero. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void makesubseg(struct mesh *m, struct osub *newsubseg)
+#else /* not ANSI_DECLARATORS */
+void makesubseg(m, newsubseg)
+struct mesh *m;
+struct osub *newsubseg;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ newsubseg->ss = (subseg *) poolalloc(&m->subsegs);
+ /* Initialize the two adjoining subsegments to be the omnipresent */
+ /* subsegment. */
+ newsubseg->ss[0] = (subseg) m->dummysub;
+ newsubseg->ss[1] = (subseg) m->dummysub;
+ /* Four NULL vertices. */
+ newsubseg->ss[2] = (subseg) NULL;
+ newsubseg->ss[3] = (subseg) NULL;
+ newsubseg->ss[4] = (subseg) NULL;
+ newsubseg->ss[5] = (subseg) NULL;
+ /* Initialize the two adjoining triangles to be "outer space." */
+ newsubseg->ss[6] = (subseg) m->dummytri;
+ newsubseg->ss[7] = (subseg) m->dummytri;
+ /* Set the boundary marker to zero. */
+ setmark(*newsubseg, 0);
+
+ newsubseg->ssorient = 0;
+}
+
+/** **/
+/** **/
+/********* Constructors end here *********/
+
+/********* Geometric primitives begin here *********/
+/** **/
+/** **/
+
+/* The adaptive exact arithmetic geometric predicates implemented herein are */
+/* described in detail in my paper, "Adaptive Precision Floating-Point */
+/* Arithmetic and Fast Robust Geometric Predicates." See the header for a */
+/* full citation. */
+
+/* Which of the following two methods of finding the absolute values is */
+/* fastest is compiler-dependent. A few compilers can inline and optimize */
+/* the fabs() call; but most will incur the overhead of a function call, */
+/* which is disastrously slow. A faster way on IEEE machines might be to */
+/* mask the appropriate bit, but that's difficult to do in C without */
+/* forcing the value to be stored to memory (rather than be kept in the */
+/* register to which the optimizer assigned it). */
+
+#define Absolute(a) ((a) >= 0.0 ? (a) : -(a))
+/* #define Absolute(a) fabs(a) */
+
+/* Many of the operations are broken up into two pieces, a main part that */
+/* performs an approximate operation, and a "tail" that computes the */
+/* roundoff error of that operation. */
+/* */
+/* The operations Fast_Two_Sum(), Fast_Two_Diff(), Two_Sum(), Two_Diff(), */
+/* Split(), and Two_Product() are all implemented as described in the */
+/* reference. Each of these macros requires certain variables to be */
+/* defined in the calling routine. The variables `bvirt', `c', `abig', */
+/* `_i', `_j', `_k', `_l', `_m', and `_n' are declared `INEXACT' because */
+/* they store the result of an operation that may incur roundoff error. */
+/* The input parameter `x' (or the highest numbered `x_' parameter) must */
+/* also be declared `INEXACT'. */
+
+#define Fast_Two_Sum_Tail(a, b, x, y) \
+ bvirt = x - a; \
+ y = b - bvirt
+
+#define Fast_Two_Sum(a, b, x, y) \
+ x = (REAL) (a + b); \
+ Fast_Two_Sum_Tail(a, b, x, y)
+
+#define Two_Sum_Tail(a, b, x, y) \
+ bvirt = (REAL) (x - a); \
+ avirt = x - bvirt; \
+ bround = b - bvirt; \
+ around = a - avirt; \
+ y = around + bround
+
+#define Two_Sum(a, b, x, y) \
+ x = (REAL) (a + b); \
+ Two_Sum_Tail(a, b, x, y)
+
+#define Two_Diff_Tail(a, b, x, y) \
+ bvirt = (REAL) (a - x); \
+ avirt = x + bvirt; \
+ bround = bvirt - b; \
+ around = a - avirt; \
+ y = around + bround
+
+#define Two_Diff(a, b, x, y) \
+ x = (REAL) (a - b); \
+ Two_Diff_Tail(a, b, x, y)
+
+#define Split(a, ahi, alo) \
+ c = (REAL) (splitter * a); \
+ abig = (REAL) (c - a); \
+ ahi = c - abig; \
+ alo = a - ahi
+
+#define Two_Product_Tail(a, b, x, y) \
+ Split(a, ahi, alo); \
+ Split(b, bhi, blo); \
+ err1 = x - (ahi * bhi); \
+ err2 = err1 - (alo * bhi); \
+ err3 = err2 - (ahi * blo); \
+ y = (alo * blo) - err3
+
+#define Two_Product(a, b, x, y) \
+ x = (REAL) (a * b); \
+ Two_Product_Tail(a, b, x, y)
+
+/* Two_Product_Presplit() is Two_Product() where one of the inputs has */
+/* already been split. Avoids redundant splitting. */
+
+#define Two_Product_Presplit(a, b, bhi, blo, x, y) \
+ x = (REAL) (a * b); \
+ Split(a, ahi, alo); \
+ err1 = x - (ahi * bhi); \
+ err2 = err1 - (alo * bhi); \
+ err3 = err2 - (ahi * blo); \
+ y = (alo * blo) - err3
+
+/* Square() can be done more quickly than Two_Product(). */
+
+#define Square_Tail(a, x, y) \
+ Split(a, ahi, alo); \
+ err1 = x - (ahi * ahi); \
+ err3 = err1 - ((ahi + ahi) * alo); \
+ y = (alo * alo) - err3
+
+#define Square(a, x, y) \
+ x = (REAL) (a * a); \
+ Square_Tail(a, x, y)
+
+/* Macros for summing expansions of various fixed lengths. These are all */
+/* unrolled versions of Expansion_Sum(). */
+
+#define Two_One_Sum(a1, a0, b, x2, x1, x0) \
+ Two_Sum(a0, b , _i, x0); \
+ Two_Sum(a1, _i, x2, x1)
+
+#define Two_One_Diff(a1, a0, b, x2, x1, x0) \
+ Two_Diff(a0, b , _i, x0); \
+ Two_Sum( a1, _i, x2, x1)
+
+#define Two_Two_Sum(a1, a0, b1, b0, x3, x2, x1, x0) \
+ Two_One_Sum(a1, a0, b0, _j, _0, x0); \
+ Two_One_Sum(_j, _0, b1, x3, x2, x1)
+
+#define Two_Two_Diff(a1, a0, b1, b0, x3, x2, x1, x0) \
+ Two_One_Diff(a1, a0, b0, _j, _0, x0); \
+ Two_One_Diff(_j, _0, b1, x3, x2, x1)
+
+/* Macro for multiplying a two-component expansion by a single component. */
+
+#define Two_One_Product(a1, a0, b, x3, x2, x1, x0) \
+ Split(b, bhi, blo); \
+ Two_Product_Presplit(a0, b, bhi, blo, _i, x0); \
+ Two_Product_Presplit(a1, b, bhi, blo, _j, _0); \
+ Two_Sum(_i, _0, _k, x1); \
+ Fast_Two_Sum(_j, _k, x3, x2)
+
+/*****************************************************************************/
+/* */
+/* exactinit() Initialize the variables used for exact arithmetic. */
+/* */
+/* `epsilon' is the largest power of two such that 1.0 + epsilon = 1.0 in */
+/* floating-point arithmetic. `epsilon' bounds the relative roundoff */
+/* error. It is used for floating-point error analysis. */
+/* */
+/* `splitter' is used to split floating-point numbers into two half- */
+/* length significands for exact multiplication. */
+/* */
+/* I imagine that a highly optimizing compiler might be too smart for its */
+/* own good, and somehow cause this routine to fail, if it pretends that */
+/* floating-point arithmetic is too much like real arithmetic. */
+/* */
+/* Don't change this routine unless you fully understand it. */
+/* */
+/*****************************************************************************/
+
+void exactinit()
+{
+ REAL half;
+ REAL check, lastcheck;
+ int every_other;
+#ifdef LINUX
+ int cword;
+#endif /* LINUX */
+
+#ifdef CPU86
+#ifdef SINGLE
+ _control87(_PC_24, _MCW_PC); /* Set FPU control word for single precision. */
+#else /* not SINGLE */
+ _control87(_PC_53, _MCW_PC); /* Set FPU control word for double precision. */
+#endif /* not SINGLE */
+#endif /* CPU86 */
+#ifdef LINUX
+#ifdef SINGLE
+ /* cword = 4223; */
+ cword = 4210; /* set FPU control word for single precision */
+#else /* not SINGLE */
+ /* cword = 4735; */
+ cword = 4722; /* set FPU control word for double precision */
+#endif /* not SINGLE */
+ _FPU_SETCW(cword);
+#endif /* LINUX */
+
+ every_other = 1;
+ half = 0.5;
+ epsilon = 1.0;
+ splitter = 1.0;
+ check = 1.0;
+ /* Repeatedly divide `epsilon' by two until it is too small to add to */
+ /* one without causing roundoff. (Also check if the sum is equal to */
+ /* the previous sum, for machines that round up instead of using exact */
+ /* rounding. Not that these routines will work on such machines.) */
+ do {
+ lastcheck = check;
+ epsilon *= half;
+ if (every_other) {
+ splitter *= 2.0;
+ }
+ every_other = !every_other;
+ check = 1.0 + epsilon;
+ } while ((check != 1.0) && (check != lastcheck));
+ splitter += 1.0;
+ /* Error bounds for orientation and incircle tests. */
+ resulterrbound = (3.0 + 8.0 * epsilon) * epsilon;
+ ccwerrboundA = (3.0 + 16.0 * epsilon) * epsilon;
+ ccwerrboundB = (2.0 + 12.0 * epsilon) * epsilon;
+ ccwerrboundC = (9.0 + 64.0 * epsilon) * epsilon * epsilon;
+ iccerrboundA = (10.0 + 96.0 * epsilon) * epsilon;
+ iccerrboundB = (4.0 + 48.0 * epsilon) * epsilon;
+ iccerrboundC = (44.0 + 576.0 * epsilon) * epsilon * epsilon;
+ o3derrboundA = (7.0 + 56.0 * epsilon) * epsilon;
+ o3derrboundB = (3.0 + 28.0 * epsilon) * epsilon;
+ o3derrboundC = (26.0 + 288.0 * epsilon) * epsilon * epsilon;
+}
+
+/*****************************************************************************/
+/* */
+/* fast_expansion_sum_zeroelim() Sum two expansions, eliminating zero */
+/* components from the output expansion. */
+/* */
+/* Sets h = e + f. See my Robust Predicates paper for details. */
+/* */
+/* If round-to-even is used (as with IEEE 754), maintains the strongly */
+/* nonoverlapping property. (That is, if e is strongly nonoverlapping, h */
+/* will be also.) Does NOT maintain the nonoverlapping or nonadjacent */
+/* properties. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+int fast_expansion_sum_zeroelim(int elen, REAL *e, int flen, REAL *f, REAL *h)
+#else /* not ANSI_DECLARATORS */
+int fast_expansion_sum_zeroelim(elen, e, flen, f, h) /* h cannot be e or f. */
+int elen;
+REAL *e;
+int flen;
+REAL *f;
+REAL *h;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ REAL Q;
+ INEXACT REAL Qnew;
+ INEXACT REAL hh;
+ INEXACT REAL bvirt;
+ REAL avirt, bround, around;
+ int eindex, findex, hindex;
+ REAL enow, fnow;
+
+ enow = e[0];
+ fnow = f[0];
+ eindex = findex = 0;
+ if ((fnow > enow) == (fnow > -enow)) {
+ Q = enow;
+ enow = e[++eindex];
+ } else {
+ Q = fnow;
+ fnow = f[++findex];
+ }
+ hindex = 0;
+ if ((eindex < elen) && (findex < flen)) {
+ if ((fnow > enow) == (fnow > -enow)) {
+ Fast_Two_Sum(enow, Q, Qnew, hh);
+ enow = e[++eindex];
+ } else {
+ Fast_Two_Sum(fnow, Q, Qnew, hh);
+ fnow = f[++findex];
+ }
+ Q = Qnew;
+ if (hh != 0.0) {
+ h[hindex++] = hh;
+ }
+ while ((eindex < elen) && (findex < flen)) {
+ if ((fnow > enow) == (fnow > -enow)) {
+ Two_Sum(Q, enow, Qnew, hh);
+ enow = e[++eindex];
+ } else {
+ Two_Sum(Q, fnow, Qnew, hh);
+ fnow = f[++findex];
+ }
+ Q = Qnew;
+ if (hh != 0.0) {
+ h[hindex++] = hh;
+ }
+ }
+ }
+ while (eindex < elen) {
+ Two_Sum(Q, enow, Qnew, hh);
+ enow = e[++eindex];
+ Q = Qnew;
+ if (hh != 0.0) {
+ h[hindex++] = hh;
+ }
+ }
+ while (findex < flen) {
+ Two_Sum(Q, fnow, Qnew, hh);
+ fnow = f[++findex];
+ Q = Qnew;
+ if (hh != 0.0) {
+ h[hindex++] = hh;
+ }
+ }
+ if ((Q != 0.0) || (hindex == 0)) {
+ h[hindex++] = Q;
+ }
+ return hindex;
+}
+
+/*****************************************************************************/
+/* */
+/* scale_expansion_zeroelim() Multiply an expansion by a scalar, */
+/* eliminating zero components from the */
+/* output expansion. */
+/* */
+/* Sets h = be. See my Robust Predicates paper for details. */
+/* */
+/* Maintains the nonoverlapping property. If round-to-even is used (as */
+/* with IEEE 754), maintains the strongly nonoverlapping and nonadjacent */
+/* properties as well. (That is, if e has one of these properties, so */
+/* will h.) */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+int scale_expansion_zeroelim(int elen, REAL *e, REAL b, REAL *h)
+#else /* not ANSI_DECLARATORS */
+int scale_expansion_zeroelim(elen, e, b, h) /* e and h cannot be the same. */
+int elen;
+REAL *e;
+REAL b;
+REAL *h;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ INEXACT REAL Q, sum;
+ REAL hh;
+ INEXACT REAL product1;
+ REAL product0;
+ int eindex, hindex;
+ REAL enow;
+ INEXACT REAL bvirt;
+ REAL avirt, bround, around;
+ INEXACT REAL c;
+ INEXACT REAL abig;
+ REAL ahi, alo, bhi, blo;
+ REAL err1, err2, err3;
+
+ Split(b, bhi, blo);
+ Two_Product_Presplit(e[0], b, bhi, blo, Q, hh);
+ hindex = 0;
+ if (hh != 0) {
+ h[hindex++] = hh;
+ }
+ for (eindex = 1; eindex < elen; eindex++) {
+ enow = e[eindex];
+ Two_Product_Presplit(enow, b, bhi, blo, product1, product0);
+ Two_Sum(Q, product0, sum, hh);
+ if (hh != 0) {
+ h[hindex++] = hh;
+ }
+ Fast_Two_Sum(product1, sum, Q, hh);
+ if (hh != 0) {
+ h[hindex++] = hh;
+ }
+ }
+ if ((Q != 0.0) || (hindex == 0)) {
+ h[hindex++] = Q;
+ }
+ return hindex;
+}
+
+/*****************************************************************************/
+/* */
+/* estimate() Produce a one-word estimate of an expansion's value. */
+/* */
+/* See my Robust Predicates paper for details. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+REAL estimate(int elen, REAL *e)
+#else /* not ANSI_DECLARATORS */
+REAL estimate(elen, e)
+int elen;
+REAL *e;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ REAL Q;
+ int eindex;
+
+ Q = e[0];
+ for (eindex = 1; eindex < elen; eindex++) {
+ Q += e[eindex];
+ }
+ return Q;
+}
+
+/*****************************************************************************/
+/* */
+/* counterclockwise() Return a positive value if the points pa, pb, and */
+/* pc occur in counterclockwise order; a negative */
+/* value if they occur in clockwise order; and zero */
+/* if they are collinear. The result is also a rough */
+/* approximation of twice the signed area of the */
+/* triangle defined by the three points. */
+/* */
+/* Uses exact arithmetic if necessary to ensure a correct answer. The */
+/* result returned is the determinant of a matrix. This determinant is */
+/* computed adaptively, in the sense that exact arithmetic is used only to */
+/* the degree it is needed to ensure that the returned value has the */
+/* correct sign. Hence, this function is usually quite fast, but will run */
+/* more slowly when the input points are collinear or nearly so. */
+/* */
+/* See my Robust Predicates paper for details. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+REAL counterclockwiseadapt(vertex pa, vertex pb, vertex pc, REAL detsum)
+#else /* not ANSI_DECLARATORS */
+REAL counterclockwiseadapt(pa, pb, pc, detsum)
+vertex pa;
+vertex pb;
+vertex pc;
+REAL detsum;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ INEXACT REAL acx, acy, bcx, bcy;
+ REAL acxtail, acytail, bcxtail, bcytail;
+ INEXACT REAL detleft, detright;
+ REAL detlefttail, detrighttail;
+ REAL det, errbound;
+ REAL B[4], C1[8], C2[12], D[16];
+ INEXACT REAL B3;
+ int C1length, C2length, Dlength;
+ REAL u[4];
+ INEXACT REAL u3;
+ INEXACT REAL s1, t1;
+ REAL s0, t0;
+
+ INEXACT REAL bvirt;
+ REAL avirt, bround, around;
+ INEXACT REAL c;
+ INEXACT REAL abig;
+ REAL ahi, alo, bhi, blo;
+ REAL err1, err2, err3;
+ INEXACT REAL _i, _j;
+ REAL _0;
+
+ acx = (REAL) (pa[0] - pc[0]);
+ bcx = (REAL) (pb[0] - pc[0]);
+ acy = (REAL) (pa[1] - pc[1]);
+ bcy = (REAL) (pb[1] - pc[1]);
+
+ Two_Product(acx, bcy, detleft, detlefttail);
+ Two_Product(acy, bcx, detright, detrighttail);
+
+ Two_Two_Diff(detleft, detlefttail, detright, detrighttail,
+ B3, B[2], B[1], B[0]);
+ B[3] = B3;
+
+ det = estimate(4, B);
+ errbound = ccwerrboundB * detsum;
+ if ((det >= errbound) || (-det >= errbound)) {
+ return det;
+ }
+
+ Two_Diff_Tail(pa[0], pc[0], acx, acxtail);
+ Two_Diff_Tail(pb[0], pc[0], bcx, bcxtail);
+ Two_Diff_Tail(pa[1], pc[1], acy, acytail);
+ Two_Diff_Tail(pb[1], pc[1], bcy, bcytail);
+
+ if ((acxtail == 0.0) && (acytail == 0.0)
+ && (bcxtail == 0.0) && (bcytail == 0.0)) {
+ return det;
+ }
+
+ errbound = ccwerrboundC * detsum + resulterrbound * Absolute(det);
+ det += (acx * bcytail + bcy * acxtail)
+ - (acy * bcxtail + bcx * acytail);
+ if ((det >= errbound) || (-det >= errbound)) {
+ return det;
+ }
+
+ Two_Product(acxtail, bcy, s1, s0);
+ Two_Product(acytail, bcx, t1, t0);
+ Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ C1length = fast_expansion_sum_zeroelim(4, B, 4, u, C1);
+
+ Two_Product(acx, bcytail, s1, s0);
+ Two_Product(acy, bcxtail, t1, t0);
+ Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ C2length = fast_expansion_sum_zeroelim(C1length, C1, 4, u, C2);
+
+ Two_Product(acxtail, bcytail, s1, s0);
+ Two_Product(acytail, bcxtail, t1, t0);
+ Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ Dlength = fast_expansion_sum_zeroelim(C2length, C2, 4, u, D);
+
+ return(D[Dlength - 1]);
+}
+
+#ifdef ANSI_DECLARATORS
+REAL counterclockwise(struct mesh *m, struct behavior *b,
+ vertex pa, vertex pb, vertex pc)
+#else /* not ANSI_DECLARATORS */
+REAL counterclockwise(m, b, pa, pb, pc)
+struct mesh *m;
+struct behavior *b;
+vertex pa;
+vertex pb;
+vertex pc;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ REAL detleft, detright, det;
+ REAL detsum, errbound;
+
+ m->counterclockcount++;
+
+ detleft = (pa[0] - pc[0]) * (pb[1] - pc[1]);
+ detright = (pa[1] - pc[1]) * (pb[0] - pc[0]);
+ det = detleft - detright;
+
+ if (b->noexact) {
+ return det;
+ }
+
+ if (detleft > 0.0) {
+ if (detright <= 0.0) {
+ return det;
+ } else {
+ detsum = detleft + detright;
+ }
+ } else if (detleft < 0.0) {
+ if (detright >= 0.0) {
+ return det;
+ } else {
+ detsum = -detleft - detright;
+ }
+ } else {
+ return det;
+ }
+
+ errbound = ccwerrboundA * detsum;
+ if ((det >= errbound) || (-det >= errbound)) {
+ return det;
+ }
+
+ return counterclockwiseadapt(pa, pb, pc, detsum);
+}
+
+/*****************************************************************************/
+/* */
+/* incircle() Return a positive value if the point pd lies inside the */
+/* circle passing through pa, pb, and pc; a negative value if */
+/* it lies outside; and zero if the four points are cocircular.*/
+/* The points pa, pb, and pc must be in counterclockwise */
+/* order, or the sign of the result will be reversed. */
+/* */
+/* Uses exact arithmetic if necessary to ensure a correct answer. The */
+/* result returned is the determinant of a matrix. This determinant is */
+/* computed adaptively, in the sense that exact arithmetic is used only to */
+/* the degree it is needed to ensure that the returned value has the */
+/* correct sign. Hence, this function is usually quite fast, but will run */
+/* more slowly when the input points are cocircular or nearly so. */
+/* */
+/* See my Robust Predicates paper for details. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+REAL incircleadapt(vertex pa, vertex pb, vertex pc, vertex pd, REAL permanent)
+#else /* not ANSI_DECLARATORS */
+REAL incircleadapt(pa, pb, pc, pd, permanent)
+vertex pa;
+vertex pb;
+vertex pc;
+vertex pd;
+REAL permanent;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ INEXACT REAL adx, bdx, cdx, ady, bdy, cdy;
+ REAL det, errbound;
+
+ INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
+ REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
+ REAL bc[4], ca[4], ab[4];
+ INEXACT REAL bc3, ca3, ab3;
+ REAL axbc[8], axxbc[16], aybc[8], ayybc[16], adet[32];
+ int axbclen, axxbclen, aybclen, ayybclen, alen;
+ REAL bxca[8], bxxca[16], byca[8], byyca[16], bdet[32];
+ int bxcalen, bxxcalen, bycalen, byycalen, blen;
+ REAL cxab[8], cxxab[16], cyab[8], cyyab[16], cdet[32];
+ int cxablen, cxxablen, cyablen, cyyablen, clen;
+ REAL abdet[64];
+ int ablen;
+ REAL fin1[1152], fin2[1152];
+ REAL *finnow, *finother, *finswap;
+ int finlength;
+
+ REAL adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail;
+ INEXACT REAL adxadx1, adyady1, bdxbdx1, bdybdy1, cdxcdx1, cdycdy1;
+ REAL adxadx0, adyady0, bdxbdx0, bdybdy0, cdxcdx0, cdycdy0;
+ REAL aa[4], bb[4], cc[4];
+ INEXACT REAL aa3, bb3, cc3;
+ INEXACT REAL ti1, tj1;
+ REAL ti0, tj0;
+ REAL u[4], v[4];
+ INEXACT REAL u3, v3;
+ REAL temp8[8], temp16a[16], temp16b[16], temp16c[16];
+ REAL temp32a[32], temp32b[32], temp48[48], temp64[64];
+ int temp8len, temp16alen, temp16blen, temp16clen;
+ int temp32alen, temp32blen, temp48len, temp64len;
+ REAL axtbb[8], axtcc[8], aytbb[8], aytcc[8];
+ int axtbblen, axtcclen, aytbblen, aytcclen;
+ REAL bxtaa[8], bxtcc[8], bytaa[8], bytcc[8];
+ int bxtaalen, bxtcclen, bytaalen, bytcclen;
+ REAL cxtaa[8], cxtbb[8], cytaa[8], cytbb[8];
+ int cxtaalen, cxtbblen, cytaalen, cytbblen;
+ REAL axtbc[8], aytbc[8], bxtca[8], bytca[8], cxtab[8], cytab[8];
+ int axtbclen = 0, aytbclen = 0, bxtcalen = 0, bytcalen = 0, cxtablen = 0, cytablen = 0;
+ REAL axtbct[16], aytbct[16], bxtcat[16], bytcat[16], cxtabt[16], cytabt[16];
+ int axtbctlen, aytbctlen, bxtcatlen, bytcatlen, cxtabtlen, cytabtlen;
+ REAL axtbctt[8], aytbctt[8], bxtcatt[8];
+ REAL bytcatt[8], cxtabtt[8], cytabtt[8];
+ int axtbcttlen, aytbcttlen, bxtcattlen, bytcattlen, cxtabttlen, cytabttlen;
+ REAL abt[8], bct[8], cat[8];
+ int abtlen, bctlen, catlen;
+ REAL abtt[4], bctt[4], catt[4];
+ int abttlen, bcttlen, cattlen;
+ INEXACT REAL abtt3, bctt3, catt3;
+ REAL negate;
+
+ INEXACT REAL bvirt;
+ REAL avirt, bround, around;
+ INEXACT REAL c;
+ INEXACT REAL abig;
+ REAL ahi, alo, bhi, blo;
+ REAL err1, err2, err3;
+ INEXACT REAL _i, _j;
+ REAL _0;
+
+ adx = (REAL) (pa[0] - pd[0]);
+ bdx = (REAL) (pb[0] - pd[0]);
+ cdx = (REAL) (pc[0] - pd[0]);
+ ady = (REAL) (pa[1] - pd[1]);
+ bdy = (REAL) (pb[1] - pd[1]);
+ cdy = (REAL) (pc[1] - pd[1]);
+
+ Two_Product(bdx, cdy, bdxcdy1, bdxcdy0);
+ Two_Product(cdx, bdy, cdxbdy1, cdxbdy0);
+ Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]);
+ bc[3] = bc3;
+ axbclen = scale_expansion_zeroelim(4, bc, adx, axbc);
+ axxbclen = scale_expansion_zeroelim(axbclen, axbc, adx, axxbc);
+ aybclen = scale_expansion_zeroelim(4, bc, ady, aybc);
+ ayybclen = scale_expansion_zeroelim(aybclen, aybc, ady, ayybc);
+ alen = fast_expansion_sum_zeroelim(axxbclen, axxbc, ayybclen, ayybc, adet);
+
+ Two_Product(cdx, ady, cdxady1, cdxady0);
+ Two_Product(adx, cdy, adxcdy1, adxcdy0);
+ Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]);
+ ca[3] = ca3;
+ bxcalen = scale_expansion_zeroelim(4, ca, bdx, bxca);
+ bxxcalen = scale_expansion_zeroelim(bxcalen, bxca, bdx, bxxca);
+ bycalen = scale_expansion_zeroelim(4, ca, bdy, byca);
+ byycalen = scale_expansion_zeroelim(bycalen, byca, bdy, byyca);
+ blen = fast_expansion_sum_zeroelim(bxxcalen, bxxca, byycalen, byyca, bdet);
+
+ Two_Product(adx, bdy, adxbdy1, adxbdy0);
+ Two_Product(bdx, ady, bdxady1, bdxady0);
+ Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]);
+ ab[3] = ab3;
+ cxablen = scale_expansion_zeroelim(4, ab, cdx, cxab);
+ cxxablen = scale_expansion_zeroelim(cxablen, cxab, cdx, cxxab);
+ cyablen = scale_expansion_zeroelim(4, ab, cdy, cyab);
+ cyyablen = scale_expansion_zeroelim(cyablen, cyab, cdy, cyyab);
+ clen = fast_expansion_sum_zeroelim(cxxablen, cxxab, cyyablen, cyyab, cdet);
+
+ ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet);
+ finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1);
+
+ det = estimate(finlength, fin1);
+ errbound = iccerrboundB * permanent;
+ if ((det >= errbound) || (-det >= errbound)) {
+ return det;
+ }
+
+ Two_Diff_Tail(pa[0], pd[0], adx, adxtail);
+ Two_Diff_Tail(pa[1], pd[1], ady, adytail);
+ Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail);
+ Two_Diff_Tail(pb[1], pd[1], bdy, bdytail);
+ Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail);
+ Two_Diff_Tail(pc[1], pd[1], cdy, cdytail);
+ if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0)
+ && (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0)) {
+ return det;
+ }
+
+ errbound = iccerrboundC * permanent + resulterrbound * Absolute(det);
+ det += ((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail)
+ - (bdy * cdxtail + cdx * bdytail))
+ + 2.0 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx))
+ + ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail)
+ - (cdy * adxtail + adx * cdytail))
+ + 2.0 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx))
+ + ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail)
+ - (ady * bdxtail + bdx * adytail))
+ + 2.0 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx));
+ if ((det >= errbound) || (-det >= errbound)) {
+ return det;
+ }
+
+ finnow = fin1;
+ finother = fin2;
+
+ if ((bdxtail != 0.0) || (bdytail != 0.0)
+ || (cdxtail != 0.0) || (cdytail != 0.0)) {
+ Square(adx, adxadx1, adxadx0);
+ Square(ady, adyady1, adyady0);
+ Two_Two_Sum(adxadx1, adxadx0, adyady1, adyady0, aa3, aa[2], aa[1], aa[0]);
+ aa[3] = aa3;
+ }
+ if ((cdxtail != 0.0) || (cdytail != 0.0)
+ || (adxtail != 0.0) || (adytail != 0.0)) {
+ Square(bdx, bdxbdx1, bdxbdx0);
+ Square(bdy, bdybdy1, bdybdy0);
+ Two_Two_Sum(bdxbdx1, bdxbdx0, bdybdy1, bdybdy0, bb3, bb[2], bb[1], bb[0]);
+ bb[3] = bb3;
+ }
+ if ((adxtail != 0.0) || (adytail != 0.0)
+ || (bdxtail != 0.0) || (bdytail != 0.0)) {
+ Square(cdx, cdxcdx1, cdxcdx0);
+ Square(cdy, cdycdy1, cdycdy0);
+ Two_Two_Sum(cdxcdx1, cdxcdx0, cdycdy1, cdycdy0, cc3, cc[2], cc[1], cc[0]);
+ cc[3] = cc3;
+ }
+
+ if (adxtail != 0.0) {
+ axtbclen = scale_expansion_zeroelim(4, bc, adxtail, axtbc);
+ temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, 2.0 * adx,
+ temp16a);
+
+ axtcclen = scale_expansion_zeroelim(4, cc, adxtail, axtcc);
+ temp16blen = scale_expansion_zeroelim(axtcclen, axtcc, bdy, temp16b);
+
+ axtbblen = scale_expansion_zeroelim(4, bb, adxtail, axtbb);
+ temp16clen = scale_expansion_zeroelim(axtbblen, axtbb, -cdy, temp16c);
+
+ temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp16blen, temp16b, temp32a);
+ temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
+ temp32alen, temp32a, temp48);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
+ temp48, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ if (adytail != 0.0) {
+ aytbclen = scale_expansion_zeroelim(4, bc, adytail, aytbc);
+ temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, 2.0 * ady,
+ temp16a);
+
+ aytbblen = scale_expansion_zeroelim(4, bb, adytail, aytbb);
+ temp16blen = scale_expansion_zeroelim(aytbblen, aytbb, cdx, temp16b);
+
+ aytcclen = scale_expansion_zeroelim(4, cc, adytail, aytcc);
+ temp16clen = scale_expansion_zeroelim(aytcclen, aytcc, -bdx, temp16c);
+
+ temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp16blen, temp16b, temp32a);
+ temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
+ temp32alen, temp32a, temp48);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
+ temp48, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ if (bdxtail != 0.0) {
+ bxtcalen = scale_expansion_zeroelim(4, ca, bdxtail, bxtca);
+ temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, 2.0 * bdx,
+ temp16a);
+
+ bxtaalen = scale_expansion_zeroelim(4, aa, bdxtail, bxtaa);
+ temp16blen = scale_expansion_zeroelim(bxtaalen, bxtaa, cdy, temp16b);
+
+ bxtcclen = scale_expansion_zeroelim(4, cc, bdxtail, bxtcc);
+ temp16clen = scale_expansion_zeroelim(bxtcclen, bxtcc, -ady, temp16c);
+
+ temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp16blen, temp16b, temp32a);
+ temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
+ temp32alen, temp32a, temp48);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
+ temp48, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ if (bdytail != 0.0) {
+ bytcalen = scale_expansion_zeroelim(4, ca, bdytail, bytca);
+ temp16alen = scale_expansion_zeroelim(bytcalen, bytca, 2.0 * bdy,
+ temp16a);
+
+ bytcclen = scale_expansion_zeroelim(4, cc, bdytail, bytcc);
+ temp16blen = scale_expansion_zeroelim(bytcclen, bytcc, adx, temp16b);
+
+ bytaalen = scale_expansion_zeroelim(4, aa, bdytail, bytaa);
+ temp16clen = scale_expansion_zeroelim(bytaalen, bytaa, -cdx, temp16c);
+
+ temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp16blen, temp16b, temp32a);
+ temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
+ temp32alen, temp32a, temp48);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
+ temp48, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ if (cdxtail != 0.0) {
+ cxtablen = scale_expansion_zeroelim(4, ab, cdxtail, cxtab);
+ temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, 2.0 * cdx,
+ temp16a);
+
+ cxtbblen = scale_expansion_zeroelim(4, bb, cdxtail, cxtbb);
+ temp16blen = scale_expansion_zeroelim(cxtbblen, cxtbb, ady, temp16b);
+
+ cxtaalen = scale_expansion_zeroelim(4, aa, cdxtail, cxtaa);
+ temp16clen = scale_expansion_zeroelim(cxtaalen, cxtaa, -bdy, temp16c);
+
+ temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp16blen, temp16b, temp32a);
+ temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
+ temp32alen, temp32a, temp48);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
+ temp48, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ if (cdytail != 0.0) {
+ cytablen = scale_expansion_zeroelim(4, ab, cdytail, cytab);
+ temp16alen = scale_expansion_zeroelim(cytablen, cytab, 2.0 * cdy,
+ temp16a);
+
+ cytaalen = scale_expansion_zeroelim(4, aa, cdytail, cytaa);
+ temp16blen = scale_expansion_zeroelim(cytaalen, cytaa, bdx, temp16b);
+
+ cytbblen = scale_expansion_zeroelim(4, bb, cdytail, cytbb);
+ temp16clen = scale_expansion_zeroelim(cytbblen, cytbb, -adx, temp16c);
+
+ temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp16blen, temp16b, temp32a);
+ temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c,
+ temp32alen, temp32a, temp48);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
+ temp48, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+
+ if ((adxtail != 0.0) || (adytail != 0.0)) {
+ if ((bdxtail != 0.0) || (bdytail != 0.0)
+ || (cdxtail != 0.0) || (cdytail != 0.0)) {
+ Two_Product(bdxtail, cdy, ti1, ti0);
+ Two_Product(bdx, cdytail, tj1, tj0);
+ Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ negate = -bdy;
+ Two_Product(cdxtail, negate, ti1, ti0);
+ negate = -bdytail;
+ Two_Product(cdx, negate, tj1, tj0);
+ Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
+ v[3] = v3;
+ bctlen = fast_expansion_sum_zeroelim(4, u, 4, v, bct);
+
+ Two_Product(bdxtail, cdytail, ti1, ti0);
+ Two_Product(cdxtail, bdytail, tj1, tj0);
+ Two_Two_Diff(ti1, ti0, tj1, tj0, bctt3, bctt[2], bctt[1], bctt[0]);
+ bctt[3] = bctt3;
+ bcttlen = 4;
+ } else {
+ bct[0] = 0.0;
+ bctlen = 1;
+ bctt[0] = 0.0;
+ bcttlen = 1;
+ }
+
+ if (adxtail != 0.0) {
+ temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, adxtail, temp16a);
+ axtbctlen = scale_expansion_zeroelim(bctlen, bct, adxtail, axtbct);
+ temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, 2.0 * adx,
+ temp32a);
+ temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp32alen, temp32a, temp48);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
+ temp48, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ if (bdytail != 0.0) {
+ temp8len = scale_expansion_zeroelim(4, cc, adxtail, temp8);
+ temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
+ temp16a);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
+ temp16a, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ if (cdytail != 0.0) {
+ temp8len = scale_expansion_zeroelim(4, bb, -adxtail, temp8);
+ temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
+ temp16a);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
+ temp16a, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+
+ temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, adxtail,
+ temp32a);
+ axtbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adxtail, axtbctt);
+ temp16alen = scale_expansion_zeroelim(axtbcttlen, axtbctt, 2.0 * adx,
+ temp16a);
+ temp16blen = scale_expansion_zeroelim(axtbcttlen, axtbctt, adxtail,
+ temp16b);
+ temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp16blen, temp16b, temp32b);
+ temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
+ temp32blen, temp32b, temp64);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
+ temp64, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ if (adytail != 0.0) {
+ temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, adytail, temp16a);
+ aytbctlen = scale_expansion_zeroelim(bctlen, bct, adytail, aytbct);
+ temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, 2.0 * ady,
+ temp32a);
+ temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp32alen, temp32a, temp48);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
+ temp48, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+
+
+ temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, adytail,
+ temp32a);
+ aytbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adytail, aytbctt);
+ temp16alen = scale_expansion_zeroelim(aytbcttlen, aytbctt, 2.0 * ady,
+ temp16a);
+ temp16blen = scale_expansion_zeroelim(aytbcttlen, aytbctt, adytail,
+ temp16b);
+ temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp16blen, temp16b, temp32b);
+ temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
+ temp32blen, temp32b, temp64);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
+ temp64, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ }
+ if ((bdxtail != 0.0) || (bdytail != 0.0)) {
+ if ((cdxtail != 0.0) || (cdytail != 0.0)
+ || (adxtail != 0.0) || (adytail != 0.0)) {
+ Two_Product(cdxtail, ady, ti1, ti0);
+ Two_Product(cdx, adytail, tj1, tj0);
+ Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ negate = -cdy;
+ Two_Product(adxtail, negate, ti1, ti0);
+ negate = -cdytail;
+ Two_Product(adx, negate, tj1, tj0);
+ Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
+ v[3] = v3;
+ catlen = fast_expansion_sum_zeroelim(4, u, 4, v, cat);
+
+ Two_Product(cdxtail, adytail, ti1, ti0);
+ Two_Product(adxtail, cdytail, tj1, tj0);
+ Two_Two_Diff(ti1, ti0, tj1, tj0, catt3, catt[2], catt[1], catt[0]);
+ catt[3] = catt3;
+ cattlen = 4;
+ } else {
+ cat[0] = 0.0;
+ catlen = 1;
+ catt[0] = 0.0;
+ cattlen = 1;
+ }
+
+ if (bdxtail != 0.0) {
+ temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, bdxtail, temp16a);
+ bxtcatlen = scale_expansion_zeroelim(catlen, cat, bdxtail, bxtcat);
+ temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, 2.0 * bdx,
+ temp32a);
+ temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp32alen, temp32a, temp48);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
+ temp48, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ if (cdytail != 0.0) {
+ temp8len = scale_expansion_zeroelim(4, aa, bdxtail, temp8);
+ temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail,
+ temp16a);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
+ temp16a, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ if (adytail != 0.0) {
+ temp8len = scale_expansion_zeroelim(4, cc, -bdxtail, temp8);
+ temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
+ temp16a);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
+ temp16a, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+
+ temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, bdxtail,
+ temp32a);
+ bxtcattlen = scale_expansion_zeroelim(cattlen, catt, bdxtail, bxtcatt);
+ temp16alen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, 2.0 * bdx,
+ temp16a);
+ temp16blen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, bdxtail,
+ temp16b);
+ temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp16blen, temp16b, temp32b);
+ temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
+ temp32blen, temp32b, temp64);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
+ temp64, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ if (bdytail != 0.0) {
+ temp16alen = scale_expansion_zeroelim(bytcalen, bytca, bdytail, temp16a);
+ bytcatlen = scale_expansion_zeroelim(catlen, cat, bdytail, bytcat);
+ temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, 2.0 * bdy,
+ temp32a);
+ temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp32alen, temp32a, temp48);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
+ temp48, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+
+
+ temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, bdytail,
+ temp32a);
+ bytcattlen = scale_expansion_zeroelim(cattlen, catt, bdytail, bytcatt);
+ temp16alen = scale_expansion_zeroelim(bytcattlen, bytcatt, 2.0 * bdy,
+ temp16a);
+ temp16blen = scale_expansion_zeroelim(bytcattlen, bytcatt, bdytail,
+ temp16b);
+ temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp16blen, temp16b, temp32b);
+ temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
+ temp32blen, temp32b, temp64);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
+ temp64, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ }
+ if ((cdxtail != 0.0) || (cdytail != 0.0)) {
+ if ((adxtail != 0.0) || (adytail != 0.0)
+ || (bdxtail != 0.0) || (bdytail != 0.0)) {
+ Two_Product(adxtail, bdy, ti1, ti0);
+ Two_Product(adx, bdytail, tj1, tj0);
+ Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ negate = -ady;
+ Two_Product(bdxtail, negate, ti1, ti0);
+ negate = -adytail;
+ Two_Product(bdx, negate, tj1, tj0);
+ Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]);
+ v[3] = v3;
+ abtlen = fast_expansion_sum_zeroelim(4, u, 4, v, abt);
+
+ Two_Product(adxtail, bdytail, ti1, ti0);
+ Two_Product(bdxtail, adytail, tj1, tj0);
+ Two_Two_Diff(ti1, ti0, tj1, tj0, abtt3, abtt[2], abtt[1], abtt[0]);
+ abtt[3] = abtt3;
+ abttlen = 4;
+ } else {
+ abt[0] = 0.0;
+ abtlen = 1;
+ abtt[0] = 0.0;
+ abttlen = 1;
+ }
+
+ if (cdxtail != 0.0) {
+ temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, cdxtail, temp16a);
+ cxtabtlen = scale_expansion_zeroelim(abtlen, abt, cdxtail, cxtabt);
+ temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, 2.0 * cdx,
+ temp32a);
+ temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp32alen, temp32a, temp48);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
+ temp48, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ if (adytail != 0.0) {
+ temp8len = scale_expansion_zeroelim(4, bb, cdxtail, temp8);
+ temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail,
+ temp16a);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
+ temp16a, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ if (bdytail != 0.0) {
+ temp8len = scale_expansion_zeroelim(4, aa, -cdxtail, temp8);
+ temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail,
+ temp16a);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen,
+ temp16a, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+
+ temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, cdxtail,
+ temp32a);
+ cxtabttlen = scale_expansion_zeroelim(abttlen, abtt, cdxtail, cxtabtt);
+ temp16alen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, 2.0 * cdx,
+ temp16a);
+ temp16blen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, cdxtail,
+ temp16b);
+ temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp16blen, temp16b, temp32b);
+ temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
+ temp32blen, temp32b, temp64);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
+ temp64, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ if (cdytail != 0.0) {
+ temp16alen = scale_expansion_zeroelim(cytablen, cytab, cdytail, temp16a);
+ cytabtlen = scale_expansion_zeroelim(abtlen, abt, cdytail, cytabt);
+ temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, 2.0 * cdy,
+ temp32a);
+ temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp32alen, temp32a, temp48);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len,
+ temp48, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+
+
+ temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, cdytail,
+ temp32a);
+ cytabttlen = scale_expansion_zeroelim(abttlen, abtt, cdytail, cytabtt);
+ temp16alen = scale_expansion_zeroelim(cytabttlen, cytabtt, 2.0 * cdy,
+ temp16a);
+ temp16blen = scale_expansion_zeroelim(cytabttlen, cytabtt, cdytail,
+ temp16b);
+ temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a,
+ temp16blen, temp16b, temp32b);
+ temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a,
+ temp32blen, temp32b, temp64);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len,
+ temp64, finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ }
+
+ return finnow[finlength - 1];
+}
+
+#ifdef ANSI_DECLARATORS
+REAL incircle(struct mesh *m, struct behavior *b,
+ vertex pa, vertex pb, vertex pc, vertex pd)
+#else /* not ANSI_DECLARATORS */
+REAL incircle(m, b, pa, pb, pc, pd)
+struct mesh *m;
+struct behavior *b;
+vertex pa;
+vertex pb;
+vertex pc;
+vertex pd;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ REAL adx, bdx, cdx, ady, bdy, cdy;
+ REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
+ REAL alift, blift, clift;
+ REAL det;
+ REAL permanent, errbound;
+
+ m->incirclecount++;
+
+ adx = pa[0] - pd[0];
+ bdx = pb[0] - pd[0];
+ cdx = pc[0] - pd[0];
+ ady = pa[1] - pd[1];
+ bdy = pb[1] - pd[1];
+ cdy = pc[1] - pd[1];
+
+ bdxcdy = bdx * cdy;
+ cdxbdy = cdx * bdy;
+ alift = adx * adx + ady * ady;
+
+ cdxady = cdx * ady;
+ adxcdy = adx * cdy;
+ blift = bdx * bdx + bdy * bdy;
+
+ adxbdy = adx * bdy;
+ bdxady = bdx * ady;
+ clift = cdx * cdx + cdy * cdy;
+
+ det = alift * (bdxcdy - cdxbdy)
+ + blift * (cdxady - adxcdy)
+ + clift * (adxbdy - bdxady);
+
+ if (b->noexact) {
+ return det;
+ }
+
+ permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * alift
+ + (Absolute(cdxady) + Absolute(adxcdy)) * blift
+ + (Absolute(adxbdy) + Absolute(bdxady)) * clift;
+ errbound = iccerrboundA * permanent;
+ if ((det > errbound) || (-det > errbound)) {
+ return det;
+ }
+
+ return incircleadapt(pa, pb, pc, pd, permanent);
+}
+
+/*****************************************************************************/
+/* */
+/* orient3d() Return a positive value if the point pd lies below the */
+/* plane passing through pa, pb, and pc; "below" is defined so */
+/* that pa, pb, and pc appear in counterclockwise order when */
+/* viewed from above the plane. Returns a negative value if */
+/* pd lies above the plane. Returns zero if the points are */
+/* coplanar. The result is also a rough approximation of six */
+/* times the signed volume of the tetrahedron defined by the */
+/* four points. */
+/* */
+/* Uses exact arithmetic if necessary to ensure a correct answer. The */
+/* result returned is the determinant of a matrix. This determinant is */
+/* computed adaptively, in the sense that exact arithmetic is used only to */
+/* the degree it is needed to ensure that the returned value has the */
+/* correct sign. Hence, this function is usually quite fast, but will run */
+/* more slowly when the input points are coplanar or nearly so. */
+/* */
+/* See my Robust Predicates paper for details. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+REAL orient3dadapt(vertex pa, vertex pb, vertex pc, vertex pd,
+ REAL aheight, REAL bheight, REAL cheight, REAL dheight,
+ REAL permanent)
+#else /* not ANSI_DECLARATORS */
+REAL orient3dadapt(pa, pb, pc, pd,
+ aheight, bheight, cheight, dheight, permanent)
+vertex pa;
+vertex pb;
+vertex pc;
+vertex pd;
+REAL aheight;
+REAL bheight;
+REAL cheight;
+REAL dheight;
+REAL permanent;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ INEXACT REAL adx, bdx, cdx, ady, bdy, cdy, adheight, bdheight, cdheight;
+ REAL det, errbound;
+
+ INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1;
+ REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0;
+ REAL bc[4], ca[4], ab[4];
+ INEXACT REAL bc3, ca3, ab3;
+ REAL adet[8], bdet[8], cdet[8];
+ int alen, blen, clen;
+ REAL abdet[16];
+ int ablen;
+ REAL *finnow, *finother, *finswap;
+ REAL fin1[192], fin2[192];
+ int finlength;
+
+ REAL adxtail, bdxtail, cdxtail;
+ REAL adytail, bdytail, cdytail;
+ REAL adheighttail, bdheighttail, cdheighttail;
+ INEXACT REAL at_blarge, at_clarge;
+ INEXACT REAL bt_clarge, bt_alarge;
+ INEXACT REAL ct_alarge, ct_blarge;
+ REAL at_b[4], at_c[4], bt_c[4], bt_a[4], ct_a[4], ct_b[4];
+ int at_blen, at_clen, bt_clen, bt_alen, ct_alen, ct_blen;
+ INEXACT REAL bdxt_cdy1, cdxt_bdy1, cdxt_ady1;
+ INEXACT REAL adxt_cdy1, adxt_bdy1, bdxt_ady1;
+ REAL bdxt_cdy0, cdxt_bdy0, cdxt_ady0;
+ REAL adxt_cdy0, adxt_bdy0, bdxt_ady0;
+ INEXACT REAL bdyt_cdx1, cdyt_bdx1, cdyt_adx1;
+ INEXACT REAL adyt_cdx1, adyt_bdx1, bdyt_adx1;
+ REAL bdyt_cdx0, cdyt_bdx0, cdyt_adx0;
+ REAL adyt_cdx0, adyt_bdx0, bdyt_adx0;
+ REAL bct[8], cat[8], abt[8];
+ int bctlen, catlen, abtlen;
+ INEXACT REAL bdxt_cdyt1, cdxt_bdyt1, cdxt_adyt1;
+ INEXACT REAL adxt_cdyt1, adxt_bdyt1, bdxt_adyt1;
+ REAL bdxt_cdyt0, cdxt_bdyt0, cdxt_adyt0;
+ REAL adxt_cdyt0, adxt_bdyt0, bdxt_adyt0;
+ REAL u[4], v[12], w[16];
+ INEXACT REAL u3;
+ int vlength, wlength;
+ REAL negate;
+
+ INEXACT REAL bvirt;
+ REAL avirt, bround, around;
+ INEXACT REAL c;
+ INEXACT REAL abig;
+ REAL ahi, alo, bhi, blo;
+ REAL err1, err2, err3;
+ INEXACT REAL _i, _j, _k;
+ REAL _0;
+
+ adx = (REAL) (pa[0] - pd[0]);
+ bdx = (REAL) (pb[0] - pd[0]);
+ cdx = (REAL) (pc[0] - pd[0]);
+ ady = (REAL) (pa[1] - pd[1]);
+ bdy = (REAL) (pb[1] - pd[1]);
+ cdy = (REAL) (pc[1] - pd[1]);
+ adheight = (REAL) (aheight - dheight);
+ bdheight = (REAL) (bheight - dheight);
+ cdheight = (REAL) (cheight - dheight);
+
+ Two_Product(bdx, cdy, bdxcdy1, bdxcdy0);
+ Two_Product(cdx, bdy, cdxbdy1, cdxbdy0);
+ Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]);
+ bc[3] = bc3;
+ alen = scale_expansion_zeroelim(4, bc, adheight, adet);
+
+ Two_Product(cdx, ady, cdxady1, cdxady0);
+ Two_Product(adx, cdy, adxcdy1, adxcdy0);
+ Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]);
+ ca[3] = ca3;
+ blen = scale_expansion_zeroelim(4, ca, bdheight, bdet);
+
+ Two_Product(adx, bdy, adxbdy1, adxbdy0);
+ Two_Product(bdx, ady, bdxady1, bdxady0);
+ Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]);
+ ab[3] = ab3;
+ clen = scale_expansion_zeroelim(4, ab, cdheight, cdet);
+
+ ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet);
+ finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1);
+
+ det = estimate(finlength, fin1);
+ errbound = o3derrboundB * permanent;
+ if ((det >= errbound) || (-det >= errbound)) {
+ return det;
+ }
+
+ Two_Diff_Tail(pa[0], pd[0], adx, adxtail);
+ Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail);
+ Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail);
+ Two_Diff_Tail(pa[1], pd[1], ady, adytail);
+ Two_Diff_Tail(pb[1], pd[1], bdy, bdytail);
+ Two_Diff_Tail(pc[1], pd[1], cdy, cdytail);
+ Two_Diff_Tail(aheight, dheight, adheight, adheighttail);
+ Two_Diff_Tail(bheight, dheight, bdheight, bdheighttail);
+ Two_Diff_Tail(cheight, dheight, cdheight, cdheighttail);
+
+ if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0) &&
+ (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0) &&
+ (adheighttail == 0.0) &&
+ (bdheighttail == 0.0) &&
+ (cdheighttail == 0.0)) {
+ return det;
+ }
+
+ errbound = o3derrboundC * permanent + resulterrbound * Absolute(det);
+ det += (adheight * ((bdx * cdytail + cdy * bdxtail) -
+ (bdy * cdxtail + cdx * bdytail)) +
+ adheighttail * (bdx * cdy - bdy * cdx)) +
+ (bdheight * ((cdx * adytail + ady * cdxtail) -
+ (cdy * adxtail + adx * cdytail)) +
+ bdheighttail * (cdx * ady - cdy * adx)) +
+ (cdheight * ((adx * bdytail + bdy * adxtail) -
+ (ady * bdxtail + bdx * adytail)) +
+ cdheighttail * (adx * bdy - ady * bdx));
+ if ((det >= errbound) || (-det >= errbound)) {
+ return det;
+ }
+
+ finnow = fin1;
+ finother = fin2;
+
+ if (adxtail == 0.0) {
+ if (adytail == 0.0) {
+ at_b[0] = 0.0;
+ at_blen = 1;
+ at_c[0] = 0.0;
+ at_clen = 1;
+ } else {
+ negate = -adytail;
+ Two_Product(negate, bdx, at_blarge, at_b[0]);
+ at_b[1] = at_blarge;
+ at_blen = 2;
+ Two_Product(adytail, cdx, at_clarge, at_c[0]);
+ at_c[1] = at_clarge;
+ at_clen = 2;
+ }
+ } else {
+ if (adytail == 0.0) {
+ Two_Product(adxtail, bdy, at_blarge, at_b[0]);
+ at_b[1] = at_blarge;
+ at_blen = 2;
+ negate = -adxtail;
+ Two_Product(negate, cdy, at_clarge, at_c[0]);
+ at_c[1] = at_clarge;
+ at_clen = 2;
+ } else {
+ Two_Product(adxtail, bdy, adxt_bdy1, adxt_bdy0);
+ Two_Product(adytail, bdx, adyt_bdx1, adyt_bdx0);
+ Two_Two_Diff(adxt_bdy1, adxt_bdy0, adyt_bdx1, adyt_bdx0,
+ at_blarge, at_b[2], at_b[1], at_b[0]);
+ at_b[3] = at_blarge;
+ at_blen = 4;
+ Two_Product(adytail, cdx, adyt_cdx1, adyt_cdx0);
+ Two_Product(adxtail, cdy, adxt_cdy1, adxt_cdy0);
+ Two_Two_Diff(adyt_cdx1, adyt_cdx0, adxt_cdy1, adxt_cdy0,
+ at_clarge, at_c[2], at_c[1], at_c[0]);
+ at_c[3] = at_clarge;
+ at_clen = 4;
+ }
+ }
+ if (bdxtail == 0.0) {
+ if (bdytail == 0.0) {
+ bt_c[0] = 0.0;
+ bt_clen = 1;
+ bt_a[0] = 0.0;
+ bt_alen = 1;
+ } else {
+ negate = -bdytail;
+ Two_Product(negate, cdx, bt_clarge, bt_c[0]);
+ bt_c[1] = bt_clarge;
+ bt_clen = 2;
+ Two_Product(bdytail, adx, bt_alarge, bt_a[0]);
+ bt_a[1] = bt_alarge;
+ bt_alen = 2;
+ }
+ } else {
+ if (bdytail == 0.0) {
+ Two_Product(bdxtail, cdy, bt_clarge, bt_c[0]);
+ bt_c[1] = bt_clarge;
+ bt_clen = 2;
+ negate = -bdxtail;
+ Two_Product(negate, ady, bt_alarge, bt_a[0]);
+ bt_a[1] = bt_alarge;
+ bt_alen = 2;
+ } else {
+ Two_Product(bdxtail, cdy, bdxt_cdy1, bdxt_cdy0);
+ Two_Product(bdytail, cdx, bdyt_cdx1, bdyt_cdx0);
+ Two_Two_Diff(bdxt_cdy1, bdxt_cdy0, bdyt_cdx1, bdyt_cdx0,
+ bt_clarge, bt_c[2], bt_c[1], bt_c[0]);
+ bt_c[3] = bt_clarge;
+ bt_clen = 4;
+ Two_Product(bdytail, adx, bdyt_adx1, bdyt_adx0);
+ Two_Product(bdxtail, ady, bdxt_ady1, bdxt_ady0);
+ Two_Two_Diff(bdyt_adx1, bdyt_adx0, bdxt_ady1, bdxt_ady0,
+ bt_alarge, bt_a[2], bt_a[1], bt_a[0]);
+ bt_a[3] = bt_alarge;
+ bt_alen = 4;
+ }
+ }
+ if (cdxtail == 0.0) {
+ if (cdytail == 0.0) {
+ ct_a[0] = 0.0;
+ ct_alen = 1;
+ ct_b[0] = 0.0;
+ ct_blen = 1;
+ } else {
+ negate = -cdytail;
+ Two_Product(negate, adx, ct_alarge, ct_a[0]);
+ ct_a[1] = ct_alarge;
+ ct_alen = 2;
+ Two_Product(cdytail, bdx, ct_blarge, ct_b[0]);
+ ct_b[1] = ct_blarge;
+ ct_blen = 2;
+ }
+ } else {
+ if (cdytail == 0.0) {
+ Two_Product(cdxtail, ady, ct_alarge, ct_a[0]);
+ ct_a[1] = ct_alarge;
+ ct_alen = 2;
+ negate = -cdxtail;
+ Two_Product(negate, bdy, ct_blarge, ct_b[0]);
+ ct_b[1] = ct_blarge;
+ ct_blen = 2;
+ } else {
+ Two_Product(cdxtail, ady, cdxt_ady1, cdxt_ady0);
+ Two_Product(cdytail, adx, cdyt_adx1, cdyt_adx0);
+ Two_Two_Diff(cdxt_ady1, cdxt_ady0, cdyt_adx1, cdyt_adx0,
+ ct_alarge, ct_a[2], ct_a[1], ct_a[0]);
+ ct_a[3] = ct_alarge;
+ ct_alen = 4;
+ Two_Product(cdytail, bdx, cdyt_bdx1, cdyt_bdx0);
+ Two_Product(cdxtail, bdy, cdxt_bdy1, cdxt_bdy0);
+ Two_Two_Diff(cdyt_bdx1, cdyt_bdx0, cdxt_bdy1, cdxt_bdy0,
+ ct_blarge, ct_b[2], ct_b[1], ct_b[0]);
+ ct_b[3] = ct_blarge;
+ ct_blen = 4;
+ }
+ }
+
+ bctlen = fast_expansion_sum_zeroelim(bt_clen, bt_c, ct_blen, ct_b, bct);
+ wlength = scale_expansion_zeroelim(bctlen, bct, adheight, w);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+
+ catlen = fast_expansion_sum_zeroelim(ct_alen, ct_a, at_clen, at_c, cat);
+ wlength = scale_expansion_zeroelim(catlen, cat, bdheight, w);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+
+ abtlen = fast_expansion_sum_zeroelim(at_blen, at_b, bt_alen, bt_a, abt);
+ wlength = scale_expansion_zeroelim(abtlen, abt, cdheight, w);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+
+ if (adheighttail != 0.0) {
+ vlength = scale_expansion_zeroelim(4, bc, adheighttail, v);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ if (bdheighttail != 0.0) {
+ vlength = scale_expansion_zeroelim(4, ca, bdheighttail, v);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ if (cdheighttail != 0.0) {
+ vlength = scale_expansion_zeroelim(4, ab, cdheighttail, v);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, vlength, v,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+
+ if (adxtail != 0.0) {
+ if (bdytail != 0.0) {
+ Two_Product(adxtail, bdytail, adxt_bdyt1, adxt_bdyt0);
+ Two_One_Product(adxt_bdyt1, adxt_bdyt0, cdheight, u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ if (cdheighttail != 0.0) {
+ Two_One_Product(adxt_bdyt1, adxt_bdyt0, cdheighttail,
+ u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ }
+ if (cdytail != 0.0) {
+ negate = -adxtail;
+ Two_Product(negate, cdytail, adxt_cdyt1, adxt_cdyt0);
+ Two_One_Product(adxt_cdyt1, adxt_cdyt0, bdheight, u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ if (bdheighttail != 0.0) {
+ Two_One_Product(adxt_cdyt1, adxt_cdyt0, bdheighttail,
+ u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ }
+ }
+ if (bdxtail != 0.0) {
+ if (cdytail != 0.0) {
+ Two_Product(bdxtail, cdytail, bdxt_cdyt1, bdxt_cdyt0);
+ Two_One_Product(bdxt_cdyt1, bdxt_cdyt0, adheight, u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ if (adheighttail != 0.0) {
+ Two_One_Product(bdxt_cdyt1, bdxt_cdyt0, adheighttail,
+ u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ }
+ if (adytail != 0.0) {
+ negate = -bdxtail;
+ Two_Product(negate, adytail, bdxt_adyt1, bdxt_adyt0);
+ Two_One_Product(bdxt_adyt1, bdxt_adyt0, cdheight, u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ if (cdheighttail != 0.0) {
+ Two_One_Product(bdxt_adyt1, bdxt_adyt0, cdheighttail,
+ u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ }
+ }
+ if (cdxtail != 0.0) {
+ if (adytail != 0.0) {
+ Two_Product(cdxtail, adytail, cdxt_adyt1, cdxt_adyt0);
+ Two_One_Product(cdxt_adyt1, cdxt_adyt0, bdheight, u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ if (bdheighttail != 0.0) {
+ Two_One_Product(cdxt_adyt1, cdxt_adyt0, bdheighttail,
+ u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ }
+ if (bdytail != 0.0) {
+ negate = -cdxtail;
+ Two_Product(negate, bdytail, cdxt_bdyt1, cdxt_bdyt0);
+ Two_One_Product(cdxt_bdyt1, cdxt_bdyt0, adheight, u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ if (adheighttail != 0.0) {
+ Two_One_Product(cdxt_bdyt1, cdxt_bdyt0, adheighttail,
+ u3, u[2], u[1], u[0]);
+ u[3] = u3;
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, 4, u,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ }
+ }
+
+ if (adheighttail != 0.0) {
+ wlength = scale_expansion_zeroelim(bctlen, bct, adheighttail, w);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ if (bdheighttail != 0.0) {
+ wlength = scale_expansion_zeroelim(catlen, cat, bdheighttail, w);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+ if (cdheighttail != 0.0) {
+ wlength = scale_expansion_zeroelim(abtlen, abt, cdheighttail, w);
+ finlength = fast_expansion_sum_zeroelim(finlength, finnow, wlength, w,
+ finother);
+ finswap = finnow; finnow = finother; finother = finswap;
+ }
+
+ return finnow[finlength - 1];
+}
+
+#ifdef ANSI_DECLARATORS
+REAL orient3d(struct mesh *m, struct behavior *b,
+ vertex pa, vertex pb, vertex pc, vertex pd,
+ REAL aheight, REAL bheight, REAL cheight, REAL dheight)
+#else /* not ANSI_DECLARATORS */
+REAL orient3d(m, b, pa, pb, pc, pd, aheight, bheight, cheight, dheight)
+struct mesh *m;
+struct behavior *b;
+vertex pa;
+vertex pb;
+vertex pc;
+vertex pd;
+REAL aheight;
+REAL bheight;
+REAL cheight;
+REAL dheight;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ REAL adx, bdx, cdx, ady, bdy, cdy, adheight, bdheight, cdheight;
+ REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady;
+ REAL det;
+ REAL permanent, errbound;
+
+ m->orient3dcount++;
+
+ adx = pa[0] - pd[0];
+ bdx = pb[0] - pd[0];
+ cdx = pc[0] - pd[0];
+ ady = pa[1] - pd[1];
+ bdy = pb[1] - pd[1];
+ cdy = pc[1] - pd[1];
+ adheight = aheight - dheight;
+ bdheight = bheight - dheight;
+ cdheight = cheight - dheight;
+
+ bdxcdy = bdx * cdy;
+ cdxbdy = cdx * bdy;
+
+ cdxady = cdx * ady;
+ adxcdy = adx * cdy;
+
+ adxbdy = adx * bdy;
+ bdxady = bdx * ady;
+
+ det = adheight * (bdxcdy - cdxbdy)
+ + bdheight * (cdxady - adxcdy)
+ + cdheight * (adxbdy - bdxady);
+
+ if (b->noexact) {
+ return det;
+ }
+
+ permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * Absolute(adheight)
+ + (Absolute(cdxady) + Absolute(adxcdy)) * Absolute(bdheight)
+ + (Absolute(adxbdy) + Absolute(bdxady)) * Absolute(cdheight);
+ errbound = o3derrboundA * permanent;
+ if ((det > errbound) || (-det > errbound)) {
+ return det;
+ }
+
+ return orient3dadapt(pa, pb, pc, pd, aheight, bheight, cheight, dheight,
+ permanent);
+}
+
+/*****************************************************************************/
+/* */
+/* nonregular() Return a positive value if the point pd is incompatible */
+/* with the circle or plane passing through pa, pb, and pc */
+/* (meaning that pd is inside the circle or below the */
+/* plane); a negative value if it is compatible; and zero if */
+/* the four points are cocircular/coplanar. The points pa, */
+/* pb, and pc must be in counterclockwise order, or the sign */
+/* of the result will be reversed. */
+/* */
+/* If the -w switch is used, the points are lifted onto the parabolic */
+/* lifting map, then they are dropped according to their weights, then the */
+/* 3D orientation test is applied. If the -W switch is used, the points' */
+/* heights are already provided, so the 3D orientation test is applied */
+/* directly. If neither switch is used, the incircle test is applied. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+REAL nonregular(struct mesh *m, struct behavior *b,
+ vertex pa, vertex pb, vertex pc, vertex pd)
+#else /* not ANSI_DECLARATORS */
+REAL nonregular(m, b, pa, pb, pc, pd)
+struct mesh *m;
+struct behavior *b;
+vertex pa;
+vertex pb;
+vertex pc;
+vertex pd;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ if (b->weighted == 0) {
+ return incircle(m, b, pa, pb, pc, pd);
+ } else if (b->weighted == 1) {
+ return orient3d(m, b, pa, pb, pc, pd,
+ pa[0] * pa[0] + pa[1] * pa[1] - pa[2],
+ pb[0] * pb[0] + pb[1] * pb[1] - pb[2],
+ pc[0] * pc[0] + pc[1] * pc[1] - pc[2],
+ pd[0] * pd[0] + pd[1] * pd[1] - pd[2]);
+ } else {
+ return orient3d(m, b, pa, pb, pc, pd, pa[2], pb[2], pc[2], pd[2]);
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* findcircumcenter() Find the circumcenter of a triangle. */
+/* */
+/* The result is returned both in terms of x-y coordinates and xi-eta */
+/* (barycentric) coordinates. The xi-eta coordinate system is defined in */
+/* terms of the triangle: the origin of the triangle is the origin of the */
+/* coordinate system; the destination of the triangle is one unit along the */
+/* xi axis; and the apex of the triangle is one unit along the eta axis. */
+/* This procedure also returns the square of the length of the triangle's */
+/* shortest edge. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void findcircumcenter(struct mesh *m, struct behavior *b,
+ vertex torg, vertex tdest, vertex tapex,
+ vertex circumcenter, REAL *xi, REAL *eta, int offcenter)
+#else /* not ANSI_DECLARATORS */
+void findcircumcenter(m, b, torg, tdest, tapex, circumcenter, xi, eta,
+ offcenter)
+struct mesh *m;
+struct behavior *b;
+vertex torg;
+vertex tdest;
+vertex tapex;
+vertex circumcenter;
+REAL *xi;
+REAL *eta;
+int offcenter;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ REAL xdo, ydo, xao, yao;
+ REAL dodist, aodist, dadist;
+ REAL denominator;
+ REAL dx, dy, dxoff, dyoff;
+
+ m->circumcentercount++;
+
+ /* Compute the circumcenter of the triangle. */
+ xdo = tdest[0] - torg[0];
+ ydo = tdest[1] - torg[1];
+ xao = tapex[0] - torg[0];
+ yao = tapex[1] - torg[1];
+ dodist = xdo * xdo + ydo * ydo;
+ aodist = xao * xao + yao * yao;
+ dadist = (tdest[0] - tapex[0]) * (tdest[0] - tapex[0]) +
+ (tdest[1] - tapex[1]) * (tdest[1] - tapex[1]);
+ if (b->noexact) {
+ denominator = 0.5 / (xdo * yao - xao * ydo);
+ } else {
+ /* Use the counterclockwise() routine to ensure a positive (and */
+ /* reasonably accurate) result, avoiding any possibility of */
+ /* division by zero. */
+ denominator = 0.5 / counterclockwise(m, b, tdest, tapex, torg);
+ /* Don't count the above as an orientation test. */
+ m->counterclockcount--;
+ }
+ dx = (yao * dodist - ydo * aodist) * denominator;
+ dy = (xdo * aodist - xao * dodist) * denominator;
+
+ /* Find the (squared) length of the triangle's shortest edge. This */
+ /* serves as a conservative estimate of the insertion radius of the */
+ /* circumcenter's parent. The estimate is used to ensure that */
+ /* the algorithm terminates even if very small angles appear in */
+ /* the input PSLG. */
+ if ((dodist < aodist) && (dodist < dadist)) {
+ if (offcenter && (b->offconstant > 0.0)) {
+ /* Find the position of the off-center, as described by Alper Ungor. */
+ dxoff = 0.5 * xdo - b->offconstant * ydo;
+ dyoff = 0.5 * ydo + b->offconstant * xdo;
+ /* If the off-center is closer to the origin than the */
+ /* circumcenter, use the off-center instead. */
+ if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) {
+ dx = dxoff;
+ dy = dyoff;
+ }
+ }
+ } else if (aodist < dadist) {
+ if (offcenter && (b->offconstant > 0.0)) {
+ dxoff = 0.5 * xao + b->offconstant * yao;
+ dyoff = 0.5 * yao - b->offconstant * xao;
+ /* If the off-center is closer to the origin than the */
+ /* circumcenter, use the off-center instead. */
+ if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) {
+ dx = dxoff;
+ dy = dyoff;
+ }
+ }
+ } else {
+ if (offcenter && (b->offconstant > 0.0)) {
+ dxoff = 0.5 * (tapex[0] - tdest[0]) -
+ b->offconstant * (tapex[1] - tdest[1]);
+ dyoff = 0.5 * (tapex[1] - tdest[1]) +
+ b->offconstant * (tapex[0] - tdest[0]);
+ /* If the off-center is closer to the destination than the */
+ /* circumcenter, use the off-center instead. */
+ if (dxoff * dxoff + dyoff * dyoff <
+ (dx - xdo) * (dx - xdo) + (dy - ydo) * (dy - ydo)) {
+ dx = xdo + dxoff;
+ dy = ydo + dyoff;
+ }
+ }
+ }
+
+ circumcenter[0] = torg[0] + dx;
+ circumcenter[1] = torg[1] + dy;
+
+ /* To interpolate vertex attributes for the new vertex inserted at */
+ /* the circumcenter, define a coordinate system with a xi-axis, */
+ /* directed from the triangle's origin to its destination, and */
+ /* an eta-axis, directed from its origin to its apex. */
+ /* Calculate the xi and eta coordinates of the circumcenter. */
+ *xi = (yao * dx - xao * dy) * (2.0 * denominator);
+ *eta = (xdo * dy - ydo * dx) * (2.0 * denominator);
+}
+
+/** **/
+/** **/
+/********* Geometric primitives end here *********/
+
+/*****************************************************************************/
+/* */
+/* triangleinit() Initialize some variables. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void triangleinit(struct mesh *m)
+#else /* not ANSI_DECLARATORS */
+void triangleinit(m)
+struct mesh *m;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ poolzero(&m->vertices);
+ poolzero(&m->triangles);
+ poolzero(&m->subsegs);
+ poolzero(&m->viri);
+ poolzero(&m->badsubsegs);
+ poolzero(&m->badtriangles);
+ poolzero(&m->flipstackers);
+ poolzero(&m->splaynodes);
+
+ m->recenttri.tri = (triangle *) NULL; /* No triangle has been visited yet. */
+ m->undeads = 0; /* No eliminated input vertices yet. */
+ m->samples = 1; /* Point location should take at least one sample. */
+ m->checksegments = 0; /* There are no segments in the triangulation yet. */
+ m->checkquality = 0; /* The quality triangulation stage has not begun. */
+ m->incirclecount = m->counterclockcount = m->orient3dcount = 0;
+ m->hyperbolacount = m->circletopcount = m->circumcentercount = 0;
+ randomseed = 1;
+
+ exactinit(); /* Initialize exact arithmetic constants. */
+}
+
+/*****************************************************************************/
+/* */
+/* randomnation() Generate a random number between 0 and `choices' - 1. */
+/* */
+/* This is a simple linear congruential random number generator. Hence, it */
+/* is a bad random number generator, but good enough for most randomized */
+/* geometric algorithms. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+unsigned long randomnation(unsigned int choices)
+#else /* not ANSI_DECLARATORS */
+unsigned long randomnation(choices)
+unsigned int choices;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ randomseed = (randomseed * 1366l + 150889l) % 714025l;
+ return randomseed / (714025l / choices + 1);
+}
+
+/********* Mesh quality testing routines begin here *********/
+/** **/
+/** **/
+
+/*****************************************************************************/
+/* */
+/* checkmesh() Test the mesh for topological consistency. */
+/* */
+/*****************************************************************************/
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+void checkmesh(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void checkmesh(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri triangleloop;
+ struct otri oppotri, oppooppotri;
+ vertex triorg, tridest, triapex;
+ vertex oppoorg, oppodest;
+ int horrors;
+ int saveexact;
+ triangle ptr; /* Temporary variable used by sym(). */
+
+ /* Temporarily turn on exact arithmetic if it's off. */
+ saveexact = b->noexact;
+ b->noexact = 0;
+ if (!b->quiet) {
+ printf(" Checking consistency of mesh...\n");
+ }
+ horrors = 0;
+ /* Run through the list of triangles, checking each one. */
+ traversalinit(&m->triangles);
+ triangleloop.tri = triangletraverse(m);
+ while (triangleloop.tri != (triangle *) NULL) {
+ /* Check all three edges of the triangle. */
+ for (triangleloop.orient = 0; triangleloop.orient < 3;
+ triangleloop.orient++) {
+ org(triangleloop, triorg);
+ dest(triangleloop, tridest);
+ if (triangleloop.orient == 0) { /* Only test for inversion once. */
+ /* Test if the triangle is flat or inverted. */
+ apex(triangleloop, triapex);
+ if (counterclockwise(m, b, triorg, tridest, triapex) <= 0.0) {
+ printf(" !! !! Inverted ");
+ printtriangle(m, b, &triangleloop);
+ horrors++;
+ }
+ }
+ /* Find the neighboring triangle on this edge. */
+ sym(triangleloop, oppotri);
+ if (oppotri.tri != m->dummytri) {
+ /* Check that the triangle's neighbor knows it's a neighbor. */
+ sym(oppotri, oppooppotri);
+ if ((triangleloop.tri != oppooppotri.tri)
+ || (triangleloop.orient != oppooppotri.orient)) {
+ printf(" !! !! Asymmetric triangle-triangle bond:\n");
+ if (triangleloop.tri == oppooppotri.tri) {
+ printf(" (Right triangle, wrong orientation)\n");
+ }
+ printf(" First ");
+ printtriangle(m, b, &triangleloop);
+ printf(" Second (nonreciprocating) ");
+ printtriangle(m, b, &oppotri);
+ horrors++;
+ }
+ /* Check that both triangles agree on the identities */
+ /* of their shared vertices. */
+ org(oppotri, oppoorg);
+ dest(oppotri, oppodest);
+ if ((triorg != oppodest) || (tridest != oppoorg)) {
+ printf(" !! !! Mismatched edge coordinates between two triangles:\n"
+ );
+ printf(" First mismatched ");
+ printtriangle(m, b, &triangleloop);
+ printf(" Second mismatched ");
+ printtriangle(m, b, &oppotri);
+ horrors++;
+ }
+ }
+ }
+ triangleloop.tri = triangletraverse(m);
+ }
+ if (horrors == 0) {
+ if (!b->quiet) {
+ printf(" In my studied opinion, the mesh appears to be consistent.\n");
+ }
+ } else if (horrors == 1) {
+ printf(" !! !! !! !! Precisely one festering wound discovered.\n");
+ } else {
+ printf(" !! !! !! !! %d abominations witnessed.\n", horrors);
+ }
+ /* Restore the status of exact arithmetic. */
+ b->noexact = saveexact;
+}
+
+#endif /* not REDUCED */
+
+/*****************************************************************************/
+/* */
+/* checkdelaunay() Ensure that the mesh is (constrained) Delaunay. */
+/* */
+/*****************************************************************************/
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+void checkdelaunay(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void checkdelaunay(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri triangleloop;
+ struct otri oppotri;
+ struct osub opposubseg;
+ vertex triorg, tridest, triapex;
+ vertex oppoapex;
+ int shouldbedelaunay;
+ int horrors;
+ int saveexact;
+ triangle ptr; /* Temporary variable used by sym(). */
+ subseg sptr; /* Temporary variable used by tspivot(). */
+
+ /* Temporarily turn on exact arithmetic if it's off. */
+ saveexact = b->noexact;
+ b->noexact = 0;
+ if (!b->quiet) {
+ printf(" Checking Delaunay property of mesh...\n");
+ }
+ horrors = 0;
+ /* Run through the list of triangles, checking each one. */
+ traversalinit(&m->triangles);
+ triangleloop.tri = triangletraverse(m);
+ while (triangleloop.tri != (triangle *) NULL) {
+ /* Check all three edges of the triangle. */
+ for (triangleloop.orient = 0; triangleloop.orient < 3;
+ triangleloop.orient++) {
+ org(triangleloop, triorg);
+ dest(triangleloop, tridest);
+ apex(triangleloop, triapex);
+ sym(triangleloop, oppotri);
+ apex(oppotri, oppoapex);
+ /* Only test that the edge is locally Delaunay if there is an */
+ /* adjoining triangle whose pointer is larger (to ensure that */
+ /* each pair isn't tested twice). */
+ shouldbedelaunay = (oppotri.tri != m->dummytri) &&
+ !deadtri(oppotri.tri) && (triangleloop.tri < oppotri.tri) &&
+ (triorg != m->infvertex1) && (triorg != m->infvertex2) &&
+ (triorg != m->infvertex3) &&
+ (tridest != m->infvertex1) && (tridest != m->infvertex2) &&
+ (tridest != m->infvertex3) &&
+ (triapex != m->infvertex1) && (triapex != m->infvertex2) &&
+ (triapex != m->infvertex3) &&
+ (oppoapex != m->infvertex1) && (oppoapex != m->infvertex2) &&
+ (oppoapex != m->infvertex3);
+ if (m->checksegments && shouldbedelaunay) {
+ /* If a subsegment separates the triangles, then the edge is */
+ /* constrained, so no local Delaunay test should be done. */
+ tspivot(triangleloop, opposubseg);
+ if (opposubseg.ss != m->dummysub){
+ shouldbedelaunay = 0;
+ }
+ }
+ if (shouldbedelaunay) {
+ if (nonregular(m, b, triorg, tridest, triapex, oppoapex) > 0.0) {
+ if (!b->weighted) {
+ printf(" !! !! Non-Delaunay pair of triangles:\n");
+ printf(" First non-Delaunay ");
+ printtriangle(m, b, &triangleloop);
+ printf(" Second non-Delaunay ");
+ } else {
+ printf(" !! !! Non-regular pair of triangles:\n");
+ printf(" First non-regular ");
+ printtriangle(m, b, &triangleloop);
+ printf(" Second non-regular ");
+ }
+ printtriangle(m, b, &oppotri);
+ horrors++;
+ }
+ }
+ }
+ triangleloop.tri = triangletraverse(m);
+ }
+ if (horrors == 0) {
+ if (!b->quiet) {
+ printf(
+ " By virtue of my perceptive intelligence, I declare the mesh Delaunay.\n");
+ }
+ } else if (horrors == 1) {
+ printf(
+ " !! !! !! !! Precisely one terrifying transgression identified.\n");
+ } else {
+ printf(" !! !! !! !! %d obscenities viewed with horror.\n", horrors);
+ }
+ /* Restore the status of exact arithmetic. */
+ b->noexact = saveexact;
+}
+
+#endif /* not REDUCED */
+
+/*****************************************************************************/
+/* */
+/* enqueuebadtriang() Add a bad triangle data structure to the end of a */
+/* queue. */
+/* */
+/* The queue is actually a set of 4096 queues. I use multiple queues to */
+/* give priority to smaller angles. I originally implemented a heap, but */
+/* the queues are faster by a larger margin than I'd suspected. */
+/* */
+/*****************************************************************************/
+
+#ifndef CDT_ONLY
+
+#ifdef ANSI_DECLARATORS
+void enqueuebadtriang(struct mesh *m, struct behavior *b,
+ struct badtriang *badtri)
+#else /* not ANSI_DECLARATORS */
+void enqueuebadtriang(m, b, badtri)
+struct mesh *m;
+struct behavior *b;
+struct badtriang *badtri;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ REAL length, multiplier;
+ int exponent, expincrement;
+ int queuenumber;
+ int posexponent;
+ int i;
+
+ if (b->verbose > 2) {
+ printf(" Queueing bad triangle:\n");
+ printf(" (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
+ badtri->triangorg[0], badtri->triangorg[1],
+ badtri->triangdest[0], badtri->triangdest[1],
+ badtri->triangapex[0], badtri->triangapex[1]);
+ }
+
+ /* Determine the appropriate queue to put the bad triangle into. */
+ /* Recall that the key is the square of its shortest edge length. */
+ if (badtri->key >= 1.0) {
+ length = badtri->key;
+ posexponent = 1;
+ } else {
+ /* `badtri->key' is 2.0 to a negative exponent, so we'll record that */
+ /* fact and use the reciprocal of `badtri->key', which is > 1.0. */
+ length = 1.0 / badtri->key;
+ posexponent = 0;
+ }
+ /* `length' is approximately 2.0 to what exponent? The following code */
+ /* determines the answer in time logarithmic in the exponent. */
+ exponent = 0;
+ while (length > 2.0) {
+ /* Find an approximation by repeated squaring of two. */
+ expincrement = 1;
+ multiplier = 0.5;
+ while (length * multiplier * multiplier > 1.0) {
+ expincrement *= 2;
+ multiplier *= multiplier;
+ }
+ /* Reduce the value of `length', then iterate if necessary. */
+ exponent += expincrement;
+ length *= multiplier;
+ }
+ /* `length' is approximately squareroot(2.0) to what exponent? */
+ exponent = (int)(2.0 * exponent + (length > SQUAREROOTTWO));
+ /* `exponent' is now in the range 0...2047 for IEEE double precision. */
+ /* Choose a queue in the range 0...4095. The shortest edges have the */
+ /* highest priority (queue 4095). */
+ if (posexponent) {
+ queuenumber = 2047 - exponent;
+ } else {
+ queuenumber = 2048 + exponent;
+ }
+
+ /* Are we inserting into an empty queue? */
+ if (m->queuefront[queuenumber] == (struct badtriang *) NULL) {
+ /* Yes, we are inserting into an empty queue. */
+ /* Will this become the highest-priority queue? */
+ if (queuenumber > m->firstnonemptyq) {
+ /* Yes, this is the highest-priority queue. */
+ m->nextnonemptyq[queuenumber] = m->firstnonemptyq;
+ m->firstnonemptyq = queuenumber;
+ } else {
+ /* No, this is not the highest-priority queue. */
+ /* Find the queue with next higher priority. */
+ i = queuenumber + 1;
+ while (m->queuefront[i] == (struct badtriang *) NULL) {
+ i++;
+ }
+ /* Mark the newly nonempty queue as following a higher-priority queue. */
+ m->nextnonemptyq[queuenumber] = m->nextnonemptyq[i];
+ m->nextnonemptyq[i] = queuenumber;
+ }
+ /* Put the bad triangle at the beginning of the (empty) queue. */
+ m->queuefront[queuenumber] = badtri;
+ } else {
+ /* Add the bad triangle to the end of an already nonempty queue. */
+ m->queuetail[queuenumber]->nexttriang = badtri;
+ }
+ /* Maintain a pointer to the last triangle of the queue. */
+ m->queuetail[queuenumber] = badtri;
+ /* Newly enqueued bad triangle has no successor in the queue. */
+ badtri->nexttriang = (struct badtriang *) NULL;
+}
+
+#endif /* not CDT_ONLY */
+
+/*****************************************************************************/
+/* */
+/* enqueuebadtri() Add a bad triangle to the end of a queue. */
+/* */
+/* Allocates a badtriang data structure for the triangle, then passes it to */
+/* enqueuebadtriang(). */
+/* */
+/*****************************************************************************/
+
+#ifndef CDT_ONLY
+
+#ifdef ANSI_DECLARATORS
+void enqueuebadtri(struct mesh *m, struct behavior *b, struct otri *enqtri,
+ REAL minedge, vertex enqapex, vertex enqorg, vertex enqdest)
+#else /* not ANSI_DECLARATORS */
+void enqueuebadtri(m, b, enqtri, minedge, enqapex, enqorg, enqdest)
+struct mesh *m;
+struct behavior *b;
+struct otri *enqtri;
+REAL minedge;
+vertex enqapex;
+vertex enqorg;
+vertex enqdest;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct badtriang *newbad;
+
+ /* Allocate space for the bad triangle. */
+ newbad = (struct badtriang *) poolalloc(&m->badtriangles);
+ newbad->poortri = encode(*enqtri);
+ newbad->key = minedge;
+ newbad->triangapex = enqapex;
+ newbad->triangorg = enqorg;
+ newbad->triangdest = enqdest;
+ enqueuebadtriang(m, b, newbad);
+}
+
+#endif /* not CDT_ONLY */
+
+/*****************************************************************************/
+/* */
+/* dequeuebadtriang() Remove a triangle from the front of the queue. */
+/* */
+/*****************************************************************************/
+
+#ifndef CDT_ONLY
+
+#ifdef ANSI_DECLARATORS
+struct badtriang *dequeuebadtriang(struct mesh *m)
+#else /* not ANSI_DECLARATORS */
+struct badtriang *dequeuebadtriang(m)
+struct mesh *m;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct badtriang *result;
+
+ /* If no queues are nonempty, return NULL. */
+ if (m->firstnonemptyq < 0) {
+ return (struct badtriang *) NULL;
+ }
+ /* Find the first triangle of the highest-priority queue. */
+ result = m->queuefront[m->firstnonemptyq];
+ /* Remove the triangle from the queue. */
+ m->queuefront[m->firstnonemptyq] = result->nexttriang;
+ /* If this queue is now empty, note the new highest-priority */
+ /* nonempty queue. */
+ if (result == m->queuetail[m->firstnonemptyq]) {
+ m->firstnonemptyq = m->nextnonemptyq[m->firstnonemptyq];
+ }
+ return result;
+}
+
+#endif /* not CDT_ONLY */
+
+/*****************************************************************************/
+/* */
+/* checkseg4encroach() Check a subsegment to see if it is encroached; add */
+/* it to the list if it is. */
+/* */
+/* A subsegment is encroached if there is a vertex in its diametral lens. */
+/* For Ruppert's algorithm (-D switch), the "diametral lens" is the */
+/* diametral circle. For Chew's algorithm (default), the diametral lens is */
+/* just big enough to enclose two isosceles triangles whose bases are the */
+/* subsegment. Each of the two isosceles triangles has two angles equal */
+/* to `b->minangle'. */
+/* */
+/* Chew's algorithm does not require diametral lenses at all--but they save */
+/* time. Any vertex inside a subsegment's diametral lens implies that the */
+/* triangle adjoining the subsegment will be too skinny, so it's only a */
+/* matter of time before the encroaching vertex is deleted by Chew's */
+/* algorithm. It's faster to simply not insert the doomed vertex in the */
+/* first place, which is why I use diametral lenses with Chew's algorithm. */
+/* */
+/* Returns a nonzero value if the subsegment is encroached. */
+/* */
+/*****************************************************************************/
+
+#ifndef CDT_ONLY
+
+#ifdef ANSI_DECLARATORS
+int checkseg4encroach(struct mesh *m, struct behavior *b,
+ struct osub *testsubseg)
+#else /* not ANSI_DECLARATORS */
+int checkseg4encroach(m, b, testsubseg)
+struct mesh *m;
+struct behavior *b;
+struct osub *testsubseg;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri neighbortri;
+ struct osub testsym;
+ struct badsubseg *encroachedseg;
+ REAL dotproduct;
+ int encroached;
+ int sides;
+ vertex eorg, edest, eapex;
+ triangle ptr; /* Temporary variable used by stpivot(). */
+
+ encroached = 0;
+ sides = 0;
+
+ sorg(*testsubseg, eorg);
+ sdest(*testsubseg, edest);
+ /* Check one neighbor of the subsegment. */
+ stpivot(*testsubseg, neighbortri);
+ /* Does the neighbor exist, or is this a boundary edge? */
+ if (neighbortri.tri != m->dummytri) {
+ sides++;
+ /* Find a vertex opposite this subsegment. */
+ apex(neighbortri, eapex);
+ /* Check whether the apex is in the diametral lens of the subsegment */
+ /* (the diametral circle if `conformdel' is set). A dot product */
+ /* of two sides of the triangle is used to check whether the angle */
+ /* at the apex is greater than (180 - 2 `minangle') degrees (for */
+ /* lenses; 90 degrees for diametral circles). */
+ dotproduct = (eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
+ (eorg[1] - eapex[1]) * (edest[1] - eapex[1]);
+ if (dotproduct < 0.0) {
+ if (b->conformdel ||
+ (dotproduct * dotproduct >=
+ (2.0 * b->goodangle - 1.0) * (2.0 * b->goodangle - 1.0) *
+ ((eorg[0] - eapex[0]) * (eorg[0] - eapex[0]) +
+ (eorg[1] - eapex[1]) * (eorg[1] - eapex[1])) *
+ ((edest[0] - eapex[0]) * (edest[0] - eapex[0]) +
+ (edest[1] - eapex[1]) * (edest[1] - eapex[1])))) {
+ encroached = 1;
+ }
+ }
+ }
+ /* Check the other neighbor of the subsegment. */
+ ssym(*testsubseg, testsym);
+ stpivot(testsym, neighbortri);
+ /* Does the neighbor exist, or is this a boundary edge? */
+ if (neighbortri.tri != m->dummytri) {
+ sides++;
+ /* Find the other vertex opposite this subsegment. */
+ apex(neighbortri, eapex);
+ /* Check whether the apex is in the diametral lens of the subsegment */
+ /* (or the diametral circle, if `conformdel' is set). */
+ dotproduct = (eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
+ (eorg[1] - eapex[1]) * (edest[1] - eapex[1]);
+ if (dotproduct < 0.0) {
+ if (b->conformdel ||
+ (dotproduct * dotproduct >=
+ (2.0 * b->goodangle - 1.0) * (2.0 * b->goodangle - 1.0) *
+ ((eorg[0] - eapex[0]) * (eorg[0] - eapex[0]) +
+ (eorg[1] - eapex[1]) * (eorg[1] - eapex[1])) *
+ ((edest[0] - eapex[0]) * (edest[0] - eapex[0]) +
+ (edest[1] - eapex[1]) * (edest[1] - eapex[1])))) {
+ encroached += 2;
+ }
+ }
+ }
+
+ if (encroached && (!b->nobisect || ((b->nobisect == 1) && (sides == 2)))) {
+ if (b->verbose > 2) {
+ printf(
+ " Queueing encroached subsegment (%.12g, %.12g) (%.12g, %.12g).\n",
+ eorg[0], eorg[1], edest[0], edest[1]);
+ }
+ /* Add the subsegment to the list of encroached subsegments. */
+ /* Be sure to get the orientation right. */
+ encroachedseg = (struct badsubseg *) poolalloc(&m->badsubsegs);
+ if (encroached == 1) {
+ encroachedseg->encsubseg = sencode(*testsubseg);
+ encroachedseg->subsegorg = eorg;
+ encroachedseg->subsegdest = edest;
+ } else {
+ encroachedseg->encsubseg = sencode(testsym);
+ encroachedseg->subsegorg = edest;
+ encroachedseg->subsegdest = eorg;
+ }
+ }
+
+ return encroached;
+}
+
+#endif /* not CDT_ONLY */
+
+/*****************************************************************************/
+/* */
+/* testtriangle() Test a triangle for quality and size. */
+/* */
+/* Tests a triangle to see if it satisfies the minimum angle condition and */
+/* the maximum area condition. Triangles that aren't up to spec are added */
+/* to the bad triangle queue. */
+/* */
+/*****************************************************************************/
+
+#ifndef CDT_ONLY
+
+#ifdef ANSI_DECLARATORS
+void testtriangle(struct mesh *m, struct behavior *b, struct otri *testtri)
+#else /* not ANSI_DECLARATORS */
+void testtriangle(m, b, testtri)
+struct mesh *m;
+struct behavior *b;
+struct otri *testtri;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri tri1, tri2;
+ struct osub testsub;
+ vertex torg, tdest, tapex;
+ vertex base1, base2;
+ vertex org1, dest1, org2, dest2;
+ vertex joinvertex;
+ REAL dxod, dyod, dxda, dyda, dxao, dyao;
+ REAL dxod2, dyod2, dxda2, dyda2, dxao2, dyao2;
+ REAL apexlen, orglen, destlen, minedge;
+ REAL angle;
+ REAL area;
+ REAL dist1, dist2;
+ subseg sptr; /* Temporary variable used by tspivot(). */
+ triangle ptr; /* Temporary variable used by oprev() and dnext(). */
+
+ org(*testtri, torg);
+ dest(*testtri, tdest);
+ apex(*testtri, tapex);
+ dxod = torg[0] - tdest[0];
+ dyod = torg[1] - tdest[1];
+ dxda = tdest[0] - tapex[0];
+ dyda = tdest[1] - tapex[1];
+ dxao = tapex[0] - torg[0];
+ dyao = tapex[1] - torg[1];
+ dxod2 = dxod * dxod;
+ dyod2 = dyod * dyod;
+ dxda2 = dxda * dxda;
+ dyda2 = dyda * dyda;
+ dxao2 = dxao * dxao;
+ dyao2 = dyao * dyao;
+ /* Find the lengths of the triangle's three edges. */
+ apexlen = dxod2 + dyod2;
+ orglen = dxda2 + dyda2;
+ destlen = dxao2 + dyao2;
+
+ if ((apexlen < orglen) && (apexlen < destlen)) {
+ /* The edge opposite the apex is shortest. */
+ minedge = apexlen;
+ /* Find the square of the cosine of the angle at the apex. */
+ angle = dxda * dxao + dyda * dyao;
+ angle = angle * angle / (orglen * destlen);
+ base1 = torg;
+ base2 = tdest;
+ otricopy(*testtri, tri1);
+ } else if (orglen < destlen) {
+ /* The edge opposite the origin is shortest. */
+ minedge = orglen;
+ /* Find the square of the cosine of the angle at the origin. */
+ angle = dxod * dxao + dyod * dyao;
+ angle = angle * angle / (apexlen * destlen);
+ base1 = tdest;
+ base2 = tapex;
+ lnext(*testtri, tri1);
+ } else {
+ /* The edge opposite the destination is shortest. */
+ minedge = destlen;
+ /* Find the square of the cosine of the angle at the destination. */
+ angle = dxod * dxda + dyod * dyda;
+ angle = angle * angle / (apexlen * orglen);
+ base1 = tapex;
+ base2 = torg;
+ lprev(*testtri, tri1);
+ }
+
+ if (b->vararea || b->fixedarea || b->usertest) {
+ /* Check whether the area is larger than permitted. */
+ area = 0.5 * (dxod * dyda - dyod * dxda);
+ if (b->fixedarea && (area > b->maxarea)) {
+ /* Add this triangle to the list of bad triangles. */
+ enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
+ return;
+ }
+
+ /* Nonpositive area constraints are treated as unconstrained. */
+ if ((b->vararea) && (area > areabound(*testtri)) &&
+ (areabound(*testtri) > 0.0)) {
+ /* Add this triangle to the list of bad triangles. */
+ enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
+ return;
+ }
+
+ if (b->usertest) {
+ /* Check whether the user thinks this triangle is too large. */
+ if (triunsuitable(torg, tdest, tapex, area)) {
+ enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
+ return;
+ }
+ }
+ }
+
+ /* Check whether the angle is smaller than permitted. */
+ if (angle > b->goodangle) {
+ /* Use the rules of Miller, Pav, and Walkington to decide that certain */
+ /* triangles should not be split, even if they have bad angles. */
+ /* A skinny triangle is not split if its shortest edge subtends a */
+ /* small input angle, and both endpoints of the edge lie on a */
+ /* concentric circular shell. For convenience, I make a small */
+ /* adjustment to that rule: I check if the endpoints of the edge */
+ /* both lie in segment interiors, equidistant from the apex where */
+ /* the two segments meet. */
+ /* First, check if both points lie in segment interiors. */
+ if ((vertextype(base1) == SEGMENTVERTEX) &&
+ (vertextype(base2) == SEGMENTVERTEX)) {
+ /* Check if both points lie in a common segment. If they do, the */
+ /* skinny triangle is enqueued to be split as usual. */
+ tspivot(tri1, testsub);
+ if (testsub.ss == m->dummysub) {
+ /* No common segment. Find a subsegment that contains `torg'. */
+ otricopy(tri1, tri2);
+ do {
+ oprevself(tri1);
+ tspivot(tri1, testsub);
+ } while (testsub.ss == m->dummysub);
+ /* Find the endpoints of the containing segment. */
+ segorg(testsub, org1);
+ segdest(testsub, dest1);
+ /* Find a subsegment that contains `tdest'. */
+ do {
+ dnextself(tri2);
+ tspivot(tri2, testsub);
+ } while (testsub.ss == m->dummysub);
+ /* Find the endpoints of the containing segment. */
+ segorg(testsub, org2);
+ segdest(testsub, dest2);
+ /* Check if the two containing segments have an endpoint in common. */
+ joinvertex = (vertex) NULL;
+ if ((dest1[0] == org2[0]) && (dest1[1] == org2[1])) {
+ joinvertex = dest1;
+ } else if ((org1[0] == dest2[0]) && (org1[1] == dest2[1])) {
+ joinvertex = org1;
+ }
+ if (joinvertex != (vertex) NULL) {
+ /* Compute the distance from the common endpoint (of the two */
+ /* segments) to each of the endpoints of the shortest edge. */
+ dist1 = ((base1[0] - joinvertex[0]) * (base1[0] - joinvertex[0]) +
+ (base1[1] - joinvertex[1]) * (base1[1] - joinvertex[1]));
+ dist2 = ((base2[0] - joinvertex[0]) * (base2[0] - joinvertex[0]) +
+ (base2[1] - joinvertex[1]) * (base2[1] - joinvertex[1]));
+ /* If the two distances are equal, don't split the triangle. */
+ if ((dist1 < 1.001 * dist2) && (dist1 > 0.999 * dist2)) {
+ /* Return now to avoid enqueueing the bad triangle. */
+ return;
+ }
+ }
+ }
+ }
+
+ /* Add this triangle to the list of bad triangles. */
+ enqueuebadtri(m, b, testtri, minedge, tapex, torg, tdest);
+ }
+}
+
+#endif /* not CDT_ONLY */
+
+/** **/
+/** **/
+/********* Mesh quality testing routines end here *********/
+
+/********* Point location routines begin here *********/
+/** **/
+/** **/
+
+/*****************************************************************************/
+/* */
+/* makevertexmap() Construct a mapping from vertices to triangles to */
+/* improve the speed of point location for segment */
+/* insertion. */
+/* */
+/* Traverses all the triangles, and provides each corner of each triangle */
+/* with a pointer to that triangle. Of course, pointers will be */
+/* overwritten by other pointers because (almost) each vertex is a corner */
+/* of several triangles, but in the end every vertex will point to some */
+/* triangle that contains it. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void makevertexmap(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void makevertexmap(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri triangleloop;
+ vertex triorg;
+
+ if (b->verbose) {
+ printf(" Constructing mapping from vertices to triangles.\n");
+ }
+ traversalinit(&m->triangles);
+ triangleloop.tri = triangletraverse(m);
+ while (triangleloop.tri != (triangle *) NULL) {
+ /* Check all three vertices of the triangle. */
+ for (triangleloop.orient = 0; triangleloop.orient < 3;
+ triangleloop.orient++) {
+ org(triangleloop, triorg);
+ setvertex2tri(triorg, encode(triangleloop));
+ }
+ triangleloop.tri = triangletraverse(m);
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* preciselocate() Find a triangle or edge containing a given point. */
+/* */
+/* Begins its search from `searchtri'. It is important that `searchtri' */
+/* be a handle with the property that `searchpoint' is strictly to the left */
+/* of the edge denoted by `searchtri', or is collinear with that edge and */
+/* does not intersect that edge. (In particular, `searchpoint' should not */
+/* be the origin or destination of that edge.) */
+/* */
+/* These conditions are imposed because preciselocate() is normally used in */
+/* one of two situations: */
+/* */
+/* (1) To try to find the location to insert a new point. Normally, we */
+/* know an edge that the point is strictly to the left of. In the */
+/* incremental Delaunay algorithm, that edge is a bounding box edge. */
+/* In Ruppert's Delaunay refinement algorithm for quality meshing, */
+/* that edge is the shortest edge of the triangle whose circumcenter */
+/* is being inserted. */
+/* */
+/* (2) To try to find an existing point. In this case, any edge on the */
+/* convex hull is a good starting edge. You must screen out the */
+/* possibility that the vertex sought is an endpoint of the starting */
+/* edge before you call preciselocate(). */
+/* */
+/* On completion, `searchtri' is a triangle that contains `searchpoint'. */
+/* */
+/* This implementation differs from that given by Guibas and Stolfi. It */
+/* walks from triangle to triangle, crossing an edge only if `searchpoint' */
+/* is on the other side of the line containing that edge. After entering */
+/* a triangle, there are two edges by which one can leave that triangle. */
+/* If both edges are valid (`searchpoint' is on the other side of both */
+/* edges), one of the two is chosen by drawing a line perpendicular to */
+/* the entry edge (whose endpoints are `forg' and `fdest') passing through */
+/* `fapex'. Depending on which side of this perpendicular `searchpoint' */
+/* falls on, an exit edge is chosen. */
+/* */
+/* This implementation is empirically faster than the Guibas and Stolfi */
+/* point location routine (which I originally used), which tends to spiral */
+/* in toward its target. */
+/* */
+/* Returns ONVERTEX if the point lies on an existing vertex. `searchtri' */
+/* is a handle whose origin is the existing vertex. */
+/* */
+/* Returns ONEDGE if the point lies on a mesh edge. `searchtri' is a */
+/* handle whose primary edge is the edge on which the point lies. */
+/* */
+/* Returns INTRIANGLE if the point lies strictly within a triangle. */
+/* `searchtri' is a handle on the triangle that contains the point. */
+/* */
+/* Returns OUTSIDE if the point lies outside the mesh. `searchtri' is a */
+/* handle whose primary edge the point is to the right of. This might */
+/* occur when the circumcenter of a triangle falls just slightly outside */
+/* the mesh due to floating-point roundoff error. It also occurs when */
+/* seeking a hole or region point that a foolish user has placed outside */
+/* the mesh. */
+/* */
+/* If `stopatsubsegment' is nonzero, the search will stop if it tries to */
+/* walk through a subsegment, and will return OUTSIDE. */
+/* */
+/* WARNING: This routine is designed for convex triangulations, and will */
+/* not generally work after the holes and concavities have been carved. */
+/* However, it can still be used to find the circumcenter of a triangle, as */
+/* long as the search is begun from the triangle in question. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+enum locateresult preciselocate(struct mesh *m, struct behavior *b,
+ vertex searchpoint, struct otri *searchtri,
+ int stopatsubsegment)
+#else /* not ANSI_DECLARATORS */
+enum locateresult preciselocate(m, b, searchpoint, searchtri, stopatsubsegment)
+struct mesh *m;
+struct behavior *b;
+vertex searchpoint;
+struct otri *searchtri;
+int stopatsubsegment;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri backtracktri;
+ struct osub checkedge;
+ vertex forg, fdest, fapex;
+ REAL orgorient, destorient;
+ int moveleft;
+ triangle ptr; /* Temporary variable used by sym(). */
+ subseg sptr; /* Temporary variable used by tspivot(). */
+
+ if (b->verbose > 2) {
+ printf(" Searching for point (%.12g, %.12g).\n",
+ searchpoint[0], searchpoint[1]);
+ }
+ /* Where are we? */
+ org(*searchtri, forg);
+ dest(*searchtri, fdest);
+ apex(*searchtri, fapex);
+ while (1) {
+ if (b->verbose > 2) {
+ printf(" At (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
+ forg[0], forg[1], fdest[0], fdest[1], fapex[0], fapex[1]);
+ }
+ /* Check whether the apex is the point we seek. */
+ if ((fapex[0] == searchpoint[0]) && (fapex[1] == searchpoint[1])) {
+ lprevself(*searchtri);
+ return ONVERTEX;
+ }
+ /* Does the point lie on the other side of the line defined by the */
+ /* triangle edge opposite the triangle's destination? */
+ destorient = counterclockwise(m, b, forg, fapex, searchpoint);
+ /* Does the point lie on the other side of the line defined by the */
+ /* triangle edge opposite the triangle's origin? */
+ orgorient = counterclockwise(m, b, fapex, fdest, searchpoint);
+ if (destorient > 0.0) {
+ if (orgorient > 0.0) {
+ /* Move left if the inner product of (fapex - searchpoint) and */
+ /* (fdest - forg) is positive. This is equivalent to drawing */
+ /* a line perpendicular to the line (forg, fdest) and passing */
+ /* through `fapex', and determining which side of this line */
+ /* `searchpoint' falls on. */
+ moveleft = (fapex[0] - searchpoint[0]) * (fdest[0] - forg[0]) +
+ (fapex[1] - searchpoint[1]) * (fdest[1] - forg[1]) > 0.0;
+ } else {
+ moveleft = 1;
+ }
+ } else {
+ if (orgorient > 0.0) {
+ moveleft = 0;
+ } else {
+ /* The point we seek must be on the boundary of or inside this */
+ /* triangle. */
+ if (destorient == 0.0) {
+ lprevself(*searchtri);
+ return ONEDGE;
+ }
+ if (orgorient == 0.0) {
+ lnextself(*searchtri);
+ return ONEDGE;
+ }
+ return INTRIANGLE;
+ }
+ }
+
+ /* Move to another triangle. Leave a trace `backtracktri' in case */
+ /* floating-point roundoff or some such bogey causes us to walk */
+ /* off a boundary of the triangulation. */
+ if (moveleft) {
+ lprev(*searchtri, backtracktri);
+ fdest = fapex;
+ } else {
+ lnext(*searchtri, backtracktri);
+ forg = fapex;
+ }
+ sym(backtracktri, *searchtri);
+
+ if (m->checksegments && stopatsubsegment) {
+ /* Check for walking through a subsegment. */
+ tspivot(backtracktri, checkedge);
+ if (checkedge.ss != m->dummysub) {
+ /* Go back to the last triangle. */
+ otricopy(backtracktri, *searchtri);
+ return OUTSIDE;
+ }
+ }
+ /* Check for walking right out of the triangulation. */
+ if (searchtri->tri == m->dummytri) {
+ /* Go back to the last triangle. */
+ otricopy(backtracktri, *searchtri);
+ return OUTSIDE;
+ }
+
+ apex(*searchtri, fapex);
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* locate() Find a triangle or edge containing a given point. */
+/* */
+/* Searching begins from one of: the input `searchtri', a recently */
+/* encountered triangle `recenttri', or from a triangle chosen from a */
+/* random sample. The choice is made by determining which triangle's */
+/* origin is closest to the point we are searching for. Normally, */
+/* `searchtri' should be a handle on the convex hull of the triangulation. */
+/* */
+/* Details on the random sampling method can be found in the Mucke, Saias, */
+/* and Zhu paper cited in the header of this code. */
+/* */
+/* On completion, `searchtri' is a triangle that contains `searchpoint'. */
+/* */
+/* Returns ONVERTEX if the point lies on an existing vertex. `searchtri' */
+/* is a handle whose origin is the existing vertex. */
+/* */
+/* Returns ONEDGE if the point lies on a mesh edge. `searchtri' is a */
+/* handle whose primary edge is the edge on which the point lies. */
+/* */
+/* Returns INTRIANGLE if the point lies strictly within a triangle. */
+/* `searchtri' is a handle on the triangle that contains the point. */
+/* */
+/* Returns OUTSIDE if the point lies outside the mesh. `searchtri' is a */
+/* handle whose primary edge the point is to the right of. This might */
+/* occur when the circumcenter of a triangle falls just slightly outside */
+/* the mesh due to floating-point roundoff error. It also occurs when */
+/* seeking a hole or region point that a foolish user has placed outside */
+/* the mesh. */
+/* */
+/* WARNING: This routine is designed for convex triangulations, and will */
+/* not generally work after the holes and concavities have been carved. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+enum locateresult locate(struct mesh *m, struct behavior *b,
+ vertex searchpoint, struct otri *searchtri)
+#else /* not ANSI_DECLARATORS */
+enum locateresult locate(m, b, searchpoint, searchtri)
+struct mesh *m;
+struct behavior *b;
+vertex searchpoint;
+struct otri *searchtri;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ VOID **sampleblock;
+ char *firsttri;
+ struct otri sampletri;
+ vertex torg, tdest;
+ unsigned long alignptr;
+ REAL searchdist, dist;
+ REAL ahead;
+ long samplesperblock, totalsamplesleft, samplesleft;
+ long population, totalpopulation;
+ triangle ptr; /* Temporary variable used by sym(). */
+
+ if (b->verbose > 2) {
+ printf(" Randomly sampling for a triangle near point (%.12g, %.12g).\n",
+ searchpoint[0], searchpoint[1]);
+ }
+ /* Record the distance from the suggested starting triangle to the */
+ /* point we seek. */
+ org(*searchtri, torg);
+ searchdist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
+ (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
+ if (b->verbose > 2) {
+ printf(" Boundary triangle has origin (%.12g, %.12g).\n",
+ torg[0], torg[1]);
+ }
+
+ /* If a recently encountered triangle has been recorded and has not been */
+ /* deallocated, test it as a good starting point. */
+ if (m->recenttri.tri != (triangle *) NULL) {
+ if (!deadtri(m->recenttri.tri)) {
+ org(m->recenttri, torg);
+ if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
+ otricopy(m->recenttri, *searchtri);
+ return ONVERTEX;
+ }
+ dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
+ (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
+ if (dist < searchdist) {
+ otricopy(m->recenttri, *searchtri);
+ searchdist = dist;
+ if (b->verbose > 2) {
+ printf(" Choosing recent triangle with origin (%.12g, %.12g).\n",
+ torg[0], torg[1]);
+ }
+ }
+ }
+ }
+
+ /* The number of random samples taken is proportional to the cube root of */
+ /* the number of triangles in the mesh. The next bit of code assumes */
+ /* that the number of triangles increases monotonically (or at least */
+ /* doesn't decrease enough to matter). */
+ while (SAMPLEFACTOR * m->samples * m->samples * m->samples <
+ m->triangles.items) {
+ m->samples++;
+ }
+
+ /* We'll draw ceiling(samples * TRIPERBLOCK / maxitems) random samples */
+ /* from each block of triangles (except the first)--until we meet the */
+ /* sample quota. The ceiling means that blocks at the end might be */
+ /* neglected, but I don't care. */
+ samplesperblock = (m->samples * TRIPERBLOCK - 1) / m->triangles.maxitems + 1;
+ /* We'll draw ceiling(samples * itemsfirstblock / maxitems) random samples */
+ /* from the first block of triangles. */
+ samplesleft = (m->samples * m->triangles.itemsfirstblock - 1) /
+ m->triangles.maxitems + 1;
+ totalsamplesleft = m->samples;
+ population = m->triangles.itemsfirstblock;
+ totalpopulation = m->triangles.maxitems;
+ sampleblock = m->triangles.firstblock;
+ sampletri.orient = 0;
+ while (totalsamplesleft > 0) {
+ /* If we're in the last block, `population' needs to be corrected. */
+ if (population > totalpopulation) {
+ population = totalpopulation;
+ }
+ /* Find a pointer to the first triangle in the block. */
+ alignptr = (unsigned long) (sampleblock + 1);
+ firsttri = (char *) (alignptr +
+ (unsigned long) m->triangles.alignbytes -
+ (alignptr %
+ (unsigned long) m->triangles.alignbytes));
+
+ /* Choose `samplesleft' randomly sampled triangles in this block. */
+ do {
+ sampletri.tri = (triangle *) (firsttri +
+ (randomnation((unsigned int) population) *
+ m->triangles.itembytes));
+ if (!deadtri(sampletri.tri)) {
+ org(sampletri, torg);
+ dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) +
+ (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]);
+ if (dist < searchdist) {
+ otricopy(sampletri, *searchtri);
+ searchdist = dist;
+ if (b->verbose > 2) {
+ printf(" Choosing triangle with origin (%.12g, %.12g).\n",
+ torg[0], torg[1]);
+ }
+ }
+ }
+
+ samplesleft--;
+ totalsamplesleft--;
+ } while ((samplesleft > 0) && (totalsamplesleft > 0));
+
+ if (totalsamplesleft > 0) {
+ sampleblock = (VOID **) *sampleblock;
+ samplesleft = samplesperblock;
+ totalpopulation -= population;
+ population = TRIPERBLOCK;
+ }
+ }
+
+ /* Where are we? */
+ org(*searchtri, torg);
+ dest(*searchtri, tdest);
+ /* Check the starting triangle's vertices. */
+ if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) {
+ return ONVERTEX;
+ }
+ if ((tdest[0] == searchpoint[0]) && (tdest[1] == searchpoint[1])) {
+ lnextself(*searchtri);
+ return ONVERTEX;
+ }
+ /* Orient `searchtri' to fit the preconditions of calling preciselocate(). */
+ ahead = counterclockwise(m, b, torg, tdest, searchpoint);
+ if (ahead < 0.0) {
+ /* Turn around so that `searchpoint' is to the left of the */
+ /* edge specified by `searchtri'. */
+ symself(*searchtri);
+ } else if (ahead == 0.0) {
+ /* Check if `searchpoint' is between `torg' and `tdest'. */
+ if (((torg[0] < searchpoint[0]) == (searchpoint[0] < tdest[0])) &&
+ ((torg[1] < searchpoint[1]) == (searchpoint[1] < tdest[1]))) {
+ return ONEDGE;
+ }
+ }
+ return preciselocate(m, b, searchpoint, searchtri, 0);
+}
+
+/** **/
+/** **/
+/********* Point location routines end here *********/
+
+/********* Mesh transformation routines begin here *********/
+/** **/
+/** **/
+
+/*****************************************************************************/
+/* */
+/* insertsubseg() Create a new subsegment and insert it between two */
+/* triangles. */
+/* */
+/* The new subsegment is inserted at the edge described by the handle */
+/* `tri'. Its vertices are properly initialized. The marker `subsegmark' */
+/* is applied to the subsegment and, if appropriate, its vertices. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void insertsubseg(struct mesh *m, struct behavior *b, struct otri *tri,
+ int subsegmark)
+#else /* not ANSI_DECLARATORS */
+void insertsubseg(m, b, tri, subsegmark)
+struct mesh *m;
+struct behavior *b;
+struct otri *tri; /* Edge at which to insert the new subsegment. */
+int subsegmark; /* Marker for the new subsegment. */
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri oppotri;
+ struct osub newsubseg;
+ vertex triorg, tridest;
+ triangle ptr; /* Temporary variable used by sym(). */
+ subseg sptr; /* Temporary variable used by tspivot(). */
+
+ org(*tri, triorg);
+ dest(*tri, tridest);
+ /* Mark vertices if possible. */
+ if (vertexmark(triorg) == 0) {
+ setvertexmark(triorg, subsegmark);
+ }
+ if (vertexmark(tridest) == 0) {
+ setvertexmark(tridest, subsegmark);
+ }
+ /* Check if there's already a subsegment here. */
+ tspivot(*tri, newsubseg);
+ if (newsubseg.ss == m->dummysub) {
+ /* Make new subsegment and initialize its vertices. */
+ makesubseg(m, &newsubseg);
+ setsorg(newsubseg, tridest);
+ setsdest(newsubseg, triorg);
+ setsegorg(newsubseg, tridest);
+ setsegdest(newsubseg, triorg);
+ /* Bond new subsegment to the two triangles it is sandwiched between. */
+ /* Note that the facing triangle `oppotri' might be equal to */
+ /* `dummytri' (outer space), but the new subsegment is bonded to it */
+ /* all the same. */
+ tsbond(*tri, newsubseg);
+ sym(*tri, oppotri);
+ ssymself(newsubseg);
+ tsbond(oppotri, newsubseg);
+ setmark(newsubseg, subsegmark);
+ if (b->verbose > 2) {
+ printf(" Inserting new ");
+ printsubseg(m, b, &newsubseg);
+ }
+ } else {
+ if (mark(newsubseg) == 0) {
+ setmark(newsubseg, subsegmark);
+ }
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* Terminology */
+/* */
+/* A "local transformation" replaces a small set of triangles with another */
+/* set of triangles. This may or may not involve inserting or deleting a */
+/* vertex. */
+/* */
+/* The term "casing" is used to describe the set of triangles that are */
+/* attached to the triangles being transformed, but are not transformed */
+/* themselves. Think of the casing as a fixed hollow structure inside */
+/* which all the action happens. A "casing" is only defined relative to */
+/* a single transformation; each occurrence of a transformation will */
+/* involve a different casing. */
+/* */
+/*****************************************************************************/
+
+/*****************************************************************************/
+/* */
+/* flip() Transform two triangles to two different triangles by flipping */
+/* an edge counterclockwise within a quadrilateral. */
+/* */
+/* Imagine the original triangles, abc and bad, oriented so that the */
+/* shared edge ab lies in a horizontal plane, with the vertex b on the left */
+/* and the vertex a on the right. The vertex c lies below the edge, and */
+/* the vertex d lies above the edge. The `flipedge' handle holds the edge */
+/* ab of triangle abc, and is directed left, from vertex a to vertex b. */
+/* */
+/* The triangles abc and bad are deleted and replaced by the triangles cdb */
+/* and dca. The triangles that represent abc and bad are NOT deallocated; */
+/* they are reused for dca and cdb, respectively. Hence, any handles that */
+/* may have held the original triangles are still valid, although not */
+/* directed as they were before. */
+/* */
+/* Upon completion of this routine, the `flipedge' handle holds the edge */
+/* dc of triangle dca, and is directed down, from vertex d to vertex c. */
+/* (Hence, the two triangles have rotated counterclockwise.) */
+/* */
+/* WARNING: This transformation is geometrically valid only if the */
+/* quadrilateral adbc is convex. Furthermore, this transformation is */
+/* valid only if there is not a subsegment between the triangles abc and */
+/* bad. This routine does not check either of these preconditions, and */
+/* it is the responsibility of the calling routine to ensure that they are */
+/* met. If they are not, the streets shall be filled with wailing and */
+/* gnashing of teeth. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void flip(struct mesh *m, struct behavior *b, struct otri *flipedge)
+#else /* not ANSI_DECLARATORS */
+void flip(m, b, flipedge)
+struct mesh *m;
+struct behavior *b;
+struct otri *flipedge; /* Handle for the triangle abc. */
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri botleft, botright;
+ struct otri topleft, topright;
+ struct otri top;
+ struct otri botlcasing, botrcasing;
+ struct otri toplcasing, toprcasing;
+ struct osub botlsubseg, botrsubseg;
+ struct osub toplsubseg, toprsubseg;
+ vertex leftvertex, rightvertex, botvertex;
+ vertex farvertex;
+ triangle ptr; /* Temporary variable used by sym(). */
+ subseg sptr; /* Temporary variable used by tspivot(). */
+
+ /* Identify the vertices of the quadrilateral. */
+ org(*flipedge, rightvertex);
+ dest(*flipedge, leftvertex);
+ apex(*flipedge, botvertex);
+ sym(*flipedge, top);
+#ifdef SELF_CHECK
+ if (top.tri == m->dummytri) {
+ printf("Internal error in flip(): Attempt to flip on boundary.\n");
+ lnextself(*flipedge);
+ return;
+ }
+ if (m->checksegments) {
+ tspivot(*flipedge, toplsubseg);
+ if (toplsubseg.ss != m->dummysub) {
+ printf("Internal error in flip(): Attempt to flip a segment.\n");
+ lnextself(*flipedge);
+ return;
+ }
+ }
+#endif /* SELF_CHECK */
+ apex(top, farvertex);
+
+ /* Identify the casing of the quadrilateral. */
+ lprev(top, topleft);
+ sym(topleft, toplcasing);
+ lnext(top, topright);
+ sym(topright, toprcasing);
+ lnext(*flipedge, botleft);
+ sym(botleft, botlcasing);
+ lprev(*flipedge, botright);
+ sym(botright, botrcasing);
+ /* Rotate the quadrilateral one-quarter turn counterclockwise. */
+ bond(topleft, botlcasing);
+ bond(botleft, botrcasing);
+ bond(botright, toprcasing);
+ bond(topright, toplcasing);
+
+ if (m->checksegments) {
+ /* Check for subsegments and rebond them to the quadrilateral. */
+ tspivot(topleft, toplsubseg);
+ tspivot(botleft, botlsubseg);
+ tspivot(botright, botrsubseg);
+ tspivot(topright, toprsubseg);
+ if (toplsubseg.ss == m->dummysub) {
+ tsdissolve(topright);
+ } else {
+ tsbond(topright, toplsubseg);
+ }
+ if (botlsubseg.ss == m->dummysub) {
+ tsdissolve(topleft);
+ } else {
+ tsbond(topleft, botlsubseg);
+ }
+ if (botrsubseg.ss == m->dummysub) {
+ tsdissolve(botleft);
+ } else {
+ tsbond(botleft, botrsubseg);
+ }
+ if (toprsubseg.ss == m->dummysub) {
+ tsdissolve(botright);
+ } else {
+ tsbond(botright, toprsubseg);
+ }
+ }
+
+ /* New vertex assignments for the rotated quadrilateral. */
+ setorg(*flipedge, farvertex);
+ setdest(*flipedge, botvertex);
+ setapex(*flipedge, rightvertex);
+ setorg(top, botvertex);
+ setdest(top, farvertex);
+ setapex(top, leftvertex);
+ if (b->verbose > 2) {
+ printf(" Edge flip results in left ");
+ printtriangle(m, b, &top);
+ printf(" and right ");
+ printtriangle(m, b, flipedge);
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* unflip() Transform two triangles to two different triangles by */
+/* flipping an edge clockwise within a quadrilateral. Reverses */
+/* the flip() operation so that the data structures representing */
+/* the triangles are back where they were before the flip(). */
+/* */
+/* Imagine the original triangles, abc and bad, oriented so that the */
+/* shared edge ab lies in a horizontal plane, with the vertex b on the left */
+/* and the vertex a on the right. The vertex c lies below the edge, and */
+/* the vertex d lies above the edge. The `flipedge' handle holds the edge */
+/* ab of triangle abc, and is directed left, from vertex a to vertex b. */
+/* */
+/* The triangles abc and bad are deleted and replaced by the triangles cdb */
+/* and dca. The triangles that represent abc and bad are NOT deallocated; */
+/* they are reused for cdb and dca, respectively. Hence, any handles that */
+/* may have held the original triangles are still valid, although not */
+/* directed as they were before. */
+/* */
+/* Upon completion of this routine, the `flipedge' handle holds the edge */
+/* cd of triangle cdb, and is directed up, from vertex c to vertex d. */
+/* (Hence, the two triangles have rotated clockwise.) */
+/* */
+/* WARNING: This transformation is geometrically valid only if the */
+/* quadrilateral adbc is convex. Furthermore, this transformation is */
+/* valid only if there is not a subsegment between the triangles abc and */
+/* bad. This routine does not check either of these preconditions, and */
+/* it is the responsibility of the calling routine to ensure that they are */
+/* met. If they are not, the streets shall be filled with wailing and */
+/* gnashing of teeth. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void unflip(struct mesh *m, struct behavior *b, struct otri *flipedge)
+#else /* not ANSI_DECLARATORS */
+void unflip(m, b, flipedge)
+struct mesh *m;
+struct behavior *b;
+struct otri *flipedge; /* Handle for the triangle abc. */
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri botleft, botright;
+ struct otri topleft, topright;
+ struct otri top;
+ struct otri botlcasing, botrcasing;
+ struct otri toplcasing, toprcasing;
+ struct osub botlsubseg, botrsubseg;
+ struct osub toplsubseg, toprsubseg;
+ vertex leftvertex, rightvertex, botvertex;
+ vertex farvertex;
+ triangle ptr; /* Temporary variable used by sym(). */
+ subseg sptr; /* Temporary variable used by tspivot(). */
+
+ /* Identify the vertices of the quadrilateral. */
+ org(*flipedge, rightvertex);
+ dest(*flipedge, leftvertex);
+ apex(*flipedge, botvertex);
+ sym(*flipedge, top);
+#ifdef SELF_CHECK
+ if (top.tri == m->dummytri) {
+ printf("Internal error in unflip(): Attempt to flip on boundary.\n");
+ lnextself(*flipedge);
+ return;
+ }
+ if (m->checksegments) {
+ tspivot(*flipedge, toplsubseg);
+ if (toplsubseg.ss != m->dummysub) {
+ printf("Internal error in unflip(): Attempt to flip a subsegment.\n");
+ lnextself(*flipedge);
+ return;
+ }
+ }
+#endif /* SELF_CHECK */
+ apex(top, farvertex);
+
+ /* Identify the casing of the quadrilateral. */
+ lprev(top, topleft);
+ sym(topleft, toplcasing);
+ lnext(top, topright);
+ sym(topright, toprcasing);
+ lnext(*flipedge, botleft);
+ sym(botleft, botlcasing);
+ lprev(*flipedge, botright);
+ sym(botright, botrcasing);
+ /* Rotate the quadrilateral one-quarter turn clockwise. */
+ bond(topleft, toprcasing);
+ bond(botleft, toplcasing);
+ bond(botright, botlcasing);
+ bond(topright, botrcasing);
+
+ if (m->checksegments) {
+ /* Check for subsegments and rebond them to the quadrilateral. */
+ tspivot(topleft, toplsubseg);
+ tspivot(botleft, botlsubseg);
+ tspivot(botright, botrsubseg);
+ tspivot(topright, toprsubseg);
+ if (toplsubseg.ss == m->dummysub) {
+ tsdissolve(botleft);
+ } else {
+ tsbond(botleft, toplsubseg);
+ }
+ if (botlsubseg.ss == m->dummysub) {
+ tsdissolve(botright);
+ } else {
+ tsbond(botright, botlsubseg);
+ }
+ if (botrsubseg.ss == m->dummysub) {
+ tsdissolve(topright);
+ } else {
+ tsbond(topright, botrsubseg);
+ }
+ if (toprsubseg.ss == m->dummysub) {
+ tsdissolve(topleft);
+ } else {
+ tsbond(topleft, toprsubseg);
+ }
+ }
+
+ /* New vertex assignments for the rotated quadrilateral. */
+ setorg(*flipedge, botvertex);
+ setdest(*flipedge, farvertex);
+ setapex(*flipedge, leftvertex);
+ setorg(top, farvertex);
+ setdest(top, botvertex);
+ setapex(top, rightvertex);
+ if (b->verbose > 2) {
+ printf(" Edge unflip results in left ");
+ printtriangle(m, b, flipedge);
+ printf(" and right ");
+ printtriangle(m, b, &top);
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* insertvertex() Insert a vertex into a Delaunay triangulation, */
+/* performing flips as necessary to maintain the Delaunay */
+/* property. */
+/* */
+/* The point `insertvertex' is located. If `searchtri.tri' is not NULL, */
+/* the search for the containing triangle begins from `searchtri'. If */
+/* `searchtri.tri' is NULL, a full point location procedure is called. */
+/* If `insertvertex' is found inside a triangle, the triangle is split into */
+/* three; if `insertvertex' lies on an edge, the edge is split in two, */
+/* thereby splitting the two adjacent triangles into four. Edge flips are */
+/* used to restore the Delaunay property. If `insertvertex' lies on an */
+/* existing vertex, no action is taken, and the value DUPLICATEVERTEX is */
+/* returned. On return, `searchtri' is set to a handle whose origin is the */
+/* existing vertex. */
+/* */
+/* Normally, the parameter `splitseg' is set to NULL, implying that no */
+/* subsegment should be split. In this case, if `insertvertex' is found to */
+/* lie on a segment, no action is taken, and the value VIOLATINGVERTEX is */
+/* returned. On return, `searchtri' is set to a handle whose primary edge */
+/* is the violated subsegment. */
+/* */
+/* If the calling routine wishes to split a subsegment by inserting a */
+/* vertex in it, the parameter `splitseg' should be that subsegment. In */
+/* this case, `searchtri' MUST be the triangle handle reached by pivoting */
+/* from that subsegment; no point location is done. */
+/* */
+/* `segmentflaws' and `triflaws' are flags that indicate whether or not */
+/* there should be checks for the creation of encroached subsegments or bad */
+/* quality triangles. If a newly inserted vertex encroaches upon */
+/* subsegments, these subsegments are added to the list of subsegments to */
+/* be split if `segmentflaws' is set. If bad triangles are created, these */
+/* are added to the queue if `triflaws' is set. */
+/* */
+/* If a duplicate vertex or violated segment does not prevent the vertex */
+/* from being inserted, the return value will be ENCROACHINGVERTEX if the */
+/* vertex encroaches upon a subsegment (and checking is enabled), or */
+/* SUCCESSFULVERTEX otherwise. In either case, `searchtri' is set to a */
+/* handle whose origin is the newly inserted vertex. */
+/* */
+/* insertvertex() does not use flip() for reasons of speed; some */
+/* information can be reused from edge flip to edge flip, like the */
+/* locations of subsegments. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+enum insertvertexresult insertvertex(struct mesh *m, struct behavior *b,
+ vertex newvertex, struct otri *searchtri,
+ struct osub *splitseg,
+ int segmentflaws, int triflaws)
+#else /* not ANSI_DECLARATORS */
+enum insertvertexresult insertvertex(m, b, newvertex, searchtri, splitseg,
+ segmentflaws, triflaws)
+struct mesh *m;
+struct behavior *b;
+vertex newvertex;
+struct otri *searchtri;
+struct osub *splitseg;
+int segmentflaws;
+int triflaws;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri horiz;
+ struct otri top;
+ struct otri botleft, botright;
+ struct otri topleft, topright;
+ struct otri newbotleft, newbotright;
+ struct otri newtopright;
+ struct otri botlcasing, botrcasing;
+ struct otri toplcasing, toprcasing;
+ struct otri testtri;
+ struct osub botlsubseg, botrsubseg;
+ struct osub toplsubseg, toprsubseg;
+ struct osub brokensubseg;
+ struct osub checksubseg;
+ struct osub rightsubseg;
+ struct osub newsubseg;
+ struct badsubseg *encroached;
+ struct flipstacker *newflip;
+ vertex first;
+ vertex leftvertex, rightvertex, botvertex, topvertex, farvertex;
+ vertex segmentorg, segmentdest;
+ REAL attrib;
+ REAL area;
+ enum insertvertexresult success;
+ enum locateresult intersect;
+ int doflip;
+ int mirrorflag;
+ int enq;
+ int i;
+ triangle ptr; /* Temporary variable used by sym(). */
+ subseg sptr; /* Temporary variable used by spivot() and tspivot(). */
+
+ if (b->verbose > 1) {
+ printf(" Inserting (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
+ }
+
+ if (splitseg == (struct osub *) NULL) {
+ /* Find the location of the vertex to be inserted. Check if a good */
+ /* starting triangle has already been provided by the caller. */
+ if (searchtri->tri == m->dummytri) {
+ /* Find a boundary triangle. */
+ horiz.tri = m->dummytri;
+ horiz.orient = 0;
+ symself(horiz);
+ /* Search for a triangle containing `newvertex'. */
+ intersect = locate(m, b, newvertex, &horiz);
+ } else {
+ /* Start searching from the triangle provided by the caller. */
+ otricopy(*searchtri, horiz);
+ intersect = preciselocate(m, b, newvertex, &horiz, 1);
+ }
+ } else {
+ /* The calling routine provides the subsegment in which */
+ /* the vertex is inserted. */
+ otricopy(*searchtri, horiz);
+ intersect = ONEDGE;
+ }
+
+ if (intersect == ONVERTEX) {
+ /* There's already a vertex there. Return in `searchtri' a triangle */
+ /* whose origin is the existing vertex. */
+ otricopy(horiz, *searchtri);
+ otricopy(horiz, m->recenttri);
+ return DUPLICATEVERTEX;
+ }
+ if ((intersect == ONEDGE) || (intersect == OUTSIDE)) {
+ /* The vertex falls on an edge or boundary. */
+ if (m->checksegments && (splitseg == (struct osub *) NULL)) {
+ /* Check whether the vertex falls on a subsegment. */
+ tspivot(horiz, brokensubseg);
+ if (brokensubseg.ss != m->dummysub) {
+ /* The vertex falls on a subsegment, and hence will not be inserted. */
+ if (segmentflaws) {
+ enq = b->nobisect != 2;
+ if (enq && (b->nobisect == 1)) {
+ /* This subsegment may be split only if it is an */
+ /* internal boundary. */
+ sym(horiz, testtri);
+ enq = testtri.tri != m->dummytri;
+ }
+ if (enq) {
+ /* Add the subsegment to the list of encroached subsegments. */
+ encroached = (struct badsubseg *) poolalloc(&m->badsubsegs);
+ encroached->encsubseg = sencode(brokensubseg);
+ sorg(brokensubseg, encroached->subsegorg);
+ sdest(brokensubseg, encroached->subsegdest);
+ if (b->verbose > 2) {
+ printf(
+ " Queueing encroached subsegment (%.12g, %.12g) (%.12g, %.12g).\n",
+ encroached->subsegorg[0], encroached->subsegorg[1],
+ encroached->subsegdest[0], encroached->subsegdest[1]);
+ }
+ }
+ }
+ /* Return a handle whose primary edge contains the vertex, */
+ /* which has not been inserted. */
+ otricopy(horiz, *searchtri);
+ otricopy(horiz, m->recenttri);
+ return VIOLATINGVERTEX;
+ }
+ }
+
+ /* Insert the vertex on an edge, dividing one triangle into two (if */
+ /* the edge lies on a boundary) or two triangles into four. */
+ lprev(horiz, botright);
+ sym(botright, botrcasing);
+ sym(horiz, topright);
+ /* Is there a second triangle? (Or does this edge lie on a boundary?) */
+ mirrorflag = topright.tri != m->dummytri;
+ if (mirrorflag) {
+ lnextself(topright);
+ sym(topright, toprcasing);
+ maketriangle(m, b, &newtopright);
+ } else {
+ /* Splitting a boundary edge increases the number of boundary edges. */
+ m->hullsize++;
+ }
+ maketriangle(m, b, &newbotright);
+
+ /* Set the vertices of changed and new triangles. */
+ org(horiz, rightvertex);
+ dest(horiz, leftvertex);
+ apex(horiz, botvertex);
+ setorg(newbotright, botvertex);
+ setdest(newbotright, rightvertex);
+ setapex(newbotright, newvertex);
+ setorg(horiz, newvertex);
+ for (i = 0; i < m->eextras; i++) {
+ /* Set the element attributes of a new triangle. */
+ setelemattribute(newbotright, i, elemattribute(botright, i));
+ }
+ if (b->vararea) {
+ /* Set the area constraint of a new triangle. */
+ setareabound(newbotright, areabound(botright));
+ }
+ if (mirrorflag) {
+ dest(topright, topvertex);
+ setorg(newtopright, rightvertex);
+ setdest(newtopright, topvertex);
+ setapex(newtopright, newvertex);
+ setorg(topright, newvertex);
+ for (i = 0; i < m->eextras; i++) {
+ /* Set the element attributes of another new triangle. */
+ setelemattribute(newtopright, i, elemattribute(topright, i));
+ }
+ if (b->vararea) {
+ /* Set the area constraint of another new triangle. */
+ setareabound(newtopright, areabound(topright));
+ }
+ }
+
+ /* There may be subsegments that need to be bonded */
+ /* to the new triangle(s). */
+ if (m->checksegments) {
+ tspivot(botright, botrsubseg);
+ if (botrsubseg.ss != m->dummysub) {
+ tsdissolve(botright);
+ tsbond(newbotright, botrsubseg);
+ }
+ if (mirrorflag) {
+ tspivot(topright, toprsubseg);
+ if (toprsubseg.ss != m->dummysub) {
+ tsdissolve(topright);
+ tsbond(newtopright, toprsubseg);
+ }
+ }
+ }
+
+ /* Bond the new triangle(s) to the surrounding triangles. */
+ bond(newbotright, botrcasing);
+ lprevself(newbotright);
+ bond(newbotright, botright);
+ lprevself(newbotright);
+ if (mirrorflag) {
+ bond(newtopright, toprcasing);
+ lnextself(newtopright);
+ bond(newtopright, topright);
+ lnextself(newtopright);
+ bond(newtopright, newbotright);
+ }
+
+ if (splitseg != (struct osub *) NULL) {
+ /* Split the subsegment into two. */
+ setsdest(*splitseg, newvertex);
+ segorg(*splitseg, segmentorg);
+ segdest(*splitseg, segmentdest);
+ ssymself(*splitseg);
+ spivot(*splitseg, rightsubseg);
+ insertsubseg(m, b, &newbotright, mark(*splitseg));
+ tspivot(newbotright, newsubseg);
+ setsegorg(newsubseg, segmentorg);
+ setsegdest(newsubseg, segmentdest);
+ sbond(*splitseg, newsubseg);
+ ssymself(newsubseg);
+ sbond(newsubseg, rightsubseg);
+ ssymself(*splitseg);
+ /* Transfer the subsegment's boundary marker to the vertex */
+ /* if required. */
+ if (vertexmark(newvertex) == 0) {
+ setvertexmark(newvertex, mark(*splitseg));
+ }
+ }
+
+ if (m->checkquality) {
+ poolrestart(&m->flipstackers);
+ m->lastflip = (struct flipstacker *) poolalloc(&m->flipstackers);
+ m->lastflip->flippedtri = encode(horiz);
+ m->lastflip->prevflip = (struct flipstacker *) &insertvertex;
+ }
+
+#ifdef SELF_CHECK
+ if (counterclockwise(m, b, rightvertex, leftvertex, botvertex) < 0.0) {
+ printf("Internal error in insertvertex():\n");
+ printf(
+ " Clockwise triangle prior to edge vertex insertion (bottom).\n");
+ }
+ if (mirrorflag) {
+ if (counterclockwise(m, b, leftvertex, rightvertex, topvertex) < 0.0) {
+ printf("Internal error in insertvertex():\n");
+ printf(" Clockwise triangle prior to edge vertex insertion (top).\n");
+ }
+ if (counterclockwise(m, b, rightvertex, topvertex, newvertex) < 0.0) {
+ printf("Internal error in insertvertex():\n");
+ printf(
+ " Clockwise triangle after edge vertex insertion (top right).\n");
+ }
+ if (counterclockwise(m, b, topvertex, leftvertex, newvertex) < 0.0) {
+ printf("Internal error in insertvertex():\n");
+ printf(
+ " Clockwise triangle after edge vertex insertion (top left).\n");
+ }
+ }
+ if (counterclockwise(m, b, leftvertex, botvertex, newvertex) < 0.0) {
+ printf("Internal error in insertvertex():\n");
+ printf(
+ " Clockwise triangle after edge vertex insertion (bottom left).\n");
+ }
+ if (counterclockwise(m, b, botvertex, rightvertex, newvertex) < 0.0) {
+ printf("Internal error in insertvertex():\n");
+ printf(
+ " Clockwise triangle after edge vertex insertion (bottom right).\n");
+ }
+#endif /* SELF_CHECK */
+ if (b->verbose > 2) {
+ printf(" Updating bottom left ");
+ printtriangle(m, b, &botright);
+ if (mirrorflag) {
+ printf(" Updating top left ");
+ printtriangle(m, b, &topright);
+ printf(" Creating top right ");
+ printtriangle(m, b, &newtopright);
+ }
+ printf(" Creating bottom right ");
+ printtriangle(m, b, &newbotright);
+ }
+
+ /* Position `horiz' on the first edge to check for */
+ /* the Delaunay property. */
+ lnextself(horiz);
+ } else {
+ /* Insert the vertex in a triangle, splitting it into three. */
+ lnext(horiz, botleft);
+ lprev(horiz, botright);
+ sym(botleft, botlcasing);
+ sym(botright, botrcasing);
+ maketriangle(m, b, &newbotleft);
+ maketriangle(m, b, &newbotright);
+
+ /* Set the vertices of changed and new triangles. */
+ org(horiz, rightvertex);
+ dest(horiz, leftvertex);
+ apex(horiz, botvertex);
+ setorg(newbotleft, leftvertex);
+ setdest(newbotleft, botvertex);
+ setapex(newbotleft, newvertex);
+ setorg(newbotright, botvertex);
+ setdest(newbotright, rightvertex);
+ setapex(newbotright, newvertex);
+ setapex(horiz, newvertex);
+ for (i = 0; i < m->eextras; i++) {
+ /* Set the element attributes of the new triangles. */
+ attrib = elemattribute(horiz, i);
+ setelemattribute(newbotleft, i, attrib);
+ setelemattribute(newbotright, i, attrib);
+ }
+ if (b->vararea) {
+ /* Set the area constraint of the new triangles. */
+ area = areabound(horiz);
+ setareabound(newbotleft, area);
+ setareabound(newbotright, area);
+ }
+
+ /* There may be subsegments that need to be bonded */
+ /* to the new triangles. */
+ if (m->checksegments) {
+ tspivot(botleft, botlsubseg);
+ if (botlsubseg.ss != m->dummysub) {
+ tsdissolve(botleft);
+ tsbond(newbotleft, botlsubseg);
+ }
+ tspivot(botright, botrsubseg);
+ if (botrsubseg.ss != m->dummysub) {
+ tsdissolve(botright);
+ tsbond(newbotright, botrsubseg);
+ }
+ }
+
+ /* Bond the new triangles to the surrounding triangles. */
+ bond(newbotleft, botlcasing);
+ bond(newbotright, botrcasing);
+ lnextself(newbotleft);
+ lprevself(newbotright);
+ bond(newbotleft, newbotright);
+ lnextself(newbotleft);
+ bond(botleft, newbotleft);
+ lprevself(newbotright);
+ bond(botright, newbotright);
+
+ if (m->checkquality) {
+ poolrestart(&m->flipstackers);
+ m->lastflip = (struct flipstacker *) poolalloc(&m->flipstackers);
+ m->lastflip->flippedtri = encode(horiz);
+ m->lastflip->prevflip = (struct flipstacker *) NULL;
+ }
+
+#ifdef SELF_CHECK
+ if (counterclockwise(m, b, rightvertex, leftvertex, botvertex) < 0.0) {
+ printf("Internal error in insertvertex():\n");
+ printf(" Clockwise triangle prior to vertex insertion.\n");
+ }
+ if (counterclockwise(m, b, rightvertex, leftvertex, newvertex) < 0.0) {
+ printf("Internal error in insertvertex():\n");
+ printf(" Clockwise triangle after vertex insertion (top).\n");
+ }
+ if (counterclockwise(m, b, leftvertex, botvertex, newvertex) < 0.0) {
+ printf("Internal error in insertvertex():\n");
+ printf(" Clockwise triangle after vertex insertion (left).\n");
+ }
+ if (counterclockwise(m, b, botvertex, rightvertex, newvertex) < 0.0) {
+ printf("Internal error in insertvertex():\n");
+ printf(" Clockwise triangle after vertex insertion (right).\n");
+ }
+#endif /* SELF_CHECK */
+ if (b->verbose > 2) {
+ printf(" Updating top ");
+ printtriangle(m, b, &horiz);
+ printf(" Creating left ");
+ printtriangle(m, b, &newbotleft);
+ printf(" Creating right ");
+ printtriangle(m, b, &newbotright);
+ }
+ }
+
+ /* The insertion is successful by default, unless an encroached */
+ /* subsegment is found. */
+ success = SUCCESSFULVERTEX;
+ /* Circle around the newly inserted vertex, checking each edge opposite */
+ /* it for the Delaunay property. Non-Delaunay edges are flipped. */
+ /* `horiz' is always the edge being checked. `first' marks where to */
+ /* stop circling. */
+ org(horiz, first);
+ rightvertex = first;
+ dest(horiz, leftvertex);
+ /* Circle until finished. */
+ while (1) {
+ /* By default, the edge will be flipped. */
+ doflip = 1;
+
+ if (m->checksegments) {
+ /* Check for a subsegment, which cannot be flipped. */
+ tspivot(horiz, checksubseg);
+ if (checksubseg.ss != m->dummysub) {
+ /* The edge is a subsegment and cannot be flipped. */
+ doflip = 0;
+#ifndef CDT_ONLY
+ if (segmentflaws) {
+ /* Does the new vertex encroach upon this subsegment? */
+ if (checkseg4encroach(m, b, &checksubseg)) {
+ success = ENCROACHINGVERTEX;
+ }
+ }
+#endif /* not CDT_ONLY */
+ }
+ }
+
+ if (doflip) {
+ /* Check if the edge is a boundary edge. */
+ sym(horiz, top);
+ if (top.tri == m->dummytri) {
+ /* The edge is a boundary edge and cannot be flipped. */
+ doflip = 0;
+ } else {
+ /* Find the vertex on the other side of the edge. */
+ apex(top, farvertex);
+ /* In the incremental Delaunay triangulation algorithm, any of */
+ /* `leftvertex', `rightvertex', and `farvertex' could be vertices */
+ /* of the triangular bounding box. These vertices must be */
+ /* treated as if they are infinitely distant, even though their */
+ /* "coordinates" are not. */
+ if ((leftvertex == m->infvertex1) || (leftvertex == m->infvertex2) ||
+ (leftvertex == m->infvertex3)) {
+ /* `leftvertex' is infinitely distant. Check the convexity of */
+ /* the boundary of the triangulation. 'farvertex' might be */
+ /* infinite as well, but trust me, this same condition should */
+ /* be applied. */
+ doflip = counterclockwise(m, b, newvertex, rightvertex, farvertex)
+ > 0.0;
+ } else if ((rightvertex == m->infvertex1) ||
+ (rightvertex == m->infvertex2) ||
+ (rightvertex == m->infvertex3)) {
+ /* `rightvertex' is infinitely distant. Check the convexity of */
+ /* the boundary of the triangulation. 'farvertex' might be */
+ /* infinite as well, but trust me, this same condition should */
+ /* be applied. */
+ doflip = counterclockwise(m, b, farvertex, leftvertex, newvertex)
+ > 0.0;
+ } else if ((farvertex == m->infvertex1) ||
+ (farvertex == m->infvertex2) ||
+ (farvertex == m->infvertex3)) {
+ /* `farvertex' is infinitely distant and cannot be inside */
+ /* the circumcircle of the triangle `horiz'. */
+ doflip = 0;
+ } else {
+ /* Test whether the edge is locally Delaunay. */
+ doflip = incircle(m, b, leftvertex, newvertex, rightvertex,
+ farvertex) > 0.0;
+ }
+ if (doflip) {
+ /* We made it! Flip the edge `horiz' by rotating its containing */
+ /* quadrilateral (the two triangles adjacent to `horiz'). */
+ /* Identify the casing of the quadrilateral. */
+ lprev(top, topleft);
+ sym(topleft, toplcasing);
+ lnext(top, topright);
+ sym(topright, toprcasing);
+ lnext(horiz, botleft);
+ sym(botleft, botlcasing);
+ lprev(horiz, botright);
+ sym(botright, botrcasing);
+ /* Rotate the quadrilateral one-quarter turn counterclockwise. */
+ bond(topleft, botlcasing);
+ bond(botleft, botrcasing);
+ bond(botright, toprcasing);
+ bond(topright, toplcasing);
+ if (m->checksegments) {
+ /* Check for subsegments and rebond them to the quadrilateral. */
+ tspivot(topleft, toplsubseg);
+ tspivot(botleft, botlsubseg);
+ tspivot(botright, botrsubseg);
+ tspivot(topright, toprsubseg);
+ if (toplsubseg.ss == m->dummysub) {
+ tsdissolve(topright);
+ } else {
+ tsbond(topright, toplsubseg);
+ }
+ if (botlsubseg.ss == m->dummysub) {
+ tsdissolve(topleft);
+ } else {
+ tsbond(topleft, botlsubseg);
+ }
+ if (botrsubseg.ss == m->dummysub) {
+ tsdissolve(botleft);
+ } else {
+ tsbond(botleft, botrsubseg);
+ }
+ if (toprsubseg.ss == m->dummysub) {
+ tsdissolve(botright);
+ } else {
+ tsbond(botright, toprsubseg);
+ }
+ }
+ /* New vertex assignments for the rotated quadrilateral. */
+ setorg(horiz, farvertex);
+ setdest(horiz, newvertex);
+ setapex(horiz, rightvertex);
+ setorg(top, newvertex);
+ setdest(top, farvertex);
+ setapex(top, leftvertex);
+ for (i = 0; i < m->eextras; i++) {
+ /* Take the average of the two triangles' attributes. */
+ attrib = 0.5 * (elemattribute(top, i) + elemattribute(horiz, i));
+ setelemattribute(top, i, attrib);
+ setelemattribute(horiz, i, attrib);
+ }
+ if (b->vararea) {
+ if ((areabound(top) <= 0.0) || (areabound(horiz) <= 0.0)) {
+ area = -1.0;
+ } else {
+ /* Take the average of the two triangles' area constraints. */
+ /* This prevents small area constraints from migrating a */
+ /* long, long way from their original location due to flips. */
+ area = 0.5 * (areabound(top) + areabound(horiz));
+ }
+ setareabound(top, area);
+ setareabound(horiz, area);
+ }
+
+ if (m->checkquality) {
+ newflip = (struct flipstacker *) poolalloc(&m->flipstackers);
+ newflip->flippedtri = encode(horiz);
+ newflip->prevflip = m->lastflip;
+ m->lastflip = newflip;
+ }
+
+#ifdef SELF_CHECK
+ if (newvertex != (vertex) NULL) {
+ if (counterclockwise(m, b, leftvertex, newvertex, rightvertex) <
+ 0.0) {
+ printf("Internal error in insertvertex():\n");
+ printf(" Clockwise triangle prior to edge flip (bottom).\n");
+ }
+ /* The following test has been removed because constrainededge() */
+ /* sometimes generates inverted triangles that insertvertex() */
+ /* removes. */
+/*
+ if (counterclockwise(m, b, rightvertex, farvertex, leftvertex) <
+ 0.0) {
+ printf("Internal error in insertvertex():\n");
+ printf(" Clockwise triangle prior to edge flip (top).\n");
+ }
+*/
+ if (counterclockwise(m, b, farvertex, leftvertex, newvertex) <
+ 0.0) {
+ printf("Internal error in insertvertex():\n");
+ printf(" Clockwise triangle after edge flip (left).\n");
+ }
+ if (counterclockwise(m, b, newvertex, rightvertex, farvertex) <
+ 0.0) {
+ printf("Internal error in insertvertex():\n");
+ printf(" Clockwise triangle after edge flip (right).\n");
+ }
+ }
+#endif /* SELF_CHECK */
+ if (b->verbose > 2) {
+ printf(" Edge flip results in left ");
+ lnextself(topleft);
+ printtriangle(m, b, &topleft);
+ printf(" and right ");
+ printtriangle(m, b, &horiz);
+ }
+ /* On the next iterations, consider the two edges that were */
+ /* exposed (this is, are now visible to the newly inserted */
+ /* vertex) by the edge flip. */
+ lprevself(horiz);
+ leftvertex = farvertex;
+ }
+ }
+ }
+ if (!doflip) {
+ /* The handle `horiz' is accepted as locally Delaunay. */
+#ifndef CDT_ONLY
+ if (triflaws) {
+ /* Check the triangle `horiz' for quality. */
+ testtriangle(m, b, &horiz);
+ }
+#endif /* not CDT_ONLY */
+ /* Look for the next edge around the newly inserted vertex. */
+ lnextself(horiz);
+ sym(horiz, testtri);
+ /* Check for finishing a complete revolution about the new vertex, or */
+ /* falling outside of the triangulation. The latter will happen */
+ /* when a vertex is inserted at a boundary. */
+ if ((leftvertex == first) || (testtri.tri == m->dummytri)) {
+ /* We're done. Return a triangle whose origin is the new vertex. */
+ lnext(horiz, *searchtri);
+ lnext(horiz, m->recenttri);
+ return success;
+ }
+ /* Finish finding the next edge around the newly inserted vertex. */
+ lnext(testtri, horiz);
+ rightvertex = leftvertex;
+ dest(horiz, leftvertex);
+ }
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* triangulatepolygon() Find the Delaunay triangulation of a polygon that */
+/* has a certain "nice" shape. This includes the */
+/* polygons that result from deletion of a vertex or */
+/* insertion of a segment. */
+/* */
+/* This is a conceptually difficult routine. The starting assumption is */
+/* that we have a polygon with n sides. n - 1 of these sides are currently */
+/* represented as edges in the mesh. One side, called the "base", need not */
+/* be. */
+/* */
+/* Inside the polygon is a structure I call a "fan", consisting of n - 1 */
+/* triangles that share a common origin. For each of these triangles, the */
+/* edge opposite the origin is one of the sides of the polygon. The */
+/* primary edge of each triangle is the edge directed from the origin to */
+/* the destination; note that this is not the same edge that is a side of */
+/* the polygon. `firstedge' is the primary edge of the first triangle. */
+/* From there, the triangles follow in counterclockwise order about the */
+/* polygon, until `lastedge', the primary edge of the last triangle. */
+/* `firstedge' and `lastedge' are probably connected to other triangles */
+/* beyond the extremes of the fan, but their identity is not important, as */
+/* long as the fan remains connected to them. */
+/* */
+/* Imagine the polygon oriented so that its base is at the bottom. This */
+/* puts `firstedge' on the far right, and `lastedge' on the far left. */
+/* The right vertex of the base is the destination of `firstedge', and the */
+/* left vertex of the base is the apex of `lastedge'. */
+/* */
+/* The challenge now is to find the right sequence of edge flips to */
+/* transform the fan into a Delaunay triangulation of the polygon. Each */
+/* edge flip effectively removes one triangle from the fan, committing it */
+/* to the polygon. The resulting polygon has one fewer edge. If `doflip' */
+/* is set, the final flip will be performed, resulting in a fan of one */
+/* (useless?) triangle. If `doflip' is not set, the final flip is not */
+/* performed, resulting in a fan of two triangles, and an unfinished */
+/* triangular polygon that is not yet filled out with a single triangle. */
+/* On completion of the routine, `lastedge' is the last remaining triangle, */
+/* or the leftmost of the last two. */
+/* */
+/* Although the flips are performed in the order described above, the */
+/* decisions about what flips to perform are made in precisely the reverse */
+/* order. The recursive triangulatepolygon() procedure makes a decision, */
+/* uses up to two recursive calls to triangulate the "subproblems" */
+/* (polygons with fewer edges), and then performs an edge flip. */
+/* */
+/* The "decision" it makes is which vertex of the polygon should be */
+/* connected to the base. This decision is made by testing every possible */
+/* vertex. Once the best vertex is found, the two edges that connect this */
+/* vertex to the base become the bases for two smaller polygons. These */
+/* are triangulated recursively. Unfortunately, this approach can take */
+/* O(n^2) time not only in the worst case, but in many common cases. It's */
+/* rarely a big deal for vertex deletion, where n is rarely larger than */
+/* ten, but it could be a big deal for segment insertion, especially if */
+/* there's a lot of long segments that each cut many triangles. I ought to */
+/* code a faster algorithm some day. */
+/* */
+/* The `edgecount' parameter is the number of sides of the polygon, */
+/* including its base. `triflaws' is a flag that determines whether the */
+/* new triangles should be tested for quality, and enqueued if they are */
+/* bad. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void triangulatepolygon(struct mesh *m, struct behavior *b,
+ struct otri *firstedge, struct otri *lastedge,
+ int edgecount, int doflip, int triflaws)
+#else /* not ANSI_DECLARATORS */
+void triangulatepolygon(m, b, firstedge, lastedge, edgecount, doflip, triflaws)
+struct mesh *m;
+struct behavior *b;
+struct otri *firstedge;
+struct otri *lastedge;
+int edgecount;
+int doflip;
+int triflaws;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri testtri;
+ struct otri besttri;
+ struct otri tempedge;
+ vertex leftbasevertex, rightbasevertex;
+ vertex testvertex;
+ vertex bestvertex;
+ int bestnumber;
+ int i;
+ triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */
+
+ /* Identify the base vertices. */
+ apex(*lastedge, leftbasevertex);
+ dest(*firstedge, rightbasevertex);
+ if (b->verbose > 2) {
+ printf(" Triangulating interior polygon at edge\n");
+ printf(" (%.12g, %.12g) (%.12g, %.12g)\n", leftbasevertex[0],
+ leftbasevertex[1], rightbasevertex[0], rightbasevertex[1]);
+ }
+ /* Find the best vertex to connect the base to. */
+ onext(*firstedge, besttri);
+ dest(besttri, bestvertex);
+ otricopy(besttri, testtri);
+ bestnumber = 1;
+ for (i = 2; i <= edgecount - 2; i++) {
+ onextself(testtri);
+ dest(testtri, testvertex);
+ /* Is this a better vertex? */
+ if (incircle(m, b, leftbasevertex, rightbasevertex, bestvertex,
+ testvertex) > 0.0) {
+ otricopy(testtri, besttri);
+ bestvertex = testvertex;
+ bestnumber = i;
+ }
+ }
+ if (b->verbose > 2) {
+ printf(" Connecting edge to (%.12g, %.12g)\n", bestvertex[0],
+ bestvertex[1]);
+ }
+ if (bestnumber > 1) {
+ /* Recursively triangulate the smaller polygon on the right. */
+ oprev(besttri, tempedge);
+ triangulatepolygon(m, b, firstedge, &tempedge, bestnumber + 1, 1,
+ triflaws);
+ }
+ if (bestnumber < edgecount - 2) {
+ /* Recursively triangulate the smaller polygon on the left. */
+ sym(besttri, tempedge);
+ triangulatepolygon(m, b, &besttri, lastedge, edgecount - bestnumber, 1,
+ triflaws);
+ /* Find `besttri' again; it may have been lost to edge flips. */
+ sym(tempedge, besttri);
+ }
+ if (doflip) {
+ /* Do one final edge flip. */
+ flip(m, b, &besttri);
+#ifndef CDT_ONLY
+ if (triflaws) {
+ /* Check the quality of the newly committed triangle. */
+ sym(besttri, testtri);
+ testtriangle(m, b, &testtri);
+ }
+#endif /* not CDT_ONLY */
+ }
+ /* Return the base triangle. */
+ otricopy(besttri, *lastedge);
+}
+
+/*****************************************************************************/
+/* */
+/* deletevertex() Delete a vertex from a Delaunay triangulation, ensuring */
+/* that the triangulation remains Delaunay. */
+/* */
+/* The origin of `deltri' is deleted. The union of the triangles adjacent */
+/* to this vertex is a polygon, for which the Delaunay triangulation is */
+/* found. Two triangles are removed from the mesh. */
+/* */
+/* Only interior vertices that do not lie on segments or boundaries may be */
+/* deleted. */
+/* */
+/*****************************************************************************/
+
+#ifndef CDT_ONLY
+
+#ifdef ANSI_DECLARATORS
+void deletevertex(struct mesh *m, struct behavior *b, struct otri *deltri)
+#else /* not ANSI_DECLARATORS */
+void deletevertex(m, b, deltri)
+struct mesh *m;
+struct behavior *b;
+struct otri *deltri;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri countingtri;
+ struct otri firstedge, lastedge;
+ struct otri deltriright;
+ struct otri lefttri, righttri;
+ struct otri leftcasing, rightcasing;
+ struct osub leftsubseg, rightsubseg;
+ vertex delvertex;
+ vertex neworg;
+ int edgecount;
+ triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */
+ subseg sptr; /* Temporary variable used by tspivot(). */
+
+ org(*deltri, delvertex);
+ if (b->verbose > 1) {
+ printf(" Deleting (%.12g, %.12g).\n", delvertex[0], delvertex[1]);
+ }
+ vertexdealloc(m, delvertex);
+
+ /* Count the degree of the vertex being deleted. */
+ onext(*deltri, countingtri);
+ edgecount = 1;
+ while (!otriequal(*deltri, countingtri)) {
+#ifdef SELF_CHECK
+ if (countingtri.tri == m->dummytri) {
+ printf("Internal error in deletevertex():\n");
+ printf(" Attempt to delete boundary vertex.\n");
+ internalerror();
+ }
+#endif /* SELF_CHECK */
+ edgecount++;
+ onextself(countingtri);
+ }
+
+#ifdef SELF_CHECK
+ if (edgecount < 3) {
+ printf("Internal error in deletevertex():\n Vertex has degree %d.\n",
+ edgecount);
+ internalerror();
+ }
+#endif /* SELF_CHECK */
+ if (edgecount > 3) {
+ /* Triangulate the polygon defined by the union of all triangles */
+ /* adjacent to the vertex being deleted. Check the quality of */
+ /* the resulting triangles. */
+ onext(*deltri, firstedge);
+ oprev(*deltri, lastedge);
+ triangulatepolygon(m, b, &firstedge, &lastedge, edgecount, 0,
+ !b->nobisect);
+ }
+ /* Splice out two triangles. */
+ lprev(*deltri, deltriright);
+ dnext(*deltri, lefttri);
+ sym(lefttri, leftcasing);
+ oprev(deltriright, righttri);
+ sym(righttri, rightcasing);
+ bond(*deltri, leftcasing);
+ bond(deltriright, rightcasing);
+ tspivot(lefttri, leftsubseg);
+ if (leftsubseg.ss != m->dummysub) {
+ tsbond(*deltri, leftsubseg);
+ }
+ tspivot(righttri, rightsubseg);
+ if (rightsubseg.ss != m->dummysub) {
+ tsbond(deltriright, rightsubseg);
+ }
+
+ /* Set the new origin of `deltri' and check its quality. */
+ org(lefttri, neworg);
+ setorg(*deltri, neworg);
+ if (!b->nobisect) {
+ testtriangle(m, b, deltri);
+ }
+
+ /* Delete the two spliced-out triangles. */
+ triangledealloc(m, lefttri.tri);
+ triangledealloc(m, righttri.tri);
+}
+
+#endif /* not CDT_ONLY */
+
+/*****************************************************************************/
+/* */
+/* undovertex() Undo the most recent vertex insertion. */
+/* */
+/* Walks through the list of transformations (flips and a vertex insertion) */
+/* in the reverse of the order in which they were done, and undoes them. */
+/* The inserted vertex is removed from the triangulation and deallocated. */
+/* Two triangles (possibly just one) are also deallocated. */
+/* */
+/*****************************************************************************/
+
+#ifndef CDT_ONLY
+
+#ifdef ANSI_DECLARATORS
+void undovertex(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void undovertex(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri fliptri;
+ struct otri botleft, botright, topright;
+ struct otri botlcasing, botrcasing, toprcasing;
+ struct otri gluetri;
+ struct osub botlsubseg, botrsubseg, toprsubseg;
+ vertex botvertex, rightvertex;
+ triangle ptr; /* Temporary variable used by sym(). */
+ subseg sptr; /* Temporary variable used by tspivot(). */
+
+ /* Walk through the list of transformations (flips and a vertex insertion) */
+ /* in the reverse of the order in which they were done, and undo them. */
+ while (m->lastflip != (struct flipstacker *) NULL) {
+ /* Find a triangle involved in the last unreversed transformation. */
+ decode(m->lastflip->flippedtri, fliptri);
+
+ /* We are reversing one of three transformations: a trisection of one */
+ /* triangle into three (by inserting a vertex in the triangle), a */
+ /* bisection of two triangles into four (by inserting a vertex in an */
+ /* edge), or an edge flip. */
+ if (m->lastflip->prevflip == (struct flipstacker *) NULL) {
+ /* Restore a triangle that was split into three triangles, */
+ /* so it is again one triangle. */
+ dprev(fliptri, botleft);
+ lnextself(botleft);
+ onext(fliptri, botright);
+ lprevself(botright);
+ sym(botleft, botlcasing);
+ sym(botright, botrcasing);
+ dest(botleft, botvertex);
+
+ setapex(fliptri, botvertex);
+ lnextself(fliptri);
+ bond(fliptri, botlcasing);
+ tspivot(botleft, botlsubseg);
+ tsbond(fliptri, botlsubseg);
+ lnextself(fliptri);
+ bond(fliptri, botrcasing);
+ tspivot(botright, botrsubseg);
+ tsbond(fliptri, botrsubseg);
+
+ /* Delete the two spliced-out triangles. */
+ triangledealloc(m, botleft.tri);
+ triangledealloc(m, botright.tri);
+ } else if (m->lastflip->prevflip == (struct flipstacker *) &insertvertex) {
+ /* Restore two triangles that were split into four triangles, */
+ /* so they are again two triangles. */
+ lprev(fliptri, gluetri);
+ sym(gluetri, botright);
+ lnextself(botright);
+ sym(botright, botrcasing);
+ dest(botright, rightvertex);
+
+ setorg(fliptri, rightvertex);
+ bond(gluetri, botrcasing);
+ tspivot(botright, botrsubseg);
+ tsbond(gluetri, botrsubseg);
+
+ /* Delete the spliced-out triangle. */
+ triangledealloc(m, botright.tri);
+
+ sym(fliptri, gluetri);
+ if (gluetri.tri != m->dummytri) {
+ lnextself(gluetri);
+ dnext(gluetri, topright);
+ sym(topright, toprcasing);
+
+ setorg(gluetri, rightvertex);
+ bond(gluetri, toprcasing);
+ tspivot(topright, toprsubseg);
+ tsbond(gluetri, toprsubseg);
+
+ /* Delete the spliced-out triangle. */
+ triangledealloc(m, topright.tri);
+ }
+
+ /* This is the end of the list, sneakily encoded. */
+ m->lastflip->prevflip = (struct flipstacker *) NULL;
+ } else {
+ /* Undo an edge flip. */
+ unflip(m, b, &fliptri);
+ }
+
+ /* Go on and process the next transformation. */
+ m->lastflip = m->lastflip->prevflip;
+ }
+}
+
+#endif /* not CDT_ONLY */
+
+/** **/
+/** **/
+/********* Mesh transformation routines end here *********/
+
+/********* Divide-and-conquer Delaunay triangulation begins here *********/
+/** **/
+/** **/
+
+/*****************************************************************************/
+/* */
+/* The divide-and-conquer bounding box */
+/* */
+/* I originally implemented the divide-and-conquer and incremental Delaunay */
+/* triangulations using the edge-based data structure presented by Guibas */
+/* and Stolfi. Switching to a triangle-based data structure doubled the */
+/* speed. However, I had to think of a few extra tricks to maintain the */
+/* elegance of the original algorithms. */
+/* */
+/* The "bounding box" used by my variant of the divide-and-conquer */
+/* algorithm uses one triangle for each edge of the convex hull of the */
+/* triangulation. These bounding triangles all share a common apical */
+/* vertex, which is represented by NULL and which represents nothing. */
+/* The bounding triangles are linked in a circular fan about this NULL */
+/* vertex, and the edges on the convex hull of the triangulation appear */
+/* opposite the NULL vertex. You might find it easiest to imagine that */
+/* the NULL vertex is a point in 3D space behind the center of the */
+/* triangulation, and that the bounding triangles form a sort of cone. */
+/* */
+/* This bounding box makes it easy to represent degenerate cases. For */
+/* instance, the triangulation of two vertices is a single edge. This edge */
+/* is represented by two bounding box triangles, one on each "side" of the */
+/* edge. These triangles are also linked together in a fan about the NULL */
+/* vertex. */
+/* */
+/* The bounding box also makes it easy to traverse the convex hull, as the */
+/* divide-and-conquer algorithm needs to do. */
+/* */
+/*****************************************************************************/
+
+/*****************************************************************************/
+/* */
+/* vertexsort() Sort an array of vertices by x-coordinate, using the */
+/* y-coordinate as a secondary key. */
+/* */
+/* Uses quicksort. Randomized O(n log n) time. No, I did not make any of */
+/* the usual quicksort mistakes. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void vertexsort(vertex *sortarray, int arraysize)
+#else /* not ANSI_DECLARATORS */
+void vertexsort(sortarray, arraysize)
+vertex *sortarray;
+int arraysize;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ int left, right;
+ int pivot;
+ REAL pivotx, pivoty;
+ vertex temp;
+
+ if (arraysize == 2) {
+ /* Recursive base case. */
+ if ((sortarray[0][0] > sortarray[1][0]) ||
+ ((sortarray[0][0] == sortarray[1][0]) &&
+ (sortarray[0][1] > sortarray[1][1]))) {
+ temp = sortarray[1];
+ sortarray[1] = sortarray[0];
+ sortarray[0] = temp;
+ }
+ return;
+ }
+ /* Choose a random pivot to split the array. */
+ pivot = (int) randomnation((unsigned int) arraysize);
+ pivotx = sortarray[pivot][0];
+ pivoty = sortarray[pivot][1];
+ /* Split the array. */
+ left = -1;
+ right = arraysize;
+ while (left < right) {
+ /* Search for a vertex whose x-coordinate is too large for the left. */
+ do {
+ left++;
+ } while ((left <= right) && ((sortarray[left][0] < pivotx) ||
+ ((sortarray[left][0] == pivotx) &&
+ (sortarray[left][1] < pivoty))));
+ /* Search for a vertex whose x-coordinate is too small for the right. */
+ do {
+ right--;
+ } while ((left <= right) && ((sortarray[right][0] > pivotx) ||
+ ((sortarray[right][0] == pivotx) &&
+ (sortarray[right][1] > pivoty))));
+ if (left < right) {
+ /* Swap the left and right vertices. */
+ temp = sortarray[left];
+ sortarray[left] = sortarray[right];
+ sortarray[right] = temp;
+ }
+ }
+ if (left > 1) {
+ /* Recursively sort the left subset. */
+ vertexsort(sortarray, left);
+ }
+ if (right < arraysize - 2) {
+ /* Recursively sort the right subset. */
+ vertexsort(&sortarray[right + 1], arraysize - right - 1);
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* vertexmedian() An order statistic algorithm, almost. Shuffles an */
+/* array of vertices so that the first `median' vertices */
+/* occur lexicographically before the remaining vertices. */
+/* */
+/* Uses the x-coordinate as the primary key if axis == 0; the y-coordinate */
+/* if axis == 1. Very similar to the vertexsort() procedure, but runs in */
+/* randomized linear time. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void vertexmedian(vertex *sortarray, int arraysize, int median, int axis)
+#else /* not ANSI_DECLARATORS */
+void vertexmedian(sortarray, arraysize, median, axis)
+vertex *sortarray;
+int arraysize;
+int median;
+int axis;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ int left, right;
+ int pivot;
+ REAL pivot1, pivot2;
+ vertex temp;
+
+ if (arraysize == 2) {
+ /* Recursive base case. */
+ if ((sortarray[0][axis] > sortarray[1][axis]) ||
+ ((sortarray[0][axis] == sortarray[1][axis]) &&
+ (sortarray[0][1 - axis] > sortarray[1][1 - axis]))) {
+ temp = sortarray[1];
+ sortarray[1] = sortarray[0];
+ sortarray[0] = temp;
+ }
+ return;
+ }
+ /* Choose a random pivot to split the array. */
+ pivot = (int) randomnation((unsigned int) arraysize);
+ pivot1 = sortarray[pivot][axis];
+ pivot2 = sortarray[pivot][1 - axis];
+ /* Split the array. */
+ left = -1;
+ right = arraysize;
+ while (left < right) {
+ /* Search for a vertex whose x-coordinate is too large for the left. */
+ do {
+ left++;
+ } while ((left <= right) && ((sortarray[left][axis] < pivot1) ||
+ ((sortarray[left][axis] == pivot1) &&
+ (sortarray[left][1 - axis] < pivot2))));
+ /* Search for a vertex whose x-coordinate is too small for the right. */
+ do {
+ right--;
+ } while ((left <= right) && ((sortarray[right][axis] > pivot1) ||
+ ((sortarray[right][axis] == pivot1) &&
+ (sortarray[right][1 - axis] > pivot2))));
+ if (left < right) {
+ /* Swap the left and right vertices. */
+ temp = sortarray[left];
+ sortarray[left] = sortarray[right];
+ sortarray[right] = temp;
+ }
+ }
+ /* Unlike in vertexsort(), at most one of the following */
+ /* conditionals is true. */
+ if (left > median) {
+ /* Recursively shuffle the left subset. */
+ vertexmedian(sortarray, left, median, axis);
+ }
+ if (right < median - 1) {
+ /* Recursively shuffle the right subset. */
+ vertexmedian(&sortarray[right + 1], arraysize - right - 1,
+ median - right - 1, axis);
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* alternateaxes() Sorts the vertices as appropriate for the divide-and- */
+/* conquer algorithm with alternating cuts. */
+/* */
+/* Partitions by x-coordinate if axis == 0; by y-coordinate if axis == 1. */
+/* For the base case, subsets containing only two or three vertices are */
+/* always sorted by x-coordinate. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void alternateaxes(vertex *sortarray, int arraysize, int axis)
+#else /* not ANSI_DECLARATORS */
+void alternateaxes(sortarray, arraysize, axis)
+vertex *sortarray;
+int arraysize;
+int axis;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ int divider;
+
+ divider = arraysize >> 1;
+ if (arraysize <= 3) {
+ /* Recursive base case: subsets of two or three vertices will be */
+ /* handled specially, and should always be sorted by x-coordinate. */
+ axis = 0;
+ }
+ /* Partition with a horizontal or vertical cut. */
+ vertexmedian(sortarray, arraysize, divider, axis);
+ /* Recursively partition the subsets with a cross cut. */
+ if (arraysize - divider >= 2) {
+ if (divider >= 2) {
+ alternateaxes(sortarray, divider, 1 - axis);
+ }
+ alternateaxes(&sortarray[divider], arraysize - divider, 1 - axis);
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* mergehulls() Merge two adjacent Delaunay triangulations into a */
+/* single Delaunay triangulation. */
+/* */
+/* This is similar to the algorithm given by Guibas and Stolfi, but uses */
+/* a triangle-based, rather than edge-based, data structure. */
+/* */
+/* The algorithm walks up the gap between the two triangulations, knitting */
+/* them together. As they are merged, some of their bounding triangles */
+/* are converted into real triangles of the triangulation. The procedure */
+/* pulls each hull's bounding triangles apart, then knits them together */
+/* like the teeth of two gears. The Delaunay property determines, at each */
+/* step, whether the next "tooth" is a bounding triangle of the left hull */
+/* or the right. When a bounding triangle becomes real, its apex is */
+/* changed from NULL to a real vertex. */
+/* */
+/* Only two new triangles need to be allocated. These become new bounding */
+/* triangles at the top and bottom of the seam. They are used to connect */
+/* the remaining bounding triangles (those that have not been converted */
+/* into real triangles) into a single fan. */
+/* */
+/* On entry, `farleft' and `innerleft' are bounding triangles of the left */
+/* triangulation. The origin of `farleft' is the leftmost vertex, and */
+/* the destination of `innerleft' is the rightmost vertex of the */
+/* triangulation. Similarly, `innerright' and `farright' are bounding */
+/* triangles of the right triangulation. The origin of `innerright' and */
+/* destination of `farright' are the leftmost and rightmost vertices. */
+/* */
+/* On completion, the origin of `farleft' is the leftmost vertex of the */
+/* merged triangulation, and the destination of `farright' is the rightmost */
+/* vertex. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void mergehulls(struct mesh *m, struct behavior *b, struct otri *farleft,
+ struct otri *innerleft, struct otri *innerright,
+ struct otri *farright, int axis)
+#else /* not ANSI_DECLARATORS */
+void mergehulls(m, b, farleft, innerleft, innerright, farright, axis)
+struct mesh *m;
+struct behavior *b;
+struct otri *farleft;
+struct otri *innerleft;
+struct otri *innerright;
+struct otri *farright;
+int axis;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri leftcand, rightcand;
+ struct otri baseedge;
+ struct otri nextedge;
+ struct otri sidecasing, topcasing, outercasing;
+ struct otri checkedge;
+ vertex innerleftdest;
+ vertex innerrightorg;
+ vertex innerleftapex, innerrightapex;
+ vertex farleftpt, farrightpt;
+ vertex farleftapex, farrightapex;
+ vertex lowerleft, lowerright;
+ vertex upperleft, upperright;
+ vertex nextapex;
+ vertex checkvertex;
+ int changemade;
+ int badedge;
+ int leftfinished, rightfinished;
+ triangle ptr; /* Temporary variable used by sym(). */
+
+ dest(*innerleft, innerleftdest);
+ apex(*innerleft, innerleftapex);
+ org(*innerright, innerrightorg);
+ apex(*innerright, innerrightapex);
+ /* Special treatment for horizontal cuts. */
+ if (b->dwyer && (axis == 1)) {
+ org(*farleft, farleftpt);
+ apex(*farleft, farleftapex);
+ dest(*farright, farrightpt);
+ apex(*farright, farrightapex);
+ /* The pointers to the extremal vertices are shifted to point to the */
+ /* topmost and bottommost vertex of each hull, rather than the */
+ /* leftmost and rightmost vertices. */
+ while (farleftapex[1] < farleftpt[1]) {
+ lnextself(*farleft);
+ symself(*farleft);
+ farleftpt = farleftapex;
+ apex(*farleft, farleftapex);
+ }
+ sym(*innerleft, checkedge);
+ apex(checkedge, checkvertex);
+ while (checkvertex[1] > innerleftdest[1]) {
+ lnext(checkedge, *innerleft);
+ innerleftapex = innerleftdest;
+ innerleftdest = checkvertex;
+ sym(*innerleft, checkedge);
+ apex(checkedge, checkvertex);
+ }
+ while (innerrightapex[1] < innerrightorg[1]) {
+ lnextself(*innerright);
+ symself(*innerright);
+ innerrightorg = innerrightapex;
+ apex(*innerright, innerrightapex);
+ }
+ sym(*farright, checkedge);
+ apex(checkedge, checkvertex);
+ while (checkvertex[1] > farrightpt[1]) {
+ lnext(checkedge, *farright);
+ farrightapex = farrightpt;
+ farrightpt = checkvertex;
+ sym(*farright, checkedge);
+ apex(checkedge, checkvertex);
+ }
+ }
+ /* Find a line tangent to and below both hulls. */
+ do {
+ changemade = 0;
+ /* Make innerleftdest the "bottommost" vertex of the left hull. */
+ if (counterclockwise(m, b, innerleftdest, innerleftapex, innerrightorg) >
+ 0.0) {
+ lprevself(*innerleft);
+ symself(*innerleft);
+ innerleftdest = innerleftapex;
+ apex(*innerleft, innerleftapex);
+ changemade = 1;
+ }
+ /* Make innerrightorg the "bottommost" vertex of the right hull. */
+ if (counterclockwise(m, b, innerrightapex, innerrightorg, innerleftdest) >
+ 0.0) {
+ lnextself(*innerright);
+ symself(*innerright);
+ innerrightorg = innerrightapex;
+ apex(*innerright, innerrightapex);
+ changemade = 1;
+ }
+ } while (changemade);
+ /* Find the two candidates to be the next "gear tooth." */
+ sym(*innerleft, leftcand);
+ sym(*innerright, rightcand);
+ /* Create the bottom new bounding triangle. */
+ maketriangle(m, b, &baseedge);
+ /* Connect it to the bounding boxes of the left and right triangulations. */
+ bond(baseedge, *innerleft);
+ lnextself(baseedge);
+ bond(baseedge, *innerright);
+ lnextself(baseedge);
+ setorg(baseedge, innerrightorg);
+ setdest(baseedge, innerleftdest);
+ /* Apex is intentionally left NULL. */
+ if (b->verbose > 2) {
+ printf(" Creating base bounding ");
+ printtriangle(m, b, &baseedge);
+ }
+ /* Fix the extreme triangles if necessary. */
+ org(*farleft, farleftpt);
+ if (innerleftdest == farleftpt) {
+ lnext(baseedge, *farleft);
+ }
+ dest(*farright, farrightpt);
+ if (innerrightorg == farrightpt) {
+ lprev(baseedge, *farright);
+ }
+ /* The vertices of the current knitting edge. */
+ lowerleft = innerleftdest;
+ lowerright = innerrightorg;
+ /* The candidate vertices for knitting. */
+ apex(leftcand, upperleft);
+ apex(rightcand, upperright);
+ /* Walk up the gap between the two triangulations, knitting them together. */
+ while (1) {
+ /* Have we reached the top? (This isn't quite the right question, */
+ /* because even though the left triangulation might seem finished now, */
+ /* moving up on the right triangulation might reveal a new vertex of */
+ /* the left triangulation. And vice-versa.) */
+ leftfinished = counterclockwise(m, b, upperleft, lowerleft, lowerright) <=
+ 0.0;
+ rightfinished = counterclockwise(m, b, upperright, lowerleft, lowerright)
+ <= 0.0;
+ if (leftfinished && rightfinished) {
+ /* Create the top new bounding triangle. */
+ maketriangle(m, b, &nextedge);
+ setorg(nextedge, lowerleft);
+ setdest(nextedge, lowerright);
+ /* Apex is intentionally left NULL. */
+ /* Connect it to the bounding boxes of the two triangulations. */
+ bond(nextedge, baseedge);
+ lnextself(nextedge);
+ bond(nextedge, rightcand);
+ lnextself(nextedge);
+ bond(nextedge, leftcand);
+ if (b->verbose > 2) {
+ printf(" Creating top bounding ");
+ printtriangle(m, b, &nextedge);
+ }
+ /* Special treatment for horizontal cuts. */
+ if (b->dwyer && (axis == 1)) {
+ org(*farleft, farleftpt);
+ apex(*farleft, farleftapex);
+ dest(*farright, farrightpt);
+ apex(*farright, farrightapex);
+ sym(*farleft, checkedge);
+ apex(checkedge, checkvertex);
+ /* The pointers to the extremal vertices are restored to the */
+ /* leftmost and rightmost vertices (rather than topmost and */
+ /* bottommost). */
+ while (checkvertex[0] < farleftpt[0]) {
+ lprev(checkedge, *farleft);
+ farleftapex = farleftpt;
+ farleftpt = checkvertex;
+ sym(*farleft, checkedge);
+ apex(checkedge, checkvertex);
+ }
+ while (farrightapex[0] > farrightpt[0]) {
+ lprevself(*farright);
+ symself(*farright);
+ farrightpt = farrightapex;
+ apex(*farright, farrightapex);
+ }
+ }
+ return;
+ }
+ /* Consider eliminating edges from the left triangulation. */
+ if (!leftfinished) {
+ /* What vertex would be exposed if an edge were deleted? */
+ lprev(leftcand, nextedge);
+ symself(nextedge);
+ apex(nextedge, nextapex);
+ /* If nextapex is NULL, then no vertex would be exposed; the */
+ /* triangulation would have been eaten right through. */
+ if (nextapex != (vertex) NULL) {
+ /* Check whether the edge is Delaunay. */
+ badedge = incircle(m, b, lowerleft, lowerright, upperleft, nextapex) >
+ 0.0;
+ while (badedge) {
+ /* Eliminate the edge with an edge flip. As a result, the */
+ /* left triangulation will have one more boundary triangle. */
+ lnextself(nextedge);
+ sym(nextedge, topcasing);
+ lnextself(nextedge);
+ sym(nextedge, sidecasing);
+ bond(nextedge, topcasing);
+ bond(leftcand, sidecasing);
+ lnextself(leftcand);
+ sym(leftcand, outercasing);
+ lprevself(nextedge);
+ bond(nextedge, outercasing);
+ /* Correct the vertices to reflect the edge flip. */
+ setorg(leftcand, lowerleft);
+ setdest(leftcand, NULL);
+ setapex(leftcand, nextapex);
+ setorg(nextedge, NULL);
+ setdest(nextedge, upperleft);
+ setapex(nextedge, nextapex);
+ /* Consider the newly exposed vertex. */
+ upperleft = nextapex;
+ /* What vertex would be exposed if another edge were deleted? */
+ otricopy(sidecasing, nextedge);
+ apex(nextedge, nextapex);
+ if (nextapex != (vertex) NULL) {
+ /* Check whether the edge is Delaunay. */
+ badedge = incircle(m, b, lowerleft, lowerright, upperleft,
+ nextapex) > 0.0;
+ } else {
+ /* Avoid eating right through the triangulation. */
+ badedge = 0;
+ }
+ }
+ }
+ }
+ /* Consider eliminating edges from the right triangulation. */
+ if (!rightfinished) {
+ /* What vertex would be exposed if an edge were deleted? */
+ lnext(rightcand, nextedge);
+ symself(nextedge);
+ apex(nextedge, nextapex);
+ /* If nextapex is NULL, then no vertex would be exposed; the */
+ /* triangulation would have been eaten right through. */
+ if (nextapex != (vertex) NULL) {
+ /* Check whether the edge is Delaunay. */
+ badedge = incircle(m, b, lowerleft, lowerright, upperright, nextapex) >
+ 0.0;
+ while (badedge) {
+ /* Eliminate the edge with an edge flip. As a result, the */
+ /* right triangulation will have one more boundary triangle. */
+ lprevself(nextedge);
+ sym(nextedge, topcasing);
+ lprevself(nextedge);
+ sym(nextedge, sidecasing);
+ bond(nextedge, topcasing);
+ bond(rightcand, sidecasing);
+ lprevself(rightcand);
+ sym(rightcand, outercasing);
+ lnextself(nextedge);
+ bond(nextedge, outercasing);
+ /* Correct the vertices to reflect the edge flip. */
+ setorg(rightcand, NULL);
+ setdest(rightcand, lowerright);
+ setapex(rightcand, nextapex);
+ setorg(nextedge, upperright);
+ setdest(nextedge, NULL);
+ setapex(nextedge, nextapex);
+ /* Consider the newly exposed vertex. */
+ upperright = nextapex;
+ /* What vertex would be exposed if another edge were deleted? */
+ otricopy(sidecasing, nextedge);
+ apex(nextedge, nextapex);
+ if (nextapex != (vertex) NULL) {
+ /* Check whether the edge is Delaunay. */
+ badedge = incircle(m, b, lowerleft, lowerright, upperright,
+ nextapex) > 0.0;
+ } else {
+ /* Avoid eating right through the triangulation. */
+ badedge = 0;
+ }
+ }
+ }
+ }
+ if (leftfinished || (!rightfinished &&
+ (incircle(m, b, upperleft, lowerleft, lowerright, upperright) >
+ 0.0))) {
+ /* Knit the triangulations, adding an edge from `lowerleft' */
+ /* to `upperright'. */
+ bond(baseedge, rightcand);
+ lprev(rightcand, baseedge);
+ setdest(baseedge, lowerleft);
+ lowerright = upperright;
+ sym(baseedge, rightcand);
+ apex(rightcand, upperright);
+ } else {
+ /* Knit the triangulations, adding an edge from `upperleft' */
+ /* to `lowerright'. */
+ bond(baseedge, leftcand);
+ lnext(leftcand, baseedge);
+ setorg(baseedge, lowerright);
+ lowerleft = upperleft;
+ sym(baseedge, leftcand);
+ apex(leftcand, upperleft);
+ }
+ if (b->verbose > 2) {
+ printf(" Connecting ");
+ printtriangle(m, b, &baseedge);
+ }
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* divconqrecurse() Recursively form a Delaunay triangulation by the */
+/* divide-and-conquer method. */
+/* */
+/* Recursively breaks down the problem into smaller pieces, which are */
+/* knitted together by mergehulls(). The base cases (problems of two or */
+/* three vertices) are handled specially here. */
+/* */
+/* On completion, `farleft' and `farright' are bounding triangles such that */
+/* the origin of `farleft' is the leftmost vertex (breaking ties by */
+/* choosing the highest leftmost vertex), and the destination of */
+/* `farright' is the rightmost vertex (breaking ties by choosing the */
+/* lowest rightmost vertex). */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void divconqrecurse(struct mesh *m, struct behavior *b, vertex *sortarray,
+ int vertices, int axis,
+ struct otri *farleft, struct otri *farright)
+#else /* not ANSI_DECLARATORS */
+void divconqrecurse(m, b, sortarray, vertices, axis, farleft, farright)
+struct mesh *m;
+struct behavior *b;
+vertex *sortarray;
+int vertices;
+int axis;
+struct otri *farleft;
+struct otri *farright;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri midtri, tri1, tri2, tri3;
+ struct otri innerleft, innerright;
+ REAL area;
+ int divider;
+
+ if (b->verbose > 2) {
+ printf(" Triangulating %d vertices.\n", vertices);
+ }
+ if (vertices == 2) {
+ /* The triangulation of two vertices is an edge. An edge is */
+ /* represented by two bounding triangles. */
+ maketriangle(m, b, farleft);
+ setorg(*farleft, sortarray[0]);
+ setdest(*farleft, sortarray[1]);
+ /* The apex is intentionally left NULL. */
+ maketriangle(m, b, farright);
+ setorg(*farright, sortarray[1]);
+ setdest(*farright, sortarray[0]);
+ /* The apex is intentionally left NULL. */
+ bond(*farleft, *farright);
+ lprevself(*farleft);
+ lnextself(*farright);
+ bond(*farleft, *farright);
+ lprevself(*farleft);
+ lnextself(*farright);
+ bond(*farleft, *farright);
+ if (b->verbose > 2) {
+ printf(" Creating ");
+ printtriangle(m, b, farleft);
+ printf(" Creating ");
+ printtriangle(m, b, farright);
+ }
+ /* Ensure that the origin of `farleft' is sortarray[0]. */
+ lprev(*farright, *farleft);
+ return;
+ } else if (vertices == 3) {
+ /* The triangulation of three vertices is either a triangle (with */
+ /* three bounding triangles) or two edges (with four bounding */
+ /* triangles). In either case, four triangles are created. */
+ maketriangle(m, b, &midtri);
+ maketriangle(m, b, &tri1);
+ maketriangle(m, b, &tri2);
+ maketriangle(m, b, &tri3);
+ area = counterclockwise(m, b, sortarray[0], sortarray[1], sortarray[2]);
+ if (area == 0.0) {
+ /* Three collinear vertices; the triangulation is two edges. */
+ setorg(midtri, sortarray[0]);
+ setdest(midtri, sortarray[1]);
+ setorg(tri1, sortarray[1]);
+ setdest(tri1, sortarray[0]);
+ setorg(tri2, sortarray[2]);
+ setdest(tri2, sortarray[1]);
+ setorg(tri3, sortarray[1]);
+ setdest(tri3, sortarray[2]);
+ /* All apices are intentionally left NULL. */
+ bond(midtri, tri1);
+ bond(tri2, tri3);
+ lnextself(midtri);
+ lprevself(tri1);
+ lnextself(tri2);
+ lprevself(tri3);
+ bond(midtri, tri3);
+ bond(tri1, tri2);
+ lnextself(midtri);
+ lprevself(tri1);
+ lnextself(tri2);
+ lprevself(tri3);
+ bond(midtri, tri1);
+ bond(tri2, tri3);
+ /* Ensure that the origin of `farleft' is sortarray[0]. */
+ otricopy(tri1, *farleft);
+ /* Ensure that the destination of `farright' is sortarray[2]. */
+ otricopy(tri2, *farright);
+ } else {
+ /* The three vertices are not collinear; the triangulation is one */
+ /* triangle, namely `midtri'. */
+ setorg(midtri, sortarray[0]);
+ setdest(tri1, sortarray[0]);
+ setorg(tri3, sortarray[0]);
+ /* Apices of tri1, tri2, and tri3 are left NULL. */
+ if (area > 0.0) {
+ /* The vertices are in counterclockwise order. */
+ setdest(midtri, sortarray[1]);
+ setorg(tri1, sortarray[1]);
+ setdest(tri2, sortarray[1]);
+ setapex(midtri, sortarray[2]);
+ setorg(tri2, sortarray[2]);
+ setdest(tri3, sortarray[2]);
+ } else {
+ /* The vertices are in clockwise order. */
+ setdest(midtri, sortarray[2]);
+ setorg(tri1, sortarray[2]);
+ setdest(tri2, sortarray[2]);
+ setapex(midtri, sortarray[1]);
+ setorg(tri2, sortarray[1]);
+ setdest(tri3, sortarray[1]);
+ }
+ /* The topology does not depend on how the vertices are ordered. */
+ bond(midtri, tri1);
+ lnextself(midtri);
+ bond(midtri, tri2);
+ lnextself(midtri);
+ bond(midtri, tri3);
+ lprevself(tri1);
+ lnextself(tri2);
+ bond(tri1, tri2);
+ lprevself(tri1);
+ lprevself(tri3);
+ bond(tri1, tri3);
+ lnextself(tri2);
+ lprevself(tri3);
+ bond(tri2, tri3);
+ /* Ensure that the origin of `farleft' is sortarray[0]. */
+ otricopy(tri1, *farleft);
+ /* Ensure that the destination of `farright' is sortarray[2]. */
+ if (area > 0.0) {
+ otricopy(tri2, *farright);
+ } else {
+ lnext(*farleft, *farright);
+ }
+ }
+ if (b->verbose > 2) {
+ printf(" Creating ");
+ printtriangle(m, b, &midtri);
+ printf(" Creating ");
+ printtriangle(m, b, &tri1);
+ printf(" Creating ");
+ printtriangle(m, b, &tri2);
+ printf(" Creating ");
+ printtriangle(m, b, &tri3);
+ }
+ return;
+ } else {
+ /* Split the vertices in half. */
+ divider = vertices >> 1;
+ /* Recursively triangulate each half. */
+ divconqrecurse(m, b, sortarray, divider, 1 - axis, farleft, &innerleft);
+ divconqrecurse(m, b, &sortarray[divider], vertices - divider, 1 - axis,
+ &innerright, farright);
+ if (b->verbose > 1) {
+ printf(" Joining triangulations with %d and %d vertices.\n", divider,
+ vertices - divider);
+ }
+ /* Merge the two triangulations into one. */
+ mergehulls(m, b, farleft, &innerleft, &innerright, farright, axis);
+ }
+}
+
+#ifdef ANSI_DECLARATORS
+long removeghosts(struct mesh *m, struct behavior *b, struct otri *startghost)
+#else /* not ANSI_DECLARATORS */
+long removeghosts(m, b, startghost)
+struct mesh *m;
+struct behavior *b;
+struct otri *startghost;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri searchedge;
+ struct otri dissolveedge;
+ struct otri deadtriangle;
+ vertex markorg;
+ long hullsize;
+ triangle ptr; /* Temporary variable used by sym(). */
+
+ if (b->verbose) {
+ printf(" Removing ghost triangles.\n");
+ }
+ /* Find an edge on the convex hull to start point location from. */
+ lprev(*startghost, searchedge);
+ symself(searchedge);
+ m->dummytri[0] = encode(searchedge);
+ /* Remove the bounding box and count the convex hull edges. */
+ otricopy(*startghost, dissolveedge);
+ hullsize = 0;
+ do {
+ hullsize++;
+ lnext(dissolveedge, deadtriangle);
+ lprevself(dissolveedge);
+ symself(dissolveedge);
+ /* If no PSLG is involved, set the boundary markers of all the vertices */
+ /* on the convex hull. If a PSLG is used, this step is done later. */
+ if (!b->poly) {
+ /* Watch out for the case where all the input vertices are collinear. */
+ if (dissolveedge.tri != m->dummytri) {
+ org(dissolveedge, markorg);
+ if (vertexmark(markorg) == 0) {
+ setvertexmark(markorg, 1);
+ }
+ }
+ }
+ /* Remove a bounding triangle from a convex hull triangle. */
+ dissolve(dissolveedge);
+ /* Find the next bounding triangle. */
+ sym(deadtriangle, dissolveedge);
+ /* Delete the bounding triangle. */
+ triangledealloc(m, deadtriangle.tri);
+ } while (!otriequal(dissolveedge, *startghost));
+ return hullsize;
+}
+
+/*****************************************************************************/
+/* */
+/* divconqdelaunay() Form a Delaunay triangulation by the divide-and- */
+/* conquer method. */
+/* */
+/* Sorts the vertices, calls a recursive procedure to triangulate them, and */
+/* removes the bounding box, setting boundary markers as appropriate. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+long divconqdelaunay(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+long divconqdelaunay(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ vertex *sortarray;
+ struct otri hullleft, hullright;
+ int divider;
+ int i, j;
+
+ if (b->verbose) {
+ printf(" Sorting vertices.\n");
+ }
+
+ /* Allocate an array of pointers to vertices for sorting. */
+ sortarray = (vertex *) trimalloc(m->invertices * (int) sizeof(vertex));
+ traversalinit(&m->vertices);
+ for (i = 0; i < m->invertices; i++) {
+ sortarray[i] = vertextraverse(m);
+ }
+ /* Sort the vertices. */
+ vertexsort(sortarray, m->invertices);
+ /* Discard duplicate vertices, which can really mess up the algorithm. */
+ i = 0;
+ for (j = 1; j < m->invertices; j++) {
+ if ((sortarray[i][0] == sortarray[j][0])
+ && (sortarray[i][1] == sortarray[j][1])) {
+ if (!b->quiet) {
+ printf(
+"Warning: A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
+ sortarray[j][0], sortarray[j][1]);
+ }
+ setvertextype(sortarray[j], UNDEADVERTEX);
+ m->undeads++;
+ } else {
+ i++;
+ sortarray[i] = sortarray[j];
+ }
+ }
+ i++;
+ if (b->dwyer) {
+ /* Re-sort the array of vertices to accommodate alternating cuts. */
+ divider = i >> 1;
+ if (i - divider >= 2) {
+ if (divider >= 2) {
+ alternateaxes(sortarray, divider, 1);
+ }
+ alternateaxes(&sortarray[divider], i - divider, 1);
+ }
+ }
+
+ if (b->verbose) {
+ printf(" Forming triangulation.\n");
+ }
+
+ /* Form the Delaunay triangulation. */
+ divconqrecurse(m, b, sortarray, i, 0, &hullleft, &hullright);
+ trifree((VOID *) sortarray);
+
+ return removeghosts(m, b, &hullleft);
+}
+
+/** **/
+/** **/
+/********* Divide-and-conquer Delaunay triangulation ends here *********/
+
+/********* Incremental Delaunay triangulation begins here *********/
+/** **/
+/** **/
+
+/*****************************************************************************/
+/* */
+/* boundingbox() Form an "infinite" bounding triangle to insert vertices */
+/* into. */
+/* */
+/* The vertices at "infinity" are assigned finite coordinates, which are */
+/* used by the point location routines, but (mostly) ignored by the */
+/* Delaunay edge flip routines. */
+/* */
+/*****************************************************************************/
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+void boundingbox(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void boundingbox(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri inftri; /* Handle for the triangular bounding box. */
+ REAL width;
+
+ if (b->verbose) {
+ printf(" Creating triangular bounding box.\n");
+ }
+ /* Find the width (or height, whichever is larger) of the triangulation. */
+ width = m->xmax - m->xmin;
+ if (m->ymax - m->ymin > width) {
+ width = m->ymax - m->ymin;
+ }
+ if (width == 0.0) {
+ width = 1.0;
+ }
+ /* Create the vertices of the bounding box. */
+ m->infvertex1 = (vertex) trimalloc(m->vertices.itembytes);
+ m->infvertex2 = (vertex) trimalloc(m->vertices.itembytes);
+ m->infvertex3 = (vertex) trimalloc(m->vertices.itembytes);
+ m->infvertex1[0] = m->xmin - 50.0 * width;
+ m->infvertex1[1] = m->ymin - 40.0 * width;
+ m->infvertex2[0] = m->xmax + 50.0 * width;
+ m->infvertex2[1] = m->ymin - 40.0 * width;
+ m->infvertex3[0] = 0.5 * (m->xmin + m->xmax);
+ m->infvertex3[1] = m->ymax + 60.0 * width;
+
+ /* Create the bounding box. */
+ maketriangle(m, b, &inftri);
+ setorg(inftri, m->infvertex1);
+ setdest(inftri, m->infvertex2);
+ setapex(inftri, m->infvertex3);
+ /* Link dummytri to the bounding box so we can always find an */
+ /* edge to begin searching (point location) from. */
+ m->dummytri[0] = (triangle) inftri.tri;
+ if (b->verbose > 2) {
+ printf(" Creating ");
+ printtriangle(m, b, &inftri);
+ }
+}
+
+#endif /* not REDUCED */
+
+/*****************************************************************************/
+/* */
+/* removebox() Remove the "infinite" bounding triangle, setting boundary */
+/* markers as appropriate. */
+/* */
+/* The triangular bounding box has three boundary triangles (one for each */
+/* side of the bounding box), and a bunch of triangles fanning out from */
+/* the three bounding box vertices (one triangle for each edge of the */
+/* convex hull of the inner mesh). This routine removes these triangles. */
+/* */
+/* Returns the number of edges on the convex hull of the triangulation. */
+/* */
+/*****************************************************************************/
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+long removebox(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+long removebox(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri deadtriangle;
+ struct otri searchedge;
+ struct otri checkedge;
+ struct otri nextedge, finaledge, dissolveedge;
+ vertex markorg;
+ long hullsize;
+ triangle ptr; /* Temporary variable used by sym(). */
+
+ if (b->verbose) {
+ printf(" Removing triangular bounding box.\n");
+ }
+ /* Find a boundary triangle. */
+ nextedge.tri = m->dummytri;
+ nextedge.orient = 0;
+ symself(nextedge);
+ /* Mark a place to stop. */
+ lprev(nextedge, finaledge);
+ lnextself(nextedge);
+ symself(nextedge);
+ /* Find a triangle (on the boundary of the vertex set) that isn't */
+ /* a bounding box triangle. */
+ lprev(nextedge, searchedge);
+ symself(searchedge);
+ /* Check whether nextedge is another boundary triangle */
+ /* adjacent to the first one. */
+ lnext(nextedge, checkedge);
+ symself(checkedge);
+ if (checkedge.tri == m->dummytri) {
+ /* Go on to the next triangle. There are only three boundary */
+ /* triangles, and this next triangle cannot be the third one, */
+ /* so it's safe to stop here. */
+ lprevself(searchedge);
+ symself(searchedge);
+ }
+ /* Find a new boundary edge to search from, as the current search */
+ /* edge lies on a bounding box triangle and will be deleted. */
+ m->dummytri[0] = encode(searchedge);
+ hullsize = -2l;
+ while (!otriequal(nextedge, finaledge)) {
+ hullsize++;
+ lprev(nextedge, dissolveedge);
+ symself(dissolveedge);
+ /* If not using a PSLG, the vertices should be marked now. */
+ /* (If using a PSLG, markhull() will do the job.) */
+ if (!b->poly) {
+ /* Be careful! One must check for the case where all the input */
+ /* vertices are collinear, and thus all the triangles are part of */
+ /* the bounding box. Otherwise, the setvertexmark() call below */
+ /* will cause a bad pointer reference. */
+ if (dissolveedge.tri != m->dummytri) {
+ org(dissolveedge, markorg);
+ if (vertexmark(markorg) == 0) {
+ setvertexmark(markorg, 1);
+ }
+ }
+ }
+ /* Disconnect the bounding box triangle from the mesh triangle. */
+ dissolve(dissolveedge);
+ lnext(nextedge, deadtriangle);
+ sym(deadtriangle, nextedge);
+ /* Get rid of the bounding box triangle. */
+ triangledealloc(m, deadtriangle.tri);
+ /* Do we need to turn the corner? */
+ if (nextedge.tri == m->dummytri) {
+ /* Turn the corner. */
+ otricopy(dissolveedge, nextedge);
+ }
+ }
+ triangledealloc(m, finaledge.tri);
+
+ trifree((VOID *) m->infvertex1); /* Deallocate the bounding box vertices. */
+ trifree((VOID *) m->infvertex2);
+ trifree((VOID *) m->infvertex3);
+
+ return hullsize;
+}
+
+#endif /* not REDUCED */
+
+/*****************************************************************************/
+/* */
+/* incrementaldelaunay() Form a Delaunay triangulation by incrementally */
+/* inserting vertices. */
+/* */
+/* Returns the number of edges on the convex hull of the triangulation. */
+/* */
+/*****************************************************************************/
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+long incrementaldelaunay(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+long incrementaldelaunay(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri starttri;
+ vertex vertexloop;
+
+ /* Create a triangular bounding box. */
+ boundingbox(m, b);
+ if (b->verbose) {
+ printf(" Incrementally inserting vertices.\n");
+ }
+ traversalinit(&m->vertices);
+ vertexloop = vertextraverse(m);
+ while (vertexloop != (vertex) NULL) {
+ starttri.tri = m->dummytri;
+ if (insertvertex(m, b, vertexloop, &starttri, (struct osub *) NULL, 0, 0)
+ == DUPLICATEVERTEX) {
+ if (!b->quiet) {
+ printf(
+"Warning: A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
+ vertexloop[0], vertexloop[1]);
+ }
+ setvertextype(vertexloop, UNDEADVERTEX);
+ m->undeads++;
+ }
+ vertexloop = vertextraverse(m);
+ }
+ /* Remove the bounding box. */
+ return removebox(m, b);
+}
+
+#endif /* not REDUCED */
+
+/** **/
+/** **/
+/********* Incremental Delaunay triangulation ends here *********/
+
+/********* Sweepline Delaunay triangulation begins here *********/
+/** **/
+/** **/
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+void eventheapinsert(struct event **heap, int heapsize, struct event *newevent)
+#else /* not ANSI_DECLARATORS */
+void eventheapinsert(heap, heapsize, newevent)
+struct event **heap;
+int heapsize;
+struct event *newevent;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ REAL eventx, eventy;
+ int eventnum;
+ int parent;
+ int notdone;
+
+ eventx = newevent->xkey;
+ eventy = newevent->ykey;
+ eventnum = heapsize;
+ notdone = eventnum > 0;
+ while (notdone) {
+ parent = (eventnum - 1) >> 1;
+ if ((heap[parent]->ykey < eventy) ||
+ ((heap[parent]->ykey == eventy)
+ && (heap[parent]->xkey <= eventx))) {
+ notdone = 0;
+ } else {
+ heap[eventnum] = heap[parent];
+ heap[eventnum]->heapposition = eventnum;
+
+ eventnum = parent;
+ notdone = eventnum > 0;
+ }
+ }
+ heap[eventnum] = newevent;
+ newevent->heapposition = eventnum;
+}
+
+#endif /* not REDUCED */
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+void eventheapify(struct event **heap, int heapsize, int eventnum)
+#else /* not ANSI_DECLARATORS */
+void eventheapify(heap, heapsize, eventnum)
+struct event **heap;
+int heapsize;
+int eventnum;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct event *thisevent;
+ REAL eventx, eventy;
+ int leftchild, rightchild;
+ int smallest;
+ int notdone;
+
+ thisevent = heap[eventnum];
+ eventx = thisevent->xkey;
+ eventy = thisevent->ykey;
+ leftchild = 2 * eventnum + 1;
+ notdone = leftchild < heapsize;
+ while (notdone) {
+ if ((heap[leftchild]->ykey < eventy) ||
+ ((heap[leftchild]->ykey == eventy)
+ && (heap[leftchild]->xkey < eventx))) {
+ smallest = leftchild;
+ } else {
+ smallest = eventnum;
+ }
+ rightchild = leftchild + 1;
+ if (rightchild < heapsize) {
+ if ((heap[rightchild]->ykey < heap[smallest]->ykey) ||
+ ((heap[rightchild]->ykey == heap[smallest]->ykey)
+ && (heap[rightchild]->xkey < heap[smallest]->xkey))) {
+ smallest = rightchild;
+ }
+ }
+ if (smallest == eventnum) {
+ notdone = 0;
+ } else {
+ heap[eventnum] = heap[smallest];
+ heap[eventnum]->heapposition = eventnum;
+ heap[smallest] = thisevent;
+ thisevent->heapposition = smallest;
+
+ eventnum = smallest;
+ leftchild = 2 * eventnum + 1;
+ notdone = leftchild < heapsize;
+ }
+ }
+}
+
+#endif /* not REDUCED */
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+void eventheapdelete(struct event **heap, int heapsize, int eventnum)
+#else /* not ANSI_DECLARATORS */
+void eventheapdelete(heap, heapsize, eventnum)
+struct event **heap;
+int heapsize;
+int eventnum;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct event *moveevent;
+ REAL eventx, eventy;
+ int parent;
+ int notdone;
+
+ moveevent = heap[heapsize - 1];
+ if (eventnum > 0) {
+ eventx = moveevent->xkey;
+ eventy = moveevent->ykey;
+ do {
+ parent = (eventnum - 1) >> 1;
+ if ((heap[parent]->ykey < eventy) ||
+ ((heap[parent]->ykey == eventy)
+ && (heap[parent]->xkey <= eventx))) {
+ notdone = 0;
+ } else {
+ heap[eventnum] = heap[parent];
+ heap[eventnum]->heapposition = eventnum;
+
+ eventnum = parent;
+ notdone = eventnum > 0;
+ }
+ } while (notdone);
+ }
+ heap[eventnum] = moveevent;
+ moveevent->heapposition = eventnum;
+ eventheapify(heap, heapsize - 1, eventnum);
+}
+
+#endif /* not REDUCED */
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+void createeventheap(struct mesh *m, struct event ***eventheap,
+ struct event **events, struct event **freeevents)
+#else /* not ANSI_DECLARATORS */
+void createeventheap(m, eventheap, events, freeevents)
+struct mesh *m;
+struct event ***eventheap;
+struct event **events;
+struct event **freeevents;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ vertex thisvertex;
+ int maxevents;
+ int i;
+
+ maxevents = (3 * m->invertices) / 2;
+ *eventheap = (struct event **) trimalloc(maxevents *
+ (int) sizeof(struct event *));
+ *events = (struct event *) trimalloc(maxevents * (int) sizeof(struct event));
+ traversalinit(&m->vertices);
+ for (i = 0; i < m->invertices; i++) {
+ thisvertex = vertextraverse(m);
+ (*events)[i].eventptr = (VOID *) thisvertex;
+ (*events)[i].xkey = thisvertex[0];
+ (*events)[i].ykey = thisvertex[1];
+ eventheapinsert(*eventheap, i, *events + i);
+ }
+ *freeevents = (struct event *) NULL;
+ for (i = maxevents - 1; i >= m->invertices; i--) {
+ (*events)[i].eventptr = (VOID *) *freeevents;
+ *freeevents = *events + i;
+ }
+}
+
+#endif /* not REDUCED */
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+int rightofhyperbola(struct mesh *m, struct otri *fronttri, vertex newsite)
+#else /* not ANSI_DECLARATORS */
+int rightofhyperbola(m, fronttri, newsite)
+struct mesh *m;
+struct otri *fronttri;
+vertex newsite;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ vertex leftvertex, rightvertex;
+ REAL dxa, dya, dxb, dyb;
+
+ m->hyperbolacount++;
+
+ dest(*fronttri, leftvertex);
+ apex(*fronttri, rightvertex);
+ if ((leftvertex[1] < rightvertex[1]) ||
+ ((leftvertex[1] == rightvertex[1]) &&
+ (leftvertex[0] < rightvertex[0]))) {
+ if (newsite[0] >= rightvertex[0]) {
+ return 1;
+ }
+ } else {
+ if (newsite[0] <= leftvertex[0]) {
+ return 0;
+ }
+ }
+ dxa = leftvertex[0] - newsite[0];
+ dya = leftvertex[1] - newsite[1];
+ dxb = rightvertex[0] - newsite[0];
+ dyb = rightvertex[1] - newsite[1];
+ return dya * (dxb * dxb + dyb * dyb) > dyb * (dxa * dxa + dya * dya);
+}
+
+#endif /* not REDUCED */
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+REAL circletop(struct mesh *m, vertex pa, vertex pb, vertex pc, REAL ccwabc)
+#else /* not ANSI_DECLARATORS */
+REAL circletop(m, pa, pb, pc, ccwabc)
+struct mesh *m;
+vertex pa;
+vertex pb;
+vertex pc;
+REAL ccwabc;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ REAL xac, yac, xbc, ybc, xab, yab;
+ REAL aclen2, bclen2, ablen2;
+
+ m->circletopcount++;
+
+ xac = pa[0] - pc[0];
+ yac = pa[1] - pc[1];
+ xbc = pb[0] - pc[0];
+ ybc = pb[1] - pc[1];
+ xab = pa[0] - pb[0];
+ yab = pa[1] - pb[1];
+ aclen2 = xac * xac + yac * yac;
+ bclen2 = xbc * xbc + ybc * ybc;
+ ablen2 = xab * xab + yab * yab;
+ return pc[1] + (xac * bclen2 - xbc * aclen2 + sqrt(aclen2 * bclen2 * ablen2))
+ / (2.0 * ccwabc);
+}
+
+#endif /* not REDUCED */
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+void check4deadevent(struct otri *checktri, struct event **freeevents,
+ struct event **eventheap, int *heapsize)
+#else /* not ANSI_DECLARATORS */
+void check4deadevent(checktri, freeevents, eventheap, heapsize)
+struct otri *checktri;
+struct event **freeevents;
+struct event **eventheap;
+int *heapsize;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct event *deadevent;
+ vertex eventvertex;
+ int eventnum;
+
+ org(*checktri, eventvertex);
+ if (eventvertex != (vertex) NULL) {
+ deadevent = (struct event *) eventvertex;
+ eventnum = deadevent->heapposition;
+ deadevent->eventptr = (VOID *) *freeevents;
+ *freeevents = deadevent;
+ eventheapdelete(eventheap, *heapsize, eventnum);
+ (*heapsize)--;
+ setorg(*checktri, NULL);
+ }
+}
+
+#endif /* not REDUCED */
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+struct splaynode *splay(struct mesh *m, struct splaynode *splaytree,
+ vertex searchpoint, struct otri *searchtri)
+#else /* not ANSI_DECLARATORS */
+struct splaynode *splay(m, splaytree, searchpoint, searchtri)
+struct mesh *m;
+struct splaynode *splaytree;
+vertex searchpoint;
+struct otri *searchtri;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct splaynode *child, *grandchild;
+ struct splaynode *lefttree, *righttree;
+ struct splaynode *leftright;
+ vertex checkvertex;
+ int rightofroot, rightofchild;
+
+ if (splaytree == (struct splaynode *) NULL) {
+ return (struct splaynode *) NULL;
+ }
+ dest(splaytree->keyedge, checkvertex);
+ if (checkvertex == splaytree->keydest) {
+ rightofroot = rightofhyperbola(m, &splaytree->keyedge, searchpoint);
+ if (rightofroot) {
+ otricopy(splaytree->keyedge, *searchtri);
+ child = splaytree->rchild;
+ } else {
+ child = splaytree->lchild;
+ }
+ if (child == (struct splaynode *) NULL) {
+ return splaytree;
+ }
+ dest(child->keyedge, checkvertex);
+ if (checkvertex != child->keydest) {
+ child = splay(m, child, searchpoint, searchtri);
+ if (child == (struct splaynode *) NULL) {
+ if (rightofroot) {
+ splaytree->rchild = (struct splaynode *) NULL;
+ } else {
+ splaytree->lchild = (struct splaynode *) NULL;
+ }
+ return splaytree;
+ }
+ }
+ rightofchild = rightofhyperbola(m, &child->keyedge, searchpoint);
+ if (rightofchild) {
+ otricopy(child->keyedge, *searchtri);
+ grandchild = splay(m, child->rchild, searchpoint, searchtri);
+ child->rchild = grandchild;
+ } else {
+ grandchild = splay(m, child->lchild, searchpoint, searchtri);
+ child->lchild = grandchild;
+ }
+ if (grandchild == (struct splaynode *) NULL) {
+ if (rightofroot) {
+ splaytree->rchild = child->lchild;
+ child->lchild = splaytree;
+ } else {
+ splaytree->lchild = child->rchild;
+ child->rchild = splaytree;
+ }
+ return child;
+ }
+ if (rightofchild) {
+ if (rightofroot) {
+ splaytree->rchild = child->lchild;
+ child->lchild = splaytree;
+ } else {
+ splaytree->lchild = grandchild->rchild;
+ grandchild->rchild = splaytree;
+ }
+ child->rchild = grandchild->lchild;
+ grandchild->lchild = child;
+ } else {
+ if (rightofroot) {
+ splaytree->rchild = grandchild->lchild;
+ grandchild->lchild = splaytree;
+ } else {
+ splaytree->lchild = child->rchild;
+ child->rchild = splaytree;
+ }
+ child->lchild = grandchild->rchild;
+ grandchild->rchild = child;
+ }
+ return grandchild;
+ } else {
+ lefttree = splay(m, splaytree->lchild, searchpoint, searchtri);
+ righttree = splay(m, splaytree->rchild, searchpoint, searchtri);
+
+ pooldealloc(&m->splaynodes, (VOID *) splaytree);
+ if (lefttree == (struct splaynode *) NULL) {
+ return righttree;
+ } else if (righttree == (struct splaynode *) NULL) {
+ return lefttree;
+ } else if (lefttree->rchild == (struct splaynode *) NULL) {
+ lefttree->rchild = righttree->lchild;
+ righttree->lchild = lefttree;
+ return righttree;
+ } else if (righttree->lchild == (struct splaynode *) NULL) {
+ righttree->lchild = lefttree->rchild;
+ lefttree->rchild = righttree;
+ return lefttree;
+ } else {
+/* printf("Holy Toledo!!!\n"); */
+ leftright = lefttree->rchild;
+ while (leftright->rchild != (struct splaynode *) NULL) {
+ leftright = leftright->rchild;
+ }
+ leftright->rchild = righttree;
+ return lefttree;
+ }
+ }
+}
+
+#endif /* not REDUCED */
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+struct splaynode *splayinsert(struct mesh *m, struct splaynode *splayroot,
+ struct otri *newkey, vertex searchpoint)
+#else /* not ANSI_DECLARATORS */
+struct splaynode *splayinsert(m, splayroot, newkey, searchpoint)
+struct mesh *m;
+struct splaynode *splayroot;
+struct otri *newkey;
+vertex searchpoint;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct splaynode *newsplaynode;
+
+ newsplaynode = (struct splaynode *) poolalloc(&m->splaynodes);
+ otricopy(*newkey, newsplaynode->keyedge);
+ dest(*newkey, newsplaynode->keydest);
+ if (splayroot == (struct splaynode *) NULL) {
+ newsplaynode->lchild = (struct splaynode *) NULL;
+ newsplaynode->rchild = (struct splaynode *) NULL;
+ } else if (rightofhyperbola(m, &splayroot->keyedge, searchpoint)) {
+ newsplaynode->lchild = splayroot;
+ newsplaynode->rchild = splayroot->rchild;
+ splayroot->rchild = (struct splaynode *) NULL;
+ } else {
+ newsplaynode->lchild = splayroot->lchild;
+ newsplaynode->rchild = splayroot;
+ splayroot->lchild = (struct splaynode *) NULL;
+ }
+ return newsplaynode;
+}
+
+#endif /* not REDUCED */
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+struct splaynode *circletopinsert(struct mesh *m, struct behavior *b,
+ struct splaynode *splayroot,
+ struct otri *newkey,
+ vertex pa, vertex pb, vertex pc, REAL topy)
+#else /* not ANSI_DECLARATORS */
+struct splaynode *circletopinsert(m, b, splayroot, newkey, pa, pb, pc, topy)
+struct mesh *m;
+struct behavior *b;
+struct splaynode *splayroot;
+struct otri *newkey;
+vertex pa;
+vertex pb;
+vertex pc;
+REAL topy;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ REAL ccwabc;
+ REAL xac, yac, xbc, ybc;
+ REAL aclen2, bclen2;
+ REAL searchpoint[2];
+ struct otri dummytri;
+
+ ccwabc = counterclockwise(m, b, pa, pb, pc);
+ xac = pa[0] - pc[0];
+ yac = pa[1] - pc[1];
+ xbc = pb[0] - pc[0];
+ ybc = pb[1] - pc[1];
+ aclen2 = xac * xac + yac * yac;
+ bclen2 = xbc * xbc + ybc * ybc;
+ searchpoint[0] = pc[0] - (yac * bclen2 - ybc * aclen2) / (2.0 * ccwabc);
+ searchpoint[1] = topy;
+ return splayinsert(m, splay(m, splayroot, (vertex) searchpoint, &dummytri),
+ newkey, (vertex) searchpoint);
+}
+
+#endif /* not REDUCED */
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+struct splaynode *frontlocate(struct mesh *m, struct splaynode *splayroot,
+ struct otri *bottommost, vertex searchvertex,
+ struct otri *searchtri, int *farright)
+#else /* not ANSI_DECLARATORS */
+struct splaynode *frontlocate(m, splayroot, bottommost, searchvertex,
+ searchtri, farright)
+struct mesh *m;
+struct splaynode *splayroot;
+struct otri *bottommost;
+vertex searchvertex;
+struct otri *searchtri;
+int *farright;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ int farrightflag;
+ triangle ptr; /* Temporary variable used by onext(). */
+
+ otricopy(*bottommost, *searchtri);
+ splayroot = splay(m, splayroot, searchvertex, searchtri);
+
+ farrightflag = 0;
+ while (!farrightflag && rightofhyperbola(m, searchtri, searchvertex)) {
+ onextself(*searchtri);
+ farrightflag = otriequal(*searchtri, *bottommost);
+ }
+ *farright = farrightflag;
+ return splayroot;
+}
+
+#endif /* not REDUCED */
+
+#ifndef REDUCED
+
+#ifdef ANSI_DECLARATORS
+long sweeplinedelaunay(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+long sweeplinedelaunay(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct event **eventheap;
+ struct event *events;
+ struct event *freeevents;
+ struct event *nextevent;
+ struct event *newevent;
+ struct splaynode *splayroot;
+ struct otri bottommost;
+ struct otri searchtri;
+ struct otri fliptri;
+ struct otri lefttri, righttri, farlefttri, farrighttri;
+ struct otri inserttri;
+ vertex firstvertex, secondvertex;
+ vertex nextvertex, lastvertex;
+ vertex connectvertex;
+ vertex leftvertex, midvertex, rightvertex;
+ REAL lefttest, righttest;
+ int heapsize;
+ int check4events, farrightflag;
+ triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */
+
+ poolinit(&m->splaynodes, sizeof(struct splaynode), SPLAYNODEPERBLOCK,
+ SPLAYNODEPERBLOCK, 0);
+ splayroot = (struct splaynode *) NULL;
+
+ if (b->verbose) {
+ printf(" Placing vertices in event heap.\n");
+ }
+ createeventheap(m, &eventheap, &events, &freeevents);
+ heapsize = m->invertices;
+
+ if (b->verbose) {
+ printf(" Forming triangulation.\n");
+ }
+ maketriangle(m, b, &lefttri);
+ maketriangle(m, b, &righttri);
+ bond(lefttri, righttri);
+ lnextself(lefttri);
+ lprevself(righttri);
+ bond(lefttri, righttri);
+ lnextself(lefttri);
+ lprevself(righttri);
+ bond(lefttri, righttri);
+ firstvertex = (vertex) eventheap[0]->eventptr;
+ eventheap[0]->eventptr = (VOID *) freeevents;
+ freeevents = eventheap[0];
+ eventheapdelete(eventheap, heapsize, 0);
+ heapsize--;
+ do {
+ if (heapsize == 0) {
+ printf("Error: Input vertices are all identical.\n");
+ triexit(1);
+ }
+ secondvertex = (vertex) eventheap[0]->eventptr;
+ eventheap[0]->eventptr = (VOID *) freeevents;
+ freeevents = eventheap[0];
+ eventheapdelete(eventheap, heapsize, 0);
+ heapsize--;
+ if ((firstvertex[0] == secondvertex[0]) &&
+ (firstvertex[1] == secondvertex[1])) {
+ if (!b->quiet) {
+ printf(
+"Warning: A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
+ secondvertex[0], secondvertex[1]);
+ }
+ setvertextype(secondvertex, UNDEADVERTEX);
+ m->undeads++;
+ }
+ } while ((firstvertex[0] == secondvertex[0]) &&
+ (firstvertex[1] == secondvertex[1]));
+ setorg(lefttri, firstvertex);
+ setdest(lefttri, secondvertex);
+ setorg(righttri, secondvertex);
+ setdest(righttri, firstvertex);
+ lprev(lefttri, bottommost);
+ lastvertex = secondvertex;
+ while (heapsize > 0) {
+ nextevent = eventheap[0];
+ eventheapdelete(eventheap, heapsize, 0);
+ heapsize--;
+ check4events = 1;
+ if (nextevent->xkey < m->xmin) {
+ decode(nextevent->eventptr, fliptri);
+ oprev(fliptri, farlefttri);
+ check4deadevent(&farlefttri, &freeevents, eventheap, &heapsize);
+ onext(fliptri, farrighttri);
+ check4deadevent(&farrighttri, &freeevents, eventheap, &heapsize);
+
+ if (otriequal(farlefttri, bottommost)) {
+ lprev(fliptri, bottommost);
+ }
+ flip(m, b, &fliptri);
+ setapex(fliptri, NULL);
+ lprev(fliptri, lefttri);
+ lnext(fliptri, righttri);
+ sym(lefttri, farlefttri);
+
+ if (randomnation(SAMPLERATE) == 0) {
+ symself(fliptri);
+ dest(fliptri, leftvertex);
+ apex(fliptri, midvertex);
+ org(fliptri, rightvertex);
+ splayroot = circletopinsert(m, b, splayroot, &lefttri, leftvertex,
+ midvertex, rightvertex, nextevent->ykey);
+ }
+ } else {
+ nextvertex = (vertex) nextevent->eventptr;
+ if ((nextvertex[0] == lastvertex[0]) &&
+ (nextvertex[1] == lastvertex[1])) {
+ if (!b->quiet) {
+ printf(
+"Warning: A duplicate vertex at (%.12g, %.12g) appeared and was ignored.\n",
+ nextvertex[0], nextvertex[1]);
+ }
+ setvertextype(nextvertex, UNDEADVERTEX);
+ m->undeads++;
+ check4events = 0;
+ } else {
+ lastvertex = nextvertex;
+
+ splayroot = frontlocate(m, splayroot, &bottommost, nextvertex,
+ &searchtri, &farrightflag);
+/*
+ otricopy(bottommost, searchtri);
+ farrightflag = 0;
+ while (!farrightflag && rightofhyperbola(m, &searchtri, nextvertex)) {
+ onextself(searchtri);
+ farrightflag = otriequal(searchtri, bottommost);
+ }
+*/
+
+ check4deadevent(&searchtri, &freeevents, eventheap, &heapsize);
+
+ otricopy(searchtri, farrighttri);
+ sym(searchtri, farlefttri);
+ maketriangle(m, b, &lefttri);
+ maketriangle(m, b, &righttri);
+ dest(farrighttri, connectvertex);
+ setorg(lefttri, connectvertex);
+ setdest(lefttri, nextvertex);
+ setorg(righttri, nextvertex);
+ setdest(righttri, connectvertex);
+ bond(lefttri, righttri);
+ lnextself(lefttri);
+ lprevself(righttri);
+ bond(lefttri, righttri);
+ lnextself(lefttri);
+ lprevself(righttri);
+ bond(lefttri, farlefttri);
+ bond(righttri, farrighttri);
+ if (!farrightflag && otriequal(farrighttri, bottommost)) {
+ otricopy(lefttri, bottommost);
+ }
+
+ if (randomnation(SAMPLERATE) == 0) {
+ splayroot = splayinsert(m, splayroot, &lefttri, nextvertex);
+ } else if (randomnation(SAMPLERATE) == 0) {
+ lnext(righttri, inserttri);
+ splayroot = splayinsert(m, splayroot, &inserttri, nextvertex);
+ }
+ }
+ }
+ nextevent->eventptr = (VOID *) freeevents;
+ freeevents = nextevent;
+
+ if (check4events) {
+ apex(farlefttri, leftvertex);
+ dest(lefttri, midvertex);
+ apex(lefttri, rightvertex);
+ lefttest = counterclockwise(m, b, leftvertex, midvertex, rightvertex);
+ if (lefttest > 0.0) {
+ newevent = freeevents;
+ freeevents = (struct event *) freeevents->eventptr;
+ newevent->xkey = m->xminextreme;
+ newevent->ykey = circletop(m, leftvertex, midvertex, rightvertex,
+ lefttest);
+ newevent->eventptr = (VOID *) encode(lefttri);
+ eventheapinsert(eventheap, heapsize, newevent);
+ heapsize++;
+ setorg(lefttri, newevent);
+ }
+ apex(righttri, leftvertex);
+ org(righttri, midvertex);
+ apex(farrighttri, rightvertex);
+ righttest = counterclockwise(m, b, leftvertex, midvertex, rightvertex);
+ if (righttest > 0.0) {
+ newevent = freeevents;
+ freeevents = (struct event *) freeevents->eventptr;
+ newevent->xkey = m->xminextreme;
+ newevent->ykey = circletop(m, leftvertex, midvertex, rightvertex,
+ righttest);
+ newevent->eventptr = (VOID *) encode(farrighttri);
+ eventheapinsert(eventheap, heapsize, newevent);
+ heapsize++;
+ setorg(farrighttri, newevent);
+ }
+ }
+ }
+
+ pooldeinit(&m->splaynodes);
+ lprevself(bottommost);
+ return removeghosts(m, b, &bottommost);
+}
+
+#endif /* not REDUCED */
+
+/** **/
+/** **/
+/********* Sweepline Delaunay triangulation ends here *********/
+
+/********* General mesh construction routines begin here *********/
+/** **/
+/** **/
+
+/*****************************************************************************/
+/* */
+/* delaunay() Form a Delaunay triangulation. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+long delaunay(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+long delaunay(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ long hulledges;
+
+ m->eextras = 0;
+ initializetrisubpools(m, b);
+
+#ifdef REDUCED
+ if (!b->quiet) {
+ printf(
+ "Constructing Delaunay triangulation by divide-and-conquer method.\n");
+ }
+ hulledges = divconqdelaunay(m, b);
+#else /* not REDUCED */
+ if (!b->quiet) {
+ printf("Constructing Delaunay triangulation ");
+ if (b->incremental) {
+ printf("by incremental method.\n");
+ } else if (b->sweepline) {
+ printf("by sweepline method.\n");
+ } else {
+ printf("by divide-and-conquer method.\n");
+ }
+ }
+ if (b->incremental) {
+ hulledges = incrementaldelaunay(m, b);
+ } else if (b->sweepline) {
+ hulledges = sweeplinedelaunay(m, b);
+ } else {
+ hulledges = divconqdelaunay(m, b);
+ }
+#endif /* not REDUCED */
+
+ if (m->triangles.items == 0) {
+ /* The input vertices were all collinear, so there are no triangles. */
+ return 0l;
+ } else {
+ return hulledges;
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* reconstruct() Reconstruct a triangulation from its .ele (and possibly */
+/* .poly) file. Used when the -r switch is used. */
+/* */
+/* Reads an .ele file and reconstructs the original mesh. If the -p switch */
+/* is used, this procedure will also read a .poly file and reconstruct the */
+/* subsegments of the original mesh. If the -a switch is used, this */
+/* procedure will also read an .area file and set a maximum area constraint */
+/* on each triangle. */
+/* */
+/* Vertices that are not corners of triangles, such as nodes on edges of */
+/* subparametric elements, are discarded. */
+/* */
+/* This routine finds the adjacencies between triangles (and subsegments) */
+/* by forming one stack of triangles for each vertex. Each triangle is on */
+/* three different stacks simultaneously. Each triangle's subsegment */
+/* pointers are used to link the items in each stack. This memory-saving */
+/* feature makes the code harder to read. The most important thing to keep */
+/* in mind is that each triangle is removed from a stack precisely when */
+/* the corresponding pointer is adjusted to refer to a subsegment rather */
+/* than the next triangle of the stack. */
+/* */
+/*****************************************************************************/
+
+#ifndef CDT_ONLY
+
+#ifdef TRILIBRARY
+
+#ifdef ANSI_DECLARATORS
+int reconstruct(struct mesh *m, struct behavior *b, int *trianglelist,
+ REAL *triangleattriblist, REAL *trianglearealist,
+ int elements, int corners, int attribs,
+ int *segmentlist,int *segmentmarkerlist, int numberofsegments)
+#else /* not ANSI_DECLARATORS */
+int reconstruct(m, b, trianglelist, triangleattriblist, trianglearealist,
+ elements, corners, attribs, segmentlist, segmentmarkerlist,
+ numberofsegments)
+struct mesh *m;
+struct behavior *b;
+int *trianglelist;
+REAL *triangleattriblist;
+REAL *trianglearealist;
+int elements;
+int corners;
+int attribs;
+int *segmentlist;
+int *segmentmarkerlist;
+int numberofsegments;
+#endif /* not ANSI_DECLARATORS */
+
+#else /* not TRILIBRARY */
+
+#ifdef ANSI_DECLARATORS
+long reconstruct(struct mesh *m, struct behavior *b, char *elefilename,
+ char *areafilename, char *polyfilename, FILE *polyfile)
+#else /* not ANSI_DECLARATORS */
+long reconstruct(m, b, elefilename, areafilename, polyfilename, polyfile)
+struct mesh *m;
+struct behavior *b;
+char *elefilename;
+char *areafilename;
+char *polyfilename;
+FILE *polyfile;
+#endif /* not ANSI_DECLARATORS */
+
+#endif /* not TRILIBRARY */
+
+{
+#ifdef TRILIBRARY
+ int vertexindex;
+ int attribindex;
+#else /* not TRILIBRARY */
+ FILE *elefile;
+ FILE *areafile;
+ char inputline[INPUTLINESIZE];
+ char *stringptr;
+ int areaelements;
+#endif /* not TRILIBRARY */
+ struct otri triangleloop;
+ struct otri triangleleft;
+ struct otri checktri;
+ struct otri checkleft;
+ struct otri checkneighbor;
+ struct osub subsegloop;
+ triangle *vertexarray;
+ triangle *prevlink;
+ triangle nexttri;
+ vertex tdest, tapex;
+ vertex checkdest, checkapex;
+ vertex shorg;
+ vertex killvertex;
+ vertex segmentorg, segmentdest;
+ REAL area;
+ int corner[3];
+ int end[2];
+ int killvertexindex;
+ int incorners;
+ int segmentmarkers;
+ int boundmarker;
+ int aroundvertex;
+ long hullsize;
+ int notfound;
+ long elementnumber, segmentnumber;
+ int i, j;
+ triangle ptr; /* Temporary variable used by sym(). */
+
+#ifdef TRILIBRARY
+ m->inelements = elements;
+ incorners = corners;
+ if (incorners < 3) {
+ printf("Error: Triangles must have at least 3 vertices.\n");
+ triexit(1);
+ }
+ m->eextras = attribs;
+#else /* not TRILIBRARY */
+ /* Read the triangles from an .ele file. */
+ if (!b->quiet) {
+ printf("Opening %s.\n", elefilename);
+ }
+ elefile = fopen(elefilename, "r");
+ if (elefile == (FILE *) NULL) {
+ printf(" Error: Cannot access file %s.\n", elefilename);
+ triexit(1);
+ }
+ /* Read number of triangles, number of vertices per triangle, and */
+ /* number of triangle attributes from .ele file. */
+ stringptr = readline(inputline, elefile, elefilename);
+ m->inelements = (int) strtol(stringptr, &stringptr, 0);
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ incorners = 3;
+ } else {
+ incorners = (int) strtol(stringptr, &stringptr, 0);
+ if (incorners < 3) {
+ printf("Error: Triangles in %s must have at least 3 vertices.\n",
+ elefilename);
+ triexit(1);
+ }
+ }
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ m->eextras = 0;
+ } else {
+ m->eextras = (int) strtol(stringptr, &stringptr, 0);
+ }
+#endif /* not TRILIBRARY */
+
+ initializetrisubpools(m, b);
+
+ /* Create the triangles. */
+ for (elementnumber = 1; elementnumber <= m->inelements; elementnumber++) {
+ maketriangle(m, b, &triangleloop);
+ /* Mark the triangle as living. */
+ triangleloop.tri[3] = (triangle) triangleloop.tri;
+ }
+
+ segmentmarkers = 0;
+ if (b->poly) {
+#ifdef TRILIBRARY
+ m->insegments = numberofsegments;
+ segmentmarkers = segmentmarkerlist != (int *) NULL;
+#else /* not TRILIBRARY */
+ /* Read number of segments and number of segment */
+ /* boundary markers from .poly file. */
+ stringptr = readline(inputline, polyfile, b->inpolyfilename);
+ m->insegments = (int) strtol(stringptr, &stringptr, 0);
+ stringptr = findfield(stringptr);
+ if (*stringptr != '\0') {
+ segmentmarkers = (int) strtol(stringptr, &stringptr, 0);
+ }
+#endif /* not TRILIBRARY */
+
+ /* Create the subsegments. */
+ for (segmentnumber = 1; segmentnumber <= m->insegments; segmentnumber++) {
+ makesubseg(m, &subsegloop);
+ /* Mark the subsegment as living. */
+ subsegloop.ss[2] = (subseg) subsegloop.ss;
+ }
+ }
+
+#ifdef TRILIBRARY
+ vertexindex = 0;
+ attribindex = 0;
+#else /* not TRILIBRARY */
+ if (b->vararea) {
+ /* Open an .area file, check for consistency with the .ele file. */
+ if (!b->quiet) {
+ printf("Opening %s.\n", areafilename);
+ }
+ areafile = fopen(areafilename, "r");
+ if (areafile == (FILE *) NULL) {
+ printf(" Error: Cannot access file %s.\n", areafilename);
+ triexit(1);
+ }
+ stringptr = readline(inputline, areafile, areafilename);
+ areaelements = (int) strtol(stringptr, &stringptr, 0);
+ if (areaelements != m->inelements) {
+ printf("Error: %s and %s disagree on number of triangles.\n",
+ elefilename, areafilename);
+ triexit(1);
+ }
+ }
+#endif /* not TRILIBRARY */
+
+ if (!b->quiet) {
+ printf("Reconstructing mesh.\n");
+ }
+ /* Allocate a temporary array that maps each vertex to some adjacent */
+ /* triangle. I took care to allocate all the permanent memory for */
+ /* triangles and subsegments first. */
+ vertexarray = (triangle *) trimalloc(m->vertices.items *
+ (int) sizeof(triangle));
+ /* Each vertex is initially unrepresented. */
+ for (i = 0; i < m->vertices.items; i++) {
+ vertexarray[i] = (triangle) m->dummytri;
+ }
+
+ if (b->verbose) {
+ printf(" Assembling triangles.\n");
+ }
+ /* Read the triangles from the .ele file, and link */
+ /* together those that share an edge. */
+ traversalinit(&m->triangles);
+ triangleloop.tri = triangletraverse(m);
+ elementnumber = b->firstnumber;
+ while (triangleloop.tri != (triangle *) NULL) {
+#ifdef TRILIBRARY
+ /* Copy the triangle's three corners. */
+ for (j = 0; j < 3; j++) {
+ corner[j] = trianglelist[vertexindex++];
+ if ((corner[j] < b->firstnumber) ||
+ (corner[j] >= b->firstnumber + m->invertices)) {
+ printf("Error: Triangle %ld has an invalid vertex index.\n",
+ elementnumber);
+ triexit(1);
+ }
+ }
+#else /* not TRILIBRARY */
+ /* Read triangle number and the triangle's three corners. */
+ stringptr = readline(inputline, elefile, elefilename);
+ for (j = 0; j < 3; j++) {
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ printf("Error: Triangle %ld is missing vertex %d in %s.\n",
+ elementnumber, j + 1, elefilename);
+ triexit(1);
+ } else {
+ corner[j] = (int) strtol(stringptr, &stringptr, 0);
+ if ((corner[j] < b->firstnumber) ||
+ (corner[j] >= b->firstnumber + m->invertices)) {
+ printf("Error: Triangle %ld has an invalid vertex index.\n",
+ elementnumber);
+ triexit(1);
+ }
+ }
+ }
+#endif /* not TRILIBRARY */
+
+ /* Find out about (and throw away) extra nodes. */
+ for (j = 3; j < incorners; j++) {
+#ifdef TRILIBRARY
+ killvertexindex = trianglelist[vertexindex++];
+#else /* not TRILIBRARY */
+ stringptr = findfield(stringptr);
+ if (*stringptr != '\0') {
+ killvertexindex = (int) strtol(stringptr, &stringptr, 0);
+#endif /* not TRILIBRARY */
+ if ((killvertexindex >= b->firstnumber) &&
+ (killvertexindex < b->firstnumber + m->invertices)) {
+ /* Delete the non-corner vertex if it's not already deleted. */
+ killvertex = getvertex(m, b, killvertexindex);
+ if (vertextype(killvertex) != DEADVERTEX) {
+ vertexdealloc(m, killvertex);
+ }
+ }
+#ifndef TRILIBRARY
+ }
+#endif /* not TRILIBRARY */
+ }
+
+ /* Read the triangle's attributes. */
+ for (j = 0; j < m->eextras; j++) {
+#ifdef TRILIBRARY
+ setelemattribute(triangleloop, j, triangleattriblist[attribindex++]);
+#else /* not TRILIBRARY */
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ setelemattribute(triangleloop, j, 0);
+ } else {
+ setelemattribute(triangleloop, j,
+ (REAL) strtod(stringptr, &stringptr));
+ }
+#endif /* not TRILIBRARY */
+ }
+
+ if (b->vararea) {
+#ifdef TRILIBRARY
+ area = trianglearealist[elementnumber - b->firstnumber];
+#else /* not TRILIBRARY */
+ /* Read an area constraint from the .area file. */
+ stringptr = readline(inputline, areafile, areafilename);
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ area = -1.0; /* No constraint on this triangle. */
+ } else {
+ area = (REAL) strtod(stringptr, &stringptr);
+ }
+#endif /* not TRILIBRARY */
+ setareabound(triangleloop, area);
+ }
+
+ /* Set the triangle's vertices. */
+ triangleloop.orient = 0;
+ setorg(triangleloop, getvertex(m, b, corner[0]));
+ setdest(triangleloop, getvertex(m, b, corner[1]));
+ setapex(triangleloop, getvertex(m, b, corner[2]));
+ /* Try linking the triangle to others that share these vertices. */
+ for (triangleloop.orient = 0; triangleloop.orient < 3;
+ triangleloop.orient++) {
+ /* Take the number for the origin of triangleloop. */
+ aroundvertex = corner[triangleloop.orient];
+ /* Look for other triangles having this vertex. */
+ nexttri = vertexarray[aroundvertex - b->firstnumber];
+ /* Link the current triangle to the next one in the stack. */
+ triangleloop.tri[6 + triangleloop.orient] = nexttri;
+ /* Push the current triangle onto the stack. */
+ vertexarray[aroundvertex - b->firstnumber] = encode(triangleloop);
+ decode(nexttri, checktri);
+ if (checktri.tri != m->dummytri) {
+ dest(triangleloop, tdest);
+ apex(triangleloop, tapex);
+ /* Look for other triangles that share an edge. */
+ do {
+ dest(checktri, checkdest);
+ apex(checktri, checkapex);
+ if (tapex == checkdest) {
+ /* The two triangles share an edge; bond them together. */
+ lprev(triangleloop, triangleleft);
+ bond(triangleleft, checktri);
+ }
+ if (tdest == checkapex) {
+ /* The two triangles share an edge; bond them together. */
+ lprev(checktri, checkleft);
+ bond(triangleloop, checkleft);
+ }
+ /* Find the next triangle in the stack. */
+ nexttri = checktri.tri[6 + checktri.orient];
+ decode(nexttri, checktri);
+ } while (checktri.tri != m->dummytri);
+ }
+ }
+ triangleloop.tri = triangletraverse(m);
+ elementnumber++;
+ }
+
+#ifdef TRILIBRARY
+ vertexindex = 0;
+#else /* not TRILIBRARY */
+ fclose(elefile);
+ if (b->vararea) {
+ fclose(areafile);
+ }
+#endif /* not TRILIBRARY */
+
+ hullsize = 0; /* Prepare to count the boundary edges. */
+ if (b->poly) {
+ if (b->verbose) {
+ printf(" Marking segments in triangulation.\n");
+ }
+ /* Read the segments from the .poly file, and link them */
+ /* to their neighboring triangles. */
+ boundmarker = 0;
+ traversalinit(&m->subsegs);
+ subsegloop.ss = subsegtraverse(m);
+ segmentnumber = b->firstnumber;
+ while (subsegloop.ss != (subseg *) NULL) {
+#ifdef TRILIBRARY
+ end[0] = segmentlist[vertexindex++];
+ end[1] = segmentlist[vertexindex++];
+ if (segmentmarkers) {
+ boundmarker = segmentmarkerlist[segmentnumber - b->firstnumber];
+ }
+#else /* not TRILIBRARY */
+ /* Read the endpoints of each segment, and possibly a boundary marker. */
+ stringptr = readline(inputline, polyfile, b->inpolyfilename);
+ /* Skip the first (segment number) field. */
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ printf("Error: Segment %ld has no endpoints in %s.\n", segmentnumber,
+ polyfilename);
+ triexit(1);
+ } else {
+ end[0] = (int) strtol(stringptr, &stringptr, 0);
+ }
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ printf("Error: Segment %ld is missing its second endpoint in %s.\n",
+ segmentnumber, polyfilename);
+ triexit(1);
+ } else {
+ end[1] = (int) strtol(stringptr, &stringptr, 0);
+ }
+ if (segmentmarkers) {
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ boundmarker = 0;
+ } else {
+ boundmarker = (int) strtol(stringptr, &stringptr, 0);
+ }
+ }
+#endif /* not TRILIBRARY */
+ for (j = 0; j < 2; j++) {
+ if ((end[j] < b->firstnumber) ||
+ (end[j] >= b->firstnumber + m->invertices)) {
+ printf("Error: Segment %ld has an invalid vertex index.\n",
+ segmentnumber);
+ triexit(1);
+ }
+ }
+
+ /* set the subsegment's vertices. */
+ subsegloop.ssorient = 0;
+ segmentorg = getvertex(m, b, end[0]);
+ segmentdest = getvertex(m, b, end[1]);
+ setsorg(subsegloop, segmentorg);
+ setsdest(subsegloop, segmentdest);
+ setsegorg(subsegloop, segmentorg);
+ setsegdest(subsegloop, segmentdest);
+ setmark(subsegloop, boundmarker);
+ /* Try linking the subsegment to triangles that share these vertices. */
+ for (subsegloop.ssorient = 0; subsegloop.ssorient < 2;
+ subsegloop.ssorient++) {
+ /* Take the number for the destination of subsegloop. */
+ aroundvertex = end[1 - subsegloop.ssorient];
+ /* Look for triangles having this vertex. */
+ prevlink = &vertexarray[aroundvertex - b->firstnumber];
+ nexttri = vertexarray[aroundvertex - b->firstnumber];
+ decode(nexttri, checktri);
+ sorg(subsegloop, shorg);
+ notfound = 1;
+ /* Look for triangles having this edge. Note that I'm only */
+ /* comparing each triangle's destination with the subsegment; */
+ /* each triangle's apex is handled through a different vertex. */
+ /* Because each triangle appears on three vertices' lists, each */
+ /* occurrence of a triangle on a list can (and does) represent */
+ /* an edge. In this way, most edges are represented twice, and */
+ /* every triangle-subsegment bond is represented once. */
+ while (notfound && (checktri.tri != m->dummytri)) {
+ dest(checktri, checkdest);
+ if (shorg == checkdest) {
+ /* We have a match. Remove this triangle from the list. */
+ *prevlink = checktri.tri[6 + checktri.orient];
+ /* Bond the subsegment to the triangle. */
+ tsbond(checktri, subsegloop);
+ /* Check if this is a boundary edge. */
+ sym(checktri, checkneighbor);
+ if (checkneighbor.tri == m->dummytri) {
+ /* The next line doesn't insert a subsegment (because there's */
+ /* already one there), but it sets the boundary markers of */
+ /* the existing subsegment and its vertices. */
+ insertsubseg(m, b, &checktri, 1);
+ hullsize++;
+ }
+ notfound = 0;
+ }
+ /* Find the next triangle in the stack. */
+ prevlink = &checktri.tri[6 + checktri.orient];
+ nexttri = checktri.tri[6 + checktri.orient];
+ decode(nexttri, checktri);
+ }
+ }
+ subsegloop.ss = subsegtraverse(m);
+ segmentnumber++;
+ }
+ }
+
+ /* Mark the remaining edges as not being attached to any subsegment. */
+ /* Also, count the (yet uncounted) boundary edges. */
+ for (i = 0; i < m->vertices.items; i++) {
+ /* Search the stack of triangles adjacent to a vertex. */
+ nexttri = vertexarray[i];
+ decode(nexttri, checktri);
+ while (checktri.tri != m->dummytri) {
+ /* Find the next triangle in the stack before this */
+ /* information gets overwritten. */
+ nexttri = checktri.tri[6 + checktri.orient];
+ /* No adjacent subsegment. (This overwrites the stack info.) */
+ tsdissolve(checktri);
+ sym(checktri, checkneighbor);
+ if (checkneighbor.tri == m->dummytri) {
+ insertsubseg(m, b, &checktri, 1);
+ hullsize++;
+ }
+ decode(nexttri, checktri);
+ }
+ }
+
+ trifree((VOID *) vertexarray);
+ return hullsize;
+}
+
+#endif /* not CDT_ONLY */
+
+/** **/
+/** **/
+/********* General mesh construction routines end here *********/
+
+/********* Segment insertion begins here *********/
+/** **/
+/** **/
+
+/*****************************************************************************/
+/* */
+/* finddirection() Find the first triangle on the path from one point */
+/* to another. */
+/* */
+/* Finds the triangle that intersects a line segment drawn from the */
+/* origin of `searchtri' to the point `searchpoint', and returns the result */
+/* in `searchtri'. The origin of `searchtri' does not change, even though */
+/* the triangle returned may differ from the one passed in. This routine */
+/* is used to find the direction to move in to get from one point to */
+/* another. */
+/* */
+/* The return value notes whether the destination or apex of the found */
+/* triangle is collinear with the two points in question. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+enum finddirectionresult finddirection(struct mesh *m, struct behavior *b,
+ struct otri *searchtri,
+ vertex searchpoint)
+#else /* not ANSI_DECLARATORS */
+enum finddirectionresult finddirection(m, b, searchtri, searchpoint)
+struct mesh *m;
+struct behavior *b;
+struct otri *searchtri;
+vertex searchpoint;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri checktri;
+ vertex startvertex;
+ vertex leftvertex, rightvertex;
+ REAL leftccw, rightccw;
+ int leftflag, rightflag;
+ triangle ptr; /* Temporary variable used by onext() and oprev(). */
+
+ org(*searchtri, startvertex);
+ dest(*searchtri, rightvertex);
+ apex(*searchtri, leftvertex);
+ /* Is `searchpoint' to the left? */
+ leftccw = counterclockwise(m, b, searchpoint, startvertex, leftvertex);
+ leftflag = leftccw > 0.0;
+ /* Is `searchpoint' to the right? */
+ rightccw = counterclockwise(m, b, startvertex, searchpoint, rightvertex);
+ rightflag = rightccw > 0.0;
+ if (leftflag && rightflag) {
+ /* `searchtri' faces directly away from `searchpoint'. We could go left */
+ /* or right. Ask whether it's a triangle or a boundary on the left. */
+ onext(*searchtri, checktri);
+ if (checktri.tri == m->dummytri) {
+ leftflag = 0;
+ } else {
+ rightflag = 0;
+ }
+ }
+ while (leftflag) {
+ /* Turn left until satisfied. */
+ onextself(*searchtri);
+ if (searchtri->tri == m->dummytri) {
+ printf("Internal error in finddirection(): Unable to find a\n");
+ printf(" triangle leading from (%.12g, %.12g) to", startvertex[0],
+ startvertex[1]);
+ printf(" (%.12g, %.12g).\n", searchpoint[0], searchpoint[1]);
+ internalerror();
+ }
+ apex(*searchtri, leftvertex);
+ rightccw = leftccw;
+ leftccw = counterclockwise(m, b, searchpoint, startvertex, leftvertex);
+ leftflag = leftccw > 0.0;
+ }
+ while (rightflag) {
+ /* Turn right until satisfied. */
+ oprevself(*searchtri);
+ if (searchtri->tri == m->dummytri) {
+ printf("Internal error in finddirection(): Unable to find a\n");
+ printf(" triangle leading from (%.12g, %.12g) to", startvertex[0],
+ startvertex[1]);
+ printf(" (%.12g, %.12g).\n", searchpoint[0], searchpoint[1]);
+ internalerror();
+ }
+ dest(*searchtri, rightvertex);
+ leftccw = rightccw;
+ rightccw = counterclockwise(m, b, startvertex, searchpoint, rightvertex);
+ rightflag = rightccw > 0.0;
+ }
+ if (leftccw == 0.0) {
+ return LEFTCOLLINEAR;
+ } else if (rightccw == 0.0) {
+ return RIGHTCOLLINEAR;
+ } else {
+ return WITHIN;
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* segmentintersection() Find the intersection of an existing segment */
+/* and a segment that is being inserted. Insert */
+/* a vertex at the intersection, splitting an */
+/* existing subsegment. */
+/* */
+/* The segment being inserted connects the apex of splittri to endpoint2. */
+/* splitsubseg is the subsegment being split, and MUST adjoin splittri. */
+/* Hence, endpoints of the subsegment being split are the origin and */
+/* destination of splittri. */
+/* */
+/* On completion, splittri is a handle having the newly inserted */
+/* intersection point as its origin, and endpoint1 as its destination. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void segmentintersection(struct mesh *m, struct behavior *b,
+ struct otri *splittri, struct osub *splitsubseg,
+ vertex endpoint2)
+#else /* not ANSI_DECLARATORS */
+void segmentintersection(m, b, splittri, splitsubseg, endpoint2)
+struct mesh *m;
+struct behavior *b;
+struct otri *splittri;
+struct osub *splitsubseg;
+vertex endpoint2;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct osub opposubseg;
+ vertex endpoint1;
+ vertex torg, tdest;
+ vertex leftvertex, rightvertex;
+ vertex newvertex;
+ enum insertvertexresult success;
+ enum finddirectionresult collinear;
+ REAL ex, ey;
+ REAL tx, ty;
+ REAL etx, ety;
+ REAL split, denom;
+ int i;
+ triangle ptr; /* Temporary variable used by onext(). */
+ subseg sptr; /* Temporary variable used by snext(). */
+
+ /* Find the other three segment endpoints. */
+ apex(*splittri, endpoint1);
+ org(*splittri, torg);
+ dest(*splittri, tdest);
+ /* Segment intersection formulae; see the Antonio reference. */
+ tx = tdest[0] - torg[0];
+ ty = tdest[1] - torg[1];
+ ex = endpoint2[0] - endpoint1[0];
+ ey = endpoint2[1] - endpoint1[1];
+ etx = torg[0] - endpoint2[0];
+ ety = torg[1] - endpoint2[1];
+ denom = ty * ex - tx * ey;
+ if (denom == 0.0) {
+ printf("Internal error in segmentintersection():");
+ printf(" Attempt to find intersection of parallel segments.\n");
+ internalerror();
+ }
+ split = (ey * etx - ex * ety) / denom;
+ /* Create the new vertex. */
+ newvertex = (vertex) poolalloc(&m->vertices);
+ /* Interpolate its coordinate and attributes. */
+ for (i = 0; i < 2 + m->nextras; i++) {
+ newvertex[i] = torg[i] + split * (tdest[i] - torg[i]);
+ }
+ setvertexmark(newvertex, mark(*splitsubseg));
+ setvertextype(newvertex, INPUTVERTEX);
+ if (b->verbose > 1) {
+ printf(
+ " Splitting subsegment (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
+ torg[0], torg[1], tdest[0], tdest[1], newvertex[0], newvertex[1]);
+ }
+ /* Insert the intersection vertex. This should always succeed. */
+ success = insertvertex(m, b, newvertex, splittri, splitsubseg, 0, 0);
+ if (success != SUCCESSFULVERTEX) {
+ printf("Internal error in segmentintersection():\n");
+ printf(" Failure to split a segment.\n");
+ internalerror();
+ }
+ /* Record a triangle whose origin is the new vertex. */
+ setvertex2tri(newvertex, encode(*splittri));
+ if (m->steinerleft > 0) {
+ m->steinerleft--;
+ }
+
+ /* Divide the segment into two, and correct the segment endpoints. */
+ ssymself(*splitsubseg);
+ spivot(*splitsubseg, opposubseg);
+ sdissolve(*splitsubseg);
+ sdissolve(opposubseg);
+ do {
+ setsegorg(*splitsubseg, newvertex);
+ snextself(*splitsubseg);
+ } while (splitsubseg->ss != m->dummysub);
+ do {
+ setsegorg(opposubseg, newvertex);
+ snextself(opposubseg);
+ } while (opposubseg.ss != m->dummysub);
+
+ /* Inserting the vertex may have caused edge flips. We wish to rediscover */
+ /* the edge connecting endpoint1 to the new intersection vertex. */
+ collinear = finddirection(m, b, splittri, endpoint1);
+ dest(*splittri, rightvertex);
+ apex(*splittri, leftvertex);
+ if ((leftvertex[0] == endpoint1[0]) && (leftvertex[1] == endpoint1[1])) {
+ onextself(*splittri);
+ } else if ((rightvertex[0] != endpoint1[0]) ||
+ (rightvertex[1] != endpoint1[1])) {
+ printf("Internal error in segmentintersection():\n");
+ printf(" Topological inconsistency after splitting a segment.\n");
+ internalerror();
+ }
+ /* `splittri' should have destination endpoint1. */
+}
+
+/*****************************************************************************/
+/* */
+/* scoutsegment() Scout the first triangle on the path from one endpoint */
+/* to another, and check for completion (reaching the */
+/* second endpoint), a collinear vertex, or the */
+/* intersection of two segments. */
+/* */
+/* Returns one if the entire segment is successfully inserted, and zero if */
+/* the job must be finished by conformingedge() or constrainededge(). */
+/* */
+/* If the first triangle on the path has the second endpoint as its */
+/* destination or apex, a subsegment is inserted and the job is done. */
+/* */
+/* If the first triangle on the path has a destination or apex that lies on */
+/* the segment, a subsegment is inserted connecting the first endpoint to */
+/* the collinear vertex, and the search is continued from the collinear */
+/* vertex. */
+/* */
+/* If the first triangle on the path has a subsegment opposite its origin, */
+/* then there is a segment that intersects the segment being inserted. */
+/* Their intersection vertex is inserted, splitting the subsegment. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+int scoutsegment(struct mesh *m, struct behavior *b, struct otri *searchtri,
+ vertex endpoint2, int newmark)
+#else /* not ANSI_DECLARATORS */
+int scoutsegment(m, b, searchtri, endpoint2, newmark)
+struct mesh *m;
+struct behavior *b;
+struct otri *searchtri;
+vertex endpoint2;
+int newmark;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri crosstri;
+ struct osub crosssubseg;
+ vertex leftvertex, rightvertex;
+ enum finddirectionresult collinear;
+ subseg sptr; /* Temporary variable used by tspivot(). */
+
+ collinear = finddirection(m, b, searchtri, endpoint2);
+ dest(*searchtri, rightvertex);
+ apex(*searchtri, leftvertex);
+ if (((leftvertex[0] == endpoint2[0]) && (leftvertex[1] == endpoint2[1])) ||
+ ((rightvertex[0] == endpoint2[0]) && (rightvertex[1] == endpoint2[1]))) {
+ /* The segment is already an edge in the mesh. */
+ if ((leftvertex[0] == endpoint2[0]) && (leftvertex[1] == endpoint2[1])) {
+ lprevself(*searchtri);
+ }
+ /* Insert a subsegment, if there isn't already one there. */
+ insertsubseg(m, b, searchtri, newmark);
+ return 1;
+ } else if (collinear == LEFTCOLLINEAR) {
+ /* We've collided with a vertex between the segment's endpoints. */
+ /* Make the collinear vertex be the triangle's origin. */
+ lprevself(*searchtri);
+ insertsubseg(m, b, searchtri, newmark);
+ /* Insert the remainder of the segment. */
+ return scoutsegment(m, b, searchtri, endpoint2, newmark);
+ } else if (collinear == RIGHTCOLLINEAR) {
+ /* We've collided with a vertex between the segment's endpoints. */
+ insertsubseg(m, b, searchtri, newmark);
+ /* Make the collinear vertex be the triangle's origin. */
+ lnextself(*searchtri);
+ /* Insert the remainder of the segment. */
+ return scoutsegment(m, b, searchtri, endpoint2, newmark);
+ } else {
+ lnext(*searchtri, crosstri);
+ tspivot(crosstri, crosssubseg);
+ /* Check for a crossing segment. */
+ if (crosssubseg.ss == m->dummysub) {
+ return 0;
+ } else {
+ /* Insert a vertex at the intersection. */
+ segmentintersection(m, b, &crosstri, &crosssubseg, endpoint2);
+ otricopy(crosstri, *searchtri);
+ insertsubseg(m, b, searchtri, newmark);
+ /* Insert the remainder of the segment. */
+ return scoutsegment(m, b, searchtri, endpoint2, newmark);
+ }
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* conformingedge() Force a segment into a conforming Delaunay */
+/* triangulation by inserting a vertex at its midpoint, */
+/* and recursively forcing in the two half-segments if */
+/* necessary. */
+/* */
+/* Generates a sequence of subsegments connecting `endpoint1' to */
+/* `endpoint2'. `newmark' is the boundary marker of the segment, assigned */
+/* to each new splitting vertex and subsegment. */
+/* */
+/* Note that conformingedge() does not always maintain the conforming */
+/* Delaunay property. Once inserted, segments are locked into place; */
+/* vertices inserted later (to force other segments in) may render these */
+/* fixed segments non-Delaunay. The conforming Delaunay property will be */
+/* restored by enforcequality() by splitting encroached subsegments. */
+/* */
+/*****************************************************************************/
+
+#ifndef REDUCED
+#ifndef CDT_ONLY
+
+#ifdef ANSI_DECLARATORS
+void conformingedge(struct mesh *m, struct behavior *b,
+ vertex endpoint1, vertex endpoint2, int newmark)
+#else /* not ANSI_DECLARATORS */
+void conformingedge(m, b, endpoint1, endpoint2, newmark)
+struct mesh *m;
+struct behavior *b;
+vertex endpoint1;
+vertex endpoint2;
+int newmark;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri searchtri1, searchtri2;
+ struct osub brokensubseg;
+ vertex newvertex;
+ vertex midvertex1, midvertex2;
+ enum insertvertexresult success;
+ int i;
+ subseg sptr; /* Temporary variable used by tspivot(). */
+
+ if (b->verbose > 2) {
+ printf("Forcing segment into triangulation by recursive splitting:\n");
+ printf(" (%.12g, %.12g) (%.12g, %.12g)\n", endpoint1[0], endpoint1[1],
+ endpoint2[0], endpoint2[1]);
+ }
+ /* Create a new vertex to insert in the middle of the segment. */
+ newvertex = (vertex) poolalloc(&m->vertices);
+ /* Interpolate coordinates and attributes. */
+ for (i = 0; i < 2 + m->nextras; i++) {
+ newvertex[i] = 0.5 * (endpoint1[i] + endpoint2[i]);
+ }
+ setvertexmark(newvertex, newmark);
+ setvertextype(newvertex, SEGMENTVERTEX);
+ /* No known triangle to search from. */
+ searchtri1.tri = m->dummytri;
+ /* Attempt to insert the new vertex. */
+ success = insertvertex(m, b, newvertex, &searchtri1, (struct osub *) NULL,
+ 0, 0);
+ if (success == DUPLICATEVERTEX) {
+ if (b->verbose > 2) {
+ printf(" Segment intersects existing vertex (%.12g, %.12g).\n",
+ newvertex[0], newvertex[1]);
+ }
+ /* Use the vertex that's already there. */
+ vertexdealloc(m, newvertex);
+ org(searchtri1, newvertex);
+ } else {
+ if (success == VIOLATINGVERTEX) {
+ if (b->verbose > 2) {
+ printf(" Two segments intersect at (%.12g, %.12g).\n",
+ newvertex[0], newvertex[1]);
+ }
+ /* By fluke, we've landed right on another segment. Split it. */
+ tspivot(searchtri1, brokensubseg);
+ success = insertvertex(m, b, newvertex, &searchtri1, &brokensubseg,
+ 0, 0);
+ if (success != SUCCESSFULVERTEX) {
+ printf("Internal error in conformingedge():\n");
+ printf(" Failure to split a segment.\n");
+ internalerror();
+ }
+ }
+ /* The vertex has been inserted successfully. */
+ if (m->steinerleft > 0) {
+ m->steinerleft--;
+ }
+ }
+ otricopy(searchtri1, searchtri2);
+ /* `searchtri1' and `searchtri2' are fastened at their origins to */
+ /* `newvertex', and will be directed toward `endpoint1' and `endpoint2' */
+ /* respectively. First, we must get `searchtri2' out of the way so it */
+ /* won't be invalidated during the insertion of the first half of the */
+ /* segment. */
+ finddirection(m, b, &searchtri2, endpoint2);
+ if (!scoutsegment(m, b, &searchtri1, endpoint1, newmark)) {
+ /* The origin of searchtri1 may have changed if a collision with an */
+ /* intervening vertex on the segment occurred. */
+ org(searchtri1, midvertex1);
+ conformingedge(m, b, midvertex1, endpoint1, newmark);
+ }
+ if (!scoutsegment(m, b, &searchtri2, endpoint2, newmark)) {
+ /* The origin of searchtri2 may have changed if a collision with an */
+ /* intervening vertex on the segment occurred. */
+ org(searchtri2, midvertex2);
+ conformingedge(m, b, midvertex2, endpoint2, newmark);
+ }
+}
+
+#endif /* not CDT_ONLY */
+#endif /* not REDUCED */
+
+/*****************************************************************************/
+/* */
+/* delaunayfixup() Enforce the Delaunay condition at an edge, fanning out */
+/* recursively from an existing vertex. Pay special */
+/* attention to stacking inverted triangles. */
+/* */
+/* This is a support routine for inserting segments into a constrained */
+/* Delaunay triangulation. */
+/* */
+/* The origin of fixuptri is treated as if it has just been inserted, and */
+/* the local Delaunay condition needs to be enforced. It is only enforced */
+/* in one sector, however, that being the angular range defined by */
+/* fixuptri. */
+/* */
+/* This routine also needs to make decisions regarding the "stacking" of */
+/* triangles. (Read the description of constrainededge() below before */
+/* reading on here, so you understand the algorithm.) If the position of */
+/* the new vertex (the origin of fixuptri) indicates that the vertex before */
+/* it on the polygon is a reflex vertex, then "stack" the triangle by */
+/* doing nothing. (fixuptri is an inverted triangle, which is how stacked */
+/* triangles are identified.) */
+/* */
+/* Otherwise, check whether the vertex before that was a reflex vertex. */
+/* If so, perform an edge flip, thereby eliminating an inverted triangle */
+/* (popping it off the stack). The edge flip may result in the creation */
+/* of a new inverted triangle, depending on whether or not the new vertex */
+/* is visible to the vertex three edges behind on the polygon. */
+/* */
+/* If neither of the two vertices behind the new vertex are reflex */
+/* vertices, fixuptri and fartri, the triangle opposite it, are not */
+/* inverted; hence, ensure that the edge between them is locally Delaunay. */
+/* */
+/* `leftside' indicates whether or not fixuptri is to the left of the */
+/* segment being inserted. (Imagine that the segment is pointing up from */
+/* endpoint1 to endpoint2.) */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void delaunayfixup(struct mesh *m, struct behavior *b,
+ struct otri *fixuptri, int leftside)
+#else /* not ANSI_DECLARATORS */
+void delaunayfixup(m, b, fixuptri, leftside)
+struct mesh *m;
+struct behavior *b;
+struct otri *fixuptri;
+int leftside;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri neartri;
+ struct otri fartri;
+ struct osub faredge;
+ vertex nearvertex, leftvertex, rightvertex, farvertex;
+ triangle ptr; /* Temporary variable used by sym(). */
+ subseg sptr; /* Temporary variable used by tspivot(). */
+
+ lnext(*fixuptri, neartri);
+ sym(neartri, fartri);
+ /* Check if the edge opposite the origin of fixuptri can be flipped. */
+ if (fartri.tri == m->dummytri) {
+ return;
+ }
+ tspivot(neartri, faredge);
+ if (faredge.ss != m->dummysub) {
+ return;
+ }
+ /* Find all the relevant vertices. */
+ apex(neartri, nearvertex);
+ org(neartri, leftvertex);
+ dest(neartri, rightvertex);
+ apex(fartri, farvertex);
+ /* Check whether the previous polygon vertex is a reflex vertex. */
+ if (leftside) {
+ if (counterclockwise(m, b, nearvertex, leftvertex, farvertex) <= 0.0) {
+ /* leftvertex is a reflex vertex too. Nothing can */
+ /* be done until a convex section is found. */
+ return;
+ }
+ } else {
+ if (counterclockwise(m, b, farvertex, rightvertex, nearvertex) <= 0.0) {
+ /* rightvertex is a reflex vertex too. Nothing can */
+ /* be done until a convex section is found. */
+ return;
+ }
+ }
+ if (counterclockwise(m, b, rightvertex, leftvertex, farvertex) > 0.0) {
+ /* fartri is not an inverted triangle, and farvertex is not a reflex */
+ /* vertex. As there are no reflex vertices, fixuptri isn't an */
+ /* inverted triangle, either. Hence, test the edge between the */
+ /* triangles to ensure it is locally Delaunay. */
+ if (incircle(m, b, leftvertex, farvertex, rightvertex, nearvertex) <=
+ 0.0) {
+ return;
+ }
+ /* Not locally Delaunay; go on to an edge flip. */
+ } /* else fartri is inverted; remove it from the stack by flipping. */
+ flip(m, b, &neartri);
+ lprevself(*fixuptri); /* Restore the origin of fixuptri after the flip. */
+ /* Recursively process the two triangles that result from the flip. */
+ delaunayfixup(m, b, fixuptri, leftside);
+ delaunayfixup(m, b, &fartri, leftside);
+}
+
+/*****************************************************************************/
+/* */
+/* constrainededge() Force a segment into a constrained Delaunay */
+/* triangulation by deleting the triangles it */
+/* intersects, and triangulating the polygons that */
+/* form on each side of it. */
+/* */
+/* Generates a single subsegment connecting `endpoint1' to `endpoint2'. */
+/* The triangle `starttri' has `endpoint1' as its origin. `newmark' is the */
+/* boundary marker of the segment. */
+/* */
+/* To insert a segment, every triangle whose interior intersects the */
+/* segment is deleted. The union of these deleted triangles is a polygon */
+/* (which is not necessarily monotone, but is close enough), which is */
+/* divided into two polygons by the new segment. This routine's task is */
+/* to generate the Delaunay triangulation of these two polygons. */
+/* */
+/* You might think of this routine's behavior as a two-step process. The */
+/* first step is to walk from endpoint1 to endpoint2, flipping each edge */
+/* encountered. This step creates a fan of edges connected to endpoint1, */
+/* including the desired edge to endpoint2. The second step enforces the */
+/* Delaunay condition on each side of the segment in an incremental manner: */
+/* proceeding along the polygon from endpoint1 to endpoint2 (this is done */
+/* independently on each side of the segment), each vertex is "enforced" */
+/* as if it had just been inserted, but affecting only the previous */
+/* vertices. The result is the same as if the vertices had been inserted */
+/* in the order they appear on the polygon, so the result is Delaunay. */
+/* */
+/* In truth, constrainededge() interleaves these two steps. The procedure */
+/* walks from endpoint1 to endpoint2, and each time an edge is encountered */
+/* and flipped, the newly exposed vertex (at the far end of the flipped */
+/* edge) is "enforced" upon the previously flipped edges, usually affecting */
+/* only one side of the polygon (depending upon which side of the segment */
+/* the vertex falls on). */
+/* */
+/* The algorithm is complicated by the need to handle polygons that are not */
+/* convex. Although the polygon is not necessarily monotone, it can be */
+/* triangulated in a manner similar to the stack-based algorithms for */
+/* monotone polygons. For each reflex vertex (local concavity) of the */
+/* polygon, there will be an inverted triangle formed by one of the edge */
+/* flips. (An inverted triangle is one with negative area - that is, its */
+/* vertices are arranged in clockwise order - and is best thought of as a */
+/* wrinkle in the fabric of the mesh.) Each inverted triangle can be */
+/* thought of as a reflex vertex pushed on the stack, waiting to be fixed */
+/* later. */
+/* */
+/* A reflex vertex is popped from the stack when a vertex is inserted that */
+/* is visible to the reflex vertex. (However, if the vertex behind the */
+/* reflex vertex is not visible to the reflex vertex, a new inverted */
+/* triangle will take its place on the stack.) These details are handled */
+/* by the delaunayfixup() routine above. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void constrainededge(struct mesh *m, struct behavior *b,
+ struct otri *starttri, vertex endpoint2, int newmark)
+#else /* not ANSI_DECLARATORS */
+void constrainededge(m, b, starttri, endpoint2, newmark)
+struct mesh *m;
+struct behavior *b;
+struct otri *starttri;
+vertex endpoint2;
+int newmark;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri fixuptri, fixuptri2;
+ struct osub crosssubseg;
+ vertex endpoint1;
+ vertex farvertex;
+ REAL area;
+ int collision;
+ int done;
+ triangle ptr; /* Temporary variable used by sym() and oprev(). */
+ subseg sptr; /* Temporary variable used by tspivot(). */
+
+ org(*starttri, endpoint1);
+ lnext(*starttri, fixuptri);
+ flip(m, b, &fixuptri);
+ /* `collision' indicates whether we have found a vertex directly */
+ /* between endpoint1 and endpoint2. */
+ collision = 0;
+ done = 0;
+ do {
+ org(fixuptri, farvertex);
+ /* `farvertex' is the extreme point of the polygon we are "digging" */
+ /* to get from endpoint1 to endpoint2. */
+ if ((farvertex[0] == endpoint2[0]) && (farvertex[1] == endpoint2[1])) {
+ oprev(fixuptri, fixuptri2);
+ /* Enforce the Delaunay condition around endpoint2. */
+ delaunayfixup(m, b, &fixuptri, 0);
+ delaunayfixup(m, b, &fixuptri2, 1);
+ done = 1;
+ } else {
+ /* Check whether farvertex is to the left or right of the segment */
+ /* being inserted, to decide which edge of fixuptri to dig */
+ /* through next. */
+ area = counterclockwise(m, b, endpoint1, endpoint2, farvertex);
+ if (area == 0.0) {
+ /* We've collided with a vertex between endpoint1 and endpoint2. */
+ collision = 1;
+ oprev(fixuptri, fixuptri2);
+ /* Enforce the Delaunay condition around farvertex. */
+ delaunayfixup(m, b, &fixuptri, 0);
+ delaunayfixup(m, b, &fixuptri2, 1);
+ done = 1;
+ } else {
+ if (area > 0.0) { /* farvertex is to the left of the segment. */
+ oprev(fixuptri, fixuptri2);
+ /* Enforce the Delaunay condition around farvertex, on the */
+ /* left side of the segment only. */
+ delaunayfixup(m, b, &fixuptri2, 1);
+ /* Flip the edge that crosses the segment. After the edge is */
+ /* flipped, one of its endpoints is the fan vertex, and the */
+ /* destination of fixuptri is the fan vertex. */
+ lprevself(fixuptri);
+ } else { /* farvertex is to the right of the segment. */
+ delaunayfixup(m, b, &fixuptri, 0);
+ /* Flip the edge that crosses the segment. After the edge is */
+ /* flipped, one of its endpoints is the fan vertex, and the */
+ /* destination of fixuptri is the fan vertex. */
+ oprevself(fixuptri);
+ }
+ /* Check for two intersecting segments. */
+ tspivot(fixuptri, crosssubseg);
+ if (crosssubseg.ss == m->dummysub) {
+ flip(m, b, &fixuptri); /* May create inverted triangle at left. */
+ } else {
+ /* We've collided with a segment between endpoint1 and endpoint2. */
+ collision = 1;
+ /* Insert a vertex at the intersection. */
+ segmentintersection(m, b, &fixuptri, &crosssubseg, endpoint2);
+ done = 1;
+ }
+ }
+ }
+ } while (!done);
+ /* Insert a subsegment to make the segment permanent. */
+ insertsubseg(m, b, &fixuptri, newmark);
+ /* If there was a collision with an interceding vertex, install another */
+ /* segment connecting that vertex with endpoint2. */
+ if (collision) {
+ /* Insert the remainder of the segment. */
+ if (!scoutsegment(m, b, &fixuptri, endpoint2, newmark)) {
+ constrainededge(m, b, &fixuptri, endpoint2, newmark);
+ }
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* insertsegment() Insert a PSLG segment into a triangulation. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void insertsegment(struct mesh *m, struct behavior *b,
+ vertex endpoint1, vertex endpoint2, int newmark)
+#else /* not ANSI_DECLARATORS */
+void insertsegment(m, b, endpoint1, endpoint2, newmark)
+struct mesh *m;
+struct behavior *b;
+vertex endpoint1;
+vertex endpoint2;
+int newmark;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri searchtri1, searchtri2;
+ triangle encodedtri;
+ vertex checkvertex;
+ triangle ptr; /* Temporary variable used by sym(). */
+
+ if (b->verbose > 1) {
+ printf(" Connecting (%.12g, %.12g) to (%.12g, %.12g).\n",
+ endpoint1[0], endpoint1[1], endpoint2[0], endpoint2[1]);
+ }
+
+ /* Find a triangle whose origin is the segment's first endpoint. */
+ checkvertex = (vertex) NULL;
+ encodedtri = vertex2tri(endpoint1);
+ if (encodedtri != (triangle) NULL) {
+ decode(encodedtri, searchtri1);
+ org(searchtri1, checkvertex);
+ }
+ if (checkvertex != endpoint1) {
+ /* Find a boundary triangle to search from. */
+ searchtri1.tri = m->dummytri;
+ searchtri1.orient = 0;
+ symself(searchtri1);
+ /* Search for the segment's first endpoint by point location. */
+ if (locate(m, b, endpoint1, &searchtri1) != ONVERTEX) {
+ printf(
+ "Internal error in insertsegment(): Unable to locate PSLG vertex\n");
+ printf(" (%.12g, %.12g) in triangulation.\n",
+ endpoint1[0], endpoint1[1]);
+ internalerror();
+ }
+ }
+ /* Remember this triangle to improve subsequent point location. */
+ otricopy(searchtri1, m->recenttri);
+ /* Scout the beginnings of a path from the first endpoint */
+ /* toward the second. */
+ if (scoutsegment(m, b, &searchtri1, endpoint2, newmark)) {
+ /* The segment was easily inserted. */
+ return;
+ }
+ /* The first endpoint may have changed if a collision with an intervening */
+ /* vertex on the segment occurred. */
+ org(searchtri1, endpoint1);
+
+ /* Find a triangle whose origin is the segment's second endpoint. */
+ checkvertex = (vertex) NULL;
+ encodedtri = vertex2tri(endpoint2);
+ if (encodedtri != (triangle) NULL) {
+ decode(encodedtri, searchtri2);
+ org(searchtri2, checkvertex);
+ }
+ if (checkvertex != endpoint2) {
+ /* Find a boundary triangle to search from. */
+ searchtri2.tri = m->dummytri;
+ searchtri2.orient = 0;
+ symself(searchtri2);
+ /* Search for the segment's second endpoint by point location. */
+ if (locate(m, b, endpoint2, &searchtri2) != ONVERTEX) {
+ printf(
+ "Internal error in insertsegment(): Unable to locate PSLG vertex\n");
+ printf(" (%.12g, %.12g) in triangulation.\n",
+ endpoint2[0], endpoint2[1]);
+ internalerror();
+ }
+ }
+ /* Remember this triangle to improve subsequent point location. */
+ otricopy(searchtri2, m->recenttri);
+ /* Scout the beginnings of a path from the second endpoint */
+ /* toward the first. */
+ if (scoutsegment(m, b, &searchtri2, endpoint1, newmark)) {
+ /* The segment was easily inserted. */
+ return;
+ }
+ /* The second endpoint may have changed if a collision with an intervening */
+ /* vertex on the segment occurred. */
+ org(searchtri2, endpoint2);
+
+#ifndef REDUCED
+#ifndef CDT_ONLY
+ if (b->splitseg) {
+ /* Insert vertices to force the segment into the triangulation. */
+ conformingedge(m, b, endpoint1, endpoint2, newmark);
+ } else {
+#endif /* not CDT_ONLY */
+#endif /* not REDUCED */
+ /* Insert the segment directly into the triangulation. */
+ constrainededge(m, b, &searchtri1, endpoint2, newmark);
+#ifndef REDUCED
+#ifndef CDT_ONLY
+ }
+#endif /* not CDT_ONLY */
+#endif /* not REDUCED */
+}
+
+/*****************************************************************************/
+/* */
+/* markhull() Cover the convex hull of a triangulation with subsegments. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void markhull(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void markhull(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri hulltri;
+ struct otri nexttri;
+ struct otri starttri;
+ triangle ptr; /* Temporary variable used by sym() and oprev(). */
+
+ /* Find a triangle handle on the hull. */
+ hulltri.tri = m->dummytri;
+ hulltri.orient = 0;
+ symself(hulltri);
+ /* Remember where we started so we know when to stop. */
+ otricopy(hulltri, starttri);
+ /* Go once counterclockwise around the convex hull. */
+ do {
+ /* Create a subsegment if there isn't already one here. */
+ insertsubseg(m, b, &hulltri, 1);
+ /* To find the next hull edge, go clockwise around the next vertex. */
+ lnextself(hulltri);
+ oprev(hulltri, nexttri);
+ while (nexttri.tri != m->dummytri) {
+ otricopy(nexttri, hulltri);
+ oprev(hulltri, nexttri);
+ }
+ } while (!otriequal(hulltri, starttri));
+}
+
+/*****************************************************************************/
+/* */
+/* formskeleton() Create the segments of a triangulation, including PSLG */
+/* segments and edges on the convex hull. */
+/* */
+/* The PSLG segments are read from a .poly file. The return value is the */
+/* number of segments in the file. */
+/* */
+/*****************************************************************************/
+
+#ifdef TRILIBRARY
+
+#ifdef ANSI_DECLARATORS
+void formskeleton(struct mesh *m, struct behavior *b, int *segmentlist,
+ int *segmentmarkerlist, int numberofsegments)
+#else /* not ANSI_DECLARATORS */
+void formskeleton(m, b, segmentlist, segmentmarkerlist, numberofsegments)
+struct mesh *m;
+struct behavior *b;
+int *segmentlist;
+int *segmentmarkerlist;
+int numberofsegments;
+#endif /* not ANSI_DECLARATORS */
+
+#else /* not TRILIBRARY */
+
+#ifdef ANSI_DECLARATORS
+void formskeleton(struct mesh *m, struct behavior *b,
+ FILE *polyfile, char *polyfilename)
+#else /* not ANSI_DECLARATORS */
+void formskeleton(m, b, polyfile, polyfilename)
+struct mesh *m;
+struct behavior *b;
+FILE *polyfile;
+char *polyfilename;
+#endif /* not ANSI_DECLARATORS */
+
+#endif /* not TRILIBRARY */
+
+{
+#ifdef TRILIBRARY
+ char polyfilename[6];
+ int index;
+#else /* not TRILIBRARY */
+ char inputline[INPUTLINESIZE];
+ char *stringptr;
+#endif /* not TRILIBRARY */
+ vertex endpoint1, endpoint2;
+ int segmentmarkers;
+ int end1, end2;
+ int boundmarker;
+ int i;
+
+ if (b->poly) {
+ if (!b->quiet) {
+ printf("Recovering segments in Delaunay triangulation.\n");
+ }
+#ifdef TRILIBRARY
+ strcpy(polyfilename, "input");
+ m->insegments = numberofsegments;
+ segmentmarkers = segmentmarkerlist != (int *) NULL;
+ index = 0;
+#else /* not TRILIBRARY */
+ /* Read the segments from a .poly file. */
+ /* Read number of segments and number of boundary markers. */
+ stringptr = readline(inputline, polyfile, polyfilename);
+ m->insegments = (int) strtol(stringptr, &stringptr, 0);
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ segmentmarkers = 0;
+ } else {
+ segmentmarkers = (int) strtol(stringptr, &stringptr, 0);
+ }
+#endif /* not TRILIBRARY */
+ /* If the input vertices are collinear, there is no triangulation, */
+ /* so don't try to insert segments. */
+ if (m->triangles.items == 0) {
+ return;
+ }
+
+ /* If segments are to be inserted, compute a mapping */
+ /* from vertices to triangles. */
+ if (m->insegments > 0) {
+ makevertexmap(m, b);
+ if (b->verbose) {
+ printf(" Recovering PSLG segments.\n");
+ }
+ }
+
+ boundmarker = 0;
+ /* Read and insert the segments. */
+ for (i = 0; i < m->insegments; i++) {
+#ifdef TRILIBRARY
+ end1 = segmentlist[index++];
+ end2 = segmentlist[index++];
+ if (segmentmarkers) {
+ boundmarker = segmentmarkerlist[i];
+ }
+#else /* not TRILIBRARY */
+ stringptr = readline(inputline, polyfile, b->inpolyfilename);
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ printf("Error: Segment %d has no endpoints in %s.\n",
+ b->firstnumber + i, polyfilename);
+ triexit(1);
+ } else {
+ end1 = (int) strtol(stringptr, &stringptr, 0);
+ }
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ printf("Error: Segment %d is missing its second endpoint in %s.\n",
+ b->firstnumber + i, polyfilename);
+ triexit(1);
+ } else {
+ end2 = (int) strtol(stringptr, &stringptr, 0);
+ }
+ if (segmentmarkers) {
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ boundmarker = 0;
+ } else {
+ boundmarker = (int) strtol(stringptr, &stringptr, 0);
+ }
+ }
+#endif /* not TRILIBRARY */
+ if ((end1 < b->firstnumber) ||
+ (end1 >= b->firstnumber + m->invertices)) {
+ if (!b->quiet) {
+ printf("Warning: Invalid first endpoint of segment %d in %s.\n",
+ b->firstnumber + i, polyfilename);
+ }
+ } else if ((end2 < b->firstnumber) ||
+ (end2 >= b->firstnumber + m->invertices)) {
+ if (!b->quiet) {
+ printf("Warning: Invalid second endpoint of segment %d in %s.\n",
+ b->firstnumber + i, polyfilename);
+ }
+ } else {
+ /* Find the vertices numbered `end1' and `end2'. */
+ endpoint1 = getvertex(m, b, end1);
+ endpoint2 = getvertex(m, b, end2);
+ if ((endpoint1[0] == endpoint2[0]) && (endpoint1[1] == endpoint2[1])) {
+ if (!b->quiet) {
+ printf("Warning: Endpoints of segment %d are coincident in %s.\n",
+ b->firstnumber + i, polyfilename);
+ }
+ } else {
+ insertsegment(m, b, endpoint1, endpoint2, boundmarker);
+ }
+ }
+ }
+ } else {
+ m->insegments = 0;
+ }
+ if (b->convex || !b->poly) {
+ /* Enclose the convex hull with subsegments. */
+ if (b->verbose) {
+ printf(" Enclosing convex hull with segments.\n");
+ }
+ markhull(m, b);
+ }
+}
+
+/** **/
+/** **/
+/********* Segment insertion ends here *********/
+
+/********* Carving out holes and concavities begins here *********/
+/** **/
+/** **/
+
+/*****************************************************************************/
+/* */
+/* infecthull() Virally infect all of the triangles of the convex hull */
+/* that are not protected by subsegments. Where there are */
+/* subsegments, set boundary markers as appropriate. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void infecthull(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void infecthull(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri hulltri;
+ struct otri nexttri;
+ struct otri starttri;
+ struct osub hullsubseg;
+ triangle **deadtriangle;
+ vertex horg, hdest;
+ triangle ptr; /* Temporary variable used by sym(). */
+ subseg sptr; /* Temporary variable used by tspivot(). */
+
+ if (b->verbose) {
+ printf(" Marking concavities (external triangles) for elimination.\n");
+ }
+ /* Find a triangle handle on the hull. */
+ hulltri.tri = m->dummytri;
+ hulltri.orient = 0;
+ symself(hulltri);
+ /* Remember where we started so we know when to stop. */
+ otricopy(hulltri, starttri);
+ /* Go once counterclockwise around the convex hull. */
+ do {
+ /* Ignore triangles that are already infected. */
+ if (!infected(hulltri)) {
+ /* Is the triangle protected by a subsegment? */
+ tspivot(hulltri, hullsubseg);
+ if (hullsubseg.ss == m->dummysub) {
+ /* The triangle is not protected; infect it. */
+ if (!infected(hulltri)) {
+ infect(hulltri);
+ deadtriangle = (triangle **) poolalloc(&m->viri);
+ *deadtriangle = hulltri.tri;
+ }
+ } else {
+ /* The triangle is protected; set boundary markers if appropriate. */
+ if (mark(hullsubseg) == 0) {
+ setmark(hullsubseg, 1);
+ org(hulltri, horg);
+ dest(hulltri, hdest);
+ if (vertexmark(horg) == 0) {
+ setvertexmark(horg, 1);
+ }
+ if (vertexmark(hdest) == 0) {
+ setvertexmark(hdest, 1);
+ }
+ }
+ }
+ }
+ /* To find the next hull edge, go clockwise around the next vertex. */
+ lnextself(hulltri);
+ oprev(hulltri, nexttri);
+ while (nexttri.tri != m->dummytri) {
+ otricopy(nexttri, hulltri);
+ oprev(hulltri, nexttri);
+ }
+ } while (!otriequal(hulltri, starttri));
+}
+
+/*****************************************************************************/
+/* */
+/* plague() Spread the virus from all infected triangles to any neighbors */
+/* not protected by subsegments. Delete all infected triangles. */
+/* */
+/* This is the procedure that actually creates holes and concavities. */
+/* */
+/* This procedure operates in two phases. The first phase identifies all */
+/* the triangles that will die, and marks them as infected. They are */
+/* marked to ensure that each triangle is added to the virus pool only */
+/* once, so the procedure will terminate. */
+/* */
+/* The second phase actually eliminates the infected triangles. It also */
+/* eliminates orphaned vertices. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void plague(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void plague(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri testtri;
+ struct otri neighbor;
+ triangle **virusloop;
+ triangle **deadtriangle;
+ struct osub neighborsubseg;
+ vertex testvertex;
+ vertex norg, ndest;
+ vertex deadorg, deaddest, deadapex;
+ int killorg;
+ triangle ptr; /* Temporary variable used by sym() and onext(). */
+ subseg sptr; /* Temporary variable used by tspivot(). */
+
+ if (b->verbose) {
+ printf(" Marking neighbors of marked triangles.\n");
+ }
+ /* Loop through all the infected triangles, spreading the virus to */
+ /* their neighbors, then to their neighbors' neighbors. */
+ traversalinit(&m->viri);
+ virusloop = (triangle **) traverse(&m->viri);
+ while (virusloop != (triangle **) NULL) {
+ testtri.tri = *virusloop;
+ /* A triangle is marked as infected by messing with one of its pointers */
+ /* to subsegments, setting it to an illegal value. Hence, we have to */
+ /* temporarily uninfect this triangle so that we can examine its */
+ /* adjacent subsegments. */
+ uninfect(testtri);
+ if (b->verbose > 2) {
+ /* Assign the triangle an orientation for convenience in */
+ /* checking its vertices. */
+ testtri.orient = 0;
+ org(testtri, deadorg);
+ dest(testtri, deaddest);
+ apex(testtri, deadapex);
+ printf(" Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
+ deadorg[0], deadorg[1], deaddest[0], deaddest[1],
+ deadapex[0], deadapex[1]);
+ }
+ /* Check each of the triangle's three neighbors. */
+ for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
+ /* Find the neighbor. */
+ sym(testtri, neighbor);
+ /* Check for a subsegment between the triangle and its neighbor. */
+ tspivot(testtri, neighborsubseg);
+ /* Check if the neighbor is nonexistent or already infected. */
+ if ((neighbor.tri == m->dummytri) || infected(neighbor)) {
+ if (neighborsubseg.ss != m->dummysub) {
+ /* There is a subsegment separating the triangle from its */
+ /* neighbor, but both triangles are dying, so the subsegment */
+ /* dies too. */
+ subsegdealloc(m, neighborsubseg.ss);
+ if (neighbor.tri != m->dummytri) {
+ /* Make sure the subsegment doesn't get deallocated again */
+ /* later when the infected neighbor is visited. */
+ uninfect(neighbor);
+ tsdissolve(neighbor);
+ infect(neighbor);
+ }
+ }
+ } else { /* The neighbor exists and is not infected. */
+ if (neighborsubseg.ss == m->dummysub) {
+ /* There is no subsegment protecting the neighbor, so */
+ /* the neighbor becomes infected. */
+ if (b->verbose > 2) {
+ org(neighbor, deadorg);
+ dest(neighbor, deaddest);
+ apex(neighbor, deadapex);
+ printf(
+ " Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
+ deadorg[0], deadorg[1], deaddest[0], deaddest[1],
+ deadapex[0], deadapex[1]);
+ }
+ infect(neighbor);
+ /* Ensure that the neighbor's neighbors will be infected. */
+ deadtriangle = (triangle **) poolalloc(&m->viri);
+ *deadtriangle = neighbor.tri;
+ } else { /* The neighbor is protected by a subsegment. */
+ /* Remove this triangle from the subsegment. */
+ stdissolve(neighborsubseg);
+ /* The subsegment becomes a boundary. Set markers accordingly. */
+ if (mark(neighborsubseg) == 0) {
+ setmark(neighborsubseg, 1);
+ }
+ org(neighbor, norg);
+ dest(neighbor, ndest);
+ if (vertexmark(norg) == 0) {
+ setvertexmark(norg, 1);
+ }
+ if (vertexmark(ndest) == 0) {
+ setvertexmark(ndest, 1);
+ }
+ }
+ }
+ }
+ /* Remark the triangle as infected, so it doesn't get added to the */
+ /* virus pool again. */
+ infect(testtri);
+ virusloop = (triangle **) traverse(&m->viri);
+ }
+
+ if (b->verbose) {
+ printf(" Deleting marked triangles.\n");
+ }
+
+ traversalinit(&m->viri);
+ virusloop = (triangle **) traverse(&m->viri);
+ while (virusloop != (triangle **) NULL) {
+ testtri.tri = *virusloop;
+
+ /* Check each of the three corners of the triangle for elimination. */
+ /* This is done by walking around each vertex, checking if it is */
+ /* still connected to at least one live triangle. */
+ for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
+ org(testtri, testvertex);
+ /* Check if the vertex has already been tested. */
+ if (testvertex != (vertex) NULL) {
+ killorg = 1;
+ /* Mark the corner of the triangle as having been tested. */
+ setorg(testtri, NULL);
+ /* Walk counterclockwise about the vertex. */
+ onext(testtri, neighbor);
+ /* Stop upon reaching a boundary or the starting triangle. */
+ while ((neighbor.tri != m->dummytri) &&
+ (!otriequal(neighbor, testtri))) {
+ if (infected(neighbor)) {
+ /* Mark the corner of this triangle as having been tested. */
+ setorg(neighbor, NULL);
+ } else {
+ /* A live triangle. The vertex survives. */
+ killorg = 0;
+ }
+ /* Walk counterclockwise about the vertex. */
+ onextself(neighbor);
+ }
+ /* If we reached a boundary, we must walk clockwise as well. */
+ if (neighbor.tri == m->dummytri) {
+ /* Walk clockwise about the vertex. */
+ oprev(testtri, neighbor);
+ /* Stop upon reaching a boundary. */
+ while (neighbor.tri != m->dummytri) {
+ if (infected(neighbor)) {
+ /* Mark the corner of this triangle as having been tested. */
+ setorg(neighbor, NULL);
+ } else {
+ /* A live triangle. The vertex survives. */
+ killorg = 0;
+ }
+ /* Walk clockwise about the vertex. */
+ oprevself(neighbor);
+ }
+ }
+ if (killorg) {
+ if (b->verbose > 1) {
+ printf(" Deleting vertex (%.12g, %.12g)\n",
+ testvertex[0], testvertex[1]);
+ }
+ setvertextype(testvertex, UNDEADVERTEX);
+ m->undeads++;
+ }
+ }
+ }
+
+ /* Record changes in the number of boundary edges, and disconnect */
+ /* dead triangles from their neighbors. */
+ for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
+ sym(testtri, neighbor);
+ if (neighbor.tri == m->dummytri) {
+ /* There is no neighboring triangle on this edge, so this edge */
+ /* is a boundary edge. This triangle is being deleted, so this */
+ /* boundary edge is deleted. */
+ m->hullsize--;
+ } else {
+ /* Disconnect the triangle from its neighbor. */
+ dissolve(neighbor);
+ /* There is a neighboring triangle on this edge, so this edge */
+ /* becomes a boundary edge when this triangle is deleted. */
+ m->hullsize++;
+ }
+ }
+ /* Return the dead triangle to the pool of triangles. */
+ triangledealloc(m, testtri.tri);
+ virusloop = (triangle **) traverse(&m->viri);
+ }
+ /* Empty the virus pool. */
+ poolrestart(&m->viri);
+}
+
+/*****************************************************************************/
+/* */
+/* regionplague() Spread regional attributes and/or area constraints */
+/* (from a .poly file) throughout the mesh. */
+/* */
+/* This procedure operates in two phases. The first phase spreads an */
+/* attribute and/or an area constraint through a (segment-bounded) region. */
+/* The triangles are marked to ensure that each triangle is added to the */
+/* virus pool only once, so the procedure will terminate. */
+/* */
+/* The second phase uninfects all infected triangles, returning them to */
+/* normal. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void regionplague(struct mesh *m, struct behavior *b,
+ REAL attribute, REAL area)
+#else /* not ANSI_DECLARATORS */
+void regionplague(m, b, attribute, area)
+struct mesh *m;
+struct behavior *b;
+REAL attribute;
+REAL area;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri testtri;
+ struct otri neighbor;
+ triangle **virusloop;
+ triangle **regiontri;
+ struct osub neighborsubseg;
+ vertex regionorg, regiondest, regionapex;
+ triangle ptr; /* Temporary variable used by sym() and onext(). */
+ subseg sptr; /* Temporary variable used by tspivot(). */
+
+ if (b->verbose > 1) {
+ printf(" Marking neighbors of marked triangles.\n");
+ }
+ /* Loop through all the infected triangles, spreading the attribute */
+ /* and/or area constraint to their neighbors, then to their neighbors' */
+ /* neighbors. */
+ traversalinit(&m->viri);
+ virusloop = (triangle **) traverse(&m->viri);
+ while (virusloop != (triangle **) NULL) {
+ testtri.tri = *virusloop;
+ /* A triangle is marked as infected by messing with one of its pointers */
+ /* to subsegments, setting it to an illegal value. Hence, we have to */
+ /* temporarily uninfect this triangle so that we can examine its */
+ /* adjacent subsegments. */
+ uninfect(testtri);
+ if (b->regionattrib) {
+ /* Set an attribute. */
+ setelemattribute(testtri, m->eextras, attribute);
+ }
+ if (b->vararea) {
+ /* Set an area constraint. */
+ setareabound(testtri, area);
+ }
+ if (b->verbose > 2) {
+ /* Assign the triangle an orientation for convenience in */
+ /* checking its vertices. */
+ testtri.orient = 0;
+ org(testtri, regionorg);
+ dest(testtri, regiondest);
+ apex(testtri, regionapex);
+ printf(" Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
+ regionorg[0], regionorg[1], regiondest[0], regiondest[1],
+ regionapex[0], regionapex[1]);
+ }
+ /* Check each of the triangle's three neighbors. */
+ for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) {
+ /* Find the neighbor. */
+ sym(testtri, neighbor);
+ /* Check for a subsegment between the triangle and its neighbor. */
+ tspivot(testtri, neighborsubseg);
+ /* Make sure the neighbor exists, is not already infected, and */
+ /* isn't protected by a subsegment. */
+ if ((neighbor.tri != m->dummytri) && !infected(neighbor)
+ && (neighborsubseg.ss == m->dummysub)) {
+ if (b->verbose > 2) {
+ org(neighbor, regionorg);
+ dest(neighbor, regiondest);
+ apex(neighbor, regionapex);
+ printf(" Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
+ regionorg[0], regionorg[1], regiondest[0], regiondest[1],
+ regionapex[0], regionapex[1]);
+ }
+ /* Infect the neighbor. */
+ infect(neighbor);
+ /* Ensure that the neighbor's neighbors will be infected. */
+ regiontri = (triangle **) poolalloc(&m->viri);
+ *regiontri = neighbor.tri;
+ }
+ }
+ /* Remark the triangle as infected, so it doesn't get added to the */
+ /* virus pool again. */
+ infect(testtri);
+ virusloop = (triangle **) traverse(&m->viri);
+ }
+
+ /* Uninfect all triangles. */
+ if (b->verbose > 1) {
+ printf(" Unmarking marked triangles.\n");
+ }
+ traversalinit(&m->viri);
+ virusloop = (triangle **) traverse(&m->viri);
+ while (virusloop != (triangle **) NULL) {
+ testtri.tri = *virusloop;
+ uninfect(testtri);
+ virusloop = (triangle **) traverse(&m->viri);
+ }
+ /* Empty the virus pool. */
+ poolrestart(&m->viri);
+}
+
+/*****************************************************************************/
+/* */
+/* carveholes() Find the holes and infect them. Find the area */
+/* constraints and infect them. Infect the convex hull. */
+/* Spread the infection and kill triangles. Spread the */
+/* area constraints. */
+/* */
+/* This routine mainly calls other routines to carry out all these */
+/* functions. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void carveholes(struct mesh *m, struct behavior *b, REAL *holelist, int holes,
+ REAL *regionlist, int regions)
+#else /* not ANSI_DECLARATORS */
+void carveholes(m, b, holelist, holes, regionlist, regions)
+struct mesh *m;
+struct behavior *b;
+REAL *holelist;
+int holes;
+REAL *regionlist;
+int regions;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri searchtri;
+ struct otri triangleloop;
+ struct otri *regiontris;
+ triangle **holetri;
+ triangle **regiontri;
+ vertex searchorg, searchdest;
+ enum locateresult intersect;
+ int i;
+ triangle ptr; /* Temporary variable used by sym(). */
+
+ if (!(b->quiet || (b->noholes && b->convex))) {
+ printf("Removing unwanted triangles.\n");
+ if (b->verbose && (holes > 0)) {
+ printf(" Marking holes for elimination.\n");
+ }
+ }
+
+ if (regions > 0) {
+ /* Allocate storage for the triangles in which region points fall. */
+ regiontris = (struct otri *) trimalloc(regions *
+ (int) sizeof(struct otri));
+ } else {
+ regiontris = (struct otri *) NULL;
+ }
+
+ if (((holes > 0) && !b->noholes) || !b->convex || (regions > 0)) {
+ /* Initialize a pool of viri to be used for holes, concavities, */
+ /* regional attributes, and/or regional area constraints. */
+ poolinit(&m->viri, sizeof(triangle *), VIRUSPERBLOCK, VIRUSPERBLOCK, 0);
+ }
+
+ if (!b->convex) {
+ /* Mark as infected any unprotected triangles on the boundary. */
+ /* This is one way by which concavities are created. */
+ infecthull(m, b);
+ }
+
+ if ((holes > 0) && !b->noholes) {
+ /* Infect each triangle in which a hole lies. */
+ for (i = 0; i < 2 * holes; i += 2) {
+ /* Ignore holes that aren't within the bounds of the mesh. */
+ if ((holelist[i] >= m->xmin) && (holelist[i] <= m->xmax)
+ && (holelist[i + 1] >= m->ymin) && (holelist[i + 1] <= m->ymax)) {
+ /* Start searching from some triangle on the outer boundary. */
+ searchtri.tri = m->dummytri;
+ searchtri.orient = 0;
+ symself(searchtri);
+ /* Ensure that the hole is to the left of this boundary edge; */
+ /* otherwise, locate() will falsely report that the hole */
+ /* falls within the starting triangle. */
+ org(searchtri, searchorg);
+ dest(searchtri, searchdest);
+ if (counterclockwise(m, b, searchorg, searchdest, &holelist[i]) >
+ 0.0) {
+ /* Find a triangle that contains the hole. */
+ intersect = locate(m, b, &holelist[i], &searchtri);
+ if ((intersect != OUTSIDE) && (!infected(searchtri))) {
+ /* Infect the triangle. This is done by marking the triangle */
+ /* as infected and including the triangle in the virus pool. */
+ infect(searchtri);
+ holetri = (triangle **) poolalloc(&m->viri);
+ *holetri = searchtri.tri;
+ }
+ }
+ }
+ }
+ }
+
+ /* Now, we have to find all the regions BEFORE we carve the holes, because */
+ /* locate() won't work when the triangulation is no longer convex. */
+ /* (Incidentally, this is the reason why regional attributes and area */
+ /* constraints can't be used when refining a preexisting mesh, which */
+ /* might not be convex; they can only be used with a freshly */
+ /* triangulated PSLG.) */
+ if (regions > 0) {
+ /* Find the starting triangle for each region. */
+ for (i = 0; i < regions; i++) {
+ regiontris[i].tri = m->dummytri;
+ /* Ignore region points that aren't within the bounds of the mesh. */
+ if ((regionlist[4 * i] >= m->xmin) && (regionlist[4 * i] <= m->xmax) &&
+ (regionlist[4 * i + 1] >= m->ymin) &&
+ (regionlist[4 * i + 1] <= m->ymax)) {
+ /* Start searching from some triangle on the outer boundary. */
+ searchtri.tri = m->dummytri;
+ searchtri.orient = 0;
+ symself(searchtri);
+ /* Ensure that the region point is to the left of this boundary */
+ /* edge; otherwise, locate() will falsely report that the */
+ /* region point falls within the starting triangle. */
+ org(searchtri, searchorg);
+ dest(searchtri, searchdest);
+ if (counterclockwise(m, b, searchorg, searchdest, ®ionlist[4 * i]) >
+ 0.0) {
+ /* Find a triangle that contains the region point. */
+ intersect = locate(m, b, ®ionlist[4 * i], &searchtri);
+ if ((intersect != OUTSIDE) && (!infected(searchtri))) {
+ /* Record the triangle for processing after the */
+ /* holes have been carved. */
+ otricopy(searchtri, regiontris[i]);
+ }
+ }
+ }
+ }
+ }
+
+ if (m->viri.items > 0) {
+ /* Carve the holes and concavities. */
+ plague(m, b);
+ }
+ /* The virus pool should be empty now. */
+
+ if (regions > 0) {
+ if (!b->quiet) {
+ if (b->regionattrib) {
+ if (b->vararea) {
+ printf("Spreading regional attributes and area constraints.\n");
+ } else {
+ printf("Spreading regional attributes.\n");
+ }
+ } else {
+ printf("Spreading regional area constraints.\n");
+ }
+ }
+ if (b->regionattrib && !b->refine) {
+ /* Assign every triangle a regional attribute of zero. */
+ traversalinit(&m->triangles);
+ triangleloop.orient = 0;
+ triangleloop.tri = triangletraverse(m);
+ while (triangleloop.tri != (triangle *) NULL) {
+ setelemattribute(triangleloop, m->eextras, 0.0);
+ triangleloop.tri = triangletraverse(m);
+ }
+ }
+ for (i = 0; i < regions; i++) {
+ if (regiontris[i].tri != m->dummytri) {
+ /* Make sure the triangle under consideration still exists. */
+ /* It may have been eaten by the virus. */
+ if (!deadtri(regiontris[i].tri)) {
+ /* Put one triangle in the virus pool. */
+ infect(regiontris[i]);
+ regiontri = (triangle **) poolalloc(&m->viri);
+ *regiontri = regiontris[i].tri;
+ /* Apply one region's attribute and/or area constraint. */
+ regionplague(m, b, regionlist[4 * i + 2], regionlist[4 * i + 3]);
+ /* The virus pool should be empty now. */
+ }
+ }
+ }
+ if (b->regionattrib && !b->refine) {
+ /* Note the fact that each triangle has an additional attribute. */
+ m->eextras++;
+ }
+ }
+
+ /* Free up memory. */
+ if (((holes > 0) && !b->noholes) || !b->convex || (regions > 0)) {
+ pooldeinit(&m->viri);
+ }
+ if (regions > 0) {
+ trifree((VOID *) regiontris);
+ }
+}
+
+/** **/
+/** **/
+/********* Carving out holes and concavities ends here *********/
+
+/********* Mesh quality maintenance begins here *********/
+/** **/
+/** **/
+
+/*****************************************************************************/
+/* */
+/* tallyencs() Traverse the entire list of subsegments, and check each */
+/* to see if it is encroached. If so, add it to the list. */
+/* */
+/*****************************************************************************/
+
+#ifndef CDT_ONLY
+
+#ifdef ANSI_DECLARATORS
+void tallyencs(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void tallyencs(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct osub subsegloop;
+ int dummy;
+
+ traversalinit(&m->subsegs);
+ subsegloop.ssorient = 0;
+ subsegloop.ss = subsegtraverse(m);
+ while (subsegloop.ss != (subseg *) NULL) {
+ /* If the segment is encroached, add it to the list. */
+ dummy = checkseg4encroach(m, b, &subsegloop);
+ subsegloop.ss = subsegtraverse(m);
+ }
+}
+
+#endif /* not CDT_ONLY */
+
+/*****************************************************************************/
+/* */
+/* precisionerror() Print an error message for precision problems. */
+/* */
+/*****************************************************************************/
+
+#ifndef CDT_ONLY
+
+void precisionerror()
+{
+ printf("Try increasing the area criterion and/or reducing the minimum\n");
+ printf(" allowable angle so that tiny triangles are not created.\n");
+#ifdef SINGLE
+ printf("Alternatively, try recompiling me with double precision\n");
+ printf(" arithmetic (by removing \"#define SINGLE\" from the\n");
+ printf(" source file or \"-DSINGLE\" from the makefile).\n");
+#endif /* SINGLE */
+}
+
+#endif /* not CDT_ONLY */
+
+/*****************************************************************************/
+/* */
+/* splitencsegs() Split all the encroached subsegments. */
+/* */
+/* Each encroached subsegment is repaired by splitting it - inserting a */
+/* vertex at or near its midpoint. Newly inserted vertices may encroach */
+/* upon other subsegments; these are also repaired. */
+/* */
+/* `triflaws' is a flag that specifies whether one should take note of new */
+/* bad triangles that result from inserting vertices to repair encroached */
+/* subsegments. */
+/* */
+/*****************************************************************************/
+
+#ifndef CDT_ONLY
+
+#ifdef ANSI_DECLARATORS
+void splitencsegs(struct mesh *m, struct behavior *b, int triflaws)
+#else /* not ANSI_DECLARATORS */
+void splitencsegs(m, b, triflaws)
+struct mesh *m;
+struct behavior *b;
+int triflaws;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri enctri;
+ struct otri testtri;
+ struct osub testsh;
+ struct osub currentenc;
+ struct badsubseg *encloop;
+ vertex eorg, edest, eapex;
+ vertex newvertex;
+ enum insertvertexresult success;
+ REAL segmentlength, nearestpoweroftwo;
+ REAL split;
+ REAL multiplier, divisor;
+ int acuteorg, acuteorg2, acutedest, acutedest2;
+ int dummy;
+ int i;
+ triangle ptr; /* Temporary variable used by stpivot(). */
+ subseg sptr; /* Temporary variable used by snext(). */
+
+ /* Note that steinerleft == -1 if an unlimited number */
+ /* of Steiner points is allowed. */
+ while ((m->badsubsegs.items > 0) && (m->steinerleft != 0)) {
+ traversalinit(&m->badsubsegs);
+ encloop = badsubsegtraverse(m);
+ while ((encloop != (struct badsubseg *) NULL) && (m->steinerleft != 0)) {
+ sdecode(encloop->encsubseg, currentenc);
+ sorg(currentenc, eorg);
+ sdest(currentenc, edest);
+ /* Make sure that this segment is still the same segment it was */
+ /* when it was determined to be encroached. If the segment was */
+ /* enqueued multiple times (because several newly inserted */
+ /* vertices encroached it), it may have already been split. */
+ if (!deadsubseg(currentenc.ss) &&
+ (eorg == encloop->subsegorg) && (edest == encloop->subsegdest)) {
+ /* To decide where to split a segment, we need to know if the */
+ /* segment shares an endpoint with an adjacent segment. */
+ /* The concern is that, if we simply split every encroached */
+ /* segment in its center, two adjacent segments with a small */
+ /* angle between them might lead to an infinite loop; each */
+ /* vertex added to split one segment will encroach upon the */
+ /* other segment, which must then be split with a vertex that */
+ /* will encroach upon the first segment, and so on forever. */
+ /* To avoid this, imagine a set of concentric circles, whose */
+ /* radii are powers of two, about each segment endpoint. */
+ /* These concentric circles determine where the segment is */
+ /* split. (If both endpoints are shared with adjacent */
+ /* segments, split the segment in the middle, and apply the */
+ /* concentric circles for later splittings.) */
+
+ /* Is the origin shared with another segment? */
+ stpivot(currentenc, enctri);
+ lnext(enctri, testtri);
+ tspivot(testtri, testsh);
+ acuteorg = testsh.ss != m->dummysub;
+ /* Is the destination shared with another segment? */
+ lnextself(testtri);
+ tspivot(testtri, testsh);
+ acutedest = testsh.ss != m->dummysub;
+
+ /* If we're using Chew's algorithm (rather than Ruppert's) */
+ /* to define encroachment, delete free vertices from the */
+ /* subsegment's diametral circle. */
+ if (!b->conformdel && !acuteorg && !acutedest) {
+ apex(enctri, eapex);
+ while ((vertextype(eapex) == FREEVERTEX) &&
+ ((eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
+ (eorg[1] - eapex[1]) * (edest[1] - eapex[1]) < 0.0)) {
+ deletevertex(m, b, &testtri);
+ stpivot(currentenc, enctri);
+ apex(enctri, eapex);
+ lprev(enctri, testtri);
+ }
+ }
+
+ /* Now, check the other side of the segment, if there's a triangle */
+ /* there. */
+ sym(enctri, testtri);
+ if (testtri.tri != m->dummytri) {
+ /* Is the destination shared with another segment? */
+ lnextself(testtri);
+ tspivot(testtri, testsh);
+ acutedest2 = testsh.ss != m->dummysub;
+ acutedest = acutedest || acutedest2;
+ /* Is the origin shared with another segment? */
+ lnextself(testtri);
+ tspivot(testtri, testsh);
+ acuteorg2 = testsh.ss != m->dummysub;
+ acuteorg = acuteorg || acuteorg2;
+
+ /* Delete free vertices from the subsegment's diametral circle. */
+ if (!b->conformdel && !acuteorg2 && !acutedest2) {
+ org(testtri, eapex);
+ while ((vertextype(eapex) == FREEVERTEX) &&
+ ((eorg[0] - eapex[0]) * (edest[0] - eapex[0]) +
+ (eorg[1] - eapex[1]) * (edest[1] - eapex[1]) < 0.0)) {
+ deletevertex(m, b, &testtri);
+ sym(enctri, testtri);
+ apex(testtri, eapex);
+ lprevself(testtri);
+ }
+ }
+ }
+
+ /* Use the concentric circles if exactly one endpoint is shared */
+ /* with another adjacent segment. */
+ if (acuteorg || acutedest) {
+ segmentlength = sqrt((edest[0] - eorg[0]) * (edest[0] - eorg[0]) +
+ (edest[1] - eorg[1]) * (edest[1] - eorg[1]));
+ /* Find the power of two that most evenly splits the segment. */
+ /* The worst case is a 2:1 ratio between subsegment lengths. */
+ nearestpoweroftwo = 1.0;
+ while (segmentlength > 3.0 * nearestpoweroftwo) {
+ nearestpoweroftwo *= 2.0;
+ }
+ while (segmentlength < 1.5 * nearestpoweroftwo) {
+ nearestpoweroftwo *= 0.5;
+ }
+ /* Where do we split the segment? */
+ split = nearestpoweroftwo / segmentlength;
+ if (acutedest) {
+ split = 1.0 - split;
+ }
+ } else {
+ /* If we're not worried about adjacent segments, split */
+ /* this segment in the middle. */
+ split = 0.5;
+ }
+
+ /* Create the new vertex. */
+ newvertex = (vertex) poolalloc(&m->vertices);
+ /* Interpolate its coordinate and attributes. */
+ for (i = 0; i < 2 + m->nextras; i++) {
+ newvertex[i] = eorg[i] + split * (edest[i] - eorg[i]);
+ }
+
+ if (!b->noexact) {
+ /* Roundoff in the above calculation may yield a `newvertex' */
+ /* that is not precisely collinear with `eorg' and `edest'. */
+ /* Improve collinearity by one step of iterative refinement. */
+ multiplier = counterclockwise(m, b, eorg, edest, newvertex);
+ divisor = ((eorg[0] - edest[0]) * (eorg[0] - edest[0]) +
+ (eorg[1] - edest[1]) * (eorg[1] - edest[1]));
+ if ((multiplier != 0.0) && (divisor != 0.0)) {
+ multiplier = multiplier / divisor;
+ /* Watch out for NANs. */
+ if (multiplier == multiplier) {
+ newvertex[0] += multiplier * (edest[1] - eorg[1]);
+ newvertex[1] += multiplier * (eorg[0] - edest[0]);
+ }
+ }
+ }
+
+ setvertexmark(newvertex, mark(currentenc));
+ setvertextype(newvertex, SEGMENTVERTEX);
+ if (b->verbose > 1) {
+ printf(
+ " Splitting subsegment (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n",
+ eorg[0], eorg[1], edest[0], edest[1],
+ newvertex[0], newvertex[1]);
+ }
+ /* Check whether the new vertex lies on an endpoint. */
+ if (((newvertex[0] == eorg[0]) && (newvertex[1] == eorg[1])) ||
+ ((newvertex[0] == edest[0]) && (newvertex[1] == edest[1]))) {
+ printf("Error: Ran out of precision at (%.12g, %.12g).\n",
+ newvertex[0], newvertex[1]);
+ printf("I attempted to split a segment to a smaller size than\n");
+ printf(" can be accommodated by the finite precision of\n");
+ printf(" floating point arithmetic.\n");
+ precisionerror();
+ triexit(1);
+ }
+ /* Insert the splitting vertex. This should always succeed. */
+ success = insertvertex(m, b, newvertex, &enctri, ¤tenc,
+ 1, triflaws);
+ if ((success != SUCCESSFULVERTEX) && (success != ENCROACHINGVERTEX)) {
+ printf("Internal error in splitencsegs():\n");
+ printf(" Failure to split a segment.\n");
+ internalerror();
+ }
+ if (m->steinerleft > 0) {
+ m->steinerleft--;
+ }
+ /* Check the two new subsegments to see if they're encroached. */
+ dummy = checkseg4encroach(m, b, ¤tenc);
+ snextself(currentenc);
+ dummy = checkseg4encroach(m, b, ¤tenc);
+ }
+
+ badsubsegdealloc(m, encloop);
+ encloop = badsubsegtraverse(m);
+ }
+ }
+}
+
+#endif /* not CDT_ONLY */
+
+/*****************************************************************************/
+/* */
+/* tallyfaces() Test every triangle in the mesh for quality measures. */
+/* */
+/*****************************************************************************/
+
+#ifndef CDT_ONLY
+
+#ifdef ANSI_DECLARATORS
+void tallyfaces(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void tallyfaces(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri triangleloop;
+
+ if (b->verbose) {
+ printf(" Making a list of bad triangles.\n");
+ }
+ traversalinit(&m->triangles);
+ triangleloop.orient = 0;
+ triangleloop.tri = triangletraverse(m);
+ while (triangleloop.tri != (triangle *) NULL) {
+ /* If the triangle is bad, enqueue it. */
+ testtriangle(m, b, &triangleloop);
+ triangleloop.tri = triangletraverse(m);
+ }
+}
+
+#endif /* not CDT_ONLY */
+
+/*****************************************************************************/
+/* */
+/* splittriangle() Inserts a vertex at the circumcenter of a triangle. */
+/* Deletes the newly inserted vertex if it encroaches */
+/* upon a segment. */
+/* */
+/*****************************************************************************/
+
+#ifndef CDT_ONLY
+
+#ifdef ANSI_DECLARATORS
+void splittriangle(struct mesh *m, struct behavior *b,
+ struct badtriang *badtri)
+#else /* not ANSI_DECLARATORS */
+void splittriangle(m, b, badtri)
+struct mesh *m;
+struct behavior *b;
+struct badtriang *badtri;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri badotri;
+ vertex borg, bdest, bapex;
+ vertex newvertex;
+ REAL xi, eta;
+ enum insertvertexresult success;
+ int errorflag;
+ int i;
+
+ decode(badtri->poortri, badotri);
+ org(badotri, borg);
+ dest(badotri, bdest);
+ apex(badotri, bapex);
+ /* Make sure that this triangle is still the same triangle it was */
+ /* when it was tested and determined to be of bad quality. */
+ /* Subsequent transformations may have made it a different triangle. */
+ if (!deadtri(badotri.tri) && (borg == badtri->triangorg) &&
+ (bdest == badtri->triangdest) && (bapex == badtri->triangapex)) {
+ if (b->verbose > 1) {
+ printf(" Splitting this triangle at its circumcenter:\n");
+ printf(" (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", borg[0],
+ borg[1], bdest[0], bdest[1], bapex[0], bapex[1]);
+ }
+
+ errorflag = 0;
+ /* Create a new vertex at the triangle's circumcenter. */
+ newvertex = (vertex) poolalloc(&m->vertices);
+ findcircumcenter(m, b, borg, bdest, bapex, newvertex, &xi, &eta, 1);
+
+ /* Check whether the new vertex lies on a triangle vertex. */
+ if (((newvertex[0] == borg[0]) && (newvertex[1] == borg[1])) ||
+ ((newvertex[0] == bdest[0]) && (newvertex[1] == bdest[1])) ||
+ ((newvertex[0] == bapex[0]) && (newvertex[1] == bapex[1]))) {
+ if (!b->quiet) {
+ printf(
+ "Warning: New vertex (%.12g, %.12g) falls on existing vertex.\n",
+ newvertex[0], newvertex[1]);
+ errorflag = 1;
+ }
+ vertexdealloc(m, newvertex);
+ } else {
+ for (i = 2; i < 2 + m->nextras; i++) {
+ /* Interpolate the vertex attributes at the circumcenter. */
+ newvertex[i] = borg[i] + xi * (bdest[i] - borg[i])
+ + eta * (bapex[i] - borg[i]);
+ }
+ /* The new vertex must be in the interior, and therefore is a */
+ /* free vertex with a marker of zero. */
+ setvertexmark(newvertex, 0);
+ setvertextype(newvertex, FREEVERTEX);
+
+ /* Ensure that the handle `badotri' does not represent the longest */
+ /* edge of the triangle. This ensures that the circumcenter must */
+ /* fall to the left of this edge, so point location will work. */
+ /* (If the angle org-apex-dest exceeds 90 degrees, then the */
+ /* circumcenter lies outside the org-dest edge, and eta is */
+ /* negative. Roundoff error might prevent eta from being */
+ /* negative when it should be, so I test eta against xi.) */
+ if (eta < xi) {
+ lprevself(badotri);
+ }
+
+ /* Insert the circumcenter, searching from the edge of the triangle, */
+ /* and maintain the Delaunay property of the triangulation. */
+ success = insertvertex(m, b, newvertex, &badotri, (struct osub *) NULL,
+ 1, 1);
+ if (success == SUCCESSFULVERTEX) {
+ if (m->steinerleft > 0) {
+ m->steinerleft--;
+ }
+ } else if (success == ENCROACHINGVERTEX) {
+ /* If the newly inserted vertex encroaches upon a subsegment, */
+ /* delete the new vertex. */
+ undovertex(m, b);
+ if (b->verbose > 1) {
+ printf(" Rejecting (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
+ }
+ vertexdealloc(m, newvertex);
+ } else if (success == VIOLATINGVERTEX) {
+ /* Failed to insert the new vertex, but some subsegment was */
+ /* marked as being encroached. */
+ vertexdealloc(m, newvertex);
+ } else { /* success == DUPLICATEVERTEX */
+ /* Couldn't insert the new vertex because a vertex is already there. */
+ if (!b->quiet) {
+ printf(
+ "Warning: New vertex (%.12g, %.12g) falls on existing vertex.\n",
+ newvertex[0], newvertex[1]);
+ errorflag = 1;
+ }
+ vertexdealloc(m, newvertex);
+ }
+ }
+ if (errorflag) {
+ if (b->verbose) {
+ printf(" The new vertex is at the circumcenter of triangle\n");
+ printf(" (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n",
+ borg[0], borg[1], bdest[0], bdest[1], bapex[0], bapex[1]);
+ }
+ printf("This probably means that I am trying to refine triangles\n");
+ printf(" to a smaller size than can be accommodated by the finite\n");
+ printf(" precision of floating point arithmetic. (You can be\n");
+ printf(" sure of this if I fail to terminate.)\n");
+ precisionerror();
+ }
+ }
+}
+
+#endif /* not CDT_ONLY */
+
+/*****************************************************************************/
+/* */
+/* enforcequality() Remove all the encroached subsegments and bad */
+/* triangles from the triangulation. */
+/* */
+/*****************************************************************************/
+
+#ifndef CDT_ONLY
+
+#ifdef ANSI_DECLARATORS
+void enforcequality(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void enforcequality(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct badtriang *badtri;
+ int i;
+
+ if (!b->quiet) {
+ printf("Adding Steiner points to enforce quality.\n");
+ }
+ /* Initialize the pool of encroached subsegments. */
+ poolinit(&m->badsubsegs, sizeof(struct badsubseg), BADSUBSEGPERBLOCK,
+ BADSUBSEGPERBLOCK, 0);
+ if (b->verbose) {
+ printf(" Looking for encroached subsegments.\n");
+ }
+ /* Test all segments to see if they're encroached. */
+ tallyencs(m, b);
+ if (b->verbose && (m->badsubsegs.items > 0)) {
+ printf(" Splitting encroached subsegments.\n");
+ }
+ /* Fix encroached subsegments without noting bad triangles. */
+ splitencsegs(m, b, 0);
+ /* At this point, if we haven't run out of Steiner points, the */
+ /* triangulation should be (conforming) Delaunay. */
+
+ /* Next, we worry about enforcing triangle quality. */
+ if ((b->minangle > 0.0) || b->vararea || b->fixedarea || b->usertest) {
+ /* Initialize the pool of bad triangles. */
+ poolinit(&m->badtriangles, sizeof(struct badtriang), BADTRIPERBLOCK,
+ BADTRIPERBLOCK, 0);
+ /* Initialize the queues of bad triangles. */
+ for (i = 0; i < 4096; i++) {
+ m->queuefront[i] = (struct badtriang *) NULL;
+ }
+ m->firstnonemptyq = -1;
+ /* Test all triangles to see if they're bad. */
+ tallyfaces(m, b);
+ /* Initialize the pool of recently flipped triangles. */
+ poolinit(&m->flipstackers, sizeof(struct flipstacker), FLIPSTACKERPERBLOCK,
+ FLIPSTACKERPERBLOCK, 0);
+ m->checkquality = 1;
+ if (b->verbose) {
+ printf(" Splitting bad triangles.\n");
+ }
+ while ((m->badtriangles.items > 0) && (m->steinerleft != 0)) {
+ /* Fix one bad triangle by inserting a vertex at its circumcenter. */
+ badtri = dequeuebadtriang(m);
+ splittriangle(m, b, badtri);
+ if (m->badsubsegs.items > 0) {
+ /* Put bad triangle back in queue for another try later. */
+ enqueuebadtriang(m, b, badtri);
+ /* Fix any encroached subsegments that resulted. */
+ /* Record any new bad triangles that result. */
+ splitencsegs(m, b, 1);
+ } else {
+ /* Return the bad triangle to the pool. */
+ pooldealloc(&m->badtriangles, (VOID *) badtri);
+ }
+ }
+ }
+ /* At this point, if the "-D" switch was selected and we haven't run out */
+ /* of Steiner points, the triangulation should be (conforming) Delaunay */
+ /* and have no low-quality triangles. */
+
+ /* Might we have run out of Steiner points too soon? */
+ if (!b->quiet && b->conformdel && (m->badsubsegs.items > 0) &&
+ (m->steinerleft == 0)) {
+ printf("\nWarning: I ran out of Steiner points, but the mesh has\n");
+ if (m->badsubsegs.items == 1) {
+ printf(" one encroached subsegment, and therefore might not be truly\n"
+ );
+ } else {
+ printf(" %ld encroached subsegments, and therefore might not be truly\n"
+ , m->badsubsegs.items);
+ }
+ printf(" Delaunay. If the Delaunay property is important to you,\n");
+ printf(" try increasing the number of Steiner points (controlled by\n");
+ printf(" the -S switch) slightly and try again.\n\n");
+ }
+}
+
+#endif /* not CDT_ONLY */
+
+/** **/
+/** **/
+/********* Mesh quality maintenance ends here *********/
+
+/*****************************************************************************/
+/* */
+/* highorder() Create extra nodes for quadratic subparametric elements. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void highorder(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void highorder(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri triangleloop, trisym;
+ struct osub checkmark;
+ vertex newvertex;
+ vertex torg, tdest;
+ int i;
+ triangle ptr; /* Temporary variable used by sym(). */
+ subseg sptr; /* Temporary variable used by tspivot(). */
+
+ if (!b->quiet) {
+ printf("Adding vertices for second-order triangles.\n");
+ }
+ /* The following line ensures that dead items in the pool of nodes */
+ /* cannot be allocated for the extra nodes associated with high */
+ /* order elements. This ensures that the primary nodes (at the */
+ /* corners of elements) will occur earlier in the output files, and */
+ /* have lower indices, than the extra nodes. */
+ m->vertices.deaditemstack = (VOID *) NULL;
+
+ traversalinit(&m->triangles);
+ triangleloop.tri = triangletraverse(m);
+ /* To loop over the set of edges, loop over all triangles, and look at */
+ /* the three edges of each triangle. If there isn't another triangle */
+ /* adjacent to the edge, operate on the edge. If there is another */
+ /* adjacent triangle, operate on the edge only if the current triangle */
+ /* has a smaller pointer than its neighbor. This way, each edge is */
+ /* considered only once. */
+ while (triangleloop.tri != (triangle *) NULL) {
+ for (triangleloop.orient = 0; triangleloop.orient < 3;
+ triangleloop.orient++) {
+ sym(triangleloop, trisym);
+ if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
+ org(triangleloop, torg);
+ dest(triangleloop, tdest);
+ /* Create a new node in the middle of the edge. Interpolate */
+ /* its attributes. */
+ newvertex = (vertex) poolalloc(&m->vertices);
+ for (i = 0; i < 2 + m->nextras; i++) {
+ newvertex[i] = 0.5 * (torg[i] + tdest[i]);
+ }
+ /* Set the new node's marker to zero or one, depending on */
+ /* whether it lies on a boundary. */
+ setvertexmark(newvertex, trisym.tri == m->dummytri);
+ setvertextype(newvertex,
+ trisym.tri == m->dummytri ? FREEVERTEX : SEGMENTVERTEX);
+ if (b->usesegments) {
+ tspivot(triangleloop, checkmark);
+ /* If this edge is a segment, transfer the marker to the new node. */
+ if (checkmark.ss != m->dummysub) {
+ setvertexmark(newvertex, mark(checkmark));
+ setvertextype(newvertex, SEGMENTVERTEX);
+ }
+ }
+ if (b->verbose > 1) {
+ printf(" Creating (%.12g, %.12g).\n", newvertex[0], newvertex[1]);
+ }
+ /* Record the new node in the (one or two) adjacent elements. */
+ triangleloop.tri[m->highorderindex + triangleloop.orient] =
+ (triangle) newvertex;
+ if (trisym.tri != m->dummytri) {
+ trisym.tri[m->highorderindex + trisym.orient] = (triangle) newvertex;
+ }
+ }
+ }
+ triangleloop.tri = triangletraverse(m);
+ }
+}
+
+/********* File I/O routines begin here *********/
+/** **/
+/** **/
+
+/*****************************************************************************/
+/* */
+/* readline() Read a nonempty line from a file. */
+/* */
+/* A line is considered "nonempty" if it contains something that looks like */
+/* a number. Comments (prefaced by `#') are ignored. */
+/* */
+/*****************************************************************************/
+
+#ifndef TRILIBRARY
+
+#ifdef ANSI_DECLARATORS
+char *readline(char *string, FILE *infile, char *infilename)
+#else /* not ANSI_DECLARATORS */
+char *readline(string, infile, infilename)
+char *string;
+FILE *infile;
+char *infilename;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ char *result;
+
+ /* Search for something that looks like a number. */
+ do {
+ result = fgets(string, INPUTLINESIZE, infile);
+ if (result == (char *) NULL) {
+ printf(" Error: Unexpected end of file in %s.\n", infilename);
+ triexit(1);
+ }
+ /* Skip anything that doesn't look like a number, a comment, */
+ /* or the end of a line. */
+ while ((*result != '\0') && (*result != '#')
+ && (*result != '.') && (*result != '+') && (*result != '-')
+ && ((*result < '0') || (*result > '9'))) {
+ result++;
+ }
+ /* If it's a comment or end of line, read another line and try again. */
+ } while ((*result == '#') || (*result == '\0'));
+ return result;
+}
+
+#endif /* not TRILIBRARY */
+
+/*****************************************************************************/
+/* */
+/* findfield() Find the next field of a string. */
+/* */
+/* Jumps past the current field by searching for whitespace, then jumps */
+/* past the whitespace to find the next field. */
+/* */
+/*****************************************************************************/
+
+#ifndef TRILIBRARY
+
+#ifdef ANSI_DECLARATORS
+char *findfield(char *string)
+#else /* not ANSI_DECLARATORS */
+char *findfield(string)
+char *string;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ char *result;
+
+ result = string;
+ /* Skip the current field. Stop upon reaching whitespace. */
+ while ((*result != '\0') && (*result != '#')
+ && (*result != ' ') && (*result != '\t')) {
+ result++;
+ }
+ /* Now skip the whitespace and anything else that doesn't look like a */
+ /* number, a comment, or the end of a line. */
+ while ((*result != '\0') && (*result != '#')
+ && (*result != '.') && (*result != '+') && (*result != '-')
+ && ((*result < '0') || (*result > '9'))) {
+ result++;
+ }
+ /* Check for a comment (prefixed with `#'). */
+ if (*result == '#') {
+ *result = '\0';
+ }
+ return result;
+}
+
+#endif /* not TRILIBRARY */
+
+/*****************************************************************************/
+/* */
+/* readnodes() Read the vertices from a file, which may be a .node or */
+/* .poly file. */
+/* */
+/*****************************************************************************/
+
+#ifndef TRILIBRARY
+
+#ifdef ANSI_DECLARATORS
+void readnodes(struct mesh *m, struct behavior *b, char *nodefilename,
+ char *polyfilename, FILE **polyfile)
+#else /* not ANSI_DECLARATORS */
+void readnodes(m, b, nodefilename, polyfilename, polyfile)
+struct mesh *m;
+struct behavior *b;
+char *nodefilename;
+char *polyfilename;
+FILE **polyfile;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ FILE *infile;
+ vertex vertexloop;
+ char inputline[INPUTLINESIZE];
+ char *stringptr;
+ char *infilename;
+ REAL x, y;
+ int firstnode;
+ int nodemarkers;
+ int currentmarker;
+ int i, j;
+
+ if (b->poly) {
+ /* Read the vertices from a .poly file. */
+ if (!b->quiet) {
+ printf("Opening %s.\n", polyfilename);
+ }
+ *polyfile = fopen(polyfilename, "r");
+ if (*polyfile == (FILE *) NULL) {
+ printf(" Error: Cannot access file %s.\n", polyfilename);
+ triexit(1);
+ }
+ /* Read number of vertices, number of dimensions, number of vertex */
+ /* attributes, and number of boundary markers. */
+ stringptr = readline(inputline, *polyfile, polyfilename);
+ m->invertices = (int) strtol(stringptr, &stringptr, 0);
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ m->mesh_dim = 2;
+ } else {
+ m->mesh_dim = (int) strtol(stringptr, &stringptr, 0);
+ }
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ m->nextras = 0;
+ } else {
+ m->nextras = (int) strtol(stringptr, &stringptr, 0);
+ }
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ nodemarkers = 0;
+ } else {
+ nodemarkers = (int) strtol(stringptr, &stringptr, 0);
+ }
+ if (m->invertices > 0) {
+ infile = *polyfile;
+ infilename = polyfilename;
+ m->readnodefile = 0;
+ } else {
+ /* If the .poly file claims there are zero vertices, that means that */
+ /* the vertices should be read from a separate .node file. */
+ m->readnodefile = 1;
+ infilename = nodefilename;
+ }
+ } else {
+ m->readnodefile = 1;
+ infilename = nodefilename;
+ *polyfile = (FILE *) NULL;
+ }
+
+ if (m->readnodefile) {
+ /* Read the vertices from a .node file. */
+ if (!b->quiet) {
+ printf("Opening %s.\n", nodefilename);
+ }
+ infile = fopen(nodefilename, "r");
+ if (infile == (FILE *) NULL) {
+ printf(" Error: Cannot access file %s.\n", nodefilename);
+ triexit(1);
+ }
+ /* Read number of vertices, number of dimensions, number of vertex */
+ /* attributes, and number of boundary markers. */
+ stringptr = readline(inputline, infile, nodefilename);
+ m->invertices = (int) strtol(stringptr, &stringptr, 0);
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ m->mesh_dim = 2;
+ } else {
+ m->mesh_dim = (int) strtol(stringptr, &stringptr, 0);
+ }
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ m->nextras = 0;
+ } else {
+ m->nextras = (int) strtol(stringptr, &stringptr, 0);
+ }
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ nodemarkers = 0;
+ } else {
+ nodemarkers = (int) strtol(stringptr, &stringptr, 0);
+ }
+ }
+
+ if (m->invertices < 3) {
+ printf("Error: Input must have at least three input vertices.\n");
+ triexit(1);
+ }
+ if (m->mesh_dim != 2) {
+ printf("Error: Triangle only works with two-dimensional meshes.\n");
+ triexit(1);
+ }
+ if (m->nextras == 0) {
+ b->weighted = 0;
+ }
+
+ initializevertexpool(m, b);
+
+ /* Read the vertices. */
+ for (i = 0; i < m->invertices; i++) {
+ vertexloop = (vertex) poolalloc(&m->vertices);
+ stringptr = readline(inputline, infile, infilename);
+ if (i == 0) {
+ firstnode = (int) strtol(stringptr, &stringptr, 0);
+ if ((firstnode == 0) || (firstnode == 1)) {
+ b->firstnumber = firstnode;
+ }
+ }
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ printf("Error: Vertex %d has no x coordinate.\n", b->firstnumber + i);
+ triexit(1);
+ }
+ x = (REAL) strtod(stringptr, &stringptr);
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ printf("Error: Vertex %d has no y coordinate.\n", b->firstnumber + i);
+ triexit(1);
+ }
+ y = (REAL) strtod(stringptr, &stringptr);
+ vertexloop[0] = x;
+ vertexloop[1] = y;
+ /* Read the vertex attributes. */
+ for (j = 2; j < 2 + m->nextras; j++) {
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ vertexloop[j] = 0.0;
+ } else {
+ vertexloop[j] = (REAL) strtod(stringptr, &stringptr);
+ }
+ }
+ if (nodemarkers) {
+ /* Read a vertex marker. */
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ setvertexmark(vertexloop, 0);
+ } else {
+ currentmarker = (int) strtol(stringptr, &stringptr, 0);
+ setvertexmark(vertexloop, currentmarker);
+ }
+ } else {
+ /* If no markers are specified in the file, they default to zero. */
+ setvertexmark(vertexloop, 0);
+ }
+ setvertextype(vertexloop, INPUTVERTEX);
+ /* Determine the smallest and largest x and y coordinates. */
+ if (i == 0) {
+ m->xmin = m->xmax = x;
+ m->ymin = m->ymax = y;
+ } else {
+ m->xmin = (x < m->xmin) ? x : m->xmin;
+ m->xmax = (x > m->xmax) ? x : m->xmax;
+ m->ymin = (y < m->ymin) ? y : m->ymin;
+ m->ymax = (y > m->ymax) ? y : m->ymax;
+ }
+ }
+ if (m->readnodefile) {
+ fclose(infile);
+ }
+
+ /* Nonexistent x value used as a flag to mark circle events in sweepline */
+ /* Delaunay algorithm. */
+ m->xminextreme = 10 * m->xmin - 9 * m->xmax;
+}
+
+#endif /* not TRILIBRARY */
+
+/*****************************************************************************/
+/* */
+/* transfernodes() Read the vertices from memory. */
+/* */
+/*****************************************************************************/
+
+#ifdef TRILIBRARY
+
+#ifdef ANSI_DECLARATORS
+void transfernodes(struct mesh *m, struct behavior *b, REAL *pointlist,
+ REAL *pointattriblist, int *pointmarkerlist,
+ int numberofpoints, int numberofpointattribs)
+#else /* not ANSI_DECLARATORS */
+void transfernodes(m, b, pointlist, pointattriblist, pointmarkerlist,
+ numberofpoints, numberofpointattribs)
+struct mesh *m;
+struct behavior *b;
+REAL *pointlist;
+REAL *pointattriblist;
+int *pointmarkerlist;
+int numberofpoints;
+int numberofpointattribs;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ vertex vertexloop;
+ REAL x, y;
+ int i, j;
+ int coordindex;
+ int attribindex;
+
+ m->invertices = numberofpoints;
+ m->mesh_dim = 2;
+ m->nextras = numberofpointattribs;
+ m->readnodefile = 0;
+ if (m->invertices < 3) {
+ printf("Error: Input must have at least three input vertices.\n");
+ triexit(1);
+ }
+ if (m->nextras == 0) {
+ b->weighted = 0;
+ }
+
+ initializevertexpool(m, b);
+
+ /* Read the vertices. */
+ coordindex = 0;
+ attribindex = 0;
+ for (i = 0; i < m->invertices; i++) {
+ vertexloop = (vertex) poolalloc(&m->vertices);
+ /* Read the vertex coordinates. */
+ x = vertexloop[0] = pointlist[coordindex++];
+ y = vertexloop[1] = pointlist[coordindex++];
+ /* Read the vertex attributes. */
+ for (j = 0; j < numberofpointattribs; j++) {
+ vertexloop[2 + j] = pointattriblist[attribindex++];
+ }
+ if (pointmarkerlist != (int *) NULL) {
+ /* Read a vertex marker. */
+ setvertexmark(vertexloop, pointmarkerlist[i]);
+ } else {
+ /* If no markers are specified, they default to zero. */
+ setvertexmark(vertexloop, 0);
+ }
+ setvertextype(vertexloop, INPUTVERTEX);
+ /* Determine the smallest and largest x and y coordinates. */
+ if (i == 0) {
+ m->xmin = m->xmax = x;
+ m->ymin = m->ymax = y;
+ } else {
+ m->xmin = (x < m->xmin) ? x : m->xmin;
+ m->xmax = (x > m->xmax) ? x : m->xmax;
+ m->ymin = (y < m->ymin) ? y : m->ymin;
+ m->ymax = (y > m->ymax) ? y : m->ymax;
+ }
+ }
+
+ /* Nonexistent x value used as a flag to mark circle events in sweepline */
+ /* Delaunay algorithm. */
+ m->xminextreme = 10 * m->xmin - 9 * m->xmax;
+}
+
+#endif /* TRILIBRARY */
+
+/*****************************************************************************/
+/* */
+/* readholes() Read the holes, and possibly regional attributes and area */
+/* constraints, from a .poly file. */
+/* */
+/*****************************************************************************/
+
+#ifndef TRILIBRARY
+
+#ifdef ANSI_DECLARATORS
+void readholes(struct mesh *m, struct behavior *b,
+ FILE *polyfile, char *polyfilename, REAL **hlist, int *holes,
+ REAL **rlist, int *regions)
+#else /* not ANSI_DECLARATORS */
+void readholes(m, b, polyfile, polyfilename, hlist, holes, rlist, regions)
+struct mesh *m;
+struct behavior *b;
+FILE *polyfile;
+char *polyfilename;
+REAL **hlist;
+int *holes;
+REAL **rlist;
+int *regions;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ REAL *holelist;
+ REAL *regionlist;
+ char inputline[INPUTLINESIZE];
+ char *stringptr;
+ int index;
+ int i;
+
+ /* Read the holes. */
+ stringptr = readline(inputline, polyfile, polyfilename);
+ *holes = (int) strtol(stringptr, &stringptr, 0);
+ if (*holes > 0) {
+ holelist = (REAL *) trimalloc(2 * *holes * (int) sizeof(REAL));
+ *hlist = holelist;
+ for (i = 0; i < 2 * *holes; i += 2) {
+ stringptr = readline(inputline, polyfile, polyfilename);
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ printf("Error: Hole %d has no x coordinate.\n",
+ b->firstnumber + (i >> 1));
+ triexit(1);
+ } else {
+ holelist[i] = (REAL) strtod(stringptr, &stringptr);
+ }
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ printf("Error: Hole %d has no y coordinate.\n",
+ b->firstnumber + (i >> 1));
+ triexit(1);
+ } else {
+ holelist[i + 1] = (REAL) strtod(stringptr, &stringptr);
+ }
+ }
+ } else {
+ *hlist = (REAL *) NULL;
+ }
+
+#ifndef CDT_ONLY
+ if ((b->regionattrib || b->vararea) && !b->refine) {
+ /* Read the area constraints. */
+ stringptr = readline(inputline, polyfile, polyfilename);
+ *regions = (int) strtol(stringptr, &stringptr, 0);
+ if (*regions > 0) {
+ regionlist = (REAL *) trimalloc(4 * *regions * (int) sizeof(REAL));
+ *rlist = regionlist;
+ index = 0;
+ for (i = 0; i < *regions; i++) {
+ stringptr = readline(inputline, polyfile, polyfilename);
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ printf("Error: Region %d has no x coordinate.\n",
+ b->firstnumber + i);
+ triexit(1);
+ } else {
+ regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
+ }
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ printf("Error: Region %d has no y coordinate.\n",
+ b->firstnumber + i);
+ triexit(1);
+ } else {
+ regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
+ }
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ printf(
+ "Error: Region %d has no region attribute or area constraint.\n",
+ b->firstnumber + i);
+ triexit(1);
+ } else {
+ regionlist[index++] = (REAL) strtod(stringptr, &stringptr);
+ }
+ stringptr = findfield(stringptr);
+ if (*stringptr == '\0') {
+ regionlist[index] = regionlist[index - 1];
+ } else {
+ regionlist[index] = (REAL) strtod(stringptr, &stringptr);
+ }
+ index++;
+ }
+ }
+ } else {
+ /* Set `*regions' to zero to avoid an accidental free() later. */
+ *regions = 0;
+ *rlist = (REAL *) NULL;
+ }
+#endif /* not CDT_ONLY */
+
+ fclose(polyfile);
+}
+
+#endif /* not TRILIBRARY */
+
+/*****************************************************************************/
+/* */
+/* finishfile() Write the command line to the output file so the user */
+/* can remember how the file was generated. Close the file. */
+/* */
+/*****************************************************************************/
+
+#ifndef TRILIBRARY
+
+#ifdef ANSI_DECLARATORS
+void finishfile(FILE *outfile, int argc, char **argv)
+#else /* not ANSI_DECLARATORS */
+void finishfile(outfile, argc, argv)
+FILE *outfile;
+int argc;
+char **argv;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ int i;
+
+ fprintf(outfile, "# Generated by");
+ for (i = 0; i < argc; i++) {
+ fprintf(outfile, " ");
+ fputs(argv[i], outfile);
+ }
+ fprintf(outfile, "\n");
+ fclose(outfile);
+}
+
+#endif /* not TRILIBRARY */
+
+/*****************************************************************************/
+/* */
+/* writenodes() Number the vertices and write them to a .node file. */
+/* */
+/* To save memory, the vertex numbers are written over the boundary markers */
+/* after the vertices are written to a file. */
+/* */
+/*****************************************************************************/
+
+#ifdef TRILIBRARY
+
+#ifdef ANSI_DECLARATORS
+void writenodes(struct mesh *m, struct behavior *b, REAL **pointlist,
+ REAL **pointattriblist, int **pointmarkerlist)
+#else /* not ANSI_DECLARATORS */
+void writenodes(m, b, pointlist, pointattriblist, pointmarkerlist)
+struct mesh *m;
+struct behavior *b;
+REAL **pointlist;
+REAL **pointattriblist;
+int **pointmarkerlist;
+#endif /* not ANSI_DECLARATORS */
+
+#else /* not TRILIBRARY */
+
+#ifdef ANSI_DECLARATORS
+void writenodes(struct mesh *m, struct behavior *b, char *nodefilename,
+ int argc, char **argv)
+#else /* not ANSI_DECLARATORS */
+void writenodes(m, b, nodefilename, argc, argv)
+struct mesh *m;
+struct behavior *b;
+char *nodefilename;
+int argc;
+char **argv;
+#endif /* not ANSI_DECLARATORS */
+
+#endif /* not TRILIBRARY */
+
+{
+#ifdef TRILIBRARY
+ REAL *plist;
+ REAL *palist;
+ int *pmlist;
+ int coordindex;
+ int attribindex;
+#else /* not TRILIBRARY */
+ FILE *outfile;
+#endif /* not TRILIBRARY */
+ vertex vertexloop;
+ long outvertices;
+ int vertexnumber;
+ int i;
+
+ if (b->jettison) {
+ outvertices = m->vertices.items - m->undeads;
+ } else {
+ outvertices = m->vertices.items;
+ }
+
+#ifdef TRILIBRARY
+ if (!b->quiet) {
+ printf("Writing vertices.\n");
+ }
+ /* Allocate memory for output vertices if necessary. */
+ if (*pointlist == (REAL *) NULL) {
+ *pointlist = (REAL *) trimalloc((int) (outvertices * 2 * sizeof(REAL)));
+ }
+ /* Allocate memory for output vertex attributes if necessary. */
+ if ((m->nextras > 0) && (*pointattriblist == (REAL *) NULL)) {
+ *pointattriblist = (REAL *) trimalloc((int) (outvertices * m->nextras *
+ sizeof(REAL)));
+ }
+ /* Allocate memory for output vertex markers if necessary. */
+ if (!b->nobound && (*pointmarkerlist == (int *) NULL)) {
+ *pointmarkerlist = (int *) trimalloc((int) (outvertices * sizeof(int)));
+ }
+ plist = *pointlist;
+ palist = *pointattriblist;
+ pmlist = *pointmarkerlist;
+ coordindex = 0;
+ attribindex = 0;
+#else /* not TRILIBRARY */
+ if (!b->quiet) {
+ printf("Writing %s.\n", nodefilename);
+ }
+ outfile = fopen(nodefilename, "w");
+ if (outfile == (FILE *) NULL) {
+ printf(" Error: Cannot create file %s.\n", nodefilename);
+ triexit(1);
+ }
+ /* Number of vertices, number of dimensions, number of vertex attributes, */
+ /* and number of boundary markers (zero or one). */
+ fprintf(outfile, "%ld %d %d %d\n", outvertices, m->mesh_dim,
+ m->nextras, 1 - b->nobound);
+#endif /* not TRILIBRARY */
+
+ traversalinit(&m->vertices);
+ vertexnumber = b->firstnumber;
+ vertexloop = vertextraverse(m);
+ while (vertexloop != (vertex) NULL) {
+ if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
+#ifdef TRILIBRARY
+ /* X and y coordinates. */
+ plist[coordindex++] = vertexloop[0];
+ plist[coordindex++] = vertexloop[1];
+ /* Vertex attributes. */
+ for (i = 0; i < m->nextras; i++) {
+ palist[attribindex++] = vertexloop[2 + i];
+ }
+ if (!b->nobound) {
+ /* Copy the boundary marker. */
+ pmlist[vertexnumber - b->firstnumber] = vertexmark(vertexloop);
+ }
+#else /* not TRILIBRARY */
+ /* Vertex number, x and y coordinates. */
+ fprintf(outfile, "%4d %.17g %.17g", vertexnumber, vertexloop[0],
+ vertexloop[1]);
+ for (i = 0; i < m->nextras; i++) {
+ /* Write an attribute. */
+ fprintf(outfile, " %.17g", vertexloop[i + 2]);
+ }
+ if (b->nobound) {
+ fprintf(outfile, "\n");
+ } else {
+ /* Write the boundary marker. */
+ fprintf(outfile, " %d\n", vertexmark(vertexloop));
+ }
+#endif /* not TRILIBRARY */
+
+ setvertexmark(vertexloop, vertexnumber);
+ vertexnumber++;
+ }
+ vertexloop = vertextraverse(m);
+ }
+
+#ifndef TRILIBRARY
+ finishfile(outfile, argc, argv);
+#endif /* not TRILIBRARY */
+}
+
+/*****************************************************************************/
+/* */
+/* numbernodes() Number the vertices. */
+/* */
+/* Each vertex is assigned a marker equal to its number. */
+/* */
+/* Used when writenodes() is not called because no .node file is written. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void numbernodes(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void numbernodes(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ vertex vertexloop;
+ int vertexnumber;
+
+ traversalinit(&m->vertices);
+ vertexnumber = b->firstnumber;
+ vertexloop = vertextraverse(m);
+ while (vertexloop != (vertex) NULL) {
+ setvertexmark(vertexloop, vertexnumber);
+ if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
+ vertexnumber++;
+ }
+ vertexloop = vertextraverse(m);
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* writeelements() Write the triangles to an .ele file. */
+/* */
+/*****************************************************************************/
+
+#ifdef TRILIBRARY
+
+#ifdef ANSI_DECLARATORS
+void writeelements(struct mesh *m, struct behavior *b,
+ int **trianglelist, REAL **triangleattriblist)
+#else /* not ANSI_DECLARATORS */
+void writeelements(m, b, trianglelist, triangleattriblist)
+struct mesh *m;
+struct behavior *b;
+int **trianglelist;
+REAL **triangleattriblist;
+#endif /* not ANSI_DECLARATORS */
+
+#else /* not TRILIBRARY */
+
+#ifdef ANSI_DECLARATORS
+void writeelements(struct mesh *m, struct behavior *b, char *elefilename,
+ int argc, char **argv)
+#else /* not ANSI_DECLARATORS */
+void writeelements(m, b, elefilename, argc, argv)
+struct mesh *m;
+struct behavior *b;
+char *elefilename;
+int argc;
+char **argv;
+#endif /* not ANSI_DECLARATORS */
+
+#endif /* not TRILIBRARY */
+
+{
+#ifdef TRILIBRARY
+ int *tlist;
+ REAL *talist;
+ int vertexindex;
+ int attribindex;
+#else /* not TRILIBRARY */
+ FILE *outfile;
+#endif /* not TRILIBRARY */
+ struct otri triangleloop;
+ vertex p1, p2, p3;
+ vertex mid1, mid2, mid3;
+ long elementnumber;
+ int i;
+
+#ifdef TRILIBRARY
+ if (!b->quiet) {
+ printf("Writing triangles.\n");
+ }
+ /* Allocate memory for output triangles if necessary. */
+ if (*trianglelist == (int *) NULL) {
+ *trianglelist = (int *) trimalloc((int) (m->triangles.items *
+ ((b->order + 1) * (b->order + 2) /
+ 2) * sizeof(int)));
+ }
+ /* Allocate memory for output triangle attributes if necessary. */
+ if ((m->eextras > 0) && (*triangleattriblist == (REAL *) NULL)) {
+ *triangleattriblist = (REAL *) trimalloc((int) (m->triangles.items *
+ m->eextras *
+ sizeof(REAL)));
+ }
+ tlist = *trianglelist;
+ talist = *triangleattriblist;
+ vertexindex = 0;
+ attribindex = 0;
+#else /* not TRILIBRARY */
+ if (!b->quiet) {
+ printf("Writing %s.\n", elefilename);
+ }
+ outfile = fopen(elefilename, "w");
+ if (outfile == (FILE *) NULL) {
+ printf(" Error: Cannot create file %s.\n", elefilename);
+ triexit(1);
+ }
+ /* Number of triangles, vertices per triangle, attributes per triangle. */
+ fprintf(outfile, "%ld %d %d\n", m->triangles.items,
+ (b->order + 1) * (b->order + 2) / 2, m->eextras);
+#endif /* not TRILIBRARY */
+
+ traversalinit(&m->triangles);
+ triangleloop.tri = triangletraverse(m);
+ triangleloop.orient = 0;
+ elementnumber = b->firstnumber;
+ while (triangleloop.tri != (triangle *) NULL) {
+ org(triangleloop, p1);
+ dest(triangleloop, p2);
+ apex(triangleloop, p3);
+ if (b->order == 1) {
+#ifdef TRILIBRARY
+ tlist[vertexindex++] = vertexmark(p1);
+ tlist[vertexindex++] = vertexmark(p2);
+ tlist[vertexindex++] = vertexmark(p3);
+#else /* not TRILIBRARY */
+ /* Triangle number, indices for three vertices. */
+ fprintf(outfile, "%4ld %4d %4d %4d", elementnumber,
+ vertexmark(p1), vertexmark(p2), vertexmark(p3));
+#endif /* not TRILIBRARY */
+ } else {
+ mid1 = (vertex) triangleloop.tri[m->highorderindex + 1];
+ mid2 = (vertex) triangleloop.tri[m->highorderindex + 2];
+ mid3 = (vertex) triangleloop.tri[m->highorderindex];
+#ifdef TRILIBRARY
+ tlist[vertexindex++] = vertexmark(p1);
+ tlist[vertexindex++] = vertexmark(p2);
+ tlist[vertexindex++] = vertexmark(p3);
+ tlist[vertexindex++] = vertexmark(mid1);
+ tlist[vertexindex++] = vertexmark(mid2);
+ tlist[vertexindex++] = vertexmark(mid3);
+#else /* not TRILIBRARY */
+ /* Triangle number, indices for six vertices. */
+ fprintf(outfile, "%4ld %4d %4d %4d %4d %4d %4d", elementnumber,
+ vertexmark(p1), vertexmark(p2), vertexmark(p3), vertexmark(mid1),
+ vertexmark(mid2), vertexmark(mid3));
+#endif /* not TRILIBRARY */
+ }
+
+#ifdef TRILIBRARY
+ for (i = 0; i < m->eextras; i++) {
+ talist[attribindex++] = elemattribute(triangleloop, i);
+ }
+#else /* not TRILIBRARY */
+ for (i = 0; i < m->eextras; i++) {
+ fprintf(outfile, " %.17g", elemattribute(triangleloop, i));
+ }
+ fprintf(outfile, "\n");
+#endif /* not TRILIBRARY */
+
+ triangleloop.tri = triangletraverse(m);
+ elementnumber++;
+ }
+
+#ifndef TRILIBRARY
+ finishfile(outfile, argc, argv);
+#endif /* not TRILIBRARY */
+}
+
+/*****************************************************************************/
+/* */
+/* writepoly() Write the segments and holes to a .poly file. */
+/* */
+/*****************************************************************************/
+
+#ifdef TRILIBRARY
+
+#ifdef ANSI_DECLARATORS
+void writepoly(struct mesh *m, struct behavior *b,
+ int **segmentlist, int **segmentmarkerlist)
+#else /* not ANSI_DECLARATORS */
+void writepoly(m, b, segmentlist, segmentmarkerlist)
+struct mesh *m;
+struct behavior *b;
+int **segmentlist;
+int **segmentmarkerlist;
+#endif /* not ANSI_DECLARATORS */
+
+#else /* not TRILIBRARY */
+
+#ifdef ANSI_DECLARATORS
+void writepoly(struct mesh *m, struct behavior *b, char *polyfilename,
+ REAL *holelist, int holes, REAL *regionlist, int regions,
+ int argc, char **argv)
+#else /* not ANSI_DECLARATORS */
+void writepoly(m, b, polyfilename, holelist, holes, regionlist, regions,
+ argc, argv)
+struct mesh *m;
+struct behavior *b;
+char *polyfilename;
+REAL *holelist;
+int holes;
+REAL *regionlist;
+int regions;
+int argc;
+char **argv;
+#endif /* not ANSI_DECLARATORS */
+
+#endif /* not TRILIBRARY */
+
+{
+#ifdef TRILIBRARY
+ int *slist;
+ int *smlist;
+ int index;
+#else /* not TRILIBRARY */
+ FILE *outfile;
+ long holenumber, regionnumber;
+#endif /* not TRILIBRARY */
+ struct osub subsegloop;
+ vertex endpoint1, endpoint2;
+ long subsegnumber;
+
+#ifdef TRILIBRARY
+ if (!b->quiet) {
+ printf("Writing segments.\n");
+ }
+ /* Allocate memory for output segments if necessary. */
+ if (*segmentlist == (int *) NULL) {
+ *segmentlist = (int *) trimalloc((int) (m->subsegs.items * 2 *
+ sizeof(int)));
+ }
+ /* Allocate memory for output segment markers if necessary. */
+ if (!b->nobound && (*segmentmarkerlist == (int *) NULL)) {
+ *segmentmarkerlist = (int *) trimalloc((int) (m->subsegs.items *
+ sizeof(int)));
+ }
+ slist = *segmentlist;
+ smlist = *segmentmarkerlist;
+ index = 0;
+#else /* not TRILIBRARY */
+ if (!b->quiet) {
+ printf("Writing %s.\n", polyfilename);
+ }
+ outfile = fopen(polyfilename, "w");
+ if (outfile == (FILE *) NULL) {
+ printf(" Error: Cannot create file %s.\n", polyfilename);
+ triexit(1);
+ }
+ /* The zero indicates that the vertices are in a separate .node file. */
+ /* Followed by number of dimensions, number of vertex attributes, */
+ /* and number of boundary markers (zero or one). */
+ fprintf(outfile, "%d %d %d %d\n", 0, m->mesh_dim, m->nextras,
+ 1 - b->nobound);
+ /* Number of segments, number of boundary markers (zero or one). */
+ fprintf(outfile, "%ld %d\n", m->subsegs.items, 1 - b->nobound);
+#endif /* not TRILIBRARY */
+
+ traversalinit(&m->subsegs);
+ subsegloop.ss = subsegtraverse(m);
+ subsegloop.ssorient = 0;
+ subsegnumber = b->firstnumber;
+ while (subsegloop.ss != (subseg *) NULL) {
+ sorg(subsegloop, endpoint1);
+ sdest(subsegloop, endpoint2);
+#ifdef TRILIBRARY
+ /* Copy indices of the segment's two endpoints. */
+ slist[index++] = vertexmark(endpoint1);
+ slist[index++] = vertexmark(endpoint2);
+ if (!b->nobound) {
+ /* Copy the boundary marker. */
+ smlist[subsegnumber - b->firstnumber] = mark(subsegloop);
+ }
+#else /* not TRILIBRARY */
+ /* Segment number, indices of its two endpoints, and possibly a marker. */
+ if (b->nobound) {
+ fprintf(outfile, "%4ld %4d %4d\n", subsegnumber,
+ vertexmark(endpoint1), vertexmark(endpoint2));
+ } else {
+ fprintf(outfile, "%4ld %4d %4d %4d\n", subsegnumber,
+ vertexmark(endpoint1), vertexmark(endpoint2), mark(subsegloop));
+ }
+#endif /* not TRILIBRARY */
+
+ subsegloop.ss = subsegtraverse(m);
+ subsegnumber++;
+ }
+
+#ifndef TRILIBRARY
+#ifndef CDT_ONLY
+ fprintf(outfile, "%d\n", holes);
+ if (holes > 0) {
+ for (holenumber = 0; holenumber < holes; holenumber++) {
+ /* Hole number, x and y coordinates. */
+ fprintf(outfile, "%4ld %.17g %.17g\n", b->firstnumber + holenumber,
+ holelist[2 * holenumber], holelist[2 * holenumber + 1]);
+ }
+ }
+ if (regions > 0) {
+ fprintf(outfile, "%d\n", regions);
+ for (regionnumber = 0; regionnumber < regions; regionnumber++) {
+ /* Region number, x and y coordinates, attribute, maximum area. */
+ fprintf(outfile, "%4ld %.17g %.17g %.17g %.17g\n",
+ b->firstnumber + regionnumber,
+ regionlist[4 * regionnumber], regionlist[4 * regionnumber + 1],
+ regionlist[4 * regionnumber + 2],
+ regionlist[4 * regionnumber + 3]);
+ }
+ }
+#endif /* not CDT_ONLY */
+
+ finishfile(outfile, argc, argv);
+#endif /* not TRILIBRARY */
+}
+
+/*****************************************************************************/
+/* */
+/* writeedges() Write the edges to an .edge file. */
+/* */
+/*****************************************************************************/
+
+#ifdef TRILIBRARY
+
+#ifdef ANSI_DECLARATORS
+void writeedges(struct mesh *m, struct behavior *b,
+ int **edgelist, int **edgemarkerlist)
+#else /* not ANSI_DECLARATORS */
+void writeedges(m, b, edgelist, edgemarkerlist)
+struct mesh *m;
+struct behavior *b;
+int **edgelist;
+int **edgemarkerlist;
+#endif /* not ANSI_DECLARATORS */
+
+#else /* not TRILIBRARY */
+
+#ifdef ANSI_DECLARATORS
+void writeedges(struct mesh *m, struct behavior *b, char *edgefilename,
+ int argc, char **argv)
+#else /* not ANSI_DECLARATORS */
+void writeedges(m, b, edgefilename, argc, argv)
+struct mesh *m;
+struct behavior *b;
+char *edgefilename;
+int argc;
+char **argv;
+#endif /* not ANSI_DECLARATORS */
+
+#endif /* not TRILIBRARY */
+
+{
+#ifdef TRILIBRARY
+ int *elist;
+ int *emlist;
+ int index;
+#else /* not TRILIBRARY */
+ FILE *outfile;
+#endif /* not TRILIBRARY */
+ struct otri triangleloop, trisym;
+ struct osub checkmark;
+ vertex p1, p2;
+ long edgenumber;
+ triangle ptr; /* Temporary variable used by sym(). */
+ subseg sptr; /* Temporary variable used by tspivot(). */
+
+#ifdef TRILIBRARY
+ if (!b->quiet) {
+ printf("Writing edges.\n");
+ }
+ /* Allocate memory for edges if necessary. */
+ if (*edgelist == (int *) NULL) {
+ *edgelist = (int *) trimalloc((int) (m->edges * 2 * sizeof(int)));
+ }
+ /* Allocate memory for edge markers if necessary. */
+ if (!b->nobound && (*edgemarkerlist == (int *) NULL)) {
+ *edgemarkerlist = (int *) trimalloc((int) (m->edges * sizeof(int)));
+ }
+ elist = *edgelist;
+ emlist = *edgemarkerlist;
+ index = 0;
+#else /* not TRILIBRARY */
+ if (!b->quiet) {
+ printf("Writing %s.\n", edgefilename);
+ }
+ outfile = fopen(edgefilename, "w");
+ if (outfile == (FILE *) NULL) {
+ printf(" Error: Cannot create file %s.\n", edgefilename);
+ triexit(1);
+ }
+ /* Number of edges, number of boundary markers (zero or one). */
+ fprintf(outfile, "%ld %d\n", m->edges, 1 - b->nobound);
+#endif /* not TRILIBRARY */
+
+ traversalinit(&m->triangles);
+ triangleloop.tri = triangletraverse(m);
+ edgenumber = b->firstnumber;
+ /* To loop over the set of edges, loop over all triangles, and look at */
+ /* the three edges of each triangle. If there isn't another triangle */
+ /* adjacent to the edge, operate on the edge. If there is another */
+ /* adjacent triangle, operate on the edge only if the current triangle */
+ /* has a smaller pointer than its neighbor. This way, each edge is */
+ /* considered only once. */
+ while (triangleloop.tri != (triangle *) NULL) {
+ for (triangleloop.orient = 0; triangleloop.orient < 3;
+ triangleloop.orient++) {
+ sym(triangleloop, trisym);
+ if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
+ org(triangleloop, p1);
+ dest(triangleloop, p2);
+#ifdef TRILIBRARY
+ elist[index++] = vertexmark(p1);
+ elist[index++] = vertexmark(p2);
+#endif /* TRILIBRARY */
+ if (b->nobound) {
+#ifndef TRILIBRARY
+ /* Edge number, indices of two endpoints. */
+ fprintf(outfile, "%4ld %d %d\n", edgenumber,
+ vertexmark(p1), vertexmark(p2));
+#endif /* not TRILIBRARY */
+ } else {
+ /* Edge number, indices of two endpoints, and a boundary marker. */
+ /* If there's no subsegment, the boundary marker is zero. */
+ if (b->usesegments) {
+ tspivot(triangleloop, checkmark);
+ if (checkmark.ss == m->dummysub) {
+#ifdef TRILIBRARY
+ emlist[edgenumber - b->firstnumber] = 0;
+#else /* not TRILIBRARY */
+ fprintf(outfile, "%4ld %d %d %d\n", edgenumber,
+ vertexmark(p1), vertexmark(p2), 0);
+#endif /* not TRILIBRARY */
+ } else {
+#ifdef TRILIBRARY
+ emlist[edgenumber - b->firstnumber] = mark(checkmark);
+#else /* not TRILIBRARY */
+ fprintf(outfile, "%4ld %d %d %d\n", edgenumber,
+ vertexmark(p1), vertexmark(p2), mark(checkmark));
+#endif /* not TRILIBRARY */
+ }
+ } else {
+#ifdef TRILIBRARY
+ emlist[edgenumber - b->firstnumber] = trisym.tri == m->dummytri;
+#else /* not TRILIBRARY */
+ fprintf(outfile, "%4ld %d %d %d\n", edgenumber,
+ vertexmark(p1), vertexmark(p2), trisym.tri == m->dummytri);
+#endif /* not TRILIBRARY */
+ }
+ }
+ edgenumber++;
+ }
+ }
+ triangleloop.tri = triangletraverse(m);
+ }
+
+#ifndef TRILIBRARY
+ finishfile(outfile, argc, argv);
+#endif /* not TRILIBRARY */
+}
+
+/*****************************************************************************/
+/* */
+/* writevoronoi() Write the Voronoi diagram to a .v.node and .v.edge */
+/* file. */
+/* */
+/* The Voronoi diagram is the geometric dual of the Delaunay triangulation. */
+/* Hence, the Voronoi vertices are listed by traversing the Delaunay */
+/* triangles, and the Voronoi edges are listed by traversing the Delaunay */
+/* edges. */
+/* */
+/* WARNING: In order to assign numbers to the Voronoi vertices, this */
+/* procedure messes up the subsegments or the extra nodes of every */
+/* element. Hence, you should call this procedure last. */
+/* */
+/*****************************************************************************/
+
+#ifdef TRILIBRARY
+
+#ifdef ANSI_DECLARATORS
+void writevoronoi(struct mesh *m, struct behavior *b, REAL **vpointlist,
+ REAL **vpointattriblist, int **vpointmarkerlist,
+ int **vedgelist, int **vedgemarkerlist, REAL **vnormlist)
+#else /* not ANSI_DECLARATORS */
+void writevoronoi(m, b, vpointlist, vpointattriblist, vpointmarkerlist,
+ vedgelist, vedgemarkerlist, vnormlist)
+struct mesh *m;
+struct behavior *b;
+REAL **vpointlist;
+REAL **vpointattriblist;
+int **vpointmarkerlist;
+int **vedgelist;
+int **vedgemarkerlist;
+REAL **vnormlist;
+#endif /* not ANSI_DECLARATORS */
+
+#else /* not TRILIBRARY */
+
+#ifdef ANSI_DECLARATORS
+void writevoronoi(struct mesh *m, struct behavior *b, char *vnodefilename,
+ char *vedgefilename, int argc, char **argv)
+#else /* not ANSI_DECLARATORS */
+void writevoronoi(m, b, vnodefilename, vedgefilename, argc, argv)
+struct mesh *m;
+struct behavior *b;
+char *vnodefilename;
+char *vedgefilename;
+int argc;
+char **argv;
+#endif /* not ANSI_DECLARATORS */
+
+#endif /* not TRILIBRARY */
+
+{
+#ifdef TRILIBRARY
+ REAL *plist;
+ REAL *palist;
+ int *elist;
+ REAL *normlist;
+ int coordindex;
+ int attribindex;
+#else /* not TRILIBRARY */
+ FILE *outfile;
+#endif /* not TRILIBRARY */
+ struct otri triangleloop, trisym;
+ vertex torg, tdest, tapex;
+ REAL circumcenter[2];
+ REAL xi, eta;
+ long vnodenumber, vedgenumber;
+ int p1, p2;
+ int i;
+ triangle ptr; /* Temporary variable used by sym(). */
+
+#ifdef TRILIBRARY
+ if (!b->quiet) {
+ printf("Writing Voronoi vertices.\n");
+ }
+ /* Allocate memory for Voronoi vertices if necessary. */
+ if (*vpointlist == (REAL *) NULL) {
+ *vpointlist = (REAL *) trimalloc((int) (m->triangles.items * 2 *
+ sizeof(REAL)));
+ }
+ /* Allocate memory for Voronoi vertex attributes if necessary. */
+ if (*vpointattriblist == (REAL *) NULL) {
+ *vpointattriblist = (REAL *) trimalloc((int) (m->triangles.items *
+ m->nextras * sizeof(REAL)));
+ }
+ *vpointmarkerlist = (int *) NULL;
+ plist = *vpointlist;
+ palist = *vpointattriblist;
+ coordindex = 0;
+ attribindex = 0;
+#else /* not TRILIBRARY */
+ if (!b->quiet) {
+ printf("Writing %s.\n", vnodefilename);
+ }
+ outfile = fopen(vnodefilename, "w");
+ if (outfile == (FILE *) NULL) {
+ printf(" Error: Cannot create file %s.\n", vnodefilename);
+ triexit(1);
+ }
+ /* Number of triangles, two dimensions, number of vertex attributes, */
+ /* no markers. */
+ fprintf(outfile, "%ld %d %d %d\n", m->triangles.items, 2, m->nextras, 0);
+#endif /* not TRILIBRARY */
+
+ traversalinit(&m->triangles);
+ triangleloop.tri = triangletraverse(m);
+ triangleloop.orient = 0;
+ vnodenumber = b->firstnumber;
+ while (triangleloop.tri != (triangle *) NULL) {
+ org(triangleloop, torg);
+ dest(triangleloop, tdest);
+ apex(triangleloop, tapex);
+ findcircumcenter(m, b, torg, tdest, tapex, circumcenter, &xi, &eta, 0);
+#ifdef TRILIBRARY
+ /* X and y coordinates. */
+ plist[coordindex++] = circumcenter[0];
+ plist[coordindex++] = circumcenter[1];
+ for (i = 2; i < 2 + m->nextras; i++) {
+ /* Interpolate the vertex attributes at the circumcenter. */
+ palist[attribindex++] = torg[i] + xi * (tdest[i] - torg[i])
+ + eta * (tapex[i] - torg[i]);
+ }
+#else /* not TRILIBRARY */
+ /* Voronoi vertex number, x and y coordinates. */
+ fprintf(outfile, "%4ld %.17g %.17g", vnodenumber, circumcenter[0],
+ circumcenter[1]);
+ for (i = 2; i < 2 + m->nextras; i++) {
+ /* Interpolate the vertex attributes at the circumcenter. */
+ fprintf(outfile, " %.17g", torg[i] + xi * (tdest[i] - torg[i])
+ + eta * (tapex[i] - torg[i]));
+ }
+ fprintf(outfile, "\n");
+#endif /* not TRILIBRARY */
+
+ * (int *) (triangleloop.tri + 6) = (int) vnodenumber;
+ triangleloop.tri = triangletraverse(m);
+ vnodenumber++;
+ }
+
+#ifndef TRILIBRARY
+ finishfile(outfile, argc, argv);
+#endif /* not TRILIBRARY */
+
+#ifdef TRILIBRARY
+ if (!b->quiet) {
+ printf("Writing Voronoi edges.\n");
+ }
+ /* Allocate memory for output Voronoi edges if necessary. */
+ if (*vedgelist == (int *) NULL) {
+ *vedgelist = (int *) trimalloc((int) (m->edges * 2 * sizeof(int)));
+ }
+ *vedgemarkerlist = (int *) NULL;
+ /* Allocate memory for output Voronoi norms if necessary. */
+ if (*vnormlist == (REAL *) NULL) {
+ *vnormlist = (REAL *) trimalloc((int) (m->edges * 2 * sizeof(REAL)));
+ }
+ elist = *vedgelist;
+ normlist = *vnormlist;
+ coordindex = 0;
+#else /* not TRILIBRARY */
+ if (!b->quiet) {
+ printf("Writing %s.\n", vedgefilename);
+ }
+ outfile = fopen(vedgefilename, "w");
+ if (outfile == (FILE *) NULL) {
+ printf(" Error: Cannot create file %s.\n", vedgefilename);
+ triexit(1);
+ }
+ /* Number of edges, zero boundary markers. */
+ fprintf(outfile, "%ld %d\n", m->edges, 0);
+#endif /* not TRILIBRARY */
+
+ traversalinit(&m->triangles);
+ triangleloop.tri = triangletraverse(m);
+ vedgenumber = b->firstnumber;
+ /* To loop over the set of edges, loop over all triangles, and look at */
+ /* the three edges of each triangle. If there isn't another triangle */
+ /* adjacent to the edge, operate on the edge. If there is another */
+ /* adjacent triangle, operate on the edge only if the current triangle */
+ /* has a smaller pointer than its neighbor. This way, each edge is */
+ /* considered only once. */
+ while (triangleloop.tri != (triangle *) NULL) {
+ for (triangleloop.orient = 0; triangleloop.orient < 3;
+ triangleloop.orient++) {
+ sym(triangleloop, trisym);
+ if ((triangleloop.tri < trisym.tri) || (trisym.tri == m->dummytri)) {
+ /* Find the number of this triangle (and Voronoi vertex). */
+ p1 = * (int *) (triangleloop.tri + 6);
+ if (trisym.tri == m->dummytri) {
+ org(triangleloop, torg);
+ dest(triangleloop, tdest);
+#ifdef TRILIBRARY
+ /* Copy an infinite ray. Index of one endpoint, and -1. */
+ elist[coordindex] = p1;
+ normlist[coordindex++] = tdest[1] - torg[1];
+ elist[coordindex] = -1;
+ normlist[coordindex++] = torg[0] - tdest[0];
+#else /* not TRILIBRARY */
+ /* Write an infinite ray. Edge number, index of one endpoint, -1, */
+ /* and x and y coordinates of a vector representing the */
+ /* direction of the ray. */
+ fprintf(outfile, "%4ld %d %d %.17g %.17g\n", vedgenumber,
+ p1, -1, tdest[1] - torg[1], torg[0] - tdest[0]);
+#endif /* not TRILIBRARY */
+ } else {
+ /* Find the number of the adjacent triangle (and Voronoi vertex). */
+ p2 = * (int *) (trisym.tri + 6);
+ /* Finite edge. Write indices of two endpoints. */
+#ifdef TRILIBRARY
+ elist[coordindex] = p1;
+ normlist[coordindex++] = 0.0;
+ elist[coordindex] = p2;
+ normlist[coordindex++] = 0.0;
+#else /* not TRILIBRARY */
+ fprintf(outfile, "%4ld %d %d\n", vedgenumber, p1, p2);
+#endif /* not TRILIBRARY */
+ }
+ vedgenumber++;
+ }
+ }
+ triangleloop.tri = triangletraverse(m);
+ }
+
+#ifndef TRILIBRARY
+ finishfile(outfile, argc, argv);
+#endif /* not TRILIBRARY */
+}
+
+#ifdef TRILIBRARY
+
+#ifdef ANSI_DECLARATORS
+void writeneighbors(struct mesh *m, struct behavior *b, int **neighborlist)
+#else /* not ANSI_DECLARATORS */
+void writeneighbors(m, b, neighborlist)
+struct mesh *m;
+struct behavior *b;
+int **neighborlist;
+#endif /* not ANSI_DECLARATORS */
+
+#else /* not TRILIBRARY */
+
+#ifdef ANSI_DECLARATORS
+void writeneighbors(struct mesh *m, struct behavior *b, char *neighborfilename,
+ int argc, char **argv)
+#else /* not ANSI_DECLARATORS */
+void writeneighbors(m, b, neighborfilename, argc, argv)
+struct mesh *m;
+struct behavior *b;
+char *neighborfilename;
+int argc;
+char **argv;
+#endif /* not ANSI_DECLARATORS */
+
+#endif /* not TRILIBRARY */
+
+{
+#ifdef TRILIBRARY
+ int *nlist;
+ int index;
+#else /* not TRILIBRARY */
+ FILE *outfile;
+#endif /* not TRILIBRARY */
+ struct otri triangleloop, trisym;
+ long elementnumber;
+ int neighbor1, neighbor2, neighbor3;
+ triangle ptr; /* Temporary variable used by sym(). */
+
+#ifdef TRILIBRARY
+ if (!b->quiet) {
+ printf("Writing neighbors.\n");
+ }
+ /* Allocate memory for neighbors if necessary. */
+ if (*neighborlist == (int *) NULL) {
+ *neighborlist = (int *) trimalloc((int) (m->triangles.items * 3 *
+ sizeof(int)));
+ }
+ nlist = *neighborlist;
+ index = 0;
+#else /* not TRILIBRARY */
+ if (!b->quiet) {
+ printf("Writing %s.\n", neighborfilename);
+ }
+ outfile = fopen(neighborfilename, "w");
+ if (outfile == (FILE *) NULL) {
+ printf(" Error: Cannot create file %s.\n", neighborfilename);
+ triexit(1);
+ }
+ /* Number of triangles, three neighbors per triangle. */
+ fprintf(outfile, "%ld %d\n", m->triangles.items, 3);
+#endif /* not TRILIBRARY */
+
+ traversalinit(&m->triangles);
+ triangleloop.tri = triangletraverse(m);
+ triangleloop.orient = 0;
+ elementnumber = b->firstnumber;
+ while (triangleloop.tri != (triangle *) NULL) {
+ * (int *) (triangleloop.tri + 6) = (int) elementnumber;
+ triangleloop.tri = triangletraverse(m);
+ elementnumber++;
+ }
+ * (int *) (m->dummytri + 6) = -1;
+
+ traversalinit(&m->triangles);
+ triangleloop.tri = triangletraverse(m);
+ elementnumber = b->firstnumber;
+ while (triangleloop.tri != (triangle *) NULL) {
+ triangleloop.orient = 1;
+ sym(triangleloop, trisym);
+ neighbor1 = * (int *) (trisym.tri + 6);
+ triangleloop.orient = 2;
+ sym(triangleloop, trisym);
+ neighbor2 = * (int *) (trisym.tri + 6);
+ triangleloop.orient = 0;
+ sym(triangleloop, trisym);
+ neighbor3 = * (int *) (trisym.tri + 6);
+#ifdef TRILIBRARY
+ nlist[index++] = neighbor1;
+ nlist[index++] = neighbor2;
+ nlist[index++] = neighbor3;
+#else /* not TRILIBRARY */
+ /* Triangle number, neighboring triangle numbers. */
+ fprintf(outfile, "%4ld %d %d %d\n", elementnumber,
+ neighbor1, neighbor2, neighbor3);
+#endif /* not TRILIBRARY */
+
+ triangleloop.tri = triangletraverse(m);
+ elementnumber++;
+ }
+
+#ifndef TRILIBRARY
+ finishfile(outfile, argc, argv);
+#endif /* not TRILIBRARY */
+}
+
+/*****************************************************************************/
+/* */
+/* writeoff() Write the triangulation to an .off file. */
+/* */
+/* OFF stands for the Object File Format, a format used by the Geometry */
+/* Center's Geomview package. */
+/* */
+/*****************************************************************************/
+
+#ifndef TRILIBRARY
+
+#ifdef ANSI_DECLARATORS
+void writeoff(struct mesh *m, struct behavior *b, char *offfilename,
+ int argc, char **argv)
+#else /* not ANSI_DECLARATORS */
+void writeoff(m, b, offfilename, argc, argv)
+struct mesh *m;
+struct behavior *b;
+char *offfilename;
+int argc;
+char **argv;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ FILE *outfile;
+ struct otri triangleloop;
+ vertex vertexloop;
+ vertex p1, p2, p3;
+ long outvertices;
+
+ if (!b->quiet) {
+ printf("Writing %s.\n", offfilename);
+ }
+
+ if (b->jettison) {
+ outvertices = m->vertices.items - m->undeads;
+ } else {
+ outvertices = m->vertices.items;
+ }
+
+ outfile = fopen(offfilename, "w");
+ if (outfile == (FILE *) NULL) {
+ printf(" Error: Cannot create file %s.\n", offfilename);
+ triexit(1);
+ }
+ /* Number of vertices, triangles, and edges. */
+ fprintf(outfile, "OFF\n%ld %ld %ld\n", outvertices, m->triangles.items,
+ m->edges);
+
+ /* Write the vertices. */
+ traversalinit(&m->vertices);
+ vertexloop = vertextraverse(m);
+ while (vertexloop != (vertex) NULL) {
+ if (!b->jettison || (vertextype(vertexloop) != UNDEADVERTEX)) {
+ /* The "0.0" is here because the OFF format uses 3D coordinates. */
+ fprintf(outfile, " %.17g %.17g %.17g\n", vertexloop[0], vertexloop[1],
+ 0.0);
+ }
+ vertexloop = vertextraverse(m);
+ }
+
+ /* Write the triangles. */
+ traversalinit(&m->triangles);
+ triangleloop.tri = triangletraverse(m);
+ triangleloop.orient = 0;
+ while (triangleloop.tri != (triangle *) NULL) {
+ org(triangleloop, p1);
+ dest(triangleloop, p2);
+ apex(triangleloop, p3);
+ /* The "3" means a three-vertex polygon. */
+ fprintf(outfile, " 3 %4d %4d %4d\n", vertexmark(p1) - b->firstnumber,
+ vertexmark(p2) - b->firstnumber, vertexmark(p3) - b->firstnumber);
+ triangleloop.tri = triangletraverse(m);
+ }
+ finishfile(outfile, argc, argv);
+}
+
+#endif /* not TRILIBRARY */
+
+/** **/
+/** **/
+/********* File I/O routines end here *********/
+
+/*****************************************************************************/
+/* */
+/* quality_statistics() Print statistics about the quality of the mesh. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void quality_statistics(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void quality_statistics(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ struct otri triangleloop;
+ vertex p[3];
+ REAL cossquaretable[8];
+ REAL ratiotable[16];
+ REAL dx[3], dy[3];
+ REAL edgelength[3];
+ REAL dotproduct;
+ REAL cossquare;
+ REAL triarea;
+ REAL shortest, longest;
+ REAL trilongest2;
+ REAL smallestarea, biggestarea;
+ REAL triminaltitude2;
+ REAL minaltitude;
+ REAL triaspect2;
+ REAL worstaspect;
+ REAL smallestangle, biggestangle;
+ REAL radconst, degconst;
+ int angletable[18];
+ int aspecttable[16];
+ int aspectindex;
+ int tendegree;
+ int acutebiggest;
+ int i, ii, j, k;
+
+ printf("Mesh quality statistics:\n\n");
+ radconst = PI / 18.0;
+ degconst = 180.0 / PI;
+ for (i = 0; i < 8; i++) {
+ cossquaretable[i] = cos(radconst * (REAL) (i + 1));
+ cossquaretable[i] = cossquaretable[i] * cossquaretable[i];
+ }
+ for (i = 0; i < 18; i++) {
+ angletable[i] = 0;
+ }
+
+ ratiotable[0] = 1.5; ratiotable[1] = 2.0;
+ ratiotable[2] = 2.5; ratiotable[3] = 3.0;
+ ratiotable[4] = 4.0; ratiotable[5] = 6.0;
+ ratiotable[6] = 10.0; ratiotable[7] = 15.0;
+ ratiotable[8] = 25.0; ratiotable[9] = 50.0;
+ ratiotable[10] = 100.0; ratiotable[11] = 300.0;
+ ratiotable[12] = 1000.0; ratiotable[13] = 10000.0;
+ ratiotable[14] = 100000.0; ratiotable[15] = 0.0;
+ for (i = 0; i < 16; i++) {
+ aspecttable[i] = 0;
+ }
+
+ worstaspect = 0.0;
+ minaltitude = m->xmax - m->xmin + m->ymax - m->ymin;
+ minaltitude = minaltitude * minaltitude;
+ shortest = minaltitude;
+ longest = 0.0;
+ smallestarea = minaltitude;
+ biggestarea = 0.0;
+ worstaspect = 0.0;
+ smallestangle = 0.0;
+ biggestangle = 2.0;
+ acutebiggest = 1;
+
+ traversalinit(&m->triangles);
+ triangleloop.tri = triangletraverse(m);
+ triangleloop.orient = 0;
+ while (triangleloop.tri != (triangle *) NULL) {
+ org(triangleloop, p[0]);
+ dest(triangleloop, p[1]);
+ apex(triangleloop, p[2]);
+ trilongest2 = 0.0;
+
+ for (i = 0; i < 3; i++) {
+ j = plus1mod3[i];
+ k = minus1mod3[i];
+ dx[i] = p[j][0] - p[k][0];
+ dy[i] = p[j][1] - p[k][1];
+ edgelength[i] = dx[i] * dx[i] + dy[i] * dy[i];
+ if (edgelength[i] > trilongest2) {
+ trilongest2 = edgelength[i];
+ }
+ if (edgelength[i] > longest) {
+ longest = edgelength[i];
+ }
+ if (edgelength[i] < shortest) {
+ shortest = edgelength[i];
+ }
+ }
+
+ triarea = counterclockwise(m, b, p[0], p[1], p[2]);
+ if (triarea < smallestarea) {
+ smallestarea = triarea;
+ }
+ if (triarea > biggestarea) {
+ biggestarea = triarea;
+ }
+ triminaltitude2 = triarea * triarea / trilongest2;
+ if (triminaltitude2 < minaltitude) {
+ minaltitude = triminaltitude2;
+ }
+ triaspect2 = trilongest2 / triminaltitude2;
+ if (triaspect2 > worstaspect) {
+ worstaspect = triaspect2;
+ }
+ aspectindex = 0;
+ while ((triaspect2 > ratiotable[aspectindex] * ratiotable[aspectindex])
+ && (aspectindex < 15)) {
+ aspectindex++;
+ }
+ aspecttable[aspectindex]++;
+
+ for (i = 0; i < 3; i++) {
+ j = plus1mod3[i];
+ k = minus1mod3[i];
+ dotproduct = dx[j] * dx[k] + dy[j] * dy[k];
+ cossquare = dotproduct * dotproduct / (edgelength[j] * edgelength[k]);
+ tendegree = 8;
+ for (ii = 7; ii >= 0; ii--) {
+ if (cossquare > cossquaretable[ii]) {
+ tendegree = ii;
+ }
+ }
+ if (dotproduct <= 0.0) {
+ angletable[tendegree]++;
+ if (cossquare > smallestangle) {
+ smallestangle = cossquare;
+ }
+ if (acutebiggest && (cossquare < biggestangle)) {
+ biggestangle = cossquare;
+ }
+ } else {
+ angletable[17 - tendegree]++;
+ if (acutebiggest || (cossquare > biggestangle)) {
+ biggestangle = cossquare;
+ acutebiggest = 0;
+ }
+ }
+ }
+ triangleloop.tri = triangletraverse(m);
+ }
+
+ shortest = sqrt(shortest);
+ longest = sqrt(longest);
+ minaltitude = sqrt(minaltitude);
+ worstaspect = sqrt(worstaspect);
+ smallestarea *= 0.5;
+ biggestarea *= 0.5;
+ if (smallestangle >= 1.0) {
+ smallestangle = 0.0;
+ } else {
+ smallestangle = degconst * acos(sqrt(smallestangle));
+ }
+ if (biggestangle >= 1.0) {
+ biggestangle = 180.0;
+ } else {
+ if (acutebiggest) {
+ biggestangle = degconst * acos(sqrt(biggestangle));
+ } else {
+ biggestangle = 180.0 - degconst * acos(sqrt(biggestangle));
+ }
+ }
+
+ printf(" Smallest area: %16.5g | Largest area: %16.5g\n",
+ smallestarea, biggestarea);
+ printf(" Shortest edge: %16.5g | Longest edge: %16.5g\n",
+ shortest, longest);
+ printf(" Shortest altitude: %12.5g | Largest aspect ratio: %8.5g\n\n",
+ minaltitude, worstaspect);
+
+ printf(" Triangle aspect ratio histogram:\n");
+ printf(" 1.1547 - %-6.6g : %8d | %6.6g - %-6.6g : %8d\n",
+ ratiotable[0], aspecttable[0], ratiotable[7], ratiotable[8],
+ aspecttable[8]);
+ for (i = 1; i < 7; i++) {
+ printf(" %6.6g - %-6.6g : %8d | %6.6g - %-6.6g : %8d\n",
+ ratiotable[i - 1], ratiotable[i], aspecttable[i],
+ ratiotable[i + 7], ratiotable[i + 8], aspecttable[i + 8]);
+ }
+ printf(" %6.6g - %-6.6g : %8d | %6.6g - : %8d\n",
+ ratiotable[6], ratiotable[7], aspecttable[7], ratiotable[14],
+ aspecttable[15]);
+ printf(" (Aspect ratio is longest edge divided by shortest altitude)\n\n");
+
+ printf(" Smallest angle: %15.5g | Largest angle: %15.5g\n\n",
+ smallestangle, biggestangle);
+
+ printf(" Angle histogram:\n");
+ for (i = 0; i < 9; i++) {
+ printf(" %3d - %3d degrees: %8d | %3d - %3d degrees: %8d\n",
+ i * 10, i * 10 + 10, angletable[i],
+ i * 10 + 90, i * 10 + 100, angletable[i + 9]);
+ }
+ printf("\n");
+}
+
+/*****************************************************************************/
+/* */
+/* statistics() Print all sorts of cool facts. */
+/* */
+/*****************************************************************************/
+
+#ifdef ANSI_DECLARATORS
+void statistics(struct mesh *m, struct behavior *b)
+#else /* not ANSI_DECLARATORS */
+void statistics(m, b)
+struct mesh *m;
+struct behavior *b;
+#endif /* not ANSI_DECLARATORS */
+
+{
+ printf("\nStatistics:\n\n");
+ printf(" Input vertices: %d\n", m->invertices);
+ if (b->refine) {
+ printf(" Input triangles: %d\n", m->inelements);
+ }
+ if (b->poly) {
+ printf(" Input segments: %d\n", m->insegments);
+ if (!b->refine) {
+ printf(" Input holes: %d\n", m->holes);
+ }
+ }
+
+ printf("\n Mesh vertices: %ld\n", m->vertices.items - m->undeads);
+ printf(" Mesh triangles: %ld\n", m->triangles.items);
+ printf(" Mesh edges: %ld\n", m->edges);
+ printf(" Mesh exterior boundary edges: %ld\n", m->hullsize);
+ if (b->poly || b->refine) {
+ printf(" Mesh interior boundary edges: %ld\n",
+ m->subsegs.items - m->hullsize);
+ printf(" Mesh subsegments (constrained edges): %ld\n",
+ m->subsegs.items);
+ }
+ printf("\n");
+
+ if (b->verbose) {
+ quality_statistics(m, b);
+ printf("Memory allocation statistics:\n\n");
+ printf(" Maximum number of vertices: %ld\n", m->vertices.maxitems);
+ printf(" Maximum number of triangles: %ld\n", m->triangles.maxitems);
+ if (m->subsegs.maxitems > 0) {
+ printf(" Maximum number of subsegments: %ld\n", m->subsegs.maxitems);
+ }
+ if (m->viri.maxitems > 0) {
+ printf(" Maximum number of viri: %ld\n", m->viri.maxitems);
+ }
+ if (m->badsubsegs.maxitems > 0) {
+ printf(" Maximum number of encroached subsegments: %ld\n",
+ m->badsubsegs.maxitems);
+ }
+ if (m->badtriangles.maxitems > 0) {
+ printf(" Maximum number of bad triangles: %ld\n",
+ m->badtriangles.maxitems);
+ }
+ if (m->flipstackers.maxitems > 0) {
+ printf(" Maximum number of stacked triangle flips: %ld\n",
+ m->flipstackers.maxitems);
+ }
+ if (m->splaynodes.maxitems > 0) {
+ printf(" Maximum number of splay tree nodes: %ld\n",
+ m->splaynodes.maxitems);
+ }
+ printf(" Approximate heap memory use (bytes): %ld\n\n",
+ m->vertices.maxitems * m->vertices.itembytes +
+ m->triangles.maxitems * m->triangles.itembytes +
+ m->subsegs.maxitems * m->subsegs.itembytes +
+ m->viri.maxitems * m->viri.itembytes +
+ m->badsubsegs.maxitems * m->badsubsegs.itembytes +
+ m->badtriangles.maxitems * m->badtriangles.itembytes +
+ m->flipstackers.maxitems * m->flipstackers.itembytes +
+ m->splaynodes.maxitems * m->splaynodes.itembytes);
+
+ printf("Algorithmic statistics:\n\n");
+ if (!b->weighted) {
+ printf(" Number of incircle tests: %ld\n", m->incirclecount);
+ } else {
+ printf(" Number of 3D orientation tests: %ld\n", m->orient3dcount);
+ }
+ printf(" Number of 2D orientation tests: %ld\n", m->counterclockcount);
+ if (m->hyperbolacount > 0) {
+ printf(" Number of right-of-hyperbola tests: %ld\n",
+ m->hyperbolacount);
+ }
+ if (m->circletopcount > 0) {
+ printf(" Number of circle top computations: %ld\n",
+ m->circletopcount);
+ }
+ if (m->circumcentercount > 0) {
+ printf(" Number of triangle circumcenter computations: %ld\n",
+ m->circumcentercount);
+ }
+ printf("\n");
+ }
+}
+
+/*****************************************************************************/
+/* */
+/* main() or triangulate() Gosh, do everything. */
+/* */
+/* The sequence is roughly as follows. Many of these steps can be skipped, */
+/* depending on the command line switches. */
+/* */
+/* - Initialize constants and parse the command line. */
+/* - Read the vertices from a file and either */
+/* - triangulate them (no -r), or */
+/* - read an old mesh from files and reconstruct it (-r). */
+/* - Insert the PSLG segments (-p), and possibly segments on the convex */
+/* hull (-c). */
+/* - Read the holes (-p), regional attributes (-pA), and regional area */
+/* constraints (-pa). Carve the holes and concavities, and spread the */
+/* regional attributes and area constraints. */
+/* - Enforce the constraints on minimum angle (-q) and maximum area (-a). */
+/* Also enforce the conforming Delaunay property (-q and -a). */
+/* - Compute the number of edges in the resulting mesh. */
+/* - Promote the mesh's linear triangles to higher order elements (-o). */
+/* - Write the output files and print the statistics. */
+/* - Check the consistency and Delaunay property of the mesh (-C). */
+/* */
+/*****************************************************************************/
+
+#ifdef TRILIBRARY
+
+#ifdef ANSI_DECLARATORS
+void triangulate(char *triswitches, struct triangulateio *in,
+ struct triangulateio *out, struct triangulateio *vorout)
+#else /* not ANSI_DECLARATORS */
+void triangulate(triswitches, in, out, vorout)
+char *triswitches;
+struct triangulateio *in;
+struct triangulateio *out;
+struct triangulateio *vorout;
+#endif /* not ANSI_DECLARATORS */
+
+#else /* not TRILIBRARY */
+
+#ifdef ANSI_DECLARATORS
+int main(int argc, char **argv)
+#else /* not ANSI_DECLARATORS */
+int main(argc, argv)
+int argc;
+char **argv;
+#endif /* not ANSI_DECLARATORS */
+
+#endif /* not TRILIBRARY */
+
+{
+ struct mesh m;
+ struct behavior b;
+ REAL *holearray; /* Array of holes. */
+ REAL *regionarray; /* Array of regional attributes and area constraints. */
+#ifndef TRILIBRARY
+ FILE *polyfile;
+#endif /* not TRILIBRARY */
+#ifndef NO_TIMER
+ /* Variables for timing the performance of Triangle. The types are */
+ /* defined in sys/time.h. */
+ struct timeval tv0, tv1, tv2, tv3, tv4, tv5, tv6;
+ struct timezone tz;
+#endif /* not NO_TIMER */
+
+#ifndef NO_TIMER
+ gettimeofday(&tv0, &tz);
+#endif /* not NO_TIMER */
+
+ triangleinit(&m);
+#ifdef TRILIBRARY
+ parsecommandline(1, &triswitches, &b);
+#else /* not TRILIBRARY */
+ parsecommandline(argc, argv, &b);
+#endif /* not TRILIBRARY */
+ m.steinerleft = b.steiner;
+
+#ifdef TRILIBRARY
+ transfernodes(&m, &b, in->pointlist, in->pointattributelist,
+ in->pointmarkerlist, in->numberofpoints,
+ in->numberofpointattributes);
+#else /* not TRILIBRARY */
+ readnodes(&m, &b, b.innodefilename, b.inpolyfilename, &polyfile);
+#endif /* not TRILIBRARY */
+
+#ifndef NO_TIMER
+ if (!b.quiet) {
+ gettimeofday(&tv1, &tz);
+ }
+#endif /* not NO_TIMER */
+
+#ifdef CDT_ONLY
+ m.hullsize = delaunay(&m, &b); /* Triangulate the vertices. */
+#else /* not CDT_ONLY */
+ if (b.refine) {
+ /* Read and reconstruct a mesh. */
+#ifdef TRILIBRARY
+ m.hullsize = reconstruct(&m, &b, in->trianglelist,
+ in->triangleattributelist, in->trianglearealist,
+ in->numberoftriangles, in->numberofcorners,
+ in->numberoftriangleattributes,
+ in->segmentlist, in->segmentmarkerlist,
+ in->numberofsegments);
+#else /* not TRILIBRARY */
+ m.hullsize = reconstruct(&m, &b, b.inelefilename, b.areafilename,
+ b.inpolyfilename, polyfile);
+#endif /* not TRILIBRARY */
+ } else {
+ m.hullsize = delaunay(&m, &b); /* Triangulate the vertices. */
+ }
+#endif /* not CDT_ONLY */
+
+#ifndef NO_TIMER
+ if (!b.quiet) {
+ gettimeofday(&tv2, &tz);
+ if (b.refine) {
+ printf("Mesh reconstruction");
+ } else {
+ printf("Delaunay");
+ }
+ printf(" milliseconds: %ld\n", 1000l * (tv2.tv_sec - tv1.tv_sec) +
+ (tv2.tv_usec - tv1.tv_usec) / 1000l);
+ }
+#endif /* not NO_TIMER */
+
+ /* Ensure that no vertex can be mistaken for a triangular bounding */
+ /* box vertex in insertvertex(). */
+ m.infvertex1 = (vertex) NULL;
+ m.infvertex2 = (vertex) NULL;
+ m.infvertex3 = (vertex) NULL;
+
+ if (b.usesegments) {
+ m.checksegments = 1; /* Segments will be introduced next. */
+ if (!b.refine) {
+ /* Insert PSLG segments and/or convex hull segments. */
+#ifdef TRILIBRARY
+ formskeleton(&m, &b, in->segmentlist,
+ in->segmentmarkerlist, in->numberofsegments);
+#else /* not TRILIBRARY */
+ formskeleton(&m, &b, polyfile, b.inpolyfilename);
+#endif /* not TRILIBRARY */
+ }
+ }
+
+#ifndef NO_TIMER
+ if (!b.quiet) {
+ gettimeofday(&tv3, &tz);
+ if (b.usesegments && !b.refine) {
+ printf("Segment milliseconds: %ld\n",
+ 1000l * (tv3.tv_sec - tv2.tv_sec) +
+ (tv3.tv_usec - tv2.tv_usec) / 1000l);
+ }
+ }
+#endif /* not NO_TIMER */
+
+ if (b.poly && (m.triangles.items > 0)) {
+#ifdef TRILIBRARY
+ holearray = in->holelist;
+ m.holes = in->numberofholes;
+ regionarray = in->regionlist;
+ m.regions = in->numberofregions;
+#else /* not TRILIBRARY */
+ readholes(&m, &b, polyfile, b.inpolyfilename, &holearray, &m.holes,
+ ®ionarray, &m.regions);
+#endif /* not TRILIBRARY */
+ if (!b.refine) {
+ /* Carve out holes and concavities. */
+ carveholes(&m, &b, holearray, m.holes, regionarray, m.regions);
+ }
+ } else {
+ /* Without a PSLG, there can be no holes or regional attributes */
+ /* or area constraints. The following are set to zero to avoid */
+ /* an accidental free() later. */
+ m.holes = 0;
+ m.regions = 0;
+ }
+
+#ifndef NO_TIMER
+ if (!b.quiet) {
+ gettimeofday(&tv4, &tz);
+ if (b.poly && !b.refine) {
+ printf("Hole milliseconds: %ld\n", 1000l * (tv4.tv_sec - tv3.tv_sec) +
+ (tv4.tv_usec - tv3.tv_usec) / 1000l);
+ }
+ }
+#endif /* not NO_TIMER */
+
+#ifndef CDT_ONLY
+ if (b.quality && (m.triangles.items > 0)) {
+ enforcequality(&m, &b); /* Enforce angle and area constraints. */
+ }
+#endif /* not CDT_ONLY */
+
+#ifndef NO_TIMER
+ if (!b.quiet) {
+ gettimeofday(&tv5, &tz);
+#ifndef CDT_ONLY
+ if (b.quality) {
+ printf("Quality milliseconds: %ld\n",
+ 1000l * (tv5.tv_sec - tv4.tv_sec) +
+ (tv5.tv_usec - tv4.tv_usec) / 1000l);
+ }
+#endif /* not CDT_ONLY */
+ }
+#endif /* not NO_TIMER */
+
+ /* Calculate the number of edges. */
+ m.edges = (3l * m.triangles.items + m.hullsize) / 2l;
+
+ if (b.order > 1) {
+ highorder(&m, &b); /* Promote elements to higher polynomial order. */
+ }
+ if (!b.quiet) {
+ printf("\n");
+ }
+
+#ifdef TRILIBRARY
+ if (b.jettison) {
+ out->numberofpoints = m.vertices.items - m.undeads;
+ } else {
+ out->numberofpoints = m.vertices.items;
+ }
+ out->numberofpointattributes = m.nextras;
+ out->numberoftriangles = m.triangles.items;
+ out->numberofcorners = (b.order + 1) * (b.order + 2) / 2;
+ out->numberoftriangleattributes = m.eextras;
+ out->numberofedges = m.edges;
+ if (b.usesegments) {
+ out->numberofsegments = m.subsegs.items;
+ } else {
+ out->numberofsegments = m.hullsize;
+ }
+ if (vorout != (struct triangulateio *) NULL) {
+ vorout->numberofpoints = m.triangles.items;
+ vorout->numberofpointattributes = m.nextras;
+ vorout->numberofedges = m.edges;
+ }
+#endif /* TRILIBRARY */
+ /* If not using iteration numbers, don't write a .node file if one was */
+ /* read, because the original one would be overwritten! */
+ if (b.nonodewritten || (b.noiterationnum && m.readnodefile)) {
+ if (!b.quiet) {
+#ifdef TRILIBRARY
+ printf("NOT writing vertices.\n");
+#else /* not TRILIBRARY */
+ printf("NOT writing a .node file.\n");
+#endif /* not TRILIBRARY */
+ }
+ numbernodes(&m, &b); /* We must remember to number the vertices. */
+ } else {
+ /* writenodes() numbers the vertices too. */
+#ifdef TRILIBRARY
+ writenodes(&m, &b, &out->pointlist, &out->pointattributelist,
+ &out->pointmarkerlist);
+#else /* not TRILIBRARY */
+ writenodes(&m, &b, b.outnodefilename, argc, argv);
+#endif /* TRILIBRARY */
+ }
+ if (b.noelewritten) {
+ if (!b.quiet) {
+#ifdef TRILIBRARY
+ printf("NOT writing triangles.\n");
+#else /* not TRILIBRARY */
+ printf("NOT writing an .ele file.\n");
+#endif /* not TRILIBRARY */
+ }
+ } else {
+#ifdef TRILIBRARY
+ writeelements(&m, &b, &out->trianglelist, &out->triangleattributelist);
+#else /* not TRILIBRARY */
+ writeelements(&m, &b, b.outelefilename, argc, argv);
+#endif /* not TRILIBRARY */
+ }
+ /* The -c switch (convex switch) causes a PSLG to be written */
+ /* even if none was read. */
+ if (b.poly || b.convex) {
+ /* If not using iteration numbers, don't overwrite the .poly file. */
+ if (b.nopolywritten || b.noiterationnum) {
+ if (!b.quiet) {
+#ifdef TRILIBRARY
+ printf("NOT writing segments.\n");
+#else /* not TRILIBRARY */
+ printf("NOT writing a .poly file.\n");
+#endif /* not TRILIBRARY */
+ }
+ } else {
+#ifdef TRILIBRARY
+ writepoly(&m, &b, &out->segmentlist, &out->segmentmarkerlist);
+ out->numberofholes = m.holes;
+ out->numberofregions = m.regions;
+ if (b.poly) {
+ out->holelist = in->holelist;
+ out->regionlist = in->regionlist;
+ } else {
+ out->holelist = (REAL *) NULL;
+ out->regionlist = (REAL *) NULL;
+ }
+#else /* not TRILIBRARY */
+ writepoly(&m, &b, b.outpolyfilename, holearray, m.holes, regionarray,
+ m.regions, argc, argv);
+#endif /* not TRILIBRARY */
+ }
+ }
+#ifndef TRILIBRARY
+#ifndef CDT_ONLY
+ if (m.regions > 0) {
+ trifree((VOID *) regionarray);
+ }
+#endif /* not CDT_ONLY */
+ if (m.holes > 0) {
+ trifree((VOID *) holearray);
+ }
+ if (b.geomview) {
+ writeoff(&m, &b, b.offfilename, argc, argv);
+ }
+#endif /* not TRILIBRARY */
+ if (b.edgesout) {
+#ifdef TRILIBRARY
+ writeedges(&m, &b, &out->edgelist, &out->edgemarkerlist);
+#else /* not TRILIBRARY */
+ writeedges(&m, &b, b.edgefilename, argc, argv);
+#endif /* not TRILIBRARY */
+ }
+ if (b.voronoi) {
+#ifdef TRILIBRARY
+ writevoronoi(&m, &b, &vorout->pointlist, &vorout->pointattributelist,
+ &vorout->pointmarkerlist, &vorout->edgelist,
+ &vorout->edgemarkerlist, &vorout->normlist);
+#else /* not TRILIBRARY */
+ writevoronoi(&m, &b, b.vnodefilename, b.vedgefilename, argc, argv);
+#endif /* not TRILIBRARY */
+ }
+ if (b.neighbors) {
+#ifdef TRILIBRARY
+ writeneighbors(&m, &b, &out->neighborlist);
+#else /* not TRILIBRARY */
+ writeneighbors(&m, &b, b.neighborfilename, argc, argv);
+#endif /* not TRILIBRARY */
+ }
+
+ if (!b.quiet) {
+#ifndef NO_TIMER
+ gettimeofday(&tv6, &tz);
+ printf("\nOutput milliseconds: %ld\n",
+ 1000l * (tv6.tv_sec - tv5.tv_sec) +
+ (tv6.tv_usec - tv5.tv_usec) / 1000l);
+ printf("Total running milliseconds: %ld\n",
+ 1000l * (tv6.tv_sec - tv0.tv_sec) +
+ (tv6.tv_usec - tv0.tv_usec) / 1000l);
+#endif /* not NO_TIMER */
+
+ statistics(&m, &b);
+ }
+
+#ifndef REDUCED
+ if (b.docheck) {
+ checkmesh(&m, &b);
+ checkdelaunay(&m, &b);
+ }
+#endif /* not REDUCED */
+
+ triangledeinit(&m, &b);
+#ifndef TRILIBRARY
+ return 0;
+#endif /* not TRILIBRARY */
+}
diff --git a/src/modules/grid/grid_gridding/nn/triangle.h b/src/modules/grid/grid_gridding/nn/triangle.h
new file mode 100644
index 0000000..c78fe20
--- /dev/null
+++ b/src/modules/grid/grid_gridding/nn/triangle.h
@@ -0,0 +1,296 @@
+/**********************************************************
+ * Version $Id: triangle.h 911 2011-02-14 16:38:15Z reklov_w $
+ *********************************************************/
+/*****************************************************************************/
+/* */
+/* (triangle.h) */
+/* */
+/* Include file for programs that call Triangle. */
+/* */
+/* Accompanies Triangle Version 1.6 */
+/* July 28, 2005 */
+/* */
+/* Copyright 1996, 2005 */
+/* Jonathan Richard Shewchuk */
+/* 2360 Woolsey #H */
+/* Berkeley, California 94705-1927 */
+/* jrs at cs.berkeley.edu */
+/* */
+/*****************************************************************************/
+
+/*****************************************************************************/
+/* */
+/* How to call Triangle from another program */
+/* */
+/* */
+/* If you haven't read Triangle's instructions (run "triangle -h" to read */
+/* them), you won't understand what follows. */
+/* */
+/* Triangle must be compiled into an object file (triangle.o) with the */
+/* TRILIBRARY symbol defined (generally by using the -DTRILIBRARY compiler */
+/* switch). The makefile included with Triangle will do this for you if */
+/* you run "make trilibrary". The resulting object file can be called via */
+/* the procedure triangulate(). */
+/* */
+/* If the size of the object file is important to you, you may wish to */
+/* generate a reduced version of triangle.o. The REDUCED symbol gets rid */
+/* of all features that are primarily of research interest. Specifically, */
+/* the -DREDUCED switch eliminates Triangle's -i, -F, -s, and -C switches. */
+/* The CDT_ONLY symbol gets rid of all meshing algorithms above and beyond */
+/* constrained Delaunay triangulation. Specifically, the -DCDT_ONLY switch */
+/* eliminates Triangle's -r, -q, -a, -u, -D, -Y, -S, and -s switches. */
+/* */
+/* IMPORTANT: These definitions (TRILIBRARY, REDUCED, CDT_ONLY) must be */
+/* made in the makefile or in triangle.c itself. Putting these definitions */
+/* in this file (triangle.h) will not create the desired effect. */
+/* */
+/* */
+/* The calling convention for triangulate() follows. */
+/* */
+/* void triangulate(triswitches, in, out, vorout) */
+/* char *triswitches; */
+/* struct triangulateio *in; */
+/* struct triangulateio *out; */
+/* struct triangulateio *vorout; */
+/* */
+/* `triswitches' is a string containing the command line switches you wish */
+/* to invoke. No initial dash is required. Some suggestions: */
+/* */
+/* - You'll probably find it convenient to use the `z' switch so that */
+/* points (and other items) are numbered from zero. This simplifies */
+/* indexing, because the first item of any type always starts at index */
+/* [0] of the corresponding array, whether that item's number is zero or */
+/* one. */
+/* - You'll probably want to use the `Q' (quiet) switch in your final code, */
+/* but you can take advantage of Triangle's printed output (including the */
+/* `V' switch) while debugging. */
+/* - If you are not using the `q', `a', `u', `D', `j', or `s' switches, */
+/* then the output points will be identical to the input points, except */
+/* possibly for the boundary markers. If you don't need the boundary */
+/* markers, you should use the `N' (no nodes output) switch to save */
+/* memory. (If you do need boundary markers, but need to save memory, a */
+/* good nasty trick is to set out->pointlist equal to in->pointlist */
+/* before calling triangulate(), so that Triangle overwrites the input */
+/* points with identical copies.) */
+/* - The `I' (no iteration numbers) and `g' (.off file output) switches */
+/* have no effect when Triangle is compiled with TRILIBRARY defined. */
+/* */
+/* `in', `out', and `vorout' are descriptions of the input, the output, */
+/* and the Voronoi output. If the `v' (Voronoi output) switch is not used, */
+/* `vorout' may be NULL. `in' and `out' may never be NULL. */
+/* */
+/* Certain fields of the input and output structures must be initialized, */
+/* as described below. */
+/* */
+/*****************************************************************************/
+
+/*****************************************************************************/
+/* */
+/* The `triangulateio' structure. */
+/* */
+/* Used to pass data into and out of the triangulate() procedure. */
+/* */
+/* */
+/* Arrays are used to store points, triangles, markers, and so forth. In */
+/* all cases, the first item in any array is stored starting at index [0]. */
+/* However, that item is item number `1' unless the `z' switch is used, in */
+/* which case it is item number `0'. Hence, you may find it easier to */
+/* index points (and triangles in the neighbor list) if you use the `z' */
+/* switch. Unless, of course, you're calling Triangle from a Fortran */
+/* program. */
+/* */
+/* Description of fields (except the `numberof' fields, which are obvious): */
+/* */
+/* `pointlist': An array of point coordinates. The first point's x */
+/* coordinate is at index [0] and its y coordinate at index [1], followed */
+/* by the coordinates of the remaining points. Each point occupies two */
+/* REALs. */
+/* `pointattributelist': An array of point attributes. Each point's */
+/* attributes occupy `numberofpointattributes' REALs. */
+/* `pointmarkerlist': An array of point markers; one int per point. */
+/* */
+/* `trianglelist': An array of triangle corners. The first triangle's */
+/* first corner is at index [0], followed by its other two corners in */
+/* counterclockwise order, followed by any other nodes if the triangle */
+/* represents a nonlinear element. Each triangle occupies */
+/* `numberofcorners' ints. */
+/* `triangleattributelist': An array of triangle attributes. Each */
+/* triangle's attributes occupy `numberoftriangleattributes' REALs. */
+/* `trianglearealist': An array of triangle area constraints; one REAL per */
+/* triangle. Input only. */
+/* `neighborlist': An array of triangle neighbors; three ints per */
+/* triangle. Output only. */
+/* */
+/* `segmentlist': An array of segment endpoints. The first segment's */
+/* endpoints are at indices [0] and [1], followed by the remaining */
+/* segments. Two ints per segment. */
+/* `segmentmarkerlist': An array of segment markers; one int per segment. */
+/* */
+/* `holelist': An array of holes. The first hole's x and y coordinates */
+/* are at indices [0] and [1], followed by the remaining holes. Two */
+/* REALs per hole. Input only, although the pointer is copied to the */
+/* output structure for your convenience. */
+/* */
+/* `regionlist': An array of regional attributes and area constraints. */
+/* The first constraint's x and y coordinates are at indices [0] and [1], */
+/* followed by the regional attribute at index [2], followed by the */
+/* maximum area at index [3], followed by the remaining area constraints. */
+/* Four REALs per area constraint. Note that each regional attribute is */
+/* used only if you select the `A' switch, and each area constraint is */
+/* used only if you select the `a' switch (with no number following), but */
+/* omitting one of these switches does not change the memory layout. */
+/* Input only, although the pointer is copied to the output structure for */
+/* your convenience. */
+/* */
+/* `edgelist': An array of edge endpoints. The first edge's endpoints are */
+/* at indices [0] and [1], followed by the remaining edges. Two ints per */
+/* edge. Output only. */
+/* `edgemarkerlist': An array of edge markers; one int per edge. Output */
+/* only. */
+/* `normlist': An array of normal vectors, used for infinite rays in */
+/* Voronoi diagrams. The first normal vector's x and y magnitudes are */
+/* at indices [0] and [1], followed by the remaining vectors. For each */
+/* finite edge in a Voronoi diagram, the normal vector written is the */
+/* zero vector. Two REALs per edge. Output only. */
+/* */
+/* */
+/* Any input fields that Triangle will examine must be initialized. */
+/* Furthermore, for each output array that Triangle will write to, you */
+/* must either provide space by setting the appropriate pointer to point */
+/* to the space you want the data written to, or you must initialize the */
+/* pointer to NULL, which tells Triangle to allocate space for the results. */
+/* The latter option is preferable, because Triangle always knows exactly */
+/* how much space to allocate. The former option is provided mainly for */
+/* people who need to call Triangle from Fortran code, though it also makes */
+/* possible some nasty space-saving tricks, like writing the output to the */
+/* same arrays as the input. */
+/* */
+/* Triangle will not free() any input or output arrays, including those it */
+/* allocates itself; that's up to you. You should free arrays allocated by */
+/* Triangle by calling the trifree() procedure defined below. (By default, */
+/* trifree() just calls the standard free() library procedure, but */
+/* applications that call triangulate() may replace trimalloc() and */
+/* trifree() in triangle.c to use specialized memory allocators.) */
+/* */
+/* Here's a guide to help you decide which fields you must initialize */
+/* before you call triangulate(). */
+/* */
+/* `in': */
+/* */
+/* - `pointlist' must always point to a list of points; `numberofpoints' */
+/* and `numberofpointattributes' must be properly set. */
+/* `pointmarkerlist' must either be set to NULL (in which case all */
+/* markers default to zero), or must point to a list of markers. If */
+/* `numberofpointattributes' is not zero, `pointattributelist' must */
+/* point to a list of point attributes. */
+/* - If the `r' switch is used, `trianglelist' must point to a list of */
+/* triangles, and `numberoftriangles', `numberofcorners', and */
+/* `numberoftriangleattributes' must be properly set. If */
+/* `numberoftriangleattributes' is not zero, `triangleattributelist' */
+/* must point to a list of triangle attributes. If the `a' switch is */
+/* used (with no number following), `trianglearealist' must point to a */
+/* list of triangle area constraints. `neighborlist' may be ignored. */
+/* - If the `p' switch is used, `segmentlist' must point to a list of */
+/* segments, `numberofsegments' must be properly set, and */
+/* `segmentmarkerlist' must either be set to NULL (in which case all */
+/* markers default to zero), or must point to a list of markers. */
+/* - If the `p' switch is used without the `r' switch, then */
+/* `numberofholes' and `numberofregions' must be properly set. If */
+/* `numberofholes' is not zero, `holelist' must point to a list of */
+/* holes. If `numberofregions' is not zero, `regionlist' must point to */
+/* a list of region constraints. */
+/* - If the `p' switch is used, `holelist', `numberofholes', */
+/* `regionlist', and `numberofregions' is copied to `out'. (You can */
+/* nonetheless get away with not initializing them if the `r' switch is */
+/* used.) */
+/* - `edgelist', `edgemarkerlist', `normlist', and `numberofedges' may be */
+/* ignored. */
+/* */
+/* `out': */
+/* */
+/* - `pointlist' must be initialized (NULL or pointing to memory) unless */
+/* the `N' switch is used. `pointmarkerlist' must be initialized */
+/* unless the `N' or `B' switch is used. If `N' is not used and */
+/* `in->numberofpointattributes' is not zero, `pointattributelist' must */
+/* be initialized. */
+/* - `trianglelist' must be initialized unless the `E' switch is used. */
+/* `neighborlist' must be initialized if the `n' switch is used. If */
+/* the `E' switch is not used and (`in->numberofelementattributes' is */
+/* not zero or the `A' switch is used), `elementattributelist' must be */
+/* initialized. `trianglearealist' may be ignored. */
+/* - `segmentlist' must be initialized if the `p' or `c' switch is used, */
+/* and the `P' switch is not used. `segmentmarkerlist' must also be */
+/* initialized under these circumstances unless the `B' switch is used. */
+/* - `edgelist' must be initialized if the `e' switch is used. */
+/* `edgemarkerlist' must be initialized if the `e' switch is used and */
+/* the `B' switch is not. */
+/* - `holelist', `regionlist', `normlist', and all scalars may be ignored.*/
+/* */
+/* `vorout' (only needed if `v' switch is used): */
+/* */
+/* - `pointlist' must be initialized. If `in->numberofpointattributes' */
+/* is not zero, `pointattributelist' must be initialized. */
+/* `pointmarkerlist' may be ignored. */
+/* - `edgelist' and `normlist' must both be initialized. */
+/* `edgemarkerlist' may be ignored. */
+/* - Everything else may be ignored. */
+/* */
+/* After a call to triangulate(), the valid fields of `out' and `vorout' */
+/* will depend, in an obvious way, on the choice of switches used. Note */
+/* that when the `p' switch is used, the pointers `holelist' and */
+/* `regionlist' are copied from `in' to `out', but no new space is */
+/* allocated; be careful that you don't free() the same array twice. On */
+/* the other hand, Triangle will never copy the `pointlist' pointer (or any */
+/* others); new space is allocated for `out->pointlist', or if the `N' */
+/* switch is used, `out->pointlist' remains uninitialized. */
+/* */
+/* All of the meaningful `numberof' fields will be properly set; for */
+/* instance, `numberofedges' will represent the number of edges in the */
+/* triangulation whether or not the edges were written. If segments are */
+/* not used, `numberofsegments' will indicate the number of boundary edges. */
+/* */
+/*****************************************************************************/
+
+#define REAL double
+
+struct triangulateio {
+ REAL *pointlist; /* In / out */
+ REAL *pointattributelist; /* In / out */
+ int *pointmarkerlist; /* In / out */
+ int numberofpoints; /* In / out */
+ int numberofpointattributes; /* In / out */
+
+ int *trianglelist; /* In / out */
+ REAL *triangleattributelist; /* In / out */
+ REAL *trianglearealist; /* In only */
+ int *neighborlist; /* Out only */
+ int numberoftriangles; /* In / out */
+ int numberofcorners; /* In / out */
+ int numberoftriangleattributes; /* In / out */
+
+ int *segmentlist; /* In / out */
+ int *segmentmarkerlist; /* In / out */
+ int numberofsegments; /* In / out */
+
+ REAL *holelist; /* In / pointer to array copied out */
+ int numberofholes; /* In / copied out */
+
+ REAL *regionlist; /* In / pointer to array copied out */
+ int numberofregions; /* In / copied out */
+
+ int *edgelist; /* Out only */
+ int *edgemarkerlist; /* Not used with Voronoi diagram; out only */
+ REAL *normlist; /* Used only with Voronoi diagram; out only */
+ int numberofedges; /* Out only */
+};
+
+#define ANSI_DECLARATORS
+
+#ifdef ANSI_DECLARATORS
+void triangulate(char *, struct triangulateio *, struct triangulateio *,
+ struct triangulateio *);
+void trifree(void *memptr);
+#else /* not ANSI_DECLARATORS */
+void triangulate();
+void trifree();
+#endif /* not ANSI_DECLARATORS */
diff --git a/src/modules/grid/grid_spline/Gridding_Spline_MBA.cpp b/src/modules/grid/grid_spline/Gridding_Spline_MBA.cpp
index 1e8779b..939db16 100644
--- a/src/modules/grid/grid_spline/Gridding_Spline_MBA.cpp
+++ b/src/modules/grid/grid_spline/Gridding_Spline_MBA.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: Gridding_Spline_MBA.cpp 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: Gridding_Spline_MBA.cpp 2624 2015-09-30 15:33:53Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -76,7 +76,7 @@ CGridding_Spline_MBA::CGridding_Spline_MBA(void)
{
Set_Name (_TL("Multilevel B-Spline Interpolation"));
- Set_Author (SG_T("(c) 2006 by O.Conrad"));
+ Set_Author ("O.Conrad (c) 2006");
Set_Description (_TW(
"Multilevel B-spline algorithm for spatial interpolation of scattered data "
@@ -101,7 +101,6 @@ CGridding_Spline_MBA::CGridding_Spline_MBA(void)
Parameters.Add_Choice(
NULL , "METHOD" , _TL("Method"),
_TL(""),
-
CSG_String::Format(SG_T("%s|%s|"),
_TL("without B-spline refinement"),
_TL("with B-spline refinement")
@@ -124,7 +123,7 @@ CGridding_Spline_MBA::CGridding_Spline_MBA(void)
NULL , "UPDATE" , _TL("Update View"),
_TL(""),
PARAMETER_TYPE_Bool , false
- );
+ )->Set_UseInCMD(false);
}
//---------------------------------------------------------
diff --git a/src/modules/grid/grid_tools/Grid_Gaps.cpp b/src/modules/grid/grid_tools/Grid_Gaps.cpp
index 25db0fd..8219cb7 100644
--- a/src/modules/grid/grid_tools/Grid_Gaps.cpp
+++ b/src/modules/grid/grid_tools/Grid_Gaps.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: Grid_Gaps.cpp 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: Grid_Gaps.cpp 2623 2015-09-30 13:32:06Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -84,39 +84,36 @@
CGrid_Gaps::CGrid_Gaps(void)
{
//-----------------------------------------------------
- Set_Name(_TL("Close Gaps"));
+ Set_Name (_TL("Close Gaps"));
- Set_Author (SG_T("(c) 2002 by O.Conrad"));
+ Set_Author ("O.Conrad (c) 2002");
Set_Description (_TW(
"Close gaps of a grid data set (i.e. eliminate no data values). "
"If the target is not set, the changes will be stored to the original grid. ")
);
-
//-----------------------------------------------------
Parameters.Add_Grid(
- NULL, "INPUT" , _TL("Grid"),
+ NULL , "INPUT" , _TL("Grid"),
_TL(""),
PARAMETER_INPUT
);
Parameters.Add_Grid(
- NULL, "MASK" , _TL("Mask"),
+ NULL , "MASK" , _TL("Mask"),
_TL(""),
PARAMETER_INPUT_OPTIONAL
);
Parameters.Add_Grid(
- NULL, "RESULT" , _TL("Changed Grid"),
+ NULL , "RESULT" , _TL("Changed Grid"),
_TL(""),
PARAMETER_OUTPUT_OPTIONAL
);
-
- //-----------------------------------------------------
Parameters.Add_Value(
- NULL, "THRESHOLD" , _TL("Tension Threshold"),
+ NULL , "THRESHOLD" , _TL("Tension Threshold"),
_TL(""), PARAMETER_TYPE_Double, 0.1
);
}
@@ -135,40 +132,27 @@ CGrid_Gaps::~CGrid_Gaps(void)
//---------------------------------------------------------
bool CGrid_Gaps::On_Execute(void)
{
- bool bKillInput;
-
//-----------------------------------------------------
- pInput = Parameters("INPUT") ->asGrid();
- pMask = Parameters("MASK") ->asGrid();
-
- if( Parameters("RESULT")->asGrid() == NULL || Parameters("RESULT")->asGrid() == pInput )
- {
- pResult = pInput;
- Parameters("RESULT")->Set_Value(pResult);
+ CSG_Grid Input;
- pInput = SG_Create_Grid(pInput);
- pInput->Assign(pResult);
+ pInput = Parameters("INPUT" )->asGrid();
+ pMask = Parameters("MASK" )->asGrid();
+ pResult = Parameters("RESULT")->asGrid();
- bKillInput = true;
- }
- else
+ if( !pResult || pResult == pInput )
{
- pResult = Parameters("RESULT")->asGrid();
- pResult->Get_History().Assign(pInput->Get_History());
-
- bKillInput = false;
+ Parameters("RESULT")->Set_Value(pResult = pInput);
+ Input.Create(*pInput);
+ Input.Get_History() = pInput->Get_History();
+ pInput = &Input;
}
//-----------------------------------------------------
Tension_Main();
//-----------------------------------------------------
- if( bKillInput )
- {
- delete(pInput);
- }
+ if( Input.is_Valid() ) Parameters("INPUT")->asGrid()->Get_History() = Input.Get_History();
- //-----------------------------------------------------
return( true );
}
diff --git a/src/modules/imagery/imagery_classification/MLB_Interface.cpp b/src/modules/imagery/imagery_classification/MLB_Interface.cpp
index 8171b8d..9d954ef 100644
--- a/src/modules/imagery/imagery_classification/MLB_Interface.cpp
+++ b/src/modules/imagery/imagery_classification/MLB_Interface.cpp
@@ -102,6 +102,7 @@ CSG_String Get_Info(int i)
#include "change_detection.h"
#include "decision_tree.h"
#include "classify_supervised_polygons.h"
+#include "classification_quality.h"
//---------------------------------------------------------
@@ -117,8 +118,9 @@ CSG_Module * Create_Module(int i)
case 3: return( new CDecision_Tree );
case 4: return( new CPolygon_Classify_Supervised( true) );
case 5: return( new CPolygon_Classify_Supervised(false) );
+ case 6: return( new CClassification_Quality );
- case 6: return( NULL );
+ case 7: return( NULL );
default: return( MLB_INTERFACE_SKIP_MODULE );
}
}
diff --git a/src/modules/imagery/imagery_classification/Makefile.am b/src/modules/imagery/imagery_classification/Makefile.am
index 70dfe4a..9bd0932 100644
--- a/src/modules/imagery/imagery_classification/Makefile.am
+++ b/src/modules/imagery/imagery_classification/Makefile.am
@@ -11,12 +11,14 @@ AM_LDFLAGS = -fPIC -shared -avoid-version
pkglib_LTLIBRARIES = libimagery_classification.la
libimagery_classification_la_SOURCES =\
change_detection.cpp\
+classification_quality.cpp\
classify_cluster_analysis.cpp\
classify_supervised.cpp\
classify_supervised_polygons.cpp\
decision_tree.cpp\
MLB_Interface.cpp\
change_detection.h\
+classification_quality.h\
classify_cluster_analysis.h\
classify_supervised.h\
classify_supervised_polygons.h\
diff --git a/src/modules/imagery/imagery_classification/Makefile.in b/src/modules/imagery/imagery_classification/Makefile.in
index bd701f5..32d5db8 100644
--- a/src/modules/imagery/imagery_classification/Makefile.in
+++ b/src/modules/imagery/imagery_classification/Makefile.in
@@ -128,9 +128,9 @@ LTLIBRARIES = $(pkglib_LTLIBRARIES)
libimagery_classification_la_DEPENDENCIES = \
$(top_srcdir)/src/saga_core/saga_api/libsaga_api.la
am_libimagery_classification_la_OBJECTS = change_detection.lo \
- classify_cluster_analysis.lo classify_supervised.lo \
- classify_supervised_polygons.lo decision_tree.lo \
- MLB_Interface.lo
+ classification_quality.lo classify_cluster_analysis.lo \
+ classify_supervised.lo classify_supervised_polygons.lo \
+ decision_tree.lo MLB_Interface.lo
libimagery_classification_la_OBJECTS = \
$(am_libimagery_classification_la_OBJECTS)
AM_V_lt = $(am__v_lt_ at AM_V@)
@@ -372,12 +372,14 @@ AM_LDFLAGS = -fPIC -shared -avoid-version
pkglib_LTLIBRARIES = libimagery_classification.la
libimagery_classification_la_SOURCES = \
change_detection.cpp\
+classification_quality.cpp\
classify_cluster_analysis.cpp\
classify_supervised.cpp\
classify_supervised_polygons.cpp\
decision_tree.cpp\
MLB_Interface.cpp\
change_detection.h\
+classification_quality.h\
classify_cluster_analysis.h\
classify_supervised.h\
classify_supervised_polygons.h\
@@ -466,6 +468,7 @@ distclean-compile:
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/MLB_Interface.Plo at am__quote@
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/change_detection.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/classification_quality.Plo at am__quote@
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/classify_cluster_analysis.Plo at am__quote@
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/classify_supervised.Plo at am__quote@
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/classify_supervised_polygons.Plo at am__quote@
diff --git a/src/modules/imagery/imagery_classification/change_detection.cpp b/src/modules/imagery/imagery_classification/change_detection.cpp
index 54ed49a..d0ed46b 100644
--- a/src/modules/imagery/imagery_classification/change_detection.cpp
+++ b/src/modules/imagery/imagery_classification/change_detection.cpp
@@ -74,39 +74,46 @@ CChange_Detection::CChange_Detection(void)
CSG_Parameter *pNode, *pTable;
//-----------------------------------------------------
- Set_Name (_TL("Change Detection"));
+ Set_Name (_TL("Confusion Matrix (Two Grids)"));
- Set_Author (SG_T("O.Conrad (c) 2010"));
+ Set_Author ("O.Conrad (c) 2010");
Set_Description (_TW(
- "Change detection for classified grids."
+ "Compares two classified grids and creates a confusion matrix "
+ "and derived coefficients as well as the combinations of both "
+ "classifications as new grid. "
+ "Grid classes have to be defined with a look-up table and "
+ "values of both grids must match each other for the "
+ "subsequent comparison. "
+ "A typical application is a change detection analysis "
+ "based on land cover classification of satellite imagery. "
));
//-----------------------------------------------------
pNode = Parameters.Add_Grid(
- NULL , "INITIAL" , _TL("Initial State"),
+ NULL , "ONE" , _TL("Classification 1"),
_TL(""),
PARAMETER_INPUT
);
- pTable = Parameters.Add_Table(pNode, "INI_LUT" , _TL("Look-up Table") , _TL(""), PARAMETER_INPUT_OPTIONAL);
- Parameters.Add_Table_Field(pTable, "INI_LUT_MIN", _TL("Value") , _TL(""), false);
- Parameters.Add_Table_Field(pTable, "INI_LUT_MAX", _TL("Value (Maximum)"), _TL(""), true );
- Parameters.Add_Table_Field(pTable, "INI_LUT_NAM", _TL("Name") , _TL(""), true);
+ pTable = Parameters.Add_Table(pNode, "ONE_LUT" , _TL("Look-up Table") , _TL(""), PARAMETER_INPUT_OPTIONAL);
+ Parameters.Add_Table_Field(pTable, "ONE_LUT_MIN", _TL("Value") , _TL(""), false);
+ Parameters.Add_Table_Field(pTable, "ONE_LUT_MAX", _TL("Value (Maximum)"), _TL(""), true );
+ Parameters.Add_Table_Field(pTable, "ONE_LUT_NAM", _TL("Name") , _TL(""), true);
pNode = Parameters.Add_Grid(
- NULL , "FINAL" , _TL("Final State"),
+ NULL , "TWO" , _TL("Classification 2"),
_TL(""),
PARAMETER_INPUT
);
- pTable = Parameters.Add_Table(pNode, "FIN_LUT" , _TL("Look-up Table") , _TL(""), PARAMETER_INPUT_OPTIONAL);
- Parameters.Add_Table_Field(pTable, "FIN_LUT_MIN", _TL("Value") , _TL(""), false);
- Parameters.Add_Table_Field(pTable, "FIN_LUT_MAX", _TL("Value (Maximum)"), _TL(""), true );
- Parameters.Add_Table_Field(pTable, "FIN_LUT_NAM", _TL("Name") , _TL(""), true);
+ pTable = Parameters.Add_Table(pNode, "TWO_LUT" , _TL("Look-up Table") , _TL(""), PARAMETER_INPUT_OPTIONAL);
+ Parameters.Add_Table_Field(pTable, "TWO_LUT_MIN", _TL("Value") , _TL(""), false);
+ Parameters.Add_Table_Field(pTable, "TWO_LUT_MAX", _TL("Value (Maximum)"), _TL(""), true );
+ Parameters.Add_Table_Field(pTable, "TWO_LUT_NAM", _TL("Name") , _TL(""), true);
Parameters.Add_Grid(
- NULL , "CHANGE" , _TL("Changes"),
+ NULL , "COMBINED" , _TL("Combined Classes"),
_TL(""),
PARAMETER_OUTPUT
);
@@ -118,7 +125,7 @@ CChange_Detection::CChange_Detection(void)
);
pNode = Parameters.Add_Table(
- NULL , "CHANGES" , _TL("Changes"),
+ NULL , "CONFUSION" , _TL("Confusion Matrix"),
_TL(""),
PARAMETER_OUTPUT
);
@@ -126,12 +133,24 @@ CChange_Detection::CChange_Detection(void)
Parameters.Add_Choice(
pNode , "OUTPUT" , _TL("Output as..."),
_TL(""),
- CSG_String::Format(SG_T("%s|%s|%s|"),
+ CSG_String::Format("%s|%s|%s|",
_TL("cells"),
_TL("percent"),
_TL("area")
), 0
);
+
+ Parameters.Add_Table(
+ NULL , "CLASSES" , _TL("Class Values"),
+ _TL(""),
+ PARAMETER_OUTPUT
+ );
+
+ Parameters.Add_Table(
+ NULL , "SUMMARY" , _TL("Summary"),
+ _TL(""),
+ PARAMETER_OUTPUT
+ );
}
@@ -142,18 +161,24 @@ CChange_Detection::CChange_Detection(void)
//---------------------------------------------------------
int CChange_Detection::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
{
- if( !SG_STR_CMP(pParameter->Get_Identifier(), SG_T("INI_LUT")) )
+ if( !SG_STR_CMP(pParameter->Get_Identifier(), "ONE_LUT") )
+ {
+ pParameters->Set_Enabled("ONE_LUT_MIN", pParameter->asTable() != NULL);
+ pParameters->Set_Enabled("ONE_LUT_MAX", pParameter->asTable() != NULL);
+ pParameters->Set_Enabled("ONE_LUT_NAM", pParameter->asTable() != NULL);
+ }
+
+ if( !SG_STR_CMP(pParameter->Get_Identifier(), "TWO_LUT") )
{
- pParameters->Get_Parameter("INI_LUT_MIN")->Set_Enabled(pParameter->asTable() != NULL);
- pParameters->Get_Parameter("INI_LUT_MAX")->Set_Enabled(pParameter->asTable() != NULL);
- pParameters->Get_Parameter("INI_LUT_NAM")->Set_Enabled(pParameter->asTable() != NULL);
+ pParameters->Set_Enabled("TWO_LUT_MIN", pParameter->asTable() != NULL);
+ pParameters->Set_Enabled("TWO_LUT_MAX", pParameter->asTable() != NULL);
+ pParameters->Set_Enabled("TWO_LUT_NAM", pParameter->asTable() != NULL);
}
- if( !SG_STR_CMP(pParameter->Get_Identifier(), SG_T("FIN_LUT")) )
+ if( !SG_STR_CMP(pParameter->Get_Identifier(), "NOCHANGE") )
{
- pParameters->Get_Parameter("FIN_LUT_MIN")->Set_Enabled(pParameter->asTable() != NULL);
- pParameters->Get_Parameter("FIN_LUT_MAX")->Set_Enabled(pParameter->asTable() != NULL);
- pParameters->Get_Parameter("FIN_LUT_NAM")->Set_Enabled(pParameter->asTable() != NULL);
+ pParameters->Set_Enabled("CLASSES" , pParameter->asBool());
+ pParameters->Set_Enabled("SUMMARY" , pParameter->asBool());
}
return( 1 );
@@ -168,33 +193,35 @@ int CChange_Detection::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Par
bool CChange_Detection::On_Execute(void)
{
bool bNoChange;
- int iInitial, iFinal;
+ int iOne, iTwo;
CSG_Matrix Identity;
- CSG_Table Initial, Final, *pChanges;
- CSG_Grid *pInitial, *pFinal, *pChange;
+ CSG_Table One, Two, *pConfusion, *pClasses, *pSummary;
+ CSG_Grid *pOne, *pTwo, *pCombined;
//-----------------------------------------------------
- pInitial = Parameters("INITIAL") ->asGrid();
- pFinal = Parameters("FINAL") ->asGrid();
- pChange = Parameters("CHANGE") ->asGrid();
- pChanges = Parameters("CHANGES") ->asTable();
- bNoChange = Parameters("NOCHANGE")->asBool();
-
- if( !Get_Classes(Initial, pInitial, true) )
+ pOne = Parameters("ONE" )->asGrid();
+ pTwo = Parameters("TWO" )->asGrid();
+ pCombined = Parameters("COMBINED" )->asGrid();
+ pConfusion = Parameters("CONFUSION")->asTable();
+ pClasses = Parameters("CLASSES" )->asTable();
+ pSummary = Parameters("SUMMARY" )->asTable();
+ bNoChange = Parameters("NOCHANGE" )->asBool();
+
+ if( !Get_Classes(One, pOne, true) )
{
Error_Set(_TL("no class definitions for initial state"));
return( false );
}
- if( !Get_Classes(Final, pFinal, false) )
+ if( !Get_Classes(Two, pTwo, false) )
{
Error_Set(_TL("no class definitions for final state"));
return( false );
}
- if( !Get_Changes(Initial, Final, pChanges, Identity) )
+ if( !Get_Changes(One, Two, pConfusion, Identity) )
{
return( false );
}
@@ -204,18 +231,18 @@ bool CChange_Detection::On_Execute(void)
{
for(int x=0; x<Get_NX(); x++)
{
- iInitial = Get_Class(Initial, pInitial->asDouble(x, y));
- iFinal = Get_Class(Final , pFinal ->asDouble(x, y));
+ iOne = Get_Class(One, pOne->asDouble(x, y));
+ iTwo = Get_Class(Two, pTwo->asDouble(x, y));
- if( bNoChange || !Identity[iInitial][iFinal] )
+ if( bNoChange || !Identity[iOne][iTwo] )
{
- pChanges->Get_Record(iInitial)->Add_Value(1 + iFinal, 1);
+ pConfusion->Get_Record(iOne)->Add_Value(1 + iTwo, 1);
- pChange->Set_Value(x, y, (pChanges->Get_Field_Count() - 1) * iInitial + iFinal);
+ pCombined->Set_Value(x, y, (pConfusion->Get_Field_Count() - 1) * iOne + iTwo);
}
else
{
- pChange->Set_Value(x, y, -1);
+ pCombined->Set_Value(x, y, -1);
}
}
}
@@ -223,43 +250,51 @@ bool CChange_Detection::On_Execute(void)
//-----------------------------------------------------
CSG_Parameters P;
- if( DataObject_Get_Parameters(pChange, P) && P("COLORS_TYPE") && P("LUT") )
+ if( DataObject_Get_Parameters(pCombined, P) && P("COLORS_TYPE") && P("LUT") )
{
CSG_Table *pLUT = P("LUT")->asTable();
- CSG_Colors cRandom(pChanges->Get_Count());
+ CSG_Colors cRandom(pConfusion->Get_Count());
cRandom.Random();
pLUT->Del_Records();
- for(iInitial=0; iInitial<pChanges->Get_Count(); iInitial++)
+ for(iOne=0; iOne<pConfusion->Get_Count(); iOne++)
{
- CSG_Colors cRamp(pChanges->Get_Field_Count() - 1);
+ CSG_Colors cRamp(pConfusion->Get_Field_Count() - 1);
- cRamp.Set_Ramp(cRandom[iInitial], cRandom[iInitial]);
+ cRamp.Set_Ramp(cRandom[iOne], cRandom[iOne]);
cRamp.Set_Ramp_Brighness(225, 50);
- for(iFinal=0; iFinal<pChanges->Get_Field_Count()-1; iFinal++)
+ for(iTwo=0; iTwo<pConfusion->Get_Field_Count()-1; iTwo++)
{
- if( pChanges->Get_Record(iInitial)->asInt(1 + iFinal) > 0 )
+ if( pConfusion->Get_Record(iOne)->asInt(1 + iTwo) > 0 )
{
CSG_Table_Record *pClass = pLUT->Add_Record();
- pClass->Set_Value(0, cRamp.Get_Color(iFinal));
- pClass->Set_Value(1, CSG_String::Format(SG_T("%s >> %s"), pChanges->Get_Record(iInitial)->asString(0), pChanges->Get_Field_Name(1 + iFinal)));
- pClass->Set_Value(3, (pChanges->Get_Field_Count() - 1) * iInitial + iFinal);
- pClass->Set_Value(4, (pChanges->Get_Field_Count() - 1) * iInitial + iFinal);
+ pClass->Set_Value(0, cRamp.Get_Color(iTwo));
+ pClass->Set_Value(1, CSG_String::Format("%s >> %s", pConfusion->Get_Record(iOne)->asString(0), pConfusion->Get_Field_Name(1 + iTwo)));
+ pClass->Set_Value(3, (pConfusion->Get_Field_Count() - 1) * iOne + iTwo);
+ pClass->Set_Value(4, (pConfusion->Get_Field_Count() - 1) * iOne + iTwo);
}
}
}
P("COLORS_TYPE")->Set_Value(1); // Color Classification Type: Lookup Table
- DataObject_Set_Parameters(pChange, P);
+ DataObject_Set_Parameters(pCombined, P);
}
//-----------------------------------------------------
+ if( bNoChange )
+ {
+ Get_Quality(*pConfusion, *pClasses, *pSummary);
+
+ pClasses ->Set_Name(CSG_String::Format("%s [%s - %s]", _TL("Class Values"), pOne->Get_Name(), pTwo->Get_Name()));
+ pSummary ->Set_Name(CSG_String::Format("%s [%s - %s]", _TL("Summary" ), pOne->Get_Name(), pTwo->Get_Name()));
+ }
+
double Factor;
switch( Parameters("OUTPUT")->asInt() )
@@ -271,20 +306,19 @@ bool CChange_Detection::On_Execute(void)
if( Factor != 1.0 )
{
- for(iInitial=0; iInitial<pChanges->Get_Count(); iInitial++)
+ for(iOne=0; iOne<pConfusion->Get_Count(); iOne++)
{
- for(iFinal=0; iFinal<pChanges->Get_Field_Count()-1; iFinal++)
+ for(iTwo=0; iTwo<pConfusion->Get_Field_Count()-1; iTwo++)
{
- pChanges->Get_Record(iInitial)->Mul_Value(1 + iFinal, Factor);
+ pConfusion->Get_Record(iOne)->Mul_Value(1 + iTwo, Factor);
}
}
}
//-----------------------------------------------------
- pChanges ->Set_Name(CSG_String::Format(SG_T("%s [%s >> %s]"), _TL("Changes"), pInitial->Get_Name(), pFinal->Get_Name()));
-
- pChange ->Set_Name(CSG_String::Format(SG_T("%s [%s >> %s]"), _TL("Changes"), pInitial->Get_Name(), pFinal->Get_Name()));
- pChange ->Set_NoData_Value(-1);
+ pConfusion->Set_Name(CSG_String::Format("%s [%s - %s]", _TL("Confusion" ), pOne->Get_Name(), pTwo->Get_Name()));
+ pCombined ->Set_Name(CSG_String::Format("%s [%s - %s]", _TL("Combination" ), pOne->Get_Name(), pTwo->Get_Name()));
+ pCombined ->Set_NoData_Value(-1);
return( true );
}
@@ -295,6 +329,76 @@ bool CChange_Detection::On_Execute(void)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
+bool CChange_Detection::Get_Quality(CSG_Table &Confusion, CSG_Table &Classes, CSG_Table &Summary)
+{
+ if( Confusion.Get_Count() != Confusion.Get_Field_Count() - 1 )
+ {
+ Message_Add(_TL("Quality assessment is not calculated, because the number of classes in the input grids differ."));
+
+ return( false );
+ }
+
+ //-----------------------------------------------------
+ Classes.Destroy();
+ Classes.Add_Field("Class" , SG_DATATYPE_String);
+ Classes.Add_Field("SumRef" , SG_DATATYPE_Int);
+ Classes.Add_Field("AccProd" , SG_DATATYPE_Double);
+ Classes.Add_Field("SumClassified", SG_DATATYPE_Int);
+ Classes.Add_Field("AccUser" , SG_DATATYPE_Double);
+ Classes.Set_Record_Count(Confusion.Get_Count());
+
+ sLong nTotal = 0, nTrue = 0, nProd = 0;
+
+ for(int i=0; i<Confusion.Get_Count(); i++)
+ {
+ sLong nOne = 0;
+ sLong nTwo = 0;
+
+ for(int j=0; j<Confusion.Get_Count(); j++)
+ {
+ nOne += Confusion[j].asLong(1 + i);
+ nTwo += Confusion[i].asLong(1 + j);
+ }
+
+ Classes[i].Set_Value(0, Confusion[i].asString(0));
+ Classes[i].Set_Value(1, nOne);
+ Classes[i].Set_Value(2, nOne <= 0 ? -1. : Confusion[i].asLong(1 + i) / (double)nOne);
+ Classes[i].Set_Value(3, nTwo);
+ Classes[i].Set_Value(4, nTwo <= 0 ? -1. : Confusion[i].asLong(1 + i) / (double)nTwo);
+
+ nTotal += nOne;
+ nTrue += Confusion[i].asLong(1 + i);
+ nProd += nOne * nTwo;
+ }
+
+ //-----------------------------------------------------
+ Summary.Destroy();
+ Summary.Add_Field("NAME" , SG_DATATYPE_String);
+ Summary.Add_Field("VALUE", SG_DATATYPE_Double);
+ Summary.Set_Record_Count(2);
+
+ double k = nTotal*nTotal - nProd, OA = 0.0;
+
+ if( k != 0.0 )
+ {
+ Summary[0].Set_Value(0, "Kappa" ); Summary[0].Set_Value(1, k = (nTotal * nTrue - nProd) / k);
+ Summary[1].Set_Value(0, "Overall Accuracy"); Summary[1].Set_Value(1, OA = nTrue / (double)nTotal);
+
+ Message_Add(CSG_String::Format("\n%s: %f", _TL("Kappa" ), k ), false);
+ Message_Add(CSG_String::Format("\n%s: %f", _TL("Overall Accuracy"), OA), false);
+
+ return( true );
+ }
+
+ return( false );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
enum
{
CLASS_NAM = 0,
@@ -309,16 +413,16 @@ bool CChange_Detection::Get_Classes(CSG_Table &Classes, CSG_Grid *pGrid, bool bI
Classes.Destroy();
- Classes.Add_Field(_TL("NAME") , SG_DATATYPE_String);
- Classes.Add_Field(_TL("MIN") , SG_DATATYPE_Double);
- Classes.Add_Field(_TL("MAX") , SG_DATATYPE_Double);
+ Classes.Add_Field(_TL("NAME"), SG_DATATYPE_String);
+ Classes.Add_Field(_TL("MIN" ), SG_DATATYPE_Double);
+ Classes.Add_Field(_TL("MAX" ), SG_DATATYPE_Double);
//-----------------------------------------------------
- if( (pClasses = Parameters(bInitial ? "INI_LUT" : "FIN_LUT")->asTable()) != NULL )
+ if( (pClasses = Parameters(bInitial ? "ONE_LUT" : "TWO_LUT")->asTable()) != NULL )
{
- int fNam = Parameters(bInitial ? "INI_LUT_NAM" : "FIN_LUT_NAM")->asInt();
- int fMin = Parameters(bInitial ? "INI_LUT_MIN" : "FIN_LUT_MIN")->asInt();
- int fMax = Parameters(bInitial ? "INI_LUT_MAX" : "FIN_LUT_MAX")->asInt();
+ int fNam = Parameters(bInitial ? "ONE_LUT_NAM" : "TWO_LUT_NAM")->asInt();
+ int fMin = Parameters(bInitial ? "ONE_LUT_MIN" : "TWO_LUT_MIN")->asInt();
+ int fMax = Parameters(bInitial ? "ONE_LUT_MAX" : "TWO_LUT_MAX")->asInt();
if( fNam < 0 || fNam >= pClasses->Get_Field_Count() ) { fNam = fMin; }
if( fMax < 0 || fMax >= pClasses->Get_Field_Count() ) { fMax = fMin; }
@@ -385,44 +489,46 @@ bool CChange_Detection::Get_Classes(CSG_Table &Classes, CSG_Grid *pGrid, bool bI
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-bool CChange_Detection::Get_Changes(CSG_Table &Initial, CSG_Table &Final, CSG_Table *pChanges, CSG_Matrix &Identity)
+bool CChange_Detection::Get_Changes(CSG_Table &One, CSG_Table &Two, CSG_Table *pConfusion, CSG_Matrix &Identity)
{
- int iInitial, iFinal;
+ int iOne, iTwo;
//-----------------------------------------------------
- Identity.Create(Final.Get_Count() + 1, Initial.Get_Count() + 1);
+ Identity.Create(Two.Get_Count() + 1, One.Get_Count() + 1);
- for(iInitial=0; iInitial<Initial.Get_Count(); iInitial++)
+ for(iOne=0; iOne<One.Get_Count(); iOne++)
{
- CSG_String s = Initial[iInitial].asString(CLASS_NAM);
+ CSG_String s = One[iOne].asString(CLASS_NAM);
- for(iFinal=0; iFinal<Final.Get_Count(); iFinal++)
+ for(iTwo=0; iTwo<Two.Get_Count(); iTwo++)
{
- Identity[iInitial][iFinal] = s.Cmp(Final[iFinal].asString(CLASS_NAM)) ? 0 : 1;
+ Identity[iOne][iTwo] = s.Cmp(Two[iTwo].asString(CLASS_NAM)) ? 0 : 1;
}
}
- Identity[Initial.Get_Count()][Final.Get_Count()] = 1; // unclassified
+ Identity[One.Get_Count()][Two.Get_Count()] = 1; // unclassified
//-----------------------------------------------------
- pChanges->Destroy();
+ TSG_Data_Type Fieldtype = Parameters("OUTPUT")->asInt() == 0 ? SG_DATATYPE_Long : SG_DATATYPE_Double;
+
+ pConfusion->Destroy();
- pChanges->Add_Field(_TL("Name"), SG_DATATYPE_String);
+ pConfusion->Add_Field(_TL("Name"), SG_DATATYPE_String);
- for(iFinal=0; iFinal<Final.Get_Count(); iFinal++)
+ for(iTwo=0; iTwo<Two.Get_Count(); iTwo++)
{
- pChanges->Add_Field(Final[iFinal].asString(CLASS_NAM), SG_DATATYPE_Double);
+ pConfusion->Add_Field(Two[iTwo].asString(CLASS_NAM), Fieldtype);
}
- pChanges->Add_Field(_TL("Unclassified"), SG_DATATYPE_Double);
+ pConfusion->Add_Field(_TL("Unclassified"), SG_DATATYPE_Double);
//-----------------------------------------------------
- for(iInitial=0; iInitial<Initial.Get_Count(); iInitial++)
+ for(iOne=0; iOne<One.Get_Count(); iOne++)
{
- pChanges->Add_Record()->Set_Value(0, Initial[iInitial].asString(CLASS_NAM));
+ pConfusion->Add_Record()->Set_Value(0, One[iOne].asString(CLASS_NAM));
}
- pChanges->Add_Record()->Set_Value(0, _TL("Unclassified"));
+ pConfusion->Add_Record()->Set_Value(0, _TL("Unclassified"));
return( true );
}
diff --git a/src/modules/imagery/imagery_classification/change_detection.h b/src/modules/imagery/imagery_classification/change_detection.h
index e61cfb2..8ce7552 100644
--- a/src/modules/imagery/imagery_classification/change_detection.h
+++ b/src/modules/imagery/imagery_classification/change_detection.h
@@ -95,6 +95,8 @@ protected:
private:
+ bool Get_Quality (CSG_Table &Confusion, CSG_Table &Classes, CSG_Table &Summary);
+
bool Get_Classes (CSG_Table &Classes, CSG_Grid *pGrid, bool bInitial);
bool Get_Changes (CSG_Table &Initial, CSG_Table &Final, CSG_Table *pChanges, CSG_Matrix &Identity);
diff --git a/src/modules/imagery/imagery_classification/classification_quality.cpp b/src/modules/imagery/imagery_classification/classification_quality.cpp
new file mode 100644
index 0000000..f2e3389
--- /dev/null
+++ b/src/modules/imagery/imagery_classification/classification_quality.cpp
@@ -0,0 +1,429 @@
+/**********************************************************
+ * Version $Id: classification_quality.cpp 1921 2014-01-09 10:24:11Z oconrad $
+ *********************************************************/
+
+///////////////////////////////////////////////////////////
+// //
+// SAGA //
+// //
+// System for Automated Geoscientific Analyses //
+// //
+// Module Library: //
+// imagery_classification //
+// //
+//-------------------------------------------------------//
+// //
+// classification_quality.cpp //
+// //
+// Copyright (C) 2015 by //
+// Olaf Conrad //
+// //
+//-------------------------------------------------------//
+// //
+// This file is part of 'SAGA - System for Automated //
+// Geoscientific Analyses'. SAGA 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; version 2 of the License. //
+// //
+// SAGA 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 Street, 5th Floor, Boston, MA 02110-1301, //
+// USA. //
+// //
+//-------------------------------------------------------//
+// //
+// e-mail: oconrad at saga-gis.org //
+// //
+// contact: Olaf Conrad //
+// Institute of Geography //
+// University of Hamburg //
+// Germany //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+#include "classification_quality.h"
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+CClassification_Quality::CClassification_Quality(void)
+{
+ CSG_Parameter *pNode, *pTable;
+
+ //-----------------------------------------------------
+ Set_Name (_TL("Confusion Matrix (Polygons / Grid)"));
+
+ Set_Author ("O.Conrad (c) 2015");
+
+ Set_Description (_TW(
+ "Compares a classified polygons layer with grid classes and "
+ "creates a confusion matrix and derived coefficients. "
+ "Grid classes have to be defined with a look-up table and "
+ "values must match those of the polygon classes for the "
+ "subsequent comparison. "
+ "This tool is typically used for a quality assessment of a "
+ "supervised classification. "
+ ));
+
+ //-----------------------------------------------------
+ pNode = Parameters.Add_Grid(
+ NULL , "GRID" , _TL("Classification"),
+ _TL(""),
+ PARAMETER_INPUT
+ );
+
+ pTable = Parameters.Add_Table(pNode, "GRID_LUT" , _TL("Look-up Table" ), _TL(""), PARAMETER_INPUT_OPTIONAL);
+ Parameters.Add_Table_Field(pTable, "GRID_LUT_MIN", _TL("Value" ), _TL(""), false);
+ Parameters.Add_Table_Field(pTable, "GRID_LUT_MAX", _TL("Value (Maximum)"), _TL(""), true );
+ Parameters.Add_Table_Field(pTable, "GRID_LUT_NAM", _TL("Name" ), _TL(""), true);
+
+ pNode = Parameters.Add_Shapes(
+ NULL , "POLYGONS" , _TL("Polygons"),
+ _TL(""),
+ PARAMETER_INPUT
+ );
+
+ Parameters.Add_Table_Field(
+ pNode , "FIELD" , _TL("Classes"),
+ _TL("")
+ );
+
+ Parameters.Add_Table(
+ NULL , "CONFUSION" , _TL("Confusion Matrix"),
+ _TL(""),
+ PARAMETER_OUTPUT
+ );
+
+ Parameters.Add_Table(
+ NULL , "CLASSES" , _TL("Class Values"),
+ _TL(""),
+ PARAMETER_OUTPUT
+ );
+
+ Parameters.Add_Table(
+ NULL , "SUMMARY" , _TL("Summary"),
+ _TL(""),
+ PARAMETER_OUTPUT
+ );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+int CClassification_Quality::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
+{
+ if( !SG_STR_CMP(pParameter->Get_Identifier(), "GRID_LUT") )
+ {
+ pParameters->Set_Enabled("GRID_LUT_MIN", pParameter->asTable() != NULL);
+ pParameters->Set_Enabled("GRID_LUT_MAX", pParameter->asTable() != NULL);
+ pParameters->Set_Enabled("GRID_LUT_NAM", pParameter->asTable() != NULL);
+ }
+
+ return( CSG_Module_Grid::On_Parameters_Enable(pParameters, pParameter) );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CClassification_Quality::On_Execute(void)
+{
+ //-----------------------------------------------------
+ CSG_Shapes *pPolygons = Parameters("POLYGONS")->asShapes();
+
+ if( !pPolygons->is_Valid() )
+ {
+ Error_Set(_TL("invalid polygons"));
+
+ return( false );
+ }
+
+ //-----------------------------------------------------
+ CSG_Table &Confusion = *Parameters("CONFUSION")->asTable();
+
+ int Field = Parameters("FIELD")->asInt();
+
+ if( !Get_Classes(pPolygons, Field, Confusion) )
+ {
+ Error_Set(_TL("invalid polygons"));
+
+ return( false );
+ }
+
+ //-----------------------------------------------------
+ CSG_Grid *pGrid = Parameters("GRID")->asGrid();
+
+ if( !Get_Classes(pGrid) )
+ {
+ Error_Set(_TL("no class definitions for grid"));
+
+ return( false );
+ }
+
+ Confusion.Set_Name(CSG_String::Format("%s [%s - %s]", _TL("Confusion Matrix"), pPolygons->Get_Name(), pGrid->Get_Name()));
+
+ //-----------------------------------------------------
+ TSG_Point p; p.y = Get_YMin();
+
+ for(int y=0; y<Get_NY() && Set_Progress(y); y++, p.y+=Get_Cellsize())
+ {
+ p.x = Get_XMin();
+
+ for(int x=0; x<Get_NX(); x++, p.x+=Get_Cellsize())
+ {
+ int iGrid = Get_Class(pGrid->asInt(x, y));
+
+ if( iGrid >= 0 )
+ {
+ for(int iPolygon=0; iPolygon<pPolygons->Get_Count(); iPolygon++)
+ {
+ CSG_Shape_Polygon *pPolygon = (CSG_Shape_Polygon *)pPolygons->Get_Shape(iPolygon);
+
+ if( pPolygon->Contains(p) )
+ {
+ int iPolygon = Get_Class(pPolygon->asString(Field));
+
+ if( iPolygon >= 0 )
+ {
+ Confusion[iGrid].Add_Value(1 + iPolygon, 1);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ //-----------------------------------------------------
+ CSG_Table &Classes = *Parameters("CLASSES")->asTable();
+
+ Classes.Destroy();
+ Classes.Set_Name(CSG_String::Format("%s [%s - %s]", _TL("Class Values"), pPolygons->Get_Name(), pGrid->Get_Name()));
+ Classes.Add_Field("Class" , SG_DATATYPE_String);
+ Classes.Add_Field("SumRef" , SG_DATATYPE_Int);
+ Classes.Add_Field("AccProd" , SG_DATATYPE_Double);
+ Classes.Add_Field("SumClassified", SG_DATATYPE_Int);
+ Classes.Add_Field("AccUser" , SG_DATATYPE_Double);
+ Classes.Set_Record_Count(m_Classes.Get_Count());
+
+ sLong nTotal = 0, nTrue = 0, nProd = 0;
+
+ for(int i=0; i<m_Classes.Get_Count(); i++)
+ {
+ sLong nPoly = 0;
+ sLong nGrid = 0;
+
+ for(int j=0; j<m_Classes.Get_Count(); j++)
+ {
+ nPoly += Confusion[j].asLong(1 + i);
+ nGrid += Confusion[i].asLong(1 + j);
+ }
+
+ Classes[i].Set_Value(0, m_Classes[i].asString(0));
+ Classes[i].Set_Value(1, nPoly);
+ Classes[i].Set_Value(2, nPoly <= 0 ? -1. : Confusion[i].asLong(1 + i) / (double)nPoly);
+ Classes[i].Set_Value(3, nGrid);
+ Classes[i].Set_Value(4, nGrid <= 0 ? -1. : Confusion[i].asLong(1 + i) / (double)nGrid);
+
+ nTotal += nPoly;
+ nTrue += Confusion[i].asLong(1 + i);
+ nProd += nPoly * nGrid;
+ }
+
+ //-----------------------------------------------------
+ CSG_Table &Summary = *Parameters("SUMMARY")->asTable();
+
+ Summary.Destroy();
+ Summary.Set_Name(CSG_String::Format("%s [%s - %s]", _TL("Summary"), pPolygons->Get_Name(), pGrid->Get_Name()));
+ Summary.Add_Field("NAME" , SG_DATATYPE_String);
+ Summary.Add_Field("VALUE", SG_DATATYPE_Double);
+ Summary.Set_Record_Count(2);
+
+ double k = nTotal*nTotal - nProd, OA = 0.0;
+
+ if( k != 0.0 )
+ {
+ Summary[0].Set_Value(0, "Kappa" ); Summary[0].Set_Value(1, k = (nTotal * nTrue - nProd) / k);
+ Summary[1].Set_Value(0, "Overall Accuracy"); Summary[1].Set_Value(1, OA = nTrue / (double)nTotal);
+
+ Message_Add(CSG_String::Format("\n%s: %f", _TL("Kappa" ), k ), false);
+ Message_Add(CSG_String::Format("\n%s: %f", _TL("Overall Accuracy"), OA), false);
+ }
+
+ //-----------------------------------------------------
+ m_Classes.Destroy();
+
+ return( true );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+enum
+{
+ CLASS_NAM = 0,
+ CLASS_MIN,
+ CLASS_MAX
+};
+
+//---------------------------------------------------------
+bool CClassification_Quality::Get_Classes(CSG_Shapes *pPolygons, int Field, CSG_Table &Confusion)
+{
+ m_Classes.Destroy();
+
+ m_Classes.Add_Field("NAM", SG_DATATYPE_String);
+ m_Classes.Add_Field("MIN", SG_DATATYPE_Double);
+ m_Classes.Add_Field("MAX", SG_DATATYPE_Double);
+
+ Confusion.Destroy();
+ Confusion.Add_Field("CLASS", SG_DATATYPE_String);
+
+ CSG_String Class;
+
+ pPolygons->Set_Index(Field, TABLE_INDEX_Ascending);
+
+ for(int i=0; i<pPolygons->Get_Count() && Set_Progress(i, pPolygons->Get_Count()); i++)
+ {
+ CSG_Shape *pPolygon = pPolygons->Get_Shape_byIndex(i);
+
+ if( m_Classes.Get_Count() == 0 || Class.Cmp(pPolygon->asString(Field)) ) // category changed
+ {
+ Class = pPolygon->asString(Field);
+
+ Confusion.Add_Field(Class, SG_DATATYPE_Int);
+ Confusion.Add_Record()->Set_Value(0, Class);
+
+ m_Classes.Add_Record()->Set_Value(0, Class);
+ }
+ }
+
+ Confusion.Set_Record_Count(m_Classes.Get_Count());
+
+ //-----------------------------------------------------
+ return( m_Classes.Get_Count() > 0 );
+}
+
+//---------------------------------------------------------
+bool CClassification_Quality::Get_Classes(CSG_Grid *pGrid)
+{
+ int fNam, fMin, fMax;
+
+ CSG_Table *pLUT;
+
+ //-----------------------------------------------------
+ if( (pLUT = Parameters("GRID_LUT")->asTable()) != NULL )
+ {
+ fNam = Parameters("GRID_LUT_NAM")->asInt();
+ fMin = Parameters("GRID_LUT_MIN")->asInt();
+ fMax = Parameters("GRID_LUT_MAX")->asInt();
+
+ if( fNam < 0 || fNam >= pLUT->Get_Field_Count() ) { fNam = fMin; }
+ if( fMax < 0 || fMax >= pLUT->Get_Field_Count() ) { fMax = fMin; }
+ }
+ else if( DataObject_Get_Parameter(pGrid, "LUT") )
+ {
+ pLUT = DataObject_Get_Parameter(pGrid, "LUT")->asTable();
+
+ fNam = 1;
+ fMin = 3;
+ fMax = 4;
+ }
+
+ if( !pLUT )
+ {
+ return( false );
+ }
+
+ //-----------------------------------------------------
+ for(int iClass=0; iClass<pLUT->Get_Count(); iClass++)
+ {
+ CSG_Table_Record *pClass = m_Classes.Get_Record(Get_Class(pLUT->Get_Record(iClass)->asString(fNam)));
+
+ if( pClass )
+ {
+ double min = pLUT->Get_Record(iClass)->asDouble(fMin);
+ double max = pLUT->Get_Record(iClass)->asDouble(fMax);
+
+ pClass->Set_Value(CLASS_MIN, min);
+ pClass->Set_Value(CLASS_MAX, min < max ? max : min);
+ }
+ }
+
+ //-----------------------------------------------------
+ return( m_Classes.Get_Count() > 0 );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+int CClassification_Quality::Get_Class(const CSG_String &Value)
+{
+ for(int i=0; i<m_Classes.Get_Count(); i++)
+ {
+ if( !Value.Cmp(m_Classes[i].asString(CLASS_NAM)) )
+ {
+ return( i );
+ }
+ }
+
+ return( -1 );
+}
+
+//---------------------------------------------------------
+int CClassification_Quality::Get_Class(double Value)
+{
+ for(int i=0; i<m_Classes.Get_Count(); i++)
+ {
+ double min = m_Classes[i].asDouble(CLASS_MIN);
+ double max = m_Classes[i].asDouble(CLASS_MAX);
+
+ if( min <= Value && Value <= max )
+ {
+ return( i );
+ }
+ }
+
+ return( -1 );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
diff --git a/src/modules/imagery/imagery_classification/change_detection.h b/src/modules/imagery/imagery_classification/classification_quality.h
similarity index 85%
copy from src/modules/imagery/imagery_classification/change_detection.h
copy to src/modules/imagery/imagery_classification/classification_quality.h
index e61cfb2..8b862d4 100644
--- a/src/modules/imagery/imagery_classification/change_detection.h
+++ b/src/modules/imagery/imagery_classification/classification_quality.h
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: change_detection.h 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: classification_quality.h 1921 2014-01-09 10:24:11Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -13,9 +13,9 @@
// //
//-------------------------------------------------------//
// //
-// change_detection.h //
+// classification_quality.h //
// //
-// Copyright (C) 2010 by //
+// Copyright (C) 2015 by //
// Olaf Conrad //
// //
//-------------------------------------------------------//
@@ -59,8 +59,8 @@
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-#ifndef HEADER_INCLUDED__change_detection_H
-#define HEADER_INCLUDED__change_detection_H
+#ifndef HEADER_INCLUDED__classification_quality_H
+#define HEADER_INCLUDED__classification_quality_H
///////////////////////////////////////////////////////////
@@ -80,10 +80,10 @@
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-class CChange_Detection : public CSG_Module_Grid
+class CClassification_Quality : public CSG_Module_Grid
{
public:
- CChange_Detection(void);
+ CClassification_Quality(void);
protected:
@@ -95,11 +95,14 @@ protected:
private:
- bool Get_Classes (CSG_Table &Classes, CSG_Grid *pGrid, bool bInitial);
- bool Get_Changes (CSG_Table &Initial, CSG_Table &Final, CSG_Table *pChanges, CSG_Matrix &Identity);
+ CSG_Table m_Classes;
- int Cmp_Class (CSG_Table &Classes, double Value, int iClass);
- int Get_Class (CSG_Table &Classes, double Value);
+
+ bool Get_Classes (CSG_Shapes *pPolygons, int Field, CSG_Table &Confusion);
+ bool Get_Classes (CSG_Grid *pGrid);
+
+ int Get_Class (const CSG_String &Value);
+ int Get_Class (double Value);
};
@@ -111,4 +114,4 @@ private:
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-#endif // #ifndef HEADER_INCLUDED__change_detection_H
+#endif // #ifndef HEADER_INCLUDED__classification_quality_H
diff --git a/src/modules/imagery/imagery_svm/svm.cpp b/src/modules/imagery/imagery_svm/svm.cpp
new file mode 100644
index 0000000..1ecb291
--- /dev/null
+++ b/src/modules/imagery/imagery_svm/svm.cpp
@@ -0,0 +1,3089 @@
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <ctype.h>
+#include <float.h>
+#include <string.h>
+#include <stdarg.h>
+#include <limits.h>
+#include "svm.h"
+int libsvm_version = LIBSVM_VERSION;
+typedef float Qfloat;
+typedef signed char schar;
+#ifndef min
+template <class T> static inline T min(T x,T y) { return (x<y)?x:y; }
+#endif
+#ifndef max
+template <class T> static inline T max(T x,T y) { return (x>y)?x:y; }
+#endif
+template <class T> static inline void swap(T& x, T& y) { T t=x; x=y; y=t; }
+template <class S, class T> static inline void clone(T*& dst, S* src, int n)
+{
+ dst = new T[n];
+ memcpy((void *)dst,(void *)src,sizeof(T)*n);
+}
+static inline double powi(double base, int times)
+{
+ double tmp = base, ret = 1.0;
+
+ for(int t=times; t>0; t/=2)
+ {
+ if(t%2==1) ret*=tmp;
+ tmp = tmp * tmp;
+ }
+ return ret;
+}
+#define INF HUGE_VAL
+#define TAU 1e-12
+#define Malloc(type,n) (type *)malloc((n)*sizeof(type))
+
+static void print_string_stdout(const char *s)
+{
+ fputs(s,stdout);
+ fflush(stdout);
+}
+static void (*svm_print_string) (const char *) = &print_string_stdout;
+#if 1
+static void info(const char *fmt,...)
+{
+ char buf[BUFSIZ];
+ va_list ap;
+ va_start(ap,fmt);
+ vsprintf(buf,fmt,ap);
+ va_end(ap);
+ (*svm_print_string)(buf);
+}
+#else
+static void info(const char *fmt,...) {}
+#endif
+
+//
+// Kernel Cache
+//
+// l is the number of total data items
+// size is the cache size limit in bytes
+//
+class Cache
+{
+public:
+ Cache(int l,long int size);
+ ~Cache();
+
+ // request data [0,len)
+ // return some position p where [p,len) need to be filled
+ // (p >= len if nothing needs to be filled)
+ int get_data(const int index, Qfloat **data, int len);
+ void swap_index(int i, int j);
+private:
+ int l;
+ long int size;
+ struct head_t
+ {
+ head_t *prev, *next; // a circular list
+ Qfloat *data;
+ int len; // data[0,len) is cached in this entry
+ };
+
+ head_t *head;
+ head_t lru_head;
+ void lru_delete(head_t *h);
+ void lru_insert(head_t *h);
+};
+
+Cache::Cache(int l_,long int size_):l(l_),size(size_)
+{
+ head = (head_t *)calloc(l,sizeof(head_t)); // initialized to 0
+ size /= sizeof(Qfloat);
+ size -= l * sizeof(head_t) / sizeof(Qfloat);
+ size = max(size, 2 * (long int) l); // cache must be large enough for two columns
+ lru_head.next = lru_head.prev = &lru_head;
+}
+
+Cache::~Cache()
+{
+ for(head_t *h = lru_head.next; h != &lru_head; h=h->next)
+ free(h->data);
+ free(head);
+}
+
+void Cache::lru_delete(head_t *h)
+{
+ // delete from current location
+ h->prev->next = h->next;
+ h->next->prev = h->prev;
+}
+
+void Cache::lru_insert(head_t *h)
+{
+ // insert to last position
+ h->next = &lru_head;
+ h->prev = lru_head.prev;
+ h->prev->next = h;
+ h->next->prev = h;
+}
+
+int Cache::get_data(const int index, Qfloat **data, int len)
+{
+ head_t *h = &head[index];
+ if(h->len) lru_delete(h);
+ int more = len - h->len;
+
+ if(more > 0)
+ {
+ // free old space
+ while(size < more)
+ {
+ head_t *old = lru_head.next;
+ lru_delete(old);
+ free(old->data);
+ size += old->len;
+ old->data = 0;
+ old->len = 0;
+ }
+
+ // allocate new space
+ h->data = (Qfloat *)realloc(h->data,sizeof(Qfloat)*len);
+ size -= more;
+ swap(h->len,len);
+ }
+
+ lru_insert(h);
+ *data = h->data;
+ return len;
+}
+
+void Cache::swap_index(int i, int j)
+{
+ if(i==j) return;
+
+ if(head[i].len) lru_delete(&head[i]);
+ if(head[j].len) lru_delete(&head[j]);
+ swap(head[i].data,head[j].data);
+ swap(head[i].len,head[j].len);
+ if(head[i].len) lru_insert(&head[i]);
+ if(head[j].len) lru_insert(&head[j]);
+
+ if(i>j) swap(i,j);
+ for(head_t *h = lru_head.next; h!=&lru_head; h=h->next)
+ {
+ if(h->len > i)
+ {
+ if(h->len > j)
+ swap(h->data[i],h->data[j]);
+ else
+ {
+ // give up
+ lru_delete(h);
+ free(h->data);
+ size += h->len;
+ h->data = 0;
+ h->len = 0;
+ }
+ }
+ }
+}
+
+//
+// Kernel evaluation
+//
+// the static method k_function is for doing single kernel evaluation
+// the constructor of Kernel prepares to calculate the l*l kernel matrix
+// the member function get_Q is for getting one column from the Q Matrix
+//
+class QMatrix {
+public:
+ virtual Qfloat *get_Q(int column, int len) const = 0;
+ virtual double *get_QD() const = 0;
+ virtual void swap_index(int i, int j) const = 0;
+ virtual ~QMatrix() {}
+};
+
+class Kernel: public QMatrix {
+public:
+ Kernel(int l, svm_node * const * x, const svm_parameter& param);
+ virtual ~Kernel();
+
+ static double k_function(const svm_node *x, const svm_node *y,
+ const svm_parameter& param);
+ virtual Qfloat *get_Q(int column, int len) const = 0;
+ virtual double *get_QD() const = 0;
+ virtual void swap_index(int i, int j) const // no so const...
+ {
+ swap(x[i],x[j]);
+ if(x_square) swap(x_square[i],x_square[j]);
+ }
+protected:
+
+ double (Kernel::*kernel_function)(int i, int j) const;
+
+private:
+ const svm_node **x;
+ double *x_square;
+
+ // svm_parameter
+ const int kernel_type;
+ const int degree;
+ const double gamma;
+ const double coef0;
+
+ static double dot(const svm_node *px, const svm_node *py);
+ double kernel_linear(int i, int j) const
+ {
+ return dot(x[i],x[j]);
+ }
+ double kernel_poly(int i, int j) const
+ {
+ return powi(gamma*dot(x[i],x[j])+coef0,degree);
+ }
+ double kernel_rbf(int i, int j) const
+ {
+ return exp(-gamma*(x_square[i]+x_square[j]-2*dot(x[i],x[j])));
+ }
+ double kernel_sigmoid(int i, int j) const
+ {
+ return tanh(gamma*dot(x[i],x[j])+coef0);
+ }
+ double kernel_precomputed(int i, int j) const
+ {
+ return x[i][(int)(x[j][0].value)].value;
+ }
+};
+
+Kernel::Kernel(int l, svm_node * const * x_, const svm_parameter& param)
+:kernel_type(param.kernel_type), degree(param.degree),
+ gamma(param.gamma), coef0(param.coef0)
+{
+ switch(kernel_type)
+ {
+ case LINEAR:
+ kernel_function = &Kernel::kernel_linear;
+ break;
+ case POLY:
+ kernel_function = &Kernel::kernel_poly;
+ break;
+ case RBF:
+ kernel_function = &Kernel::kernel_rbf;
+ break;
+ case SIGMOID:
+ kernel_function = &Kernel::kernel_sigmoid;
+ break;
+ case PRECOMPUTED:
+ kernel_function = &Kernel::kernel_precomputed;
+ break;
+ }
+
+ clone(x,x_,l);
+
+ if(kernel_type == RBF)
+ {
+ x_square = new double[l];
+ for(int i=0;i<l;i++)
+ x_square[i] = dot(x[i],x[i]);
+ }
+ else
+ x_square = 0;
+}
+
+Kernel::~Kernel()
+{
+ delete[] x;
+ delete[] x_square;
+}
+
+double Kernel::dot(const svm_node *px, const svm_node *py)
+{
+ double sum = 0;
+ while(px->index != -1 && py->index != -1)
+ {
+ if(px->index == py->index)
+ {
+ sum += px->value * py->value;
+ ++px;
+ ++py;
+ }
+ else
+ {
+ if(px->index > py->index)
+ ++py;
+ else
+ ++px;
+ }
+ }
+ return sum;
+}
+
+double Kernel::k_function(const svm_node *x, const svm_node *y,
+ const svm_parameter& param)
+{
+ switch(param.kernel_type)
+ {
+ case LINEAR:
+ return dot(x,y);
+ case POLY:
+ return powi(param.gamma*dot(x,y)+param.coef0,param.degree);
+ case RBF:
+ {
+ double sum = 0;
+ while(x->index != -1 && y->index !=-1)
+ {
+ if(x->index == y->index)
+ {
+ double d = x->value - y->value;
+ sum += d*d;
+ ++x;
+ ++y;
+ }
+ else
+ {
+ if(x->index > y->index)
+ {
+ sum += y->value * y->value;
+ ++y;
+ }
+ else
+ {
+ sum += x->value * x->value;
+ ++x;
+ }
+ }
+ }
+
+ while(x->index != -1)
+ {
+ sum += x->value * x->value;
+ ++x;
+ }
+
+ while(y->index != -1)
+ {
+ sum += y->value * y->value;
+ ++y;
+ }
+
+ return exp(-param.gamma*sum);
+ }
+ case SIGMOID:
+ return tanh(param.gamma*dot(x,y)+param.coef0);
+ case PRECOMPUTED: //x: test (validation), y: SV
+ return x[(int)(y->value)].value;
+ default:
+ return 0; // Unreachable
+ }
+}
+
+// An SMO algorithm in Fan et al., JMLR 6(2005), p. 1889--1918
+// Solves:
+//
+// min 0.5(\alpha^T Q \alpha) + p^T \alpha
+//
+// y^T \alpha = \delta
+// y_i = +1 or -1
+// 0 <= alpha_i <= Cp for y_i = 1
+// 0 <= alpha_i <= Cn for y_i = -1
+//
+// Given:
+//
+// Q, p, y, Cp, Cn, and an initial feasible point \alpha
+// l is the size of vectors and matrices
+// eps is the stopping tolerance
+//
+// solution will be put in \alpha, objective value will be put in obj
+//
+class Solver {
+public:
+ Solver() {};
+ virtual ~Solver() {};
+
+ struct SolutionInfo {
+ double obj;
+ double rho;
+ double upper_bound_p;
+ double upper_bound_n;
+ double r; // for Solver_NU
+ };
+
+ void Solve(int l, const QMatrix& Q, const double *p_, const schar *y_,
+ double *alpha_, double Cp, double Cn, double eps,
+ SolutionInfo* si, int shrinking);
+protected:
+ int active_size;
+ schar *y;
+ double *G; // gradient of objective function
+ enum { LOWER_BOUND, UPPER_BOUND, FREE };
+ char *alpha_status; // LOWER_BOUND, UPPER_BOUND, FREE
+ double *alpha;
+ const QMatrix *Q;
+ const double *QD;
+ double eps;
+ double Cp,Cn;
+ double *p;
+ int *active_set;
+ double *G_bar; // gradient, if we treat free variables as 0
+ int l;
+ bool unshrink; // XXX
+
+ double get_C(int i)
+ {
+ return (y[i] > 0)? Cp : Cn;
+ }
+ void update_alpha_status(int i)
+ {
+ if(alpha[i] >= get_C(i))
+ alpha_status[i] = UPPER_BOUND;
+ else if(alpha[i] <= 0)
+ alpha_status[i] = LOWER_BOUND;
+ else alpha_status[i] = FREE;
+ }
+ bool is_upper_bound(int i) { return alpha_status[i] == UPPER_BOUND; }
+ bool is_lower_bound(int i) { return alpha_status[i] == LOWER_BOUND; }
+ bool is_free(int i) { return alpha_status[i] == FREE; }
+ void swap_index(int i, int j);
+ void reconstruct_gradient();
+ virtual int select_working_set(int &i, int &j);
+ virtual double calculate_rho();
+ virtual void do_shrinking();
+private:
+ bool be_shrunk(int i, double Gmax1, double Gmax2);
+};
+
+void Solver::swap_index(int i, int j)
+{
+ Q->swap_index(i,j);
+ swap(y[i],y[j]);
+ swap(G[i],G[j]);
+ swap(alpha_status[i],alpha_status[j]);
+ swap(alpha[i],alpha[j]);
+ swap(p[i],p[j]);
+ swap(active_set[i],active_set[j]);
+ swap(G_bar[i],G_bar[j]);
+}
+
+void Solver::reconstruct_gradient()
+{
+ // reconstruct inactive elements of G from G_bar and free variables
+
+ if(active_size == l) return;
+
+ int i,j;
+ int nr_free = 0;
+
+ for(j=active_size;j<l;j++)
+ G[j] = G_bar[j] + p[j];
+
+ for(j=0;j<active_size;j++)
+ if(is_free(j))
+ nr_free++;
+
+ if(2*nr_free < active_size)
+ info("\nWARNING: using -h 0 may be faster\n");
+
+ if (nr_free*l > 2*active_size*(l-active_size))
+ {
+ for(i=active_size;i<l;i++)
+ {
+ const Qfloat *Q_i = Q->get_Q(i,active_size);
+ for(j=0;j<active_size;j++)
+ if(is_free(j))
+ G[i] += alpha[j] * Q_i[j];
+ }
+ }
+ else
+ {
+ for(i=0;i<active_size;i++)
+ if(is_free(i))
+ {
+ const Qfloat *Q_i = Q->get_Q(i,l);
+ double alpha_i = alpha[i];
+ for(j=active_size;j<l;j++)
+ G[j] += alpha_i * Q_i[j];
+ }
+ }
+}
+
+void Solver::Solve(int l, const QMatrix& Q, const double *p_, const schar *y_,
+ double *alpha_, double Cp, double Cn, double eps,
+ SolutionInfo* si, int shrinking)
+{
+ this->l = l;
+ this->Q = &Q;
+ QD=Q.get_QD();
+ clone(p, p_,l);
+ clone(y, y_,l);
+ clone(alpha,alpha_,l);
+ this->Cp = Cp;
+ this->Cn = Cn;
+ this->eps = eps;
+ unshrink = false;
+
+ // initialize alpha_status
+ {
+ alpha_status = new char[l];
+ for(int i=0;i<l;i++)
+ update_alpha_status(i);
+ }
+
+ // initialize active set (for shrinking)
+ {
+ active_set = new int[l];
+ for(int i=0;i<l;i++)
+ active_set[i] = i;
+ active_size = l;
+ }
+
+ // initialize gradient
+ {
+ G = new double[l];
+ G_bar = new double[l];
+ int i;
+ for(i=0;i<l;i++)
+ {
+ G[i] = p[i];
+ G_bar[i] = 0;
+ }
+ for(i=0;i<l;i++)
+ if(!is_lower_bound(i))
+ {
+ const Qfloat *Q_i = Q.get_Q(i,l);
+ double alpha_i = alpha[i];
+ int j;
+ for(j=0;j<l;j++)
+ G[j] += alpha_i*Q_i[j];
+ if(is_upper_bound(i))
+ for(j=0;j<l;j++)
+ G_bar[j] += get_C(i) * Q_i[j];
+ }
+ }
+
+ // optimization step
+
+ int iter = 0;
+ int max_iter = max(10000000, l>INT_MAX/100 ? INT_MAX : 100*l);
+ int counter = min(l,1000)+1;
+
+ while(iter < max_iter)
+ {
+ // show progress and do shrinking
+
+ if(--counter == 0)
+ {
+ counter = min(l,1000);
+ if(shrinking) do_shrinking();
+ info(".");
+ }
+
+ int i,j;
+ if(select_working_set(i,j)!=0)
+ {
+ // reconstruct the whole gradient
+ reconstruct_gradient();
+ // reset active set size and check
+ active_size = l;
+ info("*");
+ if(select_working_set(i,j)!=0)
+ break;
+ else
+ counter = 1; // do shrinking next iteration
+ }
+
+ ++iter;
+
+ // update alpha[i] and alpha[j], handle bounds carefully
+
+ const Qfloat *Q_i = Q.get_Q(i,active_size);
+ const Qfloat *Q_j = Q.get_Q(j,active_size);
+
+ double C_i = get_C(i);
+ double C_j = get_C(j);
+
+ double old_alpha_i = alpha[i];
+ double old_alpha_j = alpha[j];
+
+ if(y[i]!=y[j])
+ {
+ double quad_coef = QD[i]+QD[j]+2*Q_i[j];
+ if (quad_coef <= 0)
+ quad_coef = TAU;
+ double delta = (-G[i]-G[j])/quad_coef;
+ double diff = alpha[i] - alpha[j];
+ alpha[i] += delta;
+ alpha[j] += delta;
+
+ if(diff > 0)
+ {
+ if(alpha[j] < 0)
+ {
+ alpha[j] = 0;
+ alpha[i] = diff;
+ }
+ }
+ else
+ {
+ if(alpha[i] < 0)
+ {
+ alpha[i] = 0;
+ alpha[j] = -diff;
+ }
+ }
+ if(diff > C_i - C_j)
+ {
+ if(alpha[i] > C_i)
+ {
+ alpha[i] = C_i;
+ alpha[j] = C_i - diff;
+ }
+ }
+ else
+ {
+ if(alpha[j] > C_j)
+ {
+ alpha[j] = C_j;
+ alpha[i] = C_j + diff;
+ }
+ }
+ }
+ else
+ {
+ double quad_coef = QD[i]+QD[j]-2*Q_i[j];
+ if (quad_coef <= 0)
+ quad_coef = TAU;
+ double delta = (G[i]-G[j])/quad_coef;
+ double sum = alpha[i] + alpha[j];
+ alpha[i] -= delta;
+ alpha[j] += delta;
+
+ if(sum > C_i)
+ {
+ if(alpha[i] > C_i)
+ {
+ alpha[i] = C_i;
+ alpha[j] = sum - C_i;
+ }
+ }
+ else
+ {
+ if(alpha[j] < 0)
+ {
+ alpha[j] = 0;
+ alpha[i] = sum;
+ }
+ }
+ if(sum > C_j)
+ {
+ if(alpha[j] > C_j)
+ {
+ alpha[j] = C_j;
+ alpha[i] = sum - C_j;
+ }
+ }
+ else
+ {
+ if(alpha[i] < 0)
+ {
+ alpha[i] = 0;
+ alpha[j] = sum;
+ }
+ }
+ }
+
+ // update G
+
+ double delta_alpha_i = alpha[i] - old_alpha_i;
+ double delta_alpha_j = alpha[j] - old_alpha_j;
+
+ for(int k=0;k<active_size;k++)
+ {
+ G[k] += Q_i[k]*delta_alpha_i + Q_j[k]*delta_alpha_j;
+ }
+
+ // update alpha_status and G_bar
+
+ {
+ bool ui = is_upper_bound(i);
+ bool uj = is_upper_bound(j);
+ update_alpha_status(i);
+ update_alpha_status(j);
+ int k;
+ if(ui != is_upper_bound(i))
+ {
+ Q_i = Q.get_Q(i,l);
+ if(ui)
+ for(k=0;k<l;k++)
+ G_bar[k] -= C_i * Q_i[k];
+ else
+ for(k=0;k<l;k++)
+ G_bar[k] += C_i * Q_i[k];
+ }
+
+ if(uj != is_upper_bound(j))
+ {
+ Q_j = Q.get_Q(j,l);
+ if(uj)
+ for(k=0;k<l;k++)
+ G_bar[k] -= C_j * Q_j[k];
+ else
+ for(k=0;k<l;k++)
+ G_bar[k] += C_j * Q_j[k];
+ }
+ }
+ }
+
+ if(iter >= max_iter)
+ {
+ if(active_size < l)
+ {
+ // reconstruct the whole gradient to calculate objective value
+ reconstruct_gradient();
+ active_size = l;
+ info("*");
+ }
+ info("\nWARNING: reaching max number of iterations");
+ }
+
+ // calculate rho
+
+ si->rho = calculate_rho();
+
+ // calculate objective value
+ {
+ double v = 0;
+ int i;
+ for(i=0;i<l;i++)
+ v += alpha[i] * (G[i] + p[i]);
+
+ si->obj = v/2;
+ }
+
+ // put back the solution
+ {
+ for(int i=0;i<l;i++)
+ alpha_[active_set[i]] = alpha[i];
+ }
+
+ // juggle everything back
+ /*{
+ for(int i=0;i<l;i++)
+ while(active_set[i] != i)
+ swap_index(i,active_set[i]);
+ // or Q.swap_index(i,active_set[i]);
+ }*/
+
+ si->upper_bound_p = Cp;
+ si->upper_bound_n = Cn;
+
+ info("\noptimization finished, #iter = %d\n",iter);
+
+ delete[] p;
+ delete[] y;
+ delete[] alpha;
+ delete[] alpha_status;
+ delete[] active_set;
+ delete[] G;
+ delete[] G_bar;
+}
+
+// return 1 if already optimal, return 0 otherwise
+int Solver::select_working_set(int &out_i, int &out_j)
+{
+ // return i,j such that
+ // i: maximizes -y_i * grad(f)_i, i in I_up(\alpha)
+ // j: minimizes the decrease of obj value
+ // (if quadratic coefficeint <= 0, replace it with tau)
+ // -y_j*grad(f)_j < -y_i*grad(f)_i, j in I_low(\alpha)
+
+ double Gmax = -INF;
+ double Gmax2 = -INF;
+ int Gmax_idx = -1;
+ int Gmin_idx = -1;
+ double obj_diff_min = INF;
+
+ for(int t=0;t<active_size;t++)
+ if(y[t]==+1)
+ {
+ if(!is_upper_bound(t))
+ if(-G[t] >= Gmax)
+ {
+ Gmax = -G[t];
+ Gmax_idx = t;
+ }
+ }
+ else
+ {
+ if(!is_lower_bound(t))
+ if(G[t] >= Gmax)
+ {
+ Gmax = G[t];
+ Gmax_idx = t;
+ }
+ }
+
+ int i = Gmax_idx;
+ const Qfloat *Q_i = NULL;
+ if(i != -1) // NULL Q_i not accessed: Gmax=-INF if i=-1
+ Q_i = Q->get_Q(i,active_size);
+
+ for(int j=0;j<active_size;j++)
+ {
+ if(y[j]==+1)
+ {
+ if (!is_lower_bound(j))
+ {
+ double grad_diff=Gmax+G[j];
+ if (G[j] >= Gmax2)
+ Gmax2 = G[j];
+ if (grad_diff > 0)
+ {
+ double obj_diff;
+ double quad_coef = QD[i]+QD[j]-2.0*y[i]*Q_i[j];
+ if (quad_coef > 0)
+ obj_diff = -(grad_diff*grad_diff)/quad_coef;
+ else
+ obj_diff = -(grad_diff*grad_diff)/TAU;
+
+ if (obj_diff <= obj_diff_min)
+ {
+ Gmin_idx=j;
+ obj_diff_min = obj_diff;
+ }
+ }
+ }
+ }
+ else
+ {
+ if (!is_upper_bound(j))
+ {
+ double grad_diff= Gmax-G[j];
+ if (-G[j] >= Gmax2)
+ Gmax2 = -G[j];
+ if (grad_diff > 0)
+ {
+ double obj_diff;
+ double quad_coef = QD[i]+QD[j]+2.0*y[i]*Q_i[j];
+ if (quad_coef > 0)
+ obj_diff = -(grad_diff*grad_diff)/quad_coef;
+ else
+ obj_diff = -(grad_diff*grad_diff)/TAU;
+
+ if (obj_diff <= obj_diff_min)
+ {
+ Gmin_idx=j;
+ obj_diff_min = obj_diff;
+ }
+ }
+ }
+ }
+ }
+
+ if(Gmax+Gmax2 < eps)
+ return 1;
+
+ out_i = Gmax_idx;
+ out_j = Gmin_idx;
+ return 0;
+}
+
+bool Solver::be_shrunk(int i, double Gmax1, double Gmax2)
+{
+ if(is_upper_bound(i))
+ {
+ if(y[i]==+1)
+ return(-G[i] > Gmax1);
+ else
+ return(-G[i] > Gmax2);
+ }
+ else if(is_lower_bound(i))
+ {
+ if(y[i]==+1)
+ return(G[i] > Gmax2);
+ else
+ return(G[i] > Gmax1);
+ }
+ else
+ return(false);
+}
+
+void Solver::do_shrinking()
+{
+ int i;
+ double Gmax1 = -INF; // max { -y_i * grad(f)_i | i in I_up(\alpha) }
+ double Gmax2 = -INF; // max { y_i * grad(f)_i | i in I_low(\alpha) }
+
+ // find maximal violating pair first
+ for(i=0;i<active_size;i++)
+ {
+ if(y[i]==+1)
+ {
+ if(!is_upper_bound(i))
+ {
+ if(-G[i] >= Gmax1)
+ Gmax1 = -G[i];
+ }
+ if(!is_lower_bound(i))
+ {
+ if(G[i] >= Gmax2)
+ Gmax2 = G[i];
+ }
+ }
+ else
+ {
+ if(!is_upper_bound(i))
+ {
+ if(-G[i] >= Gmax2)
+ Gmax2 = -G[i];
+ }
+ if(!is_lower_bound(i))
+ {
+ if(G[i] >= Gmax1)
+ Gmax1 = G[i];
+ }
+ }
+ }
+
+ if(unshrink == false && Gmax1 + Gmax2 <= eps*10)
+ {
+ unshrink = true;
+ reconstruct_gradient();
+ active_size = l;
+ info("*");
+ }
+
+ for(i=0;i<active_size;i++)
+ if (be_shrunk(i, Gmax1, Gmax2))
+ {
+ active_size--;
+ while (active_size > i)
+ {
+ if (!be_shrunk(active_size, Gmax1, Gmax2))
+ {
+ swap_index(i,active_size);
+ break;
+ }
+ active_size--;
+ }
+ }
+}
+
+double Solver::calculate_rho()
+{
+ double r;
+ int nr_free = 0;
+ double ub = INF, lb = -INF, sum_free = 0;
+ for(int i=0;i<active_size;i++)
+ {
+ double yG = y[i]*G[i];
+
+ if(is_upper_bound(i))
+ {
+ if(y[i]==-1)
+ ub = min(ub,yG);
+ else
+ lb = max(lb,yG);
+ }
+ else if(is_lower_bound(i))
+ {
+ if(y[i]==+1)
+ ub = min(ub,yG);
+ else
+ lb = max(lb,yG);
+ }
+ else
+ {
+ ++nr_free;
+ sum_free += yG;
+ }
+ }
+
+ if(nr_free>0)
+ r = sum_free/nr_free;
+ else
+ r = (ub+lb)/2;
+
+ return r;
+}
+
+//
+// Solver for nu-svm classification and regression
+//
+// additional constraint: e^T \alpha = constant
+//
+class Solver_NU : public Solver
+{
+public:
+ Solver_NU() {}
+ void Solve(int l, const QMatrix& Q, const double *p, const schar *y,
+ double *alpha, double Cp, double Cn, double eps,
+ SolutionInfo* si, int shrinking)
+ {
+ this->si = si;
+ Solver::Solve(l,Q,p,y,alpha,Cp,Cn,eps,si,shrinking);
+ }
+private:
+ SolutionInfo *si;
+ int select_working_set(int &i, int &j);
+ double calculate_rho();
+ bool be_shrunk(int i, double Gmax1, double Gmax2, double Gmax3, double Gmax4);
+ void do_shrinking();
+};
+
+// return 1 if already optimal, return 0 otherwise
+int Solver_NU::select_working_set(int &out_i, int &out_j)
+{
+ // return i,j such that y_i = y_j and
+ // i: maximizes -y_i * grad(f)_i, i in I_up(\alpha)
+ // j: minimizes the decrease of obj value
+ // (if quadratic coefficeint <= 0, replace it with tau)
+ // -y_j*grad(f)_j < -y_i*grad(f)_i, j in I_low(\alpha)
+
+ double Gmaxp = -INF;
+ double Gmaxp2 = -INF;
+ int Gmaxp_idx = -1;
+
+ double Gmaxn = -INF;
+ double Gmaxn2 = -INF;
+ int Gmaxn_idx = -1;
+
+ int Gmin_idx = -1;
+ double obj_diff_min = INF;
+
+ for(int t=0;t<active_size;t++)
+ if(y[t]==+1)
+ {
+ if(!is_upper_bound(t))
+ if(-G[t] >= Gmaxp)
+ {
+ Gmaxp = -G[t];
+ Gmaxp_idx = t;
+ }
+ }
+ else
+ {
+ if(!is_lower_bound(t))
+ if(G[t] >= Gmaxn)
+ {
+ Gmaxn = G[t];
+ Gmaxn_idx = t;
+ }
+ }
+
+ int ip = Gmaxp_idx;
+ int in = Gmaxn_idx;
+ const Qfloat *Q_ip = NULL;
+ const Qfloat *Q_in = NULL;
+ if(ip != -1) // NULL Q_ip not accessed: Gmaxp=-INF if ip=-1
+ Q_ip = Q->get_Q(ip,active_size);
+ if(in != -1)
+ Q_in = Q->get_Q(in,active_size);
+
+ for(int j=0;j<active_size;j++)
+ {
+ if(y[j]==+1)
+ {
+ if (!is_lower_bound(j))
+ {
+ double grad_diff=Gmaxp+G[j];
+ if (G[j] >= Gmaxp2)
+ Gmaxp2 = G[j];
+ if (grad_diff > 0)
+ {
+ double obj_diff;
+ double quad_coef = QD[ip]+QD[j]-2*Q_ip[j];
+ if (quad_coef > 0)
+ obj_diff = -(grad_diff*grad_diff)/quad_coef;
+ else
+ obj_diff = -(grad_diff*grad_diff)/TAU;
+
+ if (obj_diff <= obj_diff_min)
+ {
+ Gmin_idx=j;
+ obj_diff_min = obj_diff;
+ }
+ }
+ }
+ }
+ else
+ {
+ if (!is_upper_bound(j))
+ {
+ double grad_diff=Gmaxn-G[j];
+ if (-G[j] >= Gmaxn2)
+ Gmaxn2 = -G[j];
+ if (grad_diff > 0)
+ {
+ double obj_diff;
+ double quad_coef = QD[in]+QD[j]-2*Q_in[j];
+ if (quad_coef > 0)
+ obj_diff = -(grad_diff*grad_diff)/quad_coef;
+ else
+ obj_diff = -(grad_diff*grad_diff)/TAU;
+
+ if (obj_diff <= obj_diff_min)
+ {
+ Gmin_idx=j;
+ obj_diff_min = obj_diff;
+ }
+ }
+ }
+ }
+ }
+
+ if(max(Gmaxp+Gmaxp2,Gmaxn+Gmaxn2) < eps)
+ return 1;
+
+ if (y[Gmin_idx] == +1)
+ out_i = Gmaxp_idx;
+ else
+ out_i = Gmaxn_idx;
+ out_j = Gmin_idx;
+
+ return 0;
+}
+
+bool Solver_NU::be_shrunk(int i, double Gmax1, double Gmax2, double Gmax3, double Gmax4)
+{
+ if(is_upper_bound(i))
+ {
+ if(y[i]==+1)
+ return(-G[i] > Gmax1);
+ else
+ return(-G[i] > Gmax4);
+ }
+ else if(is_lower_bound(i))
+ {
+ if(y[i]==+1)
+ return(G[i] > Gmax2);
+ else
+ return(G[i] > Gmax3);
+ }
+ else
+ return(false);
+}
+
+void Solver_NU::do_shrinking()
+{
+ double Gmax1 = -INF; // max { -y_i * grad(f)_i | y_i = +1, i in I_up(\alpha) }
+ double Gmax2 = -INF; // max { y_i * grad(f)_i | y_i = +1, i in I_low(\alpha) }
+ double Gmax3 = -INF; // max { -y_i * grad(f)_i | y_i = -1, i in I_up(\alpha) }
+ double Gmax4 = -INF; // max { y_i * grad(f)_i | y_i = -1, i in I_low(\alpha) }
+
+ // find maximal violating pair first
+ int i;
+ for(i=0;i<active_size;i++)
+ {
+ if(!is_upper_bound(i))
+ {
+ if(y[i]==+1)
+ {
+ if(-G[i] > Gmax1) Gmax1 = -G[i];
+ }
+ else if(-G[i] > Gmax4) Gmax4 = -G[i];
+ }
+ if(!is_lower_bound(i))
+ {
+ if(y[i]==+1)
+ {
+ if(G[i] > Gmax2) Gmax2 = G[i];
+ }
+ else if(G[i] > Gmax3) Gmax3 = G[i];
+ }
+ }
+
+ if(unshrink == false && max(Gmax1+Gmax2,Gmax3+Gmax4) <= eps*10)
+ {
+ unshrink = true;
+ reconstruct_gradient();
+ active_size = l;
+ }
+
+ for(i=0;i<active_size;i++)
+ if (be_shrunk(i, Gmax1, Gmax2, Gmax3, Gmax4))
+ {
+ active_size--;
+ while (active_size > i)
+ {
+ if (!be_shrunk(active_size, Gmax1, Gmax2, Gmax3, Gmax4))
+ {
+ swap_index(i,active_size);
+ break;
+ }
+ active_size--;
+ }
+ }
+}
+
+double Solver_NU::calculate_rho()
+{
+ int nr_free1 = 0,nr_free2 = 0;
+ double ub1 = INF, ub2 = INF;
+ double lb1 = -INF, lb2 = -INF;
+ double sum_free1 = 0, sum_free2 = 0;
+
+ for(int i=0;i<active_size;i++)
+ {
+ if(y[i]==+1)
+ {
+ if(is_upper_bound(i))
+ lb1 = max(lb1,G[i]);
+ else if(is_lower_bound(i))
+ ub1 = min(ub1,G[i]);
+ else
+ {
+ ++nr_free1;
+ sum_free1 += G[i];
+ }
+ }
+ else
+ {
+ if(is_upper_bound(i))
+ lb2 = max(lb2,G[i]);
+ else if(is_lower_bound(i))
+ ub2 = min(ub2,G[i]);
+ else
+ {
+ ++nr_free2;
+ sum_free2 += G[i];
+ }
+ }
+ }
+
+ double r1,r2;
+ if(nr_free1 > 0)
+ r1 = sum_free1/nr_free1;
+ else
+ r1 = (ub1+lb1)/2;
+
+ if(nr_free2 > 0)
+ r2 = sum_free2/nr_free2;
+ else
+ r2 = (ub2+lb2)/2;
+
+ si->r = (r1+r2)/2;
+ return (r1-r2)/2;
+}
+
+//
+// Q matrices for various formulations
+//
+class SVC_Q: public Kernel
+{
+public:
+ SVC_Q(const svm_problem& prob, const svm_parameter& param, const schar *y_)
+ :Kernel(prob.l, prob.x, param)
+ {
+ clone(y,y_,prob.l);
+ cache = new Cache(prob.l,(long int)(param.cache_size*(1<<20)));
+ QD = new double[prob.l];
+ for(int i=0;i<prob.l;i++)
+ QD[i] = (this->*kernel_function)(i,i);
+ }
+
+ Qfloat *get_Q(int i, int len) const
+ {
+ Qfloat *data;
+ int start, j;
+ if((start = cache->get_data(i,&data,len)) < len)
+ {
+ for(j=start;j<len;j++)
+ data[j] = (Qfloat)(y[i]*y[j]*(this->*kernel_function)(i,j));
+ }
+ return data;
+ }
+
+ double *get_QD() const
+ {
+ return QD;
+ }
+
+ void swap_index(int i, int j) const
+ {
+ cache->swap_index(i,j);
+ Kernel::swap_index(i,j);
+ swap(y[i],y[j]);
+ swap(QD[i],QD[j]);
+ }
+
+ ~SVC_Q()
+ {
+ delete[] y;
+ delete cache;
+ delete[] QD;
+ }
+private:
+ schar *y;
+ Cache *cache;
+ double *QD;
+};
+
+class ONE_CLASS_Q: public Kernel
+{
+public:
+ ONE_CLASS_Q(const svm_problem& prob, const svm_parameter& param)
+ :Kernel(prob.l, prob.x, param)
+ {
+ cache = new Cache(prob.l,(long int)(param.cache_size*(1<<20)));
+ QD = new double[prob.l];
+ for(int i=0;i<prob.l;i++)
+ QD[i] = (this->*kernel_function)(i,i);
+ }
+
+ Qfloat *get_Q(int i, int len) const
+ {
+ Qfloat *data;
+ int start, j;
+ if((start = cache->get_data(i,&data,len)) < len)
+ {
+ for(j=start;j<len;j++)
+ data[j] = (Qfloat)(this->*kernel_function)(i,j);
+ }
+ return data;
+ }
+
+ double *get_QD() const
+ {
+ return QD;
+ }
+
+ void swap_index(int i, int j) const
+ {
+ cache->swap_index(i,j);
+ Kernel::swap_index(i,j);
+ swap(QD[i],QD[j]);
+ }
+
+ ~ONE_CLASS_Q()
+ {
+ delete cache;
+ delete[] QD;
+ }
+private:
+ Cache *cache;
+ double *QD;
+};
+
+class SVR_Q: public Kernel
+{
+public:
+ SVR_Q(const svm_problem& prob, const svm_parameter& param)
+ :Kernel(prob.l, prob.x, param)
+ {
+ l = prob.l;
+ cache = new Cache(l,(long int)(param.cache_size*(1<<20)));
+ QD = new double[2*l];
+ sign = new schar[2*l];
+ index = new int[2*l];
+ for(int k=0;k<l;k++)
+ {
+ sign[k] = 1;
+ sign[k+l] = -1;
+ index[k] = k;
+ index[k+l] = k;
+ QD[k] = (this->*kernel_function)(k,k);
+ QD[k+l] = QD[k];
+ }
+ buffer[0] = new Qfloat[2*l];
+ buffer[1] = new Qfloat[2*l];
+ next_buffer = 0;
+ }
+
+ void swap_index(int i, int j) const
+ {
+ swap(sign[i],sign[j]);
+ swap(index[i],index[j]);
+ swap(QD[i],QD[j]);
+ }
+
+ Qfloat *get_Q(int i, int len) const
+ {
+ Qfloat *data;
+ int j, real_i = index[i];
+ if(cache->get_data(real_i,&data,l) < l)
+ {
+ for(j=0;j<l;j++)
+ data[j] = (Qfloat)(this->*kernel_function)(real_i,j);
+ }
+
+ // reorder and copy
+ Qfloat *buf = buffer[next_buffer];
+ next_buffer = 1 - next_buffer;
+ schar si = sign[i];
+ for(j=0;j<len;j++)
+ buf[j] = (Qfloat) si * (Qfloat) sign[j] * data[index[j]];
+ return buf;
+ }
+
+ double *get_QD() const
+ {
+ return QD;
+ }
+
+ ~SVR_Q()
+ {
+ delete cache;
+ delete[] sign;
+ delete[] index;
+ delete[] buffer[0];
+ delete[] buffer[1];
+ delete[] QD;
+ }
+private:
+ int l;
+ Cache *cache;
+ schar *sign;
+ int *index;
+ mutable int next_buffer;
+ Qfloat *buffer[2];
+ double *QD;
+};
+
+//
+// construct and solve various formulations
+//
+static void solve_c_svc(
+ const svm_problem *prob, const svm_parameter* param,
+ double *alpha, Solver::SolutionInfo* si, double Cp, double Cn)
+{
+ int l = prob->l;
+ double *minus_ones = new double[l];
+ schar *y = new schar[l];
+
+ int i;
+
+ for(i=0;i<l;i++)
+ {
+ alpha[i] = 0;
+ minus_ones[i] = -1;
+ if(prob->y[i] > 0) y[i] = +1; else y[i] = -1;
+ }
+
+ Solver s;
+ s.Solve(l, SVC_Q(*prob,*param,y), minus_ones, y,
+ alpha, Cp, Cn, param->eps, si, param->shrinking);
+
+ double sum_alpha=0;
+ for(i=0;i<l;i++)
+ sum_alpha += alpha[i];
+
+ if (Cp==Cn)
+ info("nu = %f\n", sum_alpha/(Cp*prob->l));
+
+ for(i=0;i<l;i++)
+ alpha[i] *= y[i];
+
+ delete[] minus_ones;
+ delete[] y;
+}
+
+static void solve_nu_svc(
+ const svm_problem *prob, const svm_parameter *param,
+ double *alpha, Solver::SolutionInfo* si)
+{
+ int i;
+ int l = prob->l;
+ double nu = param->nu;
+
+ schar *y = new schar[l];
+
+ for(i=0;i<l;i++)
+ if(prob->y[i]>0)
+ y[i] = +1;
+ else
+ y[i] = -1;
+
+ double sum_pos = nu*l/2;
+ double sum_neg = nu*l/2;
+
+ for(i=0;i<l;i++)
+ if(y[i] == +1)
+ {
+ alpha[i] = min(1.0,sum_pos);
+ sum_pos -= alpha[i];
+ }
+ else
+ {
+ alpha[i] = min(1.0,sum_neg);
+ sum_neg -= alpha[i];
+ }
+
+ double *zeros = new double[l];
+
+ for(i=0;i<l;i++)
+ zeros[i] = 0;
+
+ Solver_NU s;
+ s.Solve(l, SVC_Q(*prob,*param,y), zeros, y,
+ alpha, 1.0, 1.0, param->eps, si, param->shrinking);
+ double r = si->r;
+
+ info("C = %f\n",1/r);
+
+ for(i=0;i<l;i++)
+ alpha[i] *= y[i]/r;
+
+ si->rho /= r;
+ si->obj /= (r*r);
+ si->upper_bound_p = 1/r;
+ si->upper_bound_n = 1/r;
+
+ delete[] y;
+ delete[] zeros;
+}
+
+static void solve_one_class(
+ const svm_problem *prob, const svm_parameter *param,
+ double *alpha, Solver::SolutionInfo* si)
+{
+ int l = prob->l;
+ double *zeros = new double[l];
+ schar *ones = new schar[l];
+ int i;
+
+ int n = (int)(param->nu*prob->l); // # of alpha's at upper bound
+
+ for(i=0;i<n;i++)
+ alpha[i] = 1;
+ if(n<prob->l)
+ alpha[n] = param->nu * prob->l - n;
+ for(i=n+1;i<l;i++)
+ alpha[i] = 0;
+
+ for(i=0;i<l;i++)
+ {
+ zeros[i] = 0;
+ ones[i] = 1;
+ }
+
+ Solver s;
+ s.Solve(l, ONE_CLASS_Q(*prob,*param), zeros, ones,
+ alpha, 1.0, 1.0, param->eps, si, param->shrinking);
+
+ delete[] zeros;
+ delete[] ones;
+}
+
+static void solve_epsilon_svr(
+ const svm_problem *prob, const svm_parameter *param,
+ double *alpha, Solver::SolutionInfo* si)
+{
+ int l = prob->l;
+ double *alpha2 = new double[2*l];
+ double *linear_term = new double[2*l];
+ schar *y = new schar[2*l];
+ int i;
+
+ for(i=0;i<l;i++)
+ {
+ alpha2[i] = 0;
+ linear_term[i] = param->p - prob->y[i];
+ y[i] = 1;
+
+ alpha2[i+l] = 0;
+ linear_term[i+l] = param->p + prob->y[i];
+ y[i+l] = -1;
+ }
+
+ Solver s;
+ s.Solve(2*l, SVR_Q(*prob,*param), linear_term, y,
+ alpha2, param->C, param->C, param->eps, si, param->shrinking);
+
+ double sum_alpha = 0;
+ for(i=0;i<l;i++)
+ {
+ alpha[i] = alpha2[i] - alpha2[i+l];
+ sum_alpha += fabs(alpha[i]);
+ }
+ info("nu = %f\n",sum_alpha/(param->C*l));
+
+ delete[] alpha2;
+ delete[] linear_term;
+ delete[] y;
+}
+
+static void solve_nu_svr(
+ const svm_problem *prob, const svm_parameter *param,
+ double *alpha, Solver::SolutionInfo* si)
+{
+ int l = prob->l;
+ double C = param->C;
+ double *alpha2 = new double[2*l];
+ double *linear_term = new double[2*l];
+ schar *y = new schar[2*l];
+ int i;
+
+ double sum = C * param->nu * l / 2;
+ for(i=0;i<l;i++)
+ {
+ alpha2[i] = alpha2[i+l] = min(sum,C);
+ sum -= alpha2[i];
+
+ linear_term[i] = - prob->y[i];
+ y[i] = 1;
+
+ linear_term[i+l] = prob->y[i];
+ y[i+l] = -1;
+ }
+
+ Solver_NU s;
+ s.Solve(2*l, SVR_Q(*prob,*param), linear_term, y,
+ alpha2, C, C, param->eps, si, param->shrinking);
+
+ info("epsilon = %f\n",-si->r);
+
+ for(i=0;i<l;i++)
+ alpha[i] = alpha2[i] - alpha2[i+l];
+
+ delete[] alpha2;
+ delete[] linear_term;
+ delete[] y;
+}
+
+//
+// decision_function
+//
+struct decision_function
+{
+ double *alpha;
+ double rho;
+};
+
+static decision_function svm_train_one(
+ const svm_problem *prob, const svm_parameter *param,
+ double Cp, double Cn)
+{
+ double *alpha = Malloc(double,prob->l);
+ Solver::SolutionInfo si;
+ switch(param->svm_type)
+ {
+ case C_SVC:
+ solve_c_svc(prob,param,alpha,&si,Cp,Cn);
+ break;
+ case NU_SVC:
+ solve_nu_svc(prob,param,alpha,&si);
+ break;
+ case ONE_CLASS:
+ solve_one_class(prob,param,alpha,&si);
+ break;
+ case EPSILON_SVR:
+ solve_epsilon_svr(prob,param,alpha,&si);
+ break;
+ case NU_SVR:
+ solve_nu_svr(prob,param,alpha,&si);
+ break;
+ }
+
+ info("obj = %f, rho = %f\n",si.obj,si.rho);
+
+ // output SVs
+
+ int nSV = 0;
+ int nBSV = 0;
+ for(int i=0;i<prob->l;i++)
+ {
+ if(fabs(alpha[i]) > 0)
+ {
+ ++nSV;
+ if(prob->y[i] > 0)
+ {
+ if(fabs(alpha[i]) >= si.upper_bound_p)
+ ++nBSV;
+ }
+ else
+ {
+ if(fabs(alpha[i]) >= si.upper_bound_n)
+ ++nBSV;
+ }
+ }
+ }
+
+ info("nSV = %d, nBSV = %d\n",nSV,nBSV);
+
+ decision_function f;
+ f.alpha = alpha;
+ f.rho = si.rho;
+ return f;
+}
+
+// Platt's binary SVM Probablistic Output: an improvement from Lin et al.
+static void sigmoid_train(
+ int l, const double *dec_values, const double *labels,
+ double& A, double& B)
+{
+ double prior1=0, prior0 = 0;
+ int i;
+
+ for (i=0;i<l;i++)
+ if (labels[i] > 0) prior1+=1;
+ else prior0+=1;
+
+ int max_iter=100; // Maximal number of iterations
+ double min_step=1e-10; // Minimal step taken in line search
+ double sigma=1e-12; // For numerically strict PD of Hessian
+ double eps=1e-5;
+ double hiTarget=(prior1+1.0)/(prior1+2.0);
+ double loTarget=1/(prior0+2.0);
+ double *t=Malloc(double,l);
+ double fApB,p,q,h11,h22,h21,g1,g2,det,dA,dB,gd,stepsize;
+ double newA,newB,newf,d1,d2;
+ int iter;
+
+ // Initial Point and Initial Fun Value
+ A=0.0; B=log((prior0+1.0)/(prior1+1.0));
+ double fval = 0.0;
+
+ for (i=0;i<l;i++)
+ {
+ if (labels[i]>0) t[i]=hiTarget;
+ else t[i]=loTarget;
+ fApB = dec_values[i]*A+B;
+ if (fApB>=0)
+ fval += t[i]*fApB + log(1+exp(-fApB));
+ else
+ fval += (t[i] - 1)*fApB +log(1+exp(fApB));
+ }
+ for (iter=0;iter<max_iter;iter++)
+ {
+ // Update Gradient and Hessian (use H' = H + sigma I)
+ h11=sigma; // numerically ensures strict PD
+ h22=sigma;
+ h21=0.0;g1=0.0;g2=0.0;
+ for (i=0;i<l;i++)
+ {
+ fApB = dec_values[i]*A+B;
+ if (fApB >= 0)
+ {
+ p=exp(-fApB)/(1.0+exp(-fApB));
+ q=1.0/(1.0+exp(-fApB));
+ }
+ else
+ {
+ p=1.0/(1.0+exp(fApB));
+ q=exp(fApB)/(1.0+exp(fApB));
+ }
+ d2=p*q;
+ h11+=dec_values[i]*dec_values[i]*d2;
+ h22+=d2;
+ h21+=dec_values[i]*d2;
+ d1=t[i]-p;
+ g1+=dec_values[i]*d1;
+ g2+=d1;
+ }
+
+ // Stopping Criteria
+ if (fabs(g1)<eps && fabs(g2)<eps)
+ break;
+
+ // Finding Newton direction: -inv(H') * g
+ det=h11*h22-h21*h21;
+ dA=-(h22*g1 - h21 * g2) / det;
+ dB=-(-h21*g1+ h11 * g2) / det;
+ gd=g1*dA+g2*dB;
+
+
+ stepsize = 1; // Line Search
+ while (stepsize >= min_step)
+ {
+ newA = A + stepsize * dA;
+ newB = B + stepsize * dB;
+
+ // New function value
+ newf = 0.0;
+ for (i=0;i<l;i++)
+ {
+ fApB = dec_values[i]*newA+newB;
+ if (fApB >= 0)
+ newf += t[i]*fApB + log(1+exp(-fApB));
+ else
+ newf += (t[i] - 1)*fApB +log(1+exp(fApB));
+ }
+ // Check sufficient decrease
+ if (newf<fval+0.0001*stepsize*gd)
+ {
+ A=newA;B=newB;fval=newf;
+ break;
+ }
+ else
+ stepsize = stepsize / 2.0;
+ }
+
+ if (stepsize < min_step)
+ {
+ info("Line search fails in two-class probability estimates\n");
+ break;
+ }
+ }
+
+ if (iter>=max_iter)
+ info("Reaching maximal iterations in two-class probability estimates\n");
+ free(t);
+}
+
+static double sigmoid_predict(double decision_value, double A, double B)
+{
+ double fApB = decision_value*A+B;
+ // 1-p used later; avoid catastrophic cancellation
+ if (fApB >= 0)
+ return exp(-fApB)/(1.0+exp(-fApB));
+ else
+ return 1.0/(1+exp(fApB)) ;
+}
+
+// Method 2 from the multiclass_prob paper by Wu, Lin, and Weng
+static void multiclass_probability(int k, double **r, double *p)
+{
+ int t,j;
+ int iter = 0, max_iter=max(100,k);
+ double **Q=Malloc(double *,k);
+ double *Qp=Malloc(double,k);
+ double pQp, eps=0.005/k;
+
+ for (t=0;t<k;t++)
+ {
+ p[t]=1.0/k; // Valid if k = 1
+ Q[t]=Malloc(double,k);
+ Q[t][t]=0;
+ for (j=0;j<t;j++)
+ {
+ Q[t][t]+=r[j][t]*r[j][t];
+ Q[t][j]=Q[j][t];
+ }
+ for (j=t+1;j<k;j++)
+ {
+ Q[t][t]+=r[j][t]*r[j][t];
+ Q[t][j]=-r[j][t]*r[t][j];
+ }
+ }
+ for (iter=0;iter<max_iter;iter++)
+ {
+ // stopping condition, recalculate QP,pQP for numerical accuracy
+ pQp=0;
+ for (t=0;t<k;t++)
+ {
+ Qp[t]=0;
+ for (j=0;j<k;j++)
+ Qp[t]+=Q[t][j]*p[j];
+ pQp+=p[t]*Qp[t];
+ }
+ double max_error=0;
+ for (t=0;t<k;t++)
+ {
+ double error=fabs(Qp[t]-pQp);
+ if (error>max_error)
+ max_error=error;
+ }
+ if (max_error<eps) break;
+
+ for (t=0;t<k;t++)
+ {
+ double diff=(-Qp[t]+pQp)/Q[t][t];
+ p[t]+=diff;
+ pQp=(pQp+diff*(diff*Q[t][t]+2*Qp[t]))/(1+diff)/(1+diff);
+ for (j=0;j<k;j++)
+ {
+ Qp[j]=(Qp[j]+diff*Q[t][j])/(1+diff);
+ p[j]/=(1+diff);
+ }
+ }
+ }
+ if (iter>=max_iter)
+ info("Exceeds max_iter in multiclass_prob\n");
+ for(t=0;t<k;t++) free(Q[t]);
+ free(Q);
+ free(Qp);
+}
+
+// Cross-validation decision values for probability estimates
+static void svm_binary_svc_probability(
+ const svm_problem *prob, const svm_parameter *param,
+ double Cp, double Cn, double& probA, double& probB)
+{
+ int i;
+ int nr_fold = 5;
+ int *perm = Malloc(int,prob->l);
+ double *dec_values = Malloc(double,prob->l);
+
+ // random shuffle
+ for(i=0;i<prob->l;i++) perm[i]=i;
+ for(i=0;i<prob->l;i++)
+ {
+ int j = i+rand()%(prob->l-i);
+ swap(perm[i],perm[j]);
+ }
+ for(i=0;i<nr_fold;i++)
+ {
+ int begin = i*prob->l/nr_fold;
+ int end = (i+1)*prob->l/nr_fold;
+ int j,k;
+ struct svm_problem subprob;
+
+ subprob.l = prob->l-(end-begin);
+ subprob.x = Malloc(struct svm_node*,subprob.l);
+ subprob.y = Malloc(double,subprob.l);
+
+ k=0;
+ for(j=0;j<begin;j++)
+ {
+ subprob.x[k] = prob->x[perm[j]];
+ subprob.y[k] = prob->y[perm[j]];
+ ++k;
+ }
+ for(j=end;j<prob->l;j++)
+ {
+ subprob.x[k] = prob->x[perm[j]];
+ subprob.y[k] = prob->y[perm[j]];
+ ++k;
+ }
+ int p_count=0,n_count=0;
+ for(j=0;j<k;j++)
+ if(subprob.y[j]>0)
+ p_count++;
+ else
+ n_count++;
+
+ if(p_count==0 && n_count==0)
+ for(j=begin;j<end;j++)
+ dec_values[perm[j]] = 0;
+ else if(p_count > 0 && n_count == 0)
+ for(j=begin;j<end;j++)
+ dec_values[perm[j]] = 1;
+ else if(p_count == 0 && n_count > 0)
+ for(j=begin;j<end;j++)
+ dec_values[perm[j]] = -1;
+ else
+ {
+ svm_parameter subparam = *param;
+ subparam.probability=0;
+ subparam.C=1.0;
+ subparam.nr_weight=2;
+ subparam.weight_label = Malloc(int,2);
+ subparam.weight = Malloc(double,2);
+ subparam.weight_label[0]=+1;
+ subparam.weight_label[1]=-1;
+ subparam.weight[0]=Cp;
+ subparam.weight[1]=Cn;
+ struct svm_model *submodel = svm_train(&subprob,&subparam);
+ for(j=begin;j<end;j++)
+ {
+ svm_predict_values(submodel,prob->x[perm[j]],&(dec_values[perm[j]]));
+ // ensure +1 -1 order; reason not using CV subroutine
+ dec_values[perm[j]] *= submodel->label[0];
+ }
+ svm_free_and_destroy_model(&submodel);
+ svm_destroy_param(&subparam);
+ }
+ free(subprob.x);
+ free(subprob.y);
+ }
+ sigmoid_train(prob->l,dec_values,prob->y,probA,probB);
+ free(dec_values);
+ free(perm);
+}
+
+// Return parameter of a Laplace distribution
+static double svm_svr_probability(
+ const svm_problem *prob, const svm_parameter *param)
+{
+ int i;
+ int nr_fold = 5;
+ double *ymv = Malloc(double,prob->l);
+ double mae = 0;
+
+ svm_parameter newparam = *param;
+ newparam.probability = 0;
+ svm_cross_validation(prob,&newparam,nr_fold,ymv);
+ for(i=0;i<prob->l;i++)
+ {
+ ymv[i]=prob->y[i]-ymv[i];
+ mae += fabs(ymv[i]);
+ }
+ mae /= prob->l;
+ double std=sqrt(2*mae*mae);
+ int count=0;
+ mae=0;
+ for(i=0;i<prob->l;i++)
+ if (fabs(ymv[i]) > 5*std)
+ count=count+1;
+ else
+ mae+=fabs(ymv[i]);
+ mae /= (prob->l-count);
+ info("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma= %g\n",mae);
+ free(ymv);
+ return mae;
+}
+
+
+// label: label name, start: begin of each class, count: #data of classes, perm: indices to the original data
+// perm, length l, must be allocated before calling this subroutine
+static void svm_group_classes(const svm_problem *prob, int *nr_class_ret, int **label_ret, int **start_ret, int **count_ret, int *perm)
+{
+ int l = prob->l;
+ int max_nr_class = 16;
+ int nr_class = 0;
+ int *label = Malloc(int,max_nr_class);
+ int *count = Malloc(int,max_nr_class);
+ int *data_label = Malloc(int,l);
+ int i;
+
+ for(i=0;i<l;i++)
+ {
+ int this_label = (int)prob->y[i];
+ int j;
+ for(j=0;j<nr_class;j++)
+ {
+ if(this_label == label[j])
+ {
+ ++count[j];
+ break;
+ }
+ }
+ data_label[i] = j;
+ if(j == nr_class)
+ {
+ if(nr_class == max_nr_class)
+ {
+ max_nr_class *= 2;
+ label = (int *)realloc(label,max_nr_class*sizeof(int));
+ count = (int *)realloc(count,max_nr_class*sizeof(int));
+ }
+ label[nr_class] = this_label;
+ count[nr_class] = 1;
+ ++nr_class;
+ }
+ }
+
+ int *start = Malloc(int,nr_class);
+ start[0] = 0;
+ for(i=1;i<nr_class;i++)
+ start[i] = start[i-1]+count[i-1];
+ for(i=0;i<l;i++)
+ {
+ perm[start[data_label[i]]] = i;
+ ++start[data_label[i]];
+ }
+ start[0] = 0;
+ for(i=1;i<nr_class;i++)
+ start[i] = start[i-1]+count[i-1];
+
+ *nr_class_ret = nr_class;
+ *label_ret = label;
+ *start_ret = start;
+ *count_ret = count;
+ free(data_label);
+}
+
+//
+// Interface functions
+//
+svm_model *svm_train(const svm_problem *prob, const svm_parameter *param)
+{
+ svm_model *model = Malloc(svm_model,1);
+ model->param = *param;
+ model->free_sv = 0; // XXX
+
+ if(param->svm_type == ONE_CLASS ||
+ param->svm_type == EPSILON_SVR ||
+ param->svm_type == NU_SVR)
+ {
+ // regression or one-class-svm
+ model->nr_class = 2;
+ model->label = NULL;
+ model->nSV = NULL;
+ model->probA = NULL; model->probB = NULL;
+ model->sv_coef = Malloc(double *,1);
+
+ if(param->probability &&
+ (param->svm_type == EPSILON_SVR ||
+ param->svm_type == NU_SVR))
+ {
+ model->probA = Malloc(double,1);
+ model->probA[0] = svm_svr_probability(prob,param);
+ }
+
+ decision_function f = svm_train_one(prob,param,0,0);
+ model->rho = Malloc(double,1);
+ model->rho[0] = f.rho;
+
+ int nSV = 0;
+ int i;
+ for(i=0;i<prob->l;i++)
+ if(fabs(f.alpha[i]) > 0) ++nSV;
+ model->l = nSV;
+ model->SV = Malloc(svm_node *,nSV);
+ model->sv_coef[0] = Malloc(double,nSV);
+ int j = 0;
+ for(i=0;i<prob->l;i++)
+ if(fabs(f.alpha[i]) > 0)
+ {
+ model->SV[j] = prob->x[i];
+ model->sv_coef[0][j] = f.alpha[i];
+ ++j;
+ }
+
+ free(f.alpha);
+ }
+ else
+ {
+ // classification
+ int l = prob->l;
+ int nr_class;
+ int *label = NULL;
+ int *start = NULL;
+ int *count = NULL;
+ int *perm = Malloc(int,l);
+
+ // group training data of the same class
+ svm_group_classes(prob,&nr_class,&label,&start,&count,perm);
+ if(nr_class == 1)
+ info("WARNING: training data in only one class. See README for details.\n");
+
+ svm_node **x = Malloc(svm_node *,l);
+ int i;
+ for(i=0;i<l;i++)
+ x[i] = prob->x[perm[i]];
+
+ // calculate weighted C
+
+ double *weighted_C = Malloc(double, nr_class);
+ for(i=0;i<nr_class;i++)
+ weighted_C[i] = param->C;
+ for(i=0;i<param->nr_weight;i++)
+ {
+ int j;
+ for(j=0;j<nr_class;j++)
+ if(param->weight_label[i] == label[j])
+ break;
+ if(j == nr_class)
+ fprintf(stderr,"WARNING: class label %d specified in weight is not found\n", param->weight_label[i]);
+ else
+ weighted_C[j] *= param->weight[i];
+ }
+
+ // train k*(k-1)/2 models
+
+ bool *nonzero = Malloc(bool,l);
+ for(i=0;i<l;i++)
+ nonzero[i] = false;
+ decision_function *f = Malloc(decision_function,nr_class*(nr_class-1)/2);
+
+ double *probA=NULL,*probB=NULL;
+ if (param->probability)
+ {
+ probA=Malloc(double,nr_class*(nr_class-1)/2);
+ probB=Malloc(double,nr_class*(nr_class-1)/2);
+ }
+
+ int p = 0;
+ for(i=0;i<nr_class;i++)
+ for(int j=i+1;j<nr_class;j++)
+ {
+ svm_problem sub_prob;
+ int si = start[i], sj = start[j];
+ int ci = count[i], cj = count[j];
+ sub_prob.l = ci+cj;
+ sub_prob.x = Malloc(svm_node *,sub_prob.l);
+ sub_prob.y = Malloc(double,sub_prob.l);
+ int k;
+ for(k=0;k<ci;k++)
+ {
+ sub_prob.x[k] = x[si+k];
+ sub_prob.y[k] = +1;
+ }
+ for(k=0;k<cj;k++)
+ {
+ sub_prob.x[ci+k] = x[sj+k];
+ sub_prob.y[ci+k] = -1;
+ }
+
+ if(param->probability)
+ svm_binary_svc_probability(&sub_prob,param,weighted_C[i],weighted_C[j],probA[p],probB[p]);
+
+ f[p] = svm_train_one(&sub_prob,param,weighted_C[i],weighted_C[j]);
+ for(k=0;k<ci;k++)
+ if(!nonzero[si+k] && fabs(f[p].alpha[k]) > 0)
+ nonzero[si+k] = true;
+ for(k=0;k<cj;k++)
+ if(!nonzero[sj+k] && fabs(f[p].alpha[ci+k]) > 0)
+ nonzero[sj+k] = true;
+ free(sub_prob.x);
+ free(sub_prob.y);
+ ++p;
+ }
+
+ // build output
+
+ model->nr_class = nr_class;
+
+ model->label = Malloc(int,nr_class);
+ for(i=0;i<nr_class;i++)
+ model->label[i] = label[i];
+
+ model->rho = Malloc(double,nr_class*(nr_class-1)/2);
+ for(i=0;i<nr_class*(nr_class-1)/2;i++)
+ model->rho[i] = f[i].rho;
+
+ if(param->probability)
+ {
+ model->probA = Malloc(double,nr_class*(nr_class-1)/2);
+ model->probB = Malloc(double,nr_class*(nr_class-1)/2);
+ for(i=0;i<nr_class*(nr_class-1)/2;i++)
+ {
+ model->probA[i] = probA[i];
+ model->probB[i] = probB[i];
+ }
+ }
+ else
+ {
+ model->probA=NULL;
+ model->probB=NULL;
+ }
+
+ int total_sv = 0;
+ int *nz_count = Malloc(int,nr_class);
+ model->nSV = Malloc(int,nr_class);
+ for(i=0;i<nr_class;i++)
+ {
+ int nSV = 0;
+ for(int j=0;j<count[i];j++)
+ if(nonzero[start[i]+j])
+ {
+ ++nSV;
+ ++total_sv;
+ }
+ model->nSV[i] = nSV;
+ nz_count[i] = nSV;
+ }
+
+ info("Total nSV = %d\n",total_sv);
+
+ model->l = total_sv;
+ model->SV = Malloc(svm_node *,total_sv);
+ p = 0;
+ for(i=0;i<l;i++)
+ if(nonzero[i]) model->SV[p++] = x[i];
+
+ int *nz_start = Malloc(int,nr_class);
+ nz_start[0] = 0;
+ for(i=1;i<nr_class;i++)
+ nz_start[i] = nz_start[i-1]+nz_count[i-1];
+
+ model->sv_coef = Malloc(double *,nr_class-1);
+ for(i=0;i<nr_class-1;i++)
+ model->sv_coef[i] = Malloc(double,total_sv);
+
+ p = 0;
+ for(i=0;i<nr_class;i++)
+ for(int j=i+1;j<nr_class;j++)
+ {
+ // classifier (i,j): coefficients with
+ // i are in sv_coef[j-1][nz_start[i]...],
+ // j are in sv_coef[i][nz_start[j]...]
+
+ int si = start[i];
+ int sj = start[j];
+ int ci = count[i];
+ int cj = count[j];
+
+ int q = nz_start[i];
+ int k;
+ for(k=0;k<ci;k++)
+ if(nonzero[si+k])
+ model->sv_coef[j-1][q++] = f[p].alpha[k];
+ q = nz_start[j];
+ for(k=0;k<cj;k++)
+ if(nonzero[sj+k])
+ model->sv_coef[i][q++] = f[p].alpha[ci+k];
+ ++p;
+ }
+
+ free(label);
+ free(probA);
+ free(probB);
+ free(count);
+ free(perm);
+ free(start);
+ free(x);
+ free(weighted_C);
+ free(nonzero);
+ for(i=0;i<nr_class*(nr_class-1)/2;i++)
+ free(f[i].alpha);
+ free(f);
+ free(nz_count);
+ free(nz_start);
+ }
+ return model;
+}
+
+// Stratified cross validation
+void svm_cross_validation(const svm_problem *prob, const svm_parameter *param, int nr_fold, double *target)
+{
+ int i;
+ int *fold_start = Malloc(int,nr_fold+1);
+ int l = prob->l;
+ int *perm = Malloc(int,l);
+ int nr_class;
+
+ // stratified cv may not give leave-one-out rate
+ // Each class to l folds -> some folds may have zero elements
+ if((param->svm_type == C_SVC ||
+ param->svm_type == NU_SVC) && nr_fold < l)
+ {
+ int *start = NULL;
+ int *label = NULL;
+ int *count = NULL;
+ svm_group_classes(prob,&nr_class,&label,&start,&count,perm);
+
+ // random shuffle and then data grouped by fold using the array perm
+ int *fold_count = Malloc(int,nr_fold);
+ int c;
+ int *index = Malloc(int,l);
+ for(i=0;i<l;i++)
+ index[i]=perm[i];
+ for (c=0; c<nr_class; c++)
+ for(i=0;i<count[c];i++)
+ {
+ int j = i+rand()%(count[c]-i);
+ swap(index[start[c]+j],index[start[c]+i]);
+ }
+ for(i=0;i<nr_fold;i++)
+ {
+ fold_count[i] = 0;
+ for (c=0; c<nr_class;c++)
+ fold_count[i]+=(i+1)*count[c]/nr_fold-i*count[c]/nr_fold;
+ }
+ fold_start[0]=0;
+ for (i=1;i<=nr_fold;i++)
+ fold_start[i] = fold_start[i-1]+fold_count[i-1];
+ for (c=0; c<nr_class;c++)
+ for(i=0;i<nr_fold;i++)
+ {
+ int begin = start[c]+i*count[c]/nr_fold;
+ int end = start[c]+(i+1)*count[c]/nr_fold;
+ for(int j=begin;j<end;j++)
+ {
+ perm[fold_start[i]] = index[j];
+ fold_start[i]++;
+ }
+ }
+ fold_start[0]=0;
+ for (i=1;i<=nr_fold;i++)
+ fold_start[i] = fold_start[i-1]+fold_count[i-1];
+ free(start);
+ free(label);
+ free(count);
+ free(index);
+ free(fold_count);
+ }
+ else
+ {
+ for(i=0;i<l;i++) perm[i]=i;
+ for(i=0;i<l;i++)
+ {
+ int j = i+rand()%(l-i);
+ swap(perm[i],perm[j]);
+ }
+ for(i=0;i<=nr_fold;i++)
+ fold_start[i]=i*l/nr_fold;
+ }
+
+ for(i=0;i<nr_fold;i++)
+ {
+ int begin = fold_start[i];
+ int end = fold_start[i+1];
+ int j,k;
+ struct svm_problem subprob;
+
+ subprob.l = l-(end-begin);
+ subprob.x = Malloc(struct svm_node*,subprob.l);
+ subprob.y = Malloc(double,subprob.l);
+
+ k=0;
+ for(j=0;j<begin;j++)
+ {
+ subprob.x[k] = prob->x[perm[j]];
+ subprob.y[k] = prob->y[perm[j]];
+ ++k;
+ }
+ for(j=end;j<l;j++)
+ {
+ subprob.x[k] = prob->x[perm[j]];
+ subprob.y[k] = prob->y[perm[j]];
+ ++k;
+ }
+ struct svm_model *submodel = svm_train(&subprob,param);
+ if(param->probability &&
+ (param->svm_type == C_SVC || param->svm_type == NU_SVC))
+ {
+ double *prob_estimates=Malloc(double,svm_get_nr_class(submodel));
+ for(j=begin;j<end;j++)
+ target[perm[j]] = svm_predict_probability(submodel,prob->x[perm[j]],prob_estimates);
+ free(prob_estimates);
+ }
+ else
+ for(j=begin;j<end;j++)
+ target[perm[j]] = svm_predict(submodel,prob->x[perm[j]]);
+ svm_free_and_destroy_model(&submodel);
+ free(subprob.x);
+ free(subprob.y);
+ }
+ free(fold_start);
+ free(perm);
+}
+
+
+int svm_get_svm_type(const svm_model *model)
+{
+ return model->param.svm_type;
+}
+
+int svm_get_nr_class(const svm_model *model)
+{
+ return model->nr_class;
+}
+
+void svm_get_labels(const svm_model *model, int* label)
+{
+ if (model->label != NULL)
+ for(int i=0;i<model->nr_class;i++)
+ label[i] = model->label[i];
+}
+
+double svm_get_svr_probability(const svm_model *model)
+{
+ if ((model->param.svm_type == EPSILON_SVR || model->param.svm_type == NU_SVR) &&
+ model->probA!=NULL)
+ return model->probA[0];
+ else
+ {
+ fprintf(stderr,"Model doesn't contain information for SVR probability inference\n");
+ return 0;
+ }
+}
+
+double svm_predict_values(const svm_model *model, const svm_node *x, double* dec_values)
+{
+ int i;
+ if(model->param.svm_type == ONE_CLASS ||
+ model->param.svm_type == EPSILON_SVR ||
+ model->param.svm_type == NU_SVR)
+ {
+ double *sv_coef = model->sv_coef[0];
+ double sum = 0;
+ for(i=0;i<model->l;i++)
+ sum += sv_coef[i] * Kernel::k_function(x,model->SV[i],model->param);
+ sum -= model->rho[0];
+ *dec_values = sum;
+
+ if(model->param.svm_type == ONE_CLASS)
+ return (sum>0)?1:-1;
+ else
+ return sum;
+ }
+ else
+ {
+ int nr_class = model->nr_class;
+ int l = model->l;
+
+ double *kvalue = Malloc(double,l);
+ for(i=0;i<l;i++)
+ kvalue[i] = Kernel::k_function(x,model->SV[i],model->param);
+
+ int *start = Malloc(int,nr_class);
+ start[0] = 0;
+ for(i=1;i<nr_class;i++)
+ start[i] = start[i-1]+model->nSV[i-1];
+
+ int *vote = Malloc(int,nr_class);
+ for(i=0;i<nr_class;i++)
+ vote[i] = 0;
+
+ int p=0;
+ for(i=0;i<nr_class;i++)
+ for(int j=i+1;j<nr_class;j++)
+ {
+ double sum = 0;
+ int si = start[i];
+ int sj = start[j];
+ int ci = model->nSV[i];
+ int cj = model->nSV[j];
+
+ int k;
+ double *coef1 = model->sv_coef[j-1];
+ double *coef2 = model->sv_coef[i];
+ for(k=0;k<ci;k++)
+ sum += coef1[si+k] * kvalue[si+k];
+ for(k=0;k<cj;k++)
+ sum += coef2[sj+k] * kvalue[sj+k];
+ sum -= model->rho[p];
+ dec_values[p] = sum;
+
+ if(dec_values[p] > 0)
+ ++vote[i];
+ else
+ ++vote[j];
+ p++;
+ }
+
+ int vote_max_idx = 0;
+ for(i=1;i<nr_class;i++)
+ if(vote[i] > vote[vote_max_idx])
+ vote_max_idx = i;
+
+ free(kvalue);
+ free(start);
+ free(vote);
+ return model->label[vote_max_idx];
+ }
+}
+
+double svm_predict(const svm_model *model, const svm_node *x)
+{
+ int nr_class = model->nr_class;
+ double *dec_values;
+ if(model->param.svm_type == ONE_CLASS ||
+ model->param.svm_type == EPSILON_SVR ||
+ model->param.svm_type == NU_SVR)
+ dec_values = Malloc(double, 1);
+ else
+ dec_values = Malloc(double, nr_class*(nr_class-1)/2);
+ double pred_result = svm_predict_values(model, x, dec_values);
+ free(dec_values);
+ return pred_result;
+}
+
+double svm_predict_probability(
+ const svm_model *model, const svm_node *x, double *prob_estimates)
+{
+ if ((model->param.svm_type == C_SVC || model->param.svm_type == NU_SVC) &&
+ model->probA!=NULL && model->probB!=NULL)
+ {
+ int i;
+ int nr_class = model->nr_class;
+ double *dec_values = Malloc(double, nr_class*(nr_class-1)/2);
+ svm_predict_values(model, x, dec_values);
+
+ double min_prob=1e-7;
+ double **pairwise_prob=Malloc(double *,nr_class);
+ for(i=0;i<nr_class;i++)
+ pairwise_prob[i]=Malloc(double,nr_class);
+ int k=0;
+ for(i=0;i<nr_class;i++)
+ for(int j=i+1;j<nr_class;j++)
+ {
+ pairwise_prob[i][j]=min(max(sigmoid_predict(dec_values[k],model->probA[k],model->probB[k]),min_prob),1-min_prob);
+ pairwise_prob[j][i]=1-pairwise_prob[i][j];
+ k++;
+ }
+ multiclass_probability(nr_class,pairwise_prob,prob_estimates);
+
+ int prob_max_idx = 0;
+ for(i=1;i<nr_class;i++)
+ if(prob_estimates[i] > prob_estimates[prob_max_idx])
+ prob_max_idx = i;
+ for(i=0;i<nr_class;i++)
+ free(pairwise_prob[i]);
+ free(dec_values);
+ free(pairwise_prob);
+ return model->label[prob_max_idx];
+ }
+ else
+ return svm_predict(model, x);
+}
+
+static const char *svm_type_table[] =
+{
+ "c_svc","nu_svc","one_class","epsilon_svr","nu_svr",NULL
+};
+
+static const char *kernel_type_table[]=
+{
+ "linear","polynomial","rbf","sigmoid","precomputed",NULL
+};
+
+int svm_save_model(const char *model_file_name, const svm_model *model)
+{
+ FILE *fp = fopen(model_file_name,"w");
+ if(fp==NULL) return -1;
+
+ const svm_parameter& param = model->param;
+
+ fprintf(fp,"svm_type %s\n", svm_type_table[param.svm_type]);
+ fprintf(fp,"kernel_type %s\n", kernel_type_table[param.kernel_type]);
+
+ if(param.kernel_type == POLY)
+ fprintf(fp,"degree %d\n", param.degree);
+
+ if(param.kernel_type == POLY || param.kernel_type == RBF || param.kernel_type == SIGMOID)
+ fprintf(fp,"gamma %g\n", param.gamma);
+
+ if(param.kernel_type == POLY || param.kernel_type == SIGMOID)
+ fprintf(fp,"coef0 %g\n", param.coef0);
+
+ int nr_class = model->nr_class;
+ int l = model->l;
+ fprintf(fp, "nr_class %d\n", nr_class);
+ fprintf(fp, "total_sv %d\n",l);
+
+ {
+ fprintf(fp, "rho");
+ for(int i=0;i<nr_class*(nr_class-1)/2;i++)
+ fprintf(fp," %g",model->rho[i]);
+ fprintf(fp, "\n");
+ }
+
+ if(model->label)
+ {
+ fprintf(fp, "label");
+ for(int i=0;i<nr_class;i++)
+ fprintf(fp," %d",model->label[i]);
+ fprintf(fp, "\n");
+ }
+
+ if(model->probA) // regression has probA only
+ {
+ fprintf(fp, "probA");
+ for(int i=0;i<nr_class*(nr_class-1)/2;i++)
+ fprintf(fp," %g",model->probA[i]);
+ fprintf(fp, "\n");
+ }
+ if(model->probB)
+ {
+ fprintf(fp, "probB");
+ for(int i=0;i<nr_class*(nr_class-1)/2;i++)
+ fprintf(fp," %g",model->probB[i]);
+ fprintf(fp, "\n");
+ }
+
+ if(model->nSV)
+ {
+ fprintf(fp, "nr_sv");
+ for(int i=0;i<nr_class;i++)
+ fprintf(fp," %d",model->nSV[i]);
+ fprintf(fp, "\n");
+ }
+
+ fprintf(fp, "SV\n");
+ const double * const *sv_coef = model->sv_coef;
+ const svm_node * const *SV = model->SV;
+
+ for(int i=0;i<l;i++)
+ {
+ for(int j=0;j<nr_class-1;j++)
+ fprintf(fp, "%.16g ",sv_coef[j][i]);
+
+ const svm_node *p = SV[i];
+
+ if(param.kernel_type == PRECOMPUTED)
+ fprintf(fp,"0:%d ",(int)(p->value));
+ else
+ while(p->index != -1)
+ {
+ fprintf(fp,"%d:%.8g ",p->index,p->value);
+ p++;
+ }
+ fprintf(fp, "\n");
+ }
+ if (ferror(fp) != 0 || fclose(fp) != 0) return -1;
+ else return 0;
+}
+
+static char *line = NULL;
+static int max_line_len;
+
+static char* readline(FILE *input)
+{
+ int len;
+
+ if(fgets(line,max_line_len,input) == NULL)
+ return NULL;
+
+ while(strrchr(line,'\n') == NULL)
+ {
+ max_line_len *= 2;
+ line = (char *) realloc(line,max_line_len);
+ len = (int) strlen(line);
+ if(fgets(line+len,max_line_len-len,input) == NULL)
+ break;
+ }
+ return line;
+}
+
+svm_model *svm_load_model(const char *model_file_name)
+{
+ FILE *fp = fopen(model_file_name,"rb");
+ if(fp==NULL) return NULL;
+
+ // read parameters
+
+ svm_model *model = Malloc(svm_model,1);
+ svm_parameter& param = model->param;
+ model->rho = NULL;
+ model->probA = NULL;
+ model->probB = NULL;
+ model->label = NULL;
+ model->nSV = NULL;
+
+ char cmd[81];
+ while(1)
+ {
+ fscanf(fp,"%80s",cmd);
+
+ if(strcmp(cmd,"svm_type")==0)
+ {
+ fscanf(fp,"%80s",cmd);
+ int i;
+ for(i=0;svm_type_table[i];i++)
+ {
+ if(strcmp(svm_type_table[i],cmd)==0)
+ {
+ param.svm_type=i;
+ break;
+ }
+ }
+ if(svm_type_table[i] == NULL)
+ {
+ fprintf(stderr,"unknown svm type.\n");
+ free(model->rho);
+ free(model->label);
+ free(model->nSV);
+ free(model);
+ return NULL;
+ }
+ }
+ else if(strcmp(cmd,"kernel_type")==0)
+ {
+ fscanf(fp,"%80s",cmd);
+ int i;
+ for(i=0;kernel_type_table[i];i++)
+ {
+ if(strcmp(kernel_type_table[i],cmd)==0)
+ {
+ param.kernel_type=i;
+ break;
+ }
+ }
+ if(kernel_type_table[i] == NULL)
+ {
+ fprintf(stderr,"unknown kernel function.\n");
+ free(model->rho);
+ free(model->label);
+ free(model->nSV);
+ free(model);
+ return NULL;
+ }
+ }
+ else if(strcmp(cmd,"degree")==0)
+ fscanf(fp,"%d",¶m.degree);
+ else if(strcmp(cmd,"gamma")==0)
+ fscanf(fp,"%lf",¶m.gamma);
+ else if(strcmp(cmd,"coef0")==0)
+ fscanf(fp,"%lf",¶m.coef0);
+ else if(strcmp(cmd,"nr_class")==0)
+ fscanf(fp,"%d",&model->nr_class);
+ else if(strcmp(cmd,"total_sv")==0)
+ fscanf(fp,"%d",&model->l);
+ else if(strcmp(cmd,"rho")==0)
+ {
+ int n = model->nr_class * (model->nr_class-1)/2;
+ model->rho = Malloc(double,n);
+ for(int i=0;i<n;i++)
+ fscanf(fp,"%lf",&model->rho[i]);
+ }
+ else if(strcmp(cmd,"label")==0)
+ {
+ int n = model->nr_class;
+ model->label = Malloc(int,n);
+ for(int i=0;i<n;i++)
+ fscanf(fp,"%d",&model->label[i]);
+ }
+ else if(strcmp(cmd,"probA")==0)
+ {
+ int n = model->nr_class * (model->nr_class-1)/2;
+ model->probA = Malloc(double,n);
+ for(int i=0;i<n;i++)
+ fscanf(fp,"%lf",&model->probA[i]);
+ }
+ else if(strcmp(cmd,"probB")==0)
+ {
+ int n = model->nr_class * (model->nr_class-1)/2;
+ model->probB = Malloc(double,n);
+ for(int i=0;i<n;i++)
+ fscanf(fp,"%lf",&model->probB[i]);
+ }
+ else if(strcmp(cmd,"nr_sv")==0)
+ {
+ int n = model->nr_class;
+ model->nSV = Malloc(int,n);
+ for(int i=0;i<n;i++)
+ fscanf(fp,"%d",&model->nSV[i]);
+ }
+ else if(strcmp(cmd,"SV")==0)
+ {
+ while(1)
+ {
+ int c = getc(fp);
+ if(c==EOF || c=='\n') break;
+ }
+ break;
+ }
+ else
+ {
+ fprintf(stderr,"unknown text in model file: [%s]\n",cmd);
+ free(model->rho);
+ free(model->label);
+ free(model->nSV);
+ free(model);
+ return NULL;
+ }
+ }
+
+ // read sv_coef and SV
+
+ int elements = 0;
+ long pos = ftell(fp);
+
+ max_line_len = 1024;
+ line = Malloc(char,max_line_len);
+ char *p,*endptr,*idx,*val;
+
+ while(readline(fp)!=NULL)
+ {
+ p = strtok(line,":");
+ while(1)
+ {
+ p = strtok(NULL,":");
+ if(p == NULL)
+ break;
+ ++elements;
+ }
+ }
+ elements += model->l;
+
+ fseek(fp,pos,SEEK_SET);
+
+ int m = model->nr_class - 1;
+ int l = model->l;
+ model->sv_coef = Malloc(double *,m);
+ int i;
+ for(i=0;i<m;i++)
+ model->sv_coef[i] = Malloc(double,l);
+ model->SV = Malloc(svm_node*,l);
+ svm_node *x_space = NULL;
+ if(l>0) x_space = Malloc(svm_node,elements);
+
+ int j=0;
+ for(i=0;i<l;i++)
+ {
+ readline(fp);
+ model->SV[i] = &x_space[j];
+
+ p = strtok(line, " \t");
+ model->sv_coef[0][i] = strtod(p,&endptr);
+ for(int k=1;k<m;k++)
+ {
+ p = strtok(NULL, " \t");
+ model->sv_coef[k][i] = strtod(p,&endptr);
+ }
+
+ while(1)
+ {
+ idx = strtok(NULL, ":");
+ val = strtok(NULL, " \t");
+
+ if(val == NULL)
+ break;
+ x_space[j].index = (int) strtol(idx,&endptr,10);
+ x_space[j].value = strtod(val,&endptr);
+
+ ++j;
+ }
+ x_space[j++].index = -1;
+ }
+ free(line);
+
+ if (ferror(fp) != 0 || fclose(fp) != 0)
+ return NULL;
+
+ model->free_sv = 1; // XXX
+ return model;
+}
+
+void svm_free_model_content(svm_model* model_ptr)
+{
+ if(model_ptr->free_sv && model_ptr->l > 0 && model_ptr->SV != NULL)
+ free((void *)(model_ptr->SV[0]));
+ if(model_ptr->sv_coef)
+ {
+ for(int i=0;i<model_ptr->nr_class-1;i++)
+ free(model_ptr->sv_coef[i]);
+ }
+
+ free(model_ptr->SV);
+ model_ptr->SV = NULL;
+
+ free(model_ptr->sv_coef);
+ model_ptr->sv_coef = NULL;
+
+ free(model_ptr->rho);
+ model_ptr->rho = NULL;
+
+ free(model_ptr->label);
+ model_ptr->label= NULL;
+
+ free(model_ptr->probA);
+ model_ptr->probA = NULL;
+
+ free(model_ptr->probB);
+ model_ptr->probB= NULL;
+
+ free(model_ptr->nSV);
+ model_ptr->nSV = NULL;
+}
+
+void svm_free_and_destroy_model(svm_model** model_ptr_ptr)
+{
+ if(model_ptr_ptr != NULL && *model_ptr_ptr != NULL)
+ {
+ svm_free_model_content(*model_ptr_ptr);
+ free(*model_ptr_ptr);
+ *model_ptr_ptr = NULL;
+ }
+}
+
+void svm_destroy_param(svm_parameter* param)
+{
+ free(param->weight_label);
+ free(param->weight);
+}
+
+const char *svm_check_parameter(const svm_problem *prob, const svm_parameter *param)
+{
+ // svm_type
+
+ int svm_type = param->svm_type;
+ if(svm_type != C_SVC &&
+ svm_type != NU_SVC &&
+ svm_type != ONE_CLASS &&
+ svm_type != EPSILON_SVR &&
+ svm_type != NU_SVR)
+ return "unknown svm type";
+
+ // kernel_type, degree
+
+ int kernel_type = param->kernel_type;
+ if(kernel_type != LINEAR &&
+ kernel_type != POLY &&
+ kernel_type != RBF &&
+ kernel_type != SIGMOID &&
+ kernel_type != PRECOMPUTED)
+ return "unknown kernel type";
+
+ if(param->gamma < 0)
+ return "gamma < 0";
+
+ if(param->degree < 0)
+ return "degree of polynomial kernel < 0";
+
+ // cache_size,eps,C,nu,p,shrinking
+
+ if(param->cache_size <= 0)
+ return "cache_size <= 0";
+
+ if(param->eps <= 0)
+ return "eps <= 0";
+
+ if(svm_type == C_SVC ||
+ svm_type == EPSILON_SVR ||
+ svm_type == NU_SVR)
+ if(param->C <= 0)
+ return "C <= 0";
+
+ if(svm_type == NU_SVC ||
+ svm_type == ONE_CLASS ||
+ svm_type == NU_SVR)
+ if(param->nu <= 0 || param->nu > 1)
+ return "nu <= 0 or nu > 1";
+
+ if(svm_type == EPSILON_SVR)
+ if(param->p < 0)
+ return "p < 0";
+
+ if(param->shrinking != 0 &&
+ param->shrinking != 1)
+ return "shrinking != 0 and shrinking != 1";
+
+ if(param->probability != 0 &&
+ param->probability != 1)
+ return "probability != 0 and probability != 1";
+
+ if(param->probability == 1 &&
+ svm_type == ONE_CLASS)
+ return "one-class SVM probability output not supported yet";
+
+
+ // check whether nu-svc is feasible
+
+ if(svm_type == NU_SVC)
+ {
+ int l = prob->l;
+ int max_nr_class = 16;
+ int nr_class = 0;
+ int *label = Malloc(int,max_nr_class);
+ int *count = Malloc(int,max_nr_class);
+
+ int i;
+ for(i=0;i<l;i++)
+ {
+ int this_label = (int)prob->y[i];
+ int j;
+ for(j=0;j<nr_class;j++)
+ if(this_label == label[j])
+ {
+ ++count[j];
+ break;
+ }
+ if(j == nr_class)
+ {
+ if(nr_class == max_nr_class)
+ {
+ max_nr_class *= 2;
+ label = (int *)realloc(label,max_nr_class*sizeof(int));
+ count = (int *)realloc(count,max_nr_class*sizeof(int));
+ }
+ label[nr_class] = this_label;
+ count[nr_class] = 1;
+ ++nr_class;
+ }
+ }
+
+ for(i=0;i<nr_class;i++)
+ {
+ int n1 = count[i];
+ for(int j=i+1;j<nr_class;j++)
+ {
+ int n2 = count[j];
+ if(param->nu*(n1+n2)/2 > min(n1,n2))
+ {
+ free(label);
+ free(count);
+ return "specified nu is infeasible";
+ }
+ }
+ }
+ free(label);
+ free(count);
+ }
+
+ return NULL;
+}
+
+int svm_check_probability_model(const svm_model *model)
+{
+ return ((model->param.svm_type == C_SVC || model->param.svm_type == NU_SVC) &&
+ model->probA!=NULL && model->probB!=NULL) ||
+ ((model->param.svm_type == EPSILON_SVR || model->param.svm_type == NU_SVR) &&
+ model->probA!=NULL);
+}
+
+void svm_set_print_string_function(void (*print_func)(const char *))
+{
+ if(print_func == NULL)
+ svm_print_string = &print_string_stdout;
+ else
+ svm_print_string = print_func;
+}
diff --git a/src/modules/imagery/imagery_svm/svm.h b/src/modules/imagery/imagery_svm/svm.h
new file mode 100644
index 0000000..dbc5e08
--- /dev/null
+++ b/src/modules/imagery/imagery_svm/svm.h
@@ -0,0 +1,101 @@
+#ifndef _LIBSVM_H
+#define _LIBSVM_H
+
+#define LIBSVM_VERSION 311
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int libsvm_version;
+
+struct svm_node
+{
+ int index;
+ double value;
+};
+
+struct svm_problem
+{
+ int l;
+ double *y;
+ struct svm_node **x;
+};
+
+enum { C_SVC, NU_SVC, ONE_CLASS, EPSILON_SVR, NU_SVR }; /* svm_type */
+enum { LINEAR, POLY, RBF, SIGMOID, PRECOMPUTED }; /* kernel_type */
+
+struct svm_parameter
+{
+ int svm_type;
+ int kernel_type;
+ int degree; /* for poly */
+ double gamma; /* for poly/rbf/sigmoid */
+ double coef0; /* for poly/sigmoid */
+
+ /* these are for training only */
+ double cache_size; /* in MB */
+ double eps; /* stopping criteria */
+ double C; /* for C_SVC, EPSILON_SVR and NU_SVR */
+ int nr_weight; /* for C_SVC */
+ int *weight_label; /* for C_SVC */
+ double* weight; /* for C_SVC */
+ double nu; /* for NU_SVC, ONE_CLASS, and NU_SVR */
+ double p; /* for EPSILON_SVR */
+ int shrinking; /* use the shrinking heuristics */
+ int probability; /* do probability estimates */
+};
+
+//
+// svm_model
+//
+struct svm_model
+{
+ struct svm_parameter param; /* parameter */
+ int nr_class; /* number of classes, = 2 in regression/one class svm */
+ int l; /* total #SV */
+ struct svm_node **SV; /* SVs (SV[l]) */
+ double **sv_coef; /* coefficients for SVs in decision functions (sv_coef[k-1][l]) */
+ double *rho; /* constants in decision functions (rho[k*(k-1)/2]) */
+ double *probA; /* pariwise probability information */
+ double *probB;
+
+ /* for classification only */
+
+ int *label; /* label of each class (label[k]) */
+ int *nSV; /* number of SVs for each class (nSV[k]) */
+ /* nSV[0] + nSV[1] + ... + nSV[k-1] = l */
+ /* XXX */
+ int free_sv; /* 1 if svm_model is created by svm_load_model*/
+ /* 0 if svm_model is created by svm_train */
+};
+
+struct svm_model *svm_train(const struct svm_problem *prob, const struct svm_parameter *param);
+void svm_cross_validation(const struct svm_problem *prob, const struct svm_parameter *param, int nr_fold, double *target);
+
+int svm_save_model(const char *model_file_name, const struct svm_model *model);
+struct svm_model *svm_load_model(const char *model_file_name);
+
+int svm_get_svm_type(const struct svm_model *model);
+int svm_get_nr_class(const struct svm_model *model);
+void svm_get_labels(const struct svm_model *model, int *label);
+double svm_get_svr_probability(const struct svm_model *model);
+
+double svm_predict_values(const struct svm_model *model, const struct svm_node *x, double* dec_values);
+double svm_predict(const struct svm_model *model, const struct svm_node *x);
+double svm_predict_probability(const struct svm_model *model, const struct svm_node *x, double* prob_estimates);
+
+void svm_free_model_content(struct svm_model *model_ptr);
+void svm_free_and_destroy_model(struct svm_model **model_ptr_ptr);
+void svm_destroy_param(struct svm_parameter *param);
+
+const char *svm_check_parameter(const struct svm_problem *prob, const struct svm_parameter *param);
+int svm_check_probability_model(const struct svm_model *model);
+
+void svm_set_print_string_function(void (*print_func)(const char *));
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _LIBSVM_H */
diff --git a/src/modules/io/io_gdal/gdal_import.cpp b/src/modules/io/io_gdal/gdal_import.cpp
index 0755912..a08345f 100644
--- a/src/modules/io/io_gdal/gdal_import.cpp
+++ b/src/modules/io/io_gdal/gdal_import.cpp
@@ -119,14 +119,11 @@ CGDAL_Import::CGDAL_Import(void)
);
//-----------------------------------------------------
- if( SG_UI_Get_Window_Main() )
- {
- Parameters.Add_Value(
- NULL , "SELECT" , _TL("Select from Multiple Bands"),
- _TL(""),
- PARAMETER_TYPE_Bool, true
- );
- }
+ Parameters.Add_Value(
+ NULL , "SELECT" , _TL("Select from Multiple Bands"),
+ _TL(""),
+ PARAMETER_TYPE_Bool, true
+ )->Set_UseInCMD(false);
//-----------------------------------------------------
pNode = Parameters.Add_Value(
diff --git a/src/modules/pointcloud/pointcloud_tools/pc_attribute_calculator.cpp b/src/modules/pointcloud/pointcloud_tools/pc_attribute_calculator.cpp
index d50534f..b384c4a 100644
--- a/src/modules/pointcloud/pointcloud_tools/pc_attribute_calculator.cpp
+++ b/src/modules/pointcloud/pointcloud_tools/pc_attribute_calculator.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: pc_attribute_calculator.cpp 2287 2014-10-15 15:25:59Z reklov_w $
+ * Version $Id: pc_attribute_calculator.cpp 2627 2015-10-01 09:29:25Z reklov_w $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -157,6 +157,16 @@ CPC_Attribute_Calculator::~CPC_Attribute_Calculator(void)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
+bool CPC_Attribute_Calculator::On_Before_Execution(void)
+{
+ if( Parameters("PC_OUT")->asPointCloud() == Parameters("PC_IN")->asPointCloud() )
+ Parameters("PC_OUT")->Set_Value(DATAOBJECT_NOTSET);
+
+ return (true);
+}
+
+
+//---------------------------------------------------------
bool CPC_Attribute_Calculator::On_Execute(void)
{
CSG_PointCloud *pInput, *pResult;
@@ -219,13 +229,14 @@ bool CPC_Attribute_Calculator::On_Execute(void)
}
//-----------------------------------------------------
- CSG_String sDatasetName;
+ CSG_String sName;
+ CSG_MetaData History;
if (!pResult || pResult == pInput)
{
+ sName = pInput->Get_Name();
pResult = SG_Create_PointCloud(pInput);
-
- sDatasetName = pInput->Get_Name();
+ History = pInput->Get_History();
}
else
{
@@ -278,8 +289,10 @@ bool CPC_Attribute_Calculator::On_Execute(void)
if (!Parameters("PC_OUT")->asPointCloud() || Parameters("PC_OUT")->asPointCloud() == pInput)
{
pInput->Assign(pResult);
- pInput->Set_Name(sDatasetName);
- DataObject_Update(pInput);
+ pInput->Get_History() = History;
+ pInput->Set_Name(sName);
+ Parameters("PC_OUT")->Set_Value(pInput);
+
delete(pResult);
}
else
diff --git a/src/modules/pointcloud/pointcloud_tools/pc_attribute_calculator.h b/src/modules/pointcloud/pointcloud_tools/pc_attribute_calculator.h
index 7f9946d..ed15272 100644
--- a/src/modules/pointcloud/pointcloud_tools/pc_attribute_calculator.h
+++ b/src/modules/pointcloud/pointcloud_tools/pc_attribute_calculator.h
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: pc_attribute_calculator.h 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: pc_attribute_calculator.h 2627 2015-10-01 09:29:25Z reklov_w $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -92,6 +92,7 @@ public:
protected:
+ virtual bool On_Before_Execution (void);
virtual bool On_Execute (void);
virtual int On_Parameter_Changed(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
diff --git a/src/modules/pointcloud/pointcloud_tools/pc_drop_attribute.cpp b/src/modules/pointcloud/pointcloud_tools/pc_drop_attribute.cpp
index 998935b..f910aba 100644
--- a/src/modules/pointcloud/pointcloud_tools/pc_drop_attribute.cpp
+++ b/src/modules/pointcloud/pointcloud_tools/pc_drop_attribute.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: pc_drop_attribute.cpp 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: pc_drop_attribute.cpp 2626 2015-10-01 09:06:32Z reklov_w $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -84,36 +84,26 @@ CPC_Drop_Attribute::CPC_Drop_Attribute(void)
"The module can be used to drop attributes from a point cloud. "
"In case the output dataset is not set, the attribute(s) will be dropped "
"from the input dataset, i.e. the input dataset will be overwritten.\n\n"
- "Module usage is different between SAGA GUI and SAGA CMD: With "
- "SAGA GUI you will get prompted to choose the attributes to drop "
- "once you execute the module. With SAGA CMD you have to provide "
- "a string with the -FIELDS parameter containing the field numbers "
- "(separated by semicolon). Field numbers start with 1, e.g. "
- "-FIELDS=\"5;8;9\".\n\n"
));
//-----------------------------------------------------
- Parameters.Add_PointCloud(
+ CSG_Parameter *pNode = Parameters.Add_PointCloud(
NULL , "INPUT" ,_TL("Input"),
- _TL("Point Cloud to drop attribute from."),
+ _TL("Point cloud to drop attribute(s) from."),
PARAMETER_INPUT
);
+ Parameters.Add_Table_Fields(
+ pNode , "FIELDS" , _TL("Attributes"),
+ _TL("The attribute field(s) to drop.")
+ );
+
Parameters.Add_PointCloud(
NULL , "OUTPUT" , _TL("Output"),
- _TL("Point Cloud with attribute dropped."),
+ _TL("Point cloud with attribute(s) dropped."),
PARAMETER_OUTPUT_OPTIONAL
);
-
- if (!SG_UI_Get_Window_Main())
- {
- Parameters.Add_String(
- NULL , "FIELDS" , _TL("Fields"),
- _TL("The numbers (starting from 1) of the fields to drop, separated by semicolon, e.g. \"5;8;9\""),
- SG_T("")
- );
- }
}
@@ -124,14 +114,21 @@ CPC_Drop_Attribute::CPC_Drop_Attribute(void)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
+bool CPC_Drop_Attribute::On_Before_Execution(void)
+{
+ if( Parameters("OUTPUT")->asPointCloud() == Parameters("INPUT")->asPointCloud() )
+ Parameters("OUTPUT")->Set_Value(DATAOBJECT_NOTSET);
+
+ return (true);
+}
+
+
+//---------------------------------------------------------
bool CPC_Drop_Attribute::On_Execute(void)
{
CSG_PointCloud *pInput, *pOutput;
- CSG_String sName;
CSG_Parameters sParms;
-
- CSG_Parameters P;
- CSG_String s;
+ int *Features, nFeatures;
std::set<int> setCols;
std::set<int>::iterator it;
@@ -140,86 +137,40 @@ bool CPC_Drop_Attribute::On_Execute(void)
pOutput = Parameters("OUTPUT")->asPointCloud();
+ //-------------------------------------------------
+ Features = (int *)Parameters("FIELDS")->asPointer();
+ nFeatures = Parameters("FIELDS")->asInt ();
+
+ if( !Features || nFeatures <= 0 )
+ {
+ Error_Set(_TL("You must specify at least one attribute to drop!"));
+
+ return( false );
+ }
+
//-----------------------------------------------------
+ CSG_String sName;
+ CSG_MetaData History;
+
if( !pOutput || pOutput == pInput )
{
sName = pInput->Get_Name();
pOutput = SG_Create_PointCloud(pInput);
+ History = pInput->Get_History();
}
else
{
- sName = CSG_String::Format(SG_T("%s_discardedAttr"), pInput->Get_Name());
+ sName = CSG_String::Format(SG_T("%s_droppedAttr"), pInput->Get_Name());
pOutput->Create(pInput);
}
//-----------------------------------------------------
- if( SG_UI_Get_Window_Main() )
- {
- P.Set_Name(_TL("Check the attributes to drop"));
-
- for(int iAttr=0; iAttr<pInput->Get_Attribute_Count(); iAttr++)
- {
- s.Printf(SG_T("ATTR_%03d"), iAttr);
- P.Add_Value(NULL, s, CSG_String::Format(SG_T("%s"), pInput->Get_Attribute_Name(iAttr)), _TL(""), PARAMETER_TYPE_Bool, false);
- }
+ setCols.clear();
- //-----------------------------------------------------
- if( Dlg_Parameters(&P, _TL("Field Properties")) )
- {
- setCols.clear();
-
- for(int iAttr=0; iAttr<pInput->Get_Attribute_Count(); iAttr++)
- {
- if( P(CSG_String::Format(SG_T("ATTR_%03d" ), iAttr).c_str())->asBool() )
- {
- setCols.insert(iAttr + 3);
- }
- }
- }
- else
- return( false );
- }
- else // CMD
- {
- CSG_String sFields, sPrecision;
- CSG_String token;
- int iValue;
-
-
- sFields = Parameters("FIELDS")->asString();
-
- CSG_String_Tokenizer tkz_fields(sFields, ";", SG_TOKEN_STRTOK);
-
- while( tkz_fields.Has_More_Tokens() )
- {
- token = tkz_fields.Get_Next_Token();
-
- if( token.Length() == 0 )
- break;
-
- if( !token.asInt(iValue) )
- {
- SG_UI_Msg_Add_Error(_TL("Error parsing attribute fields: can't convert to number"));
- return( false );
- }
-
- iValue -= 1;
-
- if( iValue < 3 || iValue > pInput->Get_Field_Count()-1 )
- {
- SG_UI_Msg_Add_Error(_TL("Error parsing attribute fields: field index out of range"));
- return( false );
- }
- else
- setCols.insert(iValue);
- }
- }
-
- if( setCols.size() == 0 )
+ for( int i=0; i<nFeatures; i++ )
{
- SG_UI_Msg_Add_Error(_TL("You must specify at least one attribute to drop!"));
- return( false );
+ setCols.insert(Features[i]);
}
@@ -255,9 +206,10 @@ bool CPC_Drop_Attribute::On_Execute(void)
if (!Parameters("OUTPUT")->asPointCloud() || Parameters("OUTPUT")->asPointCloud() == pInput )
{
pInput->Assign(pOutput);
+ pInput->Get_History() = History;
pInput->Set_Name(sName);
+ Parameters("OUTPUT")->Set_Value(pInput);
- DataObject_Update(pInput);
delete(pOutput);
DataObject_Get_Parameters(pInput, sParms);
diff --git a/src/modules/pointcloud/pointcloud_tools/pc_drop_attribute.h b/src/modules/pointcloud/pointcloud_tools/pc_drop_attribute.h
index 49bd05c..7d2fb9b 100644
--- a/src/modules/pointcloud/pointcloud_tools/pc_drop_attribute.h
+++ b/src/modules/pointcloud/pointcloud_tools/pc_drop_attribute.h
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: pc_drop_attribute.h 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: pc_drop_attribute.h 2626 2015-10-01 09:06:32Z reklov_w $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -91,6 +91,7 @@ public:
protected:
+ virtual bool On_Before_Execution (void);
virtual bool On_Execute (void);
diff --git a/src/modules/pointcloud/pointcloud_tools/pc_merge.cpp b/src/modules/pointcloud/pointcloud_tools/pc_merge.cpp
index 88c6bae..8d2c112 100644
--- a/src/modules/pointcloud/pointcloud_tools/pc_merge.cpp
+++ b/src/modules/pointcloud/pointcloud_tools/pc_merge.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: pc_merge.cpp 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: pc_merge.cpp 2608 2015-09-27 12:54:38Z reklov_w $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -107,6 +107,12 @@ CPC_Merge::CPC_Merge(void)
_TL("Add unique identifier attribute field to output, ID resembles processing order."),
PARAMETER_TYPE_Bool, false
);
+
+ Parameters.Add_Value(
+ Parameters("ADD_IDENTIFIER") , "START_VALUE" , _TL("Start Value"),
+ _TL("The start value to use for the identifier."),
+ PARAMETER_TYPE_Int, 0
+ );
}
@@ -126,6 +132,7 @@ bool CPC_Merge::On_Execute(void)
{
CSG_PointCloud *pMain, *pAdd, *pResult;
bool bID;
+ int iStartValue;
int iAccept = 0;
CSG_Parameter_PointCloud_List *pPointCloudList;
@@ -137,7 +144,7 @@ bool CPC_Merge::On_Execute(void)
pPointCloudList = Parameters("PC_LAYERS")->asPointCloudList();
pResult = Parameters("PC_OUT")->asPointCloud();
bID = Parameters("ADD_IDENTIFIER")->asBool();
-
+ iStartValue = Parameters("START_VALUE")->asInt();
pResult->Create(pMain);
pResult->Set_Name(CSG_String::Format(_TL("%s_merged"), pMain->Get_Name()));
@@ -163,11 +170,12 @@ bool CPC_Merge::On_Execute(void)
}
if( bID )
- pResult->Set_Attribute(iAccept, pMain->Get_Attribute_Count(), 0);
+ pResult->Set_Attribute(iAccept, pMain->Get_Attribute_Count(), iStartValue);
iAccept++;
}
+
//copy additional layer into destination
if( (pPointCloudList = Parameters("PC_LAYERS")->asPointCloudList()) != NULL && pPointCloudList->Get_Count() > 0 )
{
@@ -211,7 +219,9 @@ bool CPC_Merge::On_Execute(void)
}
if( bID )
- pResult->Set_Attribute(iAccept, pMain->Get_Attribute_Count(), iLayer + 1);
+ {
+ pResult->Set_Attribute(iAccept, pMain->Get_Attribute_Count(), iLayer + iStartValue + 1);
+ }
iAccept++;
}
@@ -241,6 +251,18 @@ bool CPC_Merge::On_Execute(void)
}
+//---------------------------------------------------------
+int CPC_Merge::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
+{
+ if( !SG_STR_CMP(pParameter->Get_Identifier(), SG_T("ADD_IDENTIFIER")) )
+ {
+ pParameters->Get_Parameter("START_VALUE")->Set_Enabled(pParameter->asBool());
+ }
+
+ //-----------------------------------------------------
+ return (1);
+}
+
///////////////////////////////////////////////////////////
// //
// //
diff --git a/src/modules/pointcloud/pointcloud_tools/pc_merge.h b/src/modules/pointcloud/pointcloud_tools/pc_merge.h
index dbf5579..49aebbd 100644
--- a/src/modules/pointcloud/pointcloud_tools/pc_merge.h
+++ b/src/modules/pointcloud/pointcloud_tools/pc_merge.h
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: pc_merge.h 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: pc_merge.h 2608 2015-09-27 12:54:38Z reklov_w $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -88,6 +88,7 @@ protected:
virtual bool On_Execute (void);
+ virtual int On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter);
private:
diff --git a/src/modules/shapes/shapes_tools/shapes_split_randomly.cpp b/src/modules/shapes/shapes_tools/shapes_split_randomly.cpp
index 0249a8b..da11160 100644
--- a/src/modules/shapes/shapes_tools/shapes_split_randomly.cpp
+++ b/src/modules/shapes/shapes_tools/shapes_split_randomly.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: shapes_split_randomly.cpp 2298 2014-10-20 09:30:29Z oconrad $
+ * Version $Id: shapes_split_randomly.cpp 2642 2015-10-08 11:57:54Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -75,17 +75,25 @@ CShapes_Split_Randomly::CShapes_Split_Randomly(void)
Set_Author ("O.Conrad (c) 2008");
Set_Description (_TW(
- "Randomly splits one shapes layer into to new shapes layers. "
+ "Randomly splits one layer into to two new layers. "
"Useful to create a control group for model testing. "
+ "Optionally this can be done category-wise if a category "
+ "field is specified. "
));
//-----------------------------------------------------
- Parameters.Add_Shapes(
+ CSG_Parameter *pNode = Parameters.Add_Shapes(
NULL , "SHAPES" , _TL("Shapes"),
_TL(""),
PARAMETER_INPUT
);
+ Parameters.Add_Table_Field(
+ pNode , "FIELD" , _TL("Categories"),
+ _TL(""),
+ true
+ );
+
Parameters.Add_Shapes(
NULL , "A" , _TL("Group A"),
_TL(""),
@@ -114,8 +122,6 @@ CShapes_Split_Randomly::CShapes_Split_Randomly(void)
///////////////////////////////////////////////////////////
// //
-// //
-// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
@@ -126,7 +132,7 @@ bool CShapes_Split_Randomly::On_Execute(void)
if( !pShapes->is_Valid() )
{
- Error_Set(SG_T("invalid input"));
+ Error_Set("invalid input");
return( false );
}
@@ -137,12 +143,61 @@ bool CShapes_Split_Randomly::On_Execute(void)
pSplit[0] = Parameters("A")->asShapes();
pSplit[1] = Parameters("B")->asShapes();
- pSplit[0]->Create(pShapes->Get_Type(), CSG_String::Format(SG_T("%s [%d%%]"), pShapes->Get_Name(), (int)(100.5 - Percent)), pShapes);
- pSplit[1]->Create(pShapes->Get_Type(), CSG_String::Format(SG_T("%s [%d%%]"), pShapes->Get_Name(), (int)( 0.5 + Percent)), pShapes);
+ pSplit[0]->Create(pShapes->Get_Type(), CSG_String::Format("%s [%d%%]", pShapes->Get_Name(), (int)(100.5 - Percent)), pShapes);
+ pSplit[1]->Create(pShapes->Get_Type(), CSG_String::Format("%s [%d%%]", pShapes->Get_Name(), (int)( 0.5 + Percent)), pShapes);
CSG_Random::Initialize(); // initialize with current time
//-----------------------------------------------------
+ int Field = Parameters("FIELD")->asInt();
+
+ if( Field < 0 )
+ {
+ Split(pShapes, pSplit, Percent);
+ }
+ else // stratified
+ {
+ CSG_String Category;
+ CSG_Shapes Shapes(pShapes->Get_Type(), pShapes->Get_Name(), pShapes);
+
+ pShapes->Set_Index(Field, TABLE_INDEX_Ascending);
+
+ for(int i=0; i<pShapes->Get_Count() && Set_Progress(i, pShapes->Get_Count()); i++)
+ {
+ CSG_Shape *pShape = pShapes->Get_Shape_byIndex(i);
+
+ if( Shapes.Get_Count() == 0 )
+ {
+ Category = pShape->asString(Field);
+ }
+ else if( Category.Cmp(pShape->asString(Field)) ) // category changed
+ {
+ Category = pShape->asString(Field);
+
+ Split(&Shapes, pSplit, Percent);
+
+ Shapes.Del_Shapes();
+ }
+
+ Shapes.Add_Shape(pShape);
+ }
+
+ Split(&Shapes, pSplit, Percent); // don't forget to split last category
+ }
+
+ //-----------------------------------------------------
+ return( true );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CShapes_Split_Randomly::Split(CSG_Shapes *pShapes, CSG_Shapes *pSplit[2], double Percent)
+{
+ //-----------------------------------------------------
if( !Parameters("EXACT")->asBool() )
{
for(int i=0; i<pShapes->Get_Count() && Set_Progress(i, pShapes->Get_Count()); i++)
@@ -177,9 +232,6 @@ bool CShapes_Split_Randomly::On_Execute(void)
pSplit[i < n ? 1 : 0]->Add_Shape(pShapes->Get_Shape(Random[i].asInt(0)));
}
}
-
- //-----------------------------------------------------
- return( true );
}
diff --git a/src/modules/shapes/shapes_tools/shapes_split_randomly.h b/src/modules/shapes/shapes_tools/shapes_split_randomly.h
index ece16aa..a66605e 100644
--- a/src/modules/shapes/shapes_tools/shapes_split_randomly.h
+++ b/src/modules/shapes/shapes_tools/shapes_split_randomly.h
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: shapes_split_randomly.h 2108 2014-05-05 09:16:47Z oconrad $
+ * Version $Id: shapes_split_randomly.h 2642 2015-10-08 11:57:54Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -77,12 +77,17 @@ class CShapes_Split_Randomly : public CSG_Module
public:
CShapes_Split_Randomly(void);
- virtual CSG_String Get_MenuPath (void) { return( _TL("A:Shapes|Construction") ); }
+ virtual CSG_String Get_MenuPath (void) { return( _TL("A:Shapes|Construction") ); }
protected:
- virtual bool On_Execute (void);
+ virtual bool On_Execute (void);
+
+
+private:
+
+ void Split (CSG_Shapes *pShapes, CSG_Shapes *pSplit[2], double Percent);
};
diff --git a/src/modules/simulation/sim_fire_spreading/Forecasting.cpp b/src/modules/simulation/sim_fire_spreading/Forecasting.cpp
new file mode 100644
index 0000000..82ed1f9
--- /dev/null
+++ b/src/modules/simulation/sim_fire_spreading/Forecasting.cpp
@@ -0,0 +1,666 @@
+/**********************************************************
+ * Version $Id: Forecasting.cpp 911 2011-02-14 16:38:15Z reklov_w $
+ *********************************************************/
+/*******************************************************************************
+ Forecasting.cpp
+ Copyright (C) Victor Olaya
+
+ 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 Street, 5th Floor, Boston, MA 02110-1301, USA
+*******************************************************************************/
+
+//#include "../../../modules/grid/grid_tools/Grid_Gaps.h"
+
+#include "Forecasting.h"
+
+#include <time.h>
+
+#define MS2FTMIN (60.0 / 0.3048)
+#define FTMIN2MMIN 0.3048
+#define MIN_RATIO_BURNT_AREA 2.
+
+CForecasting::CForecasting(void){
+
+ Set_Name (_TL("Fire Risk Analysis"));
+ Set_Author (SG_T("(c) 2004 Victor Olaya"));
+ Set_Description (_TW(
+ "Fire risk analysis based on the BEHAVE fire modeling system "
+ "supported by the U.S. Forest Service, Fire and Aviation Management. "
+ "Find more information on BEHAVE at the <i>Public Domain Software for the Wildland Fire Community</i> at "
+ "<a target=\"_blank\" href=\"http://fire.org\">http://fire.org</a>\n"
+ "\n"
+ "Reference:\n"
+ "Andrews, P.L. (1986): BEHAVE: Fire Behavior Prediction and Fuel Modeling System - "
+ "Burn Subsystem, Part 1. U.S. Department of Agriculture, Forest Service General, Technical Report INT-194. "
+ ));
+
+ Parameters.Add_Grid(NULL,
+ "DEM",
+ _TL("DEM"),
+ _TL(""),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "FUEL",
+ _TL("Fuel Model"),
+ _TL(""),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "WINDSPD",
+ _TL("Wind Speed"),
+ _TL("Wind Speed (m/s)"),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "WINDDIR",
+ _TL("Wind Direction"),
+ _TL("Wind Direction (degrees clockwise from north)"),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "M1H",
+ _TL("Dead Fuel Moisture 1H"),
+ _TL(""),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "M10H",
+ _TL("Dead Fuel Moisture 10H"),
+ _TL(""),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "M100H",
+ _TL("Dead Fuel Moisture 100H"),
+ _TL(""),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "MHERB",
+ _TL("Herbaceous Fuel Moisture"),
+ _TL(""),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "MWOOD",
+ _TL("Wood Fuel Moisture"),
+ _TL(""),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "VALUE",
+ _TL("Value"),
+ _TL(""),
+ PARAMETER_INPUT_OPTIONAL);
+
+ Parameters.Add_Grid(NULL,
+ "BASEPROB",
+ _TL("Base Probability"),
+ _TL(""),
+ PARAMETER_INPUT_OPTIONAL);
+
+ Parameters.Add_Grid(NULL,
+ "DANGER",
+ _TL("Danger"),
+ _TL(""),
+ PARAMETER_OUTPUT);
+
+ Parameters.Add_Grid(NULL,
+ "COMPPROB",
+ _TL("Compound Probability"),
+ _TL(""),
+ PARAMETER_OUTPUT);
+
+ Parameters.Add_Grid(NULL,
+ "PRIORITY",
+ _TL("Priority Index"),
+ _TL(""),
+ PARAMETER_OUTPUT);
+
+ Parameters.Add_Value(NULL,
+ "MONTECARLO",
+ _TL("Number of Events"),
+ _TL("N\xc3\xbamero of Monte-Carlo events"),
+ PARAMETER_TYPE_Int,
+ 1000,
+ 1.,
+ true);
+
+ Parameters.Add_Value(NULL,
+ "INTERVAL",
+ _TL("Fire Length"),
+ _TL("Fire Length (min)"),
+ PARAMETER_TYPE_Double,
+ 100,
+ 1.,
+ true);
+
+
+}//constructor
+
+CForecasting::~CForecasting(void)
+{
+}//destructor
+
+bool CForecasting::On_Execute(void){
+
+ AssignParameters();
+ CalculateGrids();
+
+ delete m_pSlopeGrid;
+ delete m_pAspectGrid;
+
+ return true;
+
+}//method
+
+bool CForecasting::AssignParameters(){
+
+ int x,y;
+
+ m_pDEM = Parameters("DEM")->asGrid();
+ m_pFuelGrid = Parameters("FUEL")->asGrid();
+ m_pWindDirGrid = Parameters("WINDDIR")->asGrid();
+ m_pWindSpdGrid = Parameters("WINDSPD")->asGrid();
+ m_pM1Grid = Parameters("M1H")->asGrid();
+ m_pM10Grid = Parameters("M10H")->asGrid();
+ m_pM100Grid = Parameters("M100H")->asGrid();
+ m_pMHerbGrid = Parameters("MHERB")->asGrid();
+ m_pMWoodGrid = Parameters("MWOOD")->asGrid();
+ m_pDangerGrid = Parameters("DANGER")->asGrid();
+ m_pValueGrid = Parameters("VALUE")->asGrid();
+ m_pBaseProbabilityGrid = Parameters("BASEPROB")->asGrid();
+ m_pCompoundProbabilityGrid = Parameters("COMPPROB")->asGrid();
+ m_pPriorityIndexGrid = Parameters("PRIORITY")->asGrid();
+ m_iInterval = Parameters("INTERVAL")->asInt();
+ m_iNumEvents = Parameters("MONTECARLO")->asInt();
+
+ /* create a standard fuel model catalog and a flame length table. */
+ m_Catalog = Fire_FuelCatalogCreateStandard("Standard", 13);
+ Fire_FlameLengthTable(m_Catalog, 500, 0.1);
+
+ if (!m_pBaseProbabilityGrid){
+ m_pBaseProbabilityGrid = SG_Create_Grid(m_pDEM, SG_DATATYPE_Double);
+ m_pBaseProbabilityGrid->Assign(1);
+ }//if
+ if (!m_pValueGrid){
+ m_pValueGrid = SG_Create_Grid(m_pDEM, SG_DATATYPE_Double);
+ m_pValueGrid->Assign(1);
+ }//if
+
+ //substitute no-data values
+ for(y=0; y<Get_NY() && Set_Progress(y); y++){
+ for(x=0; x<Get_NX(); x++){
+
+ if (m_pWindSpdGrid->is_NoData(x, y)){
+ m_pWindSpdGrid->Set_Value(x, y, 0.);
+ }//if
+ if (m_pWindDirGrid->is_NoData(x, y)){
+ m_pWindDirGrid->Set_Value(x, y, 0.);
+ }//if
+ if (m_pM1Grid->is_NoData(x, y)){
+ m_pM1Grid->Set_Value(x, y, 0.);
+ }//if
+ if (m_pM10Grid->is_NoData(x, y)){
+ m_pM10Grid->Set_Value(x, y, 0.);
+ }//if
+ if (m_pM100Grid->is_NoData(x, y)){
+ m_pM100Grid->Set_Value(x, y, 0.);
+ }//if
+ if (m_pMHerbGrid->is_NoData(x, y)){
+ m_pMHerbGrid->Set_Value(x, y, 0.);
+ }//if
+ if (m_pMWoodGrid->is_NoData(x, y)){
+ m_pMWoodGrid->Set_Value(x, y, 0.);
+ }//if
+ if (m_pBaseProbabilityGrid->is_NoData(x, y)){
+ m_pBaseProbabilityGrid->Set_Value(x, y, 0.);
+ }//if
+
+ }//for
+ }//for
+
+
+ //-----------------------------------------------------
+ // calculate slope and aspect using CSG_Grid class'
+ // built-in function (after Zevenbergen & Thorne)...
+
+ m_pSlopeGrid = SG_Create_Grid(m_pDEM, SG_DATATYPE_Double);
+ m_pAspectGrid = SG_Create_Grid(m_pDEM, SG_DATATYPE_Double);
+
+ for(y=0; y<Get_NY() && Set_Progress(y); y++)
+ {
+ for(x=0; x<Get_NX(); x++)
+ {
+ double slope, aspect;
+
+ if( m_pDEM->Get_Gradient(x, y, slope, aspect) )
+ {
+ m_pSlopeGrid ->Set_Value(x, y, slope);
+ m_pAspectGrid ->Set_Value(x, y, aspect);
+ }
+ else
+ {
+ m_pSlopeGrid ->Set_NoData(x, y);
+ m_pAspectGrid ->Set_NoData(x, y);
+ }
+ }
+ }
+
+
+ //-----------------------------------------------------
+ m_pTimeGrid = SG_Create_Grid(m_pDEM, SG_DATATYPE_Double);
+
+ m_pTimeGrid->Assign((double)0);
+ m_pDangerGrid->Assign((double)0);
+ m_pCompoundProbabilityGrid->Assign((double)0);
+
+ //m_pPriorityIndexGrid = Get_SafeNew_Grid(m_pDEM, SG_DATATYPE_Double);
+
+ return true;
+
+}//method
+
+
+void CForecasting::CalculateGrids(){
+
+ int x,y;
+ int i;
+ int iRecommendedNumFires;
+ double dDanger;
+ double dTotalBurntArea = 0;
+ CSG_String sMessage;
+
+ m_CentralPoints .Clear();
+ m_AdjPoints .Clear();
+
+ srand((unsigned int)time(NULL));
+
+ Process_Set_Text(_TL("Calculating danger..."));
+ for(i=0; i<m_iNumEvents && Set_Progress(i, m_iNumEvents); i++){
+ x = rand() % (m_pDEM->Get_NX()-1);
+ y = rand() % (m_pDEM->Get_NY()-1);
+ m_CentralPoints.Clear();
+ m_CentralPoints.Add(x,y);
+ m_pTimeGrid->Set_Value(x,y,0.0);
+ dDanger = CalculateFireSpreading();
+ dTotalBurntArea += dDanger;
+ m_pDangerGrid->Set_Value(x, y, dDanger);
+ }//for
+
+ m_CentralPoints .Clear();
+ m_AdjPoints .Clear();
+
+ m_pDangerGrid->Set_NoData_Value(0.0);
+ m_pDangerGrid->Set_Unit(_TL("m2/h"));
+
+ Process_Set_Text(_TL("Closing Gaps..."));
+
+ if( !Gaps_Close(m_pDangerGrid) )
+ {
+ return;
+ }//if
+
+ for (y=0; y<Get_NY(); y++){
+ for (x=0; x<Get_NX(); x++){
+ m_pCompoundProbabilityGrid->Set_Value(x,y,
+ m_pCompoundProbabilityGrid->asFloat(x,y) / (float)m_iNumEvents);
+ m_pPriorityIndexGrid->Set_Value(x, y, m_pCompoundProbabilityGrid->asFloat(x,y)*
+ m_pDangerGrid->asFloat(x,y));
+ }//for
+ }//for
+
+ float dRatio = (float)(dTotalBurntArea / (m_pDEM->Get_Cellsize() * m_pDEM->Get_Cellsize()));
+ if (dRatio < MIN_RATIO_BURNT_AREA){
+ iRecommendedNumFires =(int)((float) m_iNumEvents / dRatio * (float) MIN_RATIO_BURNT_AREA);
+ sMessage.Printf(
+ _TL("** Warning : Number of events might not be representative.\nMinimum number recommended: ")
+ );
+ sMessage += SG_Get_String(iRecommendedNumFires, 0);
+ sMessage += SG_T("\n");
+ Message_Add(sMessage.c_str());
+ }//if
+
+}//method
+
+double CForecasting::CalculateFireSpreading(){
+
+ int x,y;
+ int x2,y2;
+ int n;
+ bool bReturn = false;
+ /* neighbor's address*/ /* N NE E SE S SW W NW */
+ static int nX[8] = { 0, 1, 1, 1, 0, -1, -1, -1};
+ static int nY[8] = { 1, 1, 0, -1, -1, -1, 0, 1};
+ double nDist[8]; /* distance to each neighbor */
+ double nAzm[8]; /* compass azimuth to each neighbor (0=N) */
+ size_t modelNumber; /* fuel model number at current cell */
+ double moisture[6]; /* fuel moisture content at current cell */
+ double dSpreadRate; /* spread rate in direction of neighbor */
+ double dSpreadTime; /* time to spread from cell to neighbor */
+ double dIgnTime; /* time neighbor is ignited by current cell */
+ double dWindSpd;
+ double dBurntValue = 0;
+ double dProbability;
+
+ m_pTimeGrid->Assign(0.0);
+
+ for (n=0; n<8; n++){
+ nDist[n] = sqrt ( nX[n] * m_pDEM->Get_Cellsize() * nX[n] * m_pDEM->Get_Cellsize()
+ + nY[n] * m_pDEM->Get_Cellsize() * nY[n] * m_pDEM->Get_Cellsize() );
+ nAzm[n] = n * 45.;
+ }//for
+
+ x = m_CentralPoints.Get_X(0);
+ y = m_CentralPoints.Get_Y(0);
+ dProbability = (float)(rand()) / (float)(RAND_MAX);
+
+ if (m_pBaseProbabilityGrid->asFloat(x,y) < dProbability){
+ return 0;
+ }//if
+
+ while (m_CentralPoints.Get_Count()!=0){
+
+ for (int iPt=0; iPt<m_CentralPoints.Get_Count();iPt++){
+
+ x = m_CentralPoints.Get_X(iPt);
+ y = m_CentralPoints.Get_Y(iPt);
+
+ if (!m_pDEM->is_NoData(x,y) && !m_pFuelGrid->is_NoData(x,y)){
+
+ modelNumber = (size_t) m_pFuelGrid->asInt(x, y);
+ moisture[0] = m_pM1Grid->asFloat(x, y);
+ moisture[1] = m_pM10Grid->asFloat(x, y);
+ moisture[2] = m_pM100Grid->asFloat(x, y);
+ moisture[3] = m_pM100Grid->asFloat(x, y);
+ moisture[4] = m_pMHerbGrid->asFloat(x, y);;
+ moisture[5] = m_pMWoodGrid->asFloat(x, y);
+ dWindSpd = m_pWindSpdGrid->asFloat(x,y) * MS2FTMIN;
+ Fire_SpreadNoWindNoSlope(m_Catalog, modelNumber, moisture);
+ Fire_SpreadWindSlopeMax(m_Catalog, modelNumber, dWindSpd,
+ m_pWindDirGrid->asFloat(x,y), tan(m_pSlopeGrid->asFloat(x,y)),
+ m_pAspectGrid->asFloat(x,y));
+
+ for (n=0; n<8; n++){
+ x2 = x + nX[n];
+ y2 = y + nY[n];
+ if (m_pTimeGrid->is_InGrid(x2,y2,false)){
+ Fire_SpreadAtAzimuth(m_Catalog, modelNumber, nAzm[n], FIRE_NONE);
+ dSpreadRate = Fuel_SpreadAny(m_Catalog, modelNumber); // in ft/min (awkward...)
+ dSpreadRate *= FTMIN2MMIN; //a bit better...
+ if (dSpreadRate > Smidgen){
+ dSpreadTime = nDist[n] / dSpreadRate;
+ dIgnTime = m_pTimeGrid->asDouble(x,y) + dSpreadTime;
+ if (dIgnTime < m_iInterval){
+ if (m_pTimeGrid->asDouble(x2,y2) == 0.0
+ || m_pTimeGrid->asDouble(x2, y2)>dIgnTime){
+ if (m_pTimeGrid->asDouble(x2, y2)==0.0){
+ dBurntValue += m_pValueGrid->asDouble(x2, y2);
+ m_pCompoundProbabilityGrid->Set_Value(x2,y2,
+ m_pCompoundProbabilityGrid->asFloat(x2,y2) + 1);
+ }//if
+ m_pTimeGrid->Set_Value(x2, y2, dIgnTime);
+ m_AdjPoints.Add(x2,y2);
+ }//if
+ }//if
+ }//if
+ }//if
+ }//for
+ }//if
+ }//for
+
+ m_CentralPoints.Clear();
+ for (int i=0; i<m_AdjPoints.Get_Count(); i++){
+ x= m_AdjPoints.Get_X(i);
+ y = m_AdjPoints.Get_Y(i);
+ m_CentralPoints.Add(x, y);
+ }//for
+ m_AdjPoints.Clear();
+
+ }//while
+
+ return dBurntValue;
+
+}//method
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CForecasting::Gaps_Close(CSG_Grid *pInput)
+{
+ int iStep, iStart, n;
+ double max, Threshold;
+ CSG_Grid *pResult, *pTension_Keep, *pTension_Temp;
+
+ //-----------------------------------------------------
+ pResult = pInput;
+ pInput = SG_Create_Grid(pInput);
+ pInput->Assign(pResult);
+
+ //-----------------------------------------------------
+ Threshold = 0.1;
+
+ n = Get_NX() > Get_NY() ? Get_NX() : Get_NY();
+ iStep = 0;
+ do { iStep++; } while( pow(2.0, iStep + 1) < n );
+ iStart = (int)pow(2.0, iStep);
+
+ pTension_Keep = new CSG_Grid(pResult, SG_DATATYPE_Byte);
+ pTension_Temp = new CSG_Grid(pResult);
+
+ pResult->Assign_NoData();
+
+ for(iStep=iStart; iStep>=1; iStep/=2)
+ {
+ Gaps_Tension_Init(iStep, pTension_Temp, pTension_Keep, pResult, pInput);
+
+ do
+ {
+ max = Gaps_Tension_Step(iStep, pTension_Temp, pTension_Keep, pResult);
+ }
+ while( max > Threshold && Process_Get_Okay(true) );
+ }
+
+ //-----------------------------------------------------
+ delete(pTension_Keep);
+ delete(pTension_Temp);
+ delete(pInput);
+
+ return( true );
+}
+
+//---------------------------------------------------------
+void CForecasting::Gaps_Tension_Init(int iStep, CSG_Grid *pTension_Temp, CSG_Grid *pTension_Keep, CSG_Grid *pResult, CSG_Grid *pInput)
+{
+ int x, y, i, ix, iy, nx, ny, nz;
+ double z;
+
+ //-----------------------------------------------------
+ // 1. Channels...
+
+ pTension_Temp->Assign_NoData();
+ pTension_Keep->Assign();
+
+ for(y=0; y<Get_NY(); y+=iStep)
+ {
+ ny = y + iStep < Get_NY() ? y + iStep : Get_NY();
+
+ for(x=0; x<Get_NX(); x+=iStep)
+ {
+ if( !pInput->is_NoData(x, y) )
+ {
+ pTension_Temp->Set_Value(x, y, pInput->asDouble(x, y) );
+ pTension_Keep->Set_Value(x, y, 1.0);
+ }
+ else
+ {
+ nx = x + iStep < Get_NX() ? x + iStep : Get_NX();
+ nz = 0;
+ z = 0.0;
+
+ for(iy=y; iy<ny; iy++)
+ {
+ for(ix=x; ix<nx; ix++)
+ {
+ if( pInput->is_InGrid(ix, iy) )
+ {
+ z += pInput->asDouble(ix, iy);
+ nz++;
+ }
+ }
+ }
+
+ if( nz > 0 )
+ {
+ pTension_Temp->Set_Value(x, y, z / (double)nz );
+ pTension_Keep->Set_Value(x, y, 1.0);
+ }
+ }
+ }
+ }
+
+ //-----------------------------------------------------
+ // 2. Previous Iteration...
+
+ for(y=0; y<Get_NY(); y+=iStep)
+ {
+ for(x=0; x<Get_NX(); x+=iStep)
+ {
+ if( pTension_Keep->asByte(x, y) == false )
+ {
+ if( !pResult->is_NoData(x, y) )
+ {
+ pTension_Temp->Set_Value(x, y, pResult->asDouble(x, y));
+ }
+ else
+ {
+ nz = 0;
+ z = 0.0;
+
+ for(i=0; i<8; i++)
+ {
+ ix = x + iStep * Get_System()->Get_xTo(i);
+ iy = y + iStep * Get_System()->Get_yTo(i);
+
+ if( pResult->is_InGrid(ix, iy) )
+ {
+ z += pResult->asDouble(ix, iy);
+ nz++;
+ }
+ }
+
+ if( nz > 0.0 )
+ {
+ pTension_Temp->Set_Value(x, y, z / (double)nz);
+ }
+ else
+ {
+ pTension_Temp->Set_Value(x, y, pInput->asDouble(x, y));
+ }
+ }
+ }
+ }
+ }
+
+ //-----------------------------------------------------
+ // 3. ...
+
+ pResult->Assign(pTension_Temp);
+}
+
+//---------------------------------------------------------
+double CForecasting::Gaps_Tension_Step(int iStep, CSG_Grid *pTension_Temp, CSG_Grid *pTension_Keep, CSG_Grid *pResult)
+{
+ int x, y;
+ double d, dMax;
+
+ dMax = 0.0;
+
+ for(y=0; y<Get_NY(); y+=iStep)
+ {
+ for(x=0; x<Get_NX(); x+=iStep)
+ {
+ if( pTension_Keep->asByte(x, y) == false )
+ {
+ d = Gaps_Tension_Change(x, y, iStep, pResult);
+
+ pTension_Temp->Set_Value(x, y, d);
+
+ d = fabs(d - pResult->asDouble(x, y));
+
+ if( d > dMax )
+ {
+ dMax = d;
+ }
+ }
+ }
+ }
+
+ for(y=0; y<Get_NY(); y+=iStep)
+ {
+ for(x=0; x<Get_NX(); x+=iStep)
+ {
+ if( pTension_Keep->asByte(x, y) == false )
+ {
+ pResult->Set_Value(x, y, pTension_Temp->asDouble(x, y));
+ }
+ }
+ }
+
+ return( dMax );
+}
+
+//---------------------------------------------------------
+double CForecasting::Gaps_Tension_Change(int x, int y, int iStep, CSG_Grid *pResult)
+{
+ int i, ix, iy;
+ double n, d, dz;
+
+ for(i=0, d=0.0, n=0.0; i<8; i++)
+ {
+ ix = x + iStep * Get_System()->Get_xTo(i);
+ iy = y + iStep * Get_System()->Get_yTo(i);
+
+ if( pResult->is_InGrid(ix, iy) )
+ {
+ dz = 1.0 / Get_System()->Get_UnitLength(i);
+ d += dz * pResult->asDouble(ix, iy);
+ n += dz;
+ }
+ }
+
+ if( n > 0.0 )
+ {
+ d /= n;
+
+ return( d );
+ }
+
+ return( pResult->asDouble(x, y) );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
diff --git a/src/modules/simulation/sim_fire_spreading/Forecasting.h b/src/modules/simulation/sim_fire_spreading/Forecasting.h
new file mode 100644
index 0000000..728d56a
--- /dev/null
+++ b/src/modules/simulation/sim_fire_spreading/Forecasting.h
@@ -0,0 +1,84 @@
+/**********************************************************
+ * Version $Id: Forecasting.h 911 2011-02-14 16:38:15Z reklov_w $
+ *********************************************************/
+/*******************************************************************************
+ Forecasting.h
+ Copyright (C) Victor Olaya
+
+ 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 Street, 5th Floor, Boston, MA 02110-1301, USA
+*******************************************************************************/
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "MLB_Interface.h"
+#include "fireLib.h"
+
+class CForecasting : public CSG_Module_Grid {
+
+private:
+
+ CSG_Grid *m_pDEM;
+ CSG_Grid *m_pWindSpdGrid; /* ptr to wind speed map (m/s) */
+ CSG_Grid *m_pWindDirGrid; /* ptr to wind direction map (deg from north) */
+ CSG_Grid *m_pM1Grid; /* ptr to 1-hr dead fuel moisture map */
+ CSG_Grid *m_pM10Grid; /* ptr to 10-hr dead fuel moisture map */
+ CSG_Grid *m_pM100Grid; /* ptr to 100-hr dead fuel moisture map */
+ CSG_Grid *m_pMHerbGrid; /* ptr to live herbaceous fuel moisture map */
+ CSG_Grid *m_pMWoodGrid; /* ptr to live stem fuel moisture map */
+ CSG_Grid *m_pFuelGrid; /* ptr to fuel model map */
+ CSG_Grid *m_pValueGrid; /* ptr to cell value map */
+
+ CSG_Grid *m_pDangerGrid; /* ptr to danger map (in burnt m2 / h) */
+ CSG_Grid *m_pBaseProbabilityGrid;
+ CSG_Grid *m_pCompoundProbabilityGrid;
+
+ CSG_Grid *m_pPriorityIndexGrid;
+
+ CSG_Grid *m_pSlopeGrid; /* ptr to slope map (rise/reach) */
+ CSG_Grid *m_pAspectGrid; /* ptr to aspect map (degrees from north) */
+
+ CSG_Grid *m_pTimeGrid;
+
+ FuelCatalogPtr m_Catalog; /* fuel catalog handle */
+
+ CSG_Points_Int m_CentralPoints;
+ CSG_Points_Int m_AdjPoints;
+
+ int m_iInterval;
+ int m_iNumEvents;
+
+ bool AssignParameters();
+ void CalculateGrids();
+ double CalculateFireSpreading();
+
+ bool Gaps_Close (CSG_Grid *pInput);
+ void Gaps_Tension_Init (int iStep, CSG_Grid *pTension_Temp, CSG_Grid *pTension_Keep, CSG_Grid *pResult, CSG_Grid *pInput);
+ double Gaps_Tension_Step (int iStep, CSG_Grid *pTension_Temp, CSG_Grid *pTension_Keep, CSG_Grid *pResult);
+ double Gaps_Tension_Change (int x, int y, int iStep, CSG_Grid *pResult);
+
+
+public:
+
+ CForecasting(void);
+ virtual ~CForecasting(void);
+
+protected:
+
+ virtual bool On_Execute(void);
+
+};
+
diff --git a/src/modules/imagery/imagery_classification/MLB_Interface.cpp b/src/modules/simulation/sim_fire_spreading/MLB_Interface.cpp
similarity index 62%
copy from src/modules/imagery/imagery_classification/MLB_Interface.cpp
copy to src/modules/simulation/sim_fire_spreading/MLB_Interface.cpp
index 8171b8d..142dba6 100644
--- a/src/modules/imagery/imagery_classification/MLB_Interface.cpp
+++ b/src/modules/simulation/sim_fire_spreading/MLB_Interface.cpp
@@ -6,10 +6,10 @@
// //
// SAGA //
// //
-// System for Automated Geoscientific Analyses //
+// System for an Automated Geo-Scientific Analysis //
// //
// Module Library: //
-// imagery_classification //
+// Fire_Spreading //
// //
//-------------------------------------------------------//
// //
@@ -20,8 +20,8 @@
// //
//-------------------------------------------------------//
// //
-// This file is part of 'SAGA - System for Automated //
-// Geoscientific Analyses'. SAGA is free software; you //
+// This file is part of 'SAGA - System for an Automated //
+// Geo-Scientific Analysis'. SAGA 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; version 2 of the License. //
@@ -40,19 +40,13 @@
// //
//-------------------------------------------------------//
// //
-// e-mail: oconrad at saga-gis.org //
+// e-mail: volaya at saga-gis.org //
// //
-// contact: Olaf Conrad //
-// Institute of Geography //
-// University of Goettingen //
-// Goldschmidtstr. 5 //
-// 37077 Goettingen //
-// Germany //
+// contact: Victor Olaya //
+// Spain //
// //
///////////////////////////////////////////////////////////
-//---------------------------------------------------------
-
///////////////////////////////////////////////////////////
// //
@@ -60,67 +54,65 @@
// //
///////////////////////////////////////////////////////////
-//---------------------------------------------------------
-// 1. Include the appropriate SAGA-API header...
-
#include "MLB_Interface.h"
-
-//---------------------------------------------------------
-// 2. Place general module library informations here...
-
CSG_String Get_Info(int i)
{
switch( i )
{
case MLB_INFO_Name: default:
- return( _TL("Classification") );
+ return( _TL("Fire Spreading Analysis") );
case MLB_INFO_Category:
- return( _TL("Imagery") );
-
+ return( _TL("Simulation") );
+
case MLB_INFO_Author:
- return( SG_T("O. Conrad (c) 2002-11") );
+ return( SG_T("Victor Olaya (c) 2004") );
case MLB_INFO_Description:
- return( _TL("Classification tools for grids.") );
+ return( _TW(
+ "Fire spreading analyses based on the BEHAVE fire modeling system "
+ "supported by the U.S. Forest Service, Fire and Aviation Management. "
+ "Find more information on BEHAVE at the <i>Public Domain Software for the Wildland Fire Community</i> at "
+ "<a target=\"_blank\" href=\"http://fire.org\">http://fire.org</a>\n"
+ "\n"
+ "Reference:\n"
+ "Andrews, P.L. (1986): BEHAVE: Fire Behavior Prediction and Fuel Modeling System - "
+ "Burn Subsystem, Part 1. U.S. Department of Agriculture, Forest Service General, Technical Report INT-194. "
+ ));
case MLB_INFO_Version:
return( SG_T("1.0") );
case MLB_INFO_Menu_Path:
- return( _TL("Imagery|Classification") );
+ return( _TL("Simulation|Fire Spreading") );
}
}
-
-//---------------------------------------------------------
-// 3. Include the headers of your modules here...
-
-#include "classify_supervised.h"
-#include "classify_cluster_analysis.h"
-#include "change_detection.h"
-#include "decision_tree.h"
-#include "classify_supervised_polygons.h"
-
-
-//---------------------------------------------------------
-// 4. Allow your modules to be created here...
+#include "Simulate.h"
+#include "Forecasting.h"
CSG_Module * Create_Module(int i)
{
+
+ CSG_Module *pModule;
+
switch( i )
{
- case 0: return( new CGrid_Classify_Supervised );
- case 1: return( new CGrid_Cluster_Analysis );
- case 2: return( new CChange_Detection );
- case 3: return( new CDecision_Tree );
- case 4: return( new CPolygon_Classify_Supervised( true) );
- case 5: return( new CPolygon_Classify_Supervised(false) );
-
- case 6: return( NULL );
- default: return( MLB_INTERFACE_SKIP_MODULE );
+ case 0:
+ pModule = new CForecasting;
+ break;
+
+ case 1:
+ pModule = new CSimulate;
+ break;
+
+ default:
+ pModule = NULL;
+ break;
}
+
+ return( pModule );
}
diff --git a/src/modules/shapes/shapes_tools/shapes_split_randomly.h b/src/modules/simulation/sim_fire_spreading/MLB_Interface.h
similarity index 75%
copy from src/modules/shapes/shapes_tools/shapes_split_randomly.h
copy to src/modules/simulation/sim_fire_spreading/MLB_Interface.h
index ece16aa..f8c09f4 100644
--- a/src/modules/shapes/shapes_tools/shapes_split_randomly.h
+++ b/src/modules/simulation/sim_fire_spreading/MLB_Interface.h
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: shapes_split_randomly.h 2108 2014-05-05 09:16:47Z oconrad $
+ * Version $Id: MLB_Interface.h 1922 2014-01-09 10:28:46Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -9,13 +9,13 @@
// System for Automated Geoscientific Analyses //
// //
// Module Library: //
-// shapes_tools //
+// Terrain_Analysis //
// //
//-------------------------------------------------------//
// //
-// Shapes_Split_Randomly.h //
+// MLB_Interface.h //
// //
-// Copyright (C) 2008 by //
+// Copyright (C) 2003 by //
// Olaf Conrad //
// //
//-------------------------------------------------------//
@@ -40,8 +40,6 @@
// //
//-------------------------------------------------------//
// //
-// e-mail: oconrad at saga-gis.org //
-// //
// contact: Olaf Conrad //
// Institute of Geography //
// University of Goettingen //
@@ -49,49 +47,26 @@
// 37077 Goettingen //
// Germany //
// //
+// e-mail: oconrad at saga-gis.org //
+// //
///////////////////////////////////////////////////////////
-///////////////////////////////////////////////////////////
-// //
-// //
-// //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
-#ifndef HEADER_INCLUDED__Shapes_Split_Randomly_H
-#define HEADER_INCLUDED__Shapes_Split_Randomly_H
-
//---------------------------------------------------------
-#include "MLB_Interface.h"
///////////////////////////////////////////////////////////
// //
-// //
+// Include the SAGA-API here //
// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-class CShapes_Split_Randomly : public CSG_Module
-{
-public:
- CShapes_Split_Randomly(void);
-
- virtual CSG_String Get_MenuPath (void) { return( _TL("A:Shapes|Construction") ); }
-
-
-protected:
-
- virtual bool On_Execute (void);
-
-};
+#ifndef HEADER_INCLUDED__MLB_INTERFACE_H
+#define HEADER_INCLUDED__MLB_INTERFACE_H
+//---------------------------------------------------------
+#include <saga_api/saga_api.h>
-///////////////////////////////////////////////////////////
-// //
-// //
-// //
-///////////////////////////////////////////////////////////
//---------------------------------------------------------
-#endif // #ifndef HEADER_INCLUDED__Shapes_Split_Randomly_H
+#endif // #ifndef HEADER_INCLUDED__MLB_INTERFACE_H
diff --git a/src/modules/simulation/sim_fire_spreading/Makefile.am b/src/modules/simulation/sim_fire_spreading/Makefile.am
new file mode 100644
index 0000000..08acfe5
--- /dev/null
+++ b/src/modules/simulation/sim_fire_spreading/Makefile.am
@@ -0,0 +1,26 @@
+#
+# $Id: Makefile.am 1277 2011-12-22 15:48:59Z reklov_w $
+#
+if DEBUG
+DBGFLAGS = -g -DDEBUG
+endif
+if SAGA_UNICODE
+UC_DEFS = -D_SAGA_UNICODE
+endif
+DEF_SAGA = -D_SAGA_LINUX -D_TYPEDEF_BYTE -D_TYPEDEF_WORD
+CXX_INCS = -I$(top_srcdir)/src/saga_core -I$(top_srcdir)/src/modules/grid/grid_tools
+AM_CXXFLAGS = -fPIC $(CXX_INCS) $(DEF_SAGA) $(UC_DEFS) $(DBGFLAGS) $(GOMPFLAGS)
+AM_LDFLAGS = -fPIC -shared -avoid-version
+pkglib_LTLIBRARIES = libsim_fire_spreading.la
+libsim_fire_spreading_la_SOURCES =\
+fireLib.c\
+Forecasting.cpp\
+MLB_Interface.cpp\
+Simulate.cpp\
+fireLib.h\
+Forecasting.h\
+MLB_Interface.h\
+Simulate.h
+
+libsim_fire_spreading_la_LIBADD = $(top_srcdir)/src/saga_core/saga_api/libsaga_api.la
+
diff --git a/src/modules/climate/climate_tools/Makefile.in b/src/modules/simulation/sim_fire_spreading/Makefile.in
similarity index 87%
copy from src/modules/climate/climate_tools/Makefile.in
copy to src/modules/simulation/sim_fire_spreading/Makefile.in
index 5c278c1..5512c8d 100644
--- a/src/modules/climate/climate_tools/Makefile.in
+++ b/src/modules/simulation/sim_fire_spreading/Makefile.in
@@ -78,7 +78,7 @@ PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = @build@
host_triplet = @host@
-subdir = src/modules/climate/climate_tools
+subdir = src/modules/simulation/sim_fire_spreading
DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
$(top_srcdir)/depcomp
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
@@ -125,11 +125,12 @@ am__uninstall_files_from_dir = { \
}
am__installdirs = "$(DESTDIR)$(pkglibdir)"
LTLIBRARIES = $(pkglib_LTLIBRARIES)
-libclimate_tools_la_DEPENDENCIES = \
+libsim_fire_spreading_la_DEPENDENCIES = \
$(top_srcdir)/src/saga_core/saga_api/libsaga_api.la
-am_libclimate_tools_la_OBJECTS = etp_hargreave.lo \
- grid_levels_interpolation.lo milankovic.lo MLB_Interface.lo
-libclimate_tools_la_OBJECTS = $(am_libclimate_tools_la_OBJECTS)
+am_libsim_fire_spreading_la_OBJECTS = fireLib.lo Forecasting.lo \
+ MLB_Interface.lo Simulate.lo
+libsim_fire_spreading_la_OBJECTS = \
+ $(am_libsim_fire_spreading_la_OBJECTS)
AM_V_lt = $(am__v_lt_ at AM_V@)
am__v_lt_ = $(am__v_lt_ at AM_DEFAULT_V@)
am__v_lt_0 = --silent
@@ -150,24 +151,6 @@ DEFAULT_INCLUDES = -I. at am__isrc@ -I$(top_builddir)
depcomp = $(SHELL) $(top_srcdir)/depcomp
am__depfiles_maybe = depfiles
am__mv = mv -f
-CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
- $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS)
-LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \
- $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \
- $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
- $(AM_CXXFLAGS) $(CXXFLAGS)
-AM_V_CXX = $(am__v_CXX_ at AM_V@)
-am__v_CXX_ = $(am__v_CXX_ at AM_DEFAULT_V@)
-am__v_CXX_0 = @echo " CXX " $@;
-am__v_CXX_1 =
-CXXLD = $(CXX)
-CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \
- $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \
- $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
-AM_V_CXXLD = $(am__v_CXXLD_ at AM_V@)
-am__v_CXXLD_ = $(am__v_CXXLD_ at AM_DEFAULT_V@)
-am__v_CXXLD_0 = @echo " CXXLD " $@;
-am__v_CXXLD_1 =
COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \
$(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS)
LTCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CC $(AM_LIBTOOLFLAGS) \
@@ -186,8 +169,26 @@ AM_V_CCLD = $(am__v_CCLD_ at AM_V@)
am__v_CCLD_ = $(am__v_CCLD_ at AM_DEFAULT_V@)
am__v_CCLD_0 = @echo " CCLD " $@;
am__v_CCLD_1 =
-SOURCES = $(libclimate_tools_la_SOURCES)
-DIST_SOURCES = $(libclimate_tools_la_SOURCES)
+CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
+ $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS)
+LTCXXCOMPILE = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \
+ $(LIBTOOLFLAGS) --mode=compile $(CXX) $(DEFS) \
+ $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) \
+ $(AM_CXXFLAGS) $(CXXFLAGS)
+AM_V_CXX = $(am__v_CXX_ at AM_V@)
+am__v_CXX_ = $(am__v_CXX_ at AM_DEFAULT_V@)
+am__v_CXX_0 = @echo " CXX " $@;
+am__v_CXX_1 =
+CXXLD = $(CXX)
+CXXLINK = $(LIBTOOL) $(AM_V_lt) --tag=CXX $(AM_LIBTOOLFLAGS) \
+ $(LIBTOOLFLAGS) --mode=link $(CXXLD) $(AM_CXXFLAGS) \
+ $(CXXFLAGS) $(AM_LDFLAGS) $(LDFLAGS) -o $@
+AM_V_CXXLD = $(am__v_CXXLD_ at AM_V@)
+am__v_CXXLD_ = $(am__v_CXXLD_ at AM_DEFAULT_V@)
+am__v_CXXLD_0 = @echo " CXXLD " $@;
+am__v_CXXLD_1 =
+SOURCES = $(libsim_fire_spreading_la_SOURCES)
+DIST_SOURCES = $(libsim_fire_spreading_la_SOURCES)
am__can_run_installinfo = \
case $$AM_UPDATE_INFO_DIR in \
n|no|NO) false;; \
@@ -367,25 +368,25 @@ top_srcdir = @top_srcdir@
@DEBUG_TRUE at DBGFLAGS = -g -DDEBUG
@SAGA_UNICODE_TRUE at UC_DEFS = -D_SAGA_UNICODE
DEF_SAGA = -D_SAGA_LINUX -D_TYPEDEF_BYTE -D_TYPEDEF_WORD
-CXX_INCS = -I$(top_srcdir)/src/saga_core
+CXX_INCS = -I$(top_srcdir)/src/saga_core -I$(top_srcdir)/src/modules/grid/grid_tools
AM_CXXFLAGS = -fPIC $(CXX_INCS) $(DEF_SAGA) $(UC_DEFS) $(DBGFLAGS) $(GOMPFLAGS)
-AM_LDFLAGS = -fPIC -shared -avoid-version
-pkglib_LTLIBRARIES = libclimate_tools.la
-libclimate_tools_la_SOURCES = \
-etp_hargreave.cpp\
-grid_levels_interpolation.cpp\
-milankovic.cpp\
+AM_LDFLAGS = -fPIC -shared -avoid-version
+pkglib_LTLIBRARIES = libsim_fire_spreading.la
+libsim_fire_spreading_la_SOURCES = \
+fireLib.c\
+Forecasting.cpp\
MLB_Interface.cpp\
-etp_hargreave.h\
-grid_levels_interpolation.h\
-milankovic.h\
-MLB_Interface.h
+Simulate.cpp\
+fireLib.h\
+Forecasting.h\
+MLB_Interface.h\
+Simulate.h
-libclimate_tools_la_LIBADD = $(top_srcdir)/src/saga_core/saga_api/libsaga_api.la
+libsim_fire_spreading_la_LIBADD = $(top_srcdir)/src/saga_core/saga_api/libsaga_api.la
all: all-am
.SUFFIXES:
-.SUFFIXES: .cpp .lo .o .obj
+.SUFFIXES: .c .cpp .lo .o .obj
$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
@@ -395,9 +396,9 @@ $(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
exit 1;; \
esac; \
done; \
- echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/modules/climate/climate_tools/Makefile'; \
+ echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign src/modules/simulation/sim_fire_spreading/Makefile'; \
$(am__cd) $(top_srcdir) && \
- $(AUTOMAKE) --foreign src/modules/climate/climate_tools/Makefile
+ $(AUTOMAKE) --foreign src/modules/simulation/sim_fire_spreading/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
@@ -452,8 +453,8 @@ clean-pkglibLTLIBRARIES:
rm -f $${locs}; \
}
-libclimate_tools.la: $(libclimate_tools_la_OBJECTS) $(libclimate_tools_la_DEPENDENCIES) $(EXTRA_libclimate_tools_la_DEPENDENCIES)
- $(AM_V_CXXLD)$(CXXLINK) -rpath $(pkglibdir) $(libclimate_tools_la_OBJECTS) $(libclimate_tools_la_LIBADD) $(LIBS)
+libsim_fire_spreading.la: $(libsim_fire_spreading_la_OBJECTS) $(libsim_fire_spreading_la_DEPENDENCIES) $(EXTRA_libsim_fire_spreading_la_DEPENDENCIES)
+ $(AM_V_CXXLD)$(CXXLINK) -rpath $(pkglibdir) $(libsim_fire_spreading_la_OBJECTS) $(libsim_fire_spreading_la_LIBADD) $(LIBS)
mostlyclean-compile:
-rm -f *.$(OBJEXT)
@@ -461,10 +462,34 @@ mostlyclean-compile:
distclean-compile:
-rm -f *.tab.c
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/Forecasting.Plo at am__quote@
@AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/MLB_Interface.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/etp_hargreave.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/grid_levels_interpolation.Plo at am__quote@
- at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/milankovic.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/Simulate.Plo at am__quote@
+ at AMDEP_TRUE@@am__include@ @am__quote at ./$(DEPDIR)/fireLib.Plo at am__quote@
+
+.c.o:
+ at am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
+ at am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
+ at am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(AM_V_CC at am__nodep@)$(COMPILE) -c -o $@ $<
+
+.c.obj:
+ at am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.obj$$||'`;\
+ at am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ `$(CYGPATH_W) '$<'` &&\
+ at am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Po
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(AM_V_CC at am__nodep@)$(COMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
+
+.c.lo:
+ at am__fastdepCC_TRUE@ $(AM_V_CC)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.lo$$||'`;\
+ at am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $$depbase.Tpo -c -o $@ $< &&\
+ at am__fastdepCC_TRUE@ $(am__mv) $$depbase.Tpo $$depbase.Plo
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ $(AM_V_CC)source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@
+ at AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+ at am__fastdepCC_FALSE@ $(AM_V_CC at am__nodep@)$(LTCOMPILE) -c -o $@ $<
.cpp.o:
@am__fastdepCXX_TRUE@ $(AM_V_CXX)depbase=`echo $@ | sed 's|[^/]*$$|$(DEPDIR)/&|;s|\.o$$||'`;\
diff --git a/src/modules/simulation/sim_fire_spreading/Simulate.cpp b/src/modules/simulation/sim_fire_spreading/Simulate.cpp
new file mode 100644
index 0000000..9a305d5
--- /dev/null
+++ b/src/modules/simulation/sim_fire_spreading/Simulate.cpp
@@ -0,0 +1,363 @@
+/**********************************************************
+ * Version $Id: Simulate.cpp 911 2011-02-14 16:38:15Z reklov_w $
+ *********************************************************/
+/*******************************************************************************
+ Simulate.cpp
+ Copyright (C) Victor Olaya
+
+ 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 Street, 5th Floor, Boston, MA 02110-1301, USA
+*******************************************************************************/
+
+#include "Simulate.h"
+
+#define MS2FTMIN (60.0 / 0.3048)
+#define FTMIN2MMIN 0.3048
+#define BTU2KCAL 0.252164401
+#define FT2M 0.3048
+#define NO_TIME_LIMIT -1
+#define THRESHOLD_FOR_DIFFERENCE 0.1
+
+CSimulate::CSimulate(void){
+
+ Set_Name (_TL("Simulation"));
+ Set_Author (SG_T("(c) 2004 Victor Olaya"));
+ Set_Description (_TW(
+ "Fire simulation based on the BEHAVE fire modeling system "
+ "supported by the U.S. Forest Service, Fire and Aviation Management. "
+ "Find more information on BEHAVE at the <i>Public Domain Software for the Wildland Fire Community</i> at "
+ "<a target=\"_blank\" href=\"http://fire.org\">http://fire.org</a>\n"
+ "\n"
+ "Reference:\n"
+ "Andrews, P.L. (1986): BEHAVE: Fire Behavior Prediction and Fuel Modeling System - "
+ "Burn Subsystem, Part 1. U.S. Department of Agriculture, Forest Service General, Technical Report INT-194. "
+ ));
+
+ Parameters.Add_Grid(NULL,
+ "DEM",
+ _TL("DEM"),
+ _TL(""),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "FUEL",
+ _TL("Fuel Model"),
+ _TL(""),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "WINDSPD",
+ _TL("Wind Speed"),
+ _TL("Wind speed (m/s)"),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "WINDDIR",
+ _TL("Wind Direction"),
+ _TL("Wind direction (degrees clockwise from north)"),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "M1H",
+ _TL("Dead Fuel Moisture 1H"),
+ _TL(""),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "M10H",
+ _TL("Dead Fuel Moisture 10H"),
+ _TL(""),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "M100H",
+ _TL("Dead Fuel Moisture 100H"),
+ _TL(""),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "MHERB",
+ _TL("Herbaceous Fuel Moisture"),
+ _TL(""),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "MWOOD",
+ _TL("Wood Fuel Moisture"),
+ _TL(""),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "IGNITION",
+ _TL("Ignition Points"),
+ _TL(""),
+ PARAMETER_INPUT);
+
+ Parameters.Add_Grid(NULL,
+ "TIME",
+ _TL("Time"),
+ _TL(""),
+ PARAMETER_OUTPUT);
+
+ Parameters.Add_Grid(NULL,
+ "FLAME",
+ _TL("Flame Length"),
+ _TL("Flame Length (m)"),
+ PARAMETER_OUTPUT);
+
+ Parameters.Add_Grid(NULL,
+ "INTENSITY",
+ _TL("Intensity"),
+ _TL("Intensity (Kcal/m)"),
+ PARAMETER_OUTPUT);
+
+ Parameters.Add_Value(NULL,
+ "UPDATEVIEW",
+ _TL("Update View"),
+ _TL("Update view during simulation."),
+ PARAMETER_TYPE_Bool,
+ true);
+
+}//constructor
+
+CSimulate::~CSimulate(void){}
+
+bool CSimulate::On_Execute(void){
+
+ AssignParameters();
+ CalculateFire();
+
+ DeleteObjects();
+ return true;
+
+}//method
+
+void CSimulate::DeleteObjects(){
+
+ delete m_pAspectGrid;
+ delete m_pSlopeGrid;
+
+ m_CentralPoints .Clear();
+ m_AdjPoints .Clear();
+
+}//method
+
+bool CSimulate::AssignParameters(){
+
+ int x,y;
+
+ m_pDEM = Parameters("DEM")->asGrid();
+ m_pFuelGrid = Parameters("FUEL")->asGrid();
+ m_pIgnGrid = Parameters("IGNITION")->asGrid();
+ m_pWindDirGrid = Parameters("WINDDIR")->asGrid();
+ m_pWindSpdGrid = Parameters("WINDSPD")->asGrid();
+ m_pM1Grid = Parameters("M1H")->asGrid();
+ m_pM10Grid = Parameters("M10H")->asGrid();
+ m_pM100Grid = Parameters("M100H")->asGrid();
+ m_pMHerbGrid = Parameters("MHERB")->asGrid();
+ m_pMWoodGrid = Parameters("MWOOD")->asGrid();
+ m_pTimeGrid = Parameters("TIME")->asGrid();
+ m_pFlameGrid = Parameters("FLAME")->asGrid();
+ m_pIntensityGrid = Parameters("INTENSITY")->asGrid();
+
+ m_Catalog = Fire_FuelCatalogCreateStandard("Standard", 13);
+ Fire_FlameLengthTable(m_Catalog, 500, 0.1);
+
+ //substitute no-data values
+ for(y=0; y<Get_NY() && Set_Progress(y); y++){
+ for(x=0; x<Get_NX(); x++){
+
+ if (m_pWindSpdGrid->is_NoData(x, y)){
+ m_pWindSpdGrid->Set_Value(x, y, 0.);
+ }//if
+ if (m_pWindDirGrid->is_NoData(x, y)){
+ m_pWindDirGrid->Set_Value(x, y, 0.);
+ }//if
+ if (m_pM1Grid->is_NoData(x, y)){
+ m_pM1Grid->Set_Value(x, y, 0.);
+ }//if
+ if (m_pM10Grid->is_NoData(x, y)){
+ m_pM10Grid->Set_Value(x, y, 0.);
+ }//if
+ if (m_pM100Grid->is_NoData(x, y)){
+ m_pM100Grid->Set_Value(x, y, 0.);
+ }//if
+ if (m_pMHerbGrid->is_NoData(x, y)){
+ m_pMHerbGrid->Set_Value(x, y, 0.);
+ }//if
+ if (m_pMWoodGrid->is_NoData(x, y)){
+ m_pMWoodGrid->Set_Value(x, y, 0.);
+ }//if
+
+ }//for
+ }//for
+
+
+ //-----------------------------------------------------
+ // calculate slope and aspect using CSG_Grid class'
+ // built-in function (after Zevenbergen & Thorne)...
+
+ m_pSlopeGrid = SG_Create_Grid(m_pDEM, SG_DATATYPE_Double);
+ m_pAspectGrid = SG_Create_Grid(m_pDEM, SG_DATATYPE_Double);
+
+ for(y=0; y<Get_NY() && Set_Progress(y); y++)
+ {
+ for(x=0; x<Get_NX(); x++)
+ {
+ double slope, aspect;
+
+ if( m_pDEM->Get_Gradient(x, y, slope, aspect) )
+ {
+ m_pSlopeGrid ->Set_Value(x, y, slope);
+ m_pAspectGrid ->Set_Value(x, y, aspect);
+ }
+ else
+ {
+ m_pSlopeGrid ->Set_NoData(x, y);
+ m_pAspectGrid ->Set_NoData(x, y);
+ }
+ }
+ }
+
+
+ //-----------------------------------------------------
+ m_pTimeGrid->Assign((double)0);
+
+ return true;
+
+}//method
+
+void CSimulate::CalculateFire(){
+
+ int x,y;
+
+ Process_Set_Text(_TL("Simulating..."));
+ m_CentralPoints .Clear();
+ m_AdjPoints .Clear();
+
+ m_CentralPoints.Clear();
+ for(y=0; y<Get_NY(); y++){
+ for(x=0; x<Get_NX(); x++){
+ if (!m_pIgnGrid->is_NoData(x,y)){
+ m_CentralPoints.Add(x,y);
+ m_pTimeGrid->Set_Value(x,y,0.0);
+ }//if
+ }//for
+ }//for
+ CalculateFireSpreading(NO_TIME_LIMIT);
+
+ m_pTimeGrid->Set_NoData_Value(0.);
+
+
+}//method
+
+
+int CSimulate::CalculateFireSpreading(float fTimeLimit){
+
+ int x,y;
+ int x2,y2;
+ int n;
+ bool bReturn = false;
+ /* neighbor's address*/ /* N NE E SE S SW W NW */
+ static int nX[8] = { 0, 1, 1, 1, 0, -1, -1, -1};
+ static int nY[8] = { 1, 1, 0, -1, -1, -1, 0, 1};
+ double nDist[8]; /* distance to each neighbor */
+ double nAzm[8]; /* compass azimuth to each neighbor (0=N) */
+ size_t modelNumber; /* fuel model number at current cell */
+ double moisture[6]; /* fuel moisture content at current cell */
+ double dSpreadRate; /* spread rate in direction of neighbor */
+ double dSpreadTime; /* time to spread from cell to neighbor */
+ double dIgnTime; /* time neighbor is ignited by current cell */
+ double dWindSpd;
+ int iBurntCells = 0;
+
+ bool bUpdate = Parameters("UPDATEVIEW")->asBool();
+
+ for (n=0; n<8; n++){
+ nDist[n] = sqrt ( nX[n] * m_pDEM->Get_Cellsize() * nX[n] * m_pDEM->Get_Cellsize()
+ + nY[n] * m_pDEM->Get_Cellsize() * nY[n] * m_pDEM->Get_Cellsize() );
+ nAzm[n] = n * 45.;
+ }//for
+
+ while (m_CentralPoints.Get_Count()!=0){
+
+ for (int iPt=0; iPt<m_CentralPoints.Get_Count();iPt++){
+
+ x = m_CentralPoints.Get_X(iPt);
+ y = m_CentralPoints.Get_Y(iPt);
+
+ if (!m_pDEM->is_NoData(x,y) && !m_pFuelGrid->is_NoData(x,y)){
+
+ modelNumber = (size_t) m_pFuelGrid->asInt(x, y);
+ moisture[0] = m_pM1Grid->asFloat(x, y);
+ moisture[1] = m_pM10Grid->asFloat(x, y);
+ moisture[2] = m_pM100Grid->asFloat(x, y);
+ moisture[3] = m_pM100Grid->asFloat(x, y);
+ moisture[4] = m_pMHerbGrid->asFloat(x, y);;
+ moisture[5] = m_pMWoodGrid->asFloat(x, y);
+ dWindSpd = m_pWindSpdGrid->asFloat(x,y) * MS2FTMIN;
+ Fire_SpreadNoWindNoSlope(m_Catalog, modelNumber, moisture);
+ Fire_SpreadWindSlopeMax(m_Catalog, modelNumber, dWindSpd,
+ m_pWindDirGrid->asFloat(x,y), tan(m_pSlopeGrid->asFloat(x,y)),
+ m_pAspectGrid->asFloat(x,y));
+
+ for (n=0; n<8; n++){
+ x2 = x + nX[n];
+ y2 = y + nY[n];
+ if (m_pTimeGrid->is_InGrid(x2,y2,false)){
+ Fire_SpreadAtAzimuth(m_Catalog, modelNumber, nAzm[n], FIRE_BYRAMS);
+ dSpreadRate = Fuel_SpreadAny(m_Catalog, modelNumber); // in ft/min (awkward...)
+ dSpreadRate *= FTMIN2MMIN; //a bit better...
+ if (dSpreadRate > Smidgen){
+ dSpreadTime = nDist[n] / dSpreadRate;
+ if (fTimeLimit == NO_TIME_LIMIT){
+ dIgnTime = m_pTimeGrid->asDouble(x,y) + dSpreadTime;
+ if (m_pTimeGrid->asDouble(x2,y2) == 0.0
+ || m_pTimeGrid->asDouble(x2, y2) > dIgnTime + THRESHOLD_FOR_DIFFERENCE ){
+ m_pTimeGrid->Set_Value(x2, y2, dIgnTime);
+ m_AdjPoints.Add(x2,y2);
+ Fire_FlameScorch(m_Catalog, modelNumber, FIRE_FLAME);
+ m_pFlameGrid->Set_Value(x2, y2, Fuel_FlameLength(m_Catalog, modelNumber) * FT2M);
+ m_pIntensityGrid->Set_Value(x2, y2, Fuel_ByramsIntensity(m_Catalog, modelNumber)
+ * BTU2KCAL / FT2M );
+ }//if
+ }//if
+ }//if
+ }//if
+ }//for
+ }//if
+ }//for
+
+ m_CentralPoints.Clear();
+ for (int i=0; i<m_AdjPoints.Get_Count(); i++){
+ x= m_AdjPoints.Get_X(i);
+ y = m_AdjPoints.Get_Y(i);
+ m_CentralPoints.Add(x, y);
+ }//for
+ m_AdjPoints.Clear();
+
+ if (fTimeLimit == NO_TIME_LIMIT){
+ Process_Get_Okay(true);
+ }//if
+
+ if (bUpdate){
+ DataObject_Update(m_pTimeGrid, true);
+ }
+
+ }//while
+
+ return iBurntCells;
+
+}//method
+
diff --git a/src/modules/simulation/sim_fire_spreading/Simulate.h b/src/modules/simulation/sim_fire_spreading/Simulate.h
new file mode 100644
index 0000000..ed2ff06
--- /dev/null
+++ b/src/modules/simulation/sim_fire_spreading/Simulate.h
@@ -0,0 +1,81 @@
+/**********************************************************
+ * Version $Id: Simulate.h 911 2011-02-14 16:38:15Z reklov_w $
+ *********************************************************/
+/*******************************************************************************
+ Simulate.h
+ Copyright (C) Victor Olaya
+
+ 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 Street, 5th Floor, Boston, MA 02110-1301, USA
+*******************************************************************************/
+
+#if _MSC_VER > 1000
+#pragma once
+#endif // _MSC_VER > 1000
+
+#include "MLB_Interface.h"
+#include "fireLib.h"
+
+class CSimulate : public CSG_Module_Grid {
+
+private:
+
+ CSG_Grid *m_pDEM;
+ CSG_Grid *m_pIgnGrid; /* ptr to ignition time map (minutes) */
+ CSG_Grid *m_pWindSpdGrid; /* ptr to wind speed map (m/s) */
+ CSG_Grid *m_pWindDirGrid; /* ptr to wind direction map (deg from north) */
+ CSG_Grid *m_pM1Grid; /* ptr to 1-hr dead fuel moisture map */
+ CSG_Grid *m_pM10Grid; /* ptr to 10-hr dead fuel moisture map */
+ CSG_Grid *m_pM100Grid; /* ptr to 100-hr dead fuel moisture map */
+ CSG_Grid *m_pMHerbGrid; /* ptr to live herbaceous fuel moisture map */
+ CSG_Grid *m_pMWoodGrid; /* ptr to live stem fuel moisture map */
+ CSG_Grid *m_pFuelGrid; /* ptr to fuel model map */
+ CSG_Grid *m_pValueGrid;
+
+ CSG_Grid *m_pFlameGrid; /* ptr to flame length map (m) */
+ CSG_Grid *m_pIntensityGrid;
+
+ CSG_Grid *m_pSlopeGrid; /* ptr to slope map (rise/reach) */
+ CSG_Grid *m_pAspectGrid; /* ptr to aspect map (degrees from north) */
+
+ CSG_Grid *m_pTimeGrid;
+ //CSG_Grid *m_pVolatileTimeGrid;
+
+ FuelCatalogPtr m_Catalog; /* fuel catalog handle */
+
+ int m_iLength;
+
+ CSG_Points_Int m_CentralPoints;
+ CSG_Points_Int m_AdjPoints;
+
+ int *m_pLength;
+ int m_iMaxTime; //in s
+ int m_iTimeInterval; //in s
+
+ bool AssignParameters();
+ void CalculateFire();
+ int CalculateFireSpreading(float);
+ void DeleteObjects();
+
+public:
+
+ CSimulate(void);
+ virtual ~CSimulate(void);
+
+protected:
+
+ virtual bool On_Execute(void);
+
+};
+
diff --git a/src/modules/simulation/sim_fire_spreading/fireLib.c b/src/modules/simulation/sim_fire_spreading/fireLib.c
new file mode 100644
index 0000000..53b16a0
--- /dev/null
+++ b/src/modules/simulation/sim_fire_spreading/fireLib.c
@@ -0,0 +1,1817 @@
+/**********************************************************
+ * Version $Id: fireLib.c 911 2011-02-14 16:38:15Z reklov_w $
+ *********************************************************/
+/*
+ *******************************************************************************
+ *
+ * fireLib.c
+ *
+ * Description
+ * Library of BEHAVE (Andrews 1986) fire behavior algorithms
+ * encapsulated and optimized for fire behavior simulation.
+ *
+ * Legalities
+ * Copyright (c) 1996 Collin D. Bevins.
+ * See the file "license.txt" for information on usage and
+ * redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
+ *
+ * Naming Conventions
+ * All function names begin with "Fire_".
+ * All fuel model and behavior parameter access macros begin with "Fuel_".
+ * All fuel catalog parameter access macros begin with "FuelCat_".
+ *
+ * Functions
+ * There are 8 functions to create and destroy fuel models and catalogs:
+ *
+ * Fire_FuelCatalogCreate(name, maxModels)
+ * Creates a new fuel catalog capable of holding maxModels.
+ *
+ * Fire_FuelCatalogCreateStandard(name, maxModels)
+ * Creates a new fuel catalog capable of holding maxModels,
+ * and fills models 0-13 with standard fire behavior models.
+ *
+ * Fire_FuelModelCreate(catalog, model, name, desc, depth, mext,
+ * adjust, maxParticles)
+ * Adds or replaces a fuel model in the catalog. The model will
+ * accept up to maxParticles particles.
+ *
+ * Fire_FuelModelExists(catalog, model)
+ * Returns 1 if model exists within the catalog.
+ *
+ * Fire_FuelParticleAdd(catalog, model, live, load, savr, dens, heat,
+ * stot, seff)
+ * Adds a fuel particle to a fuel model.
+ *
+ * Fire_FlameLengthTable ( catalog, flameClasses, flameStep )
+ * Creates a flame length look-up table containing flameClasses
+ * number of classes, with each class spanning "flameStep"
+ * feet of flame length. Creating a flame length table can
+ * significantly improve performance at the expense of user
+ * specified precision.
+ *
+ * Fire_FuelModelDestroy(catalog, model)
+ * Destroys the model within the catalog.
+ *
+ * Fire_FuelCatalogDestroy(catalog)
+ * Destroys the catalog and all models within it.
+ *
+ * There are 5 functions to process data within fuel models:
+ *
+ * Fire_FuelCombustion(catalog, model)
+ * Computes all the fuel-dependent model variables.
+ * Called only once for each fuel model.
+ * Called automatically by Fire_SpreadNoWindNoSlope().
+ *
+ * Fire_SpreadNoWindNoSlope(catalog, model, moisture[6])
+ * Determines reaction intensity, heat per unit area, and the
+ * no-wind no-slope spread rate.
+ *
+ * Fire_SpreadWindSlopeMax(catalog, model, windFpm, windDeg, slope,
+ * aspectDeg)
+ * Determines maximum spread rate and azimuth of maximum spread
+ * based upon input parameters and results of the most recent
+ * call to Fire_SpreadNoWindNoSlope() for this model.
+ *
+ * Fire_SpreadAtAzimuth(catalog, model, azimuth, doWhich)
+ * Determines the spread rate in the specified azimuth based
+ * upon the results of the most recent call to
+ * Fire_SpreadWindSlopeMax() for this model. The "doWhich"
+ * parameter is the result of ORing the constants FIRE_BYRAMS,
+ * FIRE_FLAME, and FIRE_SCORCH to request computation of the
+ * associated fire variables.
+ *
+ * Fire_FlameScorch(catalog, model, doWhich)
+ * Determines the flame length and/or scorch height based upon
+ * the most recent call to Fire_SpreadAtAzimuth().
+ *
+ * History
+ * 1996/09/04 Version 1.0.0 release.
+ * 1999/03/05 Fixed NNFL07 live SAVR from 1500 to 1550.
+ *
+ *******************************************************************************
+ */
+
+#include "fireLib.h"
+
+#ifndef M_PI
+#define M_PI 3.14159
+#endif
+
+/*
+ *******************************************************************************
+ *
+ * Fire_FuelCombustion()
+ *
+ * Description
+ * Calculates and stores all the fuel-dependent combustion variables.
+ *
+ * Side Effects
+ * All combustion varaiables are reclaculated for the model.
+ * All behavior and environment variables are reset to zero.
+ *
+ * Function Returns
+ * FIRE_STATUS_OK or FIRE_STATUS_ERROR.
+ * Return status and error text are stored in the Fire Catalog's buffers.
+ *
+ *******************************************************************************
+ */
+
+int
+Fire_FuelCombustion (FuelCatalogPtr catalog, size_t model )
+ //FuelCatalogPtr catalog; /* FuelCatalogData instance pointer */
+ //size_t model; /* fuel model id number [0-maxModels] */
+{
+ size_t particle, size, life;
+
+ double sizeClassAreaWtg[FIRE_LIFE_CATS][FIRE_SIZE_CLASSES];
+ double lifeLoad[FIRE_LIFE_CATS];
+ double lifeArea[FIRE_LIFE_CATS];
+ double lifeSavr[FIRE_LIFE_CATS];
+ double lifeHeat[FIRE_LIFE_CATS];
+ double lifeSeff[FIRE_LIFE_CATS];
+ double lifeEtaS[FIRE_LIFE_CATS];
+
+ double totalArea;
+ double fineLive;
+ double beta;
+ double betaOpt;
+ double sigma;
+ double ratio;
+ double aa;
+ double sigma15;
+ double gammaMax;
+ double gamma;
+ double c;
+ double e;
+
+ /* Validate catalog and fuel model existence. */
+ assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
+ if ( ! Fire_FuelModelExists(catalog,model) )
+ {
+ sprintf(FuelCat_Error(catalog),
+ "Fire_FuelCombustion(): el modelo de combustible %d no existe en el cat�logo de combuestibles \"%s\".",
+ model, FuelCat_Name(catalog));
+ return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
+ }
+
+ /* Initialize the model's fuel particle dependent variables. */
+ for ( particle=0; particle<Fuel_Particles(catalog,model); particle++ )
+ {
+ Fuel_AreaWtg(catalog,model,particle) = 0.;
+ Fuel_SizeAreaWtg(catalog,model,particle) = 0.;
+ Fuel_Moisture(catalog,model,particle) = 0.;
+ }
+
+ /* Initialize the model's fuel combustion variables. */
+ /* The following are calculated by this function. */
+ Fuel_FineDead(catalog,model) = 0.0;
+ Fuel_LiveMextFactor(catalog,model) = 0.0;
+ Fuel_BulkDensity(catalog,model) = 0.0;
+ Fuel_ResidenceTime(catalog,model) = 0.0;
+ Fuel_PropFlux(catalog,model) = 0.0;
+ Fuel_SlopeK(catalog,model) = 0.0;
+ Fuel_WindB(catalog,model) = 0.0;
+ Fuel_WindE(catalog,model) = 0.0;
+ Fuel_WindK(catalog,model) = 0.0;
+
+ for (life=0; life<FIRE_LIFE_CATS; life++)
+ {
+ Fuel_LifeAreaWtg(catalog,model,life) = 0.;
+ Fuel_LifeRxFactor(catalog,model,life) = 0.;
+ lifeLoad[life] = 0.;
+ lifeArea[life] = 0.;
+ lifeSavr[life] = 0.;
+ lifeHeat[life] = 0.;
+ lifeEtaS[life] = 0.;
+ lifeSeff[life] = 0.;
+ for ( size=0; size<FIRE_SIZE_CLASSES; size++ )
+ sizeClassAreaWtg[life][size] = 0.;
+ }
+
+ /* Initialize the model's fire behavior variables. */
+ /* These are calculated by Fire_SpreadNoWindNoSlope(). */
+ Fuel_Spread0(catalog,model) = 0.;
+ Fuel_RxIntensity(catalog,model) = 0.;
+ Fuel_HeatPerUnitArea(catalog,model) = 0.;
+
+ /* Initialize the model's fire behavior variables. */
+ /* These are calculated by Fire_SpreadWindSlopeMax(). */
+ Fuel_SpreadMax(catalog,model) = 0.;
+ Fuel_AzimuthMax(catalog,model) = 0.;
+ Fuel_EffectiveWind(catalog,model) = 0.;
+ Fuel_PhiSlope(catalog,model) = 0.;
+ Fuel_PhiWind(catalog,model) = 0.;
+ Fuel_PhiEffWind(catalog,model) = 0.;
+ Fuel_LwRatio(catalog,model) = 1.;
+ Fuel_Eccentricity(catalog,model) = 0.;
+ Fuel_WindLimit(catalog,model) = 0;
+
+ /* Initialize the model's fire behavior variables. */
+ /* These are calculated by Fire_SpreadAtAzimuth(). */
+ Fuel_SpreadAny(catalog,model) = 0.;
+ Fuel_AzimuthAny(catalog,model) = 0.;
+ Fuel_ByramsIntensity(catalog,model) = 0.;
+ Fuel_FlameLength(catalog,model) = 0.;
+ Fuel_ScorchHeight(catalog,model) = 0.;
+
+ /* Initialize the model's environmental variables. */
+ Fuel_WindSpeed(catalog,model) = 0.;
+ Fuel_WindDir(catalog,model) = 0.;
+ Fuel_Slope(catalog,model) = 0.;
+ Fuel_Aspect(catalog,model) = 0.;
+ for ( size=0; size<FIRE_MCLASSES; size++ )
+ Fuel_EnvMoisture(catalog,model,size) = 0.;
+
+ /* Initialize the model's combustion flag. */
+ Fuel_CombustionFlag(catalog,model) = 1;
+
+ /* If the model has no particles, we're all done. */
+ if ( Fuel_Particles(catalog,model) <= 0 )
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+
+ /* Initialize local fuel bed and combustion variables. */
+ beta = betaOpt = sigma = ratio = aa = sigma15 = 0.;
+ gamma = gammaMax = c = e = fineLive = totalArea = 0.;
+
+ /* Accumulate surface areas by life category for the entire fuel bed. */
+ for ( particle=0; particle<Fuel_Particles(catalog,model); particle++ )
+ {
+ life = Fuel_Live(catalog,model,particle);
+ lifeArea[life] += Fuel_SurfaceArea(catalog,model,particle);
+ totalArea += Fuel_SurfaceArea(catalog,model,particle);
+ }
+
+ /* If no surface area, we're all done. */
+ if ( totalArea <= Smidgen )
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+
+ /* Surface area wtg factor for each particle within its life category */
+ /* and within its size class category (used to weight loading). */
+ for ( particle=0; particle<Fuel_Particles(catalog,model); particle++ )
+ {
+ life = Fuel_Live(catalog,model,particle);
+ if ( lifeArea[life] > Smidgen )
+ {
+ Fuel_AreaWtg(catalog,model,particle) =
+ Fuel_SurfaceArea(catalog,model,particle) / lifeArea[life];
+
+ size = Fuel_SizeClass(catalog,model,particle);
+ sizeClassAreaWtg[life][size] +=
+ Fuel_AreaWtg(catalog,model,particle);
+ }
+ }
+
+ /* Assign size class surface area weights to each particle. */
+ for ( particle=0; particle<Fuel_Particles(catalog,model); particle++ )
+ {
+ life = Fuel_Live(catalog,model,particle);
+ size = Fuel_SizeClass(catalog,model,particle);
+ Fuel_SizeAreaWtg(catalog,model,particle) = sizeClassAreaWtg[life][size];
+ }
+
+ /* Derive life category surface area weighting factors. */
+ for ( life=0; life<FIRE_LIFE_CATS; life++ )
+ Fuel_LifeAreaWtg(catalog,model,life) = lifeArea[life] / totalArea;
+
+ /* Accumulate life category weighted load, heat, savr, and seff. */
+ for ( particle=0; particle<Fuel_Particles(catalog,model); particle++ )
+ {
+ life = Fuel_Live(catalog,model,particle);
+
+ lifeLoad[life] += Fuel_SizeAreaWtg(catalog,model,particle)
+ * Fuel_Load(catalog,model,particle)
+ * (1. - Fuel_SiTotal(catalog,model,particle));
+
+ lifeSavr[life] += Fuel_AreaWtg(catalog,model,particle)
+ * Fuel_Savr(catalog,model,particle);
+
+ lifeHeat[life] += Fuel_AreaWtg(catalog,model,particle)
+ * Fuel_Heat(catalog,model,particle);
+
+ lifeSeff[life] += Fuel_AreaWtg(catalog,model,particle)
+ * Fuel_SiEffective(catalog,model,particle);
+
+ Fuel_BulkDensity(catalog,model) += Fuel_Load(catalog,model,particle);
+
+ if ( Fuel_Density(catalog,model,particle) > Smidgen )
+ beta += Fuel_Load(catalog,model,particle)
+ / Fuel_Density(catalog,model,particle);
+ }
+
+ /* Accumulate life category contribution to reaction intensity. */
+ for ( life=0; life<FIRE_LIFE_CATS; life++ )
+ {
+ sigma += Fuel_LifeAreaWtg(catalog,model,life) * lifeSavr[life];
+
+ lifeEtaS[life] = 1.;
+ if (lifeSeff[life] > 0.)
+ {
+ if ( (lifeEtaS[life] = 0.174 / pow(lifeSeff[life], 0.19)) > 1.0 )
+ lifeEtaS[life] = 1.0;
+ }
+
+ Fuel_LifeRxFactor(catalog,model,life) =
+ lifeLoad[life] * lifeHeat[life] * lifeEtaS[life];
+ }
+
+ /* Fuel model residence time */
+ Fuel_ResidenceTime(catalog,model) = 384. / sigma;
+
+ /* Fuel model bulk density */
+ if ( Fuel_Depth(catalog,model) > Smidgen )
+ {
+ Fuel_BulkDensity(catalog,model) /= Fuel_Depth(catalog,model);
+ beta /= Fuel_Depth(catalog,model);
+ }
+
+ /* Propagating flux depends upon sigma and beta only. */
+ Fuel_PropFlux(catalog,model) =
+ exp((0.792 + 0.681*sqrt(sigma)) * (beta+0.1)) / (192.+0.2595*sigma);
+
+ /* Gamma */
+ betaOpt = 3.348 / (pow(sigma, 0.8189));
+ ratio = beta / betaOpt;
+ aa = 133. / (pow(sigma, 0.7913));
+ sigma15 = pow(sigma, 1.5);
+ gammaMax = sigma15 / (495. + 0.0594*sigma15);
+ gamma = gammaMax * pow(ratio, aa) * exp(aa * (1.-ratio));
+
+ /* Factor gamma into life category reaction intensity contribution. */
+ for ( life=0; life<FIRE_LIFE_CATS; life++ )
+ Fuel_LifeRxFactor(catalog,model,life) *= gamma;
+
+ /* Slope and wind intermediates constants for the fuel model. */
+ Fuel_SlopeK(catalog,model) = 5.275 * pow(beta, -0.3);
+ Fuel_WindB(catalog,model) = 0.02526 * pow(sigma, 0.54);
+
+ c = 7.47 * exp(-0.133 * pow(sigma, 0.55));
+ e = 0.715 * exp(-0.000359 * sigma);
+ Fuel_WindK(catalog,model) = c * pow(ratio, -e);
+ Fuel_WindE(catalog,model) = pow(ratio, e) / c;
+
+ /* If no live fuel, we're done. */
+ if ( lifeLoad[FIRE_LIFE_LIVE] < Smidgen )
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+
+ /* Fine dead fuel and fine live fuel factors. */
+ for ( particle=0; particle<Fuel_Particles(catalog,model); particle++ )
+ {
+ if ( Fuel_Live(catalog,model,particle) )
+ fineLive
+ += Fuel_Load(catalog,model,particle)
+ * exp(-500. / Fuel_Savr(catalog,model,particle));
+ else
+ Fuel_FineDead(catalog,model)
+ += Fuel_Load(catalog,model,particle)
+ * Fuel_SigmaFactor(catalog,model,particle);
+ }
+
+ /* Live fuel extinction moisture factor. */
+ if ( fineLive > Smidgen )
+ Fuel_LiveMextFactor(catalog,model)
+ = 2.9 * Fuel_FineDead(catalog,model) / fineLive;
+
+ /* That's all, folks!. */
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+}
+
+/*
+ *******************************************************************************
+ *
+ * Fire_SpreadNoWindNoSlope()
+ *
+ * Description
+ * Calculates the fire reaction intensity and no-wind, no-slope spread
+ * rate given the fuel model, combustion, and moisture regime inputs.
+ *
+ * Side Effects
+ * Updates the following fire behavior variables:
+ * Fuel_RxIntensity(catalog,model).
+ * Fuel_HeatPerUnitArea(catalog,model).
+ * Fuel_Spread0(catalog,model).
+ * Fuel_SpreadMax(catalog,model) = Fuel_Spread0(catalog,model)
+ * Fuel_SpreadAny(catalog,model) = Fuel_Spread0(catalog,model)
+ * Fuel_AzimuthAny(catalog,model) = 0.
+ * Fuel_AzimuthMax(catalog,model) = 0.
+ *
+ * Function Returns
+ * FIRE_STATUS_OK or FIRE_STATUS_ERROR.
+ * Return status and error text are stored in the Fire Catalog's buffers.
+ *
+ *******************************************************************************
+ */
+
+int
+Fire_SpreadNoWindNoSlope ( FuelCatalogPtr catalog, size_t model, double moisture[FIRE_MCLASSES] )
+ // FuelCatalogPtr catalog; /* FuelCatalogData instance pointer */
+ // size_t model; /* fuel model number [0-maxModels] */
+ // double moisture[FIRE_MCLASSES]; /* array of fuel moistures (fractions) */
+{
+ size_t mclass, particle, life, nlive;
+ double wfmd;
+ double rbQig;
+ double fdmois;
+ double qig;
+ double ratio;
+ double lifeMoisture[FIRE_LIFE_CATS];
+ double lifeEtaM[FIRE_LIFE_CATS];
+ double lifeMext[FIRE_LIFE_CATS];
+
+ static size_t TimeLagClass[FIRE_SIZE_CLASSES] = {0, 0, 1, 1, 2, 2};
+
+ /* Validate the catalog and fuel model. */
+ assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
+ if ( ! Fire_FuelModelExists(catalog,model) )
+ {
+ sprintf(FuelCat_Error(catalog),
+ "Fire_SpreadNoWindNoSlope(): el modelo de combustible %d no existe en el cat�logo de combustibles \"%s\".",
+ model, FuelCat_Name(catalog));
+ return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
+ }
+
+ /* Check if we must recalculate combustion intermediates. */
+ if ( ! Fuel_CombustionFlag(catalog,model) )
+ {
+ Fire_FuelCombustion(catalog,model);
+ }
+
+ /* Otherwise check if the moisture environment has changed. */
+ else
+ {
+ for ( mclass=0; mclass<FIRE_MCLASSES; mclass++ )
+ if ( ! Equal(moisture[mclass],Fuel_EnvMoisture(catalog,model,mclass)) )
+ break;
+
+ /* If no change in fuel moisture, no more computation is needed. */
+ if ( mclass == FIRE_MCLASSES )
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+ }
+
+ /* Store the new moistures in the fuel's environmental moisture array. */
+ for ( mclass=0; mclass<FIRE_MCLASSES; mclass++ )
+ Fuel_EnvMoisture(catalog,model,mclass) = moisture[mclass];
+
+ /* Initialize the model's fire behavior variables. */
+ /* These are calculated by this function. */
+ Fuel_Spread0(catalog,model) = 0.;
+ Fuel_RxIntensity(catalog,model) = 0.;
+ Fuel_HeatPerUnitArea(catalog,model) = 0.;
+
+ /* Initialize the model's fire behavior variables. */
+ /* These are calculated by Fire_SpreadWindSlopeMax(). */
+ Fuel_SpreadMax(catalog,model) = 0.;
+ Fuel_AzimuthMax(catalog,model) = 0.;
+
+ /* Initialize the model's fire behavior variables. */
+ /* These are calculated by Fire_SpreadAtAzimuth(). */
+ Fuel_SpreadAny(catalog,model) = 0.;
+ Fuel_AzimuthAny(catalog,model) = 0.;
+ Fuel_ByramsIntensity(catalog,model) = 0.;
+ Fuel_FlameLength(catalog,model) = 0.;
+ Fuel_ScorchHeight(catalog,model) = 0.;
+
+ /* If no fuel particles, return. */
+ if (Fuel_Particles(catalog,model) <= 0)
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+
+ /* Initialize local variables. */
+ wfmd = fdmois = rbQig = 0.;
+ for ( life=0; life<FIRE_LIFE_CATS; life++ )
+ {
+ lifeMoisture[life] = 0.;
+ lifeEtaM[life] = 0.;
+ lifeMext[life] = 0.;
+ }
+
+ /* Assign particle moistures based upon their size class. */
+ nlive = 0;
+ for ( particle=0; particle<Fuel_Particles(catalog,model); particle++ )
+ {
+ /* if this is a dead fuel, accumulate its wtd fuel moisture. */
+ if ( Fuel_Live(catalog,model,particle) == FIRE_LIFE_DEAD )
+ {
+ mclass = TimeLagClass[Fuel_SizeClass(catalog,model,particle)];
+ wfmd += moisture[mclass]
+ * Fuel_SigmaFactor(catalog,model,particle)
+ * Fuel_Load(catalog,model,particle);
+ }
+ else
+ {
+ nlive++;
+ mclass = (Fuel_Type(catalog,model,particle) == FIRE_TYPE_HERB) ?
+ FIRE_MCLASS_HERB : FIRE_MCLASS_WOOD;
+ }
+
+ /* Assign this particle the fuel moisture for its size class. */
+ Fuel_Moisture(catalog,model,particle) = moisture[mclass];
+ }
+
+ /* Compute live fuel extinction moisture. */
+ if ( nlive )
+ {
+ fdmois = ( Fuel_FineDead(catalog,model) > Smidgen ) ?
+ (wfmd / Fuel_FineDead(catalog,model)) : 0.;
+
+ lifeMext[FIRE_LIFE_LIVE]
+ = ((Fuel_LiveMextFactor(catalog,model)
+ * (1.0 - fdmois/Fuel_Mext(catalog,model))) - 0.226);
+
+ if ( lifeMext[FIRE_LIFE_LIVE] < Fuel_Mext(catalog,model) )
+ lifeMext[FIRE_LIFE_LIVE] = Fuel_Mext(catalog,model);
+ }
+
+ /* Dead fuel extinction moisture is a fuel model input. */
+ lifeMext[FIRE_LIFE_DEAD] = Fuel_Mext(catalog,model);
+
+ /* Compute category weighted moisture and accumulate the rbQig. */
+ for (particle=0; particle<Fuel_Particles(catalog,model); particle++)
+ {
+ qig = 250. + 1116. * Fuel_Moisture(catalog,model,particle);
+
+ life = Fuel_Live(catalog,model,particle);
+
+ lifeMoisture[life] += Fuel_AreaWtg(catalog,model,particle)
+ * Fuel_Moisture(catalog,model,particle);
+
+ rbQig += qig
+ * Fuel_AreaWtg(catalog,model,particle)
+ * Fuel_LifeAreaWtg(catalog,model,life)
+ * Fuel_SigmaFactor(catalog,model,particle);
+ }
+
+ /* Complete the rbQig calculation. */
+ rbQig *= Fuel_BulkDensity(catalog,model);
+
+ /* Compute moisture damping coeff by life class, and combine with the */
+ /* life class's rx factor to get the total reaction intensity. */
+ for (life=0; life<FIRE_LIFE_CATS; life++)
+ {
+ ratio = 0.;
+ if ( lifeMext[life] > Smidgen )
+ {
+ ratio = lifeMoisture[life] / lifeMext[life];
+ lifeEtaM[life] =
+ 1.0 - 2.59*ratio + 5.11*ratio*ratio - 3.52*ratio*ratio*ratio;
+ }
+
+ /* If category moisture exceeds category extinction moisture, */
+ /* the damping coefficient is zero. */
+ if ( lifeMoisture[life] >= lifeMext[life] )
+ lifeEtaM[life] = 0.;
+
+ /* Accumulate total reaction intensity. */
+ Fuel_RxIntensity(catalog,model)
+ += Fuel_LifeRxFactor(catalog,model,life)
+ * lifeEtaM[life];
+ }
+
+ /* Calculate heat per unit area from rx intensity and residence time. */
+ Fuel_HeatPerUnitArea(catalog,model)
+ = Fuel_RxIntensity(catalog,model)
+ * Fuel_ResidenceTime(catalog,model);
+
+ /* Calculate no-wind, no-slope spread rate. */
+ Fuel_Spread0(catalog,model)
+ = (rbQig > Smidgen)
+ ? Fuel_RxIntensity(catalog,model) * Fuel_PropFlux(catalog,model) / rbQig
+ : 0.;
+
+ /* Re-initialize spread in maximum and any azimuth to no wind-no slope. */
+ Fuel_SpreadMax(catalog,model) = Fuel_Spread0(catalog,model);
+ Fuel_SpreadAny(catalog,model) = Fuel_Spread0(catalog,model);
+ Fuel_AzimuthMax(catalog,model) = Fuel_AzimuthAny(catalog,model) = 0.;
+
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+}
+
+/*
+ *******************************************************************************
+ *
+ * Fire_SpreadWindSlopeMax()
+ *
+ * Description
+ * Calculates maximum fire spread rate and direction under the given
+ * wind-slope conditions. Results depend only upon:
+ * - no wind-slope spread rate
+ * - wind speed and direction
+ * - aspect and slope
+ *
+ * Side Effects
+ * Updates the following variables:
+ * Fuel_Slope() = slope;
+ * Fuel_PhiSlope().
+ * Fuel_Wind() = windFpm;
+ * Fuel_PhiWind().
+ * Fuel_Aspect(catalog,model) = aspect;
+ * Fuel_WindDir(catalog,model) = windDeg;
+ * Fuel_PhiEffWind(catalog,model) = phiEw;
+ * Fuel_EffectiveWind(catalog,model) = effectiveWind;
+ * Fuel_WindLimit(catalog,model) = windLimit;
+ * Fuel_SpreadMax(catalog,model) = spreadMax;
+ * Fuel_AzimuthMax(catalog,model) = azimuthMax;
+ * Fuel_LwRatio(catalog,model) = lwRatio;
+ * Fuel_Eccentricity(catalog,model) = eccentricity;
+ *
+ * Resets Fire_SpreadAtAzimuth() variables:
+ * Fuel_SpreadAny(catalog,model) = spreadMax;
+ * Fuel_AzimuthAny(catalog,model) = azimuthMax;
+ * Fuel_ByramsIntensity(catalog,model) = 0.;
+ * Fuel_FlameLength(catalog,model) = 0.;
+ * Fuel_ScorchHeight(catalog,model) = 0.;
+ *
+ * Previous Fire_SpreadAtAzimiuth() results become obsolete for this model.
+ *
+ * Function Returns
+ * FIRE_STATUS_OK or FIRE_STATUS_ERROR.
+ * Return status and error text are stored in the Fire Catalog's buffers.
+ *
+ *******************************************************************************
+ */
+
+int
+Fire_SpreadWindSlopeMax ( FuelCatalogPtr catalog, size_t model, double windFpm, double windDeg, double slope, double aspect )
+ // FuelCatalogPtr catalog; /* FuelCatalogData instance pointer */
+ // size_t model; /* fuel model number [0-maxModels] */
+ // double windFpm; /* wind speed (ft/min) */
+ // double windDeg; /* wind bearing vector (compass degrees) */
+ // double slope; /* slope (rise/reach) */
+ // double aspect; /* aspect (downslope) azimuth (compass deg) */
+{
+ double upslope, azimuthMax, phiEw;
+ double splitDeg, splitRad;
+ double slpRate, wndRate, rv, spreadMax;
+ double x, y, al, a;
+ double maxWind, effectiveWind, lwRatio, eccentricity;
+ size_t doEffectiveWind, checkWindLimit, windLimit;
+
+ /* Validate the catalog and fuel model. */
+ assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
+ if ( ! Fire_FuelModelExists(catalog,model) )
+ {
+ sprintf(FuelCat_Error(catalog),
+ "Fire_SpreadMax(): el modelo de combustible %d no existe en el cat�logo de combustibles \"%s\".",
+ model, FuelCat_Name(catalog));
+ return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
+ }
+
+ /* Recalculate slope factors ONLY if different from previous model input. */
+ if ( ! Equal(Fuel_Slope(catalog,model),slope) )
+ {
+ Fuel_PhiSlope(catalog,model) =
+ Fuel_SlopeK(catalog,model) * slope * slope;
+ Fuel_Slope(catalog,model) = slope;
+ }
+
+ /* Recalculate wind factors ONLY if different from previous model input. */
+ if ( ! Equal(Fuel_WindSpeed(catalog,model),windFpm) )
+ {
+ Fuel_PhiWind(catalog,model) = (windFpm < Smidgen) ? 0. :
+ Fuel_WindK(catalog,model) * pow(windFpm, Fuel_WindB(catalog,model));
+ Fuel_WindSpeed(catalog,model) = windFpm;
+ }
+
+ /* Combine wind and slope factors. */
+ phiEw = Fuel_PhiSlope(catalog,model) + Fuel_PhiWind(catalog,model);
+ windLimit = 0;
+ lwRatio = 1.;
+ eccentricity = 0.;
+ upslope = (aspect>=180.) ? aspect-180. : aspect+180.;
+
+ /* Situation 1: no fire spread or reaction intensity. */
+ if ( Fuel_Spread0(catalog,model) < Smidgen )
+ {
+ spreadMax = 0.;
+ azimuthMax = 0;
+ /* There IS an effective wind even if there is no fire. */
+ doEffectiveWind = 1;
+ /* But since BEHAVE doesn't calculate effective wind when no spread. */
+ /* we wont either. */
+ effectiveWind = 0.;
+ doEffectiveWind = 0;
+ checkWindLimit = 0;
+ }
+
+ /* Situation 2: no wind and no wind */
+ else if ( phiEw < Smidgen )
+ {
+ phiEw = 0.;
+ effectiveWind = 0.;
+ doEffectiveWind = 0;
+ spreadMax = Fuel_Spread0(catalog,model);
+ azimuthMax = 0;
+ checkWindLimit = 0;
+ }
+
+ /* Situation 3: wind with no slope. */
+ else if ( slope < Smidgen )
+ {
+ effectiveWind = windFpm;
+ doEffectiveWind = 0;
+ spreadMax = Fuel_Spread0(catalog,model) * (1. + phiEw);
+ azimuthMax = windDeg;
+ checkWindLimit = 1;
+ }
+
+ /* Situation 4: slope with no wind. */
+ else if ( windFpm < Smidgen )
+ {
+ doEffectiveWind = 1;
+ spreadMax = Fuel_Spread0(catalog,model) * (1. + phiEw);
+ azimuthMax = upslope;
+ checkWindLimit = 1;
+ }
+
+ /* Situation 5: wind blows upslope. */
+ else if ( Equal(upslope,windDeg) )
+ {
+ doEffectiveWind = 1;
+ spreadMax = Fuel_Spread0(catalog,model) * (1. + phiEw);
+ azimuthMax = upslope;
+ checkWindLimit = 1;
+ }
+
+ /* Situation 6: wind blows cross slope. */
+ else
+ {
+ /* Recalculate spread rate in the optimal direction. */
+ splitDeg = (upslope<=windDeg) ? windDeg-upslope : 360.-upslope+windDeg;
+ splitRad = DegreesToRadians(splitDeg);
+ slpRate = Fuel_Spread0(catalog,model) * Fuel_PhiSlope(catalog,model);
+ wndRate = Fuel_Spread0(catalog,model) * Fuel_PhiWind(catalog,model);
+ x = slpRate + wndRate * cos(splitRad);
+ y = wndRate * sin(splitRad);
+ rv = sqrt(x*x + y*y);
+ spreadMax= Fuel_Spread0(catalog,model) + rv;
+
+ /* Recalculate phiEw in the optimal direction. */
+ phiEw = spreadMax / Fuel_Spread0(catalog,model) - 1.0;
+ doEffectiveWind = (phiEw > Smidgen) ? 1 : 0;
+ checkWindLimit = 1;
+
+ /* Recalculate direction of maximum spread in azimuth degrees. */
+ al = asin(fabs(y) / rv);
+ if ( x >= 0. )
+ a = (y >= 0.) ? al : M_PI + M_PI - al;
+ else
+ a = (y >= 0.) ? (M_PI - al) : (M_PI + al);
+
+ splitDeg = RadiansToDegrees(a);
+ if ( (azimuthMax = upslope + splitDeg) > 360. )
+ azimuthMax -= 360.;
+ }
+
+ /* Recalculate effective wind speed based upon phiEw. */
+ if ( doEffectiveWind )
+ effectiveWind = pow( (phiEw * Fuel_WindE(catalog,model)),
+ (1. / Fuel_WindB(catalog,model)) );
+
+ /* If effective wind exceeds maximum wind, scale back spread & phiEw. */
+ if ( checkWindLimit )
+ {
+ maxWind = 0.9 * Fuel_RxIntensity(catalog,model);
+ if ( effectiveWind > maxWind )
+ {
+ phiEw = (maxWind < Smidgen) ? 0. :
+ Fuel_WindK(catalog,model) * pow(maxWind, Fuel_WindB(catalog,model));
+
+ spreadMax = Fuel_Spread0(catalog,model) * (1. + phiEw);
+ effectiveWind = maxWind;
+ windLimit = 1;
+ }
+ }
+
+ /* Determine fire ellipse parameters from the effective wind speed. */
+ /* = 1. + 0.25 * (Fuel_EffectiveWind(catalog,model) / 88.0); */
+ if ( effectiveWind > Smidgen )
+ {
+ lwRatio = 1. + 0.002840909 * effectiveWind;
+ eccentricity = sqrt(lwRatio * lwRatio - 1.0) / lwRatio;
+ }
+
+ /* Store the results. */
+ Fuel_Aspect(catalog,model) = aspect;
+ Fuel_WindDir(catalog,model) = windDeg;
+ Fuel_PhiEffWind(catalog,model) = phiEw;
+ Fuel_EffectiveWind(catalog,model)= effectiveWind;
+ Fuel_WindLimit(catalog,model) = windLimit;
+ Fuel_SpreadMax(catalog,model) = Fuel_SpreadAny(catalog,model) = spreadMax;
+ Fuel_AzimuthMax(catalog,model) = Fuel_AzimuthAny(catalog,model) = azimuthMax;
+ Fuel_LwRatio(catalog,model) = lwRatio;
+ Fuel_Eccentricity(catalog,model) = eccentricity;
+
+ /* Initialize behavior variables updated by Fire_SpreadAtAzimuth(). */
+ Fuel_ByramsIntensity(catalog,model) = 0.;
+ Fuel_FlameLength(catalog,model) = 0.;
+ Fuel_ScorchHeight(catalog,model) = 0.;
+
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+}
+
+/*
+ *******************************************************************************
+ *
+ * Fire_SpreadAtAzimuth()
+ *
+ * Description
+ * Calculates fire spread rate in a specified direction and optionally
+ * calculates the fireline intensity, flame length, and scorch height
+ * along the fire spread vector.
+ *
+ * Side Effects
+ * The following variables are updated:
+ * Fuel_SpreadAny(catalog,model)
+ * Fuel_AzimuthAny(catalog,model) == azimuth;
+ * Fuel_ByramsIntensity(catalog,model) is updated if FIRE_BYRAMS.
+ * Fuel_FlameLength(catalog,model) is updated if FIRE_FLAME.
+ * Fuel_ScorchHeight(catalog,model) is updated if FIRE_SCORCH.
+ * Notes
+ * The calculations depend upon the most recent calls to
+ * Fire_SpreadNoWindNoSlope() and Fire_SpreadWindSlopeMax() for this model.
+ *
+ * The input azimuth is the degrees clockwise from north.
+ *
+ * Function Returns
+ * FIRE_STATUS_OK or FIRE_STATUS_ERROR.
+ * Return status and error text are stored in the Fire Catalog's buffers.
+ *
+ *******************************************************************************
+ */
+
+int
+Fire_SpreadAtAzimuth ( FuelCatalogPtr catalog, size_t model, double azimuth, size_t which )
+ // FuelCatalogPtr catalog; /* FuelCatalogData instance pointer */
+ // size_t model; /* fuel model number [0-maxModels] */
+ // double azimuth; /* fire spread azimuth (deg from upslope) */
+ // size_t which; /* FIRE_NONE | FIRE_BYRAMS | FIRE_FLAME | FIRE_SCORCH */
+{
+ double dir;
+ double radians;
+ double byrams;
+ double mph;
+ size_t lo, hi, mid, n;
+
+ /* Validate catalog and the fuel model. */
+ assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
+ if ( ! Fire_FuelModelExists(catalog,model) )
+ {
+ sprintf(FuelCat_Error(catalog),
+ "Fire_SpreadAtAzimuth(): el modelo de combustible %d no existe en el cat�logo de combustibles \"%s\".",
+ model, FuelCat_Name(catalog));
+ return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
+ }
+
+ /* Situation 1: no fire or reaction intensity, so no Byrams or flame. */
+ if ( Fuel_SpreadMax(catalog,model) < Smidgen )
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+
+ /* Situation 2: phiEw is zero OR azimuth is in the max spread direction */
+ if ( Fuel_PhiEffWind(catalog,model) < Smidgen
+ || Equal(Fuel_AzimuthMax(catalog,model),azimuth) )
+ {
+ Fuel_SpreadAny(catalog,model) = Fuel_SpreadMax(catalog,model);
+ }
+
+ /* Situation 3: wind and/or slope and azimuth not in max spread direction */
+ else
+ {
+ /* Angle between maximum spread azimuth and requested azimuth. */
+ if ( (dir = fabs(Fuel_AzimuthMax(catalog,model) - azimuth)) > 180. )
+ dir = 360. - dir;
+ radians = DegreesToRadians(dir);
+
+ /* Calculate the fire spread rate in this azimuth. */
+ Fuel_SpreadAny(catalog,model)
+ = Fuel_SpreadMax(catalog,model)
+ * (1. - Fuel_Eccentricity(catalog,model))
+ / (1. - Fuel_Eccentricity(catalog,model) * cos(radians));
+ }
+ Fuel_AzimuthAny(catalog,model) = azimuth;
+
+ /* Additional fire behavior outputs. */
+ if ( which )
+ {
+ /* Must compute Byram's if any of the three are requested. */
+ byrams = Fuel_ResidenceTime(catalog,model)
+ * Fuel_SpreadAny(catalog,model)
+ * Fuel_RxIntensity(catalog,model)
+ / 60.;
+
+ /* Byrams intensity is requested. */
+ if ( which & FIRE_BYRAMS )
+ Fuel_ByramsIntensity(catalog,model) = byrams;
+
+ /* Flame length is requested. */
+ if ( (which & FIRE_FLAME) )
+ {
+ if ( byrams < Smidgen )
+ {
+ Fuel_FlameLength(catalog,model) = 0.;
+ }
+ else
+ {
+ /* Use lookup table if it exists & includes this intensity. */
+ if ( (n = FuelCat_FlameClasses(catalog)) > 0
+ && FuelCat_FlameArray(catalog)[n-1] > byrams )
+ {
+ hi = n-1;
+ lo = 0;
+ do {
+ mid = lo + (hi-lo)/2;
+ if ( FuelCat_FlameArray(catalog)[mid] > byrams )
+ hi = mid;
+ else
+ lo = mid + 1;
+ } while (lo != hi);
+ Fuel_FlameLength(catalog,model) =
+ FuelCat_FlameStep(catalog) * (lo+1);
+ }
+ /* otherwise compute flame length from scratch. */
+ else
+ {
+ Fuel_FlameLength(catalog,model) = 0.45 * pow(byrams, 0.46);
+ }
+ }
+ }
+
+ /* Scorch height is requested. */
+ if ( (which & FIRE_SCORCH) )
+ {
+ if ( byrams < Smidgen )
+ {
+ Fuel_ScorchHeight(catalog,model) = 0.;
+ }
+ else
+ {
+ mph = Fuel_WindSpeed(catalog,model) / 88.;
+ Fuel_ScorchHeight(catalog,model) =
+ pow(byrams, 1.166667) / sqrt(byrams + (mph * mph * mph));
+ /* Fuel_ScorchHeight(catalog,model) *= (63. / (140. - temp_f) ); */
+ }
+ }
+ }
+
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+}
+
+/*
+ *******************************************************************************
+ *
+ * Fire_FlameScorch()
+ *
+ * Description
+ * Calculates the flame length and/or scorch height for the current
+ * Byram's intensity and azimuth (as determined by the most recent
+ * call to Fire_SpreadAtAzimuth()).
+ * Uses the Flame Length Table if it exists.
+ * Offers a method of getting flame length if Fire_SpreadAtAzimuth()
+ * is not calculating it.
+ *
+ * Side Effects
+ * The following variables are updated:
+ * Fuel_FlameLength(catalog,model) is updated.
+ * Fuel_ScorchHeight(catalog,model)
+ * Notes
+ * The calculations depend upon the most recent calls to
+ * Fire_SpreadNoWindNoSlope(), Fire_SpreadWindSlopeMax(), and
+ * Fire_SpreadAtAzimuth() for this model.
+ *
+ * Function Returns
+ * FIRE_STATUS_OK or FIRE_STATUS_ERROR.
+ * Return status and error text are stored in the Fire Catalog's buffers.
+ *
+ *******************************************************************************
+ */
+
+int
+Fire_FlameScorch ( FuelCatalogPtr catalog, size_t model, size_t which )
+ // FuelCatalogPtr catalog; /* FuelCatalogData instance pointer */
+ // size_t model; /* fuel model number [0-maxModels] */
+ // size_t which; /* FIRE_NONE | FIRE_BYRAMS | FIRE_FLAME | FIRE_SCORCH */
+{
+ double byrams;
+ double mph;
+ size_t lo, hi, mid, n;
+
+ /* Validate catalog and the fuel model. */
+ assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
+ if ( ! Fire_FuelModelExists(catalog,model) )
+ {
+ sprintf(FuelCat_Error(catalog),
+ "Fire_FlameScorch(): el modelo de combustible %d no existe en el cat�logo de combustibles \"%s\".",
+ model, FuelCat_Name(catalog));
+ return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
+ }
+
+ byrams = Fuel_ResidenceTime(catalog,model)
+ * Fuel_SpreadAny(catalog,model)
+ * Fuel_RxIntensity(catalog,model)
+ / 60.;
+
+ /* Flame length is requested. */
+ if ( (which & FIRE_FLAME) )
+ {
+ if ( byrams < Smidgen )
+ {
+ Fuel_FlameLength(catalog,model) = 0.;
+ }
+ else
+ {
+ /* Use lookup table if it exists & includes this intensity. */
+ if ( (n = FuelCat_FlameClasses(catalog)) > 0
+ && FuelCat_FlameArray(catalog)[n-1] > byrams )
+ {
+ hi = n-1;
+ lo = 0;
+ do {
+ mid = lo + (hi-lo)/2;
+ if ( FuelCat_FlameArray(catalog)[mid] > byrams )
+ hi = mid;
+ else
+ lo = mid + 1;
+ } while (lo != hi);
+ Fuel_FlameLength(catalog,model) =
+ FuelCat_FlameStep(catalog) * (lo+1);
+ }
+ /* otherwise compute flame length from scratch. */
+ else
+ {
+ Fuel_FlameLength(catalog,model) = 0.45 * pow(byrams, 0.46);
+ }
+ }
+ }
+
+ /* Scorch height is requested. */
+ if ( (which & FIRE_SCORCH) )
+ {
+ if ( byrams < Smidgen )
+ {
+ Fuel_ScorchHeight(catalog,model) = 0.;
+ }
+ else
+ {
+ mph = Fuel_WindSpeed(catalog,model) / 88.;
+ Fuel_ScorchHeight(catalog,model) =
+ pow(byrams, 1.166667) / sqrt(byrams + (mph * mph * mph));
+ /* Fuel_ScorchHeight(catalog,model) *= (63. / (140. - temp_f) ); */
+ }
+ }
+
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+}
+
+/*
+ *******************************************************************************
+ *
+ * Fire_FlameLengthTable()
+ *
+ * Description
+ * Creates a flame length lookup table containing "flameClasses" classes
+ * with each class spanning "flameStep" feet.
+ *
+ * Discussion
+ * Since flame length is strictly an output variable (e.g., it is never
+ * used as the basis for subsequent computations), we can usually afford
+ * to round it to some precision that makes sense to fire managers.
+ * Usually this will be in 1 foot or perhaps 6 inch increments. The call
+ *
+ *
+ * creates a flame length table for flame lengths of 1 through 500 feet.
+ *
+ * Fire_SpreadAtAzimuth() uses the flame table (if one is defined for the
+ * catalog) to avoid using the costly pow() function for highly iterative
+ * flame length calculations, saving a considerable amount of processing
+ * time. Fire_SpreadAtAzimuth() will still use the pow() function to
+ * compute flame length if (1) a flame length table is not defined,
+ * (2) the fireline intensity exceeds the upper limit of the currently
+ * defined flame length table, or (3) the flame length table becomes
+ * undefined by a Fire_FlameLengthTable(catalog, 0, 0.) call.
+ *
+ *
+ * Examples
+ * Fire_FlameLengthTable(catalog, 200, 1.0);
+ * Creates a table for flame lengths of 1 through 200 feet in 1-foot
+ * intervals. Any previously defined flame length table for this
+ * fuel catalog is destroyed.
+ *
+ * Fire_FlameLengthTable(catalog, 500, 0.5);
+ * Creates a table for flame lengths of 0.5 through 250 feet in 6-inch
+ * intervals. ANy previously defined flame length table for this
+ * fuel catalog is destroyed.
+ *
+ * Fire_FlameLengthTable(catalog, 0, 0.);
+ * Destroys any existing flame length table for this catalog, and
+ * forces actual flame length computation using pow() function.
+ *
+ * Side Effects
+ * If a flame length table currently exists, it is destroyed, and the
+ * FuelCat_FlameArray(), FuelCat_FlameClasses(), and
+ * FuelCat_FlameStep() are set to NULL, 0, and 0.0, respectively.
+ *
+ * If fireClasses > 0, allocates a flame length table and fills it with
+ * the fireline intensity associated with the upper limit of each flame
+ * length class. The FuelCat_FlameArray(), FuelCat_FlameClasses(), and
+ * FuelCat_FlameStep() are then updated.
+ *
+ * Function Returns
+ * FIRE_STATUS_OK or FIRE_STATUS_ERROR.
+ * Return status and error text are stored in the Fire Catalog's buffers.
+ *
+ *******************************************************************************
+ */
+
+int
+Fire_FlameLengthTable ( FuelCatalogPtr catalog, size_t flameClasses, double flameStep )
+ // FuelCatalogPtr catalog; /* FuelCatalogData instance pointer */
+ // size_t flameClasses; /* number of flame length classes */
+ // double flameStep; /* flame length step value per class */
+{
+ double power, flame;
+ size_t i;
+
+ /* Validate the catalog. */
+ assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
+
+ /* If a flame table already exists, destroy it. */
+ if ( FuelCat_FlameArray(catalog) )
+ {
+ free(FuelCat_FlameArray(catalog));
+ FuelCat_FlameArray(catalog) = NULL;
+ FuelCat_FlameClasses(catalog) = 0;
+ FuelCat_FlameStep(catalog) = 0.0;
+ }
+
+ /* If flameClasses is zero, simply return. */
+ if ( flameClasses == 0 )
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+
+ /* Otherwise create a new flame table. */
+ if ( (FuelCat_FlameArray(catalog) = (double *)
+ calloc(flameClasses, sizeof(double))) == NULL )
+ {
+ sprintf(FuelCat_Error(catalog),
+ "Fire_FlameLengthTable(): imposible asignar tabla de longitud de llama con %d clases de %f pies.",
+ flameClasses, flameStep);
+ return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
+ }
+
+ /* Fill the array. */
+ power = 1. / .46;
+ for ( i=0; i<flameClasses; i++ )
+ {
+ flame = flameStep * (i+1);
+ FuelCat_FlameArray(catalog)[i] = pow((flame / .45), power);
+ }
+ FuelCat_FlameClasses(catalog) = flameClasses;
+ FuelCat_FlameStep(catalog) = flameStep;
+
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+}
+
+/*
+ *******************************************************************************
+ *
+ * Fire_FuelCatalogCreate()
+ *
+ * Description
+ * Creates a new fuel model catalog capable of holding fuel models with
+ * id's in the range [0..maxModel].
+ * The catalog is filled by subsequent calls to Fire_FuelModelCreate().
+ *
+ * Side Effects
+ * Allocates a new FuelCatalogData structure.
+ * Allocates an error text buffer for the catalog.
+ * Allocates a name for the catalog.
+ * Allocates an array of pointers to FuelData structures (the FuelData
+ * structures themselves are allocated by Fire_FuelModelCreate() and
+ * their pointers are stored here).
+ *
+ * Notes
+ * The FuelCatalog contains a dynamically-allocated array of pointers
+ * to FuelData blocks. These pointers are initially NULL and are
+ * subsequently assigned by Fire_FuelModelCreate(). The array provides
+ * the programmer with a means of directly accessing fuel models via
+ * their model number, which is handy when simulating fire growth.
+ *
+ * Function Returns
+ * While most FireLib functions return a status code, this one returns
+ * a pointer to the new FuelCatalogData on success or NULL if unable
+ * to allocate any of the dynamic structures.
+ *
+ *******************************************************************************
+ */
+
+FuelCatalogPtr
+Fire_FuelCatalogCreate ( char *name, size_t maxModels )
+ // char *name; /* FuelCatalogData instance name */
+ // size_t maxModels; /* maximum modelId allowed in this catalog */
+{
+ FuelCatalogPtr catalog;
+ static char *blank = {""};
+
+ /* Catch a NULL name. */
+ if ( name == NULL )
+ name = blank;
+
+ /* Allocate the FireCatalogData structure. */
+ if ( (catalog = (FuelCatalogPtr) malloc(sizeof(FuelCatalogData))) == NULL )
+ {
+ fprintf(stderr,
+ "Fire_FuelCatalogCreate(): imposible asignar el objeto \"%s\" del cat�logo de combustibles.\n",
+ name);
+ return (NULL);
+ }
+
+ /* Assign the magic cookie right away. */
+ FuelCat_MagicCookie(catalog) = FIRE_CATALOG_MAGIC;
+
+ /* Allocate and store the catalog instance name. */
+ if ( (FuelCat_Name(catalog) = strdup(name)) == NULL )
+ {
+ fprintf(stderr,
+ "Fire_FuelCatalogCreate(): imposible duplicar el nombre \"%s\" del cat�logo de combustibles.\n",
+ name);
+ free(catalog);
+ return (NULL);
+ }
+
+ /* Allocate the FireCatalogData error message buffer. */
+ if ( (FuelCat_Error(catalog) =
+ (char *) calloc(FIRE_ERROR_BUFFER_SIZE, sizeof(char))) == NULL )
+ {
+ fprintf(stderr,
+ "Fire_FuelCatalogCreate(): imposible asignar el bufer de error \"%s\" del cat�logo de combustibles.\n",
+ name);
+ free(FuelCat_Name(catalog));
+ free(catalog);
+ return (NULL);
+ }
+ FuelCat_Status(catalog) = FIRE_STATUS_ERROR;
+
+ /* Allocate a FuelModelPtr array to handle models [0..maxModels]. */
+ maxModels++;
+ FuelCat_MaxModels(catalog) = maxModels;
+ if ( (FuelCat_ModelArray(catalog) = (FuelModelPtr *)
+ calloc(FuelCat_MaxModels(catalog), sizeof(FuelModelPtr))) == NULL )
+ {
+ fprintf(stderr,
+ "Fire_FuelCatalogCreate(): imposible asignar \"%s\" con %d modelos de combustible del cat�logo de combustibles.\n",
+ name, maxModels);
+ free(FuelCat_Error(catalog));
+ free(FuelCat_Name(catalog));
+ free(catalog);
+ return (NULL);
+ }
+
+ /* Initialize variables and return ptr to this instance. */
+ FuelCat_FlameArray(catalog) = NULL;
+ FuelCat_FlameClasses(catalog) = 0;
+ FuelCat_FlameStep(catalog) = 0.0;
+ FuelCat_Status(catalog) = FIRE_STATUS_OK;
+ return (catalog);
+}
+
+/*
+ *******************************************************************************
+ *
+ * Fire_FuelCatalogCreateStandard()
+ *
+ * Description
+ * Creates a new fuel model catalog capable of holding fuel models with
+ * id's in the range [0..maxModel].
+ * The catalog is then filled with the 13 standard fire behavior fuel
+ * models. Other models may be added by subsequent calls to
+ * Fire_FuelModelCreate().
+ *
+ * Side Effects
+ * Allocates a new FuelCatalogData structure.
+ * Fills the catalog with standard fuels models 0-13.
+ *
+ * Function Returns
+ * While most FireLib functions return a status code, this one returns
+ * a pointer to the new FuelCatalogData on success, or NULL if unable
+ * to allocate any of the dynamic structures.
+ *
+ *******************************************************************************
+ */
+
+FuelCatalogPtr
+Fire_FuelCatalogCreateStandard (char *name, size_t maxModels )
+ // char *name; /* FuelCatalogData instance name */
+ // size_t maxModels; /* maximum modelId allowed in this catalog */
+{
+ FuelCatalogPtr catalog;
+ double stot, seff, heat, dens, adjust;
+ size_t m, p;
+
+ /* Fuel model definitions. */
+ typedef struct {
+ char *name; double depth; double mext; size_t maxParticles; char *desc;
+ } StandardModels;
+
+ StandardModels M[14] = {
+ {"NoFuel", 0.1, 0.01, 0, "No Combustible Fuel" },
+ {"NFFL01", 1.0, 0.12, 1, "Short Grass (1 ft)" },
+ {"NFFL02", 1.0, 0.15, 4, "Timber (grass & understory)" },
+ {"NFFL03", 2.5, 0.25, 1, "Tall Grass (2.5 ft)" },
+ {"NFFL04", 6.0, 0.20, 4, "Chaparral (6 ft)" },
+ {"NFFL05", 2.0, 0.20, 3, "Brush (2 ft)" },
+ {"NFFL06", 2.5, 0.25, 3, "Dormant Brush & Hardwood Slash" },
+ {"NFFL07", 2.5, 0.40, 4, "Southern Rough" },
+ {"NFFL08", 0.2, 0.30, 3, "Closed Timber Litter" },
+ {"NFFL09", 0.2, 0.25, 3, "Hardwood Litter" },
+ {"NFFL10", 1.0, 0.25, 4, "Timber (litter & understory)" },
+ {"NFFL11", 1.0, 0.15, 3, "Light Logging Slash" },
+ {"NFFL12", 2.3, 0.20, 3, "Medium Logging Slash" },
+ {"NFFL13", 3.0, 0.25, 3, "Heavy Logging Slash" }
+ };
+
+ /* Fuel particle definitions. */
+ typedef struct {
+ size_t model; size_t type; double load; double savr;
+ } StandardParticle;
+
+ static StandardParticle P[39] = {
+ { 1, FIRE_TYPE_DEAD, 0.0340, 3500.},
+ { 2, FIRE_TYPE_DEAD, 0.0920, 3000.},
+ { 2, FIRE_TYPE_DEAD, 0.0460, 109.},
+ { 2, FIRE_TYPE_DEAD, 0.0230, 30.},
+ { 2, FIRE_TYPE_HERB, 0.0230, 1500.},
+ { 3, FIRE_TYPE_DEAD, 0.1380, 1500.},
+ { 4, FIRE_TYPE_DEAD, 0.2300, 2000.},
+ { 4, FIRE_TYPE_DEAD, 0.1840, 109.},
+ { 4, FIRE_TYPE_DEAD, 0.0920, 30.},
+ { 4, FIRE_TYPE_WOOD, 0.2300, 1500.},
+ { 5, FIRE_TYPE_DEAD, 0.0460, 2000.},
+ { 5, FIRE_TYPE_DEAD, 0.0230, 109.},
+ { 5, FIRE_TYPE_WOOD, 0.0920, 1500.},
+ { 6, FIRE_TYPE_DEAD, 0.0690, 1750.},
+ { 6, FIRE_TYPE_DEAD, 0.1150, 109.},
+ { 6, FIRE_TYPE_DEAD, 0.0920, 30.},
+ { 7, FIRE_TYPE_DEAD, 0.0520, 1750.},
+ { 7, FIRE_TYPE_DEAD, 0.0860, 109.},
+ { 7, FIRE_TYPE_DEAD, 0.0690, 30.},
+ { 7, FIRE_TYPE_WOOD, 0.0170, 1550.},
+ { 8, FIRE_TYPE_DEAD, 0.0690, 2000.},
+ { 8, FIRE_TYPE_DEAD, 0.0460, 109.},
+ { 8, FIRE_TYPE_DEAD, 0.1150, 30.},
+ { 9, FIRE_TYPE_DEAD, 0.1340, 2500.},
+ { 9, FIRE_TYPE_DEAD, 0.0190, 109.},
+ { 9, FIRE_TYPE_DEAD, 0.0070, 30.},
+ {10, FIRE_TYPE_DEAD, 0.1380, 2000.},
+ {10, FIRE_TYPE_DEAD, 0.0920, 109.},
+ {10, FIRE_TYPE_DEAD, 0.2300, 30.},
+ {10, FIRE_TYPE_WOOD, 0.0920, 1500.},
+ {11, FIRE_TYPE_DEAD, 0.0690, 1500.},
+ {11, FIRE_TYPE_DEAD, 0.2070, 109.},
+ {11, FIRE_TYPE_DEAD, 0.2530, 30.},
+ {12, FIRE_TYPE_DEAD, 0.1840, 1500.},
+ {12, FIRE_TYPE_DEAD, 0.6440, 109.},
+ {12, FIRE_TYPE_DEAD, 0.7590, 30.},
+ {13, FIRE_TYPE_DEAD, 0.3220, 1500.},
+ {13, FIRE_TYPE_DEAD, 1.0580, 109.},
+ {13, FIRE_TYPE_DEAD, 1.2880, 30.},
+ };
+
+ /* First, create the catalog. */
+ if ( maxModels < 13 )
+ maxModels = 13;
+ if ( (catalog = Fire_FuelCatalogCreate(name, maxModels)) == NULL )
+ return (NULL);
+
+ /* Second, create all 14 models. */
+ adjust = 1.0;
+ for ( m=0; m<14; m++ )
+ {
+ if ( Fire_FuelModelCreate(catalog, m, M[m].name, M[m].desc, M[m].depth,
+ M[m].mext, adjust, M[m].maxParticles) != FIRE_STATUS_OK )
+ {
+ fprintf(stderr, "%s\n", FuelCat_Error(catalog));
+ Fire_FuelCatalogDestroy(catalog);
+ return (NULL);
+ }
+ }
+
+ /* Finally, add all the fuel particles. */
+ stot = 0.0555;
+ seff = 0.0100;
+ heat = 8000.0;
+ dens = 32.0;
+ for ( p=0; p<39; p++ )
+ {
+ if ( Fire_FuelParticleAdd(catalog, P[p].model, P[p].type, P[p].load,
+ P[p].savr, dens, heat, stot, seff) != FIRE_STATUS_OK )
+ {
+ fprintf(stderr, "%s\n", FuelCat_Error(catalog));
+ Fire_FuelCatalogDestroy(catalog);
+ return (NULL);
+ }
+ }
+
+ return (catalog);
+}
+
+/*
+ *******************************************************************************
+ *
+ * Fire_FuelCatalogDestroy()
+ *
+ * Description
+ * Destroys the fuel catalog and all its associated models and particles.
+ *
+ * Side Effects
+ * Destroys all FuelData instances belonging to the catalog.
+ * Frees the array of pointers to FuelData structures.
+ * Frees the catalog name.
+ * Frees the catalog error text buffer.
+ * Frees the FuelCatalog instance.
+ *
+ * Function Returns
+ * FIRE_STATUS_OK or FIRE_STATUS_ERROR.
+ * Return status and error text are stored in the Fire Catalog's buffers.
+ *
+ *******************************************************************************
+ */
+
+int
+Fire_FuelCatalogDestroy ( FuelCatalogPtr catalog )
+ // FuelCatalogPtr catalog; /* FuelCatalogData instance to destroy. */
+{
+ size_t model;
+
+ /* Validate the catalog. */
+ assert(catalog!=NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
+
+ /* First destroy all the fuel models in this catalog. */
+ /* The free the catalog's array of FuelData pointers. */
+ if ( FuelCat_ModelArray(catalog) )
+ {
+ for ( model=0; model <= FuelCat_MaxModels(catalog); model++ )
+ {
+ if ( FuelCat_ModelPtr(catalog,model) )
+ Fire_FuelModelDestroy(catalog, model);
+ }
+ free(FuelCat_ModelArray(catalog));
+ FuelCat_ModelArray(catalog) = NULL;
+ }
+
+ /* Next destroy the flame length table. */
+ if ( FuelCat_FlameArray(catalog) )
+ {
+ free(FuelCat_FlameArray(catalog));
+ FuelCat_FlameArray(catalog) = NULL;
+ FuelCat_FlameClasses(catalog) = 0;
+ FuelCat_FlameStep(catalog) = 0.0;
+ }
+
+ /* Then free the name and error buffer for this FuelCatalogData instance. */
+ if ( FuelCat_Error(catalog) )
+ {
+ free(FuelCat_Error(catalog));
+ FuelCat_Error(catalog) = NULL;
+ }
+
+ if ( FuelCat_Name(catalog) )
+ {
+ free(FuelCat_Name(catalog));
+ FuelCat_Name(catalog) = NULL;
+ }
+
+ /* Finally,free the FuelCatalogData instance and return. */
+ free(catalog);
+
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+}
+
+/*
+ *******************************************************************************
+ *
+ * Fire_FuelModelCreate()
+ *
+ * Description
+ * Creates a new fuel model able to hold maxParticles fuel particles.
+ * Fuel particles are subsequently added by Fire_FuelParticleAdd().
+ *
+ * Side Effects
+ * Any existing fuel model with modelId in the Fuel Catalog is destroyed.
+ * Allocates the fuel model's FuelData block.
+ * Allocates the fuel model's name string.
+ * Allocates the fuel model's description string.
+ * Allocates the fuel model's fuel particle pointer array of maxParticles
+ * (the FuelParticleData blocks are actually allocated within
+ * Fire_FuelparticleAdd() and thier pointers stored in this array).
+ * The fuel model's address is stored in the fuel catalog's pointer array.
+ *
+ * Function Returns
+ * FIRE_STATUS_OK or FIRE_STATUS_ERROR.
+ * Return status and error text are stored in the Fire Catalog's buffers.
+ *
+ *******************************************************************************
+ */
+
+int
+Fire_FuelModelCreate (FuelCatalogPtr catalog, size_t model, char *name, char *desc, double depth, double mext, double adjust, size_t maxParticles)
+ // FuelCatalogPtr catalog; /* FuelCatalogData instance */
+ // size_t model; /* fuel model number [0-maxModels] */
+ // char *name; /* short name */
+ // char *desc; /* longer description */
+ // double depth; /* bed depth (ft) */
+ // double mext; /* moisture of extinction (dl) */
+ // double adjust; /* spread adjustment factor (dl) */
+ // size_t maxParticles; /* maximum number of fuel model particles */
+{
+ static char *blank = {""};
+ size_t particle;
+
+ /* Validate the catalog. */
+ assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
+
+ /* Make sure model id is within range. */
+ if ( model > FuelCat_MaxModels(catalog) )
+ {
+ sprintf(FuelCat_Error(catalog),
+ "Fire_FuelModelCreate(): fuel model \"%s\" number %d exceeds fuel catalog \"%s\" range [0..%d].",
+ name, model, FuelCat_Name(catalog), FuelCat_MaxModels(catalog));
+ return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
+ }
+
+ /* Validate depth and mext. */
+ if ( depth < Smidgen )
+ {
+ sprintf(FuelCat_Error(catalog),
+ "Fire_FuelModelCreate(): el modelo de combustible \"%s\" n�mero %d de ancho %5.4f es demasiado peque�o.",
+ name, model, depth);
+ return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
+ }
+
+ if ( mext < Smidgen )
+ {
+ sprintf(FuelCat_Error(catalog),
+ "Fire_FuelModelCreate(): el modelo de combustible \"%s\" n�mero %d de humedad de extinci�n %5.4f es demasiado peque�o.",
+ name, model, mext);
+ return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
+ }
+
+ /* If this model already exists, delete it. */
+ if ( FuelCat_ModelPtr(catalog,model) )
+ Fire_FuelModelDestroy(catalog, model);
+
+ /* Allocate the model's FuelData structure. */
+ if ( maxParticles < 1 )
+ maxParticles = 1;
+ if ( (FuelCat_ModelPtr(catalog,model) =
+ (FuelModelPtr) calloc(1, sizeof(FuelModelData))) == NULL
+ || (Fuel_ParticleArray(catalog,model) =
+ (PartPtr *) calloc(maxParticles, sizeof(PartPtr))) == NULL )
+ {
+ Fire_FuelModelDestroy(catalog, model);
+ sprintf(FuelCat_Error(catalog),
+ "Fire_FuelModelCreate(): imposible asignar el modelos de combustible \"%s\" n�mero %d para el cat�logo de combustibles \"%s\".",
+ name, model, FuelCat_Name(catalog));
+ return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
+ }
+
+ /* Catch NULL names and descriptions. */
+ if ( name == NULL )
+ name = blank;
+ if ( desc == NULL )
+ desc = blank;
+
+ /* Store remaining attributes. */
+ Fuel_Model(catalog,model) = model;
+ Fuel_Depth(catalog,model) = depth;
+ Fuel_Mext(catalog,model) = mext;
+ Fuel_SpreadAdjustment(catalog,model) = adjust;
+ Fuel_Name(catalog,model) = strdup(name);
+ Fuel_Desc(catalog,model) = strdup(desc);
+ Fuel_CombustionFlag(catalog,model) = 0;
+ Fuel_MaxParticles(catalog,model) = maxParticles;
+ Fuel_Particles(catalog,model) = 0;
+ for ( particle=0; particle<Fuel_MaxParticles(catalog,model); particle++ )
+ Fuel_ParticlePtr(catalog,model,particle) = NULL;
+
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+}
+
+/*
+ *******************************************************************************
+ *
+ * Fire_FuelModelDestroy()
+ *
+ * Description
+ * Deletes the specified fuel model.
+ * Note: this is one of only 3 functions that use the modelId instead
+ * of a FuelData pointer to identify the model.
+ *
+ * Side Effects
+ * Free's all fuel particles added to the fuel model.
+ * Free's the fuel particle pointer array.
+ * Free's the fuel model's name.
+ * Free's the fuel model's description.
+ * Free's the fuel model's FuelData block.
+ * Sets the Fuel Catalog's pointer for this fuel model to NULL.
+ *
+ * Function Returns
+ * FIRE_STATUS_OK or FIRE_STATUS_ERROR.
+ * Return status and error text are stored in the Fire Catalog's buffers.
+ *
+ *******************************************************************************
+ */
+
+int
+Fire_FuelModelDestroy ( FuelCatalogPtr catalog, size_t model )
+ // FuelCatalogPtr catalog; /* FuelCatalogData instance pointer */
+ // size_t model; /* fuel model id number [0-maxModels] */
+{
+ size_t particle;
+
+ /* Validate the catalog. */
+ assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
+
+ /* Make sure model id is within range and exists. */
+ if ( ! Fire_FuelModelExists(catalog,model) )
+ {
+ sprintf(FuelCat_Error(catalog),
+ "Fire_FuelModelDestroy(): el modelo de combustible %d no existe en el cat�logo de combustibles \"%s\".",
+ model, FuelCat_Name(catalog));
+ return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
+ }
+
+ /* Free all the fuel model particles and their pointer array. */
+ if ( Fuel_ParticleArray(catalog,model) )
+ {
+ for (particle=0; particle<Fuel_MaxParticles(catalog,model); particle++)
+ {
+ if ( Fuel_ParticlePtr(catalog,model,particle) )
+ {
+ free(Fuel_ParticlePtr(catalog,model,particle));
+ Fuel_ParticlePtr(catalog,model,particle) = NULL;
+ }
+ }
+ free(Fuel_ParticleArray(catalog,model));
+ Fuel_ParticleArray(catalog,model) = NULL;
+ }
+
+ /* Free the fuel model name and description. */
+ if ( Fuel_Name(catalog,model) )
+ {
+ free(Fuel_Name(catalog,model));
+ Fuel_Name(catalog,model) = NULL;
+ }
+
+ if ( Fuel_Desc(catalog,model) )
+ {
+ free(Fuel_Desc(catalog,model));
+ Fuel_Desc(catalog,model) = NULL;
+ }
+
+ /* Now free the FuelData instance and reset its catalog entry. */
+ free(FuelCat_ModelPtr(catalog,model));
+ FuelCat_ModelPtr(catalog,model) = NULL;
+
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+}
+
+/*
+ *******************************************************************************
+ *
+ * Fire_FuelModelExists()
+ *
+ * Description
+ * Performs a sanity check to make sure the catalog pointer is valid
+ * and the fuel model number is within range and exists.
+ *
+ * Side Effects
+ * None.
+ *
+ * Function Returns
+ * 1 if "model" exists, 0 if it is undefined.
+ *
+ *******************************************************************************
+ */
+
+int
+Fire_FuelModelExists ( FuelCatalogPtr catalog, size_t model )
+ // FuelCatalogPtr catalog; /* FuelCatalogData instance pointer */
+ // size_t model; /* fuel model id number [0-maxModels] */
+{
+ /* Validate the model number. */
+ if ( model > FuelCat_MaxModels(catalog)
+ || ! FuelCat_ModelPtr(catalog,model) )
+ return (int) 0;
+
+ return (int) 1;
+}
+
+/*
+ *******************************************************************************
+ *
+ * Fire_FuelParticleAdd()
+ *
+ * Description
+ * Adds a fuel particle to the specified fuel model.
+ *
+ * Side Effects
+ * A FuelParticleData is allocated and appended to the model's array.
+ * The fuel model's particle counter is incremented.
+ * The fuel model's combustion flag set to 0.
+ *
+ * Function Returns
+ * FIRE_STATUS_OK or FIRE_STATUS_ERROR.
+ * Return status and error text are stored in the Fire Catalog's buffers.
+ *
+ *******************************************************************************
+ */
+
+int
+Fire_FuelParticleAdd ( FuelCatalogPtr catalog, size_t model, size_t type, double load, double savr, double dens, double heat, double stot, double seff )
+ // FuelCatalogPtr catalog; /* FuelCatalogData instance pointer */
+ // size_t model; /* fuel model id number [0-maxModels] */
+ // size_t type; /* FIRE_TYPE_DEAD, _TYPE_HERB, or _TYPE_WOOD */
+ // double load; /* fuel load (lbs/ft2) */
+ // double savr; /* surface-area-to-volume ratio (ft2/ft3) */
+ // double dens; /* density (lbs/ft3) */
+ // double heat; /* heat of combustion (btus/lb) */
+ // double stot; /* total silica content (lb/lb) */
+ // double seff; /* effective silica content (lb/lb) */
+{
+ static double Size_boundary[FIRE_SIZE_CLASSES] =
+ {1200., 192., 96., 48., 16., 0.};
+ size_t particle, size;
+
+ /* Validate the catalog. */
+ assert(catalog!= NULL && FuelCat_MagicCookie(catalog)==FIRE_CATALOG_MAGIC);
+
+ /* Validate the fuel model. */
+ if ( ! Fire_FuelModelExists(catalog,model) )
+ {
+ sprintf(FuelCat_Error(catalog),
+ "Fire_FuelParticleAdd(): el modelo de combustible %d no existe en el cat�logo de combustibles \"%s\".",
+ model, FuelCat_Name(catalog));
+ return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
+ }
+
+ /* Validate the "type" parameter. */
+ if ( type != FIRE_TYPE_DEAD
+ && type != FIRE_TYPE_HERB
+ && type != FIRE_TYPE_WOOD )
+ {
+ sprintf(FuelCat_Error(catalog),
+ "Fire_FuelParticleAdd(): el modelo de combustible %d de tipo de valor (arg #3) no es FIRE_TYPE_DEAD, FIRE_TYPE_HERB, o FIRE_TYPE_WOOD.",
+ model);
+ return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
+ }
+
+ /* Allocate a new FuelParticle */
+ particle = Fuel_Particles(catalog,model);
+ if ( (Fuel_ParticlePtr(catalog,model,particle) =
+ (PartPtr) calloc(1, sizeof(FuelParticleData))) == NULL )
+ {
+ sprintf(FuelCat_Error(catalog),
+ "Fire_FuelParticleAdd(): imposible asignar la part�cula de combustible al modelo de combustible \"%s\" n�mero %d en el cat�logo de combustibles \"%s\".",
+ Fuel_Name(catalog,model), model, FuelCat_Name(catalog));
+ return (FuelCat_Status(catalog) = FIRE_STATUS_ERROR);
+ }
+
+ /* Store the input particle attributes. */
+ Fuel_Type(catalog,model,particle) = type;
+ Fuel_Load(catalog,model,particle) = load;
+ Fuel_Savr(catalog,model,particle) = savr;
+ Fuel_Density(catalog,model,particle) = dens;
+ Fuel_Heat(catalog,model,particle) = heat;
+ Fuel_SiTotal(catalog,model,particle) = stot;
+ Fuel_SiEffective(catalog,model,particle)= seff;
+
+ /* Fuel life category. */
+ Fuel_Live(catalog,model,particle) =
+ (type==FIRE_TYPE_DEAD) ? FIRE_LIFE_DEAD : FIRE_LIFE_LIVE;
+
+ /* Fuel particle surface area. */
+ Fuel_SurfaceArea(catalog,model,particle) =
+ (dens > Smidgen) ? load * savr / dens : 0.;
+
+ /* Particle SAVR exponent factor. */
+ Fuel_SigmaFactor(catalog,model,particle) =
+ (savr > Smidgen) ? exp(-138. / savr) : 0.;
+
+ /* Particle size class. */
+ for ( size=0; savr < Size_boundary[size]; size++ )
+ /* NOTHING */ ;
+ Fuel_SizeClass(catalog,model,particle) = size;
+
+ /* Initialize particle attributes that are bed & environ dependent. */
+ Fuel_AreaWtg(catalog,model,particle) = 0.;
+ Fuel_SizeAreaWtg(catalog,model,particle) = 0.;
+ Fuel_Moisture(catalog,model,particle) = 0.;
+
+ /* Increment the fuel model's particle counter and reset it flag. */
+ Fuel_Particles(catalog,model)++;
+ Fuel_CombustionFlag(catalog,model) = 0;
+
+ return (FuelCat_Status(catalog) = FIRE_STATUS_OK);
+}
+
+/*
+ *******************************************************************************
+ * End of fireLib.c
+ *******************************************************************************
+ */
diff --git a/src/modules/simulation/sim_fire_spreading/fireLib.h b/src/modules/simulation/sim_fire_spreading/fireLib.h
new file mode 100644
index 0000000..8effef1
--- /dev/null
+++ b/src/modules/simulation/sim_fire_spreading/fireLib.h
@@ -0,0 +1,551 @@
+/**********************************************************
+ * Version $Id: fireLib.h 911 2011-02-14 16:38:15Z reklov_w $
+ *********************************************************/
+/*
+ *******************************************************************************
+ *
+ * fireLib.h
+ *
+ * Description
+ * Library of BEHAVE (Andrews 1986) fire behavior algorithms
+ * encapsulated and optimized for fire behavior simulation.
+ *
+ * Legalities
+ * Copyright (c) 1996 Collin D. Bevins.
+ * See the file "license.txt" for information on usage and
+ * redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
+ *
+ * Description
+ * This header file describes the externally-visible facilities of
+ * the Fire Behavior Library C API.
+ *
+ * This file really needs to be split into public and private portions.
+ *
+ * History
+ * 1996/09/04 Version 1.0.0 release.
+ * 1999/03/05 Fixed NNFL07 live SAVR from 1500 to 1550.
+ *
+ *******************************************************************************
+ */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+#include <assert.h>
+
+#ifndef _FIRE_LIB
+#define _FIRE_LIB 1
+
+#define FIRELIB_VERSION "1.0"
+#define FIRELIB_MAJOR_VERSION 1
+#define FIRELIB_MINOR_VERSION 0
+#define FIRELIB_PATCH_LEVEL 1
+
+/*
+ *------------------------------------------------------------------------------
+ * Definitions that allow this header file to be used either with or
+ * without ANSI C features like function prototypes.
+ *------------------------------------------------------------------------------
+ */
+
+#undef _ANSI_ARGS_
+#undef CONST
+#if ((defined(__STDC__) || defined(SABER)) && !defined(NO_PROTOTYPE)) || defined(__cplusplus)
+# define _USING_PROTOTYPES_ 1
+# define _ANSI_ARGS_(x) x
+# define CONST const
+# ifdef __cplusplus
+# define VARARGS(first) (first, ...)
+# else
+# define VARARGS(first) ()
+# endif
+#else
+# define _ANSI_ARGS_(x) ()
+# define CONST
+#endif
+
+#ifdef __cplusplus
+# define EXTERN extern "C"
+#else
+# define EXTERN extern
+#endif
+
+/*
+ *------------------------------------------------------------------------------
+ * Macro to use instead of "void" for arguments that must have type "void *"
+ * in ANSI C; maps them to type "char *" in non-ANSI systems.
+ *------------------------------------------------------------------------------
+ */
+
+#ifndef VOID
+# ifdef __STDC__
+# define VOID void
+# else
+# define VOID char
+# endif
+#endif
+
+/*
+ *------------------------------------------------------------------------------
+ * Macro pseudo functions.
+ *------------------------------------------------------------------------------
+ */
+
+#define Smidgen (0.000001)
+#define DegreesToRadians(x) ((x)*0.017453293)
+#define RadiansToDegrees(x) ((x)*57.29577951)
+#define IsZero(x) (fabs(x)<Smidgen)
+#define Equal(x,y) (fabs((x)-(y))<Smidgen)
+
+/*
+ *------------------------------------------------------------------------------
+ * Firelib return status codes.
+ *------------------------------------------------------------------------------
+ */
+
+#define FIRE_STATUS_OK (0)
+#define FIRE_STATUS_ERROR (-1)
+#define FIRE_STATUS_EOF (1)
+
+/*
+ *------------------------------------------------------------------------------
+ * Fuel moisture and mass weighting classes.
+ *------------------------------------------------------------------------------
+ */
+
+#define FIRE_LIFE_CATS (2) /* Number of fuel particle life categories */
+#define FIRE_LIFE_DEAD (0)
+#define FIRE_LIFE_LIVE (1)
+
+#define FIRE_SIZE_CLASSES (6) /* Number of mass weighting classes. */
+
+#define FIRE_MCLASSES (6) /* Number of fuel moisture classes. */
+#define FIRE_MCLASS_1HR (0)
+#define FIRE_MCLASS_10HR (1)
+#define FIRE_MCLASS_100HR (2)
+#define FIRE_MCLASS_1000HR (3)
+#define FIRE_MCLASS_HERB (4)
+#define FIRE_MCLASS_WOOD (5)
+
+/*
+ *------------------------------------------------------------------------------
+ * FuelParticleData structure: fuel particle input and intermediate attributes.
+ *------------------------------------------------------------------------------
+ */
+
+typedef struct fuelParticleDataStruct
+{
+ /* INPUT */
+ double load; /* fuel loading (lb/sqft) */
+ double savr; /* surface area-to-volume ratio (1/ft) */
+ double dens; /* particle density (lb/cuft) */
+ double heat; /* heat of combustion (BTU/lb) */
+ double stot; /* total silica content (fraction odw) */
+ double seff; /* effective silica content (fraction odw) */
+ /* PARTICLE_DEPENDENT */
+ double area; /* surface area */
+ double sigma; /* exp(-138./sigma) (dl) */
+ /* MODEL-DEPENDENT */
+ double awtg; /* surface area derived weighting factor (dl) */
+ double gwtg; /* size class area weighting factor */
+ /* ENVIRONMENT-DEPENDENT */
+ double mois; /* particle moisture content (fraction) */
+ size_t live; /* life category 0=dead, 1=live */
+ size_t type; /* type category 0=dead, 1=herb, 2=live woody */
+ size_t sizeClass; /* fuel moisture size class */
+} FuelParticleData, *FuelParticlePtr, *PartPtr;
+
+#define FIRE_TYPE_DEAD (1)
+#define FIRE_TYPE_HERB (2)
+#define FIRE_TYPE_WOOD (3)
+
+/* FuelParticleData structure access macros. */
+
+#define Fuel_Live(catalog,model,particle) \
+ ((catalog)->modelPtr[(model)]->partPtr[(particle)]->live)
+
+#define Fuel_Type(catalog,model,particle) \
+ ((catalog)->modelPtr[(model)]->partPtr[(particle)]->type)
+
+#define Fuel_SizeClass(catalog,model,particle) \
+ ((catalog)->modelPtr[(model)]->partPtr[(particle)]->sizeClass)
+
+#define Fuel_Load(catalog,model,particle) \
+ ((catalog)->modelPtr[(model)]->partPtr[(particle)]->load)
+
+#define Fuel_Savr(catalog,model,particle) \
+ ((catalog)->modelPtr[(model)]->partPtr[(particle)]->savr)
+
+#define Fuel_Heat(catalog,model,particle) \
+ ((catalog)->modelPtr[(model)]->partPtr[(particle)]->heat)
+
+#define Fuel_Density(catalog,model,particle) \
+ ((catalog)->modelPtr[(model)]->partPtr[(particle)]->dens)
+
+#define Fuel_SiTotal(catalog,model,particle) \
+ ((catalog)->modelPtr[(model)]->partPtr[(particle)]->stot)
+
+#define Fuel_SiEffective(catalog,model,particle) \
+ ((catalog)->modelPtr[(model)]->partPtr[(particle)]->seff)
+
+#define Fuel_SurfaceArea(catalog,model,particle) \
+ ((catalog)->modelPtr[(model)]->partPtr[(particle)]->area)
+
+#define Fuel_AreaWtg(catalog,model,particle) \
+ ((catalog)->modelPtr[(model)]->partPtr[(particle)]->awtg)
+
+#define Fuel_SizeAreaWtg(catalog,model,particle) \
+ ((catalog)->modelPtr[(model)]->partPtr[(particle)]->gwtg)
+
+#define Fuel_SigmaFactor(catalog,model,particle) \
+ ((catalog)->modelPtr[(model)]->partPtr[(particle)]->sigma)
+
+#define Fuel_Moisture(catalog,model,particle) \
+ ((catalog)->modelPtr[(model)]->partPtr[(particle)]->mois)
+
+/*
+ *------------------------------------------------------------------------------
+ * FuelModelData structure: fuel model bed input attributes.
+ *------------------------------------------------------------------------------
+ */
+
+typedef struct fuelModelDataStruct
+{
+ /* Input variables. */
+ size_t modelId; /* fuel model number */
+ size_t combustion; /* 0 if combustion not yet calculated */
+ size_t maxParticles; /* maximum number of FuelParticles */
+ size_t particles; /* current number of FuelParticles */
+ PartPtr *partPtr; /* array of pointers to Fuel Particles */
+ char *name; /* fuel model short name */
+ char *desc; /* fuel model description text */
+ char *reserved1; /* used for alignment */
+ double depth; /* fuel bed depth (ft) */
+ double mext; /* dead fuel extinction moisture (fraction) */
+ double adjust; /* spread rate adjustment factor (dl) */
+ /* Combustion intermediates. */
+ double awtg[2]; /* dead & live fuel area weighting factors */
+ double rxFactor[2]; /* dead and live fuel rx factors */
+ double fineDead; /* fine dead fuel ratio */
+ double liveFactor; /* live fuel moisture extinction factor */
+ double rhob; /* fuel bed bulk density */
+ double taur; /* residence time (min) */
+ double propFlux; /* propagating flux ratio */
+ double slopeK; /* slope parameter 'k' */
+ double windB; /* wind parameter 'b' */
+ double windE; /* wind parameter (ratio**e/c) */
+ double windK; /* wind parameter (c * ratio**-e) */
+ /* Current environment. */
+ double moisture[FIRE_MCLASSES]; /* array of fuel moistures (fraction odw) */
+ double windFpm; /* wind speed (ft/min) */
+ double windDeg; /* wind vector (degrees from upslope) */
+ double slope; /* slope (rise/reach) */
+ double aspect; /* aspect (downslope) azimuth (compass degs) */
+ /* Updated by Fire_SpreadNoWindNoSlope() */
+ double rxInt; /* reaction intensity (BTU/sqft/min) */
+ double spread0; /* no-wind, no-slope spread rate (ft/min) */
+ double hpua; /* heat per unit area (BTU/sqft) */
+ /* Updated by Fire_SpreadWindSlopeMax() */
+ double spreadMax; /* spread in direction of max spread (ft/min) */
+ double azimuthMax; /* direction of maximum spread (degrees) */
+ double effWind; /* effective windspeed */
+ double lwRatio; /* length-to-width ratio for eff windspeed */
+ double eccentricity; /* eccentricity of ellipse for eff windspeed */
+ double phiW; /* wind factor */
+ double phiS; /* slope factor */
+ double phiEw; /* combined wind-slope factor */
+ size_t wLimit; /* wind limit 0=not reached, 1=reached */
+ size_t reserved2; /* used for alignment */
+ /* Updated by Fire_SpreadAtAzimuth() */
+ double spreadAny; /* spread rate at arbitrary azimuth (ft/min) */
+ double azimuthAny; /* direction of arbitrary spread (degrees) */
+ double byrams; /* fireline intensity (BTU/ft/s) */
+ double flame; /* flame length (ft) */
+ double scorch; /* scorch height (ft) */
+} FuelModelData, *FuelModelPtr;
+
+/* Fuel model input variable macros. */
+#define Fuel_Model(catalog,model) \
+ ((catalog)->modelPtr[(model)]->modelId)
+
+#define Fuel_Name(catalog,model) \
+ ((catalog)->modelPtr[(model)]->name)
+
+#define Fuel_Desc(catalog,model) \
+ ((catalog)->modelPtr[(model)]->desc)
+
+#define Fuel_Depth(catalog,model) \
+ ((catalog)->modelPtr[(model)]->depth)
+
+#define Fuel_Mext(catalog,model) \
+ ((catalog)->modelPtr[(model)]->mext)
+
+#define Fuel_SpreadAdjustment(catalog,model) \
+ ((catalog)->modelPtr[(model)]->adjust)
+
+#define Fuel_CombustionFlag(catalog,model) \
+ ((catalog)->modelPtr[(model)]->combustion)
+
+#define Fuel_MaxParticles(catalog,model) \
+ ((catalog)->modelPtr[(model)]->maxParticles)
+
+#define Fuel_Particles(catalog,model) \
+ ((catalog)->modelPtr[(model)]->particles)
+
+#define Fuel_ParticleArray(catalog,model) \
+ ((catalog)->modelPtr[(model)]->partPtr)
+
+#define Fuel_ParticlePtr(catalog,model,particle) \
+ ((catalog)->modelPtr[(model)]->partPtr[(particle)])
+
+/* Fuel model combustion intermediates macros. */
+#define Fuel_LifeAreaWtg(catalog,model,life) \
+ ((catalog)->modelPtr[(model)]->awtg[(life)])
+
+#define Fuel_LifeRxFactor(catalog,model,life) \
+ ((catalog)->modelPtr[(model)]->rxFactor[(life)])
+
+#define Fuel_FineDead(catalog,model) \
+ ((catalog)->modelPtr[(model)]->fineDead)
+
+#define Fuel_LiveMextFactor(catalog,model) \
+ ((catalog)->modelPtr[(model)]->liveFactor)
+
+#define Fuel_BulkDensity(catalog,model) \
+ ((catalog)->modelPtr[(model)]->rhob)
+
+#define Fuel_ResidenceTime(catalog,model) \
+ ((catalog)->modelPtr[(model)]->taur)
+
+#define Fuel_PropFlux(catalog,model) \
+ ((catalog)->modelPtr[(model)]->propFlux)
+
+#define Fuel_SlopeK(catalog,model) \
+ ((catalog)->modelPtr[(model)]->slopeK)
+
+#define Fuel_WindB(catalog,model) \
+ ((catalog)->modelPtr[(model)]->windB)
+
+#define Fuel_WindE(catalog,model) \
+ ((catalog)->modelPtr[(model)]->windE)
+
+#define Fuel_WindK(catalog,model) \
+ ((catalog)->modelPtr[(model)]->windK)
+
+/* Fuel model fire behavior variable macros. */
+#define Fuel_RxIntensity(catalog,model) \
+ ((catalog)->modelPtr[(model)]->rxInt)
+
+#define Fuel_Spread0(catalog,model) \
+ ((catalog)->modelPtr[(model)]->spread0)
+
+#define Fuel_HeatPerUnitArea(catalog,model) \
+ ((catalog)->modelPtr[(model)]->hpua)
+
+#define Fuel_SpreadMax(catalog,model) \
+ ((catalog)->modelPtr[(model)]->spreadMax)
+
+#define Fuel_AzimuthMax(catalog,model) \
+ ((catalog)->modelPtr[(model)]->azimuthMax)
+
+#define Fuel_SpreadAny(catalog,model) \
+ ((catalog)->modelPtr[(model)]->spreadAny)
+
+#define Fuel_AzimuthAny(catalog,model) \
+ ((catalog)->modelPtr[(model)]->azimuthAny)
+
+#define Fuel_EffectiveWind(catalog,model) \
+ ((catalog)->modelPtr[(model)]->effWind)
+
+#define Fuel_LwRatio(catalog,model) \
+ ((catalog)->modelPtr[(model)]->lwRatio)
+
+#define Fuel_Eccentricity(catalog,model) \
+ ((catalog)->modelPtr[(model)]->eccentricity)
+
+#define Fuel_PhiWind(catalog,model) \
+ ((catalog)->modelPtr[(model)]->phiW)
+
+#define Fuel_PhiSlope(catalog,model) \
+ ((catalog)->modelPtr[(model)]->phiS)
+
+#define Fuel_PhiEffWind(catalog,model) \
+ ((catalog)->modelPtr[(model)]->phiEw)
+
+#define Fuel_WindLimit(catalog,model) \
+ ((catalog)->modelPtr[(model)]->wLimit)
+
+#define Fuel_ByramsIntensity(catalog,model) \
+ ((catalog)->modelPtr[(model)]->byrams)
+
+#define Fuel_FlameLength(catalog,model) \
+ ((catalog)->modelPtr[(model)]->flame)
+
+#define Fuel_ScorchHeight(catalog,model) \
+ ((catalog)->modelPtr[(model)]->scorch)
+
+/* Fuel model environment variable macros. */
+#define Fuel_EnvMoisture(catalog,model,mclass) \
+ ((catalog)->modelPtr[(model)]->moisture[(mclass)])
+
+#define Fuel_WindSpeed(catalog,model) \
+ ((catalog)->modelPtr[(model)]->windFpm)
+
+#define Fuel_WindDir(catalog,model) \
+ ((catalog)->modelPtr[(model)]->windDeg)
+
+#define Fuel_Slope(catalog,model) \
+ ((catalog)->modelPtr[(model)]->slope)
+
+#define Fuel_Aspect(catalog,model) \
+ ((catalog)->modelPtr[(model)]->aspect)
+
+/*
+ *------------------------------------------------------------------------------
+ * FuelCatData structure; provides a complete fuel catalog.
+ *------------------------------------------------------------------------------
+ */
+
+#define FIRE_CATALOG_MAGIC (19520904L)
+#define FIRE_ERROR_BUFFER_SIZE (1024)
+
+typedef struct fuelCatalogStruct
+{
+ long magicCookie; /* magic cookie for sanity checking */
+ int status; /* return status of most recent call */
+ size_t maxModels; /* maximum number of models in this catalog */
+ size_t flameClasses; /* size of the flame length array */
+ char *name; /* name for this catalog instance */
+ char *error; /* error message buffer */
+ FuelModelPtr *modelPtr; /* array of ModelPtr[maxModels+1] */
+ double *flamePtr; /* flame length lookup array */
+ double flameStep; /* size of each flame length table class (ft) */
+} FuelCatalogData, *FuelCatalogPtr;
+
+#define FuelCat_MagicCookie(catalog) (catalog->magicCookie)
+#define FuelCat_MaxModels(catalog) (catalog->maxModels)
+#define FuelCat_Status(catalog) (catalog->status)
+#define FuelCat_FlameClasses(catalog) (catalog->flameClasses)
+#define FuelCat_FlameStep(catalog) (catalog->flameStep)
+#define FuelCat_FlameArray(catalog) (catalog->flamePtr)
+#define FuelCat_Name(catalog) (catalog->name)
+#define FuelCat_Error(catalog) (catalog->error)
+#define FuelCat_ModelArray(catalog) (catalog->modelPtr)
+#define FuelCat_ModelPtr(catalog,model) (catalog->modelPtr[model])
+
+/*
+ *------------------------------------------------------------------------------
+ * Function prototypes for fire behavior computations.
+ *------------------------------------------------------------------------------
+ */
+
+#define FIRE_NONE (0)
+#define FIRE_BYRAMS (1)
+#define FIRE_FLAME (2)
+#define FIRE_SCORCH (4)
+
+EXTERN int Fire_FlameScorch _ANSI_ARGS_((
+ FuelCatalogPtr catalog, /* FuelCatalogData instance pointer */
+ size_t model, /* fuel model number [0-maxModels] */
+ size_t doWhich /* FIRE_NONE | FIRE_BYRAMS | FIRE_FLAME | FIRE_SCORCH */
+ )) ;
+
+EXTERN int Fire_FuelCombustion _ANSI_ARGS_((
+ FuelCatalogPtr catalog, /* FuelCatalogData instance pointer */
+ size_t model /* fuel model number [0-maxModels] */
+ )) ;
+
+EXTERN int Fire_SpreadNoWindNoSlope _ANSI_ARGS_((
+ FuelCatalogPtr catalog, /* FuelCatalogData instance pointer */
+ size_t model, /* fuel model number [0-maxModels] */
+ double moisture[FIRE_MCLASSES] /* array of fuel moistures (fractions) */
+ )) ;
+
+EXTERN int Fire_SpreadWindSlopeMax _ANSI_ARGS_((
+ FuelCatalogPtr catalog, /* FuelCatalogData instance pointer */
+ size_t model, /* fuel model number [0-maxModels] */
+ double windFpm, /* wind speed (ft/min) */
+ double windDeg, /* wind bearing vector (compass degs) */
+ double slope, /* slope (rise/reach) */
+ double aspect /* aspect (downslope) azimuth (compass degs) */
+ )) ;
+
+EXTERN int Fire_SpreadAtAzimuth _ANSI_ARGS_((
+ FuelCatalogPtr catalog, /* FuelCatalogData instance pointer */
+ size_t model, /* fuel model number [0-maxModels] */
+ double azimuth, /* fire spread azimuth (deg from upslope) */
+ size_t doWhich /* FIRE_NONE | FIRE_BYRAMS | FIRE_FLAME | FIRE_SCORCH */
+ )) ;
+
+/*
+ *------------------------------------------------------------------------------
+ * Function prototypes for creating and destroying fuel catalogs, fuel models,
+ * fuel particles, and flame length tables.
+ *------------------------------------------------------------------------------
+ */
+
+EXTERN int Fire_FlameLengthTable _ANSI_ARGS_((
+ FuelCatalogPtr catalog, /* FuelCatalogData instance pointer */
+ size_t flameClasses, /* number of flame length classes */
+ double flameStep /* flame length step value per class */
+ )) ;
+
+EXTERN FuelCatalogPtr Fire_FuelCatalogCreate _ANSI_ARGS_((
+ char *name, /* FuelCatalogData instance name */
+ size_t maxModels /* maximum modelId allowed in this catalog */
+ )) ;
+
+EXTERN FuelCatalogPtr Fire_FuelCatalogCreateStandard _ANSI_ARGS_((
+ char *name, /* FuelCatalogData instance name */
+ size_t maxModels /* maximum modelId allowed in this catalog */
+ )) ;
+
+EXTERN int Fire_FuelCatalogDestroy _ANSI_ARGS_((
+ FuelCatalogPtr catalog /* FuelCatalogData instance pointer */
+ )) ;
+
+EXTERN int Fire_FuelModelCreate _ANSI_ARGS_((
+ FuelCatalogPtr catalog, /* FuelCatalogData instance */
+ size_t model, /* fuel model number [0-maxModels] */
+ char *name, /* short name */
+ char *desc, /* longer description */
+ double depth, /* bed depth (ft) */
+ double mext, /* moisture of extinction (dl) */
+ double adjust, /* spread adjustment factor (dl) */
+ size_t maxParticles /* maximum number of fuel model particles */
+ )) ;
+
+EXTERN int Fire_FuelModelDestroy _ANSI_ARGS_((
+ FuelCatalogPtr catalog, /* FuelCatalogData instance pointer */
+ size_t model /* fuel model id number [0-maxModels] */
+ )) ;
+
+EXTERN int Fire_FuelModelExists _ANSI_ARGS_((
+ FuelCatalogPtr catalog, /* FuelCatalogData instance pointer */
+ size_t model /* fuel model id number [0-maxModels] */
+ )) ;
+
+EXTERN int Fire_FuelParticleAdd _ANSI_ARGS_((
+ FuelCatalogPtr catalog, /* FuelCatalogData instance pointer */
+ size_t model, /* fuel model id number [0-maxModels] */
+ size_t type, /* FIRE_TYPE_DEAD, _TYPE_HERB, or _TYPE_WOOD */
+ double load, /* fuel load (lbs/ft2) */
+ double savr, /* surface-area-to-volume ratio (ft2/ft3) */
+ double dens, /* density (lbs/ft3) */
+ double heat, /* heat of combustion (btus/lb) */
+ double stot, /* total silica content (lb/lb) */
+ double seff /* effective silica content (lb/lb) */
+ )) ;
+
+#ifdef NEED_STRDUP
+char *strdup ( const char *str ) ;
+#endif
+
+#endif
+
+/*
+ *******************************************************************************
+ * End of fireLib.h
+ *******************************************************************************
+ */
diff --git a/src/modules/statistics/statistics_kriging/kriging_base.cpp b/src/modules/statistics/statistics_kriging/kriging_base.cpp
index c59ce8a..24b6062 100644
--- a/src/modules/statistics/statistics_kriging/kriging_base.cpp
+++ b/src/modules/statistics/statistics_kriging/kriging_base.cpp
@@ -121,32 +121,32 @@ CKriging_Base::CKriging_Base(void)
///////////////////////////////////////////////////////
//-----------------------------------------------------
+ Parameters.Add_Value(
+ NULL , "VAR_MAXDIST" , _TL("Maximum Distance"),
+ _TL(""),
+ PARAMETER_TYPE_Double, -1.0
+ )->Set_UseInGUI(false);
+
+ Parameters.Add_Value(
+ NULL , "VAR_NCLASSES" , _TL("Lag Distance Classes"),
+ _TL("initial number of lag distance classes"),
+ PARAMETER_TYPE_Int, 100, 1, true
+ )->Set_UseInGUI(false);
+
+ Parameters.Add_Value(
+ NULL , "VAR_NSKIP" , _TL("Skip"),
+ _TL(""),
+ PARAMETER_TYPE_Int, 1, 1, true
+ )->Set_UseInGUI(false);
+
+ Parameters.Add_String(
+ NULL , "VAR_MODEL" , _TL("Model"),
+ _TL(""),
+ SG_T("a + b * x")
+ )->Set_UseInGUI(false);
+
if( !SG_UI_Get_Window_Main() )
{
- Parameters.Add_Value(
- NULL , "VAR_MAXDIST" , _TL("Maximum Distance"),
- _TL(""),
- PARAMETER_TYPE_Double, -1.0
- );
-
- Parameters.Add_Value(
- NULL , "VAR_NCLASSES" , _TL("Lag Distance Classes"),
- _TL("initial number of lag distance classes"),
- PARAMETER_TYPE_Int, 100, 1, true
- );
-
- Parameters.Add_Value(
- NULL , "VAR_NSKIP" , _TL("Skip"),
- _TL(""),
- PARAMETER_TYPE_Int, 1, 1, true
- );
-
- Parameters.Add_String(
- NULL , "VAR_MODEL" , _TL("Model"),
- _TL(""),
- SG_T("a + b * x")
- );
-
m_pVariogram = NULL;
}
else
diff --git a/src/modules/statistics/statistics_kriging/kriging_regression.cpp b/src/modules/statistics/statistics_kriging/kriging_regression.cpp
index 34a1232..f2706bb 100644
--- a/src/modules/statistics/statistics_kriging/kriging_regression.cpp
+++ b/src/modules/statistics/statistics_kriging/kriging_regression.cpp
@@ -157,32 +157,29 @@ CKriging_Regression::CKriging_Regression(void)
///////////////////////////////////////////////////////
//-----------------------------------------------------
- if( !SG_UI_Get_Window_Main() )
- {
- Parameters.Add_Value(
- NULL , "VAR_MAXDIST" , _TL("Maximum Distance"),
- _TL("maximum distance for variogram estimation"),
- PARAMETER_TYPE_Double, -1.0
- );
-
- Parameters.Add_Value(
- NULL , "VAR_NCLASSES" , _TL("Lag Distance Classes"),
- _TL("initial number of lag distance classes for variogram estimation"),
- PARAMETER_TYPE_Int, 100, 1, true
- );
-
- Parameters.Add_Value(
- NULL , "VAR_NSKIP" , _TL("Skip"),
- _TL(""),
- PARAMETER_TYPE_Int, 1, 1, true
- );
-
- Parameters.Add_String(
- NULL , "VAR_MODEL" , _TL("Variogram Model"),
- _TL(""),
- "a + b * x"
- );
- }
+ Parameters.Add_Value(
+ NULL , "VAR_MAXDIST" , _TL("Maximum Distance"),
+ _TL("maximum distance for variogram estimation"),
+ PARAMETER_TYPE_Double, -1.0
+ )->Set_UseInGUI(false);
+
+ Parameters.Add_Value(
+ NULL , "VAR_NCLASSES" , _TL("Lag Distance Classes"),
+ _TL("initial number of lag distance classes for variogram estimation"),
+ PARAMETER_TYPE_Int, 100, 1, true
+ )->Set_UseInGUI(false);
+
+ Parameters.Add_Value(
+ NULL , "VAR_NSKIP" , _TL("Skip"),
+ _TL(""),
+ PARAMETER_TYPE_Int, 1, 1, true
+ )->Set_UseInGUI(false);
+
+ Parameters.Add_String(
+ NULL , "VAR_MODEL" , _TL("Variogram Model"),
+ _TL(""),
+ "a + b * x"
+ )->Set_UseInGUI(false);
///////////////////////////////////////////////////////
//-----------------------------------------------------
diff --git a/src/modules/statistics/statistics_kriging/semivariogram.cpp b/src/modules/statistics/statistics_kriging/semivariogram.cpp
index 25751a7..8a03ada 100644
--- a/src/modules/statistics/statistics_kriging/semivariogram.cpp
+++ b/src/modules/statistics/statistics_kriging/semivariogram.cpp
@@ -109,32 +109,29 @@ CSemiVariogram::CSemiVariogram(void)
);
//-----------------------------------------------------
- if( !SG_UI_Get_Window_Main() )
- {
- Parameters.Add_Value(
- NULL , "VAR_MAXDIST" , _TL("Maximum Distance"),
- _TL(""),
- PARAMETER_TYPE_Double , -1.0
- );
-
- Parameters.Add_Value(
- NULL , "VAR_NCLASSES" , _TL("Lag Distance Classes"),
- _TL("initial number of lag distance classes"),
- PARAMETER_TYPE_Int , 100, 1, true
- );
-
- Parameters.Add_Value(
- NULL , "VAR_NSKIP" , _TL("Skip"),
- _TL(""),
- PARAMETER_TYPE_Int, 1, 1, true
- );
-
- Parameters.Add_String(
- NULL , "VAR_MODEL" , _TL("Model"),
- _TL(""),
- SG_T("a + b * x")
- );
- }
+ Parameters.Add_Value(
+ NULL , "VAR_MAXDIST" , _TL("Maximum Distance"),
+ _TL(""),
+ PARAMETER_TYPE_Double , -1.0
+ )->Set_UseInGUI(false);
+
+ Parameters.Add_Value(
+ NULL , "VAR_NCLASSES" , _TL("Lag Distance Classes"),
+ _TL("initial number of lag distance classes"),
+ PARAMETER_TYPE_Int , 100, 1, true
+ )->Set_UseInGUI(false);
+
+ Parameters.Add_Value(
+ NULL , "VAR_NSKIP" , _TL("Skip"),
+ _TL(""),
+ PARAMETER_TYPE_Int, 1, 1, true
+ )->Set_UseInGUI(false);
+
+ Parameters.Add_String(
+ NULL , "VAR_MODEL" , _TL("Model"),
+ _TL(""),
+ SG_T("a + b * x")
+ )->Set_UseInGUI(false);
}
diff --git a/src/modules/terrain_analysis/ta_lighting/SolarRadiation.cpp b/src/modules/terrain_analysis/ta_lighting/SolarRadiation.cpp
index ea9c679..61dec87 100644
--- a/src/modules/terrain_analysis/ta_lighting/SolarRadiation.cpp
+++ b/src/modules/terrain_analysis/ta_lighting/SolarRadiation.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: SolarRadiation.cpp 2137 2014-06-05 08:23:17Z oconrad $
+ * Version $Id: SolarRadiation.cpp 2636 2015-10-06 16:10:24Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -73,97 +73,40 @@
//---------------------------------------------------------
CSolarRadiation::CSolarRadiation(void)
{
- CSG_Parameter *pNode_1, *pNode_2;
+ CSG_Parameter *pNode, *pNode_2;
//-----------------------------------------------------
Set_Name (_TL("Potential Incoming Solar Radiation"));
- Set_Author (SG_T("O.Conrad (c) 2010"));
+ Set_Author ("O.Conrad (c) 2010");
Set_Description (_TW(
"Calculation of potential incoming solar radiation (insolation).\n"
+ "Times of sunrise/sunset will only be calculated if time span is set to single day.\n"
"\n"
"References:\n<ul>"
"<li>Boehner, J., Antonic, O. (2009): Land Surface Parameters Specific to Topo-Climatology. in Hengl, T. & Reuter, H.I. [Eds.]: Geomorphometry - Concepts, Software, Applications.</li>"
"<li>Oke, T.R. (1988): Boundary Layer Climates. London, Taylor & Francis.</li>"
"<li>Wilson, J.P., Gallant, J.C. [Eds.] (2000): Terrain Analysis - Principles and Applications. New York, John Wiley & Sons, Inc.</li>"
+ "<li>Joint Research Centre: <a target=\"_blank\" href=\"http://re.jrc.ec.europa.eu/pvgis/\">GIS solar radiation database for Europe</a> and <a target=\"_blank\" href=\"http://re.jrc.ec.europa.eu/pvgis/solres/solmod3.htm\">Solar radiation and GIS</a>.</li>"
+ "<li>Hofierka, J., Suri, M. (2002): The solar radiation model for Open source GIS: implementation and applications. International GRASS users conference in Trento, Italy, September 2002. <a target=\"_blank\" href=\"http://skagit.meas.ncsu.edu/~jaroslav/trento/Hofierka_Jaroslav.pdf\">pdf</a>.</li>"
"</ul>\n"
"\n*) Most options should do well, but TAPES-G based diffuse irradiance calculation ('Atmospheric Effects' methods 2 and 3) needs further revision!"
));
//-----------------------------------------------------
- Parameters.Add_Grid(
- NULL , "GRD_DEM" , _TL("Elevation"),
- _TL(""),
- PARAMETER_INPUT
- );
-
- Parameters.Add_Grid(
- NULL , "GRD_SVF" , _TL("Sky View Factor"),
- _TL(""),
- PARAMETER_INPUT_OPTIONAL
- );
-
- Parameters.Add_Grid(
- NULL , "GRD_VAPOUR" , _TL("Water Vapour Pressure [mbar]"),
- _TL(""),
- PARAMETER_INPUT_OPTIONAL
- );
-
- Parameters.Add_Grid(
- NULL , "GRD_LAT" , _TL("Latitude [degree]"),
- _TL(""),
- PARAMETER_INPUT_OPTIONAL
- );
-
- Parameters.Add_Grid(
- NULL , "GRD_LON" , _TL("Longitude [degree]"),
- _TL(""),
- PARAMETER_INPUT_OPTIONAL
- );
-
- Parameters.Add_Grid(
- NULL , "GRD_DIRECT" , _TL("Direct Insolation"),
- _TL(""),
- PARAMETER_OUTPUT
- );
-
- Parameters.Add_Grid(
- NULL , "GRD_DIFFUS" , _TL("Diffuse Insolation"),
- _TL(""),
- PARAMETER_OUTPUT
- );
-
- Parameters.Add_Grid(
- NULL , "GRD_TOTAL" , _TL("Total Insolation"),
- _TL("Total insolation, the sum of direct and diffuse incoming solar radiation."),
- PARAMETER_OUTPUT_OPTIONAL
- );
-
- Parameters.Add_Grid(
- NULL , "GRD_RATIO" , _TL("Direct to Diffuse Ratio"),
- _TL(""),
- PARAMETER_OUTPUT_OPTIONAL
- );
-
- Parameters.Add_Grid(
- NULL , "DURATION" , _TL("Duration of Insolation"),
- _TL(""),
- PARAMETER_OUTPUT_OPTIONAL
- );
-
- Parameters.Add_Grid(
- NULL , "SUNRISE" , _TL("Sunrise"),
- _TL("time of sunrise/sunset is only calculated if time span is set to single day"),
- PARAMETER_OUTPUT_OPTIONAL
- );
-
- Parameters.Add_Grid(
- NULL , "SUNSET" , _TL("Sunset"),
- _TL("time of sunrise/sunset is only calculated if time span is set to single day"),
- PARAMETER_OUTPUT_OPTIONAL
- );
+ Parameters.Add_Grid (NULL, "GRD_DEM" , _TL("Elevation" ), _TL(""), PARAMETER_INPUT);
+ Parameters.Add_Grid (NULL, "GRD_SVF" , _TL("Sky View Factor" ), _TL(""), PARAMETER_INPUT_OPTIONAL);
+ Parameters.Add_Grid_or_Const(NULL, "GRD_VAPOUR" , _TL("Water Vapour Pressure [mbar]"), _TL(""), 10.0, 0.0, true);
+ Parameters.Add_Grid_or_Const(NULL, "GRD_LINKE" , _TL("Linke Turbidity Coefficient" ), _TL(""), 3.0, 0.0, true);
+ Parameters.Add_Grid (NULL, "GRD_DIRECT" , _TL("Direct Insolation" ), _TL(""), PARAMETER_OUTPUT);
+ Parameters.Add_Grid (NULL, "GRD_DIFFUS" , _TL("Diffuse Insolation" ), _TL(""), PARAMETER_OUTPUT);
+ Parameters.Add_Grid (NULL, "GRD_TOTAL" , _TL("Total Insolation" ), _TL(""), PARAMETER_OUTPUT_OPTIONAL);
+ Parameters.Add_Grid (NULL, "GRD_RATIO" , _TL("Direct to Diffuse Ratio" ), _TL(""), PARAMETER_OUTPUT_OPTIONAL);
+ Parameters.Add_Grid (NULL, "GRD_DURATION", _TL("Duration of Insolation" ), _TL(""), PARAMETER_OUTPUT_OPTIONAL);
+ Parameters.Add_Grid (NULL, "GRD_SUNRISE" , _TL("Sunrise" ), _TL(""), PARAMETER_OUTPUT_OPTIONAL);
+ Parameters.Add_Grid (NULL, "GRD_SUNSET" , _TL("Sunset" ), _TL(""), PARAMETER_OUTPUT_OPTIONAL);
//-----------------------------------------------------
Parameters.Add_Value(
@@ -182,94 +125,59 @@ CSolarRadiation::CSolarRadiation(void)
NULL , "UNITS" , _TL("Units"),
_TL("Units for output radiation values."),
CSG_String::Format(SG_T("%s|%s|%s|"),
- SG_T("kWh / m\xb2"),
- SG_T("kJ / m\xb2"),
- SG_T("J / cm\xb2")
+ SG_T("kWh / m2"),
+ SG_T("kJ / m2"),
+ SG_T("J / cm2")
), 0
);
Parameters.Add_Choice(
NULL , "SHADOW" , _TL("Shadow"),
- _TL("Choose 'slim' to trace grid node's shadow, 'fat' to trace the whole cell's shadow. The first is slightly faster but might show some artifacts."),
- CSG_String::Format(SG_T("%s|%s|"),
+ _TL("Choose 'slim' to trace grid node's shadow, 'fat' to trace the whole cell's shadow, or ignore shadowing effects. The first is slightly faster but might show some artifacts."),
+ CSG_String::Format("%s|%s|%s|",
_TL("slim"),
- _TL("fat")
+ _TL("fat"),
+ _TL("none")
), 1
);
- //-----------------------------------------------------
- pNode_1 = Parameters.Add_Node(
- NULL , "NODE_LOCATION" , _TL("Location"),
- _TL("")
+ pNode = Parameters.Add_Choice(
+ NULL , "UPDATE" , _TL("Update"),
+ _TL("show direct insolation for each time step."),
+ CSG_String::Format("%s|%s|%s|",
+ _TL("do not update"),
+ _TL("fit histogram stretch for each time step"),
+ _TL("constant histogram stretch for all time steps")
+ ), 0
);
Parameters.Add_Value(
- pNode_1 , "LATITUDE" , _TL("Latitude"),
- _TL(""),
- PARAMETER_TYPE_Degree , 53.0, -90.0, true, 90.0, true
- );
-
- CSG_Parameters *pParameters = Parameters.Add_Parameters(
- pNode_1 , "BENDING" , _TL("Planetary Bending"),
- _TL("")
- )->asParameters();
-
- pParameters->Add_Value(
- NULL , "BENDING" , _TL("Include Planetery Bending"),
- _TL(""),
- PARAMETER_TYPE_Bool , false
- );
-
- pParameters->Add_Value(
- NULL , "RADIUS" , _TL("Planetary Radius"),
- _TL(""),
- PARAMETER_TYPE_Double , 6366737.96, 0.0, true
- );
-
- pNode_1 = pParameters->Add_Choice(
- NULL , "LAT_OFFSET" , _TL("Latitude relates to grid's..."),
- _TL(""),
- CSG_String::Format(SG_T("%s|%s|%s|%s|"),
- _TL("bottom"),
- _TL("center"),
- _TL("top"),
- _TL("user defined reference")
- ), 3
- );
-
- pParameters->Add_Value(
- pNode_1 , "LAT_REF_USER" , _TL("Latitude (user defined reference)"),
+ pNode , "UPDATE_STRETCH" , _TL("Constant Histogram Stretch"),
_TL(""),
- PARAMETER_TYPE_Double , 0.0
+ PARAMETER_TYPE_Double , 1.0, 0.0, true
);
- pNode_1 = pParameters->Add_Choice(
- NULL , "LON_OFFSET" , _TL("Local time relates to grid's..."),
+ //-----------------------------------------------------
+ pNode = Parameters.Add_Choice(
+ NULL , "LOCATION" , _TL("Location"),
_TL(""),
- CSG_String::Format(SG_T("%s|%s|%s|%s|"),
- _TL("left"),
- _TL("center"),
- _TL("right"),
- _TL("user defined reference")
- ), 1
+ CSG_String::Format("%s|%s|",
+ _TL("constant latitude"),
+ _TL("calculate from grid system")
+ ), 0
);
- pParameters->Add_Value(
- pNode_1 , "LON_REF_USER" , _TL("Local Time (user defined reference)"),
+ Parameters.Add_Value(
+ pNode , "LATITUDE" , _TL("Latitude"),
_TL(""),
- PARAMETER_TYPE_Double , 0.0
+ PARAMETER_TYPE_Degree , 53.0, -90.0, true, 90.0, true
);
//-----------------------------------------------------
- pNode_1 = Parameters.Add_Node(
- NULL , "NODE_TIME" , _TL("Time"),
- _TL("")
- );
-
- Parameters.Add_Choice(
- pNode_1 , "PERIOD" , _TL("Time Period"),
+ pNode = Parameters.Add_Choice(
+ NULL , "PERIOD" , _TL("Time Period"),
_TL(""),
- CSG_String::Format(SG_T("%s|%s|%s|"),
+ CSG_String::Format("%s|%s|%s|",
_TL("moment"),
_TL("day"),
_TL("range of days")
@@ -277,146 +185,80 @@ CSolarRadiation::CSolarRadiation(void)
);
Parameters.Add_Value(
- pNode_1 , "MOMENT" , _TL("Moment [h]"),
+ pNode , "MOMENT" , _TL("Moment [h]"),
_TL(""),
PARAMETER_TYPE_Double , 12.0, 0.0, true, 24.0, true
);
Parameters.Add_Range(
- pNode_1 , "HOUR_RANGE" , _TL("Time Span [h]"),
+ pNode , "HOUR_RANGE" , _TL("Time Span [h]"),
_TL("Time span used for the calculation of daily radiation sums."),
0.0, 24.0, 0.0 , true, 24.0, true
);
Parameters.Add_Value(
- pNode_1 , "DHOUR" , _TL("Time Resolution [h]: Day"),
+ pNode , "HOUR_STEP" , _TL("Time Resolution [h]: Day"),
_TL("Time step size for a day's calculation given in hours."),
PARAMETER_TYPE_Double , 0.5, 0.0, true, 24.0, true
);
Parameters.Add_Value(
- pNode_1 , "DDAYS" , _TL("Time Resolution [d]: Range of Days"),
+ pNode , "DAYS_STEP" , _TL("Time Resolution [d]: Range of Days"),
_TL("Time step size for a range of days calculation given in days."),
PARAMETER_TYPE_Int , 5, 1, true
);
- Parameters.Add_Choice(
- pNode_1 , "UPDATE" , _TL("Update"),
- _TL("show direct insolation for each time step."),
- CSG_String::Format(SG_T("%s|%s|%s|"),
- _TL("do not update"),
- _TL("update, colour stretch for each time step"),
- _TL("update, fixed colour stretch")
- ), 0
- );
-
//-----------------------------------------------------
- pNode_2 = Parameters.Add_Node(
- pNode_1 , "NODE_DAY_A" , _TL("Day of Year"),
- _TL("")
- );
-
- Parameters.Add_Choice(
- pNode_2 , "DAY_A" , _TL("Day of Month"),
- _TL(""),
- SG_T("1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|"), 20
- );
-
- Parameters.Add_Choice(
- pNode_2 , "MON_A" , _TL("Month"),
- _TL(""),
- CSG_String::Format(SG_T("%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|"),
- _TL("January") , _TL("February") , _TL("March") , _TL("April") , _TL("May") , _TL("June"),
- _TL("July") , _TL("August") , _TL("September") , _TL("October"), _TL("November") , _TL("December")
- ), 2
- );
+ pNode_2 = Parameters.Add_Node(pNode, "DATE_A", _TL("Date"), _TL(""));
- pNode_2 = Parameters.Add_Node(
- pNode_1 , "NODE_DAY_B" , _TL("Day of Year (End of Range)"),
- _TL("")
- );
+ Parameters.Add_Value (pNode_2, "DAY_A", _TL("Day" ), _TL(""), PARAMETER_TYPE_Int, CSG_DateTime::Get_Current_Day(), 1, true, 31, true);
+ Parameters.Add_Choice(pNode_2, "MON_A", _TL("Month"), _TL(""), CSG_DateTime::Get_Month_Choices(), CSG_DateTime::Get_Current_Month());
+ Parameters.Add_Value (pNode_2, "YEAR_A", _TL("Year" ), _TL(""), PARAMETER_TYPE_Int, CSG_DateTime::Get_Current_Year());
- Parameters.Add_Choice(
- pNode_2 , "DAY_B" , _TL("Day of Month"),
- _TL(""),
- SG_T("1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31|"), 20
- );
+ pNode_2 = Parameters.Add_Node(pNode, "DATE_B", _TL("2nd Date (End of Range)"), _TL(""));
- Parameters.Add_Choice(
- pNode_2 , "MON_B" , _TL("Month"),
- _TL(""),
- CSG_String::Format(SG_T("%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|"),
- _TL("January") , _TL("February") , _TL("March") , _TL("April") , _TL("May") , _TL("June"),
- _TL("July") , _TL("August") , _TL("September") , _TL("October"), _TL("November") , _TL("December")
- ), 3
- );
+ Parameters.Add_Value (pNode_2, "DAY_B", _TL("Day" ), _TL(""), PARAMETER_TYPE_Int, CSG_DateTime::Get_Current_Day(), 1, true, 31, true);
+ Parameters.Add_Choice(pNode_2, "MON_B", _TL("Month"), _TL(""), CSG_DateTime::Get_Month_Choices(), CSG_DateTime::Get_Current_Month());
+ Parameters.Add_Value (pNode_2, "YEAR_B", _TL("Year" ), _TL(""), PARAMETER_TYPE_Int, CSG_DateTime::Get_Current_Year());
//-----------------------------------------------------
- pNode_1 = Parameters.Add_Node(
- NULL , "NODE_METHOD" , _TL("Atmospheric Effects"),
- _TL("")
- );
-
- Parameters.Add_Choice(
- pNode_1 , "METHOD" , _TL("Atmospheric Effects"),
+ pNode = Parameters.Add_Choice(
+ NULL , "METHOD" , _TL("Atmospheric Effects"),
_TL(""),
- CSG_String::Format(SG_T("%s|%s|%s|"),
+ CSG_String::Format("%s|%s|%s|%s|",
_TL("Height of Atmosphere and Vapour Pressure"),
_TL("Air Pressure, Water and Dust Content"),
- _TL("Lumped Atmospheric Transmittance")
- ), 0
- );
-
- //-----------------------------------------------------
- pNode_2 = Parameters.Add_Node(
- pNode_1 , "NODE_SADO" , _TL("Height of Atmosphere and Vapour Pressure"),
- _TL("")
+ _TL("Lumped Atmospheric Transmittance"),
+ _TL("Hofierka and Suri")
+ ), 2
);
Parameters.Add_Value(
- pNode_2 , "ATMOSPHERE" , _TL("Height of Atmosphere [m]"),
+ pNode , "ATMOSPHERE" , _TL("Height of Atmosphere [m]"),
_TL(""),
PARAMETER_TYPE_Double , 12000.0, 0.0, true
);
Parameters.Add_Value(
- pNode_2 , "VAPOUR" , _TL("Water Vapour Pressure [mbar]"),
- _TL("This value is used as constant if no vapour pressure grid is given."),
- PARAMETER_TYPE_Double , 10, 0.0, true
- );
-
- //-----------------------------------------------------
- pNode_2 = Parameters.Add_Node(
- pNode_1 , "NODE_COMPONENTS" , _TL("Air Pressure, Water and Dust Content"),
- _TL("")
- );
-
- Parameters.Add_Value(
- pNode_2 , "PRESSURE" , _TL("Atmospheric Pressure [mbar]"),
+ pNode , "PRESSURE" , _TL("Barometric Pressure [mbar]"),
_TL(""),
PARAMETER_TYPE_Double, 1013, 0.0, true
);
Parameters.Add_Value(
- pNode_2 , "WATER" , _TL("Water Content [cm]"),
+ pNode , "WATER" , _TL("Water Content [cm]"),
_TL("Water content of a vertical slice of atmosphere in cm: 1.5 to 1.7, average=1.68"),
PARAMETER_TYPE_Double, 1.68, 0.0, true
);
Parameters.Add_Value(
- pNode_2 , "DUST" , _TL("Dust [ppm]"),
+ pNode , "DUST" , _TL("Dust [ppm]"),
_TL("Dust factor: 100 ppm (standard)"),
PARAMETER_TYPE_Double, 100, 0.0, true
);
- //-----------------------------------------------------
- pNode_2 = Parameters.Add_Node(
- pNode_1 , "NODE_LUMPED" , _TL("Lumped Atmospheric Transmittance"),
- _TL("")
- );
-
Parameters.Add_Value(
- pNode_2 , "LUMPED" , _TL("Lumped Atmospheric Transmittance [Percent]"),
+ pNode , "LUMPED" , _TL("Lumped Atmospheric Transmittance [Percent]"),
_TL("The transmittance of the atmosphere, usually between 60 and 80 percent."),
PARAMETER_TYPE_Double, 70, 0.0, true, 100.0, true
);
@@ -425,160 +267,157 @@ CSolarRadiation::CSolarRadiation(void)
///////////////////////////////////////////////////////////
// //
-// //
-// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-int CSolarRadiation::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
+int CSolarRadiation::On_Parameter_Changed(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
{
- //-----------------------------------------------------
- if( !SG_STR_CMP(pParameter->Get_Identifier(), SG_T("GRD_LAT")) )
+ if( !SG_STR_CMP(pParameter->Get_Identifier(), "GRD_DEM") && pParameter->asGrid() && pParameter->asGrid()->Get_Projection().is_Okay() )
{
- pParameters->Get_Parameter("NODE_LOCATION")->Set_Enabled(pParameter->asGrid() == NULL);
+ CSG_Shapes srcCenter(SHAPE_TYPE_Point), dstCenter(SHAPE_TYPE_Point);
+
+ srcCenter.Get_Projection() = pParameter->asGrid()->Get_Projection();
+ srcCenter.Add_Shape()->Add_Point(pParameter->asGrid()->Get_System().Get_Extent().Get_Center());
+
+ bool bResult;
+
+ SG_RUN_MODULE(bResult, "pj_proj4", 2, // Coordinate Transformation (Shapes)
+ SG_MODULE_PARAMETER_SET("SOURCE" , &srcCenter)
+ && SG_MODULE_PARAMETER_SET("TARGET" , &dstCenter)
+ && SG_MODULE_PARAMETER_SET("CRS_PROJ4", SG_T("+proj=longlat +ellps=WGS84 +datum=WGS84"))
+ )
+
+ if( bResult )
+ {
+ pParameters->Get_Parameter("LATITUDE")->Set_Value(dstCenter.Get_Shape(0)->Get_Point(0).y);
+ }
}
- //-----------------------------------------------------
- if( !SG_STR_CMP(pParameter->Get_Identifier(), SG_T("GRD_VAPOUR")) )
+ return( CSG_Module_Grid::On_Parameter_Changed(pParameters, pParameter) );
+}
+
+//---------------------------------------------------------
+int CSolarRadiation::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
+{
+ if( !SG_STR_CMP(pParameter->Get_Identifier(), "UPDATE") )
{
- pParameters->Get_Parameter("VAPOUR")->Set_Enabled(pParameter->asGrid() == NULL);
+ pParameters->Set_Enabled("UPDATE_STRETCH", pParameter->asInt() == 2);
}
- //-----------------------------------------------------
- if( !SG_STR_CMP(pParameter->Get_Identifier(), SG_T("PERIOD")) )
+ if( !SG_STR_CMP(pParameter->Get_Identifier(), "LOCATION") )
{
- int Value = pParameter->asInt();
-
- pParameters->Get_Parameter("MOMENT" )->Set_Enabled(Value == 0);
- pParameters->Get_Parameter("UPDATE" )->Set_Enabled(Value >= 1);
- pParameters->Get_Parameter("HOUR_RANGE")->Set_Enabled(Value >= 1);
- pParameters->Get_Parameter("DHOUR" )->Set_Enabled(Value >= 1);
- pParameters->Get_Parameter("DDAYS" )->Set_Enabled(Value == 2);
- pParameters->Get_Parameter("NODE_DAY_B")->Set_Enabled(Value == 2);
+ pParameters->Set_Enabled("LATITUDE" , pParameter->asInt() == 0);
}
- //-----------------------------------------------------
- if( !SG_STR_CMP(pParameter->Get_Identifier(), SG_T("METHOD")) )
+ if( !SG_STR_CMP(pParameter->Get_Identifier(), "PERIOD") )
{
- int Value = pParameter->asInt();
+ pParameters->Set_Enabled("MOMENT" , pParameter->asInt() == 0);
+ pParameters->Set_Enabled("GRD_DURATION" , pParameter->asInt() == 1);
+ pParameters->Set_Enabled("GRD_SUNRISE" , pParameter->asInt() == 1);
+ pParameters->Set_Enabled("GRD_SUNSET" , pParameter->asInt() == 1);
+ pParameters->Set_Enabled("UPDATE" , pParameter->asInt() >= 1);
+ pParameters->Set_Enabled("HOUR_RANGE" , pParameter->asInt() >= 1);
+ pParameters->Set_Enabled("HOUR_STEP" , pParameter->asInt() >= 1);
+ pParameters->Set_Enabled("DATE_B" , pParameter->asInt() == 2);
+ pParameters->Set_Enabled("DAYS_STEP" , pParameter->asInt() == 2);
+ }
- pParameters->Get_Parameter("GRD_VAPOUR" )->Set_Enabled(Value == 0);
- pParameters->Get_Parameter("NODE_SADO" )->Set_Enabled(Value == 0);
- pParameters->Get_Parameter("NODE_COMPONENTS")->Set_Enabled(Value == 1);
- pParameters->Get_Parameter("NODE_LUMPED" )->Set_Enabled(Value == 2);
+ if( !SG_STR_CMP(pParameter->Get_Identifier(), "METHOD") )
+ {
+ pParameters->Set_Enabled("GRD_VAPOUR" , pParameter->asInt() == 0);
+ pParameters->Set_Enabled("ATMOSPHERE" , pParameter->asInt() == 0);
+ pParameters->Set_Enabled("PRESSURE" , pParameter->asInt() == 1);
+ pParameters->Set_Enabled("WATER" , pParameter->asInt() == 1);
+ pParameters->Set_Enabled("DUST" , pParameter->asInt() == 1);
+ pParameters->Set_Enabled("LUMPED" , pParameter->asInt() == 2);
+ pParameters->Set_Enabled("GRD_LINKE" , pParameter->asInt() == 3);
+ pParameters->Set_Enabled("LOCALSVF" , pParameter->asInt() != 3);
}
- return( 0 );
+ return( CSG_Module_Grid::On_Parameters_Enable(pParameters, pParameter) );
}
///////////////////////////////////////////////////////////
// //
-// //
-// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
bool CSolarRadiation::On_Execute(void)
{
- int x, y;
-
//-----------------------------------------------------
m_pDEM = Parameters("GRD_DEM" )->asGrid();
+ m_pSVF = Parameters("GRD_SVF" )->asGrid();
m_pVapour = Parameters("GRD_VAPOUR")->asGrid();
- m_pSVF = Parameters("GRD_SVF" ) ->asGrid();
+ m_Vapour = Parameters("GRD_VAPOUR")->asDouble();
+ m_pLinke = Parameters("GRD_LINKE" )->asGrid();
+ m_Linke = Parameters("GRD_LINKE" )->asDouble();
m_pDirect = Parameters("GRD_DIRECT")->asGrid();
m_pDiffus = Parameters("GRD_DIFFUS")->asGrid();
m_pTotal = Parameters("GRD_TOTAL" )->asGrid();
m_pRatio = Parameters("GRD_RATIO" )->asGrid();
- m_pDuration = Parameters("DURATION" )->asGrid();
- m_pSunrise = Parameters("SUNRISE" )->asGrid();
- m_pSunset = Parameters("SUNSET" )->asGrid();
- m_bUpdate = Parameters("UPDATE" )->asInt();
+ m_pDuration = NULL;
+ m_pSunrise = NULL;
+ m_pSunset = NULL;
- m_Solar_Const = Parameters("SOLARCONST")->asDouble() / 1000.0; // >> [kW / m�]
- m_bLocalSVF = Parameters("LOCALSVF" )->asBool();
- m_Shadowing = Parameters("SHADOW" )->asInt();
+ m_bLocalSVF = Parameters("LOCALSVF" )->asBool ();
+ m_Shadowing = Parameters("SHADOW" )->asInt ();
- m_Method = Parameters("METHOD" )->asInt();
+ m_Method = Parameters("METHOD" )->asInt ();
m_Atmosphere = Parameters("ATMOSPHERE")->asDouble();
- m_Vapour = Parameters("VAPOUR" )->asDouble();
- m_Transmittance = Parameters("LUMPED" )->asDouble() / 100.0; // percent to ratio
+ m_Transmittance = Parameters("LUMPED" )->asDouble() / 100.0; // percent to ratio
m_Pressure = Parameters("PRESSURE" )->asDouble();
m_Water = Parameters("WATER" )->asDouble();
m_Dust = Parameters("DUST" )->asDouble();
- m_Time = Parameters("PERIOD" )->asInt();
- m_dHour = Parameters("DHOUR" )->asDouble();
- m_dDays = Parameters("DDAYS" )->asInt();
-
- m_Latitude = Parameters("LATITUDE" )->asDouble() * M_DEG_TO_RAD;
-
- m_bBending = Parameters("BENDING" )->asParameters()->Get_Parameter("BENDING")->asBool() || Parameters("GRD_LAT")->asGrid() || Parameters("GRD_LON")->asGrid();
-
//-----------------------------------------------------
- switch( m_Time )
- {
- case 0: // moment
- m_Hour_A = Parameters("MOMENT")->asDouble();
- m_Day_A = Parameters("DAY_A")->asInt() + 1 + Get_Day_of_Year(Parameters("MON_A")->asInt());
- break;
-
- case 1: // day
- m_Hour_A = Parameters("HOUR_RANGE")->asRange()->Get_LoVal();
- m_Hour_B = Parameters("HOUR_RANGE")->asRange()->Get_HiVal();
- m_Day_A = Parameters("DAY_A")->asInt() + 1 + Get_Day_of_Year(Parameters("MON_A")->asInt());
- m_Day_B = m_Day_A;
- break;
+ CSG_Colors Colors(11, SG_COLORS_YELLOW_RED, true);
- case 2: // range of days
- m_Hour_A = Parameters("HOUR_RANGE")->asRange()->Get_LoVal();
- m_Hour_B = Parameters("HOUR_RANGE")->asRange()->Get_HiVal();
- m_Day_A = Parameters("DAY_A")->asInt() + 1 + Get_Day_of_Year(Parameters("MON_A")->asInt());
- m_Day_B = Parameters("DAY_B")->asInt() + 1 + Get_Day_of_Year(Parameters("MON_B")->asInt());
+ Colors.Set_Ramp(SG_GET_RGB( 0, 0, 64), SG_GET_RGB(255, 159, 0), 0, 5);
+ Colors.Set_Ramp(SG_GET_RGB(255, 159, 0), SG_GET_RGB(255, 255, 255), 5, 10);
- if( m_Day_B < m_Day_A )
- {
- m_Day_B += 365;
- }
- break;
- }
+ DataObject_Set_Colors(m_pDirect, Colors);
+ DataObject_Set_Colors(m_pDiffus, Colors);
+ DataObject_Set_Colors(m_pTotal , Colors);
+ DataObject_Set_Colors(m_pRatio , 11, SG_COLORS_RED_GREY_BLUE, true);
//-----------------------------------------------------
- CSG_Colors Colors(100, SG_COLORS_YELLOW_RED, true);
+ m_Latitude = Parameters("LATITUDE")->asDouble() * M_DEG_TO_RAD;
- Colors.Set_Ramp(SG_GET_RGB( 0, 0, 64), SG_GET_RGB(255, 159, 0), 0, 50);
- Colors.Set_Ramp(SG_GET_RGB(255, 159, 0), SG_GET_RGB(255, 255, 255), 50, 99);
+ if( (m_Location = Parameters("LOCATION")->asInt()) != 0 )
+ {
+ m_Sun_Height .Create(*Get_System());
+ m_Sun_Azimuth.Create(*Get_System());
- DataObject_Set_Colors(m_pDirect , Colors);
- DataObject_Set_Colors(m_pDiffus , Colors);
- DataObject_Set_Colors(m_pTotal , Colors);
- DataObject_Set_Colors(m_pRatio , 100, SG_COLORS_RED_GREY_BLUE , true);
- DataObject_Set_Colors(m_pDuration, 100, SG_COLORS_YELLOW_RED , true);
- DataObject_Set_Colors(m_pSunrise , 100, SG_COLORS_YELLOW_RED , false);
- DataObject_Set_Colors(m_pSunset , 100, SG_COLORS_YELLOW_RED , true);
+ m_Lat .Create(*Get_System());
+ m_Lon .Create(*Get_System());
- //-----------------------------------------------------
- if( m_pDuration ) m_pDuration->Assign_NoData();
- if( m_pSunrise ) m_pSunrise ->Assign_NoData();
- if( m_pSunset ) m_pSunset ->Assign_NoData();
+ SG_RUN_MODULE_ExitOnError("pj_proj4", 17, // geographic coordinate grids
+ SG_MODULE_PARAMETER_SET("GRID", m_pDEM)
+ && SG_MODULE_PARAMETER_SET("LON" , &m_Lon)
+ && SG_MODULE_PARAMETER_SET("LAT" , &m_Lat)
+ )
- if( m_pDuration ) m_pDuration->Set_Unit(_TL("h"));
- if( m_pSunrise ) m_pSunrise ->Set_Unit(_TL("h"));
- if( m_pSunset ) m_pSunset ->Set_Unit(_TL("h"));
+ m_Lat.Set_Scaling(M_DEG_TO_RAD);
+ m_Lon.Set_Scaling(M_DEG_TO_RAD, -M_DEG_TO_RAD * m_Lon.asDouble(Get_NX() / 2, Get_NY() / 2));
+
+ Message_Add(CSG_String::Format("\n%s: %f <-> %f", _TL("Longitude"), M_RAD_TO_DEG * m_Lon.Get_ZMin(), M_RAD_TO_DEG * m_Lon.Get_ZMax()), false);
+ Message_Add(CSG_String::Format("\n%s: %f <-> %f", _TL("Latitude" ), M_RAD_TO_DEG * m_Lat.Get_ZMin(), M_RAD_TO_DEG * m_Lat.Get_ZMax()), false);
+ }
//-----------------------------------------------------
- Process_Set_Text(_TL("initialising gradient..."));
+ Process_Set_Text(_TL("Slopes"));
- m_Shade .Create(*Get_System(), SG_DATATYPE_Float);
- m_Slope .Create(*Get_System(), SG_DATATYPE_Float);
- m_Aspect.Create(*Get_System(), SG_DATATYPE_Float);
+ m_Shade .Create(*Get_System());
+ m_Slope .Create(*Get_System());
+ m_Aspect.Create(*Get_System());
- for(y=0; y<Get_NY() && Set_Progress(y); y++)
+ for(int y=0; y<Get_NY() && Set_Progress(y); y++)
{
- for(x=0; x<Get_NX(); x++)
+ #pragma omp parallel for
+ for(int x=0; x<Get_NX(); x++)
{
double s, a;
@@ -596,85 +435,14 @@ bool CSolarRadiation::On_Execute(void)
}
//-----------------------------------------------------
- if( m_bBending )
- {
- Process_Set_Text(_TL("initialising planetary bending..."));
-
- m_Lat .Create(*Get_System(), SG_DATATYPE_Float);
- m_Lon .Create(*Get_System(), SG_DATATYPE_Float);
- m_Sol_Height .Create(*Get_System(), SG_DATATYPE_Float);
- m_Sol_Azimuth .Create(*Get_System(), SG_DATATYPE_Float);
-
- //-------------------------------------------------
- if( Parameters("GRD_LAT")->asGrid() || Parameters("GRD_LON")->asGrid() )
- {
- if( Parameters("GRD_LAT")->asGrid() )
- {
- m_Lat = *Parameters("GRD_LAT")->asGrid();
- m_Lat *= M_DEG_TO_RAD;
- }
-
- if( Parameters("GRD_LON")->asGrid() )
- {
- m_Lon = *Parameters("GRD_LON")->asGrid();
- m_Lon *= M_DEG_TO_RAD;
- }
- }
-
- //-------------------------------------------------
- else
- {
- int Offset;
- double d, dx, dy, dxA, dyA, Radius, Reference;
-
- Offset = Parameters("BENDING")->asParameters()->Get_Parameter("LON_OFFSET") ->asInt();
- Reference = Parameters("BENDING")->asParameters()->Get_Parameter("LON_REF_USER")->asDouble();
- Radius = Parameters("BENDING")->asParameters()->Get_Parameter("RADIUS") ->asDouble();
- d = 1.0 / Radius;
-
- switch( Offset )
- {
- case 0: dxA = Get_System()->Get_Extent().Get_XMin(); break; // left
- case 1: dxA = Get_System()->Get_Extent().Get_XCenter(); break; // center
- case 2: dxA = Get_System()->Get_Extent().Get_XMax(); break; // right
- case 3: dxA = Reference; break; // user defined coordinate
- }
-
- Offset = Parameters("BENDING")->asParameters()->Get_Parameter("LAT_OFFSET") ->asInt();
- Reference = Parameters("BENDING")->asParameters()->Get_Parameter("LAT_REF_USER")->asDouble();
-
- switch( Offset )
- {
- case 0: dyA = Get_System()->Get_Extent().Get_YMin(); break; // bottom
- case 1: dyA = Get_System()->Get_Extent().Get_YCenter(); break; // center
- case 2: dyA = Get_System()->Get_Extent().Get_YMax(); break; // top
- case 3: dyA = Reference; break; // user defined coordinate
- }
-
- dxA = d * (Get_XMin() - dxA);
- dyA = d * (Get_YMin() - dyA) + m_Latitude;
- d *= Get_Cellsize();
-
- for(y=0, dy=dyA; y<Get_NY() && Set_Progress(y); y++, dy+=d)
- {
- for(x=0, dx=dxA; x<Get_NX(); x++, dx+=d)
- {
- m_Lat.Set_Value(x, y, dy);
- m_Lon.Set_Value(x, y, dx);
- }
- }
- }
- }
-
- //-----------------------------------------------------
if( Get_Insolation() )
{
- Finalise();
+ Finalize();
return( true );
}
- Finalise();
+ Finalize();
return( false );
}
@@ -682,18 +450,16 @@ bool CSolarRadiation::On_Execute(void)
///////////////////////////////////////////////////////////
// //
-// //
-// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-bool CSolarRadiation::Finalise(void)
+bool CSolarRadiation::Finalize(void)
{
double dUnit;
CSG_String Unit;
//-----------------------------------------------------
- if( m_Time == 0 ) // moment
+ if( Parameters("PERIOD")->asInt() == 0 ) // moment
{
Unit = SG_T("W / m\xb2");
dUnit = 1000.0;
@@ -750,14 +516,13 @@ bool CSolarRadiation::Finalise(void)
}
//-----------------------------------------------------
- m_Shade .Destroy();
- m_Slope .Destroy();
- m_Aspect .Destroy();
-
- m_Lat .Destroy();
- m_Lon .Destroy();
- m_Sol_Height .Destroy();
- m_Sol_Azimuth .Destroy();
+ m_Shade .Destroy();
+ m_Slope .Destroy();
+ m_Aspect .Destroy();
+ m_Lat .Destroy();
+ m_Lon .Destroy();
+ m_Sun_Height .Destroy();
+ m_Sun_Azimuth.Destroy();
//-----------------------------------------------------
return( true );
@@ -774,61 +539,95 @@ bool CSolarRadiation::Finalise(void)
bool CSolarRadiation::Get_Insolation(void)
{
//-----------------------------------------------------
- if( m_Time == 0 ) // Moment
+ switch( Parameters("PERIOD")->asInt() ? Parameters("UPDATE")->asInt() : 0 )
{
- m_pDirect->Assign(0.0);
- m_pDiffus->Assign(0.0);
-
- Get_Insolation(m_Day_A, m_Hour_A);
+ case 1: DataObject_Update(m_pDirect , SG_UI_DATAOBJECT_SHOW); break;
+ case 2: DataObject_Update(m_pDirect, 0.0, Parameters("UPDATE_STRETCH")->asDouble(), SG_UI_DATAOBJECT_SHOW); break;
}
//-----------------------------------------------------
- else if( m_Time == 1 ) // One Day
- {
- Get_Insolation(m_Day_A);
- }
+ CSG_DateTime Date((CSG_DateTime::TSG_DateTime)Parameters("DAY_A")->asInt(), (CSG_DateTime::Month)Parameters("MON_A")->asInt(), Parameters("YEAR_A")->asInt());
- //-----------------------------------------------------
- else if( m_Day_B - m_Day_A <= m_dDays ) // Range of Days (one representative calculation)
+ switch( Parameters("PERIOD")->asInt() )
{
- Get_Insolation(m_Day_A + m_dDays / 2);
+ //-----------------------------------------------------
+ case 0: // Moment
- m_pDirect->Multiply(m_Day_B - m_Day_A);
- m_pDiffus->Multiply(m_Day_B - m_Day_A);
- }
+ m_pDirect->Assign(0.0);
+ m_pDiffus->Assign(0.0);
+
+ return( Get_Insolation(Date, Parameters("MOMENT")->asDouble()) );
//-----------------------------------------------------
- else // Range of Days (more than one time step)
- {
- CSG_Grid Direct, Diffus;
+ case 1: // One Day
- Direct.Create(*Get_System(), SG_DATATYPE_Float);
- Diffus.Create(*Get_System(), SG_DATATYPE_Float);
+ if( !!(m_pDuration = Parameters("GRD_DURATION")->asGrid()) ) { DataObject_Set_Colors(m_pDuration, 11, SG_COLORS_YELLOW_RED, true); m_pDuration->Assign_NoData(); m_pDuration->Set_Unit(_TL("h")); }
+ if( !!(m_pSunrise = Parameters("GRD_SUNRISE" )->asGrid()) ) { DataObject_Set_Colors(m_pSunrise , 11, SG_COLORS_YELLOW_RED, false); m_pSunrise ->Assign_NoData(); m_pSunrise ->Set_Unit(_TL("h")); }
+ if( !!(m_pSunset = Parameters("GRD_SUNSET" )->asGrid()) ) { DataObject_Set_Colors(m_pSunset , 11, SG_COLORS_YELLOW_RED, true); m_pSunset ->Assign_NoData(); m_pSunset ->Set_Unit(_TL("h")); }
- Direct.Assign(0.0);
- Diffus.Assign(0.0);
+ return( Get_Insolation(Date) );
- for(int Day=m_Day_A+m_dDays/2; Day<=m_Day_B && Process_Get_Okay(false); Day+=m_dDays)
+ //-----------------------------------------------------
+ case 2: // Range of Days
{
- Get_Insolation(Day);
+ CSG_DateTime Stop((CSG_DateTime::TSG_DateTime)Parameters("DAY_B")->asInt(), (CSG_DateTime::Month)Parameters("MON_B")->asInt(), Parameters("YEAR_B")->asInt());
- SG_UI_Progress_Lock(true);
+ int dDays = Parameters("DAYS_STEP")->asInt();
- Direct.Add(*m_pDirect);
- Diffus.Add(*m_pDiffus);
+ //---------------------------------------------
+ // one representative calculation
- SG_UI_Progress_Lock(false);
- }
+ if( Stop.Get_JDN() - Date.Get_JDN() <= dDays )
+ {
+ Date.Set(Date.Get_JDN() + 0.5 * (dDays = (int)(Stop.Get_JDN() - Date.Get_JDN())));
- m_pDirect->Assign(&Direct);
- m_pDiffus->Assign(&Diffus);
+ Get_Insolation(Date);
+
+ m_pDirect->Multiply(1 + dDays);
+ m_pDiffus->Multiply(1 + dDays);
+ }
+
+ //---------------------------------------------
+ // more than one time step of days
+
+ else
+ {
+ CSG_Grid Direct, Diffus;
+
+ Direct.Create(*Get_System(), SG_DATATYPE_Float);
+ Diffus.Create(*Get_System(), SG_DATATYPE_Float);
+
+ Direct.Assign(0.0);
+ Diffus.Assign(0.0);
+
+ CSG_TimeSpan dStep(24.0 * dDays);
- m_pDirect->Multiply(m_dDays);
- m_pDiffus->Multiply(m_dDays);
+ for( ; Date<=Stop && Process_Get_Okay(false); Date+=dStep)
+ {
+ Get_Insolation(Date);
+
+ SG_UI_Progress_Lock(true);
+
+ Direct.Add(*m_pDirect);
+ Diffus.Add(*m_pDiffus);
+
+ SG_UI_Progress_Lock(false);
+ }
+
+ SG_UI_Progress_Lock(true);
+
+ m_pDirect->Assign(&Direct); m_pDirect->Multiply(dDays);
+ m_pDiffus->Assign(&Diffus); m_pDiffus->Multiply(dDays);
+
+ SG_UI_Progress_Lock(false);
+ }
+ }
+
+ return( true );
}
//-----------------------------------------------------
- return( true );
+ return( false );
}
@@ -837,72 +636,68 @@ bool CSolarRadiation::Get_Insolation(void)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-bool CSolarRadiation::Get_Insolation(int Day)
+bool CSolarRadiation::Get_Insolation(CSG_DateTime Date)
{
- //-----------------------------------------------------
- double Range = 0.000001 + cos(M_DEG_TO_RAD * fabs(m_Latitude)) * sin(M_PI * ((80 + Day) % 365) / 365.0);
- CSG_Grid Direct;
+ SG_UI_Progress_Lock(true);
- if( m_bUpdate )
- {
- if( m_bUpdate == 2 )
- {
- DataObject_Update(m_pDirect, 0.0, Range, SG_UI_DATAOBJECT_SHOW);
- }
- else
- {
- DataObject_Update(m_pDirect, SG_UI_DATAOBJECT_SHOW);
- }
+ //-----------------------------------------------------
+ int Update = Parameters("UPDATE")->asInt();
+ double dUpdate = Parameters("UPDATE_STRETCH")->asDouble();
- Direct.Create(*Get_System(), SG_DATATYPE_Float);
- }
+ CSG_Grid Direct;
//-----------------------------------------------------
- bool bDay, bWasDay = false;
+ bool bWasDay = false;
+
+ double Hour_A = Parameters("HOUR_RANGE")->asRange()->Get_LoVal();
+ double Hour_B = Parameters("HOUR_RANGE")->asRange()->Get_HiVal();
+ double dHour = Parameters("HOUR_STEP" )->asDouble();
m_pDirect->Assign(0.0);
m_pDiffus->Assign(0.0);
- for(double Hour=m_Hour_A; Hour<=m_Hour_B && Set_Progress(Hour - m_Hour_A, m_Hour_B - m_Hour_A); Hour+=m_dHour)
+ for(double Hour=Hour_A; Hour<=Hour_B && Set_Progress(Hour - Hour_A, Hour_B - Hour_A); Hour+=dHour)
{
- Process_Set_Text(CSG_String::Format(SG_T("%s %d(%d-%d), %s %02d:%02d"), _TL("day"), Day, m_Day_A, m_Day_B, _TL("local time"), (int)Hour, (int)(60.0 * fmod(Hour, 1.0))));
-
+ SG_UI_Progress_Lock(false);
+ bool bDay = Get_Insolation(Date, Hour);
SG_UI_Progress_Lock(true);
- bDay = Get_Insolation(Day, Hour);
-
- if( m_bUpdate && (bDay || bWasDay) )
+ if( Update && (bDay || bWasDay) )
{
bWasDay = bDay;
- if( m_bUpdate == 2 )
- {
- DataObject_Update(m_pDirect, 0.0, Range, SG_UI_DATAOBJECT_SHOW);
- }
- else
+ switch( Update )
{
- DataObject_Update(m_pDirect, SG_UI_DATAOBJECT_SHOW);
+ case 1: DataObject_Update(m_pDirect , SG_UI_DATAOBJECT_SHOW); break;
+ case 2: DataObject_Update(m_pDirect, 0.0, dUpdate, SG_UI_DATAOBJECT_SHOW); break;
}
if( bDay )
{
- Direct += *m_pDirect;
-
+ if( !Direct.is_Valid() )
+ {
+ Direct.Create(*m_pDirect);
+ }
+ else
+ {
+ Direct.Add (*m_pDirect);
+ }
+
m_pDirect->Assign(0.0);
}
}
-
- SG_UI_Progress_Lock(false);
}
//-----------------------------------------------------
- if( m_bUpdate )
+ if( Update )
{
m_pDirect->Assign(&Direct);
}
- m_pDirect->Multiply(m_dHour);
- m_pDiffus->Multiply(m_dHour);
+ m_pDirect->Multiply(dHour);
+ m_pDiffus->Multiply(dHour);
+
+ SG_UI_Progress_Lock(false);
return( true );
}
@@ -913,27 +708,38 @@ bool CSolarRadiation::Get_Insolation(int Day)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-bool CSolarRadiation::Get_Insolation(int Day, double Hour)
+bool CSolarRadiation::Get_Insolation(CSG_DateTime Date, double Hour)
{
+ Date.Set_Hour(Hour);
+
+ Process_Set_Text(Date.Format("%A, %d. %B %Y, %X"));
+
+ double JDN = floor(Date.Get_JDN()) - 0.5 + Hour / 24.0; // relate to UTC, avoid problems with daylight saving time
+
+ //-----------------------------------------------------
+ m_Solar_Const = Parameters("SOLARCONST")->asDouble() / 1000.0; // >> [kW / m�]
+
+ m_Solar_Const *= 1.0 + 0.03344 * cos(Date.Get_DayOfYear() * 2.0 * M_PI / 365.25 - 0.048869); // corrected for Earth's orbit eccentricity
+
//-----------------------------------------------------
- if( m_bBending )
+ if( m_Location )
{
bool bDayLight = false;
- #pragma omp parallel for
- for(int y=0; y<Get_NY(); y++)
+ for(int y=0; y<Get_NY() && Process_Get_Okay(); y++)
{
- for(int x=0; x<Get_NX() && Process_Get_Okay(); x++)
+ #pragma omp parallel for
+ for(int x=0; x<Get_NX(); x++)
{
- double Sol_Height = -1.0, Sol_Azimuth = -1.0;
+ double Sun_Height, Sun_Azimuth;
- if( Get_Solar_Position(Day, Hour, m_Lat.asDouble(x, y), m_Lon.asDouble(x, y), Sol_Height, Sol_Azimuth) )
+ if( SG_Get_Sun_Position(JDN, m_Lon.asDouble(x, y), m_Lat.asDouble(x, y), Sun_Height, Sun_Azimuth) )
{
bDayLight = true;
}
- m_Sol_Height .Set_Value(x, y, Sol_Height);
- m_Sol_Azimuth.Set_Value(x, y, Sol_Azimuth);
+ m_Sun_Height .Set_Value(x, y, Sun_Height);
+ m_Sun_Azimuth.Set_Value(x, y, Sun_Azimuth);
}
}
@@ -946,11 +752,11 @@ bool CSolarRadiation::Get_Insolation(int Day, double Hour)
//-----------------------------------------------------
else
{
- double Sol_Height, Sol_Azimuth;
+ double Sun_Height, Sun_Azimuth;
- if( Get_Solar_Position(Day, Hour, m_Latitude, 0.0, Sol_Height, Sol_Azimuth) )
+ if( SG_Get_Sun_Position(JDN, 0.0, m_Latitude, Sun_Height, Sun_Azimuth) )
{
- return( Get_Insolation(Sol_Height, Sol_Azimuth, Hour) );
+ return( Get_Insolation(Sun_Height, Sun_Azimuth, Hour) );
}
}
@@ -964,13 +770,18 @@ bool CSolarRadiation::Get_Insolation(int Day, double Hour)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-bool CSolarRadiation::Get_Insolation(double Sol_Height, double Sol_Azimuth, double Hour)
+bool CSolarRadiation::Get_Insolation(double Sun_Height, double Sun_Azimuth, double Hour)
{
- Get_Shade(Sol_Height, Sol_Azimuth);
+ if( !Get_Shade(Sun_Height, Sun_Azimuth) )
+ {
+ return( false );
+ }
+
+ double dHour = Parameters("HOUR_STEP")->asDouble();
- #pragma omp parallel for
- for(int y=0; y<Get_NY(); y++)
+ for(int y=0; y<Get_NY() && Process_Get_Okay(); y++)
{
+ #pragma omp parallel for
for(int x=0; x<Get_NX(); x++)
{
if( m_pDEM->is_NoData(x, y) )
@@ -983,8 +794,8 @@ bool CSolarRadiation::Get_Insolation(double Sol_Height, double Sol_Azimuth, doub
double Direct, Diffus;
if( Get_Irradiance(x, y,
- m_bBending ? m_Sol_Height .asDouble(x, y) : Sol_Height,
- m_bBending ? m_Sol_Azimuth.asDouble(x, y) : Sol_Azimuth,
+ m_Location ? m_Sun_Height .asDouble(x, y) : Sun_Height,
+ m_Location ? m_Sun_Azimuth.asDouble(x, y) : Sun_Azimuth,
Direct, Diffus) )
{
m_pDirect->Add_Value(x, y, Direct);
@@ -996,22 +807,22 @@ bool CSolarRadiation::Get_Insolation(double Sol_Height, double Sol_Azimuth, doub
{
if( m_pDuration->is_NoData(x, y) )
{
- m_pDuration ->Set_Value(x, y, m_dHour);
+ m_pDuration->Set_Value(x, y, dHour);
}
else
{
- m_pDuration ->Add_Value(x, y, m_dHour);
+ m_pDuration->Add_Value(x, y, dHour);
}
}
if( m_pSunrise && (m_pSunrise->is_NoData(x, y) || m_pSunrise->asDouble(x, y) > Hour) )
{
- m_pSunrise ->Set_Value(x, y, Hour);
+ m_pSunrise->Set_Value(x, y, Hour);
}
if( m_pSunset )
{
- m_pSunset ->Set_Value(x, y, Hour);
+ m_pSunset->Set_Value(x, y, Hour);
}
}
}
@@ -1030,7 +841,7 @@ bool CSolarRadiation::Get_Insolation(double Sol_Height, double Sol_Azimuth, doub
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-inline double CSolarRadiation::Get_Air_Mass(double Sol_Height)
+inline double CSolarRadiation::Get_Air_Mass(double Sun_Height)
{
static const double Air_Mass[32] = // Optical air mass in 1 degree increments for zenith angles >=60 [after LIST, 1968; p. 422]
{
@@ -1039,86 +850,147 @@ inline double CSolarRadiation::Get_Air_Mass(double Sol_Height)
};
//-------------------------------------------------
- double Zenith = M_PI_090 - Sol_Height;
-
- if( Zenith <= 60.0 * M_DEG_TO_RAD )
+ if( Sun_Height > 30.0 * M_DEG_TO_RAD )
{
- return( 1.0 / cos(Zenith) );
+ return( 1.0 / cos(M_PI_090 - Sun_Height) );
}
- else
- {
- double z = M_RAD_TO_DEG * Zenith - 60.0;
- int i = (int)z;
- return( Air_Mass[i] + (z - i) * (Air_Mass[i + 1] - Air_Mass[i]) );
- }
+ double z = 30.0 - M_RAD_TO_DEG * Sun_Height;
+ int i = (int)z;
+
+ return( Air_Mass[i] + (z - i) * (Air_Mass[i + 1] - Air_Mass[i]) );
}
//---------------------------------------------------------
-inline bool CSolarRadiation::Get_Irradiance(int x, int y, double Sol_Height, double Sol_Azimuth, double &Direct, double &Diffus)
+inline bool CSolarRadiation::Get_Irradiance(int x, int y, double Sun_Height, double Sun_Azimuth, double &Direct, double &Diffus)
{
- if( Sol_Height <= 0.0 )
+ //-----------------------------------------------------
+ if( Sun_Height <= 0.0 )
{
return( false );
}
- //-----------------------------------------------------
- double Elevation, Slope, Solar_Angle;
-
- Elevation = m_pDEM->asDouble(x, y);
- Slope = m_Slope.asDouble(x, y);
- Solar_Angle = m_Shade.asDouble(x, y) > 0.0 ? 0.0 : cos(Slope) * cos(Sol_Height - M_PI_090) + sin(Slope) * sin(M_PI_090 - Sol_Height) * cos(Sol_Azimuth - m_Aspect.asDouble(x, y));
+ double Elevation = m_pDEM->asDouble(x, y);
+ double Slope = m_Slope.asDouble(x, y);
+ double Solar_Angle = m_Shade.asDouble(x, y) > 0.0 ? 0.0 : // solar incidence angle measured between the Sun and the inclined surface
+ cos(Slope) * cos(Sun_Height - M_PI_090) + sin(Slope) * sin(M_PI_090 - Sun_Height) * cos(Sun_Azimuth - m_Aspect.asDouble(x, y));
//-----------------------------------------------------
- if( m_Method == 0 ) // Boehner
+ if( m_Method == 3 ) // Hofierka & Suri 2002
{
- double A, E, Vapour;
+ double h_0 = Sun_Height; // * M_RAD_TO_DEG; // ???!!
+ double sin_h_0 = sin(Sun_Height);
+ double d_exp = Solar_Angle;
+ double T_LK = m_pLinke && !m_pLinke->is_NoData(x, y) ? m_pLinke->asDouble(x, y) : m_Linke;
+
+ //-------------------------------------------------
+ double h_0ref = h_0 + 0.061359 * (0.1594 + 1.123 * h_0 + 0.065656 * h_0*h_0) / (1. + 28.9344 * h_0 + 277.3971 * h_0*h_0);
+ double m = exp(-Elevation / 8434.5) / (sin_h_0 + 0.50572 * pow(h_0ref + 6.07995, -1.6364));
+ double d_R = m <= 20.0
+ ? 1. / ( 6.6296 + 1.7513 * m - 0.1202 * m*m + 0.0065 * m*m*m - 0.00013 * m*m*m*m)
+ : 1. / (10.4 + 0.718 * m);
+ double B_0c = m_Solar_Const * exp(-0.8662 * T_LK * m * d_R);
+ double B_hc = B_0c * sin_h_0;
+
+ Direct = B_0c * sin(d_exp); // B_ic
+
+ //-------------------------------------------------
+ double Tn = -0.015843 + 0.030543 * T_LK + 0.0003797 * T_LK*T_LK;
+ double A1 = 0.26463 - 0.061581 * T_LK + 0.0031408 * T_LK*T_LK; if( A1 * Tn < 0.0022 ) A1 = 0.0022 / Tn;
+ double A2 = 2.04020 + 0.018945 * T_LK - 0.011161 * T_LK*T_LK;
+ double A3 = -1.3025 + 0.039231 * T_LK + 0.0085079 * T_LK*T_LK;
+ double F_d = A1 + A2 * sin_h_0 + A3 * sin_h_0*sin_h_0;
+ double D_hc = m_Solar_Const * Tn * F_d;
- Vapour = m_pVapour && !m_pVapour->is_NoData(x, y) ? m_pVapour->asDouble(x, y) : m_Vapour;
- Vapour = Vapour > 0.0 ? sqrt(Vapour) : 0.0;
- E = 0.9160 - 0.05125 * Vapour;
- A = 0.4158 + 0.03990 * Vapour;
+ double K_b = B_hc / (m_Solar_Const * sin_h_0);
+ double F = 0.5 * (1. + cos(Slope)) + (sin(Slope) - Slope * cos(Slope) - M_PI * SG_Get_Square(sin(Slope / 2.0)));
- Direct = pow(E, (1.0 - Elevation / m_Atmosphere) / sin(Sol_Height));
+ if( m_Shade.asDouble(x, y) > 0.0 ) // shadowed surface
+ {
+ Diffus = D_hc * F * 0.25227;
+ }
+ else if( Sun_Height >= 0.1 ) // sunlit surface, height of Sun above 5.7�
+ {
+ F *= 0.00263 - 0.712 * K_b - 0.6883 * K_b*K_b; // * N
- Diffus = m_Atmosphere / (m_Atmosphere - Elevation) * (0.0001165 * SG_Get_Square(M_RAD_TO_DEG * Sol_Height) - 0.0152 * M_RAD_TO_DEG * Sol_Height + A);
- Diffus = Direct * sin(Sol_Height) * (1.0 / (1.0 - Diffus) - 1.0);
+ Diffus = D_hc * F * (1. - K_b) + K_b * sin(d_exp) / sin_h_0;
+ }
+ else
+ {
+ double A_LN = Sun_Azimuth - m_Aspect.asDouble(x, y);
+
+ // if( A_LN < -M_PI_180 ) A_LN += M_PI_360; else if( A_LN > M_PI_180 ) A_LN -= M_PI_360; // quatsch!!!
+
+ F *= 0.00263 - 0.712 * K_b - 0.6883 * K_b*K_b; // * N
+
+ Diffus = D_hc * F * (1. - K_b) + K_b * sin(Slope) * cos(A_LN) / (0.1 - 0.008 * h_0);
+ }
+
+ if( m_pSVF && !m_pSVF->is_NoData(x, y) )
+ {
+ Diffus *= m_pSVF->asDouble(x, y);
+ }
}
//-----------------------------------------------------
- else // TAPES
+ else
{
- double Air_Mass = Get_Air_Mass(Sol_Height) * (m_Pressure / pow(10.0, Elevation * 5.4667E-05)) / 1013.0;
-
- //-------------------------------------------------
- if( m_Method == 1 ) // Air Pressure, Water and Dust Content
+ if( m_Method == 0 ) // Boehner
{
- double AW, TW, TD, TDC;
+ double A, E, Vapour;
- AW = 1.0 - 0.077 * pow(m_Water * Air_Mass, 0.3); // absorption by water vapour
- TW = pow(0.975, m_Water * Air_Mass); // scattering by water vapour | problem (?!): fortran source differs from paper
- TD = pow(0.950, m_Water * m_Dust / 100.0); // scattering by dust | problem (?!): 100ppm := 1, 300ppm := 2
- TDC = pow(0.900, Air_Mass) + 0.026 * (Air_Mass - 1.0); // scattering by a dust free atmosphere
+ Vapour = m_pVapour && !m_pVapour->is_NoData(x, y) ? m_pVapour->asDouble(x, y) : m_Vapour;
+ Vapour = Vapour > 0.0 ? sqrt(Vapour) : 0.0;
+ E = 0.9160 - 0.05125 * Vapour;
+ A = 0.4158 + 0.03990 * Vapour;
- Direct = AW * TW * TD * TDC;
- Diffus = 0.5 * (AW - Direct);
+ Direct = pow(E, (1.0 - Elevation / m_Atmosphere) / sin(Sun_Height));
+
+ Diffus = m_Atmosphere / (m_Atmosphere - Elevation) * (0.0001165 * SG_Get_Square(M_RAD_TO_DEG * Sun_Height) - 0.0152 * M_RAD_TO_DEG * Sun_Height + A);
+ Diffus = Direct * sin(Sun_Height) * (1.0 / (1.0 - Diffus) - 1.0);
}
//-------------------------------------------------
- else // Lumped Atmospheric Transmittance
+ else // TAPES
{
- Direct = pow(m_Transmittance, Air_Mass);
- Diffus = 0.271 - 0.294 * Direct;
+ double Air_Mass = Get_Air_Mass(Sun_Height) * (m_Pressure / pow(10.0, Elevation * 5.4667E-05)) / 1013.0;
+
+ //---------------------------------------------
+ if( m_Method == 1 ) // Air Pressure, Water and Dust Content
+ {
+ double AW, TW, TD, TDC;
+
+ AW = 1.0 - 0.077 * pow(m_Water * Air_Mass, 0.3); // absorption by water vapour
+ TW = pow(0.975, m_Water * Air_Mass); // scattering by water vapour | problem (?!): fortran source differs from paper
+ TD = pow(0.950, m_Water * m_Dust / 100.0); // scattering by dust | problem (?!): 100ppm := 1, 300ppm := 2
+ TDC = pow(0.900, Air_Mass) + 0.026 * (Air_Mass - 1.0); // scattering by a dust free atmosphere
+
+ Direct = AW * TW * TD * TDC;
+ Diffus = 0.5 * (AW - Direct);
+ }
+
+ //---------------------------------------------
+ else // Lumped Atmospheric Transmittance
+ {
+ Direct = pow(m_Transmittance, Air_Mass);
+ Diffus = 0.271 - 0.294 * Direct;
+ }
+
+ if( Sun_Height < M_RAD_TO_DEG )
+ {
+ Diffus *= Sun_Height;
+ }
}
- }
- //-----------------------------------------------------
- Direct = Solar_Angle <= 0.0 ? 0.0 : Solar_Angle * Direct * m_Solar_Const;
+ //-------------------------------------------------
+ Direct = Solar_Angle <= 0.0 ? 0.0 : Solar_Angle * Direct * m_Solar_Const;
- double SVF = m_pSVF && !m_pSVF->is_NoData(x, y) ? m_pSVF->asDouble(x, y) : m_bLocalSVF ? (1.0 + cos(Slope)) / 2.0 : 1.0;
+ double SVF = m_pSVF && !m_pSVF->is_NoData(x, y) ? m_pSVF->asDouble(x, y) : m_bLocalSVF ? (1.0 + cos(Slope)) / 2.0 : 1.0;
- Diffus = m_Solar_Const * Diffus * SVF;
+ Diffus = m_Solar_Const * Diffus * SVF;
+ }
+ //-----------------------------------------------------
if( Direct < 0.0 ) { Direct = 0.0; } else if( Direct > m_Solar_Const ) { Direct = m_Solar_Const; }
if( Diffus < 0.0 ) { Diffus = 0.0; } else if( Diffus > m_Solar_Const ) { Diffus = m_Solar_Const; }
@@ -1140,7 +1012,7 @@ C ==================================================================
C ***************************************************************
C AM Optical air mass in 1 degree increments for zenith angles
C >=60 [LIST, 1968; p. 422]
-C U Water content of a vertical slice of atmosphere in cm:
+C U Water content of a vertical slice of atmosphere in cm:
C 1.5 to 1.7, average=1.68
C D Dust factor: 1=100 ppm (standard); 2=300 ppm
C P Barometric pressure in mb
@@ -1189,9 +1061,14 @@ C ====================================================================*/
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-inline void CSolarRadiation::Get_Shade_Params(double Sol_Height, double Sol_Azimuth, double &dx, double &dy, double &dz)
+inline bool CSolarRadiation::Get_Shade_Params(double Sun_Height, double Sun_Azimuth, double &dx, double &dy, double &dz)
{
- dz = Sol_Azimuth + M_PI_180;
+ if( Sun_Height <= 0.0 )
+ {
+ return( false );
+ }
+
+ dz = Sun_Azimuth + M_PI_180;
dx = sin(dz);
dy = cos(dz);
@@ -1211,36 +1088,42 @@ inline void CSolarRadiation::Get_Shade_Params(double Sol_Height, double Sol_Azim
dy = dy < 0 ? -1 : 1;
}
- dz = tan(Sol_Height) * sqrt(dx*dx + dy*dy) * Get_Cellsize();
+ dz = tan(Sun_Height) * sqrt(dx*dx + dy*dy) * Get_Cellsize();
+
+ return( true );
}
//---------------------------------------------------------
-bool CSolarRadiation::Get_Shade(double Sol_Height, double Sol_Azimuth)
+bool CSolarRadiation::Get_Shade(double Sun_Height, double Sun_Azimuth)
{
const double dShadow = 0.49;
m_Shade.Assign(0.0);
- if( !m_bBending )
+ //-----------------------------------------------------
+ if( m_Location == 0 )
{
double dx, dy, dz;
- Get_Shade_Params(Sol_Height, Sol_Azimuth, dx, dy, dz);
+ if( !Get_Shade_Params(Sun_Height, Sun_Azimuth, dx, dy, dz) )
+ {
+ return( false );
+ }
- #pragma omp parallel for
- for(int y=0; y<Get_NY(); y++)
+ for(int y=0; y<Get_NY() && Process_Get_Okay(); y++)
{
+ #pragma omp parallel for
for(int x=0; x<Get_NX(); x++)
{
if( !m_pDEM->is_NoData(x, y) )
{
switch( m_Shadowing )
{
- default: // slim
+ case 0: // slim
Set_Shade(x, y, m_pDEM->asDouble(x, y), dx, dy, dz);
break;
- case 1: // fat
+ case 1: // fat
Set_Shade(x - dShadow, y - dShadow, m_pDEM->asDouble(x, y), dx, dy, dz);
Set_Shade(x + dShadow, y - dShadow, m_pDEM->asDouble(x, y), dx, dy, dz);
Set_Shade(x - dShadow, y + dShadow, m_pDEM->asDouble(x, y), dx, dy, dz);
@@ -1255,20 +1138,20 @@ bool CSolarRadiation::Get_Shade(double Sol_Height, double Sol_Azimuth)
//-----------------------------------------------------
else
{
- #pragma omp parallel for
- for(int y=0; y<Get_NY(); y++)
+ for(int y=0; y<Get_NY() && Process_Get_Okay(); y++)
{
+ #pragma omp parallel for
for(int x=0; x<Get_NX(); x++)
{
if( !m_pDEM->is_NoData(x, y) )
{
switch( m_Shadowing )
{
- default: // slim
+ case 0: // slim
Set_Shade_Bended(x, y, m_pDEM->asDouble(x, y));
break;
- case 1: // fat
+ case 1: // fat
Set_Shade_Bended(x - dShadow, y - dShadow, m_pDEM->asDouble(x, y));
Set_Shade_Bended(x + dShadow, y - dShadow, m_pDEM->asDouble(x, y));
Set_Shade_Bended(x - dShadow, y + dShadow, m_pDEM->asDouble(x, y));
@@ -1280,6 +1163,7 @@ bool CSolarRadiation::Get_Shade(double Sol_Height, double Sol_Azimuth)
}
}
+ //-----------------------------------------------------
return( true );
}
@@ -1318,13 +1202,16 @@ void CSolarRadiation::Set_Shade_Bended(double x, double y, double z)
{
double dx, dy, dz;
- Get_Shade_Params(m_Sol_Height.asDouble(ix, iy), m_Sol_Azimuth.asDouble(ix, iy), dx, dy, dz);
+ if( !Get_Shade_Params(m_Sun_Height.asDouble(ix, iy), m_Sun_Azimuth.asDouble(ix, iy), dx, dy, dz) )
+ {
+ return;
+ }
x += dx; ix = (int)x;
y += dy; iy = (int)y;
z -= dz;
- if( !is_InGrid(ix, iy) )
+ if( !m_pDEM->is_InGrid(ix, iy) )
{
return;
}
@@ -1351,113 +1238,3 @@ void CSolarRadiation::Set_Shade_Bended(double x, double y, double z)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-inline int CSolarRadiation::Get_Day_of_Year(int Month)
-{
- static const int Day[13] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
-
- return( Month < 0 ? 0 : Month > 12 ? Day[12] : Day[Month] );
-}
-
-//---------------------------------------------------------
-inline bool CSolarRadiation::Get_Solar_Position(int Day, double Hour, double LAT, double LON, double &Sol_Height, double &Sol_Azimuth)
-{
- static const double ECLIPTIC_OBL = M_DEG_TO_RAD * 23.43999; // obliquity of ecliptic
-
- int i;
-
- double JD, T, M, L, X, Y, Z, R, UTime,
- DEC, RA, theta, tau,
- Month, Year = 2000;
-
- //-----------------------------------------------------
- Day %= 365;
-
- for(Month=1, i=0; i<=12; i++)
- {
- if( Day < Get_Day_of_Year(i) )
- {
- Month = i;
- Day -= Get_Day_of_Year(i - 1);
- break;
- }
- }
-
- if( Month < 1 || Month > 12 ) // nur Tag (1 - 365) zaehlt...
- {
- Month = 1;
- }
-
- if( Month <= 2 )
- {
- Month += 12;
- Year -= 1;
- }
-
-
- //-----------------------------------------------------
-
-// UTime = Hour - LON * 12.0 / M_PI;
- UTime = Hour;
-
-
- //-----------------------------------------------------
- // 1. Julian Date...
-
- JD = (int)(365.25 * Year) + (int)(30.6001 * (Month + 1)) - 15 + 1720996.5 + Day + UTime / 24.0;
- T = (JD - 2451545.0 ) / 36525.0; // number of Julian centuries since 2000/01/01 at 12 UT (JD = 2451545.0)
-
-
- //-----------------------------------------------------
- // 2. Solar Coordinates (according to: Jean Meeus: Astronomical Algorithms), accuracy of 0.01 degree
-
- M = M_DEG_TO_RAD * (357.52910 + 35999.05030 * T - 0.0001559 * T * T - 0.00000048 * T * T * T); // mean anomaly
- L = M_DEG_TO_RAD * ( (280.46645 + 36000.76983 * T + 0.0003032 * T * T) // mean longitude
- + ( (1.914600 - 0.004817 * T - 0.000014 * T * T) * sin(M)
- + (0.019993 - 0.000101 * T) * sin(2 * M) + 0.000290 * sin(3 * M) // true longitude
- )
- );
-
-
- //-----------------------------------------------------
- // 3. convert ecliptic longitude to right ascension RA and declination delta
-
- X = cos(L);
- Y = cos(ECLIPTIC_OBL) * sin(L);
- Z = sin(ECLIPTIC_OBL) * sin(L);
- R = sqrt(1.0 - Z*Z);
-
- DEC = atan2(Z, R);
- RA = 2.0 * atan2(Y, (X + R));
-
-
- //-----------------------------------------------------
- // 4. compute sidereal time (degree) at Greenwich local sidereal time at longitude (Degree)
-
- theta = LON + M_DEG_TO_RAD * (280.46061837 + 360.98564736629 * (JD - 2451545.0) + T*T * (0.000387933 - T / 38710000.0));
-
-
- //-----------------------------------------------------
- // 5. compute local hour angle (degree)
-
- tau = theta - RA;
-
-
- //-----------------------------------------------------
- // 6. convert (tau, delta) to horizon coordinates (h, az) of the observer
-
- Sol_Height = asin ( sin(LAT) * sin(DEC) + cos(LAT) * cos(DEC) * cos(tau) );
-
- Sol_Azimuth = atan2( -sin(tau) * cos(DEC), cos(LAT) * sin(DEC) - sin(LAT) * cos(DEC) * cos(tau) );
-// Sol_Azimuth = atan2( -sin(Tau), cos(LAT) * tan(DEC) - sin(LAT) * cos(Tau) ); // previous formula gives same result but is better because of division by zero effects...
-
- return( Sol_Height > 0.0 );
-}
-
-
-///////////////////////////////////////////////////////////
-// //
-// //
-// //
-///////////////////////////////////////////////////////////
-
-//---------------------------------------------------------
diff --git a/src/modules/terrain_analysis/ta_lighting/SolarRadiation.h b/src/modules/terrain_analysis/ta_lighting/SolarRadiation.h
index f05fac0..11e8b4b 100644
--- a/src/modules/terrain_analysis/ta_lighting/SolarRadiation.h
+++ b/src/modules/terrain_analysis/ta_lighting/SolarRadiation.h
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: SolarRadiation.h 2137 2014-06-05 08:23:17Z oconrad $
+ * Version $Id: SolarRadiation.h 2636 2015-10-06 16:10:24Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -74,6 +74,8 @@
//---------------------------------------------------------
#include "MLB_Interface.h"
+#include <saga_api/datetime.h>
+
///////////////////////////////////////////////////////////
// //
@@ -90,6 +92,7 @@ public:
protected:
+ virtual int On_Parameter_Changed (CSG_Parameters *pParameters, CSG_Parameter *pParameter);
virtual int On_Parameters_Enable (CSG_Parameters *pParameters, CSG_Parameter *pParameter);
virtual bool On_Execute (void);
@@ -97,36 +100,32 @@ protected:
private:
- bool m_bLocalSVF, m_bBending;
+ bool m_bLocalSVF;
- int m_Time, m_Method, m_Shadowing, m_Day_A, m_Day_B, m_dDays, m_bUpdate;
+ int m_Method, m_Location, m_Shadowing;
- double m_Solar_Const, m_Hour_A, m_Hour_B, m_dHour, m_Latitude, m_Atmosphere, m_Vapour, m_Transmittance, m_Pressure, m_Water, m_Dust;
+ double m_Solar_Const, m_Latitude, m_Linke, m_Vapour, m_Atmosphere, m_Transmittance, m_Pressure, m_Water, m_Dust;
- CSG_Grid *m_pDEM, *m_pVapour, *m_pSVF, *m_pDirect, *m_pDiffus, *m_pTotal, *m_pRatio, *m_pDuration, *m_pSunrise, *m_pSunset,
- m_Slope, m_Aspect, m_Shade, m_Lat, m_Lon, m_Sol_Height, m_Sol_Azimuth;
+ CSG_Grid *m_pDEM, *m_pSVF, *m_pLinke, *m_pVapour, *m_pDirect, *m_pDiffus, *m_pTotal, *m_pRatio, *m_pDuration, *m_pSunrise, *m_pSunset,
+ m_Slope, m_Aspect, m_Shade, m_Lat, m_Lon, m_Sun_Height, m_Sun_Azimuth;
- bool Finalise (void);
+ bool Finalize (void);
bool Get_Insolation (void);
- bool Get_Insolation (int Day);
- bool Get_Insolation (int Day, double Hour);
- bool Get_Insolation (double Sol_Height, double Sol_Azimuth, double Hour);
-
- double Get_Air_Mass (double Sol_Height);
+ bool Get_Insolation (CSG_DateTime Date);
+ bool Get_Insolation (CSG_DateTime Date, double Hour);
+ bool Get_Insolation (double Sun_Height, double Sun_Azimuth, double Hour);
- bool Get_Irradiance (int x, int y, double Sol_Height, double Sol_Azimuth, double &Direct, double &Diffus);
+ double Get_Air_Mass (double Sun_Height);
+ bool Get_Irradiance (int x, int y, double Sun_Height, double Sun_Azimuth, double &Direct, double &Diffus);
bool is_Shadowed (int x, int y);
- void Get_Shade_Params (double Sol_Height, double Sol_Azimuth, double &dx, double &dy, double &dz);
- bool Get_Shade (double Sol_Height, double Sol_Azimuth);
+ bool Get_Shade_Params (double Sun_Height, double Sun_Azimuth, double &dx, double &dy, double &dz);
+ bool Get_Shade (double Sun_Height, double Sun_Azimuth);
void Set_Shade (double x, double y, double z, double dx, double dy, double dz);
void Set_Shade_Bended (double x, double y, double z);
- int Get_Day_of_Year (int Month);
- bool Get_Solar_Position (int Day, double Hour, double Lat, double Lon, double &Sol_Height, double &Sol_Azimuth);
-
};
diff --git a/src/modules/terrain_analysis/ta_morphometry/MLB_Interface.cpp b/src/modules/terrain_analysis/ta_morphometry/MLB_Interface.cpp
index 16e7da8..86eb1cb 100644
--- a/src/modules/terrain_analysis/ta_morphometry/MLB_Interface.cpp
+++ b/src/modules/terrain_analysis/ta_morphometry/MLB_Interface.cpp
@@ -148,6 +148,7 @@ CSG_Module * Create_Module(int i)
case 24: return( new CTop_Hat );
case 25: return( new CFuzzy_Landform_Elements );
case 26: return( new CCurvature_UpDownSlope );
+ case 27: return( new CWind_Exposition );
case 30: return( NULL );
default: return( MLB_INTERFACE_SKIP_MODULE );
diff --git a/src/modules/terrain_analysis/ta_morphometry/wind_effect.cpp b/src/modules/terrain_analysis/ta_morphometry/wind_effect.cpp
index 96a8fbc..a175ecc 100644
--- a/src/modules/terrain_analysis/ta_morphometry/wind_effect.cpp
+++ b/src/modules/terrain_analysis/ta_morphometry/wind_effect.cpp
@@ -77,17 +77,24 @@ CWind_Effect::CWind_Effect(void)
Set_Name (_TL("Wind Effect (Windward / Leeward Index)"));
- Set_Author (SG_T("J.Boehner, A.Ringeler (c) 2008, O.Conrad (c) 2011"));
+ Set_Author ("J.Boehner, A.Ringeler (c) 2008, O.Conrad (c) 2011");
Set_Description (_TW(
"The 'Wind Effect' is a dimensionless index. Values below 1 indicate wind shadowed areas "
"whereas values above 1 indicate areas exposed to wind, all with regard to the specified "
"wind direction. Wind direction, i.e. the direction into which the wind blows, might be "
"either constant or variying in space, if a wind direction grid is supplied.\n"
- "\nReferences:\n"
- "- Boehner, J., Antonic, O. (2009): 'Land-surface parameters specific to topo-climatology'."
+ "\nReferences:\n<ul>"
+ "<ul><li>"
+ " Boehner, J., Antonic, O. (2009):"
+ " Land-surface parameters specific to topo-climatology."
" in: Hengl, T., Reuter, H. (Eds.): 'Geomorphometry - Concepts, Software, Applications'."
- " Developments in Soil Science, Volume 33, p.195-226, Elsevier.\n"
+ " Developments in Soil Science, Volume 33, p.195-226, Elsevier."
+ "</li><li>"
+ " Gerlitz, L., Conrad, O., B�hner, J. (2015):"
+ " Large scale atmospheric forcing and topographic modification of precipitation rates over High Asia � a neural network based approach."
+ " Earth System Dynamics, 6, 1-21. doi:10.5194/esd-6-1-2015."
+ "</li></ul>\n"
));
Parameters.Add_Grid(
@@ -105,7 +112,7 @@ CWind_Effect::CWind_Effect(void)
Parameters.Add_Choice(
pNode , "DIR_UNITS" , _TL("Wind Direction Units"),
_TL(""),
- CSG_String::Format(SG_T("%s|%s|"),
+ CSG_String::Format("%s|%s|",
_TL("radians"),
_TL("degree")
), 0
@@ -175,8 +182,6 @@ CWind_Effect::CWind_Effect(void)
///////////////////////////////////////////////////////////
// //
-// //
-// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
@@ -202,14 +207,12 @@ int CWind_Effect::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Paramete
pParameters->Set_Enabled("PYRAMIDS" , pParameter->asBool() == false);
}
- return( 1 );
+ return( CSG_Module_Grid::On_Parameters_Enable(pParameters, pParameter) );
}
///////////////////////////////////////////////////////////
// //
-// //
-// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
@@ -369,8 +372,6 @@ bool CWind_Effect::On_Execute(void)
///////////////////////////////////////////////////////////
// //
-// //
-// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
@@ -448,8 +449,6 @@ inline bool CWind_Effect::Get_Z(const TSG_Point &Position, double Distance, doub
///////////////////////////////////////////////////////////
// //
-// //
-// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
@@ -522,8 +521,6 @@ void CWind_Effect::Get_Lee(int x, int y, double &Sum_A, double &Sum_B)
///////////////////////////////////////////////////////////
// //
-// //
-// //
///////////////////////////////////////////////////////////
//---------------------------------------------------------
@@ -579,3 +576,169 @@ void CWind_Effect::Get_Lee_Old(int x, int y, double dx, double dy, double &Sum_A
///////////////////////////////////////////////////////////
//---------------------------------------------------------
+CWind_Exposition::CWind_Exposition(void)
+{
+ Set_Name (_TL("Wind Exposition Index"));
+
+ Set_Author ("J.Boehner, O.Conrad (c) 2015");
+
+ Set_Description (_TW(
+ "This tool calculates the average 'Wind Effect Index' for all directions using an angular step. "
+ "Like the 'Wind Effect Index' it is a dimensionless index. Values below 1 indicate wind shadowed areas "
+ "whereas values above 1 indicate areas exposed to wind.\n"
+ "\nReferences:\n"
+ "<ul><li>"
+ " Boehner, J., Antonic, O. (2009):"
+ " Land-surface parameters specific to topo-climatology."
+ " in: Hengl, T., Reuter, H. (Eds.): 'Geomorphometry - Concepts, Software, Applications'."
+ " Developments in Soil Science, Volume 33, p.195-226, Elsevier."
+ "</li><li>"
+ " Gerlitz, L., Conrad, O., B�hner, J. (2015):"
+ " Large scale atmospheric forcing and topographic modification of precipitation rates over High Asia � a neural network based approach."
+ " Earth System Dynamics, 6, 1-21. doi:10.5194/esd-6-1-2015."
+ "</li></ul>\n"
+ ));
+
+ Parameters.Add_Grid(
+ NULL , "DEM" , _TL("Elevation"),
+ _TL(""),
+ PARAMETER_INPUT
+ );
+
+ Parameters.Add_Grid(
+ NULL , "EXPOSITION" , _TL("Wind Exposition"),
+ _TL(""),
+ PARAMETER_OUTPUT
+ );
+
+ Parameters.Add_Value(
+ NULL , "MAXDIST" , _TL("Search Distance [km]"),
+ _TL(""),
+ PARAMETER_TYPE_Double, 300.0, 0.0, true
+ );
+
+ Parameters.Add_Value(
+ NULL , "STEP" , _TL("Angular Step Size (Degree)"),
+ _TL(""),
+ PARAMETER_TYPE_Double, 15.0, 1.0, true, 45.0, true
+ );
+
+ Parameters.Add_Value(
+ NULL , "OLDVER" , _TL("Old Version"),
+ _TL("use old version for constant wind direction (no acceleration and averaging option)"),
+ PARAMETER_TYPE_Bool, false
+ );
+
+ Parameters.Add_Value(
+ NULL , "ACCEL" , _TL("Acceleration"),
+ _TL(""),
+ PARAMETER_TYPE_Double, 1.5, 1.0, true
+ );
+
+ Parameters.Add_Value(
+ NULL , "PYRAMIDS" , _TL("Elevation Averaging"),
+ _TL("use more averaged elevations when looking at increasing distances"),
+ PARAMETER_TYPE_Bool, false
+ );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+int CWind_Exposition::On_Parameters_Enable(CSG_Parameters *pParameters, CSG_Parameter *pParameter)
+{
+ if( !SG_STR_CMP(pParameter->Get_Identifier(), "OLDVER") )
+ {
+ pParameters->Set_Enabled("ACCEL" , pParameter->asBool() == false);
+ pParameters->Set_Enabled("PYRAMIDS" , pParameter->asBool() == false);
+ }
+
+ return( CSG_Module_Grid::On_Parameters_Enable(pParameters, pParameter) );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool CWind_Exposition::On_Execute(void)
+{
+ //-----------------------------------------------------
+ CSG_Grid Exposition(*Get_System()), *pExposition = Parameters("EXPOSITION")->asGrid();
+
+ CSG_Colors Colors(5);
+
+ Colors.Set_Color(0, 255, 127, 63);
+ Colors.Set_Color(1, 255, 255, 127);
+ Colors.Set_Color(2, 255, 255, 255);
+ Colors.Set_Color(3, 127, 127, 175);
+ Colors.Set_Color(4, 0, 0, 100);
+
+ DataObject_Set_Colors(pExposition, Colors);
+
+ //-----------------------------------------------------
+ CWind_Effect Tool;
+
+ Tool.Settings_Push(NULL);
+
+ Tool.Set_Parameter("EFFECT" , &Exposition);
+ Tool.Set_Parameter("DEM" , Parameters("DEM" ));
+ Tool.Set_Parameter("MAXDIST" , Parameters("MAXDIST" ));
+ Tool.Set_Parameter("OLDVER" , Parameters("OLDVER" ));
+ Tool.Set_Parameter("ACCEL" , Parameters("ACCEL" ));
+ Tool.Set_Parameter("PYRAMIDS" , Parameters("PYRAMIDS"));
+
+ //-----------------------------------------------------
+ int nDirections = 0;
+ double dDirection = Parameters("STEP")->asDouble();
+
+ for(double Direction=0.0; Direction<360.0 && Process_Get_Okay(); Direction+=dDirection)
+ {
+ Process_Set_Text(CSG_String::Format("%s: %.1f", _TL("Direction"), Direction));
+
+ Tool.Set_Parameter("DIR_CONST", Direction);
+
+ SG_UI_Msg_Lock(true);
+
+ if( Tool.Execute() )
+ {
+ SG_UI_Progress_Lock(true);
+
+ if( nDirections++ == 0 )
+ {
+ pExposition->Assign(&Exposition);
+ }
+ else
+ {
+ pExposition->Add (Exposition);
+ }
+
+ SG_UI_Progress_Lock(false);
+ }
+
+ SG_UI_Msg_Lock(false);
+ }
+
+ //-----------------------------------------------------
+ if( nDirections > 0 )
+ {
+ pExposition->Multiply(1.0 / (double)nDirections);
+
+ return( true );
+ }
+
+ return( false );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
diff --git a/src/modules/terrain_analysis/ta_morphometry/wind_effect.h b/src/modules/terrain_analysis/ta_morphometry/wind_effect.h
index 9da3901..03e0a55 100644
--- a/src/modules/terrain_analysis/ta_morphometry/wind_effect.h
+++ b/src/modules/terrain_analysis/ta_morphometry/wind_effect.h
@@ -80,7 +80,7 @@ class CWind_Effect : public CSG_Module_Grid
public:
CWind_Effect(void);
- virtual CSG_String Get_MenuPath (void) { return( _TL("A:Terrain Analysis|Climate and Weather" )); }
+ virtual CSG_String Get_MenuPath (void) { return( _TL("A:Terrain Analysis|Climate and Weather") ); }
protected:
@@ -117,6 +117,31 @@ private:
///////////////////////////////////////////////////////////
// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+class CWind_Exposition : public CSG_Module_Grid
+{
+public:
+ CWind_Exposition(void);
+
+ virtual CSG_String Get_MenuPath (void) { return( _TL("A:Terrain Analysis|Climate and Weather") ); }
+
+
+protected:
+
+ virtual int On_Parameters_Enable (CSG_Parameters *pParameters, CSG_Parameter *pParameter);
+
+ virtual bool On_Execute (void);
+
+
+private:
+
+};
+
+
+///////////////////////////////////////////////////////////
+// //
// //
// //
///////////////////////////////////////////////////////////
diff --git a/src/modules/tin/tin_viewer/tin_view_module.cpp b/src/modules/tin/tin_viewer/tin_view_module.cpp
index 653a5e9..dbcb755 100644
--- a/src/modules/tin/tin_viewer/tin_view_module.cpp
+++ b/src/modules/tin/tin_viewer/tin_view_module.cpp
@@ -120,13 +120,6 @@ CTIN_View_Module::CTIN_View_Module(void)
//---------------------------------------------------------
bool CTIN_View_Module::On_Execute(void)
{
- if( !SG_UI_Get_Window_Main() )
- {
- Message_Add(_TL("point cloud viewer can only be run from graphical user interface"));
-
- return( false );
- }
-
CSG_TIN *pTIN = Parameters("TIN")->asTIN();
if( pTIN->Get_Count() <= 0 )
diff --git a/src/saga_core/saga_api/api_callback.cpp b/src/saga_core/saga_api/api_callback.cpp
index 70a0d1a..45b99bd 100644
--- a/src/saga_core/saga_api/api_callback.cpp
+++ b/src/saga_core/saga_api/api_callback.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: api_callback.cpp 2428 2015-02-26 17:14:47Z oconrad $
+ * Version $Id: api_callback.cpp 2640 2015-10-07 17:29:38Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -439,6 +439,20 @@ void SG_UI_Msg_Add_Execution(const CSG_String &Message, bool bNewLine, TSG_UI_M
///////////////////////////////////////////////////////////
//---------------------------------------------------------
+void SG_UI_ProgressAndMsg_Lock (bool bOn)
+{
+ SG_UI_Progress_Lock(bOn);
+ SG_UI_Msg_Lock (bOn);
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
bool SG_UI_DataObject_Add(CSG_Data_Object *pDataObject, int Show)
{
if( gSG_UI_Callback && pDataObject )
diff --git a/src/saga_core/saga_api/api_core.h b/src/saga_core/saga_api/api_core.h
index 6db93c5..4d83058 100644
--- a/src/saga_core/saga_api/api_core.h
+++ b/src/saga_core/saga_api/api_core.h
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: api_core.h 2564 2015-09-01 13:06:20Z oconrad $
+ * Version $Id: api_core.h 2640 2015-10-07 17:29:38Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -1372,6 +1372,8 @@ SAGA_API_DLL_EXPORT void SG_UI_Msg_Add (const CSG_String &Message, bool b
SAGA_API_DLL_EXPORT void SG_UI_Msg_Add_Error (const CSG_String &Message);
SAGA_API_DLL_EXPORT void SG_UI_Msg_Add_Execution (const CSG_String &Message, bool bNewLine, TSG_UI_MSG_STYLE Style = SG_UI_MSG_STYLE_NORMAL);
+SAGA_API_DLL_EXPORT void SG_UI_ProgressAndMsg_Lock (bool bOn);
+
SAGA_API_DLL_EXPORT bool SG_UI_DataObject_Add (class CSG_Data_Object *pDataObject, int Show);
SAGA_API_DLL_EXPORT bool SG_UI_DataObject_Update (class CSG_Data_Object *pDataObject, int Show, class CSG_Parameters *pParameters);
SAGA_API_DLL_EXPORT bool SG_UI_DataObject_Show (class CSG_Data_Object *pDataObject, int Show);
diff --git a/src/saga_core/saga_api/api_memory.cpp b/src/saga_core/saga_api/api_memory.cpp
index 47381e6..b15d80f 100644
--- a/src/saga_core/saga_api/api_memory.cpp
+++ b/src/saga_core/saga_api/api_memory.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: api_memory.cpp 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: api_memory.cpp 2639 2015-10-07 10:59:17Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -427,12 +427,12 @@ bool CSG_Array::Inc_Array (void **pArray)
//---------------------------------------------------------
bool CSG_Array::Dec_Array (bool bShrink)
{
- return( m_Values > 0 ? Set_Array(m_nValues - 1, bShrink) : false );
+ return( m_nValues > 0 ? Set_Array(m_nValues - 1, bShrink) : false );
}
bool CSG_Array::Dec_Array (void **pArray, bool bShrink)
{
- return( m_Values > 0 ? Set_Array(m_nValues - 1, pArray, bShrink) : false );
+ return( m_nValues > 0 ? Set_Array(m_nValues - 1, pArray, bShrink) : false );
}
diff --git a/src/saga_core/saga_api/datetime.cpp b/src/saga_core/saga_api/datetime.cpp
index cbc2743..3a90082 100644
--- a/src/saga_core/saga_api/datetime.cpp
+++ b/src/saga_core/saga_api/datetime.cpp
@@ -193,6 +193,21 @@ CSG_DateTime & CSG_DateTime::Set_Hour(unsigned short Value)
return( *this );
}
+CSG_DateTime & CSG_DateTime::Set_Hour(double Value)
+{
+ m_pDateTime->ResetTime();
+
+ if( Value > 0.0 && Value < 24.0 )
+ {
+ m_pDateTime->SetHour ((wxDateTime::wxDateTime_t)Value); Value = (Value - (wxDateTime::wxDateTime_t)Value) * 60.0;
+ m_pDateTime->SetMinute ((wxDateTime::wxDateTime_t)Value); Value = (Value - (wxDateTime::wxDateTime_t)Value) * 60.0;
+ m_pDateTime->SetSecond ((wxDateTime::wxDateTime_t)Value); Value = (Value - (wxDateTime::wxDateTime_t)Value) * 1000.0;
+ m_pDateTime->SetMillisecond((wxDateTime::wxDateTime_t)Value);
+ }
+
+ return( *this );
+}
+
//---------------------------------------------------------
CSG_DateTime & CSG_DateTime::Set_Day(unsigned short Value)
{
@@ -233,6 +248,26 @@ CSG_DateTime & CSG_DateTime::Reset_Time(void)
return( *this );
}
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+CSG_DateTime & CSG_DateTime::Make_UTC(bool noDST)
+{
+ m_pDateTime->MakeUTC(noDST);
+
+ return( *this );
+}
+
+//---------------------------------------------------------
+bool CSG_DateTime::is_DST(void) const
+{
+ return( m_pDateTime->IsDST() != 0 );
+}
+
+
///////////////////////////////////////////////////////////
// //
///////////////////////////////////////////////////////////
@@ -372,32 +407,32 @@ bool CSG_DateTime::is_StrictlyBetween(const CSG_DateTime &t1, const CSG_DateTime
//---------------------------------------------------------
CSG_String CSG_DateTime::Format(const CSG_String &Format) const
{
- wxString s(m_pDateTime->Format(Format.c_str())); return( &s ); // CSG_String _s(&s); return( _s );
+ wxString s(m_pDateTime->Format(Format.c_str())); CSG_String _s(&s); return( _s );
}
CSG_String CSG_DateTime::Format_Date(void) const
{
- wxString s(m_pDateTime->FormatDate()); return( &s ); // CSG_String _s(&s); return( _s );
+ wxString s(m_pDateTime->FormatDate()); CSG_String _s(&s); return( _s );
}
CSG_String CSG_DateTime::Format_Time(void) const
{
- wxString s(m_pDateTime->FormatTime()); return( &s ); // CSG_String _s(&s); return( _s );
+ wxString s(m_pDateTime->FormatTime()); CSG_String _s(&s); return( _s );
}
CSG_String CSG_DateTime::Format_ISODate(void) const
{
- wxString s(m_pDateTime->FormatISODate()); return( &s ); // CSG_String _s(&s); return( _s );
+ wxString s(m_pDateTime->FormatISODate()); CSG_String _s(&s); return( _s );
}
CSG_String CSG_DateTime::Format_ISOTime(void) const
{
- wxString s(m_pDateTime->FormatISOTime()); return( &s ); // CSG_String _s(&s); return( _s );
+ wxString s(m_pDateTime->FormatISOTime()); CSG_String _s(&s); return( _s );
}
CSG_String CSG_DateTime::Format_ISOCombined(char sep) const
{
- wxString s(m_pDateTime->FormatISOCombined(sep)); return( &s ); // CSG_String _s(&s); return( _s );
+ wxString s(m_pDateTime->FormatISOCombined(sep)); CSG_String _s(&s); return( _s );
}
//---------------------------------------------------------
@@ -448,28 +483,44 @@ bool CSG_DateTime::Parse_ISOTime(const CSG_String &date)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-CSG_DateTime::Month CSG_DateTime::Get_Current_Month(void) { return( (Month)wxDateTime::GetCurrentMonth() ); }
-int CSG_DateTime::Get_Current_Year (void) { return( wxDateTime::GetCurrentYear () ); }
+CSG_DateTime::TSG_DateTime CSG_DateTime::Get_Current_Day(void)
+{
+ CSG_DateTime Now;
+
+ Now.Set_To_Current();
+
+ return( Now.Get_Day() );
+}
+
+CSG_DateTime::Month CSG_DateTime::Get_Current_Month(void)
+{
+ return( (Month)wxDateTime::GetCurrentMonth() );
+}
+
+int CSG_DateTime::Get_Current_Year(void)
+{
+ return( wxDateTime::GetCurrentYear() );
+}
//---------------------------------------------------------
CSG_String CSG_DateTime::Get_MonthName(Month month, NameFlags flags)
{
- wxString s(wxDateTime::GetMonthName ((wxDateTime::Month)month , (wxDateTime::NameFlags)flags)); return( &s ); // CSG_String _s(&s); return( _s );
+ wxString s(wxDateTime::GetMonthName ((wxDateTime::Month)month , (wxDateTime::NameFlags)flags)); CSG_String _s(&s); return( _s );
}
CSG_String CSG_DateTime::Get_EnglishMonthName(Month month, NameFlags flags)
{
- wxString s(wxDateTime::GetEnglishMonthName ((wxDateTime::Month)month , (wxDateTime::NameFlags)flags)); return( &s ); // CSG_String _s(&s); return( _s );
+ wxString s(wxDateTime::GetEnglishMonthName ((wxDateTime::Month)month , (wxDateTime::NameFlags)flags)); CSG_String _s(&s); return( _s );
}
CSG_String CSG_DateTime::Get_WeekDayName(WeekDay weekday, NameFlags flags)
{
- wxString s(wxDateTime::GetWeekDayName ((wxDateTime::WeekDay)weekday, (wxDateTime::NameFlags)flags)); return( &s ); // CSG_String _s(&s); return( _s );
+ wxString s(wxDateTime::GetWeekDayName ((wxDateTime::WeekDay)weekday, (wxDateTime::NameFlags)flags)); CSG_String _s(&s); return( _s );
}
CSG_String CSG_DateTime::Get_EnglishWeekDayName(WeekDay weekday, NameFlags flags)
{
- wxString s(wxDateTime::GetEnglishWeekDayName((wxDateTime::WeekDay)weekday, (wxDateTime::NameFlags)flags)); return( &s ); // CSG_String _s(&s); return( _s );
+ wxString s(wxDateTime::GetEnglishWeekDayName((wxDateTime::WeekDay)weekday, (wxDateTime::NameFlags)flags)); CSG_String _s(&s); return( _s );
}
//---------------------------------------------------------
@@ -503,7 +554,107 @@ CSG_DateTime CSG_DateTime::Now(void)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
+CSG_String CSG_DateTime::Get_Month_Choices(void)
+{
+ CSG_String Choices;
+
+ Choices.Printf("%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|",
+ _TL("January"), _TL("February"), _TL("March" ), _TL("April" ), _TL("May" ), _TL("June" ),
+ _TL("July" ), _TL("August" ), _TL("September"), _TL("October"), _TL("November"), _TL("December")
+ );
+ return( Choices );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+#include "mat_tools.h"
+
+//---------------------------------------------------------
+/**
+ * Calculates the Sun's position for given date and time
+ * as declination and right ascension angles (radians).
+ * Solar coordinates according to
+ * Jean Meeus: Astronomical Algorithms, accuracy of 0.01 degree
+*/
+//---------------------------------------------------------
+bool SG_Get_Sun_Position(double JulianDayNumber, double &RA, double &Dec)
+{
+ //-----------------------------------------------------
+ double T = (JulianDayNumber - 2451545.0 ) / 36525.0; // Number of Julian centuries since 2000/01/01 at 12 UT (JDN = 2451545.0)
+
+ double M = M_DEG_TO_RAD * (357.52910 + 35999.05030 * T - 0.0001559 * T*T - 0.00000048 * T*T*T); // mean anomaly
+ double L = M_DEG_TO_RAD * ((280.46645 + 36000.76983 * T + 0.0003032 * T*T) // mean longitude
+ + ((1.914600 - 0.004817 * T - 0.000014 * T*T) * sin(M)
+ + (0.019993 - 0.000101 * T) * sin(2.0 * M) + 0.000290 * sin(3.0 * M))); // true longitude
+
+ //-----------------------------------------------------
+ // convert ecliptic longitude to right ascension RA and declination delta
+
+ static const double Ecliptic_Obliquity = M_DEG_TO_RAD * 23.43929111;
+
+ double X = cos(L);
+ double Y = cos(Ecliptic_Obliquity) * sin(L);
+ double Z = sin(Ecliptic_Obliquity) * sin(L);
+ double R = sqrt(1.0 - Z*Z);
+
+ Dec = atan2(Z, R);
+ RA = 2.0 * atan2(Y, (X + R));
+
+ return( true );
+}
+
+//---------------------------------------------------------
+bool SG_Get_Sun_Position(const CSG_DateTime &Time, double &RA, double &Dec)
+{
+ return( SG_Get_Sun_Position(Time.Get_JDN(), RA, Dec) );
+}
+
+//---------------------------------------------------------
+/**
+ * Calculates the Sun's position for given date and time
+ * and position on Earth as given by longitude and latitude (radians).
+ * Height and Azimuth are calculated as radians.
+ * Returns true if Sun is above horizon.
+*/
+//---------------------------------------------------------
+bool SG_Get_Sun_Position(double JulianDayNumber, double Longitude, double Latitude, double &Height, double &Azimuth)
+{
+ //-----------------------------------------------------
+ // 1. Get right ascension RA and declination delta
+
+ double RA, Delta; SG_Get_Sun_Position(JulianDayNumber, RA, Delta);
+
+ //-----------------------------------------------------
+ // 2. compute sidereal time (radians) at Greenwich local sidereal time at longitude (radians)
+
+ double T = (JulianDayNumber - 2451545.0 ) / 36525.0;
+
+ double Theta = Longitude + M_DEG_TO_RAD * (280.46061837 + 360.98564736629 * (JulianDayNumber - 2451545.0) + T*T * (0.000387933 - T / 38710000.0));
+
+ double Tau = Theta - RA; // compute local hour angle (radians)
+
+ //-----------------------------------------------------
+ // 3. convert (tau, delta) to horizon coordinates (h, az) of the observer
+
+ Height = asin ( sin(Latitude) * sin(Delta) + cos(Latitude) * cos(Delta) * cos(Tau));
+ Azimuth = atan2(-sin(Tau) * cos(Delta), cos(Latitude) * sin(Delta) - sin(Latitude) * cos(Delta) * cos(Tau));
+// Azimuth = atan2(-sin(Tau), cos(Latitude) * tan(Delta) - sin(Latitude) * cos(Tau)); // previous formula gives same result but is better because of division by zero effects...
+
+ return( Height > 0.0 );
+}
+
+//---------------------------------------------------------
+bool SG_Get_Sun_Position(const CSG_DateTime &Time, double Longitude, double Latitude, double &Height, double &Azimuth)
+{
+ return( SG_Get_Sun_Position(Time.Get_JDN(), Longitude, Latitude, Height, Azimuth) );
+}
///////////////////////////////////////////////////////////
diff --git a/src/saga_core/saga_api/datetime.h b/src/saga_core/saga_api/datetime.h
index a9dfa27..a572a37 100644
--- a/src/saga_core/saga_api/datetime.h
+++ b/src/saga_core/saga_api/datetime.h
@@ -103,6 +103,7 @@ public:
CSG_TimeSpan(void) { m_span = 0l ; }
CSG_TimeSpan(const CSG_TimeSpan &ts) { m_span = ts.m_span; }
CSG_TimeSpan(const sLong &diff) { m_span = diff ; }
+ CSG_TimeSpan(double hours) { m_span = (sLong)(1000*60*60 * hours); }
CSG_TimeSpan(long hours, long min = 0, sLong sec = 0, sLong msec = 0)
{
m_span = msec + 1000 * (sec + 60 * (min + 60 * hours));
@@ -242,6 +243,7 @@ public:
CSG_DateTime & Set_Second (unsigned short Value);
CSG_DateTime & Set_Minute (unsigned short Value);
CSG_DateTime & Set_Hour (unsigned short Value);
+ CSG_DateTime & Set_Hour (double Value);
CSG_DateTime & Set_Day (unsigned short Value);
CSG_DateTime & Set_Month (Month Value);
CSG_DateTime & Set_Year (int Value);
@@ -250,6 +252,12 @@ public:
CSG_DateTime & Reset_Time (void);
+
+ //-----------------------------------------------------
+ CSG_DateTime & Make_UTC (bool noDST = false);
+
+ bool is_DST (void) const;
+
//-----------------------------------------------------
CSG_DateTime Add (const CSG_TimeSpan &TimeSpan) const;
@@ -332,8 +340,9 @@ public:
bool Parse_ISODate (const CSG_String &date);
bool Parse_ISOTime (const CSG_String &date);
-
+
//-----------------------------------------------------
+ static TSG_DateTime Get_Current_Day (void);
static Month Get_Current_Month (void);
static int Get_Current_Year (void);
@@ -348,8 +357,9 @@ public:
static bool is_LeapYear (int year = Inv_Year);
static CSG_DateTime Now (void);
-
+ static CSG_String Get_Month_Choices (void);
+
private:
@@ -365,4 +375,18 @@ private:
///////////////////////////////////////////////////////////
//---------------------------------------------------------
+SAGA_API_DLL_EXPORT bool SG_Get_Sun_Position (double JulianDayNumber, double &RA, double &Dec);
+SAGA_API_DLL_EXPORT bool SG_Get_Sun_Position (const CSG_DateTime &Time, double &RA, double &Dec);
+
+SAGA_API_DLL_EXPORT bool SG_Get_Sun_Position (double JulianDayNumber, double Longitude, double Latitude, double &Height, double &Azimuth);
+SAGA_API_DLL_EXPORT bool SG_Get_Sun_Position (const CSG_DateTime &Time, double Longitude, double Latitude, double &Height, double &Azimuth);
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
#endif // #ifndef HEADER_INCLUDED__SAGA_API__datetime_H
diff --git a/src/saga_core/saga_api/grid.cpp b/src/saga_core/saga_api/grid.cpp
index 7b2faeb..1b89dc4 100644
--- a/src/saga_core/saga_api/grid.cpp
+++ b/src/saga_core/saga_api/grid.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: grid.cpp 2590 2015-09-18 15:42:35Z oconrad $
+ * Version $Id: grid.cpp 2641 2015-10-08 10:00:15Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -64,8 +64,8 @@
//---------------------------------------------------------
#include "grid.h"
-
#include "data_manager.h"
+#include "module_library.h"
///////////////////////////////////////////////////////////
@@ -278,10 +278,27 @@ bool CSG_Grid::Create(const CSG_Grid &Grid)
Set_Name (Grid.Get_Name ());
Set_Description (Grid.Get_Description());
Set_Unit (Grid.Get_Unit ());
- Set_Scaling (Grid.Get_Scaling(), Grid.Get_Offset());
Set_NoData_Value_Range(Grid.Get_NoData_Value(), Grid.Get_NoData_hiValue());
- return( Assign((CSG_Grid *)&Grid, GRID_INTERPOLATION_Undefined) );
+ for(int y=0; y<Get_NY() && SG_UI_Process_Set_Progress(y, Get_NY()); y++)
+ {
+ #pragma omp parallel for
+ for(int x=0; x<Get_NX(); x++)
+ {
+ if( Grid.is_NoData(x, y) )
+ {
+ Set_NoData(x, y);
+ }
+ else
+ {
+ Set_Value(x, y, Grid.asDouble(x, y, false));
+ }
+ }
+ }
+
+ Set_Scaling(Grid.Get_Scaling(), Grid.Get_Offset());
+
+ return( true );
}
return( false );
@@ -313,13 +330,77 @@ bool CSG_Grid::Create(const CSG_String &File_Name, TSG_Data_Type Type, TSG_Grid_
{
Destroy();
- SG_UI_Msg_Add(CSG_String::Format(SG_T("%s: %s..."), _TL("Load grid"), File_Name.c_str()), true);
+ SG_UI_Msg_Add(CSG_String::Format("%s: %s...", _TL("Load grid"), File_Name.c_str()), true);
+
+ //-----------------------------------------------------
+ bool bResult = File_Name.BeforeFirst(':').Cmp("PGSQL") && SG_File_Exists(File_Name) && _Load(File_Name, Type, Memory_Type, bLoadData);
+
+ if( bResult )
+ {
+ // nop
+ }
+
+ //-----------------------------------------------------
+ else if( File_Name.BeforeFirst(':').Cmp("PGSQL") == 0 ) // database source
+ {
+ CSG_String s(File_Name);
+
+ s = s.AfterFirst(':'); CSG_String Host (s.BeforeFirst(':'));
+ s = s.AfterFirst(':'); CSG_String Port (s.BeforeFirst(':'));
+ s = s.AfterFirst(':'); CSG_String DBName(s.BeforeFirst(':'));
+ s = s.AfterFirst(':'); CSG_String Table (s.BeforeFirst(':'));
+ s = s.AfterFirst(':'); CSG_String rid (s.BeforeFirst(':').AfterFirst('='));
+
+ CSG_Module *pModule = SG_Get_Module_Library_Manager().Get_Module("db_pgsql", 0); // CGet_Connections
+
+ if( pModule != NULL )
+ {
+ SG_UI_ProgressAndMsg_Lock(true);
+
+ //---------------------------------------------
+ CSG_Table Connections;
+ CSG_String Connection = DBName + " [" + Host + ":" + Port + "]";
+
+ pModule->Settings_Push();
+
+ if( pModule->On_Before_Execution() && SG_MODULE_PARAMETER_SET("CONNECTIONS", &Connections) && pModule->Execute() ) // CGet_Connections
+ {
+ for(int i=0; !bResult && i<Connections.Get_Count(); i++)
+ {
+ if( !Connection.Cmp(Connections[i].asString(0)) )
+ {
+ bResult = true;
+ }
+ }
+ }
+
+ pModule->Settings_Pop();
+
+ //---------------------------------------------
+ if( bResult && (bResult = (pModule = SG_Get_Module_Library_Manager().Get_Module("db_pgsql", 33)) != NULL) == true ) // CPGIS_Raster_Load_Band
+ {
+ pModule->Settings_Push();
+
+ bResult = pModule->On_Before_Execution()
+ && SG_MODULE_PARAMETER_SET("CONNECTION", Connection)
+ && SG_MODULE_PARAMETER_SET("TABLES" , Table)
+ && SG_MODULE_PARAMETER_SET("RID" , rid)
+ && SG_MODULE_PARAMETER_SET("GRID" , this)
+ && pModule->Execute();
+
+ pModule->Settings_Pop();
+ }
+
+ SG_UI_ProgressAndMsg_Lock(false);
+ }
+ }
//-----------------------------------------------------
- if( _Load(File_Name, Type, Memory_Type, bLoadData) )
+ if( bResult )
{
m_bCreated = true;
+ Set_Modified(false);
Set_Update_Flag();
SG_UI_Msg_Add(_TL("okay"), false, SG_UI_MSG_STYLE_SUCCESS);
@@ -332,8 +413,6 @@ bool CSG_Grid::Create(const CSG_String &File_Name, TSG_Data_Type Type, TSG_Grid_
SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
- SG_UI_Msg_Add_Error(_TL("Grid file could not be opened."));
-
return( false );
}
diff --git a/src/saga_core/saga_api/grid_io.cpp b/src/saga_core/saga_api/grid_io.cpp
index 39176b4..0197346 100644
--- a/src/saga_core/saga_api/grid_io.cpp
+++ b/src/saga_core/saga_api/grid_io.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: grid_io.cpp 2590 2015-09-18 15:42:35Z oconrad $
+ * Version $Id: grid_io.cpp 2630 2015-10-01 10:01:07Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -100,6 +100,11 @@ bool CSG_Grid::_Load(const CSG_String &File_Name, TSG_Data_Type Type, TSG_Grid_M
return( true );
}
+ if( SG_File_Cmp_Extension(File_Name, SG_T("sgrd")) || SG_File_Cmp_Extension(File_Name, SG_T("dgm")) )
+ { // couldn't load saga raster ??? then return immediately !!!
+ return( false );
+ }
+
Set_File_Name(File_Name, false);
//-----------------------------------------------------
@@ -756,35 +761,30 @@ bool CSG_Grid::_Load_Surfer(const CSG_String &File_Name, TSG_Grid_Memory_Type Me
// d = (r.yMax - r.yMin) / (ny - 1.0); // we could proof for equal cellsize in direction of y...
//-------------------------------------------------
- if( !Create(SG_DATATYPE_Float, nx, ny, d, r.xMin, r.yMin, Memory_Type) )
- {
- return( false );
- }
-
- if( !bLoadData )
- {
- return( true );
- }
-
- if( Stream.is_EOF() )
+ if( !Create(SG_DATATYPE_Float, nx, ny, d, r.xMin, r.yMin, Memory_Type) || Stream.is_EOF() )
{
return( false );
}
//-------------------------------------------------
- float *fLine = (float *)SG_Malloc(Get_NX() * sizeof(float));
-
- for(int y=0; y<Get_NY() && !Stream.is_EOF() && SG_UI_Process_Set_Progress(y, Get_NY()); y++)
+ if( bLoadData )
{
- Stream.Read(fLine, sizeof(float), Get_NX());
+ float *fLine = (float *)SG_Malloc(Get_NX() * sizeof(float));
- for(int x=0; x<Get_NX(); x++)
+ for(int y=0; y<Get_NY() && !Stream.is_EOF() && SG_UI_Process_Set_Progress(y, Get_NY()); y++)
{
- Set_Value(x, y, fLine[x]);
+ Stream.Read(fLine, sizeof(float), Get_NX());
+
+ for(int x=0; x<Get_NX(); x++)
+ {
+ Set_Value(x, y, fLine[x]);
+ }
}
+
+ SG_Free(fLine);
}
- SG_Free(fLine);
+ Get_MetaData().Add_Child("SURFER_GRID", "Surfer Grid (Binary)");
}
//-----------------------------------------------------
@@ -803,36 +803,34 @@ bool CSG_Grid::_Load_Surfer(const CSG_String &File_Name, TSG_Grid_Memory_Type Me
// d = (r.yMax - r.yMin) / (ny - 1.0); // we could proof for equal cellsize in direction of y...
//-------------------------------------------------
- if( !Create(SG_DATATYPE_Float, nx, ny, d, r.xMin, r.yMin, Memory_Type) && bLoadData && !Stream.is_EOF() )
- {
- return( false );
- }
-
- if( !bLoadData )
- {
- return( true );
- }
-
- if( Stream.is_EOF() )
+ if( !Create(SG_DATATYPE_Float, nx, ny, d, r.xMin, r.yMin, Memory_Type) || Stream.is_EOF() )
{
return( false );
}
//-------------------------------------------------
- for(int y=0; y<Get_NY() && !Stream.is_EOF() && SG_UI_Process_Set_Progress(y, Get_NY()); y++)
+ if( bLoadData )
{
- for(int x=0; x<Get_NX(); x++)
+ for(int y=0; y<Get_NY() && !Stream.is_EOF() && SG_UI_Process_Set_Progress(y, Get_NY()); y++)
{
- fscanf(Stream.Get_Stream(), "%lf", &d);
+ for(int x=0; x<Get_NX(); x++)
+ {
+ fscanf(Stream.Get_Stream(), "%lf", &d);
- Set_Value(x, y, d);
+ Set_Value(x, y, d);
+ }
}
}
+
+ Get_MetaData().Add_Child("SURFER_GRID", "Surfer Grid (ASCII)");
}
//-------------------------------------------------
SG_UI_Process_Set_Ready();
+ Set_File_Name(File_Name);
+ Load_MetaData(File_Name);
+
return( true );
}
diff --git a/src/saga_core/saga_api/grid_operation.cpp b/src/saga_core/saga_api/grid_operation.cpp
index 61d5035..bf6fc96 100644
--- a/src/saga_core/saga_api/grid_operation.cpp
+++ b/src/saga_core/saga_api/grid_operation.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: grid_operation.cpp 2230 2014-09-11 16:23:09Z oconrad $
+ * Version $Id: grid_operation.cpp 2632 2015-10-01 14:12:13Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -696,47 +696,51 @@ CSG_Grid & CSG_Grid::_Operation_Arithmetic(const CSG_Grid &Grid, TSG_Grid_Operat
{
if( is_Intersecting(Grid.Get_Extent()) )
{
- int x, y;
- double xWorld, yWorld, Value;
- TSG_Grid_Interpolation Interpolation;
+ TSG_Grid_Interpolation Interpolation =
+ Get_Cellsize() == Grid.Get_Cellsize() && fmod(Get_XMin() - Grid.Get_XMin(), Get_Cellsize()) == 0.0
+ && Get_Cellsize() == Grid.Get_Cellsize() && fmod(Get_YMin() - Grid.Get_YMin(), Get_Cellsize()) == 0.0
+ ? GRID_INTERPOLATION_NearestNeighbour
+ : GRID_INTERPOLATION_BSpline;
- Interpolation = Get_Cellsize() == Grid.Get_Cellsize() && fmod(Get_XMin() - Grid.Get_XMin(), Get_Cellsize()) == 0.0
- && Get_Cellsize() == Grid.Get_Cellsize() && fmod(Get_YMin() - Grid.Get_YMin(), Get_Cellsize()) == 0.0
- ? GRID_INTERPOLATION_NearestNeighbour
- : GRID_INTERPOLATION_BSpline;
-
- for(y=0, yWorld=Get_YMin(); y<Get_NY() && SG_UI_Process_Set_Progress(y, Get_NY()); y++, yWorld+=Get_Cellsize())
+ for(int y=0; y<Get_NY() && SG_UI_Process_Set_Progress(y, Get_NY()); y++)
{
- for(x=0, xWorld=Get_XMin(); x<Get_NX(); x++, xWorld+=Get_Cellsize())
+ double yWorld = Get_YMin() + y * Get_Cellsize();
+
+ #pragma omp parallel for
+ for(int x=0; x<Get_NX(); x++)
{
- if( !Grid.Get_Value(xWorld, yWorld, Value, Interpolation, true) )
- {
- Set_NoData(x, y);
- }
- else switch( Operation )
+ if( !is_NoData(x, y) )
{
- case GRID_OPERATION_Addition:
- Add_Value(x, y, Value);
- break;
+ double xWorld = Get_XMin() + x * Get_Cellsize(), Value;
- case GRID_OPERATION_Subtraction:
- Add_Value(x, y, -Value);
- break;
+ if( Grid.Get_Value(xWorld, yWorld, Value, Interpolation, false, true) )
+ {
+ switch( Operation )
+ {
+ case GRID_OPERATION_Addition:
+ Add_Value(x, y, Value);
+ break;
- case GRID_OPERATION_Multiplication:
- Mul_Value(x, y, Value);
- break;
+ case GRID_OPERATION_Subtraction:
+ Add_Value(x, y, -Value);
+ break;
- case GRID_OPERATION_Division:
- if( Value != 0.0 )
- {
- Mul_Value(x, y, 1.0 / Value);
- }
- else
- {
- Set_NoData(x, y);
+ case GRID_OPERATION_Multiplication:
+ Mul_Value(x, y, Value);
+ break;
+
+ case GRID_OPERATION_Division:
+ if( Value != 0.0 )
+ {
+ Mul_Value(x, y, 1.0 / Value);
+ }
+ else
+ {
+ Set_NoData(x, y);
+ }
+ break;
+ }
}
- break;
}
}
}
diff --git a/src/saga_core/saga_api/module.cpp b/src/saga_core/saga_api/module.cpp
index 54e635f..d3b1ea8 100644
--- a/src/saga_core/saga_api/module.cpp
+++ b/src/saga_core/saga_api/module.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: module.cpp 2432 2015-03-04 15:09:34Z oconrad $
+ * Version $Id: module.cpp 2624 2015-09-30 15:33:53Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -1185,6 +1185,8 @@ void _Add_XML(CSG_MetaData *pParent, CSG_Parameter *pParameter, CSG_String ID =
#define SUMMARY_ADD_STR(label, value) s += CSG_String::Format(SG_T("<tr><td valign=\"top\">%s</td><td valign=\"top\">%s</td></tr>"), label, value)
#define SUMMARY_ADD_INT(label, value) s += CSG_String::Format(SG_T("<tr><td valign=\"top\">%s</td><td valign=\"top\">%d</td></tr>"), label, value)
+#define SUMMARY_DO_ADD (SG_UI_Get_Window_Main() ? Parameters(i)->do_UseInGUI() : Parameters(i)->do_UseInCMD())
+
//---------------------------------------------------------
CSG_String CSG_Module::Get_Summary(bool bParameters, const CSG_String &Menu, const CSG_String &Description, bool bXML)
{
@@ -1213,7 +1215,7 @@ CSG_String CSG_Module::Get_Summary(bool bParameters, const CSG_String &Menu, con
{
for(i=0; i<Parameters.Get_Count(); i++)
{
- if( Parameters(i)->is_Input() )
+ if( SUMMARY_DO_ADD && Parameters(i)->is_Input() )
{
_Add_XML(&m, Parameters(i));
}
@@ -1221,7 +1223,7 @@ CSG_String CSG_Module::Get_Summary(bool bParameters, const CSG_String &Menu, con
for(i=0; i<Parameters.Get_Count(); i++)
{
- if( Parameters(i)->is_Output() )
+ if( SUMMARY_DO_ADD && Parameters(i)->is_Output() )
{
_Add_XML(&m, Parameters(i));
}
@@ -1229,7 +1231,7 @@ CSG_String CSG_Module::Get_Summary(bool bParameters, const CSG_String &Menu, con
for(i=0; i<Parameters.Get_Count(); i++)
{
- if( Parameters(i)->is_Option()
+ if( SUMMARY_DO_ADD && Parameters(i)->is_Option()
&& Parameters(i)->Get_Type() != PARAMETER_TYPE_Node
&& Parameters(i)->Get_Type() != PARAMETER_TYPE_Grid_System )
{
@@ -1299,7 +1301,7 @@ CSG_String CSG_Module::Get_Summary(bool bParameters, const CSG_String &Menu, con
{
CSG_Parameter *pParameter = Parameters(i);
- if( pParameter->is_Input() )
+ if( SUMMARY_DO_ADD && pParameter->is_Input() )
{
if( bFirst )
{
@@ -1323,7 +1325,7 @@ CSG_String CSG_Module::Get_Summary(bool bParameters, const CSG_String &Menu, con
{
CSG_Parameter *pParameter = Parameters(i);
- if( pParameter->is_Output() )
+ if( SUMMARY_DO_ADD && pParameter->is_Output() )
{
if( bFirst )
{
@@ -1347,7 +1349,7 @@ CSG_String CSG_Module::Get_Summary(bool bParameters, const CSG_String &Menu, con
{
CSG_Parameter *pParameter = Parameters(i);
- if( pParameter->is_Option() && pParameter->Get_Type() != PARAMETER_TYPE_Grid_System )
+ if( SUMMARY_DO_ADD && pParameter->is_Option() && pParameter->Get_Type() != PARAMETER_TYPE_Grid_System )
{
if( bFirst )
{
diff --git a/src/saga_core/saga_api/module_chain.cpp b/src/saga_core/saga_api/module_chain.cpp
index 712ca9f..2269e7a 100644
--- a/src/saga_core/saga_api/module_chain.cpp
+++ b/src/saga_core/saga_api/module_chain.cpp
@@ -270,7 +270,7 @@ bool CSG_Module_Chain::Create(const CSG_String &File)
case PARAMETER_TYPE_TIN : Parameters.Add_TIN (pParent, ID, Name, Desc, Constraint); break;
case PARAMETER_TYPE_PointCloud : Parameters.Add_PointCloud (pParent, ID, Name, Desc, Constraint); break;
- case PARAMETER_TYPE_Grid_List : Parameters.Add_Grid_List (pParent, ID, Name, Desc, Constraint); break;
+ case PARAMETER_TYPE_Grid_List : Parameters.Add_Grid_List (pParent, ID, Name, Desc, Constraint, !IS_TRUE_PROPERTY(Parameter, "no_system")); break;
case PARAMETER_TYPE_Table_List : Parameters.Add_Table_List (pParent, ID, Name, Desc, Constraint); break;
case PARAMETER_TYPE_Shapes_List : Parameters.Add_Shapes_List (pParent, ID, Name, Desc, Constraint); break;
case PARAMETER_TYPE_TIN_List : Parameters.Add_TIN_List (pParent, ID, Name, Desc, Constraint); break;
@@ -353,19 +353,28 @@ bool CSG_Module_Chain::Data_Add(const CSG_String &ID, CSG_Parameter *pData)
return( false );
}
- switch( pData->Get_Type() )
+ CSG_Parameter *pParameter = m_Data(ID);
+
+ if( pParameter ) // don't add twice with same identifier
+ {
+ if( pParameter->Get_Type() != pData->Get_Type() )
+ {
+ return( false );
+ }
+ }
+ else switch( pData->Get_Type() )
{
- case PARAMETER_TYPE_PointCloud : m_Data.Add_PointCloud (NULL, ID, "", "", 0)->Assign(pData); break;
- case PARAMETER_TYPE_Grid : m_Data.Add_Grid (NULL, ID, "", "", 0)->Assign(pData); break;
- case PARAMETER_TYPE_Table : m_Data.Add_Table (NULL, ID, "", "", 0)->Assign(pData); break;
- case PARAMETER_TYPE_Shapes : m_Data.Add_Shapes (NULL, ID, "", "", 0)->Assign(pData); break;
- case PARAMETER_TYPE_TIN : m_Data.Add_TIN (NULL, ID, "", "", 0)->Assign(pData); break;
-
- case PARAMETER_TYPE_PointCloud_List: m_Data.Add_PointCloud_List(NULL, ID, "", "", 0)->Assign(pData); break;
- case PARAMETER_TYPE_Grid_List : m_Data.Add_Grid_List (NULL, ID, "", "", 0)->Assign(pData); break;
- case PARAMETER_TYPE_Table_List : m_Data.Add_Table_List (NULL, ID, "", "", 0)->Assign(pData); break;
- case PARAMETER_TYPE_Shapes_List : m_Data.Add_Shapes_List (NULL, ID, "", "", 0)->Assign(pData); break;
- case PARAMETER_TYPE_TIN_List : m_Data.Add_TIN_List (NULL, ID, "", "", 0)->Assign(pData); break;
+ case PARAMETER_TYPE_PointCloud : pParameter = m_Data.Add_PointCloud (NULL, ID, "", "", 0 ); break;
+ case PARAMETER_TYPE_Grid : pParameter = m_Data.Add_Grid (NULL, ID, "", "", 0 ); break;
+ case PARAMETER_TYPE_Table : pParameter = m_Data.Add_Table (NULL, ID, "", "", 0 ); break;
+ case PARAMETER_TYPE_Shapes : pParameter = m_Data.Add_Shapes (NULL, ID, "", "", 0 ); break;
+ case PARAMETER_TYPE_TIN : pParameter = m_Data.Add_TIN (NULL, ID, "", "", 0 ); break;
+
+ case PARAMETER_TYPE_PointCloud_List: pParameter = m_Data.Add_PointCloud_List(NULL, ID, "", "", 0 ); break;
+ case PARAMETER_TYPE_Grid_List : pParameter = m_Data.Add_Grid_List (NULL, ID, "", "", 0, false); break;
+ case PARAMETER_TYPE_Table_List : pParameter = m_Data.Add_Table_List (NULL, ID, "", "", 0 ); break;
+ case PARAMETER_TYPE_Shapes_List : pParameter = m_Data.Add_Shapes_List (NULL, ID, "", "", 0 ); break;
+ case PARAMETER_TYPE_TIN_List : pParameter = m_Data.Add_TIN_List (NULL, ID, "", "", 0 ); break;
case PARAMETER_TYPE_DataObject_Output:
return( true );
@@ -374,6 +383,8 @@ bool CSG_Module_Chain::Data_Add(const CSG_String &ID, CSG_Parameter *pData)
return( false );
}
+ pParameter->Assign(pData);
+
if( pData->is_DataObject() )
{
m_Data_Manager.Add(pData->asDataObject());
@@ -455,6 +466,16 @@ bool CSG_Module_Chain::Data_Finalize(void)
}
else if( Parameters(i)->is_DataObject_List() )
{
+ if( Parameters(i)->is_Output() && m_Data(Parameters(i)->Get_Identifier()) ) // output lists cannot be up-to-date yet
+ {
+ CSG_Parameter *pData = m_Data(Parameters(i)->Get_Identifier());
+
+ for(int j=0; j<pData->asList()->Get_Count(); j++) // csg_parameter::assign() will not work, if parameters data manager is the standard data manager because it checks for existing data sets
+ {
+ Parameters(i)->asList()->Add_Item(pData->asList()->asDataObject(j));
+ }
+ }
+
for(int j=0; j<Parameters(i)->asList()->Get_Count(); j++)
{
m_Data_Manager.Delete(Parameters(i)->asList()->asDataObject(j), true);
@@ -673,13 +694,17 @@ bool CSG_Module_Chain::Tool_Run(const CSG_MetaData &Tool)
bool bResult = false;
- if( !Tool_Initialize(Tool, pModule) )
+ if( !pModule->On_Before_Execution() )
+ {
+ Error_Fmt("%s [%s].[%s]", _TL("before tool execution check failed"), pModule->Get_Library().c_str(), pModule->Get_Name().c_str());
+ }
+ else if( !Tool_Initialize(Tool, pModule) )
{
- Error_Fmt("%s [%s].[%s]", _TL("tool initialization failed"), pModule->Get_Library().c_str(), pModule->Get_Name().c_str());
+ Error_Fmt("%s [%s].[%s]", _TL("tool initialization failed" ), pModule->Get_Library().c_str(), pModule->Get_Name().c_str());
}
else if( !(bResult = pModule->Execute()) )
{
- Error_Fmt("%s [%s].[%s]", _TL("tool execution failed" ), pModule->Get_Library().c_str(), pModule->Get_Name().c_str());
+ Error_Fmt("%s [%s].[%s]", _TL("tool execution failed" ), pModule->Get_Library().c_str(), pModule->Get_Name().c_str());
}
Tool_Finalize(Tool, pModule);
@@ -746,8 +771,6 @@ bool CSG_Module_Chain::Tool_Get_Parameter(const CSG_MetaData &Parameter, CSG_Mod
bool CSG_Module_Chain::Tool_Initialize(const CSG_MetaData &Tool, CSG_Module *pModule)
{
//-----------------------------------------------------
- pModule->Set_Callback(); // ???!!!
-
int i;
//-----------------------------------------------------
@@ -813,7 +836,14 @@ bool CSG_Module_Chain::Tool_Initialize(const CSG_MetaData &Tool, CSG_Module *pMo
{
if( !pParameter->Assign(m_Data(Parameter.Get_Content())) )
{
- pParameter->Set_Value(DATAOBJECT_CREATE);
+ if( pParameter->is_DataObject() )
+ {
+ pParameter->Set_Value(DATAOBJECT_CREATE);
+ }
+ else if( pParameter->is_DataObject_List() )
+ {
+ pParameter->asList()->Del_Items();
+ }
}
}
}
@@ -906,7 +936,7 @@ bool CSG_Module_Chain::Tool_Finalize(const CSG_MetaData &Tool, CSG_Module *pModu
}
else if( pParameter->is_DataObject_List() )
{
- for(int k=0; k<m_Data.Get_Count(); k++)
+ for(int k=0; k<pParameter->asList()->Get_Count(); k++)
{
if( !Data_Exists(pParameter->asList()->asDataObject(k)) )
{
diff --git a/src/saga_core/saga_api/module_library.h b/src/saga_core/saga_api/module_library.h
index e70c907..cba3261 100644
--- a/src/saga_core/saga_api/module_library.h
+++ b/src/saga_core/saga_api/module_library.h
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: module_library.h 2378 2015-01-28 19:26:13Z oconrad $
+ * Version $Id: module_library.h 2640 2015-10-07 17:29:38Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -243,7 +243,7 @@ SAGA_API_DLL_EXPORT CSG_Module_Library_Manager & SG_Get_Module_Library_Manager (
\
pModule->Settings_Push();\
\
- if( !(CONDITION) )\
+ if( !pModule->On_Before_Execution() || !(CONDITION) )\
{\
Error_Set(CSG_String::Format(SG_T("%s [%s].[%s]"), _TL("could not initialize tool"), SG_T(LIBRARY), pModule->Get_Name().c_str()));\
}\
@@ -282,6 +282,11 @@ SAGA_API_DLL_EXPORT CSG_Module_Library_Manager & SG_Get_Module_Library_Manager (
&& pModule->Get_Parameters()->Get_Parameter(IDENTIFIER)->asList()->Add_Item(VALUE)\
)
+#define SG_MODULE_SET_DATAOBJECT_LIST(IDENTIFIER, VALUE) (\
+ pModule->Get_Parameters()->Get_Parameter(IDENTIFIER)\
+ && pModule->Get_Parameters()->Get_Parameter(IDENTIFIER)->asList()\
+ && pModule->Get_Parameters()->Get_Parameter(IDENTIFIER)->asList()->Assign(VALUE)\
+)
///////////////////////////////////////////////////////////
// //
diff --git a/src/saga_core/saga_api/parameter.cpp b/src/saga_core/saga_api/parameter.cpp
index db7943b..f5e8cc0 100644
--- a/src/saga_core/saga_api/parameter.cpp
+++ b/src/saga_core/saga_api/parameter.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: parameter.cpp 2415 2015-02-18 14:27:34Z oconrad $
+ * Version $Id: parameter.cpp 2624 2015-09-30 15:33:53Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -95,9 +95,11 @@ CSG_Parameter::CSG_Parameter(CSG_Parameters *pOwner, CSG_Parameter *pParent, con
}
//-----------------------------------------------------
+ m_pData = NULL;
+
switch( Type )
{
- default: m_pData = NULL; break;
+ default: break;
case PARAMETER_TYPE_Node: m_pData = new CSG_Parameter_Node (this, Constraint); break;
@@ -148,6 +150,13 @@ CSG_Parameter::CSG_Parameter(CSG_Parameters *pOwner, CSG_Parameter *pParent, con
m_Children = NULL;
break;
}
+
+ //-----------------------------------------------------
+ if( m_pParent && m_pParent->m_pData )
+ {
+ Set_UseInCMD(m_pParent->do_UseInCMD());
+ Set_UseInGUI(m_pParent->do_UseInGUI());
+ }
}
//---------------------------------------------------------
@@ -186,6 +195,49 @@ void CSG_Parameter::_Add_Child(CSG_Parameter *pChild)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
+void CSG_Parameter::Set_UseInGUI(bool bDoUse)
+{
+ if( bDoUse )
+ {
+ m_pData->m_Constraint &= ~PARAMETER_NOT_FOR_GUI;
+ }
+ else
+ {
+ m_pData->m_Constraint |= PARAMETER_NOT_FOR_GUI;
+ }
+
+ for(int i=0; i<Get_Children_Count(); i++)
+ {
+ Get_Child(i)->Set_UseInGUI(bDoUse);
+ }
+}
+
+//---------------------------------------------------------
+void CSG_Parameter::Set_UseInCMD(bool bDoUse)
+{
+ if( bDoUse )
+ {
+ m_pData->m_Constraint &= ~PARAMETER_NOT_FOR_CMD;
+ }
+ else
+ {
+ m_pData->m_Constraint |= PARAMETER_NOT_FOR_CMD;
+ }
+
+ for(int i=0; i<Get_Children_Count(); i++)
+ {
+ Get_Child(i)->Set_UseInCMD(bDoUse);
+ }
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
bool CSG_Parameter::Set_Enabled(bool bEnabled)
{
if( m_bEnabled != bEnabled )
@@ -201,6 +253,16 @@ bool CSG_Parameter::Set_Enabled(bool bEnabled)
//---------------------------------------------------------
bool CSG_Parameter::is_Enabled(void) const
{
+ if( do_UseInGUI() == false && SG_UI_Get_Window_Main() != NULL )
+ {
+ return( false );
+ }
+
+ if( do_UseInCMD() == false && SG_UI_Get_Window_Main() == NULL )
+ {
+ return( false );
+ }
+
return( m_bEnabled && (Get_Parent() == NULL || Get_Parent()->is_Enabled()) );
}
diff --git a/src/saga_core/saga_api/parameter_data.cpp b/src/saga_core/saga_api/parameter_data.cpp
index ad93763..cabee01 100644
--- a/src/saga_core/saga_api/parameter_data.cpp
+++ b/src/saga_core/saga_api/parameter_data.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: parameter_data.cpp 2590 2015-09-18 15:42:35Z oconrad $
+ * Version $Id: parameter_data.cpp 2640 2015-10-07 17:29:38Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -1961,7 +1961,7 @@ bool CSG_Parameter_Data_Object::On_Serialize(CSG_MetaData &Entry, bool bSave)
{
Entry.Set_Content("CREATE");
}
- else if( m_pDataObject == DATAOBJECT_NOTSET || !SG_File_Exists(m_pDataObject->Get_File_Name(false)) )
+ else if( m_pDataObject == DATAOBJECT_NOTSET )//|| !SG_File_Exists(m_pDataObject->Get_File_Name(false)) )
{
Entry.Set_Content("NOT SET");
}
@@ -2491,9 +2491,11 @@ bool CSG_Parameter_List::On_Serialize(CSG_MetaData &Entry, bool bSave)
{
for(int i=0; i<Get_Count(); i++)
{
- if( SG_File_Exists(asDataObject(i)->Get_File_Name()) )
+ CSG_String File = asDataObject(i)->Get_File_Name(false);
+
+ if( File.BeforeFirst(':').Cmp("PGSQL") || SG_File_Exists(File) )
{
- Entry.Add_Child(SG_T("DATA"), asDataObject(i)->Get_File_Name());
+ Entry.Add_Child(SG_T("DATA"), File);
}
}
}
@@ -2656,7 +2658,6 @@ CSG_Parameter_Parameters::CSG_Parameter_Parameters(CSG_Parameter *pOwner, long C
: CSG_Parameter_Data(pOwner, Constraint)
{
m_pParameters = new CSG_Parameters(pOwner->Get_Owner()->Get_Owner(), pOwner->Get_Name(), pOwner->Get_Description(), pOwner->Get_Identifier());
- m_pParameters ->Set_Callback();
}
CSG_Parameter_Parameters::~CSG_Parameter_Parameters(void)
diff --git a/src/saga_core/saga_api/parameters.cpp b/src/saga_core/saga_api/parameters.cpp
index 8318540..7aaa87c 100644
--- a/src/saga_core/saga_api/parameters.cpp
+++ b/src/saga_core/saga_api/parameters.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: parameters.cpp 2432 2015-03-04 15:09:34Z oconrad $
+ * Version $Id: parameters.cpp 2604 2015-09-25 16:18:14Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -119,7 +119,7 @@ void CSG_Parameters::_On_Construction(void)
m_nParameters = 0;
m_Callback = NULL;
- m_bCallback = false;
+ m_bCallback = true;
m_pGrid_System = NULL;
}
@@ -335,8 +335,10 @@ CSG_Parameter * CSG_Parameters::Add_Choice(CSG_Parameter *pParent, const CSG_Str
m_pData = (CSG_Parameter_Choice *)pParameter->m_pData;
m_pData->Set_Items(Items);
+ bool bCallback = Set_Callback(false);
pParameter->Set_Value (Default);
pParameter->Set_Default(Default);
+ Set_Callback(bCallback);
return( pParameter );
}
@@ -366,8 +368,10 @@ CSG_Parameter * CSG_Parameters::Add_FilePath(CSG_Parameter *pParent, const CSG_S
m_pData->Set_Flag_Multiple (bMultiple);
m_pData->Set_Flag_Directory (bDirectory);
+ bool bCallback = Set_Callback(false);
pParameter->Set_Value (Default);
pParameter->Set_Default(Default);
+ Set_Callback(bCallback);
return( pParameter );
}
@@ -381,8 +385,10 @@ CSG_Parameter * CSG_Parameters::Add_Font(CSG_Parameter *pParent, const CSG_Strin
if( pInit && *pInit )
{
+ bool bCallback = Set_Callback(false);
pParameter->Set_Value (pInit);
pParameter->Set_Default(pInit);
+ Set_Callback(bCallback);
}
return( pParameter );
@@ -773,7 +779,9 @@ CSG_Parameter * CSG_Parameters::_Add_Value(CSG_Parameter *pParent, const CSG_Str
}
}
- pParameter->Set_Value(Value);
+ bool bCallback = Set_Callback(false);
+ pParameter->Set_Value (Value);
+ Set_Callback(bCallback);
return( pParameter );
}
@@ -819,8 +827,10 @@ CSG_Parameter * CSG_Parameters::_Add_String(CSG_Parameter *pParent, const CSG_St
pParameter = _Add(pParent, Identifier, Name, Description, bLongText ? PARAMETER_TYPE_Text : PARAMETER_TYPE_String, bInformation ? PARAMETER_INFORMATION : 0);
+ bool bCallback = Set_Callback(false);
pParameter->Set_Value (String);
pParameter->Set_Default(String);
+ Set_Callback(bCallback);
((CSG_Parameter_String *)pParameter->Get_Data())->Set_Password(bPassword);
@@ -1497,16 +1507,12 @@ bool CSG_Parameters::Get_String(CSG_String &String, bool bOptionsOnly)
{
CSG_Parameter *p = m_Parameters[i];
- if( (!bOptionsOnly || p->is_Option()) && !p->is_Information() && !(p->Get_Type() == PARAMETER_TYPE_String && ((CSG_Parameter_String *)p->Get_Data())->is_Password()) )
+ if( (!bOptionsOnly || p->is_Option()) && p->is_Enabled() && !p->is_Information() && !(p->Get_Type() == PARAMETER_TYPE_String && ((CSG_Parameter_String *)p->Get_Data())->is_Password()) )
{
bResult = true;
- // String.Append(CSG_String::Format(SG_T("[%s] %s: %s\n"),
- // p->Get_Type_Name(),
- String.Append(CSG_String::Format(SG_T("%s: %s\n"),
- p->Get_Name(),
- p->asString()
- ));
+ // String += CSG_String::Format("[%s] %s: %s\n", p->Get_Type_Name(), p->Get_Name(), p->asString());
+ String += CSG_String::Format("%s: %s\n", p->Get_Name(), p->asString());
}
}
}
diff --git a/src/saga_core/saga_api/parameters.h b/src/saga_core/saga_api/parameters.h
index 1ad1df2..139a783 100644
--- a/src/saga_core/saga_api/parameters.h
+++ b/src/saga_core/saga_api/parameters.h
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: parameters.h 2432 2015-03-04 15:09:34Z oconrad $
+ * Version $Id: parameters.h 2619 2015-09-29 13:51:55Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -93,6 +93,8 @@
#define PARAMETER_OPTIONAL 0x04
#define PARAMETER_INFORMATION 0x08
#define PARAMETER_IGNORE_PROJECTION 0x10
+#define PARAMETER_NOT_FOR_GUI 0x20
+#define PARAMETER_NOT_FOR_CMD 0x40
#define PARAMETER_INPUT_OPTIONAL (PARAMETER_INPUT | PARAMETER_OPTIONAL)
#define PARAMETER_OUTPUT_OPTIONAL (PARAMETER_OUTPUT | PARAMETER_OPTIONAL)
@@ -208,6 +210,8 @@ typedef int (* TSG_PFNC_Parameter_Changed) (CSG_Parameter *pParameter, int Flag
//---------------------------------------------------------
class SAGA_API_DLL_EXPORT CSG_Parameter_Data
{
+ friend class CSG_Parameter;
+
public:
CSG_Parameter_Data(CSG_Parameter *pOwner, long Constraint);
virtual ~CSG_Parameter_Data(void) {}
@@ -1267,6 +1271,12 @@ public:
bool is_Parameters (void) const;
bool is_Serializable (void) const;
+ void Set_UseInGUI (bool bDoUse = false);
+ void Set_UseInCMD (bool bDoUse = false);
+
+ bool do_UseInGUI (void) const { return( !(m_pData->Get_Constraint() & PARAMETER_NOT_FOR_GUI) ); }
+ bool do_UseInCMD (void) const { return( !(m_pData->Get_Constraint() & PARAMETER_NOT_FOR_CMD) ); }
+
TSG_Data_Object_Type Get_DataObject_Type (void) const;
int Get_Children_Count (void) const { return( m_nChildren ); }
diff --git a/src/saga_core/saga_api/saga_api.h b/src/saga_core/saga_api/saga_api.h
index ad349fa..38de08b 100644
--- a/src/saga_core/saga_api/saga_api.h
+++ b/src/saga_core/saga_api/saga_api.h
@@ -128,8 +128,8 @@
//---------------------------------------------------------
#define SAGA_MAJOR_VERSION 2
#define SAGA_MINOR_VERSION 2
-#define SAGA_RELEASE_NUMBER 1
-#define SAGA_VERSION SG_T("2.2.1")
+#define SAGA_RELEASE_NUMBER 2
+#define SAGA_VERSION SG_T("2.2.2")
///////////////////////////////////////////////////////////
diff --git a/src/saga_core/saga_api/shapes.cpp b/src/saga_core/saga_api/shapes.cpp
index c4cdcba..37868de 100644
--- a/src/saga_core/saga_api/shapes.cpp
+++ b/src/saga_core/saga_api/shapes.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: shapes.cpp 2558 2015-08-19 14:56:36Z oconrad $
+ * Version $Id: shapes.cpp 2641 2015-10-08 10:00:15Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -65,6 +65,7 @@
//---------------------------------------------------------
#include "shapes.h"
#include "pointcloud.h"
+#include "module_library.h"
///////////////////////////////////////////////////////////
@@ -225,31 +226,97 @@ bool CSG_Shapes::Create(const CSG_String &File_Name)
{
Destroy();
- SG_UI_Msg_Add(CSG_String::Format(SG_T("%s: %s..."), _TL("Load shapes"), File_Name.c_str()), true);
+ SG_UI_Msg_Add(CSG_String::Format("%s: %s...", _TL("Load shapes"), File_Name.c_str()), true);
- bool bResult = _Load_ESRI(File_Name);
-
- Set_File_Name(File_Name, true);
- Load_MetaData(File_Name);
+ //-----------------------------------------------------
+ bool bResult = File_Name.BeforeFirst(':').Cmp("PGSQL") && SG_File_Exists(File_Name) && _Load_ESRI(File_Name);
if( bResult )
{
- SG_UI_Msg_Add(_TL("okay"), false, SG_UI_MSG_STYLE_SUCCESS);
+ Set_File_Name(File_Name, true);
+ Load_MetaData(File_Name);
}
- else
+
+ //-----------------------------------------------------
+ else if( File_Name.BeforeFirst(':').Cmp("PGSQL") == 0 ) // database source
{
- for(int iShape=Get_Count()-1; iShape >= 0; iShape--)
+ CSG_String s(File_Name);
+
+ s = s.AfterFirst(':'); CSG_String Host (s.BeforeFirst(':'));
+ s = s.AfterFirst(':'); CSG_String Port (s.BeforeFirst(':'));
+ s = s.AfterFirst(':'); CSG_String DBName(s.BeforeFirst(':'));
+ s = s.AfterFirst(':'); CSG_String Table (s.BeforeFirst(':'));
+
+ CSG_Module *pModule = SG_Get_Module_Library_Manager().Get_Module("db_pgsql", 0); // CGet_Connections
+
+ if( pModule != NULL )
{
- if( !Get_Shape(iShape)->is_Valid() )
+ SG_UI_ProgressAndMsg_Lock(true);
+
+ //---------------------------------------------
+ CSG_Table Connections;
+ CSG_String Connection = DBName + " [" + Host + ":" + Port + "]";
+
+ pModule->Settings_Push();
+
+ if( pModule->On_Before_Execution() && SG_MODULE_PARAMETER_SET("CONNECTIONS", &Connections) && pModule->Execute() ) // CGet_Connections
{
- Del_Shape(iShape);
+ for(int i=0; !bResult && i<Connections.Get_Count(); i++)
+ {
+ if( !Connection.Cmp(Connections[i].asString(0)) )
+ {
+ bResult = true;
+ }
+ }
+ }
+
+ pModule->Settings_Pop();
+
+ //---------------------------------------------
+ if( bResult && (bResult = (pModule = SG_Get_Module_Library_Manager().Get_Module("db_pgsql", 20)) != NULL) == true ) // CPGIS_Shapes_Load
+ {
+ pModule->Settings_Push();
+
+ bResult = pModule->On_Before_Execution()
+ && SG_MODULE_PARAMETER_SET("CONNECTION", Connection)
+ && SG_MODULE_PARAMETER_SET("TABLES" , Table)
+ && SG_MODULE_PARAMETER_SET("SHAPES" , this)
+ && pModule->Execute();
+
+ pModule->Settings_Pop();
}
+
+ SG_UI_ProgressAndMsg_Lock(false);
+ }
+ }
+
+ //-----------------------------------------------------
+ if( bResult )
+ {
+ Set_Modified(false);
+ Set_Update_Flag();
+
+ SG_UI_Msg_Add(_TL("okay"), false, SG_UI_MSG_STYLE_SUCCESS);
+
+ return( true );
+ }
+
+ for(int iShape=Get_Count()-1; iShape>=0; iShape--) // be kind, keep at least those shapes that have been loaded successfully
+ {
+ if( !Get_Shape(iShape)->is_Valid() )
+ {
+ Del_Shape(iShape);
}
+ }
- SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
+ if( Get_Count() <= 0 )
+ {
+ Destroy();
}
- return( bResult );
+ SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
+
+ return( false );
}
//---------------------------------------------------------
diff --git a/src/saga_core/saga_api/table.cpp b/src/saga_core/saga_api/table.cpp
index 704a556..d3a5752 100644
--- a/src/saga_core/saga_api/table.cpp
+++ b/src/saga_core/saga_api/table.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: table.cpp 1921 2014-01-09 10:24:11Z oconrad $
+ * Version $Id: table.cpp 2641 2015-10-08 10:00:15Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -65,6 +65,7 @@
//---------------------------------------------------------
#include "table.h"
#include "shapes.h"
+#include "module_library.h"
///////////////////////////////////////////////////////////
@@ -169,7 +170,88 @@ CSG_Table::CSG_Table(const CSG_String &File_Name, TSG_Table_File_Type Format)
bool CSG_Table::Create(const CSG_String &File_Name, TSG_Table_File_Type Format)
{
- return( _Load(File_Name, Format, NULL) );
+ Destroy();
+
+ SG_UI_Msg_Add(CSG_String::Format("%s: %s...", _TL("Load table"), File_Name.c_str()), true);
+
+ //-----------------------------------------------------
+ bool bResult = File_Name.BeforeFirst(':').Cmp("PGSQL") && SG_File_Exists(File_Name) && _Load(File_Name, Format, NULL);
+
+ if( bResult )
+ {
+ Set_File_Name(File_Name, true);
+ Load_MetaData(File_Name);
+ }
+
+ //-----------------------------------------------------
+ else if( File_Name.BeforeFirst(':').Cmp("PGSQL") == 0 ) // database source
+ {
+ CSG_String s(File_Name);
+
+ s = s.AfterFirst(':'); CSG_String Host (s.BeforeFirst(':'));
+ s = s.AfterFirst(':'); CSG_String Port (s.BeforeFirst(':'));
+ s = s.AfterFirst(':'); CSG_String DBName(s.BeforeFirst(':'));
+ s = s.AfterFirst(':'); CSG_String Table (s.BeforeFirst(':'));
+
+ CSG_Module *pModule = SG_Get_Module_Library_Manager().Get_Module("db_pgsql", 0); // CGet_Connections
+
+ if( pModule != NULL )
+ {
+ SG_UI_ProgressAndMsg_Lock(true);
+
+ //---------------------------------------------
+ CSG_Table Connections;
+ CSG_String Connection = DBName + " [" + Host + ":" + Port + "]";
+
+ pModule->Settings_Push();
+
+ if( pModule->On_Before_Execution() && SG_MODULE_PARAMETER_SET("CONNECTIONS", &Connections) && pModule->Execute() ) // CGet_Connections
+ {
+ for(int i=0; !bResult && i<Connections.Get_Count(); i++)
+ {
+ if( !Connection.Cmp(Connections[i].asString(0)) )
+ {
+ bResult = true;
+ }
+ }
+ }
+
+ pModule->Settings_Pop();
+
+ //---------------------------------------------
+ if( bResult && (bResult = (pModule = SG_Get_Module_Library_Manager().Get_Module("db_pgsql", 12)) != NULL) == true ) // CPGIS_Table_Load
+ {
+ pModule->Settings_Push();
+
+ bResult = pModule->On_Before_Execution()
+ && SG_MODULE_PARAMETER_SET("CONNECTION", Connection)
+ && SG_MODULE_PARAMETER_SET("TABLES" , Table)
+ && SG_MODULE_PARAMETER_SET("TABLE" , this)
+ && pModule->Execute();
+
+ pModule->Settings_Pop();
+ }
+
+ SG_UI_ProgressAndMsg_Lock(false);
+ }
+ }
+
+ //-----------------------------------------------------
+ if( bResult )
+ {
+ Set_Modified(false);
+ Set_Update_Flag();
+
+ SG_UI_Msg_Add(_TL("okay"), false, SG_UI_MSG_STYLE_SUCCESS);
+
+ return( true );
+ }
+
+ Destroy();
+
+ SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
+
+ return( false );
}
//---------------------------------------------------------
diff --git a/src/saga_core/saga_api/table_io.cpp b/src/saga_core/saga_api/table_io.cpp
index 8725fd9..79fa6bb 100644
--- a/src/saga_core/saga_api/table_io.cpp
+++ b/src/saga_core/saga_api/table_io.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: table_io.cpp 2558 2015-08-19 14:56:36Z oconrad $
+ * Version $Id: table_io.cpp 2633 2015-10-02 16:24:33Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -81,14 +81,9 @@ bool CSG_Table::_Load(const CSG_String &File_Name, TSG_Table_File_Type Format, c
return( false );
}
- bool bResult;
- CSG_String fName, sSeparator(Separator && *Separator ? Separator : SG_T("\t"));
-
- Destroy();
-
- SG_UI_Msg_Add(CSG_String::Format(SG_T("%s: %s..."), _TL("Load table"), File_Name.c_str()), true);
-
//-----------------------------------------------------
+ CSG_String sSeparator(Separator && *Separator ? Separator : SG_T("\t"));
+
if( Format == TABLE_FILETYPE_Undefined )
{
if( SG_File_Cmp_Extension(File_Name, SG_T("dbf")) )
@@ -101,52 +96,24 @@ bool CSG_Table::_Load(const CSG_String &File_Name, TSG_Table_File_Type Format, c
if( !Separator || *Separator == '\0' )
{
- sSeparator = SG_T(","); // comma separated values
+ sSeparator = ","; // comma separated values
}
}
- else //if( SG_File_Cmp_Extension(File_Name, SG_T("txt")) )
- {
- Format = TABLE_FILETYPE_Text;
- }
}
//-----------------------------------------------------
switch( Format )
{
- case TABLE_FILETYPE_Text:
- bResult = _Load_Text (File_Name, true , sSeparator);
- break;
+ case TABLE_FILETYPE_Text: default:
+ return( _Load_Text (File_Name, true , sSeparator) );
case TABLE_FILETYPE_Text_NoHeadLine:
- bResult = _Load_Text (File_Name, false, sSeparator);
- break;
+ return( _Load_Text (File_Name, false, sSeparator) );
case TABLE_FILETYPE_DBase:
- bResult = _Load_DBase(File_Name);
- break;
-
- default:
- bResult = false;
+ return( _Load_DBase(File_Name) );
}
- //-----------------------------------------------------
- if( bResult )
- {
- Set_Modified(false);
-
- Set_Update_Flag();
-
- Set_File_Name(File_Name, true);
-
- Load_MetaData(File_Name);
-
- SG_UI_Msg_Add(_TL("okay"), false, SG_UI_MSG_STYLE_SUCCESS);
-
- return( true );
- }
-
- SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
-
return( false );
}
diff --git a/src/saga_core/saga_cmd/module_library.cpp b/src/saga_core/saga_cmd/module_library.cpp
index 8b244fd..790b943 100644
--- a/src/saga_core/saga_cmd/module_library.cpp
+++ b/src/saga_core/saga_cmd/module_library.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: module_library.cpp 2598 2015-09-23 14:12:34Z oconrad $
+ * Version $Id: module_library.cpp 2624 2015-09-30 15:33:53Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -287,6 +287,11 @@ bool CCMD_Module::_Set_Parameters(CSG_Parameters *pParameters)
{
CSG_Parameter *pParameter = pParameters->Get_Parameter(i);
+ if( pParameter->do_UseInCMD() == false )
+ {
+ continue;
+ }
+
wxString Description = pParameter->Get_Description(
PARAMETER_DESCRIPTION_NAME|PARAMETER_DESCRIPTION_TYPE|PARAMETER_DESCRIPTION_PROPERTIES, SG_T("\n\t")
).c_str();
diff --git a/src/saga_core/saga_gui/active.cpp b/src/saga_core/saga_gui/active.cpp
index 3db9650..197340e 100644
--- a/src/saga_core/saga_gui/active.cpp
+++ b/src/saga_core/saga_gui/active.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: active.cpp 2279 2014-10-07 14:46:43Z oconrad $
+ * Version $Id: active.cpp 2629 2015-10-01 09:40:40Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -466,6 +466,8 @@ bool CACTIVE::Update(CWKSP_Base_Item *pItem, bool bSave)
if( !bSave )
{
Update_Description();
+
+ m_pHistory->Set_Item(pItem);
}
return( true );
diff --git a/src/saga_core/saga_gui/data_source.cpp b/src/saga_core/saga_gui/data_source.cpp
index b138a0d..7148d75 100644
--- a/src/saga_core/saga_gui/data_source.cpp
+++ b/src/saga_core/saga_gui/data_source.cpp
@@ -184,6 +184,12 @@ CData_Source::~CData_Source(void)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
+void CData_Source::Autoconnect_DB(void)
+{
+ m_pPgSQL->Autoconnect();
+}
+
+//---------------------------------------------------------
bool CData_Source::Set_Data_Source(CWKSP_Base_Item *pItem)
{
if( pItem == NULL )
diff --git a/src/saga_core/saga_gui/data_source.h b/src/saga_core/saga_gui/data_source.h
index 32bcab3..4fb5c3d 100644
--- a/src/saga_core/saga_gui/data_source.h
+++ b/src/saga_core/saga_gui/data_source.h
@@ -88,6 +88,8 @@ public:
void Add_Pages (void);
+ void Autoconnect_DB (void);
+
class CData_Source_Files * Get_Files (void) { return( m_pFiles ); }
bool Set_Data_Source (class CWKSP_Base_Item *pItem);
diff --git a/src/saga_core/saga_gui/data_source_odbc.cpp b/src/saga_core/saga_gui/data_source_odbc.cpp
index 1363fda..8b30d1f 100644
--- a/src/saga_core/saga_gui/data_source_odbc.cpp
+++ b/src/saga_core/saga_gui/data_source_odbc.cpp
@@ -20,13 +20,13 @@
// //
//-------------------------------------------------------//
// //
-// This file is part of 'MicroCity: Spatial Analysis and //
-// Simulation Framework'. MicroCity is free software;you //
+// This file is part of 'SAGA - System for Automated //
+// Geoscientific Analyses'. SAGA 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; version 2 of the License. //
// //
-// MicroCity is distributed in the hope that it will be //
+// SAGA 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 //
@@ -295,19 +295,9 @@ void CData_Source_ODBC::On_Item_Menu(wxTreeEvent &event)
\
if( pModule )\
{\
- CSG_Parameters P; P.Assign(pModule->Get_Parameters());\
- \
- pModule->Set_Manager(NULL);\
- pModule->Get_Parameters()->Set_Callback(true);\
- pModule->On_Before_Execution();\
- \
- if( (CONDITION) && pModule->Execute() )\
- {\
- bRetVal = true;\
- }\
- \
- pModule->Get_Parameters()->Assign_Values(&P);\
- pModule->Set_Manager(P.Get_Manager());\
+ pModule->Settings_Push(NULL);\
+ bRetVal = pModule->On_Before_Execution() && (CONDITION) && pModule->Execute();\
+ pModule->Settings_Pop();\
}\
}
diff --git a/src/saga_core/saga_gui/data_source_pgsql.cpp b/src/saga_core/saga_gui/data_source_pgsql.cpp
index 322da5c..56a0322 100644
--- a/src/saga_core/saga_gui/data_source_pgsql.cpp
+++ b/src/saga_core/saga_gui/data_source_pgsql.cpp
@@ -20,13 +20,13 @@
// //
//-------------------------------------------------------//
// //
-// This file is part of 'MicroCity: Spatial Analysis and //
-// Simulation Framework'. MicroCity is free software;you //
+// This file is part of 'SAGA - System for Automated //
+// Geoscientific Analyses'. SAGA 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; version 2 of the License. //
// //
-// MicroCity is distributed in the hope that it will be //
+// SAGA 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 //
@@ -84,9 +84,11 @@
enum
{
TYPE_ROOT = 0,
+ TYPE_SERVER,
TYPE_SOURCE,
TYPE_TABLE,
TYPE_SHAPES,
+ TYPE_GRIDS,
TYPE_GRID
};
@@ -94,6 +96,7 @@ enum
enum
{
IMG_ROOT = 0,
+ IMG_SERVER,
IMG_SRC_CLOSED,
IMG_SRC_OPENED,
IMG_TABLE,
@@ -101,19 +104,20 @@ enum
IMG_POINTS,
IMG_LINE,
IMG_POLYGON,
+ IMG_GRIDS,
IMG_GRID
};
//---------------------------------------------------------
enum
{
- DB_PGSQL_Get_Connections = 0,
- DB_PGSQL_Get_Connection = 1,
- DB_PGSQL_Del_Connection = 2,
- DB_PGSQL_Del_Connections = 3,
- DB_PGSQL_Transaction_Start = 4,
- DB_PGSQL_Transaction_Stop = 5,
- DB_PGSQL_Execute_SQL = 6,
+ DB_PGSQL_Get_Connections = 0,
+ DB_PGSQL_Get_Connection = 1,
+ DB_PGSQL_Del_Connection = 2,
+ DB_PGSQL_Del_Connections = 3,
+ DB_PGSQL_Transaction_Start = 4,
+ DB_PGSQL_Transaction_Stop = 5,
+ DB_PGSQL_Execute_SQL = 6,
DB_PGSQL_Table_List = 10,
DB_PGSQL_Table_Info = 11,
@@ -127,8 +131,12 @@ enum
DB_PGSQL_Shapes_SRID_Update = 22,
DB_PGSQL_Raster_Load = 30,
+ DB_PGSQL_Raster_Load_Band = 33,
DB_PGSQL_Raster_Save = 31,
- DB_PGSQL_Raster_SRID_Update = 32
+ DB_PGSQL_Raster_SRID_Update = 32,
+
+ DB_PGSQL_DB_Create = 35,
+ DB_PGSQL_DB_Drop = 36
};
@@ -139,32 +147,20 @@ enum
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-#define RUN_MODULE(MODULE, bRetVal, CONDITION) {\
- \
- bRetVal = false;\
- \
- CSG_Module *pModule = SG_Get_Module_Library_Manager().Get_Module(SG_T("db_pgsql"), MODULE);\
+#define RUN_MODULE(MODULE, bManager, CONDITION) bool bResult = false;\
+{\
+ CSG_Module *pModule = SG_Get_Module_Library_Manager().Get_Module("db_pgsql", MODULE);\
\
if( pModule )\
{\
- CSG_Parameters P; P.Assign(pModule->Get_Parameters());\
- \
- pModule->Set_Manager(NULL);\
- pModule->Get_Parameters()->Set_Callback(true);\
- pModule->On_Before_Execution();\
- \
- if( (CONDITION) && pModule->Execute() )\
- {\
- bRetVal = true;\
- }\
- \
- pModule->Get_Parameters()->Assign_Values(&P);\
- pModule->Set_Manager(P.Get_Manager());\
+ pModule->Settings_Push(bManager ? &SG_Get_Data_Manager() : NULL);\
+ bResult = pModule->On_Before_Execution() && (CONDITION) && pModule->Execute();\
+ pModule->Settings_Pop();\
}\
}
//---------------------------------------------------------
-#define SET_PARAMETER(IDENTIFIER, VALUE) pModule->Get_Parameters()->Set_Parameter(SG_T(IDENTIFIER), VALUE)
+#define SET_PARAMETER(IDENTIFIER, VALUE) pModule->Set_Parameter(IDENTIFIER, VALUE)
///////////////////////////////////////////////////////////
@@ -174,12 +170,11 @@ enum
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-bool is_Connected (const CSG_String &Server)
+bool PGSQL_is_Connected (const CSG_String &Server)
{
- bool bResult;
CSG_Table Connections;
- RUN_MODULE(DB_PGSQL_Get_Connections, bResult, SET_PARAMETER("CONNECTIONS", &Connections)); // CGet_Connections
+ RUN_MODULE(DB_PGSQL_Get_Connections, false, SET_PARAMETER("CONNECTIONS", &Connections)); // CGet_Connections
for(int i=0; bResult && i<Connections.Get_Count(); i++)
{
@@ -195,6 +190,91 @@ bool is_Connected (const CSG_String &Server)
///////////////////////////////////////////////////////////
// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool PGSQL_Get_Connections (CSG_Strings &Servers, double vPostGIS)
+{
+ Servers.Clear();
+
+ CSG_Table Connections;
+
+ RUN_MODULE(DB_PGSQL_Get_Connections, false, SET_PARAMETER("CONNECTIONS", &Connections)); // CGet_Connections
+
+ for(int i=0; bResult && i<Connections.Get_Count(); i++)
+ {
+ if( vPostGIS <= 0.0 || vPostGIS <= Connections[i].asDouble("PostGIS") )
+ {
+ Servers += Connections[i].asString(0);
+ }
+ }
+
+ return( Servers.Get_Count() > 0 );
+}
+
+//---------------------------------------------------------
+bool PGSQL_has_Connections (double vPostGIS)
+{
+ CSG_Strings Servers;
+
+ return( PGSQL_Get_Connections(Servers, vPostGIS) );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+bool PGSQL_Save_Table (CSG_Table *pTable)
+{
+ CSG_Module *pModule = SG_Get_Module_Library_Manager().Get_Module("db_pgsql", DB_PGSQL_Table_Save);
+
+ if( pModule && pModule->On_Before_Execution() && pModule->Set_Parameter("SHAPES", pTable)
+ && DLG_Parameters(pModule->Get_Parameters()) && pModule->Execute() )
+ {
+ return( true );
+ }
+
+ return( false );
+}
+
+//---------------------------------------------------------
+bool PGSQL_Save_Shapes (CSG_Shapes *pShapes)
+{
+ CSG_Module *pModule = SG_Get_Module_Library_Manager().Get_Module("db_pgsql", DB_PGSQL_Shapes_Save);
+
+ if( pModule && pModule->On_Before_Execution() && pModule->Set_Parameter("SHAPES", pShapes)
+ && DLG_Parameters(pModule->Get_Parameters()) && pModule->Execute() )
+ {
+ return( true );
+ }
+
+ return( false );
+}
+
+//---------------------------------------------------------
+bool PGSQL_Save_Grid (CSG_Grid *pGrid)
+{
+ CSG_Module *pModule = SG_Get_Module_Library_Manager().Get_Module("db_pgsql", DB_PGSQL_Raster_Save);
+
+ if( pModule && pModule->On_Before_Execution() && pModule->Set_Parameter("NAME", pGrid->Get_Name()) )
+ {
+ pModule->Get_Parameters()->Get_Parameter("GRIDS")->asList()->Del_Items();
+
+ if( pModule->Get_Parameters()->Get_Parameter("GRIDS")->asList()->Add_Item(pGrid)
+ && DLG_Parameters(pModule->Get_Parameters()) && pModule->Execute() )
+ {
+ return( true );
+ }
+ }
+
+ return( false );
+}
+
+
+///////////////////////////////////////////////////////////
+// //
// //
// //
///////////////////////////////////////////////////////////
@@ -203,21 +283,31 @@ bool is_Connected (const CSG_String &Server)
class CData_Source_PgSQL_Data : public wxTreeItemData
{
public:
- CData_Source_PgSQL_Data(int Type, const CSG_String &Value = SG_T(""), const CSG_String &Server = "")
- : m_Type(Type), m_Value(Value), m_Server(Server)
+ CData_Source_PgSQL_Data(int Type, const CSG_String &Value = "", const CSG_String &Server = "", const CSG_String &Username = "", const CSG_String &Password = "")
+ : m_Type(Type), m_Value(Value), m_Server(Server), m_Username(Username), m_Password(Password)
{}
- int Get_Type (void) const { return( m_Type ); }
- const CSG_String & Get_Value (void) const { return( m_Value ); }
- const CSG_String & Get_Server (void) const { return( m_Server ); }
+ int Get_Type (void) const { return( m_Type ); }
+ const CSG_String & Get_Value (void) const { return( m_Value ); }
+ const CSG_String & Get_Server (void) const { return( m_Server ); }
+
+ void Set_Username (const SG_Char *Username) { m_Username = Username; }
+ const CSG_String & Get_Username (void) const { return( m_Username ); }
+ void Set_Password (const SG_Char *Password) { m_Password = Password; }
+ const CSG_String & Get_Password (void) const { return( m_Password ); }
+
+ CSG_String Get_Host (void) const { return( m_Server.AfterLast ('[').BeforeFirst(':') ); }
+ CSG_String Get_Port (void) const { return( m_Server.AfterLast (':').BeforeFirst(']') ); }
+ CSG_String Get_DBName (void) const { CSG_String s(m_Server.BeforeLast('[')); s.Trim(true); return( s ); }
+
+ bool is_Connected (void) const { return( PGSQL_is_Connected(m_Server) ); }
- bool is_Connected (void) const { return( ::is_Connected(m_Server) ); }
private:
int m_Type;
- CSG_String m_Value, m_Server;
+ CSG_String m_Value, m_Server, m_Username, m_Password;
};
@@ -231,6 +321,8 @@ private:
//---------------------------------------------------------
BEGIN_EVENT_TABLE(CData_Source_PgSQL, wxTreeCtrl)
EVT_MENU (ID_CMD_DB_REFRESH , CData_Source_PgSQL::On_Refresh)
+ EVT_MENU (ID_CMD_DB_SOURCE_CREATE , CData_Source_PgSQL::On_Source_Create)
+ EVT_MENU (ID_CMD_DB_SOURCE_DROP , CData_Source_PgSQL::On_Source_Drop)
EVT_MENU (ID_CMD_DB_SOURCE_OPEN , CData_Source_PgSQL::On_Source_Open)
EVT_MENU (ID_CMD_DB_SOURCE_CLOSE , CData_Source_PgSQL::On_Source_Close)
EVT_MENU (ID_CMD_DB_SOURCE_CLOSE_ALL , CData_Source_PgSQL::On_Sources_Close)
@@ -261,49 +353,120 @@ CData_Source_PgSQL::CData_Source_PgSQL(wxWindow *pParent)
: wxTreeCtrl(pParent, ID_WND_DATA_SOURCE_DATABASE)
{
AssignImageList(new wxImageList(IMG_SIZE_TREECTRL, IMG_SIZE_TREECTRL, true, 0));
- IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_DB_SOURCES); // IMG_ROOT
- IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_DB_SOURCE_OFF); // IMG_SRC_CLOSED
- IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_DB_SOURCE_ON); // IMG_SRC_OPENED
- IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_DB_TABLE); // IMG_TABLE
- IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_SHAPES_POINT); // IMG_POINT
- IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_SHAPES_POINTS); // IMG_POINTS
- IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_SHAPES_LINE); // IMG_LINE
+ IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_DB_SOURCES ); // IMG_ROOT
+ IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_DB_SOURCES ); // IMG_SERVER
+ IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_DB_SOURCE_OFF ); // IMG_SRC_CLOSED
+ IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_DB_SOURCE_ON ); // IMG_SRC_OPENED
+ IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_DB_TABLE ); // IMG_TABLE
+ IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_SHAPES_POINT ); // IMG_POINT
+ IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_SHAPES_POINTS ); // IMG_POINTS
+ IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_SHAPES_LINE ); // IMG_LINE
IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_SHAPES_POLYGON); // IMG_POLYGON
- IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_GRID); // IMG_GRID
+ IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_GRID_MANAGER ); // IMG_GRIDS
+ IMG_ADD_TO_TREECTRL(ID_IMG_WKSP_GRID ); // IMG_GRID
AddRoot(_TL("PostgreSQL Sources"), IMG_ROOT, IMG_ROOT, new CData_Source_PgSQL_Data(TYPE_ROOT));
//-----------------------------------------------------
+ SG_UI_Msg_Lock(true);
+
wxString Server;
for(int i=0; CONFIG_Read(CFG_PGSQL_DIR, wxString::Format(CFG_PGSQL_SRC, i), Server); i++)
{
- Update_Source(AppendItem(GetRootItem(), Server.c_str(), IMG_SRC_CLOSED, IMG_SRC_CLOSED,
- new CData_Source_PgSQL_Data(TYPE_SOURCE, &Server, &Server)
- ));
+ wxString User, Password;
+
+ if( Server.Find("|") > 0 )
+ {
+ User = Server.AfterFirst ('|').BeforeFirst('|');
+ Password = Server.AfterLast ('|');
+ Server = Server.BeforeFirst('|');
+ }
+
+ CData_Source_PgSQL_Data *pData = new CData_Source_PgSQL_Data(TYPE_SOURCE, &Server, &Server, &User, &Password);
+
+ Update_Source(AppendItem(Get_Server_Item(Server, true), pData->Get_DBName().c_str(), IMG_SRC_CLOSED, IMG_SRC_CLOSED, pData));
}
Update_Sources();
+
+ SG_UI_Msg_Lock(false);
}
//---------------------------------------------------------
CData_Source_PgSQL::~CData_Source_PgSQL(void)
{
- wxTreeItemIdValue Cookie;
- wxTreeItemId Item = GetFirstChild(GetRootItem(), Cookie);
+ long Reopen = 0;
+
+ CONFIG_Read("/DATA", "PROJECT_DB_REOPEN", Reopen);
CONFIG_Delete(CFG_PGSQL_DIR);
- for(int i=0; Item.IsOk(); )
+ wxTreeItemIdValue srvCookie; wxTreeItemId srvItem = GetFirstChild(GetRootItem(), srvCookie);
+
+ for(int i=0; srvItem.IsOk(); )
{
- CData_Source_PgSQL_Data *pData = (CData_Source_PgSQL_Data *)GetItemData(Item);
+ wxTreeItemIdValue Cookie; wxTreeItemId Item = GetFirstChild(srvItem, Cookie);
- if( pData && pData->Get_Type() == TYPE_SOURCE )
+ while( Item.IsOk() )
{
- CONFIG_Write(CFG_PGSQL_DIR, wxString::Format(CFG_PGSQL_SRC, i++), pData->Get_Server().c_str());
+ CData_Source_PgSQL_Data *pData = (CData_Source_PgSQL_Data *)GetItemData(Item);
+
+ if( pData && pData->Get_Type() == TYPE_SOURCE )
+ {
+ CSG_String Connection = pData->Get_Server().c_str();
+
+ if( Reopen != 0 && pData->is_Connected() && !pData->Get_Username().is_Empty() ) // store user and password
+ {
+ Connection += "|" + pData->Get_Username() + "|" + pData->Get_Password();
+ }
+
+ CONFIG_Write(CFG_PGSQL_DIR, wxString::Format(CFG_PGSQL_SRC, i++), Connection.c_str());
+ }
+
+ Item = GetNextChild(Item, Cookie);
}
- Item = GetNextChild(Item, Cookie);
+ srvItem = GetNextChild(srvItem, srvCookie);
+ }
+}
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
+void CData_Source_PgSQL::Autoconnect(void)
+{
+ long Reopen = 0;
+
+ CONFIG_Read("/DATA", "PROJECT_DB_REOPEN", Reopen);
+
+ if( Reopen != 0 )
+ {
+ wxTreeItemIdValue srvCookie; wxTreeItemId srvItem = GetFirstChild(GetRootItem(), srvCookie);
+
+ while( srvItem.IsOk() )
+ {
+ wxTreeItemIdValue Cookie; wxTreeItemId Item = GetFirstChild(srvItem, Cookie);
+
+ while( Item.IsOk() )
+ {
+ CData_Source_PgSQL_Data *pData = Item.IsOk() ? (CData_Source_PgSQL_Data *)GetItemData(Item) : NULL; if( pData == NULL ) return;
+
+ if( pData->Get_Type() == TYPE_SOURCE && !pData->Get_Username().is_Empty() )
+ {
+ Source_Open(pData, false);
+ }
+
+ Item = GetNextChild(Item, Cookie);
+ }
+
+ srvItem = GetNextChild(srvItem, srvCookie);
+ }
}
}
@@ -321,6 +484,18 @@ void CData_Source_PgSQL::On_Refresh(wxCommandEvent &WXUNUSED(event))
}
//---------------------------------------------------------
+void CData_Source_PgSQL::On_Source_Create(wxCommandEvent &WXUNUSED(event))
+{
+ Source_Create(GetSelection());
+}
+
+//---------------------------------------------------------
+void CData_Source_PgSQL::On_Source_Drop(wxCommandEvent &WXUNUSED(event))
+{
+ Source_Drop(GetSelection());
+}
+
+//---------------------------------------------------------
void CData_Source_PgSQL::On_Source_Open(wxCommandEvent &WXUNUSED(event))
{
Source_Open(GetSelection());
@@ -386,12 +561,17 @@ void CData_Source_PgSQL::On_Item_Activated(wxTreeEvent &event)
Update_Sources();
break;
+ case TYPE_SERVER:
+ Update_Sources(event.GetItem());
+ break;
+
case TYPE_SOURCE:
Source_Open(event.GetItem());
break;
case TYPE_TABLE:
case TYPE_SHAPES:
+ case TYPE_GRIDS:
case TYPE_GRID:
Table_Open(event.GetItem());
break;
@@ -417,6 +597,14 @@ void CData_Source_PgSQL::On_Item_Menu(wxTreeEvent &event)
{
case TYPE_ROOT:
CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_REFRESH);
+ CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_SOURCE_CREATE);
+ CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_SOURCE_OPEN);
+ CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_SOURCE_CLOSE_ALL);
+ break;
+
+ case TYPE_SERVER:
+ CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_REFRESH);
+ CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_SOURCE_CREATE);
CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_SOURCE_OPEN);
CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_SOURCE_CLOSE_ALL);
break;
@@ -431,6 +619,7 @@ void CData_Source_PgSQL::On_Item_Menu(wxTreeEvent &event)
else
{
CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_REFRESH);
+ CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_SOURCE_DROP);
CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_SOURCE_CLOSE);
CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_SOURCE_DELETE);
CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_TABLE_FROM_QUERY);
@@ -439,12 +628,18 @@ void CData_Source_PgSQL::On_Item_Menu(wxTreeEvent &event)
case TYPE_TABLE:
case TYPE_SHAPES:
- case TYPE_GRID:
+ case TYPE_GRIDS:
CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_TABLE_OPEN);
CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_TABLE_RENAME);
CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_TABLE_DELETE);
CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_TABLE_INFO);
break;
+
+ case TYPE_GRID:
+ CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_TABLE_OPEN);
+ CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_TABLE_RENAME);
+ CMD_Menu_Add_Item(&Menu, false, ID_CMD_DB_TABLE_DELETE);
+ break;
}
if( Menu.GetMenuItemCount() > 0 )
@@ -461,17 +656,50 @@ void CData_Source_PgSQL::On_Item_Menu(wxTreeEvent &event)
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-wxTreeItemId CData_Source_PgSQL::Find_Source(const wxString &Server)
+wxTreeItemId CData_Source_PgSQL::Get_Server_Item(const wxString &Server, bool bCreate)
{
- wxTreeItemIdValue Cookie;
+ wxString Name = Server.AfterFirst('[').BeforeFirst(']');
- wxTreeItemId Item = GetFirstChild(GetRootItem(), Cookie);
+ wxTreeItemIdValue Cookie; wxTreeItemId Item = GetFirstChild(GetRootItem(), Cookie);
- while( Item.IsOk() && Server.Cmp(GetItemText(Item)) )
+ while( Item.IsOk() )
{
+ if( !Name.Cmp(GetItemText(Item)) )
+ {
+ return( Item );
+ }
+
Item = GetNextChild(Item, Cookie);
}
+ if( bCreate )
+ {
+ Item = AppendItem(GetRootItem(), Name, IMG_SERVER, IMG_SERVER, new CData_Source_PgSQL_Data(TYPE_SERVER, &Name, &Name));
+
+ SortChildren(GetRootItem());
+ Expand (GetRootItem());
+ }
+
+ return( Item );
+}
+
+//---------------------------------------------------------
+wxTreeItemId CData_Source_PgSQL::Find_Source(const wxString &Server)
+{
+ wxTreeItemId Item = Get_Server_Item(Server, false);
+
+ if( Item.IsOk() )
+ {
+ wxTreeItemIdValue Cookie; Item = GetFirstChild(Item, Cookie);
+
+ wxString Name = Server.BeforeLast('['); Name.Trim(true);
+
+ while( Item.IsOk() && Name.Cmp(GetItemText(Item)) )
+ {
+ Item = GetNextChild(Item, Cookie);
+ }
+ }
+
return( Item );
}
@@ -483,19 +711,18 @@ void CData_Source_PgSQL::Update_Item(const wxTreeItemId &Item)
switch( pData->Get_Type() )
{
case TYPE_ROOT: Update_Sources(); break;
- case TYPE_SOURCE: Update_Source(Item); break;
+ case TYPE_SERVER: Update_Sources(Item); break;
+ case TYPE_SOURCE: Update_Source (Item); break;
}
}
//---------------------------------------------------------
-void CData_Source_PgSQL::Update_Sources(void)
+void CData_Source_PgSQL::Update_Sources(const wxTreeItemId &Root)
{
Freeze();
//-----------------------------------------------------
- wxTreeItemIdValue Cookie;
-
- wxTreeItemId Item = GetFirstChild(GetRootItem(), Cookie);
+ wxTreeItemIdValue Cookie; wxTreeItemId Item = GetFirstChild(Root, Cookie);
while( Item.IsOk() )
{
@@ -505,10 +732,9 @@ void CData_Source_PgSQL::Update_Sources(void)
}
//-----------------------------------------------------
- bool bResult;
CSG_Table Connections;
- RUN_MODULE(DB_PGSQL_Get_Connections, bResult, SET_PARAMETER("CONNECTIONS", &Connections)); // CGet_Connections
+ RUN_MODULE(DB_PGSQL_Get_Connections, false, SET_PARAMETER("CONNECTIONS", &Connections)); // CGet_Connections
for(int i=0; i<Connections.Get_Count(); i++)
{
@@ -519,13 +745,26 @@ void CData_Source_PgSQL::Update_Sources(void)
}
//-----------------------------------------------------
- SortChildren(GetRootItem());
- Expand (GetRootItem());
+ SortChildren(Root);
+ Expand (Root);
Thaw();
}
//---------------------------------------------------------
+void CData_Source_PgSQL::Update_Sources(void)
+{
+ wxTreeItemIdValue Cookie; wxTreeItemId Item = GetFirstChild(GetRootItem(), Cookie);
+
+ while( Item.IsOk() )
+ {
+ Update_Sources(Item);
+
+ Item = GetNextChild(Item, Cookie);
+ }
+}
+
+//---------------------------------------------------------
void CData_Source_PgSQL::Update_Source(const wxString &Server)
{
if( Server.IsEmpty() )
@@ -537,11 +776,11 @@ void CData_Source_PgSQL::Update_Source(const wxString &Server)
wxTreeItemId Item = Find_Source(Server);
- if( !Item.IsOk() && is_Connected(&Server) )
+ if( !Item.IsOk() && PGSQL_is_Connected(&Server) )
{
- Item = AppendItem(GetRootItem(), Server.c_str(), IMG_SRC_OPENED, IMG_SRC_OPENED,
- new CData_Source_PgSQL_Data(TYPE_SOURCE, &Server, &Server)
- );
+ CData_Source_PgSQL_Data *pData = new CData_Source_PgSQL_Data(TYPE_SOURCE, &Server, &Server);
+
+ Item = AppendItem(Get_Server_Item(Server, true), pData->Get_DBName().c_str(), IMG_SRC_OPENED, IMG_SRC_OPENED, pData);
}
Update_Source(Item);
@@ -572,10 +811,9 @@ void CData_Source_PgSQL::Update_Source(const wxTreeItemId &Item)
SetItemImage(Item, IMG_SRC_OPENED, wxTreeItemIcon_Normal);
SetItemImage(Item, IMG_SRC_OPENED, wxTreeItemIcon_Selected);
- bool bResult;
CSG_Table Tables;
- RUN_MODULE(DB_PGSQL_Table_List, bResult, // CTable_List
+ RUN_MODULE(DB_PGSQL_Table_List, false, // CTable_List
SET_PARAMETER("CONNECTION", pData->Get_Value())
&& SET_PARAMETER("TABLES" , &Tables)
);
@@ -599,11 +837,11 @@ void CData_Source_PgSQL::Update_Source(const wxTreeItemId &Item)
case SHAPE_TYPE_Polygon: Append_Table(Item, Tables[i].asString(0), TYPE_SHAPES, IMG_POLYGON); break;
}
}
- else if( !s.Cmp("RASTER" ) ) Append_Table(Item, Tables[i].asString(0), TYPE_GRID , IMG_GRID );
+ else if( !s.Cmp("RASTER" ) ) Append_Table(Item, Tables[i].asString(0), TYPE_GRIDS , IMG_GRIDS );
else if( !s.Cmp("TABLE" ) ) Append_Table(Item, Tables[i].asString(0), TYPE_TABLE , IMG_TABLE );
}
- Expand (Item);
+ Expand(Item);
}
Thaw();
@@ -614,7 +852,29 @@ void CData_Source_PgSQL::Append_Table(const wxTreeItemId &Parent, const SG_Char
{
CData_Source_PgSQL_Data *pData = Parent.IsOk() ? (CData_Source_PgSQL_Data *)GetItemData(Parent) : NULL; if( pData == NULL ) return;
- AppendItem(Parent, Name, Image, Image, new CData_Source_PgSQL_Data(Type, Name, pData->Get_Server()));
+ wxTreeItemId Item = AppendItem(Parent, Name, Image, Image, new CData_Source_PgSQL_Data(Type, Name, pData->Get_Server()));
+
+ if( Type == TYPE_GRIDS )
+ {
+ CSG_Table Grids;
+
+ RUN_MODULE(DB_PGSQL_Table_Query, false, // CTable_Query
+ SET_PARAMETER("CONNECTION", pData->Get_Server())
+ && SET_PARAMETER("TABLES" , Name)
+ && SET_PARAMETER("TABLE" , &Grids)
+ && SET_PARAMETER("FIELDS" , SG_T("rid, name"))
+ );
+
+ if( bResult )
+ {
+ for(int i=0; i<Grids.Get_Count(); i++)
+ {
+ AppendItem(Item, Grids[i].asString(1), IMG_GRID, IMG_GRID,
+ new CData_Source_PgSQL_Data(TYPE_GRID, CSG_String::Format("%s:rid=%d", Name, Grids[i].asInt(0)), pData->Get_Server())
+ );
+ }
+ }
+ }
}
@@ -625,49 +885,135 @@ void CData_Source_PgSQL::Append_Table(const wxTreeItemId &Parent, const SG_Char
///////////////////////////////////////////////////////////
//---------------------------------------------------------
-void CData_Source_PgSQL::Source_Open(const wxTreeItemId &Item)
+bool CData_Source_PgSQL::Source_Create(const wxTreeItemId &Item)
{
- CData_Source_PgSQL_Data *pData = Item.IsOk() ? (CData_Source_PgSQL_Data *)GetItemData(Item) : NULL; if( pData == NULL ) return;
+ CData_Source_PgSQL_Data *pData = Item.IsOk() ? (CData_Source_PgSQL_Data *)GetItemData(Item) : NULL; if( pData == NULL ) return( false );
- if( pData->Get_Type() == TYPE_ROOT )
+ if( pData->Get_Type() == TYPE_ROOT
+ || pData->Get_Type() == TYPE_SERVER )
{
- CSG_Module *pModule = SG_Get_Module_Library_Manager().Get_Module(SG_T("db_pgsql"), DB_PGSQL_Get_Connection); // CGet_Connection
+ CSG_Module *pModule = SG_Get_Module_Library_Manager().Get_Module("db_pgsql", DB_PGSQL_DB_Create);
- if( pModule && pModule->On_Before_Execution() && DLG_Parameters(pModule->Get_Parameters()) )
+ if( pModule && pModule->On_Before_Execution() )
{
- pModule->Execute();
+ if( pData->Get_Type() == TYPE_SERVER )
+ {
+ pModule->Set_Parameter("PG_HOST", pData->Get_Host());
+ pModule->Set_Parameter("PG_PORT", pData->Get_Port());
+ }
+
+ if( DLG_Parameters(pModule->Get_Parameters()) )
+ {
+ pModule->Execute();
+ }
}
}
- else if( pData->is_Connected() )
+
+ return( true );
+}
+
+//---------------------------------------------------------
+bool CData_Source_PgSQL::Source_Drop(const wxTreeItemId &Item)
+{
+ static wxString Username = "postgres", Password = "postgres";
+
+ CData_Source_PgSQL_Data *pData = Item.IsOk() ? (CData_Source_PgSQL_Data *)GetItemData(Item) : NULL; if( pData == NULL ) return( false );
+
+ if( !DLG_Login(Username, Password, _TL("Drop Database")) )
{
- Update_Source(Item);
+ return( false );
}
- else
+
+ pData->Set_Username(Username);
+ pData->Set_Password(Password);
+
+ if( pData->Get_Type() == TYPE_SOURCE && pData->is_Connected() )
{
- static wxString Username = "postgres", Password = "postgres";
+ RUN_MODULE(DB_PGSQL_DB_Drop, true, // CDatabase_Drop
+ SET_PARAMETER("PG_HOST", pData->Get_Host ())
+ && SET_PARAMETER("PG_PORT", pData->Get_Port ())
+ && SET_PARAMETER("PG_NAME", pData->Get_DBName ())
+ && SET_PARAMETER("PG_USER", pData->Get_Username())
+ && SET_PARAMETER("PG_PWD" , pData->Get_Password())
+ );
+
+ return( bResult );
+ }
+
+ return( false );
+}
+
+//---------------------------------------------------------
+bool CData_Source_PgSQL::Source_Open(CData_Source_PgSQL_Data *pData, bool bDialog)
+{
+ static wxString Username = "postgres", Password = "postgres";
- if( DLG_Login(Username, Password) )
+ if( bDialog )
+ {
+ if( !DLG_Login(Username, Password) )
{
- bool bResult;
-
- CSG_String Host = pData->Get_Server().AfterLast ('[').BeforeFirst(':');
- CSG_String Port = pData->Get_Server().AfterLast (':').BeforeFirst(']');
- CSG_String Name = pData->Get_Server().BeforeLast('['); Name.Trim(true);
-
- RUN_MODULE(DB_PGSQL_Get_Connection, bResult, // CGet_Connection
- SET_PARAMETER("PG_HOST", Host)
- && SET_PARAMETER("PG_PORT", Port)
- && SET_PARAMETER("PG_NAME", Name)
- && SET_PARAMETER("PG_USER", Username)
- && SET_PARAMETER("PG_PWD" , Password)
- );
+ return( false );
+ }
+
+ pData->Set_Username(Username);
+ pData->Set_Password(Password);
+ }
+
+ //-----------------------------------------------------
+ MSG_General_Add(wxString::Format("%s: %s...", _TL("Connect to Database"), pData->Get_Server().c_str()), true, true);
+
+ RUN_MODULE(DB_PGSQL_Get_Connection, false, // CGet_Connection
+ SET_PARAMETER("PG_HOST", pData->Get_Host ())
+ && SET_PARAMETER("PG_PORT", pData->Get_Port ())
+ && SET_PARAMETER("PG_NAME", pData->Get_DBName ())
+ && SET_PARAMETER("PG_USER", pData->Get_Username())
+ && SET_PARAMETER("PG_PWD" , pData->Get_Password())
+ );
+
+ if( bResult )
+ {
+ MSG_General_Add(_TL("okay"), false, false, SG_UI_MSG_STYLE_SUCCESS);
- if( !bResult )
+ return( true );
+ }
+
+ MSG_General_Add(_TL("failed"), false, false, SG_UI_MSG_STYLE_FAILURE);
+
+ return( false );
+}
+
+//---------------------------------------------------------
+void CData_Source_PgSQL::Source_Open(const wxTreeItemId &Item)
+{
+ CData_Source_PgSQL_Data *pData = Item.IsOk() ? (CData_Source_PgSQL_Data *)GetItemData(Item) : NULL; if( pData == NULL ) return;
+
+ if( pData->Get_Type() == TYPE_ROOT
+ || pData->Get_Type() == TYPE_SERVER )
+ {
+ CSG_Module *pModule = SG_Get_Module_Library_Manager().Get_Module("db_pgsql", DB_PGSQL_Get_Connection); // CGet_Connection
+
+ if( pModule && pModule->On_Before_Execution() )
+ {
+ if( pData->Get_Type() == TYPE_SERVER )
+ {
+ pModule->Set_Parameter("PG_HOST", pData->Get_Host());
+ pModule->Set_Parameter("PG_PORT", pData->Get_Port());
+ }
+
+ if( DLG_Parameters(pModule->Get_Parameters()) )
{
- DLG_Message_Show_Error(_TL("Could not connect to data source."), _TL("Connect to PostgreSQL"));
+ pModule->Execute();
}
}
}
+ else if( pData->is_Connected() )
+ {
+ Update_Source(Item);
+ }
+ else if( !Source_Open(pData, true) )
+ {
+ DLG_Message_Show_Error(_TL("Could not connect to data source."), _TL("Connect to PostgreSQL"));
+ }
}
//---------------------------------------------------------
@@ -677,31 +1023,24 @@ void CData_Source_PgSQL::Source_Close(const wxTreeItemId &Item, bool bDelete)
if( pData->is_Connected() )
{
- CSG_Module *pModule = SG_Get_Module_Library_Manager().Get_Module(SG_T("db_pgsql"), DB_PGSQL_Del_Connection); // CDel_Connection
-
- if( pModule )
- {
- pModule->On_Before_Execution();
- pModule->Get_Parameters()->Set_Parameter("CONNECTION", pData->Get_Server());
- pModule->Execute();
- }
+ RUN_MODULE(DB_PGSQL_Del_Connection, true, SET_PARAMETER("CONNECTION", pData->Get_Server()));
}
if( bDelete )
{
Delete(Item);
}
+ else
+ {
+ pData->Set_Username(SG_T(""));
+ pData->Set_Password(SG_T(""));
+ }
}
//---------------------------------------------------------
void CData_Source_PgSQL::Sources_Close(void)
{
- CSG_Module *pModule = SG_Get_Module_Library_Manager().Get_Module(SG_T("db_pgsql"), DB_PGSQL_Del_Connections); // CDel_Connections
-
- if( pModule )
- {
- pModule->Execute();
- }
+ RUN_MODULE(DB_PGSQL_Del_Connections, true, true);
}
@@ -721,18 +1060,14 @@ void CData_Source_PgSQL::Table_Open(const wxTreeItemId &Item)
{
CSG_Table *pTable = SG_Create_Table();
- bool bResult;
-
- RUN_MODULE(DB_PGSQL_Table_Load, bResult, // CTable_Load
+ RUN_MODULE(DB_PGSQL_Table_Load, true, // CTable_Load
SET_PARAMETER("CONNECTION", pData->Get_Server())
- && SET_PARAMETER("TABLES" , pData->Get_Value())
+ && SET_PARAMETER("TABLES" , pData->Get_Value ())
&& SET_PARAMETER("TABLE" , pTable)
);
if( bResult )
{
- SG_Get_Data_Manager().Add(pTable);
-
g_pData->Show(pTable, 0);
}
else
@@ -746,18 +1081,14 @@ void CData_Source_PgSQL::Table_Open(const wxTreeItemId &Item)
{
CSG_Shapes *pShapes = SG_Create_Shapes();
- bool bResult;
-
- RUN_MODULE(DB_PGSQL_Shapes_Load, bResult, // CPGIS_Shapes_Load
+ RUN_MODULE(DB_PGSQL_Shapes_Load, true, // CPGIS_Shapes_Load
SET_PARAMETER("CONNECTION", pData->Get_Server())
- && SET_PARAMETER("TABLES" , pData->Get_Value())
+ && SET_PARAMETER("TABLES" , pData->Get_Value ())
&& SET_PARAMETER("SHAPES" , pShapes)
);
if( bResult )
{
- SG_Get_Data_Manager().Add(pShapes);
-
// g_pData->Show(pShapes, SG_UI_DATAOBJECT_SHOW_NEW_MAP);
}
else
@@ -767,17 +1098,22 @@ void CData_Source_PgSQL::Table_Open(const wxTreeItemId &Item)
}
//-----------------------------------------------------
- if( pData->Get_Type() == TYPE_GRID )
+ if( pData->Get_Type() == TYPE_GRIDS )
{
- CSG_Module *pModule = SG_Get_Module_Library_Manager().Get_Module(SG_T("db_pgsql"), DB_PGSQL_Raster_Load); // CPGIS_Raster_Load
+ RUN_MODULE(DB_PGSQL_Raster_Load, true,
+ SET_PARAMETER("CONNECTION", pData->Get_Server())
+ && SET_PARAMETER("TABLES" , pData->Get_Value ())
+ );
+ }
- if( pModule )
- {
- pModule->On_Before_Execution();
- pModule->Get_Parameters()->Set_Parameter("CONNECTION", pData->Get_Server());
- pModule->Get_Parameters()->Set_Parameter("TABLES" , pData->Get_Value ());
- pModule->Execute();
- }
+ //-----------------------------------------------------
+ if( pData->Get_Type() == TYPE_GRID )
+ {
+ RUN_MODULE(DB_PGSQL_Raster_Load, true,
+ SET_PARAMETER("CONNECTION", pData->Get_Server())
+ && SET_PARAMETER("TABLES" , pData->Get_Value ().BeforeFirst(':'))
+ && SET_PARAMETER("WHERE" , pData->Get_Value ().AfterFirst (':'))
+ );
}
}
@@ -786,23 +1122,47 @@ void CData_Source_PgSQL::Table_Rename(const wxTreeItemId &Item)
{
CData_Source_PgSQL_Data *pData = Item.IsOk() ? (CData_Source_PgSQL_Data *)GetItemData(Item) : NULL; if( pData == NULL ) return;
- wxString Name = pData->Get_Value().c_str();
+ wxString Name = GetItemText(Item);
- if( DLG_Get_Text(Name, _TL("Rename Table"), _TL("Name")) )
+ switch( pData->Get_Type() )
{
- CSG_String SQL = "ALTER TABLE \"" + pData->Get_Value() + "\" RENAME TO \"" + CSG_String(&Name) + "\";";
+ //-----------------------------------------------------
+ case TYPE_GRID:
+ if( DLG_Get_Text(Name, _TL("Rename Raster Band"), _TL("Name")) )
+ {
+ CSG_String Table = pData->Get_Value().BeforeFirst(':');
+ CSG_String rid = pData->Get_Value().AfterFirst (':');
+ CSG_String SQL = "UPDATE \"" + Table + "\" SET name='" + CSG_String(&Name) + "' WHERE " + rid + ";";
- bool bResult;
+ RUN_MODULE(DB_PGSQL_Execute_SQL, false,
+ SET_PARAMETER("CONNECTION", pData->Get_Server())
+ && SET_PARAMETER("SQL" , SQL)
+ );
- RUN_MODULE(DB_PGSQL_Execute_SQL, bResult,
- SET_PARAMETER("CONNECTION", pData->Get_Server())
- && SET_PARAMETER("SQL" , SQL)
- );
+ if( bResult )
+ {
+ SetItemText(Item, Name);
+ }
+ }
+ break;
- if( bResult )
+ //-----------------------------------------------------
+ default:
+ if( DLG_Get_Text(Name, _TL("Rename Table"), _TL("Name")) )
{
- SetItemText(Item, Name);
+ CSG_String SQL = "ALTER TABLE \"" + pData->Get_Value() + "\" RENAME TO \"" + CSG_String(&Name) + "\";";
+
+ RUN_MODULE(DB_PGSQL_Execute_SQL, false,
+ SET_PARAMETER("CONNECTION", pData->Get_Server())
+ && SET_PARAMETER("SQL" , SQL)
+ );
+
+ if( bResult )
+ {
+ SetItemText(Item, Name);
+ }
}
+ break;
}
}
@@ -811,19 +1171,21 @@ void CData_Source_PgSQL::Table_Info(const wxTreeItemId &Item)
{
CData_Source_PgSQL_Data *pData = Item.IsOk() ? (CData_Source_PgSQL_Data *)GetItemData(Item) : NULL; if( pData == NULL ) return;
- CSG_Module *pModule = SG_Get_Module_Library_Manager().Get_Module(SG_T("db_pgsql"), DB_PGSQL_Table_Info);
+ CSG_Table *pTable = SG_Create_Table();
+
+ RUN_MODULE(DB_PGSQL_Table_Info, true, // CTable_Info
+ SET_PARAMETER("CONNECTION", pData->Get_Server())
+ && SET_PARAMETER("TABLES" , pData->Get_Value ())
+ && SET_PARAMETER("TABLE" , pTable)
+ );
- if( pModule )
+ if( bResult )
{
- pModule->On_Before_Execution();
- pModule->Get_Parameters()->Set_Parameter("CONNECTION", pData->Get_Server());
- pModule->Get_Parameters()->Set_Parameter("TABLES" , pData->Get_Value ());
- pModule->Get_Parameters()->Set_Parameter("TABLE" , DATAOBJECT_NOTSET );
-
- if( pModule->Execute() )
- {
- g_pData->Show(pModule->Get_Parameters()->Get_Parameter("TABLE")->asTable());
- }
+ g_pData->Show(pTable, 0);
+ }
+ else
+ {
+ delete(pTable);
}
}
@@ -832,27 +1194,61 @@ void CData_Source_PgSQL::Table_Drop(const wxTreeItemId &Item)
{
CData_Source_PgSQL_Data *pData = Item.IsOk() ? (CData_Source_PgSQL_Data *)GetItemData(Item) : NULL; if( pData == NULL ) return;
- if( DLG_Message_Confirm(wxString::Format(wxT("%s [%s]"), _TL("Do you really want to delete the table"), pData->Get_Value().c_str()), _TL("Table Deletion")) )
+ wxString Name = GetItemText(Item);
+
+ switch( pData->Get_Type() )
{
- MSG_General_Add(wxString::Format(wxT("%s: [%s] %s..."), _TL("Deleting table"), pData->Get_Server().c_str(), pData->Get_Value().c_str()), true, true);
+ //-----------------------------------------------------
+ case TYPE_GRID:
+ if( DLG_Message_Confirm(wxString::Format("%s [%s]", _TL("Do you really want to delete this raster band"), Name.c_str()), _TL("Raster Band Deletion")) )
+ {
+ MSG_General_Add(wxString::Format("%s: [%s] %s...", _TL("Deleting raster band"), pData->Get_Server().c_str(), Name.c_str()), true, true);
- bool bResult;
+ CSG_String Table = pData->Get_Value().BeforeFirst(':');
+ CSG_String rid = pData->Get_Value().AfterFirst (':');
+ CSG_String SQL = "DELETE FROM \"" + Table + "\" WHERE " + rid + ";";
- RUN_MODULE(DB_PGSQL_Table_Drop, bResult, // CTable_Drop
- SET_PARAMETER("CONNECTION", pData->Get_Server())
- && SET_PARAMETER("TABLES" , pData->Get_Value())
- );
+ RUN_MODULE(DB_PGSQL_Execute_SQL, false,
+ SET_PARAMETER("CONNECTION", pData->Get_Server())
+ && SET_PARAMETER("SQL" , SQL)
+ );
- if( bResult )
- {
- Delete(Item);
+ if( bResult )
+ {
+ Delete(Item);
- MSG_General_Add(_TL("okay"), false, false, SG_UI_MSG_STYLE_SUCCESS);
+ MSG_General_Add(_TL("okay"), false, false, SG_UI_MSG_STYLE_SUCCESS);
+ }
+ else
+ {
+ MSG_General_Add(_TL("failed"), false, false, SG_UI_MSG_STYLE_FAILURE);
+ }
}
- else
+ break;
+
+ //-----------------------------------------------------
+ default:
+ if( DLG_Message_Confirm(wxString::Format("%s [%s]", _TL("Do you really want to delete the table"), pData->Get_Value().c_str()), _TL("Table Deletion")) )
{
- MSG_General_Add(_TL("failed"), false, false, SG_UI_MSG_STYLE_FAILURE);
+ MSG_General_Add(wxString::Format("%s: [%s] %s...", _TL("Deleting table"), pData->Get_Server().c_str(), pData->Get_Value().c_str()), true, true);
+
+ RUN_MODULE(DB_PGSQL_Table_Drop, false, // CTable_Drop
+ SET_PARAMETER("CONNECTION", pData->Get_Server())
+ && SET_PARAMETER("TABLES" , pData->Get_Value())
+ );
+
+ if( bResult )
+ {
+ Delete(Item);
+
+ MSG_General_Add(_TL("okay"), false, false, SG_UI_MSG_STYLE_SUCCESS);
+ }
+ else
+ {
+ MSG_General_Add(_TL("failed"), false, false, SG_UI_MSG_STYLE_FAILURE);
+ }
}
+ break;
}
}
diff --git a/src/saga_core/saga_gui/data_source_pgsql.h b/src/saga_core/saga_gui/data_source_pgsql.h
index 98dffff..fbbf961 100644
--- a/src/saga_core/saga_gui/data_source_pgsql.h
+++ b/src/saga_core/saga_gui/data_source_pgsql.h
@@ -80,12 +80,31 @@
///////////////////////////////////////////////////////////
//---------------------------------------------------------
+bool PGSQL_is_Connected (const CSG_String &Server);
+
+bool PGSQL_has_Connections (double vPostGIS = 0.0);
+bool PGSQL_Get_Connections (CSG_Strings &Servers, double vPostGIS = 0.0);
+
+bool PGSQL_Save_Table (CSG_Table *pTable);
+bool PGSQL_Save_Shapes (CSG_Shapes *pShapes);
+bool PGSQL_Save_Grid (CSG_Grid *pGrid);
+
+
+///////////////////////////////////////////////////////////
+// //
+// //
+// //
+///////////////////////////////////////////////////////////
+
+//---------------------------------------------------------
class CData_Source_PgSQL : public wxTreeCtrl
{
public:
CData_Source_PgSQL(wxWindow *pParent);
virtual ~CData_Source_PgSQL(void);
+ void Autoconnect (void);
+
void Update_Sources (void);
void Update_Source (const wxString &Server);
@@ -97,6 +116,8 @@ private:
void On_Item_Menu (wxTreeEvent &event);
void On_Refresh (wxCommandEvent &event);
+ void On_Source_Create (wxCommandEvent &event);
+ void On_Source_Drop (wxCommandEvent &event);
void On_Source_Open (wxCommandEvent &event);
void On_Source_Close (wxCommandEvent &event);
void On_Sources_Close (wxCommandEvent &event);
@@ -106,6 +127,9 @@ private:
void On_Table_Info (wxCommandEvent &event);
void On_Table_Drop (wxCommandEvent &event);
+ bool Source_Create (const wxTreeItemId &Item);
+ bool Source_Drop (const wxTreeItemId &Item);
+ bool Source_Open (class CData_Source_PgSQL_Data *pData, bool bDialog);
void Source_Open (const wxTreeItemId &Item);
void Source_Close (const wxTreeItemId &Item, bool bDelete);
void Sources_Close (void);
@@ -114,8 +138,10 @@ private:
void Table_Info (const wxTreeItemId &Item);
void Table_Drop (const wxTreeItemId &Item);
+ wxTreeItemId Get_Server_Item (const wxString &Server, bool bCreate);
wxTreeItemId Find_Source (const wxString &Server);
void Update_Item (const wxTreeItemId &Item);
+ void Update_Sources (const wxTreeItemId &Root);
void Update_Source (const wxTreeItemId &Item);
void Append_Table (const wxTreeItemId &Parent, const SG_Char *Name, int Type, int Image);
diff --git a/src/saga_core/saga_gui/info_messages.cpp b/src/saga_core/saga_gui/info_messages.cpp
index 22a79d3..1882626 100644
--- a/src/saga_core/saga_gui/info_messages.cpp
+++ b/src/saga_core/saga_gui/info_messages.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: info_messages.cpp 2375 2015-01-28 19:18:55Z oconrad $
+ * Version $Id: info_messages.cpp 2616 2015-09-29 13:48:28Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -300,21 +300,24 @@ void CINFO_Messages::Add_Line(void)
//---------------------------------------------------------
void CINFO_Messages::Add_String(wxString sMessage, bool bNewLine, bool bTime, TSG_UI_MSG_STYLE Style)
{
- if( bNewLine )
+ if( !sMessage.IsEmpty() )
{
- _Add_Text(wxT("\n"));
- }
+ if( bNewLine )
+ {
+ _Add_Text(wxT("\n"));
+ }
- if( bTime )
- {
- Add_Time(false);
+ if( bTime )
+ {
+ Add_Time(false);
- _Add_Text(wxT(" "));
- }
+ _Add_Text(wxT(" "));
+ }
- _Set_Style(Style);
+ _Set_Style(Style);
- _Add_Text(sMessage);
+ _Add_Text(sMessage);
+ }
}
diff --git a/src/saga_core/saga_gui/parameters_control.cpp b/src/saga_core/saga_gui/parameters_control.cpp
index 68f8838..741e81b 100644
--- a/src/saga_core/saga_gui/parameters_control.cpp
+++ b/src/saga_core/saga_gui/parameters_control.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: parameters_control.cpp 2078 2014-04-02 16:35:47Z oconrad $
+ * Version $Id: parameters_control.cpp 2624 2015-09-30 15:33:53Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -458,7 +458,7 @@ void CParameters_Control::_Add_Properties(CSG_Parameters *pParameters)
for(int i=0; i<pParameters->Get_Count(); i++)
{
- if( pParameters->Get_Parameter(i)->Get_Parent() == NULL )
+ if( pParameters->Get_Parameter(i)->do_UseInGUI() && pParameters->Get_Parameter(i)->Get_Parent() == NULL )
{
pRoot = NULL;
@@ -536,16 +536,19 @@ void CParameters_Control::_Add_Properties(CSG_Parameters *pParameters)
//---------------------------------------------------------
void CParameters_Control::_Add_Property(wxPGProperty *pParent, CSG_Parameter *pParameter)
{
- wxPGProperty *pProperty = _Get_Property(pParent, pParameter);
-
- if( pParameter->Get_Children_Count() > 0 )
+ if( pParameter->do_UseInGUI() )
{
- for(int i=0; i<pParameter->Get_Children_Count(); i++)
+ wxPGProperty *pProperty = _Get_Property(pParent, pParameter);
+
+ if( pParameter->Get_Children_Count() > 0 )
{
- _Add_Property(pProperty, pParameter->Get_Child(i));
- }
+ for(int i=0; i<pParameter->Get_Children_Count(); i++)
+ {
+ _Add_Property(pProperty, pParameter->Get_Child(i));
+ }
- m_pPG->Expand(pProperty);
+ m_pPG->Expand(pProperty);
+ }
}
}
diff --git a/src/saga_core/saga_gui/project.cpp b/src/saga_core/saga_gui/project.cpp
index 2004905..b7ba7d8 100644
--- a/src/saga_core/saga_gui/project.cpp
+++ b/src/saga_core/saga_gui/project.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: project.cpp 2590 2015-09-18 15:42:35Z oconrad $
+ * Version $Id: project.cpp 2640 2015-10-07 17:29:38Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -284,7 +284,7 @@ bool CWKSP_Project::_Load(const wxString &FileName, bool bAdd, bool bUpdateMenu)
//-------------------------------------------------
g_pSAGA_Frame->Freeze();
- if( (pNode = Project.Get_Child(SG_T("MAPS"))) != NULL && pNode->Get_Children_Count() > 0 )
+ if( (pNode = Project.Get_Child("MAPS")) != NULL && pNode->Get_Children_Count() > 0 )
{
for(int j=0; j<pNode->Get_Children_Count(); j++)
{
@@ -470,7 +470,7 @@ bool CWKSP_Project::_Save(const wxString &FileName, bool bSaveModified, bool bUp
//---------------------------------------------------------
bool CWKSP_Project::_Load_Data(CSG_MetaData &Entry, const wxString &ProjectDir, bool bLoad, const CSG_String &Version)
{
- if( Entry.Get_Name().Cmp(SG_T("DATASET")) )
+ if( Entry.Get_Name().Cmp("DATASET") || !Entry.Get_Child("FILE") || Entry.Get_Child("FILE")->Get_Content().is_Empty() )
{
return( false );
}
@@ -488,25 +488,22 @@ bool CWKSP_Project::_Load_Data(CSG_MetaData &Entry, const wxString &ProjectDir,
return( false );
}
- if( !Entry.Get_Child(SG_T("FILE")) )
- {
- return( false );
- }
-
- wxString File(Get_FilePath_Absolute(ProjectDir, Entry.Get_Child(SG_T("FILE"))->Get_Content().c_str()));
+ //-----------------------------------------------------
+ wxString File = Entry.Get_Child("FILE")->Get_Content().c_str();
- if( !wxFileExists(File) )
+ if( File.Find("PGSQL") != 0 && wxFileExists(Get_FilePath_Absolute(ProjectDir, File)) )
{
- MSG_Error_Add(wxString::Format("%s [%s]", _TL("data file does not exist"), File.c_str()));
-
- return( false );
+ File = Get_FilePath_Absolute(ProjectDir, File);
}
CWKSP_Base_Item *pItem = bLoad ? g_pData->Open(File, Type) : _Get_byFileName(File);
if( !pItem || !pItem->Get_Parameters() || !Entry.Get_Child("PARAMETERS") )
{
- MSG_Error_Add(wxString::Format("%s [%s]", _TL("failed to load data"), File.c_str()));
+ if( bLoad )
+ {
+ MSG_Error_Add(wxString::Format("%s [%s]", _TL("failed to load data"), File.c_str()));
+ }
return( false );
}
@@ -516,11 +513,11 @@ bool CWKSP_Project::_Load_Data(CSG_MetaData &Entry, const wxString &ProjectDir,
for(int i=0; i<pEntry->Get_Children_Count(); i++)
{
- if( !pEntry->Get_Child(i)->Get_Name().CmpNoCase("DATA") && !pEntry->Get_Child(i)->Get_Content().is_Empty() )
+ if( !pEntry->Get_Child(i)->Get_Name().CmpNoCase("DATA") && !pEntry->Get_Child(i)->Get_Content().is_Empty() && pEntry->Get_Child(i)->Get_Content().BeforeFirst(':').Cmp("PGSQL") )
{
- wxString s(Get_FilePath_Absolute(ProjectDir, pEntry->Get_Child(i)->Get_Content().w_str()));
+ wxString File(Get_FilePath_Absolute(ProjectDir, pEntry->Get_Child(i)->Get_Content().w_str()));
- pEntry->Get_Child(i)->Set_Content(&s);
+ pEntry->Get_Child(i)->Set_Content(&File);
// if( SG_Compare_SAGA_Version(Version) < 0 )
{
@@ -547,7 +544,7 @@ bool CWKSP_Project::_Load_Data(CSG_MetaData &Entry, const wxString &ProjectDir,
//---------------------------------------------------------
bool CWKSP_Project::_Save_Data(CSG_MetaData &Entry, const wxString &ProjectDir, CSG_Data_Object *pDataObject, CSG_Parameters *pParameters)
{
- if( !pDataObject || !pDataObject->Get_File_Name(false) || !wxFileExists(pDataObject->Get_File_Name(false)) )
+ if( !pDataObject || !pDataObject->Get_File_Name(false) || SG_STR_LEN(pDataObject->Get_File_Name(false)) == 0 )
{
return( false );
}
@@ -557,16 +554,27 @@ bool CWKSP_Project::_Save_Data(CSG_MetaData &Entry, const wxString &ProjectDir,
switch( pDataObject->Get_ObjectType() )
{
default: return( false );
- case DATAOBJECT_TYPE_Grid: pEntry->Add_Property("type", "GRID" ); break;
- case DATAOBJECT_TYPE_Table: pEntry->Add_Property("type", "TABLE" ); break;
- case DATAOBJECT_TYPE_Shapes: pEntry->Add_Property("type", "SHAPES"); break;
- case DATAOBJECT_TYPE_TIN: pEntry->Add_Property("type", "TIN" ); break;
+ case DATAOBJECT_TYPE_Grid : pEntry->Add_Property("type", "GRID" ); break;
+ case DATAOBJECT_TYPE_Table : pEntry->Add_Property("type", "TABLE" ); break;
+ case DATAOBJECT_TYPE_Shapes : pEntry->Add_Property("type", "SHAPES"); break;
+ case DATAOBJECT_TYPE_TIN : pEntry->Add_Property("type", "TIN" ); break;
case DATAOBJECT_TYPE_PointCloud: pEntry->Add_Property("type", "POINTS"); break;
}
- wxString s(Get_FilePath_Relative(ProjectDir, pDataObject->Get_File_Name(false)));
+ if( wxFileExists(pDataObject->Get_File_Name(false)) )
+ {
+ wxString s(Get_FilePath_Relative(ProjectDir, pDataObject->Get_File_Name(false)));
- pEntry->Add_Child("FILE", &s);
+ pEntry->Add_Child("FILE", &s);
+ }
+ else if( pDataObject->Get_MetaData_DB().Get_Children_Count() > 0 )
+ {
+ pEntry->Add_Child("FILE", pDataObject->Get_File_Name(false));
+ }
+ else
+ {
+ return( false );
+ }
if( pParameters )
{
@@ -579,11 +587,16 @@ bool CWKSP_Project::_Save_Data(CSG_MetaData &Entry, const wxString &ProjectDir,
for(int i=0; i<pEntry->Get_Children_Count(); i++)
{
- if( !pEntry->Get_Child(i)->Get_Name().CmpNoCase("DATA") && SG_File_Exists(pEntry->Get_Child(i)->Get_Content()) )
+ if( !pEntry->Get_Child(i)->Get_Name().CmpNoCase("DATA") )
{
- wxString s(Get_FilePath_Relative(ProjectDir, pEntry->Get_Child(i)->Get_Content().w_str()));
+ CSG_String File = pEntry->Get_Child(i)->Get_Content();
+
+ if( File.BeforeFirst(':').Cmp("PGSQL") && SG_File_Exists(File) )
+ {
+ wxString s(Get_FilePath_Relative(ProjectDir, File.w_str()));
- pEntry->Get_Child(i)->Set_Content(&s);
+ pEntry->Get_Child(i)->Set_Content(&s);
+ }
}
}
}
@@ -627,7 +640,14 @@ bool CWKSP_Project::_Load_Map(CSG_MetaData &Entry, const wxString &ProjectDir)
{
if( !pNode->Get_Child(i)->Get_Name().Cmp("FILE") )
{
- CWKSP_Base_Item *pItem = _Get_byFileName(Get_FilePath_Absolute(ProjectDir, pNode->Get_Child(i)->Get_Content().w_str()));
+ wxString FileName(pNode->Get_Child(i)->Get_Content().w_str());
+
+ if( FileName.Find("PGSQL") != 0 )
+ {
+ FileName = Get_FilePath_Absolute(ProjectDir, FileName);
+ }
+
+ CWKSP_Base_Item *pItem = _Get_byFileName(FileName);
if( pItem &&
( pItem->Get_Type() == WKSP_ITEM_Grid
@@ -652,7 +672,14 @@ bool CWKSP_Project::_Load_Map(CSG_MetaData &Entry, const wxString &ProjectDir)
{
if( !pNode->Get_Child(i)->Get_Name().Cmp("FILE") )
{
- CWKSP_Base_Item *pItem = _Get_byFileName(Get_FilePath_Absolute(ProjectDir, pNode->Get_Child(i)->Get_Content().w_str()));
+ wxString FileName(pNode->Get_Child(i)->Get_Content().w_str());
+
+ if( FileName.Find("PGSQL") != 0 )
+ {
+ FileName = Get_FilePath_Absolute(ProjectDir, FileName);
+ }
+
+ CWKSP_Base_Item *pItem = _Get_byFileName(FileName);
if( pItem &&
( pItem->Get_Type() == WKSP_ITEM_Grid
@@ -707,11 +734,14 @@ bool CWKSP_Project::_Save_Map(CSG_MetaData &Entry, const wxString &ProjectDir, C
{
CSG_Data_Object *pObject = ((CWKSP_Map_Layer *)pMap->Get_Item(i))->Get_Layer()->Get_Object();
- if( pObject && pObject->Get_File_Name(false) && wxFileExists(pObject->Get_File_Name(false)) )
+ if( pObject && pObject->Get_File_Name(false) && *pObject->Get_File_Name(false) )
{
- wxString s(Get_FilePath_Relative(ProjectDir, pObject->Get_File_Name(false)));
+ wxString FileName(pObject->Get_File_Name(false));
- pEntry->Add_Child("FILE", &s);
+ if( FileName.Find("PGSQL") == 0 || wxFileExists(FileName = Get_FilePath_Relative(ProjectDir, FileName)) )
+ {
+ pEntry->Add_Child("FILE", &FileName);
+ }
}
}
diff --git a/src/saga_core/saga_gui/res/saga_tip.txt b/src/saga_core/saga_gui/res/saga_tip.txt
index 6b47c56..debaf75 100644
--- a/src/saga_core/saga_gui/res/saga_tip.txt
+++ b/src/saga_core/saga_gui/res/saga_tip.txt
@@ -1,23 +1,20 @@
-that you can resize the Workspace, Messages and Object Properties windows by grabbing the border of the window?
-that you can move the Workspace, Messages and Object Properties windows by grabbing the title bar of the windows? Once you approach a docking position, it will be displayed in transparent red.
-that a lot of functionality becomes available when you do a right-click on an object in the Workspace window?
-that you can display a histogram of a grid data layer by a right-click on a data set in the Layers or Data Tab of the Workspace window?
+that you can resize the Manager, Messages and Properties windows by grabbing the border of the window?
+that you can move the Manager, Messages and Properties windows by grabbing the title bar of the windows? Once you approach a docking position, it will be displayed in transparent grey.
+that a lot of functionality becomes available when you do a right-click on an object in the Manager window?
+that you can display a histogram of a grid data layer by a right-click on a data set in the Data tab of the Manager window?
that you can use the mouse pointer in a histogram window to interactively adjust the value range the selected color ramp is applied to? Just click and drag to mark the desired range. A right-click returns to the full value range.
-that you can overlay multiple data sets in a Map View? To change the drawing order of the map layers do a right-click on a data set in the Maps Tab of the Workspace window.
+that you can overlay multiple data sets in a Map View? In order to change the drawing order of the map layers do a right-click on a data set selected in the Maps tab of the Manager window.
that you can create nice hillshaded maps by overlaying your data on top of an analytical hillshading grid and setting the transparency of your grid to an appealing amount?
-that there are two ways to execute a module? You can use the Modules menu to open up its dialog or you can access it via the Workspace Modules Tab. In case you do the latter, there will be more information about module operation available via the Description Tab of the Object Properties window.
-that interactive modules are executed as long as you execute them again, i.e. to exit an interactive module you simply have to execute it again?
-that profiles are not further implemented in the GUI but included as stand-alone modules?
-that once you executed a profile module you need to select the Arrow tool to draw a profile?
-that you can display a profile by adding the corresponding output shape to a map view? You can do this while the module is running.
-that there is a history file kept with each grid, documenting how this data set was derived? The History is displayed in the Description Tab of the Object Properties window as soon as you select the grid in the Workspace window.
+that there are two ways to execute a tool? You can use the Geoprocessing menu to open up its dialog or you can access it via the Manager Tools tab. In case you do the latter, there will be more information about tool operation available via the Description tab of the Properties window.
+that interactive tools are executed as long as you execute them again, i.e. to exit an interactive tool you simply have to execute it again?
+that once you executed an interactive tool you need to select the Arrow tool and use it in an Map View?
+that there is a history file kept with each data set, documenting how this data set was derived? The history is displayed in the Description tab of the Properties window as soon as you select the data set in the Manager window.
that there is also a Command Line Interpreter available? It can be used for automating your tasks via batch scripting.
-that you can access the SAGA API via Python?
-that you can use the Synchronize Map Extents tool to synchronize the map extents of all open map view windows?
-that you can use the Action tool to select a feature on the active shapes data layer and display its' attributes in the Attributes tab area of the Object Properties Window?
-that you can use the Shapes/Tools/Construction/Merge Shapes Layer module to merge two shapes data layers into a composite?
-that you can view actual grid cell data values on a grid data layer by zooming in to grid cell level granularity?
-that you can use the Table Calculator module to create a new attribute in a shapes data layer based on one or more existing attributes for the layer?
-that you can use the Terrain Analysis - Lighting, Visibility - Visibility (single point) [Interactive] module to create a seen area for a vantage point?
-that you can use the 3D - Sequencer tool to create a fly-through based on a DEM map view window that optionally includes other grid and shapes data layers?
-that you can see in the Message window what the current project is?
+that you can access the SAGA API via python?
+that you can use the Synchronize Map Extents button in the toolbar to synchronize the map extents of all open Map View windows?
+that you can use the Action tool to select a feature on the active shapes data layer and display its' attributes in the Attributes tab area of the Properties window?
+that you can use the Shapes - Tools - Merge Layers tool to merge two shapes data layers into a composite?
+that you can view actual grid cell data values on a grid data layer by checking the Show Cell Values parameter in the Settings tab of the data set and zooming in to grid cell level granularity?
+that you can use the Table - Shapes - Table Calculator (Shapes) tool to create a new attribute field in a shapes data layer based on one or more existing attributes for the layer?
+that you can use the Terrain Analysis - Lighting, Visibility - Visibility (single point) [Interactive] tool to create a seen area for a vantage point?
+that you can use the 3D View - Sequencer tool to create a fly-through based on a DEM Map View window that optionally includes other grid and shapes data layers?
diff --git a/src/saga_core/saga_gui/res_commands.cpp b/src/saga_core/saga_gui/res_commands.cpp
index b96382f..833997d 100644
--- a/src/saga_core/saga_gui/res_commands.cpp
+++ b/src/saga_core/saga_gui/res_commands.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: res_commands.cpp 2527 2015-06-30 15:38:35Z oconrad $
+ * Version $Id: res_commands.cpp 2650 2015-10-15 17:01:38Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -123,10 +123,12 @@ wxString CMD_Get_Name(int Cmd_ID)
case ID_CMD_DATASOURCE_REFRESH: return( _TL("Refresh") );
case ID_CMD_DB_REFRESH: return( _TL("Refresh") );
+ case ID_CMD_DB_SOURCE_CREATE: return( _TL("New") );
+ case ID_CMD_DB_SOURCE_DROP: return( _TL("Drop") );
case ID_CMD_DB_SOURCE_OPEN: return( _TL("Open") );
case ID_CMD_DB_SOURCE_CLOSE: return( _TL("Close") );
case ID_CMD_DB_SOURCE_CLOSE_ALL: return( _TL("Close All") );
- case ID_CMD_DB_SOURCE_DELETE: return( _TL("Delete") );
+ case ID_CMD_DB_SOURCE_DELETE: return( _TL("Remove") );
case ID_CMD_DB_TABLE_OPEN: return( _TL("Load") );
case ID_CMD_DB_TABLE_DELETE: return( _TL("Delete") );
case ID_CMD_DB_TABLE_RENAME: return( _TL("Rename") );
@@ -161,18 +163,9 @@ wxString CMD_Get_Name(int Cmd_ID)
case ID_CMD_TABLES_OPEN:
case ID_CMD_TIN_OPEN:
case ID_CMD_POINTCLOUD_OPEN: return( _TL("Load") );
-
- case ID_CMD_GRIDS_SAVE:
- case ID_CMD_SHAPES_SAVE:
- case ID_CMD_TABLES_SAVE:
- case ID_CMD_TIN_SAVE:
- case ID_CMD_POINTCLOUD_SAVE: return( _TL("Save") );
-
- case ID_CMD_GRIDS_SAVEAS:
- case ID_CMD_SHAPES_SAVEAS:
- case ID_CMD_TABLES_SAVEAS:
- case ID_CMD_TIN_SAVEAS:
- case ID_CMD_POINTCLOUD_SAVEAS: return( _TL("Save As...") );
+ case ID_CMD_DATA_SAVE: return( _TL("Save") );
+ case ID_CMD_DATA_SAVEAS: return( _TL("Save as...") );
+ case ID_CMD_DATA_SAVETODB: return( _TL("Save to Database...") );
case ID_CMD_GRIDS_SHOW:
case ID_CMD_SHAPES_SHOW:
diff --git a/src/saga_core/saga_gui/res_commands.h b/src/saga_core/saga_gui/res_commands.h
index 092bd30..4d5591e 100644
--- a/src/saga_core/saga_gui/res_commands.h
+++ b/src/saga_core/saga_gui/res_commands.h
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: res_commands.h 2501 2015-06-12 10:02:42Z oconrad $
+ * Version $Id: res_commands.h 2650 2015-10-15 17:01:38Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -129,6 +129,8 @@ enum ID_COMMANDS
ID_CMD_DATASOURCE_REFRESH,
ID_CMD_DB_REFRESH,
+ ID_CMD_DB_SOURCE_CREATE,
+ ID_CMD_DB_SOURCE_DROP,
ID_CMD_DB_SOURCE_OPEN,
ID_CMD_DB_SOURCE_CLOSE,
ID_CMD_DB_SOURCE_CLOSE_ALL,
@@ -168,14 +170,15 @@ enum ID_COMMANDS
ID_CMD_DATA_HISTORY_OPTIONS_COLLAPSE,
ID_CMD_DATA_HISTORY_OPTIONS_EXPAND,
ID_CMD_DATA_PROJECTION,
+ ID_CMD_DATA_SAVE,
+ ID_CMD_DATA_SAVEAS,
+ ID_CMD_DATA_SAVETODB,
ID_CMD_DATA_LAST,
ID_CMD_GRIDS_FIRST,
ID_CMD_GRIDS_RECENT_FIRST,
ID_CMD_GRIDS_RECENT_LAST = RECENT_COUNT + ID_CMD_GRIDS_RECENT_FIRST,
ID_CMD_GRIDS_OPEN,
- ID_CMD_GRIDS_SAVE,
- ID_CMD_GRIDS_SAVEAS,
ID_CMD_GRIDS_SAVEAS_IMAGE,
ID_CMD_GRIDS_SHOW,
ID_CMD_GRIDS_HISTOGRAM,
@@ -194,14 +197,13 @@ enum ID_COMMANDS
ID_CMD_SHAPES_RECENT_FIRST,
ID_CMD_SHAPES_RECENT_LAST = RECENT_COUNT + ID_CMD_SHAPES_RECENT_FIRST,
ID_CMD_SHAPES_OPEN,
- ID_CMD_SHAPES_SAVE,
- ID_CMD_SHAPES_SAVEAS,
ID_CMD_SHAPES_SHOW,
ID_CMD_SHAPES_HISTOGRAM,
ID_CMD_SHAPES_RANGE_MINMAX,
ID_CMD_SHAPES_RANGE_STDDEV150,
ID_CMD_SHAPES_RANGE_STDDEV200,
ID_CMD_SHAPES_SET_LUT,
+ ID_CMD_SHAPES_SAVE_ATTRIBUTES,
ID_CMD_SHAPES_EDIT_SHAPE,
ID_CMD_SHAPES_EDIT_SEL_CLEAR,
ID_CMD_SHAPES_EDIT_SEL_INVERT,
@@ -219,8 +221,6 @@ enum ID_COMMANDS
ID_CMD_TABLES_RECENT_FIRST,
ID_CMD_TABLES_RECENT_LAST = RECENT_COUNT + ID_CMD_TABLES_RECENT_FIRST,
ID_CMD_TABLES_OPEN,
- ID_CMD_TABLES_SAVE,
- ID_CMD_TABLES_SAVEAS,
ID_CMD_TABLES_SHOW,
ID_CMD_TABLES_DIAGRAM,
ID_CMD_TABLES_SCATTERPLOT,
@@ -230,8 +230,6 @@ enum ID_COMMANDS
ID_CMD_TIN_RECENT_FIRST,
ID_CMD_TIN_RECENT_LAST = RECENT_COUNT + ID_CMD_TIN_RECENT_FIRST,
ID_CMD_TIN_OPEN,
- ID_CMD_TIN_SAVE,
- ID_CMD_TIN_SAVEAS,
ID_CMD_TIN_SHOW,
ID_CMD_TIN_LAST,
@@ -239,8 +237,6 @@ enum ID_COMMANDS
ID_CMD_POINTCLOUD_RECENT_FIRST,
ID_CMD_POINTCLOUD_RECENT_LAST = RECENT_COUNT + ID_CMD_POINTCLOUD_RECENT_FIRST,
ID_CMD_POINTCLOUD_OPEN,
- ID_CMD_POINTCLOUD_SAVE,
- ID_CMD_POINTCLOUD_SAVEAS,
ID_CMD_POINTCLOUD_SHOW,
ID_CMD_POINTCLOUD_RANGE_MINMAX,
ID_CMD_POINTCLOUD_RANGE_STDDEV150,
diff --git a/src/saga_core/saga_gui/saga_frame.cpp b/src/saga_core/saga_gui/saga_frame.cpp
index 3106a6b..dcd7573 100644
--- a/src/saga_core/saga_gui/saga_frame.cpp
+++ b/src/saga_core/saga_gui/saga_frame.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: saga_frame.cpp 2590 2015-09-18 15:42:35Z oconrad $
+ * Version $Id: saga_frame.cpp 2640 2015-10-07 17:29:38Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -349,6 +349,9 @@ CSAGA_Frame::CSAGA_Frame(void)
#endif
Update();
+
+ //-----------------------------------------------------
+ m_pData_Source->Autoconnect_DB();
}
//---------------------------------------------------------
diff --git a/src/saga_core/saga_gui/wksp_data_item.cpp b/src/saga_core/saga_gui/wksp_data_item.cpp
index b2b7f16..4aa9044 100644
--- a/src/saga_core/saga_gui/wksp_data_item.cpp
+++ b/src/saga_core/saga_gui/wksp_data_item.cpp
@@ -84,6 +84,8 @@
#include "view_histogram.h"
#include "view_scatterplot.h"
+#include "data_source_pgsql.h"
+
///////////////////////////////////////////////////////////
// //
@@ -135,21 +137,24 @@ bool CWKSP_Data_Item::On_Command(int Cmd_ID)
default:
return( CWKSP_Base_Item::On_Command(Cmd_ID) );
- case ID_CMD_TABLES_SAVE:
- case ID_CMD_TIN_SAVE:
- case ID_CMD_POINTCLOUD_SAVE:
- case ID_CMD_SHAPES_SAVE:
- case ID_CMD_GRIDS_SAVE:
+ case ID_CMD_DATA_SAVE:
Save(m_pObject->Get_File_Name());
break;
- case ID_CMD_TABLES_SAVEAS:
- case ID_CMD_TIN_SAVEAS:
- case ID_CMD_POINTCLOUD_SAVEAS:
- case ID_CMD_SHAPES_SAVEAS:
- case ID_CMD_GRIDS_SAVEAS:
+ case ID_CMD_DATA_SAVEAS:
Save();
break;
+
+ case ID_CMD_DATA_SAVETODB:
+ switch( Get_Type() )
+ {
+ case WKSP_ITEM_Table : PGSQL_Save_Table ((CSG_Table *)m_pObject); break;
+ case WKSP_ITEM_Shapes: PGSQL_Save_Shapes((CSG_Shapes *)m_pObject); break;
+ case WKSP_ITEM_Grid : PGSQL_Save_Grid ((CSG_Grid *)m_pObject); break;
+
+ default: break;
+ }
+ break;
}
return( true );
@@ -163,13 +168,13 @@ bool CWKSP_Data_Item::On_Command_UI(wxUpdateUIEvent &event)
default:
return( CWKSP_Base_Item::On_Command_UI(event) );
- case ID_CMD_TABLES_SAVE:
- case ID_CMD_TIN_SAVE:
- case ID_CMD_POINTCLOUD_SAVE:
- case ID_CMD_SHAPES_SAVE:
- case ID_CMD_GRIDS_SAVE:
+ case ID_CMD_DATA_SAVE:
event.Enable(m_pObject->is_Modified() && m_pObject->Get_File_Name() && *(m_pObject->Get_File_Name()));
break;
+
+ case ID_CMD_DATA_SAVETODB:
+ event.Enable(PGSQL_has_Connections());
+ break;
}
return( true );
@@ -239,30 +244,29 @@ void CWKSP_Data_Item::On_Create_Parameters(void)
//---------------------------------------------------------
bool CWKSP_Data_Item::Save(void)
{
- bool bResult;
-
- wxString FileName = m_pObject->Get_File_Name() && *m_pObject->Get_File_Name()
- ? m_pObject->Get_File_Name()
- : m_pObject->Get_Name();
+ int idDlg;
switch( Get_Type() )
{
- default: bResult = false; break;
- case WKSP_ITEM_Table: bResult = DLG_Save(FileName, ID_DLG_TABLES_SAVE ); break;
- case WKSP_ITEM_TIN:
- case WKSP_ITEM_Shapes: bResult = DLG_Save(FileName, ID_DLG_SHAPES_SAVE ); break;
- case WKSP_ITEM_PointCloud: bResult = DLG_Save(FileName, ID_DLG_POINTCLOUD_SAVE); break;
- case WKSP_ITEM_Grid: bResult = DLG_Save(FileName, ID_DLG_GRIDS_SAVE ); break;
+ case WKSP_ITEM_Table : idDlg = ID_DLG_TABLES_SAVE ; break;
+ case WKSP_ITEM_TIN :
+ case WKSP_ITEM_Shapes : idDlg = ID_DLG_SHAPES_SAVE ; break;
+ case WKSP_ITEM_PointCloud: idDlg = ID_DLG_POINTCLOUD_SAVE; break;
+ case WKSP_ITEM_Grid : idDlg = ID_DLG_GRIDS_SAVE ; break;
+
+ default: return( false );
}
- if( bResult )
- {
- bResult = m_pObject->Save(&FileName);
+ wxString FileName = m_pObject->Get_File_Name() && *m_pObject->Get_File_Name()
+ ? m_pObject->Get_File_Name()
+ : m_pObject->Get_Name();
- PROCESS_Set_Okay();
+ if( DLG_Save(FileName, idDlg) && m_pObject->Save(&FileName) )
+ {
+ return( true );
}
- return( bResult );
+ return( false );
}
//---------------------------------------------------------
diff --git a/src/saga_core/saga_gui/wksp_data_manager.cpp b/src/saga_core/saga_gui/wksp_data_manager.cpp
index 443aff8..94878a6 100644
--- a/src/saga_core/saga_gui/wksp_data_manager.cpp
+++ b/src/saga_core/saga_gui/wksp_data_manager.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: wksp_data_manager.cpp 2590 2015-09-18 15:42:35Z oconrad $
+ * Version $Id: wksp_data_manager.cpp 2633 2015-10-02 16:24:33Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -158,6 +158,15 @@ CWKSP_Data_Manager::CWKSP_Data_Manager(void)
pNode_1->Set_Enabled(false);
#endif
+ pNode_1 = m_Parameters.Add_Choice(
+ pNode , "PROJECT_DB_REOPEN" , _TL("Reopen Database Connections"),
+ _TL("Reopen PostgreSQL database connections. Warning: if set to true account information including unencrypted paswords for automatic connection will be stored."),
+ CSG_String::Format("%s|%s|",
+ _TL("no"),
+ _TL("yes")
+ ), 0
+ );
+
m_Parameters.Add_Value(
pNode , "NUMBERING" , _TL("Numbering of Data Sets"),
_TL("Leading zeros for data set numbering. Set to -1 for not using numbers at all."),
diff --git a/src/saga_core/saga_gui/wksp_grid.cpp b/src/saga_core/saga_gui/wksp_grid.cpp
index b727966..6cfc340 100644
--- a/src/saga_core/saga_gui/wksp_grid.cpp
+++ b/src/saga_core/saga_gui/wksp_grid.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: wksp_grid.cpp 2590 2015-09-18 15:42:35Z oconrad $
+ * Version $Id: wksp_grid.cpp 2650 2015-10-15 17:01:38Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -84,6 +84,8 @@
#include "wksp_grid_manager.h"
#include "wksp_grid.h"
+#include "data_source_pgsql.h"
+
///////////////////////////////////////////////////////////
// //
@@ -119,34 +121,54 @@ wxString CWKSP_Grid::Get_Description(void)
s += wxT("<table border=\"0\">");
- DESC_ADD_STR (_TL("Name") , m_pObject->Get_Name());
- DESC_ADD_STR (_TL("Description") , m_pObject->Get_Description());
- DESC_ADD_STR (_TL("File") , SG_File_Exists(m_pObject->Get_File_Name(false)) ? m_pObject->Get_File_Name(false) : _TL("memory"));
- if( m_pObject->Get_MetaData()("GDAL_DRIVER") )
+ DESC_ADD_STR (_TL("Name" ), m_pObject->Get_Name());
+ DESC_ADD_STR (_TL("Description" ), m_pObject->Get_Description());
+
+ if( SG_File_Exists(m_pObject->Get_File_Name(false)) )
+ {
+ DESC_ADD_STR (_TL("File" ), m_pObject->Get_File_Name(false));
+
+ if( m_pObject->Get_MetaData()("GDAL_DRIVER") )
+ DESC_ADD_STR (_TL("Driver" ), m_pObject->Get_MetaData()["GDAL_DRIVER"].Get_Content().c_str());
+
+ if( m_pObject->Get_MetaData()("SURFER_GRID") )
+ DESC_ADD_STR (_TL("Driver" ), m_pObject->Get_MetaData()["SURFER_GRID"].Get_Content().c_str());
+ }
+ else if( m_pObject->Get_MetaData_DB().Get_Children_Count() )
{
- DESC_ADD_STR (_TL("Driver") , m_pObject->Get_MetaData()["GDAL_DRIVER"].Get_Content().c_str());
+ DESC_ADD_STR(_TL("File" ), m_pObject->Get_File_Name(false));
+ //const CSG_MetaData &DB = m_pObject->Get_MetaData_DB();
+ //if( DB("DBMS") ) DESC_ADD_STR (_TL("DBMS" ), DB["DBMS"].Get_Content().c_str());
+ //if( DB("HOST") ) DESC_ADD_STR (_TL("Host" ), DB["DBMS"].Get_Content().c_str());
+ //if( DB("PORT") ) DESC_ADD_STR (_TL("Port" ), DB["DBMS"].Get_Content().c_str());
+ //if( DB("NAME") ) DESC_ADD_STR (_TL("Database"), DB["NAME"].Get_Content().c_str());
+ }
+ else
+ {
+ DESC_ADD_STR (_TL("File" ), _TL("memory"));
}
- DESC_ADD_STR (_TL("Modified") , m_pObject->is_Modified() ? _TL("yes") : _TL("no"));
- DESC_ADD_STR (_TL("Projection") , m_pObject->Get_Projection().Get_Description().c_str());
- DESC_ADD_FLT (_TL("West") , Get_Grid()->Get_XMin());
- DESC_ADD_FLT (_TL("East") , Get_Grid()->Get_XMax());
- DESC_ADD_FLT (_TL("West-East") , Get_Grid()->Get_XRange());
- DESC_ADD_FLT (_TL("South") , Get_Grid()->Get_YMin());
- DESC_ADD_FLT (_TL("North") , Get_Grid()->Get_YMax());
- DESC_ADD_FLT (_TL("South-North") , Get_Grid()->Get_YRange());
- DESC_ADD_FLT (_TL("Cell Size") , Get_Grid()->Get_Cellsize());
- DESC_ADD_INT (_TL("Number of Columns") , Get_Grid()->Get_NX());
- DESC_ADD_INT (_TL("Number of Rows") , Get_Grid()->Get_NY());
- DESC_ADD_LONG(_TL("Number of Cells") , Get_Grid()->Get_NCells());
- DESC_ADD_LONG(_TL("No Data Cells") , Get_Grid()->Get_NoData_Count());
- DESC_ADD_STR (_TL("Value Type") , SG_Data_Type_Get_Name(Get_Grid()->Get_Type()).c_str());
- DESC_ADD_FLT (_TL("Value Minimum") , Get_Grid()->Get_ZMin());
- DESC_ADD_FLT (_TL("Value Maximum") , Get_Grid()->Get_ZMax());
- DESC_ADD_FLT (_TL("Value Range") , Get_Grid()->Get_ZRange());
- DESC_ADD_STR (_TL("No Data Value") , Get_Grid()->Get_NoData_Value() < Get_Grid()->Get_NoData_hiValue() ? CSG_String::Format(SG_T("%f - %f"), Get_Grid()->Get_NoData_Value(), Get_Grid()->Get_NoData_hiValue()).c_str() : SG_Get_String(Get_Grid()->Get_NoData_Value(), -2).c_str());
- DESC_ADD_FLT (_TL("Arithmetic Mean") , Get_Grid()->Get_Mean());
- DESC_ADD_FLT (_TL("Standard Deviation") , Get_Grid()->Get_StdDev());
- DESC_ADD_STR (_TL("Memory Size") , Get_nBytes_asString(Get_Grid()->Get_Memory_Size(), 2).c_str());
+
+ DESC_ADD_STR (_TL("Modified" ), m_pObject->is_Modified() ? _TL("yes") : _TL("no"));
+ DESC_ADD_STR (_TL("Projection" ), m_pObject->Get_Projection().Get_Description().c_str());
+ DESC_ADD_FLT (_TL("West" ), Get_Grid()->Get_XMin ());
+ DESC_ADD_FLT (_TL("East" ), Get_Grid()->Get_XMax ());
+ DESC_ADD_FLT (_TL("West-East" ), Get_Grid()->Get_XRange ());
+ DESC_ADD_FLT (_TL("South" ), Get_Grid()->Get_YMin ());
+ DESC_ADD_FLT (_TL("North" ), Get_Grid()->Get_YMax ());
+ DESC_ADD_FLT (_TL("South-North" ), Get_Grid()->Get_YRange ());
+ DESC_ADD_FLT (_TL("Cell Size" ), Get_Grid()->Get_Cellsize ());
+ DESC_ADD_INT (_TL("Number of Columns" ), Get_Grid()->Get_NX ());
+ DESC_ADD_INT (_TL("Number of Rows" ), Get_Grid()->Get_NY ());
+ DESC_ADD_LONG(_TL("Number of Cells" ), Get_Grid()->Get_NCells ());
+ DESC_ADD_LONG(_TL("No Data Cells" ), Get_Grid()->Get_NoData_Count());
+ DESC_ADD_STR (_TL("Value Type" ), SG_Data_Type_Get_Name(Get_Grid()->Get_Type()).c_str());
+ DESC_ADD_FLT (_TL("Value Minimum" ), Get_Grid()->Get_ZMin ());
+ DESC_ADD_FLT (_TL("Value Maximum" ), Get_Grid()->Get_ZMax ());
+ DESC_ADD_FLT (_TL("Value Range" ), Get_Grid()->Get_ZRange ());
+ DESC_ADD_STR (_TL("No Data Value" ), Get_Grid()->Get_NoData_Value() < Get_Grid()->Get_NoData_hiValue() ? CSG_String::Format(SG_T("%f - %f"), Get_Grid()->Get_NoData_Value(), Get_Grid()->Get_NoData_hiValue()).c_str() : SG_Get_String(Get_Grid()->Get_NoData_Value(), -2).c_str());
+ DESC_ADD_FLT (_TL("Arithmetic Mean" ), Get_Grid()->Get_Mean ());
+ DESC_ADD_FLT (_TL("Standard Deviation"), Get_Grid()->Get_StdDev ());
+ DESC_ADD_STR (_TL("Memory Size" ), Get_nBytes_asString(Get_Grid()->Get_Memory_Size(), 2).c_str());
if( Get_Grid()->is_Compressed() )
{
@@ -176,8 +198,12 @@ wxMenu * CWKSP_Grid::Get_Menu(void)
CMD_Menu_Add_Item(pMenu, false, ID_CMD_WKSP_ITEM_CLOSE);
CMD_Menu_Add_Item(pMenu, false, ID_CMD_GRIDS_SHOW);
pMenu->AppendSeparator();
- CMD_Menu_Add_Item(pMenu, false, ID_CMD_GRIDS_SAVE);
- CMD_Menu_Add_Item(pMenu, false, ID_CMD_GRIDS_SAVEAS);
+ CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_SAVE);
+ CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_SAVEAS);
+ if( PGSQL_has_Connections() )
+ {
+ CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_SAVETODB);
+ }
CMD_Menu_Add_Item(pMenu, false, ID_CMD_GRIDS_SAVEAS_IMAGE);
pMenu->AppendSeparator();
CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECTION);
diff --git a/src/saga_core/saga_gui/wksp_pointcloud.cpp b/src/saga_core/saga_gui/wksp_pointcloud.cpp
index 932637f..cf6e547 100644
--- a/src/saga_core/saga_gui/wksp_pointcloud.cpp
+++ b/src/saga_core/saga_gui/wksp_pointcloud.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: wksp_pointcloud.cpp 2548 2015-08-13 13:07:55Z oconrad $
+ * Version $Id: wksp_pointcloud.cpp 2650 2015-10-15 17:01:38Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -163,8 +163,8 @@ wxMenu * CWKSP_PointCloud::Get_Menu(void)
CMD_Menu_Add_Item(pMenu, false, ID_CMD_WKSP_ITEM_CLOSE);
CMD_Menu_Add_Item(pMenu, false, ID_CMD_POINTCLOUD_SHOW);
pMenu->AppendSeparator();
- CMD_Menu_Add_Item(pMenu, false, ID_CMD_POINTCLOUD_SAVE);
- CMD_Menu_Add_Item(pMenu, false, ID_CMD_POINTCLOUD_SAVEAS);
+ CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_SAVE);
+ CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_SAVEAS);
pMenu->AppendSeparator();
CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECTION);
pMenu->AppendSeparator();
diff --git a/src/saga_core/saga_gui/wksp_shapes.cpp b/src/saga_core/saga_gui/wksp_shapes.cpp
index c7e6b9a..9d973be 100644
--- a/src/saga_core/saga_gui/wksp_shapes.cpp
+++ b/src/saga_core/saga_gui/wksp_shapes.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: wksp_shapes.cpp 2548 2015-08-13 13:07:55Z oconrad $
+ * Version $Id: wksp_shapes.cpp 2650 2015-10-15 17:01:38Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -72,6 +72,8 @@
#include "wksp_shapes.h"
#include "wksp_table.h"
+#include "data_source_pgsql.h"
+
///////////////////////////////////////////////////////////
// //
@@ -122,20 +124,36 @@ wxString CWKSP_Shapes::Get_Description(void)
s += wxT("<table border=\"0\">");
- DESC_ADD_STR(_TL("Name") , m_pObject->Get_Name());
- DESC_ADD_STR(_TL("Description") , m_pObject->Get_Description());
- DESC_ADD_STR(_TL("File") , SG_File_Exists(m_pObject->Get_File_Name()) ? m_pObject->Get_File_Name() : _TL("memory"));
- DESC_ADD_STR(_TL("Modified") , m_pObject->is_Modified() ? _TL("yes") : _TL("no"));
- DESC_ADD_STR(_TL("Projection") , m_pObject->Get_Projection().Get_Description().c_str());
- DESC_ADD_FLT(_TL("West") , Get_Shapes()->Get_Extent().Get_XMin());
- DESC_ADD_FLT(_TL("East") , Get_Shapes()->Get_Extent().Get_XMax());
- DESC_ADD_FLT(_TL("West-East") , Get_Shapes()->Get_Extent().Get_XRange());
- DESC_ADD_FLT(_TL("South") , Get_Shapes()->Get_Extent().Get_YMin());
- DESC_ADD_FLT(_TL("North") , Get_Shapes()->Get_Extent().Get_YMax());
- DESC_ADD_FLT(_TL("South-North") , Get_Shapes()->Get_Extent().Get_YRange());
- DESC_ADD_STR(_TL("Type") , SG_Get_ShapeType_Name(Get_Shapes()->Get_Type()).c_str());
- DESC_ADD_STR(_TL("Vertex Type") , Get_Shapes()->Get_Vertex_Type() == 0 ? _TL("X, Y") : Get_Shapes()->Get_Vertex_Type() == 1 ? _TL("X, Y, Z") : _TL("X, Y, Z, M"));
- DESC_ADD_INT(_TL("Number Of Shapes"), Get_Shapes()->Get_Count());
+ DESC_ADD_STR(_TL("Name" ), m_pObject->Get_Name());
+ DESC_ADD_STR(_TL("Description" ), m_pObject->Get_Description());
+
+ if( SG_File_Exists(m_pObject->Get_File_Name(false)) )
+ {
+ DESC_ADD_STR(_TL("File" ), m_pObject->Get_File_Name(false));
+
+ if( m_pObject->Get_MetaData()("GDAL_DRIVER") )
+ DESC_ADD_STR(_TL("Driver" ), m_pObject->Get_MetaData()["GDAL_DRIVER"].Get_Content().c_str());
+ }
+ else if( m_pObject->Get_MetaData_DB().Get_Children_Count() )
+ {
+ DESC_ADD_STR(_TL("File" ), m_pObject->Get_File_Name(false));
+ }
+ else
+ {
+ DESC_ADD_STR(_TL("File" ), _TL("memory"));
+ }
+
+ DESC_ADD_STR(_TL("Modified" ), m_pObject->is_Modified() ? _TL("yes") : _TL("no"));
+ DESC_ADD_STR(_TL("Projection" ), m_pObject->Get_Projection().Get_Description().c_str());
+ DESC_ADD_FLT(_TL("West" ), Get_Shapes()->Get_Extent().Get_XMin ());
+ DESC_ADD_FLT(_TL("East" ), Get_Shapes()->Get_Extent().Get_XMax ());
+ DESC_ADD_FLT(_TL("West-East" ), Get_Shapes()->Get_Extent().Get_XRange());
+ DESC_ADD_FLT(_TL("South" ), Get_Shapes()->Get_Extent().Get_YMin ());
+ DESC_ADD_FLT(_TL("North" ), Get_Shapes()->Get_Extent().Get_YMax ());
+ DESC_ADD_FLT(_TL("South-North" ), Get_Shapes()->Get_Extent().Get_YRange());
+ DESC_ADD_STR(_TL("Type" ), SG_Get_ShapeType_Name(Get_Shapes()->Get_Type()).c_str());
+ DESC_ADD_STR(_TL("Vertex Type" ), Get_Shapes()->Get_Vertex_Type() == 0 ? _TL("X, Y") : Get_Shapes()->Get_Vertex_Type() == 1 ? _TL("X, Y, Z") : _TL("X, Y, Z, M"));
+ DESC_ADD_INT(_TL("Number of Shapes"), Get_Shapes()->Get_Count());
s += wxT("</table>");
@@ -157,8 +175,12 @@ wxMenu * CWKSP_Shapes::Get_Menu(void)
CMD_Menu_Add_Item(pMenu, false, ID_CMD_WKSP_ITEM_CLOSE);
CMD_Menu_Add_Item(pMenu, false, ID_CMD_SHAPES_SHOW);
pMenu->AppendSeparator();
- CMD_Menu_Add_Item(pMenu, false, ID_CMD_SHAPES_SAVE);
- CMD_Menu_Add_Item(pMenu, false, ID_CMD_SHAPES_SAVEAS);
+ CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_SAVE);
+ CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_SAVEAS);
+ if( PGSQL_has_Connections() )
+ {
+ CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_SAVETODB);
+ }
pMenu->AppendSeparator();
CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_PROJECTION);
pMenu->AppendSeparator();
@@ -172,7 +194,7 @@ wxMenu * CWKSP_Shapes::Get_Menu(void)
CMD_Menu_Add_Item(pTable, true, ID_CMD_TABLES_SHOW);
CMD_Menu_Add_Item(pTable, true, ID_CMD_TABLES_DIAGRAM);
CMD_Menu_Add_Item(pTable, false, ID_CMD_TABLES_SCATTERPLOT);
- CMD_Menu_Add_Item(pTable, false, ID_CMD_TABLES_SAVEAS);
+ CMD_Menu_Add_Item(pTable, false, ID_CMD_SHAPES_SAVE_ATTRIBUTES);
pMenu->Append(ID_CMD_WKSP_FIRST, _TL("Attributes"), pTable);
pMenu->Append(ID_CMD_WKSP_FIRST, _TL("Edit"), Edit_Get_Menu());
@@ -228,7 +250,7 @@ bool CWKSP_Shapes::On_Command(int Cmd_ID)
Add_ScatterPlot();
break;
- case ID_CMD_TABLES_SAVEAS:
+ case ID_CMD_SHAPES_SAVE_ATTRIBUTES:
{
wxString File(m_pObject->Get_File_Name());
diff --git a/src/saga_core/saga_gui/wksp_table.cpp b/src/saga_core/saga_gui/wksp_table.cpp
index 23da969..b476133 100644
--- a/src/saga_core/saga_gui/wksp_table.cpp
+++ b/src/saga_core/saga_gui/wksp_table.cpp
@@ -1,5 +1,5 @@
/**********************************************************
- * Version $Id: wksp_table.cpp 2061 2014-03-20 11:48:01Z oconrad $
+ * Version $Id: wksp_table.cpp 2650 2015-10-15 17:01:38Z oconrad $
*********************************************************/
///////////////////////////////////////////////////////////
@@ -73,6 +73,8 @@
#include "view_table.h"
#include "view_table_diagram.h"
+#include "data_source_pgsql.h"
+
///////////////////////////////////////////////////////////
// //
@@ -119,12 +121,24 @@ wxString CWKSP_Table::Get_Description(void)
s += wxT("<table border=\"0\">");
- DESC_ADD_STR(_TL("Name") , m_pObject->Get_Name());
- DESC_ADD_STR(_TL("Description") , m_pObject->Get_Description());
- DESC_ADD_STR(_TL("File") , SG_File_Exists(m_pObject->Get_File_Name()) ? m_pObject->Get_File_Name() : _TL("memory"));
- DESC_ADD_STR(_TL("Modified") , m_pObject->is_Modified() ? _TL("yes") : _TL("no"));
- DESC_ADD_INT(_TL("Attributes") , Get_Table()->Get_Field_Count());
- DESC_ADD_INT(_TL("Records") , Get_Table()->Get_Record_Count());
+ DESC_ADD_STR(_TL("Name" ), m_pObject->Get_Name());
+ DESC_ADD_STR(_TL("Description" ), m_pObject->Get_Description());
+
+ if( SG_File_Exists(m_pObject->Get_File_Name(false)) )
+ {
+ DESC_ADD_STR(_TL("File" ), m_pObject->Get_File_Name(false));
+ }
+ else if( m_pObject->Get_MetaData_DB().Get_Children_Count() )
+ {
+ DESC_ADD_STR(_TL("File" ), m_pObject->Get_File_Name(false));
+ }
+ else
+ {
+ DESC_ADD_STR(_TL("File" ), _TL("memory"));
+ }
+
+ DESC_ADD_STR(_TL("Modified" ), m_pObject->is_Modified() ? _TL("yes") : _TL("no"));
+ DESC_ADD_INT(_TL("Number of Records"), Get_Table()->Get_Count());
s += wxT("</table>");
@@ -149,8 +163,12 @@ wxMenu * CWKSP_Table::Get_Menu(void)
if( m_pObject->Get_ObjectType() == DATAOBJECT_TYPE_Table )
{
CMD_Menu_Add_Item(pMenu, false, ID_CMD_WKSP_ITEM_CLOSE);
- CMD_Menu_Add_Item(pMenu, false, ID_CMD_TABLES_SAVE);
- CMD_Menu_Add_Item(pMenu, false, ID_CMD_TABLES_SAVEAS);
+ CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_SAVE);
+ CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_SAVEAS);
+ if( PGSQL_has_Connections() )
+ {
+ CMD_Menu_Add_Item(pMenu, false, ID_CMD_DATA_SAVETODB);
+ }
}
CMD_Menu_Add_Item(pMenu, true, ID_CMD_TABLES_SHOW);
diff --git a/src/scripting/python/examples/00_grid_create_dummy.py b/src/scripting/python/examples/00_grid_create_dummy.py
new file mode 100644
index 0000000..01bf57c
--- /dev/null
+++ b/src/scripting/python/examples/00_grid_create_dummy.py
@@ -0,0 +1,70 @@
+#! /usr/bin/env python
+
+import saga_api, sys, os
+
+##########################################
+def grid_create_dummy(fASC):
+
+ ### load all module libraries from a directory at once:
+ if os.name == 'nt': # Windows
+ os.environ['PATH'] = os.environ['PATH'] + ';' + os.environ['SAGA_32'] + '/dll'
+ saga_api.SG_Get_Module_Library_Manager().Add_Directory(os.environ['SAGA_32' ] + '/modules', 0)
+ else: # Linux
+ saga_api.SG_Get_Module_Library_Manager().Add_Directory(os.environ['SAGA_MLB'], 0)
+
+ print '__________________'
+ print 'number of loaded libraries: ' + str(saga_api.SG_Get_Module_Library_Manager().Get_Count())
+ #print saga_api.SG_Get_Module_Library_Manager().Get_Summary(saga_api.SG_SUMMARY_FMT_FLAT_NO_INTERACTIVE).c_str()
+ print '__________________'
+
+ ### create a dummy DEM:
+ m = saga_api.SG_Get_Module_Library_Manager().Get_Module(saga_api.CSG_String('grid_calculus'), 6)
+ print m.Get_Name().c_str()
+
+ p = m.Get_Parameters()
+ p(saga_api.CSG_String('RADIUS' )).Set_Value( 25)
+ p(saga_api.CSG_String('ITERATIONS')).Set_Value(250)
+
+ p = m.Get_Parameters(saga_api.CSG_String('TARGET'))
+ p(saga_api.CSG_String('USER_SIZE')).Set_Value( 10)
+ p(saga_api.CSG_String('USER_XMAX')).Set_Value(2000)
+ p(saga_api.CSG_String('USER_YMAX')).Set_Value(2000)
+
+ if m.Execute() == 0:
+ print 'ERROR: executing module [' + m.Get_Name().c_str() + ']'
+ return 0
+
+ dem = p(saga_api.CSG_String('OUT_GRID')).asGrid()
+
+ ### save dummy to esri ascii grid file:
+ m = saga_api.SG_Get_Module_Library_Manager().Get_Module(saga_api.CSG_String('io_grid'), 0)
+ print m.Get_Name().c_str()
+
+ p = m.Get_Parameters()
+ p(saga_api.CSG_String('GRID')).Set_Value(dem)
+ p(saga_api.CSG_String('FILE')).Set_Value(saga_api.CSG_String(fASC))
+ p(saga_api.CSG_String('PREC')).Set_Value(2)
+
+ if m.Execute() == 0:
+ print 'ERROR: executing module [' + m.Get_Name().c_str() + ']'
+ return 0
+
+ print 'success'
+ return 1
+
+##########################################
+if __name__ == '__main__':
+ print 'Python - Version ' + sys.version
+ print saga_api.SAGA_API_Get_Version()
+ print
+
+ if len(sys.argv) != 2:
+ print 'Usage: 00_grid_create_dummy.py <out: ascii grid file>'
+ print '... try to save as <test.asc> in current working directory'
+ fASC = './test.asc'
+ else:
+ fASC = sys.argv[1]
+ if os.path.split(fASC)[0] == '':
+ fASC = './' + fASC
+
+ grid_create_dummy(fASC)
diff --git a/src/scripting/python/examples/01_grid_asc_to_saga.py b/src/scripting/python/examples/01_grid_asc_to_saga.py
new file mode 100644
index 0000000..1d9f7e0
--- /dev/null
+++ b/src/scripting/python/examples/01_grid_asc_to_saga.py
@@ -0,0 +1,57 @@
+#! /usr/bin/env python
+
+import saga_api, sys, os
+
+##########################################
+def grid_asc2sgrd(fASC):
+
+### load all module libraries from a directory at once:
+# if os.name == 'nt': # Windows
+# saga_api.SG_Get_Module_Library_Manager().Add_Directory(os.environ['SAGA_32' ], 0)
+# else: # Linux
+# saga_api.SG_Get_Module_Library_Manager().Add_Directory(os.environ['SAGA_MLB'], 0)
+# print '__________________'
+# print 'number of loaded libraries: ' + str(saga_api.SG_Get_Module_Library_Manager().Get_Count())
+# print saga_api.SG_Get_Module_Library_Manager().Get_Summary(saga_api.SG_SUMMARY_FMT_FLAT_NO_INTERACTIVE).c_str()
+# print '__________________'
+
+### load just the needed module library:
+ if os.name == 'nt': # Windows
+ saga_api.SG_Get_Module_Library_Manager().Add_Library(os.environ['SAGA_32' ] + '/modules/io_grid.dll')
+ else: # Linux
+ saga_api.SG_Get_Module_Library_Manager().Add_Library(os.environ['SAGA_MLB'] + '/libio_grid.so')
+
+ sASC = saga_api.CSG_String(fASC)
+ m = saga_api.SG_Get_Module_Library_Manager().Get_Module(saga_api.CSG_String('io_grid'), 1)
+ print m.Get_Description().c_str()
+
+ p = m.Get_Parameters()
+ p(saga_api.CSG_String('FILE')).Set_Value(sASC)
+
+ if m.Execute() == 0:
+ print 'ERROR: executing module [' + m.Get_Name().c_str() + ']'
+ return 0
+
+ if p(saga_api.CSG_String('GRID')).asGrid().Save(sASC) == 0:
+ print 'ERROR: saving grid [' + sASC + ']'
+ return 0
+
+ print 'success'
+ return 1
+
+##########################################
+if __name__ == '__main__':
+ print 'Python - Version ' + sys.version
+ print saga_api.SAGA_API_Get_Version()
+ print
+
+ if len(sys.argv) != 2:
+ print 'Usage: grid_asc_to_saga.py <in: ascii grid file>'
+ print '... trying to run with test_data'
+ fASC = './test.asc'
+ else:
+ fASC = sys.argv[1]
+ if os.path.split(fASC)[0] == '':
+ fASC = './' + fASC
+
+ grid_asc2sgrd(fASC)
diff --git a/src/scripting/python/examples/02_grid_morphometry.py b/src/scripting/python/examples/02_grid_morphometry.py
new file mode 100644
index 0000000..7b6de48
--- /dev/null
+++ b/src/scripting/python/examples/02_grid_morphometry.py
@@ -0,0 +1,90 @@
+#! /usr/bin/env python
+
+import saga_api, sys, os
+
+##########################################
+def morphometry(fDEM):
+ # ------------------------------------
+ # initializations
+
+ dem = saga_api.SG_Get_Data_Manager().Add_Grid(unicode(fDEM))
+ if dem == None or dem.is_Valid() == 0:
+ print 'ERROR: loading grid [' + fDEM + ']'
+ return 0
+
+ path = os.path.split(fDEM)[0]
+ if path == '':
+ path = './'
+
+ slope = saga_api.SG_Get_Data_Manager().Add_Grid(dem.Get_System())
+ aspect = saga_api.SG_Get_Data_Manager().Add_Grid(dem.Get_System())
+ hcurv = saga_api.SG_Get_Data_Manager().Add_Grid(dem.Get_System())
+ vcurv = saga_api.SG_Get_Data_Manager().Add_Grid(dem.Get_System())
+ ccurv = saga_api.SG_Get_Data_Manager().Add_Grid(dem.Get_System())
+
+ # ------------------------------------
+ # 'Slope, Aspect, Curvature'
+
+ m = saga_api.SG_Get_Module_Library_Manager().Get_Module(saga_api.CSG_String('ta_morphometry'), 0)
+ p = m.Get_Parameters()
+ p.Get_Grid_System().Assign(dem.Get_System()) # grid module needs to use conformant grid system!
+ p(saga_api.CSG_String('ELEVATION')).Set_Value(dem)
+ p(saga_api.CSG_String('SLOPE' )).Set_Value(slope)
+ p(saga_api.CSG_String('ASPECT' )).Set_Value(aspect)
+ p(saga_api.CSG_String('C_CROS' )).Set_Value(hcurv)
+ p(saga_api.CSG_String('C_LONG' )).Set_Value(vcurv)
+
+ if m.Execute() == 0:
+ print 'ERROR: executing module [' + m.Get_Name().c_str() + ']'
+ return 0
+
+ slope .Save(saga_api.CSG_String(path + '/slope' ))
+ aspect.Save(saga_api.CSG_String(path + '/aspect'))
+ hcurv .Save(saga_api.CSG_String(path + '/hcurv' ))
+ vcurv .Save(saga_api.CSG_String(path + '/vcurv' ))
+
+ # ------------------------------------
+ # 'Curvature Classification'
+
+ m = saga_api.SG_Get_Module_Library_Manager().Get_Module(saga_api.CSG_String('ta_morphometry'), 4)
+ p = m.Get_Parameters()
+ p.Get_Grid_System().Assign(dem.Get_System()) # grid module needs to use conformant grid system!
+ p(saga_api.CSG_String('DEM' )).Set_Value(dem)
+ p(saga_api.CSG_String('CLASS' )).Set_Value(ccurv)
+
+ if m.Execute() == 0:
+ print 'ERROR: executing module [' + m.Get_Name().c_str() + ']'
+ return 0
+
+ ccurv .Save(saga_api.CSG_String(path + '/ccurv' ))
+
+ # ------------------------------------
+ print 'success'
+
+ return 1
+
+
+##########################################
+if __name__ == '__main__':
+ print 'Python - Version ' + sys.version
+ print saga_api.SAGA_API_Get_Version()
+ print
+
+ if len( sys.argv ) != 2:
+ print 'Usage: morphometry.py <in: elevation>'
+ print '... trying to run with test_data'
+ fDEM = './test.sgrd'
+ else:
+ fDEM = sys.argv[1]
+ if os.path.split(fDEM)[0] == '':
+ fDEM = './' + fDEM
+
+ saga_api.SG_UI_Msg_Lock(1)
+ if os.name == 'nt': # Windows
+ os.environ['PATH'] = os.environ['PATH'] + ';' + os.environ['SAGA_32'] + '/dll'
+ saga_api.SG_Get_Module_Library_Manager().Add_Directory(os.environ['SAGA_32' ] + '/modules', 0)
+ else: # Linux
+ saga_api.SG_Get_Module_Library_Manager().Add_Directory(os.environ['SAGA_MLB'], 0)
+ saga_api.SG_UI_Msg_Lock(0)
+
+ morphometry(fDEM)
diff --git a/src/scripting/python/examples/03_grid_difference.py b/src/scripting/python/examples/03_grid_difference.py
new file mode 100644
index 0000000..fb9b6a0
--- /dev/null
+++ b/src/scripting/python/examples/03_grid_difference.py
@@ -0,0 +1,66 @@
+#! /usr/bin/env python
+
+import saga_api, sys, os
+
+##########################################
+def grid_difference(fA, fB, fC, bPixelWise):
+ A = saga_api.SG_Create_Grid()
+ if A.Create(saga_api.CSG_String(fA)) == 0:
+ print 'ERROR: loading grid [' + fA + ']'
+ return 0
+
+ B = saga_api.SG_Create_Grid()
+ if B.Create(saga_api.CSG_String(fB)) == 0:
+ print 'ERROR: loading grid [' + fB + ']'
+ return 0
+
+ if A.is_Compatible(B) == 0:
+ print 'ERROR: grids [' + fA + '] and [' + fB + '] are not compatible'
+ return 0
+
+ if bPixelWise == 1: # pixelwise calculation, slower than second solution
+ C = saga_api.SG_Create_Grid(A.Get_System())
+ for y in range(0, C.Get_NY()):
+ for x in range(0, C.Get_NX()):
+ if A.is_NoData(x, y) or B.is_NoData(x, y):
+ C.Set_NoData(x, y)
+ else:
+ C.Set_Value(x, y, A.asDouble(x, y) - B.asDouble(x, y))
+ print '.',
+ C.Save(saga_api.CSG_String(fC))
+ print
+
+ else: # using built-in CSG_Grid function 'Subtract()'
+ C = saga_api.SG_Create_Grid(A)
+ C.Subtract(B)
+ C.Save(saga_api.CSG_String(fC))
+
+ print 'success'
+ return 1
+
+##########################################
+if __name__ == '__main__':
+ print 'Python - Version ' + sys.version
+ print saga_api.SAGA_API_Get_Version()
+ print
+
+ if len( sys.argv ) != 4:
+ print 'Usage: grid_difference.py <in: grid a> <in: grid b> <out: grid a-b)>'
+ print '... trying to run with test_data'
+ fA = './test.sgrd'
+ fB = './test.sgrd'
+ fC = './test_difference.sgrd'
+ else:
+ fA = sys.argv[1]
+ if os.path.split(fA)[0] == '':
+ fA = './' + fA
+
+ fB = sys.argv[2]
+ if os.path.split(fB)[0] == '':
+ fB = './' + fB
+
+ fC = sys.argv[3]
+ if os.path.split(fC)[0] == '':
+ fC = './' + fC
+
+ grid_difference(fA, fB, fC, 1)
diff --git a/src/scripting/python/examples/04_grid_contour.py b/src/scripting/python/examples/04_grid_contour.py
new file mode 100644
index 0000000..2974de4
--- /dev/null
+++ b/src/scripting/python/examples/04_grid_contour.py
@@ -0,0 +1,57 @@
+#! /usr/bin/env python
+
+import saga_api, sys, os
+
+##########################################
+def grid_contour(fGrid, fLines):
+ Grid = saga_api.SG_Get_Data_Manager().Add_Grid(unicode(fGrid))
+ if Grid == None or Grid.is_Valid() == 0:
+ print 'ERROR: loading grid [' + fGrid + ']'
+ return 0
+
+ Lines = saga_api.SG_Get_Data_Manager().Add_Shapes()
+
+ # ------------------------------------
+ if os.name == 'nt': # Windows
+ saga_api.SG_Get_Module_Library_Manager().Add_Library(os.environ['SAGA_32' ] + '/modules/shapes_grid.dll')
+ else: # Linux
+ saga_api.SG_Get_Module_Library_Manager().Add_Library(os.environ['SAGA_MLB'] + '/libshapes_grid.so')
+
+ m = saga_api.SG_Get_Module_Library_Manager().Get_Module(saga_api.CSG_String('shapes_grid'), 5) # 'Contour Lines from Grid'
+ p = m.Get_Parameters()
+ p.Get_Grid_System().Assign(Grid.Get_System()) # module needs to use conformant grid system!
+ p(saga_api.CSG_String('GRID' )).Set_Value(Grid)
+ p(saga_api.CSG_String('CONTOUR')).Set_Value(Lines)
+ p(saga_api.CSG_String('ZSTEP' )).Set_Value(25.0)
+
+ if m.Execute() == 0:
+ print 'ERROR: executing module [' + m.Get_Name().c_str() + ']'
+ return 0
+
+ # ------------------------------------
+ Lines.Save(saga_api.CSG_String(fLines))
+
+ print 'success'
+ return 1
+
+##########################################
+if __name__ == '__main__':
+ print 'Python - Version ' + sys.version
+ print saga_api.SAGA_API_Get_Version()
+ print
+
+ if len( sys.argv ) != 4:
+ print 'Usage: grid_contour.py <in: grid> <out: contour>'
+ print '... trying to run with test_data'
+ fGrid = './test.sgrd'
+ fLines = './test_contours'
+ else:
+ fGrid = sys.argv[1]
+ if os.path.split(fGrid)[0] == '':
+ fGrid = './' + fGrid
+
+ fLines = sys.argv[2]
+ if os.path.split(fLines)[0] == '':
+ fLines = './' + fLines
+
+ grid_contour(fGrid, fLines)
diff --git a/src/scripting/python/examples/05_shp2xyz.py b/src/scripting/python/examples/05_shp2xyz.py
new file mode 100644
index 0000000..4b34dfc
--- /dev/null
+++ b/src/scripting/python/examples/05_shp2xyz.py
@@ -0,0 +1,48 @@
+#! /usr/bin/env python
+
+import saga_api, sys, os
+
+##########################################
+def shp2xyz(fshp, fxyz):
+ shp = saga_api.SG_Get_Data_Manager().Add_Shapes(unicode(fshp))
+ if shp == None or shp.is_Valid() == 0:
+ print 'ERROR: loading shapes [' + fshp + ']'
+ return 0
+
+ # ------------------------------------
+ if os.name == 'nt': # Windows
+ saga_api.SG_Get_Module_Library_Manager().Add_Library(os.environ['SAGA_32' ] + '/modules/io_shapes.dll')
+ else: # Linux
+ saga_api.SG_Get_Module_Library_Manager().Add_Library(os.environ['SAGA_MLB'] + '/libio_shapes.so')
+
+ m = saga_api.SG_Get_Module_Library_Manager().Get_Module(saga_api.CSG_String('io_shapes'), 2) # 'Export Shapes to XYZ'
+ p = m.Get_Parameters()
+ p(saga_api.CSG_String('POINTS' )).Set_Value(shp)
+ p(saga_api.CSG_String('FILENAME')).Set_Value(saga_api.CSG_String(fxyz))
+
+ if m.Execute() == 0:
+ print 'ERROR: executing module [' + m.Get_Name().c_str() + ']'
+ return 0
+
+ # ------------------------------------
+ print 'success'
+ return 1
+
+##########################################
+if __name__ == '__main__':
+ print 'Python - Version ' + sys.version
+ print saga_api.SAGA_API_Get_Version()
+ print
+
+ if len( sys.argv ) != 3:
+ print 'Usage: shp2xyz.py <in: shape file> <out: x/y/z-data as text table>'
+ print '... trying to run with test_data'
+ fshp = './test_contours.shp'
+ fxyz = './test.xyz'
+ else:
+ fshp = sys.argv[1]
+ if os.path.split(fshp)[0] == '':
+ fshp = './' + fshp
+ fxyz = sys.argv[2]
+
+ shp2xyz(fshp, fxyz)
diff --git a/src/scripting/python/examples/06_xyz2shp.py b/src/scripting/python/examples/06_xyz2shp.py
new file mode 100644
index 0000000..0f574a7
--- /dev/null
+++ b/src/scripting/python/examples/06_xyz2shp.py
@@ -0,0 +1,69 @@
+#! /usr/bin/env python
+
+import saga_api, sys, os
+
+##########################################
+def xyz2shp(fTable):
+ table = saga_api.SG_Get_Data_Manager().Add_Table()
+ if table.Create(saga_api.CSG_String(fTable)) == 0:
+ table.Add_Field(saga_api.CSG_String('X'), saga_api.SG_DATATYPE_Double)
+ table.Add_Field(saga_api.CSG_String('Y'), saga_api.SG_DATATYPE_Double)
+ table.Add_Field(saga_api.CSG_String('Z'), saga_api.SG_DATATYPE_Double)
+ rec = table.Add_Record()
+ rec.Set_Value(0,0)
+ rec.Set_Value(1,0)
+ rec.Set_Value(2,2)
+ rec = table.Add_Record()
+ rec.Set_Value(0,0)
+ rec.Set_Value(1,1)
+ rec.Set_Value(2,2)
+ rec = table.Add_Record()
+ rec.Set_Value(0,1)
+ rec.Set_Value(1,1)
+ rec.Set_Value(2,1)
+ rec = table.Add_Record()
+ rec.Set_Value(0,1)
+ rec.Set_Value(1,0)
+ rec.Set_Value(2,1)
+
+ points = saga_api.SG_Get_Data_Manager().Add_Shapes(saga_api.SHAPE_TYPE_Point)
+
+ # ------------------------------------
+ if os.name == 'nt': # Windows
+ saga_api.SG_Get_Module_Library_Manager().Add_Library(os.environ['SAGA_32' ] + '/modules/shapes_points.dll')
+ else: # Linux
+ saga_api.SG_Get_Module_Library_Manager().Add_Library(os.environ['SAGA_MLB'] + '/libshapes_points.so')
+
+ m = saga_api.SG_Get_Module_Library_Manager().Get_Module(saga_api.CSG_String('shapes_points'), 0) # 'Convert Table to Points'
+ p = m.Get_Parameters()
+ p(saga_api.CSG_String('TABLE' )).Set_Value(table)
+ p(saga_api.CSG_String('POINTS')).Set_Value(points)
+ p(saga_api.CSG_String('X' )).Set_Value(0)
+ p(saga_api.CSG_String('Y' )).Set_Value(1)
+
+ if m.Execute() == 0:
+ print 'ERROR: executing module [' + m.Get_Name().c_str() + ']'
+ return 0
+
+ # ------------------------------------
+ points.Save(saga_api.CSG_String(fTable))
+
+ print 'success'
+ return 1
+
+##########################################
+if __name__ == '__main__':
+ print 'Python - Version ' + sys.version
+ print saga_api.SAGA_API_Get_Version()
+ print
+
+ if len( sys.argv ) != 2:
+ print 'Usage: xyz2shp.py <in: x/y/z-data as text or dbase table>'
+ print '... trying to run with test_data'
+ fTable = './test_pts_xyz.xyz'
+ else:
+ fTable = sys.argv[ 1 ]
+ if os.path.split(fTable)[0] == '':
+ fTable = './' + fTable
+
+ xyz2shp(fTable)
diff --git a/src/scripting/python/helpers/print_version.py b/src/scripting/python/helpers/print_version.py
new file mode 100755
index 0000000..329ab57
--- /dev/null
+++ b/src/scripting/python/helpers/print_version.py
@@ -0,0 +1,13 @@
+#! /usr/bin/env python
+
+import saga_api, sys, os
+
+##########################################
+
+if __name__ == '__main__':
+ print
+ print '--------------------------------------------------------------------------------'
+ print '# ' + saga_api.SAGA_API_Get_Version()
+ print '# Python - Version: ' + sys.version
+ print '--------------------------------------------------------------------------------'
+ print
diff --git a/src/scripting/python/helpers/saga_cmd_param_interface/environment.py b/src/scripting/python/helpers/saga_cmd_param_interface/environment.py
new file mode 100644
index 0000000..349b88c
--- /dev/null
+++ b/src/scripting/python/helpers/saga_cmd_param_interface/environment.py
@@ -0,0 +1,31 @@
+#!/usr/bin/env python
+
+# ----------------------------------------------------------------------
+# environmental configuration file "environment.py" for the
+# saga_cmd parameter interface generator "param_interface.py"
+
+# copyright (C) 2015 by Volker Wichmann
+# released under the GNU General Public License as published by the
+# Free Software Foundation; version 2 of the License.
+
+# purpose:
+# definition of file paths for the saga_cmd executable, the SAGA_MLB
+# environmental variable, and the name of the output file
+#
+# usage:
+# edit the file paths to match the saga installation of which you like
+# to generate the parameter interface
+# ----------------------------------------------------------------------
+
+import os
+
+# ----------------------------------------------------------------------
+if (os.name == 'posix'):
+ SAGA_CMD = '/usr/local/bin/saga_cmd'
+ SAGA_MLB = 'usr/local/lib/saga'
+ OUTFILE = '/home/vw/Desktop/saga_cmd_interface.txt'
+else:
+ SAGA_CMD = '"C:\\Program Files\\SAGA-GIS\\saga_cmd.exe"'
+ SAGA_MLB = '"C:\\Program Files\\SAGA-GIS\\modules"'
+ OUTFILE = 'C:\\users\\vw\\Desktop\\saga_cmd_interface.txt'
+
diff --git a/src/scripting/python/helpers/saga_cmd_param_interface/param_interface.py b/src/scripting/python/helpers/saga_cmd_param_interface/param_interface.py
new file mode 100644
index 0000000..ec674ba
--- /dev/null
+++ b/src/scripting/python/helpers/saga_cmd_param_interface/param_interface.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python
+
+# ----------------------------------------------------------------------
+# saga_cmd parameter interface generator "param_interface.py"
+
+# copyright (C) 2015 by Volker Wichmann
+# released under the GNU General Public License as published by the
+# Free Software Foundation; version 2 of the License.
+
+# purpose:
+# generate a simple text-based description of the saga_cmd parameter
+# interface of a SAGA binary installation.
+# this allows to detect changes in the parameter interface of different
+# SAGA versions.
+#
+# usage:
+# in order to run this script, you have to edit the "environment.py"
+# file to match the file paths of the SAGA installation you like to
+# investigate.
+# the editing of the "tools.py" is usually not necessary as it contains
+# all SAGA tools available and tools that not found are silently
+# skipped.
+#
+# run the script twice on two different SAGA installations in order to
+# generate a description of the saga_cmd parameter interface for each
+# version.
+# with a diff (compare) of both output files it is possible to easily
+# detect changes in the saga_cmd parameter interface of individual
+# tools.
+# ----------------------------------------------------------------------
+
+import os, subprocess, sys, environment, tools
+
+# ----------------------------------------------------------------------
+os.putenv('SAGA_MLB', environment.SAGA_MLB)
+
+outfile = open(environment.OUTFILE, 'wb')
+
+for tool in range(len(tools.tools)):
+ bPrint = False
+
+ try:
+ cmd = subprocess.Popen(environment.SAGA_CMD + ' ' +
+ tools.tools[tool][0] + ' ' + str(tools.tools[tool][1]),
+ shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+
+ for line in cmd.stdout:
+ if 'Error:' in line:
+ break
+ if 'Usage:' in line:
+ bPrint = True
+ outfile.write('<TOOL>\n')
+ outfile.write(tools.tools[tool][2] + '\n')
+ if bPrint:
+ outfile.write(' '.join(line.split()) + '\n')
+
+ if bPrint:
+ outfile.write('</TOOL>\n\n')
+
+ except Exception, e:
+ print 'ERROR: Could not execute command - %s\n' % e
+ sys.exit(1)
+
+outfile.close
diff --git a/src/scripting/python/helpers/saga_cmd_param_interface/tools.py b/src/scripting/python/helpers/saga_cmd_param_interface/tools.py
new file mode 100644
index 0000000..579c17a
--- /dev/null
+++ b/src/scripting/python/helpers/saga_cmd_param_interface/tools.py
@@ -0,0 +1,638 @@
+#!/usr/bin/env python
+
+# ----------------------------------------------------------------------
+# tools configuration file "tools.py" for the
+# saga_cmd parameter interface generator "param_interface.py"
+
+# copyright (C) 2015 by Volker Wichmann
+# released under the GNU General Public License as published by the
+# Free Software Foundation; version 2 of the License.
+
+# purpose:
+# this is the list of SAGA tools for which the parameter interface
+# should be created
+#
+# usage:
+# the list of tools has a STRICT ORDER:
+# * new tools (and libraries) have to be appended at the end
+# * tools renamed have to be edited in place
+# usually you do not need to edit this list because for a specific
+# SAGA version as the "param_interface.py" generator silently skips
+# tools that are not found.
+# ----------------------------------------------------------------------
+
+# ----------------------------------------------------------------------
+tools = [
+['climate_tools', 0, 'Multi Level to Surface Interpolation'],
+['climate_tools', 1, 'Multi Level to Points Interpolation'],
+['climate_tools', 2, 'Earth\'s Orbital Parameters'],
+['climate_tools', 3, 'Annual Course of Daily Insolation'],
+['climate_tools', 4, 'Daily Insolation over Latitude'],
+['climate_tools', 5, 'Monthly Global by Latitude'],
+['climate_tools', 6, 'PET (after Hargreaves, Table)'],
+['climate_tools', 7, 'Daily to Hourly PET'],
+['contrib_perego', 0, 'Average With Thereshold 1'],
+['contrib_perego', 1, 'Average With Thereshold 2'],
+['contrib_perego', 2, 'Average With Thereshold 3'],
+['contrib_perego', 3, 'Average With Mask 1'],
+['contrib_perego', 4, 'Average With Mask 2'],
+['contrib_perego', 5, 'Destriping'],
+['contrib_perego', 6, 'Destriping with Mask'],
+['contrib_perego', 7, 'Directional Average'],
+['db_odbc', 0, 'Connect to ODBC Source'],
+['db_odbc', 1, 'Disconnect from ODBC Source'],
+['db_odbc', 2, 'Commit/Rollback Transaction'],
+['db_odbc', 3, 'Execute SQL'],
+['db_odbc', 4, 'List Table Fields'],
+['db_odbc', 5, 'Import Table'],
+['db_odbc', 6, 'Export Table'],
+['db_odbc', 7, 'Drop Table'],
+['db_odbc', 8, 'Import Table from SQL Query'],
+['db_odbc', 9, 'List ODBC Servers'],
+['db_odbc', 10, 'List Tables'],
+['db_odbc', 11, 'Disconnect All'],
+['db_pgsql', 0, 'List PostgreSQL Connections'],
+['db_pgsql', 1, 'Connect to PostgreSQL'],
+['db_pgsql', 2, 'Disconnect from PostgreSQL'],
+['db_pgsql', 3, 'Disconnect All'],
+['db_pgsql', 4, 'Begin Transaction'],
+['db_pgsql', 5, 'Commit/Rollback Transaction'],
+['db_pgsql', 6, 'Execute SQL'],
+['db_pgsql', 10, 'List Tables'],
+['db_pgsql', 11, 'List Table Fields'],
+['db_pgsql', 12, 'Import Table'],
+['db_pgsql', 13, 'Export Table'],
+['db_pgsql', 14, 'Drop Table'],
+['db_pgsql', 15, 'Import Table from SQL Query'],
+['db_pgsql', 20, 'Import Shapes from PostGIS'],
+['db_pgsql', 21, 'Export Shapes to PostGIS'],
+['db_pgsql', 22, 'Update Shapes SRID'],
+['db_pgsql', 30, 'Import Raster from PostGIS'],
+['db_pgsql', 31, 'Export Raster to PostGIS'],
+['db_pgsql', 32, 'Update Raster SRID'],
+['docs_html', 1, 'SVG Interactive Map'],
+['docs_pdf', 0, 'Shapes Report'],
+['docs_pdf', 1, 'Shapes Summary Report'],
+['docs_pdf', 2, 'Terrain Path Cross Sections'],
+['garden_3d_viewer', 0, 'TIN Viewer'],
+['garden_3d_viewer', 1, 'Point Cloud Viewer'],
+['garden_3d_viewer', 2, '3D Shapes Viewer'],
+['garden_3d_viewer', 3, 'Globe Viewer for Grids'],
+['garden_3d_viewer', 4, 'Multiple Grids Viewer'],
+['garden_fractals', 0, 'Bifurcation'],
+['garden_fractals', 1, 'Pythagoras\' Tree'],
+['garden_fractals', 3, 'Fractal Dimension of Grid Surface'],
+['garden_fractals', 5, 'Gaussian Landscapes'],
+['garden_learn_to_program', 0, '01: My first module'],
+['garden_learn_to_program', 1, '02: Pixel by pixel operations with two grids'],
+['garden_learn_to_program', 2, '03: Direct neighbours'],
+['garden_learn_to_program', 3, '04: Direct neighbours - more...'],
+['garden_learn_to_program', 4, '05: Direct neighbours - slope and aspect'],
+['garden_learn_to_program', 5, '06: Extended neighbourhoods'],
+['garden_learn_to_program', 6, '07: Extended neighbourhoods - catchment areas (trace flow)'],
+['garden_learn_to_program', 7, '08: Extended neighbourhoods - catchment areas (parallel)'],
+['garden_learn_to_program', 8, '09: Extended neighbourhoods - catchment areas (recursive)'],
+['garden_learn_to_program', 9, '10: Dynamic Simulation - Life'],
+['garden_learn_to_program', 10, '11: Dynamic Simulation - Soil Nitrogen Dynamics'],
+['garden_learn_to_program', 11, '12: First steps with shapes'],
+['garden_learn_to_program', 12, '13: Reprojecting a shapes layer'],
+['garden_learn_to_program', 13, '14: Vectorising channel lines'],
+['garden_webservices', 0, 'Import a Map via Web Map Service (WMS)'],
+['grid_analysis', 0, 'Accumulated Cost (Isotropic)'],
+['grid_analysis', 1, 'Accumulated Cost (Anisotropic)'],
+['grid_analysis', 5, 'Least Cost Paths'],
+['grid_analysis', 6, 'Change Vector Analysis'],
+['grid_analysis', 7, 'Covered Distance'],
+['grid_analysis', 8, 'Pattern Analysis'],
+['grid_analysis', 9, 'Layer of extreme value'],
+['grid_analysis', 10, 'Analytical Hierarchy Process'],
+['grid_analysis', 11, 'Ordered Weighted Averaging (OWA)'],
+['grid_analysis', 12, 'Aggregation Index'],
+['grid_analysis', 13, 'Cross-Classification and Tabulation'],
+['grid_analysis', 14, 'Soil Texture Classification'],
+['grid_analysis', 15, 'Fragmentation (Standard)'],
+['grid_analysis', 16, 'Fragmentation (Alternative)'],
+['grid_analysis', 17, 'Fragmentation Classes from Density and Connectivity'],
+['grid_analysis', 18, 'Accumulation Functions'],
+['grid_analysis', 19, 'IMCORR - Feature Tracking'],
+['grid_analysis', 20, 'Soil Texture Classification for Tables'],
+['grid_calculus', 0, 'Grid Normalisation'],
+['grid_calculus', 1, 'Grid Calculator'],
+['grid_calculus', 2, 'Grid Volume'],
+['grid_calculus', 3, 'Grid Difference'],
+['grid_calculus', 4, 'Function'],
+['grid_calculus', 5, 'Geometric Figures'],
+['grid_calculus', 6, 'Random Terrain'],
+['grid_calculus', 7, 'Random Field'],
+['grid_calculus', 8, 'Grids Sum'],
+['grid_calculus', 9, 'Grids Product'],
+['grid_calculus', 10, 'Grid Standardisation'],
+['grid_calculus', 11, 'Fuzzify'],
+['grid_calculus', 12, 'Fuzzy Intersection (AND)'],
+['grid_calculus', 13, 'Fuzzy Union (OR)'],
+['grid_calculus', 14, 'Metric Conversions'],
+['grid_calculus', 15, 'Gradient Vector from Cartesian to Polar Coordinates'],
+['grid_calculus', 16, 'Gradient Vector from Polar to Cartesian Coordinates'],
+['grid_calculus', 18, 'Grid Division'],
+['grid_calculus', 19, 'Spherical Harmonic Synthesis'],
+['grid_calculus_bsl', 0, 'BSL'],
+['grid_calculus_bsl', 1, 'BSL from File'],
+['grid_filter', 0, 'Simple Filter'],
+['grid_filter', 1, 'Gaussian Filter'],
+['grid_filter', 2, 'Laplacian Filter'],
+['grid_filter', 3, 'Multi Direction Lee Filter'],
+['grid_filter', 4, 'User Defined Filter'],
+['grid_filter', 5, 'Filter Clumps'],
+['grid_filter', 6, 'Majority Filter'],
+['grid_filter', 7, 'DTM Filter (slope-based)'],
+['grid_filter', 8, 'Morphological Filter'],
+['grid_filter', 9, 'Rank Filter'],
+['grid_filter', 10, 'Mesh Denoise'],
+['grid_filter', 11, 'Resampling Filter'],
+['grid_filter', 12, 'Geodesic Morphological Reconstruction'],
+['grid_filter', 13, 'Binary Erosion-Reconstruction'],
+['grid_filter', 14, 'Connectivity Analysis'],
+['grid_filter', 15, 'Sieving Classes'],
+['grid_gridding', 0, 'Shapes to Grid'],
+['grid_gridding', 1, 'Inverse Distance Weighted'],
+['grid_gridding', 2, 'Nearest Neighbour'],
+['grid_gridding', 3, 'Natural Neighbour'],
+['grid_gridding', 4, 'Modifed Quadratic Shepard'],
+['grid_gridding', 5, 'Triangulation'],
+['grid_gridding', 6, 'Kernel Density Estimation'],
+['grid_gridding', 7, 'Angular Distance Weighted'],
+['grid_spline', 1, 'Thin Plate Spline'],
+['grid_spline', 2, 'Thin Plate Spline (TIN)'],
+['grid_spline', 3, 'B-Spline Approximation'],
+['grid_spline', 4, 'Multilevel B-Spline Interpolation'],
+['grid_spline', 5, 'Multilevel B-Spline Interpolation (from Grid)'],
+['grid_spline', 6, 'Cubic Spline Approximation'],
+['grid_spline', 7, 'Multilevel B-Spline Interpolation for Categories'],
+['grid_tools', 0, 'Resampling'],
+['grid_tools', 1, 'Aggregate'],
+['grid_tools', 3, 'Mosaicking'],
+['grid_tools', 4, 'Constant Grid'],
+['grid_tools', 5, 'Patching'],
+['grid_tools', 6, 'Close One Cell Gaps'],
+['grid_tools', 7, 'Close Gaps'],
+['grid_tools', 8, 'Grid Buffer'],
+['grid_tools', 9, 'Threshold Buffer'],
+['grid_tools', 10, 'Grid Proximity Buffer'],
+['grid_tools', 11, 'Change Data Storage'],
+['grid_tools', 12, 'Change Grid Values'],
+['grid_tools', 15, 'Reclassify Grid Values'],
+['grid_tools', 17, 'Crop to Data'],
+['grid_tools', 18, 'Invert Data/No-Data'],
+['grid_tools', 19, 'Grid Orientation'],
+['grid_tools', 20, 'Combine Grids'],
+['grid_tools', 21, 'Grid Cell Index'],
+['grid_tools', 22, 'Grids from classified grid and table'],
+['grid_tools', 23, 'Create Grid System'],
+['grid_tools', 24, 'Grid Masking'],
+['grid_tools', 25, 'Close Gaps with Spline'],
+['grid_tools', 26, 'Proximity Grid'],
+['grid_tools', 27, 'Tiling'],
+['grid_tools', 28, 'Shrink and Expand'],
+['grid_tools', 29, 'Close Gaps with Stepwise Resampling'],
+['grid_tools', 30, 'Transpose Grids'],
+['grid_tools', 31, 'Clip Grids'],
+['grid_visualisation', 0, 'Color Palette Rotation'],
+['grid_visualisation', 1, 'Color Blending'],
+['grid_visualisation', 2, 'Fit Color Palette to Grid Values'],
+['grid_visualisation', 3, 'RGB Composite'],
+['grid_visualisation', 4, 'Create 3D Image'],
+['grid_visualisation', 5, 'Color Triangle Composite'],
+['grid_visualisation', 6, 'Histogram Surface'],
+['grid_visualisation', 7, 'Aspect-Slope Grid'],
+['grid_visualisation', 8, 'Terrain Map View'],
+['grid_visualisation', 9, 'Split RGB Composite'],
+['imagery_classification', 0, 'Supervised Classification for Grids'],
+['imagery_classification', 1, 'Cluster Analysis for Grids'],
+['imagery_classification', 2, 'Confusion Matrix (Two Grids)'],
+['imagery_classification', 3, 'Decision Tree'],
+['imagery_classification', 4, 'Supervised Classification for Shapes'],
+['imagery_classification', 5, 'Supervised Classification for Tables'],
+['imagery_opencv', 0, 'Morphological Filter (OpenCV)'],
+['imagery_opencv', 1, 'Fourier Transformation (OpenCV)'],
+['imagery_opencv', 2, 'Single Value Decomposition (OpenCV)'],
+['imagery_opencv', 3, 'Neural Networks (OpenCV)'],
+['imagery_opencv', 4, 'Stereo Match (OpenCV)'],
+['imagery_photogrammetry', 0, 'Resection (Terrestrial)'],
+['imagery_photogrammetry', 1, 'Colorisation (PC)'],
+['imagery_segmentation', 0, 'Watershed Segmentation'],
+['imagery_segmentation', 1, 'Grid Skeletonization'],
+['imagery_segmentation', 2, 'Seed Generation'],
+['imagery_segmentation', 3, 'Seeded Region Growing'],
+['imagery_svm', 0, 'SVM Classification'],
+['imagery_tools', 0, 'Vegetation Index (Distance Based)'],
+['imagery_tools', 1, 'Vegetation Index (Slope Based)'],
+['imagery_tools', 2, 'Enhanced Vegetation Index'],
+['imagery_tools', 3, 'Tasseled Cap Transformation'],
+['imagery_tools', 4, 'IHS Sharpening'],
+['imagery_tools', 5, 'Colour Normalized Brovey Sharpening'],
+['imagery_tools', 6, 'Colour Normalized Spectral Sharpening'],
+['imagery_tools', 7, 'Principle Components Based Image Sharpening'],
+['imagery_tools', 8, 'Top of Atmosphere Reflectance'],
+['imagery_tools', 9, 'Automated Cloud Cover Assessment'],
+['imagery_tools', 10, 'Landsat Import with Options'],
+['imagery_vigra', 0, 'Smoothing (ViGrA)'],
+['imagery_vigra', 1, 'Edge Detection (ViGrA)'],
+['imagery_vigra', 2, 'Morphological Filter (ViGrA)'],
+['imagery_vigra', 3, 'Distance (ViGrA)'],
+['imagery_vigra', 4, 'Watershed Segmentation (ViGrA)'],
+['imagery_vigra', 5, 'Fourier Transform (ViGrA)'],
+['imagery_vigra', 6, 'Fourier Transform Inverse (ViGrA)'],
+['imagery_vigra', 7, 'Fourier Transform (Real, ViGrA)'],
+['imagery_vigra', 8, 'Fourier Filter (ViGrA)'],
+['imagery_vigra', 9, 'Random Forest Classification (ViGrA)'],
+['imagery_vigra', 10, 'Random Forest Presence Prediction (ViGrA)'],
+['io_esri_e00', 0, 'Import ESRI E00 File'],
+['io_gdal', 0, 'GDAL: Import Raster'],
+['io_gdal', 1, 'GDAL: Export Raster'],
+['io_gdal', 2, 'GDAL: Export Raster to GeoTIFF'],
+['io_gdal', 3, 'OGR: Import Vector Data'],
+['io_gdal', 4, 'OGR: Export Vector Data'],
+['io_gdal', 5, 'OGR: Export Shapes to KML'],
+['io_gdal', 6, 'GDAL: Import NetCDF'],
+['io_gps', 0, 'GPX to shapefile'],
+['io_gps', 1, 'GPSBabel'],
+['io_grid', 0, 'Export ESRI Arc/Info Grid'],
+['io_grid', 1, 'Import ESRI Arc/Info Grid'],
+['io_grid', 2, 'Export Surfer Grid'],
+['io_grid', 3, 'Import Surfer Grid'],
+['io_grid', 4, 'Import Binary Raw Data'],
+['io_grid', 5, 'Export Grid to XYZ'],
+['io_grid', 6, 'Import Grid from XYZ'],
+['io_grid', 7, 'Import USGS SRTM Grid'],
+['io_grid', 8, 'Import MOLA Grid (MEGDR)'],
+['io_grid', 9, 'Import SRTM30 DEM'],
+['io_grid', 10, 'Export True Color Bitmap'],
+['io_grid', 11, 'Import Erdas LAN/GIS'],
+['io_grid', 12, 'Import Grid from Table'],
+['io_grid', 13, 'Import WRF Geogrid Binary Format'],
+['io_grid', 14, 'Export WRF Geogrid Binary Format'],
+['io_grid', 15, 'Import Building Sketches from CityGML'],
+['io_grid_grib2', 0, 'Import GRIB2 record'],
+['io_grid_image', 0, 'Export Image (bmp, jpg, pcx, png, tif)'],
+['io_grid_image', 1, 'Import Image (bmp, jpg, png, tif, gif, pnm, xpm)'],
+['io_grid_image', 2, 'Export Grid to KML'],
+['io_shapes', 0, 'Export GStat Shapes'],
+['io_shapes', 1, 'Import GStat Shapes'],
+['io_shapes', 2, 'Export Shapes to XYZ'],
+['io_shapes', 3, 'Import Shapes from XYZ'],
+['io_shapes', 4, 'Export Shapes to Generate'],
+['io_shapes', 5, 'Export Surfer Blanking File'],
+['io_shapes', 6, 'Import Surfer Blanking Files'],
+['io_shapes', 7, 'Export Atlas Boundary File'],
+['io_shapes', 8, 'Import Atlas Boundary File'],
+['io_shapes', 9, 'Export WASP terrain map file'],
+['io_shapes', 10, 'Import WASP terrain map file'],
+['io_shapes', 11, 'Import Stereo Lithography File (STL)'],
+['io_shapes', 12, 'Export TIN to Stereo Lithography File (STL)'],
+['io_shapes', 13, 'Import GPX'],
+['io_shapes', 14, 'Export GPX'],
+['io_shapes', 15, 'Import Point Cloud from Shape File'],
+['io_shapes', 16, 'Import Point Cloud from Text File'],
+['io_shapes', 17, 'Export Scalable Vector Graphics (SVG) File'],
+['io_shapes', 18, 'Export Point Cloud to Text File'],
+['io_shapes', 19, 'Import Simple Features from Well Known Text'],
+['io_shapes', 20, 'Export Simple Features to Well Known Text'],
+['io_shapes_dxf', 0, 'Import DXF Files'],
+['io_shapes_las', 0, 'Export LAS Files'],
+['io_shapes_las', 1, 'Import LAS Files'],
+['io_shapes_las', 2, 'LAS Info'],
+['io_table', 0, 'Export Text Table'],
+['io_table', 1, 'Import Text Table'],
+['io_table', 2, 'Import Text Table with Numbers only'],
+['io_table', 3, 'Import Text Table (Fixed Column Sizes)'],
+['io_virtual', 0, 'Create Virtual Point Cloud Dataset'],
+['io_virtual', 1, 'Get Subset from Virtual Point Cloud'],
+['io_virtual', 2, 'Create Tileshape from Virtual Point Cloud'],
+['io_virtual', 4, 'Get Grid from Virtual Point Cloud'],
+['io_virtual', 6, 'Remove Overlap from Virtual Point Cloud Tiles'],
+['pj_georeference', 1, 'Rectify Grid'],
+['pj_georeference', 2, 'Warping Shapes'],
+['pj_georeference', 4, 'Direct Georeferencing of Airborne Photographs'],
+['pj_georeference', 5, 'Define Georeference for Grids'],
+['pj_georeference', 6, 'World File from Flight and Camera Settings'],
+['pj_geotrans', 0, 'GeoTrans (Shapes)'],
+['pj_geotrans', 1, 'GeoTrans (Grid)'],
+['pj_proj4', 0, 'Set Coordinate Reference System'],
+['pj_proj4', 1, 'Coordinate Transformation (Shapes List)'],
+['pj_proj4', 2, 'Coordinate Transformation (Shapes)'],
+['pj_proj4', 3, 'Coordinate Transformation (Grid List)'],
+['pj_proj4', 4, 'Coordinate Transformation (Grid)'],
+['pj_proj4', 5, '[deprecated] Proj.4 (Command Line Arguments, Shapes)'],
+['pj_proj4', 6, '[deprecated] Proj.4 (Dialog, Shapes)'],
+['pj_proj4', 7, '[deprecated] Proj.4 (Command Line Arguments, Grid)'],
+['pj_proj4', 8, '[deprecated] Proj.4 (Dialog, Grid)'],
+['pj_proj4', 9, '[deprecated] Proj.4 (Command Line Arguments, List of Shapes Layers)'],
+['pj_proj4', 10, '[deprecated] Proj.4 (Dialog, List of Shapes Layers)'],
+['pj_proj4', 11, '[deprecated] Proj.4 (Command Line Arguments, List of Grids)'],
+['pj_proj4', 12, '[deprecated] Proj.4 (Dialog, List of Grids)'],
+['pj_proj4', 13, 'Change Longitudinal Range for Grids'],
+['pj_proj4', 14, 'Latitude/Longitude Graticule'],
+['pj_proj4', 15, 'Coordinate Reference System Picker'],
+['pj_proj4', 16, 'Tissot\'s Indicatrix'],
+['pj_proj4', 17, 'Geographic Coordinate Grids'],
+['pj_proj4', 18, 'Coordinate Transformation (Point Cloud List)'],
+['pj_proj4', 19, 'Coordinate Transformation (Point Cloud)'],
+['pj_proj4', 20, 'Geographic Distances'],
+['pj_proj4', 21, 'Geographic Distances (Pair of Coordinates)'],
+['pointcloud_tools', 0, 'Point Cloud Cutter'],
+['pointcloud_tools', 2, 'Point Cloud from Grid Points'],
+['pointcloud_tools', 3, 'Point Cloud from Shapes'],
+['pointcloud_tools', 4, 'Point Cloud to Grid'],
+['pointcloud_tools', 5, 'Point Cloud to Shapes'],
+['pointcloud_tools', 6, 'Point Cloud Reclassifier / Subset Extractor'],
+['pointcloud_tools', 7, 'Drop Point Cloud Attributes'],
+['pointcloud_tools', 8, 'Transform Point Cloud'],
+['pointcloud_tools', 9, 'Point Cloud Thinning (simple)'],
+['pointcloud_tools', 10, 'Point Cloud Attribute Calculator'],
+['pointcloud_tools', 11, 'Cluster Analysis for Point Clouds'],
+['pointcloud_tools', 12, 'Merge Point Clouds'],
+['pointcloud_viewer', 0, '[deprecated] Point Cloud Viewer'],
+['shapes_grid', 0, 'Add Grid Values to Points'],
+['shapes_grid', 1, 'Add Grid Values to Shapes'],
+['shapes_grid', 2, 'Grid Statistics for Polygons'],
+['shapes_grid', 3, 'Grid Values to Points'],
+['shapes_grid', 4, 'Grid Values to Points (randomly)'],
+['shapes_grid', 5, 'Contour Lines from Grid'],
+['shapes_grid', 6, 'Vectorising Grid Classes'],
+['shapes_grid', 7, 'Clip Grid with Polygon'],
+['shapes_grid', 8, 'Grid Statistics for Points'],
+['shapes_grid', 9, 'Local Minima and Maxima'],
+['shapes_grid', 10, 'Grid System Extent'],
+['shapes_grid', 11, 'Clip Grid with Rectangle'],
+['shapes_grid', 15, 'Gradient Vectors from Surface'],
+['shapes_grid', 16, 'Gradient Vectors from Direction and Length'],
+['shapes_grid', 17, 'Gradient Vectors from Directional Components'],
+['shapes_lines', 0, 'Convert Polygons to Lines'],
+['shapes_lines', 1, 'Convert Points to Line(s)'],
+['shapes_lines', 2, 'Line Properties'],
+['shapes_lines', 3, 'Line-Polygon Intersection'],
+['shapes_lines', 4, 'Line Simplification'],
+['shapes_lines', 5, 'Line Dissolve'],
+['shapes_lines', 6, 'Split Lines with Lines'],
+['shapes_lines', 7, 'Line Smoothing'],
+['shapes_points', 0, 'Convert Table to Points'],
+['shapes_points', 1, 'Count Points in Polygons'],
+['shapes_points', 2, 'Create Point Grid'],
+['shapes_points', 3, 'Point Distances'],
+['shapes_points', 4, 'Fit N Points to shape'],
+['shapes_points', 5, 'Convert Lines to Points'],
+['shapes_points', 6, 'Add Coordinates to points'],
+['shapes_points', 7, 'Remove Duplicate Points'],
+['shapes_points', 8, 'Clip Points with Polygons'],
+['shapes_points', 9, 'Separate points by direction'],
+['shapes_points', 10, 'Add Polygon Attributes to Points'],
+['shapes_points', 11, 'Points Filter'],
+['shapes_points', 12, 'Convex Hull'],
+['shapes_points', 14, 'Points Thinning'],
+['shapes_points', 15, 'Convert Multipoints to Points'],
+['shapes_points', 16, 'Thiessen Polygons'],
+['shapes_points', 17, 'Aggregate Point Observations'],
+['shapes_points', 18, 'Snap Points to Points'],
+['shapes_points', 19, 'Snap Points to Lines'],
+['shapes_points', 20, 'Snap Points to Grid'],
+['shapes_polygons', 1, 'Polygon Centroids'],
+['shapes_polygons', 2, 'Polygon Properties'],
+['shapes_polygons', 3, 'Convert Lines to Polygons'],
+['shapes_polygons', 4, 'Point Statistics for Polygons'],
+['shapes_polygons', 5, 'Polygon Dissolve'],
+['shapes_polygons', 6, 'Convert Polygon/Line Vertices to Points'],
+['shapes_polygons', 7, 'Polygon Shape Indices'],
+['shapes_polygons', 8, 'Polygon-Line Intersection'],
+['shapes_polygons', 9, 'Polygons to Edges and Nodes'],
+['shapes_polygons', 10, 'Polygon Parts to Separate Polygons'],
+['shapes_polygons', 11, 'Polygon Clipping'],
+['shapes_polygons', 12, 'Polygon Self-Intersection'],
+['shapes_polygons', 14, 'Intersect'],
+['shapes_polygons', 15, 'Difference'],
+['shapes_polygons', 16, 'Symmetrical Difference'],
+['shapes_polygons', 17, 'Union'],
+['shapes_polygons', 18, 'Update'],
+['shapes_polygons', 19, 'Identity'],
+['shapes_polygons', 20, 'Add Point Attributes to Polygons'],
+['shapes_polygons', 21, 'Flatten Polygon Layer'],
+['shapes_polygons', 22, 'Shared Polygon Edges'],
+['shapes_tools', 0, 'Create New Shapes Layer'],
+['shapes_tools', 2, 'Merge Layers'],
+['shapes_tools', 3, 'Select by Attributes... (Numerical Expression)'],
+['shapes_tools', 4, 'Select by Attributes... (String Expression)'],
+['shapes_tools', 5, 'Select by Location...'],
+['shapes_tools', 6, 'Copy Selection to New Shapes Layer'],
+['shapes_tools', 7, 'Delete Selection from Shapes Layer'],
+['shapes_tools', 8, 'Invert Selection of Shapes Layer'],
+['shapes_tools', 9, 'Split Shapes Layer Completely'],
+['shapes_tools', 10, 'Transform Shapes'],
+['shapes_tools', 11, 'Create Chart Layer (bars/sectors)'],
+['shapes_tools', 12, 'Create Graticule'],
+['shapes_tools', 13, 'Cut Shapes Layer'],
+['shapes_tools', 15, 'Split Shapes Layer'],
+['shapes_tools', 16, 'Split Shapes Layer Randomly'],
+['shapes_tools', 17, 'Split Table/Shapes by Attribute'],
+['shapes_tools', 18, 'Shapes Buffer'],
+['shapes_tools', 19, 'Get Shapes Extents'],
+['shapes_tools', 20, 'QuadTree Structure to Shapes'],
+['shapes_tools', 21, 'Polar to Cartesian Coordinates'],
+['shapes_tools', 22, 'Generate Shapes'],
+['shapes_tools', 23, 'Convert Vertex Type (2D/3D)'],
+['shapes_tools', 24, 'Merge Tables'],
+['shapes_tools', 25, 'Land Use Scenario Generator'],
+['shapes_transect', 0, 'Transect through polygon shapefile'],
+['sim_cellular_automata', 0, 'Conway\'s Life'],
+['sim_cellular_automata', 1, 'Wa-Tor'],
+['sim_ecosystems_hugget', 0, '01: A Simple Litter System'],
+['sim_ecosystems_hugget', 1, '02: Carbon Cycle Simulation for Terrestrial Biomass'],
+['sim_ecosystems_hugget', 2, '03: Spatially Distributed Simulation of Soil Nitrogen Dynamics'],
+['sim_erosion', 0, 'MMF-SAGA Soil Erosion Mode'],
+['sim_fire_spreading', 0, 'Fire Risk Analysis'],
+['sim_fire_spreading', 1, 'Simulation'],
+['sim_hydrology', 0, 'Soil Moisture Content'],
+['sim_hydrology', 1, 'Overland Flow - Kinematic Wave D8'],
+['sim_hydrology', 2, 'TOPMODEL'],
+['sim_hydrology', 3, 'Water Retention Capacity'],
+['sim_hydrology', 4, 'Diffuse Pollution Risk'],
+['sim_ihacres', 0, 'IHACRES Calibration (2)'],
+['sim_ihacres', 1, 'IHACRES Version 1.0'],
+['sim_ihacres', 2, 'IHACRES Basin'],
+['sim_ihacres', 3, 'IHACRES Elevation Bands'],
+['sim_ihacres', 4, 'IHACRES Elevation Bands Calibration'],
+['statistics_grid', 0, 'Fast Representativeness'],
+['statistics_grid', 1, 'Residual Analysis (Grid)'],
+['statistics_grid', 2, 'Representativeness (Grid)'],
+['statistics_grid', 3, 'Radius of Variance (Grid)'],
+['statistics_grid', 4, 'Statistics for Grids'],
+['statistics_grid', 5, 'Zonal Grid Statistics'],
+['statistics_grid', 6, 'Directional Statistics for Single Grid'],
+['statistics_grid', 7, 'Global Moran\'s I for Grids'],
+['statistics_grid', 8, 'Principle Components Analysis'],
+['statistics_grid', 9, 'Multi-Band Variation'],
+['statistics_grid', 10, 'Inverse Principle Components Rotation'],
+['statistics_grid', 11, 'Longitudinal Grid Statistics'],
+['statistics_grid', 12, 'Meridional Grid Statistics'],
+['statistics_grid', 13, 'Save Grid Statistics to Table'],
+['statistics_kriging', 0, 'Ordinary Kriging'],
+['statistics_kriging', 1, 'Simple Kriging'],
+['statistics_kriging', 2, 'Universal Kriging'],
+['statistics_kriging', 3, 'Regression Kriging'],
+['statistics_kriging', 4, 'Variogram (Dialog)'],
+['statistics_points', 0, 'Variogram'],
+['statistics_points', 1, 'Variogram Cloud'],
+['statistics_points', 2, 'Variogram Surface'],
+['statistics_points', 3, 'Minimum Distance Analysis'],
+['statistics_points', 4, 'Spatial Point Pattern Analysis'],
+['statistics_regression', 0, 'Regression Analysis (Points and Predictor Grid)'],
+['statistics_regression', 1, 'Multiple Regression Analysis (Points and Predictor Grids)'],
+['statistics_regression', 2, 'Polynomial Regression'],
+['statistics_regression', 3, 'GWR for Single Predictor (Gridded Model Output)'],
+['statistics_regression', 4, 'GWR for Single Predictor Grid'],
+['statistics_regression', 5, 'GWR for Multiple Predictors (Gridded Model Output)'],
+['statistics_regression', 6, 'GWR for Multiple Predictor Grids'],
+['statistics_regression', 7, 'GWR for Multiple Predictors'],
+['statistics_regression', 8, 'Multiple Regression Analysis (Grid and Predictor Grids)'],
+['statistics_regression', 9, 'Polynomial Trend from Grids'],
+['statistics_regression', 10, 'Trend Analysis'],
+['statistics_regression', 11, 'Trend Analysis (Shapes)'],
+['statistics_regression', 12, 'Multiple Linear Regression Analysis'],
+['statistics_regression', 13, 'Multiple Linear Regression Analysis (Shapes)'],
+['statistics_regression', 14, 'GWR for Grid Downscaling'],
+['statistics_regression', 15, 'Zonal Multiple Regression Analysis (Points and Predictor Grids)'],
+['ta_channels', 0, 'Channel Network'],
+['ta_channels', 1, 'Watershed Basins'],
+['ta_channels', 2, 'Watershed Basins (Extended)'],
+['ta_channels', 3, 'Vertical Distance to Channel Network'],
+['ta_channels', 4, 'Overland Flow Distance to Channel Network'],
+['ta_channels', 5, 'Channel Network and Drainage Basins'],
+['ta_channels', 6, 'Strahler Order'],
+['ta_channels', 7, 'Valley Depth'],
+['ta_compound', 0, 'Basic Terrain Analysis'],
+['ta_hydrology', 0, 'Flow Accumulation (Top-Down)'],
+['ta_hydrology', 1, 'Flow Accumulation (Recursive)'],
+['ta_hydrology', 2, 'Flow Accumulation (Flow Tracing)'],
+['ta_hydrology', 4, 'Upslope Area'],
+['ta_hydrology', 6, 'Flow Path Length'],
+['ta_hydrology', 7, 'Slope Length'],
+['ta_hydrology', 10, 'Cell Balance'],
+['ta_hydrology', 13, 'Edge Contamination'],
+['ta_hydrology', 15, 'SAGA Wetness Index'],
+['ta_hydrology', 16, 'Lake Flood'],
+['ta_hydrology', 18, 'Flow Accumulation (Mass-Flux Method)'],
+['ta_hydrology', 19, 'Flow Width and Specific Catchment Area'],
+['ta_hydrology', 20, 'Topographic Wetness Index (TWI)'],
+['ta_hydrology', 21, 'Stream Power Index'],
+['ta_hydrology', 22, 'LS Factor'],
+['ta_hydrology', 23, 'Melton Ruggedness Number'],
+['ta_hydrology', 24, 'TCI Low'],
+['ta_hydrology', 25, 'LS-Factor, Field Based'],
+['ta_hydrology', 26, 'Slope Limited Flow Accumulation'],
+['ta_lighting', 0, 'Analytical Hillshading'],
+['ta_lighting', 2, 'Potential Incoming Solar Radiation'],
+['ta_lighting', 3, 'Sky View Factor'],
+['ta_lighting', 4, 'Topographic Correction'],
+['ta_lighting', 5, 'Topographic Openness'],
+['ta_lighting', 6, 'Visibility (points)'],
+['ta_morphometry', 0, 'Slope, Aspect, Curvature'],
+['ta_morphometry', 1, 'Convergence Index'],
+['ta_morphometry', 2, 'Convergence Index (Search Radius)'],
+['ta_morphometry', 3, 'Surface Specific Points'],
+['ta_morphometry', 4, 'Curvature Classification'],
+['ta_morphometry', 5, 'Hypsometry'],
+['ta_morphometry', 6, 'Real Surface Area'],
+['ta_morphometry', 7, 'Morphometric Protection Index'],
+['ta_morphometry', 8, 'Multiresolution Index of Valley Bottom Flatness (MRVBF)'],
+['ta_morphometry', 9, 'Downslope Distance Gradient'],
+['ta_morphometry', 10, 'Mass Balance Index'],
+['ta_morphometry', 11, 'Effective Air Flow Heights'],
+['ta_morphometry', 12, 'Diurnal Anisotropic Heating'],
+['ta_morphometry', 13, 'Land Surface Temperature'],
+['ta_morphometry', 14, 'Relative Heights and Slope Positions'],
+['ta_morphometry', 15, 'Wind Effect (Windward / Leeward Index)'],
+['ta_morphometry', 16, 'Terrain Ruggedness Index (TRI)'],
+['ta_morphometry', 17, 'Vector Ruggedness Measure (VRM)'],
+['ta_morphometry', 18, 'Topographic Position Index (TPI)'],
+['ta_morphometry', 19, 'TPI Based Landform Classification'],
+['ta_morphometry', 20, 'Terrain Surface Texture'],
+['ta_morphometry', 21, 'Terrain Surface Convexity'],
+['ta_morphometry', 22, 'Terrain Surface Classification'],
+['ta_morphometry', 23, 'Morphometric Features'],
+['ta_morphometry', 24, 'Valley and Ridge Detection (Top Hat Approach)'],
+['ta_morphometry', 25, 'Fuzzy Landform Element Classification'],
+['ta_morphometry', 26, 'Upslope and Downslope Curvature'],
+['ta_preprocessor', 0, 'Flat Detection'],
+['ta_preprocessor', 1, 'Sink Drainage Route Detection'],
+['ta_preprocessor', 2, 'Sink Removal'],
+['ta_preprocessor', 3, 'Fill Sinks (Planchon/Darboux, 2001)'],
+['ta_preprocessor', 4, 'Fill Sinks (Wang & Liu)'],
+['ta_preprocessor', 5, 'Fill Sinks XXL (Wang & Liu)'],
+['ta_preprocessor', 6, 'Burn Stream Network into DEM'],
+['ta_profiles', 3, 'Cross Profiles'],
+['ta_profiles', 4, 'Profiles from Lines'],
+['ta_profiles', 5, 'Profile from points'],
+['ta_slope_stability', 0, 'SAFETYFACTOR'],
+['ta_slope_stability', 1, 'TOBIA'],
+['ta_slope_stability', 2, 'SHALSTAB'],
+['ta_slope_stability', 3, 'WETNESS'],
+['ta_slope_stability', 4, 'WEDGEFAIL'],
+['ta_slope_stability', 5, 'ANGMAP'],
+['table_calculus', 0, 'Function Fit'],
+['table_calculus', 1, 'Table Calculator'],
+['table_calculus', 2, 'Table Calculator (Shapes)'],
+['table_calculus', 5, 'Running Average'],
+['table_calculus', 6, 'Cluster Analysis'],
+['table_calculus', 7, 'Principle Components Analysis'],
+['table_calculus', 8, 'Fill Gaps in Records'],
+['table_calculus', 11, 'Find Field of Extreme Value'],
+['table_calculus', 12, 'Minimum Redundancy Feature Selection'],
+['table_calculus', 14, 'Cluster Analysis (Shapes)'],
+['table_calculus', 15, 'Field Statistics'],
+['table_tools', 0, 'Create New Table'],
+['table_tools', 1, 'Transpose Table'],
+['table_tools', 2, 'Enumerate Table Field'],
+['table_tools', 3, 'Join Attributes from a Table'],
+['table_tools', 4, 'Join Attributes from a Table (Shapes)'],
+['table_tools', 5, 'Change Date Format'],
+['table_tools', 6, 'Change Time Format'],
+['table_tools', 7, 'Change Field Type'],
+['table_tools', 8, 'Append Fields from another Table'],
+['table_tools', 9, 'Change Color Format'],
+['table_tools', 10, 'Replace Text'],
+['table_tools', 11, 'Delete Fields'],
+['table_tools', 15, 'Copy Selection'],
+['table_tools', 16, 'Delete Selection'],
+['table_tools', 17, 'Invert Selection'],
+['table_tools', 18, 'Select by Numerical Expression'],
+['table_tools', 19, 'Select by String Expression'],
+['table_tools', 20, 'Add Indicator Fields for Categories'],
+['tin_tools', 0, 'Grid to TIN'],
+['tin_tools', 1, 'Grid to TIN (Surface Specific Points)'],
+['tin_tools', 2, 'Shapes to TIN'],
+['tin_tools', 3, 'TIN to Shapes'],
+['tin_tools', 4, 'Gradient'],
+['tin_tools', 5, 'Flow Accumulation (Trace)'],
+['tin_tools', 6, 'Flow Accumulation (Parallel)'],
+['tin_viewer', 0, '[deprecated] TIN Viewer'],
+['sim_rivflow', 0, 'RiverBasin'],
+['sim_rivflow', 1, 'LandFlow Version 1.0 (build 3.5.1b)'],
+['sim_rivflow', 3, 'RiverGridGeneration'],
+['sim_rivflow', 4, 'GridCombination'],
+['io_grid', 16, 'Import, Clip and Resample Grids'],
+['climate_tools', 8, 'PET (after Hargreaves, Grid)'],
+['grid_visualisation', 10, 'Select Look-up Table for Grid Visualization'],
+['grid_tools', 32, 'Select Grid from List'],
+['imagery_maxent', 0, 'Maximum Entropy Classifcation'],
+['imagery_maxent', 1, 'Maximum Entropy Presence Prediction'],
+['io_grid_image', 3, 'Import Grids from KML'],
+['pointcloud_tools', 13, 'Point Cloud from Table'],
+['shapes_lines', 8, 'Split Lines at Points'],
+['grid_filter', 16, 'Wombling (Edge Detection)'],
+['grid_analysis', 21, 'Diversity of Categories'],
+['climate_tools', 9, 'Sunrise and Sunset'],
+['grid_filter', 17, 'Wombling for Multiple Features (Edge Detection)'],
+['db_pgsql', 33, 'Import Single Raster Band from PostGIS'],
+['ta_morphometry', 27, 'Wind Exposition Index'],
+['imagery_classification', 7, 'Confusion Matrix (Polygons / Grid)'],
+['db_pgsql', 35, 'Create Database'],
+['db_pgsql', 36, 'Drop Database']
+]
diff --git a/src/scripting/python/test_data/test.mgrd b/src/scripting/python/test_data/test.mgrd
new file mode 100644
index 0000000..48b2b1b
--- /dev/null
+++ b/src/scripting/python/test_data/test.mgrd
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<SAGA_METADATA>
+ <HISTORY>
+ <MODULE>Grid Calculator</MODULE>
+ <OPTION type="text" id="FORMULA" name="Formula">(a+10)*100</OPTION>
+ <OPTION type="text" id="NAME" name="Name">Calculation [(a+10)*100]</OPTION>
+ <OPTION type="boolean" id="FNAME" name="Take Formula">TRUE</OPTION>
+ <OPTION type="boolean" id="USE_NODATA" name="Use NoData">FALSE</OPTION>
+ <DATA_LIST type="grid_list" id="GRIDS" name="Grids">
+ <DATA>
+ <MODULE>Geometric Figures</MODULE>
+ <OPTION type="integer" id="CELL_COUNT" name="Cell Count">10</OPTION>
+ <OPTION type="double" id="CELL_SIZE" name="Cell Size">1.000000</OPTION>
+ <OPTION type="choice" id="FIGURE" name="Figure">0</OPTION>
+ <OPTION type="double" id="PLANE" name="Direction of Plane [Degree]">22.500000</OPTION>
+ </DATA>
+ </DATA_LIST>
+ </HISTORY>
+ <SOURCE>
+ <FILE>/home/vw/devel/saga/trunk/saga-gis/src/scripting/python/test_data/test.sgrd</FILE>
+ <DATABASE></DATABASE>
+ <PROJECTION></PROJECTION>
+ </SOURCE>
+</SAGA_METADATA>
diff --git a/src/scripting/python/test_data/test.sdat b/src/scripting/python/test_data/test.sdat
new file mode 100644
index 0000000..e433b88
--- /dev/null
+++ b/src/scripting/python/test_data/test.sdat
@@ -0,0 +1 @@
+�O�ǀO�ǀO��#jD��D��D#jD�O�ǀO�ǀO�ǀO��;��C�xD��D��!D��!D��D�xD;��C�O�ǀO�ǏxD��!D�
1D#C:D#C:D�
1D��!D�xD�O��#jD��D�
1D��DD�xRD�xRD��DD�
1D��D#jD��D��!D#C:D�xRD�RhD�RhD�xRD#C:D��!D��D��D��!D#C:D�xRD�RhD�RhD�xRD#C:D��!D��D#jD��D�
1D��DD�xRD�xRD��DD�
1D��D#jD�O�ǏxD��!D�
1D#C:D#C:D�
1D��!D�xD�O�ǀO��;��C�xD��D��!D��!D��D�xD;��C�O�ǀO�ǀO�ǀO��#jD��D��D#jD�O�ǀO�ǀO��
\ No newline at end of file
diff --git a/src/scripting/python/test_data/test.sgrd b/src/scripting/python/test_data/test.sgrd
new file mode 100644
index 0000000..95cc38b
--- /dev/null
+++ b/src/scripting/python/test_data/test.sgrd
@@ -0,0 +1,14 @@
+NAME = test
+DESCRIPTION =
+UNIT =
+DATAFILE_OFFSET = 0
+DATAFORMAT = FLOAT
+BYTEORDER_BIG = FALSE
+POSITION_XMIN = 0.0000000000
+POSITION_YMIN = 0.0000000000
+CELLCOUNT_X = 10
+CELLCOUNT_Y = 10
+CELLSIZE = 1.0000000000
+Z_FACTOR = 1.000000
+NODATA_VALUE = -99999.000000
+TOPTOBOTTOM = FALSE
diff --git a/src/scripting/python/test_data/test_ascii.asc b/src/scripting/python/test_data/test_ascii.asc
new file mode 100644
index 0000000..b304c83
--- /dev/null
+++ b/src/scripting/python/test_data/test_ascii.asc
@@ -0,0 +1,16 @@
+NCOLS 10
+NROWS 10
+XLLCORNER -0.5000000000
+YLLCORNER -0.5000000000
+CELLSIZE 1.000000
+NODATA_VALUE -99999.0000
+-99999.0000 -99999.0000 -99999.0000 525.6584 547.2307 547.2307 525.6584 -99999.0000 -99999.0000 -99999.0000
+-99999.0000 505.0252 569.8837 619.2114 646.4466 646.4466 619.2114 569.8837 505.0252 -99999.0000
+-99999.0000 569.8837 646.4466 708.4524 745.0490 745.0490 708.4524 646.4466 569.8837 -99999.0000
+525.6584 619.2114 708.4524 787.8680 841.8861 841.8861 787.8680 708.4524 619.2114 525.6584
+547.2307 646.4466 745.0490 841.8861 929.2893 929.2893 841.8861 745.0490 646.4466 547.2307
+547.2307 646.4466 745.0490 841.8861 929.2893 929.2893 841.8861 745.0490 646.4466 547.2307
+525.6584 619.2114 708.4524 787.8680 841.8861 841.8861 787.8680 708.4524 619.2114 525.6584
+-99999.0000 569.8837 646.4466 708.4524 745.0490 745.0490 708.4524 646.4466 569.8837 -99999.0000
+-99999.0000 505.0252 569.8837 619.2114 646.4466 646.4466 619.2114 569.8837 505.0252 -99999.0000
+-99999.0000 -99999.0000 -99999.0000 525.6584 547.2307 547.2307 525.6584 -99999.0000 -99999.0000 -99999.0000
diff --git a/src/scripting/python/test_data/test_pts.dbf b/src/scripting/python/test_data/test_pts.dbf
new file mode 100644
index 0000000..f3f5665
Binary files /dev/null and b/src/scripting/python/test_data/test_pts.dbf differ
diff --git a/src/scripting/python/test_data/test_pts.mshp b/src/scripting/python/test_data/test_pts.mshp
new file mode 100644
index 0000000..0165801
--- /dev/null
+++ b/src/scripting/python/test_data/test_pts.mshp
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<SAGA_METADATA>
+ <HISTORY>
+ <MODULE>Grid Values to Points</MODULE>
+ <OPTION type="boolean" id="NODATA" name="Exclude NoData Cells">TRUE</OPTION>
+ <OPTION type="choice" id="TYPE" name="Type">0</OPTION>
+ <DATA_LIST type="grid_list" id="GRIDS" name="Grids">
+ <DATA>
+ <MODULE>Grid Calculator</MODULE>
+ <OPTION type="text" id="FORMULA" name="Formula">(a+10)*100</OPTION>
+ <OPTION type="text" id="NAME" name="Name">Calculation [(a+10)*100]</OPTION>
+ <OPTION type="boolean" id="FNAME" name="Take Formula">TRUE</OPTION>
+ <OPTION type="boolean" id="USE_NODATA" name="Use NoData">FALSE</OPTION>
+ <DATA_LIST type="grid_list" id="GRIDS" name="Grids">
+ <DATA>
+ <MODULE>Geometric Figures</MODULE>
+ <OPTION type="integer" id="CELL_COUNT" name="Cell Count">10</OPTION>
+ <OPTION type="double" id="CELL_SIZE" name="Cell Size">1.000000</OPTION>
+ <OPTION type="choice" id="FIGURE" name="Figure">0</OPTION>
+ <OPTION type="double" id="PLANE" name="Direction of Plane [Degree]">22.500000</OPTION>
+ </DATA>
+ </DATA_LIST>
+ </DATA>
+ </DATA_LIST>
+ </HISTORY>
+ <SOURCE>
+ <FILE>/home/vw/devel/saga/trunk/saga-gis/src/scripting/python/test_data/test_pts.shp</FILE>
+ <DATABASE></DATABASE>
+ <PROJECTION></PROJECTION>
+ </SOURCE>
+</SAGA_METADATA>
diff --git a/src/scripting/python/test_data/test_pts.shp b/src/scripting/python/test_data/test_pts.shp
new file mode 100644
index 0000000..312c686
Binary files /dev/null and b/src/scripting/python/test_data/test_pts.shp differ
diff --git a/src/scripting/python/test_data/test_pts.shx b/src/scripting/python/test_data/test_pts.shx
new file mode 100644
index 0000000..e3764e0
Binary files /dev/null and b/src/scripting/python/test_data/test_pts.shx differ
diff --git a/src/scripting/python/test_data/test_pts_xyz.xyz b/src/scripting/python/test_data/test_pts_xyz.xyz
new file mode 100644
index 0000000..82d6bda
--- /dev/null
+++ b/src/scripting/python/test_data/test_pts_xyz.xyz
@@ -0,0 +1,81 @@
+X Y Z
+3.000000 0.000000 1.000000
+4.000000 0.000000 2.000000
+5.000000 0.000000 3.000000
+6.000000 0.000000 4.000000
+1.000000 1.000000 5.000000
+2.000000 1.000000 6.000000
+3.000000 1.000000 7.000000
+4.000000 1.000000 8.000000
+5.000000 1.000000 9.000000
+6.000000 1.000000 10.000000
+7.000000 1.000000 11.000000
+8.000000 1.000000 12.000000
+1.000000 2.000000 13.000000
+2.000000 2.000000 14.000000
+3.000000 2.000000 15.000000
+4.000000 2.000000 16.000000
+5.000000 2.000000 17.000000
+6.000000 2.000000 18.000000
+7.000000 2.000000 19.000000
+8.000000 2.000000 20.000000
+0.000000 3.000000 21.000000
+1.000000 3.000000 22.000000
+2.000000 3.000000 23.000000
+3.000000 3.000000 24.000000
+4.000000 3.000000 25.000000
+5.000000 3.000000 26.000000
+6.000000 3.000000 27.000000
+7.000000 3.000000 28.000000
+8.000000 3.000000 29.000000
+9.000000 3.000000 30.000000
+0.000000 4.000000 31.000000
+1.000000 4.000000 32.000000
+2.000000 4.000000 33.000000
+3.000000 4.000000 34.000000
+4.000000 4.000000 35.000000
+5.000000 4.000000 36.000000
+6.000000 4.000000 37.000000
+7.000000 4.000000 38.000000
+8.000000 4.000000 39.000000
+9.000000 4.000000 40.000000
+0.000000 5.000000 41.000000
+1.000000 5.000000 42.000000
+2.000000 5.000000 43.000000
+3.000000 5.000000 44.000000
+4.000000 5.000000 45.000000
+5.000000 5.000000 46.000000
+6.000000 5.000000 47.000000
+7.000000 5.000000 48.000000
+8.000000 5.000000 49.000000
+9.000000 5.000000 50.000000
+0.000000 6.000000 51.000000
+1.000000 6.000000 52.000000
+2.000000 6.000000 53.000000
+3.000000 6.000000 54.000000
+4.000000 6.000000 55.000000
+5.000000 6.000000 56.000000
+6.000000 6.000000 57.000000
+7.000000 6.000000 58.000000
+8.000000 6.000000 59.000000
+9.000000 6.000000 60.000000
+1.000000 7.000000 61.000000
+2.000000 7.000000 62.000000
+3.000000 7.000000 63.000000
+4.000000 7.000000 64.000000
+5.000000 7.000000 65.000000
+6.000000 7.000000 66.000000
+7.000000 7.000000 67.000000
+8.000000 7.000000 68.000000
+1.000000 8.000000 69.000000
+2.000000 8.000000 70.000000
+3.000000 8.000000 71.000000
+4.000000 8.000000 72.000000
+5.000000 8.000000 73.000000
+6.000000 8.000000 74.000000
+7.000000 8.000000 75.000000
+8.000000 8.000000 76.000000
+3.000000 9.000000 77.000000
+4.000000 9.000000 78.000000
+5.000000 9.000000 79.000000
+6.000000 9.000000 80.000000
diff --git a/src/scripting/toolchains/cluster_terrain.xml b/src/scripting/toolchains/cluster_terrain.xml
new file mode 100644
index 0000000..383f6b6
--- /dev/null
+++ b/src/scripting/toolchains/cluster_terrain.xml
@@ -0,0 +1,63 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<toolchain saga-version="2.1.3">
+ <group>terrain_analysis</group>
+ <identifier>TerrainCluster</identifier>
+ <name>Terrain Clustering</name>
+ <author>O.Conrad (c) 2014</author>
+ <description>created from history</description>
+ <menu>Terrain Classification</menu>
+ <parameters>
+ <option varname="GRID_SYSTEM" type="grid_system">
+ <name>Grid System</name>
+ </option>
+ <input varname="ELEVATION" type="grid" parent="GRID_SYSTEM">
+ <name>Elevation</name>
+ </input>
+ <output varname="CLUSTER" type="grid" parent="GRID_SYSTEM">
+ <name>Clusters</name>
+ </output>
+ <option varname="NCLUSTER" type="integer">
+ <name>Number of Terrain Classes</name>
+ <value>5</value>
+ </option>
+ <option varname="MAXITER" type="integer">
+ <name>Maximum Iterations</name>
+ <value>25</value>
+ </option>
+ </parameters>
+ <tools>
+ <tool library="ta_morphometry" module="14" name="Relative Heights and Slope Positions">
+ <input id="DEM">ELEVATION</input>
+ <output id="NH">NORMHEIGHT</output>
+ </tool>
+ <tool id="tool_06" library="ta_lighting" module="5" name="Topographic Openness">
+ <output id="NEG">OPEN_NEG</output>
+ <output id="POS">OPEN_POS</output>
+ <option id="RADIUS">10000.000000</option>
+ <option id="METHOD">1</option>
+ <option id="DLEVEL">3.000000</option>
+ <option id="NDIRS">8</option>
+ <input id="DEM">ELEVATION</input>
+ </tool>
+ <tool id="tool_04" library="ta_morphometry" module="0" name="Slope, Aspect, Curvature">
+ <output id="SLOPE">SLOPE</output>
+ <output id="C_TANG">C_TANG</output>
+ <output id="C_LONG">C_LONG</output>
+ <option id="UNIT_SLOPE">0</option>
+ <input id="ELEVATION">ELEVATION</input>
+ </tool>
+ <tool id="cluster" library="imagery_classification" module="1" name="Cluster Analysis for Grids">
+ <output id="CLUSTER">CLUSTER</output>
+ <option id="METHOD">1</option>
+ <option id="NCLUSTER" varname="true">NCLUSTER</option>
+ <option id="MAXITER" varname="true">MAXITER</option>
+ <option id="NORMALISE">1</option>
+ <input id="GRIDS">NORMHEIGHT</input>
+ <input id="GRIDS">SLOPE</input>
+ <input id="GRIDS">C_TANG</input>
+ <input id="GRIDS">C_LONG</input>
+ <input id="GRIDS">OPEN_POS</input>
+ <input id="GRIDS">OPEN_NEG</input>
+ </tool>
+ </tools>
+</toolchain>
diff --git a/src/scripting/toolchains/gridding.xml b/src/scripting/toolchains/gridding.xml
new file mode 100644
index 0000000..a602f2f
--- /dev/null
+++ b/src/scripting/toolchains/gridding.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<toolchain saga-version="2.1.3">
+ <group></group>
+ <identifier>gridding</identifier>
+ <name>Gridding of Points</name>
+ <author>O.Conrad (c) 2014</author>
+ <menu absolute="true">Garden|Tool Chain Examples</menu>
+ <description>
+ This tool chain simply demonstrates how to create an output grid without having to choose a target grid system before execution by setting the output parameter's <i>"target"</i> attribute to <i>"none"</i>.
+ </description>
+ <parameters>
+ <input varname="POINTS" type="shapes">
+ <name>Points</name>
+ </input>
+ <option varname="ATTRIBUTE" type="table_field" parent="POINTS">
+ <name>Attribute</name>
+ <description>attribute to become interpolated</description>
+ </option>
+ <option varname="CELL_SIZE" type="double">
+ <name>Cell Size</name>
+ <description>cell size of target grid</description>
+ <value>10.0</value>
+ </option>
+ <output varname="INTERPOLATION" type="grid" target="none">
+ <name>Interpolation</name>
+ </output>
+ </parameters>
+ <tools>
+ <tool library="grid_spline" module="4" name="Multilevel B-Spline Interpolation">
+ <input id="SHAPES">POINTS</input>
+ <option id="FIELD" varname="true">ATTRIBUTE</option>
+ <option id="TARGET_USER_SIZE" varname="true">CELL_SIZE</option>
+ <output id="TARGET_OUT_GRID">INTERPOLATION</output>
+ </tool>
+ </tools>
+</toolchain>
diff --git a/src/scripting/toolchains/imagery_lczc.xml b/src/scripting/toolchains/imagery_lczc.xml
new file mode 100644
index 0000000..84727ac
--- /dev/null
+++ b/src/scripting/toolchains/imagery_lczc.xml
@@ -0,0 +1,134 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<toolchain saga-version="2.2.0">
+ <group>toolchains</group>
+ <identifier>lczc</identifier>
+ <menu absolute="true">Imagery|Classification</menu>
+ <name>Local Climate Zone Classification</name>
+ <author>B. Bechtel, O. Conrad (c) 2015</author>
+ <description>
+ Reference:
+ Bechtel, B., Alexander, P. J., Böhner, J., Ching, J., Conrad, O., Feddema, J., Gerald, M., See, L., Stewart, I. (2015). Mapping local climate zones for a worldwide database of the form and function of cities. ISPRS International Journal of Geo-Information, 4(1), 199-219. doi:10.3390/ijgi4010199.
+ </description>
+
+ <parameters>
+ <option varname="GRID_SYSTEM" type="grid_system">
+ <name>Grid System</name>
+ </option>
+ <option varname="FILE_TRAINING" type="file">
+ <name>Training Areas</name>
+ <filter>KML/KMZ Files|*.kml;*.kmz|All Files|*.*</filter>
+ </option>
+ <option varname="RF_TREE_COUNT" type="integer">
+ <name>Random Forest Tree Count</name>
+ <value min="1">32</value>
+ <description>How many trees to create?</description>
+ </option>
+ <option varname="FILTER_RADIUS" type="integer">
+ <condition type="exists">LCZC_FILTERED</condition>
+ <name>Majority Filter Radius</name>
+ <value min="1">2</value>
+ </option>
+ <option varname="FILE_CLASS_DEF" type="file">
+ <name>Class Definition File</name>
+ <filter>Table Files|*.txt;*.dbf;*csv|All Files|*.*</filter>
+ </option>
+ <option varname="FILE_LCZC" type="file" save="true">
+ <name>Save LCZC as...</name>
+ <value></value>
+ <filter>KMZ Files|*.kmz|All Files|*.*</filter>
+ </option>
+ <option varname="FILE_LCZC_FILTERED" type="file" save="true">
+ <condition type="exists">LCZC_FILTERED</condition>
+ <name>Save LCZC (Filtered) as...</name>
+ <value></value>
+ <filter>KMZ Files|*.kmz|All Files|*.*</filter>
+ </option>
+ <input varname="FEATURES" type="grid_list" parent="GRID_SYSTEM">
+ <name>Features</name>
+ </input>
+ <output varname="LCZC" type="grid" parent="GRID_SYSTEM">
+ <name>LCZC</name>
+ </output>
+ <output varname="LCZC_FILTERED" type="grid" optional="true" parent="GRID_SYSTEM">
+ <name>LCZC (Filtered)</name>
+ </output>
+ </parameters>
+
+ <tools>
+ <tool library="io_gdal" module="3" name="OGR: Import Vector Data">
+ <output id="SHAPES">TRAINING_SINGLE</output>
+ <option id="FILES" varname="true">FILE_TRAINING</option>
+ <option id="GEOM_TYPE">9</option>
+ </tool>
+ <tool library="shapes_tools" module="2" name="Merge Layers">
+ <input id="INPUT">TRAINING_SINGLE</input>
+ <option id="SRCINFO">TRUE</option>
+ <option id="MATCH">TRUE</option>
+ <output id="MERGED">TRAINING_MERGED</output>
+ </tool>
+ <tool library="grid_tools" module="32" name="Select Grid from List">
+ <input id="GRIDS">FEATURES</input>
+ <output id="GRID">FEATURE</output>
+ <option id="INDEX">0</option>
+ </tool>
+ <tool library="pj_proj4" module="2" name="Coordinate Transformation (Shapes)">
+ <input id="PICK" parms="CRS_GRID">FEATURE</input>
+ <input id="SOURCE">TRAINING_MERGED</input>
+ <output id="TARGET">TRAINING_PROJ</output>
+ </tool>
+ <tool library="imagery_vigra" module="9" name="Random Forest Classification (ViGrA)">
+ <input id="FEATURES">FEATURES</input>
+ <input id="TRAINING">TRAINING_PROJ</input>
+ <option id="FIELD">Source</option>
+ <option id="LABEL_AS_ID">TRUE</option>
+ <option id="DO_MRMR">FALSE</option>
+ <option id="RF_TREE_COUNT" varname="true">RF_TREE_COUNT</option>
+ <option id="RF_TREE_SAMPLES">1.000000</option>
+ <output id="CLASSES">LCZC</output>
+ </tool>
+
+ <condition type="not_equal" value="" variable="FILE_CLASS_DEF">
+ <tool library="io_table" module="1" name="Import Text Table">
+ <option id="FILENAME" varname="true">FILE_CLASS_DEF</option>
+ <output id="TABLE">CLASS_DEF</output>
+ </tool>
+ <tool library="grid_visualisation" module="10" name="Select Look-up Table for Grid Visualization">
+ <input id="GRID">LCZC</input>
+ <input id="LUT">CLASS_DEF</input>
+ </tool>
+ </condition>
+
+ <condition type="not_equal" value="" variable="FILE_LCZC">
+ <tool library="io_grid_image" module="2" name="Export Grid to KML">
+ <input id="GRID">LCZC</input>
+ <input id="LUT">CLASS_DEF</input>
+ <option id="FILE" varname="true">FILE_LCZC</option>
+ <option id="COLOURING">3</option>
+ <option id="INTERPOL">false</option>
+ <option id="OUTPUT">2</option>
+ </tool>
+ </condition>
+
+ <condition type="exists" variable="LCZC_FILTERED">
+ <tool library="grid_filter" module="6" name="Majority Filter">
+ <input id="INPUT">LCZC</input>
+ <option id="RADIUS" varname="true">FILTER_RADIUS</option>
+ <output id="RESULT">LCZC_FILTERED</output>
+ </tool>
+ <tool library="grid_visualisation" module="10" name="Select Look-up Table for Grid Visualization">
+ <input id="GRID">LCZC_FILTERED</input>
+ <input id="LUT">CLASS_DEF</input>
+ </tool>
+ <condition type="not_equal" value="" variable="FILE_LCZC_FILTERED">
+ <tool library="io_grid_image" module="2" name="Export Grid to KML">
+ <input id="GRID">LCZC_FILTERED</input>
+ <input id="LUT">CLASS_DEF</input>
+ <option id="FILE" varname="true">FILE_LCZC_FILTERED</option>
+ <option id="COLOURING">3</option>
+ <option id="INTERPOL">false</option>
+ <option id="OUTPUT">2</option>
+ </tool>
+ </condition>
+ </condition>
+ </tools>
+</toolchain>
diff --git a/src/scripting/toolchains/obia.xml b/src/scripting/toolchains/obia.xml
new file mode 100644
index 0000000..39ee208
--- /dev/null
+++ b/src/scripting/toolchains/obia.xml
@@ -0,0 +1,113 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<toolchain saga-version="2.1.3">
+ <group></group>
+ <identifier>obia</identifier>
+ <name>Object Based Image Segmentation</name>
+ <author>O.Conrad (c) 2014</author>
+ <description>created from history</description>
+ <menu absolute="true">Imagery|Segmentation</menu>
+ <parameters>
+ <option varname="GRID_SYSTEM" type="grid_system">
+ <name>Grid System</name>
+ </option>
+ <input varname="FEATURES" type="grid_list" parent="GRID_SYSTEM">
+ <name>Features</name>
+ </input>
+ <output varname="OBJECTS" type="shapes">
+ <name>Objects</name>
+ </output>
+ <option varname="SEEDS_BAND_WIDTH" type="double">
+ <name>Band Width</name>
+ <description>increase band width to get less seed points</description>
+ <value>2</value>
+ </option>
+ <option varname="MAJORITY_RADIUS" type="integer">
+ <name>Generalization</name>
+ <description>majority filter radius</description>
+ <value>1</value>
+ </option>
+ <option varname="NCLUSTER" type="integer">
+ <name>Number of Clusters</name>
+ <description>number of clusters</description>
+ <value>12</value>
+ </option>
+ <option varname="NORMALIZE" type="boolean">
+ <name>Normalize</name>
+ <description>number of clusters</description>
+ <value>false</value>
+ </option>
+ </parameters>
+ <tools>
+ <tool library="imagery_segmentation" module="2" name="Seed Generation">
+ <option id="SEED_TYPE">0</option>
+ <option id="METHOD">0</option>
+ <option id="BAND_WIDTH" varname="1">SEEDS_BAND_WIDTH</option>
+ <option id="NORMALIZE" varname="true">NORMALIZE</option>
+ <input id="FEATURES">FEATURES</input>
+ <output id="SEED_GRID">SEED_GRID</output>
+ </tool>
+ <tool library="imagery_segmentation" module="3" name="Simple Region Growing">
+ <output id="SEGMENTS">SEGMENTS_GRID</output>
+ <option id="NORMALIZE" varname="true">NORMALIZE</option>
+ <option id="NEIGHBOUR">1</option>
+ <option id="METHOD">0</option>
+ <option id="SIG_1">1.000000</option>
+ <option id="SIG_2">1.000000</option>
+ <option id="THRESHOLD">0.000000</option>
+ <option id="REFRESH">FALSE</option>
+ <option id="LEAFSIZE">256</option>
+ <input id="SEEDS">SEED_GRID</input>
+ <input id="FEATURES">FEATURES</input>
+ </tool>
+ <tool library="grid_filter" module="6" name="Majority Filter">
+ <option id="MODE">1</option>
+ <option id="THRESHOLD">0.000000</option>
+ <option id="RADIUS" varname="1">MAJORITY_RADIUS</option>
+ <input id="INPUT">SEGMENTS_GRID</input>
+ <output id="RESULT">SEGMENTS_GRID_B</output>
+ </tool>
+ <tool library="shapes_grid" module="6" name="Vectorising Grid Classes">
+ <output id="POLYGONS">SEGMENTS</output>
+ <option id="CLASS_ALL">1</option>
+ <option id="CLASS_ID">1.000000</option>
+ <option id="SPLIT">0</option>
+ <option id="ALLVERTICES">FALSE</option>
+ <input id="GRID">SEGMENTS_GRID_B</input>
+ </tool>
+ <tool library="shapes_grid" module="2" name="Grid Statistics for Polygons">
+ <output id="RESULT">CLUSTERS</output>
+ <option id="METHOD">0</option>
+ <option id="NAMING">1</option>
+ <option id="COUNT">FALSE</option>
+ <option id="MIN">FALSE</option>
+ <option id="MAX">FALSE</option>
+ <option id="RANGE">FALSE</option>
+ <option id="SUM">FALSE</option>
+ <option id="MEAN">TRUE</option>
+ <option id="VAR">FALSE</option>
+ <option id="STDDEV">FALSE</option>
+ <option id="QUANTILE">0</option>
+ <input id="GRIDS">FEATURES</input>
+ <input id="POLYGONS">SEGMENTS</input>
+ </tool>
+ <tool library="table_calculus" module="14" name="Cluster Analysis">
+ <option id="FIELDS">3,4,5,6,7,8,9,10,11,12,13,14</option>
+ <option id="METHOD">1</option>
+ <option id="NCLUSTER" varname="1">NCLUSTER</option>
+ <option id="NORMALISE">FALSE</option>
+ <input id="INPUT">CLUSTERS</input>
+ </tool>
+ <tool library="shapes_polygons" module="5" name="Polygon Dissolve">
+ <output id="DISSOLVED">DISSOLVED</output>
+ <option id="FIELD_1">CLUSTER</option>
+ <option id="BND_KEEP">FALSE</option>
+ <option id="STAT_FIELDS"><no attributes></option>
+ <input id="POLYGONS">CLUSTERS</input>
+ </tool>
+ <tool library="shapes_polygons" module="10" name="Polygon Parts to Separate Polygons">
+ <output id="PARTS">OBJECTS</output>
+ <option id="LAKES">FALSE</option>
+ <input id="POLYGONS">DISSOLVED</input>
+ </tool>
+ </tools>
+</toolchain>
diff --git a/src/scripting/toolchains/points_to_contour.xml b/src/scripting/toolchains/points_to_contour.xml
new file mode 100644
index 0000000..1c9ace0
--- /dev/null
+++ b/src/scripting/toolchains/points_to_contour.xml
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<toolchain saga-version="2.1.3">
+ <group></group>
+ <identifier>PointsToContour</identifier>
+ <name>Contour Lines from Points</name>
+ <author>O.Conrad (c) 2014</author>
+ <description>created from history</description>
+ <menu absolute="true">Shapes|Points</menu>
+ <parameters>
+ <input varname="SHAPES" type="shapes">
+ <name>Points</name>
+ </input>
+ <output varname="CONTOUR" type="shapes">
+ <name>Contour Lines</name>
+ </output>
+ <option varname="ATTRIBUTE" type="table_field" parent="SHAPES">
+ <name>Attribute</name>
+ <description>attribute to become interpolated</description>
+ </option>
+ <option varname="CELL_SIZE" type="double">
+ <name>Precision</name>
+ <description>this is the internal grid cell size determining the precision of contours</description>
+ <value>10.0</value>
+ </option>
+ <option varname="ZSTEP" type="double">
+ <name>Equidistance</name>
+ <value>10.0</value>
+ </option>
+ </parameters>
+ <tools>
+ <tool library="grid_spline" module="4" name="Multilevel B-Spline Interpolation">
+ <option id="FIELD" varname="1">ATTRIBUTE</option>
+ <option id="METHOD">1</option>
+ <option id="EPSILON">0.000100</option>
+ <option id="LEVEL_MAX">11</option>
+ <input id="SHAPES">SHAPES</input>
+ <option id="TARGET_USER_SIZE" varname="1">CELL_SIZE</option>
+ <output id="TARGET_OUT_GRID">INTERPOLATION</output>
+ </tool>
+ <tool library="shapes_grid" module="5" name="Contour Lines from Grid">
+ <option id="ZSTEP" varname="1">ZSTEP</option>
+ <option id="ZMIN">0.000000</option>
+ <option id="ZMAX">10000.000000</option>
+ <input id="GRID">INTERPOLATION</input>
+ <output id="CONTOUR">CONTOUR</output>
+ </tool>
+ </tools>
+</toolchain>
diff --git a/src/scripting/toolchains/sieve_and_clump.xml b/src/scripting/toolchains/sieve_and_clump.xml
new file mode 100644
index 0000000..f88cc49
--- /dev/null
+++ b/src/scripting/toolchains/sieve_and_clump.xml
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<toolchain saga-version="2.1.3">
+ <group></group>
+ <identifier>SieveAndClump</identifier>
+ <name>Sieve and Clump</name>
+ <author>O.Conrad (c) 2014</author>
+ <description>created from history</description>
+ <menu absolute="true">Grid|Filter</menu>
+ <parameters>
+ <option varname="GRID_SYSTEM" type="grid_system">
+ <name>Grid System</name>
+ </option>
+ <input varname="CLASSES" type="grid" parent="GRID_SYSTEM">
+ <name>Classes</name>
+ </input>
+ <output varname="FILTERED" type="grid" parent="GRID_SYSTEM">
+ <name>Sieve and Clump</name>
+ </output>
+ <option varname="SIEVE" type="integer">
+ <name>Sieving Threshold</name>
+ <value>2</value>
+ </option>
+ <option varname="EXPAND" type="integer">
+ <name>Maximum Expansion Distance</name>
+ <value>4</value>
+ </option>
+ </parameters>
+ <tools>
+ <tool library="grid_filter" module="15" name="Sieving Classes">
+ <option id="MODE">1</option>
+ <option id="ALL">1</option>
+ <option id="THRESHOLD" varname="1">SIEVE</option>
+ <output id="OUTPUT">SIEVED</output>
+ <input id="INPUT">CLASSES</input>
+ </tool>
+ <tool library="grid_tools" module="28" name="Shrink and Expand">
+ <option id="OPERATION">3</option>
+ <option id="CIRCLE">1</option>
+ <option id="EXPAND">3</option>
+ <option id="RADIUS" varname="1">EXPAND</option>
+ <output id="RESULT">FILTERED</output>
+ <input id="INPUT">SIEVED</input>
+ </tool>
+ </tools>
+</toolchain>
diff --git a/src/scripting/toolchains/temperature_downscaling.xml b/src/scripting/toolchains/temperature_downscaling.xml
new file mode 100644
index 0000000..bd70f0a
--- /dev/null
+++ b/src/scripting/toolchains/temperature_downscaling.xml
@@ -0,0 +1,92 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<toolchain saga-version="2.2.0">
+ <group>climate</group>
+ <identifier>t_downscale</identifier>
+ <menu absolute="true">Climate|Tools</menu>
+ <name>Lapse Rate Based Temperature Downscaling</name>
+ <author>Conrad (c) 2015</author>
+ <description>
+ The lapse rate based temperature downscaling is quite simple but
+ might perform well for mountainous regions, where a the altitudinal
+ gradient is the main driver for local temperature variation.
+ First, a given lapse rate is used to estimate a sea level temperature from
+ elevations and temperatures at a coarse resolution. Second, the same
+ lapse rate is used to estimate the terrain surface temperature using higher
+ resoluted elevation data with the spline interpolated sea level temperatures
+ from the previous step.
+ </description>
+
+ <parameters>
+ <option varname="LORES_GRID_SYSTEM" type="grid_system">
+ <name>Coarse Resolution</name>
+ </option>
+ <input varname="LORES_DEM" type="grid" parent="LORES_GRID_SYSTEM">
+ <name>Elevation</name>
+ </input>
+ <input varname="LORES_T" type="grid" parent="LORES_GRID_SYSTEM">
+ <name>Temperature</name>
+ </input>
+ <input varname="LAPSE_RATES" type="grid" parent="LORES_GRID_SYSTEM" optional="true">
+ <name>Lapse Rate</name>
+ <description>lapse rate in degree of temperature per 100 meter</description>
+ </input>
+ <output varname="LORES_SLT" type="grid" parent="LORES_GRID_SYSTEM" optional="true">
+ <name>Temperature at Sea Level</name>
+ </output>
+
+ <option varname="HIRES_GRID_SYSTEM" type="grid_system">
+ <name>High Resolution</name>
+ </option>
+ <input varname="HIRES_DEM" type="grid" parent="HIRES_GRID_SYSTEM">
+ <name>Elevation</name>
+ </input>
+ <output varname="HIRES_T" type="grid" parent="HIRES_GRID_SYSTEM">
+ <name>Temperature</name>
+ </output>
+
+ <option varname="LAPSE_RATE" type="double">
+ <name>Lapse Rate</name>
+ <value min="0.0">0.6</value>
+ <description>lapse rate in degree of temperature per 100 meter</description>
+ <condition type="not_exists">LAPSE_RATES</condition>
+ </option>
+ </parameters>
+
+ <tools>
+ <condition type="exists" varname="LAPSE_RATES">
+ <tool library="grid_calculus" module="1" name="Grid Calculator">
+ <input id="GRIDS">LORES_DEM</input>
+ <input id="GRIDS">LORES_T</input>
+ <input id="GRIDS">LAPSE_RATES</input>
+ <output id="RESULT">LORES_SLT</output>
+ <option id="FORMULA">g2 + g1 * g3 / 100</option>
+ <option id="NAME">Temperature at Sea Level</option>
+ </tool>
+ <tool library="grid_calculus" module="1" name="Grid Calculator">
+ <input id="GRIDS">HIRES_DEM</input>
+ <input id="XGRIDS">LORES_SLT</input>
+ <input id="XGRIDS">LAPSE_RATES</input>
+ <output id="RESULT">HIRES_T</output>
+ <option id="FORMULA">h1 - g1 * h2 / 100</option>
+ <option id="NAME">Temperature</option>
+ </tool>
+ </condition>
+
+ <condition type="not_exists" varname="LAPSE_RATES">
+ <tool library="grid_calculus" module="1" name="Grid Calculator">
+ <input id="GRIDS">LORES_DEM</input>
+ <input id="GRIDS">LORES_T</input>
+ <output id="RESULT">LORES_SLT</output>
+ <option id="FORMULA">g2 + g1 * $(LAPSE_RATE) / 100</option>
+ <option id="NAME">Temperature at Sea Level</option>
+ </tool>
+ <tool library="grid_calculus" module="1" name="Grid Calculator">
+ <input id="GRIDS">HIRES_DEM</input>
+ <input id="XGRIDS">LORES_SLT</input>
+ <output id="RESULT">HIRES_T</output>
+ <option id="FORMULA">h1 - g1 * $(LAPSE_RATE) / 100</option>
+ <option id="NAME">Temperature</option>
+ </tool>
+ </condition>
+ </tools>
+</toolchain>
diff --git a/src/scripting/toolchains/terrain_analysis.xml b/src/scripting/toolchains/terrain_analysis.xml
new file mode 100644
index 0000000..be409fb
--- /dev/null
+++ b/src/scripting/toolchains/terrain_analysis.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<toolchains version="1.0.0">
+ <group>terrain_analysis</group>
+ <identifier>terrain_analysis</identifier>
+ <name>Terrain Analysis</name>
+ <description>Tool chains dedicated to terrain analysis.</description>
+ <menu>Terrain Analysis</menu>
+</toolchains>
diff --git a/src/scripting/toolchains/terrain_segmentation.xml b/src/scripting/toolchains/terrain_segmentation.xml
new file mode 100644
index 0000000..8b93260
--- /dev/null
+++ b/src/scripting/toolchains/terrain_segmentation.xml
@@ -0,0 +1,148 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<toolchain saga-version="2.1.3">
+ <group>terrain_analysis</group>
+ <identifier>ReliefSegmentation</identifier>
+ <name>Relief Segmentation</name>
+ <description>created from history</description>
+ <menu>Terrain Classification</menu>
+ <parameters>
+ <option id="GRID_SYSTEM" type="grid_system">
+ <name>Grid System</name>
+ </option>
+ <input varname="ELEVATION" type="grid" parent="GRID_SYSTEM">
+ <name>Elevation</name>
+ </input>
+ <output varname="OBJECTS" type="shapes">
+ <name>Objects</name>
+ </output>
+ <option varname="TPI_RADIUS" type="range">
+ <name>Position Index Radius</name>
+ <description>position index radius in map units</description>
+ <value>100;1000</value>
+ </option>
+ <option varname="BAND_WIDTH" type="double">
+ <name>Band Width</name>
+ <description>increase band width to get less seed points</description>
+ <value>2</value>
+ </option>
+ <option varname="NCLUSTER" type="integer">
+ <name>Number of Clusters</name>
+ <description>number of clusters</description>
+ <value>10</value>
+ </option>
+ </parameters>
+ <tools>
+ <tool library="ta_lighting" module="5" name="Topographic Openness">
+ <output id="NEG">OPEN_NEG</output>
+ <output id="POS">OPEN_POS</output>
+ <option id="RADIUS">10000.000000</option>
+ <option id="METHOD">1</option>
+ <option id="DLEVEL">3.000000</option>
+ <option id="NDIRS">8</option>
+ <input id="DEM">ELEVATION</input>
+ </tool>
+ <tool library="ta_morphometry" module="0" name="Slope, Aspect, Curvature">
+ <output id="SLOPE">SLOPE</output>
+ <option id="UNIT_SLOPE">0</option>
+ <input id="ELEVATION">ELEVATION</input>
+ </tool>
+ <tool library="ta_morphometry" module="18" name="Topographic Position Index (TPI)">
+ <input id="DEM">ELEVATION</input>
+ <output id="TPI">TPI</output>
+ <option id="STANDARD">no</option>
+ <option id="RADIUS">[0.000000] - [1000.000000]</option>
+ <option id="DW_WEIGHTING">0</option>
+ </tool>
+ <tool library="ta_hydrology" module="15" name="SAGA Wetness Index">
+ <input id="DEM">ELEVATION</input>
+ <output id="AREA"></output>
+ <output id="SLOPE"></output>
+ <output id="AREA_MOD"></output>
+ <output id="TWI">TWI</output>
+ <option id="SUCTION">10.000000</option>
+ <option id="AREA_TYPE">2</option>
+ <option id="SLOPE_TYPE">0</option>
+ <option id="SLOPE_MIN">0.000000</option>
+ <option id="SLOPE_OFF">0.100000</option>
+ <option id="SLOPE_WEIGHT">1.000000</option>
+ </tool>
+
+ <tool library="statistics_grid" module="8" name="Principle Components Analysis">
+ <input id="GRIDS">ELEVATION</input>
+ <input id="GRIDS">TWI</input>
+ <input id="GRIDS">SLOPE</input>
+ <input id="GRIDS">TPI</input>
+ <input id="GRIDS">OPEN_POS</input>
+ <input id="GRIDS">OPEN_NEG</input>
+ <output id="PCA">FEATURES</output>
+ <option id="METHOD">1</option>
+ <option id="NFIRST">4</option>
+ </tool>
+
+ <tool library="imagery_segmentation" module="2" name="Seed Generation">
+ <output id="SEED_GRID">SEED_GRID</output>
+ <option id="SEED_TYPE">0</option>
+ <option id="METHOD">0</option>
+ <option id="BAND_WIDTH" varname="true">BAND_WIDTH</option>
+ <option id="NORMALIZE">TRUE</option>
+ <input id="FEATURES">FEATURES</input>
+ </tool>
+ <tool library="imagery_segmentation" module="3" name="Simple Region Growing">
+ <output id="SEGMENTS">SEGMENTS_GRID</output>
+ <option id="NORMALIZE">TRUE</option>
+ <option id="NEIGHBOUR">1</option>
+ <option id="METHOD">1</option>
+ <option id="SIG_1">1.000000</option>
+ <option id="SIG_2">1.000000</option>
+ <option id="THRESHOLD">0.000000</option>
+ <option id="REFRESH">FALSE</option>
+ <option id="LEAFSIZE">256</option>
+ <input id="SEEDS">SEED_GRID</input>
+ <input id="FEATURES">FEATURES</input>
+ </tool>
+
+ <tool library="shapes_grid" module="6" name="Vectorising Grid Classes">
+ <output id="POLYGONS">SEGMENTS</output>
+ <option id="CLASS_ALL">1</option>
+ <option id="CLASS_ID">1.000000</option>
+ <option id="SPLIT">0</option>
+ <option id="ALLVERTICES">FALSE</option>
+ <input id="GRID">SEGMENTS_GRID</input>
+ </tool>
+ <tool library="shapes_grid" module="2" name="Grid Statistics for Polygons">
+ <output id="RESULT">CLUSTERS</output>
+ <option id="METHOD">0</option>
+ <option id="NAMING">1</option>
+ <option id="COUNT">FALSE</option>
+ <option id="MIN">FALSE</option>
+ <option id="MAX">FALSE</option>
+ <option id="RANGE">FALSE</option>
+ <option id="SUM">FALSE</option>
+ <option id="MEAN">TRUE</option>
+ <option id="VAR">FALSE</option>
+ <option id="STDDEV">FALSE</option>
+ <option id="QUANTILE">0</option>
+ <input id="GRIDS">FEATURES</input>
+ <input id="POLYGONS">SEGMENTS</input>
+ </tool>
+ <tool library="table_calculus" module="14" name="Cluster Analysis">
+ <option id="FIELDS">3,4,5,6,7,8,9,10,11,12,13,14</option>
+ <option id="METHOD">1</option>
+ <option id="NCLUSTER" varname="true">NCLUSTER</option>
+ <option id="NORMALISE">TRUE</option>
+ <input id="INPUT">CLUSTERS</input>
+ </tool>
+ <tool library="shapes_polygons" module="5" name="Polygon Dissolve">
+ <output id="DISSOLVED">DISSOLVED</output>
+ <option id="FIELD_1">CLUSTER</option>
+ <option id="BND_KEEP">FALSE</option>
+ <option id="STAT_FIELDS"><no attributes></option>
+ <input id="POLYGONS">CLUSTERS</input>
+ </tool>
+ <tool library="shapes_polygons" module="10" name="Polygon Parts to Separate Polygons">
+ <output id="PARTS">OBJECTS</output>
+ <option id="LAKES">FALSE</option>
+ <input id="POLYGONS">DISSOLVED</input>
+ </tool>
+ </tools>
+</toolchain>
diff --git a/src/scripting/toolchains/twi.xml b/src/scripting/toolchains/twi.xml
new file mode 100644
index 0000000..1b623c2
--- /dev/null
+++ b/src/scripting/toolchains/twi.xml
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<toolchain saga-version="2.1.3">
+ <group>terrain_analysis</group>
+ <identifier>twi</identifier>
+ <name>Topographic Wetness Index (One Step)</name>
+ <author>O.Conrad (c) 2014</author>
+ <description>created from history</description>
+ <menu>Hydrology|Topographic Indices</menu>
+ <parameters>
+ <option varname="GRID_SYSTEM" type="grid_system">
+ <name>Grid System</name>
+ </option>
+ <input varname="DEM" type="grid" parent="GRID_SYSTEM">
+ <name>Elevation</name>
+ </input>
+ <output varname="TWI" type="grid" parent="GRID_SYSTEM">
+ <name>Topographic Wetness Index</name>
+ </output>
+ <option varname="FLOW_METHOD" type="choice">
+ <name>Flow Distribution</name>
+ <choices>Deterministic 8|Rho 8|Braunschweiger Reliefmodell|Deterministic Infinity|Multiple Flow Direction|Multiple Triangular Flow Direction|Multiple Maximum Downslope Gradient Based Flow Direction|</choices>
+ <value>4</value>
+ </option>
+ </parameters>
+ <tools>
+ <tool library="ta_preprocessor" module="2" name="Sink Removal">
+ <input id="DEM">DEM</input>
+ <output id="DEM_PREPROC">DEM_PREPROC</output>
+ </tool>
+ <tool library="ta_hydrology" module="0" name="Catchment Area (Top-Down)">
+ <input id="ELEVATION">DEM_PREPROC</input>
+ <output id="CAREA">CAREA</output>
+ <option id="METHOD" varname="true">FLOW_METHOD</option>
+ </tool>
+ <tool library="ta_hydrology" module="19" name="Flow Width and Specific Catchment Area">
+ <input id="DEM">DEM_PREPROC</input>
+ <input id="TCA">CAREA</input>
+ <output id="SCA">SCA</output>
+ <option id="METHOD">2</option>
+ </tool>
+ <tool library="ta_morphometry" module="0" name="Slope, Aspect, Curvature">
+ <input id="ELEVATION">DEM_PREPROC</input>
+ <output id="SLOPE">SLOPE</output>
+ <option id="METHOD">6</option>
+ </tool>
+ <tool library="ta_hydrology" module="20" name="Topographic Wetness Index (TWI)">
+ <input id="SLOPE">SLOPE</input>
+ <input id="AREA">SCA</input>
+ <output id="TWI">TWI</output>
+ <option id="CONV">0</option>
+ <option id="METHOD">0</option>
+ </tool>
+ </tools>
+</toolchain>
diff --git a/src/scripting/toolchains/upslope_height.xml b/src/scripting/toolchains/upslope_height.xml
new file mode 100644
index 0000000..a0dde0b
--- /dev/null
+++ b/src/scripting/toolchains/upslope_height.xml
@@ -0,0 +1,104 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<toolchain saga-version="2.1.3">
+ <group>terrain_analysis</group>
+ <identifier>upslope_height</identifier>
+ <name>Upslope Height, Slope, Aspect</name>
+ <description>
+ This tool calculates the mean height, mean slope and mean aspect of the upslope contributing area.
+ </description>
+ <menu>Hydrology|Flow Accumulation</menu>
+ <parameters>
+ <option varname="GRID_SYSTEM" type="grid_system">
+ <name>Grid System</name>
+ </option>
+ <input varname="DEM" type="grid" parent="GRID_SYSTEM">
+ <name>Elevation</name>
+ </input>
+ <output varname="HEIGHT" type="grid" parent="GRID_SYSTEM">
+ <name>Upslope Height</name>
+ <output_name>Height [Mean of Upslope Area]</output_name>
+ <colours>11</colours>
+ </output>
+ <output varname="SLOPE" type="grid" parent="GRID_SYSTEM">
+ <name>Slope</name>
+ <output_name>Slope [Mean of Upslope Area]</output_name>
+ <colours>9</colours>
+ </output>
+ <output varname="ASPECT" type="grid" parent="GRID_SYSTEM">
+ <name>Aspect</name>
+ <output_name>Aspect [Mean of Upslope Area]</output_name>
+ <colours>26</colours>
+ </output>
+ <option varname="FLOW_METHOD" type="choice">
+ <name>Flow Distribution</name>
+ <choices>Deterministic 8|Rho 8|Braunschweiger Reliefmodell|Deterministic Infinity|Multiple Flow Direction|Multiple Triangular Flow Direction|Multiple Maximum Downslope Gradient Based Flow Direction|</choices>
+ <value>4</value>
+ </option>
+ </parameters>
+ <tools>
+ <tool library="ta_preprocessor" module="2" name="Sink Removal">
+ <input id="DEM">DEM</input>
+ <output id="DEM_PREPROC">DEM_PREPROC</output>
+ <option id="METHOD">1</option>
+ </tool>
+
+ <tool id="tool_02" library="ta_hydrology" module="0" name="Catchment Area (Top-Down)">
+ <input id="ELEVATION">DEM_PREPROC</input>
+ <input id="VAL_INPUT">DEM</input>
+ <output id="VAL_MEAN">MEAN</output>
+ <option id="METHOD" varname="true">FLOW_METHOD</option>
+ </tool>
+ <tool id="tool_01" library="grid_calculus" module="3" name="Grid Difference">
+ <input id="A">MEAN</input>
+ <input id="B">DEM</input>
+ <output id="C">HEIGHT</output>
+ </tool>
+
+ <tool library="ta_morphometry" module="0" name="Slope, Aspect, Curvature">
+ <input id="ELEVATION">DEM</input>
+ <output id="SLOPE">TMP</output>
+ <output id="ASPECT">ASPECT</output>
+ <option id="METHOD">6</option>
+ </tool>
+
+ <tool library="ta_hydrology" module="0" name="Catchment Area (Top-Down)">
+ <input id="ELEVATION">DEM_PREPROC</input>
+ <input id="VAL_INPUT">TMP</input>
+ <output id="VAL_MEAN">SLOPE</output>
+ <option id="METHOD" varname="true">FLOW_METHOD</option>
+ </tool>
+
+ <tool library="grid_calculus" module="1" name="Grid Calculator">
+ <input id="GRIDS">ASPECT</input>
+ <output id="RESULT">TMP</output>
+ <option id="NAME">sin(aspect)</option>
+ <option id="FORMULA">sin(g1)</option>
+ </tool>
+ <tool library="ta_hydrology" module="0" name="Catchment Area (Top-Down)">
+ <input id="ELEVATION">DEM_PREPROC</input>
+ <input id="VAL_INPUT">TMP</input>
+ <output id="VAL_MEAN">SIN_ASPECT</output>
+ <option id="METHOD" varname="true">FLOW_METHOD</option>
+ </tool>
+
+ <tool library="grid_calculus" module="1" name="Grid Calculator">
+ <input id="GRIDS">ASPECT</input>
+ <output id="RESULT">TMP</output>
+ <option id="NAME">cos(aspect)</option>
+ <option id="FORMULA">cos(g1)</option>
+ </tool>
+ <tool library="ta_hydrology" module="0" name="Catchment Area (Top-Down)">
+ <input id="ELEVATION">DEM_PREPROC</input>
+ <input id="VAL_INPUT">TMP</input>
+ <output id="VAL_MEAN">COS_ASPECT</output>
+ <option id="METHOD" varname="true">FLOW_METHOD</option>
+ </tool>
+
+ <tool library="grid_calculus" module="1" name="Grid Calculator">
+ <input id="GRIDS">COS_ASPECT</input>
+ <input id="GRIDS">SIN_ASPECT</input>
+ <output id="RESULT">ASPECT</output>
+ <option id="FORMULA">mod((180 + 270) - (atan2(g1, g2) * 180 / pi()), 360)</option>
+ </tool>
+ </tools>
+</toolchain>
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-grass/saga.git
More information about the Pkg-grass-devel
mailing list