//--------------------------------------------------------- bool CLines_From_Points::On_Execute(void) { int Order, Separate, Elevation; CSG_String s; CSG_Shape *pLine , *pPoint; CSG_Shapes *pLines, *pPoints; pPoints = Parameters("POINTS" )->asShapes(); pLines = Parameters("LINES" )->asShapes(); Order = Parameters("ORDER" )->asInt(); Separate = Parameters("SEPARATE" )->asInt(); Elevation = Parameters("ELEVATION")->asInt(); //------------------------------------------------- if( pPoints->Get_Count() < 1 ) { return( false ); } //------------------------------------------------- pLines->Create(SHAPE_TYPE_Line, pPoints->Get_Name(), NULL, Elevation >= 0 ? SG_VERTEX_TYPE_XYZ : SG_VERTEX_TYPE_XY); pLines->Add_Field(SG_T("ID"), SG_DATATYPE_Int); if( Separate >= 0 ) { pLines->Add_Field(pPoints->Get_Field_Name(Separate), pPoints->Get_Field_Type(Separate)); pPoints->Set_Index(Separate, TABLE_INDEX_Ascending, Order, TABLE_INDEX_Ascending); } else { pPoints->Set_Index(Order, TABLE_INDEX_Ascending); } //------------------------------------------------- for(int iPoint=0; iPoint<pPoints->Get_Count(); iPoint++) { pPoint = pPoints->Get_Shape_byIndex(iPoint); if( pLines->Get_Count() == 0 || (Separate >= 0 && s.Cmp(pPoint->asString(Separate))) ) { pLine = pLines->Add_Shape(); pLine->Set_Value(0, pLines->Get_Count()); if( Separate >= 0 ) { pLine->Set_Value(1, s = pPoint->asString(Separate)); } } pLine->Add_Point(pPoint->Get_Point(0)); if( Elevation >= 0 ) { pLine->Set_Z(pPoint->asDouble(Elevation), iPoint); } } return( true ); }

WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR lpCmdLine, int) { try { GetWindowsVersion(); } catch(Exception * E) { MessageBox(NULL,E->Message.c_str(),"错误",MB_OK | MB_ICONSTOP); return 99; } DateSeparator = '-'; ShortDateFormat = "yyyy-m-d"; try { ProcessExitCode = 0; frmExportToDB = NULL; SlentMode = false; LogFile = NULL; Application->Initialize(); Application->Title = "PowerBill通用话单查询转换系统"; InCmdMode = strlen(lpCmdLine) > 0; FTPTimeout = -1; //分析参数 if(InCmdMode) { AnsiString Parameters(lpCmdLine); AnsiString ListFileName = ""; AnsiString LogFileName = ""; AnsiString TableName = ""; AnsiString DBName = ""; AnsiString BillName = ""; AnsiString TempPath = ""; bool TransFieldValue = false; int MaxError = 0; int pos1 = 1; int pos2 = Parameters.Pos("="); AnsiString ParamName,ParamValue; AnsiString Message; bool VerifyFile = true; int JobMode = 1; AnsiString DirList; AnsiString FTPServer; while(pos2 > 0) { ParamName = LowerCase(Parameters.SubString(pos1,pos2 - 1).Trim()); Parameters = Parameters.SubString(pos2 + 1,Parameters.Length() - pos2); if(Parameters.SubString(1,1) == "\"") { Parameters = Parameters.SubString(2,Parameters.Length() - 1); pos2 = Parameters.Pos("\""); if(pos2 < 1) break; ParamValue = Parameters.SubString(1,pos2 - 1); Parameters = Parameters.SubString(pos2 + 1,Parameters.Length() - pos2); pos2 = GetNextCharPos(Parameters.c_str()); Parameters = Parameters.SubString(pos2,Parameters.Length() - pos2 + 1); } else { pos2 = Parameters.Pos(" "); if(pos2 < 1) { ParamValue = Parameters.SubString(1,Parameters.Length()); } else { ParamValue = Parameters.SubString(1,pos2 - 1); Parameters = Parameters.SubString(pos2 + 1,Parameters.Length() - ParamValue.Length()); pos2 = GetNextCharPos(Parameters.c_str()); Parameters = Parameters.SubString(pos2 + 1,Parameters.Length() - pos2); } } if(ParamName == "files") ListFileName = ParamValue; else if(ParamName == "db") DBName = ParamValue; else if(ParamName == "table") TableName = ParamValue; else if(ParamName == "silent") SlentMode = ParamValue == "1" || ParamValue.LowerCase() == "true" || ParamValue.LowerCase() == "yes"; else if(ParamName == "log") LogFileName = ParamValue; else if(ParamName == "maxdberrors") { if(IsNumber(ParamValue.c_str())) MaxError = StrToInt(ParamValue); else Message += "最大错误数无效[" + ParamValue + "];"; } else if(ParamName == "tempdir") { TempPath = ParamValue; } else if(ParamName == "billname") BillName = ParamValue; else if(ParamName == "trans") TransFieldValue = ParamValue == "1" || ParamValue.LowerCase() == "true" || ParamValue.LowerCase() == "yes"; //else if(ParamName == "verifyfile") // VerifyFile = ParamValue == "1" || ParamValue.LowerCase() == "true"; else if(ParamName == "mode") { if(ParamValue == "local") JobMode = 1; else if(ParamValue == "ftp") JobMode = 2; else Message += "指定的工作模式无效[" + ParamValue + "]"; } else if(ParamName == "ftpserver") { FTPServer = ParamValue; } else if(ParamName == "dirlist") { DirList = ParamValue; } else if(ParamName == "timeout") { if(IsNumber(ParamValue.c_str())) FTPTimeout = StrToInt(ParamValue); } else { Message += "无效参数[" + ParamName + "];"; } pos2 = Parameters.Pos("="); } if(Message == "") { if(TableName == "") Message += "没有指定导入数据的目标表;"; if(DBName == "") Message += "没有指定要导入的目标数据库的连接名称;"; if(BillName == "") Message += "没有指定话单格式名称"; if(JobMode == 1) { if(ListFileName == "") Message += "没有指定导入文件列表文本文件;"; if(!FileExists(ListFileName)) Message += "指定的导入文件列表文本文件不存在;"; } else if(JobMode == 2) { if(DirList == "") Message += "没有指定FTP列表文件;"; if(!FileExists(DirList)) Message += "指定的FTP目录列表文本文件不存在;"; if(FTPServer == "") Message += "没有指定FTP服务器名称;"; } } LogFile = fopen(LogFileName.c_str(),"w"); if(LogFile == NULL) { LogFileName = ExtractFilePath(Application->ExeName) + "ibill.log"; LogFile = fopen(LogFileName.c_str(),"w"); if(LogFile == NULL) ExitProcess(3); } if(SlentMode) { AllocConsole(); SetConsoleCtrlHandler(HandlerRoutine,true); } if(Message != "") { ShowErrorMessage(Application->Handle,Message.c_str(),true,2); } BeginJob(JobMode,ListFileName, BillName, DBName, TableName, LogFileName, TempPath, TransFieldValue, MaxError,VerifyFile,FTPServer,DirList,0); fclose(LogFile); if(SlentMode) FreeConsole(); ExitProcess(ProcessExitCode); } else { Application->CreateForm(__classid(TfrmMain), &frmMain); Application->Run(); } } catch (Exception &exception) { //Application->ShowException(&exception); } catch (...) { try { throw Exception(""); } catch (Exception &exception) { //Application->ShowException(&exception); } } return 0; }

StatementNode* Parser::Instruction() { if(currenttoken->type == Si) { ConsumeToken(); ExpressionNode* condition=Expresion(); if(currenttoken->type != Entonces) throw invalid_argument("Se esperaba palabra reservada entonces. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); ConsumeToken(); vector<StatementNode*> codeTrue=InstructionList(); vector<StatementNode*> codeFalse=SiInstructionPrime(); return new SiNode(condition,codeTrue,codeFalse); } else if(currenttoken->type == Para) { ConsumeToken(); VariableNode * id=Variable(); if(currenttoken->type != ValueAllocation) throw invalid_argument("Se esperaba <-. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); ConsumeToken(); ExpressionNode* value=Expresion(); if(currenttoken->type != Hasta) throw invalid_argument("Se esperaba palabra reservada hasta. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); ConsumeToken(); ExpressionNode* condition = Expresion(); if(currenttoken->type != Haga) throw invalid_argument("Se esperaba palabra reservada haga. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); ConsumeToken(); vector<StatementNode*> code =InstructionList(); if(currenttoken->type != Fin) throw invalid_argument("Se esperaba palabra reservada fin. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); ConsumeToken(); if(currenttoken->type != Para) throw invalid_argument("Se esperaba palabra reservada para. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); ConsumeToken(); return new ParaNode(new AssignmentNode(id,value),condition,code); } else if(currenttoken->type == Id) { VariableNode* id=Variable(); if(currenttoken->type != ValueAllocation) throw invalid_argument("Se esperaba <-. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); ConsumeToken(); ExpressionNode* expression=Expresion(); return new AssignmentNode(id,expression); } else if(currenttoken->type == Escriba) { ConsumeToken(); vector<ExpressionNode*> exprList=ExpressionListNotNull(); return new EscribaNode(exprList); } else if(currenttoken->type == Mientras) { ConsumeToken(); ExpressionNode * condition=Expresion(); if(currenttoken->type != Haga) throw invalid_argument("Se esperaba palabra reservada haga. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); ConsumeToken(); vector<StatementNode*>code=InstructionList(); if(currenttoken->type != Fin) throw invalid_argument("Se esperaba palabra reservada fin. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); ConsumeToken(); if(currenttoken->type != Mientras) throw invalid_argument("Se esperaba palabra reservada mientras. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); ConsumeToken(); return new MientrasNode(condition,code); } else if(currenttoken->type == Repita) { ConsumeToken(); vector<StatementNode*> code=InstructionList(); if(currenttoken->type != Hasta) throw invalid_argument("Se esperaba palabra reservada hasta. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); ConsumeToken(); ExpressionNode*condition=Expresion(); return new RepitaNode(code,condition); } else if(currenttoken->type == Caso) { ConsumeToken(); VariableNode * id=Variable(); vector<CasoLineNode*> cases=CasoList(); vector<StatementNode*> defaultcase=CasoSino(); if(currenttoken->type != Fin) throw invalid_argument("Se esperaba palabra reservada fin. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); ConsumeToken(); if(currenttoken->type != Caso) throw invalid_argument("Se esperaba palabra reservada caso. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); ConsumeToken(); return new CasoNode(id,cases,defaultcase); } else if(currenttoken->type == Abrir) { ConsumeToken(); string archiveId=Archive(); if(currenttoken->type != Como) throw invalid_argument("Se esperaba palabra reservada como. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); ConsumeToken(); VariableNode* archiveType=Variable(); vector<ModeNode*> modes=ModeList(); return new AbrirArchivoNode(archiveId,archiveType,modes); } else if(currenttoken->type == Cerrar) { ConsumeToken(); VariableNode* id= Variable(); return new CerrarArchivoNode(id); } else if(currenttoken->type == Leer) { ConsumeToken(); VariableNode* archive=Variable(); if(currenttoken->type != Coma) throw invalid_argument("Se esperaba ,. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); ConsumeToken(); VariableNode* data=Variable(); return new LeerArchivoNode(archive,data); } else if(currenttoken->type == Escribir) { ConsumeToken(); VariableNode* archive=Variable(); if(currenttoken->type != Coma) throw invalid_argument("Se esperaba ,. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); ConsumeToken(); VariableNode* data=Variable(); return new EscribirArchivoNode(archive,data); } else if(currenttoken->type == Llamar) { ConsumeToken(); if(currenttoken->type != Id) throw invalid_argument("Se esperaba un id. Row:"+to_string(currenttoken->row)+"Column:"+to_string(currenttoken->column)); string id=currenttoken->lexeme; ConsumeToken(); vector<ExpressionNode*> parameters=Parameters(); return new LlamarNode(id,parameters); } else if(currenttoken->type == Retorne) { ConsumeToken(); ExpressionNode* id=Expresion(); return new RetorneNode(id); } }

bool CSimulateVariableWind::AssignParameters(){ int x,y; m_pDEM = Parameters("DEM")->asGrid(); m_pFuelGrid = Parameters("FUEL")->asGrid(); m_iWindDirGrids = Parameters("WINDDIR")->asInt(); m_pWindDirGrids =(CSG_Grid **)Parameters("WINDDIR")->asPointer(); m_iWindSpdGrids = Parameters("WINDSPD")->asInt(); m_pWindSpdGrids =(CSG_Grid **)Parameters("WINDSPD")->asPointer(); 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_fTimeLimit = Parameters("SIMULATIONTIME")->asInt(); m_fIgnTime = Parameters("IGNTIME")->asDouble(); m_fInterval = Parameters("INTERVAL")->asDouble(); m_fWorldX = Parameters("COORDX")->asDouble(); m_fWorldY = Parameters("COORDY")->asDouble(); m_iGridX = (int) ((m_fWorldX - m_pDEM->Get_XMin()) / m_pDEM->Get_Cellsize()); m_iGridY = (int) ((m_fWorldY - m_pDEM->Get_YMin()) / m_pDEM->Get_Cellsize()); m_Catalog = Fire_FuelCatalogCreateStandard("Standard", 13); Fire_FlameLengthTable(m_Catalog, 500, 0.1); if (!m_iWindDirGrids){ m_pWindDirGrids = new CSG_Grid*[1]; m_pWindDirGrids[0] = SG_Create_Grid(m_pDEM); m_pWindDirGrids[0]->Assign(Parameters("DEFAULTWINDDIR")->asDouble()); m_bDeleteWindDirGrid = true; }//if else{ m_bDeleteWindDirGrid = false; }//else if (!m_iWindSpdGrids){ m_pWindSpdGrids = new CSG_Grid*[1]; m_pWindSpdGrids[0] = SG_Create_Grid(m_pDEM); m_pWindSpdGrids[0]->Assign(Parameters("DEFAULTWINDSPD")->asDouble()); m_bDeleteWindSpdGrid = true; }//if else{ m_bDeleteWindSpdGrid = false; }//else //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 m_pReactionIntensityGrid = SG_Create_Grid(m_pDEM, SG_DATATYPE_Double); m_pEffectiveWindGrid = SG_Create_Grid(m_pDEM, SG_DATATYPE_Double); m_pHeatPerUnitAreaGrid = SG_Create_Grid(m_pDEM, SG_DATATYPE_Double); //----------------------------------------------------- m_pSlopeGrid = SG_Create_Grid(m_pDEM, SG_DATATYPE_Float); m_pAspectGrid = SG_Create_Grid(m_pDEM, SG_DATATYPE_Float); 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

//--------------------------------------------------------- bool CSelect_Location::On_Execute(void) { int Method, Condition; m_pShapes = Parameters("SHAPES") ->asShapes(); m_pLocations = Parameters("LOCATIONS") ->asShapes(); Condition = Parameters("CONDITION") ->asInt(); Method = Parameters("METHOD") ->asInt(); //----------------------------------------------------- switch( Condition ) { case 0: // intersect if( ((m_pShapes ->Get_Type() == SHAPE_TYPE_Point || m_pShapes ->Get_Type() == SHAPE_TYPE_Points) && m_pLocations->Get_Type() != SHAPE_TYPE_Polygon) || ((m_pLocations->Get_Type() == SHAPE_TYPE_Point || m_pLocations->Get_Type() == SHAPE_TYPE_Points) && m_pShapes ->Get_Type() != SHAPE_TYPE_Polygon) ) { Error_Set(_TL("points can only intersect with polygons")); return( false ); } break; case 1: // are completely within case 3: // have their centroid in if( m_pLocations->Get_Type() != SHAPE_TYPE_Polygon ) { Error_Set(_TL("this operation requires locations to be of type polygon")); return( false ); } break; case 2: // completely contain case 4: // contain the centroid of if( m_pShapes->Get_Type() != SHAPE_TYPE_Polygon ) { Error_Set(_TL("this operation requires selectable shapes to be of type polygon")); return( false ); } break; } //----------------------------------------------------- for(int i=0; i<m_pShapes->Get_Count() && Set_Progress(i, m_pShapes->Get_Count()); i++) { CSG_Shape *pShape = m_pShapes->Get_Shape(i); switch( Method ) { case 0: // New selection if( ( pShape->is_Selected() && !Do_Select(pShape, Condition)) || (!pShape->is_Selected() && Do_Select(pShape, Condition)) ) { m_pShapes->Select(i, true); } break; case 1: // Add to current selection if( !pShape->is_Selected() && Do_Select(pShape, Condition) ) { m_pShapes->Select(i, true); } break; case 2: // Select from current selection if( pShape->is_Selected() && !Do_Select(pShape, Condition) ) { m_pShapes->Select(i, true); } break; case 3: // Remove from current selection if( pShape->is_Selected() && Do_Select(pShape, Condition) ) { m_pShapes->Select(i, true); } break; } } //----------------------------------------------------- Message_Add(CSG_String::Format(SG_T("%s: %d"), _TL("selected shapes"), m_pShapes->Get_Selection_Count())); DataObject_Update(m_pShapes); return( true ); }

//--------------------------------------------------------- bool CGW_Multi_Regression_Grid::Initialize(CSG_Shapes *pPoints, int iDependent, CSG_Parameter_Grid_List *pPredictors) { //----------------------------------------------------- if( (m_nPredictors = pPredictors->Get_Count()) <= 0 ) { return( false ); } if( !pPoints->Get_Extent().Intersects(Get_System()->Get_Extent()) ) { return( false ); } //----------------------------------------------------- int iPredictor, Interpolation = GRID_INTERPOLATION_BSpline; m_Points.Create (SHAPE_TYPE_Point); m_Points.Set_Name (Parameters("DEPENDENT")->asString()); m_Points.Add_Field(Parameters("DEPENDENT")->asString(), SG_DATATYPE_Double); for(iPredictor=0; iPredictor<pPredictors->Get_Count(); iPredictor++) { m_Points.Add_Field(pPredictors->asGrid(iPredictor)->Get_Name(), SG_DATATYPE_Double); } //----------------------------------------------------- for(int iPoint=0; iPoint<pPoints->Get_Count() && Set_Progress(iPoint, pPoints->Get_Count()); iPoint++) { CSG_Shape *pPoint = pPoints->Get_Shape(iPoint); if( !pPoint->is_NoData(iDependent) ) { CSG_Vector z(1 + m_nPredictors); z[0] = pPoint->asDouble(iDependent); TSG_Point Point = pPoint->Get_Point(0); bool bAdd = true; for(iPredictor=0; bAdd && iPredictor<m_nPredictors; iPredictor++) { if( !pPredictors->asGrid(iPredictor)->Get_Value(Point, z[iPredictor + 1], Interpolation) ) { bAdd = false; } } if( bAdd ) { (pPoint = m_Points.Add_Shape())->Add_Point(Point); for(iPredictor=0; iPredictor<=m_nPredictors; iPredictor++) { pPoint->Set_Value(iPredictor, z[iPredictor]); } } } } //----------------------------------------------------- m_nPoints_Min = Parameters("SEARCH_POINTS_MIN")->asInt (); m_nPoints_Max = Parameters("SEARCH_POINTS_ALL")->asInt () == 0 ? Parameters("SEARCH_POINTS_MAX")->asInt () : 0; m_Radius = Parameters("SEARCH_RANGE" )->asInt () == 0 ? Parameters("SEARCH_RADIUS" )->asDouble() : 0.0; m_Direction = Parameters("SEARCH_DIRECTION" )->asInt () == 0 ? -1 : 4; m_Weighting.Set_Parameters(&Parameters); return( m_Points.Get_Count() > m_nPredictors && ((m_nPoints_Max <= 0 && m_Radius <= 0.0) || m_Search.Create(&m_Points, -1)) ); }

//--------------------------------------------------------- bool CTasseled_Cap::On_Execute(void) { CSG_Grid *pBand[6], *pBright, *pGreen, *pWet; pBand[0] = Parameters("BLUE" )->asGrid(); pBand[1] = Parameters("GREEN" )->asGrid(); pBand[2] = Parameters("RED" )->asGrid(); pBand[3] = Parameters("NIR" )->asGrid(); pBand[4] = Parameters("MIR1" )->asGrid(); pBand[5] = Parameters("MIR2" )->asGrid(); pBright = Parameters("BRIGHTNESS")->asGrid(); pGreen = Parameters("GREENNESS" )->asGrid(); pWet = Parameters("WETNESS" )->asGrid(); DataObject_Set_Colors(pBright, 100, SG_COLORS_BLACK_WHITE , false); DataObject_Set_Colors(pGreen , 100, SG_COLORS_WHITE_GREEN , false); DataObject_Set_Colors(pWet , 100, SG_COLORS_RED_GREY_BLUE, false); for(int y=0; y<Get_NY() && Set_Progress(y); y++) { for(int x=0; x<Get_NX(); x++) { if( pBand[0]->is_NoData(x, y) || pBand[1]->is_NoData(x, y) || pBand[2]->is_NoData(x, y) || pBand[3]->is_NoData(x, y) || pBand[4]->is_NoData(x, y) || pBand[5]->is_NoData(x, y) ) { pBright ->Set_NoData(x, y); pGreen ->Set_NoData(x, y); pWet ->Set_NoData(x, y); } else { double b[6]; b[0] = pBand[0]->asDouble(x, y); b[1] = pBand[1]->asDouble(x, y); b[2] = pBand[2]->asDouble(x, y); b[3] = pBand[3]->asDouble(x, y); b[4] = pBand[4]->asDouble(x, y); b[5] = pBand[5]->asDouble(x, y); pBright ->Set_Value(x, y, 0.3037 * b[0] + 0.2793 * b[1] + 0.4743 * b[2] + 0.5585 * b[3] + 0.5082 * b[4] + 0.1863 * b[5] ); pGreen ->Set_Value(x, y, -0.2848 * b[0] - 0.2435 * b[1] - 0.5436 * b[2] + 0.7243 * b[3] + 0.0840 * b[4] - 0.1800 * b[5] ); pWet ->Set_Value(x, y, 0.1509 * b[0] + 0.1973 * b[1] + 0.3279 * b[2] + 0.3406 * b[3] - 0.7112 * b[4] - 0.4572 * b[5] ); } } } return( true ); }

//--------------------------------------------------------- bool CGWR_Grid_Downscaling::On_Execute(void) { //----------------------------------------------------- CSG_Parameter_Grid_List *pPredictors = Parameters("PREDICTORS")->asGridList(); if( (m_nPredictors = pPredictors->Get_Count()) <= 0 ) { return( false ); } m_pDependent = Parameters("DEPENDENT")->asGrid(); if( !m_pDependent->Get_Extent().Intersects(Get_System()->Get_Extent()) ) { return( false ); } //----------------------------------------------------- int i; Process_Set_Text(_TL("upscaling of predictors")); m_pPredictors = (CSG_Grid **)SG_Calloc(m_nPredictors , sizeof(CSG_Grid *)); m_pModel = (CSG_Grid **)SG_Calloc(m_nPredictors + 1, sizeof(CSG_Grid *)); for(i=0; i<m_nPredictors; i++) { m_pPredictors[i] = SG_Create_Grid(m_pDependent->Get_System()); m_pPredictors[i] ->Assign(pPredictors->asGrid(i), GRID_INTERPOLATION_NearestNeighbour); // GRID_INTERPOLATION_Mean_Cells m_pModel [i] = SG_Create_Grid(m_pDependent->Get_System()); m_pModel [i] ->Set_Name(CSG_String::Format(SG_T("%s [%s]"), pPredictors->asGrid(i)->Get_Name(), _TL("Factor"))); } m_pModel[m_nPredictors] = SG_Create_Grid(m_pDependent->Get_System()); m_pModel[m_nPredictors] ->Set_Name(_TL("Intercept")); //----------------------------------------------------- Process_Set_Text(_TL("model creation")); bool bResult = Get_Model(); //----------------------------------------------------- for(i=0; i<m_nPredictors; i++) { delete(m_pPredictors[i]); m_pPredictors[i] = pPredictors->asGrid(i); } //----------------------------------------------------- if( bResult ) { Process_Set_Text(_TL("downscaling")); bResult = Set_Model(); } //----------------------------------------------------- if( Parameters("MODEL_OUT")->asBool() ) { CSG_Parameter_Grid_List *pModel = Parameters("MODEL")->asGridList(); pModel->Del_Items(); pModel->Add_Item(m_pModel[m_nPredictors]); for(i=0; i<m_nPredictors; i++) { pModel->Add_Item(m_pModel[i]); } } else { for(i=0; i<=m_nPredictors; i++) { delete(m_pModel[i]); } } SG_FREE_SAFE(m_pModel); SG_FREE_SAFE(m_pPredictors); return( bResult ); }

//--------------------------------------------------------- bool CLAS_Import::On_Execute(void) { CSG_Parameter_PointCloud_List *pPointsList; bool bValidity; CSG_Strings Files; int RGBrange; int cntInvalid = 0; bValidity = Parameters("VALID")->asBool(); RGBrange = Parameters("RGB_RANGE")->asInt(); //----------------------------------------------------- if( !Parameters("FILES")->asFilePath()->Get_FilePaths(Files) ) { return( false ); } //----------------------------------------------------- pPointsList = Parameters("POINTS")->asPointCloudList(); pPointsList ->Del_Items(); for(int i=0; i<Files.Get_Count(); i++) { SG_UI_Msg_Add(CSG_String::Format(_TL("Parsing %s ... "), SG_File_Get_Name(Files[i], true).c_str()), true); std::ifstream ifs; ifs.open(Files[i].b_str(), std::ios::in | std::ios::binary); if( !ifs ) { SG_UI_Msg_Add_Error(CSG_String::Format(_TL("Unable to open LAS file!"))); continue; } //----------------------------------------------------- // Check if LAS version is supported liblas::LASReader *pReader; try { pReader = new liblas::LASReader(ifs); } catch(std::exception &e) { SG_UI_Msg_Add_Error(CSG_String::Format(_TL("LAS header exception: %s"), e.what())); ifs.close(); return( false ); } catch(...) { SG_UI_Msg_Add_Error(CSG_String::Format(_TL("Unknown LAS header exception!"))); ifs.close(); return( false ); } delete (pReader); ifs.clear(); //----------------------------------------------------- liblas::LASReader reader(ifs); liblas::LASHeader const& header = reader.GetHeader(); //----------------------------------------------------- int nFields, iField[VAR_Count]; CSG_PointCloud *pPoints = SG_Create_PointCloud(); pPoints->Set_Name(SG_File_Get_Name(Files[i], false)); nFields = 3; ADD_FIELD("T", VAR_T, _TL("gps-time") , SG_DATATYPE_Double); // SG_DATATYPE_Long ADD_FIELD("i", VAR_i, _TL("intensity") , SG_DATATYPE_Float); // SG_DATATYPE_Word ADD_FIELD("a", VAR_a, _TL("scan angle") , SG_DATATYPE_Float); // SG_DATATYPE_Byte ADD_FIELD("r", VAR_r, _TL("number of the return") , SG_DATATYPE_Int); ADD_FIELD("c", VAR_c, _TL("classification") , SG_DATATYPE_Int); // SG_DATATYPE_Byte ADD_FIELD("u", VAR_u, _TL("user data") , SG_DATATYPE_Double); // SG_DATATYPE_Byte ADD_FIELD("n", VAR_n, _TL("number of returns of given pulse") , SG_DATATYPE_Int); ADD_FIELD("R", VAR_R, _TL("red channel color") , SG_DATATYPE_Int); // SG_DATATYPE_Word ADD_FIELD("G", VAR_G, _TL("green channel color") , SG_DATATYPE_Int); ADD_FIELD("B", VAR_B, _TL("blue channel color") , SG_DATATYPE_Int); ADD_FIELD("e", VAR_e, _TL("edge of flight line flag") , SG_DATATYPE_Char); ADD_FIELD("d", VAR_d, _TL("direction of scan flag") , SG_DATATYPE_Char); ADD_FIELD("p", VAR_p, _TL("point source ID") , SG_DATATYPE_Int); // SG_DATATYPE_Word ADD_FIELD("C", VAR_C, _TL("rgb color") , SG_DATATYPE_Int); //----------------------------------------------------- int iPoint = 0; try { while( reader.ReadNextPoint() ) { if (iPoint % 100000) SG_UI_Process_Set_Progress(iPoint, header.GetPointRecordsCount()); liblas::LASPoint const& point = reader.GetPoint(); if( bValidity ) { if( !point.IsValid() ) { cntInvalid++; continue; } } pPoints->Add_Point(point.GetX(), point.GetY(), point.GetZ()); if( iField[VAR_T] > 0 ) pPoints->Set_Value(iPoint, iField[VAR_T], point.GetTime()); if( iField[VAR_i] > 0 ) pPoints->Set_Value(iPoint, iField[VAR_i], point.GetIntensity()); if( iField[VAR_a] > 0 ) pPoints->Set_Value(iPoint, iField[VAR_a], point.GetScanAngleRank()); if( iField[VAR_r] > 0 ) pPoints->Set_Value(iPoint, iField[VAR_r], point.GetReturnNumber()); if( iField[VAR_c] > 0 ) pPoints->Set_Value(iPoint, iField[VAR_c], point.GetClassification()); if( iField[VAR_u] > 0 ) pPoints->Set_Value(iPoint, iField[VAR_u], point.GetUserData()); if( iField[VAR_n] > 0 ) pPoints->Set_Value(iPoint, iField[VAR_n], point.GetNumberOfReturns()); if( iField[VAR_R] > 0 ) pPoints->Set_Value(iPoint, iField[VAR_R], point.GetColor().GetRed()); if( iField[VAR_G] > 0 ) pPoints->Set_Value(iPoint, iField[VAR_G], point.GetColor().GetGreen()); if( iField[VAR_B] > 0 ) pPoints->Set_Value(iPoint, iField[VAR_B], point.GetColor().GetBlue()); if( iField[VAR_e] > 0 ) pPoints->Set_Value(iPoint, iField[VAR_e], point.GetFlightLineEdge()); if( iField[VAR_d] > 0 ) pPoints->Set_Value(iPoint, iField[VAR_d], point.GetScanDirection()); if( iField[VAR_p] > 0 ) pPoints->Set_Value(iPoint, iField[VAR_p], point.GetPointSourceID()); if( iField[VAR_C] > 0 ) { double r, g, b; r = point.GetColor().GetRed(); g = point.GetColor().GetGreen(); b = point.GetColor().GetBlue(); if (RGBrange == 0) // 16 bit { r = r / 65535 * 255; g = g / 65535 * 255; b = b / 65535 * 255; } pPoints->Set_Value(iPoint, iField[VAR_C], SG_GET_RGB(r, g, b)); } iPoint++; } } catch(std::exception &e) { SG_UI_Msg_Add_Error(CSG_String::Format(_TL("LAS reader exception: %s"), e.what())); ifs.close(); return( false ); } catch(...) { SG_UI_Msg_Add_Error(CSG_String::Format(_TL("Unknown LAS reader exception!"))); ifs.close(); return( false ); } ifs.close(); pPointsList->Add_Item(pPoints); DataObject_Add(pPoints); //----------------------------------------------------- CSG_Parameters sParms; DataObject_Get_Parameters(pPoints, sParms); if (sParms("METRIC_ATTRIB") && sParms("COLORS_TYPE") && sParms("METRIC_COLORS") && sParms("METRIC_ZRANGE") && sParms("DISPLAY_VALUE_AGGREGATE")) { sParms("DISPLAY_VALUE_AGGREGATE")->Set_Value(3); // highest z sParms("COLORS_TYPE")->Set_Value(2); // graduated color sParms("METRIC_COLORS")->asColors()->Set_Count(255); // number of colors sParms("METRIC_ATTRIB")->Set_Value(2); // z attrib sParms("METRIC_ZRANGE")->asRange()->Set_Range(pPoints->Get_Minimum(2),pPoints->Get_Maximum(2)); } DataObject_Set_Parameters(pPoints, sParms); SG_UI_Msg_Add(_TL("okay"), false); } //----------------------------------------------------- if( bValidity && cntInvalid > 0 ) SG_UI_Msg_Add(CSG_String::Format(_TL("WARNING: %d invalid points skipped!"), cntInvalid), true); return( true ); }

//--------------------------------------------------------- bool CGrid_Export::On_Execute(void) { //----------------------------------------------------- int y, iy, Method; double dTrans; CSG_Grid *pGrid, *pShade, Grid, Shade; //----------------------------------------------------- pGrid = Parameters("GRID" )->asGrid(); pShade = Parameters("SHADE" )->asGrid(); Method = Parameters("COLOURING" )->asInt (); dTrans = Parameters("SHADE_TRANS" )->asDouble() / 100.0; if( !pGrid ) { return( false ); } //----------------------------------------------------- if( Method == 5 ) // same as in graphical user interface { if( !SG_UI_DataObject_asImage(pGrid, &Grid) ) { Error_Set("could not retrieve colour coding from graphical user interface."); return( false ); } } else { double zMin, zScale; CSG_Colors Colors; CSG_Table LUT; if( SG_UI_Get_Window_Main() ) { Colors.Assign(Parameters("COL_PALETTE")->asColors()); } else { Colors.Set_Palette( Parameters("COL_PALETTE")->asInt (), Parameters("COL_REVERT" )->asBool(), Parameters("COL_COUNT" )->asInt () ); } switch( Method ) { case 0: // stretch to grid's standard deviation zMin = pGrid->Get_Mean() - Parameters("STDDEV")->asDouble() * pGrid->Get_StdDev(); zScale = Colors.Get_Count() / (2 * Parameters("STDDEV")->asDouble() * pGrid->Get_StdDev()); break; case 1: // stretch to grid's value range zMin = pGrid->Get_ZMin(); zScale = Colors.Get_Count() / pGrid->Get_ZRange(); break; case 2: // stretch to specified value range zMin = Parameters("STRETCH")->asRange()->Get_LoVal(); if( zMin >= (zScale = Parameters("STRETCH")->asRange()->Get_HiVal()) ) { Error_Set(_TL("invalid user specified value range.")); return( false ); } zScale = Colors.Get_Count() / (zScale - zMin); break; case 3: // lookup table if( !Parameters("LUT")->asTable() || Parameters("LUT")->asTable()->Get_Field_Count() < 5 ) { Error_Set(_TL("invalid lookup table.")); return( false ); } LUT.Create(*Parameters("LUT")->asTable()); break; case 4: // rgb coded values break; } //------------------------------------------------- Grid.Create(*Get_System(), SG_DATATYPE_Int); for(y=0, iy=Get_NY()-1; y<Get_NY() && Set_Progress(y); y++, iy--) { #pragma omp parallel for for(int x=0; x<Get_NX(); x++) { double z = pGrid->asDouble(x, y); if( Method == 3 ) // lookup table { int i, iColor = -1; for(i=0; iColor<0 && i<LUT.Get_Count(); i++) { if( z == LUT[i][3] ) { Grid.Set_Value(x, iy, LUT[iColor = i].asInt(0)); } } for(i=0; iColor<0 && i<LUT.Get_Count(); i++) { if( z >= LUT[i][3] && z <= LUT[i][4] ) { Grid.Set_Value(x, iy, LUT[iColor = i].asInt(0)); } } if( iColor < 0 ) { Grid.Set_NoData(x, iy); } } else if( pGrid->is_NoData(x, y) ) { Grid.Set_NoData(x, iy); } else if( Method == 4 ) // rgb coded values { Grid.Set_Value(x, iy, z); } else { int i = (int)(zScale * (z - zMin)); Grid.Set_Value(x, iy, Colors[i < 0 ? 0 : i >= Colors.Get_Count() ? Colors.Get_Count() - 1 : i]); } } } } //----------------------------------------------------- if( !pShade || pShade->Get_ZRange() <= 0.0 ) { pShade = NULL; } else { double dMinBright, dMaxBright; dMinBright = Parameters("SHADE_BRIGHT")->asRange()->Get_LoVal() / 100.0; dMaxBright = Parameters("SHADE_BRIGHT")->asRange()->Get_HiVal() / 100.0; if( dMinBright >= dMaxBright ) { SG_UI_Msg_Add_Error(_TL("Minimum shade brightness must be lower than maximum shade brightness!")); return( false ); } int nColors = 100; CSG_Colors Colors(nColors, SG_COLORS_BLACK_WHITE, true); //------------------------------------------------- Shade.Create(*Get_System(), SG_DATATYPE_Int); for(y=0, iy=Get_NY()-1; y<Get_NY() && Set_Progress(y); y++, iy--) { #pragma omp parallel for for(int x=0; x<Get_NX(); x++) { if( pShade->is_NoData(x, y) ) { Shade.Set_NoData(x, iy); } else { Shade.Set_Value (x, iy, Colors[(int)(nColors * (dMaxBright - dMinBright) * (pShade->asDouble(x, y) - pShade->Get_ZMin()) / pShade->Get_ZRange() + dMinBright)]); } } } } //----------------------------------------------------- wxImage Image(Get_NX(), Get_NY()); if( Grid.Get_NoData_Count() > 0 ) { Image.SetAlpha(); } for(y=0; y<Get_NY() && Set_Progress(y); y++) { #pragma omp parallel for for(int x=0; x<Get_NX(); x++) { if( Grid.is_NoData(x, y) || (pShade != NULL && Shade.is_NoData(x, y)) ) { if( Image.HasAlpha() ) { Image.SetAlpha(x, y, wxIMAGE_ALPHA_TRANSPARENT); } Image.SetRGB(x, y, 255, 255, 255); } else { if( Image.HasAlpha() ) { Image.SetAlpha(x, y, wxIMAGE_ALPHA_OPAQUE); } int r, g, b, c = Grid.asInt(x, y); r = SG_GET_R(c); g = SG_GET_G(c); b = SG_GET_B(c); if( pShade ) { c = Shade.asInt(x, y); r = dTrans * r + SG_GET_R(c) * (1.0 - dTrans); g = dTrans * g + SG_GET_G(c) * (1.0 - dTrans); b = dTrans * b + SG_GET_B(c) * (1.0 - dTrans); } Image.SetRGB(x, y, r, g, b); } } } //------------------------------------------------- CSG_String fName(Parameters("FILE")->asString()); if( !SG_File_Cmp_Extension(fName, SG_T("bmp")) && !SG_File_Cmp_Extension(fName, SG_T("jpg")) && !SG_File_Cmp_Extension(fName, SG_T("pcx")) && !SG_File_Cmp_Extension(fName, SG_T("png")) && !SG_File_Cmp_Extension(fName, SG_T("tif")) ) { fName = SG_File_Make_Path(NULL, fName, SG_T("png")); Parameters("FILE")->Set_Value(fName); } //----------------------------------------------------- wxImageHandler *pImgHandler = NULL; if( !SG_UI_Get_Window_Main() ) { if( SG_File_Cmp_Extension(fName, SG_T("jpg")) ) pImgHandler = new wxJPEGHandler; else if( SG_File_Cmp_Extension(fName, SG_T("pcx")) ) pImgHandler = new wxPCXHandler; else if( SG_File_Cmp_Extension(fName, SG_T("tif")) ) pImgHandler = new wxTIFFHandler; #ifdef _SAGA_MSW else if( SG_File_Cmp_Extension(fName, SG_T("bmp")) ) pImgHandler = new wxBMPHandler; #endif else // if( SG_File_Cmp_Extension(fName, SG_T("png")) ) pImgHandler = new wxPNGHandler; wxImage::AddHandler(pImgHandler); } if( !Image.SaveFile(fName.c_str()) ) { Error_Set(CSG_String::Format(SG_T("%s [%s]"), _TL("could not save image file"), fName.c_str())); return( false ); } pGrid->Get_Projection().Save(SG_File_Make_Path(NULL, fName, SG_T("prj")), SG_PROJ_FMT_WKT); //----------------------------------------------------- CSG_File Stream; if( SG_File_Cmp_Extension(fName, SG_T("bmp")) ) Stream.Open(SG_File_Make_Path(NULL, fName, SG_T("bpw")), SG_FILE_W, false); else if( SG_File_Cmp_Extension(fName, SG_T("jpg")) ) Stream.Open(SG_File_Make_Path(NULL, fName, SG_T("jgw")), SG_FILE_W, false); else if( SG_File_Cmp_Extension(fName, SG_T("pcx")) ) Stream.Open(SG_File_Make_Path(NULL, fName, SG_T("pxw")), SG_FILE_W, false); else if( SG_File_Cmp_Extension(fName, SG_T("png")) ) Stream.Open(SG_File_Make_Path(NULL, fName, SG_T("pgw")), SG_FILE_W, false); else if( SG_File_Cmp_Extension(fName, SG_T("tif")) ) Stream.Open(SG_File_Make_Path(NULL, fName, SG_T("tfw")), SG_FILE_W, false); if( Stream.is_Open() ) { Stream.Printf(SG_T("%.10f\n%f\n%f\n%.10f\n%.10f\n%.10f\n"), pGrid->Get_Cellsize(), 0.0, 0.0, -pGrid->Get_Cellsize(), pGrid->Get_XMin(), pGrid->Get_YMax() ); } //----------------------------------------------------- if( Parameters("FILE_KML")->asBool() ) { CSG_MetaData KML; KML.Set_Name("kml"); KML.Add_Property("xmlns", "http://www.opengis.net/kml/2.2"); // CSG_MetaData *pFolder = KML.Add_Child("Folder"); // pFolder->Add_Child("name" , "Raster exported from SAGA"); // pFolder->Add_Child("description", "System for Automated Geoscientific Analyses - www.saga-gis.org"); // CSG_MetaData *pOverlay = pFolder->Add_Child("GroundOverlay"); CSG_MetaData *pOverlay = KML.Add_Child("GroundOverlay"); pOverlay->Add_Child("name" , pGrid->Get_Name()); pOverlay->Add_Child("description", pGrid->Get_Description()); pOverlay->Add_Child("Icon" )->Add_Child("href", SG_File_Get_Name(fName, true)); pOverlay->Add_Child("LatLonBox" ); pOverlay->Get_Child("LatLonBox" )->Add_Child("north", pGrid->Get_YMax()); pOverlay->Get_Child("LatLonBox" )->Add_Child("south", pGrid->Get_YMin()); pOverlay->Get_Child("LatLonBox" )->Add_Child("east" , pGrid->Get_XMax()); pOverlay->Get_Child("LatLonBox" )->Add_Child("west" , pGrid->Get_XMin()); KML.Save(fName, SG_T("kml")); } //----------------------------------------------------- if( !SG_UI_Get_Window_Main() && pImgHandler != NULL) { wxImage::RemoveHandler(pImgHandler->GetName()); } //----------------------------------------------------- return( true ); }

//--------------------------------------------------------- bool Cdirectional1::On_Execute(void) { int x, y, r1, dxmax, dymax, ix, ax, ay, bx, by, iy, iv, iw, n; double r2, ang, a, si, si2, co, co2, cosi, sico, r2co, r2si, Sum; CSG_Grid *pInput, *pResult; pInput = Parameters("INPUT")->asGrid(); pResult = Parameters("RESULT")->asGrid(); ang = Parameters("ANG")->asDouble(); r1 = Parameters("R1")->asInt(); r2 = Parameters("R2")->asDouble(); //----------------------------------------------------- a = ang * 6.283185307179586 / 360; si = sin(a); co = cos(a); si2 = si * si; co2 = co * co; dxmax = (int)((r1*sqrt(co2))+(r2*sqrt(si2))); dymax = (int)((r1*sqrt(si2))+(r2*sqrt(co2))); if(si2 >= co2) { cosi = co / si; r2si = r2 / sqrt(si2); for(y=0; y<Get_NY() && Set_Progress(y); y++) { for(x=0; x<Get_NX(); x++) { Sum = 0.0; n = 0; //---------------------------------------------------- if( (ax = x - dxmax) < 0 ) { ax = 0; } if( (bx = x + dxmax) >= Get_NX() ) { bx = Get_NX() - 1; } if( (ay = y - dymax) < 0 ) { ay = 0; } if( (by = y + dymax) >= Get_NY() ) { by = Get_NY() - 1; } //----------------------------------------------------- for(ix=ax; ix<=bx; ix++) { iv = x - ix; for(iy=ay; iy<=by; iy++) { iw = y - iy; if( iv >= (iw*cosi - r2si) && iv <= (iw*cosi + r2si)) { Sum += pInput->asDouble(ix, iy); n++; } } } if( n > 0 ) { pResult->Set_Value(x, y, Sum/n); } } } } if(si2 < co2) { sico = si / co; r2co = r2 / sqrt(co2); for(y=0; y<Get_NY() && Set_Progress(y); y++) { for(x=0; x<Get_NX(); x++) { Sum = 0.0; n = 0; //---------------------------------------------------- if( (ax = x - dxmax) < 0 ) { ax = 0; } if( (bx = x + dxmax) >= Get_NX() ) { bx = Get_NX() - 1; } if( (ay = y - dymax) < 0 ) { ay = 0; } if( (by = y + dymax) >= Get_NY() ) { by = Get_NY() - 1; } //----------------------------------------------------- for(iy=ay; iy<=by; iy++) { iw = y - iy; for(ix=ax; ix<=bx; ix++) { iv = x - ix; if( iw >= (iv*sico - r2co) && iw <= (iv*sico + r2co)) { Sum += pInput->asDouble(ix, iy); n++; } } } if( n > 0 ) { pResult->Set_Value(x, y, Sum/n); } } } } return( true ); }

//--------------------------------------------------------- bool CGrid_Cross_Profiles::On_Execute(void) { int iLine, iPart, iPoint, nSamples; double Distance, Length, dLine, dist, dx, dy; TSG_Point iPt, jPt, dPt, aPt, bPt; CSG_Shapes *pLines, *pProfiles; CSG_Shape *pLine, *pProfile; //----------------------------------------------------- m_pDEM = Parameters("DEM") ->asGrid(); pProfiles = Parameters("PROFILES") ->asShapes(); pLines = Parameters("LINES") ->asShapes(); Distance = Parameters("DIST_LINE") ->asDouble(); Length = Parameters("DIST_PROFILE")->asDouble(); nSamples = Parameters("NUM_PROFILE") ->asInt(); //----------------------------------------------------- pProfiles->Create(SHAPE_TYPE_Line, _TL("Profiles")); pProfiles->Add_Field("ID" , SG_DATATYPE_Int); pProfiles->Add_Field("LINE" , SG_DATATYPE_Int); pProfiles->Add_Field("PART" , SG_DATATYPE_Int); for(iPoint=0; iPoint<nSamples; iPoint++) { pProfiles->Add_Field(CSG_String::Format(SG_T("X%03d"), iPoint), SG_DATATYPE_Double); } //----------------------------------------------------- for(iLine=0; iLine<pLines->Get_Count() && Set_Progress(iLine, pLines->Get_Count()); iLine++) { pLine = pLines->Get_Shape(iLine); for(iPart=0; iPart<pLine->Get_Part_Count(); iPart++) { if( pLine->Get_Point_Count(iPart) > 1 ) { dist = 0.0; iPt = pLine->Get_Point(0, iPart); for(iPoint=1; iPoint<pLine->Get_Point_Count(iPart); iPoint++) { jPt = iPt; iPt = pLine->Get_Point(iPoint, iPart); dx = iPt.x - jPt.x; dy = iPt.y - jPt.y; dLine = sqrt(dx*dx + dy*dy); dx /= dLine; dy /= dLine; while( dist < dLine ) { dPt.x = jPt.x + dist * dx; dPt.y = jPt.y + dist * dy; if( m_pDEM->is_InGrid_byPos(dPt) ) { aPt.x = dPt.x + dy * Length; aPt.y = dPt.y - dx * Length; bPt.x = dPt.x - dy * Length; bPt.y = dPt.y + dx * Length; pProfile = pProfiles->Add_Shape(); pProfile->Add_Point(aPt); pProfile->Add_Point(bPt); pProfile->Set_Value(0, pProfiles->Get_Count()); pProfile->Set_Value(1, iLine); pProfile->Set_Value(2, iPart); Get_Profile(pProfile, aPt, bPt, nSamples); } dist += Distance; } dist -= dLine; } } } } //----------------------------------------------------- if( pProfiles->Get_Count() > 0 ) { if( Parameters("DOCUMENT")->asString() ) { Make_Report(Parameters("DOCUMENT")->asString(), m_pDEM, pLines, pProfiles, Distance); } return( true ); } return( false ); }

//--------------------------------------------------------- bool CGSGrid_Statistics_To_Table::On_Execute(void) { //----------------------------------------------------- CSG_Parameter_Grid_List *pGrids = Parameters("GRIDS")->asGridList(); if( pGrids->Get_Count() < 1 ) { Error_Set(_TL("no grids in selection")); return( false ); } //----------------------------------------------------- CSG_Table *pTable = Parameters("STATS")->asTable(); pTable->Destroy(); pTable->Set_Name(_TL("Statistics for Grids")); pTable->Add_Field(_TL("NAME"), SG_DATATYPE_String); if( Parameters("DATA_CELLS" )->asBool() ) pTable->Add_Field(_TL("DATA_CELLS" ), SG_DATATYPE_Int); if( Parameters("NODATA_CELLS")->asBool() ) pTable->Add_Field(_TL("NODATA_CELLS"), SG_DATATYPE_Int); if( Parameters("CELLSIZE" )->asBool() ) pTable->Add_Field(_TL("CELLSIZE" ), SG_DATATYPE_Double); if( Parameters("MEAN" )->asBool() ) pTable->Add_Field(_TL("MEAN" ), SG_DATATYPE_Double); if( Parameters("MIN" )->asBool() ) pTable->Add_Field(_TL("MIN" ), SG_DATATYPE_Double); if( Parameters("MAX" )->asBool() ) pTable->Add_Field(_TL("MAX" ), SG_DATATYPE_Double); if( Parameters("RANGE" )->asBool() ) pTable->Add_Field(_TL("RANGE" ), SG_DATATYPE_Double); if( Parameters("VAR" )->asBool() ) pTable->Add_Field(_TL("VAR" ), SG_DATATYPE_Double); if( Parameters("STDDEV" )->asBool() ) pTable->Add_Field(_TL("STDDEV" ), SG_DATATYPE_Double); if( Parameters("STDDEVLO" )->asBool() ) pTable->Add_Field(_TL("STDDEVLO" ), SG_DATATYPE_Double); if( Parameters("STDDEVHI" )->asBool() ) pTable->Add_Field(_TL("STDDEVHI" ), SG_DATATYPE_Double); if( Parameters("PCTL" )->asBool() ) pTable->Add_Field(_TL("PCTL" ), SG_DATATYPE_Double); if( pTable->Get_Field_Count() <= 1 ) { Error_Set(_TL("no parameter output specified")); return( false ); } double dRank = Parameters("PCTL")->asBool() ? Parameters("PCTL_VAL")->asDouble() : -1.0; //----------------------------------------------------- for(int i=0; i<pGrids->Get_Count() && Process_Get_Okay(); i++) { CSG_Grid *pGrid = pGrids->asGrid(i); CSG_Table_Record *pRecord = pTable->Add_Record(); pRecord->Set_Value("NAME" , pGrid->Get_Name()); pRecord->Set_Value("DATA_CELLS" , pGrid->Get_NCells() - pGrid->Get_NoData_Count()); pRecord->Set_Value("NODATA_CELLS", pGrid->Get_NoData_Count()); pRecord->Set_Value("CELLSIZE" , pGrid->Get_Cellsize()); pRecord->Set_Value("MEAN" , pGrid->Get_ArithMean()); pRecord->Set_Value("MIN" , pGrid->Get_ZMin()); pRecord->Set_Value("MAX" , pGrid->Get_ZMax()); pRecord->Set_Value("RANGE" , pGrid->Get_ZRange()); pRecord->Set_Value("VAR" , pGrid->Get_Variance()); pRecord->Set_Value("STDDEV" , pGrid->Get_StdDev()); pRecord->Set_Value("STDDEVLO" , pGrid->Get_ArithMean() - pGrid->Get_StdDev()); pRecord->Set_Value("STDDEVHI" , pGrid->Get_ArithMean() + pGrid->Get_StdDev()); if( dRank > 0.0 && dRank < 100.0 ) { pRecord->Set_Value("PCTL", pGrid->Get_Percentile(dRank)); // this is a time consuming operation } } if( dRank > 0.0 && dRank < 100.0 ) { pTable->Set_Field_Name(pTable->Get_Field_Count() - 1, CSG_String::Format(SG_T("%s%02d"), _TL("PCTL"), (int)dRank)); } return( true ); }

//--------------------------------------------------------- bool CGSGrid_Statistics::On_Execute(void) { //----------------------------------------------------- CSG_Parameter_Grid_List *pGrids = Parameters("GRIDS")->asGridList(); if( pGrids->Get_Count() <= 1 ) { Error_Set(_TL("no grids in selection")); return( false ); } //----------------------------------------------------- CSG_Grid *pMean = Parameters("MEAN" )->asGrid(); CSG_Grid *pMin = Parameters("MIN" )->asGrid(); CSG_Grid *pMax = Parameters("MAX" )->asGrid(); CSG_Grid *pRange = Parameters("RANGE" )->asGrid(); CSG_Grid *pSum = Parameters("SUM" )->asGrid(); CSG_Grid *pVar = Parameters("VAR" )->asGrid(); CSG_Grid *pStdDev = Parameters("STDDEV" )->asGrid(); CSG_Grid *pStdDevLo = Parameters("STDDEVLO")->asGrid(); CSG_Grid *pStdDevHi = Parameters("STDDEVHI")->asGrid(); CSG_Grid *pPercentile = Parameters("PCTL" )->asGrid(); if( !pMean && !pMin && !pMax && !pRange && !pSum && !pVar && !pStdDev && !pStdDevLo && !pStdDevHi && !pPercentile ) { Error_Set(_TL("no parameter output specified")); return( false ); } double dRank = Parameters("PCTL_VAL")->asDouble() / 100.0; //----------------------------------------------------- for(int y=0; y<Get_NY() && Set_Progress(y); y++) { #pragma omp parallel for for(int x=0; x<Get_NX(); x++) { CSG_Table Values; CSG_Simple_Statistics s; for(int i=0; i<pGrids->Get_Count(); i++) { if( !pGrids->asGrid(i)->is_NoData(x, y) ) { double z = pGrids->asGrid(i)->asDouble(x, y); s.Add_Value(z); if( pPercentile ) { if( Values.Get_Field_Count() == 0 ) { Values.Add_Field("Z", SG_DATATYPE_Double); } Values.Add_Record()->Set_Value(0, z); } } } //----------------------------------------- if( s.Get_Count() <= 0 ) { if( pMean ) pMean ->Set_NoData(x, y); if( pMin ) pMin ->Set_NoData(x, y); if( pMax ) pMax ->Set_NoData(x, y); if( pRange ) pRange ->Set_NoData(x, y); if( pSum ) pSum ->Set_NoData(x, y); if( pVar ) pVar ->Set_NoData(x, y); if( pStdDev ) pStdDev ->Set_NoData(x, y); if( pStdDevLo ) pStdDevLo ->Set_NoData(x, y); if( pStdDevHi ) pStdDevHi ->Set_NoData(x, y); if( pPercentile ) pPercentile ->Set_NoData(x, y); } else { if( pMean ) pMean ->Set_Value(x, y, s.Get_Mean()); if( pMin ) pMin ->Set_Value(x, y, s.Get_Minimum()); if( pMax ) pMax ->Set_Value(x, y, s.Get_Maximum()); if( pRange ) pRange ->Set_Value(x, y, s.Get_Range()); if( pSum ) pSum ->Set_Value(x, y, s.Get_Sum()); if( pVar ) pVar ->Set_Value(x, y, s.Get_Variance()); if( pStdDev ) pStdDev ->Set_Value(x, y, s.Get_StdDev()); if( pStdDevLo ) pStdDevLo ->Set_Value(x, y, s.Get_Mean() - s.Get_StdDev()); if( pStdDevHi ) pStdDevHi ->Set_Value(x, y, s.Get_Mean() + s.Get_StdDev()); if( pPercentile ) { Values.Set_Index(0, TABLE_INDEX_Ascending); pPercentile->Set_Value(x, y, Values.Get_Record_byIndex((int)(dRank * s.Get_Count()))->asDouble(0)); } } } } //----------------------------------------------------- return( true ); }

//--------------------------------------------------------- bool CKriging_Regression::On_Execute(void) { //----------------------------------------------------- CSG_Shapes Points(SHAPE_TYPE_Point); CSG_Grid *pPrediction = Parameters("PREDICTION")->asGrid(); CSG_Grid *pRegression = Parameters("REGRESSION")->asGrid(); CSG_Grid *pResiduals = Parameters("RESIDUALS" )->asGrid(); CSG_Grid *pVariance = Parameters("VARIANCE" )->asGrid(); //----------------------------------------------------- if( !pResiduals ) { pResiduals = pPrediction; } //----------------------------------------------------- SG_RUN_TOOL_ExitOnError("statistics_regression", 1, // Multiple Regression Analysis (Points and Predictor Grids) SG_TOOL_PARAMETER_SET("PREDICTORS", Parameters("PREDICTORS")) && SG_TOOL_PARAMETER_SET("POINTS" , Parameters("POINTS" )) && SG_TOOL_PARAMETER_SET("ATTRIBUTE" , Parameters("FIELD" )) && SG_TOOL_PARAMETER_SET("INFO_COEFF", Parameters("INFO_COEFF")) && SG_TOOL_PARAMETER_SET("INFO_MODEL", Parameters("INFO_MODEL")) && SG_TOOL_PARAMETER_SET("INFO_STEPS", Parameters("INFO_STEPS")) && SG_TOOL_PARAMETER_SET("RESAMPLING", Parameters("RESAMPLING")) && SG_TOOL_PARAMETER_SET("COORD_X" , Parameters("COORD_X" )) && SG_TOOL_PARAMETER_SET("COORD_Y" , Parameters("COORD_Y" )) && SG_TOOL_PARAMETER_SET("INTERCEPT" , Parameters("INTERCEPT" )) && SG_TOOL_PARAMETER_SET("METHOD" , Parameters("METHOD" )) && SG_TOOL_PARAMETER_SET("P_VALUE" , Parameters("P_VALUE" )) && SG_TOOL_PARAMETER_SET("REGRESSION", pRegression) && SG_TOOL_PARAMETER_SET("RESIDUALS" , &Points ) ); //----------------------------------------------------- CSG_Tool *pK = Parameters("KRIGING")->asInt() == 0 ? (CSG_Tool *)&m_SK : (CSG_Tool *)&m_OK; Process_Set_Text(pK->Get_Name()); pK->Set_Manager(NULL); if( !pK->Set_Parameter("POINTS" , &Points) || !pK->Set_Parameter("FIELD" , 2) // residual || !pK->Set_Parameter("LOG" , Parameters("LOG" )) || !pK->Set_Parameter("BLOCK" , Parameters("BLOCK" )) || !pK->Set_Parameter("DBLOCK" , Parameters("DBLOCK" )) || !pK->Set_Parameter("SEARCH_RANGE" , Parameters("SEARCH_RANGE" )) || !pK->Set_Parameter("SEARCH_RADIUS" , Parameters("SEARCH_RADIUS" )) || !pK->Set_Parameter("SEARCH_POINTS_ALL", Parameters("SEARCH_POINTS_ALL")) || !pK->Set_Parameter("SEARCH_POINTS_MIN", Parameters("SEARCH_POINTS_MIN")) || !pK->Set_Parameter("SEARCH_POINTS_MAX", Parameters("SEARCH_POINTS_MAX")) || !pK->Set_Parameter("SEARCH_DIRECTION" , Parameters("SEARCH_DIRECTION" )) || !pK->Set_Parameter("TARGET_DEFINITION", 1) // grid or grid system || !pK->Set_Parameter("PREDICTION" , pResiduals) || !pK->Set_Parameter("VARIANCE" , pVariance ) || (!SG_UI_Get_Window_Main() && ( // saga_cmd !pK->Set_Parameter("VAR_MAXDIST" , Parameters("VAR_MAXDIST" )) || !pK->Set_Parameter("VAR_NCLASSES" , Parameters("VAR_NCLASSES" )) || !pK->Set_Parameter("VAR_NSKIP" , Parameters("VAR_NSKIP" )) || !pK->Set_Parameter("VAR_MODEL" , Parameters("VAR_MODEL" )))) ) { Error_Set(CSG_String::Format("%s [%s].[%s]", _TL("could not initialize tool"), _TL("statistics_regression"), pK->Get_Name().c_str())); return( false ); } if( !pK->Execute() ) { Error_Set(CSG_String::Format("%s [%s].[%s]", _TL("could not execute tool" ), _TL("statistics_regression"), pK->Get_Name().c_str())); return( false ); } //----------------------------------------------------- #pragma omp parallel for for(int y=0; y<Get_NY(); y++) { for(int x=0; x<Get_NX(); x++) { if( pRegression->is_NoData(x, y) || pResiduals->is_NoData(x, y) ) { pPrediction->Set_NoData(x, y); } else { pPrediction->Set_Value(x, y, pRegression->asDouble(x, y) + pResiduals->asDouble(x, y)); } } } //----------------------------------------------------- pRegression->Fmt_Name("%s.%s [%s]", Parameters("POINTS")->asShapes()->Get_Name(), Parameters("FIELD")->asString(), _TL("Regression")); pPrediction->Fmt_Name("%s.%s [%s]", Parameters("POINTS")->asShapes()->Get_Name(), Parameters("FIELD")->asString(), _TL("Prediction")); if( Parameters("RESIDUALS")->asGrid() ) { pResiduals->Fmt_Name("%s.%s [%s]", Parameters("POINTS")->asShapes()->Get_Name(), Parameters("FIELD")->asString(), _TL("Residuals")); } if( pVariance ) { pVariance ->Fmt_Name("%s.%s [%s]", Parameters("POINTS")->asShapes()->Get_Name(), Parameters("FIELD")->asString(), _TL("Quality")); } //----------------------------------------------------- return( true ); }

//--------------------------------------------------------- bool CHugget_02::On_Execute(void) { int iStep, nSteps; double sTime, dTime, PrimProd, cHumify, cCarbon, C_Leav, C_Bran, C_Stem, C_Root, C_Litt, C_Humu, C_Coal, P_Leav, P_Bran, P_Stem, P_Root, K_Leav_Litt, K_Bran_Litt, K_Stem_Litt, K_Root_Humu, K_Litt_Humu, K_Humu_Coal, K_Coal_Envi, d_Leav_Litt, d_Bran_Litt, d_Stem_Litt, d_Root_Humu, d_Litt_Humu, d_Humu_Coal, d_Coal_Envi; CSG_Table_Record *pRecord; CSG_Table *pTable; //----------------------------------------------------- sTime = Parameters("TIME_SPAN") ->asDouble(); dTime = Parameters("TIME_STEP") ->asDouble(); nSteps = (int)(sTime / dTime); PrimProd = Parameters("PRIMPROD") ->asDouble(); cHumify = Parameters("CHUMIFY") ->asDouble(); cCarbon = Parameters("CCARBON") ->asDouble(); P_Leav = Parameters("P_LEAV") ->asDouble(); P_Bran = Parameters("P_BRAN") ->asDouble(); P_Stem = Parameters("P_STEM") ->asDouble(); P_Root = Parameters("P_ROOT") ->asDouble(); K_Leav_Litt = Parameters("K_LEAV_LITT") ->asDouble(); K_Bran_Litt = Parameters("K_BRAN_LITT") ->asDouble(); K_Stem_Litt = Parameters("K_STEM_LITT") ->asDouble(); K_Root_Humu = Parameters("K_ROOT_HUMU") ->asDouble(); K_Litt_Humu = Parameters("K_LITT_HUMU") ->asDouble(); K_Humu_Coal = Parameters("K_HUMU_COAL") ->asDouble(); K_Coal_Envi = Parameters("K_COAL_ENVI") ->asDouble(); pTable = Parameters("TABLE") ->asTable(); pTable->Destroy(); pTable->Set_Name(_TL("Carbon Cycle Simulation")); pTable->Add_Field("STEP" , SG_DATATYPE_Int); pTable->Add_Field("TIME" , SG_DATATYPE_Double); pTable->Add_Field("LEAVES" , SG_DATATYPE_Double); pTable->Add_Field("BRANCHES", SG_DATATYPE_Double); pTable->Add_Field("STEMS" , SG_DATATYPE_Double); pTable->Add_Field("ROOTS" , SG_DATATYPE_Double); pTable->Add_Field("LITTER" , SG_DATATYPE_Double); pTable->Add_Field("HUMUS" , SG_DATATYPE_Double); pTable->Add_Field("CHARCOAL", SG_DATATYPE_Double); //----------------------------------------------------- C_Leav = 0.0; C_Bran = 0.0; C_Stem = 0.0; C_Root = 0.0; C_Litt = 0.0; C_Humu = 0.0; C_Coal = 0.0; //----------------------------------------------------- for(iStep=0; iStep<nSteps && Set_Progress(iStep, nSteps); iStep++) { WRITE_RECORD; d_Leav_Litt = K_Leav_Litt * C_Leav; d_Bran_Litt = K_Bran_Litt * C_Bran; d_Stem_Litt = K_Stem_Litt * C_Stem; d_Root_Humu = K_Root_Humu * C_Root; d_Litt_Humu = K_Litt_Humu * C_Litt; d_Humu_Coal = K_Humu_Coal * C_Humu; d_Coal_Envi = K_Coal_Envi * C_Coal; C_Leav = C_Leav + dTime * (-d_Leav_Litt + P_Leav * PrimProd); C_Bran = C_Bran + dTime * (-d_Bran_Litt + P_Bran * PrimProd); C_Stem = C_Stem + dTime * (-d_Stem_Litt + P_Stem * PrimProd); C_Root = C_Root + dTime * (-d_Root_Humu + P_Root * PrimProd); C_Litt = C_Litt + dTime * (-d_Litt_Humu + d_Leav_Litt + d_Bran_Litt + d_Stem_Litt); C_Humu = C_Humu + dTime * (-d_Humu_Coal + cHumify * (d_Root_Humu + d_Litt_Humu)); C_Coal = C_Coal + dTime * (-d_Coal_Envi + cCarbon * (d_Humu_Coal)); } WRITE_RECORD; //----------------------------------------------------- return( true ); }

//--------------------------------------------------------- bool CGW_Multi_Regression_Grid::On_Execute(void) { int i; //----------------------------------------------------- CSG_Parameter_Grid_List *pPredictors = Parameters("PREDICTORS")->asGridList(); if( !Initialize(Parameters("POINTS")->asShapes(), Parameters("DEPENDENT")->asInt(), pPredictors) ) { Finalize(); return( false ); } //----------------------------------------------------- CSG_Grid Quality; m_dimModel = *Get_System(); if( Parameters("RESOLUTION")->asInt() == 1 && Parameters("RESOLUTION_VAL")->asDouble() > Get_Cellsize() ) { CSG_Rect r(Get_System()->Get_Extent()); r.Inflate(0.5 * Parameters("RESOLUTION_VAL")->asDouble(), false); m_dimModel.Assign(Parameters("RESOLUTION_VAL")->asDouble(), r); Quality.Create(m_dimModel); m_pQuality = &Quality; } else { m_pQuality = Parameters("QUALITY")->asGrid(); } //----------------------------------------------------- Process_Set_Text(_TL("upsetting model domain")); m_pPredictors = (CSG_Grid **)SG_Calloc(m_nPredictors , sizeof(CSG_Grid *)); m_pModel = (CSG_Grid **)SG_Calloc(m_nPredictors + 1, sizeof(CSG_Grid *)); for(i=0; i<m_nPredictors; i++) { if( m_dimModel.Get_Cellsize() > Get_Cellsize() ) // scaling { m_pPredictors[i] = SG_Create_Grid(m_dimModel); m_pPredictors[i] ->Assign(pPredictors->asGrid(i), GRID_INTERPOLATION_NearestNeighbour); // GRID_INTERPOLATION_Mean_Cells } else { m_pPredictors[i] = pPredictors->asGrid(i); } m_pModel [i] = SG_Create_Grid(m_dimModel); m_pModel [i] ->Set_Name(CSG_String::Format(SG_T("%s [%s]"), pPredictors->asGrid(i)->Get_Name(), _TL("Factor"))); } m_pModel[m_nPredictors] = SG_Create_Grid(m_dimModel); m_pModel[m_nPredictors] ->Set_Name(_TL("Intercept")); //----------------------------------------------------- Process_Set_Text(_TL("model creation")); bool bResult = Get_Model(); //----------------------------------------------------- if( m_dimModel.Get_Cellsize() > Get_Cellsize() ) // scaling { for(i=0; i<m_nPredictors; i++) { delete(m_pPredictors[i]); m_pPredictors[i] = pPredictors->asGrid(i); } } //----------------------------------------------------- if( bResult ) { Process_Set_Text(_TL("model application")); bResult = Set_Model(); } //----------------------------------------------------- if( Parameters("MODEL_OUT")->asBool() ) { CSG_Parameter_Grid_List *pModel = Parameters("MODEL")->asGridList(); pModel->Del_Items(); pModel->Add_Item(m_pModel[m_nPredictors]); for(i=0; i<m_nPredictors; i++) { pModel->Add_Item(m_pModel[i]); } } else { for(i=0; i<=m_nPredictors; i++) { delete(m_pModel[i]); } } SG_FREE_SAFE(m_pModel); SG_FREE_SAFE(m_pPredictors); Finalize(); return( bResult ); }

//--------------------------------------------------------- bool CCost_Accumulated::Get_Cost(CPoints &Points) { CPoints Next; CSG_Grid Next_Index(Get_System(), SG_DATATYPE_Int); double Threshold = Parameters("THRESHOLD")->asDouble(); sLong nProcessed = Points.Get_Count(); while( Points.Get_Count() > 0 && Set_Progress_NCells(nProcessed) ) { Process_Set_Text("%s: %d", _TL("cells in process"), Points.Get_Count()); int iPoint; //------------------------------------------------- Next.Clear(); for(iPoint=0; iPoint<Points.Get_Count(); iPoint++) { TSG_Point_Int p = Points[iPoint]; double Cost = m_pCost ->asDouble(p.x, p.y); double Accu = m_pAccumulated->asDouble(p.x, p.y); for(int i=0; i<8; i++) { int ix = Get_xTo(i, p.x); int iy = Get_yTo(i, p.y); if( m_pCost->is_InGrid(ix, iy) ) { double iCost = Get_UnitLength(i); if( m_pDirection && m_pDirection->is_InGrid(p.x, p.y) && m_pDirection->is_InGrid(ix, iy) ) { static const double dAngles[8] = { 0.0, M_PI_045, M_PI_090, M_PI_135, M_PI_180, M_PI_225, M_PI_270, M_PI_315 }; double d1 = m_pDirection->asDouble(p.x, p.y); d1 = pow(cos(fabs((m_bDegree ? M_DEG_TO_RAD * d1 : d1) - dAngles[i])), m_dK); double d2 = m_pDirection->asDouble( ix, iy); d2 = pow(cos(fabs((m_bDegree ? M_DEG_TO_RAD * d2 : d2) - dAngles[i])), m_dK); iCost *= (d1 + d2) / 2.0; } iCost = Accu + iCost * (Cost + m_pCost->asDouble(ix, iy)) / 2.0; //------------------------------------- bool bProcessed = !m_pAccumulated->is_NoData(ix, iy); if( !bProcessed || m_pAccumulated->asDouble(ix, iy) > iCost + Threshold ) { if( !bProcessed ) { nProcessed++; } Next_Index .Set_Value(ix, iy, Next.Get_Count()); // remember last point (least cost!) added at position ix/iy Next .Add (ix, iy); m_pAccumulated->Set_Value(ix, iy, iCost); } } } } //------------------------------------------------- Points.Clear(); for(iPoint=0; iPoint<Next.Get_Count(); iPoint++) { TSG_Point_Int p = Next[iPoint]; if( Next_Index.asInt(p.x, p.y) == iPoint ) { Points.Add(p.x, p.y); } } } return( true ); }

//--------------------------------------------------------- bool CLeastCostPathProfile_Points::On_Execute(void) { int x, y; CSG_Shape *pShape; CSG_Shapes *pSources; CSG_Shapes *pPoints, *pLine; CSG_Parameter_Shapes_List *pShapesPoints, *pShapesLine; pSources = Parameters("SOURCE") ->asShapes(); m_pDEM = Parameters("DEM") ->asGrid(); m_pValues = Parameters("VALUES") ->asGridList(); pShapesPoints = Parameters("POINTS") ->asShapesList(); pShapesLine = Parameters("LINE") ->asShapesList(); //----------------------------------------------------- pShapesPoints ->Del_Items(); pShapesLine ->Del_Items(); //----------------------------------------------------- for( int i=0; i<pSources->Get_Count(); i++ ) { pShape = pSources->Get_Shape(i); if( Get_System()->Get_World_to_Grid(x, y, pShape->Get_Point(0)) && m_pDEM->is_InGrid(x, y) ) { //----------------------------------------------------- pPoints = SG_Create_Shapes(SHAPE_TYPE_Point, CSG_String::Format(_TL("Profile_Points_[%s]_%d"), m_pDEM->Get_Name(), i+1)); pPoints ->Add_Field("ID" , SG_DATATYPE_Int); pPoints ->Add_Field("D" , SG_DATATYPE_Double); pPoints ->Add_Field("X" , SG_DATATYPE_Double); pPoints ->Add_Field("Y" , SG_DATATYPE_Double); pPoints ->Add_Field("Z" , SG_DATATYPE_Double); for( int j=0; j<m_pValues->Get_Count(); j++) { pPoints->Add_Field(m_pValues->asGrid(j)->Get_Name(), SG_DATATYPE_Double); } //----------------------------------------------------- pLine = SG_Create_Shapes(SHAPE_TYPE_Line, CSG_String::Format(_TL("Profile_Line_[%s]_%d"), m_pDEM->Get_Name(), i+1)); pLine ->Add_Field("ID", SG_DATATYPE_Int); pLine ->Add_Shape()->Set_Value(0, 1); Set_Profile(x, y, pPoints, pLine); //----------------------------------------------------- if( pPoints->Get_Count() > 0 ) { pShapesPoints->Add_Item(pPoints); pShapesLine->Add_Item(pLine); } else { delete(pPoints); delete(pLine); } } } return( pShapesPoints->Get_Count() > 0 ); }

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

//--------------------------------------------------------- bool CGradient_Cartes_To_Polar::On_Execute(void) { bool bDegree, bClockwise; int Method; double DX, DY, DIR, Zero; CSG_Grid *pDX, *pDY, *pDIR, *pLEN; //----------------------------------------------------- pDX = Parameters("DX") ->asGrid(); pDY = Parameters("DY") ->asGrid(); pDIR = Parameters("DIR") ->asGrid(); pLEN = Parameters("LEN") ->asGrid(); bDegree = Parameters("UNITS") ->asInt() == 1; Method = Parameters("SYSTEM") ->asInt(); if( Method == 0 ) // mathematic { Zero = M_PI_090; bClockwise = false; } else { Zero = Parameters("SYSTEM_ZERO")->asDouble() * M_DEG_TO_RAD; bClockwise = Parameters("SYSTEM_ORIENT")->asInt() == 0; } //----------------------------------------------------- for(int y=0; y<Get_NY() && Set_Progress(y); y++) { for(int x=0; x<Get_NX(); x++) { if( pDX->is_NoData(x, y) || pDY->is_NoData(x, y) ) { pLEN->Set_NoData(x, y); pDIR->Set_NoData(x, y); } else { DX = pDX->asDouble(x, y); DY = pDY->asDouble(x, y); if( DX == 0.0 && DY == 0.0 ) { pLEN->Set_Value (x, y, 0.0); pDIR->Set_NoData(x, y); } else { DIR = DY != 0.0 ? fmod(M_PI_360 + atan2(DX, DY), M_PI_360) : DX < 0.0 ? M_PI_270 : M_PI_090; if( Method != 1 ) // not geographic { DIR = fmod(M_PI_360 + (bClockwise ? DIR - Zero : Zero - DIR), M_PI_360); } pLEN->Set_Value(x, y, sqrt(DX*DX + DY*DY)); pDIR->Set_Value(x, y, bDegree ? M_RAD_TO_DEG * DIR : DIR); } } } } return( true ); }

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, true)); 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

void CSimulateVariableWind::CreateReport(){ CSG_String sReportFile, sFile; int i; if (Parameters("REPORTFILE")->asString() != NULL){ sReportFile = Parameters("REPORTFILE")->asString(); CalculateReportParameters(); char cDate[81]; time_t curTime; tm * timeinfo; time(&curTime); timeinfo = gmtime(&curTime); // std::locale spanish("esp"); // std::locale::global(spanish); strftime(cDate, 80, "%#x", timeinfo); sFile += "\t\t\t SIMULACIÓN realizada el "; sFile += cDate; sFile += "\n\t\t =============================================================================="; sFile += "\n\n\t Parámetros de entrada\n"; sFile += "\t --------------------------------\n\n"; sFile += "\t\t Modelos de combustible (por area) \n: "; for (i = 0; i < 12; i++){ if (m_pAreaByFuelModel[i]){ sFile += "\t\t\t * "; sFile += SG_Get_String(i + 1, 0) + " : " + SG_Get_String(m_pAreaByFuelModel[i]) + " ha\n"; }//if }//for sFile += "\t\t Humedad de los combustibles muertos (1 h): "; sFile += SG_Get_String(m_fDeadFuelMoisture) + " %\n"; sFile += "\t\t Velocidad del viento a media llama: \n" ; for(i = 0; i < m_iWindSpdGrids; i++){ sFile += "\t\t\t * "; sFile += SG_Get_String(i * m_fInterval, 0) + " min: " + SG_Get_String(m_pMeanWindSpd[i]) + "Km/h\n"; }//for sFile += "\t\t Dirección del vector viento, desde el norte geográfico: \n"; for(i = 0; i < m_iWindDirGrids; i++){ sFile += "\t\t\t * "; sFile += SG_Get_String(i * m_fInterval, 0) + " min: " + SG_Get_String(m_pMeanWindDir[i]) + "º\n"; }//for sFile += "\t\t Pendiente del terreno media: "; sFile += SG_Get_String(m_fSlope) + " %\n"; sFile += "\t\t Orientación del terreno: "; sFile += SG_Get_String(m_fAspect) + "º\n"; sFile += "\t\t Foco de partida: X = "; sFile += SG_Get_String(Parameters("COORDX")->asDouble(), 0) + " / Y = " + SG_Get_String(Parameters("COORDY")->asDouble(), 0) + "\n"; sFile += "\t\t Tiempo de simulación: 3.0 h"; sFile += "\n\n\t Resultado de la simulación\n"; sFile += "\t --------------------------------\n\n"; sFile += "\t\t Velocidad de propagación: "; sFile += SG_Get_String(m_fMeanSpeed) + " m/min\n"; sFile += "\t\t Calor por unidad de area: "; sFile += SG_Get_String(m_fHeatPerUnitArea) + " kJ/m^2\n"; //revisar unidades!! sFile += "\t\t Intensidad de la línea de fuego: "; sFile += SG_Get_String(m_fIntensity) + " kCal/m\n"; sFile += "\t\t Longitud de la llama: "; sFile += SG_Get_String(m_fFlameHeight) + " m\n"; sFile += "\t\t Intensidad de reacción: "; sFile += SG_Get_String(m_fReactionIntensity) + " kCal/m2\n"; sFile += "\t\t Velocidad efectiva del viento: "; sFile += SG_Get_String(m_fEffectiveWind / KMH2FTMIN) + " Km/h\n"; sFile += "\t\t Dirección de máxima propagación, desde el norte geográfico: "; sFile += SG_Get_String(m_fMaxSpreadDir) + "º\n"; sFile += "\t\t Area: "; sFile += SG_Get_String(m_fArea / 10000) + " ha\n"; sFile += "\t\t Perímetro: "; sFile += SG_Get_String(m_fPerimeter) + "m\n"; //Razón Longitud/Ancho: 1.9 sFile += "\t\t Distancia de propagación hacia delante: "; sFile += SG_Get_String(m_fFrontDistance) + " m\n"; sFile += "\t\t Distancia de propagación hacia atrás: "; sFile += SG_Get_String(m_fRearDistance) + " m\n"; CSG_File file; if( file.Open(sReportFile, SG_FILE_W, false) ) { file.Write(sFile); } }//if }//method

//--------------------------------------------------------- bool CClip_Points::On_Execute(void) { int Method, iField; CSG_Shapes *pPoints, *pPolygons, *pClip; CSG_Parameter_Shapes_List *pClips; //----------------------------------------------------- pPoints = Parameters("POINTS") ->asShapes(); pPolygons = Parameters("POLYGONS") ->asShapes(); pClips = Parameters("CLIPS") ->asShapesList(); Method = Parameters("METHOD") ->asInt(); iField = Parameters("FIELD") ->asInt(); //----------------------------------------------------- if( !pPoints->is_Valid() ) { Message_Add(_TL("Invalid points layer.")); return( false ); } else if( !pPolygons->is_Valid() ) { Message_Add(_TL("Invalid polygon layer.")); return( false ); } //----------------------------------------------------- if( iField >= pPolygons->Get_Field_Count() ) { iField = -1; } pClips->Del_Items(); if( Method == 0 ) { pClip = SG_Create_Shapes(SHAPE_TYPE_Point, CSG_String::Format(SG_T("%s [%s]"), pPoints->Get_Name(), pPolygons->Get_Name()), pPoints); if( iField >= 0 ) { pClip->Add_Field(pPolygons->Get_Field_Name(iField), pPolygons->Get_Field_Type(iField)); } } //----------------------------------------------------- for(int iPolygon=0; iPolygon<pPolygons->Get_Count() && Set_Progress(iPolygon, pPolygons->Get_Count()); iPolygon++) { CSG_Shape_Polygon *pPolygon = (CSG_Shape_Polygon *)pPolygons->Get_Shape(iPolygon); if( Method == 1 ) { CSG_String Name(pPoints->Get_Name()); Name += iField >= 0 ? CSG_String::Format(SG_T(" [%s]"), pPolygon->asString(iField)) : CSG_String::Format(SG_T(" [%00d]"), 1 + pClips->Get_Count()); pClip = SG_Create_Shapes(SHAPE_TYPE_Point, Name, pPoints); if( iField >= 0 ) { pClip->Add_Field(pPolygons->Get_Field_Name(iField), pPolygons->Get_Field_Type(iField)); } } for(int iPoint=0; iPoint<pPoints->Get_Count() && Process_Get_Okay(false); iPoint++) { CSG_Shape *pPoint = pPoints->Get_Shape(iPoint); if( pPolygon->Contains(pPoint->Get_Point(0)) ) { pPoint = pClip->Add_Shape(pPoint, SHAPE_COPY); if( iField >= 0 ) { pPoint->Set_Value(pPoints->Get_Field_Count(), pPolygon->asString(iField)); } } } if( Method == 1 ) { if( pClip->Get_Count() > 0 ) { pClips->Add_Item(pClip); } else { delete(pClip); } } } //----------------------------------------------------- if( Method == 0 ) { if( pClip->Get_Count() > 0 ) { pClips->Add_Item(pClip); } else { delete(pClip); } } return( pClips->Get_Count() > 0 ); }

//--------------------------------------------------------- bool CFilter_3x3::On_Execute(void) { //----------------------------------------------------- CSG_Table *pFilter = Parameters("FILTER")->asTable() ? Parameters("FILTER" )->asTable() : Parameters("FILTER_3X3")->asTable(); if( pFilter->Get_Count() < 1 || pFilter->Get_Field_Count() < 1 ) { Error_Set(_TL("invalid filter matrix")); return( false ); } //----------------------------------------------------- CSG_Matrix Filter(pFilter->Get_Field_Count(), pFilter->Get_Count()); { for(int iy=0; iy<Filter.Get_NY(); iy++) { CSG_Table_Record *pRecord = pFilter->Get_Record(iy); for(int ix=0; ix<Filter.Get_NX(); ix++) { Filter[iy][ix] = pRecord->asDouble(ix); } } } int nx = (Filter.Get_NX() - 1) / 2; int ny = (Filter.Get_NY() - 1) / 2; //----------------------------------------------------- CSG_Grid *pInput = Parameters("INPUT" )->asGrid(); CSG_Grid *pResult = Parameters("RESULT")->asGrid(); if( !pResult || pResult == pInput ) { pResult = SG_Create_Grid(pInput); } else { pResult->Fmt_Name("%s [%s]", pInput->Get_Name(), _TL("Filter")); pResult->Set_NoData_Value(pInput->Get_NoData_Value()); } //----------------------------------------------------- bool bAbsolute = Parameters("ABSOLUTE")->asBool(); for(int y=0; y<Get_NY() && Set_Progress(y); y++) { #pragma omp parallel for for(int x=0; x<Get_NX(); x++) { double s = 0.0; double n = 0.0; if( pInput->is_InGrid(x, y) ) { for(int iy=0, jy=y-ny; iy<Filter.Get_NY(); iy++, jy++) { for(int ix=0, jx=x-nx; ix<Filter.Get_NX(); ix++, jx++) { if( pInput->is_InGrid(jx, jy) ) { s += Filter[iy][ix] * pInput->asDouble(jx, jy); n += fabs(Filter[iy][ix]); } } } } if( n > 0.0 ) { pResult->Set_Value(x, y, bAbsolute ? s : s / n); } else { pResult->Set_NoData(x, y); } } } //----------------------------------------------------- if( !Parameters("RESULT")->asGrid() || Parameters("RESULT")->asGrid() == pInput ) { pInput->Assign(pResult); delete(pResult); DataObject_Update(pInput); } return( true ); }

//--------------------------------------------------------- bool CGW_Regression::On_Execute(void) { //----------------------------------------------------- m_pPoints = Parameters("POINTS") ->asShapes(); m_iDependent = Parameters("DEPENDENT") ->asInt(); m_iPredictor = Parameters("PREDICTOR") ->asInt(); m_Radius = Parameters("RANGE") ->asInt() == 0 ? Parameters("RADIUS") ->asDouble() : 0.0; m_Mode = Parameters("MODE") ->asInt(); m_nPoints_Max = Parameters("NPOINTS") ->asInt() == 0 ? Parameters("MAXPOINTS")->asInt() : 0; m_nPoints_Min = Parameters("MINPOINTS") ->asInt(); m_Weighting.Set_Parameters(Parameters("WEIGHTING")->asParameters()); //----------------------------------------------------- if( (m_nPoints_Max > 0 || m_Radius > 0.0) && !m_Search.Create(m_pPoints, -1) ) { return( false ); } //----------------------------------------------------- m_pIntercept = NULL; m_pSlope = NULL; m_pQuality = NULL; switch( Parameters("TARGET")->asInt() ) { case 0: // user defined... if( m_Grid_Target.Init_User(m_pPoints->Get_Extent()) && Dlg_Parameters("USER") ) { m_pIntercept = m_Grid_Target.Get_User(SG_T("INTERCEPT")); m_pSlope = m_Grid_Target.Get_User(SG_T("SLOPE")); m_pQuality = m_Grid_Target.Get_User(SG_T("QUALITY")); } break; case 1: // grid... if( Dlg_Parameters("GRID") ) { m_pIntercept = m_Grid_Target.Get_Grid(SG_T("INTERCEPT")); m_pSlope = m_Grid_Target.Get_Grid(SG_T("SLOPE")); m_pQuality = m_Grid_Target.Get_Grid(SG_T("QUALITY")); } break; } if( m_pIntercept == NULL ) { m_Search.Destroy(); return( false ); } m_pIntercept->Set_Name(CSG_String::Format(SG_T("%s (%s)"), m_pPoints->Get_Name(), _TL("GWR Intercept"))); m_pSlope ->Set_Name(CSG_String::Format(SG_T("%s (%s)"), m_pPoints->Get_Name(), _TL("GWR Slope"))); m_pQuality ->Set_Name(CSG_String::Format(SG_T("%s (%s)"), m_pPoints->Get_Name(), _TL("GWR Quality"))); //----------------------------------------------------- int nPoints_Max = m_nPoints_Max > 0 ? m_nPoints_Max : m_pPoints->Get_Count(); m_y.Create(nPoints_Max); m_z.Create(nPoints_Max); m_w.Create(nPoints_Max); //----------------------------------------------------- for(int y=0; y<m_pIntercept->Get_NY() && Set_Progress(y, m_pIntercept->Get_NY()); y++) { for(int x=0; x<m_pIntercept->Get_NX(); x++) { if( !Get_Regression(x, y) ) { m_pIntercept->Set_NoData(x, y); m_pSlope ->Set_NoData(x, y); m_pQuality ->Set_NoData(x, y); } } } //----------------------------------------------------- m_y.Destroy(); m_z.Destroy(); m_w.Destroy(); m_Search.Destroy(); DataObject_Update(m_pIntercept); DataObject_Update(m_pSlope); DataObject_Update(m_pQuality); return( true ); }

//--------------------------------------------------------- bool CShapes_Cut::Get_Extent(CSG_Rect &r) { m_pPolygons = NULL; switch( Parameters("TARGET")->asInt() ) { //----------------------------------------------------- case 0: // user defined Get_Parameters("CUT")->Get_Parameter("AX")->Set_Value(r.Get_XMin()); Get_Parameters("CUT")->Get_Parameter("AY")->Set_Value(r.Get_YMin()); Get_Parameters("CUT")->Get_Parameter("BX")->Set_Value(r.Get_XMax()); Get_Parameters("CUT")->Get_Parameter("BY")->Set_Value(r.Get_YMax()); Get_Parameters("CUT")->Get_Parameter("DX")->Set_Value(r.Get_XRange()); Get_Parameters("CUT")->Get_Parameter("DY")->Set_Value(r.Get_YRange()); if( Dlg_Parameters("CUT") ) { r.Assign( Get_Parameters("CUT")->Get_Parameter("AX")->asDouble(), Get_Parameters("CUT")->Get_Parameter("AY")->asDouble(), Get_Parameters("CUT")->Get_Parameter("BX")->asDouble(), Get_Parameters("CUT")->Get_Parameter("BY")->asDouble() ); return( true ); } break; //----------------------------------------------------- case 1: // grid project if( Dlg_Parameters("GRID") ) { r.Assign(Get_Parameters("GRID")->Get_Parameter("GRID")->asGrid_System()->Get_Extent()); return( true ); } break; //----------------------------------------------------- case 2: // shapes extent if( Dlg_Parameters("SHAPES") ) { r.Assign(Get_Parameters("SHAPES")->Get_Parameter("SHAPES")->asShapes()->Get_Extent()); return( true ); } break; //----------------------------------------------------- case 3: // polygons if( Dlg_Parameters("POLYGONS") ) { r.Assign(Get_Parameters("POLYGONS")->Get_Parameter("POLYGONS")->asShapes()->Get_Extent()); m_pPolygons = Get_Parameters("POLYGONS")->Get_Parameter("POLYGONS")->asShapes(); return( true ); } break; } return( false ); }

//--------------------------------------------------------- bool CPC_Transform::On_Execute(void) { bool bCopy; double angleX, angleY, angleZ; TSG_Point_Z P, Q, Move, Scale, Anchor; CSG_PointCloud *pIn, *pOut; double a11, a12, a13, a21, a22, a23, a31, a32, a33; //----------------------------------------------------- pIn = Parameters("IN") ->asPointCloud(); pOut = Parameters("OUT") ->asPointCloud(); Scale.x = Parameters("SCALEX") ->asDouble(); Scale.y = Parameters("SCALEY") ->asDouble(); Scale.z = Parameters("SCALEZ") ->asDouble(); Move.x = Parameters("DX") ->asDouble(); Move.y = Parameters("DY") ->asDouble(); Move.z = Parameters("DZ") ->asDouble(); Anchor.x = Parameters("ANCHORX") ->asDouble(); Anchor.y = Parameters("ANCHORY") ->asDouble(); Anchor.z = Parameters("ANCHORZ") ->asDouble(); angleX = Parameters("ANGLEX") ->asDouble() * -M_DEG_TO_RAD; angleY = Parameters("ANGLEY") ->asDouble() * -M_DEG_TO_RAD; angleZ = Parameters("ANGLEZ") ->asDouble() * -M_DEG_TO_RAD; if( pIn == pOut ) { bCopy = true; pOut = SG_Create_PointCloud(); } else bCopy = false; pOut->Create(pIn); pOut->Set_Name(CSG_String::Format(SG_T("%s [%s]"), pIn->Get_Name(), _TL("Transformed"))); //----------------------------------------------------- for (int iPoint=0; iPoint<pIn->Get_Point_Count(); iPoint++) { P = pIn->Get_Point(iPoint); //anchor shift P.x -= Anchor.x; P.y -= Anchor.y; P.z -= Anchor.z; // create rotation matrix a11 = cos(angleY) * cos(angleZ); a12 = -cos(angleX) * sin(angleZ) + sin(angleX) * sin(angleY) * cos(angleZ); a13 = sin(angleX) * sin(angleZ) + cos(angleX) * sin(angleY) * cos(angleZ); a21 = cos(angleY) * sin(angleZ); a22 = cos(angleX) * cos(angleZ) + sin(angleX) * sin(angleY) * sin(angleZ); a23 = -sin(angleX) * cos(angleZ) + cos(angleX) * sin(angleY) * sin(angleZ); a31 = -sin(angleY); a32 = sin(angleX) * cos(angleY); a33 = cos(angleX) * cos(angleY); //transform Q.x = (P.x * a11 + P.y * a12 + P.z * a13) * Scale.x; Q.y = (P.x * a21 + P.y * a22 + P.z * a23) * Scale.y; Q.z = (P.x * a31 + P.y * a32 + P.z * a33) * Scale.z; //undo anchor shift and apply move Q.x += Anchor.x + Move.x; Q.y += Anchor.y + Move.y; Q.z += Anchor.z + Move.z; pOut->Add_Point(Q.x, Q.y, Q.z); for (int iField=0; iField<pIn->Get_Attribute_Count(); iField++) pOut->Set_Attribute(iPoint, iField, pIn->Get_Attribute(iPoint, iField)); } //----------------------------------------------------- if( bCopy ) { pIn->Assign(pOut); delete(pOut); } //----------------------------------------------------- return( true ); }

//--------------------------------------------------------- bool CSurfer_Import::On_Execute(void) { //----------------------------------------------------- CSG_String File = Parameters("FILE")->asString(); FILE *Stream = fopen(File.b_str(), "rb"); if( !Stream ) { Error_Set(_TL("failed to open file")); return( false ); } CSG_Grid *pGrid = NULL; char Id[4]; fread(Id, 1, 4 * sizeof(char), Stream); //----------------------------------------------------- if( !strncmp(Id, "DSRB", 4) ) // Surfer 7: Binary... { long lValue, nx, ny; double dValue, dx, dy, xmin, ymin; fread(&lValue, 1, sizeof(long), Stream); // SectionSize... fread(&lValue, 1, sizeof(long), Stream); // Version fread(&lValue, 1, sizeof(long), Stream); if( lValue == 0x44495247 ) // Grid-Header... { fread(&lValue, 1, sizeof(long ), Stream); // SectionSize... fread(&ny , 1, sizeof(long ), Stream); fread(&nx , 1, sizeof(long ), Stream); fread(&xmin , 1, sizeof(double), Stream); fread(&ymin , 1, sizeof(double), Stream); fread(&dx , 1, sizeof(double), Stream); fread(&dy , 1, sizeof(double), Stream); fread(&dValue, 1, sizeof(double), Stream); fread(&dValue, 1, sizeof(double), Stream); fread(&dValue, 1, sizeof(double), Stream); // Rotation (unused)... fread(&dValue, 1, sizeof(double), Stream); // Blank Value... fread(&lValue, 1, sizeof(long ), Stream); // ???... if( lValue == 0x41544144 ) // Load Binary Double... { fread(&lValue, 1, sizeof(long), Stream); // SectionSize... //----------------------------------------- if( !feof(Stream) && (pGrid = SG_Create_Grid(SG_DATATYPE_Double, nx, ny, dx, xmin, ymin)) != NULL ) { double *Line = (double *)SG_Malloc(pGrid->Get_NX() * sizeof(double)); for(int y=0; y<pGrid->Get_NY() && !feof(Stream) && Set_Progress(y, pGrid->Get_NY()); y++) { fread(Line, pGrid->Get_NX(), sizeof(double), Stream); for(int x=0; x<pGrid->Get_NX(); x++) { pGrid->Set_Value(x, y, Line[x]); } } SG_Free(Line); } } } } //----------------------------------------------------- else if( !strncmp(Id, "DSBB", 4) ) // Surfer 6: Binary... { short nx, ny; double dValue, dx, dy, xmin, ymin; fread(&nx , 1, sizeof(short ), Stream); fread(&ny , 1, sizeof(short ), Stream); fread(&xmin , 1, sizeof(double), Stream); fread(&dx , 1, sizeof(double), Stream); dx = (dx - xmin) / (nx - 1.0); // XMax fread(&ymin , 1, sizeof(double), Stream); fread(&dy , 1, sizeof(double), Stream); dy = (dy - ymin) / (ny - 1.0); // YMax... fread(&dValue, 1, sizeof(double), Stream); // ZMin... fread(&dValue, 1, sizeof(double), Stream); // ZMax... //------------------------------------------------- if( !feof(Stream) && (pGrid = SG_Create_Grid(SG_DATATYPE_Float, nx, ny, dx, xmin, ymin)) != NULL ) { float *Line = (float *)SG_Malloc(pGrid->Get_NX() * sizeof(float)); for(int y=0; y<pGrid->Get_NY() && !feof(Stream) && Set_Progress(y, pGrid->Get_NY()); y++) { fread(Line, pGrid->Get_NX(), sizeof(float), Stream); for(int x=0; x<pGrid->Get_NX(); x++) { pGrid->Set_Value(x, y, Line[x]); } } SG_Free(Line); } } //----------------------------------------------------- else if( !strncmp(Id, "DSAA", 4) ) // Surfer 6: ASCII... { int nx, ny; double dx, dy, xmin, ymin, dValue; fscanf(Stream, "%d %d" , &nx , &ny ); fscanf(Stream, "%lf %lf", &xmin , &dx ); dx = (dx - xmin) / (nx - 1.0); fscanf(Stream, "%lf %lf", &ymin , &dy ); dy = (dy - ymin) / (ny - 1.0); fscanf(Stream, "%lf %lf", &dValue, &dValue); //------------------------------------------------- if( !feof(Stream) && (pGrid = SG_Create_Grid(SG_DATATYPE_Float, nx, ny, dx, xmin, ymin)) != NULL ) { for(int y=0; y<pGrid->Get_NY() && !feof(Stream) && Set_Progress(y, pGrid->Get_NY()); y++) { for(int x=0; x<pGrid->Get_NX(); x++) { fscanf(Stream, "%lf", &dValue); pGrid->Set_Value(x, y, dValue); } } } } //----------------------------------------------------- fclose(Stream); if( pGrid ) { pGrid->Set_Name(SG_File_Get_Name(File, false)); pGrid->Set_NoData_Value(Parameters("NODATA")->asInt() == 0 ? NODATAVALUE : Parameters("NODATA_VAL")->asDouble()); Parameters("GRID")->Set_Value(pGrid); return( true ); } return( false ); }

//--------------------------------------------------------- bool CWatersheds::On_Execute(void) { int x, y, nCells, nCells_Min, nBasins; sLong n; CSG_Grid *pDTM, *pSeed, *pRoute; //----------------------------------------------------- pDTM = Parameters("ELEVATION") ->asGrid(); pSeed = Parameters("CHANNELS") ->asGrid(); pRoute = Parameters("SINKROUTE") ->asGrid(); nCells_Min = Parameters("MINSIZE") ->asInt(); m_pBasins = Parameters("BASINS") ->asGrid(); m_pBasins->Set_NoData_Value(NO_BASIN); m_pBasins->Assign_NoData(); m_Direction.Create(m_pBasins, SG_DATATYPE_Char); for(y=0; y<Get_NY() && Set_Progress(y); y++) { for(x=0; x<Get_NX(); x++) { if( pDTM->is_NoData(x, y) ) { m_Direction.Set_NoData(x, y); } else { if( !pRoute || (n = pRoute->asChar(x, y)) <= 0 ) { n = pDTM->Get_Gradient_NeighborDir(x, y); } m_Direction.Set_Value(x, y, n < 0 ? -1 : (n + 4) % 8); } } } //----------------------------------------------------- for(n=0, m_nBasins=0; n<Get_NCells() && Set_Progress_NCells(n); n++) { pDTM->Get_Sorted(n, x, y, true, false); if( !pSeed->is_NoData(x, y) && pSeed->asInt(x, y) < 0 ) { m_nBasins++; if( (nCells = Get_Basin(x, y)) < nCells_Min ) { nBasins = m_nBasins - 1; m_nBasins = NO_BASIN; Get_Basin(x, y); m_nBasins = nBasins; } } } //----------------------------------------------------- m_Direction.Destroy(); return( true ); }