<commit_before>#include"Lane_Detection.hpp"
bool debug=false;
//bool debug = true;

/*Utility Functions*/

void displayvector(vector<float> &v)
{
	for(auto i: v)
		cout<<i<<' ';

}

/*Convert Image to Gray on GPU*/
void convertrgb2Gray(const gpu::GpuMat& src, gpu::GpuMat& dst)
{
	gpu::cvtColor(src, dst,CV_RGB2GRAY);

}

/*Filter Image*/
void filterImage(const gpu::GpuMat& src, gpu::GpuMat& dst, float width_kernel_x, float width_kernel_y,float sigmax, float sigmay)
{
	src.convertTo(dst, CV_32F, 1.0/255.0,0);

	Mat g_kernel_y = Mat::zeros(2*width_kernel_y + 1,1,CV_32F);
	Mat g_kernel_x = Mat::zeros(1,2*width_kernel_x + 1,CV_32F);

	float variance_y, variance_x;
	variance_y = sigmay*sigmay;
	variance_x = sigmax*sigmax;

	float k1, k2,function;

	/*Calculate g_kernel_y*/
	for(int i = -width_kernel_y;i<=width_kernel_y;i++)
	{
		k1 = exp((-0.5/variance_y)*i*i);
		g_kernel_y.at<float>(i+width_kernel_y,0) = k1;
	}

	/*Calculate g_kernel_x*/
	for(int i=-width_kernel_x;i<=width_kernel_x;i++)
	{
		k2 = exp(-i*i*0.5/variance_x);
		function = (1/variance_x)*k2 - (i*i)/(variance_x*variance_x)*k2;
		g_kernel_x.at<float>(0,i+width_kernel_x) = function;
	}

	if(debug)
	{
		cout << "g_kernel_y = " << endl << " " << g_kernel_y << endl << endl;
		cout << "g_kernel_x = " << endl << " " << g_kernel_x << endl << endl;
	}

	/*Initialize Kernel*/
	Mat kernel(2*width_kernel_x+1, 2*width_kernel_y +1,CV_32F);
	kernel = g_kernel_y*g_kernel_x;

	if(debug)
	{
		cout<< "Kernel = " << endl<< " "<<kernel<<endl<<endl;
	}

	Scalar mean_kernel;
	mean_kernel = mean(kernel)(0);
	subtract(kernel,mean_kernel,kernel);

	/*Filter Image on gpu*/
	gpu::filter2D(dst,dst,-1,kernel);

}

/*Get quantile value for Thresholding*/
void getQuantile(const gpu::GpuMat& src,gpu::GpuMat& dst, float  qtile)
{
	int number_rows, number_columns;
	number_rows = src.rows;
	number_columns = src.cols;

	Mat temp_image;
	src.download(temp_image);

	Mat array = temp_image.reshape(1,number_rows*number_columns);
	float quantile = getPoints(array, qtile);

	if(debug)
	{
		cout<<quantile<<endl;
	}
	thresholdlower(src,dst,quantile);

}

float getPoints(Mat& input_image, float quantile)
{
	Size size = input_image.size();
	int num_elements = size.width*size.height;
	double min, max;
	minMaxLoc(input_image, &min,&max);

	if(num_elements == 0)
	{
		return float(0);
	}
	else if(num_elements ==1)
	{
		return input_image.at<float>(0,0);
	}
	else if(quantile <=0)
	{
		return float(min);
	}
	else if (quantile >=1)
	{
		return float(max);
	}

	double pos =(num_elements-1)*quantile;
	unsigned int index = pos;
	double delta = pos - index;

	vector<float> w(num_elements);
	w.assign((float*)input_image.datastart, (float*)input_image.dataend);

	if(debug)
	{
		for(auto i = w.begin(); i !=w.end();++i)
		{
			cout<<*i<<' ';

		}
	}

	nth_element(w.begin(),w.begin() + index,w.end());
	float i1 = *(w.begin() + index);
	float i2 = *min_element(w.begin() + index +1,w.end());
	return (float)(i1*(1.0 - delta) + i2*delta);

}

void thresholdlower(const gpu::GpuMat& src, gpu::GpuMat& dst,double threshold)
{
	double retval;
	double maxval = 0.0;
	retval = gpu::threshold(src,dst,threshold,maxval,THRESH_TOZERO);
	if(debug)
	{
		cout<<retval<<endl;
	}
}

void getclearImage(gpu::GpuMat& src, gpu::GpuMat& dst)
{
	int number_rows, number_columns;

	number_rows = src.rows;
	number_columns = src.cols;

	/*
	Mat image_to_process;
	src.download(image_to_process);

	if(debug)
	{
		cout<<number_rows<<endl;
		cout<<number_columns<<endl;
	}

	int column_index = (int)(number_columns*0.75);
	int row_index = (int)(number_rows*0.75);

	//Clear Outer Columns to Zero
	for(int i = 0;i<number_rows;i++)
	{
		for(int j = column_index;j<number_columns;j++)
		{
			image_to_process.at<float>(i,j) = float(0);
			image_to_process.at<float>(i,(j-column_index)) = float(0);

		}
	}

	for(int i = 0;i<number_columns;i++)
	{
		for(int j =0;j<(number_rows-row_index);j++)
		{
			image_to_process.at<float>(j,i) = float(0);

		}

	}

	dst.upload(image_to_process);
	*/

	//More Optimized Code Without Copying Image to host

	int column_index = (int)(number_columns*0.75);
	int row_index = (int)(number_rows*0.75);

	gpu::GpuMat temp_roi;

	temp_roi = gpu::GpuMat(src, Rect(0,0,(number_columns-column_index),number_rows-1));
	temp_roi.setTo(Scalar(0));

	temp_roi = gpu::GpuMat(src, Rect(column_index,0,(number_columns-column_index-1),number_rows-1));
	temp_roi.setTo(Scalar(0));

	temp_roi = gpu::GpuMat(src, Rect(0,0,number_columns-1,(number_rows- row_index)));
	temp_roi.setTo(Scalar(0));

	dst = src.clone();

	if(debug)
	{
		Mat dst_host;
		src.download(dst_host);
		imshow("Result", dst_host);
		waitKey(0);
	}

}

void getbinaryImage(const gpu::GpuMat& src, gpu::GpuMat& dst)
{
	double min, max ;
	gpu::minMax(src,&min,&max);

	double threshold = (max - min)/2;
	gpu::threshold(src, dst, threshold,1, THRESH_BINARY);

}

void selectROI(const gpu::GpuMat& src, gpu::GpuMat& dst)
{
	int number_rows, number_columns;

	number_rows = src.rows; //400 ()
	number_columns = src.cols;//200

	int roi_height = int(0.45*number_rows);
	dst = gpu::GpuMat(src, Rect(0,roi_height,number_columns-1, number_rows-roi_height));

	if(debug)
	{
		Mat dst_host;
		dst.download(dst_host);
		imshow("Result", dst_host);
		waitKey(0);
	}

}

void getHoughLines(const gpu::GpuMat& src, const gpu::GpuMat& gray_image)
{
	gpu::GpuMat lines, binary_image_8b;
	src.convertTo(binary_image_8b, CV_8U,255.0,0);

	vector<Vec2f>lines_host;

	//Vec2f lines_host;

	/*double e1 = getTickCount();
	gpu::HoughLines(src,lines,3,CV_PI/180,50,1,5);
	double e2 = getTickCount();
	double time = (e2 -e1)/getTickFrequency();
	cout<<time<<endl;
   */

	//gpu::HoughLines(binary_image_8b, lines, 1, CV_PI/180,65,1,10);
	Mat binary_image;
	binary_image_8b.download(binary_image);

	HoughLines(binary_image, lines_host,1, CV_PI/180, 65 );

	Mat dst_host;
	gray_image.download(dst_host);

	//gpu::HoughLinesDownload(lines, lines_host);

	/*sort(lines_host.begin(),lines_host.end(),[](const Vec2f& a, const Vec2f& b){

			return a[0] < b[0];
			});

	*/
	vector<float> dist;
	vector<float> angles;

	for(int i = 0;i<lines_host.size();i++)
	{
		dist.push_back(lines_host[i][0]);
		angles.push_back(lines_host[i][1]);

	}

	displayvector(dist);
	displayvector(angles);

	if(1)
	{
		for( int i = 0;i<lines_host.size();i++)
		{
			float rho = lines_host[i][0];
			float theta = lines_host[i][1];
			Point pt1, pt2;

			cout<<rho<<endl;
			cout<<theta<<endl;

			double a = cos(theta);
			double b = sin(theta);

			double x0 = a*rho;
			double y0 = b*rho;

			pt1.x  = (int)(x0 + 400*(-b));
			pt1.y = (int)(y0 + 400*(a));
			pt2.x = (int)(x0 - 400*(-b));
			pt2.y = (int)(x0 - 400*(a));

			line(dst_host, pt1, pt2, (0,0,255),1);

		}

		imshow("Result", dst_host);
		waitKey(0);

	}

	/*
	if(debug)
	{
		Mat dst_host;
		lines.download(dst_host);
		imshow("Result", dst_host);
		waitKey(0);
	}

	*/

}

