Esempio n. 1
1
        bool insert(T newData, float x, float y)
        {
            //std::cout << "["<< depth <<"] " << newData << " at " << x << " , " << y << " \n";
            //Make sure point is within the bounds of this node
            if (!isPointInRange(x, y, bounds))
            {
                //std::cout << "point not in bounds\n";
                //Point is not within bounds
                return false;
            }
            
            //Node isn't full yet, so add data to this node
            if (!tL && data.size() < maxCapacity)
            {
                QuadPoint<T> newPoint;
                newPoint.x = x;
                newPoint.y = y;
                newPoint.data = newData;
                data.push_back(newPoint);
                return true;
            }

            //Safety max depth
            if (depth >= MAX_TREE_DEPTH)
            {
                std::cout << "\033[31mWARNING: Max tree depth (" << MAX_TREE_DEPTH << ") reached!\033[0m\n";
                //return false;
            }
            
            //Node is full; subdivide (if not already subdivided)
            if (!tL)
            {
                subdivide();
                /*if (tL->subdivideInsert(newData, x, y)) return true;
                if (tR->subdivideInsert(newData, x, y)) return true;
                if (bL->subdivideInsert(newData, x, y)) return true;
                if (bR->subdivideInsert(newData, x, y)) return true;
                //Point wouldn't be accepted by any nodes
                //std::cout <<"point rejected; keeping\n";
                QuadPoint<T> newPoint;
                newPoint.x = x;
                newPoint.y = y;
                newPoint.data = newData;
                data.push_back(newPoint);
                return true;*/
            }

            //If already subdivided, try inserting into child nodes
            if (tL->insert(newData, x, y)) return true;
            if (tR->insert(newData, x, y)) return true;
            if (bL->insert(newData, x, y)) return true;
            if (bR->insert(newData, x, y)) return true;
            //Shouldn't ever happen
            //std::cout << "This shouldn't happen\n";
            return false;
        }
Esempio n. 2
0
// Evaluate t-SNE cost function (approximately)
double TSNE::evaluateError(int* row_P, int* col_P, double* val_P, double* Y, int N, double theta)
{
    
    // Get estimate of normalization term
    const int QT_NO_DIMS = 2;
    QuadTree* tree = new QuadTree(Y, N);
    double buff[QT_NO_DIMS] = {.0, .0};
    double sum_Q = .0;
    for(int n = 0; n < N; n++) tree->computeNonEdgeForces(n, theta, buff, &sum_Q);
    
    // Loop over all edges to compute t-SNE error
    int ind1, ind2;
    double C = .0, Q;
    for(int n = 0; n < N; n++) {
        ind1 = n * QT_NO_DIMS;
        for(int i = row_P[n]; i < row_P[n + 1]; i++) {
            Q = .0;
            ind2 = col_P[i] * QT_NO_DIMS;
            for(int d = 0; d < QT_NO_DIMS; d++) buff[d]  = Y[ind1 + d];
            for(int d = 0; d < QT_NO_DIMS; d++) buff[d] -= Y[ind2 + d];
            for(int d = 0; d < QT_NO_DIMS; d++) Q += buff[d] * buff[d];
            Q = (1.0 / (1.0 + Q)) / sum_Q;
            C += val_P[i] * log((val_P[i] + FLT_MIN) / (Q + FLT_MIN));
        }
    }
    return C;
}
Esempio n. 3
0
        //Fills the provided vector with resultant points (points
        //contained in the specified range). Returns total results
        unsigned int queryRange(aabb& range, std::vector<T>& results)
        {
            //std::cout << bounds.x << " , " << bounds.y << " w " << bounds.w << " h " << bounds.h << " \n";
            unsigned int totalResults = 0;
            //Make sure range is touching this node
            if (!isColliding(&range, &bounds))
            {
                return 0;
            }
            
            //Add points in this node to results if contained in range
            for (typename std::list<QuadPoint<T> >::iterator it = data.begin(); it!=data.end(); ++it)
            {
                //std::cout << "has point\n";
                if (isPointInRange((*it).x, (*it).y, range))
                {
                    results.push_back((*it).data);
                    totalResults++;
                }
            }

            //Let all child nodes (if any) add points
            if (!tL)
            {
                return totalResults;
            }
            totalResults += tL->queryRange(range, results);
            totalResults += tR->queryRange(range, results);
            totalResults += bL->queryRange(range, results);
            totalResults += bR->queryRange(range, results);
            
            return totalResults;
        }
