• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
newtechnology

Octree for object culling

8 posts in this topic

I want to use octree for object culling. My idea is as follows:


struct Node 

{

   bool Visible;

   AABB Box;

   bool IsLeaf;

   Node* Children[8];

};

 

//called only once for objects at init time

 

Node** Octree::AddObject(AABB box, Node* parent)

{

     if (parent->IsLeaf) 

       return &Node;

   

    if (IntersectAABBAABB(parent->box, box))

    {

          for (int i=0; i < 8; +++i)

          { 

 

                   if  (IntersectAABBAABB(parent->Children[i]->box, box))

                           AddObject(box, parent);

          }

 

    }

 

}

 

//update is called everyframe

void Octree::Update()

{  

    if (IntersectAABBFrustum(parent->box, frustum)

   {  

            parent->visible = true;

           for (int i = 0; i < 8; ++i)

              {

                //move down the tree 

               .....

 

                //check for box against frustum

                  .. 

                     //.if visible

                       

                     //set visible bool to true

                   ...

                     // check it's children and do samething

                 ...

                   //else if false, set its all children's visible bool to false without checking

                   

              }

   } else

    {

           parent->visible = false; 

            //set all children's visible bool to false without checking

     }

 

}

 

//get node for this object

 

Object* house;

 

Node** houseNode = Octree.AddObject(house.box);

 

if (*houseNode->Visible)

//draw

 

 

I need help, do you see any problems? what should I do when object is inbetween Node AABBs ?

Please give me suggestions/improvements for octree or any other data structure object culling.

I do my terrain culling in hull shader.

 

 

Also I got another problem as boxes are not in same space, I think transforming them to world space would result into wrong assumptions about object being in a particular node because AABB in world space does not tightly surround the object.

Edited by newtechnology
0

Share this post


Link to post
Share on other sites

general approach when objects are shared between node aabb's is to move them up to the parent until they fit into an appropriately sized box. If you find most of your objects are large enough to sit near the top of your tree then you'll lose a lot of benefits of having the octree.

0

Share this post


Link to post
Share on other sites

You can also try placing the objects using one of their corners instead of the center, but then you need to check 4 adjacent octree nodes to find out if an object occupies a spot instead of only a single one (because the corner is in one cell, but the object itself can occupy the 3 adjacent cells, or in other words each corner of the object occupies one octree cell)

 

This should prevent objects being lifted to the root when they are at a bad spot, however youll probably need to add some shortcuts to make accessing adjacent octree cells not kill performance.

 

The idea is the same as placing objects of side X into a uniform grid of cell size X*X based on their top left (lets say) corner, which means the object itself occupies the cell where the top left corner is but also the one to the right, down and diagonally down-right.

0

Share this post


Link to post
Share on other sites

tiny improvement... instead of the isLeaf variable you could just check if children == null.

 

Edit: sorry, was wrong.

Edited by froop
0

Share this post


Link to post
Share on other sites

The real question about octree is how achieve the ocree correct when you have object who move ?

You can't regenerate all the octree each frame, a listener is needed to know when object need to check for a change ?

0

Share this post


Link to post
Share on other sites

A big thing that strikes me here is the variable bool Node::Visible. There should not be such cache variable or stored data of a visible node. It might be the case for now that you make only single camera queries for rendering purposes, but later on you could have game logic-specific code making queries to the same acceleration structure, i.e. using the structure to do raycasting queries, or "give me objects inside this bounding sphere/box", and so on. It doesn't make sense to hardcode the Octree to contain state pertaining to the world camera.

 

Instead, I'd make a separate QueryResult object, which contains a vector/hash table of collected visible nodes. Then, when you are about to render:

 

QueryResult visibleObjects;
octree.FindVisibleObjects(cameraFrustum, &visibleObjects)
sort(visibleObjects, sceneObjectsSortPredicate); 
for (object in visibleObjects)
   render(object);

 

This collecting pass of scene objects allows you to sort, which an important optimization, i.e. it gives the ability to sort front-to-back for depth, and sort to group objects that use the same material/shader/texture, and so on.

 

At minimum, if you need to keep that boolean, strongly document the semantics that the bool Node::Visible refers to either the most recent query (effectively making it a cache for the most recent visibility query operation) or rename it to bool Node::VisibleToMainCamera; to signify that the boolean refers to whether the node is visible to the certain specific god camera that the player views the scene through.

 

Then, I'd replace Node *children[8]; with a Node *children, which I'd allocate with a children = new Node[8]; statement. Also, remove the IsLeaf boolean and replace it with a function IsLeaf() const { return children == nullptr; }

 

Also, Octree::AddObject does 9 calls to a generic IntersectAABBAABB function. That is a bit excessive, and instead I'd do something like:

 

Octree::AddObject(Node *node, Object *object, const AABB &objectAABB)
{
   vec center = node->CenterPoint();
   if (objectAABB.maxX < center.x)
   {
     // left half
     if (objectAABB.maxY < center.y)
     {
       // top half
       // test z ...
     }
     else if (objectAABB.minY > center.y)
    {
       // bottom half
       // test z...
    }
   }
   else if (objectAABB.minX > center.x)
   {
     // test y and z.
   }
}
 
Octree::AddObject(Node *node, Object *object, const AABB &objectAABB)
{
  return AddObject(node, object, ComputeObjectAABB(object));
}
 

 

this form makes one efficient AABB intersection test to place the object AABB in the proper octant, and manage the case where it straddles multiple octants. As was suggested above, there are different ways to handle this:

  • support having objects up the tree, and not just in leaves. Objects will be placed in bottommost node they fully fit
  • add to multiple children
  • add to fixed child e.g. with the top-left rule that was presented above. Then when querying, see the top-left neighbors.
  • make the octree what is known as a "loose octree" - there the neighboring octree nodes overlap in volume.

There is no single best way to handle the straddling issue, but they are a bit of "what works best" decision in my experience.

2

Share this post


Link to post
Share on other sites

A big thing that strikes me here is the variable bool Node::Visible. There should not be such cache variable or stored data of a visible node. It might be the case for now that you make only single camera queries for rendering purposes, but later on you could have game logic-specific code making queries to the same acceleration structure, i.e. using the structure to do raycasting queries, or "give me objects inside this bounding sphere/box", and so on. It doesn't make sense to hardcode the Octree to contain state pertaining to the world camera.

 

Instead, I'd make a separate QueryResult object, which contains a vector/hash table of collected visible nodes. Then, when you are about to render:

QueryResult visibleObjects;
octree.FindVisibleObjects(cameraFrustum, &visibleObjects)
sort(visibleObjects, sceneObjectsSortPredicate); 
for (object in visibleObjects)
   render(object);

This collecting pass of scene objects allows you to sort, which an important optimization, i.e. it gives the ability to sort front-to-back for depth, and sort to group objects that use the same material/shader/texture, and so on.

 

At minimum, if you need to keep that boolean, strongly document the semantics that the bool Node::Visible refers to either the most recent query (effectively making it a cache for the most recent visibility query operation) or rename it to bool Node::VisibleToMainCamera; to signify that the boolean refers to whether the node is visible to the certain specific god camera that the player views the scene through.

 

Then, I'd replace Node *children[8]; with a Node *children, which I'd allocate with a children = new Node[8]; statement. Also, remove the IsLeaf boolean and replace it with a function IsLeaf() const { return children == nullptr; }

 

Also, Octree::AddObject does 9 calls to a generic IntersectAABBAABB function. That is a bit excessive, and instead I'd do something like:

Octree::AddObject(Node *node, Object *object, const AABB &objectAABB)
{
   vec center = node->CenterPoint();
   if (objectAABB.maxX < center.x)
   {
     // left half
     if (objectAABB.maxY < center.y)
     {
       // top half
       // test z ...
     }
     else if (objectAABB.minY > center.y)
    {
       // bottom half
       // test z...
    }
   }
   else if (objectAABB.minX > center.x)
   {
     // test y and z.
   }
}
 
Octree::AddObject(Node *node, Object *object, const AABB &objectAABB)
{
  return AddObject(node, object, ComputeObjectAABB(object));
}
 

this form makes one efficient AABB intersection test to place the object AABB in the proper octant, and manage the case where it straddles multiple octants. As was suggested above, there are different ways to handle this:

  • support having objects up the tree, and not just in leaves. Objects will be placed in bottommost node they fully fit
  • add to multiple children
  • add to fixed child e.g. with the top-left rule that was presented above. Then when querying, see the top-left neighbors.
  • make the octree what is known as a "loose octree" - there the neighboring octree nodes overlap in volume.

There is no single best way to handle the straddling issue, but they are a bit of "what works best" decision in my experience.

 

 

Thanks for this, I'll change it.

 

 

EDIT: I've another question,

My octree does a TriangleAABB intersection to find out which triangle lies in which node,

I've about 125000 triangles. By how much time will this octree increase my resource build up time? (I've not yet tested octree.)

