예제 #1
0
bool  Quadtree::GetObjectsAt( list<PartitionObject*>& listOfChldObjects, float _x, float _y, float dist, U32 collisionFlags )
{
	if ( level == maxLevel ) 
	{
		CopyFilterList( objects, listOfChldObjects, collisionFlags );
		return true;
	}

	float halfX = ( x2+x1 ) * 0.5f;
	float halfY = ( y2+y1 ) * 0.5f;

	Quadtree* childToCopy = NULL;
	if ( _x > halfX && _x < x2 ) 
	{
		if ( _y > halfY && _y < y2 ) 
		{
			childToCopy = SE;
		} 
		else if ( _y > y1 && _y <= halfY ) 
		{
			childToCopy = NE;
		}
	} 
	else if ( _x > x1 && _x <= halfX ) 
	{
		if ( _y > halfY && _y < y2 ) 
		{
			childToCopy = SW;
		} 
		else if ( _y > y1 && _y <= halfY ) 
		{
			childToCopy = NW;
		}
	}

	if( childToCopy )
	{
		childToCopy->GetObjectsAt( listOfChldObjects, _x, _y, dist, collisionFlags );
		if( listOfChldObjects.size() == 0 )
		CopyFilterList( objects, listOfChldObjects, _x, _y, dist, collisionFlags );
		return true;
	}
	else// no too sure about this else case.
	{
		CopyFilterList( objects, listOfChldObjects,  _x, _y, dist, collisionFlags );
	}
	return false;
}
void NearestStarbucksApp::setup()
{
	std::string path = "Starbucks_2006.csv";
	std::ifstream ifs(path.c_str());
    std::string t;
	int n = 0;
	int len = 0;
	while(safeGetline(ifs, t)){
		if (t.length() > 1){
			++len;
		}
		else{
			break;
		}
	}
	std::ifstream ifs2(path.c_str());
	Entry* entries = new Entry[len+1];
	t = "Temporary text";
	while(safeGetline(ifs2, t)){
		if (t.length() > 1){
			n++;
		}
		else{ 
			break;
		}
		entries[n].identifier =  t.substr(0, t.find_first_of(","));
		entries[n].x = atof(t.substr(t.find(",")+1, t.rfind(",") - t.find(",")-1).c_str());
		entries[n].y = atof(t.substr(t.find_last_of(",")+1,t.length() - t.rfind(",")).c_str());
	}
	tree = new Quadtree();
	tree->build(entries, n);
}
예제 #3
0
  void add_paddle_constraints(ModifiedObjectReference& obj,
                              Quadtree& q) noexcept
  {
    for(const auto& node : find_containing_nodes(q.root(), obj.obj.volume))
    {
      for(id_type other_id : node->get_data()->ids)
      {
        if(other_id == obj.id) continue;

        const Object& other_obj = q.find_object(other_id);
        if(!isPaddle(other_obj)) continue;

        if(intersecting(obj.obj.volume, other_obj.volume))
        {
          VolumeSides cs = closest_side(obj.obj.volume, other_obj.volume);
          obj.obj.physics_options.constraints |= cs;
        }
      }
    }
  }