Esempio n. 4
0
int main()
{
    testDivision();

    length_type MAP_SIZE = length_type(64.f * 533.333f);

    Point center = {MAP_SIZE/2, MAP_SIZE/2};
    QuadTree * tree = QuadTree::create(8, center, MAP_SIZE);
    if (!tree)
        return 0;

    tree->debugSelf();

    Circle c = {MAP_SIZE/2, MAP_SIZE/2, 1};
    TreeVisitor visitor = {tree};
    AABox2d box(AABox2d::create(c));
    tree->intersectRecursive(box, visitor);
    tree->intersect(box, visitor);



    QuadIterator it = tree->deepestContaining(AABox2d::create(c));

    _getch();
    return 0;
}
Esempio n. 5
0
bool SpaceShipBeam::Update(float dt, QuadTree& tree)
{
	glm::vec3 dir(-sin(m_dir * 3.14f / 180.0f),cos(m_dir * 3.14f / 180.0f),0.0f);
	m_pos += dir * m_speed * dt;
	m_age += dt;

	tree.Erase(*this);
	m_collisionPoly.GetCircle().center = glm::vec2(m_pos.x,m_pos.y);
	tree.Insert(*this);

	std::vector<ISpatialObject*> nearObj;
	tree.QueryNearObjects(this,nearObj);

	for(unsigned int i = 0; i < nearObj.size(); ++i)
	{
		void* pInterface = nearObj[i]->QueryInterface(IDestroyable::INTERFACE_DESTROY);
		void* pBeam = nearObj[i]->QueryInterface(SpaceShipBeam::INTERFACE_BEAM);

		if(pInterface != nullptr && pBeam == nullptr)
		{
			IDestroyable* pDestroyable = static_cast<IDestroyable*>(pInterface);
			pDestroyable->Destroy();
			m_bDestroyed = true;
		}
	}

	m_animation.Update(dt);

	return m_bDestroyed || m_age > 1.5f;
}
Esempio n. 6
0
void gameMap::Draw(QuadTree<bool> &bw, int x, int y, int w, int h, const fsRendererGL& renderer)
{
    if (bw.object() == false)
    {
        if (bw.layers() == 0)
            return;
        Draw(bw[1](0, 0),  x,         y,         w / 2, h / 2, renderer);
        Draw(bw[1](1, 0), x + w / 2, y,         w / 2, h / 2, renderer);
        Draw(bw[1](0, 1),  x,         y + h / 2, w / 2, h / 2, renderer);
        Draw(bw[1](1, 1), x + w / 2, y + h / 2, w / 2, h / 2 , renderer);
    }
    else
    {
        SDL_Rect r;
        r.x = x + 1;
        r.y = y + 1;
        r.w = w - 1;
        r.h = h - 1;
        SDL_FillRect(SDL_GetVideoSurface(), &r, 0x00CCAA77);
        
        renderer.setColor( c_black );
        renderer.setAlpha( .6 );
        renderer.renderRect(x,y,x+w,y+h);
        renderer.setAlpha( .2 );
        renderer.renderRectFill(x,y,x+w,y+h);
    }
}
Esempio n. 7
0
void QuadTree::GetEntinCell(Entity* _Ent, set<Entity*> *list){

	Global->count++;

	if (Type == STEM){
		//TOP LEFT
		QuadTree* QT = children[0]; 
		if (QT->max.x > _Ent->min.x && QT->max.y > _Ent->min.y){
			QT->GetEntinCell(_Ent, list);
		}
			
		//TOP RIGHT
		QT = children[1]; 
		if (QT->min.x < _Ent->max.x && QT->max.y > _Ent->min.y){
			QT->GetEntinCell(_Ent, list);
		}

		//BOTTOM LEFT
		QT = children[2]; 
		if (QT->max.x > _Ent->min.x && QT->min.y < _Ent->max.y){
			QT->GetEntinCell(_Ent, list);
		}

		//BOTTOM RIGHT
		QT = children[3];
		if (QT->min.x < _Ent->max.x && QT->min.y < _Ent->max.y){
			QT->GetEntinCell(_Ent, list);
		}
	}else{
		FOREACH(Entity*,Entlist,a)
			list->insert((*a));
	}
}
Esempio n. 8
0
QuadTree* QuadTree::AddEntity(Entity* _Ent){  //Most basic quadtree adding, alot more complicated/better ones exist, thou i don't know them
	Drawn=false;
	//Check if its a leaf or stem
	if (Type == STEM){
		//TOP LEFT
		QuadTree* QT = children[0]; 
		if (QT->max.x > _Ent->min.x && QT->max.y > _Ent->min.y){
			QT->AddEntity(_Ent);
		}
			
		//TOP RIGHT
		QT = children[1]; 
		if (QT->min.x < _Ent->max.x && QT->max.y > _Ent->min.y){
			QT->AddEntity(_Ent);
		}

		//BOTTOM LEFT
		QT = children[2]; 
		if (QT->max.x > _Ent->min.x && QT->min.y < _Ent->max.y){
			QT->AddEntity(_Ent);
		}

		//BOTTOM RIGHT
		QT = children[3];
		if (QT->min.x < _Ent->max.x && QT->min.y < _Ent->max.y){
			QT->AddEntity(_Ent);
		}

	}else{
		Entlist.push_back(_Ent);
		return NULL;
	}
	return NULL;
}
Esempio n. 9
0
void	QuadTree::collide(QuadTree const &quadTree, QuadTree::callInfo call) const
{
	Node *node;
	Node *node2;

	if (call == QuadTree::ALL)
	{
		for (Elements::const_iterator it = this->_mainNode->getElements().begin();
			it != this->_mainNode->getElements().end(); ++it)
			quadTree.collideBranches(**it, QuadTree::ALL);
	}
	else
	{
		for (Elements::const_iterator it = this->_mainNode->getElements().begin();
			it != this->_mainNode->getElements().end(); ++it)
			quadTree.collide(**it, static_cast<QuadTree::callInfo>(QuadTree::ALL & (~call)));
	}
	for (Elements::const_iterator it = quadTree._mainNode->getElements().begin();
		it != quadTree._mainNode->getElements().end(); ++it)
		this->collide(**it, call);
	for (int i = 0; i < 4; ++i)
	{
		node = this->_mainNode->getChilds()[i];
		node2 = quadTree._mainNode->getChilds()[i];
		if (node && node2 && this->collideRect(node->getX(), node->getY(), node->getSize(), node->getSize(),
			node2->getX(), node2->getY(), node2->getSize(), node2->getSize()))
			this->collideNodes(node, node2, call);
	}
}
Esempio n. 10
0
bool QuadTree::Delete(Sprite* obj){
	if(0 == this->Count())
		return( false ); // No objects to delete.

	if(!Contains(obj->GetWorldPosition()))
		return( false ); // Out of bounds, nothing to delete.

	if(!isLeaf){ // Node
		QuadTree* dest = subtrees[SubTreeThatContains( obj->GetWorldPosition() )];
		if(dest==NULL)
			return( false ); // That branch is empty, nothing to delete.
		if( dest->Delete(obj) ){
			isDirty=true;
			objectcount--;
			return( true ); // Found that object.
		} else {
			return( false ); // Didn't find that object.
		}
	} else { // Leaf
		list<Sprite *>::iterator i = std::find( objects->begin(), objects->end(), obj);
		if(i != objects->end())
		{
			i = objects->erase( i );
			// Note that leaves don't ReBallance on delete.
			objectcount--;
			return( true );
		} else {
			return( false );
		}
	}
}
Esempio n. 11
0
vec2 Terrain::LoadVertices(
	const QuadTree<TerrainNode>::Iterator& node, 
	const Image& hmap
	)
{
	//Setup vertex data
	vec2 res = vec2(1.0f, 0.0f);
	int verticesCount = (lodResolution + 1) * (lodResolution + 1);
	vector<vec3> vertices(verticesCount), colors(verticesCount);
	float deltaX = 1.0f / node.LayerSize() / lodResolution;
	float deltaY = 1.0f / node.LayerSize() / lodResolution;
	float x = node.OffsetFloat().x;
	for (int i = 0; i <= lodResolution; i++, x += deltaX)
	{
		float y = node.OffsetFloat().y;
		for (int j = 0; j <= lodResolution; j++, y += deltaY)
		{
			float h = hmap[vec2(x, y)].x;
			res = UniteSegments(res, vec2(h));

			vertices[i*lodResolution + i + j] = vec3(x, h, y);
			colors[i*lodResolution + i + j] = vec3(0.2f, 0.2f + h, 0.4f - h);
		}
	}

	// VAO allocation
	glGenVertexArrays(1, &node->vaoID);
	// VAO setup
	glBindVertexArray(node->vaoID);
	// VBOs allocation
	glGenBuffers(2, node->vboID);
	// VBOs setup
	// vertices buffer
	glBindBuffer(GL_ARRAY_BUFFER, node->vboID[0]);
	glBufferData(GL_ARRAY_BUFFER, vertices.size() * 3 * sizeof(GLfloat), vertices.data(), GL_STATIC_DRAW);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);
	glEnableVertexAttribArray(0);
	// colors buffer
	glBindBuffer(GL_ARRAY_BUFFER, node->vboID[1]);
	glBufferData(GL_ARRAY_BUFFER, colors.size() * 3 * sizeof(GLfloat), colors.data(), GL_STATIC_DRAW);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);
	glEnableVertexAttribArray(1);
	// indices buffer
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, GetIndicesBufferID());

	OPENGL_CHECK_FOR_ERRORS();
	// release vertex data
	vertices.clear();
	colors.clear();

	if (node.Level() < maxLOD)
	{
        for (int i : {0, 1, 2, 3})
            res = UniteSegments(res, LoadVertices(node.Add(i), hmap));
	}
	node->heights = res;

	return res;
}
Esempio n. 12
0
void
GameBoard::MarkAlive(const CellSet& cells,
                     QuadTree& tree) {
  tree.Clear();
  for (CellSet::iterator it = cells.begin();
       it != cells.end(); ++it) {
    tree.Insert(*it);
  } 
}
Esempio n. 13
0
void GLrender()
{
	glClear(GL_COLOR_BUFFER_BIT);
	lines = quadtree.query(Point2D(me.c.p.x,me.c.p.y),me.c);
	quadtree.render();
  me.c.render(col);
	glFlush();	
	glutSwapBuffers();
}
Esempio n. 14
0
int main()
{
    string fichier;
    ImagePNG originale,compressee;
    QuadTree arbre;

 //   fichier = "i.png";
  //  originale.charger(fichier);

/*    cout << endl << "-------------------------------------------------" << endl;
    cout << "Original :" << endl;
    arbre.importer(originale);
    arbre.afficher();


    cout << endl << "-------------------------------------------------" << endl;
    cout << "Sans perte :" << endl;
    arbre.importer(originale);
    arbre.compressionDelta(0);
    arbre.afficher();
    compressee = arbre.exporter();
    compressee.sauver("zip-d000-"+fichier);

    cout << endl << "-------------------------------------------------" << endl;
    cout << "Delta=128 :" << endl;
    arbre.importer(originale);
    arbre.compressionDelta(128);
    arbre.afficher();
    compressee = arbre.exporter();
    compressee.sauver("zip-d128-"+fichier);

    cout << endl << "-------------------------------------------------" << endl;
    cout << "Phi=4 :" << endl;
    arbre.importer(originale);
    arbre.compressionPhi(4);
    arbre.afficher();
    compressee = arbre.exporter();
    compressee.sauver("zip-p004-"+fichier);
    
    cout << endl << "-------------------------------------------------" << endl;
    cout << "Phi=1 :" << endl;
    arbre.importer(originale);
    arbre.compressionPhi(1);
    arbre.afficher();
    compressee = arbre.exporter();
    compressee.sauver("zip-p001-"+fichier);
*/    
        cout << endl << "-------------------------------------------------" << endl;
    fichier = "pngs/16.png";
    originale.charger(fichier);
    cout << "Phi=7 :" << endl;
    arbre.importer(originale);
    arbre.compressionPhi(7);
    arbre.afficher();
    compressee = arbre.exporter();
    compressee.sauver("zip-p001-16.png");
}
Esempio n. 15
0
 //Checks if node and its children are empty
 bool isEmpty()
 {
     if (!data.empty()) return false;
     if (!tL) return true;
     if (tL->isEmpty() && tR->isEmpty() && bL->isEmpty() && bR->isEmpty())
     {
         return true;
     }
     return false;
 }