void Octree::BuildOctree(OctreeNode* parent, const std::vector<UINT>& indices)
{
size_t triCount = indices.size() / 3;
 
if(triCount < 10000) 
{
parent->IsLeaf = true;
parent->Indices = indices;
}
else
{
parent->IsLeaf = false;
 
XNA::AxisAlignedBox subbox[8];
parent->Subdivide(subbox);
 
for(int i = 0; i < 8; ++i)
{

parent->Children[i] = new OctreeNode();
parent->Children[i]->Bounds = subbox[i];
 
// Find triangles that intersect this node's bounding box.
std::vector<UINT> intersectedTriangleIndices;
for(size_t j = 0; j < triCount; ++j)
{
UINT i0 = indices[j*3+0];
UINT i1 = indices[j*3+1];
UINT i2 = indices[j*3+2];
 
XMVECTOR v0 = XMLoadFloat3(&mVertices[i0]);
XMVECTOR v1 = XMLoadFloat3(&mVertices[i1]);
XMVECTOR v2 = XMLoadFloat3(&mVertices[i2]);
 
if(XNA::IntersectTriangleAxisAlignedBox(v0, v1, v2, &subbox[i]))
{
intersectedTriangleIndices.push_back(i0);
intersectedTriangleIndices.push_back(i1);
intersectedTriangleIndices.push_back(i2);
}
}
 

BuildOctree(parent->Children[i], intersectedTriangleIndices);
}
}
}

