Quadtree for collision detection implementaion - c++

I'm trying to create a quad tree for my 3D environment (all elements are on a flat terrain, so they can be represented with 2D data), but I'm a little lost on the implementation of the finer parts of it.
I will first begin by describing my current quad tree, than move on to its flaws, and than ask the questions.
What I currently have is a quad tree that takes in a very specific rectangle in which I define the x,z,width, and forward. Here is an overview of my operations.
Insert an object into the quadtree:
Check if the current node has any child. If it does, check if the object is able to completely fit into any of the four nodes. If Possible, recurse and repeat. If the object does not completely fit into the four nodes or there are no nodes at all, it will add it to a std vector, than check if it should split. If it splits, split it and split the current objects into their respective nodes.
Delete an object from the quadtree:
Check if the object is inside the current node. Than move onto children. If found, pop the object out of the vector.
Update the quadtree:
Moving and static objects are stored in different quad trees. Moving quad tree will always delete whatever has moved and reinsert. Static quad tree just chills.
Retrieving an object
First find which of the four nodes it belongs to, than move recursively, taking all of the node's current objects and adding it to a vector that is returned at the end.
So here are my flaws: Not all of my rects are located in the leaf. I have no idea what I should do with those that intersect between the nodes. This also makes collision detection checking kinda stupid in a quad tree; why do I need to put rects inside parent nodes? I am thoroughly unhappy about the Retrieve object function.
My second flaw is that I can only take a rect in. While this was useful in making the quad tree and debugging it, I would like to move on and be able to directly put my Objects in my game inside.
So here are my questions
I've read Quadtree for 2D collision detection. Everything seems good enough, until "Objects can belong to several collections inside the quadtree. You're going to need an extra linear collection outside the quadtree to enumerate every object without duplicates."
I have no idea what that means, or how to do that. The operations for collision detection also seems much better than what I currently have. I want to know what he means and how its done.
My second question is regarding the insertion of objects into the tree. All my objects in the game would be part of a base class. Should I just make them add the base class directly? Or should I cast the objects into rects and than add a pointer to the object? I am loading some models for my game as well, and they are stretched around and played with by glScalef(). Thus it seems really hard (but possible) to get the scaling of and the position of the models after scaling.
On a side note, the main reason I am scaling the models is because I am basically making walls for a maze game. So I need them to fit perfectly around, and I can't mathematics on maya.

How do you use quad tree for 3d? Maybe you mean 2d? Because usually octree is used for 3d.
About you first question. Your objects may belong to several quads in quadtree. When you retrieve objects you need to check collision with you just check if you already detected collision between two objects and if you did you dont do the detection again to bypass duplicates. For example you have 2 objects in one quad. You check collision between 1st and second and then between 2nd and 1st. You need to check that you already detected this collision before.
Try reading this link for details.

You can try a morton curve to find overlapping area I also think you need an octree:http://dmytry.com/texts/collision_detection_using_z_order_curve_aka_Morton_order.html. Here are example of overlapping objects:https://books.google.fr/books?id=1mu099DN9UwC&pg=PA29&lpg=PA22&ots=pzvPDLu5qi&focus=viewport&dq=hilbert+curve+overlapping+objects&hl=de&output=html_text

Related

Adding a point to a 2D polygon

I have a doubly-linked list based Polygon2D class that needs to be searched and modified, and is to be used in a game engine for various utilities like collision detection and to define graphical shapes and possibly texture coordinates, among other things. The polygon should be able to be concave or convex, but it cannot intersect itself.
I'm having trouble coming up with a method to insert a point such that it doesn't cause an intersection with the polygon. What I've been doing is searching for the closest edge to the point to insert by having two pointers to nodes, both starting at the head and iterating in separate directions. When the "next" node for either is the other pointer, the search is complete and the point is inserted between the two. Otherwise, the node iterating forward goes until it gets to the closest point so far (stopping if the next node is the other pointer), then the node iterating "backwards" does the same.
Unfortunately, this still results in intersections in cases where the edge just before the forward iterating pointer or the edge just "after" the backwards iterating pointer intersects the new edge created when inserting a new point. After that, more and more intersections can easily slip in.
Here is the insert method's code.
Can I improve this algorithm and still keep it O(n) or is there an entirely different method which may work better?
As a side note, the "findClosest[Edge](vec2 pt)" search uses a slightly modified version of the algorithm, but I feel like there must be a more effective way to do these searches without using more memory or time.
As for the calculation of the distance from a given point to a vertex this Distance from a point to a polygon might help.

What type of Container should I use to hold a 2D Tile Based World's Tile Objects?

