1 (* Copyright (C) DooM 2D:Forever Developers
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.
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.
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/>.
16 {$INCLUDE ../shared/a_modes.inc}
17 {.$DEFINE aabbtree_many_asserts}
18 {$DEFINE aabbtree_query_count}
19 {.$DEFINE aabbtree_use_floats}
28 // ////////////////////////////////////////////////////////////////////////// //
30 {$IFDEF aabbtree_use_floats}TreeNumber
= Single;{$ELSE}TreeNumber
= Integer;{$ENDIF}
33 // ////////////////////////////////////////////////////////////////////////// //
41 constructor Create (ax
, ay
: Single; aangle
: Single); overload
;
42 constructor Create (ax0
, ay0
, ax1
, ay1
: Single); overload
;
43 constructor Create (constref aray
: Ray2D
); overload
;
45 procedure copyFrom (constref aray
: Ray2D
); inline;
47 procedure normalizeDir (); inline;
49 procedure setXYAngle (ax
, ay
: Single; aangle
: Single); inline;
50 procedure setX0Y0X1Y1 (ax0
, ay0
, ax1
, ay1
: Single); inline;
52 procedure atTime (time
: Single; out rx
, ry
: Integer); inline;
55 // ////////////////////////////////////////////////////////////////////////// //
59 minX
, minY
, maxX
, maxY
: TreeNumber
;
62 function getvalid (): Boolean; inline;
63 function getcenterX (): TreeNumber
; inline;
64 function getcenterY (): TreeNumber
; inline;
65 function getextentX (): TreeNumber
; inline;
66 function getextentY (): TreeNumber
; inline;
69 constructor Create (x0
, y0
, x1
, y1
: TreeNumber
); overload
;
70 constructor Create (constref aabb
: AABB2D
); overload
;
71 constructor Create (constref aabb0
, aabb1
: AABB2D
); overload
;
73 constructor CreateWH (ax
, ay
, w
, h
: TreeNumber
);
75 procedure copyFrom (constref aabb
: AABB2D
); inline;
76 procedure setDims (x0
, y0
, x1
, y1
: TreeNumber
); inline;
78 procedure setMergeTwo (constref aabb0
, aabb1
: AABB2D
); inline;
80 function volume (): TreeNumber
; inline;
82 procedure merge (constref aabb
: AABB2D
); inline;
84 // return true if the current AABB contains the AABB given in parameter
85 function contains (constref aabb
: AABB2D
): Boolean; inline; overload
;
86 function contains (ax
, ay
: TreeNumber
): Boolean; inline; overload
;
88 // return true if the current AABB is overlapping with the AABB in parameter
89 // two AABBs overlap if they overlap in the two axes at the same time
90 function overlaps (constref aabb
: AABB2D
): Boolean; inline; overload
;
92 // ray direction must be normalized
93 function intersects (constref ray
: Ray2D
; tmino
: PSingle=nil; tmaxo
: PSingle=nil): Boolean; overload
;
94 function intersects (ax
, ay
, bx
, by
: Single): Boolean; inline; overload
;
96 property valid
: Boolean read getvalid
;
97 property centerX
: TreeNumber read getcenterX
;
98 property centerY
: TreeNumber read getcenterY
;
99 property extentX
: TreeNumber read getextentX
;
100 property extentY
: TreeNumber read getextentY
;
104 // ////////////////////////////////////////////////////////////////////////// //
105 (* Dynamic AABB tree (bounding volume hierarchy)
106 * based on the code from ReactPhysics3D physics library, http://www.reactphysics3d.com
107 * Copyright (c) 2010-2016 Daniel Chappuis
109 * This software is provided 'as-is', without any express or implied warranty.
110 * In no event will the authors be held liable for any damages arising from the
111 * use of this software.
113 * Permission is granted to anyone to use this software for any purpose,
114 * including commercial applications, and to alter it and redistribute it
115 * freely, subject to the following restrictions:
117 * 1. The origin of this software must not be misrepresented; you must not claim
118 * that you wrote the original software. If you use this software in a
119 * product, an acknowledgment in the product documentation would be
120 * appreciated but is not required.
122 * 2. Altered source versions must be plainly marked as such, and must not be
123 * misrepresented as being the original software.
125 * 3. This notice may not be removed or altered from any source distribution.
127 // ////////////////////////////////////////////////////////////////////////// //
129 * This class implements a dynamic AABB tree that is used for broad-phase
130 * collision detection. This data structure is inspired by Nathanael Presson's
131 * dynamic tree implementation in BulletPhysics. The following implementation is
132 * based on the one from Erin Catto in Box2D as described in the book
133 * "Introduction to Game Physics with Box2D" by Ian Parberry.
135 // ////////////////////////////////////////////////////////////////////////// //
136 // Dynamic AABB Tree: can be used to speed up broad phase in various engines
138 generic TDynAABBTreeBase
<ITP
> = class(TObject
)
140 type TTreeFlesh
= ITP
;
144 PTreeNode
= ^TTreeNode
;
147 const NullTreeNode
= -1;
151 // a node is either in the tree (has a parent) or in the free nodes list (has a next node)
153 //nextNodeId: Integer;
154 // a node is either a leaf (has data) or is an internal node (has children)
155 children
: array [0..1] of Integer; // left and right child of the node (children[0] = left child)
156 // height of the node in the tree (-1 for free nodes)
158 // fat axis aligned bounding box (AABB) corresponding to the node
160 //TODO: `flesh` can be united with `children`
162 fleshX
, fleshY
: TreeNumber
;
163 tag
: Integer; // just a user-defined tag
165 // return true if the node is a leaf of the tree
166 procedure clear (); inline;
167 function leaf (): Boolean; inline;
168 function isfree (): Boolean; inline;
169 property nextNodeId
: Integer read parentId write parentId
;
170 //property flesh: Integer read children[0] write children[0];
172 procedure dumpToLog ();
175 TVisitCheckerCB
= function (node
: PTreeNode
): Boolean of object;
176 //TVisitVisitorCB = function (abody: TTreeFlesh; atag: Integer): Boolean is nested;
178 const ModeNoChecks
= 0;
183 // return `true` to stop
184 type TForEachLeafCB
= function (abody
: TTreeFlesh
; constref aabb
: AABB2D
): Boolean is nested
; // WARNING! don't modify AABB here!
187 // in the broad-phase collision detection (dynamic AABB tree), the AABBs are
188 // also inflated in direction of the linear motion of the body by mutliplying the
189 // followin constant with the linear velocity and the elapsed time between two frames
190 {$IFDEF aabbtree_use_floats}
191 const LinearMotionGapMultiplier
= 1.7;
193 const LinearMotionGapMultiplier
= 17; // *10
197 // called when a overlapping node has been found during the call to forEachAABBOverlap()
198 // return `true` to stop
199 type TQueryOverlapCB
= function (abody
: TTreeFlesh
; atag
: Integer): Boolean is nested
;
200 type TSegQueryCallback
= function (abody
: TTreeFlesh
; ax
, ay
, bx
, by
: Single): Single is nested
; // return dist from (ax,ay) to abody
202 PSegmentQueryResult
= ^TSegmentQueryResult
;
203 TSegmentQueryResult
= record
204 dist
: Single; // <0: nothing was hit
207 constructor Create (fuckyoufpc
: Boolean);
208 procedure reset (); inline;
209 function valid (): Boolean; inline;
213 mNodes
: array of TTreeNode
; // nodes of the tree
214 mRootNodeId
: Integer; // id of the root node of the tree
215 mFreeNodeId
: Integer; // id of the first node of the list of free (allocated) nodes in the tree that we can use
216 mAllocCount
: Integer; // number of allocated nodes in the tree
217 mNodeCount
: Integer; // number of nodes in the tree
219 // extra AABB Gap used to allow the collision shape to move a little bit
220 // without triggering a large modification of the tree which can be costly
221 mExtraGap
: TreeNumber
;
223 chkAABB
: AABB2D
; // for checkers
224 qSRes
: PSegmentQueryResult
; // for queries
227 curax
, curay
: Single;
228 curbx
, curby
: Single;
230 sqcb
: TSegQueryCallback
;
231 vstack
: array of Integer; // for `visit()`
232 vstused
: Integer; // to support recursive queries
234 function checkerAABB (node
: PTreeNode
): Boolean;
235 function checkerPoint (node
: PTreeNode
): Boolean;
236 function checkerRay (node
: PTreeNode
): Boolean;
237 function visitorRay (flesh
: TTreeFlesh
; tag
: Integer): Boolean;
239 type TQueryOverlapDg
= function (abody
: TTreeFlesh
; atag
: Integer): Boolean of object;
242 function allocateNode (): Integer;
243 procedure releaseNode (nodeId
: Integer);
244 procedure insertLeafNode (nodeId
: Integer);
245 procedure removeLeafNode (nodeId
: Integer);
246 function balanceSubTreeAtNode (nodeId
: Integer): Integer;
247 function computeHeight (nodeId
: Integer): Integer;
248 function insertObjectInternal (constref aabb
: AABB2D
; staticObject
: Boolean): Integer;
250 function visit (constref caabb
: AABB2D
; mode
: Integer; checker
: TVisitCheckerCB
; visitor
: TQueryOverlapCB
; visdg
: TQueryOverlapDg
; tagmask
: Integer): Integer;
252 function forEachNode (nodeId
: Integer; dg
: TForEachLeafCB
): Boolean;
255 {$IFDEF aabbtree_query_count}
256 mNodesVisited
, mNodesDeepVisited
: Integer;
260 constructor Create (extraAABBGap
: TreeNumber
=0);
261 destructor Destroy (); override;
263 // clear all the nodes and reset the tree
266 function forEachLeaf (dg
: TForEachLeafCB
): Boolean; // WARNING! don't modify AABB/tree here!
267 procedure getRootAABB (out aabb
: AABB2D
);
269 function isValidId (id
: Integer): Boolean; inline;
270 function getNodeObjectId (nodeid
: Integer): TTreeFlesh
; inline;
271 procedure getNodeFatAABB (out aabb
: AABB2D
; nodeid
: Integer); inline;
273 // returns `false` if nodeid is not leaf
274 function getNodeXY (nodeid
: Integer; out x
, y
: Integer): Boolean; inline;
276 // return `false` for invalid flesh
277 function getFleshAABB (out aabb
: AABB2D
; flesh
: TTreeFlesh
; tag
: Integer): Boolean; virtual; abstract;
279 // insert an object into the tree
280 // this method creates a new leaf node in the tree and returns the id of the corresponding node or -1 on error
281 // AABB for static object will not be "fat" (simple optimization)
282 // WARNING! inserting the same object several times *WILL* break everything!
283 function insertObject (flesh
: TTreeFlesh
; tag
: Integer=-1; staticObject
: Boolean=false): Integer;
285 // remove an object from the tree
286 // WARNING: ids of removed objects can be reused on later insertions!
287 procedure removeObject (nodeId
: Integer);
289 (** update the dynamic tree after an object has moved.
291 * if the new AABB of the object that has moved is still inside its fat AABB, then nothing is done.
292 * otherwise, the corresponding node is removed and reinserted into the tree.
293 * the method returns true if the object has been reinserted into the tree.
294 * the `dispX` and `dispY` parameters are the linear velocity of the AABB multiplied by the elapsed time between two frames.
295 * if the `forceReinsert` parameter is `true`, we force a removal and reinsertion of the node
296 * (this can be useful if the shape AABB has become much smaller than the previous one for instance).
298 * note that you should call this method if body's AABB was modified, even if the body wasn't moved.
300 * if `forceReinsert` = `true` and both `dispX` and `dispY` are zeroes, convert object to "static" (don't extrude AABB).
302 * return `true` if the tree was modified.
304 function updateObject (nodeId
: Integer; dispX
, dispY
: TreeNumber
; forceReinsert
: Boolean=false): Boolean; overload
;
305 function updateObject (nodeId
: Integer; forceReinsert
: Boolean=false): Boolean; overload
;
307 function aabbQuery (ax
, ay
, aw
, ah
: TreeNumber
; cb
: TQueryOverlapCB
; tagmask
: Integer=-1): TTreeFlesh
;
308 function pointQuery (ax
, ay
: TreeNumber
; cb
: TQueryOverlapCB
; tagmask
: Integer=-1): TTreeFlesh
;
309 function segmentQuery (out qr
: TSegmentQueryResult
; ax
, ay
, bx
, by
: TreeNumber
; cb
: TSegQueryCallback
; tagmask
: Integer=-1): Boolean;
311 function computeTreeHeight (): Integer; // compute the height of the tree
313 property extraGap
: TreeNumber read mExtraGap write mExtraGap
;
314 property nodeCount
: Integer read mNodeCount
;
315 property nodeAlloced
: Integer read mAllocCount
;
316 {$IFDEF aabbtree_query_count}
317 property nodesVisited
: Integer read mNodesVisited
;
318 property nodesDeepVisited
: Integer read mNodesDeepVisited
;
320 const nodesVisited
= 0;
321 const nodesDeepVisited
= 0;
326 function dtMinI (a
, b
: Integer): Integer; inline;
327 function dtMaxI (a
, b
: Integer): Integer; inline;
329 function dtMinF (a
, b
: TreeNumber
): TreeNumber
; inline;
330 function dtMaxF (a
, b
: TreeNumber
): TreeNumber
; inline;
339 // ////////////////////////////////////////////////////////////////////////// //
340 function dtMinI (a
, b
: Integer): Integer; inline; begin if (a
< b
) then result
:= a
else result
:= b
; end;
341 function dtMaxI (a
, b
: Integer): Integer; inline; begin if (a
> b
) then result
:= a
else result
:= b
; end;
343 function dtMinF (a
, b
: TreeNumber
): TreeNumber
; inline; begin if (a
< b
) then result
:= a
else result
:= b
; end;
344 function dtMaxF (a
, b
: TreeNumber
): TreeNumber
; inline; begin if (a
> b
) then result
:= a
else result
:= b
; end;
347 // ////////////////////////////////////////////////////////////////////////// //
348 constructor Ray2D
.Create (ax
, ay
: Single; aangle
: Single); begin setXYAngle(ax
, ay
, aangle
); end;
349 constructor Ray2D
.Create (ax0
, ay0
, ax1
, ay1
: Single); begin setX0Y0X1Y1(ax0
, ay0
, ax1
, ay1
); end;
350 constructor Ray2D
.Create (constref aray
: Ray2D
); overload
; begin copyFrom(aray
); end;
353 procedure Ray2D
.copyFrom (constref aray
: Ray2D
); inline;
361 procedure Ray2D
.normalizeDir (); inline;
365 invlen
:= 1.0/sqrt(dirX
*dirX
+dirY
*dirY
);
370 procedure Ray2D
.setXYAngle (ax
, ay
: Single; aangle
: Single); inline;
378 procedure Ray2D
.setX0Y0X1Y1 (ax0
, ay0
, ax1
, ay1
: Single); inline;
388 procedure Ray2D
.atTime (time
: Single; out rx
, ry
: Integer); inline;
390 rx
:= round(origX
+dirX
*time
);
391 ry
:= round(origY
+dirY
*time
);
395 // ////////////////////////////////////////////////////////////////////////// //
396 constructor AABB2D
.Create (x0
, y0
, x1
, y1
: TreeNumber
); overload
;
398 setDims(x0
, y0
, x1
, y1
);
401 constructor AABB2D
.Create (constref aabb
: AABB2D
); overload
;
406 constructor AABB2D
.Create (constref aabb0
, aabb1
: AABB2D
); overload
;
408 setMergeTwo(aabb0
, aabb1
);
411 constructor AABB2D
.CreateWH (ax
, ay
, w
, h
: TreeNumber
);
419 function AABB2D
.getvalid (): Boolean; inline; begin result
:= (minX
<= maxX
) and (minY
<= maxY
); end;
421 {$IFDEF aabbtree_use_floats}
422 function AABB2D
.getcenterX (): TreeNumber
; inline; begin result
:= (minX
+maxX
)/2.0; end;
423 function AABB2D
.getcenterY (): TreeNumber
; inline; begin result
:= (minY
+maxY
)/2.0; end;
425 function AABB2D
.getcenterX (): TreeNumber
; inline; begin result
:= (minX
+maxX
) div 2; end;
426 function AABB2D
.getcenterY (): TreeNumber
; inline; begin result
:= (minY
+maxY
) div 2; end;
428 function AABB2D
.getextentX (): TreeNumber
; inline; begin result
:= maxX
-minX
+1; end;
429 function AABB2D
.getextentY (): TreeNumber
; inline; begin result
:= maxY
-minY
+1; end;
431 procedure AABB2D
.copyFrom (constref aabb
: AABB2D
); inline;
437 {$IF DEFINED(D2F_DEBUG)}
438 if not valid
then raise Exception
.Create('copyFrom: result is fucked');
443 procedure AABB2D
.setDims (x0
, y0
, x1
, y1
: TreeNumber
); inline;
445 minX
:= dtMinF(x0
, x1
);
446 minY
:= dtMinF(y0
, y1
);
447 maxX
:= dtMaxF(x0
, x1
);
448 maxY
:= dtMaxF(y0
, y1
);
449 {$IF DEFINED(D2F_DEBUG)}
450 if not valid
then raise Exception
.Create('setDims: result is fucked');
455 procedure AABB2D
.setMergeTwo (constref aabb0
, aabb1
: AABB2D
); inline;
457 {$IF DEFINED(D2F_DEBUG)}
458 if not aabb0
.valid
then raise Exception
.Create('setMergeTwo: aabb0 is fucked');
459 if not aabb1
.valid
then raise Exception
.Create('setMergeTwo: aabb0 is fucked');
461 minX
:= dtMinF(aabb0
.minX
, aabb1
.minX
);
462 minY
:= dtMinF(aabb0
.minY
, aabb1
.minY
);
463 maxX
:= dtMaxF(aabb0
.maxX
, aabb1
.maxX
);
464 maxY
:= dtMaxF(aabb0
.maxY
, aabb1
.maxY
);
465 {$IF DEFINED(D2F_DEBUG)}
466 if not valid
then raise Exception
.Create('setMergeTwo: result is fucked');
471 function AABB2D
.volume (): TreeNumber
; inline;
473 result
:= (maxX
-minX
+1)*(maxY
-minY
+1);
477 procedure AABB2D
.merge (constref aabb
: AABB2D
); inline;
479 {$IF DEFINED(D2F_DEBUG)}
480 if not aabb
.valid
then raise Exception
.Create('merge: aabb is fucked');
482 minX
:= dtMinF(minX
, aabb
.minX
);
483 minY
:= dtMinF(minY
, aabb
.minY
);
484 maxX
:= dtMaxF(maxX
, aabb
.maxX
);
485 maxY
:= dtMaxF(maxY
, aabb
.maxY
);
486 {$IF DEFINED(D2F_DEBUG)}
487 if not valid
then raise Exception
.Create('setMergeTwo: result is fucked');
492 function AABB2D
.contains (constref aabb
: AABB2D
): Boolean; inline; overload
;
495 (aabb
.minX
>= minX
) and (aabb
.minY
>= minY
) and
496 (aabb
.maxX
<= maxX
) and (aabb
.maxY
<= maxY
);
500 function AABB2D
.contains (ax
, ay
: TreeNumber
): Boolean; inline; overload
;
502 result
:= (ax
>= minX
) and (ay
>= minY
) and (ax
<= maxX
) and (ay
<= maxY
);
506 function AABB2D
.overlaps (constref aabb
: AABB2D
): Boolean; inline; overload
;
509 // exit with no intersection if found separated along any axis
510 if (maxX
< aabb
.minX
) or (minX
> aabb
.maxX
) then exit
;
511 if (maxY
< aabb
.minY
) or (minY
> aabb
.maxY
) then exit
;
516 // something to consider here is that 0 * inf =nan which occurs when the ray starts exactly on the edge of a box
517 // https://tavianator.com/fast-branchless-raybounding-box-intersections-part-2-nans/
518 function AABB2D
.intersects (constref ray
: Ray2D
; tmino
: PSingle=nil; tmaxo
: PSingle=nil): Boolean; overload
;
520 dinv
, t1
, t2
, tmp
: Single;
527 if (ray
.dirX
<> 0.0) then
529 dinv
:= 1.0/ray
.dirX
;
530 t1
:= (minX
-ray
.origX
)*dinv
;
531 t2
:= (maxX
-ray
.origX
)*dinv
;
532 if (t1
< t2
) then tmin
:= t1
else tmin
:= t2
;
533 if (t1
> t2
) then tmax
:= t1
else tmax
:= t2
;
536 if (ray
.dirY
<> 0.0) then
538 dinv
:= 1.0/ray
.dirY
;
539 t1
:= (minY
-ray
.origY
)*dinv
;
540 t2
:= (maxY
-ray
.origY
)*dinv
;
542 if (t1
< t2
) then tmp
:= t1
else tmp
:= t2
; // min(t1, t2)
543 if (tmax
< tmp
) then tmp
:= tmax
; // min(tmax, tmp)
544 if (tmin
> tmp
) then tmin
:= tmp
; // max(tmin, tmp)
546 if (t1
> t2
) then tmp
:= t1
else tmp
:= t2
; // max(t1, t2)
547 if (tmin
> tmp
) then tmp
:= tmin
; // max(tmin, tmp)
548 if (tmax
< tmp
) then tmax
:= tmp
; // min(tmax, tmp)
550 if (tmin
> 0) then tmp
:= tmin
else tmp
:= 0;
553 if (tmino
<> nil) then tmino
^ := tmin
;
554 if (tmaxo
<> nil) then tmaxo
^ := tmax
;
563 function AABB2D
.intersects (ax
, ay
, bx
, by
: Single): Boolean; inline; overload
;
569 // it may be faster to first check if start or end point is inside AABB (this is sometimes enough for dyntree)
570 if (ax
>= minX
) and (ay
>= minY
) and (ax
<= maxX
) and (ay
<= maxY
) then exit
; // a
571 if (bx
>= minX
) and (by
>= minY
) and (bx
<= maxX
) and (by
<= maxY
) then exit
; // b
572 // nope, do it hard way
573 ray
:= Ray2D
.Create(ax
, ay
, bx
, by
);
574 if not intersects(ray
, @tmin
) then begin result
:= false; exit
; end;
575 if (tmin
< 0) then exit
; // inside, just in case
578 result
:= (tmin
*tmin
<= bx
*bx
+by
*by
);
582 // ////////////////////////////////////////////////////////////////////////// //
583 constructor TDynAABBTreeBase
.TSegmentQueryResult
.Create (fuckyoufpc
: Boolean); begin dist
:= -1; flesh
:= Default(ITP
); end;
584 procedure TDynAABBTreeBase
.TSegmentQueryResult
.reset (); inline; begin dist
:= -1; flesh
:= Default(ITP
); end;
585 function TDynAABBTreeBase
.TSegmentQueryResult
.valid (): Boolean; inline; begin result
:= (dist
>= 0) and (flesh
<> Default(ITP
)); end;
588 // ////////////////////////////////////////////////////////////////////////// //
589 function TDynAABBTreeBase
.TTreeNode
.leaf (): Boolean; inline; begin result
:= (height
= 0); end;
590 function TDynAABBTreeBase
.TTreeNode
.isfree (): Boolean; inline; begin result
:= (height
= -1); end;
592 procedure TDynAABBTreeBase
.TTreeNode
.clear (); inline;
597 flesh
:= Default(ITP
);
606 procedure TDynAABBTreeBase
.TTreeNode
.dumpToLog ();
608 e_WriteLog(Format('NODE: parentId=%d; children=[%d,%d]; height=%d; tag=%d; fleshX=%d; fleshY=%d; aabb=(%d,%d)-(%d,%d)',
609 [parentId
, children
[0], children
[1], Integer(height
), tag
, fleshX
, fleshY
, aabb
.minX
, aabb
.minY
, aabb
.maxX
, aabb
.maxY
]),
614 // ////////////////////////////////////////////////////////////////////////// //
615 // allocate and return a node to use in the tree
616 function TDynAABBTreeBase
.allocateNode (): Integer;
618 i
, newsz
, freeNodeId
: Integer;
621 // if there is no more allocated node to use
622 if (mFreeNodeId
= TTreeNode
.NullTreeNode
) then
624 {$IFDEF aabbtree_many_asserts}assert(mNodeCount
= mAllocCount
);{$ENDIF}
625 // allocate more nodes in the tree
626 if (mAllocCount
<= 16384) then newsz
:= mAllocCount
*2 else newsz
:= mAllocCount
+16384;
627 SetLength(mNodes
, newsz
);
628 mAllocCount
:= newsz
;
629 // initialize the allocated nodes
630 for i
:= mNodeCount
to mAllocCount
-1 do
632 mNodes
[i
].nextNodeId
:= i
+1;
633 mNodes
[i
].height
:= -1;
635 mNodes
[mAllocCount
-1].nextNodeId
:= TTreeNode
.NullTreeNode
;
636 mFreeNodeId
:= mNodeCount
;
638 // get the next free node
639 freeNodeId
:= mFreeNodeId
;
640 {$IFDEF aabbtree_many_asserts}assert(freeNodeId
< mAllocCount
);{$ENDIF}
641 node
:= @mNodes
[freeNodeId
];
642 mFreeNodeId
:= node
.nextNodeId
;
644 node
.parentId
:= TTreeNode
.NullTreeNode
;
647 result
:= freeNodeId
;
649 //e_WriteLog(Format('tree: allocated node #%d', [result]), MSG_NOTIFY);
654 procedure TDynAABBTreeBase
.releaseNode (nodeId
: Integer);
656 {$IFDEF aabbtree_many_asserts}assert(mNodeCount
> 0);{$ENDIF}
657 {$IFDEF aabbtree_many_asserts}assert((nodeId
>= 0) and (nodeId
< mAllocCount
));{$ENDIF}
658 {$IFDEF aabbtree_many_asserts}assert(mNodes
[nodeId
].height
>= 0);{$ENDIF}
659 mNodes
[nodeId
].nextNodeId
:= mFreeNodeId
;
660 mNodes
[nodeId
].height
:= -1;
661 mNodes
[nodeId
].flesh
:= Default(ITP
);
662 mFreeNodeId
:= nodeId
;
665 //e_WriteLog(Format('tree: released node #%d', [nodeId]), MSG_NOTIFY);
669 // insert a leaf node in the tree
670 // 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
671 procedure TDynAABBTreeBase
.insertLeafNode (nodeId
: Integer);
673 newNodeAABB
, mergedAABBs
, currentAndLeftAABB
, currentAndRightAABB
: AABB2D
;
674 currentNodeId
: Integer;
675 leftChild
, rightChild
, siblingNode
: Integer;
676 oldParentNode
, newParentNode
: Integer;
677 volumeAABB
, mergedVolume
: TreeNumber
;
678 costS
, costI
, costLeft
, costRight
: TreeNumber
;
680 // if the tree is empty
681 if (mRootNodeId
= TTreeNode
.NullTreeNode
) then
683 mRootNodeId
:= nodeId
;
684 mNodes
[mRootNodeId
].parentId
:= TTreeNode
.NullTreeNode
;
688 {$IFDEF aabbtree_many_asserts}assert(mRootNodeId
<> TTreeNode
.NullTreeNode
);{$ENDIF}
690 // find the best sibling node for the new node
691 newNodeAABB
:= AABB2D
.Create(mNodes
[nodeId
].aabb
);
692 currentNodeId
:= mRootNodeId
;
693 while not mNodes
[currentNodeId
].leaf
do
695 leftChild
:= mNodes
[currentNodeId
].children
[TTreeNode
.Left
];
696 rightChild
:= mNodes
[currentNodeId
].children
[TTreeNode
.Right
];
698 // compute the merged AABB
699 volumeAABB
:= mNodes
[currentNodeId
].aabb
.volume
;
700 mergedAABBs
:= AABB2D
.Create(mNodes
[currentNodeId
].aabb
, newNodeAABB
);
701 mergedVolume
:= mergedAABBs
.volume
;
703 // compute the cost of making the current node the sibling of the new node
704 costS
:= 2*mergedVolume
;
706 // compute the minimum cost of pushing the new node further down the tree (inheritance cost)
707 costI
:= 2*(mergedVolume
-volumeAABB
);
709 // compute the cost of descending into the left child
710 currentAndLeftAABB
:= AABB2D
.Create(newNodeAABB
, mNodes
[leftChild
].aabb
);
711 costLeft
:= currentAndLeftAABB
.volume
+costI
;
712 if not mNodes
[leftChild
].leaf
then costLeft
-= mNodes
[leftChild
].aabb
.volume
;
714 // compute the cost of descending into the right child
715 currentAndRightAABB
:= AABB2D
.Create(newNodeAABB
, mNodes
[rightChild
].aabb
);
716 costRight
:= currentAndRightAABB
.volume
+costI
;
717 if not mNodes
[rightChild
].leaf
then costRight
-= mNodes
[rightChild
].aabb
.volume
;
719 // 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
720 if (costS
< costLeft
) and (costS
< costRight
) then break
;
722 // it is cheaper to go down into a child of the current node, choose the best child
723 //currentNodeId = (costLeft < costRight ? leftChild : rightChild);
724 if (costLeft
< costRight
) then currentNodeId
:= leftChild
else currentNodeId
:= rightChild
;
727 siblingNode
:= currentNodeId
;
729 // create a new parent for the new node and the sibling node
730 oldParentNode
:= mNodes
[siblingNode
].parentId
;
731 newParentNode
:= allocateNode();
732 mNodes
[newParentNode
].parentId
:= oldParentNode
;
733 mNodes
[newParentNode
].aabb
.setMergeTwo(mNodes
[siblingNode
].aabb
, newNodeAABB
);
734 mNodes
[newParentNode
].height
:= mNodes
[siblingNode
].height
+1;
735 {$IFDEF aabbtree_many_asserts}assert(mNodes
[newParentNode
].height
> 0);{$ENDIF}
737 // if the sibling node was not the root node
738 if (oldParentNode
<> TTreeNode
.NullTreeNode
) then
740 {$IFDEF aabbtree_many_asserts}assert(not mNodes
[oldParentNode
].leaf
);{$ENDIF}
741 if (mNodes
[oldParentNode
].children
[TTreeNode
.Left
] = siblingNode
) then
743 mNodes
[oldParentNode
].children
[TTreeNode
.Left
] := newParentNode
;
747 mNodes
[oldParentNode
].children
[TTreeNode
.Right
] := newParentNode
;
749 mNodes
[newParentNode
].children
[TTreeNode
.Left
] := siblingNode
;
750 mNodes
[newParentNode
].children
[TTreeNode
.Right
] := nodeId
;
751 mNodes
[siblingNode
].parentId
:= newParentNode
;
752 mNodes
[nodeId
].parentId
:= newParentNode
;
756 // if the sibling node was the root node
757 mNodes
[newParentNode
].children
[TTreeNode
.Left
] := siblingNode
;
758 mNodes
[newParentNode
].children
[TTreeNode
.Right
] := nodeId
;
759 mNodes
[siblingNode
].parentId
:= newParentNode
;
760 mNodes
[nodeId
].parentId
:= newParentNode
;
761 mRootNodeId
:= newParentNode
;
764 // move up in the tree to change the AABBs that have changed
765 currentNodeId
:= mNodes
[nodeId
].parentId
;
766 {$IFDEF aabbtree_many_asserts}assert(not mNodes
[currentNodeId
].leaf
);{$ENDIF}
767 while (currentNodeId
<> TTreeNode
.NullTreeNode
) do
769 // balance the sub-tree of the current node if it is not balanced
770 currentNodeId
:= balanceSubTreeAtNode(currentNodeId
);
771 {$IFDEF aabbtree_many_asserts}assert(mNodes
[nodeId
].leaf
);{$ENDIF}
773 {$IFDEF aabbtree_many_asserts}assert(not mNodes
[currentNodeId
].leaf
);{$ENDIF}
774 leftChild
:= mNodes
[currentNodeId
].children
[TTreeNode
.Left
];
775 rightChild
:= mNodes
[currentNodeId
].children
[TTreeNode
.Right
];
776 {$IFDEF aabbtree_many_asserts}assert(leftChild
<> TTreeNode
.NullTreeNode
);{$ENDIF}
777 {$IFDEF aabbtree_many_asserts}assert(rightChild
<> TTreeNode
.NullTreeNode
);{$ENDIF}
779 // recompute the height of the node in the tree
780 mNodes
[currentNodeId
].height
:= dtMaxI(mNodes
[leftChild
].height
, mNodes
[rightChild
].height
)+1;
781 {$IFDEF aabbtree_many_asserts}assert(mNodes
[currentNodeId
].height
> 0);{$ENDIF}
783 // recompute the AABB of the node
784 mNodes
[currentNodeId
].aabb
.setMergeTwo(mNodes
[leftChild
].aabb
, mNodes
[rightChild
].aabb
);
786 currentNodeId
:= mNodes
[currentNodeId
].parentId
;
789 {$IFDEF aabbtree_many_asserts}assert(mNodes
[nodeId
].leaf
);{$ENDIF}
793 // remove a leaf node from the tree
794 procedure TDynAABBTreeBase
.removeLeafNode (nodeId
: Integer);
796 currentNodeId
, parentNodeId
, grandParentNodeId
, siblingNodeId
: Integer;
797 leftChildId
, rightChildId
: Integer;
799 {$IFDEF aabbtree_many_asserts}assert((nodeId
>= 0) and (nodeId
< mAllocCount
));{$ENDIF}
800 {$IFDEF aabbtree_many_asserts}assert(mNodes
[nodeId
].leaf
);{$ENDIF}
802 // if we are removing the root node (root node is a leaf in this case)
803 if (mRootNodeId
= nodeId
) then begin mRootNodeId
:= TTreeNode
.NullTreeNode
; exit
; end;
805 parentNodeId
:= mNodes
[nodeId
].parentId
;
806 grandParentNodeId
:= mNodes
[parentNodeId
].parentId
;
808 if (mNodes
[parentNodeId
].children
[TTreeNode
.Left
] = nodeId
) then
810 siblingNodeId
:= mNodes
[parentNodeId
].children
[TTreeNode
.Right
];
814 siblingNodeId
:= mNodes
[parentNodeId
].children
[TTreeNode
.Left
];
817 // if the parent of the node to remove is not the root node
818 if (grandParentNodeId
<> TTreeNode
.NullTreeNode
) then
820 // destroy the parent node
821 if (mNodes
[grandParentNodeId
].children
[TTreeNode
.Left
] = parentNodeId
) then
823 mNodes
[grandParentNodeId
].children
[TTreeNode
.Left
] := siblingNodeId
;
827 {$IFDEF aabbtree_many_asserts}assert(mNodes
[grandParentNodeId
].children
[TTreeNode
.Right
] = parentNodeId
);{$ENDIF}
828 mNodes
[grandParentNodeId
].children
[TTreeNode
.Right
] := siblingNodeId
;
830 mNodes
[siblingNodeId
].parentId
:= grandParentNodeId
;
831 releaseNode(parentNodeId
);
833 // 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
834 currentNodeId
:= grandParentNodeId
;
835 while (currentNodeId
<> TTreeNode
.NullTreeNode
) do
837 // balance the current sub-tree if necessary
838 currentNodeId
:= balanceSubTreeAtNode(currentNodeId
);
840 {$IFDEF aabbtree_many_asserts}assert(not mNodes
[currentNodeId
].leaf
);{$ENDIF}
842 // get the two children of the current node
843 leftChildId
:= mNodes
[currentNodeId
].children
[TTreeNode
.Left
];
844 rightChildId
:= mNodes
[currentNodeId
].children
[TTreeNode
.Right
];
846 // recompute the AABB and the height of the current node
847 mNodes
[currentNodeId
].aabb
.setMergeTwo(mNodes
[leftChildId
].aabb
, mNodes
[rightChildId
].aabb
);
848 mNodes
[currentNodeId
].height
:= dtMaxI(mNodes
[leftChildId
].height
, mNodes
[rightChildId
].height
)+1;
849 {$IFDEF aabbtree_many_asserts}assert(mNodes
[currentNodeId
].height
> 0);{$ENDIF}
851 currentNodeId
:= mNodes
[currentNodeId
].parentId
;
856 // if the parent of the node to remove is the root node, the sibling node becomes the new root node
857 mRootNodeId
:= siblingNodeId
;
858 mNodes
[siblingNodeId
].parentId
:= TTreeNode
.NullTreeNode
;
859 releaseNode(parentNodeId
);
864 // balance the sub-tree of a given node using left or right rotations
865 // the rotation schemes are described in the book "Introduction to Game Physics with Box2D" by Ian Parberry
866 // this method returns the new root node id
867 function TDynAABBTreeBase
.balanceSubTreeAtNode (nodeId
: Integer): Integer;
869 nodeA
, nodeB
, nodeC
, nodeF
, nodeG
: PTreeNode
;
870 nodeBId
, nodeCId
, nodeFId
, nodeGId
: Integer;
871 balanceFactor
: Integer;
873 {$IFDEF aabbtree_many_asserts}assert(nodeId
<> TTreeNode
.NullTreeNode
);{$ENDIF}
875 nodeA
:= @mNodes
[nodeId
];
877 // if the node is a leaf or the height of A's sub-tree is less than 2
878 if (nodeA
.leaf
) or (nodeA
.height
< 2) then begin result
:= nodeId
; exit
; end; // do not perform any rotation
880 // get the two children nodes
881 nodeBId
:= nodeA
.children
[TTreeNode
.Left
];
882 nodeCId
:= nodeA
.children
[TTreeNode
.Right
];
883 {$IFDEF aabbtree_many_asserts}assert((nodeBId
>= 0) and (nodeBId
< mAllocCount
));{$ENDIF}
884 {$IFDEF aabbtree_many_asserts}assert((nodeCId
>= 0) and (nodeCId
< mAllocCount
));{$ENDIF}
885 nodeB
:= @mNodes
[nodeBId
];
886 nodeC
:= @mNodes
[nodeCId
];
888 // compute the factor of the left and right sub-trees
889 balanceFactor
:= nodeC
.height
-nodeB
.height
;
891 // if the right node C is 2 higher than left node B
892 if (balanceFactor
> 1) then
894 {$IFDEF aabbtree_many_asserts}assert(not nodeC
.leaf
);{$ENDIF}
896 nodeFId
:= nodeC
.children
[TTreeNode
.Left
];
897 nodeGId
:= nodeC
.children
[TTreeNode
.Right
];
898 {$IFDEF aabbtree_many_asserts}assert((nodeFId
>= 0) and (nodeFId
< mAllocCount
));{$ENDIF}
899 {$IFDEF aabbtree_many_asserts}assert((nodeGId
>= 0) and (nodeGId
< mAllocCount
));{$ENDIF}
900 nodeF
:= @mNodes
[nodeFId
];
901 nodeG
:= @mNodes
[nodeGId
];
903 nodeC
.children
[TTreeNode
.Left
] := nodeId
;
904 nodeC
.parentId
:= nodeA
.parentId
;
905 nodeA
.parentId
:= nodeCId
;
907 if (nodeC
.parentId
<> TTreeNode
.NullTreeNode
) then
909 if (mNodes
[nodeC
.parentId
].children
[TTreeNode
.Left
] = nodeId
) then
911 mNodes
[nodeC
.parentId
].children
[TTreeNode
.Left
] := nodeCId
;
915 {$IFDEF aabbtree_many_asserts}assert(mNodes
[nodeC
.parentId
].children
[TTreeNode
.Right
] = nodeId
);{$ENDIF}
916 mNodes
[nodeC
.parentId
].children
[TTreeNode
.Right
] := nodeCId
;
921 mRootNodeId
:= nodeCId
;
924 {$IFDEF aabbtree_many_asserts}assert(not nodeC
.leaf
);{$ENDIF}
925 {$IFDEF aabbtree_many_asserts}assert(not nodeA
.leaf
);{$ENDIF}
927 // if the right node C was higher than left node B because of the F node
928 if (nodeF
.height
> nodeG
.height
) then
930 nodeC
.children
[TTreeNode
.Right
] := nodeFId
;
931 nodeA
.children
[TTreeNode
.Right
] := nodeGId
;
932 nodeG
.parentId
:= nodeId
;
934 // recompute the AABB of node A and C
935 nodeA
.aabb
.setMergeTwo(nodeB
.aabb
, nodeG
.aabb
);
936 nodeC
.aabb
.setMergeTwo(nodeA
.aabb
, nodeF
.aabb
);
938 // recompute the height of node A and C
939 nodeA
.height
:= dtMaxI(nodeB
.height
, nodeG
.height
)+1;
940 nodeC
.height
:= dtMaxI(nodeA
.height
, nodeF
.height
)+1;
941 {$IFDEF aabbtree_many_asserts}assert(nodeA
.height
> 0);{$ENDIF}
942 {$IFDEF aabbtree_many_asserts}assert(nodeC
.height
> 0);{$ENDIF}
946 // if the right node C was higher than left node B because of node G
947 nodeC
.children
[TTreeNode
.Right
] := nodeGId
;
948 nodeA
.children
[TTreeNode
.Right
] := nodeFId
;
949 nodeF
.parentId
:= nodeId
;
951 // recompute the AABB of node A and C
952 nodeA
.aabb
.setMergeTwo(nodeB
.aabb
, nodeF
.aabb
);
953 nodeC
.aabb
.setMergeTwo(nodeA
.aabb
, nodeG
.aabb
);
955 // recompute the height of node A and C
956 nodeA
.height
:= dtMaxI(nodeB
.height
, nodeF
.height
)+1;
957 nodeC
.height
:= dtMaxI(nodeA
.height
, nodeG
.height
)+1;
958 {$IFDEF aabbtree_many_asserts}assert(nodeA
.height
> 0);{$ENDIF}
959 {$IFDEF aabbtree_many_asserts}assert(nodeC
.height
> 0);{$ENDIF}
962 // return the new root of the sub-tree
967 // if the left node B is 2 higher than right node C
968 if (balanceFactor
< -1) then
970 {$IFDEF aabbtree_many_asserts}assert(not nodeB
.leaf
);{$ENDIF}
972 nodeFId
:= nodeB
.children
[TTreeNode
.Left
];
973 nodeGId
:= nodeB
.children
[TTreeNode
.Right
];
974 {$IFDEF aabbtree_many_asserts}assert((nodeFId
>= 0) and (nodeFId
< mAllocCount
));{$ENDIF}
975 {$IFDEF aabbtree_many_asserts}assert((nodeGId
>= 0) and (nodeGId
< mAllocCount
));{$ENDIF}
976 nodeF
:= @mNodes
[nodeFId
];
977 nodeG
:= @mNodes
[nodeGId
];
979 nodeB
.children
[TTreeNode
.Left
] := nodeId
;
980 nodeB
.parentId
:= nodeA
.parentId
;
981 nodeA
.parentId
:= nodeBId
;
983 if (nodeB
.parentId
<> TTreeNode
.NullTreeNode
) then
985 if (mNodes
[nodeB
.parentId
].children
[TTreeNode
.Left
] = nodeId
) then
987 mNodes
[nodeB
.parentId
].children
[TTreeNode
.Left
] := nodeBId
;
991 {$IFDEF aabbtree_many_asserts}assert(mNodes
[nodeB
.parentId
].children
[TTreeNode
.Right
] = nodeId
);{$ENDIF}
992 mNodes
[nodeB
.parentId
].children
[TTreeNode
.Right
] := nodeBId
;
997 mRootNodeId
:= nodeBId
;
1000 {$IFDEF aabbtree_many_asserts}assert(not nodeB
.leaf
);{$ENDIF}
1001 {$IFDEF aabbtree_many_asserts}assert(not nodeA
.leaf
);{$ENDIF}
1003 // if the left node B was higher than right node C because of the F node
1004 if (nodeF
.height
> nodeG
.height
) then
1006 nodeB
.children
[TTreeNode
.Right
] := nodeFId
;
1007 nodeA
.children
[TTreeNode
.Left
] := nodeGId
;
1008 nodeG
.parentId
:= nodeId
;
1010 // recompute the AABB of node A and B
1011 nodeA
.aabb
.setMergeTwo(nodeC
.aabb
, nodeG
.aabb
);
1012 nodeB
.aabb
.setMergeTwo(nodeA
.aabb
, nodeF
.aabb
);
1014 // recompute the height of node A and B
1015 nodeA
.height
:= dtMaxI(nodeC
.height
, nodeG
.height
)+1;
1016 nodeB
.height
:= dtMaxI(nodeA
.height
, nodeF
.height
)+1;
1017 {$IFDEF aabbtree_many_asserts}assert(nodeA
.height
> 0);{$ENDIF}
1018 {$IFDEF aabbtree_many_asserts}assert(nodeB
.height
> 0);{$ENDIF}
1022 // if the left node B was higher than right node C because of node G
1023 nodeB
.children
[TTreeNode
.Right
] := nodeGId
;
1024 nodeA
.children
[TTreeNode
.Left
] := nodeFId
;
1025 nodeF
.parentId
:= nodeId
;
1027 // recompute the AABB of node A and B
1028 nodeA
.aabb
.setMergeTwo(nodeC
.aabb
, nodeF
.aabb
);
1029 nodeB
.aabb
.setMergeTwo(nodeA
.aabb
, nodeG
.aabb
);
1031 // recompute the height of node A and B
1032 nodeA
.height
:= dtMaxI(nodeC
.height
, nodeF
.height
)+1;
1033 nodeB
.height
:= dtMaxI(nodeA
.height
, nodeG
.height
)+1;
1034 {$IFDEF aabbtree_many_asserts}assert(nodeA
.height
> 0);{$ENDIF}
1035 {$IFDEF aabbtree_many_asserts}assert(nodeB
.height
> 0);{$ENDIF}
1038 // return the new root of the sub-tree
1043 // if the sub-tree is balanced, return the current root node
1048 // compute the height of a given node in the tree
1049 function TDynAABBTreeBase
.computeHeight (nodeId
: Integer): Integer;
1052 leftHeight
, rightHeight
: Integer;
1054 {$IFDEF aabbtree_many_asserts}assert((nodeId
>= 0) and (nodeId
< mAllocCount
));{$ENDIF}
1055 node
:= @mNodes
[nodeId
];
1057 // if the node is a leaf, its height is zero
1058 if (node
.leaf
) then begin result
:= 0; exit
; end;
1060 // compute the height of the left and right sub-tree
1061 leftHeight
:= computeHeight(node
.children
[TTreeNode
.Left
]);
1062 rightHeight
:= computeHeight(node
.children
[TTreeNode
.Right
]);
1064 // return the height of the node
1065 result
:= 1+dtMaxI(leftHeight
, rightHeight
);
1069 // internally add an object into the tree
1070 function TDynAABBTreeBase
.insertObjectInternal (constref aabb
: AABB2D
; staticObject
: Boolean): Integer;
1075 // get the next available node (or allocate new ones if necessary)
1076 nodeId
:= allocateNode();
1078 node
:= @mNodes
[nodeId
];
1080 // create the fat aabb to use in the tree
1081 node
.aabb
:= AABB2D
.Create(aabb
);
1082 if (not staticObject
) then
1084 node
.aabb
.minX
-= mExtraGap
;
1085 node
.aabb
.minY
-= mExtraGap
;
1086 node
.aabb
.maxX
+= mExtraGap
;
1087 node
.aabb
.maxY
+= mExtraGap
;
1090 // set the height of the node in the tree
1093 // insert the new leaf node in the tree
1094 insertLeafNode(nodeId
);
1096 {$IFDEF aabbtree_many_asserts}node
:= @mNodes
[nodeId
];{$ENDIF}
1097 {$IFDEF aabbtree_many_asserts}assert(node
.leaf
);{$ENDIF}
1099 // return the id of the node
1104 // initialize the tree
1105 procedure TDynAABBTreeBase
.setup ();
1109 mRootNodeId
:= TTreeNode
.NullTreeNode
;
1111 mAllocCount
:= 8192;
1114 SetLength(mNodes
, mAllocCount
);
1115 //memset(mNodes, 0, mAllocCount*TTreeNode.sizeof);
1116 for i
:= 0 to mAllocCount
-1 do mNodes
[i
].clear();
1118 // initialize the allocated nodes
1119 for i
:= 0 to mAllocCount
-1 do
1121 mNodes
[i
].nextNodeId
:= i
+1;
1122 mNodes
[i
].height
:= -1;
1124 mNodes
[mAllocCount
-1].nextNodeId
:= TTreeNode
.NullTreeNode
;
1129 // also, checks if the tree structure is valid (for debugging purpose)
1130 function TDynAABBTreeBase
.forEachNode (nodeId
: Integer; dg
: TForEachLeafCB
): Boolean;
1133 leftChild
, rightChild
, height
: Integer;
1137 if (nodeId
= TTreeNode
.NullTreeNode
) then exit
;
1138 // if it is the root
1139 if (nodeId
= mRootNodeId
) then assert(mNodes
[nodeId
].parentId
= TTreeNode
.NullTreeNode
);
1140 // get the children nodes
1141 pNode
:= @mNodes
[nodeId
];
1142 assert(pNode
.height
>= 0);
1143 if (not pNode
.aabb
.valid
) then
1145 {$IFDEF aabbtree_use_floats}
1146 e_WriteLog(Format('AABB:(%f,%f)-(%f,%f); volume=%f; valid=%d; height=%d; leaf=%d', [pNode
.aabb
.minX
, pNode
.aabb
.minY
, pNode
.aabb
.maxX
, pNode
.aabb
.maxY
, pNode
.aabb
.volume
, Integer(pNode
.aabb
.valid
), pNode
.height
, Integer(pNode
.leaf
)]), MSG_NOTIFY
);
1148 e_WriteLog(Format('AABB:(%d,%d)-(%d,%d); volume=%d; valid=%d; height=%d; leaf=%d', [pNode
.aabb
.minX
, pNode
.aabb
.minY
, pNode
.aabb
.maxX
, pNode
.aabb
.maxY
, pNode
.aabb
.volume
, Integer(pNode
.aabb
.valid
), pNode
.height
, Integer(pNode
.leaf
)]), MSG_NOTIFY
);
1152 getFleshAABB(aabb
, pNode
.flesh
, pNode
.tag
);
1153 {$IFDEF aabbtree_use_floats}
1154 e_WriteLog(Format(' LEAF AABB:(%f,%f)-(%f,%f); valid=%d; volume=%f', [aabb
.minX
, aabb
.minY
, aabb
.maxX
, aabb
.maxY
, Integer(aabb
.valid
), aabb
.volume
]), MSG_NOTIFY
);
1156 e_WriteLog(Format(' LEAF AABB:(%d,%d)-(%d,%d); valid=%d; volume=%d', [aabb
.minX
, aabb
.minY
, aabb
.maxX
, aabb
.maxY
, Integer(aabb
.valid
), aabb
.volume
]), MSG_NOTIFY
);
1160 assert(pNode
.aabb
.valid
);
1161 assert(pNode
.aabb
.volume
> 0);
1162 // if the current node is a leaf
1163 if (pNode
.leaf
) then
1165 assert(pNode
.height
= 0);
1166 if assigned(dg
) then result
:= dg(pNode
.flesh
, pNode
.aabb
);
1170 leftChild
:= pNode
.children
[TTreeNode
.Left
];
1171 rightChild
:= pNode
.children
[TTreeNode
.Right
];
1172 // check that the children node Ids are valid
1173 assert((0 <= leftChild
) and (leftChild
< mAllocCount
));
1174 assert((0 <= rightChild
) and (rightChild
< mAllocCount
));
1175 // check that the children nodes have the correct parent node
1176 assert(mNodes
[leftChild
].parentId
= nodeId
);
1177 assert(mNodes
[rightChild
].parentId
= nodeId
);
1178 // check the height of node
1179 height
:= 1+dtMaxI(mNodes
[leftChild
].height
, mNodes
[rightChild
].height
);
1180 assert(mNodes
[nodeId
].height
= height
);
1181 // check the AABB of the node
1182 aabb
:= AABB2D
.Create(mNodes
[leftChild
].aabb
, mNodes
[rightChild
].aabb
);
1183 assert(aabb
.minX
= mNodes
[nodeId
].aabb
.minX
);
1184 assert(aabb
.minY
= mNodes
[nodeId
].aabb
.minY
);
1185 assert(aabb
.maxX
= mNodes
[nodeId
].aabb
.maxX
);
1186 assert(aabb
.maxY
= mNodes
[nodeId
].aabb
.maxY
);
1187 // recursively check the children nodes
1188 result
:= forEachNode(leftChild
, dg
);
1189 if not result
then result
:= forEachNode(rightChild
, dg
);
1194 // also, checks if the tree structure is valid (for debugging purpose)
1195 function TDynAABBTreeBase
.forEachLeaf (dg
: TForEachLeafCB
): Boolean;
1197 // recursively check each node
1198 result
:= forEachNode(mRootNodeId
, dg
);
1202 // return `true` from visitor to stop immediately
1203 // checker should check if this node should be considered to further checking
1204 // returns tree node if visitor says stop or -1
1205 function TDynAABBTreeBase
.visit (constref caabb
: AABB2D
; mode
: Integer; checker
: TVisitCheckerCB
; visitor
: TQueryOverlapCB
; visdg
: TQueryOverlapDg
; tagmask
: Integer): Integer;
1209 oldvstused
: Integer;
1211 vstk
: array of Integer;
1214 doNode
: Boolean = false;
1216 if not assigned(checker
) then begin result
:= -1; exit
; end;
1217 //if not assigned(visitor) and not assigned(visdg) then raise Exception.Create('dyntree: empty visitors aren''t supported');
1218 oldvstused
:= vstused
;
1219 if (vstused
+StackGran
> Length(vstack
)) then SetLength(vstack
, vstused
+StackGran
);
1223 {$IFDEF aabbtree_query_count}
1225 mNodesDeepVisited
:= 0;
1228 // start from root node
1229 // we can't have nested functions in generics, sorry
1233 if (vsp
>= Length(vstk
)) then SetLength(vstk
, vsp
+StackGran
);
1234 vstk
[vsp
] := mRootNodeId
;
1238 // while there are still nodes to visit
1239 while (vsp
> oldvstused
) do
1241 // get the next node id to visit
1242 // we can't have nested functions in generics, sorry
1247 nodeId
:= vstk
[vsp
];
1249 // skip it if it is a nil node
1250 if (nodeId
= TTreeNode
.NullTreeNode
) then continue
;
1251 {$IFDEF aabbtree_query_count}Inc(mNodesVisited
);{$ENDIF}
1252 // get the corresponding node
1253 node
:= @mNodes
[nodeId
];
1254 // should we investigate this node?
1256 ModeNoChecks
: doNode
:= checker(node
);
1259 //doNode := caabb.overlaps(node.aabb);
1260 // this gives small speedup (or not...)
1261 // exit with no intersection if found separated along any axis
1262 if (caabb
.maxX
< node
.aabb
.minX
) or (caabb
.minX
> node
.aabb
.maxX
) then doNode
:= false
1263 else if (caabb
.maxY
< node
.aabb
.minY
) or (caabb
.minY
> node
.aabb
.maxY
) then doNode
:= false
1264 else doNode
:= true;
1268 //doNode := node.aabb.contains(caabb.minX, caabb.minY);
1269 // this gives small speedup
1270 doNode
:= (caabb
.minX
>= node
.aabb
.minX
) and (caabb
.minY
>= node
.aabb
.minY
) and (caabb
.minX
<= node
.aabb
.maxX
) and (caabb
.minY
<= node
.aabb
.maxY
);
1275 // if the node is a leaf
1278 // call visitor on it
1279 {$IFDEF aabbtree_query_count}Inc(mNodesDeepVisited
);{$ENDIF}
1280 if (tagmask
= -1) or ((node
.tag
and tagmask
) <> 0) then
1283 // update object vars from cache, so recursive calls to `visit()` will work
1287 if assigned(visitor
) then doNode
:= visitor(node
.flesh
, node
.tag
);
1288 if assigned(visdg
) and visdg(node
.flesh
, node
.tag
) then doNode
:= true;
1289 // do some sanity checks
1290 if (vstused
<> vsp
) then raise Exception
.Create('internal error in dyntree visitor');
1296 vstused
:= oldvstused
;
1303 // if the node is not a leaf, we need to visit its children
1304 // we can't have nested functions in generics, sorry
1306 spush(node
.children
[TTreeNode
.Left
]);
1307 spush(node
.children
[TTreeNode
.Right
]);
1309 if (vsp
+2 > Length(vstk
)) then SetLength(vstk
, vsp
+StackGran
);
1310 vstk
[vsp
] := node
.children
[TTreeNode
.Left
];
1312 vstk
[vsp
] := node
.children
[TTreeNode
.Right
];
1319 result
:= -1; // oops
1321 vstused
:= oldvstused
;
1325 // add `extraAABBGap` to bounding boxes so slight object movement won't cause tree rebuilds
1326 // 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
1327 constructor TDynAABBTreeBase
.Create (extraAABBGap
: TreeNumber
=0);
1329 mExtraGap
:= extraAABBGap
;
1331 SetLength(vstack
, 2048);
1337 destructor TDynAABBTreeBase
.Destroy ();
1345 // clear all the nodes and reset the tree
1346 procedure TDynAABBTreeBase
.reset ();
1353 function TDynAABBTreeBase
.computeTreeHeight (): Integer; begin result
:= computeHeight(mRootNodeId
); end;
1356 // return the root AABB of the tree
1357 procedure TDynAABBTreeBase
.getRootAABB (out aabb
: AABB2D
);
1359 {$IFDEF aabbtree_many_asserts}assert((mRootNodeId
>= 0) and (mRootNodeId
< mAllocCount
));{$ENDIF}
1360 aabb
:= mNodes
[mRootNodeId
].aabb
;
1364 // does the given id represents a valid object?
1365 // WARNING: ids of removed objects can be reused on later insertions!
1366 function TDynAABBTreeBase
.isValidId (id
: Integer): Boolean;
1368 result
:= (id
>= 0) and (id
< mAllocCount
) and (mNodes
[id
].leaf
);
1372 // get object by nodeid; can return nil for invalid ids
1373 function TDynAABBTreeBase
.getNodeObjectId (nodeid
: Integer): TTreeFlesh
;
1375 if (nodeid
>= 0) and (nodeid
< mAllocCount
) and (mNodes
[nodeid
].leaf
) then result
:= mNodes
[nodeid
].flesh
else result
:= Default(ITP
);
1378 // get fat object AABB by nodeid; returns random shit for invalid ids
1379 procedure TDynAABBTreeBase
.getNodeFatAABB (out aabb
: AABB2D
; nodeid
: Integer);
1381 if (nodeid
>= 0) and (nodeid
< mAllocCount
) and (not mNodes
[nodeid
].isfree
) then aabb
:= AABB2D
.Create(mNodes
[nodeid
].aabb
) else aabb
:= AABB2D
.Create(0, 0, 0, 0);
1384 function TDynAABBTreeBase
.getNodeXY (nodeid
: Integer; out x
, y
: Integer): Boolean; inline;
1386 if (nodeid
>= 0) and (nodeid
< mAllocCount
) and (mNodes
[nodeid
].leaf
) then
1389 {$IFDEF aabbtree_use_floats}
1390 x
:= round(mNodes
[nodeid
].fleshX
);
1391 y
:= round(mNodes
[nodeid
].fleshY
);
1393 x
:= mNodes
[nodeid
].fleshX
;
1394 y
:= mNodes
[nodeid
].fleshY
;
1402 //if (nodeid >= 0) and (nodeid < mAllocCount) then mNodes[nodeid].dumpToLog();
1407 // insert an object into the tree
1408 // this method creates a new leaf node in the tree and returns the id of the corresponding node or -1 on error
1409 // AABB for static object will not be "fat" (simple optimization)
1410 // WARNING! inserting the same object several times *WILL* break everything!
1411 function TDynAABBTreeBase
.insertObject (flesh
: TTreeFlesh
; tag
: Integer; staticObject
: Boolean=false): Integer;
1414 nodeId
, fx
, fy
: Integer;
1416 if not getFleshAABB(aabb
, flesh
, tag
) then
1418 {$IFDEF aabbtree_use_floats}
1419 e_WriteLog(Format('trying to insert FUCKED FLESH:(%f,%f)-(%f,%f); volume=%f; valid=%d', [aabb
.minX
, aabb
.minY
, aabb
.maxX
, aabb
.maxY
, aabb
.volume
, Integer(aabb
.valid
)]), MSG_WARNING
);
1421 e_WriteLog(Format('trying to insert FUCKED FLESH:(%d,%d)-(%d,%d); volume=%d; valid=%d', [aabb
.minX
, aabb
.minY
, aabb
.maxX
, aabb
.maxY
, aabb
.volume
, Integer(aabb
.valid
)]), MSG_WARNING
);
1423 //raise Exception.Create('trying to insert invalid flesh in dyntree');
1427 if not aabb
.valid
then
1429 {$IFDEF aabbtree_use_floats}
1430 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
);
1432 e_WriteLog(Format('trying to insert FUCKED AABB:(%d,%d)-(%d,%d); volume=%d; valid=%d', [aabb
.minX
, aabb
.minY
, aabb
.maxX
, aabb
.maxY
, aabb
.volume
, Integer(aabb
.valid
)]), MSG_WARNING
);
1434 raise Exception
.Create('trying to insert invalid aabb in dyntree');
1438 //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);
1441 nodeId
:= insertObjectInternal(aabb
, staticObject
);
1442 {$IFDEF aabbtree_many_asserts}assert(mNodes
[nodeId
].leaf
);{$ENDIF}
1443 mNodes
[nodeId
].flesh
:= flesh
;
1444 mNodes
[nodeId
].tag
:= tag
;
1445 mNodes
[nodeId
].fleshX
:= fx
;
1446 mNodes
[nodeId
].fleshY
:= fy
;
1451 // remove an object from the tree
1452 // WARNING: ids of removed objects can be reused on later insertions!
1453 procedure TDynAABBTreeBase
.removeObject (nodeId
: Integer);
1455 if (nodeId
< 0) or (nodeId
>= mAllocCount
) or (not mNodes
[nodeId
].leaf
) then raise Exception
.Create('invalid node id in TDynAABBTreeBase');
1456 // remove the node from the tree
1457 removeLeafNode(nodeId
);
1458 releaseNode(nodeId
);
1462 function TDynAABBTreeBase
.updateObject (nodeId
: Integer; forceReinsert
: Boolean=false): Boolean; overload
;
1465 dispX
, dispY
: TreeNumber
;
1467 if (nodeId
< 0) or (nodeId
>= mAllocCount
) or (not mNodes
[nodeId
].leaf
) then raise Exception
.Create('invalid node id in TDynAABBTreeBase.updateObject');
1469 if not getFleshAABB(newAABB
, mNodes
[nodeId
].flesh
, mNodes
[nodeId
].tag
) then raise Exception
.Create('invalid flesh dimensions in TDynAABBTreeBase.updateObject');
1470 if not newAABB
.valid
then raise Exception
.Create('invalid flesh aabb in TDynAABBTreeBase.updateObject');
1472 dispX
:= newAABB
.minX
-mNodes
[nodeId
].fleshX
;
1473 dispY
:= newAABB
.minY
-mNodes
[nodeId
].fleshY
;
1475 if (dispX
< -16) then dispX
:= -16 else if (dispX
> 16) then dispX
:= 16;
1476 if (dispY
< -16) then dispY
:= -16 else if (dispY
> 16) then dispY
:= 16;
1478 result
:= updateObject(nodeId
, dispX
, dispY
, forceReinsert
);
1481 function TDynAABBTreeBase
.updateObject (nodeId
: Integer; dispX
, dispY
: TreeNumber
; forceReinsert
: Boolean=false): Boolean; overload
;
1487 if (nodeId
< 0) or (nodeId
>= mAllocCount
) or (not mNodes
[nodeId
].leaf
) then raise Exception
.Create('invalid node id in TDynAABBTreeBase.updateObject');
1489 if not getFleshAABB(newAABB
, mNodes
[nodeId
].flesh
, mNodes
[nodeId
].tag
) then raise Exception
.Create('invalid flesh dimensions in TDynAABBTreeBase.updateObject');
1490 if not newAABB
.valid
then raise Exception
.Create('invalid flesh aabb in TDynAABBTreeBase.updateObject');
1495 // if the new AABB is still inside the fat AABB of the node
1496 if (not forceReinsert
) and (mNodes
[nodeId
].aabb
.contains(newAABB
)) then
1498 node
:= @mNodes
[nodeId
];
1505 // if the new AABB is outside the fat AABB, we remove the corresponding node
1506 removeLeafNode(nodeId
);
1508 node
:= @mNodes
[nodeId
];
1510 // compute the fat AABB by inflating the AABB with a constant gap
1511 node
.aabb
.copyFrom(newAABB
);
1515 if (not forceReinsert
) and ((dispX
<> 0) or (dispY
<> 0)) then
1517 node
.aabb
.minX
-= mExtraGap
;
1518 node
.aabb
.minY
+= mExtraGap
;
1519 node
.aabb
.maxX
+= mExtraGap
;
1520 node
.aabb
.maxY
+= mExtraGap
;
1523 // inflate the fat AABB in direction of the linear motion of the AABB
1526 node
.aabb
.minX
+= LinearMotionGapMultiplier
*dispX
{$IFDEF aabbtree_use_floats}{$ELSE}div 10{$ENDIF};
1530 node
.aabb
.maxX
+= LinearMotionGapMultiplier
*dispX
{$IFDEF aabbtree_use_floats}{$ELSE}div 10{$ENDIF};
1535 node
.aabb
.minY
+= LinearMotionGapMultiplier
*dispY
{$IFDEF aabbtree_use_floats}{$ELSE}div 10{$ENDIF};
1539 node
.aabb
.maxY
+= LinearMotionGapMultiplier
*dispY
{$IFDEF aabbtree_use_floats}{$ELSE}div 10{$ENDIF};
1542 {$IFDEF aabbtree_many_asserts}assert(node
.aabb
.contains(newAABB
));{$ENDIF}
1544 // reinsert the node into the tree
1545 insertLeafNode(nodeId
);
1551 function TDynAABBTreeBase
.checkerAABB (node
: PTreeNode
): Boolean;
1553 result
:= chkAABB
.overlaps(node
.aabb
);
1557 // report all shapes overlapping with the AABB given in parameter
1558 function TDynAABBTreeBase
.aabbQuery (ax
, ay
, aw
, ah
: TreeNumber
; cb
: TQueryOverlapCB
; tagmask
: Integer=-1): TTreeFlesh
;
1563 result
:= Default(ITP
);
1564 if not assigned(cb
) then exit
;
1565 if (aw
< 1) or (ah
< 1) then exit
;
1566 //chkAABB := AABB2D.Create(ax, ay, ax+aw, ay+ah);
1570 chkAABB
.maxX
:= ax
+aw
;
1571 chkAABB
.maxY
:= ay
+ah
;
1572 nid
:= visit(chkAABB
, ModeAABB
, checkerAABB
, cb
, nil, tagmask
);
1574 if (nid
>= 0) then result
:= mNodes
[nid
].flesh
else result
:= Default(ITP
);
1578 function TDynAABBTreeBase
.checkerPoint (node
: PTreeNode
): Boolean;
1580 result
:= node
.aabb
.contains(chkAABB
.minX
, chkAABB
.minY
);
1584 // report body that contains the given point, or nil
1585 function TDynAABBTreeBase
.pointQuery (ax
, ay
: TreeNumber
; cb
: TQueryOverlapCB
; tagmask
: Integer=-1): TTreeFlesh
;
1591 chkAABB
:= AABB2D
.Create(ax
, ay
, ax
+1, ay
+1);
1592 nid
:= visit(chkAABB
, ModePoint
, checkerPoint
, cb
, nil, tagmask
);
1593 {$IFDEF aabbtree_many_asserts}assert((nid
< 0) or ((nid
>= 0) and (nid
< mAllocCount
) and (mNodes
[nid
].leaf
)));{$ENDIF}
1595 if (nid
>= 0) then result
:= mNodes
[nid
].flesh
else result
:= Default(ITP
);
1599 function TDynAABBTreeBase
.checkerRay (node
: PTreeNode
): Boolean;
1601 result
:= node
.aabb
.intersects(curax
, curay
, curbx
, curby
);
1604 function TDynAABBTreeBase
.visitorRay (flesh
: TTreeFlesh
; tag
: Integer): Boolean;
1606 hitFraction
: Single;
1608 hitFraction
:= sqcb(flesh
, curax
, curay
, curbx
, curby
);
1609 // if the user returned a hitFraction of zero, it means that the raycasting should stop here
1610 if (hitFraction
= 0.0) then
1613 qSRes
.flesh
:= flesh
;
1617 // if the user returned a positive fraction
1618 if (hitFraction
> 0.0) then
1620 // we update the maxFraction value and the ray AABB using the new maximum fraction
1621 if (hitFraction
< maxFraction
) then
1623 maxFraction
:= hitFraction
;
1624 qSRes
.dist
:= hitFraction
;
1625 qSRes
.flesh
:= flesh
;
1627 //curb := cura+dir*hitFraction;
1628 curbx
:= curax
+dirx
*hitFraction
;
1629 curby
:= curay
+diry
*hitFraction
;
1632 result
:= false; // continue
1636 // segment querying method
1637 function TDynAABBTreeBase
.segmentQuery (out qr
: TSegmentQueryResult
; ax
, ay
, bx
, by
: TreeNumber
; cb
: TSegQueryCallback
; tagmask
: Integer=-1): Boolean;
1639 oldmaxFraction
: Single;
1640 oldcurax
, oldcuray
: Single;
1641 oldcurbx
, oldcurby
: Single;
1642 olddirx
, olddiry
: Single;
1644 osres
: PSegmentQueryResult
;
1645 osqcb
: TSegQueryCallback
;
1647 qr
:= TSegmentQueryResult
.Create(false);
1649 if (ax
>= bx
) or (ay
>= by
) then begin result
:= false; exit
; end;
1651 oldmaxFraction
:= maxFraction
;
1659 maxFraction
:= 1.0e100
; // infinity
1665 dirx
:= curbx
-curax
;
1666 diry
:= curby
-curay
;
1668 invlen
:= 1.0/sqrt(dirx
*dirx
+diry
*diry
);
1672 //chkAABB := AABB2D.Create(0, 0, 1, 1);
1677 visit(chkAABB
, ModeNoChecks
, checkerRay
, nil, visitorRay
, tagmask
);
1687 maxFraction
:= oldmaxFraction
;