예제 #4
0
bool Quadtree::GetObjectsAtMin( list<PartitionObject*>& listOfStuff, float _x, float _y, U32 collisionFlags )
{
	if ( level == maxLevel ) 
	{
		CopyFilterList( objects, listOfStuff, collisionFlags );
		return true;
	}

	float halfX = ( x2+x1 ) * 0.5f;
	float halfY = ( y2+y1 ) * 0.5f;

	Quadtree* childToCopy = NULL;
	if ( _x > halfX && _x < x2 ) 
	{
		if ( _y > halfY && _y < y2 ) 
		{
			childToCopy = SE;
		} 
		else if ( _y > y1 && _y <= halfY ) 
		{
			childToCopy = NE;
		}
	} 
	else if ( _x > x1 && _x <= halfX ) 
	{
		if ( _y > halfY && _y < y2 ) 
		{
			childToCopy = SW;
		} 
		else if ( _y > y1 && _y <= halfY ) 
		{
			childToCopy = NW;
		}
	}

	if( childToCopy )
	{
		return childToCopy->GetObjectsAtMin( listOfStuff, _x, _y, collisionFlags );
	}
	return false;
}
예제 #5
0
int collide(Quadtree * node) {
    int collisions = 0;
    auto shapes = node->getElements();
    for (int k = 0; k < shapes->size(); k++) {
        for (int l = k; ++l < shapes->size(); l++) {
            shapes->at(k)->isColide(*shapes->at(l));
            collisions++;
        }
    }
    Quadtree * parent = node;
    while ((parent = node->getParentNode()) != nullptr) {
        auto parentShapes = parent->getElements();
        for (int k = 0; k < shapes->size(); k++) {
            for (int l = 0; l < parentShapes->size(); l++) {
                shapes->at(k)->isColide(*parentShapes->at(l));
                collisions++;
            }
        }
        
    }
    return collisions;
}
예제 #6
0
  void add_ball_constraints(ModifiedObjectReference& obj,
                            Quadtree& q) noexcept
  {
    for(const auto& node : find_containing_nodes(q.root(), obj.obj.volume))
    {
      for(id_type other_id : node->get_data()->ids)
      {
        if(other_id == obj.id) continue;

        Object& self = obj.obj;

        ModifiedObjectReference other_obj = {other_id,q.find_object(other_id)};
        if(!isBall(other_obj.obj)) continue;
        const Object& other = other_obj.obj;

        if(!intersecting(self.volume, other.volume)) continue;

        VolumeSides cs = closest_side(self.volume, other.volume);
        self.physics_options.constraints |=
                                      other.physics_options.constraints & cs;
      }
    }
  }
