UnityOctree icon indicating copy to clipboard operation
UnityOctree copied to clipboard

Performance Upgrades

Open txzeenath opened this issue 9 years ago • 17 comments

  • [x] - Combine point and bounds logic
  • [x] - Object add method.
  • [x] - Object remove method.
  • [ ] - Object move method.
  • [x] - Node splitting on-demand.
  • [x] - Branch based object count tracking.
  • [x] - Automatic merging of branches/leaves.
  • [x] - Custom intersection tests to avoid unity internal calls.
  • [x] - Get rid of dependence on unity's Bounds struct internally.
  • [x] - Instance pooling.
  • [x] - O(1) Object removal.
  • [ ] - Implement queries into tree.
  • [ ] - Implement queries from objects.
  • [ ] - Eliminate recursive methods where plausible.
  • [ ] - Documentation.
  • [ ] - Clean up/write summaries.
  • [ ] - Add queries to testing scene
  • [ ] - Add queries to tree visualization

Scrapped: Linear. Actually proved to be slower with current implementation. Directional tree growth. Not really necessary. Proper implementation avoids this need. Tree shrinking. As above.

txzeenath avatar Jun 16 '17 08:06 txzeenath

It was quite a while ago now that I profiled the octree, but I remember the biggest performance bottleneck being simply traversing the tree through the nodes. One thing I've heard of that could make a big difference there is linearizing it: https://en.wikipedia.org/wiki/Linear_octree Basically putting it into a big array. But it's not something I've done before myself.

Your recursion removal plan, if I'm reading it right, sounds almost like a less generalised version of that.

You're welcome to submit pull requests for whatever, and thanks for the ones you've put through today already. I won't guarantee I'll accept everything into the main project but it's nice to have people improving the thing.

Nition avatar Jun 16 '17 09:06 Nition

I'm totally happy to combine the point and bounds trees if the points tree can be as efficient as it was on its own. I think I was just worried originally that there'd be unnecessary overhead since a point tree is simpler, with no worrying about whether a point spans nodes.

Actually even if it's slightly less efficient it's probably still worth combining them.

Nition avatar Jun 16 '17 09:06 Nition

After you mentioned it I decided to try a linearized tree. Which is going better than expected since I really never looked into what an octree even was until checking out yours. I'm just working on optimizing add/removes at the moment. Still need to implement the queries and fully test everything in-depth.

Current performance (averaged over 20 iterations) is about 300ms to insert 300,000 objects and 200ms to remove them all (54,788 total nodes). Including time splitting/merging. It could be faster but I'm not great with the math needed to pre-calculate node positions.

txzeenath avatar Jun 21 '17 02:06 txzeenath

That's awesome, man! How do those times compare to doing the same thing on your machine with the existing (not linear) version of the tree?

Nition avatar Jun 21 '17 02:06 Nition

I still have to adapt my benchmark setup to include the other trees. Which I might do tonight. It'll give a much better idea of the gains.

I know when I was using the point tree, I was hitting 500ms or so adding/removing 8000 objects each frame (in-editor with profiler connected, so not accurate).

Note: Currently testing on an i5 ultrabook. Not sure what it runs in full release build on my i7 desktop at home

txzeenath avatar Jun 21 '17 02:06 txzeenath

A quick test with 39,304 objects shows:

  • Adding:

    • Linearized: 50ms
    • PointTree: 63ms
  • Removing:

    • Linearized: 25ms
    • PointTree: 20193ms

I had to reduce the number of objects, as the point tree freezes once you approach 100,000 (assuming recursion). I'm using pooling in the linear version, which adds a little CPU time for lookups. At low object counts(8000 or so) the point tree actually wins on adds by a few ms.

Currently only splitting single nodes at a time as well. It adds to the time on an add as I need to iterate the object list potentially 8 times per full split, but hoping it provides a speedup during traversal since child nodes only exist if they're needed. I store the existing children as a bitmask so checking for a child should be very quick.

I may switch to using two masks, one for empty children and one for children with objects. So I can cut down split time and get the benefit of not checking extra nodes during queries.

txzeenath avatar Jun 21 '17 03:06 txzeenath

That remove time! Sounds great. I've always wanted to try linearising the tree but never got around to finding the time.

Nition avatar Jun 21 '17 03:06 Nition

Main speed up on removal is because the added object is returned to the caller. You just call object.Remove(). The object holds a reference to the node it's in. So removal itself requires no traversal.

Object counts are tracked in reverse. So if you remove/add to a node at depth 10, it only has to update 10 other nodes. Which is essentially just nodes[myParentKey].branchCount-- 10 times. I call this the "branch count" and lets every node know how many objects are below them at all times.

Merging is nearly instant since you don't need to count anything. if branchCount < maxObjects, you just throw all objects below you into a list, remove the nodes, and add the objects to the top node.

txzeenath avatar Jun 21 '17 03:06 txzeenath

Tweaked some stuff in the linear version:

  • Using bitmask to tell which children have objects
    • Don't need to do a lookup to check the node
  • Added localItemCount field
    • Cheaper than using List.Count constantly
  • Added parent reference to nodes
    • Cheaper than using dictionary lookups when traversing upwards
  • Splitting into 8 every time now instead of of per-octant
    • Only iterate object list once per node split now