int main(int argc, char* argv[])
{
	/*Load Image*/

	Mat src_host;

	gpu::setDevice(0);

	src_host = imread("/home/nvidia/Lane_Detection/Test_Images/IPM_test_image_4.png");
	gpu::GpuMat input_image, gray_image;

	/*Upload Image on Gpu*/
	input_image.upload(src_host);

	/*Convert Image to Gray*/
	convertrgb2Gray(input_image, gray_image);

	if(debug)
	{
		Mat dst_host;
		gray_image.download(dst_host);
		imshow("Result",dst_host);
		waitKey(0);
	}

	/*Filter Image using 2-D Gaussian Kernel*/

	gpu::GpuMat filtered_image;
	filterImage(gray_image, filtered_image,2,2,2,10);

	if(debug)
	{
		Mat dst_host;
		filtered_image.download(dst_host);
		imshow("Result",dst_host);
		waitKey(0);
	}

	/*Threshold Image*/
	gpu::GpuMat thresholded_image ;
	getQuantile(filtered_image, thresholded_image,0.985);

	if(debug)
	{
		Mat dst_host;
		thresholded_image.download(dst_host);
		imshow("Result",dst_host);
		waitKey(0);

	}

	/*Clean Negetive Parts Of an Image*/
	gpu::GpuMat clear_thresholded_image ;
	thresholdlower(thresholded_image, clear_thresholded_image, 0);

	if(debug)
	{
		Mat dst_host;
		clear_thresholded_image.download(dst_host);
		imshow("Result", dst_host);
		waitKey(0);

	}

	/*Clear Image (Select ROI)*/
	gpu::GpuMat cleared_image;
	getclearImage(clear_thresholded_image, cleared_image);

	if(debug)
	{
		Mat dst_host;
		cleared_image.download(dst_host);
		imshow("Result", dst_host);
		waitKey(0);
	}

	gpu::GpuMat binary_image;
	getbinaryImage(cleared_image, binary_image);

	if(debug)
	{
		Mat dst_host;
		binary_image.download(dst_host);
		imshow("Result", dst_host);
		waitKey(0);
	}

	gpu::GpuMat roi_image;
	selectROI(binary_image, roi_image);

	/*Try with Hough Line Opencv*/

	getHoughLines(roi_image, gray_image);

}

<commit_msg>Updated Code<commit_after>#include"Lane_Detection.hpp"
bool debug=false;
//bool debug = true;

/*Utility Functions*/

void displayvector(vector<float> &v)
{
	for(auto i: v)
		cout<<i<<' ';

}

/*Convert Image to Gray on GPU*/
void convertrgb2Gray(const gpu::GpuMat& src, gpu::GpuMat& dst)
{
	gpu::cvtColor(src, dst,CV_RGB2GRAY);

}

/*Filter Image*/
void filterImage(const gpu::GpuMat& src, gpu::GpuMat& dst, float width_kernel_x, float width_kernel_y,float sigmax, float sigmay)
{
	src.convertTo(dst, CV_32F, 1.0/255.0,0);

	Mat g_kernel_y = Mat::zeros(2*width_kernel_y + 1,1,CV_32F);
	Mat g_kernel_x = Mat::zeros(1,2*width_kernel_x + 1,CV_32F);

	float variance_y, variance_x;
	variance_y = sigmay*sigmay;
	variance_x = sigmax*sigmax;

	float k1, k2,function;

	/*Calculate g_kernel_y*/
	for(int i = -width_kernel_y;i<=width_kernel_y;i++)
	{
		k1 = exp((-0.5/variance_y)*i*i);
		g_kernel_y.at<float>(i+width_kernel_y,0) = k1;
	}

	/*Calculate g_kernel_x*/
	for(int i=-width_kernel_x;i<=width_kernel_x;i++)
	{
		k2 = exp(-i*i*0.5/variance_x);
		function = (1/variance_x)*k2 - (i*i)/(variance_x*variance_x)*k2;
		g_kernel_x.at<float>(0,i+width_kernel_x) = function;
	}

	if(debug)
	{
		cout << "g_kernel_y = " << endl << " " << g_kernel_y << endl << endl;
		cout << "g_kernel_x = " << endl << " " << g_kernel_x << endl << endl;
	}

	/*Initialize Kernel*/
	Mat kernel(2*width_kernel_x+1, 2*width_kernel_y +1,CV_32F);
	kernel = g_kernel_y*g_kernel_x;

	if(debug)
	{
		cout<< "Kernel = " << endl<< " "<<kernel<<endl<<endl;
	}

	Scalar mean_kernel;
	mean_kernel = mean(kernel)(0);
	subtract(kernel,mean_kernel,kernel);

	/*Filter Image on gpu*/
	gpu::filter2D(dst,dst,-1,kernel);

}

/*Get quantile value for Thresholding*/
void getQuantile(const gpu::GpuMat& src,gpu::GpuMat& dst, float  qtile)
{
	int number_rows, number_columns;
	number_rows = src.rows;
	number_columns = src.cols;

	Mat temp_image;
	src.download(temp_image);

	Mat array = temp_image.reshape(1,number_rows*number_columns);
	float quantile = getPoints(array, qtile);

	if(debug)
	{
		cout<<quantile<<endl;
	}
	thresholdlower(src,dst,quantile);

}

float getPoints(Mat& input_image, float quantile)
{
	Size size = input_image.size();
	int num_elements = size.width*size.height;
	double min, max;
	minMaxLoc(input_image, &min,&max);

	if(num_elements == 0)
	{
		return float(0);
	}
	else if(num_elements ==1)
	{
		return input_image.at<float>(0,0);
	}
	else if(quantile <=0)
	{
		return float(min);
	}
	else if (quantile >=1)
	{
		return float(max);
	}

	double pos =(num_elements-1)*quantile;
	unsigned int index = pos;
	double delta = pos - index;

	vector<float> w(num_elements);
	w.assign((float*)input_image.datastart, (float*)input_image.dataend);

	if(debug)
	{
		for(auto i = w.begin(); i !=w.end();++i)
		{
			cout<<*i<<' ';

		}
	}

	nth_element(w.begin(),w.begin() + index,w.end());
	float i1 = *(w.begin() + index);
	float i2 = *min_element(w.begin() + index +1,w.end());
	return (float)(i1*(1.0 - delta) + i2*delta);

}

void thresholdlower(const gpu::GpuMat& src, gpu::GpuMat& dst,double threshold)
{
	double retval;
	double maxval = 0.0;
	retval = gpu::threshold(src,dst,threshold,maxval,THRESH_TOZERO);
	if(debug)
	{
		cout<<retval<<endl;
	}
}

void getclearImage(gpu::GpuMat& src, gpu::GpuMat& dst)
{
	int number_rows, number_columns;

	number_rows = src.rows;
	number_columns = src.cols;

	/*
	Mat image_to_process;
	src.download(image_to_process);

	if(debug)
	{
		cout<<number_rows<<endl;
		cout<<number_columns<<endl;
	}

	int column_index = (int)(number_columns*0.75);
	int row_index = (int)(number_rows*0.75);

	//Clear Outer Columns to Zero
	for(int i = 0;i<number_rows;i++)
	{
		for(int j = column_index;j<number_columns;j++)
		{
			image_to_process.at<float>(i,j) = float(0);
			image_to_process.at<float>(i,(j-column_index)) = float(0);

		}
	}

	for(int i = 0;i<number_columns;i++)
	{
		for(int j =0;j<(number_rows-row_index);j++)
		{
			image_to_process.at<float>(j,i) = float(0);

		}	pt1.x  = (int)(x0 + 400*(-b));
			pt1.y = (int)(y0 + 400*(a));
			pt2.x = (int)(x0 - 400*(-b));
			pt2.y = (int)(x0 - 400*(a));

	}

	dst.upload(image_to_process);
	*/

	//More Optimized Code Without Copying Image to host

	int column_index = (int)(number_columns*0.75);
	int row_index = (int)(number_rows*0.75);

	gpu::GpuMat temp_roi;

	temp_roi = gpu::GpuMat(src, Rect(0,0,(number_columns-column_index),number_rows-1));
	temp_roi.setTo(Scalar(0));

	temp_roi = gpu::GpuMat(src, Rect(column_index,0,(number_columns-column_index-1),number_rows-1));
	temp_roi.setTo(Scalar(0));

	temp_roi = gpu::GpuMat(src, Rect(0,0,number_columns-1,(number_rows- row_index)));
	temp_roi.setTo(Scalar(0));

	dst = src.clone();

	if(debug)
	{
		Mat dst_host;
		src.download(dst_host);
		imshow("Result", dst_host);
		waitKey(0);
	}

}

void getbinaryImage(const gpu::GpuMat& src, gpu::GpuMat& dst)
{
	double min, max ;
	gpu::minMax(src,&min,&max);

	double threshold = (max - min)/2;
	gpu::threshold(src, dst, threshold,1, THRESH_BINARY);

}

void selectROI(const gpu::GpuMat& src, gpu::GpuMat& dst)
{
	int number_rows, number_columns;

	number_rows = src.rows; //400 ()
	number_columns = src.cols;//200

	int roi_height = int(0.45*number_rows);
	cout<<roi_height<<endl;
	dst = gpu::GpuMat(src, Rect(0,176, 192, number_rows-176));

	if(debug)
	{
		Mat dst_host;
		dst.download(dst_host);
		imwrite("/home/nvidia/Binary_test_image_for_cuda_ht.png", dst_host);
		imshow("Result", dst_host);
		waitKey(0);
	}

}