I have a 2D tile based world, which is created using a simple array: World[100][100].
I plan on making the game multiplayer, so I figure it would be good to have the SERVER send the CLIENT all the tiles surrounding the player, and only the information that the CLIENT needs: What texture/sprite to render, and what position to render it.
To do this, I am assuming it would be good to make my own TILE class, which has a tileType (Grass, Sand, Water, etc.) and holds an array of 10 TileObjects.
TileObject is a class that holds three variables: objectType (Is it a Character? An Item? A tree? A rock?), an int objectID (which is linked to whatever the object actually is, so it knows the Character is "Leeroy Jenkins" and can then send Leeroy's animation & direction to the CLIENT for rendering.) and an objectPosition (X & Y from the Tile. This can extend beyond the Tile if needed.)
Although with this I am not sure how I would handle objects or characters that are larger than a single tile (such as a Dragon whose collision consumes many tiles) but it sounds like the best design.
What type of container should I use to store the TileObjects in the TILE class? Right now I have an array, but I doubt that is good for performance right? Some tiles may have 0 TileObjects, while others may have 5+. I used 10 because I severely doubt anything will ever exceed <10.
class Tile
{
private:
TileObject TileObjects[10]; //up to 10 objects on a single tile
TileTerrainType tileTerrainType; //GFX to display Grass, Sand, Water, Swamp, etc.
}
I have read many different tutorials and books, who argue completely different container types: Vectors, Maps, Linked Lists, Arrays. I just do not know what is best to store TileObjects (some of which may move constantly, can be destroyed or added like dropping/picking up items, and some which may remain stationary like a tree or rock).
I think you should have a map from co-ordinates on the world to a vector of what things are contained at those co-ordinates in the world.
As in, if I have a class Thing that represents any thing that can be on a space in the game, and a class Position with x and y parameters, I would have this:
map<Position, vector<Thing>>
initialized with one vector<Thing>, initially empty, for every position in the game (all 10000 of them).
This gives you a useful property:
Spatial partitioning. If I want to figure out what things are around me, I just have to check in the map at nine different positions. If I were to go the other way, and have one big list of Things unpartitioned by where they are, I would have to look at every single Thing in the game to make sure I'd see every single Thing that might be near me.
This provides huge speedups 1) the larger the map gets 2) the more Things exist 3) the more and more complex kinds of local interactions you demand.
What if you have a ThingID and need to get the Thing associated with it, not knowing where it is? To solve this, you can have a big map<int, Thing> of ThingIDs to Things and look in there. Of course, we see some redundancy here - we could either store the Thing in the flat map, or in the by-Position map, and have the other one just be a reference to the other (in the former case, containing just current position - in the latter case, containing just ThingID) and they must be kept in sync.
This could even lead to the 'dragon' problem being solved - if Things are in the flat map and merely references are stored in the by-position map, your Dragon could have one entry in the flat map and four references (one for each of the positions it occupies) in the by-position map, all pointing to the same thing. Then you just have to write code that is careful to not interact with an object twice, just because it happened to find it in two positions it was considering!

Bidirectional data structure for this situation

I'm studying a little part of a my game engine and wondering how to optimize some parts.
The situation is quite simple and it is the following:
I have a map of Tiles (stored in a bi-dimensional array) (~260k tiles, but assume many more)
I have a list of Items which always are in at least and at most a tile
A Tile can logically contain infinite amount of Items
During game execution many Items are continuously created and they start from their own Tile
Every Item continuously changes its Tile to one of the neighbors (up, right, down, left)
Up to now every Item has a reference to its actual Tile, and I just keep a list of items.
Every time an Item moves to an adjacent tile I just update item->tile = .. and I'm fine. This works fine but it's unidirectional.
While extending the engine I realized that I have to find all items contained in a tile many times and this is effectively degrading the performance (especially for some situations, in which I have to find all items for a range of tiles, one by one).
This means I would like to find a data structure suitable to find all the items of a specific Tile better than in O(n), but I would like to avoid much overhead in the "moving from one tile to another" phase (now it's just assigning a pointer, I would like to avoid doing many operations there, since it's quite frequent).
I'm thinking about a custom data structure to exploit the fact that items always move to neighbor cell but I'm currently groping in the dark! Any advice would be appreciated, even tricky or cryptic approaches. Unfortunately I can't just waste memory so a good trade-off is needed to.
I'm developing it in C++ with STL but without Boost. (Yes, I do know about multimap, it doesn't satisfy me, but I'll try if I don't find anything better)
struct Coordinate { int x, y; };
map<Coordinate, set<Item*>> tile_items;
This maps coordinates on the tile map to sets of Item pointers indicating which items are on that tile. You wouldn't need an entry for every coordinate, only the ones that actually have items on them. Now, I know you said this:
but I would like to avoid much overhead in the "moving from one tile
to another" phase
And this method would involve adding more overhead in that phase. But have you actually tried something like this yet and determined that it is a problem?
To me I would wrap a std::vector into a matrix type (IE impose 2d access on a 1d array) this give you fast random access to any of your tiles (implementing the matrix is trivial).
use
vector_index=y_pos*y_size+x_pos;
to index a vector of size
vector_size=y_size*x_size;
Then each item can have a std::vector of items (if the amount of items a tile has is very dynamic maybe a deque) again these are random access contains with very minimal overhead.
I would stay away from indirect containers for your use case.
PS: if you want you can have my matrix template.
If you really think having each tile store it's items will cost you too much space, consider using a quadtree to store items then. This allows you to efficiently get all the items on a tile, but leaves your Tile grid in place for item movement.