Esempio n. 16
0
void Terrain::EnableNodes(const QuadTree<TerrainNode>::Iterator& node)
{
	node->enabled = true;
	for (int i = 0; i < QTREE_CHILDREN_COUNT; i++)
	{
		if (node.Child(i))
			EnableNodes(node.Child(i));

	}
}
Esempio n. 17
0
void qtreeinit()
{
	quadtree.insert(Line2D(Point2D(100,100),Point2D(100,150)));
	quadtree.insert(Line2D(Point2D(300,100),Point2D(300,150)));
	quadtree.insert(Line2D(Point2D(450,320),Point2D(600,320)));
	quadtree.insert(Line2D(Point2D(50,360),Point2D(50,385)));
	quadtree.insert(Line2D(Point2D(150,360),Point2D(150,398)));
	quadtree.insert(Line2D(Point2D(150,405),Point2D(250,405)));
	quadtree.insert(Line2D(Point2D(150,760),Point2D(150,785)));
}
Esempio n. 18
0
void QuadTreeRenderProcessor::DetachRenderable(Renderable* renderable)
{
	assert_not_null(renderable);

	mRenderables.Remove(renderable);

	QuadTree* tree = static_cast<QuadTree*>(renderable->GetTree());
	if(tree != NULL)
		tree->Remove(renderable);
}
bool ZoneContainerComponent::insertActiveArea(Zone* newZone, ActiveArea* activeArea) {
	if (newZone == NULL)
		return false;

	if (!activeArea->isDeplyoed())
		activeArea->deploy();

	Zone* zone = activeArea->getZone();

	ManagedReference<SceneObject*> thisLocker = activeArea;

	Locker zoneLocker(newZone);

	if (activeArea->isInQuadTree() && newZone != zone) {
		activeArea->error("trying to insert to zone an object that is already in a different quadtree");

		activeArea->destroyObjectFromWorld(true);

		//StackTrace::printStackTrace();
	}

	activeArea->setZone(newZone);

	QuadTree* regionTree = newZone->getRegionTree();

	regionTree->insert(activeArea);

	//regionTree->inRange(activeArea, 512);

	// lets update area to the in range players
	SortedVector<QuadTreeEntry*> objects;
	float range = activeArea->getRadius() + 64;

	newZone->getInRangeObjects(activeArea->getPositionX(), activeArea->getPositionY(), range, &objects, false);

	for (int i = 0; i < objects.size(); ++i) {
		SceneObject* object = cast<SceneObject*>(objects.get(i));

		if (!object->isTangibleObject()) {
			continue;
		}

		TangibleObject* tano = cast<TangibleObject*>(object);
		Vector3 worldPos = object->getWorldPosition();

		if (!tano->hasActiveArea(activeArea) && activeArea->containsPoint(worldPos.getX(), worldPos.getY())) {
			tano->addActiveArea(activeArea);
			activeArea->enqueueEnterEvent(object);
		}
	}

	newZone->addSceneObject(activeArea);

	return true;
}
Esempio n. 20
0
void QuadTree<Element,Comparator>::makeSubQuadTrees() {
    QuadTree<Element,Comparator>* qt = new QuadTree<Element,Comparator>
            (this->element,QuadTreePosition::LEFT_TOP,this->parent());
    qt->setParent(this);
    qt = new QuadTree<Element,Comparator>
                (this->element,QuadTreePosition::RIGHT_TOP,this->parent());
    qt->setParent(this);
    qt = new QuadTree<Element,Comparator>
                (this->element,QuadTreePosition::LEFT_BOTTOM,this->parent());
    qt->setParent(this);
    qt = new QuadTree<Element,Comparator>
                (this->element,QuadTreePosition::RIGHT_BOTTOM,this->parent());
}
Esempio n. 21
0
        /*bool subdivideInsert(T newData, float x, float y)
        {
            //std::cout << this << "\n";
            //std::cout << "subdiv insert bounds: " << bounds.x << " , " << bounds.y << " w " << bounds.w << " h " << bounds.h;
            //std::cout << "; is in range: ";
            //Make sure point is within the bounds of this node
            if (!isPointInRange(x, y, bounds))
            {
                //std::cout << "rejected b/c bounds\n";
                //Point is not within bounds
                return false;
            }
            
            //Node isn't full yet, so add data to this node
            if (data.size() < maxCapacity)
            {
                QuadPoint<T> newPoint;
                newPoint.x = x;
                newPoint.y = y;
                newPoint.data = newData;
                data.push_back(newPoint);
                //std::cout << "data added\n";
                return true;
            }

            //Node is already full; don't try to add any more
            //std::cout << "rejected b/c full\n";
            return false;
        }*/
        void subdivide()
        {
            float halfWidth = bounds.w/2;
            float halfHeight = bounds.h/2;
            tL = new QuadTree<T>(maxCapacity, bounds.x, bounds.y, halfWidth, halfHeight, depth); 
            tR = new QuadTree<T>(maxCapacity, bounds.x + halfWidth, bounds.y, halfWidth, halfHeight, depth); 
            bL = new QuadTree<T>(maxCapacity, bounds.x, bounds.y + halfHeight, halfWidth, halfHeight, depth); 
            bR = new QuadTree<T>(maxCapacity, bounds.x + halfWidth, bounds.y + halfHeight, halfWidth, halfHeight, depth);

            //Redistribute points into child nodes
            while(!data.empty())
            {
                //std::cout << "REDIS\n";
                QuadPoint<T> newDataPoint = data.back();
                T newData = newDataPoint.data;
                float x = newDataPoint.x;
                float y = newDataPoint.y;
                //std::cout << "redis tl\n";
                if (tL->insert(newData, x, y))
                {
                    //std::cout << "success\n";
                    data.pop_back();
                    continue;
                }
                //std::cout << "redis tr\n";
                if (tR->insert(newData, x, y))
                {
                    //std::cout << "success\n";
                    data.pop_back();
                    continue;
                }
                //std::cout << "redis bl\n";
                if (bL->insert(newData, x, y))
                {
                    //std::cout << "success\n";
                    data.pop_back();
                    continue;
                }
                //std::cout << "redis br\n";
                if (bR->insert(newData, x, y))
                {
                    //std::cout << "success\n";
                    data.pop_back();
                    continue;
                }
                //For some reason a point will not be accepted, so
                //stop redistributing
                //std::cout << "[!] point not accepted\n";
                break;
            } 
        }
