Example #1
0
//---------------------------------------------------------
bool CSG_Table::_Save_Text(const CSG_String &File_Name, bool bHeadline, const SG_Char *Separator)
{
	int			iField, iRecord;
	CSG_File	Stream;

	if( Get_Field_Count() > 0 )
	{
		if( Stream.Open(File_Name, SG_FILE_W, false) )
		{
			for(iField=0; iField<Get_Field_Count(); iField++)
			{
				Stream.Printf(SG_T("%s%s"), Get_Field_Name(iField), iField < Get_Field_Count() - 1 ? Separator : SG_T("\n"));
			}

			for(iRecord=0; iRecord<Get_Record_Count() && SG_UI_Process_Set_Progress(iRecord, Get_Record_Count()); iRecord++)
			{
				for(iField=0; iField<Get_Field_Count(); iField++)
				{
					Stream.Printf(SG_T("%s"), Get_Record(iRecord)->asString(iField));
					Stream.Printf(SG_T("%s"), iField < Get_Field_Count() - 1 ? Separator : SG_T("\n"));
				}
			}

			SG_UI_Process_Set_Ready();

			return( true );
		}
	}

	return( false );
}
void Cdodproperror::DisplayFile(CSG_String path)
{

	if (SG_File_Exists(path))
	{
		CSG_File File;
		if (File.Open(path, SG_FILE_R, false))
		{
			CSG_String Line;
			while (! File.is_EOF() && File.Read_Line(Line))
			{
				Message_Add(Line);
			}
			File.Close();
		} 
		else 
		{
			Message_Add(CSG_String("Unable to open " + path + CSG_String(" for reading")));
		}
	}
	else
	{
		Message_Add(CSG_String("File '" + path + CSG_String("' does not exist")));
	}

}
//---------------------------------------------------------
bool CSurfer_BLN_Export::On_Execute(void)
{
	//-----------------------------------------------------
	CSG_File	Stream;

	if( !Stream.Open(Parameters("FILE")->asString(), SG_FILE_W) )
	{
		return( false );
	}

	CSG_Shapes	*pShapes	= Parameters("SHAPES")->asShapes();

	if( !pShapes->is_Valid() || pShapes->Get_Count() <= 0 )
	{
		return( false );
	}

	//-----------------------------------------------------
	int iName	= Parameters("BNAME" )->asBool() ? Parameters("NAME")->asInt() : -1;
	int iDesc	= Parameters("BDESC" )->asBool() ? Parameters("DESC")->asInt() : -1;
	int iZVal	= Parameters("BZVAL" )->asBool() ? Parameters("ZVAL")->asInt() : -1;

	int Flag	= 1;

	//-----------------------------------------------------
	for(int iShape=0; iShape<pShapes->Get_Count() && Set_Progress(iShape, pShapes->Get_Count()); iShape++)
	{
		CSG_Shape	*pShape	= pShapes->Get_Shape(iShape);

		for(int iPart=0; iPart<pShape->Get_Part_Count(); iPart++)
		{
			Stream.Printf(SG_T("%d,%d"), pShape->Get_Point_Count(iPart), Flag);

			if( iName >= 0 )	{	Stream.Printf(SG_T(",\"%s\""), pShape->asString(iName));	}
			if( iDesc >= 0 )	{	Stream.Printf(SG_T(",\"%s\""), pShape->asString(iDesc));	}

			Stream.Printf(SG_T("\n"));

			for(int iPoint=0; iPoint<pShape->Get_Point_Count(iPart); iPoint++)
			{
				TSG_Point	p	= pShape->Get_Point(iPoint, iPart);

				if( iZVal >= 0 )
				{
					Stream.Printf(SG_T("%f,%f,%f\n"), p.x, p.y, pShape->asDouble(iZVal));
				}
				else
				{
					Stream.Printf(SG_T("%f,%f\n"   ), p.x, p.y);
				}
			}
		}
	}

	//-----------------------------------------------------
	return( true );
}
Example #4
0
//---------------------------------------------------------
bool CSG_Grid::_Save_Native(const CSG_String &File_Name, int xA, int yA, int xN, int yN, bool bBinary)
{
	bool		bResult		= false;
	CSG_File	Stream;

	if(	Stream.Open(File_Name, SG_FILE_W, false) )
	{
		//-------------------------------------------------
		// Header...

		Stream.Printf(SG_T("%s\t= %s\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_NAME			], Get_Name() );
		Stream.Printf(SG_T("%s\t= %s\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_DESCRIPTION	], Get_Description() );
		Stream.Printf(SG_T("%s\t= %s\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_UNITNAME		], Get_Unit() );
		Stream.Printf(SG_T("%s\t= %d\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_DATAFILE_OFFSET], 0 );
		Stream.Printf(SG_T("%s\t= %s\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_DATAFORMAT		], bBinary ? gSG_Data_Type_Identifier[Get_Type()] : SG_T("ASCII") );
		Stream.Printf(SG_T("%s\t= %s\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_BYTEORDER_BIG	], GRID_FILE_KEY_FALSE );
		Stream.Printf(SG_T("%s\t= %.10f\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_POSITION_XMIN	], Get_XMin() + Get_Cellsize() * xA );
		Stream.Printf(SG_T("%s\t= %.10f\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_POSITION_YMIN	], Get_YMin() + Get_Cellsize() * yA );
		Stream.Printf(SG_T("%s\t= %d\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_CELLCOUNT_X	], xN );
		Stream.Printf(SG_T("%s\t= %d\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_CELLCOUNT_Y	], yN );
		Stream.Printf(SG_T("%s\t= %.10f\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_CELLSIZE		], Get_Cellsize() );
		Stream.Printf(SG_T("%s\t= %f\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_Z_FACTOR		], m_zFactor );
		Stream.Printf(SG_T("%s\t= %f\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_NODATA_VALUE	], Get_NoData_Value() );
		Stream.Printf(SG_T("%s\t= %s\n")	, gSG_Grid_File_Key_Names[ GRID_FILE_KEY_TOPTOBOTTOM	], GRID_FILE_KEY_FALSE );


		//-------------------------------------------------
		// Data...

		if( Stream.Open(SG_File_Make_Path(NULL, File_Name, SG_T("sdat")), SG_FILE_W, true) )
		{
			if( bBinary )
			{
				bResult		= _Save_Binary	(Stream, xA, yA, xN, yN, Get_Type(), false, false);
			}
			else
			{
				bResult		= _Save_ASCII	(Stream, xA, yA, xN, yN);
			}
		}
	}

	return( bResult );
}
//---------------------------------------------------------
bool CSG_MetaData::Load_JSON(const CSG_String &File)
{
	CSG_File	Stream;	CSG_String	JSON;

	if( Stream.Open(File, SG_FILE_R, false) && Stream.Read(JSON, (size_t)Stream.Length()) > 0 )
	{
		return( from_JSON(JSON) );
	}

	return( false );
}
//---------------------------------------------------------
bool CSG_PointCloud::_Save(const CSG_String &File_Name)
{
    CSG_File	Stream;

    SG_UI_Msg_Add(CSG_String::Format(SG_T("%s: %s..."), _TL("Save point cloud"), File_Name.c_str()), true);

    CSG_String	sFile_Name = SG_File_Make_Path(NULL, File_Name, SG_T("spc"));

    if( Stream.Open(sFile_Name, SG_FILE_W, true) == false )
    {
        SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
        SG_UI_Msg_Add_Error(_TL("unable to create file."));

        return( false );
    }

    int		i, iBuffer, nPointBytes	= m_nPointBytes - 1;

    Stream.Write((void *)PC_FILE_VERSION, 6);
    Stream.Write(&nPointBytes	, sizeof(int));
    Stream.Write(&m_nFields		, sizeof(int));

    for(i=0; i<m_nFields; i++)
    {
        Stream.Write(&m_Field_Type[i], sizeof(TSG_Data_Type));

        iBuffer	= (int)m_Field_Name[i]->Length();
        if( iBuffer >= 1024 - 1 )	iBuffer	= 1024 - 1;
        Stream.Write(&iBuffer, sizeof(int));
        Stream.Write((void *)m_Field_Name[i]->b_str(), sizeof(char), iBuffer);
    }

    _Set_Shape(m_Shapes_Index);

    for(i=0; i<Get_Count() && SG_UI_Process_Set_Progress(i, Get_Count()); i++)
    {
        Stream.Write(m_Points[i] + 1, nPointBytes);
    }

    Set_Modified(false);

    Set_File_Name(sFile_Name, true);

    Save_MetaData(File_Name);

    Get_Projection().Save(SG_File_Make_Path(NULL, File_Name, SG_T("prj")), SG_PROJ_FMT_WKT);

    SG_UI_Msg_Add(_TL("okay"), false, SG_UI_MSG_STYLE_SUCCESS);

    SG_UI_Process_Set_Ready();

    return( true );
}
Example #7
0
//---------------------------------------------------------
bool CXYZ_Export::On_Execute(void)
{
	bool					bExNoData;
	int						x, y, i;
	TSG_Point				p;
	CSG_File				Stream;
	CSG_String				FileName;
	CSG_Parameter_Grid_List	*pGrids;

	pGrids		= Parameters("GRIDS")	->asGridList();
	FileName	= Parameters("FILENAME")->asString();
	bExNoData	= Parameters("EX_NODATA")->asBool();

	if( pGrids->Get_Count() > 0 && Stream.Open(FileName, SG_FILE_W, false) )
	{
		if( Parameters("CAPTION")->asBool() )
		{
			Stream.Printf(SG_T("\"X\"\t\"Y\""));

			for(i=0; i<pGrids->Get_Count(); i++)
			{
				Stream.Printf(SG_T("\t\"%s\""), pGrids->asGrid(i)->Get_Name());
			}

			Stream.Printf(SG_T("\n"));
		}

		for(y=0, p.y=Get_YMin(); y<Get_NY() && Set_Progress(y); y++, p.y+=Get_Cellsize())
		{
			for(x=0, p.x=Get_XMin(); x<Get_NX(); x++, p.x+=Get_Cellsize())
			{
				if( !bExNoData || (bExNoData && !pGrids->asGrid(0)->is_NoData(x, y)) )
				{
					Stream.Printf(SG_T("%f\t%f"), p.x,  p.y);

					for(i=0; i<pGrids->Get_Count(); i++)
					{
						Stream.Printf(SG_T("\t%f"), pGrids->asGrid(i)->asDouble(x, y));
					}

					Stream.Printf(SG_T("\n"));
				}
			}
		}

		return( true );
	}

	return( false );
}
Example #8
0
//---------------------------------------------------------
int CTL_Extract::Read_File(const SG_Char *File, CSG_Table &Elements)
{
	//-----------------------------------------------------
	CSG_File	Stream;

	if( !Stream.Open(File, SG_FILE_R, false) )
	{
		return( 0 );
	}

	Process_Set_Text(CSG_String::Format("%s: %s", SG_T("scanning"), File));

	//-----------------------------------------------------
	CSG_String	String, Text;

	if( !Stream.Read(String, Stream.Length()) )
	{
		return( 0 );
	}

	//-----------------------------------------------------
	const SG_Char	Function[2][4]	= {	SG_T("_TL"), SG_T("_TW") };

	const SG_Char	*p		= String;

	bool			bLong	= Parameters("LONG")->asBool();

	while( *p != '\0' )
	{
		if(	!(p[0] == Function[0][0] && p[1] == Function[0][1] && p[2] == Function[0][2])
		&&	!(p[0] == Function[1][0] && p[1] == Function[1][1] && p[2] == Function[1][2] && bLong) )
		{
			p	++;
		}
		else
		{
			p	+= Read_Text(p, Text);

			if( Text.Length() > 0 )
			{
				CSG_Table_Record	*pRecord	= Elements.Add_Record();

				pRecord->Set_Value(0, Text);
				pRecord->Set_Value(1, File);
			}
		}
	}

	return( 1 );
}
Example #9
0
//---------------------------------------------------------
bool CXYZ_Import::On_Execute(void)
{
	CSG_File	Stream;

	if( !Stream.Open(Parameters("FILENAME")->asString(), SG_FILE_R) )
	{
		Error_Set(_TL("file could not be opened"));

		return( false );
	}

	//-----------------------------------------------------
	CSG_Shapes	*pPoints	= Parameters("POINTS")->asShapes();

	pPoints->Create(SHAPE_TYPE_Point, SG_File_Get_Name(Parameters("FILENAME")->asString(), false));

	pPoints->Add_Field("Z", SG_DATATYPE_Double);

	//-----------------------------------------------------
	if( Parameters("HEADLINE")->asBool() )
	{
		CSG_String	sLine;

		if( !Stream.Read_Line(sLine) )
		{
			Error_Set(_TL("could not read headline"));

			return( false );
		}
	}

	//-----------------------------------------------------
	sLong	Length	= Stream.Length();

	double	x, y, z;

	while( Stream.Scan(x) && Stream.Scan(y) && Stream.Scan(z) && Set_Progress((double)Stream.Tell(), (double)Length) )
	{
		CSG_Shape	*pPoint	= pPoints->Add_Shape();

		pPoint->Add_Point(x, y);

		pPoint->Set_Value(0, z);
	}

	return( pPoints->Get_Count() > 0 );
}
Example #10
0
//---------------------------------------------------------
bool CSG_Table::_Save_Text(const CSG_String &File_Name, bool bHeadline, const SG_Char *Separator)
{
	int			iField, iRecord;
	CSG_File	Stream;

	if( Get_Field_Count() > 0 )
	{
		if( Stream.Open(File_Name, SG_FILE_W, false) )
		{
			for(iField=0; iField<Get_Field_Count(); iField++)
			{
				Stream.Printf(SG_T("%s%s"), Get_Field_Name(iField), iField < Get_Field_Count() - 1 ? Separator : SG_T("\n"));
			}

			for(iRecord=0; iRecord<Get_Record_Count() && SG_UI_Process_Set_Progress(iRecord, Get_Record_Count()); iRecord++)
			{
				for(iField=0; iField<Get_Field_Count(); iField++)
				{
					if( !Get_Record(iRecord)->is_NoData(iField) )
					{
						switch( Get_Field_Type(iField) )
						{
						case SG_DATATYPE_String:
						case SG_DATATYPE_Date:
							Stream.Printf(SG_T("\"%s\""), Get_Record(iRecord)->asString(iField));
							break;

						default:
							Stream.Printf(SG_T("%s")    , Get_Record(iRecord)->asString(iField));
							break;
						}
					}

					Stream.Printf(SG_T("%s"), iField < Get_Field_Count() - 1 ? Separator : SG_T("\n"));
				}
			}

			SG_UI_Process_Set_Ready();

			return( true );
		}
	}

	return( false );
}
Example #11
0
//---------------------------------------------------------
bool CWKSP_Project::_Compatibility_Load_Data(const wxString &FileName)
{
	CSG_String	sLine;
	CSG_File	Stream;

	if( !Stream.Open(&FileName, SG_FILE_R, true) )
	{
		return( false );
	}

	//-------------------------------------------------
	while( Stream.Read_Line(sLine) && sLine.Cmp(DATA_ENTRIES_BEGIN) );

	if( sLine.Cmp(DATA_ENTRIES_BEGIN) )
	{
		return( false );
	}

	g_pSAGA_Frame->Freeze();

	g_pData->Get_Menu_Files()->Set_Update(false);
	while( _Compatibility_Load_Data(Stream, SG_File_Get_Path(&FileName).w_str()) );
	g_pData->Get_Menu_Files()->Set_Update(true);

	//-------------------------------------------------
	while( Stream.Read_Line(sLine) && sLine.Cmp(MAP_ENTRIES_BEGIN) );

	if( !sLine.Cmp(MAP_ENTRIES_BEGIN) )
	{
		while( _Compatibility_Load_Map(Stream, SG_File_Get_Path(&FileName).w_str()) );
	}

	switch( g_pData->Get_Parameter("PROJECT_MAP_ARRANGE")->asInt() )
	{
	case 1:	g_pSAGA_Frame->Tile(wxHORIZONTAL);	break;
	case 2:	g_pSAGA_Frame->Tile(wxVERTICAL  );	break;
	}

	g_pSAGA_Frame->Thaw();

	return( true );
}
Example #12
0
//---------------------------------------------------------
bool CSG_CURL::Request(const CSG_String &Request, const SG_Char *File)
{
	if( !is_Connected() ) { return( false ); }

	CSG_File	Answer;

	if( !Answer.Open(File, SG_FILE_W) )
	{
		m_Error.Printf("%s [%s]", _TL("Failed to open file"), File);

		return( false );
	}

	CSG_String	URL	= m_Server + "/" + Request;

	CURL_SET_OPT(1, CURLOPT_URL           , URL.b_str());
	CURL_SET_OPT(1, CURLOPT_FOLLOWLOCATION, 1L);
	CURL_SET_OPT(1, CURLOPT_WRITEFUNCTION , _Callback_Write_File);
	CURL_SET_OPT(1, CURLOPT_WRITEDATA     , &Answer);

	return( _Perform() );
}
Example #13
0
//---------------------------------------------------------
bool CResection::On_Execute(void)
{

	CSG_PointCloud			*pPoints;									// Input Point Cloud
	CSG_String				fileName;
	CSG_File				*pTabStream = NULL;
	int n					= 6;										// Number of unknowns
	CSG_Vector center(3);
	CSG_Vector target(3);

	double c			= Parameters("F")			->asDouble();		// Focal Length (mm)
	double pixWmm		= Parameters("W")			->asDouble() / 1000;// Pixel Width (mm)
	double ppOffsetX	= Parameters("ppX")			->asDouble();		// Principal Point Offset X (pixels)
	double ppOffsetY	= Parameters("ppY")			->asDouble();		// Principal Point Offset Y (pixels)
	pPoints				= Parameters("POINTS")		->asPointCloud();
	fileName			= Parameters("OUTPUT FILE")	->asString();
	center[0]			= Parameters("Xc")			->asDouble();
	center[1]			= Parameters("Yc")			->asDouble();
	center[2]			= Parameters("Zc")			->asDouble();
	target[0]			= Parameters("Xt")			->asDouble();
	target[1]			= Parameters("Yt")			->asDouble();
	target[2]			= Parameters("Zt")			->asDouble();

	int pointCount = pPoints->Get_Point_Count();

	bool estPPOffsets = false;

	if ( Parameters("EST_OFFSETS")->asBool() ) {

		estPPOffsets = true;
		n = 8;															// Increase number of unknowns by 2
	}

	bool applyDistortions = false;
	CSG_Vector K(3);

	if ( Parameters("GIVE_DISTORTIONS")->asBool() ) {

		applyDistortions = true;
		K[0]			= Parameters("K1")			->asDouble();
		K[1]			= Parameters("K2")			->asDouble();
		K[2]			= Parameters("K3")			->asDouble();

	}

	double dxapp = center [0] - target [0];
	double dyapp = center [1] - target [1];
	double dzapp = center [2] - target [2];
	double h_d	= sqrt (dxapp * dxapp + dyapp * dyapp + dzapp * dzapp);	// Distance between Proj. Center & Target (m)
	double h_dmm = h_d * 1000;											// Convert to mm

	if( fileName.Length() == 0 )
	{
		SG_UI_Msg_Add_Error(_TL("Please provide an output file name!"));
		return( false );
	}

	pTabStream = new CSG_File();

	if( !pTabStream->Open(fileName, SG_FILE_W, false) )
	{
		SG_UI_Msg_Add_Error(CSG_String::Format(_TL("Unable to open output file %s!"), fileName.c_str()));
		delete (pTabStream);
		return (false);
	}


	CSG_Vector rotns = methods::calcRotations(center,target);			// Approx. rotations omega, kappa, alpha

	CSG_String msg = "********* Initial Approximate Values *********";
	pTabStream->Write(msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);

	msg = SG_T("Rotation Angles:");
	pTabStream->Write(SG_T("\n") + msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);

	msg = SG_T("Omega:\t") + SG_Get_String(rotns[0],6,false);
	pTabStream->Write(msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);
	msg = SG_T("Kappa:\t") + SG_Get_String(rotns[1],6,false);
	pTabStream->Write(msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);
	msg = SG_T("Alpha:\t") + SG_Get_String(rotns[2],6,false);
	pTabStream->Write(msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);

	msg = SG_T("Projection Center:");
	pTabStream->Write(SG_T("\n") + msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);

	msg = SG_T("Xc:\t") + SG_Get_String(center[0],4,false);
	pTabStream->Write(msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);
	msg = SG_T("Yc:\t") + SG_Get_String(center[1],4,false);
	pTabStream->Write(msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);
	msg = SG_T("Zc:\t") + SG_Get_String(center[2],4,false);
	pTabStream->Write(msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);
	
	if (estPPOffsets) {

		msg = SG_T("Principal Point Offsets:");
		pTabStream->Write(SG_T("\n") + msg + SG_T("\n"));
		SG_UI_Msg_Add(msg, true);

		msg = SG_T("ppX:\t") + SG_Get_String(ppOffsetX,5,false);
		pTabStream->Write(msg + SG_T("\n"));
		SG_UI_Msg_Add(msg, true);
		msg = SG_T("ppY:\t") + SG_Get_String(ppOffsetY,5,false);
		pTabStream->Write(msg + SG_T("\n"));
		SG_UI_Msg_Add(msg, true);

	}

	double itrNo = 0;
	CSG_Matrix invN;
	
	while (true) {													// Begin Iterations

		itrNo++;
		
		double omega = rotns[0];
		double kappa = rotns[1];
		double alpha = rotns[2];

		CSG_Matrix R = methods::calcRotnMatrix(rotns);				// Rotation Matrix from approximate values
		CSG_Matrix E(3,3);											// [w1;w2;w3] = E * [dw;dk;da]

		E[0][0] = -1;
		E[0][1] = E[1][0] = E[2][0] = 0;
		E[0][2] = sin(kappa);
		E[1][1] = -cos(omega);
		E[1][2] = -sin(omega) * cos(kappa);
		E[2][1] = sin(omega);
		E[2][2] = -cos(omega) * cos(kappa);

		CSG_Matrix N(n,n);											// Transpose(Design Matrix) * I * Design Matrix
		CSG_Vector ATL(n);											// Transpose(Design Matrix) * I * Shortened obs. vector

		double SS = 0;
		double sigma_naught = 0;
		
		for (int i = 0; i < pointCount; i++) {
			
			CSG_Vector pqs(3);										// Approx. pi, qi, si

			for (int j = 0; j < 3; j++) {
				pqs[j] = R[j][0] * (pPoints->Get_X(i) - center[0]) +
						 R[j][1] * (pPoints->Get_Y(i) - center[1]) +
						 R[j][2] * (pPoints->Get_Z(i) - center[2]);
			}

			double p_i = pqs[0];
			double q_i = pqs[1];
			double s_i = pqs[2];

			double dR =  0;
			
			// Undistorted
			double x_u = c * p_i / q_i;
			double y_u = c * s_i / q_i;
			
			double c_hat = c;
			
			if (applyDistortions) {
				double r2 = x_u * x_u + y_u * y_u;
				dR =  K[0] * r2 + K[1] * r2 * r2 + K[2] * r2 * r2 * r2;
				c_hat = c * (1 - dR);
			}

			// Approx. image coordinates (with distortions)
			double x_i = (1 - dR) * x_u + ppOffsetX * pixWmm;
			double z_i = (1 - dR) * y_u + ppOffsetY * pixWmm;

			// Shortened obervation vector: dxi & dzi
			double dx_i = pPoints->Get_Attribute(i,0) * pixWmm - x_i;
			double dz_i = pPoints->Get_Attribute(i,1) * pixWmm - z_i;
			SS += pow(dx_i,2) + pow(dz_i,2);

			/*
				x_i, z_i in [mm]
				p_i,q_i,s_i in [m]
				h_d in [m]
				c, c_hat in [mm]
				h_dmm in [mm]
			*/
			CSG_Matrix L(3,2);										// CSG_Matrix takes columns first and rows second
			CSG_Matrix V(3,3);
			CSG_Matrix LR(3,2);
			CSG_Matrix LVE(3,2);

			L[0][0] = L[1][2] = c_hat / (1000 * q_i);
			L[0][2] = L[1][0] = 0;
			L[0][1] = -x_u * (1 - dR) / (1000 * q_i);
			L[1][1] = -y_u * (1 - dR) / (1000 * q_i);

			V[0][0] = V[1][1] = V[2][2] = 0;
			V[0][1] =  s_i / h_d;
			V[0][2] = -q_i / h_d;
			V[1][0] = -s_i / h_d;
			V[1][2] =  p_i / h_d;
			V[2][0] =  q_i / h_d;
			V[2][1] = -p_i / h_d;

			LVE = ( L * V ) * E;
			LR = L * R;

			// Design Matrix (J)
			CSG_Matrix design(n,2);

			for(int j = 0; j < 2; j++) {
				for(int k = 0; k < 3; k++) {
					design[j][k] = LVE[j][k];
					design[j][k+3] = -LR[j][k];
				}
			}

			if ( estPPOffsets ) {
				design[0][6] = design[1][7] = 1.0;
			}

			// Build Normal Matrix
			for(int j = 0; j < n; j++) {
				for(int k = 0; k < n; k++) {
					N[j][k] += (design[0][j] * design[0][k] + design[1][j] * design[1][k]);
				}
			}

			// Build Tranpose (J) * I * (Shortened obs. vector)
			for (int m=0; m < n; m++) {
				ATL[m] += design[0][m] * dx_i + design[1][m] * dz_i;
			}

			L.Destroy();
			V.Destroy();
			LR.Destroy();
			LVE.Destroy();
			pqs.Destroy();
			design.Destroy();

		} // end looping over observations

		// Eigen values and Eigen Vectors
		CSG_Vector eigenVals(n);
		CSG_Matrix eigenVecs(n,n);
		SG_Matrix_Eigen_Reduction(N, eigenVecs, eigenVals, true);

		// One of the Eigen Values is 0
		if (std::any_of(eigenVals.cbegin(),
		                eigenVals.cend(),
		                [] (double i) { return i == 0; })) {
			msg = "The Normal Matrix has a rank defect. Please measure more points.";
			pTabStream->Write(msg + SG_T("\n"));
			SG_UI_Msg_Add(msg, true);
			break;
		}

		double mx = *std::max_element(eigenVals.cbegin(), eigenVals.cend());
		double mn = *std::min_element(eigenVals.cbegin(), eigenVals.cend());

		// Ratio of Smallest to the Biggest Eigen value is too small
		if ((mn / mx) < pow(10,-12.0)) {
			msg = SG_T("Condition of the Matrix of Normal Equations:\t") + CSG_String::Format(SG_T("  %13.5e"), mn/mx);
			pTabStream->Write(msg + SG_T("\n"));
			SG_UI_Msg_Add(msg, true);
			msg = "The Normal Matrix is weakly conditioned. Please measure more points.";
			pTabStream->Write(msg + SG_T("\n"));
			SG_UI_Msg_Add(msg, true);
			break;
		}

		// Calculate the adjustments
		double absMax = 0;
		invN = N.Get_Inverse();
		CSG_Vector est_param_incs = invN * ATL;

		for (int i = 0; i < n; i++) {
			if (abs(est_param_incs[i]) > absMax) {
				absMax = abs(est_param_incs[i]);
			}
		}

		if (absMax < thresh) {
			msg = "Solution has converged.";
			pTabStream->Write(SG_T("\n") + msg + SG_T("\n"));
			SG_UI_Msg_Add(msg, true);
			break;
		}

		for (int a = 0; a < 3; a++) {
			rotns[a] += est_param_incs[a] / h_dmm;								// New Approx. rotations omega, kappa, alpha
			center[a] += est_param_incs[a+3] / 1000;							// New Approx. Projection Center
		}

		if ( estPPOffsets ) {
			ppOffsetX += (est_param_incs[6] / pixWmm);							// New Approx. Principal Point
			ppOffsetY += (est_param_incs[7] / pixWmm);
		}

		sigma_naught = sqrt(SS / (2 * pointCount - n));

		// Writing To Output File & SAGA Console
		msg = "********* Iteration: " + SG_Get_String(itrNo,0,false) + " *********";
		pTabStream->Write(SG_T("\n") + msg + SG_T("\n"));
		SG_UI_Msg_Add(msg, true);

		msg = "Sum of Squared Residuals:\t" + SG_Get_String(SS,5,false);
		pTabStream->Write(SG_T("\n") + msg + SG_T("\n"));
		SG_UI_Msg_Add(msg, true);
		
		msg = "Sigma Naught:\t" + SG_Get_String(sigma_naught,5,false);
		pTabStream->Write(msg + SG_T("\n"));
		SG_UI_Msg_Add(msg, true);
		
		msg = SG_T("Condition of the Matrix of Normal Equations:\t") + CSG_String::Format(SG_T("  %13.5e"), mn/mx);
		pTabStream->Write(msg + SG_T("\n"));
		SG_UI_Msg_Add(msg, true);
		
		R.Destroy();
		E.Destroy();
		N.Destroy();
		ATL.Destroy();
		invN.Destroy();
		eigenVals.Destroy();
		eigenVecs.Destroy();
		est_param_incs.Destroy();

	} // end of iterations

	msg = "********* Final Estimated Parameters *********";
	pTabStream->Write(SG_T("\n") + msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);

	msg = SG_T("Rotation Angles:");
	pTabStream->Write(SG_T("\n") + msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);

	msg = SG_T("Omega:\t") + SG_Get_String(rotns[0],6,false);
	pTabStream->Write(msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);
	msg = SG_T("Kappa:\t") + SG_Get_String(rotns[1],6,false);
	pTabStream->Write(msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);
	msg = SG_T("Alpha:\t") + SG_Get_String(rotns[2],6,false);
	pTabStream->Write(msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);

	msg = SG_T("Projection Center:");
	pTabStream->Write(SG_T("\n") + msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);

	msg = SG_T("Xc:\t") + SG_Get_String(center[0],4,false);
	pTabStream->Write(msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);
	msg = SG_T("Yc:\t") + SG_Get_String(center[1],4,false);
	pTabStream->Write(msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);
	msg = SG_T("Zc:\t") + SG_Get_String(center[2],4,false);
	pTabStream->Write(msg + SG_T("\n"));
	SG_UI_Msg_Add(msg, true);

	if (estPPOffsets) {

		msg = SG_T("Principal Point Offsets:");
		pTabStream->Write(SG_T("\n") + msg + SG_T("\n"));
		SG_UI_Msg_Add(msg, true);

		msg = SG_T("ppX:\t") + SG_Get_String(ppOffsetX,5,false);
		pTabStream->Write(msg + SG_T("\n"));
		SG_UI_Msg_Add(msg, true);
		msg = SG_T("ppY:\t") + SG_Get_String(ppOffsetY,5,false);
		pTabStream->Write(msg + SG_T("\n"));
		SG_UI_Msg_Add(msg, true);

	}


	K.Destroy();
	rotns.Destroy();
	center.Destroy();
	target.Destroy();

	pTabStream->Close();
	
	return true;
}
//---------------------------------------------------------
bool CPointcloud_To_Text_File::On_Execute(void)
{
	CSG_PointCloud			*pPoints;
	CSG_String				fileName;
	CSG_File				*pTabStream = NULL;
	bool					bWriteHeader;
	CSG_String				fieldSep;

	CSG_Parameters			P;
	CSG_Parameter			*pNode;
	CSG_String				s;
	std::vector<int>		vCol, vPrecision;


	//-----------------------------------------------------
	pPoints			= Parameters("POINTS")		->asPointCloud();
	fileName		= Parameters("FILE")		->asString();
	bWriteHeader	= Parameters("WRITE_HEADER")->asBool();


	switch (Parameters("FIELDSEP")->asInt())
    {
	default:
    case 0:		fieldSep = "\t";	break;
    case 1:		fieldSep = " ";		break;
    case 2:		fieldSep = ",";		break;
    }


	if( fileName.Length() == 0 )
	{
		SG_UI_Msg_Add_Error(_TL("Please provide an output file name!"));
		return( false );
	}


	if (SG_UI_Get_Window_Main())
	{
		P.Set_Name(_TL("Check the fields to export"));

		for(int iField=0; iField<pPoints->Get_Field_Count(); iField++)
		{
			s.Printf(SG_T("NODE_%03d") , iField + 1);
			pNode	= P.Add_Node(NULL, s, CSG_String::Format(_TL("%d. %s"), iField + 1, _TL("Field")), _TL(""));

			s.Printf(SG_T("FIELD_%03d"), iField);
			P.Add_Value(pNode, s, CSG_String::Format(SG_T("%s"), pPoints->Get_Field_Name(iField)), _TL(""), PARAMETER_TYPE_Bool, false);

			s.Printf(SG_T("PRECISION_%03d"), iField);
			P.Add_Value(pNode, s, _TL("Decimal Precision"), _TL(""), PARAMETER_TYPE_Int, 2.0, 0.0, true);
		}


		//-----------------------------------------------------
		if( Dlg_Parameters(&P, _TL("Field Properties")) )
		{
			vCol.clear();
			vPrecision.clear();

			for(int iField=0; iField<pPoints->Get_Field_Count(); iField++)
			{
				if( P(CSG_String::Format(SG_T("FIELD_%03d" ), iField).c_str())->asBool() )
				{
					vCol.push_back(iField);
					vPrecision.push_back(P(CSG_String::Format(SG_T("PRECISION_%03d" ), iField).c_str())->asInt());
				}
			}
		}
		else
			return( false );
	}
	else // CMD
	{
		CSG_String		sFields, sPrecision;
		CSG_String		token;
		int				iValue;


		sFields		= Parameters("FIELDS")->asString();
		sPrecision	= Parameters("PRECISIONS")->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 < 0 || iValue > pPoints->Get_Field_Count() - 1 )
			{
				SG_UI_Msg_Add_Error(_TL("Error parsing attribute fields: field index out of range"));
				return( false );
			}
			else
				vCol.push_back(iValue);
		}

		CSG_String_Tokenizer   tkz_precisons(sPrecision.c_str(), ";", SG_TOKEN_STRTOK);

		while( tkz_precisons.Has_More_Tokens() )
		{
			token	= tkz_precisons.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 );
			}

			vPrecision.push_back(iValue);
		}
	}


	if( vCol.size() == 0 )
	{
		SG_UI_Msg_Add_Error(_TL("Please provide at least one column to export!"));
		return( false );
	}

	if( vCol.size() != vPrecision.size() )
	{
		SG_UI_Msg_Add_Error(_TL("Number of fields and precisions must be equal!"));
		return( false );
	}

	//-----------------------------------------------------
	pTabStream = new CSG_File();

	if( !pTabStream->Open(fileName, SG_FILE_W, false) )
	{
		SG_UI_Msg_Add_Error(CSG_String::Format(_TL("Unable to open output file %s!"), fileName.c_str()));
		delete (pTabStream);
		return (false);
	}


	if( bWriteHeader )
	{
	    CSG_String  sHeader;

		for(size_t i=0; i<vCol.size(); i++)
		{
		    sHeader += CSG_String::Format(SG_T("%s"), pPoints->Get_Field_Name(vCol.at(i)));

		    if( i < vCol.size()-1 )
                sHeader += fieldSep.c_str();
		}

		sHeader += SG_T("\n");

		pTabStream->Write(sHeader);
	}


	for(int iPoint=0; iPoint<pPoints->Get_Count() && Set_Progress(iPoint, pPoints->Get_Count()); iPoint++)
	{
		CSG_String	sLine;

		for(size_t i=0; i<vCol.size(); i++)
		{
			switch (pPoints->Get_Field_Type(vCol.at(i)))
			{
			case SG_DATATYPE_Double:
			case SG_DATATYPE_Float:
				sLine += SG_Get_String(pPoints->Get_Value(iPoint, vCol.at(i)), vPrecision.at(i), false);
				break;
			default:
				sLine += CSG_String::Format(SG_T("%d"), (int)pPoints->Get_Value(iPoint, vCol.at(i)));
				break;
			}

            if( i < vCol.size()-1 )
                sLine += fieldSep.c_str();
		}

		sLine += SG_T("\n");

		pTabStream->Write(sLine);
	}


	pTabStream->Close();
	delete (pTabStream);

	return( true );
}
Example #15
0
//---------------------------------------------------------
bool CSTL_Export::On_Execute(void)
{
	bool		bBinary;
	int			zField;
	float		v[3];
	CSG_String	File;
	CSG_File	Stream;
	CSG_TIN		*pTIN;

	pTIN	= Parameters("TIN")		->asTIN();
	File	= Parameters("FILE")	->asString();
	zField	= Parameters("ZFIELD")	->asInt(); 
	bBinary	= Parameters("BINARY")	->asInt() == 1; 

	if( !Stream.Open(File, SG_FILE_W, bBinary) )
	{
		return( false );
	}

	//-----------------------------------------------------
	if( bBinary )
	{
		char	*sHeader	= (char *)SG_Calloc(80, sizeof(char));
		DWORD	nFacets		= pTIN->Get_Triangle_Count();
		WORD	nBytes		= 0;

		Stream.Write(sHeader , sizeof(char), 80);
		Stream.Write(&nFacets, sizeof(DWORD));

		SG_Free(sHeader);

		//-------------------------------------------------
		for(int iTriangle=0; iTriangle<pTIN->Get_Triangle_Count(); iTriangle++)
		{
			CSG_TIN_Triangle	*pTriangle	= pTIN->Get_Triangle(iTriangle);

			Get_Normal(pTriangle, zField, v);

			Stream.Write(v, sizeof(float), 3);	// facet normal

			for(int iNode=0; iNode<3; iNode++)
			{
				CSG_TIN_Node	*pNode	= pTriangle->Get_Node(iNode);

				v[0]	= (float)pNode->Get_X();
				v[1]	= (float)pNode->Get_Y();
				v[2]	= (float)pNode->asDouble(zField);

				Stream.Write(v, sizeof(float), 3);
			}

			Stream.Write(&nBytes, sizeof(WORD));
		}
	}

	//-----------------------------------------------------
	else	// ASCII
	{
		Stream.Printf(SG_T("solid %s\n"), SG_File_Get_Name(File, false).c_str());

		for(int iTriangle=0; iTriangle<pTIN->Get_Triangle_Count(); iTriangle++)
		{
			CSG_TIN_Triangle	*pTriangle	= pTIN->Get_Triangle(iTriangle);

			Get_Normal(pTriangle, zField, v);

			Stream.Printf(SG_T(" facet normal %.4f %.4f %.4f\n"), v[0], v[1], v[2]);
			Stream.Printf(SG_T("  outer loop\n"));

			for(int iNode=0; iNode<3; iNode++)
			{
				CSG_TIN_Node	*pNode	= pTriangle->Get_Node(iNode);

				v[0]	= (float)pNode->Get_X();
				v[1]	= (float)pNode->Get_Y();
				v[2]	= (float)pNode->asDouble(zField);

				Stream.Printf(SG_T("   vertex %.4f %.4f %.4f\n"), v[0], v[1], v[2]);
			}

			Stream.Printf(SG_T("  endloop\n"));
			Stream.Printf(SG_T(" endfacet\n"));		
		}

		Stream.Printf(SG_T("endsolid %s\n"), SG_File_Get_Name(File, false).c_str());
	}

	return( true );
}
Example #16
0
//---------------------------------------------------------
bool CSTL_Import::On_Execute(void)
{
	int			Method;
	DWORD		iFacette, nFacettes;
	TSTL_Point	p[3];
	CSG_String	sFile, sHeader;
	CSG_File	Stream;

	//-----------------------------------------------------
	sFile		= Parameters("FILE")		->asString();
	Method		= Parameters("METHOD")		->asInt();

	r_sin_x	= sin(Parameters("ROT_X")->asDouble() * M_DEG_TO_RAD);
	r_sin_y	= sin(Parameters("ROT_Y")->asDouble() * M_DEG_TO_RAD);
	r_sin_z	= sin(Parameters("ROT_Z")->asDouble() * M_DEG_TO_RAD);
	r_cos_x	= cos(Parameters("ROT_X")->asDouble() * M_DEG_TO_RAD);
	r_cos_y	= cos(Parameters("ROT_Y")->asDouble() * M_DEG_TO_RAD);
	r_cos_z	= cos(Parameters("ROT_Z")->asDouble() * M_DEG_TO_RAD);

	//-----------------------------------------------------
	if( !Stream.Open(sFile) )
	{
		return( false );
	}

	if( !Stream.Read(sHeader, 80) )
	{
		return( false );
	}

	Message_Add(sHeader);

	if( !Stream.Read(&nFacettes, sizeof(nFacettes)) )
	{
		return( false );
	}

	Message_Add(CSG_String::Format(SG_T("%s: %d"), _TL("Number of Facettes"), nFacettes));

	//-----------------------------------------------------
	switch( Method )
	{

	//-----------------------------------------------------
	case 0:	{	// Point Cloud
		CSG_Rect	Extent;

		if( Get_Extent(Stream, Extent, nFacettes) )
		{
			CSG_PRQuadTree	Points(Extent);
			CSG_PointCloud	*pPoints	= SG_Create_PointCloud();
			Parameters("POINTS")->Set_Value(pPoints);
			pPoints->Set_Name(SG_File_Get_Name(sFile, false));
			pPoints->Add_Field((const char *)NULL, SG_DATATYPE_Undefined);

			for(iFacette=0; iFacette<nFacettes && !Stream.is_EOF() && Set_Progress(iFacette, nFacettes); iFacette++)
			{
				if( Read_Facette(Stream, p) )
				{
					for(int i=0; i<3; i++)
					{
						if( Points.Add_Point(p[i].x, p[i].y, p[i].z) )
						{
							pPoints->Add_Point(p[i].x, p[i].y, p[i].z);
						}
					}
				}
			}
		}

	break;	}

	//-----------------------------------------------------
	case 1:	{	// Point Cloud (centered)
		CSG_PointCloud	*pPoints	= SG_Create_PointCloud();
		Parameters("POINTS")->Set_Value(pPoints);
		pPoints->Set_Name(SG_File_Get_Name(sFile, false));
		pPoints->Add_Field((const char *)NULL, SG_DATATYPE_Undefined);

		for(iFacette=0; iFacette<nFacettes && !Stream.is_EOF() && Set_Progress(iFacette, nFacettes); iFacette++)
		{
			if( Read_Facette(Stream, p) )
			{
				pPoints->Add_Point(
					(p[0].x + p[1].x + p[2].x) / 3.0,
					(p[0].y + p[1].y + p[2].y) / 3.0,
					(p[0].z + p[1].z + p[2].z) / 3.0
				);
			}
		}

	break;	}

	//-----------------------------------------------------
	case 2:	{	// Points
		CSG_Shapes	*pPoints	= SG_Create_Shapes(SHAPE_TYPE_Point, SG_File_Get_Name(sFile, false));
		pPoints->Add_Field(SG_T("Z"), SG_DATATYPE_Float);
		Parameters("SHAPES")->Set_Value(pPoints);

		for(iFacette=0; iFacette<nFacettes && !Stream.is_EOF() && Set_Progress(iFacette, nFacettes); iFacette++)
		{
			if( Read_Facette(Stream, p) )
			{
				CSG_Shape	*pPoint	= pPoints->Add_Shape();

				pPoint->Add_Point(
					(p[0].x + p[1].x + p[2].x) / 3.0,
					(p[0].y + p[1].y + p[2].y) / 3.0
				);

				pPoint->Set_Value(0,
					(p[0].z + p[1].z + p[2].z) / 3.0
				);
			}
		}

	break;	}

	//-----------------------------------------------------
	case 3:	{	// Raster
		CSG_Rect	Extent;

		if( Get_Extent(Stream, Extent, nFacettes) )
		{
			int		nx, ny;
			double	d;

			nx		= Parameters("GRID_RES")->asInt();
			d		= Extent.Get_XRange() / nx;
			ny		= 1 + (int)(Extent.Get_YRange() / d);

			m_pGrid	= SG_Create_Grid(SG_DATATYPE_Float, nx, ny, d, Extent.Get_XMin(), Extent.Get_YMin());
			m_pGrid->Set_Name(SG_File_Get_Name(sFile, false));
			m_pGrid->Set_NoData_Value(-99999);
			m_pGrid->Assign_NoData();

			Parameters("GRID")->Set_Value(m_pGrid);

			//---------------------------------------------
			for(iFacette=0; iFacette<nFacettes && !Stream.is_EOF() && Set_Progress(iFacette, nFacettes); iFacette++)
			{
				if( Read_Facette(Stream, p) )
				{
					TSG_Point_Z	Point[3];

					for(int i=0; i<3; i++)
					{
						Point[i].x	= (p[i].x - m_pGrid->Get_XMin()) / m_pGrid->Get_Cellsize();
						Point[i].y	= (p[i].y - m_pGrid->Get_YMin()) / m_pGrid->Get_Cellsize();
						Point[i].z	=  p[i].z;
					}

					Set_Triangle(Point);
				}
			}
		}

	break;	}
	}

	//-----------------------------------------------------
	return( true );
}
//---------------------------------------------------------
bool CCRU_Table_Import::On_Execute(void)
{
	//-----------------------------------------------------
	CSG_File	File;

	if( !File.Open(Parameters("FILE")->asString(), SG_FILE_R, false) )
	{
		Error_Fmt("%s [%s]", _TL("could not open file"), Parameters("FILE")->asString());

		return( false );
	}

	//-----------------------------------------------------
	CSG_String	sLine;

	if( !File.Read_Line(sLine) )
	{
		Error_Fmt("%s [%s]", _TL("failed to read header"), Parameters("FILE")->asString());

		return( false );
	}

	//-----------------------------------------------------
	int		nx, ny, nMonths;
	double	Cellsize, xMin, yMin, xMax, yMax;

	if( !File.Scan(Cellsize)
	||  !File.Scan(xMin    ) || !File.Scan(yMin    )
	||  !File.Scan(xMax    ) || !File.Scan(yMax    )
	||  !File.Scan(nx      ) || !File.Scan(ny      )
	||  !File.Scan(nMonths ) )
	{
		Error_Fmt("%s [%s]", _TL("failed to read header"), Parameters("FILE")->asString());

		return( false );
	}

	//-----------------------------------------------------
	CSG_Grid_System	System(Cellsize, xMin, yMin, nx, ny);

	if( !System.is_Valid() || System.Get_XMax() != xMax || System.Get_YMax() != yMax )
	{
		Error_Fmt("%s [%s]", _TL("failed to read header"), Parameters("FILE")->asString());

		return( false );
	}

	//-----------------------------------------------------
	bool	bShift	= Parameters("SHIFT")->asBool();

	if( bShift )
	{
		System.Assign(Cellsize, xMin - 180.0, yMin, nx, ny);
	}

	//-----------------------------------------------------
	CSG_String	Name	= SG_File_Get_Name(Parameters("FILE")->asString(), false);

	Parameters("GRIDS")->asGridList()->Del_Items();

	for(int iMonth=0; iMonth<nMonths && !File.is_EOF() && Process_Get_Okay(); iMonth++)
	{
		Process_Set_Text("%s %d", _TL("Band"), 1 + iMonth);

		CSG_Grid	*pGrid	= SG_Create_Grid(System, SG_DATATYPE_Short);

		pGrid->Fmt_Name("%s_%02d", Name.c_str(), 1 + iMonth);
		pGrid->Set_NoData_Value(-9999);
		pGrid->Get_Projection().Set_GCS_WGS84();

		Parameters("GRIDS")->asGridList()->Add_Item(pGrid);

		//-------------------------------------------------
		for(int y=0; y<ny && !File.is_EOF() && Set_Progress(y, ny); y++)
		{
			if( File.Read_Line(sLine) && sLine.Length() >= 5. * nx )
			{
				for(int x=0, xx=bShift?nx/2:x, yy=ny-1-y; x<nx; x++, xx++)
				{
					double	z;

					CSG_String	s	= sLine.Mid(x * 5, 5);

					if( s.asDouble(z) )
					{
						pGrid->Set_Value(xx % nx, yy, z);
					}
					else
					{
						pGrid->Set_NoData(xx % nx, yy);
					}
				}
			}
		}
	}

	//-----------------------------------------------------
	return( true );
}
Example #18
0
//---------------------------------------------------------
bool CWASP_MAP_Import::On_Execute(void)
{
	int			n, Method, nLength;
	double		z, dz, zMin, rLeft, rRight;
	CSG_File	Stream;
	TSG_Point	p, pu[2], pm[2];
	CSG_String	fName, sLine;
	CSG_Shape	*pLine;
	CSG_Shapes	*pLines;

	//-----------------------------------------------------
	pLines	= Parameters("SHAPES")->asShapes();
	fName	= Parameters("FILE"  )->asString();
	Method	= Parameters("METHOD")->asInt();

	//-----------------------------------------------------
	if( Stream.Open(fName, SG_FILE_R) )
	{
		nLength	= Stream.Length();

		pLines->Create(SHAPE_TYPE_Line, SG_File_Get_Name(fName, false));

		switch( Method )
		{
		case 0:	// elevation
			pLines->Add_Field("Z"		, SG_DATATYPE_Double);
			break;

		case 1:	// roughness
			pLines->Add_Field("RLEFT"	, SG_DATATYPE_Double);
			pLines->Add_Field("RRIGHT"	, SG_DATATYPE_Double);
			break;

		case 2:	// elevation and roughness
			pLines->Add_Field("Z"		, SG_DATATYPE_Double);
			pLines->Add_Field("RLEFT"	, SG_DATATYPE_Double);
			pLines->Add_Field("RRIGHT"	, SG_DATATYPE_Double);
			break;
		}


		// 1)	Text string identifying the terrain map: + ...

		Stream.Read_Line(sLine);


		// 2)	Fixed point #1 in user and metric [m] coordinates:
		//			X1(user) Y1(user) X1(metric) Y1(metric)

	//	fscanf(Stream, "%lf %lf %lf %lf", &pu[0].x, &pu[0].y, &pm[0].x, &pm[0].y);
		pu[0].x	= Stream.Scan_Double();
		pu[0].y	= Stream.Scan_Double();
		pm[0].x	= Stream.Scan_Double();
		pm[0].y	= Stream.Scan_Double();


		// 3)	Fixed point #2 in user and metric [m] coordinates:
		//			X2(user) Y2(user) X2(metric) Y2(metric)

	//	fscanf(Stream, "%lf %lf %lf %lf", &pu[1].x, &pu[1].y, &pm[1].x, &pm[1].y);
		pu[1].x	= Stream.Scan_Double();
		pu[1].y	= Stream.Scan_Double();
		pm[1].x	= Stream.Scan_Double();
		pm[1].y	= Stream.Scan_Double();


		// 4)	Scaling factor and offset for height scale (Z):
		//			Zmetric = {scaling factor}(Zuser + {offset})

	//	fscanf(Stream, "%lf %lf", &dz, &zMin);
		dz		= Stream.Scan_Double();
		zMin	= Stream.Scan_Double();


		while( !Stream.is_EOF() && Set_Progress((int)Stream.Tell(), nLength) )
		{
			pLine	= NULL;

			switch( Method )
			{
			case 0:	// elevation
				// 5a)	Height contour: elevation (Z) and number of points (n) in line:
				//			Z n

			//	fscanf(Stream, "%lf %d", &z, &n);
				z		= Stream.Scan_Double();
				n		= Stream.Scan_Int   ();

				if( !Stream.is_EOF() && n > 1 )
				{
					pLine	= pLines->Add_Shape();
					pLine->Set_Value(0, zMin + dz * z);
				}
				break;

			case 1:	// roughness
				// 5b)	Roughness change line:
				//			roughness lengths to the left (z0l) and right (z0r) side of the line,
				//			respectively, and number of points:
				//				z0l z0r n

			//	fscanf(Stream, "%lf %lf %d", &rLeft, &rRight, &n);
				rLeft	= Stream.Scan_Double();
				rRight	= Stream.Scan_Double();
				n		= Stream.Scan_Int   ();

				if( !Stream.is_EOF() && n > 1 )
				{
					pLine	= pLines->Add_Shape();
					pLine->Set_Value(0, rLeft);
					pLine->Set_Value(1, rRight);
				}
				break;

			case 2:	// elevation and roughness
				// 5c)	Roughness and contour line:
				//			roughness lengths to the left and right of the line,
				//			respectively, elevation and number of points:
				//				z0l z0r Z n

			//	fscanf(Stream, "%lf %lf %lf %d", &rLeft, &rRight, &z, &n);
				rLeft	= Stream.Scan_Double();
				rRight	= Stream.Scan_Double();
				z		= Stream.Scan_Double();
				n		= Stream.Scan_Int   ();

				if( !Stream.is_EOF() && n > 1 )
				{
					pLine	= pLines->Add_Shape();
					pLine->Set_Value(0, zMin + dz * z);
					pLine->Set_Value(1, rLeft);
					pLine->Set_Value(2, rRight);
				}
				break;
			}


			// 6–)	Cartesian coordinates (X, Y) of line described in 5a, 5b or 5c:
			//			X1 Y1 [... Xn Yn]
			//			Xn+1 Yn+1
			//			... where [] embrace optional numbers and n is > 0

			for(int i=0; i<n && !Stream.is_EOF() && Process_Get_Okay(false); i++)
			{
			//	fscanf(Stream, "%lf %lf", &p.x, &p.y);
				p.x	= Stream.Scan_Double();
				p.y	= Stream.Scan_Double();

				pLine->Add_Point(p);
			}
		}

		return( true );
	}

	return( false );
}
//---------------------------------------------------------
bool CDirect_Georeferencing_WorldFile::On_Execute(void)
{
	//-----------------------------------------------------
	int	nx	= Parameters("NX")->asInt();
	int	ny	= Parameters("NY")->asInt();

	if( !m_Georeferencer.Set_Transformation(Parameters, nx, ny) )
	{
		return( false );
	}

	//-----------------------------------------------------
	CSG_String	File	= Parameters("FILE")->asString();

	if( File.is_Empty() )
	{
		return( false );
	}

	//-----------------------------------------------------
	CSG_File	Stream;

	if( !Stream.Open(File, SG_FILE_W, false) )
	{
		return( false );
	}

	//-----------------------------------------------------
	CSG_Matrix	R(m_Georeferencer.Get_Transformation());

	R	*= 0.001 * Parameters("Z")->asDouble() / Parameters("CFL")->asDouble() * Parameters("PXSIZE")->asDouble();

	TSG_Point	p	= m_Georeferencer.Image_to_World(0, ny);

	Stream.Printf(SG_T("%.10f\n%.10f\n%.10f\n%.10f\n%.10f\n%.10f\n"),
		 R[0][0],	// A: pixel size in the x-direction in map units/pixel
		 R[1][0],	// D: rotation about y-axis
		-R[0][1],	// B: rotation about x-axis
		-R[1][1],	// E: pixel size in the y-direction in map units, almost always negative
		     p.x,	// X: top left pixel center
		     p.y	// Y: top left pixel center
	);

	//-----------------------------------------------------
	CSG_Shapes	*pExtents	= Parameters("EXTENT")->asShapes();

	if( pExtents )
	{
		pExtents->Create(SHAPE_TYPE_Polygon, SG_File_Get_Name(File, false));
		pExtents->Add_Field(_TL("NAME"), SG_DATATYPE_String);

		CSG_Shape	*pExtent	= pExtents->Add_Shape();

		p	= m_Georeferencer.Image_to_World( 0,  0);	pExtent->Add_Point(p.x, p.y);
		p	= m_Georeferencer.Image_to_World( 0, ny);	pExtent->Add_Point(p.x, p.y);
		p	= m_Georeferencer.Image_to_World(nx, ny);	pExtent->Add_Point(p.x, p.y);
		p	= m_Georeferencer.Image_to_World(nx,  0);	pExtent->Add_Point(p.x, p.y);

		pExtent->Set_Value(0, SG_File_Get_Name(File, false));
	}

	//-----------------------------------------------------
	return( true );
}
Example #20
0
//---------------------------------------------------------
bool CMOLA_Import::On_Execute(void)
{
	bool			bDown;
	int				xa, xb, y, yy, NX, NY;
	short			*sLine;
	double			D, xMin, yMin;
	CSG_File		Stream;
	TSG_Data_Type	Type;
	CSG_Grid		*pGrid;
	CSG_String		fName, sName;

	//-----------------------------------------------------
	pGrid	= NULL;

	switch( Parameters("TYPE")->asInt() )
	{
	case 0:				Type	= SG_DATATYPE_Short;	break;
	case 1: default:	Type	= SG_DATATYPE_Float;	break;
	}

	bDown	= Parameters("ORIENT")->asInt() == 1;

	//-----------------------------------------------------
	// MEGpxxnyyyrv
	// 012345678901
	//  p indicates the product type (A for areoid, C for counts, R for
	//    radius, and T for topography)
	//  xx is the latitude of the upper left corner of the image
	//  n indicates whether the latitude is north (N) or south (S)
	//  yyy is the east longitude of the upper left corner of the image
	//  r is the map resolution using the pattern
	//    c =   4 pixel per degree
	//    e =  16 pixel per degree
	//    f =  32 pixel per degree
	//    g =  64 pixel per degree
	//    h = 128 pixel per degree
	//    (This convention is consistent with that used for the Mars Digital
	//    Image Model [MDIM] archives.)
	//  v is a letter indicating the product version.

	fName	= SG_File_Get_Name(Parameters("FILE")->asString(), false);
	fName.Make_Upper();

	if( fName.Length() < 12 )
	{
		return( false );
	}

	//-----------------------------------------------------
	switch( fName[3] )
	{
	default:
		return( false );

	case 'A':
		sName.Printf(SG_T("MOLA: Areoid v%c")		, fName[11]);
		break;

	case 'C':
		sName.Printf(SG_T("MOLA: Counts v%c")		, fName[11]);
		break;

	case 'R':
		sName.Printf(SG_T("MOLA: Radius v%c")		, fName[11]);
		break;

	case 'T':
		sName.Printf(SG_T("MOLA: Topography v%c")	, fName[11]);
		break;
	}

	//-----------------------------------------------------
	switch( fName[10] )
	{
	default:
		return( false );

	case 'C':	// 1/4th degree...
		D		= 1.0 /   4.0;
		NX		=   4 * 360;
		NY		=   4 * 180;
		yMin	= - 90.0;
		xMin	= -180.0;
		break;

	case 'D':	// 1/8th degree...
		D		= 1.0 /   8.0;
		NX		=   8 * 360;
		NY		=   8 * 180;
		yMin	= - 90.0;
		xMin	= -180.0;
		break;

	case 'E':	// 1/16th degree...
		D		= 1.0 /  16.0;
		NX		=  16 * 360;
		NY		=  16 * 180;
		yMin	= - 90.0;
		xMin	= -180.0;
		break;

	case 'F':	// 1/32th degree...
		D		= 1.0 /  32.0;
		NX		=  32 * 360;
		NY		=  32 * 180;
		yMin	= - 90.0;
		xMin	= -180.0;
		break;

	case 'G':	// 1/64th degree...
		D		= 1.0 /  64.0;
		NX		=  64 * 180;
		NY		=  64 *  90;
		yMin	= (fName[6] == 'S' ? -1.0 :  1.0) * fName.Right(8).asInt();
		yMin	= bDown ? yMin - NY * D : -yMin;
		xMin	= fName.Right(5).asInt();
		if( xMin >= 180.0 )
		{
			xMin	-= 360.0;
		}
		break;

	case 'H':	// 1/128th degree...
		D		= 1.0 / 128.0;
		NX		= 128 *  90;
		NY		= 128 *  44;
		yMin	= (fName[6] == 'S' ? -1.0 :  1.0) * fName.Right(8).asInt();
		yMin	= bDown ? yMin - NY * D : -yMin;
		xMin	= fName.Right(5).asInt();
		if( xMin >= 180.0 )
		{
			xMin	-= 360.0;
		}
		break;
	}

	//-----------------------------------------------------
	if( Stream.Open(Parameters("FILE")->asString(), SG_FILE_R, true) )
	{
		if( (pGrid = SG_Create_Grid(Type, NX, NY, D, xMin + D / 2.0, yMin + D / 2.0)) != NULL )
		{
			pGrid->Set_Name(sName);
			pGrid->Set_NoData_Value(-999999);
			pGrid->Get_Projection().Create(SG_T("+proj=lonlat +units=m +a=3396200.000000 +b=3376200.000000"), SG_PROJ_FMT_Proj4);

			//---------------------------------------------
			sLine	= (short *)SG_Malloc(NX * sizeof(short));

			for(y=0; y<NY && !Stream.is_EOF() && Set_Progress(y, NY); y++)
			{
				yy	= bDown ? NY - 1 - y : y;

				Stream.Read(sLine, NX, sizeof(short));

				if( fName[10] == 'G' || fName[10] == 'H' )
				{
					for(xa=0; xa<NX; xa++)
					{
						SG_Swap_Bytes(sLine + xa, sizeof(short));

						pGrid->Set_Value(xa, yy, sLine[xa]);
					}
				}
				else
				{
					for(xa=0, xb=NX/2; xb<NX; xa++, xb++)
					{
						SG_Swap_Bytes(sLine + xa, sizeof(short));
						SG_Swap_Bytes(sLine + xb, sizeof(short));

						pGrid->Set_Value(xa, yy, sLine[xb]);
						pGrid->Set_Value(xb, yy, sLine[xa]);
					}
				}
			}

			//---------------------------------------------
			SG_Free(sLine);

			Parameters("GRID")->Set_Value(pGrid);
		}
	}

	return( pGrid != NULL );
}
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
Example #22
0
//---------------------------------------------------------
bool CXYZ_Export::On_Execute(void)
{
	bool		bHeader;
	int			Field, off_Field, Separate;
	CSG_File	Stream;
	CSG_Shapes	*pPoints;

	//-----------------------------------------------------
	pPoints		= Parameters("POINTS"  )->asShapes();
	bHeader		= Parameters("HEADER"  )->asBool();
	Field		= Parameters("FIELD"   )->asInt();
	Separate	= pPoints->Get_Type() == SHAPE_TYPE_Point ? 0
				: Parameters("SEPARATE")->asInt();
	off_Field	= pPoints->Get_ObjectType() == SG_DATAOBJECT_TYPE_PointCloud ? 2 : 0;

	//-----------------------------------------------------
	if( pPoints->Get_Field_Count() == 0 )
	{
		Error_Set(_TL("data set has no attributes"));

		return( false );
	}

	//-----------------------------------------------------
	if( !Stream.Open(Parameters("FILENAME")->asString(), SG_FILE_W, false) )
	{
		Error_Set(_TL("could not open file"));

		return( false );
	}

	//-----------------------------------------------------
	if( bHeader )
	{
		Stream.Printf("X\tY");

		if( Field < 0 )
		{
			for(int iField=off_Field; iField<pPoints->Get_Field_Count(); iField++)
			{
				Stream.Printf("\t%s", pPoints->Get_Field_Name(iField));
			}
		}
		else
		{
			Stream.Printf("\tZ");
		}

		Stream.Printf("\n");
	}

	//-------------------------------------------------
	for(int iShape=0; iShape<pPoints->Get_Count() && Set_Progress(iShape, pPoints->Get_Count()); iShape++)
	{
		CSG_Shape	*pShape	= pPoints->Get_Shape(iShape);

		for(int iPart=0; iPart<pShape->Get_Part_Count(); iPart++)
		{
			switch( Separate )
			{
			case 1:	// *
				Stream.Printf("*\n");
				break;

			case 2:	// number of points
				Stream.Printf("%d\n", pShape->Get_Point_Count(iPart));
				break;
			}

			for(int iPoint=0; iPoint<pShape->Get_Point_Count(iPart); iPoint++)
			{
				TSG_Point	Point	= pShape->Get_Point(iPoint, iPart);

				Stream.Printf("%f\t%f", Point.x, Point.y);

				if( Field < 0 )
				{
					for(int iField=off_Field; iField<pPoints->Get_Field_Count(); iField++)
					{
						switch( pPoints->Get_Field_Type(iField) )
						{
						case SG_DATATYPE_String:
						case SG_DATATYPE_Date:
							Stream.Printf("\t\"%s\"", pShape->asString(iField));
							break;

						default:
							Stream.Printf("\t%f"    , pShape->asDouble(iField));
							break;
						}
					}
				}
				else switch( pPoints->Get_Field_Type(Field) )
				{
				case SG_DATATYPE_String:
				case SG_DATATYPE_Date:
					Stream.Printf("\t\"%s\"", pShape->asString(Field));
					break;

				default:
					Stream.Printf("\t%f"    , pShape->asDouble(Field));
					break;
				}

				Stream.Printf("\n");
			}
		}
	}

	//-------------------------------------------------
	return( true );
}
Example #23
0
//---------------------------------------------------------
bool CGrid_Import::On_Execute(void)
{
	bool				bTransform;
	int					x, y, yy, Method;
	double				ax, ay, dx, dy, rx, ry, xMin, yMin, Cellsize;
	CSG_Colors			Colors;
	CSG_String			fImage, fWorld, Name;
	CSG_Grid			*pImage;
	CSG_File			Stream;
	wxImage				Image;
	wxImageHistogram	Histogram;

	//-----------------------------------------------------
	fImage	= Parameters("FILE")	->asString();
	Method	= Parameters("METHOD")	->asInt();

	Name	= SG_File_Get_Name(fImage, false);

	//-----------------------------------------------------
	wxImageHandler	*pImgHandler = NULL;

	if( !SG_UI_Get_Window_Main() )
	{
		CSG_String	fName = SG_File_Get_Name(fImage, true);

		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;
		else if( SG_File_Cmp_Extension(fName, SG_T("gif")) )
			pImgHandler = new wxGIFHandler;
		else if( SG_File_Cmp_Extension(fName, SG_T("pnm")) )
			pImgHandler = new wxPNMHandler;
		else if( SG_File_Cmp_Extension(fName, SG_T("xpm")) )
			pImgHandler = new wxXPMHandler;
#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.LoadFile(fImage.c_str()) )
	{
		return( false );
	}

	//-----------------------------------------------------
	     if( SG_File_Cmp_Extension(fImage, SG_T("bmp")) )
	{
		fWorld	= SG_File_Make_Path(NULL, fImage, SG_T("bpw"));
	}
	else if( SG_File_Cmp_Extension(fImage, SG_T("jpg")) )
	{
		fWorld	= SG_File_Make_Path(NULL, fImage, SG_T("jgw"));
	}
	else if( SG_File_Cmp_Extension(fImage, SG_T("png")) )
	{
		fWorld	= SG_File_Make_Path(NULL, fImage, SG_T("pgw"));
	}
	else if( SG_File_Cmp_Extension(fImage, SG_T("tif")) )
	{
		fWorld	= SG_File_Make_Path(NULL, fImage, SG_T("tfw"));
	}
	else
	{
		fWorld	= SG_File_Make_Path(NULL, fImage, SG_T("world"));
	}

	bTransform	= false;
	xMin		= 0.0;
	yMin		= 0.0;
	Cellsize	= 1.0;

	if(	Stream.Open(fWorld, SG_FILE_R, false) && fscanf(Stream.Get_Stream(), "%lf %lf %lf %lf %lf %lf ", &dx, &ry, &rx, &dy, &ax, &ay) == 6 )
	{
		if( dx != -dy || rx != 0.0 || ry != 0.0 )
		{
			bTransform	= true;
		}
		else
		{
			xMin		= ax;
			yMin		= ay + dy * (Image.GetHeight() - 1);
			Cellsize	= dx;
		}
	}


	//-----------------------------------------------------
	// color look-up table...

	if( Method == 0 && (yy = Image.ComputeHistogram(Histogram)) <= 256 )
	{
		Colors.Set_Count(yy);

		for(wxImageHistogram::iterator i=Histogram.begin(); i!=Histogram.end(); ++i)
		{
			Colors.Set_Color(i->second.index, SG_GET_R(i->first), SG_GET_G(i->first), SG_GET_B(i->first));
		}

		pImage	= SG_Create_Grid(yy <= 2 ? SG_DATATYPE_Bit : SG_DATATYPE_Byte, Image.GetWidth(), Image.GetHeight(), Cellsize, xMin, yMin);

		for(y=0; y<pImage->Get_NY() && Set_Progress(y, pImage->Get_NY()); y++)
		{
			yy	= bTransform ? y : pImage->Get_NY() - 1 - y;

			for(x=0; x<pImage->Get_NX(); x++)
			{
				pImage->Set_Value(x, y, Histogram[SG_GET_RGB(Image.GetRed(x, yy), Image.GetGreen(x, yy), Image.GetBlue(x, yy))].index);
			}
		}

		if( bTransform )
		{
			Set_Transformation(&pImage, ax, ay, dx, dy, rx, ry);
		}

		pImage->Set_Name(Name);
		pImage->Get_Projection().Load(SG_File_Make_Path(NULL, fImage, SG_T("prj")));
		Parameters("OUT_GRID")->Set_Value(pImage);
		DataObject_Set_Colors(pImage, Colors);
		DataObject_Update(pImage, 0, Colors.Get_Count() - 1);
	}

	//-----------------------------------------------------
	else	// true color...
	{
		pImage	= SG_Create_Grid(SG_DATATYPE_Int, Image.GetWidth(), Image.GetHeight(), Cellsize, xMin, yMin);
		pImage	->Set_Name(Name);

		for(y=0; y<pImage->Get_NY() && Set_Progress(y, pImage->Get_NY()); y++)
		{
			yy	= bTransform ? y : pImage->Get_NY() - 1 - y;

			for(x=0; x<pImage->Get_NX(); x++)
			{
				pImage->Set_Value(x, y, SG_GET_RGB(Image.GetRed(x, yy), Image.GetGreen(x, yy), Image.GetBlue(x, yy)));
			}
		}

		if( bTransform )
		{
			Set_Transformation(&pImage, ax, ay, dx, dy, rx, ry);
		}

		//-------------------------------------------------
		if( Method != 1 )	// true color...
		{
			pImage->Get_Projection().Load(fImage, SG_PROJ_FMT_WKT);
			pImage->Set_Name(Name);
			pImage->Get_Projection().Load(SG_File_Make_Path(NULL, fImage, SG_T("prj")));
			Parameters("OUT_GRID")->Set_Value(pImage);
			DataObject_Set_Colors(pImage, 100, SG_COLORS_BLACK_WHITE);
			DataObject_Set_Parameter(pImage, "COLORS_TYPE", 6);	// Color Classification Type: RGB
		}

		//-------------------------------------------------
		else				// split channels...
		{
			CSG_Grid	*pR, *pG, *pB;

			pR	= SG_Create_Grid(pImage->Get_System(), SG_DATATYPE_Byte);
			pG	= SG_Create_Grid(pImage->Get_System(), SG_DATATYPE_Byte);
			pB	= SG_Create_Grid(pImage->Get_System(), SG_DATATYPE_Byte);

			for(y=0; y<pImage->Get_NY() && Set_Progress(y, pImage->Get_NY()); y++)
			{
				for(x=0; x<pImage->Get_NX(); x++)
				{
					pR->Set_Value(x, y, SG_GET_R(pImage->asInt(x, y)));
					pG->Set_Value(x, y, SG_GET_G(pImage->asInt(x, y)));
					pB->Set_Value(x, y, SG_GET_B(pImage->asInt(x, y)));
				}
			}

			pR->Get_Projection().Load(fImage, SG_PROJ_FMT_WKT);
			pG->Get_Projection().Load(fImage, SG_PROJ_FMT_WKT);
			pB->Get_Projection().Load(fImage, SG_PROJ_FMT_WKT);

			pR->Set_Name(CSG_String::Format(SG_T("%s [R]"), Name.c_str()));
			pG->Set_Name(CSG_String::Format(SG_T("%s [G]"), Name.c_str()));
			pB->Set_Name(CSG_String::Format(SG_T("%s [B]"), Name.c_str()));

			pR->Get_Projection().Load(SG_File_Make_Path(NULL, fImage, SG_T("prj")));
			pG->Get_Projection().Load(SG_File_Make_Path(NULL, fImage, SG_T("prj")));
			pB->Get_Projection().Load(SG_File_Make_Path(NULL, fImage, SG_T("prj")));

			Parameters("OUT_RED")	->Set_Value(pR);
			Parameters("OUT_GREEN")	->Set_Value(pG);
			Parameters("OUT_BLUE")	->Set_Value(pB);

			DataObject_Set_Colors(pR, 100, SG_COLORS_BLACK_RED);
			DataObject_Set_Colors(pG, 100, SG_COLORS_BLACK_GREEN);
			DataObject_Set_Colors(pB, 100, SG_COLORS_BLACK_BLUE);
		}
	}

	//-----------------------------------------------------
	if( !SG_UI_Get_Window_Main() && pImgHandler != NULL)
	{
		wxImage::RemoveHandler(pImgHandler->GetName());
	}

	//-----------------------------------------------------
	return( true );
}
Example #24
0
//---------------------------------------------------------
bool CSG_Grid::_Load_Native(const CSG_String &File_Name, TSG_Grid_Memory_Type Memory_Type)
{
	bool			bResult, hdr_bFlip, hdr_bSwapBytes;
	int				iType, hdr_Offset, NX, NY;
	double			Cellsize, xMin, yMin;
	CSG_File		Stream;
	TSG_Data_Type	hdr_Type;
	CSG_Grid_System	System;
	CSG_String		File_Data, Value;

	//-----------------------------------------------------
	bResult	= false;

	if( Stream.Open(File_Name, SG_FILE_R, false) )
	{
		//-------------------------------------------------
		// Load Header...

		hdr_Type		= SG_DATATYPE_Undefined;
		hdr_Offset		= 0;
		hdr_bFlip		= false;
		hdr_bSwapBytes	= false;

		NX	= NY		= 0;
		Cellsize		= 0.0;
		xMin			= 0.0;
		yMin			= 0.0;

		//-------------------------------------------------
		do
		{
			switch( _Load_Native_Get_Key(Stream, Value) )
			{
			case GRID_FILE_KEY_NAME:			Set_Name		(Value);			break;
			case GRID_FILE_KEY_DESCRIPTION:		Set_Description	(Value);			break;
			case GRID_FILE_KEY_UNITNAME:		Set_Unit		(Value);			break;

			case GRID_FILE_KEY_CELLCOUNT_X:		NX				= Value.asInt();	break;
			case GRID_FILE_KEY_CELLCOUNT_Y:		NY				= Value.asInt();	break;
			case GRID_FILE_KEY_POSITION_XMIN:	xMin			= Value.asDouble();	break;
			case GRID_FILE_KEY_POSITION_YMIN:	yMin			= Value.asDouble();	break;
			case GRID_FILE_KEY_CELLSIZE:		Cellsize		= Value.asDouble();	break;
			case GRID_FILE_KEY_Z_FACTOR:		m_zFactor		= Value.asDouble();	break;
			case GRID_FILE_KEY_NODATA_VALUE:	Set_NoData_Value(Value.asDouble());	break;

			case GRID_FILE_KEY_DATAFILE_OFFSET:	hdr_Offset		= Value.asInt();	break;
			case GRID_FILE_KEY_BYTEORDER_BIG:	hdr_bSwapBytes	= Value.Find(GRID_FILE_KEY_TRUE) >= 0;	break;
			case GRID_FILE_KEY_TOPTOBOTTOM:		hdr_bFlip		= Value.Find(GRID_FILE_KEY_TRUE) >= 0;	break;

			case GRID_FILE_KEY_DATAFILE_NAME:
				if( SG_File_Get_Path(Value).Length() > 0 )
				{
					File_Data	= Value;
				}
				else
				{
					File_Data	= SG_File_Make_Path(SG_File_Get_Path(File_Name), Value);
				}
				break;

			case GRID_FILE_KEY_DATAFORMAT:
				for(iType=0; iType<SG_DATATYPE_Undefined && hdr_Type == SG_DATATYPE_Undefined; iType++)
				{
					if( Value.Find(gSG_Data_Type_Identifier[iType]) >= 0 )
					{
						hdr_Type	= (TSG_Data_Type)iType;
					}
				}
				break;
			}
		}
		while( !Stream.is_EOF() );


		//-------------------------------------------------
		// Load Data...

		if( m_System.Assign(Cellsize, xMin, yMin, NX, NY) )
		{
			//---------------------------------------------
			// ASCII...

			if( !SG_Data_Type_is_Numeric(hdr_Type) )
			{
				if( m_Type >= SG_DATATYPE_Undefined )
				{
					m_Type	= SG_DATATYPE_Float;
				}

				if(	Stream.Open(File_Data											, SG_FILE_R, false)
				||	Stream.Open(SG_File_Make_Path(NULL, File_Name, SG_T( "dat"))	, SG_FILE_R, false)
				||	Stream.Open(SG_File_Make_Path(NULL, File_Name, SG_T("sdat"))	, SG_FILE_R, false) )
				{
					Stream.Seek(hdr_Offset);
					bResult	= _Load_ASCII(Stream, Memory_Type, hdr_bFlip);
				}
			}

			//---------------------------------------------
			// Binary...

			else
			{
				if( m_Type >= SG_DATATYPE_Undefined )
				{
					m_Type	= hdr_Type;
				}

				if( (NX = SG_Grid_Cache_Check(m_System, Get_nValueBytes())) > 0 )
				{
					Set_Buffer_Size(NX);

					if( _Cache_Create(File_Data											, hdr_Type, hdr_Offset, hdr_bSwapBytes, hdr_bFlip)
					||	_Cache_Create(SG_File_Make_Path(NULL, File_Name, SG_T( "dat"))	, hdr_Type, hdr_Offset, hdr_bSwapBytes, hdr_bFlip)
					||	_Cache_Create(SG_File_Make_Path(NULL, File_Name, SG_T("sdat"))	, hdr_Type, hdr_Offset, hdr_bSwapBytes, hdr_bFlip) )
					{
						return( true );
					}

					Memory_Type	= GRID_MEMORY_Cache;
				}

				if( _Memory_Create(Memory_Type) )
				{
					if(	Stream.Open(File_Data											, SG_FILE_R, true)
					||	Stream.Open(SG_File_Make_Path(NULL, File_Name, SG_T( "dat"))	, SG_FILE_R, true)
					||	Stream.Open(SG_File_Make_Path(NULL, File_Name, SG_T("sdat"))	, SG_FILE_R, true) )
					{
						Stream.Seek(hdr_Offset);
						bResult	= _Load_Binary(Stream, hdr_Type, hdr_bFlip, hdr_bSwapBytes);
					}
				}
			}
		}
	}

	return( bResult );
}
Example #25
0
//---------------------------------------------------------
bool CSG_Table::_Load_Text(const CSG_String &File_Name, bool bHeadline, const SG_Char *Separator)
{
	int			i, iField, fLength;
	CSG_String	sLine, sField;
	CSG_File	Stream;
	CSG_Table	Table;

	//-----------------------------------------------------
	if( Stream.Open(File_Name, SG_FILE_R, false) == false )
	{
		return( false );
	}

	if( !Stream.Read_Line(sLine) )
	{
		return( false );
	}

	//-----------------------------------------------------
	sLine	+= Separator;

	while( (i = sLine.Find(Separator)) >= 0 )
	{
		sField	= bHeadline ? sLine.Left(i) : CSG_String::Format(SG_T("FIELD_%02d"), Table.Get_Field_Count() + 1);

		if( sField[0] == SG_T('\"') && sField[(int)(sField.Length() - 1)] == SG_T('\"') )	// remove quota
		{
			sField	= sField.AfterFirst('\"').BeforeLast('\"');
		}

		Table.Add_Field(sField, SG_DATATYPE_String);

		sLine.Remove(0, i + 1);
	}

	//-----------------------------------------------------
	TSG_Data_Type	*Type	= new TSG_Data_Type[Table.Get_Field_Count()];

	for(iField=0; iField<Table.Get_Field_Count(); iField++)
	{
		Type[iField]	= SG_DATATYPE_Int;
	}

	if( !bHeadline )
	{
		Stream.Seek_Start();
	}

	fLength	= Stream.Length();

	while( Stream.Read_Line(sLine) && sLine.Length() > 0 && SG_UI_Process_Set_Progress(Stream.Tell(), fLength) )
	{
		CSG_Table_Record	*pRecord	= Table._Add_Record();

		sLine	+= Separator;

		for(iField=0; iField<Table.Get_Field_Count(); iField++)
		{
			if( (i = sLine.Find(Separator)) >= 0 )
			{
				sField	= sLine.Left(i);

				if( sField[0] == SG_T('\"') && sField[(int)(sField.Length() - 1)] == SG_T('\"') )	// remove quota
				{
					sField	= sField.AfterFirst('\"').BeforeLast('\"');
				}

				if( Type[iField] != SG_DATATYPE_String )
				{
					double	Value;

					if( SG_SSCANF(sField, SG_T("%lf"), &Value) != 1 )
					{
						Type[iField]	= SG_DATATYPE_String;
					}
					else if( Type[iField] != SG_DATATYPE_Double && Value - (int)Value != 0.0 )
					{
						Type[iField]	= SG_DATATYPE_Double;
					}
				}

				pRecord->Set_Value(iField, sField);

				sLine.Remove(0, i + 1);
			}
			else
			{
				break;
			}
		}
	}

	//-----------------------------------------------------
	if( Table.Get_Count() > 0 )
	{
		for(iField=0; iField<Table.Get_Field_Count(); iField++)
		{
			Add_Field(Table.Get_Field_Name(iField), Type[iField]);
		}

		for(int iRecord=0; iRecord<Table.Get_Count() && SG_UI_Process_Set_Progress(iRecord, Table.Get_Count()); iRecord++)
		{
			CSG_Table_Record	*pRecord	= _Add_Record();

			for(iField=0; iField<Get_Field_Count(); iField++)
			{
				switch( Get_Field_Type(iField) )
				{
				default:						pRecord->Set_Value(iField, Table[iRecord].asString(iField));	break;
				case SG_DATATYPE_Int:		pRecord->Set_Value(iField, Table[iRecord].asInt   (iField));	break;
				case SG_DATATYPE_Double:	pRecord->Set_Value(iField, Table[iRecord].asDouble(iField));	break;
				}
			}
		}
	}

	delete[](Type);

	SG_UI_Process_Set_Ready();

	return( Get_Field_Count() > 0 );
}
//---------------------------------------------------------
bool CSG_PointCloud::_Load(const CSG_String &File_Name)
{
    TSG_Data_Type	Type;

    char		ID[6];
    int			i, iBuffer, nPointBytes, nFields;
    char		Name[1024];
    CSG_File	Stream;

    SG_UI_Msg_Add(CSG_String::Format(SG_T("%s: %s..."), _TL("Load point cloud"), File_Name.c_str()), true);

    //-----------------------------------------------------
    if( !Stream.Open(File_Name, SG_FILE_R, true) )
    {
        SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
        SG_UI_Msg_Add_Error(_TL("file could not be opened."));

        return( false );
    }

    if( !Stream.Read(ID, 6) || strncmp(ID, PC_FILE_VERSION, 5) != 0 )
    {
        SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
        SG_UI_Msg_Add_Error(_TL("incompatible file."));

        return( false );
    }

    if( !Stream.Read(&nPointBytes, sizeof(int)) || nPointBytes < (int)(3 * sizeof(float)) )
    {
        SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
        SG_UI_Msg_Add_Error(_TL("incompatible file."));

        return( false );
    }

    if( !Stream.Read(&nFields, sizeof(int)) || nFields < 3 )
    {
        SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
        SG_UI_Msg_Add_Error(_TL("incompatible file."));

        return( false );
    }

    //-----------------------------------------------------
    Destroy();

    for(i=0; i<nFields; i++)
    {
        if( !Stream.Read(&Type		, sizeof(TSG_Data_Type))
                ||	!Stream.Read(&iBuffer	, sizeof(int)) || !(iBuffer > 0 && iBuffer < 1024)
                ||	!Stream.Read(Name		, iBuffer) )
        {
            SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
            SG_UI_Msg_Add_Error(_TL("incompatible file."));

            return( false );
        }

        if( ID[5] == '0' )	// Data Type Definition changed!!!
        {
            switch( Type )
            {
            default:
                Type	= SG_DATATYPE_Undefined;
                break;
            case 1:
                Type	= SG_DATATYPE_Char;
                break;
            case 2:
                Type	= SG_DATATYPE_Short;
                break;
            case 3:
                Type	= SG_DATATYPE_Int;
                break;
            case 4:
                Type	= SG_DATATYPE_Long;
                break;
            case 5:
                Type	= SG_DATATYPE_Float;
                break;
            case 6:
                Type	= SG_DATATYPE_Double;
                break;
            }
        }

        Name[iBuffer]	= '\0';

        if( !_Add_Field(CSG_String((const char *)Name), Type) )
        {
            SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
            SG_UI_Msg_Add_Error(_TL("incompatible file."));

            return( false );
        }
    }

    if( m_nPointBytes != nPointBytes + 1 )
    {
        SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
        SG_UI_Msg_Add_Error(_TL("incompatible file."));

        return( false );
    }

    //-----------------------------------------------------
    sLong		fLength	= Stream.Length();

    while( _Inc_Array() && Stream.Read(m_Cursor + 1, nPointBytes) && SG_UI_Process_Set_Progress((double)Stream.Tell(), (double)fLength) )
    {}

    _Dec_Array();

    Set_File_Name(File_Name, true);

    Load_MetaData(File_Name);

    if( 0 > Get_Count() )
    {
        SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);
        SG_UI_Msg_Add_Error(_TL("no records in file."));

        return( false );
    }

    //-----------------------------------------------------
    SG_UI_Process_Set_Ready();

    Get_Projection().Load(SG_File_Make_Path(NULL, File_Name, SG_T("prj")), SG_PROJ_FMT_WKT);

    SG_UI_Msg_Add(_TL("okay"), false, SG_UI_MSG_STYLE_SUCCESS);

    return( true );
}
Example #27
0
//---------------------------------------------------------
bool CBSL_Interpreter::On_Execute(void)
{
	//-----------------------------------------------------
	Parameters("OUTPUT")->asGridList()->Del_Items();

	g_bProgress	= Parameters("PROGRESS")->asBool();

	if( m_bFile )
	{
		CSG_File	Stream;
		
		if( !Stream.Open(Parameters("BSL")->asString(), SG_FILE_R, false) )
		{
			return( false );
		}

		Stream.Read(m_BSL, Stream.Length());
	}
	else
	{
		m_BSL	= Parameters("BSL")->asString();
	}

	//-----------------------------------------------------
	if( !Parse_Vars(false) )
	{
		return( false );
	}

	//-----------------------------------------------------
	CSG_Parameters	Input(this, _TL("Input"), _TL(""), SG_T("INPUT"), true);

	FindMemoryGrids();

	for(T_InputText::iterator it=InputGrids.begin(); it!=InputGrids.end(); it++)
	{
		CSG_String	sName(it->c_str());

		Input.Add_Grid(NULL, sName, sName, _TL(""), PARAMETER_INPUT, true);
	}

	DeleteVarList();
	DeleteAnweisungList(AnweisungList);

	if( Dlg_Parameters(&Input, _TL("Input")) == false )
	{
		return( false );
	}

	//-----------------------------------------------------
	if( !Parse_Vars(true) )
	{
		return( false );
	}

	//-----------------------------------------------------
	g_pInterpreter	= this;

	if( GetMemoryGrids(&Input) )
	{
		try
		{
			ausfuehren_anweisung(AnweisungList);
		}
		catch(BBFehlerAusfuehren x)
		{
			if( x.Text == "" )
				Message_Add(_TL("unknown error: execution"));
			else
				Message_Add(CSG_String::Format(SG_T("error: %s\n"), CSG_String(x.Text.c_str()).c_str()));
		}
		catch(BBFehlerUserbreak x)
		{
			if( x.Text == "" )
				Message_Add(_TL("unknown error: user break"));
			else
				Message_Add(CSG_String::Format(SG_T("error: %s\n"), CSG_String(x.Text.c_str()).c_str()));
		}
	}

	g_pInterpreter	= NULL;

	DeleteVarList();
	DeleteAnweisungList(AnweisungList);

	return( true );
}
Example #28
0
//---------------------------------------------------------
bool CWASP_MAP_Export::On_Execute(void)
{
	//-----------------------------------------------------
	CSG_File	Stream;

	if( !Stream.Open(Parameters("FILE")->asString(), SG_FILE_W, false) )
	{
		return( false );
	}

	CSG_Shapes	*pLines	= Parameters("SHAPES")->asShapes();

	if( !pLines->is_Valid() || pLines->Get_Count() <= 0 )
	{
		return( false );
	}

	//-----------------------------------------------------
	// 1)	Text string identifying the terrain map: + ...

	Stream.Printf("+ %s\n", pLines->Get_Name());


	// 2)	Fixed point #1 in user and metric [m] coordinates:
	//			X1(user) Y1(user) X1(metric) Y1(metric)

	Stream.Printf("%f %f %f %f\n", 0.0, 0.0, 0.0, 0.0);


	// 3)	Fixed point #2 in user and metric [m] coordinates:
	//			X2(user) Y2(user) X2(metric) Y2(metric)

	Stream.Printf("%f %f %f %f\n", 1.0, 1.0, 1.0, 1.0);


	// 4)	Scaling factor and offset for height scale (Z):
	//			Zmetric = {scaling factor}(Zuser + {offset})

	Stream.Printf("%f %f\n", 1.0, 0.0);

	int	zField	= Parameters("ELEVATION")->asInt();

	//-----------------------------------------------------
	for(int iLine=0; iLine<pLines->Get_Count() && Set_Progress(iLine, pLines->Get_Count()); iLine++)
	{
		CSG_Shape	*pLine	= pLines->Get_Shape(iLine);

		for(int iPart=0; iPart<pLine->Get_Part_Count(); iPart++)
		{
			if( pLine->Get_Point_Count(iPart) > 1 )
			{
				// 5a)	Height contour: elevation (Z) and number of points (n) in line:
				//			Z n

				Stream.Printf("%f %d\n", pLine->asDouble(zField), pLine->Get_Point_Count(iPart));


				// 5b)	Roughness change line:
				//			roughness lengths to the left (z0l) and right (z0r) side of the line,
				//			respectively, and number of points:
				//				z0l z0r n

				// 5c)	Roughness and contour line:
				//			roughness lengths to the left and right of the line,
				//			respectively, elevation and number of points:
				//				z0l z0r Z n


				// 6–)	Cartesian coordinates (X, Y) of line described in 5a, 5b or 5c:
				//			X1 Y1 [... Xn Yn]
				//			Xn+1 Yn+1
				//			... where [] embrace optional numbers and n is > 0

				for(int iPoint=0; iPoint<pLine->Get_Point_Count(iPart); iPoint++)
				{
					TSG_Point	p	= pLine->Get_Point(iPoint, iPart);

					Stream.Printf("%f\t%f\n", p.x, p.y);
				}
			}
		}
	}

	//-----------------------------------------------------
	return( true );
}
Example #29
0
//---------------------------------------------------------
bool CCMD_Module::_Get_Parameters(CSG_Parameters *pParameters)
{
    if( !pParameters || m_CMD.Parse(false) != 0 )
    {
        return( false );
    }

    //-----------------------------------------------------
    int		i;

    for(i=0; i<pParameters->Get_Count(); i++)
    {
        CSG_Parameter	*pParameter	= pParameters->Get_Parameter(i);

        if( pParameter->is_Input() )
        {
            // nop now, loading options first
        }

        else if( pParameter->is_Output() )
        {
            if( pParameter->is_DataObject() && pParameter->is_Optional() && !pParameter->asDataObject() && m_CMD.Found(_Get_ID(pParameter)) )
            {
                pParameter->Set_Value(DATAOBJECT_CREATE);
            }
        }

        else if( pParameter->is_Option() && !pParameter->is_Information() )
        {
            long		l;
            double		d;
            wxString	s;

            switch( pParameter->Get_Type() )
            {
            default:
                break;

            case PARAMETER_TYPE_Parameters:
                _Get_Parameters(pParameter->asParameters());
                break;

            case PARAMETER_TYPE_Bool:
                pParameter->Set_Value(m_CMD.Found(_Get_ID(pParameter)) ? 1 : 0);
                break;

            case PARAMETER_TYPE_Int:
                if( m_CMD.Found(_Get_ID(pParameter), &l) )
                {
                    pParameter->Set_Value((int)l);
                }
                break;

            case PARAMETER_TYPE_Choice:
                if( m_CMD.Found(_Get_ID(pParameter), &s) )
                {
                    if( s.ToLong(&l) )
                    {
                        pParameter->Set_Value((int)l);
                    }
                    else
                    {
                        pParameter->Set_Value(CSG_String(&s));
                    }
                }
                break;

            case PARAMETER_TYPE_Double:
            case PARAMETER_TYPE_Degree:
                if( m_CMD.Found(_Get_ID(pParameter), &s) && s.ToDouble(&d) )
                {
                    pParameter->Set_Value(d);
                }
                break;

            case PARAMETER_TYPE_Range:
                if( m_CMD.Found(_Get_ID(pParameter, wxT("MIN")), &s) && s.ToDouble(&d) )
                {
                    pParameter->asRange()->Set_LoVal(d);
                }

                if( m_CMD.Found(_Get_ID(pParameter, wxT("MAX")), &s) && s.ToDouble(&d) )
                {
                    pParameter->asRange()->Set_HiVal(d);
                }
                break;

            case PARAMETER_TYPE_String:
                if( m_CMD.Found(_Get_ID(pParameter), &s) )
                {
                    pParameter->Set_Value(CSG_String(&s));
                }
                break;

            case PARAMETER_TYPE_Text:
                if( m_CMD.Found(_Get_ID(pParameter), &s) )
                {
                    CSG_File	Stream;

                    if( Stream.Open(CSG_String(&s)) )
                    {
                        CSG_String	t;

                        Stream.Read(t, Stream.Length());

                        pParameter->Set_Value(t.c_str());
                    }
                    else
                    {
                        pParameter->Set_Value(CSG_String(&s));
                    }
                }
                break;

            case PARAMETER_TYPE_FilePath:
                if( m_CMD.Found(_Get_ID(pParameter), &s) )
                {
                    if( pParameter->asFilePath()->is_Multiple() )
                    {
                        s.Prepend(wxT("\""));
                        s.Replace(wxT(";"), wxT("\" \""));
                        s.Append (wxT("\""));
                    }

                    pParameter->Set_Value(CSG_String(&s));
                }
                break;

            case PARAMETER_TYPE_FixedTable:
                if( m_CMD.Found(_Get_ID(pParameter), &s) )
                {
                    CSG_Table	Table(&s);
                    pParameter->asTable()->Assign_Values(&Table);
                }
                break;

            case PARAMETER_TYPE_Grid_System:
                if( pParameter->Get_Children_Count() == 0 )
                {
                    long	nx, ny;
                    double	d, x, y;

                    if(	!m_CMD.Found(_Get_ID(pParameter, wxT("NX")), &nx)
                            ||	!m_CMD.Found(_Get_ID(pParameter, wxT("NY")), &ny)
                            ||	!m_CMD.Found(_Get_ID(pParameter, wxT( "X")), &s) || !s.ToDouble(&x)
                            ||	!m_CMD.Found(_Get_ID(pParameter, wxT( "Y")), &s) || !s.ToDouble(&y)
                            ||	!m_CMD.Found(_Get_ID(pParameter, wxT( "D")), &s) || !s.ToDouble(&d) )
                    {
                        pParameter->asGrid_System()->Assign(-1, 0.0, 0.0, 0, 0);
                    }
                    else
                    {
                        pParameter->asGrid_System()->Assign(d, x, y, (int)nx, (int)ny);
                    }
                }
                break;
            }
        }
    }

    m_pModule->Update_Parameter_States();

    //-----------------------------------------------------
    for(i=0; i<pParameters->Get_Count(); i++)
    {
        CSG_Parameter	*pParameter	= pParameters->Get_Parameter(i);

        if( pParameter->is_Input() )
        {
            if( !_Load_Input(pParameters->Get_Parameter(i)) )
            {
                CMD_Print_Error(pParameters->Get_Parameter(i)->Get_Name());

                return( false );
            }
        }

        else if( pParameter->is_Option() && !pParameter->is_Information() )
        {
            long		l;
            wxString	s;

            switch( pParameter->Get_Type() )
            {
            case PARAMETER_TYPE_Table_Field:
                if( m_CMD.Found(_Get_ID(pParameter), &s) )
                {
                    if( s.ToLong(&l) )
                    {
                        pParameter->Set_Value((int)l);
                    }
                    else
                    {
                        pParameter->Set_Value(CSG_String(&s));
                    }
                }
                break;

            case PARAMETER_TYPE_Table_Fields:
                if( m_CMD.Found(_Get_ID(pParameter), &s) )
                {
                    pParameter->Set_Value(CSG_String(&s));
                }
                break;
            }
        }
    }

    //-----------------------------------------------------
    return( true );
}
Example #30
0
//---------------------------------------------------------
bool CSG_Grid::_Load_Surfer(const CSG_String &File_Name, TSG_Grid_Memory_Type Memory_Type)
{
	bool		bResult		= false;
	char		Identifier[4];
	short		sValue;
	int			x, y, NX, NY;
	float		*fLine;
	double		dValue, xMin, yMin, Cellsize;
	CSG_File	Stream;

	if( Stream.Open(File_Name, SG_FILE_R, true) )
	{
		Stream.Read(Identifier, sizeof(char), 4);

		//-------------------------------------------------
		// Binary...

		if( !strncmp(Identifier, "DSBB", 4) )
		{
			Stream.Read(&sValue	, sizeof(short));
			NX			= sValue;
			Stream.Read(&sValue	, sizeof(short));
			NY			= sValue;

			Stream.Read(&xMin	, sizeof(double));
			Stream.Read(&dValue	, sizeof(double));	// XMax
			Cellsize	= (dValue - xMin) / (NX - 1.0);

			Stream.Read(&yMin	, sizeof(double));
			Stream.Read(&dValue	, sizeof(double));	// YMax...
			//DY		= (dValue - yMin) / (NY - 1.0);		// we could check, if cellsizes (x/y) equal...

			Stream.Read(&dValue	, sizeof(double));	// ZMin...
			Stream.Read(&dValue	, sizeof(double));	// ZMax...

			//---------------------------------------------
			if( !Stream.is_EOF() && Create(SG_DATATYPE_Float, NX, NY, Cellsize, xMin, yMin, Memory_Type) )
			{
				bResult	= true;

				fLine	= (float *)SG_Malloc(Get_NX() * sizeof(float));

				for(y=0; y<Get_NY() && !Stream.is_EOF() && SG_UI_Process_Set_Progress(y, Get_NY()); y++)
				{
					Stream.Read(fLine, sizeof(float), Get_NX());

					for(x=0; x<Get_NX(); x++)
					{
						Set_Value(x, y, fLine[x]);
					}
				}

				SG_Free(fLine);
			}
		}


		//-------------------------------------------------
		// ASCII...

		else if( !strncmp(Identifier, "DSAA", 4) )
		{
			SG_FILE_SCANF(Stream.Get_Stream(), SG_T("%d %d")	, &NX	, &NY);

			SG_FILE_SCANF(Stream.Get_Stream(), SG_T("%lf %lf"), &xMin	, &dValue);
			Cellsize	= (dValue - xMin) / (NX - 1.0);

			SG_FILE_SCANF(Stream.Get_Stream(), SG_T("%lf %lf"), &yMin	, &dValue);
			//DY		= (dValue - yMin) / (NY - 1.0);

			SG_FILE_SCANF(Stream.Get_Stream(), SG_T("%lf %lf"), &dValue, &dValue);

			//---------------------------------------------
			if( !Stream.is_EOF() && Create(SG_DATATYPE_Float, NX, NY, Cellsize, xMin, yMin, Memory_Type) )
			{
				bResult	= true;

				for(y=0; y<Get_NY() && !Stream.is_EOF() && SG_UI_Process_Set_Progress(y, Get_NY()); y++)
				{
					for(x=0; x<Get_NX(); x++)
					{
						SG_FILE_SCANF(Stream.Get_Stream(), SG_T("%lf"), &dValue);

						Set_Value(x, y, dValue);
					}
				}
			}
		}

		//-------------------------------------------------
		SG_UI_Process_Set_Ready();
	}

	return( bResult );
}