void getHoughLines(const gpu::GpuMat& src, const gpu::GpuMat& gray_image)
{
	gpu::GpuMat binary_image_8b;
	src.convertTo(binary_image_8b, CV_8U,255.0,0);

	//vector<Vec2f>lines_host;

	//Vec2f lines_host;

	/*double e1 = getTickCount();
	gpu::HoughLines(src,lines,3,CV_PI/180,50,1,5);
	double e2 = getTickCount();
	double time = (e2 -e1)/getTickFrequency();
	cout<<time<<endl;
   */

	//gpu::HoughLines(binary_image_8b, lines, 1, CV_PI/180,65,1,10);
	/*Mat binary_image;
	binary_image_8b.download(binary_image);

	HoughLines(binary_image, lines_host,1, CV_PI/180, 65 );

	Mat dst_host;
	gray_image.download(dst_host);

	*/
	//gpu::HoughLinesDownload(lines, lines_host);

	/*sort(lines_host.begin(),lines_host.end(),[](const Vec2f& a, const Vec2f& b){

			return a[0] < b[0];
			});

	*/
	/*vector<float> dist;
	vector<float> angles;

	for(int i = 0;i<lines_host.size();i++)
	{
		dist.push_back(lines_host[i][0]);
		angles.push_back(lines_host[i][1]);

	}
	*/

	/*displayvector(dist);
	displayvector(angles);

 	if(1)
	{
		for( int i = 0;i<lines_host.size();i++)
		{
			float rho = lines_host[i][0];
			float theta = lines_host[i][1];
			Point pt1, pt2;

			cout<<rho<<endl;
			cout<<theta<<endl;

			double a = cos(theta);
			double b = sin(theta);

			double x0 = a*rho;
			double y0 = b*rho;

			pt1.x  = (int)(x0 + 400*(-b));
			pt1.y = (int)(y0 + 400*(a));
			pt2.x = (int)(x0 - 400*(-b));
			pt2.y = (int)(x0 - 400*(a));

			line(dst_host, pt1, pt2, (0,0,255),1);

		}

		imshow("Result", dst_host);
		waitKey(0);

	}
	*/

	/*
	if(debug)
	{
		Mat dst_host;
		lines.download(dst_host);
		imshow("Result", dst_host);
		waitKey(0);
	}

	*/

	Mat binary_image;
	binary_image_8b.download(binary_image);

	/*if(debug)
	{
		imshow("Result", binary_image);
		waitKey(0);
	}

	uchar *data = binary_image.data;
	cout<<sizeof(data)<<endl;

	*/
	//cout<<(int)*(data)<<endl;
	imshow("Test",binary_image);
	waitKey(0);
	imwrite("/home/nvidia/Binary_test_image_for_cuda_ht.png",binary_image);

}

int main(int argc, char* argv[])
{
	/*Load Image*/

	Mat src_host;

	src_host = imread("/home/nvidia/Lane_Detection/Test_Images/IPM_test_image_1.png");
	gpu::GpuMat input_image, gray_image;

	/*Upload Image on Gpu*/
	input_image.upload(src_host);

	double e1 = getTickCount();

	/*Convert Image to Gray*/
	convertrgb2Gray(input_image, gray_image);
	Mat gray_image_host ;
	gray_image.download(gray_image_host);
	imwrite("/home/nvidia/gray_image.png",gray_image_host);

	if(debug)
	{
		Mat dst_host;
		gray_image.download(dst_host);
		imshow("Result",dst_host);
		waitKey(0);
	}

	/*Filter Image using 2-D Gaussian Kernel*/

	gpu::GpuMat filtered_image;
	filterImage(gray_image, filtered_image,2,2,2,10);

	if(debug)
	{
		Mat dst_host;
		filtered_image.download(dst_host);
		imshow("Result",dst_host);
		waitKey(0);
	}

	/*Threshold Image*/
	gpu::GpuMat thresholded_image ;
	getQuantile(filtered_image, thresholded_image,0.985);

	if(debug)
	{
		Mat dst_host;
		thresholded_image.download(dst_host);
		imshow("Result",dst_host);
		waitKey(0);

	}

	/*Clean Negetive Parts Of an Image*/
	gpu::GpuMat clear_thresholded_image ;
	thresholdlower(thresholded_image, clear_thresholded_image, 0);

	if(debug)
	{
		Mat dst_host;
		clear_thresholded_image.download(dst_host);
		imshow("Result", dst_host);
		waitKey(0);

	}

	/*Clear Image (Select ROI)*/
	gpu::GpuMat cleared_image;
	getclearImage(clear_thresholded_image, cleared_image);

	if(debug)
	{
		Mat dst_host;
		cleared_image.download(dst_host);
		imshow("Result", dst_host);
		waitKey(0);
	}

	gpu::GpuMat binary_image;
	getbinaryImage(cleared_image, binary_image);

	if(debug)
	{
		Mat dst_host;
		binary_image.download(dst_host);
		imshow("Result", dst_host);
		waitKey(0);
	}

	gpu::GpuMat roi_image;
	selectROI(binary_image, roi_image);

	double e2 = getTickCount();
	double time = (e2 -e1)/getTickFrequency();
	cout<<time<<endl;

	/*Try with Hough Line Opencv*/

	getHoughLines(roi_image, gray_image);

}

<|endoftext|>


<commit_before>#include <tests/Base.hh>

#include <aleph/containers/PointCloud.hh>

#include <aleph/geometry/distances/Euclidean.hh>

#include <aleph/geometry/SphereSampling.hh>
#include <aleph/geometry/WitnessComplex.hh>

#include <aleph/persistentHomology/Calculation.hh>

#include <aleph/topology/filtrations/Data.hh>

#include <algorithm>
#include <iterator>
#include <set>
#include <vector>

template <class SimplicialComplex> std::vector<std::size_t> bettiNumbers( SimplicialComplex K )
{
  using Simplex  = typename SimplicialComplex::ValueType;
  using DataType = typename Simplex::DataType;

  K.sort( aleph::topology::filtrations::Data<typename SimplicialComplex::ValueType>() );
  auto diagrams = aleph::calculatePersistenceDiagrams( K );

  std::vector<std::size_t> betti( diagrams.size() );

  std::transform( diagrams.begin(), diagrams.end(), betti.begin(),
                  [] ( const aleph::PersistenceDiagram<DataType>& diagram )
                  {
                    return diagram.betti();
                  } );

  return betti;
}

template <class T> void test()
{
  using Distance   = aleph::distances::Euclidean<T>;
  using PointCloud = aleph::containers::PointCloud<T>;

  PointCloud pc( 8, 2 );

  pc.set(0, {-1.0, 0.0} );
  pc.set(1, { 0.0,-1.0} );
  pc.set(2, { 1.0, 0.0} );
  pc.set(3, { 2.0, 1.0} );
  pc.set(4, { 1.0, 1.0} );
  pc.set(5, { 0.0, 2.0} );
  pc.set(6, {-1.0, 1.0} );
  pc.set(7, {-2.0, 1.0} );

  std::vector<std::size_t> indices = {0,2,4,6};

  auto K
    = aleph::geometry::buildWitnessComplex<Distance>(
        pc, indices.begin(), indices.end() );

  using Simplex    = typename decltype(K)::ValueType;
  using VertexType = typename Simplex::VertexType;

  {
    std::set<VertexType> vertices;

    K.vertices( std::inserter( vertices, vertices.begin() ) );

    ALEPH_ASSERT_EQUAL( vertices.size(), indices.size() );
  }

  auto numEdges = std::count_if( K.begin(), K.end(), [] ( const Simplex& s ) { return s.dimension() == 1; } );

  ALEPH_ASSERT_EQUAL( numEdges, 4 );
}

template <class T> void testSphereReconstruction()
{
  ALEPH_TEST_BEGIN( "Witness complexes: sphere reconstruction" );

  auto samples = aleph::geometry::sphereSampling<T>( 500 );
  auto pc      = aleph::geometry::makeSphere( samples, T(1) );

  unsigned trials = 100;
  unsigned hits   = 0;

  for( unsigned i = 0; i < trials; i++ )
  {
    std::vector<std::size_t> indices = {0,1,2,3,4,5,6,7,8,9,10,11};

    using Distance = aleph::distances::Euclidean<T>;

    auto K
      = aleph::geometry::buildWitnessComplex<Distance>(
          pc, indices.begin(), indices.end() );

    auto betti = bettiNumbers(K);

    if( betti == std::vector<std::size_t>( {1,0,1} ) )
      ++hits;
  }

  // TODO:
  //  - count number of hits
  //  - check that reported percentage by de Silva is reached

  ALEPH_TEST_END();
}

int main(int, char**)
{
  test<float> ();
  test<double>();

  testSphereReconstruction<float> ();
  testSphereReconstruction<double>();
}
<commit_msg>Implemented basic disk sampling procedure<commit_after>#include <tests/Base.hh>

#include <aleph/containers/PointCloud.hh>

#include <aleph/geometry/distances/Euclidean.hh>

#include <aleph/geometry/SphereSampling.hh>
#include <aleph/geometry/WitnessComplex.hh>

#include <aleph/persistentHomology/Calculation.hh>

#include <aleph/topology/filtrations/Data.hh>

#include <algorithm>
#include <iterator>
#include <random>
#include <set>
#include <vector>

#include <cmath>

template <class T> aleph::containers::PointCloud<T> sampleFromDisk( T r, unsigned n )
{
  std::random_device rd;
  std::mt19937 rng( rd() );

  std::uniform_real_distribution<T> rDistribution  ( 0, std::next( r, std::numeric_limits<T>::max() ) );
  std::uniform_real_distribution<T> phiDistribution( 0, static_cast<T>( 2 * M_PI ) );

  aleph::containers::PointCloud<T> pc( n, 2 );

  for( unsigned i = 0; i < n; i++ )
  {
    auto phi = phiDistribution( rng );
    auto r   = rDistribution( rng );
    auto x   = r * std::cos( phi );
    auto y   = r * std::sin( phi );

    pc.set( i, {x,y} );
  }

  return pc;
}