Esempio n. 22
0
void QuadTree::RemoveEntity(Entity* _Ent){ // O(n)
	//Start at root node, and work its way down
		if (Type == STEM){
		//TOP LEFT
		QuadTree* QT = children[0]; 
		if (QT->max.x > _Ent->min.x && QT->max.y > _Ent->min.y){
			QT->RemoveEntity(_Ent);
		}
			
		//TOP RIGHT
		QT = children[1]; 
		if (QT->min.x < _Ent->max.x && QT->max.y > _Ent->min.y){
			QT->RemoveEntity(_Ent);
		}

		//BOTTOM LEFT
		QT = children[2]; 
		if (QT->max.x > _Ent->min.x && QT->min.y < _Ent->max.y){
			QT->RemoveEntity(_Ent);
		}

		//BOTTOM RIGHT
		QT = children[3];
		if (QT->min.x < _Ent->max.x && QT->min.y < _Ent->max.y){
			QT->RemoveEntity(_Ent);
		}

	}else{
		FOREACH(Entity*,Entlist,a){
			if ((*a) == _Ent){
				Entlist.erase(a);
				break;
			}
			//if (Entlist.empty())
			//	break;
		}
	}
	/*
	FOREACH(Entity*,Entlist,a){
		if ((*a) == _Ent){
			Entlist.clear();
			break;
		}
	}
	

	if (Type == STEM)
		for (int a=0;a<4;a++)
			children[a]->RemoveEntity(_Ent);
	*/
}
Esempio n. 23
0
void Terrain::UnloadVertices(const QuadTree<TerrainNode>::Iterator& node)
{
	if (node->vaoID)
	{
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		glDeleteBuffers(2, node->vboID);
		glBindVertexArray(0);
		glDeleteVertexArrays(1, &node->vaoID);
		node->vaoID = NULL;
	}

	for (int i = 0; i < QTREE_CHILDREN_COUNT; i++)
		if (node.Child(i))
			UnloadVertices(node.Child(i));
}
Esempio n. 24
0
void Terrain::DisableNodes(const QuadTree<TerrainNode>::Iterator& node)
{
	if (node->enabled)
	{
		node->enabled = false;
		if (node.Parent())
		{
			for (int i = 0; i < QTREE_NEIGHBOURS_COUNT; i++)
			if (node.Neighbour(i) && node.Neighbour(i).Parent())
			{
				DisableNodes(node.Neighbour(i).Parent());
			}
		}
	}
}
Esempio n. 25
0
        //Fills the provided array with resultant points (points
        //contained in the specified range). Returns total results
        //Pass in the maximum for the array as well as the index
        //this function should start at (usually 0)
        unsigned int queryRange(aabb& range, T* results, int& currentIndex, int maxPoints)
        {
            //std::cout << bounds.x << " , " << bounds.y << " w " << bounds.w << " h " << bounds.h << " \n";
            unsigned int totalResults = 0;
            //Make sure the array isn't full
            if (currentIndex >= maxPoints)
            {
                std::cout << "WARNING: queryPoints(): Results array full! (Max points = "<< maxPoints<< ")\n";
                return totalResults;
            }
            
            //Make sure range is touching this node
            if (!isColliding(&range, &bounds))
            {
                return 0;
            }
            
            //Add points in this node to results if contained in range
            for (typename std::list<QuadPoint<T> >::iterator it = data.begin(); it!=data.end(); ++it)
            {
                if (isPointInRange((*it).x, (*it).y, range))
                {
                    if (currentIndex < maxPoints)
                    {
                        results[currentIndex] = (*it).data;
                        totalResults++;
                        currentIndex++;
                    }
                    else
                    {
                        std::cout << "WARNING: queryPoints(): Results array full! (Max points = "<< maxPoints<< ")\n";
                        return totalResults;
                    }
                }
            }

            //Let all child nodes (if any) add points
            if (!tL)
            {
                return totalResults;
            }
            totalResults += tL->queryRange(range, results, currentIndex, maxPoints);
            totalResults += tR->queryRange(range, results, currentIndex, maxPoints);
            totalResults += bL->queryRange(range, results, currentIndex, maxPoints);
            totalResults += bR->queryRange(range, results, currentIndex, maxPoints);
            
            return totalResults;
        }
