box2d Dynamic treedynamic tree is a full binary trees, that is, a non-leaf node must have two sub-nodes (note: Full binary trees and college teachers talk about two fork trees, completely binary tree different) so what if the tree is built? First look at the source
while (M_nodes[index]. IsLeaf () = = False) {Int32 child1 = M_nodes[index].child1; Int32 child2 = M_nodes[index].child2; float32 area = M_nodes[index].aabb. Getperimeter (); Area cost B2aabb Combinedaabb; Combinedaabb.combine (M_nodes[index].aabb, Leafaabb); float32 Combinedarea = Combinedaabb.getperimeter (); Combined perimeter//cost of creating a new parent for this node and the new leaf float32 cost = 2.0f * COMBINEDAREA; Minimum cost of pushing the leaf further down the tree float32 inheritancecost = 2.0f * (Combinedarea-area); Cost of descending to Child1 float32 cost1; if (M_nodes[child1]. IsLeaf ()) {B2aabb aabb; Aabb.combine (Leafaabb, M_nodes[child1].aabb); Cost1 = Aabb. Getperimeter () + inheritancecost; } else {B2aabb aabb; Aabb.combine (Leafaabb, M_nodes[child1].aabb); float32 Oldarea = M_nodes[child1].aabb. Getperimeter (); float32 Newarea = Aabb. Getperimeter (); Cost1 = (Newarea-oldarea) + inheritancecost; }//cost of descending to Child2Float32 Cost2; if (M_nodes[child2]. IsLeaf ()) {B2aabb aabb; Aabb.combine (Leafaabb, M_nodes[child2].aabb); Cost2 = Aabb. Getperimeter () + inheritancecost; } else {B2aabb aabb; Aabb.combine (Leafaabb, M_nodes[child2].aabb); float32 Oldarea = M_nodes[child2].aabb. Getperimeter (); float32 Newarea = Aabb. Getperimeter (); Cost2 = Newarea-oldarea + inheritancecost; }//Descend according to the minimum cost. if (Cost < Cost1 && Cost < Cost2) {break; }//Descend if (Cost1 < Cost2) {index = child1; } else {index = child2; } }
Box2D uses surface area heuristic to divide the scene. Although Getperimter is used, the perimeter of the AABB is obtained and the cost is calculated. But you can find area, Totalarea, Newarea,oldarea from the variable name. This may be due to the lower cost of using the perimeter.
Insert ideas as follows: Calculate the cost of the left and right subtree, select a low-cost node, if this node is a leaf node, insert the new node. If not, repeat this step.
box2d Dynamic Tree