//---------------------------------------------------------
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 );
}
Exemple #2
0
//---------------------------------------------------------
bool CSG_Grid::_Load(const CSG_String &File_Name, TSG_Data_Type Type, TSG_Grid_Memory_Type Memory_Type)
{
	bool	bResult;

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

	m_Type	= Type;

	//-----------------------------------------------------
	SG_UI_Msg_Add(CSG_String::Format(SG_T("%s: %s..."), LNG("[MSG] Load grid"), File_Name.c_str()), true);

	if( SG_File_Cmp_Extension(File_Name, SG_T("grd")) )
	{
		bResult	= _Load_Surfer(File_Name, Memory_Type);
	}
	else
	{
		bResult	= _Load_Native(File_Name, Memory_Type);
	}

	//-----------------------------------------------------
	if( bResult )
	{
		Set_Update_Flag();

		Set_File_Name(File_Name);

		Load_MetaData(File_Name);

		m_bCreated	= true;

		SG_UI_Msg_Add(LNG("[MSG] okay"), false, SG_UI_MSG_STYLE_SUCCESS);
	}
	else
	{
		Destroy();

		SG_UI_Msg_Add(LNG("[MSG] failed"), false, SG_UI_MSG_STYLE_FAILURE);

		SG_UI_Msg_Add_Error(LNG("[ERR] Grid file could not be opened."));
	}

	//-----------------------------------------------------
	return( bResult );
}
//---------------------------------------------------------
bool CKriging_Universal::On_Initialize(void)
{
	m_pGrids		= Parameters("GRIDS"            )->asGridList();
	m_Interpolation	= Parameters("INTERPOL"         )->asInt();

	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;

	//-----------------------------------------------------
	if( m_nPoints_Max <= 0 && m_Radius <= 0 )	// global
	{
		return( CKriging_Universal_Global::On_Initialize() );
	}

	//-----------------------------------------------------
	m_Search.Create(m_pPoints->Get_Extent());

	for(int iPoint=0; iPoint<m_pPoints->Get_Count() && Set_Progress(iPoint, m_pPoints->Get_Count()); iPoint++)
	{
		CSG_Shape	*pPoint	= m_pPoints->Get_Shape(iPoint);

		if( !pPoint->is_NoData(m_zField) )
		{
			bool		bAdd	= true;

			for(int iGrid=0; iGrid<m_pGrids->Get_Count(); iGrid++)
			{
				if( !m_pGrids->asGrid(iGrid)->is_InGrid_byPos(pPoint->Get_Point(0)) )
				{
					bAdd	= false;
				}
			}

			if( bAdd )
			{
				m_Search.Add_Point(pPoint->Get_Point(0).x, pPoint->Get_Point(0).y, m_bLog ? log(pPoint->asDouble(m_zField)) : pPoint->asDouble(m_zField));
			}
		}
	}

	if( !m_Search.is_Okay() )
	{
		SG_UI_Msg_Add(_TL("could not initialize point search engine"), true);

		return( false );
	}

	//-----------------------------------------------------
	return( true );
}
Exemple #4
0
//---------------------------------------------------------
bool CSG_Shapes::Save(const CSG_String &File_Name, int Format)
{
	SG_UI_Msg_Add(CSG_String::Format(SG_T("%s: %s..."), _TL("Save shapes"), File_Name.c_str()), true);

	if( _Save_ESRI(File_Name) )
	{
		Set_Modified(false);

		Set_File_Name(File_Name, true);

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

		return( true );
	}

	SG_UI_Process_Set_Ready();
	SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);

	return( false );
}
Exemple #5
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 CKriging_Universal::On_Initialise(void)
{
	m_pGrids		= Parameters("GRIDS")		->asGridList();
	m_Interpolation	= Parameters("INTERPOL")	->asInt();

	m_Radius		= Parameters("MAXRADIUS")	->asDouble();

	m_nPoints_Min	= (int)Parameters("NPOINTS")->asRange()->Get_LoVal();
	m_nPoints_Max	= (int)Parameters("NPOINTS")->asRange()->Get_HiVal();

	m_Mode			= Parameters("MODE")		->asInt();

	//-----------------------------------------------------
	m_Search.Create(m_pPoints->Get_Extent());

	for(int iPoint=0; iPoint<m_pPoints->Get_Count() && Set_Progress(iPoint, m_pPoints->Get_Count()); iPoint++)
	{
		CSG_Shape	*pPoint	= m_pPoints->Get_Shape(iPoint);

		if( !pPoint->is_NoData(m_zField) )
		{
			bool		bAdd	= true;

			for(int iGrid=0; iGrid<m_pGrids->Get_Count(); iGrid++)
			{
				if( !m_pGrids->asGrid(iGrid)->is_InGrid_byPos(pPoint->Get_Point(0)) )
				{
					bAdd	= false;
				}
			}

			if( bAdd )
			{
				m_Search.Add_Point(pPoint->Get_Point(0).x, pPoint->Get_Point(0).y, pPoint->asDouble(m_zField));
			}
		}
	}

	if( !m_Search.is_Okay() )
	{
		SG_UI_Msg_Add(_TL("could not initialize point search engine"), true);

		return( false );
	}

	//-----------------------------------------------------
	int		nPoints_Max;

	switch( m_Mode )
	{
	default:	nPoints_Max	= m_nPoints_Max;		break;
	case 1:		nPoints_Max	= m_nPoints_Max * 4;	break;
	}

	m_Points.Set_Count	(nPoints_Max);
	m_G		.Create		(nPoints_Max + 1 + m_pGrids->Get_Count() + (m_bCoords ? 2 : 0));
	m_W		.Create		(nPoints_Max + 1 + m_pGrids->Get_Count() + (m_bCoords ? 2 : 0),
						 nPoints_Max + 1 + m_pGrids->Get_Count() + (m_bCoords ? 2 : 0));

	return( true );
}
//---------------------------------------------------------
bool CPointCloud_From_Text_File::On_Execute(void)
{
	CSG_String				fileName;
	int						iField, iType;
	TSG_Data_Type			Type;
	CSG_String				Name, Types, s;
	CSG_PointCloud			*pPoints;
	CSG_Parameters			P;
	CSG_Parameter			*pNode;
	int						xField, yField, zField, nAttribs, max_iField;
	bool					bSkipHeader;
	char					fieldSep;
	std::vector<int>		vCol;
	std::ifstream			tabStream;
    std::string				tabLine;
	double					lines;
	long					cntPt, cntInvalid;
	double					x, y, z, value;


	//-----------------------------------------------------
	fileName	= Parameters("FILE")		->asString();
	xField		= Parameters("XFIELD")		->asInt() - 1;
	yField		= Parameters("YFIELD")		->asInt() - 1;
	zField		= Parameters("ZFIELD")		->asInt() - 1;
	nAttribs	= Parameters("ATTRIBS")		->asInt();
	bSkipHeader	= Parameters("SKIP_HEADER")	->asBool();

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

	Types.Printf(SG_T("%s|%s|%s|%s|%s|"),
		_TL("1 byte integer"),
		_TL("2 byte integer"),
		_TL("4 byte integer"),
		_TL("4 byte floating point"),
		_TL("8 byte floating point")
	);

	P.Set_Name(_TL("Attribute Field Properties"));

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

		s.Printf(SG_T("FIELD_%03d"), iField);
		P.Add_String(pNode, s, _TL("Name"), _TL(""), s);

		s.Printf(SG_T("COLUMN_%03d"), iField);
		P.Add_Value(pNode, s, _TL("Attribute is Column ..."), _TL(""), PARAMETER_TYPE_Int, iField+3, 1, true);

		s.Printf(SG_T("TYPE_%03d") , iField);
		P.Add_Choice(pNode, s, _TL("Type"), _TL(""), Types, 3);
	}

	//-----------------------------------------------------
	if( nAttribs > 0 )
	{
		if( Dlg_Parameters(&P, _TL("Field Properties")) )
		{
			pPoints	= SG_Create_PointCloud();
			pPoints->Set_Name(SG_File_Get_Name(fileName, false));
			Parameters("POINTS")->Set_Value(pPoints);

			for(iField=0; iField<nAttribs; iField++)
			{

				Name		 = P(CSG_String::Format(SG_T("FIELD_%03d" ), iField + 1).c_str())->asString();
				iType		 = P(CSG_String::Format(SG_T("TYPE_%03d"  ), iField + 1).c_str())->asInt();
				vCol.push_back(P(CSG_String::Format(SG_T("COLUMN_%03d"), iField + 1).c_str())->asInt() - 1);

				switch( iType )
				{
				default:
				case 0:	Type	= SG_DATATYPE_Char;		break;
				case 1:	Type	= SG_DATATYPE_Short;	break;
				case 2:	Type	= SG_DATATYPE_Int;		break;
				case 3:	Type	= SG_DATATYPE_Float;	break;
				case 4:	Type	= SG_DATATYPE_Double;	break;
				}

				pPoints->Add_Field(Name, Type);
			}
		}
		else
			return( false );
	}
	else
	{
		pPoints	= SG_Create_PointCloud();
		pPoints->Create();
		pPoints->Set_Name(SG_File_Get_Name(fileName, false));
		Parameters("POINTS")->Set_Value(pPoints);
	}

	max_iField = M_GET_MAX(xField, yField);
    max_iField = M_GET_MAX(max_iField, zField);
	for( unsigned int i=0; i<vCol.size(); i++ )
	{
		if( max_iField < vCol.at(i) )
			max_iField = vCol.at(i);
	}

	// open input stream
    //---------------------------------------------------------
    tabStream.open(fileName.b_str(), std::ifstream::in);
    if( !tabStream )
    {
        SG_UI_Msg_Add_Error(CSG_String::Format(_TL("Unable to open input file!")));
        return (false);
    }

	tabStream.seekg(0, std::ios::end);	// get length of file
    lines = (double)tabStream.tellg();
    tabStream.seekg(0, std::ios::beg);

    std::getline(tabStream, tabLine);	// as a workaround we assume the number of lines from the length of the first line
    lines = lines / (double)tabStream.tellg();

	if( !bSkipHeader )
    {
        tabStream.clear();                      // let's forget we may have reached the EOF
        tabStream.seekg(0, std::ios::beg);      // and rewind to the beginning
    }

    
	// import
    //---------------------------------------------------------
	cntPt = cntInvalid = 0;

	SG_UI_Process_Set_Text(CSG_String::Format(_TL("Importing data ...")));

    while( std::getline(tabStream, tabLine) )
    {
        std::istringstream stream(tabLine);
        std::vector<std::string> tabCols;
        std::string tabEntry;

        if( cntPt%10000 == 0 )
            SG_UI_Process_Set_Progress((double)cntPt, lines);

        cntPt++;

        while( std::getline(stream, tabEntry, fieldSep) )      // read every column in this line and fill vector
        {
            if (tabEntry.length() == 0)
                continue;
            tabCols.push_back(tabEntry);
        }

        if ((int)tabCols.size() < max_iField - 1 )
        {
            SG_UI_Msg_Add(CSG_String::Format(_TL("WARNING: Skipping misformatted line (%.0f)!"), cntPt), true);
            cntInvalid++;
            continue;
        }

		x = strtod(tabCols[xField].c_str(), NULL);
        y = strtod(tabCols[yField].c_str(), NULL);
        z = strtod(tabCols[zField].c_str(), NULL);

		pPoints->Add_Point(x, y, z);

		for( int i=0; i<nAttribs; i++ )
		{
			value = strtod(tabCols.at(vCol.at(i)).c_str(), NULL);
			pPoints->Set_Attribute(i, value);
		}
	}

	// finalize
    //---------------------------------------------------------
	tabStream.close();

	CSG_Parameters	sParms;
	DataObject_Get_Parameters(pPoints, sParms);
	if (sParms("COLORS_ATTRIB")	&& sParms("COLORS_TYPE") && sParms("METRIC_COLORS")
		&& sParms("METRIC_ZRANGE") && sParms("COLORS_AGGREGATE"))
		{
			sParms("COLORS_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("COLORS_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);
			DataObject_Update(pPoints);
		}

	if (cntInvalid > 0)
        SG_UI_Msg_Add(CSG_String::Format(_TL("WARNING: Skipped %d invalid points!"), cntInvalid), true);

    SG_UI_Msg_Add(CSG_String::Format(_TL("%d points sucessfully imported."), (cntPt-cntInvalid)), true);

	return( true );
}
//---------------------------------------------------------
bool CGrid_Tiling::On_Execute(void)
{
	bool					bSaveTiles;
	int						ix, iy, nx, ny, Overlap;
	double					y, x, dx, dy, dCell;
	CSG_String				FilePath, BaseName;
	TSG_Data_Type			Type;
	TSG_Rect				Extent;
	TSG_Grid_Resampling	Interpolation;
	CSG_Grid				*pGrid, *pTile;
	CSG_Parameter_Grid_List	*pTiles;

	//-----------------------------------------------------
	pGrid	= Parameters("GRID")	->asGrid();
	pTiles	= Parameters("TILES")	->asGridList();
	Overlap	= Parameters("OVERLAP")	->asInt();

	bSaveTiles	= Parameters("SAVE_TILES")		->asBool();
	BaseName	= Parameters("TILE_BASENAME")	->asString();
	FilePath	= Parameters("TILE_PATH")		->asString();


	switch( Parameters("METHOD")->asInt() )
	{
	case 0: default:
		Extent.xMin		= pGrid->Get_XMin();
		Extent.xMax		= pGrid->Get_XMax();
		Extent.yMin		= pGrid->Get_YMin();
		Extent.yMax		= pGrid->Get_YMax();
		dCell			= pGrid->Get_Cellsize();
		nx				= Parameters("NX")		->asInt();
		ny				= Parameters("NY")		->asInt();
		dx				= dCell * nx;
		dy				= dCell * ny;
		Type			= pGrid->Get_Type();
		Interpolation	= GRID_RESAMPLING_NearestNeighbour;
		break;

	case 1:
		Extent.xMin		= Parameters("XRANGE")	->asRange()->Get_LoVal();
		Extent.xMax		= Parameters("XRANGE")	->asRange()->Get_HiVal();
		Extent.yMin		= Parameters("YRANGE")	->asRange()->Get_LoVal();
		Extent.yMax		= Parameters("YRANGE")	->asRange()->Get_HiVal();
		dCell			= Parameters("DCELL")	->asDouble();
		dx				= Parameters("DX")		->asDouble();
		dy				= Parameters("DY")		->asDouble();
		nx				= (int)(dx / dCell);
		ny				= (int)(dy / dCell);
		Type			= pGrid->Get_Type();
		Interpolation	= GRID_RESAMPLING_Undefined;
		break;
	}

	switch( Parameters("OVERLAP_SYM")->asInt() )
	{
	case 0: default:	// symetric
		nx		+= Overlap * 2;
		ny		+= Overlap * 2;
		break;

	case 1:				// bottom / left
		nx		+= Overlap;
		ny		+= Overlap;
		break;

	case 2:				// top / right
		nx		+= Overlap;
		ny		+= Overlap;
		Overlap	 = 0;
		break;
	}

	pTiles->Del_Items();

	//-----------------------------------------------------
	if( dx <= 0.0 || dy <= 0.0 || dCell <= 0.0 )
	{
		Message_Add(_TL("no intersection with mask grid."));

		return( false );
	}

	if( bSaveTiles )
	{
		if( !SG_STR_CMP(BaseName, SG_T("")) )
		{
			SG_UI_Msg_Add_Error(_TL("Please provide a valid base name for the output files!"));
			return( false );
		}
		if( !SG_STR_CMP(FilePath, SG_T("")) )
		{
			SG_UI_Msg_Add_Error(_TL("Please provide a valid output directory for the output files!"));
			return( false );
		}
	}


	//-----------------------------------------------------
	int		iTiles = 0;

	for(y=Extent.yMin, iy=1; y<Extent.yMax && Process_Get_Okay(); y+=dy, iy++)
	{
		for(x=Extent.xMin, ix=1; x<Extent.xMax; x+=dx, ix++)
		{
			pTile	= SG_Create_Grid(Type, nx, ny, dCell, x - dCell * Overlap, y - dCell * Overlap);
			pTile	->Assign(pGrid, Interpolation);
			pTile	->Set_Name(CSG_String::Format(SG_T("%s [%d, %d]"), pGrid->Get_Name(), iy, ix));

			if( pTile->Get_NoData_Count() == pTile->Get_NCells() )
			{
				delete(pTile);
			}
			else
			{
				if( bSaveTiles )
				{
					CSG_String FileName = CSG_String::Format(SG_T("%s/%s_%d_%d"), FilePath.c_str(), BaseName.c_str(), iy, ix);
					pTile->Save(FileName);
					delete(pTile);
				}
				else
				{
					pTiles->Add_Item(pTile);
				}

				iTiles++;
			}
		}
	}

	SG_UI_Msg_Add(CSG_String::Format(_TL("%d tiles created."), iTiles), true);

	return( iTiles > 0 );
}
//---------------------------------------------------------
bool CPointCloud_From_Text_File::On_Execute(void)
{
	CSG_String				fileName;
	int						iField, iType;
	CSG_String				Name, Types, s;
	CSG_PointCloud			*pPoints;
	CSG_Parameters			P;
	CSG_Parameter			*pNode;
	int						xField, yField, zField, nAttribs;
	bool					bSkipHeader;
	char					fieldSep;
	std::vector<int>		vCol;
	std::ifstream			tabStream;
    std::string				tabLine;
	double					lines;
	long					cntPt, cntInvalid;
	double					x, y, z;


	//-----------------------------------------------------
	fileName	= Parameters("FILE")		->asString();
	xField		= Parameters("XFIELD")		->asInt() - 1;
	yField		= Parameters("YFIELD")		->asInt() - 1;
	zField		= Parameters("ZFIELD")		->asInt() - 1;
	bSkipHeader	= Parameters("SKIP_HEADER")	->asBool();

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

    pPoints	= SG_Create_PointCloud();
    pPoints->Create();
    pPoints->Set_Name(SG_File_Get_Name(fileName, false));
    Parameters("POINTS")->Set_Value(pPoints);
    DataObject_Add(pPoints);


    //-----------------------------------------------------
    if (SG_UI_Get_Window_Main())
    {
        nAttribs	= Parameters("ATTRIBS")		->asInt();

        Types.Printf(SG_T("%s|%s|%s|%s|%s|"),
            _TL("1 byte integer"),
            _TL("2 byte integer"),
            _TL("4 byte integer"),
            _TL("4 byte floating point"),
            _TL("8 byte floating point")
        );

        P.Set_Name(_TL("Attribute Field Properties"));

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

            s.Printf(SG_T("FIELD_%03d"), iField);
            P.Add_String(pNode, s, _TL("Name"), _TL(""), s);

            s.Printf(SG_T("COLUMN_%03d"), iField);
            P.Add_Value(pNode, s, _TL("Attribute is Column ..."), _TL(""), PARAMETER_TYPE_Int, iField+3, 1, true);

            s.Printf(SG_T("TYPE_%03d") , iField);
            P.Add_Choice(pNode, s, _TL("Type"), _TL(""), Types, 3);
        }

        //-----------------------------------------------------
        if( nAttribs > 0 )
        {
            if( Dlg_Parameters(&P, _TL("Field Properties")) )
            {
                for(iField=0; iField<nAttribs; iField++)
                {

                    Name		 = P(CSG_String::Format(SG_T("FIELD_%03d" ), iField + 1).c_str())->asString();
                    iType		 = P(CSG_String::Format(SG_T("TYPE_%03d"  ), iField + 1).c_str())->asInt();
                    vCol.push_back(P(CSG_String::Format(SG_T("COLUMN_%03d"), iField + 1).c_str())->asInt() - 1);

                    pPoints->Add_Field(Name, Get_Data_Type(iType));
                }
            }
            else
                return( false );
        }
    }
    else // CMD
	{
		CSG_String		    sFields, sNames, sTypes;
		CSG_String		    token;
		int				    iValue;
		std::vector<int>	vTypes;


		sFields		= Parameters("FIELDS")->asString();
		sNames		= Parameters("FIELDNAMES")->asString();
		sTypes	    = Parameters("FIELDTYPES")->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 < 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_datatypes(sTypes, ";", SG_TOKEN_STRTOK);

		while( tkz_datatypes.Has_More_Tokens() )
		{
			token	= tkz_datatypes.Get_Next_Token();

			if( token.Length() == 0 )
				break;

			if( !token.asInt(iValue) )
			{
				SG_UI_Msg_Add_Error(_TL("Error parsing field type: can't convert to number"));
				return( false );
			}

			vTypes.push_back(iValue);
		}

		CSG_String_Tokenizer   tkz_datanames(sNames, ";", SG_TOKEN_STRTOK);

        int                 iter = 0;

		while( tkz_datanames.Has_More_Tokens() )
		{
			token	= tkz_datanames.Get_Next_Token();

			if( token.Length() == 0 )
				break;

			pPoints->Add_Field(token, Get_Data_Type(vTypes.at(iter)));

			iter++;
		}

		if( vCol.size() != vTypes.size() || (int)vCol.size() != iter )
		{
		    SG_UI_Msg_Add_Error(CSG_String::Format(_TL("Number of arguments for attribute fields (%d), names (%d) and types (%d) do not match!"), vCol.size(), iter, vTypes.size()));
            return( false );
		}
	}


	// open input stream
    //---------------------------------------------------------
    tabStream.open(fileName.b_str(), std::ifstream::in);
    if( !tabStream )
    {
        SG_UI_Msg_Add_Error(CSG_String::Format(_TL("Unable to open input file!")));
        return (false);
    }

	tabStream.seekg(0, std::ios::end);	// get length of file
    lines = (double)tabStream.tellg();
    tabStream.seekg(0, std::ios::beg);

    std::getline(tabStream, tabLine);	// as a workaround we assume the number of lines from the length of the first line
    lines = lines / (double)tabStream.tellg();

	if( !bSkipHeader )
    {
        tabStream.clear();                      // let's forget we may have reached the EOF
        tabStream.seekg(0, std::ios::beg);      // and rewind to the beginning
    }


	// import
    //---------------------------------------------------------
	cntPt = cntInvalid = 0;

	SG_UI_Process_Set_Text(CSG_String::Format(_TL("Importing data ...")));

    while( std::getline(tabStream, tabLine) )
    {
        std::istringstream stream(tabLine);
        std::vector<std::string> tabCols;
        std::string tabEntry;

        if( cntPt%10000 == 0 )
		{
            SG_UI_Process_Set_Progress((double)cntPt, lines);
		}
        cntPt++;

        while( std::getline(stream, tabEntry, fieldSep) )      // read every column in this line and fill vector
        {
            if (tabEntry.length() == 0)
                continue;
            tabCols.push_back(tabEntry);
        }

        if ((int)tabCols.size() < (vCol.size() + 3) )
        {
            SG_UI_Msg_Add(CSG_String::Format(_TL("WARNING: Skipping misformatted line: %d!"), cntPt), true);
            cntInvalid++;
            continue;
        }

        //parse line tokens
		std::vector<double> fieldValues;
		fieldValues.resize(vCol.size());

		x = strtod(tabCols[xField].c_str(), NULL);
        y = strtod(tabCols[yField].c_str(), NULL);
        z = strtod(tabCols[zField].c_str(), NULL);

		for( int i=0; i<(int)vCol.size(); i++ )
		{
			fieldValues[i] = strtod(tabCols.at(vCol.at(i)).c_str(), NULL);
		}

		pPoints->Add_Point(x, y, z);

		for( int i=0; i<(int)vCol.size(); i++ )
		{
			pPoints->Set_Attribute(i, fieldValues[i]);
		}
    }

	// finalize
    //---------------------------------------------------------
	tabStream.close();

	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);
		DataObject_Update(pPoints);
	}

	if (cntInvalid > 0)
        SG_UI_Msg_Add(CSG_String::Format(SG_T("%s: %d %s"), _TL("WARNING"), cntInvalid, _TL("invalid points have been skipped")), true);

    SG_UI_Msg_Add(CSG_String::Format(SG_T("%d %s"), (cntPt-cntInvalid), _TL("points have been imported with success")), true);

	return( true );
}
bool Cconnectivity_analysis::On_Execute(void)
{
	CSG_Grid *pinpgrid, *bingrid, *symb_grid, *hgrid;
	CSG_Shapes *pOutlines;

	bool filter, corners_centers, remove_marginal_regions;
	unsigned short numrows;
	unsigned short numcols;
	unsigned char center;
	double xmin;
	double ymin;
	short interm_grid_created;
    simple_REGIONC_list *reg_first;
    simple_REGIONC_list *reg_last;
	simple_REGIONC_list *reg_curr;

	pinpgrid = Parameters ("INPUT_GRID")->asGrid();
	bingrid = Parameters ("FILTERED_MASK")->asGrid();
	filter = Parameters ("FILTER")->asBool();
	corners_centers = Parameters ("BORDER_PIXEL_CENTERS")->asBool();
	remove_marginal_regions = Parameters ("REMOVE_MARGINAL_REGIONS")->asBool();
	pOutlines = Parameters("OUTLINES")->asShapes();
	symb_grid = Parameters ("SYMBOLIC_IMAGE")->asGrid();
	CSG_String	sName = pOutlines->Get_Name();
	pOutlines->Destroy();
	pOutlines->Set_Name(sName);
	pOutlines->Add_Field(SG_T("ID"), SG_DATATYPE_Int);

	numrows=pinpgrid->Get_NY()+2;
	numcols=pinpgrid->Get_NX()+2;
//	xmin=pinpgrid->Get_XMin()-2*pinpgrid->Get_Cellsize();
//	ymin=pinpgrid->Get_YMin()-2*pinpgrid->Get_Cellsize();

	xmin=pinpgrid->Get_XMin();
	ymin=pinpgrid->Get_YMin();

	unsigned char **bin_image;
	long **symb_image;

	if (corners_centers)
		center = 1;
	else
		center = 0;

	bin_image = (unsigned char **) matrix_all_alloc (numrows, numcols, 'U', 0);
	symb_image = (long **) matrix_all_alloc (numrows, numcols, 'L', 0);

	interm_grid_created = 0;

	//SG_Free(bin_image);
	//CSG_Grid *pTmp = new CSG_Grid();
	//delete pTmp;

	if (filter)
	{
		if (bingrid == NULL)
		{
			SG_UI_Msg_Add(_TL("Filtered mask will be created automatically ..."), true);

			bingrid = SG_Create_Grid(SG_DATATYPE_Char,
				                     pinpgrid->Get_NX(),
									 pinpgrid->Get_NY(),
									 pinpgrid->Get_Cellsize(),
									 pinpgrid->Get_XMin(),
									 pinpgrid->Get_YMin());

			if (bingrid == NULL)
			{
				SG_UI_Msg_Add_Error(_TL("Unable to create filtered mask grid!"));
	            matrix_all_free ((void **) bin_image);
	            matrix_all_free ((void **) symb_image);

				return (false);
			}

			Parameters("FILTERED_MASK")->Set_Value(bingrid);
			interm_grid_created = 1;
		}


		//-----------------------------------------------------
		RUN_MODULE("grid_filter"			, 13,
				SET_PARAMETER("INPUT_GRID"  , pinpgrid)
			&&	SET_PARAMETER("OUTPUT_GRID"	, bingrid)
			&&	SET_PARAMETER("RADIUS"		, Parameters ("SIZE")->asInt())
		)

		hgrid = bingrid;
	}
	else
	{
	    hgrid = pinpgrid;
	}

    for (int y = 0; y < hgrid->Get_NY () && Set_Progress(y, hgrid->Get_NY()); y++)
	{
	    for (int x = 0; x < hgrid->Get_NX(); x++)
		{
            if (hgrid->is_NoData(x,y))
		        bin_image[y+1][x+1] = 0;
			else
		        bin_image[y+1][x+1] = hgrid->asChar(x,y);
		}
	}


	// Here the regions are removed which have contact with the image margins;
	// this is achieved by a region growing

	if (remove_marginal_regions)
	{
		for (int y = 1; y < numrows - 1; y++)
		{
			if (bin_image [y][1] != 0)
				background_region_growing (bin_image, numrows, numcols, y, 1);

			if (bin_image [y][numcols - 2] != 0)
				background_region_growing (bin_image, numrows, numcols, y, numcols-2);
		}

		for (int x = 1; x < numcols - 1; x++)
		{
			if (bin_image [1][x] != 0)
				background_region_growing (bin_image, numrows, numcols, 1, x);

			if (bin_image [numrows-2][x] != 0)
				background_region_growing (bin_image, numrows, numcols, numrows-2, x);
		}

		if (filter)
		{
		    for (int y = 0; y < bingrid->Get_NY (); y++)
 	        {
     		    #pragma omp parallel for
		        for (int x = 0; x < bingrid->Get_NX(); x++)
		        {
			        bingrid->Set_Value(x, y, bin_image[y+1][x+1]);
		        }
	        }
		}
	}

	if (interm_grid_created)
		bingrid->Destroy();


	// The function which does the proper work: 
	// computation of the symbolic image, construction of the border chains (shapes)
	
	comb_contour_region_marking (numrows,
                                 numcols,
                                 bin_image,
                                 symb_image,
                                 &reg_first,
                                 &reg_last,
                                 center);


	for (int y = 0; y < symb_grid->Get_NY () && Set_Progress(y, symb_grid->Get_NY()); y++)
 	{
		#pragma omp parallel for
		for (int x = 0; x < symb_grid->Get_NX(); x++)
		{
			symb_grid->Set_Value(x, y, symb_image[y+1][x+1]);
		}
	}


	// Here the shapes are generated

	int iPolygon;

	for (iPolygon = 0, reg_curr = reg_first; reg_curr != NULL; reg_curr = reg_curr -> next, iPolygon++)
	{
		CSG_Shape	*pShape = pOutlines->Add_Shape();

		pShape->Set_Value(0, iPolygon);		// set ID field (= first field in table) to polygon ID

		for (simple_PIXELC_list *pix_curr = reg_curr->first_pix; pix_curr != NULL; pix_curr = pix_curr->next)
		{
			TSG_Point point = symb_grid->Get_System().Get_Grid_to_World(pix_curr->col - 1, pix_curr->row - 1);
			pShape->Add_Point(point, 0);
		}

		int iHoles;
		simple_INNER_REGION_list *inner_curr;

		for (iHoles=0, inner_curr = reg_curr->inner_first;
			 iHoles < reg_curr->num_holes;
			 iHoles++, inner_curr = inner_curr->next)
		{
			for (simple_PIXELC_list *pix_curr = inner_curr->first_pix; pix_curr != NULL; pix_curr = pix_curr->next)
			{
				TSG_Point point = symb_grid->Get_System().Get_Grid_to_World(pix_curr->col - 1, pix_curr->row - 1);
				pShape->Add_Point(point, iHoles+1);
			}
		}

        if (!corners_centers)
            shift_shape (pShape, -Get_Cellsize()/2.0, -Get_Cellsize()/2.0);
	}

	matrix_all_free ((void **) bin_image);
	matrix_all_free ((void **) symb_image);
	free_regions (&reg_first, &reg_last);

	return( true );
}
//---------------------------------------------------------
bool CGrid_IMCORR::On_Execute(void)
{
	CSG_Grid		*pGrid1, *pGrid2, *pDTM1, *pDTM2;
	CSG_Shapes		*pCorrPts, *pCorrLines;
	CSG_Shape		*pCorrPt, *pCorrLine;
	int				Search_Chipsize, Ref_Chipsize, Grid_Spacing;
	double			SpacingMetrics;

	pGrid1			= Parameters("GRID_1")->asGrid();
	pGrid2			= Parameters("GRID_2")->asGrid();
	pDTM1			= Parameters("DTM_1")->asGrid();
	pDTM2			= Parameters("DTM_2")->asGrid();
	pCorrPts		= Parameters("CORRPOINTS")->asShapes();
	pCorrLines		= Parameters("CORRLINES")->asShapes();
	Search_Chipsize	= Parameters("SEARCH_CHIPSIZE")->asInt();
	Ref_Chipsize	= Parameters("REF_CHIPSIZE")->asInt();
	SpacingMetrics	= Parameters("GRID_SPACING")->asDouble();

	Search_Chipsize = (int)(pow(2.0,4+Search_Chipsize));
	Ref_Chipsize = (int)(pow(2.0,4+Ref_Chipsize));
	if (Search_Chipsize < Ref_Chipsize)
		Search_Chipsize = Ref_Chipsize;

	CSG_String	Message = CSG_String::Format(_TL("Search chip size set to %d"), Search_Chipsize);
	SG_UI_Msg_Add(Message,true);
	Message = CSG_String::Format(_TL("Reference chip size set to %d"), Ref_Chipsize);
	SG_UI_Msg_Add(Message,true);


	if (pDTM1 == NULL || pDTM2 == NULL)
	{
		CSG_String	name = CSG_String::Format(_TL("%s_CORRPOINTS"), pGrid1->Get_Name());
		pCorrPts->Create(SHAPE_TYPE_Point, name.c_str(), pCorrPts);
		pCorrPts->Add_Field(SG_T("ID"), SG_DATATYPE_Int);
		pCorrPts->Add_Field(SG_T("GX"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("GY"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("REALX"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("REALY"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("DISP"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("STRENGTH"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("FLAG"), SG_DATATYPE_Int);
		pCorrPts->Add_Field(SG_T("XDISP"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("YDISP"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("XDISP_UNIT"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("YDISP_UNIT"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("XTARG"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("YTARG"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("XERR"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("YERR"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("ASPECT"), SG_DATATYPE_Double);

		CSG_String	name2 = CSG_String::Format(_TL("%s_DISP_VEC"), pGrid1->Get_Name());
		pCorrLines->Create(SHAPE_TYPE_Line, name2.c_str(), pCorrLines);
		pCorrLines->Add_Field(SG_T("ID"), SG_DATATYPE_Int);
		pCorrLines->Add_Field(SG_T("GX"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("GY"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("REALX"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("REALY"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("DISP"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("STRENGTH"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("FLAG"), SG_DATATYPE_Int);
		pCorrLines->Add_Field(SG_T("XDISP"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("YDISP"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("XDISP_UNIT"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("YDISP_UNIT"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("XTARG"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("YTARG"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("XERR"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("YERR"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("ASPECT"), SG_DATATYPE_Double);
	}
	else // If DTM is given the Output gets 3D
	{
		CSG_String	name = CSG_String::Format(_TL("%s_CORRPOINTS"), pGrid1->Get_Name());
		pCorrPts->Create(SHAPE_TYPE_Point, name.c_str(), pCorrPts, SG_VERTEX_TYPE_XYZ);
		pCorrPts->Add_Field(SG_T("ID"), SG_DATATYPE_Int);
		pCorrPts->Add_Field(SG_T("GX"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("GY"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("REALX"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("REALY"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("REALZ"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("DISP"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("DISP_REAL"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("STRENGTH"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("FLAG"), SG_DATATYPE_Int);
		pCorrPts->Add_Field(SG_T("XDISP"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("YDISP"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("ZDISP"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("XDISP_UNIT"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("YDISP_UNIT"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("XTARG"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("YTARG"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("ZTARG"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("XERR"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("YERR"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("ASPECT"), SG_DATATYPE_Double);
		pCorrPts->Add_Field(SG_T("SLOPE"), SG_DATATYPE_Double);

		CSG_String	name2 = CSG_String::Format(_TL("%s_DISP_VEC"), pGrid1->Get_Name());
		pCorrLines->Create(SHAPE_TYPE_Line, name2.c_str(), pCorrLines, SG_VERTEX_TYPE_XYZ);
		pCorrLines->Add_Field(SG_T("ID"), SG_DATATYPE_Int);
		pCorrLines->Add_Field(SG_T("GX"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("GY"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("REALX"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("REALY"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("REALZ"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("DISP"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("DISP_REAL"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("STRENGTH"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("FLAG"), SG_DATATYPE_Int);
		pCorrLines->Add_Field(SG_T("XDISP"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("YDISP"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("ZDISP"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("XDISP_UNIT"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("YDISP_UNIT"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("XTARG"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("YTARG"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("ZTARG"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("XERR"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("YERR"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("ASPECT"), SG_DATATYPE_Double);
		pCorrLines->Add_Field(SG_T("SLOPE"), SG_DATATYPE_Double);
	}


	// create containers
	std::vector<std::vector<double> > SearchChip;
	SearchChip.resize(Search_Chipsize);
	for(int i = 0; i < Search_Chipsize; i++)
		SearchChip[i].resize(Search_Chipsize);

	std::vector<std::vector<double> > RefChip;
	RefChip.resize(Ref_Chipsize);
	for(int i = 0; i < Ref_Chipsize; i++)
		RefChip[i].resize(Ref_Chipsize);

	// defaults for values;
	double mincorr = 2.0;
	int fitmeth = 1, okparam = 1;
	double maxdis = -1.0;

	std::vector<double>ioffrq,nomoff;
	nomoff.push_back(0.0);
	nomoff.push_back((Search_Chipsize-Ref_Chipsize)*0.5);
	nomoff.push_back((Search_Chipsize-Ref_Chipsize)*0.5);

	ioffrq.push_back(0.0);
	ioffrq.push_back(Search_Chipsize/2);
	ioffrq.push_back(Search_Chipsize/2);

	
	double disp=0.0;
	double strength=0.0;
	std::vector<double>best_fit, est_err;

	Grid_Spacing = (int)(SpacingMetrics / (pGrid1->Get_Cellsize()));


	// enshures that chips are always in grid
	int ID = 0;
	for(int gx1 = (Search_Chipsize/2-1); gx1 < pGrid1->Get_NX()-(Search_Chipsize/2) && Set_Progress(gx1, pGrid1->Get_NX()-(Search_Chipsize/2)); gx1 += Grid_Spacing)
	{
		for(int gy1 = (Search_Chipsize/2-1); gy1 < pGrid1->Get_NY()-(Search_Chipsize/2); gy1 += Grid_Spacing)
		{
			// get ref_chip
			Get_This_Chip(RefChip, pGrid1, gx1, gy1, Ref_Chipsize);

			// get search chip
			Get_This_Chip(SearchChip, pGrid2, gx1, gy1, Search_Chipsize);
			gcorr(SearchChip, RefChip, mincorr, fitmeth, maxdis, ioffrq, nomoff, okparam, strength, best_fit, est_err, disp);
			
			if (okparam ==1)
			{
				disp = sqrt(best_fit[1]*best_fit[1] + best_fit[2]*best_fit[2]) * Get_Cellsize();
				double DirNormX = (best_fit[2] * Get_Cellsize()) / disp;
				double DirNormY = (best_fit[1] * Get_Cellsize()) / disp;
				double Aspect;
				

				if((DirNormY > 0.0 && DirNormX > 0))
					Aspect = (atan(fabs(DirNormX)/fabs(DirNormY)))*M_RAD_TO_DEG;
				else if ((DirNormY <= 0.0 && DirNormX > 0))
					Aspect = 90+((atan(fabs(DirNormY)/fabs(DirNormX)))*M_RAD_TO_DEG);
				else if ((DirNormY <= 0.0 && DirNormX <= 0))
					Aspect = 180+((atan(fabs(DirNormX)/fabs(DirNormY)))*M_RAD_TO_DEG);
				else
					Aspect = 270+((atan(fabs(DirNormY)/fabs(DirNormX)))*M_RAD_TO_DEG);

				double xReal = pGrid1->Get_System().Get_xGrid_to_World(gx1);
				double yReal = pGrid1->Get_System().Get_yGrid_to_World(gy1);
				
				double xReal2	= xReal + best_fit[2] * Get_Cellsize();
				double yReal2	= yReal + best_fit[1] * Get_Cellsize();

				if (pDTM1 == NULL || pDTM2 == NULL)
				{
					pCorrPt = pCorrPts->Add_Shape();
					pCorrPt->Add_Point(xReal, yReal);
					pCorrPt->Set_Value(0, ID);
					pCorrPt->Set_Value(1, gx1);
					pCorrPt->Set_Value(2, gy1);
					pCorrPt->Set_Value(3, xReal);
					pCorrPt->Set_Value(4, yReal);
					pCorrPt->Set_Value(5, disp);
					pCorrPt->Set_Value(6, strength);
					pCorrPt->Set_Value(7, okparam);
					pCorrPt->Set_Value(8, best_fit[2] * Get_Cellsize());
					pCorrPt->Set_Value(9, best_fit[1] * Get_Cellsize());
					pCorrPt->Set_Value(10, DirNormX);
					pCorrPt->Set_Value(11, DirNormY);
					pCorrPt->Set_Value(12, xReal2);
					pCorrPt->Set_Value(13, yReal2);
					pCorrPt->Set_Value(14, est_err[2]);
					pCorrPt->Set_Value(15, est_err[1]);
					pCorrPt->Set_Value(16, Aspect);

					pCorrLine = pCorrLines->Add_Shape();
					pCorrLine->Add_Point(xReal, yReal);
					pCorrLine->Add_Point(xReal2, yReal2);
					pCorrLine->Set_Value(0, ID);
					pCorrLine->Set_Value(1, gx1);
					pCorrLine->Set_Value(2, gy1);
					pCorrLine->Set_Value(3, xReal);
					pCorrLine->Set_Value(4, yReal);
					pCorrLine->Set_Value(5, disp);
					pCorrLine->Set_Value(6, strength);
					pCorrLine->Set_Value(7, okparam);
					pCorrLine->Set_Value(8, best_fit[2] * Get_Cellsize());
					pCorrLine->Set_Value(9, best_fit[1] * Get_Cellsize());
					pCorrLine->Set_Value(10, DirNormX);
					pCorrLine->Set_Value(11, DirNormY);
					pCorrLine->Set_Value(12, xReal2);
					pCorrLine->Set_Value(13, yReal2);
					pCorrLine->Set_Value(14, est_err[2]);
					pCorrLine->Set_Value(15, est_err[1]);
					pCorrLine->Set_Value(16, Aspect);
				}
				else
				{
					double zReal2 = pDTM2->Get_Value(xReal2, yReal2);
					double zReal = pDTM1->asDouble(gx1, gy1);
					double Slope = (atan((zReal2-zReal)/fabs(disp)))*M_RAD_TO_DEG;
					double dispReal = sqrt(pow(zReal2-zReal,2) + disp*disp);
					pCorrPt = pCorrPts->Add_Shape();
					pCorrPt->Add_Point(xReal,yReal);
					pCorrPt->Set_Z(zReal,ID,0);
					pCorrPt->Set_Value(0, ID);
					pCorrPt->Set_Value(1, gx1);
					pCorrPt->Set_Value(2, gy1);
					pCorrPt->Set_Value(3, xReal);
					pCorrPt->Set_Value(4, yReal);
					pCorrPt->Set_Value(5, zReal);
					pCorrPt->Set_Value(6, disp);
					pCorrPt->Set_Value(7, dispReal);
					pCorrPt->Set_Value(8, strength);
					pCorrPt->Set_Value(9, okparam);
					pCorrPt->Set_Value(10, best_fit[2] * Get_Cellsize());
					pCorrPt->Set_Value(11, best_fit[1] * Get_Cellsize());
					pCorrPt->Set_Value(12, zReal2-zReal);
					pCorrPt->Set_Value(13, DirNormX);
					pCorrPt->Set_Value(14, DirNormY);
					pCorrPt->Set_Value(15, xReal2);
					pCorrPt->Set_Value(16, yReal2);
					pCorrPt->Set_Value(17, zReal2);
					pCorrPt->Set_Value(18, est_err[2]);
					pCorrPt->Set_Value(19, est_err[1]);
					pCorrPt->Set_Value(20, Aspect);
					pCorrPt->Set_Value(21, Slope);

					pCorrLine = pCorrLines->Add_Shape();
					pCorrLine->Add_Point(xReal, yReal);
					pCorrLine->Set_Z(zReal,0,0);
					pCorrLine->Add_Point(xReal2, yReal2);
					pCorrLine->Set_Z(zReal2,1,0);
					pCorrLine->Set_Value(0, ID);
					pCorrLine->Set_Value(1, gx1);
					pCorrLine->Set_Value(2, gy1);
					pCorrLine->Set_Value(3, xReal);
					pCorrLine->Set_Value(4, yReal);
					pCorrLine->Set_Value(5, zReal);
					pCorrLine->Set_Value(6, disp);
					pCorrLine->Set_Value(7, dispReal);
					pCorrLine->Set_Value(8, strength);
					pCorrLine->Set_Value(9, okparam);
					pCorrLine->Set_Value(10, best_fit[2] * Get_Cellsize());
					pCorrLine->Set_Value(11, best_fit[1] * Get_Cellsize());
					pCorrLine->Set_Value(12, zReal2-zReal);
					pCorrLine->Set_Value(13, DirNormX);
					pCorrLine->Set_Value(14, DirNormY);
					pCorrLine->Set_Value(15, xReal2);
					pCorrLine->Set_Value(16, yReal2);
					pCorrLine->Set_Value(17, zReal2);
					pCorrLine->Set_Value(18, est_err[2]);
					pCorrLine->Set_Value(19, est_err[1]);
					pCorrLine->Set_Value(20, Aspect);
					pCorrLine->Set_Value(21, Slope);
				}
			ID++;
			}
		}
	}

	return( true );
}
Exemple #12
0
//---------------------------------------------------------
bool CPC_Reclass_Extract::On_Execute(void)
{
	int				method;
	CSG_Parameters	sParms;

	m_pInput		= Parameters("INPUT")->asPointCloud();
	m_pResult		= Parameters("RESULT")->asPointCloud();
	method			= Parameters("METHOD")->asInt();
	m_AttrField		= Parameters("ATTRIB")->asInt();
	m_bExtract		= Parameters("MODE")->asInt() == 0 ? false : true;
	m_bCreateAttrib	= Parameters("CREATE_ATTRIB")->asBool();

	m_pResult->Create(m_pInput);

	if (m_bExtract)
		m_pResult->Set_Name(CSG_String::Format(SG_T("%s_subset_%s"), m_pInput->Get_Name(), m_pInput->Get_Field_Name(m_AttrField)));
	else
	{
		m_pResult->Set_Name(CSG_String::Format(SG_T("%s_reclass_%s"), m_pInput->Get_Name(), m_pInput->Get_Field_Name(m_AttrField)));
		if( m_bCreateAttrib )
			m_pResult->Add_Field(CSG_String::Format(SG_T("%s_reclass"), m_pInput->Get_Field_Name(m_AttrField)), m_pInput->Get_Field_Type(m_AttrField));
	}

	m_iOrig = 0;	// counter of unchanged points

	//-----------------------------------------------------
	switch( method )
	{
	case 0:	Reclass_Single();		break;
	case 1:	Reclass_Range();		break;
	case 2:	if( Reclass_Table(false) )
				break;
			else
				return( false );
	case 3:	if( Reclass_Table(true) )
				break;
			else
				return( false );
	default: break;
	}

	//-----------------------------------------------------
	DataObject_Update(m_pResult);

	DataObject_Get_Parameters(m_pResult, sParms);
	if (m_bExtract)
		Set_Display_Attributes(m_pResult, 2, sParms);
	else
	{
		if( m_bCreateAttrib )
			Set_Display_Attributes(m_pResult, m_pResult->Get_Field_Count()-1, sParms);
		else
			Set_Display_Attributes(m_pResult, m_AttrField, sParms);
	}

	if( m_bExtract)
		SG_UI_Msg_Add(CSG_String::Format(_TL("%d points out of %d extracted."), m_pInput->Get_Point_Count()-m_iOrig, m_pInput->Get_Point_Count()), true);
	else
		SG_UI_Msg_Add(CSG_String::Format(_TL("%d points out of %d reclassified."), m_pInput->Get_Point_Count()-m_iOrig, m_pInput->Get_Point_Count()), true);


	return( true );
}
//---------------------------------------------------------
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 );
}
Exemple #14
0
//---------------------------------------------------------
bool CSG_Table::_Load(const CSG_String &File_Name, TSG_Table_File_Type Format, const SG_Char *Separator)
{
	if( !::SG_File_Exists(File_Name) )
	{
		return( false );
	}

	bool		bResult;
	CSG_String	fName, sSeparator(Separator);

	_Destroy();

	SG_UI_Msg_Add(CSG_String::Format(SG_T("%s: %s..."), LNG("[MSG] Load table"), File_Name.c_str()), true);

	//-----------------------------------------------------
	if( Format == TABLE_FILETYPE_Undefined )
	{
		if( SG_File_Cmp_Extension(File_Name, SG_T("dbf")) )
		{
			Format	= TABLE_FILETYPE_DBase;
		}
		else if( SG_File_Cmp_Extension(File_Name, SG_T("csv")) )
		{
			Format	= TABLE_FILETYPE_Text;
			sSeparator	= ";";
		}
		else //if( SG_File_Cmp_Extension(File_Name, SG_T("txt")) )
		{
			Format	= TABLE_FILETYPE_Text;
		}
	}

	//-----------------------------------------------------
	switch( Format )
	{
	case TABLE_FILETYPE_Text:
		bResult	= _Load_Text (File_Name, true , sSeparator);
		break;

	case TABLE_FILETYPE_Text_NoHeadLine:
		bResult	= _Load_Text (File_Name, false, sSeparator);
		break;

	case TABLE_FILETYPE_DBase:
		bResult	= _Load_DBase(File_Name);
		break;

	default:
		bResult	= false;
	}

	//-----------------------------------------------------
	if( bResult )
	{
		Set_Modified(false);

		Set_Update_Flag();

		Set_File_Name(File_Name);

		Load_MetaData(File_Name);

		SG_UI_Msg_Add(LNG("[MSG] okay"), false, SG_UI_MSG_STYLE_SUCCESS);

		return( true );
	}

	SG_UI_Msg_Add(LNG("[MSG] failed"), false, SG_UI_MSG_STYLE_FAILURE);

	return( false );
}
Exemple #15
0
//---------------------------------------------------------
bool CSG_Table::Save(const CSG_String &File_Name, int Format, const SG_Char *Separator)
{
	bool		bResult;
	CSG_String	sSeparator(Separator);

	SG_UI_Msg_Add(CSG_String::Format(SG_T("%s: %s..."), LNG("[MSG] Save table"), File_Name.c_str()), true);

	//-----------------------------------------------------
	if( Format <= TABLE_FILETYPE_Undefined || Format > TABLE_FILETYPE_DBase )
	{
		if( SG_File_Cmp_Extension(File_Name, SG_T("dbf")) )
		{
			Format	= TABLE_FILETYPE_DBase;
		}
		else if( SG_File_Cmp_Extension(File_Name, SG_T("csv")) )
		{
			Format	= TABLE_FILETYPE_Text;
			sSeparator	= ';';
		}
		else //if( SG_File_Cmp_Extension(File_Name, SG_T("txt")) )
		{
			Format	= TABLE_FILETYPE_Text;
		}
	}

	switch( Format )
	{
	case TABLE_FILETYPE_Text:
		bResult	= _Save_Text (File_Name, true , Separator);
		break;

	case TABLE_FILETYPE_Text_NoHeadLine:
		bResult	= _Save_Text (File_Name, false, Separator);
		break;

	case TABLE_FILETYPE_DBase:
		bResult	= _Save_DBase(File_Name);
		break;
	}

	//-----------------------------------------------------
	if( bResult )
	{
		Set_Modified(false);

		Set_Update_Flag();

		Set_File_Type(Format);

		Set_File_Name(File_Name);

		Save_MetaData(File_Name);

		SG_UI_Msg_Add(LNG("[MSG] okay"), false, SG_UI_MSG_STYLE_SUCCESS);

		return( true );
	}

	SG_UI_Msg_Add(LNG("[MSG] failed"), false, SG_UI_MSG_STYLE_FAILURE);

	return( false );
}
//---------------------------------------------------------
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 );
}
Exemple #17
0
//---------------------------------------------------------
bool CLakeFloodInteractive::On_Execute_Position(CSG_Point ptWorld, TSG_Tool_Interactive_Mode Mode)
{
	//-----------------------------------------------------
	if(  Mode == TOOL_INTERACTIVE_LDOWN )
	{
		int			x, y, ix, iy, i;
		double		level;
	
		x	= Get_System()->Get_xWorld_to_Grid(ptWorld.Get_X());
		y	= Get_System()->Get_yWorld_to_Grid(ptWorld.Get_Y());
	
		if( pElev->is_InGrid(x, y, true) )
		{
			if( !m_bLevel )
				level = m_water + pElev->asDouble(x, y);
			else
				level = m_water;


			if( level <= pOlevel->asDouble(x, y) )
				return (true);


			newCell		= new CTraceOrder();
			newCell->x	= x;
			newCell->y	= y;
			firstCell	= newCell;

			pOdepth->Set_Value(x, y, level - pElev->asDouble(x, y));
			pOlevel->Set_Value(x, y, level);


			iterCell = firstCell;
			lastCell = firstCell;

			while( iterCell != NULL ) 
			{
				x	= iterCell->x;
				y	= iterCell->y;

				for( i=0; i<8; i++ )												
				{
					ix	= Get_xTo(i, x);			
					iy	= Get_yTo(i, y);			
								
					if(	is_InGrid(ix, iy) && !pElev->is_NoData(ix, iy) && pOlevel->asDouble(ix, iy) < level )
					{ 
						pOdepth->Set_Value(ix, iy, level - pElev->asDouble(ix, iy));
						pOlevel->Set_Value(ix, iy, level);
						newCell = new CTraceOrder();
						newCell->x = ix;
						newCell->y = iy;
						newCell->prev = lastCell;
						lastCell->next = newCell;
						lastCell = newCell;
					}
				}
			
				newCell = firstCell;

				if( newCell->next == NULL )
				{
					firstCell = lastCell = NULL;
					delete (newCell);
					newCell = NULL;
				}
				else
				{
					newCell->next->prev = NULL;
					firstCell = newCell->next;
					newCell->next = NULL;
					delete (newCell);
					newCell = NULL;
				}

				iterCell = firstCell;
			}

			SG_UI_Msg_Add(_TL("ready ..."), true);
			DataObject_Update(pOdepth, pOdepth->Get_ZMin(), pOdepth->Get_ZMax());
			DataObject_Update(pOlevel, pOlevel->Get_ZMin(), pOlevel->Get_ZMax());
			return( true );
		}
	}

	return( false );
}
//---------------------------------------------------------
bool CTable_Field_Statistics::On_Execute(void)
{
	CSG_Table	*pTab_in, *pTab_out;
	int			nFeatures, *Features;

	//-----------------------------------------------------
	pTab_in		= Parameters("TABLE")->asTable();
	pTab_out	= Parameters("STATISTICS")->asTable();
	
	Features	= (int *)Parameters("FIELDS")->asPointer();
	nFeatures	=        Parameters("FIELDS")->asInt    ();

	//-----------------------------------------------------
	if( !Features || nFeatures <= 0 )
	{
		Error_Set(_TL("No attribute fields selected!"));

		return( false );
	}

	//-----------------------------------------------------
	pTab_out->Destroy();
	pTab_out->Set_Name(CSG_String::Format(_TL("%s_stats"), pTab_in->Get_Name()));
	
	pTab_out->Add_Field(_TL("Field")	, SG_DATATYPE_String);
	pTab_out->Add_Field(_TL("n")		, SG_DATATYPE_Long);
	pTab_out->Add_Field(_TL("min")		, SG_DATATYPE_Double);
	pTab_out->Add_Field(_TL("max")		, SG_DATATYPE_Double);
	pTab_out->Add_Field(_TL("range")	, SG_DATATYPE_Double);
	pTab_out->Add_Field(_TL("sum")		, SG_DATATYPE_Double);
	pTab_out->Add_Field(_TL("mean")		, SG_DATATYPE_Double);
	pTab_out->Add_Field(_TL("variance")	, SG_DATATYPE_Double);
	pTab_out->Add_Field(_TL("stddev")	, SG_DATATYPE_Double);

	//-----------------------------------------------------
	for(int iFeature=0; iFeature<nFeatures; iFeature++)
	{
		if( SG_Data_Type_is_Numeric(pTab_in->Get_Field_Type(Features[iFeature])) )
		{
			CSG_Table_Record *pRecord = pTab_out->Add_Record();

			pRecord->Set_Value(0, pTab_in->Get_Field_Name(Features[iFeature]));
			pRecord->Set_Value(1, pTab_in->Get_N(Features[iFeature]));
			pRecord->Set_Value(2, pTab_in->Get_Minimum(Features[iFeature]));
			pRecord->Set_Value(3, pTab_in->Get_Maximum(Features[iFeature]));
			pRecord->Set_Value(4, pTab_in->Get_Range(Features[iFeature]));
			pRecord->Set_Value(5, pTab_in->Get_Sum(Features[iFeature]));
			pRecord->Set_Value(6, pTab_in->Get_Mean(Features[iFeature]));
			pRecord->Set_Value(7, pTab_in->Get_Variance(Features[iFeature]));
			pRecord->Set_Value(8, pTab_in->Get_StdDev(Features[iFeature]));
		}
		else
		{
			SG_UI_Msg_Add(CSG_String::Format(_TL("WARNING: skipping non-numeric field '%s'!"), pTab_in->Get_Field_Name(Features[iFeature])), true);
		}
	}

	//-----------------------------------------------------
	DataObject_Update(pTab_out);

	return( true );
}
Exemple #19
0
//---------------------------------------------------------
bool CSG_Shapes::Create(const CSG_String &File_Name)
{
	Destroy();

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

	//-----------------------------------------------------
	bool	bResult	= File_Name.BeforeFirst(':').Cmp("PGSQL") && SG_File_Exists(File_Name) && _Load_ESRI(File_Name);

	if( bResult )
	{
		Set_File_Name(File_Name, true);
	}

	//-----------------------------------------------------
	else if( File_Name.BeforeFirst(':').Cmp("PGSQL") == 0 )	// database source
	{
		CSG_String	s(File_Name);

		s	= s.AfterFirst(':');	CSG_String	Host  (s.BeforeFirst(':'));
		s	= s.AfterFirst(':');	CSG_String	Port  (s.BeforeFirst(':'));
		s	= s.AfterFirst(':');	CSG_String	DBName(s.BeforeFirst(':'));
		s	= s.AfterFirst(':');	CSG_String	Table (s.BeforeFirst(':'));

		CSG_Tool	*pTool	= SG_Get_Tool_Library_Manager().Get_Tool("db_pgsql", 0);	// CGet_Connections

		if(	pTool != NULL )
		{
			SG_UI_ProgressAndMsg_Lock(true);

			//---------------------------------------------
			CSG_Table	Connections;
			CSG_String	Connection	= DBName + " [" + Host + ":" + Port + "]";

			pTool->Settings_Push();

			if( pTool->On_Before_Execution() && SG_TOOL_PARAMETER_SET("CONNECTIONS", &Connections) && pTool->Execute() )	// CGet_Connections
			{
				for(int i=0; !bResult && i<Connections.Get_Count(); i++)
				{
					if( !Connection.Cmp(Connections[i].asString(0)) )
					{
						bResult	= true;
					}
				}
			}

			pTool->Settings_Pop();

			//---------------------------------------------
			if( bResult && (bResult = (pTool = SG_Get_Tool_Library_Manager().Get_Tool("db_pgsql", 20)) != NULL) == true )	// CPGIS_Shapes_Load
			{
				pTool->Settings_Push();

				bResult	= pTool->On_Before_Execution()
					&& SG_TOOL_PARAMETER_SET("CONNECTION", Connection)
					&& SG_TOOL_PARAMETER_SET("TABLES"    , Table)
					&& SG_TOOL_PARAMETER_SET("SHAPES"    , this)
					&& pTool->Execute();

				pTool->Settings_Pop();
			}

			SG_UI_ProgressAndMsg_Lock(false);
		}
	}

	//-----------------------------------------------------
	if( bResult )
	{
		Set_Modified(false);
		Set_Update_Flag();

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

		return( true );
	}

	for(int iShape=Get_Count()-1; iShape>=0; iShape--)	// be kind, keep at least those shapes that have been loaded successfully
	{
		if( !Get_Shape(iShape)->is_Valid() )
		{
			Del_Shape(iShape);
		}
	}

	if( Get_Count() <= 0 )
	{
		Destroy();
	}

	SG_UI_Process_Set_Ready();
	SG_UI_Msg_Add(_TL("failed"), false, SG_UI_MSG_STYLE_FAILURE);

	return( false );
}
Exemple #20
0
//---------------------------------------------------------
bool CKriging_Base::On_Execute(void)
{
	bool	bResult	= false;

	//-----------------------------------------------------
	m_Block		= Parameters("BLOCK"   )->asBool() ? Parameters("DBLOCK")->asDouble() / 2.0 : 0.0;
	m_bStdDev	= Parameters("TQUALITY")->asInt() == 0;
	m_bLog		= Parameters("LOG"     )->asBool();

	m_pPoints	= Parameters("POINTS"  )->asShapes();
	m_zField	= Parameters("ZFIELD"  )->asInt();

	if( m_pPoints->Get_Count() <= 1 )
	{
		SG_UI_Msg_Add(_TL("not enough points for interpolation"), true);

		return( false );
	}

	//-----------------------------------------------------
	CSG_Table	Variogram;

	if( SG_UI_Get_Window_Main() )
	{
		static CVariogram_Dialog	dlg;

		if( dlg.Execute(m_pPoints, m_zField, m_bLog, &Variogram, &m_Model) )
		{
			bResult	= true;
		}
	}
	else
	{
		int		nSkip		= Parameters("VAR_NSKIP"   )->asInt();
		int		nClasses	= Parameters("VAR_NCLASSES")->asInt();
		double	maxDistance	= Parameters("VAR_MAXDIST" )->asDouble();

		m_Model.Set_Formula(Parameters("VAR_MODEL")->asString());

		if( CSG_Variogram::Calculate(m_pPoints, m_zField, m_bLog, &Variogram, nClasses, maxDistance, nSkip) )
		{
			m_Model.Clr_Data();

			for(int i=0; i<Variogram.Get_Count(); i++)
			{
				CSG_Table_Record	*pRecord	= Variogram.Get_Record(i);

				m_Model.Add_Data(pRecord->asDouble(CSG_Variogram::FIELD_DISTANCE), pRecord->asDouble(CSG_Variogram::FIELD_VAR_EXP));
			}

			bResult	= m_Model.Get_Trend() || m_Model.Get_Parameter_Count() == 0;
		}
	}

	//-----------------------------------------------------
	if( bResult && (bResult = _Initialise_Grids() && On_Initialize()) )
	{
		Message_Add(CSG_String::Format(SG_T("%s: %s"), _TL("variogram model"), m_Model.Get_Formula(SG_TREND_STRING_Formula_Parameters).c_str()), false);

		for(int y=0; y<m_pGrid->Get_NY() && Set_Progress(y, m_pGrid->Get_NY()); y++)
		{
			#pragma omp parallel for
			for(int x=0; x<m_pGrid->Get_NX(); x++)
			{
				double	z, v;

				if( Get_Value(m_pGrid->Get_System().Get_Grid_to_World(x, y), z, v) )
				{
					Set_Value(x, y, z, v);
				}
				else
				{
					Set_NoData(x, y);
				}
			}
		}
	}

	//-----------------------------------------------------
	m_Model.Clr_Data();

	On_Finalize();

	return( bResult );
}
Exemple #21
0
bool CSG_Grid::Save(const CSG_String &File_Name, int Format, int xA, int yA, int xN, int yN)
{
	bool		bResult;
	CSG_String	sFile_Name	= SG_File_Make_Path(NULL, File_Name, SG_T("sgrd"));

	//-----------------------------------------------------
	if( xA	< 0 || xA >= Get_NX() - 1 )
	{
		xA	= 0;
	}

	if( yA	< 0 || yA >= Get_NY() - 1 )
	{
		yA	= 0;
	}

	if( xN	> Get_NX() - xA )
	{
		xN	= Get_NX() - xA;
	}

	if( yN	> Get_NY() - yA )
	{
		yN	= Get_NY() - yA;
	}

	//-----------------------------------------------------
	SG_UI_Msg_Add(CSG_String::Format(SG_T("%s: %s..."), LNG("[MSG] Save grid"), File_Name.c_str()), true);

	switch( Format )
	{
	default:
	case GRID_FILE_FORMAT_Binary:	// 1 - Binary
		bResult	= _Save_Native(sFile_Name, xA, yA, xN, yN, true);
		break;

	case GRID_FILE_FORMAT_ASCII:	// 2 - ASCII
		bResult	= _Save_Native(sFile_Name, xA, yA, xN, yN, false);
		break;
	}

	//-----------------------------------------------------
	if( bResult )
	{
		Set_Modified(false);

		Set_File_Name(sFile_Name);

		Save_MetaData(File_Name);

		SG_UI_Msg_Add(LNG("[MSG] okay"), false, SG_UI_MSG_STYLE_SUCCESS);
	}
	else
	{
		SG_UI_Msg_Add(LNG("[MSG] failed"), false, SG_UI_MSG_STYLE_FAILURE);

		SG_UI_Msg_Add_Error(LNG("[ERR] Grid file could not be saved."));
	}

	return( bResult );
}
Exemple #22
0
//---------------------------------------------------------
bool CPointCloud_Create_SPCVF::On_Execute(void)
{
	CSG_Strings					sFiles;
	CSG_String					sFileInputList, sFileName;
	int							iMethodPaths;

	CSG_MetaData				SPCVF;
	CSG_Projection				projSPCVF;
	double						dNoData;
	std::vector<TSG_Data_Type>	vFieldTypes;
	std::vector<CSG_String>		vFieldNames;
	double						dBBoxXMin = std::numeric_limits<int>::max();
	double						dBBoxYMin = std::numeric_limits<int>::max();
	double						dBBoxXMax = std::numeric_limits<int>::min();
	double						dBBoxYMax = std::numeric_limits<int>::min();
	int							iSkipped = 0, iEmpty = 0;
	int							iDatasetCount = 0;
	double						dPointCount = 0.0;
	double						dZMin = std::numeric_limits<double>::max();
	double						dZMax = -std::numeric_limits<double>::max();

	//-----------------------------------------------------
	sFileName		= Parameters("FILENAME")->asString();
	iMethodPaths	= Parameters("METHOD_PATHS")->asInt();
	sFileInputList	= Parameters("INPUT_FILE_LIST")->asString();

	//-----------------------------------------------------
	if( !Parameters("FILES")->asFilePath()->Get_FilePaths(sFiles) && sFileInputList.Length() <= 0 )
	{
		SG_UI_Msg_Add_Error(_TL("Please provide some input files!"));
		return( false );
	}

	//-----------------------------------------------------
	if( sFiles.Get_Count() <= 0 )
	{
		CSG_Table	*pTable = new CSG_Table();

		if( !pTable->Create(sFileInputList, TABLE_FILETYPE_Text_NoHeadLine) )
		{
			SG_UI_Msg_Add_Error(_TL("Input file list could not be opened!"));
			delete( pTable );
			return( false );
		}

		sFiles.Clear();

		for (int i=0; i<pTable->Get_Record_Count(); i++)
		{
			sFiles.Add(pTable->Get_Record(i)->asString(0));
		}

		delete( pTable );
	}


	//-----------------------------------------------------
	SPCVF.Set_Name(SG_T("SPCVFDataset"));
	SPCVF.Add_Property(SG_T("Version"), SG_T("1.1"));
	
	switch( iMethodPaths )
	{
	default:
	case 0:		SPCVF.Add_Property(SG_T("Paths"), SG_T("absolute"));	break;
	case 1:		SPCVF.Add_Property(SG_T("Paths"), SG_T("relative"));	break;
	}

	//-----------------------------------------------------
	CSG_MetaData	*pSPCVFHeader	= SPCVF.Add_Child(			SG_T("Header"));

	CSG_MetaData	*pSPCVFFiles	= pSPCVFHeader->Add_Child(	SG_T("Datasets"));
	CSG_MetaData	*pSPCVFPoints	= pSPCVFHeader->Add_Child(	SG_T("Points"));
	CSG_MetaData	*pSRS			= pSPCVFHeader->Add_Child(	SG_T("SRS"));
	CSG_MetaData	*pSPCVFBBox		= pSPCVFHeader->Add_Child(	SG_T("BBox"));
	CSG_MetaData	*pSPCVFZStats	= pSPCVFHeader->Add_Child(	SG_T("ZStats"));
	CSG_MetaData	*pSPCVFNoData	= pSPCVFHeader->Add_Child(	SG_T("NoData"));
	CSG_MetaData	*pSPCVFAttr		= pSPCVFHeader->Add_Child(	SG_T("Attributes"));

	CSG_MetaData	*pSPCVFDatasets	= NULL;
	

	//-----------------------------------------------------
	for(int i=0; i<sFiles.Get_Count() && Set_Progress(i, sFiles.Get_Count()); i++)
	{
		CSG_PointCloud	*pPC		= SG_Create_PointCloud(sFiles[i]);

		//-----------------------------------------------------
		if( i==0 )		// first dataset determines projection, NoData value and table structure
		{
			projSPCVF	= pPC->Get_Projection();
			dNoData		= pPC->Get_NoData_Value();

			pSPCVFNoData->Add_Property(SG_T("Value"), dNoData);

			pSPCVFAttr->Add_Property(SG_T("Count"), pPC->Get_Field_Count());

			for(int iField=0; iField<pPC->Get_Field_Count(); iField++)
			{
				vFieldTypes.push_back(pPC->Get_Field_Type(iField));
				vFieldNames.push_back(pPC->Get_Field_Name(iField));

				CSG_MetaData	*pSPCVFField = pSPCVFAttr->Add_Child(CSG_String::Format(SG_T("Field_%d"), iField + 1));

				pSPCVFField->Add_Property(SG_T("Name"), pPC->Get_Field_Name(iField));
				pSPCVFField->Add_Property(SG_T("Type"), gSG_Data_Type_Identifier[pPC->Get_Field_Type(iField)]);

			}

			if( projSPCVF.is_Okay() )
			{
				pSRS->Add_Property(SG_T("Projection"), projSPCVF.Get_Name());
				pSRS->Add_Property(SG_T("WKT"), projSPCVF.Get_WKT());
			}
			else
			{
				pSRS->Add_Property(SG_T("Projection"), SG_T("Undefined Coordinate System"));
			}

			pSPCVFDatasets	= SPCVF.Add_Child(SG_T("Datasets"));
		}
		else		// validate projection, NoData value and table structure
		{
			bool	bSkip = false;

			if( pPC->Get_Field_Count() != (int)vFieldTypes.size() )
			{
				bSkip = true;
			}

			if( !bSkip && projSPCVF.is_Okay() )
			{
				if ( !pPC->Get_Projection().is_Okay() || SG_STR_CMP(pPC->Get_Projection().Get_WKT(), projSPCVF.Get_WKT()) )
				{
					bSkip = true;
				}
			}

			if( !bSkip )
			{
				for(int iField=0; iField<pPC->Get_Field_Count(); iField++)
				{
					if( pPC->Get_Field_Type(iField) != vFieldTypes.at(iField) )
					{
						bSkip = true;
						break;
					}

					if( SG_STR_CMP(pPC->Get_Field_Name(iField), vFieldNames.at(iField)) )
					{
						bSkip = true;
						break;
					}
				}
			}

			if( bSkip )
			{
				SG_UI_Msg_Add(CSG_String::Format(_TL("Skipping dataset %s because of incompatibility with the first input dataset!"), sFiles[i].c_str()), true);
				delete( pPC );
				iSkipped++;
				continue;
			}
		}

		//-----------------------------------------------------
		if( pPC->Get_Point_Count() <= 0 )
		{
			delete( pPC );
			iEmpty++;
			continue;
		}

		//-----------------------------------------------------
		CSG_MetaData	*pDataset	= pSPCVFDatasets->Add_Child(SG_T("PointCloud"));

		CSG_String		sFilePath;

		switch( iMethodPaths )
		{
		default:
		case 0:		sFilePath = SG_File_Get_Path_Absolute(sFiles.Get_String(i));									break;
		case 1:		sFilePath = SG_File_Get_Path_Relative(SG_File_Get_Path(sFileName), sFiles.Get_String(i));		break;
		}

		sFilePath.Replace(SG_T("\\"), SG_T("/"));

		pDataset->Add_Property(SG_T("File"), sFilePath);

		pDataset->Add_Property(SG_T("Points"), pPC->Get_Point_Count());

		pDataset->Add_Property(SG_T("ZMin"), pPC->Get_ZMin());
		pDataset->Add_Property(SG_T("ZMax"), pPC->Get_ZMax());

		//-----------------------------------------------------
		CSG_MetaData	*pBBox		= pDataset->Add_Child(SG_T("BBox"));

		pBBox->Add_Property(SG_T("XMin"), pPC->Get_Extent().Get_XMin());
		pBBox->Add_Property(SG_T("YMin"), pPC->Get_Extent().Get_YMin());
		pBBox->Add_Property(SG_T("XMax"), pPC->Get_Extent().Get_XMax());
		pBBox->Add_Property(SG_T("YMax"), pPC->Get_Extent().Get_YMax());

		if( dBBoxXMin > pPC->Get_Extent().Get_XMin() )
			dBBoxXMin = pPC->Get_Extent().Get_XMin();
		if( dBBoxYMin > pPC->Get_Extent().Get_YMin() )
			dBBoxYMin = pPC->Get_Extent().Get_YMin();
		if( dBBoxXMax < pPC->Get_Extent().Get_XMax() )
			dBBoxXMax = pPC->Get_Extent().Get_XMax();
		if( dBBoxYMax < pPC->Get_Extent().Get_YMax() )
			dBBoxYMax = pPC->Get_Extent().Get_YMax();
		
		iDatasetCount	+= 1;
		dPointCount		+= pPC->Get_Point_Count();

		if( dZMin > pPC->Get_ZMin() )
			dZMin = pPC->Get_ZMin();
		if( dZMax < pPC->Get_ZMax() )
			dZMax = pPC->Get_ZMax();


		delete( pPC );
	}

	//-----------------------------------------------------
	pSPCVFBBox->Add_Property(SG_T("XMin"), dBBoxXMin);
	pSPCVFBBox->Add_Property(SG_T("YMin"), dBBoxYMin);
	pSPCVFBBox->Add_Property(SG_T("XMax"), dBBoxXMax);
	pSPCVFBBox->Add_Property(SG_T("YMax"), dBBoxYMax);

	pSPCVFFiles->Add_Property(SG_T("Count"), iDatasetCount);
	pSPCVFPoints->Add_Property(SG_T("Count"), CSG_String::Format(SG_T("%.0f"), dPointCount));
	pSPCVFZStats->Add_Property(SG_T("ZMin"), dZMin);
	pSPCVFZStats->Add_Property(SG_T("ZMax"), dZMax);

	//-----------------------------------------------------
	if( !SPCVF.Save(sFileName) )
	{
		SG_UI_Msg_Add_Error(CSG_String::Format(_TL("Unable to save %s file!"), sFileName.c_str()));

		return( false );
	}

	//-----------------------------------------------------
	if( iSkipped > 0 )
	{
		SG_UI_Msg_Add(CSG_String::Format(_TL("WARNING: %d dataset(s) skipped because of incompatibilities!"), iSkipped), true);
	}

	if( iEmpty > 0 )
	{
		SG_UI_Msg_Add(CSG_String::Format(_TL("WARNING: %d dataset(s) skipped because they are empty!"), iEmpty), true);
	}

	SG_UI_Msg_Add(CSG_String::Format(_TL("SPCVF successfully created from %d dataset(s)."), iDatasetCount), true);

	//-----------------------------------------------------
	return( true );
}