template <class SimplicialComplex> std::vector<std::size_t> bettiNumbers( SimplicialComplex K )
{
  using Simplex  = typename SimplicialComplex::ValueType;
  using DataType = typename Simplex::DataType;

  K.sort( aleph::topology::filtrations::Data<typename SimplicialComplex::ValueType>() );
  auto diagrams = aleph::calculatePersistenceDiagrams( K );

  std::vector<std::size_t> betti( diagrams.size() );

  std::transform( diagrams.begin(), diagrams.end(), betti.begin(),
                  [] ( const aleph::PersistenceDiagram<DataType>& diagram )
                  {
                    return diagram.betti();
                  } );

  return betti;
}

template <class T> void test()
{
  using Distance   = aleph::distances::Euclidean<T>;
  using PointCloud = aleph::containers::PointCloud<T>;

  PointCloud pc( 8, 2 );

  pc.set(0, {-1.0, 0.0} );
  pc.set(1, { 0.0,-1.0} );
  pc.set(2, { 1.0, 0.0} );
  pc.set(3, { 2.0, 1.0} );
  pc.set(4, { 1.0, 1.0} );
  pc.set(5, { 0.0, 2.0} );
  pc.set(6, {-1.0, 1.0} );
  pc.set(7, {-2.0, 1.0} );

  std::vector<std::size_t> indices = {0,2,4,6};

  auto K
    = aleph::geometry::buildWitnessComplex<Distance>(
        pc, indices.begin(), indices.end() );

  using Simplex    = typename decltype(K)::ValueType;
  using VertexType = typename Simplex::VertexType;

  {
    std::set<VertexType> vertices;

    K.vertices( std::inserter( vertices, vertices.begin() ) );

    ALEPH_ASSERT_EQUAL( vertices.size(), indices.size() );
  }

  auto numEdges = std::count_if( K.begin(), K.end(), [] ( const Simplex& s ) { return s.dimension() == 1; } );

  ALEPH_ASSERT_EQUAL( numEdges, 4 );
}

template <class T> void testSphereReconstruction()
{
  ALEPH_TEST_BEGIN( "Witness complexes: sphere reconstruction" );

  auto samples = aleph::geometry::sphereSampling<T>( 500 );
  auto pc      = aleph::geometry::makeSphere( samples, T(1) );

  unsigned trials = 100;
  unsigned hits   = 0;

  for( unsigned i = 0; i < trials; i++ )
  {
    std::vector<std::size_t> indices = {0,1,2,3,4,5,6,7,8,9,10,11};

    using Distance = aleph::distances::Euclidean<T>;

    auto K
      = aleph::geometry::buildWitnessComplex<Distance>(
          pc, indices.begin(), indices.end() );

    auto betti = bettiNumbers(K);

    if( betti == std::vector<std::size_t>( {1,0,1} ) )
      ++hits;
  }

  // TODO:
  //  - count number of hits
  //  - check that reported percentage by de Silva is reached

  ALEPH_TEST_END();
}

int main(int, char**)
{
  test<float> ();
  test<double>();

  testSphereReconstruction<float> ();
  testSphereReconstruction<double>();
}
<|endoftext|>


<commit_before>#include "CameraSystem.h"
#include "CameraInfo.h"
#include "GraphicsBackendSystem.h"
#include "InputBackendSystem.h"
#include "LookAtEntity.h"
#include "Transform.h"

CameraSystem::CameraSystem( GraphicsBackendSystem* p_gfxBackend,
							InputBackendSystem* p_inputBackend ) :
			  EntitySystem( SystemType::CameraSystem, 2,
							ComponentType::ComponentTypeIdx::CameraInfo,
							ComponentType::ComponentTypeIdx::Transform)
{
	m_gfxBackend = p_gfxBackend;
	m_inputBackend = p_inputBackend;
}

CameraSystem::~CameraSystem()
{
}

void CameraSystem::initialize()
{

}

void CameraSystem::processEntities( const vector<Entity*>& p_entities )
{
	float dt = m_world->getDelta();
	for(unsigned int i=0; i<p_entities.size(); i++ )
	{

		CameraInfo* camInfo = static_cast<CameraInfo*>(
			p_entities[i]->getComponent( ComponentType::ComponentTypeIdx::CameraInfo ) );

		Transform* transform = static_cast<Transform*>(
			p_entities[i]->getComponent( ComponentType::ComponentTypeIdx::Transform ) );

		// optional component for lookat
		LookAtEntity* lookAt=NULL;
		Component* t = p_entities[i]->getComponent( ComponentType::ComponentTypeIdx::LookAtEntity );
		if (t!=NULL)
			lookAt = static_cast<LookAtEntity*>(t);

		// Retrieve initial info
		AglVector3 position = transform->getTranslation();
		AglQuaternion rotation = transform->getRotation();
		AglVector3 lookTarget = position+transform->getMatrix().GetForward();
		AglVector3 up = transform->getMatrix().GetUp();

		// Prepare lookat values if used
		if (lookAt)
		{
			// Extract look-at entity and its transform
			Entity* targetEntity = m_world->getEntity(lookAt->getEntityId());
			Transform* targetTransform = static_cast<Transform*>(
				targetEntity->getComponent(ComponentType::ComponentTypeIdx::Transform));
			lookTarget = targetTransform->getTranslation();
			// Set up look-at vars for the view matrix
			// Create offset vector from look-at component in the space of the target
			AglVector3 offset = lookAt->getOffset();
			offset.transformNormal(targetTransform->getMatrix());
			// Transform camera up
			up = targetTransform->getMatrix().GetUp();

			// update transform
//			position = AglVector3::lerp(position,lookTarget+offset,
//										lookAt->getMoveSpd()*dt);
//			rotation = AglQuaternion::slerp(rotation,targetTransform->getRotation(),
//											lookAt->getRotationSpeed()*dt);
			position = lookTarget+offset;
			rotation = targetTransform->getRotation();
			rotation.normalize();
		}

		// Construct view matrix
		AglMatrix view = AglMatrix::createViewMatrix(position,
													 lookTarget,
													 up);

		// update of position
		transform->setTranslation( position );
		transform->setRotation( rotation );

		// Rendering preparations
		AglMatrix viewProj = AglMatrix::identityMatrix();
		viewProj = view * camInfo->m_projMat;
		viewProj = AglMatrix::transpose( viewProj );

		RendererSceneInfo tempSceneInfo;
		for( int i=0; i<16; i++ )
		{
			tempSceneInfo.viewProjectionMatrix[i] = viewProj[i];
		}

		// sets up certain "global" scene data
		GraphicsWrapper* gfxWrapper = m_gfxBackend->getGfxWrapper();
		gfxWrapper->setSceneInfo(tempSceneInfo);
	}
}
<commit_msg>minor tweak, still weird<commit_after>#include "CameraSystem.h"
#include "CameraInfo.h"
#include "GraphicsBackendSystem.h"
#include "InputBackendSystem.h"
#include "LookAtEntity.h"
#include "Transform.h"

CameraSystem::CameraSystem( GraphicsBackendSystem* p_gfxBackend,
							InputBackendSystem* p_inputBackend ) :
			  EntitySystem( SystemType::CameraSystem, 2,
							ComponentType::ComponentTypeIdx::CameraInfo,
							ComponentType::ComponentTypeIdx::Transform)
{
	m_gfxBackend = p_gfxBackend;
	m_inputBackend = p_inputBackend;
}

CameraSystem::~CameraSystem()
{
}

void CameraSystem::initialize()
{

}