Esempio n. 26
0
void TestTree::test() {
    QuadTree qt;
    vector<Object> data;
    DataGenerator::generate_ordinary(2000, QuadTree::WIDTH, QuadTree::HEIGHT, data);

    cout << data.size() << endl << "============" << endl;

    qt.root.insert_object_range(data.begin(), data.end());
    qt.root.balance_if_necessary();

    auto r = qt.range_search(Range{0, 0, 20000, 20000});

    for (auto &o: r) { cout << "(" << o.id << ", " << o.x << ", " << o.y << ") "; };

    cout << endl << r.size() << endl;
}
Esempio n. 27
0
	IntersectResult PolygonContainer<TYPE>::QueryPolygonSegmentIntersect(Segment* s)
	{
		queue<QuadTree*> trees;
		trees.push(this);
		int lx = s->GetBoundingBox()->GetMinX();
		int ly = s->GetBoundingBox()->GetMinY();
		int hx = s->GetBoundingBox()->GetMaxX();
		int hy = s->GetBoundingBox()->GetMaxY();
		IntersectResult ret = IR_SEPERATE;
		while(!trees.empty())
		{
			QuadTree* tree = trees.front();
			trees.pop();
			if(tree == 0) continue;
			QuadObjects objects = tree->GetObjects();
			QuadObjectIterator it = objects.begin();
			for(;it != objects.end();it++)
			{
				QuadObject* quad = *it;
				TYPE* poly = (TYPE*)quad;
				IntersectResult ret1 = PolygonSegmentIntersect(s, poly);
				if (ret1 == IR_WITHIN || ret1 == IR_INTERSECT) return ret1;
				ret = ret1;
			}
			Geometry::TREE_LOCATION location = tree->GetLocation(lx, ly, hx, hy);
			if(location == Geometry::TL_CHILD0)
			{
				trees.push(tree->SubNode(0));
			}
			else if(location == Geometry::TL_CHILD1)
			{
				trees.push(tree->SubNode(1));
			}
			else if(location == Geometry::TL_CHILD2)
			{
				trees.push(tree->SubNode(2));
			}
			else if(location == Geometry::TL_CHILD3)
			{
				trees.push(tree->SubNode(3));
			}
			else
			{
				trees.push(tree->SubNode(0));
				trees.push(tree->SubNode(1));
				trees.push(tree->SubNode(2));
				trees.push(tree->SubNode(3));
			}
		}
		return ret;
	}
