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 // universal spatial grid
17 {$INCLUDE ../shared/a_modes.inc}
24 TBodyProxyId
= Integer;
26 generic TBodyGridBase
<ITP
> = class(TObject
)
28 type TGridQueryCB
= function (obj
: ITP
; tag
: Integer): Boolean is nested
; // return `true` to stop
29 type TGridRayQueryCB
= function (obj
: ITP
; tag
: Integer; x
, y
, prevx
, prevy
: Integer): Boolean is nested
; // return `true` to stop
30 type TGridAlongQueryCB
= function (obj
: ITP
; tag
: Integer): Boolean is nested
; // return `true` to stop
32 const TagDisabled
= $40000000;
33 const TagFullMask
= $3fffffff;
37 GridDefaultTileSize
= 32;
38 GridCellBucketSize
= 8; // WARNING! can't be less than 2!
42 PBodyProxyRec
= ^TBodyProxyRec
;
43 TBodyProxyRec
= record
45 mX
, mY
, mWidth
, mHeight
: Integer; // aabb
46 mQueryMark
: LongWord; // was this object visited at this query?
48 mTag
: Integer; // `TagDisabled` set: disabled ;-)
49 nextLink
: TBodyProxyId
; // next free or nothing
52 procedure setup (aX
, aY
, aWidth
, aHeight
: Integer; aObj
: ITP
; aTag
: Integer);
55 PGridCell
= ^TGridCell
;
57 bodies
: array [0..GridCellBucketSize
-1] of Integer; // -1: end of list
58 next
: Integer; // in this cell; index in mCells
61 TGridInternalCB
= function (grida
: Integer; bodyId
: TBodyProxyId
): Boolean of object; // return `true` to stop
65 const mTileSize
= GridDefaultTileSize
;
68 mMinX
, mMinY
: Integer; // so grids can start at any origin
69 mWidth
, mHeight
: Integer; // in tiles
70 mGrid
: array of Integer; // mWidth*mHeight, index in mCells
71 mCells
: array of TGridCell
; // cell pool
72 mFreeCell
: Integer; // first free cell index or -1
75 mProxies
: array of TBodyProxyRec
;
76 mProxyFree
: TBodyProxyId
; // free
77 mProxyCount
: Integer; // currently used
78 mProxyMaxCount
: Integer;
81 dbgShowTraceLog
: Boolean;
84 function allocCell (): Integer;
85 procedure freeCell (idx
: Integer); // `next` is simply overwritten
87 function allocProxy (aX
, aY
, aWidth
, aHeight
: Integer; aObj
: ITP
; aTag
: Integer): TBodyProxyId
;
88 procedure freeProxy (body
: TBodyProxyId
);
90 procedure insertInternal (body
: TBodyProxyId
);
91 procedure removeInternal (body
: TBodyProxyId
);
93 function forGridRect (x
, y
, w
, h
: Integer; cb
: TGridInternalCB
; bodyId
: TBodyProxyId
): Boolean;
95 function inserter (grida
: Integer; bodyId
: TBodyProxyId
): Boolean;
96 function remover (grida
: Integer; bodyId
: TBodyProxyId
): Boolean;
98 function getProxyEnabled (pid
: TBodyProxyId
): Boolean; inline;
99 procedure setProxyEnabled (pid
: TBodyProxyId
; val
: Boolean); inline;
101 function getGridWidthPx (): Integer; inline;
102 function getGridHeightPx (): Integer; inline;
105 constructor Create (aMinPixX
, aMinPixY
, aPixWidth
, aPixHeight
: Integer{; aTileSize: Integer=GridDefaultTileSize});
106 destructor Destroy (); override;
108 function insertBody (aObj
: ITP
; ax
, ay
, aWidth
, aHeight
: Integer; aTag
: Integer=-1): TBodyProxyId
;
109 procedure removeBody (body
: TBodyProxyId
); // WARNING! this WILL destroy proxy!
111 procedure moveBody (body
: TBodyProxyId
; dx
, dy
: Integer);
112 procedure resizeBody (body
: TBodyProxyId
; sx
, sy
: Integer);
113 procedure moveResizeBody (body
: TBodyProxyId
; dx
, dy
, sx
, sy
: Integer);
115 function insideGrid (x
, y
: Integer): Boolean; inline;
117 // `false` if `body` is surely invalid
118 function getBodyXY (body
: TBodyProxyId
; out rx
, ry
: Integer): Boolean; inline;
120 //WARNING: don't modify grid while any query is in progress (no checks are made!)
121 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
122 // no callback: return `true` on the first hit
123 function forEachInAABB (x
, y
, w
, h
: Integer; cb
: TGridQueryCB
; tagmask
: Integer=-1; allowDisabled
: Boolean=false): ITP
;
125 //WARNING: don't modify grid while any query is in progress (no checks are made!)
126 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
127 // no callback: return `true` on the first hit
128 function forEachAtPoint (x
, y
: Integer; cb
: TGridQueryCB
; tagmask
: Integer=-1): ITP
;
130 //WARNING: don't modify grid while any query is in progress (no checks are made!)
131 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
132 // cb with `(nil)` will be called before processing new tile
133 // no callback: return `true` on the nearest hit
134 function traceRay (x0
, y0
, x1
, y1
: Integer; cb
: TGridRayQueryCB
; tagmask
: Integer=-1): ITP
; overload
;
135 function traceRay (out ex
, ey
: Integer; ax0
, ay0
, ax1
, ay1
: Integer; cb
: TGridRayQueryCB
; tagmask
: Integer=-1): ITP
;
137 //WARNING: don't modify grid while any query is in progress (no checks are made!)
138 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
139 // trace line along the grid, calling `cb` for all objects in passed cells, in no particular order
140 function forEachAlongLine (x0
, y0
, x1
, y1
: Integer; cb
: TGridAlongQueryCB
; tagmask
: Integer=-1): ITP
;
142 procedure dumpStats ();
144 //WARNING! no sanity checks!
145 property proxyEnabled
[pid
: TBodyProxyId
]: Boolean read getProxyEnabled write setProxyEnabled
;
147 property gridX0
: Integer read mMinX
;
148 property gridY0
: Integer read mMinY
;
149 property gridWidth
: Integer read getGridWidthPx
; // in pixels
150 property gridHeight
: Integer read getGridHeightPx
; // in pixels
154 // you are not supposed to understand this
155 // returns `true` if there is an intersection, and enter coords
156 // enter coords will be equal to (x0, y0) if starting point is inside the box
157 // if result is `false`, `inx` and `iny` are undefined
158 function lineAABBIntersects (x0
, y0
, x1
, y1
: Integer; bx
, by
, bw
, bh
: Integer; out inx
, iny
: Integer; log
: Boolean=false): Boolean;
161 procedure swapInt (var a
: Integer; var b
: Integer); inline;
162 function distanceSq (x0
, y0
, x1
, y1
: Integer): Integer; inline;
171 // ////////////////////////////////////////////////////////////////////////// //
172 procedure swapInt (var a
: Integer; var b
: Integer); inline; var t
: Integer; begin t
:= a
; a
:= b
; b
:= t
; end;
174 function distanceSq (x0
, y0
, x1
, y1
: Integer): Integer; inline; begin result
:= (x1
-x0
)*(x1
-x0
)+(y1
-y0
)*(y1
-y0
); end;
177 // ////////////////////////////////////////////////////////////////////////// //
178 // you are not supposed to understand this
179 // returns `true` if there is an intersection, and enter coords
180 // enter coords will be equal to (x0, y0) if starting point is inside the box
181 // if result is `false`, `inx` and `iny` are undefined
182 function lineAABBIntersects (x0
, y0
, x1
, y1
: Integer; bx
, by
, bw
, bh
: Integer; out inx
, iny
: Integer; log
: Boolean=false): Boolean;
184 wx0
, wy0
, wx1
, wy1
: Integer; // window coordinates
185 stx
, sty
: Integer; // "steps" for x and y axes
186 dsx
, dsy
: Integer; // "lengthes" for x and y axes
187 dx2
, dy2
: Integer; // "double lengthes" for x and y axes
188 xd
, yd
: Integer; // current coord
189 e
: Integer; // "error" (as in bresenham algo)
200 if (bw
< 1) or (bh
< 1) then exit
; // impossible box
202 if (x0
= x1
) and (y0
= y1
) then
205 result
:= (x0
>= bx
) and (y0
>= by
) and (x0
< bx
+bw
) and (y0
< by
+bh
);
209 // check if staring point is inside the box
210 if (x0
>= bx
) and (y0
>= by
) and (x0
< bx
+bw
) and (y0
< by
+bh
) then begin result
:= true; exit
; end;
218 if log
then e_WriteLog('lineAABBIntersects: 0', MSG_NOTIFY
);
222 // from left to right
223 if (x0
> wx1
) or (x1
< wx0
) then exit
; // out of screen
224 stx
:= 1; // going right
228 // from right to left
229 if (x1
> wx1
) or (x0
< wx0
) then exit
; // out of screen
230 stx
:= -1; // going left
238 if log
then e_WriteLog('lineAABBIntersects: 1', MSG_NOTIFY
);
242 // from top to bottom
243 if (y0
> wy1
) or (y1
< wy0
) then exit
; // out of screen
244 sty
:= 1; // going down
248 // from bottom to top
249 if (y1
> wy1
) or (y0
< wy0
) then exit
; // out of screen
250 sty
:= -1; // going up
285 if log
then e_WriteLog('lineAABBIntersects: 2', MSG_NOTIFY
);
290 temp
:= dx2
*(wy0
-y0
)-dsx
;
293 if (xd
> wx1
) then exit
; // x is moved out of clipping rect, nothing to do
294 if (xd
+1 >= wx0
) then
298 if (rem
> 0) then begin Inc(xd
); e
+= dy2
; end;
303 if log
then e_WriteLog('lineAABBIntersects: 3', MSG_NOTIFY
);
304 if (not xfixed
) and (x0
< wx0
) then
307 temp
:= dy2
*(wx0
-x0
);
310 if (yd
> wy1
) or (yd
= wy1
) and (rem
>= dsx
) then exit
;
313 if (rem
>= dsx
) then begin Inc(yd
); e
-= dx2
; end;
316 if log
then e_WriteLog('lineAABBIntersects: 4', MSG_NOTIFY
);
320 temp
:= dx2
*(wy1
-y0
)+dsx
;
321 term
:= x0
+temp
div dy2
;
323 if (rem
= 0) then Dec(term
);
326 if (term
> wx1
) then term
:= wx1
; // clip at right
328 Inc(term
); // draw last point
329 //if (term = xd) then exit; // this is the only point, get out of here
331 if (sty
= -1) then yd
:= -yd
;
332 if (stx
= -1) then begin xd
:= -xd
; term
:= -term
; end;
335 if log
then e_WriteLog('lineAABBIntersects: 5', MSG_NOTIFY
);
342 // ////////////////////////////////////////////////////////////////////////// //
343 procedure TBodyGridBase
.TBodyProxyRec
.setup (aX
, aY
, aWidth
, aHeight
: Integer; aObj
: ITP
; aTag
: Integer);
356 // ////////////////////////////////////////////////////////////////////////// //
357 constructor TBodyGridBase
.Create (aMinPixX
, aMinPixY
, aPixWidth
, aPixHeight
: Integer{; aTileSize: Integer=GridDefaultTileSize});
361 dbgShowTraceLog
:= false;
363 if aTileSize < 1 then aTileSize := 1;
364 if aTileSize > 8192 then aTileSize := 8192; // arbitrary limit
365 mTileSize := aTileSize;
367 if (aPixWidth
< mTileSize
) then aPixWidth
:= mTileSize
;
368 if (aPixHeight
< mTileSize
) then aPixHeight
:= mTileSize
;
371 mWidth
:= (aPixWidth
+mTileSize
-1) div mTileSize
;
372 mHeight
:= (aPixHeight
+mTileSize
-1) div mTileSize
;
373 SetLength(mGrid
, mWidth
*mHeight
);
374 SetLength(mCells
, mWidth
*mHeight
);
375 SetLength(mProxies
, 8192);
378 for idx
:= 0 to High(mCells
) do
380 mCells
[idx
].bodies
[0] := -1;
381 mCells
[idx
].next
:= idx
+1;
383 mCells
[High(mCells
)].next
:= -1; // last cell
385 for idx
:= 0 to High(mGrid
) do mGrid
[idx
] := -1;
387 for idx
:= 0 to High(mProxies
) do mProxies
[idx
].nextLink
:= idx
+1;
388 mProxies
[High(mProxies
)].nextLink
:= -1;
394 e_WriteLog(Format('created grid with size: %dx%d (tile size: %d); pix: %dx%d', [mWidth
, mHeight
, mTileSize
, mWidth
*mTileSize
, mHeight
*mTileSize
]), MSG_NOTIFY
);
398 destructor TBodyGridBase
.Destroy ();
407 // ////////////////////////////////////////////////////////////////////////// //
408 procedure TBodyGridBase
.dumpStats ();
410 idx
, mcb
, cidx
, cnt
: Integer;
413 for idx
:= 0 to High(mGrid
) do
420 cidx
:= mCells
[cidx
].next
;
422 if (mcb
< cnt
) then mcb
:= cnt
;
424 e_WriteLog(Format('grid size: %dx%d (tile size: %d); pix: %dx%d; used cells: %d; max bodies in cell: %d; max proxies allocated: %d; proxies used: %d', [mWidth
, mHeight
, mTileSize
, mWidth
*mTileSize
, mHeight
*mTileSize
, mUsedCells
, mcb
, mProxyMaxCount
, mProxyCount
]), MSG_NOTIFY
);
428 // ////////////////////////////////////////////////////////////////////////// //
429 function TBodyGridBase
.getGridWidthPx (): Integer; inline; begin result
:= mWidth
*mTileSize
; end;
430 function TBodyGridBase
.getGridHeightPx (): Integer; inline; begin result
:= mHeight
*mTileSize
; end;
433 function TBodyGridBase
.insideGrid (x
, y
: Integer): Boolean; inline;
438 result
:= (x
>= 0) and (y
>= 0) and (x
< mWidth
*mTileSize
) and (y
< mHeight
*mTileSize
);
442 function TBodyGridBase
.getBodyXY (body
: TBodyProxyId
; out rx
, ry
: Integer): Boolean; inline;
444 if (body
>= 0) and (body
< Length(mProxies
)) then
446 with mProxies
[body
] do begin rx
:= mX
; ry
:= mY
; end;
458 // ////////////////////////////////////////////////////////////////////////// //
459 function TBodyGridBase
.getProxyEnabled (pid
: TBodyProxyId
): Boolean; inline;
461 if (pid
>= 0) then result
:= ((mProxies
[pid
].mTag
and TagDisabled
) = 0) else result
:= false;
465 procedure TBodyGridBase
.setProxyEnabled (pid
: TBodyProxyId
; val
: Boolean); inline;
471 mProxies
[pid
].mTag
:= mProxies
[pid
].mTag
and not TagDisabled
;
475 mProxies
[pid
].mTag
:= mProxies
[pid
].mTag
or TagDisabled
;
481 // ////////////////////////////////////////////////////////////////////////// //
482 function TBodyGridBase
.allocCell (): Integer;
486 if (mFreeCell
< 0) then
488 // no free cells, want more
489 mFreeCell
:= Length(mCells
);
490 SetLength(mCells
, mFreeCell
+32768); // arbitrary number
491 for idx
:= mFreeCell
to High(mCells
) do
493 mCells
[idx
].bodies
[0] := -1;
494 mCells
[idx
].next
:= idx
+1;
496 mCells
[High(mCells
)].next
:= -1; // last cell
499 mFreeCell
:= mCells
[result
].next
;
500 mCells
[result
].next
:= -1;
501 mCells
[result
].bodies
[0] := -1;
503 //e_WriteLog(Format('grid: allocated new cell #%d (total: %d)', [result, mUsedCells]), MSG_NOTIFY);
507 procedure TBodyGridBase
.freeCell (idx
: Integer);
509 if (idx
>= 0) and (idx
< Length(mCells
)) then
511 //if mCells[idx].body = -1 then exit; // the thing that should not be
512 mCells
[idx
].bodies
[0] := -1;
513 mCells
[idx
].next
:= mFreeCell
;
520 // ////////////////////////////////////////////////////////////////////////// //
521 function TBodyGridBase
.allocProxy (aX
, aY
, aWidth
, aHeight
: Integer; aObj
: ITP
; aTag
: Integer): TBodyProxyId
;
526 if (mProxyFree
= -1) then
528 // no free proxies, resize list
529 olen
:= Length(mProxies
);
530 SetLength(mProxies
, olen
+8192); // arbitrary number
531 for idx
:= olen
to High(mProxies
) do mProxies
[idx
].nextLink
:= idx
+1;
532 mProxies
[High(mProxies
)].nextLink
:= -1;
536 result
:= mProxyFree
;
537 px
:= @mProxies
[result
];
538 mProxyFree
:= px
.nextLink
;
539 px
.setup(aX
, aY
, aWidth
, aHeight
, aObj
, aTag
);
544 if (mProxyMaxCount
< mProxyCount
) then mProxyMaxCount
:= mProxyCount
;
547 procedure TBodyGridBase
.freeProxy (body
: TBodyProxyId
);
549 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
550 if (mProxyCount
= 0) then raise Exception
.Create('wutafuuuuu in grid (no allocated proxies, what i should free now?)');
552 mProxies
[body
].mObj
:= nil;
553 mProxies
[body
].nextLink
:= mProxyFree
;
559 // ////////////////////////////////////////////////////////////////////////// //
560 function TBodyGridBase
.forGridRect (x
, y
, w
, h
: Integer; cb
: TGridInternalCB
; bodyId
: TBodyProxyId
): Boolean;
568 if (w
< 1) or (h
< 1) or not assigned(cb
) then exit
;
573 if (x
+w
<= 0) or (y
+h
<= 0) then exit
;
576 //tsize := mTileSize;
577 if (x
>= gw
*tsize
) or (y
>= gh
*tsize
) then exit
;
578 for gy
:= y
div tsize
to (y
+h
-1) div tsize
do
580 if (gy
< 0) then continue
;
581 if (gy
>= gh
) then break
;
582 for gx
:= x
div tsize
to (x
+w
-1) div tsize
do
584 if (gx
< 0) then continue
;
585 if (gx
>= gw
) then break
;
586 result
:= cb(gy
*gw
+gx
, bodyId
);
593 // ////////////////////////////////////////////////////////////////////////// //
594 function TBodyGridBase
.inserter (grida
: Integer; bodyId
: TBodyProxyId
): Boolean;
601 result
:= false; // never stop
602 // add body to the given grid cell
608 for f
:= 0 to High(TGridCell
.bodies
) do
610 if (pi
.bodies
[f
] = -1) then
613 pi
.bodies
[f
] := bodyId
;
614 if (f
+1 < Length(TGridCell
.bodies
)) then pi
.bodies
[f
+1] := -1;
619 // either no room, or no cell at all
621 mCells
[cidx
].bodies
[0] := bodyId
;
622 mCells
[cidx
].bodies
[1] := -1;
623 mCells
[cidx
].next
:= pc
;
624 mGrid
[grida
] := cidx
;
627 procedure TBodyGridBase
.insertInternal (body
: TBodyProxyId
);
631 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
632 px
:= @mProxies
[body
];
633 forGridRect(px
.mX
, px
.mY
, px
.mWidth
, px
.mHeight
, inserter
, body
);
637 // absolutely not tested
638 function TBodyGridBase
.remover (grida
: Integer; bodyId
: TBodyProxyId
): Boolean;
641 pidx
, idx
, tmp
: Integer;
644 result
:= false; // never stop
645 // find and remove cell
650 tmp
:= mCells
[idx
].next
;
653 while (f
< High(TGridCell
.bodies
)) do
655 if (pc
.bodies
[f
] = bodyId
) then
658 if (f
= 0) and (pc
.bodies
[1] = -1) then
660 // this cell contains no elements, remove it
661 tmp
:= mCells
[idx
].next
;
662 if (pidx
= -1) then mGrid
[grida
] := tmp
else mCells
[pidx
].next
:= tmp
;
667 // remove element from bucket
669 while (f
< High(TGridCell
.bodies
)) do
671 pc
.bodies
[f
-1] := pc
.bodies
[f
];
672 if (pc
.bodies
[f
] = -1) then break
;
675 pc
.bodies
[High(TGridCell
.bodies
)] := -1; // just in case
677 exit
; // assume that we cannot have one object added to bucket twice
686 // absolutely not tested
687 procedure TBodyGridBase
.removeInternal (body
: TBodyProxyId
);
691 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
692 px
:= @mProxies
[body
];
693 forGridRect(px
.mX
, px
.mY
, px
.mWidth
, px
.mHeight
, remover
, body
);
697 // ////////////////////////////////////////////////////////////////////////// //
698 function TBodyGridBase
.insertBody (aObj
: ITP
; aX
, aY
, aWidth
, aHeight
: Integer; aTag
: Integer=-1): TBodyProxyId
;
700 aTag
:= aTag
and TagFullMask
;
701 result
:= allocProxy(aX
, aY
, aWidth
, aHeight
, aObj
, aTag
);
702 insertInternal(result
);
706 procedure TBodyGridBase
.removeBody (body
: TBodyProxyId
);
708 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
709 removeInternal(body
);
714 // ////////////////////////////////////////////////////////////////////////// //
715 procedure TBodyGridBase
.moveResizeBody (body
: TBodyProxyId
; dx
, dy
, sx
, sy
: Integer);
718 x0
, y0
, w
, h
: Integer;
720 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
721 if (dx
= 0) and (dy
= 0) and (sx
= 0) and (sy
= 0) then exit
;
722 px
:= @mProxies
[body
];
727 // did any corner crossed tile boundary?
728 if (x0
div mTileSize
<> (x0
+dx
) div mTileSize
) or
729 (y0
div mTileSize
<> (y0
+dx
) div mTileSize
) or
730 ((x0
+w
) div mTileSize
<> (x0
+w
+sx
) div mTileSize
) or
731 ((y0
+h
) div mTileSize
<> (y0
+h
+sy
) div mTileSize
) then
733 removeInternal(body
);
738 insertInternal(body
);
749 procedure TBodyGridBase
.moveBody (body
: TBodyProxyId
; dx
, dy
: Integer);
754 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
755 if (dx
= 0) and (dy
= 0) then exit
;
756 // check if tile coords was changed
757 px
:= @mProxies
[body
];
760 if (nx
div mTileSize
<> px
.mX
div mTileSize
) or (ny
div mTileSize
<> px
.mY
div mTileSize
) then
762 // crossed tile boundary, do heavy work
763 moveResizeBody(body
, dx
, dy
, 0, 0);
767 // nothing to do with the grid, just fix coordinates
773 procedure TBodyGridBase
.resizeBody (body
: TBodyProxyId
; sx
, sy
: Integer);
779 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
780 if (sx
= 0) and (sy
= 0) then exit
;
781 // check if tile coords was changed
782 px
:= @mProxies
[body
];
787 if ((x0
+px
.mWidth
) div mTileSize
<> (x0
+nw
) div mTileSize
) or
788 ((y0
+px
.mHeight
) div mTileSize
<> (y0
+nh
) div mTileSize
) then
790 // crossed tile boundary, do heavy work
791 moveResizeBody(body
, 0, 0, sx
, sy
);
795 // nothing to do with the grid, just fix size
802 // ////////////////////////////////////////////////////////////////////////// //
803 // no callback: return `true` on the first hit
804 function TBodyGridBase
.forEachAtPoint (x
, y
: Integer; cb
: TGridQueryCB
; tagmask
: Integer=-1): ITP
;
813 result
:= Default(ITP
);
814 tagmask
:= tagmask
and TagFullMask
;
815 if (tagmask
= 0) then exit
;
817 // make coords (0,0)-based
820 if (x
< 0) or (y
< 0) or (x
>= mWidth
*mTileSize
) or (y
>= mHeight
*mTileSize
) then exit
;
822 curci
:= mGrid
[(y
div mTileSize
)*mWidth
+(x
div mTileSize
)];
827 // increase query counter
829 if (mLastQuery
= 0) then
831 // just in case of overflow
833 for idx
:= 0 to High(mProxies
) do mProxies
[idx
].mQueryMark
:= 0;
837 while (curci
<> -1) do
839 cc
:= @mCells
[curci
];
840 for f
:= 0 to High(TGridCell
.bodies
) do
842 if (cc
.bodies
[f
] = -1) then break
;
843 px
:= @mProxies
[cc
.bodies
[f
]];
845 if ((ptag
and TagDisabled
) = 0) and ((ptag
and tagmask
) <> 0) and (px
.mQueryMark
<> lq
) then
847 if (x
>= px
.mX
) and (y
>= px
.mY
) and (x
< px
.mX
+px
.mWidth
) and (y
< px
.mY
+px
.mHeight
) then
852 if cb(px
.mObj
, ptag
) then begin result
:= px
.mObj
; exit
; end;
867 // ////////////////////////////////////////////////////////////////////////// //
868 // no callback: return `true` on the first hit
869 function TBodyGridBase
.forEachInAABB (x
, y
, w
, h
: Integer; cb
: TGridQueryCB
; tagmask
: Integer=-1; allowDisabled
: Boolean=false): ITP
;
884 result
:= Default(ITP
);
885 if (w
< 1) or (h
< 1) then exit
;
886 tagmask
:= tagmask
and TagFullMask
;
887 if (tagmask
= 0) then exit
;
897 //tsize := mTileSize;
899 if (x
+w
<= 0) or (y
+h
<= 0) then exit
;
900 if (x
>= gw
*tsize
) or (y
>= mHeight
*tsize
) then exit
;
902 // increase query counter
904 if (mLastQuery
= 0) then
906 // just in case of overflow
908 for idx
:= 0 to High(mProxies
) do mProxies
[idx
].mQueryMark
:= 0;
910 //e_WriteLog(Format('grid: query #%d: (%d,%d)-(%dx%d)', [mLastQuery, minx, miny, maxx, maxy]), MSG_NOTIFY);
914 for gy
:= y
div tsize
to (y
+h
-1) div tsize
do
916 if (gy
< 0) then continue
;
917 if (gy
>= mHeight
) then break
;
918 for gx
:= x
div tsize
to (x
+w
-1) div tsize
do
920 if (gx
< 0) then continue
;
921 if (gx
>= gw
) then break
;
923 curci
:= mGrid
[gy
*gw
+gx
];
924 while (curci
<> -1) do
926 cc
:= @mCells
[curci
];
927 for f
:= 0 to High(TGridCell
.bodies
) do
929 if (cc
.bodies
[f
] = -1) then break
;
930 px
:= @mProxies
[cc
.bodies
[f
]];
932 if (not allowDisabled
) and ((ptag
and TagDisabled
) <> 0) then continue
;
933 if ((ptag
and tagmask
) <> 0) and (px
.mQueryMark
<> lq
) then
934 //if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
935 //if ( ((ptag and TagDisabled) = 0) = ignoreDisabled) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
937 if (x0
>= px
.mX
+px
.mWidth
) or (y0
>= px
.mY
+px
.mHeight
) then continue
;
938 if (x0
+w
<= px
.mX
) or (y0
+h
<= px
.mY
) then continue
;
942 if cb(px
.mObj
, ptag
) then begin result
:= px
.mObj
; exit
; end;
958 // ////////////////////////////////////////////////////////////////////////// //
959 // no callback: return `true` on the nearest hit
960 function TBodyGridBase
.traceRay (x0
, y0
, x1
, y1
: Integer; cb
: TGridRayQueryCB
; tagmask
: Integer=-1): ITP
;
964 result
:= traceRay(ex
, ey
, x0
, y0
, x1
, y1
, cb
, tagmask
);
968 // no callback: return `true` on the nearest hit
969 // you are not supposed to understand this
970 function TBodyGridBase
.traceRay (out ex
, ey
: Integer; ax0
, ay0
, ax1
, ay1
: Integer; cb
: TGridRayQueryCB
; tagmask
: Integer=-1): ITP
;
974 wx0
, wy0
, wx1
, wy1
: Integer; // window coordinates
975 stx
, sty
: Integer; // "steps" for x and y axes
976 dsx
, dsy
: Integer; // "lengthes" for x and y axes
977 dx2
, dy2
: Integer; // "double lengthes" for x and y axes
978 xd
, yd
: Integer; // current coord
979 e
: Integer; // "error" (as in bresenham algo)
982 xptr
, yptr
: PInteger;
985 prevx
, prevy
: Integer;
987 ccidx
, curci
: Integer;
989 lastGA
: Integer = -1;
992 wasHit
: Boolean = false;
993 gw
, gh
, minx
, miny
, maxx
, maxy
: Integer;
997 f
, ptag
, distSq
: Integer;
998 x0
, y0
, x1
, y1
: Integer;
1000 result
:= Default(ITP
);
1001 lastObj
:= Default(ITP
);
1002 tagmask
:= tagmask
and TagFullMask
;
1003 ex
:= ax1
; // why not?
1004 ey
:= ay1
; // why not?
1005 if (tagmask
= 0) then exit
;
1007 if (ax0
= ax1
) and (ay0
= ay1
) then exit
; // as the first point is ignored, just get outta here
1009 lastDistSq
:= distanceSq(ax0
, ay0
, ax1
, ay1
)+1;
1023 // offset query coords to (0,0)-based
1038 // from left to right
1039 if (x0
> wx1
) or (x1
< wx0
) then exit
; // out of screen
1040 stx
:= 1; // going right
1044 // from right to left
1045 if (x1
> wx1
) or (x0
< wx0
) then exit
; // out of screen
1046 stx
:= -1; // going left
1057 // from top to bottom
1058 if (y0
> wy1
) or (y1
< wy0
) then exit
; // out of screen
1059 sty
:= 1; // going down
1063 // from bottom to top
1064 if (y1
> wy1
) or (y0
< wy0
) then exit
; // out of screen
1065 sty
:= -1; // going up
1104 temp
:= dx2
*(wy0
-y0
)-dsx
;
1106 rem
:= temp
mod dy2
;
1107 if (xd
> wx1
) then exit
; // x is moved out of clipping rect, nothing to do
1108 if (xd
+1 >= wx0
) then
1112 if (rem
> 0) then begin Inc(xd
); e
+= dy2
; end;
1117 if (not xfixed
) and (x0
< wx0
) then
1120 temp
:= dy2
*(wx0
-x0
);
1122 rem
:= temp
mod dx2
;
1123 if (yd
> wy1
) or (yd
= wy1
) and (rem
>= dsx
) then exit
;
1126 if (rem
>= dsx
) then begin Inc(yd
); e
-= dx2
; end;
1132 temp
:= dx2
*(wy1
-y0
)+dsx
;
1133 term
:= x0
+temp
div dy2
;
1134 rem
:= temp
mod dy2
;
1135 if (rem
= 0) then Dec(term
);
1138 if (term
> wx1
) then term
:= wx1
; // clip at right
1140 Inc(term
); // draw last point
1141 //if (term = xd) then exit; // this is the only point, get out of here
1143 if (sty
= -1) then yd
:= -yd
;
1144 if (stx
= -1) then begin xd
:= -xd
; term
:= -term
; end;
1147 // first move, to skip starting point
1148 if (xd
= term
) then exit
;
1149 prevx
:= xptr
^+minx
;
1150 prevy
:= yptr
^+miny
;
1152 if (e
>= 0) then begin yd
+= sty
; e
-= dx2
; end else e
+= dy2
;
1155 if (xd
= term
) then exit
;
1157 if (xptr
^ < 0) or (yptr
^ < 0) or (xptr
^ >= gw
*tsize
) and (yptr
^ > mHeight
*tsize
) then raise Exception
.Create('raycaster internal error (0)');
1159 //if (dbgShowTraceLog) then e_WriteLog(Format('raycast start: (%d,%d)-(%d,%d); xptr^=%d; yptr^=%d', [ax0, ay0, ax1, ay1, xptr^, yptr^]), MSG_NOTIFY);
1161 // restore query coords
1167 // increase query counter
1169 if (mLastQuery
= 0) then
1171 // just in case of overflow
1173 for f
:= 0 to High(mProxies
) do mProxies
[f
].mQueryMark
:= 0;
1178 // draw it; can omit checks
1179 while (xd
<> term
) do
1182 if (xptr
^ < 0) or (yptr
^ < 0) or (xptr
^ >= gw
*tsize
) and (yptr
^ > mHeight
*tsize
) then raise Exception
.Create('raycaster internal error (0)');
1184 ga
:= (yptr
^ div tsize
)*gw
+(xptr
^ div tsize
);
1185 if (ga
<> lastGA
) then
1188 if (ccidx
<> -1) then
1190 // signal cell completion
1191 if assigned(cb
) then
1193 if cb(nil, 0, xptr
^+minx
, yptr
^+miny
, prevx
, prevy
) then begin result
:= lastObj
; exit
; end;
1202 ccidx
:= mGrid
[lastGA
];
1204 // has something to process in this tile?
1205 if (ccidx
<> -1) then
1209 hasUntried
:= false; // this will be set to `true` if we have some proxies we still want to process at the next step
1210 // convert coords to map (to avoid ajdusting coords inside the loop)
1213 // process cell list
1214 while (curci
<> -1) do
1216 cc
:= @mCells
[curci
];
1217 for f
:= 0 to High(TGridCell
.bodies
) do
1219 if (cc
.bodies
[f
] = -1) then break
;
1220 px
:= @mProxies
[cc
.bodies
[f
]];
1222 if ((ptag
and TagDisabled
) = 0) and ((ptag
and tagmask
) <> 0) and (px
.mQueryMark
<> lq
) then
1224 // can we process this proxy?
1225 if (x
>= px
.mX
) and (y
>= px
.mY
) and (x
< px
.mX
+px
.mWidth
) and (y
< px
.mY
+px
.mHeight
) then
1227 px
.mQueryMark
:= lq
; // mark as processed
1228 if assigned(cb
) then
1230 if cb(px
.mObj
, ptag
, x
, y
, prevx
, prevy
) then
1240 // remember this hitpoint if it is nearer than an old one
1241 distSq
:= distanceSq(ax0
, ay0
, prevx
, prevy
);
1242 if (distSq
< lastDistSq
) then
1245 lastDistSq
:= distSq
;
1254 // this is possibly interesting proxy, set "has more to check" flag
1262 // still has something interesting in this cell?
1263 if not hasUntried
then
1265 // nope, don't process this cell anymore; signal cell completion
1267 if assigned(cb
) then
1269 if cb(nil, 0, x
, y
, prevx
, prevy
) then begin result
:= lastObj
; exit
; end;
1278 //putPixel(xptr^, yptr^);
1280 prevx
:= xptr
^+minx
;
1281 prevy
:= yptr
^+miny
;
1282 if (e
>= 0) then begin yd
+= sty
; e
-= dx2
; end else e
+= dy2
;
1288 // ////////////////////////////////////////////////////////////////////////// //
1289 //FIXME! optimize this with real tile walking
1290 function TBodyGridBase
.forEachAlongLine (x0
, y0
, x1
, y1
: Integer; cb
: TGridAlongQueryCB
; tagmask
: Integer=-1): ITP
;
1296 xerr
, yerr
: Integer;
1297 incx
, incy
: Integer;
1298 stepx
, stepy
: Integer;
1300 maxx
, maxy
: Integer;
1307 minx
, miny
: Integer;
1309 lastWasInGrid
: Boolean;
1313 result
:= Default(ITP
);
1314 tagmask
:= tagmask
and TagFullMask
;
1315 if (tagmask
= 0) then exit
;
1323 if (dx
> 0) then incx
:= 1 else if (dx
< 0) then incx
:= -1 else incx
:= 0;
1324 if (dy
> 0) then incy
:= 1 else if (dy
< 0) then incy
:= -1 else incy
:= 0;
1329 if (dx
> dy
) then d
:= dx
else d
:= dy
;
1331 // `x` and `y` will be in grid coords
1335 // increase query counter
1337 if (mLastQuery
= 0) then
1339 // just in case of overflow
1341 for i
:= 0 to High(mProxies
) do mProxies
[i
].mQueryMark
:= 0;
1345 // cache various things
1346 //tsize := mTileSize;
1352 // setup distance and flags
1353 lastWasInGrid
:= (x
>= 0) and (y
>= 0) and (x
<= maxx
) and (y
<= maxy
);
1355 // setup starting tile ('cause we'll adjust tile vars only on tile edge crossing)
1356 if lastWasInGrid
then ccidx
:= mGrid
[(y
div tsize
)*gw
+(x
div tsize
)] else ccidx
:= -1;
1358 // it is slightly faster this way
1368 // invariant: one of those always changed
1369 if (xerr
< 0) and (yerr
< 0) then raise Exception
.Create('internal bug in grid raycaster (0)');
1370 if (xerr
>= 0) then begin xerr
-= d
; x
+= incx
; stepx
:= incx
; end else stepx
:= 0;
1371 if (yerr
>= 0) then begin yerr
-= d
; y
+= incy
; stepy
:= incy
; end else stepy
:= 0;
1372 // invariant: we always doing a step
1373 if ((stepx
or stepy
) = 0) then raise Exception
.Create('internal bug in grid raycaster (1)');
1375 // check for crossing tile/grid boundary
1376 if (x
>= 0) and (y
>= 0) and (x
<= maxx
) and (y
<= maxy
) then
1378 // we're still in grid
1379 lastWasInGrid
:= true;
1380 // check for tile edge crossing
1381 if (stepx
< 0) and ((x
mod tsize
) = tsize
-1) then tbcross
:= true
1382 else if (stepx
> 0) and ((x
mod tsize
) = 0) then tbcross
:= true
1383 else if (stepy
< 0) and ((y
mod tsize
) = tsize
-1) then tbcross
:= true
1384 else if (stepy
> 0) and ((y
mod tsize
) = 0) then tbcross
:= true
1385 else tbcross
:= false;
1386 // crossed tile edge?
1389 // setup new cell index
1390 ccidx
:= mGrid
[(y
div tsize
)*gw
+(x
div tsize
)];
1396 if lastWasInGrid
then exit
; // oops, stepped out of the grid -- there is no way to return
1400 // has something to process in the current cell?
1401 if (ccidx
<> -1) then
1405 // convert coords to map (to avoid ajdusting coords inside the loop)
1408 // process cell list
1409 while (curci
<> -1) do
1411 cc
:= @mCells
[curci
];
1412 for f
:= 0 to High(TGridCell
.bodies
) do
1414 if (cc
.bodies
[f
] = -1) then break
;
1415 px
:= @mProxies
[cc
.bodies
[f
]];
1417 if ((ptag
and TagDisabled
) = 0) and ((ptag
and tagmask
) <> 0) and (px
.mQueryMark
<> lq
) then
1419 px
.mQueryMark
:= lq
; // mark as processed
1420 if cb(px
.mObj
, ptag
) then begin result
:= px
.mObj
; exit
; end;
1426 ccidx
:= -1; // don't process this anymore
1427 // convert coords to grid