void CameraSystem::processEntities( const vector<Entity*>& p_entities )
{
	float dt = m_world->getDelta();
	for(unsigned int i=0; i<p_entities.size(); i++ )
	{

		CameraInfo* camInfo = static_cast<CameraInfo*>(
			p_entities[i]->getComponent( ComponentType::ComponentTypeIdx::CameraInfo ) );

		Transform* transform = static_cast<Transform*>(
			p_entities[i]->getComponent( ComponentType::ComponentTypeIdx::Transform ) );

		// optional component for lookat
		LookAtEntity* lookAt=NULL;
		Component* t = p_entities[i]->getComponent( ComponentType::ComponentTypeIdx::LookAtEntity );
		if (t!=NULL)
			lookAt = static_cast<LookAtEntity*>(t);

		// Retrieve initial info
		AglVector3 position = transform->getTranslation();
		AglQuaternion rotation = transform->getRotation();
		AglVector3 lookTarget = position+transform->getMatrix().GetForward();
		AglVector3 up = transform->getMatrix().GetUp();

		// Prepare lookat values if used
		if (lookAt)
		{
			// Extract look-at entity and its transform
			Entity* targetEntity = m_world->getEntity(lookAt->getEntityId());
			Transform* targetTransform = static_cast<Transform*>(
				targetEntity->getComponent(ComponentType::ComponentTypeIdx::Transform));
			lookTarget = targetTransform->getTranslation();
			// Set up look-at vars for the view matrix
			// Create offset vector from look-at component in the space of the target
			AglVector3 offset = lookAt->getOffset();
			offset.transformNormal(targetTransform->getMatrix());
			// Transform camera up
			up = targetTransform->getMatrix().GetUp();

			// update transform

			// position = AglVector3::lerp(position,lookTarget+offset,
			//							abs(lookAt->getMoveSpd())*dt);
			// rotation = AglQuaternion::slerp(rotation,targetTransform->getRotation(),
			//							abs(lookAt->getRotationSpeed())*dt);
			position = lookTarget+offset;
			rotation = targetTransform->getRotation();
			rotation.normalize();
		}

		// Construct view matrix
		AglMatrix view = AglMatrix::createViewMatrix(position,
													 lookTarget,
													 up);

		// update of position
		transform->setTranslation( position );
		transform->setRotation( rotation );

		// Rendering preparations
		AglMatrix viewProj = AglMatrix::identityMatrix();
		viewProj = view * camInfo->m_projMat;
		viewProj = AglMatrix::transpose( viewProj );

		RendererSceneInfo tempSceneInfo;
		for( int i=0; i<16; i++ )
		{
			tempSceneInfo.viewProjectionMatrix[i] = viewProj[i];
		}

		// sets up certain "global" scene data
		GraphicsWrapper* gfxWrapper = m_gfxBackend->getGfxWrapper();
		gfxWrapper->setSceneInfo(tempSceneInfo);
	}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: HelperCollections.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-07-10 15:02:11 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef DBA_HELPERCOLLECTIONS_HXX
#include "HelperCollections.hxx"
#endif

#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif

namespace dbaccess
{
    using namespace dbtools;
    using namespace comphelper;
    using namespace connectivity;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdbc;
    using namespace ::com::sun::star::sdb;
    using namespace ::com::sun::star::sdbcx;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::script;
    using namespace ::cppu;
    using namespace ::osl;
    // -----------------------------------------------------------------------------
    OPrivateColumns::OPrivateColumns(const ::vos::ORef< ::connectivity::OSQLColumns>& _rColumns,
                        sal_Bool _bCase,
                        ::cppu::OWeakObject& _rParent,
                        ::osl::Mutex& _rMutex,
                        const ::std::vector< ::rtl::OUString> &_rVector,
                        sal_Bool _bUseAsIndex
                    ) : sdbcx::OCollection(_rParent,_bCase,_rMutex,_rVector,_bUseAsIndex)
                        ,m_aColumns(_rColumns)
    {
    }

    // -------------------------------------------------------------------------
    OPrivateColumns* OPrivateColumns::createWithIntrinsicNames( const ::vos::ORef< ::connectivity::OSQLColumns >& _rColumns,
        sal_Bool _bCase, ::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex )
    {
        ::std::vector< ::rtl::OUString > aNames; aNames.reserve( _rColumns->size() );

        ::rtl::OUString sColumName;
        for (   ::connectivity::OSQLColumns::const_iterator column = _rColumns->begin();
                column != _rColumns->end();
                ++column
            )
        {
            Reference< XPropertySet > xColumn( *column, UNO_QUERY_THROW );
            xColumn->getPropertyValue( PROPERTY_NAME ) >>= sColumName;
            aNames.push_back( sColumName );
        }
        return new OPrivateColumns( _rColumns, _bCase, _rParent, _rMutex, aNames, sal_False );
    }

    // -------------------------------------------------------------------------
    void SAL_CALL OPrivateColumns::disposing(void)
    {
        m_aColumns = NULL;
        clear_NoDispose();
            // we're not owner of the objects we're holding, instead the object we got in our ctor is
            // So we're not allowed to dispose our elements.
        OPrivateColumns_Base::disposing();
    }
    // -------------------------------------------------------------------------
    connectivity::sdbcx::ObjectType OPrivateColumns::createObject(const ::rtl::OUString& _rName)
    {
        if ( m_aColumns.isValid() )
        {
            ::connectivity::OSQLColumns::const_iterator aIter = find(m_aColumns->begin(),m_aColumns->end(),_rName,isCaseSensitive());
            if(aIter == m_aColumns->end())
                aIter = findRealName(m_aColumns->begin(),m_aColumns->end(),_rName,isCaseSensitive());

            if(aIter != m_aColumns->end())
                return connectivity::sdbcx::ObjectType(*aIter,UNO_QUERY);

            OSL_ENSURE(0,"Column not found in collection!");
        }
        return NULL;
    }
    // -------------------------------------------------------------------------
    connectivity::sdbcx::ObjectType OPrivateTables::createObject(const ::rtl::OUString& _rName)
    {
        if ( !m_aTables.empty() )
        {
            OSQLTables::iterator aIter = m_aTables.find(_rName);
            OSL_ENSURE(aIter != m_aTables.end(),"Table not found!");
            OSL_ENSURE(aIter->second.is(),"Table is null!");
            return connectivity::sdbcx::ObjectType(m_aTables.find(_rName)->second,UNO_QUERY);
        }
        return NULL;
    }
    // -----------------------------------------------------------------------------
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.36); FILE MERGED 2006/09/01 17:24:03 kaib 1.5.36.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: HelperCollections.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 06:31:33 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBA_HELPERCOLLECTIONS_HXX
#include "HelperCollections.hxx"
#endif

#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif

namespace dbaccess
{
    using namespace dbtools;
    using namespace comphelper;
    using namespace connectivity;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdbc;
    using namespace ::com::sun::star::sdb;
    using namespace ::com::sun::star::sdbcx;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::script;
    using namespace ::cppu;
    using namespace ::osl;
    // -----------------------------------------------------------------------------
    OPrivateColumns::OPrivateColumns(const ::vos::ORef< ::connectivity::OSQLColumns>& _rColumns,
                        sal_Bool _bCase,
                        ::cppu::OWeakObject& _rParent,
                        ::osl::Mutex& _rMutex,
                        const ::std::vector< ::rtl::OUString> &_rVector,
                        sal_Bool _bUseAsIndex
                    ) : sdbcx::OCollection(_rParent,_bCase,_rMutex,_rVector,_bUseAsIndex)
                        ,m_aColumns(_rColumns)
    {
    }

    // -------------------------------------------------------------------------
    OPrivateColumns* OPrivateColumns::createWithIntrinsicNames( const ::vos::ORef< ::connectivity::OSQLColumns >& _rColumns,
        sal_Bool _bCase, ::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex )
    {
        ::std::vector< ::rtl::OUString > aNames; aNames.reserve( _rColumns->size() );

        ::rtl::OUString sColumName;
        for (   ::connectivity::OSQLColumns::const_iterator column = _rColumns->begin();
                column != _rColumns->end();
                ++column
            )
        {
            Reference< XPropertySet > xColumn( *column, UNO_QUERY_THROW );
            xColumn->getPropertyValue( PROPERTY_NAME ) >>= sColumName;
            aNames.push_back( sColumName );
        }
        return new OPrivateColumns( _rColumns, _bCase, _rParent, _rMutex, aNames, sal_False );
    }

    // -------------------------------------------------------------------------
    void SAL_CALL OPrivateColumns::disposing(void)
    {
        m_aColumns = NULL;
        clear_NoDispose();
            // we're not owner of the objects we're holding, instead the object we got in our ctor is
            // So we're not allowed to dispose our elements.
        OPrivateColumns_Base::disposing();
    }
    // -------------------------------------------------------------------------
    connectivity::sdbcx::ObjectType OPrivateColumns::createObject(const ::rtl::OUString& _rName)
    {
        if ( m_aColumns.isValid() )
        {
            ::connectivity::OSQLColumns::const_iterator aIter = find(m_aColumns->begin(),m_aColumns->end(),_rName,isCaseSensitive());
            if(aIter == m_aColumns->end())
                aIter = findRealName(m_aColumns->begin(),m_aColumns->end(),_rName,isCaseSensitive());

            if(aIter != m_aColumns->end())
                return connectivity::sdbcx::ObjectType(*aIter,UNO_QUERY);

            OSL_ENSURE(0,"Column not found in collection!");
        }
        return NULL;
    }
    // -------------------------------------------------------------------------
    connectivity::sdbcx::ObjectType OPrivateTables::createObject(const ::rtl::OUString& _rName)
    {
        if ( !m_aTables.empty() )
        {
            OSQLTables::iterator aIter = m_aTables.find(_rName);
            OSL_ENSURE(aIter != m_aTables.end(),"Table not found!");
            OSL_ENSURE(aIter->second.is(),"Table is null!");
            return connectivity::sdbcx::ObjectType(m_aTables.find(_rName)->second,UNO_QUERY);
        }
        return NULL;
    }
    // -----------------------------------------------------------------------------
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: datasource.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: fs $ $Date: 2000-10-18 16:15:16 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DBA_COREDATAACCESS_DATASOURCE_HXX_
#define _DBA_COREDATAACCESS_DATASOURCE_HXX_

#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_
#include <com/sun/star/sdbc/XDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XFORMDOCUMENTSSUPPLIER_HPP_
#include <com/sun/star/sdb/XFormDocumentsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XREPORTDOCUMENTSSUPPLIER_HPP_
#include <com/sun/star/sdb/XReportDocumentsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XQUERYDEFINITIONSSUPPLIER_HPP_
#include <com/sun/star/sdb/XQueryDefinitionsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef _CPPUHELPER_PROPSHLP_HXX
#include <cppuhelper/propshlp.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE6_HXX_
#include <cppuhelper/implbase6.hxx>
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef _DBA_REGISTRATION_HELPER_HXX_
#include "registrationhelper.hxx"
#endif
#ifndef _DBA_COREDATAACCESS_DOCUMENTCONTAINER_HXX_
#include "documentcontainer.hxx"
#endif
#ifndef _DBA_COREDATAACCESS_COMMANDCONTAINER_HXX_
#include "commandcontainer.hxx"
#endif
#ifndef _DBA_CORE_CONTAINERELEMENT_HXX_
#include "containerelement.hxx"
#endif
#ifndef _DBA_CORE_CONFIGURATIONFLUSHABLE_HXX_
#include "configurationflushable.hxx"
#endif
#ifndef _VOS_REF_HXX_
#include <vos/ref.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include <connectivity/CommonTools.hxx>
#endif
#ifndef _DBA_CONFIGNODE_HXX_
#include "confignode.hxx"
#endif

//........................................................................
namespace dbaccess
{
//........................................................................

typedef ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XConnection > OWeakConnection;
typedef std::vector< OWeakConnection > OWeakConnectionArray;

//============================================================
//= ODatabaseSource
//============================================================
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
    ODatabaseSource_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);

typedef ::cppu::ImplHelper6 <   ::com::sun::star::lang::XServiceInfo,
                                ::com::sun::star::lang::XUnoTunnel,
                                ::com::sun::star::sdbc::XDataSource,
                                ::com::sun::star::sdb::XFormDocumentsSupplier,
                                ::com::sun::star::sdb::XReportDocumentsSupplier,
                                ::com::sun::star::sdb::XQueryDefinitionsSupplier
                            >   ODatabaseSource_Base;

class ODatabaseSource   :public connectivity::OBaseMutex
                    ,public OSubComponent
                    ,public OContainerElement
                    ,public OConfigurationFlushable
                    ,public ::cppu::OPropertySetHelper
                    ,public ::comphelper::OPropertyArrayUsageHelper < ODatabaseSource >
                    ,public ODatabaseSource_Base
{
    friend class ODatabaseContext;
    friend class OConnection;
    friend ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
        ODatabaseSource_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);

protected:
    OWeakConnectionArray        m_aConnections;

    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
                                                        m_xServiceFactory;

    ODocumentContainer      m_aForms;
    ODocumentContainer      m_aReports;
    OCommandContainer       m_aCommandDefinitions;

// <properties>
    ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >
                                                        m_xNumberFormatsSupplier;
    ::rtl::OUString                                     m_sConnectURL;
    ::rtl::OUString                                     m_sName;        // transient, our creator has to tell us the title
    ::rtl::OUString                                     m_sUser;
    ::rtl::OUString                                     m_aPassword;    // transient !
    ::com::sun::star::uno::Sequence< ::rtl::OUString >  m_aTableFilter;
    ::com::sun::star::uno::Sequence< ::rtl::OUString >  m_aTableTypeFilter;
    sal_Int32                                           m_nLoginTimeout;
    sal_Bool                                            m_bReadOnly : 1;
    sal_Bool                                            m_bPasswordRequired : 1;
    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >
                                                        m_aInfo;
// </properties>

protected:
    ODatabaseSource(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory);

public:
    ODatabaseSource(
        ::cppu::OWeakObject& _rParent,
        const OConfigurationNode& _rConfigRoot,
        const ::rtl::OUString& _rRegistrationName,
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory);
    virtual ~ODatabaseSource();

// com::sun::star::lang::XTypeProvider
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException);

// com::sun::star::uno::XInterface
    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL acquire() throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL release() throw(::com::sun::star::uno::RuntimeException);

// ::com::sun::star::lang::XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException);

// ::com::sun::star::lang::XServiceInfo - static methods
    static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
    static ::rtl::OUString getImplementationName_Static(void) throw( ::com::sun::star::uno::RuntimeException );
    static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
        SAL_CALL Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);