예제 #7
0
파일: main.cpp 프로젝트: xunilrj/sandbox
int main(int argv, char** argc)
{
	int i = 0;

	Quadtree<int> tree = {};
	tree.insert({ 00,0 }, i);
	tree.insert({ 10,10 }, i);
	tree.insert({ 20,20 }, i);
	tree.insert({ 25,25 }, i);
	tree.insert({ 26,26 }, i);
	tree.insert({ 27.5,26.5 }, i);

	auto data = tree.queryRange({ { -1,-1 }, { 5, 5 } });
	return 0;
}
예제 #8
0
파일: LoadWorker.cpp 프로젝트: bsmaldon/lag
/*
==================================
 LoadWorker::run()

 Starts the worker.
==================================
*/
void LoadWorker::run()
{
	int num_files = filenames.size();

	// Has a new quadtree been created?
	bool newQuadtree = false;

	try
	{
		// For each file
		for (int i = 0; i < num_files; ++i)
		{
			std::string filename = filenames[i];
			send_message(filename);

			if (filename != "")
			{
				filetype_t file_type = test_filename(filename);

				if (file_type == UNKNOWN_FILE)
				{
					send_message(
							"Unrecognised file type. Supported formats: las, txt, csv.");
					sig_fail();
					return;
				}

				LASreadOpener lasreadopener;

				lasreadopener.set_file_name(filename.c_str());

				// ASCII files
				if (file_type == ASCII_FILE)
				{
					lasreadopener.set_parse_string(ascii_code.c_str());
					if (!use_default_scale_factors)
					{
						lasreadopener.set_scale_factor(scale_factor);
					}
				}

				// Point filter
				if (point_filter.argc != 0)
				{
					std::vector<char*> argv;
					std::transform(point_filter.args.begin(), point_filter.args.end(), std::back_inserter(argv), convert_string);
					argv.push_back(0);

					if (!lasreadopener.parse(point_filter.argc, &argv[0]))
					{
						for (size_t i = 0; i < argv.size(); ++i)
							delete[] argv[i];

						send_message("Error parsing filter parameters.");
						sig_fail();
						return;
					}

					for (size_t i = 0; i < argv.size(); ++i)
						delete[] argv[i];
				}

				reader = lasreadopener.open();

				if (reader == NULL)
				{
					send_message("Error opening the file.");
					sig_fail();
					return;
				}

				// Check if we have a latlong file
				latlong = is_latlong(reader);

				// If we have latlong convert to UTM
				if (latlong)
					convert_projection();

				// Get file boundary
				Boundary boundary = get_boundary();

				fileopener->set_utm_zone(get_utm_zone());

				// If refreshing
				if ((i == 0
						&& (create_new_quadtree
								|| !fileopener->get_loadedanyfiles()))
						|| fileopener->get_lidardata() == NULL)
				{
					// Delete old quadtree
					fileopener->delete_lidardata();

					// Create new quadree
					Quadtree* qt;

					if (!usearea)
						qt = new Quadtree(&boundary, bucketlimit, cachelimit,
								bucketLevels, resolutionbase, resolutiondepth, cache_path);
					else
					{
						qt = new Quadtree(fence.get_min_x(), fence.get_min_y(),
								fence.get_max_x(), fence.get_max_y(),
								bucketlimit, cachelimit, bucketLevels,
								resolutionbase, resolutiondepth, cache_path);
					}

					// Load points
					int points_loaded = 0;
					if (has_waveform(reader))
						points_loaded = load_points_wf(qt);
					else
						points_loaded = load_points(qt);

					// Add flightline to quadtree's flight table
					qt->addFlightline(filename);

					if (points_loaded == 0)
					{
						std::cout
								<< "LoadWorker: "
								<< filename
								<< " - no points loaded from file. Possibly because of fence."
								<< std::endl;
					}

					// Set lidardata
					fileopener->set_lidardata(qt);

					newQuadtree = true;
					qt = NULL;
				}
				else
				{
					Quadtree* qt = fileopener->get_lidardata();

					// Adjust boundary
					if (!usearea)
						qt->adjustBoundary(boundary);

					// Load points
					int points_loaded = 0;
					if (has_waveform(reader))
						points_loaded = load_points_wf(qt);
					else
						points_loaded = load_points(qt);

					qt->addFlightline(filename);

					if (points_loaded == 0)
					{
						std::cout
								<< "LoadWorker: "
								<< filename
								<< " - no points loaded from file. Possibly because of fence."
								<< std::endl;
					}

					qt = NULL;
				}

				if (reader->header.min_z < fileopener->get_minZ() || i == 0)
					fileopener->set_minZ(reader->header.min_z);
				if (reader->header.max_z > fileopener->get_maxZ() || i == 0)
					fileopener->set_maxZ(reader->header.max_z);
			}
			sig_file_loaded();
			if (stopped)
				break;
		}
	} catch (DescriptiveException& e)
	{
		if (reproject_quantizer)
			delete reproject_quantizer;
		if (saved_quantizer)
			delete saved_quantizer;

		std::cout << "LoadWorker: Error loading file.\n";
		std::cout << e.what() << "\n" << e.why() << std::endl;
		send_message(e.why());

		fileopener->delete_lidardata();

		fileopener->set_loadedanyfiles(false);
		newQuadtree = false;

		sig_fail();

		return;
	}

	// Delete quantizers somewhere
	if (latlong)
	{
		delete reproject_quantizer;
		delete saved_quantizer;
	}

	fileopener->set_newQuadtree(newQuadtree);
	sig_done();
}
예제 #9
0
#include "easypng.h"
#include "proxy.h"
#include "quadtree.h"

using namespace std;
using namespace util;

#if MP_PART(1)

// test constructor, decompress
UNIT_TEST(test_outHalf, 5, 2, 1000)
{
	PNG imgIn("in.png");

	Quadtree halfTree(imgIn, 128);
	PNG imgOut = halfTree.decompress();

	PNG imgSoln("soln_outHalf.png");
	ASSERT(imgOut == imgSoln);
	PASS;
}

#endif

#if MP_PART(2)

