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 {.$DEFINE aabbtree_use_floats}
22 interface
24 uses
28 // ////////////////////////////////////////////////////////////////////////// //
29 type
33 // ////////////////////////////////////////////////////////////////////////// //
34 type
36 public
43 public
61 // ////////////////////////////////////////////////////////////////////////// //
62 type
64 public
67 private
76 public
92 // return true if the current AABB contains the AABB given in parameter
96 // return true if the current AABB is overlapping with the AABB in parameter
97 // two AABBs overlap if they overlap in the two axes at the same time
100 // ray direction must be normalized
101 function intersects (constref ray: Ray2D; tmino: PSingle=nil; tmaxo: PSingle=nil): Boolean; overload;
103 function intersects (constref ray: Ray2D; maxtime: Single; tmino: PSingle=nil): Boolean; inline; overload;
116 // ////////////////////////////////////////////////////////////////////////// //
117 (* Dynamic AABB tree (bounding volume hierarchy)
118 * based on the code from ReactPhysics3D physics library, http://www.reactphysics3d.com
119 * Copyright (c) 2010-2016 Daniel Chappuis
120 *
121 * This software is provided 'as-is', without any express or implied warranty.
122 * In no event will the authors be held liable for any damages arising from the
123 * use of this software.
124 *
125 * Permission is granted to anyone to use this software for any purpose,
126 * including commercial applications, and to alter it and redistribute it
127 * freely, subject to the following restrictions:
128 *
129 * 1. The origin of this software must not be misrepresented; you must not claim
130 * that you wrote the original software. If you use this software in a
131 * product, an acknowledgment in the product documentation would be
132 * appreciated but is not required.
133 *
134 * 2. Altered source versions must be plainly marked as such, and must not be
135 * misrepresented as being the original software.
136 *
137 * 3. This notice may not be removed or altered from any source distribution.
138 *)
139 // ////////////////////////////////////////////////////////////////////////// //
140 (*
141 * This class implements a dynamic AABB tree that is used for broad-phase
142 * collision detection. This data structure is inspired by Nathanael Presson's
143 * dynamic tree implementation in BulletPhysics. The following implementation is
144 * based on the one from Erin Catto in Box2D as described in the book
145 * "Introduction to Game Physics with Box2D" by Ian Parberry.
146 *)
147 // ////////////////////////////////////////////////////////////////////////// //
148 // Dynamic AABB Tree: can be used to speed up broad phase in various engines
149 type
151 public
154 private
155 type
158 public
162 public
163 // a node is either in the tree (has a parent) or in the free nodes list (has a next node)
165 //nextNodeId: Integer;
166 // a node is either a leaf (has data) or is an internal node (has children)
167 children: array [0..1] of Integer; // left and right child of the node (children[0] = left child)
168 // height of the node in the tree (-1 for free nodes)
170 // fat axis aligned bounding box (AABB) corresponding to the node
172 //TODO: `flesh` can be united with `children`
176 public
177 // return true if the node is a leaf of the tree
182 //property flesh: Integer read children[0] write children[0];
188 //TVisitVisitorCB = function (abody: TTreeFlesh; atag: Integer): Boolean is nested;
194 public
195 // return `true` to stop
196 type TForEachLeafCB = function (abody: TTreeFlesh; constref aabb: AABB2D): Boolean is nested; // WARNING! don't modify AABB here!
198 public
199 // in the broad-phase collision detection (dynamic AABB tree), the AABBs are
200 // also inflated in direction of the linear motion of the body by mutliplying the
201 // followin constant with the linear velocity and the elapsed time between two frames
202 {$IFDEF aabbtree_use_floats}
204 {$ELSE}
206 {$ENDIF}
208 public
209 // called when a overlapping node has been found during the call to forEachAABBOverlap()
210 // return `true` to stop
212 type TSegQueryCallback = function (abody: TTreeFlesh; var ray: Ray2D): Single is nested; // return hit time
224 private
227 mFreeNodeId: Integer; // id of the first node of the list of free (allocated) nodes in the tree that we can use
231 // extra AABB Gap used to allow the collision shape to move a little bit
232 // without triggering a large modification of the tree which can be costly
237 // for segment query
254 private
263 function visit (constref caabb: AABB2D; mode: Integer; checker: TVisitCheckerCB; visitor: TQueryOverlapCB; visdg: TQueryOverlapDg; tagmask: Integer): Integer;
267 public
268 {$IFDEF aabbtree_query_count}
270 {$ENDIF}
272 public
276 // clear all the nodes and reset the tree
286 // returns `false` if nodeid is not leaf
289 // return `false` for invalid flesh
290 function getFleshAABB (out aabb: AABB2D; flesh: TTreeFlesh; tag: Integer): Boolean; virtual; abstract;
292 // insert an object into the tree
293 // this method creates a new leaf node in the tree and returns the id of the corresponding node or -1 on error
294 // AABB for static object will not be "fat" (simple optimization)
295 // WARNING! inserting the same object several times *WILL* break everything!
296 function insertObject (flesh: TTreeFlesh; tag: Integer=-1; staticObject: Boolean=false): Integer;
298 // remove an object from the tree
299 // WARNING: ids of removed objects can be reused on later insertions!
302 (** update the dynamic tree after an object has moved.
303 *
304 * if the new AABB of the object that has moved is still inside its fat AABB, then nothing is done.
305 * otherwise, the corresponding node is removed and reinserted into the tree.
306 * the method returns true if the object has been reinserted into the tree.
307 * the `dispX` and `dispY` parameters are the linear velocity of the AABB multiplied by the elapsed time between two frames.
308 * if the `forceReinsert` parameter is `true`, we force a removal and reinsertion of the node
309 * (this can be useful if the shape AABB has become much smaller than the previous one for instance).
310 *
311 * note that you should call this method if body's AABB was modified, even if the body wasn't moved.
312 *
313 * if `forceReinsert` = `true` and both `dispX` and `dispY` are zeroes, convert object to "static" (don't extrude AABB).
314 *
315 * return `true` if the tree was modified.
316 *)
317 function updateObject (nodeId: Integer; dispX, dispY: TreeNumber; forceReinsert: Boolean=false): Boolean; overload;
320 function aabbQuery (ax, ay, aw, ah: TreeNumber; cb: TQueryOverlapCB; tagmask: Integer=-1): TTreeFlesh;
322 function segmentQuery (out qr: TSegmentQueryResult; ax, ay, bx, by: TreeNumber; cb: TSegQueryCallback; tagmask: Integer=-1): Boolean;
329 {$IFDEF aabbtree_query_count}
332 {$ELSE}
335 {$ENDIF}
349 implementation
351 uses
352 SysUtils;
355 // ////////////////////////////////////////////////////////////////////////// //
356 function dtMinI (a, b: Integer): Integer; inline; begin if (a < b) then result := a else result := b; end;
357 function dtMaxI (a, b: Integer): Integer; inline; begin if (a > b) then result := a else result := b; end;
359 function dtMinF (a, b: TreeNumber): TreeNumber; inline; begin if (a < b) then result := a else result := b; end;
360 function dtMaxF (a, b: TreeNumber): TreeNumber; inline; begin if (a > b) then result := a else result := b; end;
362 function minSingle (a, b: Single): Single; inline; begin if (a < b) then result := a else result := b; end;
363 function maxSingle (a, b: Single): Single; inline; begin if (a > b) then result := a else result := b; end;
366 // ////////////////////////////////////////////////////////////////////////// //
367 constructor Ray2D.Create (ax, ay: Single; aangle: Single); begin setXYAngle(ax, ay, aangle); end;
368 constructor Ray2D.Create (ax0, ay0, ax1, ay1: Single); begin setX0Y0X1Y1(ax0, ay0, ax1, ay1); end;
372 function Ray2D.getOrigN (idx: Integer): Single; inline; begin if (idx = 0) then result := origX else if (idx = 1) then result := origY else result := 0; end;
373 function Ray2D.getDirN (idx: Integer): Single; inline; begin if (idx = 0) then result := dirX else if (idx = 1) then result := dirY else result := 0; end;
377 begin
385 var
387 begin
394 begin
402 begin
412 begin
418 // ////////////////////////////////////////////////////////////////////////// //
420 begin
425 begin
430 begin
435 begin
442 function AABB2D.getvalid (): Boolean; inline; begin result := (minX <= maxX) and (minY <= maxY); end;
444 {$IFDEF aabbtree_use_floats}
447 {$ELSE}
450 {$ENDIF}
454 function AABB2D.getMinN (idx: Integer): TreeNumber; inline; begin if (idx = 0) then result := minX else if (idx = 1) then result := minY else result := 0; end;
455 function AABB2D.getMaxN (idx: Integer): TreeNumber; inline; begin if (idx = 0) then result := maxX else if (idx = 1) then result := maxY else result := 0; end;
458 begin
463 {$IF DEFINED(D2F_DEBUG)}
465 {$ENDIF}
470 begin
475 {$IF DEFINED(D2F_DEBUG)}
477 {$ENDIF}
482 begin
483 {$IF DEFINED(D2F_DEBUG)}
486 {$ENDIF}
491 {$IF DEFINED(D2F_DEBUG)}
493 {$ENDIF}
498 begin
504 begin
505 {$IF DEFINED(D2F_DEBUG)}
507 {$ENDIF}
512 {$IF DEFINED(D2F_DEBUG)}
514 {$ENDIF}
519 begin
520 result :=
527 begin
533 begin
535 // exit with no intersection if found separated along any axis
542 // something to consider here is that 0 * inf =nan which occurs when the ray starts exactly on the edge of a box
543 // https://tavianator.com/fast-branchless-raybounding-box-intersections-part-2-nans/
544 {
545 function AABB2D.intersects (constref ray: Ray2D; tmino: PSingle=nil; tmaxo: PSingle=nil): Boolean; overload;
546 var
547 dinv, t1, t2, tmp: Single;
548 tmin, tmax: Single;
549 begin
550 // ok with coplanars
551 tmin := -1.0e100;
552 tmax := 1.0e100;
553 // do X
554 if (ray.dirX <> 0.0) then
555 begin
556 dinv := 1.0/ray.dirX;
557 t1 := (minX-ray.origX)*dinv;
558 t2 := (maxX-ray.origX)*dinv;
559 if (t1 < t2) then tmin := t1 else tmin := t2;
560 if (t1 > t2) then tmax := t1 else tmax := t2;
561 end;
562 // do Y
563 if (ray.dirY <> 0.0) then
564 begin
565 dinv := 1.0/ray.dirY;
566 t1 := (minY-ray.origY)*dinv;
567 t2 := (maxY-ray.origY)*dinv;
568 // tmin
569 if (t1 < t2) then tmp := t1 else tmp := t2; // min(t1, t2)
570 if (tmax < tmp) then tmp := tmax; // min(tmax, tmp)
571 if (tmin > tmp) then tmin := tmp; // max(tmin, tmp)
572 // tmax
573 if (t1 > t2) then tmp := t1 else tmp := t2; // max(t1, t2)
574 if (tmin > tmp) then tmp := tmin; // max(tmin, tmp)
575 if (tmax < tmp) then tmax := tmp; // min(tmax, tmp)
576 end;
577 if (tmin > 0) then tmp := tmin else tmp := 0;
578 if (tmax > tmp) then
579 begin
580 if (tmino <> nil) then tmino^ := tmin;
581 if (tmaxo <> nil) then tmaxo^ := tmax;
582 result := true;
583 end
584 else
585 begin
586 result := false;
587 end;
588 end;
589 }
592 function AABB2D.intersects (constref ray: Ray2D; tmino: PSingle=nil; tmaxo: PSingle=nil): Boolean; overload;
593 var
596 begin
600 begin
602 begin
603 //t1 := (self.min[i]-ray.orig[i])/ray.dir[i];
604 //t2 := (self.max[i]-ray.orig[i])/ray.dir[i];
610 end
612 begin
614 exit;
620 begin
627 function AABB2D.intersects (ax, ay, bx, by: Single; tmino: PSingle=nil): Boolean; inline; overload;
628 var
631 begin
634 // it may be faster to first check if start or end point is inside AABB (this is sometimes enough for dyntree)
637 // nope, do it hard way
639 if not intersects(ray, @tmin) then begin if (tmino <> nil) then tmino^ := tmin; result := false; exit; end;
648 function AABB2D.intersects (constref ray: Ray2D; maxtime: Single; tmino: PSingle=nil): Boolean; inline; overload;
649 var
651 begin
653 if (ray.origX >= minX) and (ray.origY >= minY) and (ray.origX <= maxX) and (ray.origY <= maxY) then
654 begin
656 exit;
658 if not intersects(ray, @tmin) then begin if (tmino <> nil) then tmino^ := -1.0; result := false; exit; end;
665 // ////////////////////////////////////////////////////////////////////////// //
666 constructor TDynAABBTreeBase.TSegmentQueryResult.Create (fuckyoufpc: Boolean); begin time := -1; flesh := Default(ITP); end;
667 procedure TDynAABBTreeBase.TSegmentQueryResult.reset (); inline; begin time := -1; flesh := Default(ITP); end;
668 function TDynAABBTreeBase.TSegmentQueryResult.valid (): Boolean; inline; begin result := (time >= 0) and (flesh <> Default(ITP)); end;
671 // ////////////////////////////////////////////////////////////////////////// //
672 function TDynAABBTreeBase.TTreeNode.leaf (): Boolean; inline; begin result := (height = 0); end;
673 function TDynAABBTreeBase.TTreeNode.isfree (): Boolean; inline; begin result := (height = -1); end;
676 begin
690 begin
691 e_WriteLog(Format('NODE: parentId=%d; children=[%d,%d]; height=%d; tag=%d; fleshX=%d; fleshY=%d; aabb=(%d,%d)-(%d,%d)',
692 [parentId, children[0], children[1], Integer(height), tag, fleshX, fleshY, aabb.minX, aabb.minY, aabb.maxX, aabb.maxY]),
693 MSG_NOTIFY);
697 // ////////////////////////////////////////////////////////////////////////// //
698 // allocate and return a node to use in the tree
700 var
703 begin
704 // if there is no more allocated node to use
706 begin
708 // allocate more nodes in the tree
712 // initialize the allocated nodes
714 begin
721 // get the next free node
732 //e_WriteLog(Format('tree: allocated node #%d', [result]), MSG_NOTIFY);
736 // release a node
738 begin
748 //e_WriteLog(Format('tree: released node #%d', [nodeId]), MSG_NOTIFY);
752 // insert a leaf node in the tree
753 // 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
755 var
762 begin
763 // if the tree is empty
765 begin
768 exit;
773 // find the best sibling node for the new node
777 begin
781 // compute the merged AABB
786 // compute the cost of making the current node the sibling of the new node
789 // compute the minimum cost of pushing the new node further down the tree (inheritance cost)
792 // compute the cost of descending into the left child
797 // compute the cost of descending into the right child
802 // 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
805 // it is cheaper to go down into a child of the current node, choose the best child
806 //currentNodeId = (costLeft < costRight ? leftChild : rightChild);
812 // create a new parent for the new node and the sibling node
820 // if the sibling node was not the root node
822 begin
825 begin
827 end
828 else
829 begin
836 end
837 else
838 begin
839 // if the sibling node was the root node
847 // move up in the tree to change the AABBs that have changed
851 begin
852 // balance the sub-tree of the current node if it is not balanced
862 // recompute the height of the node in the tree
866 // recompute the AABB of the node
876 // remove a leaf node from the tree
878 var
881 begin
885 // if we are removing the root node (root node is a leaf in this case)
892 begin
894 end
895 else
896 begin
900 // if the parent of the node to remove is not the root node
902 begin
903 // destroy the parent node
905 begin
907 end
908 else
909 begin
910 {$IFDEF aabbtree_many_asserts}assert(mNodes[grandParentNodeId].children[TTreeNode.Right] = parentNodeId);{$ENDIF}
916 // 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
919 begin
920 // balance the current sub-tree if necessary
925 // get the two children of the current node
929 // recompute the AABB and the height of the current node
931 mNodes[currentNodeId].height := dtMaxI(mNodes[leftChildId].height, mNodes[rightChildId].height)+1;
936 end
937 else
938 begin
939 // if the parent of the node to remove is the root node, the sibling node becomes the new root node
947 // balance the sub-tree of a given node using left or right rotations
948 // the rotation schemes are described in the book "Introduction to Game Physics with Box2D" by Ian Parberry
949 // this method returns the new root node id
951 var
955 begin
960 // if the node is a leaf or the height of A's sub-tree is less than 2
961 if (nodeA.leaf) or (nodeA.height < 2) then begin result := nodeId; exit; end; // do not perform any rotation
963 // get the two children nodes
971 // compute the factor of the left and right sub-trees
974 // if the right node C is 2 higher than left node B
976 begin
991 begin
993 begin
995 end
996 else
997 begin
998 {$IFDEF aabbtree_many_asserts}assert(mNodes[nodeC.parentId].children[TTreeNode.Right] = nodeId);{$ENDIF}
1001 end
1002 else
1003 begin
1010 // if the right node C was higher than left node B because of the F node
1012 begin
1017 // recompute the AABB of node A and C
1021 // recompute the height of node A and C
1026 end
1027 else
1028 begin
1029 // if the right node C was higher than left node B because of node G
1034 // recompute the AABB of node A and C
1038 // recompute the height of node A and C
1045 // return the new root of the sub-tree
1047 exit;
1050 // if the left node B is 2 higher than right node C
1052 begin
1067 begin
1069 begin
1071 end
1072 else
1073 begin
1074 {$IFDEF aabbtree_many_asserts}assert(mNodes[nodeB.parentId].children[TTreeNode.Right] = nodeId);{$ENDIF}
1077 end
1078 else
1079 begin
1086 // if the left node B was higher than right node C because of the F node
1088 begin
1093 // recompute the AABB of node A and B
1097 // recompute the height of node A and B
1102 end
1103 else
1104 begin
1105 // if the left node B was higher than right node C because of node G
1110 // recompute the AABB of node A and B
1114 // recompute the height of node A and B
1121 // return the new root of the sub-tree
1123 exit;
1126 // if the sub-tree is balanced, return the current root node
1131 // compute the height of a given node in the tree
1133 var
1136 begin
1140 // if the node is a leaf, its height is zero
1143 // compute the height of the left and right sub-tree
1147 // return the height of the node
1152 // internally add an object into the tree
1153 function TDynAABBTreeBase.insertObjectInternal (constref aabb: AABB2D; staticObject: Boolean): Integer;
1154 var
1157 begin
1158 // get the next available node (or allocate new ones if necessary)
1163 // create the fat aabb to use in the tree
1166 begin
1173 // set the height of the node in the tree
1176 // insert the new leaf node in the tree
1182 // return the id of the node
1187 // initialize the tree
1189 var
1191 begin
1198 //memset(mNodes, 0, mAllocCount*TTreeNode.sizeof);
1201 // initialize the allocated nodes
1203 begin
1212 // also, checks if the tree structure is valid (for debugging purpose)
1214 var
1218 begin
1221 // if it is the root
1223 // get the children nodes
1227 begin
1228 {$IFDEF aabbtree_use_floats}
1229 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);
1230 {$ELSE}
1231 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);
1232 {$ENDIF}
1234 begin
1236 {$IFDEF aabbtree_use_floats}
1237 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);
1238 {$ELSE}
1239 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);
1240 {$ENDIF}
1245 // if the current node is a leaf
1247 begin
1250 end
1251 else
1252 begin
1255 // check that the children node Ids are valid
1258 // check that the children nodes have the correct parent node
1261 // check the height of node
1264 // check the AABB of the node
1270 // recursively check the children nodes
1277 // also, checks if the tree structure is valid (for debugging purpose)
1279 begin
1280 // recursively check each node
1285 // return `true` from visitor to stop immediately
1286 // checker should check if this node should be considered to further checking
1287 // returns tree node if visitor says stop or -1
1288 function TDynAABBTreeBase.visit (constref caabb: AABB2D; mode: Integer; checker: TVisitCheckerCB; visitor: TQueryOverlapCB; visdg: TQueryOverlapDg; tagmask: Integer): Integer;
1289 const
1291 var
1298 begin
1300 //if not assigned(visitor) and not assigned(visdg) then raise Exception.Create('dyntree: empty visitors aren''t supported');
1306 {$IFDEF aabbtree_query_count}
1309 {$ENDIF}
1311 // start from root node
1312 // we can't have nested functions in generics, sorry
1313 {$IF FALSE}
1315 {$ELSE}
1319 {$ENDIF}
1321 // while there are still nodes to visit
1323 begin
1324 // get the next node id to visit
1325 // we can't have nested functions in generics, sorry
1326 {$IF FALSE}
1328 {$ELSE}
1331 {$ENDIF}
1332 // skip it if it is a nil node
1335 // get the corresponding node
1337 // should we investigate this node?
1340 ModeAABB:
1341 begin
1342 //doNode := caabb.overlaps(node.aabb);
1343 // this gives small speedup (or not...)
1344 // exit with no intersection if found separated along any axis
1349 ModePoint:
1350 begin
1351 //doNode := node.aabb.contains(caabb.minX, caabb.minY);
1352 // this gives small speedup
1353 doNode := (caabb.minX >= node.aabb.minX) and (caabb.minY >= node.aabb.minY) and (caabb.minX <= node.aabb.maxX) and (caabb.minY <= node.aabb.maxY);
1357 begin
1358 // if the node is a leaf
1360 begin
1361 // call visitor on it
1364 begin
1366 // update object vars from cache, so recursive calls to `visit()` will work
1369 // call callbacks
1372 // do some sanity checks
1374 // should we exit?
1376 begin
1380 exit;
1383 end
1384 else
1385 begin
1386 // if the node is not a leaf, we need to visit its children
1387 // we can't have nested functions in generics, sorry
1388 {$IF FALSE}
1391 {$ELSE}
1397 {$ENDIF}
1408 // add `extraAABBGap` to bounding boxes so slight object movement won't cause tree rebuilds
1409 // 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
1411 begin
1421 begin
1428 // clear all the nodes and reset the tree
1430 begin
1436 function TDynAABBTreeBase.computeTreeHeight (): Integer; begin result := computeHeight(mRootNodeId); end;
1439 // return the root AABB of the tree
1441 begin
1442 {$IFDEF aabbtree_many_asserts}assert((mRootNodeId >= 0) and (mRootNodeId < mAllocCount));{$ENDIF}
1447 // does the given id represents a valid object?
1448 // WARNING: ids of removed objects can be reused on later insertions!
1450 begin
1455 // get object by nodeid; can return nil for invalid ids
1457 begin
1458 if (nodeid >= 0) and (nodeid < mAllocCount) and (mNodes[nodeid].leaf) then result := mNodes[nodeid].flesh else result := Default(ITP);
1461 // get fat object AABB by nodeid; returns random shit for invalid ids
1463 begin
1464 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);
1468 begin
1470 begin
1472 {$IFDEF aabbtree_use_floats}
1475 {$ELSE}
1478 {$ENDIF}
1479 end
1480 else
1481 begin
1485 //if (nodeid >= 0) and (nodeid < mAllocCount) then mNodes[nodeid].dumpToLog();
1490 // insert an object into the tree
1491 // this method creates a new leaf node in the tree and returns the id of the corresponding node or -1 on error
1492 // AABB for static object will not be "fat" (simple optimization)
1493 // WARNING! inserting the same object several times *WILL* break everything!
1494 function TDynAABBTreeBase.insertObject (flesh: TTreeFlesh; tag: Integer; staticObject: Boolean=false): Integer;
1495 var
1498 begin
1500 begin
1501 {$IFDEF aabbtree_use_floats}
1502 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);
1503 {$ELSE}
1504 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);
1505 {$ENDIF}
1506 //raise Exception.Create('trying to insert invalid flesh in dyntree');
1508 exit;
1511 begin
1512 {$IFDEF aabbtree_use_floats}
1513 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);
1514 {$ELSE}
1515 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);
1516 {$ENDIF}
1519 exit;
1521 //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);
1534 // remove an object from the tree
1535 // WARNING: ids of removed objects can be reused on later insertions!
1537 begin
1538 if (nodeId < 0) or (nodeId >= mAllocCount) or (not mNodes[nodeId].leaf) then raise Exception.Create('invalid node id in TDynAABBTreeBase');
1539 // remove the node from the tree
1545 function TDynAABBTreeBase.updateObject (nodeId: Integer; forceReinsert: Boolean=false): Boolean; overload;
1546 var
1549 begin
1550 if (nodeId < 0) or (nodeId >= mAllocCount) or (not mNodes[nodeId].leaf) then raise Exception.Create('invalid node id in TDynAABBTreeBase.updateObject');
1552 if not getFleshAABB(newAABB, mNodes[nodeId].flesh, mNodes[nodeId].tag) then raise Exception.Create('invalid flesh dimensions in TDynAABBTreeBase.updateObject');
1553 if not newAABB.valid then raise Exception.Create('invalid flesh aabb in TDynAABBTreeBase.updateObject');
1564 function TDynAABBTreeBase.updateObject (nodeId: Integer; dispX, dispY: TreeNumber; forceReinsert: Boolean=false): Boolean; overload;
1565 var
1569 begin
1570 if (nodeId < 0) or (nodeId >= mAllocCount) or (not mNodes[nodeId].leaf) then raise Exception.Create('invalid node id in TDynAABBTreeBase.updateObject');
1572 if not getFleshAABB(newAABB, mNodes[nodeId].flesh, mNodes[nodeId].tag) then raise Exception.Create('invalid flesh dimensions in TDynAABBTreeBase.updateObject');
1573 if not newAABB.valid then raise Exception.Create('invalid flesh aabb in TDynAABBTreeBase.updateObject');
1578 // if the new AABB is still inside the fat AABB of the node
1580 begin
1585 exit;
1588 // if the new AABB is outside the fat AABB, we remove the corresponding node
1593 // compute the fat AABB by inflating the AABB with a constant gap
1599 begin
1606 // inflate the fat AABB in direction of the linear motion of the AABB
1608 begin
1609 node.aabb.minX += LinearMotionGapMultiplier*dispX {$IFDEF aabbtree_use_floats}{$ELSE}div 10{$ENDIF};
1610 end
1611 else
1612 begin
1613 node.aabb.maxX += LinearMotionGapMultiplier*dispX {$IFDEF aabbtree_use_floats}{$ELSE}div 10{$ENDIF};
1617 begin
1618 node.aabb.minY += LinearMotionGapMultiplier*dispY {$IFDEF aabbtree_use_floats}{$ELSE}div 10{$ENDIF};
1619 end
1620 else
1621 begin
1622 node.aabb.maxY += LinearMotionGapMultiplier*dispY {$IFDEF aabbtree_use_floats}{$ELSE}div 10{$ENDIF};
1627 // reinsert the node into the tree
1635 begin
1640 // report all shapes overlapping with the AABB given in parameter
1641 function TDynAABBTreeBase.aabbQuery (ax, ay, aw, ah: TreeNumber; cb: TQueryOverlapCB; tagmask: Integer=-1): TTreeFlesh;
1642 var
1645 begin
1649 //chkAABB := AABB2D.Create(ax, ay, ax+aw, ay+ah);
1662 begin
1667 // report body that contains the given point, or nil
1668 function TDynAABBTreeBase.pointQuery (ax, ay: TreeNumber; cb: TQueryOverlapCB; tagmask: Integer=-1): TTreeFlesh;
1669 var
1672 begin
1676 {$IFDEF aabbtree_many_asserts}assert((nid < 0) or ((nid >= 0) and (nid < mAllocCount) and (mNodes[nid].leaf)));{$ENDIF}
1683 var
1685 begin
1686 {$IF FALSE}
1695 tmin,
1698 {$ELSE}
1700 {
1701 e_WriteLog(Format('intersect: (%f,%f)-(%f,%f) (%d,%d)-(%d,%d) tmin=%f res=%d frac=%f', [
1702 curax, curay, curbx, curby,
1703 node.aabb.minX, node.aabb.minY,
1704 node.aabb.maxX, node.aabb.maxY,
1705 tmin,
1706 Integer(result),
1707 maxFraction
1708 ]), MSG_NOTIFY);
1709 }
1710 {$ENDIF}
1715 var
1718 begin
1724 // if the user returned a hitFraction of zero, it means that the raycasting should stop here
1726 begin
1730 exit;
1732 // if the user returned a positive fraction
1734 begin
1735 // we update the maxFraction value and the ray AABB using the new maximum fraction
1737 begin
1741 // fix curb here
1742 //curb := cura+dir*hitFraction;
1751 // segment querying method
1752 function TDynAABBTreeBase.segmentQuery (out qr: TSegmentQueryResult; ax, ay, bx, by: TreeNumber; cb: TSegQueryCallback; tagmask: Integer=-1): Boolean;
1753 var
1762 begin
1784 // normalize
1794 //chkAABB := AABB2D.Create(0, 0, 1, 1);