// com::sun::star::lang::XUnoTunnel
    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
    static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId() throw (::com::sun::star::uno::RuntimeException);

// OComponentHelper
    virtual void SAL_CALL disposing(void);

// com::sun::star::beans::XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException);

// comphelper::OPropertyArrayUsageHelper
    virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;

// cppu::OPropertySetHelper
    virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

    virtual sal_Bool SAL_CALL convertFastPropertyValue(
                            ::com::sun::star::uno::Any & rConvertedValue,
                            ::com::sun::star::uno::Any & rOldValue,
                            sal_Int32 nHandle,
                            const ::com::sun::star::uno::Any& rValue )
                                throw (::com::sun::star::lang::IllegalArgumentException);
    virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
                                sal_Int32 nHandle,
                                const ::com::sun::star::uno::Any& rValue
                                                 )
                                                 throw (::com::sun::star::uno::Exception);
    virtual void SAL_CALL getFastPropertyValue( ::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;

// ::com::sun::star::sdbc::XDataSource
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection( const ::rtl::OUString& user, const ::rtl::OUString& password ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setLoginTimeout( sal_Int32 seconds ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
    virtual sal_Int32 SAL_CALL getLoginTimeout(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

// :: com::sun::star::sdb::XFormDocumentsSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getFormDocuments(  ) throw(::com::sun::star::uno::RuntimeException);

// :: com::sun::star::sdb::XReportDocumentsSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getReportDocuments(  ) throw(::com::sun::star::uno::RuntimeException);

// :: com::sun::star::sdb::XQueryDefinitionsSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getQueryDefinitions(  ) throw(::com::sun::star::uno::RuntimeException);

protected:
    // OConfigurationFlushable
    virtual void flush_NoBroadcast_NoCommit();

protected:
// helper
    const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >&
            getNumberFormatsSupplier();

    /** open a connection for the current settings. this is the simple connection we get from the driver
        manager, so it acn be used as a master for a "high level" sdb connection.
    */
    ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > buildLowLevelConnection(
        const ::rtl::OUString& _rUid, const ::rtl::OUString& _rPwd
        );

// OContainerElement
    virtual void        inserted(
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContainer,
        const ::rtl::OUString& _rElementName,
        const OConfigurationTreeRoot& _rConfigRoot);

    virtual void        removed();

    virtual sal_Bool    isContainerElement() const { return m_aConfigurationNode.isValid(); }

// other stuff
    void    initializeFromConfiguration();
    void    flushToConfiguration();

#if 0
    void    readUIAspects(const ::vos::ORef< ::store::OStream >& _rStream);
    void    writeUIAspects(const ::vos::ORef< ::store::OStream >& _rStream);
#endif

    void    initializeDocuments(sal_Bool _bRead = sal_True);
    void    flushDocuments();
};

//........................................................................
}   // namespace dbaccess
//........................................................................

#endif // _DBA_COREDATAACCESS_DATALINK_HXX_

<commit_msg>m_bSuppressVersionColumns<commit_after>/*************************************************************************
 *
 *  $RCSfile: datasource.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: fs $ $Date: 2000-10-20 09:51:38 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DBA_COREDATAACCESS_DATASOURCE_HXX_
#define _DBA_COREDATAACCESS_DATASOURCE_HXX_

#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATASOURCE_HPP_
#include <com/sun/star/sdbc/XDataSource.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XFORMDOCUMENTSSUPPLIER_HPP_
#include <com/sun/star/sdb/XFormDocumentsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XREPORTDOCUMENTSSUPPLIER_HPP_
#include <com/sun/star/sdb/XReportDocumentsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XQUERYDEFINITIONSSUPPLIER_HPP_
#include <com/sun/star/sdb/XQueryDefinitionsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef _CPPUHELPER_PROPSHLP_HXX
#include <cppuhelper/propshlp.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE6_HXX_
#include <cppuhelper/implbase6.hxx>
#endif
#ifndef _DBASHARED_APITOOLS_HXX_
#include "apitools.hxx"
#endif
#ifndef _DBA_REGISTRATION_HELPER_HXX_
#include "registrationhelper.hxx"
#endif
#ifndef _DBA_COREDATAACCESS_DOCUMENTCONTAINER_HXX_
#include "documentcontainer.hxx"
#endif
#ifndef _DBA_COREDATAACCESS_COMMANDCONTAINER_HXX_
#include "commandcontainer.hxx"
#endif
#ifndef _DBA_CORE_CONTAINERELEMENT_HXX_
#include "containerelement.hxx"
#endif
#ifndef _DBA_CORE_CONFIGURATIONFLUSHABLE_HXX_
#include "configurationflushable.hxx"
#endif
#ifndef _VOS_REF_HXX_
#include <vos/ref.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_
#include <connectivity/CommonTools.hxx>
#endif
#ifndef _DBA_CONFIGNODE_HXX_
#include "confignode.hxx"
#endif

//........................................................................
namespace dbaccess
{
//........................................................................

typedef ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XConnection > OWeakConnection;
typedef std::vector< OWeakConnection > OWeakConnectionArray;

//============================================================
//= ODatabaseSource
//============================================================
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
    ODatabaseSource_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);

typedef ::cppu::ImplHelper6 <   ::com::sun::star::lang::XServiceInfo,
                                ::com::sun::star::lang::XUnoTunnel,
                                ::com::sun::star::sdbc::XDataSource,
                                ::com::sun::star::sdb::XFormDocumentsSupplier,
                                ::com::sun::star::sdb::XReportDocumentsSupplier,
                                ::com::sun::star::sdb::XQueryDefinitionsSupplier
                            >   ODatabaseSource_Base;

class ODatabaseSource   :public connectivity::OBaseMutex
                    ,public OSubComponent
                    ,public OContainerElement
                    ,public OConfigurationFlushable
                    ,public ::cppu::OPropertySetHelper
                    ,public ::comphelper::OPropertyArrayUsageHelper < ODatabaseSource >
                    ,public ODatabaseSource_Base
{
    friend class ODatabaseContext;
    friend class OConnection;
    friend ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
        ODatabaseSource_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);

protected:
    OWeakConnectionArray        m_aConnections;

    ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
                                                        m_xServiceFactory;

    ODocumentContainer      m_aForms;
    ODocumentContainer      m_aReports;
    OCommandContainer       m_aCommandDefinitions;

// <properties>
    ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >
                                                        m_xNumberFormatsSupplier;
    ::rtl::OUString                                     m_sConnectURL;
    ::rtl::OUString                                     m_sName;        // transient, our creator has to tell us the title
    ::rtl::OUString                                     m_sUser;
    ::rtl::OUString                                     m_aPassword;    // transient !
    ::com::sun::star::uno::Sequence< ::rtl::OUString >  m_aTableFilter;
    ::com::sun::star::uno::Sequence< ::rtl::OUString >  m_aTableTypeFilter;
    sal_Int32                                           m_nLoginTimeout;
    sal_Bool                                            m_bReadOnly : 1;
    sal_Bool                                            m_bPasswordRequired : 1;
    sal_Bool                                            m_bSuppressVersionColumns : 1;
    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >
                                                        m_aInfo;
// </properties>

protected:
    ODatabaseSource(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory);

public:
    ODatabaseSource(
        ::cppu::OWeakObject& _rParent,
        const OConfigurationNode& _rConfigRoot,
        const ::rtl::OUString& _rRegistrationName,
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory);
    virtual ~ODatabaseSource();

// com::sun::star::lang::XTypeProvider
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException);

// com::sun::star::uno::XInterface
    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL acquire() throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL release() throw(::com::sun::star::uno::RuntimeException);

// ::com::sun::star::lang::XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  ) throw(::com::sun::star::uno::RuntimeException);

// ::com::sun::star::lang::XServiceInfo - static methods
    static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
    static ::rtl::OUString getImplementationName_Static(void) throw( ::com::sun::star::uno::RuntimeException );
    static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
        SAL_CALL Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);

// com::sun::star::lang::XUnoTunnel
    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
    static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId() throw (::com::sun::star::uno::RuntimeException);

// OComponentHelper
    virtual void SAL_CALL disposing(void);

// com::sun::star::beans::XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException);

// comphelper::OPropertyArrayUsageHelper
    virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;

// cppu::OPropertySetHelper
    virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

    virtual sal_Bool SAL_CALL convertFastPropertyValue(
                            ::com::sun::star::uno::Any & rConvertedValue,
                            ::com::sun::star::uno::Any & rOldValue,
                            sal_Int32 nHandle,
                            const ::com::sun::star::uno::Any& rValue )
                                throw (::com::sun::star::lang::IllegalArgumentException);
    virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
                                sal_Int32 nHandle,
                                const ::com::sun::star::uno::Any& rValue
                                                 )
                                                 throw (::com::sun::star::uno::Exception);
    virtual void SAL_CALL getFastPropertyValue( ::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;

// ::com::sun::star::sdbc::XDataSource
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection( const ::rtl::OUString& user, const ::rtl::OUString& password ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setLoginTimeout( sal_Int32 seconds ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
    virtual sal_Int32 SAL_CALL getLoginTimeout(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

// :: com::sun::star::sdb::XFormDocumentsSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getFormDocuments(  ) throw(::com::sun::star::uno::RuntimeException);

// :: com::sun::star::sdb::XReportDocumentsSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getReportDocuments(  ) throw(::com::sun::star::uno::RuntimeException);

// :: com::sun::star::sdb::XQueryDefinitionsSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getQueryDefinitions(  ) throw(::com::sun::star::uno::RuntimeException);

protected:
    // OConfigurationFlushable
    virtual void flush_NoBroadcast_NoCommit();

protected:
// helper
    const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >&
            getNumberFormatsSupplier();

    /** open a connection for the current settings. this is the simple connection we get from the driver
        manager, so it acn be used as a master for a "high level" sdb connection.
    */
    ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > buildLowLevelConnection(
        const ::rtl::OUString& _rUid, const ::rtl::OUString& _rPwd
        );

// OContainerElement
    virtual void        inserted(
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContainer,
        const ::rtl::OUString& _rElementName,
        const OConfigurationTreeRoot& _rConfigRoot);

    virtual void        removed();

    virtual sal_Bool    isContainerElement() const { return m_aConfigurationNode.isValid(); }

// other stuff
    void    initializeFromConfiguration();
    void    flushToConfiguration();

#if 0
    void    readUIAspects(const ::vos::ORef< ::store::OStream >& _rStream);
    void    writeUIAspects(const ::vos::ORef< ::store::OStream >& _rStream);
#endif

    void    initializeDocuments(sal_Bool _bRead = sal_True);
    void    flushDocuments();
};

//........................................................................
}   // namespace dbaccess
//........................................................................