QuadTree for 2D collision detection

I'm currently working on a 2D shoot them up type of game, and I'm using a quad tree for my collision detections. I wrote a working quad tree that correctly pushes my actors into the nodes/leaves they belong to in the tree. However, I've got a few problems.
Firstly, how do I actually use my quadtree to select against which other objects an object should test collisions ? I'm unsure about how this is done.
Which brings up a second question. Say I have an object in node that is not a neighbour of another node, but that the object is large enough that it spans a few node, how can I check for an actual collision, since I'm guessing the tree might consider it's not close enough to collide with objects in a "far away" node? Should objects that don't completely fit in a node be kept in the parent node?
In my game, most of the objects are of different sizes and moving around.
I've read a good number of blogs/articles about quadtrees but most just explain how to build a tree which is not really what I'm looking for.
Any help/info is welcome.
You can establish a convention that every element is contained in the smallest quadtree node which contains it fully.
Then when you check the collisions for node A, you proceed like this:
current node = root node
check collisions of A with each element directly in current node
if A can be contained entirely in any of sub-nodes of the current node, set the current node to that sub-node and go to 2 again
finally, check collisions of A with all the elements in children nodes of the current node, recursively.
Note that the smaller the objects, the deeper they will be located in the quad tree, hence they will be compared less often.

Quadtree vs Red-Black tree for a game in C++?

I have been looking for a quadtree/quadtree node implementation on the net for ages. There is some basic stuff but nothing that I would be able to really use it a game.
My purpose is to store objects in a game for processing things such as collision detection.
I am not 100% certain that a quadtree is the best data structure to use, but from what I have read it is. I have already coded a Red-Black tree, but I don't really know if the performance would be good enough for my game (which will be an adventure 3rd person game like Ankh).
How would I write a basic but complete quadtree class (or octree) in C++?
How would you use the quad tree for collisions?
Quadtrees are used when you only need to store things that are effectively on a plane. Like units in a classic RTS where they are all on the ground or just a little bit above it. Essentially each node has links to 4 children that divide the node's space up into evenly distributed quarters.
Octrees do the same but in all three dimensions rather than just two, and thus they have 8 child nodes and partition the space up into eights. They should be used when the game entities are distributed more evenly among all three dimensions.
If you are looking for a binary tree - like a red-black tree - then you want to use a data structure called a binary space partitioning tree (BSP tree) or a version of it called the KD Tree. These partition space into halves using a plane, in the KD tree the planes are orthogonal (on the XZ, XY, ZY axes) so sometimes it works better in a 3D scene. BSP trees divide the scene up using planes in any orientation, but they can be quite useful, and they were used as far back as Doom.
Now because you've partitioned the game space you now don't have to test every game entity against every other game entity to see if they collide, which is an O(n^2) algorithm at best. Instead you query the data structure to return the game entities within a sub-region of the game space, and only perform collision detection for those nodes against each other.
This means that collision detection for all game entities should be n O(nlogn) operation (at worst).
A couple of extra things to watch out for:
Make sure you test game entities from adjacent nodes, not just the ones in the current node, since they could still collide.
Rebalance the data structure after the entities have moved since you may have empty nodes in the data structure now, or ones that contain too many entities for good performance (also the degenerate case of all entities being in the same node).
A red-black tree is not a spatial index; it can only sort on a single ordinal key. A quadtree is (for two dimensions) a spatial index that allows fast lookup and elimination of points. An Octree does the same thing for three dimensions.
The reason to use a quadtree is because you can then split on x- and y-coordinates, an octree on x, y and z, making collision detection trivial.
Quadtree: if an element is not in the topleft, it wont collide with one in topright, bottomleft or bottomright.
It is a very basic class, so I don't understand what you are missing in implementations you found.
I would not write such a class, I'd just borrow it from a project with a suitable license.
I warmly suggest you to use a rendering engine, Ogre3D for instance. As far as I know it supports Octrees for scene management. But you can extend the Octree-based class as you wish. I used to code the stuff I needed by myself, but for complex projects, it's just not the right way.
Trees in general are problematic for this in that any item inserted can lie on a boundary, and all the methods of dealing with that situation are fairly unsatisfactory.
You'll most likely want to sort your objects into moveable and static, and check anything that moved on a given frame against the static objects.
BSP Trees are the accepted solution for static geometry (boundary cases handled by splitting the object into two pieces), for dynamic try something like Sort and Sweep (also known as Sweep and Prune).
Right now STANN is the best open source implementation.
http://sites.google.com/a/compgeom.com/stann/