Esempio n. 28
0
void NGLScene::initializeGL ()
{
    ngl::NGLInit::instance();
    glClearColor (0.4,0.4,0.4,1);
    std::cout<<"Initializing NGL\n";

    ngl::Vec3 from(2,0.4,1);ngl::Vec3 to(0.5,0.4,0);ngl::Vec3 up(0,1,0);
    m_cam = new ngl::Camera(from,to,up);
    m_cam->setShape(45,(float)720/576,0.05,350);

    m_text=new ngl::Text(QFont("Arial",14));
    m_text->setScreenSize (width (),height ());

    // now to load the shader and set the values
    // grab an instance of shader manager
    ngl::ShaderLib *shader=ngl::ShaderLib::instance();
    (*shader)["nglDiffuseShader"]->use();

    shader->setShaderParam4f("Colour",1,0,0,1);
    shader->setShaderParam3f("lightPos",1,1,1);
    shader->setShaderParam4f("lightDiffuse",1,1,1,1);



    glEnable(GL_DEPTH_TEST);
    // enable multisampling for smoother drawing
    glEnable(GL_MULTISAMPLE);

    // as re-size is not explicitly called we need to do this.
   glViewport(0,0,width(),height());



    //Fill random 2D Values to Quatree
    for(int i=0;i<totalCollisionObjects;i++)
    {
       ngl::Random *rng=ngl::Random::instance ();
       int x = (int)rng->randomPositiveNumber (totalCollisionObjects);
       int y = (int)rng->randomPositiveNumber (totalCollisionObjects);

       //save positions
       Point t(x,y);
       treePositions.push_back (t);

       Point tempPoint(x,y);//or insert x,y instead of i,i to create some randomness
       tree.addPoint(tempPoint);
    }


    //find & get the collision neighbours of Point a(8,8), if (8,8) is in the tree
//    Point a(3,3);
    //Point a(2530,7399);    
//    getPointCollisions(a,&tree);

    currenttime.start ();
    tmpTimeElapsed = 0;
    fps= 0;
}
bool ZoneContainerComponent::removeActiveArea(Zone* zone, ActiveArea* activeArea) {
	if (zone == NULL)
		return false;

	ManagedReference<SceneObject*> thisLocker = activeArea;

	Locker zoneLocker(zone);

	QuadTree* regionTree = zone->getRegionTree();

	regionTree->remove(activeArea);

	// lets remove the in range active areas of players
	SortedVector<QuadTreeEntry*> objects;
	float range = activeArea->getRadius() + 64;

	zone->getInRangeObjects(activeArea->getPositionX(), activeArea->getPositionY(), range, &objects, false);

	zone->dropSceneObject(activeArea);

	zoneLocker.release();

	for (int i = 0; i < objects.size(); ++i) {
		SceneObject* object = cast<SceneObject*>(objects.get(i));

	//	Locker olocker(object);

		if (!object->isTangibleObject()) {
			continue;
		}

		TangibleObject* tano = cast<TangibleObject*>(object);

		if (tano->hasActiveArea(activeArea)) {
			tano->dropActiveArea(activeArea);
			activeArea->enqueueExitEvent(object);
		}
	}

	activeArea->notifyObservers(ObserverEventType::OBJECTREMOVEDFROMZONE, NULL, 0);

	activeArea->setZone(NULL);

	return true;
}
Esempio n. 30
0
//======================================================================
void LOSManager::init(){
  string shpFileName = "sdo_building.shp";
  string dbfFileName = "sdo_building.dbf";
  
  // ファイルを読み込んで建造物の形状データを作成
  _readFiles(shpFileName, dbfFileName);

  // ルートとなる四分木
  QuadTree* qt = new QuadTree(0,0);
  qt->set(_adfMinBounds[0], _adfMaxBounds[0],
	  _adfMinBounds[1], _adfMaxBounds[1]);
  GeoManager::addTree(qt);

  // ポリゴンを四分木に登録
  for (int i=0; i<_numPolygons; i++) {
    qt->pushQuadTree(GeoManager::polygon(i), i, 0, GeoManager::trees());
  }
}