#endif // _DBA_COREDATAACCESS_DATALINK_HXX_

<|endoftext|>


<commit_before><commit_msg>rpc_tests: use BOOST_CHECK_EQUAL<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.

#include "tests/unittests/test_suite.h"
#include "tests/cefclient/client_switches.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/test/test_suite.h"

#if defined(OS_MACOSX)
#include "base/debug/stack_trace.h"
#include "base/files/file_path.h"
#include "base/i18n/icu_util.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/test/test_timeouts.h"
#endif

CommandLine* CefTestSuite::commandline_ = NULL;

CefTestSuite::CefTestSuite(int argc, char** argv)
  : TestSuite(argc, argv) {
}

// static
void CefTestSuite::InitCommandLine(int argc, const char* const* argv) {
  if (commandline_) {
    // If this is intentional, Reset() must be called first. If we are using
    // the shared build mode, we have to share a single object across multiple
    // shared libraries.
    return;
  }

  commandline_ = new CommandLine(CommandLine::NO_PROGRAM);
#if defined(OS_WIN)
  commandline_->ParseFromString(::GetCommandLineW());
#elif defined(OS_POSIX)
  commandline_->InitFromArgv(argc, argv);
#endif
}

// static
void CefTestSuite::GetSettings(CefSettings& settings) {
#if defined(OS_WIN)
  settings.multi_threaded_message_loop =
      commandline_->HasSwitch(cefclient::kMultiThreadedMessageLoop);
#endif

  CefString(&settings.cache_path) =
      commandline_->GetSwitchValueASCII(cefclient::kCachePath);

  // Always expose the V8 gc() function to give tests finer-grained control over
  // memory management.
  std::string javascript_flags = "--expose-gc";
  // Value of kJavascriptFlags switch.
  std::string other_javascript_flags =
      commandline_->GetSwitchValueASCII("js-flags");
  if (!other_javascript_flags.empty())
    javascript_flags += " " + other_javascript_flags;
  CefString(&settings.javascript_flags) = javascript_flags;

  // Necessary for V8Test.OnUncaughtException tests.
  settings.uncaught_exception_stack_size = 10;
  settings.remote_debugging_port = 12345;
}

// static
bool CefTestSuite::GetCachePath(std::string& path) {
  DCHECK(commandline_);

  if (commandline_->HasSwitch(cefclient::kCachePath)) {
    // Set the cache_path value.
    path = commandline_->GetSwitchValueASCII(cefclient::kCachePath);
    return true;
  }

  return false;
}

#if defined(OS_MACOSX)
void CefTestSuite::Initialize() {
  // The below code is copied from base/test/test_suite.cc to avoid calling
  // RegisterMockCrApp() on Mac.

  base::FilePath exe;
  PathService::Get(base::FILE_EXE, &exe);

  // Initialize logging.
  logging::LoggingSettings log_settings;
  log_settings.log_file =
      exe.ReplaceExtension(FILE_PATH_LITERAL("log")).value().c_str();
  log_settings.logging_dest = logging::LOG_TO_ALL;
  log_settings.lock_log = logging::LOCK_LOG_FILE;
  log_settings.delete_old = logging::DELETE_OLD_LOG_FILE;
  log_settings.dcheck_state =
      logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS;
  logging::InitLogging(log_settings);

  // We want process and thread IDs because we may have multiple processes.
  // Note: temporarily enabled timestamps in an effort to catch bug 6361.
  logging::SetLogItems(true, true, true, true);

  CHECK(base::debug::EnableInProcessStackDumping());

  // In some cases, we do not want to see standard error dialogs.
  if (!base::debug::BeingDebugged() &&
      !CommandLine::ForCurrentProcess()->HasSwitch("show-error-dialogs")) {
    SuppressErrorDialogs();
    base::debug::SetSuppressDebugUI(true);
    logging::SetLogAssertHandler(UnitTestAssertHandler);
  }

  icu_util::Initialize();

  CatchMaybeTests();
  ResetCommandLine();

  TestTimeouts::Initialize();
}
#endif  // defined(OS_MACOSX)
<commit_msg>Mac: Fix compile error<commit_after>// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.

#include "tests/unittests/test_suite.h"
#include "tests/cefclient/client_switches.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/test/test_suite.h"

#if defined(OS_MACOSX)
#include "base/debug/stack_trace.h"
#include "base/files/file_path.h"
#include "base/i18n/icu_util.h"
#include "base/path_service.h"
#include "base/test/test_timeouts.h"
#endif

CommandLine* CefTestSuite::commandline_ = NULL;

CefTestSuite::CefTestSuite(int argc, char** argv)
  : TestSuite(argc, argv) {
}

// static
void CefTestSuite::InitCommandLine(int argc, const char* const* argv) {
  if (commandline_) {
    // If this is intentional, Reset() must be called first. If we are using
    // the shared build mode, we have to share a single object across multiple
    // shared libraries.
    return;
  }

  commandline_ = new CommandLine(CommandLine::NO_PROGRAM);
#if defined(OS_WIN)
  commandline_->ParseFromString(::GetCommandLineW());
#elif defined(OS_POSIX)
  commandline_->InitFromArgv(argc, argv);
#endif
}