UNIT_TEST(test_pruneSize, 0, 1, 1000)
{
	PNG imgIn("in.png");
	Quadtree fullTree;
예제 #10
0
int main(){
	Quadtree<Point,int> quadtree;

	Point p(3,3);
	p.schrijf(cout);
	cout<<"-------------------Starten van de testen-------------------"<<endl;
	quadtree.voegToe(p,11);
	quadtree.schrijf(cout);
	Quadtree<Point,int>* res = quadtree.zoek(p);
	if(res == nullptr){
		cout<<"nullptr res"<<endl;
	}
	cout<<"Ik ga het resultaat uitschrijven van de zoekfunctie: ";
	res->get()->punt.schrijf(cout);
	cout<<"-------------------Vergelijken van punt testen-------------------"<<endl;
	Point p2(2,3);
	cout<<"kleiner dan? "<<(p<p2)<<endl;
	Quadtree<Point,int>* res2 = quadtree.zoek(p2);
	if(res2->get() == nullptr){
		cout<<"nullptr res"<<endl;
	}else{
		cout<<"Ik ga het resultaat uitschrijven van de zoekfunctie: ";
		res2->get()->punt.schrijf(cout);	
	}
	cout<<"-------------------Testen van toevoegen-------------------"<<endl;
	Point p3(4,4);
	bool res4  = quadtree.voegToe(p3, 12);
	cout<< (res4 ? "Toegevoegd" : "Niet toegevoegd")<<endl;
	quadtree.schrijf(cout);
	
	cout<<"-------------------Testen van diepte in een boom-------------------"<<endl;
	int resultaat  = quadtree.diepte();
	cout<<"diepte van de boom is: "<<resultaat<<endl;


	cout<<"-------------------Testen van diepte op spiraal-------------------"<<endl;
	CsvData grafiek("dieptedata1",'.');
    vector<double> dieptedata;

	Quadtree<Point,int> testquadtree;
	vector<Point> punten;
	int grens = 200;
	for(int i=0; i<grens; i++){
		int x = i;
		int y = ( (10000-5*i)* cos(i*0.25*M_PI), (10000-5*i)* sin(i*0.25*M_PI) );
		Point punt(x,y);
		punten.push_back(punt);
		bool gelukt = testquadtree.voegToe(punt, i*20);
		double diepte = testquadtree.diepte();
		cout<<diepte<<endl;
		dieptedata.push_back(diepte);
	}
	grafiek.voegDataToe(dieptedata);

	cout<<"-------------------Testen van diepte op spiraal(randomized)-------------------"<<endl;

	Quadtree<Point,int> testquadtree2;
    vector<double> dieptedata2;

	auto engine = std::default_random_engine{};
	std::shuffle(std::begin(punten), std::end(punten), engine);
	for(int i=0; i<grens; i++){
		bool gelukt = testquadtree2.voegToe(punten[i], i*20);
		double diepte = testquadtree2.diepte();
		cout<<diepte<<endl;
		dieptedata2.push_back(diepte);
	}
	grafiek.voegDataToe(dieptedata2);

	
	
	return 0;
}
int main(int argc, char* argv[])
{
/*	MyPoint a(0.0, 0.0);
	MyPoint b(1.0, 0.0);
	MyPoint c(1.0, 1.0);
//	MyPoint d(0.1, 0.0999999999999999);
//	MyPoint d(0.1, 0.1);
	MyPoint d(0.1, 0.1000000000000001);
	
	Triangle<MyPoint> t1;
	t1.set_point(0, a);
	t1.set_point(1, b);
	t1.set_point(2, c);
	
	std::cout << std::endl;
	std::cout << "Triangle" << std::endl;
	std::cout << std::boolalpha << t1.is_left_system() << std::endl;
	std::cout << t1.area_size() << std::endl;
	std::cout << t1.contains(d) << std::endl;
	
	MyPoint e(0.0, 1.0);
	Quadrangle<MyPoint> q;
	q.set_point(0, a);
	q.set_point(1, c);
	q.set_point(2, b);
	q.set_point(3, e);
	
	std::cout << std::endl;
	std::cout << "Quadrangle" << std::endl;
	std::cout << q.area_size() << std::endl;
	std::cout << q.contains(d) << std::endl;
*/	
	GeoCoordinate lower_left;
	lower_left[0] = 0.0;
	lower_left[1] = 0.0;

	GeoCoordinate upper_right;
	upper_right[0] = 1.0;
	upper_right[1] = 1.0;
	
	
	AxisParallelRectangle<GeoCoordinate> rectangle;
	rectangle.set_point(0, lower_left);
	rectangle.set_point(1, upper_right);
	rectangle.validate_corners();
	
	std::cout << "Set span rectangle." << std::endl;
	
	int nodes = 10;
	try
	{
		if (argc > 1)
			nodes = atoi(argv[1]);
	} catch (std::exception e)
	{};
	
	std::cout << "Read #numbers: " << nodes << std::endl;
	
	Quadtree<GeoCoordinate> quadtree;
	quadtree.set_span_rectangle(rectangle);
	quadtree.set_max_depth(3);
	srand(0);
	
	std::cout << "Inited Quadtree" << std::endl;
	
	
	for (int i = 0; i < nodes; ++i)
	{
		GeoCoordinate a;
		a[0] = (static_cast<double>(rand()) / static_cast<double>(RAND_MAX));
		a[1] = (static_cast<double>(rand()) / static_cast<double>(RAND_MAX));
		quadtree.add_point(a);
	}
	
	for (int i = 0; i < nodes; i += 1)
		quadtree.move_point(i, GeoCoordinate(0.1, 0.1));
	
	quadtree.move_point(0, GeoCoordinate(0.5, 0.5));
	
	std::cout << quadtree << std::endl;
	
	std::vector< Quadtree<GeoCoordinate>::D_IndexType > results;
	AxisParallelRectangle<GeoCoordinate> qr;
	qr.set_point(0, GeoCoordinate(0.4, 0.4));
	qr.set_point(1, GeoCoordinate(0.6, 0.6));
	qr.validate_corners();
	
	quadtree.range_query(qr, results);
	
	std::cout << "Query result: size=" << results.size() << std::endl;
	std::vector< Quadtree<GeoCoordinate>::D_IndexType >::const_iterator iter = results.begin();
	std::vector< Quadtree<GeoCoordinate>::D_IndexType >::const_iterator iter_end = results.end();
	for (; iter != iter_end; ++iter)
	{
		std::cout << *iter << ", ";
	}
	std::cout << std::endl;
/*	for (int i = 0; i < nodes; ++i)
	{
		GeoCoordinate a;
		a[0] = (static_cast<double>(rand()) / static_cast<double>(RAND_MAX));
		a[1] = (static_cast<double>(rand()) / static_cast<double>(RAND_MAX));
		quadtree.add_point(a);
	}
	std::cout << "Added nodes" << std::endl;
	
	for (int i = 100; i < 500; i += 7)
		quadtree.remove_point(i);
	
	
	for (int i = 0; i < 10000; ++i)
	{
		GeoCoordinate a;
		a[0] = (static_cast<double>(rand()) / static_cast<double>(RAND_MAX));
		a[1] = (static_cast<double>(rand()) / static_cast<double>(RAND_MAX));
		
		double some_random_value
			= static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
		double sign = (some_random_value < 0.5 ? -1.0 : 1.0);
		
		GeoCoordinate b;
		b[0] = a[0] + (sign * 0.05);
		b[1] = a[1] + (sign * 0.0125);
		
		GeoCoordinate c;
		c[0] = a[0] - (sign * 0.025);
		c[1] = a[1] + (sign * 0.025);
	
		GeoCoordinate d;
		d[0] = a[0] + (sign * 0.025);
		d[1] = a[1] + (sign * 0.0375);
		
		Trapezoid<GeoCoordinate> query_trapezoid(a, b, c, d);
		
		std::vector< Quadtree<GeoCoordinate>::D_IndexType > result;
		quadtree.range_query(query_trapezoid, result);
		
//		std::cout << result.size() << "  ";
	}
	std::cout << "Made 10000 queries." << std::endl;
	
	for (int i = 0 ; i < 1000; ++i)
	{
		GeoCoordinate a;
		a[0] = (static_cast<double>(rand()) / static_cast<double>(RAND_MAX));
		a[1] = (static_cast<double>(rand()) / static_cast<double>(RAND_MAX));
		
		double some_random_value
			= static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
		double sign = (some_random_value < 0.5 ? -1.0 : 1.0);
		
		GeoCoordinate b;
		b[0] = a[0] + (sign * 0.01);
		b[1] = a[1] + (sign * 0.01);
		
		Rectangle<GeoCoordinate> query_rectangle;
		query_rectangle.set_corners(a, b);
		
		std::vector< Quadtree<GeoCoordinate>::D_IndexType > result;
		quadtree.range_query(query_rectangle, result);
		
		if (result.size() > 0)
		{
			GeoCoordinate c;
			some_random_value
				= static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
			if (some_random_value < 0.5 )
			{
				c[0] = a[0] + 0.001;
				c[1] = a[1] + 0.001;
			} else
			{
				c[0] = a[0] + 0.1;
				c[1] = a[1] + 0.1;
			}
				
			bool move_result = quadtree.move_point(result.front(), c);
			if (!move_result)
				std::cout << "Out of range: " << c << std::endl;
		}
	}
	
	std::cout << std::endl;
*/	
	return 0;
}
예제 #12
0
파일: main.cpp 프로젝트: irtefa/dumbshit
int main() {

   PNG imgIn, imgOut;
   imgIn.readFromFile("in.png");

   // test constructor, decompress
   Quadtree halfTree(imgIn, 128);
   imgOut = halfTree.decompress();
   imgOut.writeToFile("outHalf.png");

   // now for the real tests
   Quadtree fullTree;
   fullTree.buildTree(imgIn, 256);

   // you may want to experiment with different commands in this section

   // test pruneSize and idealPrune (slow in valgrind, so you may want to
   // comment these out when doing most of your testing for memory leaks)
   cout << "fullTree.pruneSize(0) = " << fullTree.pruneSize(0) << endl;
   cout << "fullTree.pruneSize(100) = " << fullTree.pruneSize(100) << endl;
   cout << "fullTree.pruneSize(1000) = " << fullTree.pruneSize(1000) << endl;
   cout << "fullTree.pruneSize(100000) = " << fullTree.pruneSize(100000) << endl;

   cout << "fullTree.idealPrune(1000) = "  << fullTree.idealPrune(1000) << endl;
   cout << "fullTree.idealPrune(10000) = " << fullTree.idealPrune(10000) << endl;


   // Test some creation/deletion functions
   Quadtree fullTree2;
   fullTree2 = fullTree;
   imgOut = fullTree2.decompress();
   imgOut.writeToFile("outCopy.png");


   //test clockwiseRotate
   fullTree.clockwiseRotate();
   imgOut = fullTree.decompress();
   imgOut.writeToFile("outRotated.png");


   // test prune
   fullTree = fullTree2;
   fullTree.prune(1000);
   imgOut = fullTree.decompress();
   imgOut.writeToFile("outPruned.png");


   // test several functions in succession
   Quadtree fullTree3(fullTree2);
   fullTree3.clockwiseRotate();
   fullTree3.prune(10000);
   fullTree3.clockwiseRotate();
   fullTree3.clockwiseRotate();
   fullTree3.clockwiseRotate();
   imgOut = fullTree3.decompress();
   imgOut.writeToFile("outEtc.png");

   // ensure that printTree still works
   Quadtree tinyTree(imgIn, 32);
   cout << "Printing tinyTree:\n";
   tinyTree.prune(100);
   tinyTree.printTree();

   return 0;
}
예제 #13
0
파일: main.cpp 프로젝트: leloulight/cs225
int main() {

   BMP imgIn, imgOut,soln_img;
   imgIn.ReadFromFile("in.bmp");

	//print soln
	soln_img.ReadFromFile("soln_outPruned.bmp");
	Quadtree soln_tree(soln_img,128);
//	soln_tree.printTree();





   // test constructor, decompress
   Quadtree halfTree(imgIn,128);
   imgOut = halfTree.decompress();
/*	cout<<endl<<endl;
	for(int y=0;y<8;y++){
		for(int x=0;x<8;x++){
			cout<<(int)imgIn(x,y)->Red<<","<<(int)imgIn(x,y)->Green<<","<<(int)imgIn(x,y)->Blue;
			if (x%8==0)
				cout<<endl;
			else
				cout<<"||";
		}
	}
	cout<<endl;
*/
   imgOut.WriteToFile("outHalf.bmp");

   // now for the real tests
   Quadtree fullTree;
   fullTree.buildTree(imgIn, 256);
   // you may want to experiment with different commands in this section

   // test pruneSize and idealPrune (slow in valgrind, so you may want to
   // comment these out when doing most of your testing for memory leaks)
   cout << "fullTree.pruneSize(0) = " << fullTree.pruneSize(0) << endl;
   cout << "fullTree.pruneSize(100) = " << fullTree.pruneSize(100) << endl;
   cout << "fullTree.pruneSize(1000) = " << fullTree.pruneSize(1000) << endl;
   cout << "fullTree.pruneSize(100000) = " << fullTree.pruneSize(100000) << endl;

   cout << "fullTree.idealPrune(1000) = "  << fullTree.idealPrune(1000) << endl;
   cout << "fullTree.idealPrune(10000) = " << fullTree.idealPrune(10000) << endl;
   cout << "fullTree.idealPrune(449) = "  << fullTree.idealPrune(1000) << endl;

/*
   // Test some creation/deletion functions
	  Quadtree fullTree2;
	  fullTree2 = fullTree;
	  imgOut = fullTree2.decompress();
//   imgOut = fullTree.decompress();
     imgOut.WriteToFile("outCopy.bmp");


   // test clockwiseRotate
   fullTree.clockwiseRotate();
   imgOut = fullTree.decompress();
   imgOut.WriteToFile("outRotated.bmp");


   // test prune
	fullTree = fullTree2;
   fullTree.prune(1000);
//	fullTree.printTree();
	imgOut = fullTree.decompress();
   Quadtree prunetree(imgOut,128);
//	prunetree.printTree();
	imgOut.WriteToFile("outPruned.bmp");


   // test several functions in succession
   Quadtree fullTree3(fullTree2);
   fullTree3.clockwiseRotate();
   fullTree3.prune(10000);
   fullTree3.clockwiseRotate();
   fullTree3.clockwiseRotate();
   fullTree3.clockwiseRotate();
   imgOut = fullTree3.decompress();
   imgOut.WriteToFile("outEtc.bmp");

   // ensure that printTree still works
   Quadtree tinyTree(imgIn, 32);
   cout << "Printing tinyTree:\n";
   tinyTree.prune(100);
   tinyTree.printTree();
*/
   return 0;
}
예제 #14
0
int main()
{
    sf::RenderWindow* window = new sf::RenderWindow(sf::VideoMode(1920, 1080), "Proto Movement & Grabity", sf::Style::Default);
    window->setFramerateLimit(60);

    //Creation d'un personnage
    Character* player = new Character("player.png");
    Quadtree* world = new Quadtree(0.0f,0.0f,window->getSize().x,window->getSize().y);

    //Pour la creation de case random
    srand(time(NULL));
    bool m_add = true;

    sf::Texture txt;
    if(!txt.loadFromFile(defaultTilePath+"Tileset.png")){
        //RAISE A LOAD TEXTURE EXCEPTION
    }
    while (window->isOpen())
    {
        // On catch les events
        sf::Event event;
        while (window->pollEvent(event))
        {
            switch(event.type)
            {
                case sf::Event::Closed :
                    window->close();
                    break;
                case sf::Event::KeyPressed :
                    {
                        switch(event.key.code)
                        {
                            case sf::Keyboard::Escape :
                                window->close();
                                break;
                            case sf::Keyboard::J :
                                {
                                    sf::Sprite spr;
                                    spr.setTexture(txt);
                                    spr.setTextureRect(sf::IntRect(416,192,SPRITE_HEIGHT,SPRITE_WIDTH));
                                    spr.setPosition(rand()%window->getSize().x,rand()%window->getSize().y);
                                    world->add(spr);
                                }
                                break;
                            case sf::Keyboard::K :
                                {
                                    if(world->isDisplayTile()) {
                                        world->displayTile(false);
                                    } else
                                    {
                                        world->displayTile(true);
                                    }
                                }
                                break;
                            case sf::Keyboard::C :
                                world->clear();
                                break;
                            case sf::Keyboard::A :
                                (m_add)?m_add = false:m_add = true;
                                break;
                            case sf::Keyboard::P :
                                std::cout << "/WARNING\\ Delete world !" << std::endl;
                                delete world;
                                std::cout << "WORLD DELETE" << std::endl;
                                world = new Quadtree(0.0f,0.0f,window->getSize().x,window->getSize().y);
                                std::cout << "New world create" << std::endl;
                                break;
                            default :
                                break;
                        }
                    }
                    break;
                case sf::Event::MouseButtonPressed :
                    {
                        switch(event.mouseButton.button)
                        {
                        case sf::Mouse::Left :
                            {
                                if(m_add)
                                {
                                    sf::Sprite spr;
                                    spr.setTexture(txt);
                                    spr.setTextureRect(sf::IntRect(416,192,SPRITE_HEIGHT,SPRITE_WIDTH));
                                    spr.setPosition(sf::Vector2f(sf::Mouse::getPosition(*window).x,sf::Mouse::getPosition(*window).y));
                                    world->add(spr);
                                } else
                                {
                                    std::vector<std::shared_ptr<sf::Sprite>> deletedObject =  world->del(sf::FloatRect(sf::Mouse::getPosition(*window).x,sf::Mouse::getPosition(*window).y,32,32));
                                    std::cout << "Deleted object : " << std::endl;
                                    for(std::vector<std::shared_ptr<sf::Sprite>>::iterator it = deletedObject.begin(); it != deletedObject.end(); it++)
                                    {
                                        std::cout << "Tile at [x=" << (*it)->getPosition().x << ";y=" << (*it)->getPosition().y << std::endl;
                                    }
                                    deletedObject.clear();
                                }
                            }
                            break;
                        case sf::Mouse::Right:
                            {
                                std::vector<std::shared_ptr<sf::Sprite>> query = world->queryRange(sf::FloatRect(sf::Mouse::getPosition(*window).x,sf::Mouse::getPosition(*window).y,32,32));
                                std::cout << "*---------*" << std::endl;
                                std::cout << "*  QUERY  *" << std::endl;
                                std::cout << "*---------*" << std::endl;
                                if(query.size() > 0)
                                {
                                    std::cout << "Il y a " << query.size() << " dans ce quadrant" << std::endl;
                                    for(std::vector<std::shared_ptr<sf::Sprite>>::iterator it = query.begin(); it != query.end(); it++)
                                    {
                                        std::cout << "Tile at [x=" << (*it)->getGlobalBounds().top << ":y=" << (*it)->getGlobalBounds().left << "]" << std::endl;
                                    }
                                } else
                                {
                                    std::cout << "Aucun tile dans le quadrant" << std::endl;
                                }
                                //delete query;
                                std::cout << "*-------------*" << std::endl;
                                std::cout << "*  FIN QUERY  *" << std::endl;
                                std::cout << "*-------------*" << std::endl;
                            }
                            break;
                        default:
                            break;
                        }
                    }
                    break;
                default :
                    break;
            }
        }

        // On gère les event clavier hors du catch pour permettre la fluidite des deplacements
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::D))
        {
            player->move(sf::Vector2f(5,0),world);
        }

        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Q))
        {
            player->move(sf::Vector2f(-5,0),world);
        }

        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space))
        {
            player->move(sf::Vector2f(0,-5),world);
        }

        if(sf::Keyboard::isKeyPressed(sf::Keyboard::S))
        {
            player->move(sf::Vector2f(0,5),world);
        }


        window->clear();
        player->draw(window);
        world->draw(window);
        window->display();
    }

    delete player;
    delete world;
    delete window;
    return 0;
}