New times:

  • 39,304 Objects

    • Add: 45ms (5ms faster)
    • Remove: 16ms (9ms faster)
  • 300,762 Objects:

    • Add: 230ms
    • Remove: 130ms

And just for fun..

  • 7,880,599 Objects
    • Add: 6.5s
    • Remove: 3.5s

txzeenath avatar Jun 21 '17 07:06 txzeenath

All that sounds logical and like good changes (although I'm not sure exactly what you mean with the "splitting into 8 every time" change TBH). I'm impressed!

Nition avatar Jun 21 '17 08:06 Nition

Originally I was splitting one octant at a time as needed in my version in order to reduce the number of nodes checked once I add queries. But now I just used a bitmask for that instead.

txzeenath avatar Jun 21 '17 09:06 txzeenath

Was doing some profiling and noticed a lot of time(relatively speaking) spent in my bit shifting methods and dictionary lookups. So I de-linearized the tree with the existing logic and it actually made it stupid fast.

  • 39,304 Objects

    • Add: 27ms
    • Remove: 17ms
  • 300,763

    • Add: 123ms
    • Remove: 118ms
  • 7,880,599

    • Add: 3.5s
    • Remove: 3.2s

I'm assuming it's a few possible factors:

  • Nodes are likely being stored on the heap, meaning the CPU cache rarely comes into play as the instances are scattered throughout.
  • Putting the children into pre-allocated arrays MIGHT be giving a small boost due to caching since they're allocated in a single "block".
  • Without using a custom dictionary with hash caching, GetHashCode actually takes a large amount of the CPU cycles, even with a primitive (uint) key type.
  • .NET is stupid

txzeenath avatar Jun 21 '17 12:06 txzeenath

That's interesting. I just had a quick look at the code in your branch. I wonder if traversing the children on Add without using recursion makes a big difference as well. Maybe a lot of the original slowness with the original version was the recursive calls, since each recursive call in C# pushes everything onto the stack and pops it when it comes back out.

Nition avatar Jun 21 '17 19:06 Nition

Eliminating recursion and religious abuse of the BestFitChild method definitely helped. Irrelevant nodes are never pulled from memory, and the stack isn't being obliterated.

The only place really using recursion is merge, since I can't think of a good way to drop down into multiple children without it.

txzeenath avatar Jun 21 '17 20:06 txzeenath

Eliminated lists for tracking objects. The constant searching was a bit slow(IndexOf on removes). Instead I turned each object into essentially a linked list node. Where each object has a reference to the next object and previous object in the chain. Nodes hold a reference to the first object. Removal is simply changing some references.

It's a little slower technically because it's having to constantly fetch from memory. But since it cuts down massively on searching it ends up being a net gain.

New times:

  • 39,304 Objects

    • Add: 24ms
    • Remove: 5ms (Original PointTree at 57ms/19,335ms with revised test)
  • 300,762 Objects:

    • Add: 113ms
    • Remove: 36ms
  • 7,880,599 Objects

    • Add: 3.1s
    • Remove: 1.03s

Think it's about time to work on queries and cleanup now. Pretty sure the base is as fast as I can make it. Right now i'm using point objects with an object limit of 8, which means a lot of splits(probably half of the CPU time is splitting). I'm curious how it runs with queries and such on bounds objects.

txzeenath avatar Jun 23 '17 02:06 txzeenath

Personally my current use for the octree is infrequent adds/removes, but frequent checks (IsColliding, GetNearby). So while fast add/remove is great, performance when using the complete tree is a big factor also.

I just did a quick test, converting GetNearby from using recursion to using a stack (like an actual c# stack object, not the stack), and it actually got a little slower. So much my idea of recursion being the source of all maladys. Tried the same thing on the SubAdd method in BoundsOctreeNode and that also got slightly slower. Your way is a little different of course, letting you traverse the children using index without the need for a stack to puch/pop from.

Just thought that was interesting.

Nition avatar Jul 07 '17 10:07 Nition

According to txzeenath - point": "Object move method" (not complete). Is this regarding actually moving objects at runtime?

Testing currently, I don't seam can make any efficient way, to move large amount of object (1k+), while updating boundries for boundsTree, without removing and adding object instances, so the tree boundary can be updated aswell. For example boundsTree.Add followed by boundsTree.Remove, wrapped in for loop for ( int i = 0; i < objects.childCount; i++ ).

For example:

for ( int i = 0; i < objects.childCount; i++ )
{

     Transform transform = object.GetChild ( i ) ;
     GameObject go = transform.gameObject ;

     boundsTree.Remove ( go  ) ;
     boundsTree.Add ( go , go.GetComponent<BoxCollider> ( ).bounds ) ;

}

I was thinking to attempt find a way, to use this octrees dev. with Unity 2018 new Job System, utilizing multi threading. But unless I find efficient way first, to update boundaries position at run time, I doubt I will consider this work. Any assist will be more than welcome.

Antypodish avatar Mar 19 '18 19:03 Antypodish