// static
void CefTestSuite::GetSettings(CefSettings& settings) {
#if defined(OS_WIN)
  settings.multi_threaded_message_loop =
      commandline_->HasSwitch(cefclient::kMultiThreadedMessageLoop);
#endif

  CefString(&settings.cache_path) =
      commandline_->GetSwitchValueASCII(cefclient::kCachePath);

  // Always expose the V8 gc() function to give tests finer-grained control over
  // memory management.
  std::string javascript_flags = "--expose-gc";
  // Value of kJavascriptFlags switch.
  std::string other_javascript_flags =
      commandline_->GetSwitchValueASCII("js-flags");
  if (!other_javascript_flags.empty())
    javascript_flags += " " + other_javascript_flags;
  CefString(&settings.javascript_flags) = javascript_flags;

  // Necessary for V8Test.OnUncaughtException tests.
  settings.uncaught_exception_stack_size = 10;
  settings.remote_debugging_port = 12345;
}

// static
bool CefTestSuite::GetCachePath(std::string& path) {
  DCHECK(commandline_);

  if (commandline_->HasSwitch(cefclient::kCachePath)) {
    // Set the cache_path value.
    path = commandline_->GetSwitchValueASCII(cefclient::kCachePath);
    return true;
  }

  return false;
}

#if defined(OS_MACOSX)
void CefTestSuite::Initialize() {
  // The below code is copied from base/test/test_suite.cc to avoid calling
  // RegisterMockCrApp() on Mac.

  base::FilePath exe;
  PathService::Get(base::FILE_EXE, &exe);

  // Initialize logging.
  logging::LoggingSettings log_settings;
  log_settings.log_file =
      exe.ReplaceExtension(FILE_PATH_LITERAL("log")).value().c_str();
  log_settings.logging_dest = logging::LOG_TO_ALL;
  log_settings.lock_log = logging::LOCK_LOG_FILE;
  log_settings.delete_old = logging::DELETE_OLD_LOG_FILE;
  log_settings.dcheck_state =
      logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS;
  logging::InitLogging(log_settings);

  // We want process and thread IDs because we may have multiple processes.
  // Note: temporarily enabled timestamps in an effort to catch bug 6361.
  logging::SetLogItems(true, true, true, true);

  CHECK(base::debug::EnableInProcessStackDumping());

  // In some cases, we do not want to see standard error dialogs.
  if (!base::debug::BeingDebugged() &&
      !CommandLine::ForCurrentProcess()->HasSwitch("show-error-dialogs")) {
    SuppressErrorDialogs();
    base::debug::SetSuppressDebugUI(true);
    logging::SetLogAssertHandler(UnitTestAssertHandler);
  }

  icu_util::Initialize();

  CatchMaybeTests();
  ResetCommandLine();

  TestTimeouts::Initialize();
}
#endif  // defined(OS_MACOSX)
<|endoftext|>


<commit_before>struct read_BMP_into_world_data(const char *imagepath)
{
    printf("Reading image %s\n", imagepath);

    // Data read from the header of the BMP file
    unsigned char header[54];
    unsigned int dataPos;
    unsigned int imageSize;
    unsigned int width, height;
    // Actual RGB image data.
    unsigned char *image_data;

    // Open the file
    FILE *file = fopen(imagepath,"rb");
    if (!file)
    {
        printf("%s could not be opened.\n", imagepath);
        getchar();
        return 0;
    }

    // Read the header, i.e. the 54 first bytes

    // If less than 54 bytes are read, it's a problem.
    if (fread(header, 1, 54, file) != 54)
    {
        printf("Not a correct BMP file\n");
        return 0;
    }

    // A BMP files always begins with "BM"
    if ((header[0] != 'B') || (header[1] != 'M'))
    {
        printf("Not a correct BMP file\n");
        return 0;
    }

    // Make sure this is a 24bpp file
    if (*(int*) & (header[0x1E]) != 0)
    {
        printf("Not a correct BMP file\n");
        return 0;
    }

    if (*(int*) & (header[0x1C]) != 24)
    {
        printf("Not a correct BMP file\n");
        return 0;
    }

    // Read the information about the image
    dataPos    = *(int*) & (header[0x0A]);
    imageSize  = *(int*) & (header[0x22]);
    width      = *(int*) & (header[0x12]);
    height     = *(int*) & (header[0x16]);

    // Some BMP files are misformatted, guess missing information
    if (imageSize == 0)
    {
        imageSize = width * height * 3; // 3 : one byte for each Red, Green and Blue component
    }

    if (dataPos == 0)
    {
        dataPos = 54; // The BMP header is done that way
    }

    // Create a buffer.
    image_data = new unsigned char [imageSize];

    // Read the actual image data from the file into the buffer.
    fread(image_data, 1, imageSize, file);

    // Everything is in memory now, the file can be closed
    fclose(file);

#define COLOR_CHANNEL_RED
#define COLOR_CHANNEL_GREEN
#define COLOR_CHANNEL_BLUE
#define COLOR_CHANNEL_MEAN

    vertex_data = new int32 [4 * imageSize];

    uint8 *image_pointer = &image_data;
    int32 *vertex_pointer = &vertex_data;

    // start processing image_data.
    for (int32 x = 0; x < width; x++)
    {
        for (int32 z = height; z >= 0; z--)
        {
            pixel_data = vertex_pointer & 0xffffff; // assumes little-endian architecture.
            vertex_pointer++ = x; // x.
#elif COLOR_CHANNEL_RED
            vertex_pointer++ = (int32) *image_pointer;       // y-coordinate is the red (R) value.
#elif COLOR_CHANNEL_GREEN
            vertex_pointer++ = (int32) *(image_pointer + 1); // y-coordinate is the green (G) value.
#elif COLOR_CHANNEL_BLUE
            vertex_pointer++ = (int32) *(image_pointer + 2); // y-coordinate is the blue (B) value.
#elif COLOR_CHANNEL_MEAN
            // y-coordinate is the mean of R, G, & B.
            vertex_pointer++ = (((int32) *imgepointer) + ((int32) *(image_pointer + 1)) + ((int32) *(image_pointer + 2))) / 3;
#endif
            image_pointer += 3 * sizeof (image_data);
            vertex_pointer++ = z; // z.
            vertex_pointer++ = 0; // not in use (for alignment only).
        }
    }
<commit_msg>Lisätty puuttuva `include <stdint.h>`.<commit_after>#include <stdint.h> // uint32_t etc.

struct read_BMP_into_world_data(const char *imagepath)
{
    printf("Reading image %s\n", imagepath);

    // Data read from the header of the BMP file
    unsigned char header[54];
    unsigned int dataPos;
    unsigned int imageSize;
    unsigned int width, height;
    // Actual RGB image data.
    unsigned char *image_data;

    // Open the file
    FILE *file = fopen(imagepath,"rb");
    if (!file)
    {
        printf("%s could not be opened.\n", imagepath);
        getchar();
        return 0;
    }

    // Read the header, i.e. the 54 first bytes

    // If less than 54 bytes are read, it's a problem.
    if (fread(header, 1, 54, file) != 54)
    {
        printf("Not a correct BMP file\n");
        return 0;
    }

    // A BMP files always begins with "BM"
    if ((header[0] != 'B') || (header[1] != 'M'))
    {
        printf("Not a correct BMP file\n");
        return 0;
    }

    // Make sure this is a 24bpp file
    if (*(int*) & (header[0x1E]) != 0)
    {
        printf("Not a correct BMP file\n");
        return 0;
    }

    if (*(int*) & (header[0x1C]) != 24)
    {
        printf("Not a correct BMP file\n");
        return 0;
    }

    // Read the information about the image
    dataPos    = *(int*) & (header[0x0A]);
    imageSize  = *(int*) & (header[0x22]);
    width      = *(int*) & (header[0x12]);
    height     = *(int*) & (header[0x16]);

    // Some BMP files are misformatted, guess missing information
    if (imageSize == 0)
    {
        imageSize = width * height * 3; // 3 : one byte for each Red, Green and Blue component
    }

    if (dataPos == 0)
    {
        dataPos = 54; // The BMP header is done that way
    }

    // Create a buffer.
    image_data = new unsigned char [imageSize];

    // Read the actual image data from the file into the buffer.
    fread(image_data, 1, imageSize, file);

    // Everything is in memory now, the file can be closed
    fclose(file);

#define COLOR_CHANNEL_RED
#define COLOR_CHANNEL_GREEN
#define COLOR_CHANNEL_BLUE
#define COLOR_CHANNEL_MEAN

    vertex_data = new int32 [4 * imageSize];

    uint8 *image_pointer = &image_data;
    int32 *vertex_pointer = &vertex_data;

    // start processing image_data.
    for (int32 x = 0; x < width; x++)
    {
        for (int32 z = height; z >= 0; z--)
        {
            pixel_data = vertex_pointer & 0xffffff; // assumes little-endian architecture.
            vertex_pointer++ = x; // x.
#elif COLOR_CHANNEL_RED
            vertex_pointer++ = (int32) *image_pointer;       // y-coordinate is the red (R) value.
#elif COLOR_CHANNEL_GREEN
            vertex_pointer++ = (int32) *(image_pointer + 1); // y-coordinate is the green (G) value.
#elif COLOR_CHANNEL_BLUE
            vertex_pointer++ = (int32) *(image_pointer + 2); // y-coordinate is the blue (B) value.
#elif COLOR_CHANNEL_MEAN
            // y-coordinate is the mean of R, G, & B.
            vertex_pointer++ = (((int32) *imgepointer) + ((int32) *(image_pointer + 1)) + ((int32) *(image_pointer + 2))) / 3;
#endif
            image_pointer += 3 * sizeof (image_data);
            vertex_pointer++ = z; // z.
            vertex_pointer++ = 0; // not in use (for alignment only).
        }
    }
<|endoftext|>