PS: my resource build up time is 2 minutes (it was faster on my old laptop)

Edited by newtechnology
0

Share this post


Link to post
Share on other sites

Hmm, if it takes 2 minutes to build an octree that consists of 125000 triangles, that sounds very slow. Some observations from the code you posted:

 

for(int i = 0; i < 8; ++i)
{
parent->Children[i] = new OctreeNode();
...
}

 

As a micro-optimization, you could just refactor so that you can do something like

 

parent->Children[i] = new OctreeNode[8];
 
That reduces the number of operator new() calls by eight-fold.
 
Also, the subdivision and termination logic is potentially very problematic. It might be that the subdivision never terminates, since that code only stops if there are less than 10k triangles in a one node. Think of a pathological case where you have 10k triangles that are *identical* in their positions. Then they always go in the exact same children since they overlap, and the loop will infinitely recurse until it runs out of memory.
 
Another potential problem is that you place triangles that overlap to duplicate nodes, but never check if that is a win. For example, you could be subdividing a node with 10k triangles, and end up cloning those triangles so that the resulting child nodes each contain a large portion of them (think e.g. all 8 nodes carrying 5000 triangles, which is 40k triangles total, even when the parent had only 10k). The code should have some heuristic to decide if subdivision is more trouble than it is worth, and then decide to stop if so.
 
Third, the code tests each triangle against eight aabbs at each level. It would be better to combine those checks: avoid doing a general triangle-aabb test, and instead do just a series of triangle-plane tests (one for +x, +y and +z facing planes), and use that info to find which octant a triangle belongs in. That saves a lot of redundant work.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0