DEADSOFTWARE

8260d9e82aea1122836db9da2e21624f4c312909
[d2df-sdl.git] / src / game / z_aabbtree.pas
1 (* Copyright (C) DooM 2D:Forever Developers
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, either version 3 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *)
16 {$INCLUDE ../shared/a_modes.inc}
17 {$DEFINE aabbtree_many_asserts}
18 {$DEFINE aabbtree_query_count}
19 unit z_aabbtree;
21 interface
23 uses e_log;
26 // ////////////////////////////////////////////////////////////////////////// //
27 type
28 Float = Single;
29 PFloat = ^Float;
31 TTreeFlesh = TObject;
34 // ////////////////////////////////////////////////////////////////////////// //
35 type
36 Ray2D = record
37 public
38 origX, origY: Float;
39 dirX, dirY: Float;
41 public
42 constructor Create (ax, ay: Float; aangle: Float); overload;
43 constructor Create (ax0, ay0, ax1, ay1: Float); overload;
44 constructor Create (const aray: Ray2D); overload;
46 procedure copyFrom (const aray: Ray2D); inline;
48 procedure normalizeDir (); inline;
50 procedure setXYAngle (ax, ay: Float; aangle: Float); inline;
51 procedure setX0Y0X1Y1 (ax0, ay0, ax1, ay1: Float); inline;
52 end;
54 // ////////////////////////////////////////////////////////////////////////// //
55 type
56 AABB2D = record
57 public
58 minX, minY, maxX, maxY: Float;
60 private
61 function getvalid (): Boolean; inline;
62 function getcenterX (): Float; inline;
63 function getcenterY (): Float; inline;
64 function getextentX (): Float; inline;
65 function getextentY (): Float; inline;
67 public
68 constructor Create (x0, y0, x1, y1: Float); overload;
69 constructor Create (const aabb: AABB2D); overload;
70 constructor Create (const aabb0, aabb1: AABB2D); overload;
72 procedure copyFrom (const aabb: AABB2D); inline;
73 procedure setDims (x0, y0, x1, y1: Float); inline;
75 procedure setMergeTwo (const aabb0, aabb1: AABB2D); inline;
77 function volume (): Float; inline;
79 procedure merge (const aabb: AABB2D); inline;
81 // return true if the current AABB contains the AABB given in parameter
82 function contains (const aabb: AABB2D): Boolean; inline; overload;
83 function contains (ax, ay: Float): Boolean; inline; overload;
85 // return true if the current AABB is overlapping with the AABB in parameter
86 // two AABBs overlap if they overlap in the two axes at the same time
87 function overlaps (const aabb: AABB2D): Boolean; inline; overload;
89 // ray direction must be normalized
90 function intersects (const ray: Ray2D; tmino: PFloat=nil; tmaxo: PFloat=nil): Boolean; overload;
91 function intersects (ax, ay, bx, by: Float): Boolean; inline; overload;
93 property valid: Boolean read getvalid;
94 property centerX: Float read getcenterX;
95 property centerY: Float read getcenterY;
96 property extentX: Float read getextentX;
97 property extentY: Float read getextentY;
98 end;
101 // ////////////////////////////////////////////////////////////////////////// //
102 (* Dynamic AABB tree (bounding volume hierarchy)
103 * based on the code from ReactPhysics3D physics library, http://www.reactphysics3d.com
104 * Copyright (c) 2010-2016 Daniel Chappuis
106 * This software is provided 'as-is', without any express or implied warranty.
107 * In no event will the authors be held liable for any damages arising from the
108 * use of this software.
110 * Permission is granted to anyone to use this software for any purpose,
111 * including commercial applications, and to alter it and redistribute it
112 * freely, subject to the following restrictions:
114 * 1. The origin of this software must not be misrepresented; you must not claim
115 * that you wrote the original software. If you use this software in a
116 * product, an acknowledgment in the product documentation would be
117 * appreciated but is not required.
119 * 2. Altered source versions must be plainly marked as such, and must not be
120 * misrepresented as being the original software.
122 * 3. This notice may not be removed or altered from any source distribution.
123 *)
124 // ////////////////////////////////////////////////////////////////////////// //
125 (*
126 * This class implements a dynamic AABB tree that is used for broad-phase
127 * collision detection. This data structure is inspired by Nathanael Presson's
128 * dynamic tree implementation in BulletPhysics. The following implementation is
129 * based on the one from Erin Catto in Box2D as described in the book
130 * "Introduction to Game Physics with Box2D" by Ian Parberry.
131 *)
132 // ////////////////////////////////////////////////////////////////////////// //
133 // Dynamic AABB Tree: can be used to speed up broad phase in various engines
134 type
135 TDynAABBTree = class(TObject)
136 private
137 type
138 PTreeNode = ^TTreeNode;
139 TTreeNode = record
140 public
141 const NullTreeNode = -1;
142 const Left = 0;
143 const Right = 1;
144 public
145 // a node is either in the tree (has a parent) or in the free nodes list (has a next node)
146 parentId: Integer;
147 //nextNodeId: Integer;
148 // a node is either a leaf (has data) or is an internal node (has children)
149 children: array [0..1] of Integer; // left and right child of the node (children[0] = left child)
150 //TODO: `flesh` can be united with `children`
151 flesh: TTreeFlesh;
152 // height of the node in the tree (-1 for free nodes)
153 height: SmallInt;
154 // fat axis aligned bounding box (AABB) corresponding to the node
155 aabb: AABB2D;
156 public
157 // return true if the node is a leaf of the tree
158 procedure clear (); inline;
159 function leaf (): Boolean; inline;
160 function free (): Boolean; inline;
161 property nextNodeId: Integer read parentId write parentId;
162 //property flesh: Integer read children[0] write children[0];
163 end;
165 TVisitCheckerCB = function (node: PTreeNode): Boolean is nested;
166 TVisitVisitorCB = function (abody: TTreeFlesh): Boolean is nested;
168 public
169 // return `true` to stop
170 type TForEachLeafCB = function (abody: TTreeFlesh; const aabb: AABB2D): Boolean is nested; // WARNING! don't modify AABB here!
172 public
173 // in the broad-phase collision detection (dynamic AABB tree), the AABBs are
174 // also inflated in direction of the linear motion of the body by mutliplying the
175 // followin constant with the linear velocity and the elapsed time between two frames
176 const LinearMotionGapMultiplier = 1.7;
178 private
179 mNodes: array of TTreeNode; // nodes of the tree
180 mRootNodeId: Integer; // id of the root node of the tree
181 mFreeNodeId: Integer; // id of the first node of the list of free (allocated) nodes in the tree that we can use
182 mAllocCount: Integer; // number of allocated nodes in the tree
183 mNodeCount: Integer; // number of nodes in the tree
185 // extra AABB Gap used to allow the collision shape to move a little bit
186 // without triggering a large modification of the tree which can be costly
187 mExtraGap: Float;
189 private
190 function allocateNode (): Integer;
191 procedure releaseNode (nodeId: Integer);
192 procedure insertLeafNode (nodeId: Integer);
193 procedure removeLeafNode (nodeId: Integer);
194 function balanceSubTreeAtNode (nodeId: Integer): Integer;
195 function computeHeight (nodeId: Integer): Integer;
196 function insertObjectInternal (var aabb: AABB2D; staticObject: Boolean): Integer;
197 procedure setup ();
198 function visit (checker: TVisitCheckerCB; visitor: TVisitVisitorCB): Integer;
200 public
201 {$IFDEF aabbtree_query_count}
202 nodesVisited, nodesDeepVisited: Integer;
203 {$ENDIF}
205 public
206 // called when a overlapping node has been found during the call to forEachAABBOverlap()
207 // return `true` to stop
208 type TQueryOverlapCB = function (abody: TTreeFlesh): Boolean is nested;
209 type TSegQueryCallback = function (abody: TTreeFlesh; ax, ay, bx, by: Float): Float is nested; // return dist from (ax,ay) to abody
211 TSegmentQueryResult = record
212 dist: Float; // <0: nothing was hit
213 flesh: TTreeFlesh;
215 procedure reset (); inline;
216 function valid (): Boolean; inline;
217 end;
219 public
220 constructor Create (extraAABBGap: Float=0.0);
221 destructor Destroy (); override;
223 // clear all the nodes and reset the tree
224 procedure reset ();
226 function forEachLeaf (dg: TForEachLeafCB): Boolean; // WARNING! don't modify AABB/tree here!
227 procedure getRootAABB (var aabb: AABB2D);
229 function isValidId (id: Integer): Boolean; inline;
230 function getNodeObjectId (nodeid: Integer): TTreeFlesh; inline;
231 procedure getNodeFatAABB (var aabb: AABB2D; nodeid: Integer); inline;
233 // return `false` for invalid flesh
234 function getFleshAABB (var aabb: AABB2D; flesh: TTreeFlesh): Boolean; virtual; abstract;
236 // insert an object into the tree
237 // this method creates a new leaf node in the tree and returns the id of the corresponding node or -1 on error
238 // AABB for static object will not be "fat" (simple optimization)
239 // WARNING! inserting the same object several times *WILL* break everything!
240 function insertObject (flesh: TTreeFlesh; staticObject: Boolean=false): Integer;
242 // remove an object from the tree
243 // WARNING: ids of removed objects can be reused on later insertions!
244 procedure removeObject (nodeId: Integer);
246 (** update the dynamic tree after an object has moved.
248 * if the new AABB of the object that has moved is still inside its fat AABB, then nothing is done.
249 * otherwise, the corresponding node is removed and reinserted into the tree.
250 * the method returns true if the object has been reinserted into the tree.
251 * the `dispX` and `dispY` parameters are the linear velocity of the AABB multiplied by the elapsed time between two frames.
252 * if the `forceReinsert` parameter is `true`, we force a removal and reinsertion of the node
253 * (this can be useful if the shape AABB has become much smaller than the previous one for instance).
255 * note that you should call this method if body's AABB was modified, even if the body wasn't moved.
257 * if `forceReinsert` = `true` and both `dispX` and `dispY` are zeroes, convert object to "static" (don't extrude AABB).
259 * return `true` if the tree was modified.
260 *)
261 function updateObject (nodeId: Integer; dispX, dispY: Float; forceReinsert: Boolean=false): Boolean;
263 procedure aabbQuery (ax, ay, aw, ah: Float; cb: TQueryOverlapCB);
264 function pointQuery (ax, ay: Float; cb: TQueryOverlapCB): TTreeFlesh;
265 function segmentQuery (var qr: TSegmentQueryResult; ax, ay, bx, by: Float; cb: TSegQueryCallback): Boolean;
267 function computeTreeHeight (): Integer; // compute the height of the tree
269 property extraGap: Float read mExtraGap write mExtraGap;
270 property nodeCount: Integer read mNodeCount;
271 property nodeAlloced: Integer read mAllocCount;
272 end;
275 implementation
277 uses
278 SysUtils;
281 // ////////////////////////////////////////////////////////////////////////// //
282 function minI (a, b: Integer): Integer; inline; begin if (a < b) then result := a else result := b; end;
283 function maxI (a, b: Integer): Integer; inline; begin if (a > b) then result := a else result := b; end;
285 function minF (a, b: Float): Float; inline; begin if (a < b) then result := a else result := b; end;
286 function maxF (a, b: Float): Float; inline; begin if (a > b) then result := a else result := b; end;
289 // ////////////////////////////////////////////////////////////////////////// //
290 constructor Ray2D.Create (ax, ay: Float; aangle: Float); begin setXYAngle(ax, ay, aangle); end;
291 constructor Ray2D.Create (ax0, ay0, ax1, ay1: Float); begin setX0Y0X1Y1(ax0, ay0, ax1, ay1); end;
292 constructor Ray2D.Create (const aray: Ray2D); overload; begin copyFrom(aray); end;
295 procedure Ray2D.copyFrom (const aray: Ray2D); inline;
296 begin
297 origX := aray.origX;
298 origY := aray.origY;
299 dirX := aray.dirX;
300 dirY := aray.dirY;
301 end;
303 procedure Ray2D.normalizeDir (); inline;
304 var
305 invlen: Float;
306 begin
307 invlen := 1.0/sqrt(dirX*dirX+dirY*dirY);
308 dirX *= invlen;
309 dirY *= invlen;
310 end;
312 procedure Ray2D.setXYAngle (ax, ay: Float; aangle: Float); inline;
313 begin
314 origX := ax;
315 origY := ay;
316 dirX := cos(aangle);
317 dirY := sin(aangle);
318 end;
320 procedure Ray2D.setX0Y0X1Y1 (ax0, ay0, ax1, ay1: Float); inline;
321 begin
322 origX := ax0;
323 origY := ay0;
324 dirX := ax1-ax0;
325 dirY := ay1-ay0;
326 normalizeDir();
327 end;
330 // ////////////////////////////////////////////////////////////////////////// //
331 constructor AABB2D.Create (x0, y0, x1, y1: Float); overload;
332 begin
333 setDims(x0, y0, x1, y1);
334 end;
336 constructor AABB2D.Create (const aabb: AABB2D); overload;
337 begin
338 copyFrom(aabb);
339 end;
341 constructor AABB2D.Create (const aabb0, aabb1: AABB2D); overload;
342 begin
343 setMergeTwo(aabb0, aabb1);
344 end;
346 function AABB2D.getvalid (): Boolean; inline; begin result := (minX < maxX) and (minY < maxY); end;
348 function AABB2D.getcenterX (): Float; inline; begin result := (minX+maxX)/2; end;
349 function AABB2D.getcenterY (): Float; inline; begin result := (minY+maxY)/2; end;
350 function AABB2D.getextentX (): Float; inline; begin result := (maxX-minX)+1; end;
351 function AABB2D.getextentY (): Float; inline; begin result := (maxY-minY)+1; end;
354 procedure AABB2D.copyFrom (const aabb: AABB2D); inline;
355 begin
356 minX := aabb.minX;
357 minY := aabb.minY;
358 maxX := aabb.maxX;
359 maxY := aabb.maxY;
360 end;
363 procedure AABB2D.setDims (x0, y0, x1, y1: Float); inline;
364 begin
365 minX := minF(x0, x1);
366 minY := minF(y0, y1);
367 maxX := maxF(x0, x1);
368 maxY := maxF(y0, y1);
369 end;
372 procedure AABB2D.setMergeTwo (const aabb0, aabb1: AABB2D); inline;
373 begin
374 minX := minF(aabb0.minX, aabb1.minX);
375 minY := minF(aabb0.minY, aabb1.minY);
376 maxX := maxF(aabb0.maxX, aabb1.maxX);
377 maxY := maxF(aabb0.maxY, aabb1.maxY);
378 end;
381 function AABB2D.volume (): Float; inline;
382 begin
383 result := (maxX-minX)*(maxY-minY);
384 end;
387 procedure AABB2D.merge (const aabb: AABB2D); inline;
388 begin
389 minX := minF(minX, aabb.minX);
390 minY := minF(minY, aabb.minY);
391 maxX := maxF(maxX, aabb.maxX);
392 maxY := maxF(maxY, aabb.maxY);
393 end;
396 function AABB2D.contains (const aabb: AABB2D): Boolean; inline; overload;
397 begin
398 result :=
399 (aabb.minX >= minX) and (aabb.minY >= minY) and
400 (aabb.maxX <= maxX) and (aabb.maxY <= maxY);
401 end;
404 function AABB2D.contains (ax, ay: Float): Boolean; inline; overload;
405 begin
406 result := (ax >= minX) and (ay >= minY) and (ax <= maxX) and (ay <= maxY);
407 end;
410 function AABB2D.overlaps (const aabb: AABB2D): Boolean; inline; overload;
411 begin
412 result := false;
413 // exit with no intersection if found separated along any axis
414 if (maxX < aabb.minX) or (minX > aabb.maxX) then exit;
415 if (maxY < aabb.minY) or (minY > aabb.maxY) then exit;
416 result := true;
417 end;
420 // something to consider here is that 0 * inf =nan which occurs when the ray starts exactly on the edge of a box
421 // https://tavianator.com/fast-branchless-raybounding-box-intersections-part-2-nans/
422 function AABB2D.intersects (const ray: Ray2D; tmino: PFloat=nil; tmaxo: PFloat=nil): Boolean; overload;
423 var
424 dinv, t1, t2, tmp: Float;
425 tmin, tmax: Float;
426 begin
427 // ok with coplanars
428 tmin := -1.0e100;
429 tmax := 1.0e100;
430 // do X
431 if (ray.dirX <> 0.0) then
432 begin
433 dinv := 1.0/ray.dirX;
434 t1 := (minX-ray.origX)*dinv;
435 t2 := (maxX-ray.origX)*dinv;
436 if (t1 < t2) then tmin := t1 else tmin := t2;
437 if (t1 > t2) then tmax := t1 else tmax := t2;
438 end;
439 // do Y
440 if (ray.dirY <> 0.0) then
441 begin
442 dinv := 1.0/ray.dirY;
443 t1 := (minY-ray.origY)*dinv;
444 t2 := (maxY-ray.origY)*dinv;
445 // tmin
446 if (t1 < t2) then tmp := t1 else tmp := t2; // min(t1, t2)
447 if (tmax < tmp) then tmp := tmax; // min(tmax, tmp)
448 if (tmin > tmp) then tmin := tmp; // max(tmin, tmp)
449 // tmax
450 if (t1 > t2) then tmp := t1 else tmp := t2; // max(t1, t2)
451 if (tmin > tmp) then tmp := tmin; // max(tmin, tmp)
452 if (tmax < tmp) then tmax := tmp; // min(tmax, tmp)
453 end;
454 if (tmin > 0) then tmp := tmin else tmp := 0;
455 if (tmax > tmp) then
456 begin
457 if (tmino <> nil) then tmino^ := tmin;
458 if (tmaxo <> nil) then tmaxo^ := tmax;
459 result := true;
460 end
461 else
462 begin
463 result := false;
464 end;
465 end;
467 function AABB2D.intersects (ax, ay, bx, by: Float): Boolean; inline; overload;
468 var
469 tmin: Float;
470 ray: Ray2D;
471 begin
472 result := true;
473 // it may be faster to first check if start or end point is inside AABB (this is sometimes enough for dyntree)
474 if (ax >= minX) and (ay >= minY) and (ax <= maxX) and (ay <= maxY) then exit; // a
475 if (bx >= minX) and (by >= minY) and (bx <= maxX) and (by <= maxY) then exit; // b
476 // nope, do it hard way
477 ray := Ray2D.Create(ax, ay, bx, by);
478 if not intersects(ray, @tmin) then begin result := false; exit; end;
479 if (tmin < 0) then exit; // inside, just in case
480 bx := bx-ax;
481 by := by-ay;
482 result := (tmin*tmin <= bx*bx+by*by);
483 end;
486 // ////////////////////////////////////////////////////////////////////////// //
487 procedure TDynAABBTree.TSegmentQueryResult.reset (); inline; begin dist := -1; flesh := nil; end;
488 function TDynAABBTree.TSegmentQueryResult.valid (): Boolean; inline; begin result := (dist >= 0) and (flesh <> nil); end;
491 // ////////////////////////////////////////////////////////////////////////// //
492 function TDynAABBTree.TTreeNode.leaf (): Boolean; inline; begin result := (height = 0); end;
493 function TDynAABBTree.TTreeNode.free (): Boolean; inline; begin result := (height = -1); end;
495 procedure TDynAABBTree.TTreeNode.clear (); inline;
496 begin
497 parentId := 0;
498 children[0] := 0;
499 children[1] := 0;
500 flesh := nil;
501 height := 0;
502 //aabb.setX0Y0X1Y1(0, 0, 0, 0);
503 aabb.minX := 0;
504 aabb.minY := 0;
505 aabb.maxX := -1;
506 aabb.maxY := -1;
507 end;
510 // ////////////////////////////////////////////////////////////////////////// //
511 // allocate and return a node to use in the tree
512 function TDynAABBTree.allocateNode (): Integer;
513 var
514 i, newsz, freeNodeId: Integer;
515 node: PTreeNode;
516 begin
517 // if there is no more allocated node to use
518 if (mFreeNodeId = TTreeNode.NullTreeNode) then
519 begin
520 {$IFDEF aabbtree_many_asserts}assert(mNodeCount = mAllocCount);{$ENDIF}
521 // allocate more nodes in the tree
522 if (mAllocCount < 8192) then newsz := mAllocCount*2 else newsz := mAllocCount+8192;
523 SetLength(mNodes, newsz);
524 mAllocCount := newsz;
525 // initialize the allocated nodes
526 for i := mNodeCount to mAllocCount-2 do
527 begin
528 mNodes[i].nextNodeId := i+1;
529 mNodes[i].height := -1;
530 end;
531 mNodes[mAllocCount-1].nextNodeId := TTreeNode.NullTreeNode;
532 mNodes[mAllocCount-1].height := -1;
533 mFreeNodeId := mNodeCount;
534 end;
535 // get the next free node
536 freeNodeId := mFreeNodeId;
537 {$IFDEF aabbtree_many_asserts}assert((freeNodeId >= mNodeCount) and (freeNodeId < mAllocCount));{$ENDIF}
538 node := @mNodes[freeNodeId];
539 mFreeNodeId := node.nextNodeId;
540 node.clear();
541 node.parentId := TTreeNode.NullTreeNode;
542 node.height := 0;
543 Inc(mNodeCount);
544 result := freeNodeId;
545 end;
548 // release a node
549 procedure TDynAABBTree.releaseNode (nodeId: Integer);
550 begin
551 {$IFDEF aabbtree_many_asserts}assert(mNodeCount > 0);{$ENDIF}
552 {$IFDEF aabbtree_many_asserts}assert((nodeId >= 0) and (nodeId < mAllocCount));{$ENDIF}
553 {$IFDEF aabbtree_many_asserts}assert(mNodes[nodeId].height >= 0);{$ENDIF}
554 mNodes[nodeId].nextNodeId := mFreeNodeId;
555 mNodes[nodeId].height := -1;
556 mFreeNodeId := nodeId;
557 Dec(mNodeCount);
558 end;
561 // insert a leaf node in the tree
562 // the process of inserting a new leaf node in the dynamic tree is described in the book "Introduction to Game Physics with Box2D" by Ian Parberry
563 procedure TDynAABBTree.insertLeafNode (nodeId: Integer);
564 var
565 newNodeAABB, mergedAABBs, currentAndLeftAABB, currentAndRightAABB: AABB2D;
566 currentNodeId: Integer;
567 leftChild, rightChild, siblingNode: Integer;
568 oldParentNode, newParentNode: Integer;
569 volumeAABB, mergedVolume: Float;
570 costS, costI, costLeft, costRight: Float;
571 begin
572 // if the tree is empty
573 if (mRootNodeId = TTreeNode.NullTreeNode) then
574 begin
575 mRootNodeId := nodeId;
576 mNodes[mRootNodeId].parentId := TTreeNode.NullTreeNode;
577 exit;
578 end;
580 {$IFDEF aabbtree_many_asserts}assert(mRootNodeId <> TTreeNode.NullTreeNode);{$ENDIF}
582 // find the best sibling node for the new node
583 newNodeAABB := mNodes[nodeId].aabb;
584 currentNodeId := mRootNodeId;
585 while not mNodes[currentNodeId].leaf do
586 begin
587 leftChild := mNodes[currentNodeId].children[TTreeNode.Left];
588 rightChild := mNodes[currentNodeId].children[TTreeNode.Right];
590 // compute the merged AABB
591 volumeAABB := mNodes[currentNodeId].aabb.volume;
592 mergedAABBs := AABB2D.Create(mNodes[currentNodeId].aabb, newNodeAABB);
593 mergedVolume := mergedAABBs.volume;
595 // compute the cost of making the current node the sibling of the new node
596 costS := 2.0*mergedVolume;
598 // compute the minimum cost of pushing the new node further down the tree (inheritance cost)
599 costI := 2.0*(mergedVolume-volumeAABB);
601 // compute the cost of descending into the left child
602 currentAndLeftAABB := AABB2D.Create(newNodeAABB, mNodes[leftChild].aabb);
603 costLeft := currentAndLeftAABB.volume+costI;
604 if not mNodes[leftChild].leaf then costLeft := costLeft-mNodes[leftChild].aabb.volume;
606 // compute the cost of descending into the right child
607 currentAndRightAABB := AABB2D.Create(newNodeAABB, mNodes[rightChild].aabb);
608 costRight := currentAndRightAABB.volume+costI;
609 if not mNodes[rightChild].leaf then costRight := costRight-mNodes[rightChild].aabb.volume;
611 // if the cost of making the current node a sibling of the new node is smaller than the cost of going down into the left or right child
612 if (costS < costLeft) and (costS < costRight) then break;
614 // it is cheaper to go down into a child of the current node, choose the best child
615 //currentNodeId = (costLeft < costRight ? leftChild : rightChild);
616 if (costLeft < costRight) then currentNodeId := leftChild else currentNodeId := rightChild;
617 end;
619 siblingNode := currentNodeId;
621 // create a new parent for the new node and the sibling node
622 oldParentNode := mNodes[siblingNode].parentId;
623 newParentNode := allocateNode();
624 mNodes[newParentNode].parentId := oldParentNode;
625 mNodes[newParentNode].aabb.setMergeTwo(mNodes[siblingNode].aabb, newNodeAABB);
626 mNodes[newParentNode].height := mNodes[siblingNode].height+1;
627 {$IFDEF aabbtree_many_asserts}assert(mNodes[newParentNode].height > 0);{$ENDIF}
629 // if the sibling node was not the root node
630 if (oldParentNode <> TTreeNode.NullTreeNode) then
631 begin
632 {$IFDEF aabbtree_many_asserts}assert(not mNodes[oldParentNode].leaf);{$ENDIF}
633 if (mNodes[oldParentNode].children[TTreeNode.Left] = siblingNode) then
634 begin
635 mNodes[oldParentNode].children[TTreeNode.Left] := newParentNode;
636 end
637 else
638 begin
639 mNodes[oldParentNode].children[TTreeNode.Right] := newParentNode;
640 end;
641 mNodes[newParentNode].children[TTreeNode.Left] := siblingNode;
642 mNodes[newParentNode].children[TTreeNode.Right] := nodeId;
643 mNodes[siblingNode].parentId := newParentNode;
644 mNodes[nodeId].parentId := newParentNode;
645 end
646 else
647 begin
648 // if the sibling node was the root node
649 mNodes[newParentNode].children[TTreeNode.Left] := siblingNode;
650 mNodes[newParentNode].children[TTreeNode.Right] := nodeId;
651 mNodes[siblingNode].parentId := newParentNode;
652 mNodes[nodeId].parentId := newParentNode;
653 mRootNodeId := newParentNode;
654 end;
656 // move up in the tree to change the AABBs that have changed
657 currentNodeId := mNodes[nodeId].parentId;
658 {$IFDEF aabbtree_many_asserts}assert(not mNodes[currentNodeId].leaf);{$ENDIF}
659 while (currentNodeId <> TTreeNode.NullTreeNode) do
660 begin
661 // balance the sub-tree of the current node if it is not balanced
662 currentNodeId := balanceSubTreeAtNode(currentNodeId);
663 {$IFDEF aabbtree_many_asserts}assert(mNodes[nodeId].leaf);{$ENDIF}
665 {$IFDEF aabbtree_many_asserts}assert(not mNodes[currentNodeId].leaf);{$ENDIF}
666 leftChild := mNodes[currentNodeId].children[TTreeNode.Left];
667 rightChild := mNodes[currentNodeId].children[TTreeNode.Right];
668 {$IFDEF aabbtree_many_asserts}assert(leftChild <> TTreeNode.NullTreeNode);{$ENDIF}
669 {$IFDEF aabbtree_many_asserts}assert(rightChild <> TTreeNode.NullTreeNode);{$ENDIF}
671 // recompute the height of the node in the tree
672 mNodes[currentNodeId].height := maxI(mNodes[leftChild].height, mNodes[rightChild].height)+1;
673 {$IFDEF aabbtree_many_asserts}assert(mNodes[currentNodeId].height > 0);{$ENDIF}
675 // recompute the AABB of the node
676 mNodes[currentNodeId].aabb.setMergeTwo(mNodes[leftChild].aabb, mNodes[rightChild].aabb);
678 currentNodeId := mNodes[currentNodeId].parentId;
679 end;
681 {$IFDEF aabbtree_many_asserts}assert(mNodes[nodeId].leaf);{$ENDIF}
682 end;
685 // remove a leaf node from the tree
686 procedure TDynAABBTree.removeLeafNode (nodeId: Integer);
687 var
688 currentNodeId, parentNodeId, grandParentNodeId, siblingNodeId: Integer;
689 leftChildId, rightChildId: Integer;
690 begin
691 {$IFDEF aabbtree_many_asserts}assert((nodeId >= 0) and (nodeId < mAllocCount));{$ENDIF}
692 {$IFDEF aabbtree_many_asserts}assert(mNodes[nodeId].leaf);{$ENDIF}
694 // if we are removing the root node (root node is a leaf in this case)
695 if (mRootNodeId = nodeId) then begin mRootNodeId := TTreeNode.NullTreeNode; exit; end;
697 parentNodeId := mNodes[nodeId].parentId;
698 grandParentNodeId := mNodes[parentNodeId].parentId;
700 if (mNodes[parentNodeId].children[TTreeNode.Left] = nodeId) then
701 begin
702 siblingNodeId := mNodes[parentNodeId].children[TTreeNode.Right];
703 end
704 else
705 begin
706 siblingNodeId := mNodes[parentNodeId].children[TTreeNode.Left];
707 end;
709 // if the parent of the node to remove is not the root node
710 if (grandParentNodeId <> TTreeNode.NullTreeNode) then
711 begin
712 // destroy the parent node
713 if (mNodes[grandParentNodeId].children[TTreeNode.Left] = parentNodeId) then
714 begin
715 mNodes[grandParentNodeId].children[TTreeNode.Left] := siblingNodeId;
716 end
717 else
718 begin
719 {$IFDEF aabbtree_many_asserts}assert(mNodes[grandParentNodeId].children[TTreeNode.Right] = parentNodeId);{$ENDIF}
720 mNodes[grandParentNodeId].children[TTreeNode.Right] := siblingNodeId;
721 end;
722 mNodes[siblingNodeId].parentId := grandParentNodeId;
723 releaseNode(parentNodeId);
725 // now, we need to recompute the AABBs of the node on the path back to the root and make sure that the tree is still balanced
726 currentNodeId := grandParentNodeId;
727 while (currentNodeId <> TTreeNode.NullTreeNode) do
728 begin
729 // balance the current sub-tree if necessary
730 currentNodeId := balanceSubTreeAtNode(currentNodeId);
732 {$IFDEF aabbtree_many_asserts}assert(not mNodes[currentNodeId].leaf);{$ENDIF}
734 // get the two children of the current node
735 leftChildId := mNodes[currentNodeId].children[TTreeNode.Left];
736 rightChildId := mNodes[currentNodeId].children[TTreeNode.Right];
738 // recompute the AABB and the height of the current node
739 mNodes[currentNodeId].aabb.setMergeTwo(mNodes[leftChildId].aabb, mNodes[rightChildId].aabb);
740 mNodes[currentNodeId].height := maxI(mNodes[leftChildId].height, mNodes[rightChildId].height)+1;
741 {$IFDEF aabbtree_many_asserts}assert(mNodes[currentNodeId].height > 0);{$ENDIF}
743 currentNodeId := mNodes[currentNodeId].parentId;
744 end;
745 end
746 else
747 begin
748 // if the parent of the node to remove is the root node, the sibling node becomes the new root node
749 mRootNodeId := siblingNodeId;
750 mNodes[siblingNodeId].parentId := TTreeNode.NullTreeNode;
751 releaseNode(parentNodeId);
752 end;
753 end;
756 // balance the sub-tree of a given node using left or right rotations
757 // the rotation schemes are described in the book "Introduction to Game Physics with Box2D" by Ian Parberry
758 // this method returns the new root node id
759 function TDynAABBTree.balanceSubTreeAtNode (nodeId: Integer): Integer;
760 var
761 nodeA, nodeB, nodeC, nodeF, nodeG: PTreeNode;
762 nodeBId, nodeCId, nodeFId, nodeGId: Integer;
763 balanceFactor: Integer;
764 begin
765 {$IFDEF aabbtree_many_asserts}assert(nodeId <> TTreeNode.NullTreeNode);{$ENDIF}
767 nodeA := @mNodes[nodeId];
769 // if the node is a leaf or the height of A's sub-tree is less than 2
770 if (nodeA.leaf) or (nodeA.height < 2) then begin result := nodeId; exit; end; // do not perform any rotation
772 // get the two children nodes
773 nodeBId := nodeA.children[TTreeNode.Left];
774 nodeCId := nodeA.children[TTreeNode.Right];
775 {$IFDEF aabbtree_many_asserts}assert((nodeBId >= 0) and (nodeBId < mAllocCount));{$ENDIF}
776 {$IFDEF aabbtree_many_asserts}assert((nodeCId >= 0) and (nodeCId < mAllocCount));{$ENDIF}
777 nodeB := @mNodes[nodeBId];
778 nodeC := @mNodes[nodeCId];
780 // compute the factor of the left and right sub-trees
781 balanceFactor := nodeC.height-nodeB.height;
783 // if the right node C is 2 higher than left node B
784 if (balanceFactor > 1.0) then
785 begin
786 {$IFDEF aabbtree_many_asserts}assert(not nodeC.leaf);{$ENDIF}
788 nodeFId := nodeC.children[TTreeNode.Left];
789 nodeGId := nodeC.children[TTreeNode.Right];
790 {$IFDEF aabbtree_many_asserts}assert((nodeFId >= 0) and (nodeFId < mAllocCount));{$ENDIF}
791 {$IFDEF aabbtree_many_asserts}assert((nodeGId >= 0) and (nodeGId < mAllocCount));{$ENDIF}
792 nodeF := @mNodes[nodeFId];
793 nodeG := @mNodes[nodeGId];
795 nodeC.children[TTreeNode.Left] := nodeId;
796 nodeC.parentId := nodeA.parentId;
797 nodeA.parentId := nodeCId;
799 if (nodeC.parentId <> TTreeNode.NullTreeNode) then
800 begin
801 if (mNodes[nodeC.parentId].children[TTreeNode.Left] = nodeId) then
802 begin
803 mNodes[nodeC.parentId].children[TTreeNode.Left] := nodeCId;
804 end
805 else
806 begin
807 {$IFDEF aabbtree_many_asserts}assert(mNodes[nodeC.parentId].children[TTreeNode.Right] = nodeId);{$ENDIF}
808 mNodes[nodeC.parentId].children[TTreeNode.Right] := nodeCId;
809 end;
810 end
811 else
812 begin
813 mRootNodeId := nodeCId;
814 end;
816 {$IFDEF aabbtree_many_asserts}assert(not nodeC.leaf);{$ENDIF}
817 {$IFDEF aabbtree_many_asserts}assert(not nodeA.leaf);{$ENDIF}
819 // if the right node C was higher than left node B because of the F node
820 if (nodeF.height > nodeG.height) then
821 begin
822 nodeC.children[TTreeNode.Right] := nodeFId;
823 nodeA.children[TTreeNode.Right] := nodeGId;
824 nodeG.parentId := nodeId;
826 // recompute the AABB of node A and C
827 nodeA.aabb.setMergeTwo(nodeB.aabb, nodeG.aabb);
828 nodeC.aabb.setMergeTwo(nodeA.aabb, nodeF.aabb);
830 // recompute the height of node A and C
831 nodeA.height := maxI(nodeB.height, nodeG.height)+1;
832 nodeC.height := maxI(nodeA.height, nodeF.height)+1;
833 {$IFDEF aabbtree_many_asserts}assert(nodeA.height > 0);{$ENDIF}
834 {$IFDEF aabbtree_many_asserts}assert(nodeC.height > 0);{$ENDIF}
835 end
836 else
837 begin
838 // if the right node C was higher than left node B because of node G
839 nodeC.children[TTreeNode.Right] := nodeGId;
840 nodeA.children[TTreeNode.Right] := nodeFId;
841 nodeF.parentId := nodeId;
843 // recompute the AABB of node A and C
844 nodeA.aabb.setMergeTwo(nodeB.aabb, nodeF.aabb);
845 nodeC.aabb.setMergeTwo(nodeA.aabb, nodeG.aabb);
847 // recompute the height of node A and C
848 nodeA.height := maxI(nodeB.height, nodeF.height)+1;
849 nodeC.height := maxI(nodeA.height, nodeG.height)+1;
850 {$IFDEF aabbtree_many_asserts}assert(nodeA.height > 0);{$ENDIF}
851 {$IFDEF aabbtree_many_asserts}assert(nodeC.height > 0);{$ENDIF}
852 end;
854 // return the new root of the sub-tree
855 result := nodeCId;
856 exit;
857 end;
859 // if the left node B is 2 higher than right node C
860 if (balanceFactor < -1) then
861 begin
862 {$IFDEF aabbtree_many_asserts}assert(not nodeB.leaf);{$ENDIF}
864 nodeFId := nodeB.children[TTreeNode.Left];
865 nodeGId := nodeB.children[TTreeNode.Right];
866 {$IFDEF aabbtree_many_asserts}assert((nodeFId >= 0) and (nodeFId < mAllocCount));{$ENDIF}
867 {$IFDEF aabbtree_many_asserts}assert((nodeGId >= 0) and (nodeGId < mAllocCount));{$ENDIF}
868 nodeF := @mNodes[nodeFId];
869 nodeG := @mNodes[nodeGId];
871 nodeB.children[TTreeNode.Left] := nodeId;
872 nodeB.parentId := nodeA.parentId;
873 nodeA.parentId := nodeBId;
875 if (nodeB.parentId <> TTreeNode.NullTreeNode) then
876 begin
877 if (mNodes[nodeB.parentId].children[TTreeNode.Left] = nodeId) then
878 begin
879 mNodes[nodeB.parentId].children[TTreeNode.Left] := nodeBId;
880 end
881 else
882 begin
883 {$IFDEF aabbtree_many_asserts}assert(mNodes[nodeB.parentId].children[TTreeNode.Right] = nodeId);{$ENDIF}
884 mNodes[nodeB.parentId].children[TTreeNode.Right] := nodeBId;
885 end;
886 end
887 else
888 begin
889 mRootNodeId := nodeBId;
890 end;
892 {$IFDEF aabbtree_many_asserts}assert(not nodeB.leaf);{$ENDIF}
893 {$IFDEF aabbtree_many_asserts}assert(not nodeA.leaf);{$ENDIF}
895 // if the left node B was higher than right node C because of the F node
896 if (nodeF.height > nodeG.height) then
897 begin
898 nodeB.children[TTreeNode.Right] := nodeFId;
899 nodeA.children[TTreeNode.Left] := nodeGId;
900 nodeG.parentId := nodeId;
902 // recompute the AABB of node A and B
903 nodeA.aabb.setMergeTwo(nodeC.aabb, nodeG.aabb);
904 nodeB.aabb.setMergeTwo(nodeA.aabb, nodeF.aabb);
906 // recompute the height of node A and B
907 nodeA.height := maxI(nodeC.height, nodeG.height)+1;
908 nodeB.height := maxI(nodeA.height, nodeF.height)+1;
909 {$IFDEF aabbtree_many_asserts}assert(nodeA.height > 0);{$ENDIF}
910 {$IFDEF aabbtree_many_asserts}assert(nodeB.height > 0);{$ENDIF}
911 end
912 else
913 begin
914 // if the left node B was higher than right node C because of node G
915 nodeB.children[TTreeNode.Right] := nodeGId;
916 nodeA.children[TTreeNode.Left] := nodeFId;
917 nodeF.parentId := nodeId;
919 // recompute the AABB of node A and B
920 nodeA.aabb.setMergeTwo(nodeC.aabb, nodeF.aabb);
921 nodeB.aabb.setMergeTwo(nodeA.aabb, nodeG.aabb);
923 // recompute the height of node A and B
924 nodeA.height := maxI(nodeC.height, nodeF.height)+1;
925 nodeB.height := maxI(nodeA.height, nodeG.height)+1;
926 {$IFDEF aabbtree_many_asserts}assert(nodeA.height > 0);{$ENDIF}
927 {$IFDEF aabbtree_many_asserts}assert(nodeB.height > 0);{$ENDIF}
928 end;
930 // return the new root of the sub-tree
931 result := nodeBId;
932 exit;
933 end;
935 // if the sub-tree is balanced, return the current root node
936 result := nodeId;
937 end;
940 // compute the height of a given node in the tree
941 function TDynAABBTree.computeHeight (nodeId: Integer): Integer;
942 var
943 node: PTreeNode;
944 leftHeight, rightHeight: Integer;
945 begin
946 {$IFDEF aabbtree_many_asserts}assert((nodeId >= 0) and (nodeId < mAllocCount));{$ENDIF}
947 node := @mNodes[nodeId];
949 // if the node is a leaf, its height is zero
950 if (node.leaf) then begin result := 0; exit; end;
952 // compute the height of the left and right sub-tree
953 leftHeight := computeHeight(node.children[TTreeNode.Left]);
954 rightHeight := computeHeight(node.children[TTreeNode.Right]);
956 // return the height of the node
957 result := 1+maxI(leftHeight, rightHeight);
958 end;
961 // internally add an object into the tree
962 function TDynAABBTree.insertObjectInternal (var aabb: AABB2D; staticObject: Boolean): Integer;
963 var
964 nodeId: Integer;
965 begin
966 // get the next available node (or allocate new ones if necessary)
967 nodeId := allocateNode();
969 // create the fat aabb to use in the tree
970 mNodes[nodeId].aabb := aabb;
971 if (not staticObject) then
972 begin
973 mNodes[nodeId].aabb.minX -= mExtraGap;
974 mNodes[nodeId].aabb.minY -= mExtraGap;
975 mNodes[nodeId].aabb.maxX += mExtraGap;
976 mNodes[nodeId].aabb.maxY += mExtraGap;
977 end;
979 // set the height of the node in the tree
980 mNodes[nodeId].height := 0;
982 // insert the new leaf node in the tree
983 insertLeafNode(nodeId);
984 {$IFDEF aabbtree_many_asserts}assert(mNodes[nodeId].leaf);{$ENDIF}
986 {$IFDEF aabbtree_many_asserts}assert(nodeId >= 0);{$ENDIF}
988 // return the id of the node
989 result := nodeId;
990 end;
993 // initialize the tree
994 procedure TDynAABBTree.setup ();
995 var
996 i: Integer;
997 begin
998 mRootNodeId := TTreeNode.NullTreeNode;
999 mNodeCount := 0;
1000 mAllocCount := 8192;
1002 SetLength(mNodes, mAllocCount);
1003 //memset(mNodes, 0, mAllocCount*TTreeNode.sizeof);
1004 for i := 0 to mAllocCount-1 do mNodes[i].clear();
1006 // initialize the allocated nodes
1007 for i := 0 to mAllocCount-2 do
1008 begin
1009 mNodes[i].nextNodeId := i+1;
1010 mNodes[i].height := -1;
1011 end;
1012 mNodes[mAllocCount-1].nextNodeId := TTreeNode.NullTreeNode;
1013 mNodes[mAllocCount-1].height := -1;
1014 mFreeNodeId := 0;
1015 end;
1018 // also, checks if the tree structure is valid (for debugging purpose)
1019 function TDynAABBTree.forEachLeaf (dg: TForEachLeafCB): Boolean;
1020 function forEachNode (nodeId: Integer): Boolean;
1021 var
1022 pNode: PTreeNode;
1023 leftChild, rightChild, height: Integer;
1024 aabb: AABB2D;
1025 begin
1026 result := false;
1027 if (nodeId = TTreeNode.NullTreeNode) then exit;
1028 // if it is the root
1029 if (nodeId = mRootNodeId) then assert(mNodes[nodeId].parentId = TTreeNode.NullTreeNode);
1030 // get the children nodes
1031 pNode := @mNodes[nodeId];
1032 assert(pNode.height >= 0);
1033 e_WriteLog(Format('AABB:(%f,%f)-(%f,%f); volume=%f; valid=%d', [pNode.aabb.minX, pNode.aabb.minY, pNode.aabb.maxX, pNode.aabb.maxY, pNode.aabb.volume, Integer(pNode.aabb.valid)]), MSG_NOTIFY);
1034 assert(pNode.aabb.valid);
1035 assert(pNode.aabb.volume > 0);
1036 // if the current node is a leaf
1037 if (pNode.leaf) then
1038 begin
1039 assert(pNode.height = 0);
1040 if assigned(dg) then result := dg(pNode.flesh, pNode.aabb);
1041 end
1042 else
1043 begin
1044 leftChild := pNode.children[TTreeNode.Left];
1045 rightChild := pNode.children[TTreeNode.Right];
1046 // check that the children node Ids are valid
1047 assert((0 <= leftChild) and (leftChild < mAllocCount));
1048 assert((0 <= rightChild) and (rightChild < mAllocCount));
1049 // check that the children nodes have the correct parent node
1050 assert(mNodes[leftChild].parentId = nodeId);
1051 assert(mNodes[rightChild].parentId = nodeId);
1052 // check the height of node
1053 height := 1+maxI(mNodes[leftChild].height, mNodes[rightChild].height);
1054 assert(mNodes[nodeId].height = height);
1055 // check the AABB of the node
1056 aabb := AABB2D.Create(mNodes[leftChild].aabb, mNodes[rightChild].aabb);
1057 assert(aabb.minX = mNodes[nodeId].aabb.minX);
1058 assert(aabb.minY = mNodes[nodeId].aabb.minY);
1059 assert(aabb.maxX = mNodes[nodeId].aabb.maxX);
1060 assert(aabb.maxY = mNodes[nodeId].aabb.maxY);
1061 // recursively check the children nodes
1062 result := forEachNode(leftChild);
1063 if not result then result := forEachNode(rightChild);
1064 end;
1065 end;
1067 begin
1068 // recursively check each node
1069 result := forEachNode(mRootNodeId);
1070 end;
1073 // return `true` from visitor to stop immediately
1074 // checker should check if this node should be considered to further checking
1075 // returns tree node if visitor says stop or -1
1076 function TDynAABBTree.visit (checker: TVisitCheckerCB; visitor: TVisitVisitorCB): Integer;
1077 var
1078 stack: array [0..255] of Integer; // stack with the nodes to visit
1079 bigstack: array of Integer = nil;
1080 sp: Integer = 0;
1082 procedure spush (id: Integer);
1083 var
1084 xsp: Integer;
1085 begin
1086 if (sp < length(stack)) then
1087 begin
1088 // use "small stack"
1089 stack[sp] := id;
1090 Inc(sp);
1091 end
1092 else
1093 begin
1094 // use "big stack"
1095 xsp := sp-length(stack);
1096 if (xsp < length(bigstack)) then
1097 begin
1098 // reuse
1099 bigstack[xsp] := id;
1100 end
1101 else
1102 begin
1103 // grow
1104 SetLength(bigstack, length(bigstack)+1);
1105 bigstack[high(bigstack)] := id;
1106 end;
1107 Inc(sp);
1108 end;
1109 end;
1111 function spop (): Integer;
1112 begin
1113 assert(sp > 0);
1114 if (sp <= length(stack)) then
1115 begin
1116 // use "small stack"
1117 Dec(sp);
1118 result := stack[sp];
1119 end
1120 else
1121 begin
1122 // use "big stack"
1123 Dec(sp);
1124 result := bigstack[sp-length(stack)];
1125 end;
1126 end;
1128 var
1129 nodeId: Integer;
1130 node: PTreeNode;
1131 begin
1132 if not assigned(checker) then begin result := -1; exit; end;
1133 //if not assigned(visitor) then begin result := -1; exit; end;
1134 try
1135 {$IFDEF aabbtree_query_count}
1136 nodesVisited := 0;
1137 nodesDeepVisited := 0;
1138 {$ENDIF}
1140 // start from root node
1141 spush(mRootNodeId);
1143 // while there are still nodes to visit
1144 while (sp > 0) do
1145 begin
1146 // get the next node id to visit
1147 nodeId := spop();
1148 // skip it if it is a nil node
1149 if (nodeId = TTreeNode.NullTreeNode) then continue;
1150 {$IFDEF aabbtree_query_count}Inc(nodesVisited);{$ENDIF}
1151 // get the corresponding node
1152 node := @mNodes[nodeId];
1153 // should we investigate this node?
1154 if (checker(node)) then
1155 begin
1156 // if the node is a leaf
1157 if (node.leaf) then
1158 begin
1159 // call visitor on it
1160 {$IFDEF aabbtree_query_count}Inc(nodesDeepVisited);{$ENDIF}
1161 if assigned(visitor) then
1162 begin
1163 if (visitor(node.flesh)) then begin result := nodeId; exit; end;
1164 end;
1165 end
1166 else
1167 begin
1168 // if the node is not a leaf, we need to visit its children
1169 spush(node.children[TTreeNode.Left]);
1170 spush(node.children[TTreeNode.Right]);
1171 end;
1172 end;
1173 end;
1175 result := -1; // oops
1176 finally
1177 bigstack := nil;
1178 end;
1179 end;
1182 // add `extraAABBGap` to bounding boxes so slight object movement won't cause tree rebuilds
1183 // extra AABB Gap used to allow the collision shape to move a little bit without triggering a large modification of the tree which can be costly
1184 constructor TDynAABBTree.Create (extraAABBGap: Float=0.0);
1185 begin
1186 mExtraGap := extraAABBGap;
1187 setup();
1188 end;
1191 destructor TDynAABBTree.Destroy ();
1192 begin
1193 mNodes := nil;
1194 inherited;
1195 end;
1198 // clear all the nodes and reset the tree
1199 procedure TDynAABBTree.reset ();
1200 begin
1201 mNodes := nil;
1202 setup();
1203 end;
1206 function TDynAABBTree.computeTreeHeight (): Integer; begin result := computeHeight(mRootNodeId); end;
1209 // return the root AABB of the tree
1210 procedure TDynAABBTree.getRootAABB (var aabb: AABB2D);
1211 begin
1212 {$IFDEF aabbtree_many_asserts}assert((mRootNodeId >= 0) and (mRootNodeId < mNodeCount));{$ENDIF}
1213 aabb := mNodes[mRootNodeId].aabb;
1214 end;
1217 // does the given id represents a valid object?
1218 // WARNING: ids of removed objects can be reused on later insertions!
1219 function TDynAABBTree.isValidId (id: Integer): Boolean;
1220 begin
1221 result := (id >= 0) and (id < mNodeCount) and (mNodes[id].leaf);
1222 end;
1225 // get object by nodeid; can return nil for invalid ids
1226 function TDynAABBTree.getNodeObjectId (nodeid: Integer): TTreeFlesh;
1227 begin
1228 if (nodeid >= 0) and (nodeid < mNodeCount) and (mNodes[nodeid].leaf) then result := mNodes[nodeid].flesh else result := nil;
1229 end;
1231 // get fat object AABB by nodeid; returns random shit for invalid ids
1232 procedure TDynAABBTree.getNodeFatAABB (var aabb: AABB2D; nodeid: Integer);
1233 begin
1234 if (nodeid >= 0) and (nodeid < mNodeCount) and (not mNodes[nodeid].free) then aabb.copyFrom(mNodes[nodeid].aabb) else aabb.setDims(0, 0, 0, 0);
1235 end;
1238 // insert an object into the tree
1239 // this method creates a new leaf node in the tree and returns the id of the corresponding node or -1 on error
1240 // AABB for static object will not be "fat" (simple optimization)
1241 // WARNING! inserting the same object several times *WILL* break everything!
1242 function TDynAABBTree.insertObject (flesh: TTreeFlesh; staticObject: Boolean=false): Integer;
1243 var
1244 aabb: AABB2D;
1245 nodeId: Integer;
1246 begin
1247 if not getFleshAABB(aabb, flesh) then
1248 begin
1249 e_WriteLog(Format('trying to insert FUCKED AABB:(%f,%f)-(%f,%f); volume=%f; valid=%d', [aabb.minX, aabb.minY, aabb.maxX, aabb.maxY, aabb.volume, Integer(aabb.valid)]), MSG_WARNING);
1250 result := -1;
1251 exit;
1252 end;
1253 e_WriteLog(Format('inserting AABB:(%f,%f)-(%f,%f); volume=%f; valid=%d', [aabb.minX, aabb.minY, aabb.maxX, aabb.maxY, aabb.volume, Integer(aabb.valid)]), MSG_NOTIFY);
1254 nodeId := insertObjectInternal(aabb, staticObject);
1255 {$IFDEF aabbtree_many_asserts}assert(mNodes[nodeId].leaf);{$ENDIF}
1256 mNodes[nodeId].flesh := flesh;
1257 result := nodeId;
1258 end;
1261 // remove an object from the tree
1262 // WARNING: ids of removed objects can be reused on later insertions!
1263 procedure TDynAABBTree.removeObject (nodeId: Integer);
1264 begin
1265 if (nodeId < 0) or (nodeId >= mNodeCount) or (not mNodes[nodeId].leaf) then raise Exception.Create('invalid node id in TDynAABBTree');
1266 // remove the node from the tree
1267 removeLeafNode(nodeId);
1268 releaseNode(nodeId);
1269 end;
1272 function TDynAABBTree.updateObject (nodeId: Integer; dispX, dispY: Float; forceReinsert: Boolean=false): Boolean;
1273 var
1274 newAABB: AABB2D;
1275 begin
1276 if (nodeId < 0) or (nodeId >= mNodeCount) or (not mNodes[nodeId].leaf) then raise Exception.Create('invalid node id in TDynAABBTree');
1278 if not getFleshAABB(newAABB, mNodes[nodeId].flesh) then raise Exception.Create('invalid node id in TDynAABBTree');
1280 // if the new AABB is still inside the fat AABB of the node
1281 if (not forceReinsert) and (mNodes[nodeId].aabb.contains(newAABB)) then begin result := false; exit; end;
1283 // if the new AABB is outside the fat AABB, we remove the corresponding node
1284 removeLeafNode(nodeId);
1286 // compute the fat AABB by inflating the AABB with a constant gap
1287 mNodes[nodeId].aabb := newAABB;
1288 if not forceReinsert and ((dispX <> 0) or (dispY <> 0)) then
1289 begin
1290 mNodes[nodeId].aabb.minX := mNodes[nodeId].aabb.minX-mExtraGap;
1291 mNodes[nodeId].aabb.minY := mNodes[nodeId].aabb.minY-mExtraGap;
1292 mNodes[nodeId].aabb.maxX := mNodes[nodeId].aabb.maxX+mExtraGap;
1293 mNodes[nodeId].aabb.maxY := mNodes[nodeId].aabb.maxY+mExtraGap;
1294 end;
1296 // inflate the fat AABB in direction of the linear motion of the AABB
1297 if (dispX < 0.0) then
1298 begin
1299 mNodes[nodeId].aabb.minX := mNodes[nodeId].aabb.minX+LinearMotionGapMultiplier*dispX;
1300 end
1301 else
1302 begin
1303 mNodes[nodeId].aabb.maxX := mNodes[nodeId].aabb.maxX+LinearMotionGapMultiplier*dispX;
1304 end;
1305 if (dispY < 0.0) then
1306 begin
1307 mNodes[nodeId].aabb.minY := mNodes[nodeId].aabb.minY+LinearMotionGapMultiplier*dispY;
1308 end
1309 else
1310 begin
1311 mNodes[nodeId].aabb.maxY := mNodes[nodeId].aabb.maxY+LinearMotionGapMultiplier*dispY;
1312 end;
1314 {$IFDEF aabbtree_many_asserts}assert(mNodes[nodeId].aabb.contains(newAABB));{$ENDIF}
1316 // reinsert the node into the tree
1317 insertLeafNode(nodeId);
1319 result := true;
1320 end;
1323 // report all shapes overlapping with the AABB given in parameter
1324 procedure TDynAABBTree.aabbQuery (ax, ay, aw, ah: Float; cb: TQueryOverlapCB);
1325 var
1326 caabb: AABB2D;
1327 function checker (node: PTreeNode): Boolean;
1328 begin
1329 result := caabb.overlaps(node.aabb);
1330 end;
1331 begin
1332 if not assigned(cb) then exit;
1333 if (aw < 1) or (ah < 1) then exit;
1334 caabb := AABB2D.Create(ax, ay, ax+aw-1, ay+ah-1);
1335 visit(checker, cb);
1336 end;
1339 // report body that contains the given point, or nil
1340 function TDynAABBTree.pointQuery (ax, ay: Float; cb: TQueryOverlapCB): TTreeFlesh;
1341 var
1342 nid: Integer;
1343 function checker (node: PTreeNode): Boolean;
1344 begin
1345 result := node.aabb.contains(ax, ay);
1346 end;
1347 begin
1348 nid := visit(checker, cb);
1349 {$IFDEF aabbtree_many_asserts}assert((nid < 0) or ((nid >= 0) and (nid < mNodeCount) and (mNodes[nid].leaf)));{$ENDIF}
1350 if (nid >= 0) then result := mNodes[nid].flesh else result := nil;
1351 end;
1354 // segment querying method
1355 function TDynAABBTree.segmentQuery (var qr: TSegmentQueryResult; ax, ay, bx, by: Float; cb: TSegQueryCallback): Boolean;
1356 var
1357 maxFraction: Float = 1.0e100; // infinity
1358 curax, curay: Float;
1359 curbx, curby: Float;
1360 dirx, diry: Float;
1361 invlen: Float;
1363 function checker (node: PTreeNode): Boolean;
1364 begin
1365 result := node.aabb.intersects(curax, curay, curbx, curby);
1366 end;
1368 function visitor (flesh: TTreeFlesh): Boolean;
1369 var
1370 hitFraction: Float;
1371 begin
1372 hitFraction := cb(flesh, curax, curay, curbx, curby);
1373 // if the user returned a hitFraction of zero, it means that the raycasting should stop here
1374 if (hitFraction = 0.0) then
1375 begin
1376 qr.dist := 0;
1377 qr.flesh := flesh;
1378 result := true;
1379 exit;
1380 end;
1381 // if the user returned a positive fraction
1382 if (hitFraction > 0.0) then
1383 begin
1384 // we update the maxFraction value and the ray AABB using the new maximum fraction
1385 if (hitFraction < maxFraction) then
1386 begin
1387 maxFraction := hitFraction;
1388 qr.dist := hitFraction;
1389 qr.flesh := flesh;
1390 // fix curb here
1391 //curb := cura+dir*hitFraction;
1392 curbx := curax+dirx*hitFraction;
1393 curby := curay+diry*hitFraction;
1394 end;
1395 end;
1396 result := false; // continue
1397 end;
1399 begin
1400 qr.reset();
1402 if (ax >= bx) or (ay >= by) then begin result := false; exit; end;
1404 curax := ax;
1405 curay := ay;
1406 curbx := bx;
1407 curby := by;
1409 dirx := (curbx-curax);
1410 diry := (curby-curay);
1411 // normalize
1412 invlen := 1.0/sqrt(dirx*dirx+diry*diry);
1413 dirx *= invlen;
1414 diry *= invlen;
1416 visit(checker, visitor);
1418 result := qr.valid;
1419 end;
1422 end.