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}
18 {$IF DEFINED(D2F_DEBUG)}
19 {.$DEFINE D2F_DEBUG_RAYTRACE}
20 {.$DEFINE D2F_DEBUG_XXQ}
21 {.$DEFINE D2F_DEBUG_MOVER}
23 {$DEFINE GRID_USE_ORTHO_ACCEL}
30 TBodyProxyId
= Integer;
32 generic TBodyGridBase
<ITP
> = class(TObject
)
34 type TGridQueryCB
= function (obj
: ITP
; tag
: Integer): Boolean is nested
; // return `true` to stop
35 type TGridRayQueryCB
= function (obj
: ITP
; tag
: Integer; x
, y
, prevx
, prevy
: Integer): Boolean is nested
; // return `true` to stop
36 type TGridAlongQueryCB
= function (obj
: ITP
; tag
: Integer): Boolean is nested
; // return `true` to stop
38 type TCellQueryCB
= procedure (x
, y
: Integer) is nested
; // top-left cell corner coords
40 const TagDisabled
= $40000000;
41 const TagFullMask
= $3fffffff;
45 GridDefaultTileSize
= 32; // must be power of two!
46 GridCellBucketSize
= 8; // WARNING! can't be less than 2!
50 PBodyProxyRec
= ^TBodyProxyRec
;
51 TBodyProxyRec
= record
53 mX
, mY
, mWidth
, mHeight
: Integer; // aabb
54 mQueryMark
: LongWord; // was this object visited at this query?
56 mTag
: Integer; // `TagDisabled` set: disabled ;-)
57 nextLink
: TBodyProxyId
; // next free or nothing
60 procedure setup (aX
, aY
, aWidth
, aHeight
: Integer; aObj
: ITP
; aTag
: Integer);
62 function getTag (): Integer; inline;
63 procedure setTag (v
: Integer); inline;
65 function getEnabled (): Boolean; inline;
66 procedure setEnabled (v
: Boolean); inline;
69 property x
: Integer read mX
;
70 property y
: Integer read mY
;
71 property width
: Integer read mWidth
;
72 property height
: Integer read mHeight
;
73 property tag
: Integer read getTag write setTag
;
74 property enabled
: Boolean read getEnabled write setEnabled
;
79 PGridCell
= ^TGridCell
;
81 bodies
: array [0..GridCellBucketSize
-1] of Integer; // -1: end of list
82 next
: Integer; // in this cell; index in mCells
85 TGridInternalCB
= function (grida
: Integer; bodyId
: TBodyProxyId
): Boolean of object; // return `true` to stop
89 const mTileSize
= GridDefaultTileSize
;
92 const tileSize
= mTileSize
;
95 mMinX
, mMinY
: Integer; // so grids can start at any origin
96 mWidth
, mHeight
: Integer; // in tiles
97 mGrid
: array of Integer; // mWidth*mHeight, index in mCells
98 mCells
: array of TGridCell
; // cell pool
99 mFreeCell
: Integer; // first free cell index or -1
100 mLastQuery
: LongWord;
102 mProxies
: array of TBodyProxyRec
;
103 mProxyFree
: TBodyProxyId
; // free
104 mProxyCount
: Integer; // currently used
105 mProxyMaxCount
: Integer;
108 dbgShowTraceLog
: Boolean;
109 {$IF DEFINED(D2F_DEBUG)}
110 dbgRayTraceTileHitCB
: TCellQueryCB
;
114 function allocCell (): Integer;
115 procedure freeCell (idx
: Integer); // `next` is simply overwritten
117 function allocProxy (aX
, aY
, aWidth
, aHeight
: Integer; aObj
: ITP
; aTag
: Integer): TBodyProxyId
;
118 procedure freeProxy (body
: TBodyProxyId
);
120 procedure insertInternal (body
: TBodyProxyId
);
121 procedure removeInternal (body
: TBodyProxyId
);
123 function forGridRect (x
, y
, w
, h
: Integer; cb
: TGridInternalCB
; bodyId
: TBodyProxyId
): Boolean;
125 function inserter (grida
: Integer; bodyId
: TBodyProxyId
): Boolean;
126 function remover (grida
: Integer; bodyId
: TBodyProxyId
): Boolean;
128 function getProxyEnabled (pid
: TBodyProxyId
): Boolean; inline;
129 procedure setProxyEnabled (pid
: TBodyProxyId
; val
: Boolean); inline;
131 function getGridWidthPx (): Integer; inline;
132 function getGridHeightPx (): Integer; inline;
134 function getProxyById (idx
: TBodyProxyId
): PBodyProxyRec
; inline;
137 constructor Create (aMinPixX
, aMinPixY
, aPixWidth
, aPixHeight
: Integer{; aTileSize: Integer=GridDefaultTileSize});
138 destructor Destroy (); override;
140 function insertBody (aObj
: ITP
; ax
, ay
, aWidth
, aHeight
: Integer; aTag
: Integer=-1): TBodyProxyId
;
141 procedure removeBody (body
: TBodyProxyId
); // WARNING! this WILL destroy proxy!
143 procedure moveBody (body
: TBodyProxyId
; nx
, ny
: Integer);
144 procedure resizeBody (body
: TBodyProxyId
; nw
, nh
: Integer);
145 procedure moveResizeBody (body
: TBodyProxyId
; nx
, ny
, nw
, nh
: Integer);
147 function insideGrid (x
, y
: Integer): Boolean; inline;
149 // `false` if `body` is surely invalid
150 function getBodyXY (body
: TBodyProxyId
; out rx
, ry
: Integer): Boolean; inline;
151 function getBodyWH (body
: TBodyProxyId
; out rw
, rh
: Integer): Boolean; inline;
152 function getBodyDims (body
: TBodyProxyId
; out rx
, ry
, rw
, rh
: Integer): Boolean; inline;
154 //WARNING: don't modify grid while any query is in progress (no checks are made!)
155 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
156 // no callback: return `true` on the first hit
157 function forEachInAABB (x
, y
, w
, h
: Integer; cb
: TGridQueryCB
; tagmask
: Integer=-1; allowDisabled
: Boolean=false): ITP
;
159 //WARNING: don't modify grid while any query is in progress (no checks are made!)
160 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
161 // no callback: return object on the first hit or nil
162 function forEachAtPoint (x
, y
: Integer; cb
: TGridQueryCB
; tagmask
: Integer=-1; exittag
: PInteger=nil): ITP
;
164 //WARNING: don't modify grid while any query is in progress (no checks are made!)
165 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
166 // cb with `(nil)` will be called before processing new tile
167 // no callback: return object of the nearest hit or nil
168 // if `inverted` is true, trace will register bodies *exluding* tagmask
169 //WARNING: don't change tags in callbacks here!
170 function traceRay (const x0
, y0
, x1
, y1
: Integer; cb
: TGridRayQueryCB
; tagmask
: Integer=-1): ITP
; overload
;
171 function traceRay (out ex
, ey
: Integer; const ax0
, ay0
, ax1
, ay1
: Integer; cb
: TGridRayQueryCB
; tagmask
: Integer=-1): ITP
;
173 //function traceOrthoRayWhileIn (const x0, y0, x1, y1: Integer; tagmask: Integer=-1): ITP; overload;
174 //function traceOrthoRayWhileIn (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; tagmask: Integer=-1): ITP;
176 //WARNING: don't modify grid while any query is in progress (no checks are made!)
177 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
178 // trace line along the grid, calling `cb` for all objects in passed cells, in no particular order
179 //WARNING: don't change tags in callbacks here!
180 function forEachAlongLine (const x0
, y0
, x1
, y1
: Integer; cb
: TGridAlongQueryCB
; tagmask
: Integer=-1; log
: Boolean=false): ITP
;
183 procedure forEachBodyCell (body
: TBodyProxyId
; cb
: TCellQueryCB
);
184 function forEachInCell (x
, y
: Integer; cb
: TGridQueryCB
): ITP
;
185 procedure dumpStats ();
188 //WARNING! no sanity checks!
189 property proxyEnabled
[pid
: TBodyProxyId
]: Boolean read getProxyEnabled write setProxyEnabled
;
191 property gridX0
: Integer read mMinX
;
192 property gridY0
: Integer read mMinY
;
193 property gridWidth
: Integer read getGridWidthPx
; // in pixels
194 property gridHeight
: Integer read getGridHeightPx
; // in pixels
196 property proxy
[idx
: TBodyProxyId
]: PBodyProxyRec read getProxyById
;
200 // you are not supposed to understand this
201 // returns `true` if there is an intersection, and enter coords
202 // enter coords will be equal to (x0, y0) if starting point is inside the box
203 // if result is `false`, `inx` and `iny` are undefined
204 function lineAABBIntersects (x0
, y0
, x1
, y1
: Integer; bx
, by
, bw
, bh
: Integer; out inx
, iny
: Integer): Boolean;
206 function distanceSq (x0
, y0
, x1
, y1
: Integer): Integer; inline;
208 procedure swapInt (var a
: Integer; var b
: Integer); inline;
209 function minInt (a
, b
: Integer): Integer; inline;
210 function maxInt (a
, b
: Integer): Integer; inline;
216 SysUtils
, e_log
, g_console
;
219 // ////////////////////////////////////////////////////////////////////////// //
220 procedure swapInt (var a
: Integer; var b
: Integer); inline; var t
: Integer; begin t
:= a
; a
:= b
; b
:= t
; end;
221 function minInt (a
, b
: Integer): Integer; inline; begin if (a
< b
) then result
:= a
else result
:= b
; end;
222 function maxInt (a
, b
: Integer): Integer; inline; begin if (a
> b
) then result
:= a
else result
:= b
; end;
224 function distanceSq (x0
, y0
, x1
, y1
: Integer): Integer; inline; begin result
:= (x1
-x0
)*(x1
-x0
)+(y1
-y0
)*(y1
-y0
); end;
227 // ////////////////////////////////////////////////////////////////////////// //
228 // you are not supposed to understand this
229 // returns `true` if there is an intersection, and enter coords
230 // enter coords will be equal to (x0, y0) if starting point is inside the box
231 // if result is `false`, `inx` and `iny` are undefined
232 function lineAABBIntersects (x0
, y0
, x1
, y1
: Integer; bx
, by
, bw
, bh
: Integer; out inx
, iny
: Integer): Boolean;
234 wx0
, wy0
, wx1
, wy1
: Integer; // window coordinates
235 stx
, sty
: Integer; // "steps" for x and y axes
236 dsx
, dsy
: Integer; // "lengthes" for x and y axes
237 dx2
, dy2
: Integer; // "double lengthes" for x and y axes
238 xd
, yd
: Integer; // current coord
239 e
: Integer; // "error" (as in bresenham algo)
250 if (bw
< 1) or (bh
< 1) then exit
; // impossible box
252 if (x0
= x1
) and (y0
= y1
) then
255 result
:= (x0
>= bx
) and (y0
>= by
) and (x0
< bx
+bw
) and (y0
< by
+bh
);
259 // check if staring point is inside the box
260 if (x0
>= bx
) and (y0
>= by
) and (x0
< bx
+bw
) and (y0
< by
+bh
) then begin result
:= true; exit
; end;
271 // from left to right
272 if (x0
> wx1
) or (x1
< wx0
) then exit
; // out of screen
273 stx
:= 1; // going right
277 // from right to left
278 if (x1
> wx1
) or (x0
< wx0
) then exit
; // out of screen
279 stx
:= -1; // going left
290 // from top to bottom
291 if (y0
> wy1
) or (y1
< wy0
) then exit
; // out of screen
292 sty
:= 1; // going down
296 // from bottom to top
297 if (y1
> wy1
) or (y0
< wy0
) then exit
; // out of screen
298 sty
:= -1; // going up
337 temp
:= dx2
*(wy0
-y0
)-dsx
;
340 if (xd
> wx1
) then exit
; // x is moved out of clipping rect, nothing to do
341 if (xd
+1 >= wx0
) then
345 if (rem
> 0) then begin Inc(xd
); e
+= dy2
; end;
350 if (not xfixed
) and (x0
< wx0
) then
353 temp
:= dy2
*(wx0
-x0
);
356 if (yd
> wy1
) or (yd
= wy1
) and (rem
>= dsx
) then exit
;
359 if (rem
>= dsx
) then begin Inc(yd
); e
-= dx2
; end;
366 temp := dx2*(wy1-y0)+dsx;
367 term := x0+temp div dy2;
369 if (rem = 0) then Dec(term);
372 if (term > wx1) then term := wx1; // clip at right
374 Inc(term); // draw last point
375 //if (term = xd) then exit; // this is the only point, get out of here
378 if (sty
= -1) then yd
:= -yd
;
379 if (stx
= -1) then begin xd
:= -xd
; {!term := -term;} end;
388 // ////////////////////////////////////////////////////////////////////////// //
389 procedure TBodyGridBase
.TBodyProxyRec
.setup (aX
, aY
, aWidth
, aHeight
: Integer; aObj
: ITP
; aTag
: Integer);
402 function TBodyGridBase
.TBodyProxyRec
.getTag (): Integer; inline;
404 result
:= mTag
and TagFullMask
;
407 procedure TBodyGridBase
.TBodyProxyRec
.setTag (v
: Integer); inline;
409 mTag
:= (mTag
and TagDisabled
) or (v
and TagFullMask
);
412 function TBodyGridBase
.TBodyProxyRec
.getEnabled (): Boolean; inline;
414 result
:= ((mTag
and TagDisabled
) = 0);
417 procedure TBodyGridBase
.TBodyProxyRec
.setEnabled (v
: Boolean); inline;
419 if v
then mTag
:= mTag
and (not TagDisabled
) else mTag
:= mTag
or TagDisabled
;
423 // ////////////////////////////////////////////////////////////////////////// //
424 constructor TBodyGridBase
.Create (aMinPixX
, aMinPixY
, aPixWidth
, aPixHeight
: Integer{; aTileSize: Integer=GridDefaultTileSize});
428 dbgShowTraceLog
:= false;
429 {$IF DEFINED(D2F_DEBUG)}
430 dbgRayTraceTileHitCB
:= nil;
433 if aTileSize < 1 then aTileSize := 1;
434 if aTileSize > 8192 then aTileSize := 8192; // arbitrary limit
435 mTileSize := aTileSize;
437 if (aPixWidth
< mTileSize
) then aPixWidth
:= mTileSize
;
438 if (aPixHeight
< mTileSize
) then aPixHeight
:= mTileSize
;
441 mWidth
:= (aPixWidth
+mTileSize
-1) div mTileSize
;
442 mHeight
:= (aPixHeight
+mTileSize
-1) div mTileSize
;
443 SetLength(mGrid
, mWidth
*mHeight
);
444 SetLength(mCells
, mWidth
*mHeight
);
445 SetLength(mProxies
, 8192);
448 for idx
:= 0 to High(mCells
) do
450 mCells
[idx
].bodies
[0] := -1;
451 mCells
[idx
].bodies
[GridCellBucketSize
-1] := -1; // "has free room" flag
452 mCells
[idx
].next
:= idx
+1;
454 mCells
[High(mCells
)].next
:= -1; // last cell
456 for idx
:= 0 to High(mGrid
) do mGrid
[idx
] := -1;
458 for idx
:= 0 to High(mProxies
) do mProxies
[idx
].nextLink
:= idx
+1;
459 mProxies
[High(mProxies
)].nextLink
:= -1;
465 e_WriteLog(Format('created grid with size: %dx%d (tile size: %d); pix: %dx%d', [mWidth
, mHeight
, mTileSize
, mWidth
*mTileSize
, mHeight
*mTileSize
]), MSG_NOTIFY
);
469 destructor TBodyGridBase
.Destroy ();
478 // ////////////////////////////////////////////////////////////////////////// //
479 procedure TBodyGridBase
.dumpStats ();
481 idx
, mcb
, cidx
, cnt
: Integer;
484 for idx
:= 0 to High(mGrid
) do
491 cidx
:= mCells
[cidx
].next
;
493 if (mcb
< cnt
) then mcb
:= cnt
;
495 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
);
499 procedure TBodyGridBase
.forEachBodyCell (body
: TBodyProxyId
; cb
: TCellQueryCB
);
504 if (body
< 0) or (body
> High(mProxies
)) or not assigned(cb
) then exit
;
505 for g
:= 0 to High(mGrid
) do
508 while (cidx
<> -1) do
511 for f
:= 0 to GridCellBucketSize
-1 do
513 if (cc
.bodies
[f
] = -1) then break
;
514 if (cc
.bodies
[f
] = body
) then cb((g
mod mWidth
)*mTileSize
+mMinX
, (g
div mWidth
)*mTileSize
+mMinY
);
523 function TBodyGridBase
.forEachInCell (x
, y
: Integer; cb
: TGridQueryCB
): ITP
;
528 result
:= Default(ITP
);
529 if not assigned(cb
) then exit
;
532 if (x
< 0) or (y
< 0) or (x
>= mWidth
*mTileSize
) or (y
> mHeight
*mTileSize
) then exit
;
533 cidx
:= mGrid
[(y
div mTileSize
)*mWidth
+(x
div mTileSize
)];
534 while (cidx
<> -1) do
537 for f
:= 0 to GridCellBucketSize
-1 do
539 if (cc
.bodies
[f
] = -1) then break
;
540 if cb(mProxies
[cc
.bodies
[f
]].mObj
, mProxies
[cc
.bodies
[f
]].mTag
) then begin result
:= mProxies
[cc
.bodies
[f
]].mObj
; exit
; end;
548 // ////////////////////////////////////////////////////////////////////////// //
549 function TBodyGridBase
.getGridWidthPx (): Integer; inline; begin result
:= mWidth
*mTileSize
; end;
550 function TBodyGridBase
.getGridHeightPx (): Integer; inline; begin result
:= mHeight
*mTileSize
; end;
553 function TBodyGridBase
.insideGrid (x
, y
: Integer): Boolean; inline;
558 result
:= (x
>= 0) and (y
>= 0) and (x
< mWidth
*mTileSize
) and (y
< mHeight
*mTileSize
);
562 function TBodyGridBase
.getBodyXY (body
: TBodyProxyId
; out rx
, ry
: Integer): Boolean; inline;
564 if (body
>= 0) and (body
< Length(mProxies
)) then
566 with mProxies
[body
] do begin rx
:= mX
; ry
:= mY
; end;
578 function TBodyGridBase
.getBodyWH (body
: TBodyProxyId
; out rw
, rh
: Integer): Boolean; inline;
580 if (body
>= 0) and (body
< Length(mProxies
)) then
582 with mProxies
[body
] do begin rw
:= mWidth
; rh
:= mHeight
; end;
594 function TBodyGridBase
.getBodyDims (body
: TBodyProxyId
; out rx
, ry
, rw
, rh
: Integer): Boolean; inline;
596 if (body
>= 0) and (body
< Length(mProxies
)) then
598 with mProxies
[body
] do begin rx
:= mX
; ry
:= mY
; rw
:= mWidth
; rh
:= mHeight
; end;
613 // ////////////////////////////////////////////////////////////////////////// //
614 function TBodyGridBase
.getProxyEnabled (pid
: TBodyProxyId
): Boolean; inline;
616 if (pid
>= 0) then result
:= ((mProxies
[pid
].mTag
and TagDisabled
) = 0) else result
:= false;
620 procedure TBodyGridBase
.setProxyEnabled (pid
: TBodyProxyId
; val
: Boolean); inline;
626 mProxies
[pid
].mTag
:= mProxies
[pid
].mTag
and not TagDisabled
;
630 mProxies
[pid
].mTag
:= mProxies
[pid
].mTag
or TagDisabled
;
636 function TBodyGridBase
.getProxyById (idx
: TBodyProxyId
): PBodyProxyRec
; inline;
638 if (idx
>= 0) and (idx
< High(mProxies
)) then result
:= @mProxies
[idx
] else result
:= nil;
642 // ////////////////////////////////////////////////////////////////////////// //
643 function TBodyGridBase
.allocCell (): Integer;
648 if (mFreeCell
< 0) then
650 // no free cells, want more
651 mFreeCell
:= Length(mCells
);
652 SetLength(mCells
, mFreeCell
+32768); // arbitrary number
653 for idx
:= mFreeCell
to High(mCells
) do
655 mCells
[idx
].bodies
[0] := -1;
656 mCells
[idx
].bodies
[GridCellBucketSize
-1] := -1; // 'has free room' flag
657 mCells
[idx
].next
:= idx
+1;
659 mCells
[High(mCells
)].next
:= -1; // last cell
662 pc
:= @mCells
[result
];
663 mFreeCell
:= pc
.next
;
666 //e_WriteLog(Format('grid: allocated new cell #%d (total: %d)', [result, mUsedCells]), MSG_NOTIFY);
670 procedure TBodyGridBase
.freeCell (idx
: Integer);
672 if (idx
>= 0) and (idx
< Length(mCells
)) then
677 bodies
[GridCellBucketSize
-1] := -1; // 'has free room' flag
686 // ////////////////////////////////////////////////////////////////////////// //
687 function TBodyGridBase
.allocProxy (aX
, aY
, aWidth
, aHeight
: Integer; aObj
: ITP
; aTag
: Integer): TBodyProxyId
;
692 if (mProxyFree
= -1) then
694 // no free proxies, resize list
695 olen
:= Length(mProxies
);
696 SetLength(mProxies
, olen
+8192); // arbitrary number
697 for idx
:= olen
to High(mProxies
) do mProxies
[idx
].nextLink
:= idx
+1;
698 mProxies
[High(mProxies
)].nextLink
:= -1;
702 result
:= mProxyFree
;
703 px
:= @mProxies
[result
];
704 mProxyFree
:= px
.nextLink
;
705 px
.setup(aX
, aY
, aWidth
, aHeight
, aObj
, aTag
);
710 if (mProxyMaxCount
< mProxyCount
) then mProxyMaxCount
:= mProxyCount
;
713 procedure TBodyGridBase
.freeProxy (body
: TBodyProxyId
);
715 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
716 if (mProxyCount
= 0) then raise Exception
.Create('wutafuuuuu in grid (no allocated proxies, what i should free now?)');
718 mProxies
[body
].mObj
:= nil;
719 mProxies
[body
].nextLink
:= mProxyFree
;
725 // ////////////////////////////////////////////////////////////////////////// //
726 function TBodyGridBase
.forGridRect (x
, y
, w
, h
: Integer; cb
: TGridInternalCB
; bodyId
: TBodyProxyId
): Boolean;
734 if (w
< 1) or (h
< 1) or not assigned(cb
) then exit
;
739 if (x
+w
<= 0) or (y
+h
<= 0) then exit
;
742 //tsize := mTileSize;
743 if (x
>= gw
*tsize
) or (y
>= gh
*tsize
) then exit
;
744 for gy
:= y
div tsize
to (y
+h
-1) div tsize
do
746 if (gy
< 0) then continue
;
747 if (gy
>= gh
) then break
;
748 for gx
:= x
div tsize
to (x
+w
-1) div tsize
do
750 if (gx
< 0) then continue
;
751 if (gx
>= gw
) then break
;
752 result
:= cb(gy
*gw
+gx
, bodyId
);
759 // ////////////////////////////////////////////////////////////////////////// //
760 function TBodyGridBase
.inserter (grida
: Integer; bodyId
: TBodyProxyId
): Boolean;
767 result
:= false; // never stop
768 // add body to the given grid cell
772 {$IF DEFINED(D2F_DEBUG)}
774 while (cidx
<> -1) do
777 for f
:= 0 to GridCellBucketSize
-1 do
779 if (pi
.bodies
[f
] = -1) then break
;
780 if (pi
.bodies
[f
] = bodyId
) then raise Exception
.Create('trying to insert already inserted proxy');
786 while (cidx
<> -1) do
789 // check "has room" flag
790 if (pi
.bodies
[GridCellBucketSize
-1] = -1) then
793 for f
:= 0 to GridCellBucketSize
-1 do
795 if (pi
.bodies
[f
] = -1) then
797 pi
.bodies
[f
] := bodyId
;
798 if (f
+1 < GridCellBucketSize
) then pi
.bodies
[f
+1] := -1;
802 raise Exception
.Create('internal error in grid inserter');
804 // no room, go to next cell in list (if there is any)
807 // no room in cells, add new cell to list
809 // either no room, or no cell at all
812 pi
.bodies
[0] := bodyId
;
815 mGrid
[grida
] := cidx
;
818 procedure TBodyGridBase
.insertInternal (body
: TBodyProxyId
);
822 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
823 px
:= @mProxies
[body
];
824 forGridRect(px
.mX
, px
.mY
, px
.mWidth
, px
.mHeight
, inserter
, body
);
828 // assume that we cannot have one object added to bucket twice
829 function TBodyGridBase
.remover (grida
: Integer; bodyId
: TBodyProxyId
): Boolean;
835 result
:= false; // never stop
836 // find and remove cell
837 pidx
:= -1; // previous cell index
838 cidx
:= mGrid
[grida
]; // current cell index
839 while (cidx
<> -1) do
842 for f
:= 0 to GridCellBucketSize
-1 do
844 if (pc
.bodies
[f
] = bodyId
) then
847 if (f
= 0) and (pc
.bodies
[1] = -1) then
849 // this cell contains no elements, remove it
850 if (pidx
= -1) then mGrid
[grida
] := pc
.next
else mCells
[pidx
].next
:= pc
.next
;
854 // remove element from bucket
855 for c
:= f
to GridCellBucketSize
-2 do
857 pc
.bodies
[c
] := pc
.bodies
[c
+1];
858 if (pc
.bodies
[c
] = -1) then break
;
860 pc
.bodies
[GridCellBucketSize
-1] := -1; // "has free room" flag
869 procedure TBodyGridBase
.removeInternal (body
: TBodyProxyId
);
873 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
874 px
:= @mProxies
[body
];
875 forGridRect(px
.mX
, px
.mY
, px
.mWidth
, px
.mHeight
, remover
, body
);
879 // ////////////////////////////////////////////////////////////////////////// //
880 function TBodyGridBase
.insertBody (aObj
: ITP
; aX
, aY
, aWidth
, aHeight
: Integer; aTag
: Integer=-1): TBodyProxyId
;
882 aTag
:= aTag
and TagFullMask
;
883 result
:= allocProxy(aX
, aY
, aWidth
, aHeight
, aObj
, aTag
);
884 insertInternal(result
);
888 procedure TBodyGridBase
.removeBody (body
: TBodyProxyId
);
890 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
891 removeInternal(body
);
896 // ////////////////////////////////////////////////////////////////////////// //
897 procedure TBodyGridBase
.moveResizeBody (body
: TBodyProxyId
; nx
, ny
, nw
, nh
: Integer);
900 x0
, y0
, w
, h
: Integer;
902 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
903 px
:= @mProxies
[body
];
908 {$IF DEFINED(D2F_DEBUG_MOVER)}
909 e_WriteLog(Format('proxy #%d: MOVERESIZE: xg=%d;yg=%d;w=%d;h=%d;nx=%d;ny=%d;nw=%d;nh=%d', [body
, x0
-mMinX
, y0
-mMinY
, w
, h
, nx
-mMinX
, ny
-mMinY
, nw
, nh
]), MSG_NOTIFY
);
911 if (nx
= x0
) and (ny
= y0
) and (nw
= w
) and (nh
= h
) then exit
;
917 // did any corner crossed tile boundary?
918 if (x0
div mTileSize
<> nx
div mTileSize
) or
919 (y0
div mTileSize
<> ny
div mTileSize
) or
920 ((x0
+w
) div mTileSize
<> (nx
+nw
) div mTileSize
) or
921 ((y0
+h
) div mTileSize
<> (ny
+nh
) div mTileSize
) then
923 removeInternal(body
);
928 insertInternal(body
);
939 //TODO: optimize for horizontal/vertical moves
940 procedure TBodyGridBase
.moveBody (body
: TBodyProxyId
; nx
, ny
: Integer);
944 ogx0
, ogx1
, ogy0
, ogy1
: Integer; // old grid rect
945 ngx0
, ngx1
, ngy0
, ngy1
: Integer; // new grid rect
950 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
951 // check if tile coords was changed
952 px
:= @mProxies
[body
];
955 if (nx
= x0
) and (ny
= y0
) then exit
;
961 // check for heavy work
964 ogx0
:= x0
div mTileSize
;
965 ogy0
:= y0
div mTileSize
;
966 ngx0
:= nx
div mTileSize
;
967 ngy0
:= ny
div mTileSize
;
968 ogx1
:= (x0
+pw
-1) div mTileSize
;
969 ogy1
:= (y0
+ph
-1) div mTileSize
;
970 ngx1
:= (nx
+pw
-1) div mTileSize
;
971 ngy1
:= (ny
+ph
-1) div mTileSize
;
972 {$IF DEFINED(D2F_DEBUG_MOVER)}
973 e_WriteLog(Format('proxy #%d: checkmove: xg=%d;yg=%d;w=%d;h=%d;nx=%d;ny=%d og:(%d,%d)-(%d,%d); ng:(%d,%d)-(%d,%d)', [body
, x0
, y0
, pw
, ph
, nx
, ny
, ogx0
, ogy0
, ogx1
, ogy1
, ngx0
, ngy0
, ngx1
, ngy1
]), MSG_NOTIFY
);
975 if (ogx0
<> ngx0
) or (ogy0
<> ngy0
) or (ogx1
<> ngx1
) or (ogy1
<> ngy1
) then
977 // crossed tile boundary, do heavy work
980 // cycle with old rect, remove body where it is necessary
981 // optimized for horizontal moves
982 {$IF DEFINED(D2F_DEBUG_MOVER)}
983 e_WriteLog(Format('proxy #%d: xg=%d;yg=%d;w=%d;h=%d;nx=%d;ny=%d og:(%d,%d)-(%d,%d); ng:(%d,%d)-(%d,%d)', [body
, x0
, y0
, pw
, ph
, nx
, ny
, ogx0
, ogy0
, ogx1
, ogy1
, ngx0
, ngy0
, ngx1
, ngy1
]), MSG_NOTIFY
);
985 // remove stale marks
986 if not ((ogy0
>= gh
) or (ogy1
< 0)) and
987 not ((ogx0
>= gw
) or (ogx1
< 0)) then
989 if (ogx0
< 0) then ogx0
:= 0;
990 if (ogy0
< 0) then ogy0
:= 0;
991 if (ogx1
> gw
-1) then ogx1
:= gw
-1;
992 if (ogy1
> gh
-1) then ogy1
:= gh
-1;
993 {$IF DEFINED(D2F_DEBUG_MOVER)}
994 e_WriteLog(Format(' norm og:(%d,%d)-(%d,%d)', [ogx0
, ogy0
, ogx1
, ogy1
]), MSG_NOTIFY
);
996 for gx
:= ogx0
to ogx1
do
998 if (gx
< ngx0
) or (gx
> ngx1
) then
1000 // this column is completely outside of new rect
1001 for gy
:= ogy0
to ogy1
do
1003 {$IF DEFINED(D2F_DEBUG_MOVER)}
1004 e_WriteLog(Format(' remove0:(%d,%d)', [gx
, gy
]), MSG_NOTIFY
);
1006 remover(gy
*gw
+gx
, body
);
1012 for gy
:= ogy0
to ogy1
do
1014 if (gy
< ngy0
) or (gy
> ngy1
) then
1016 {$IF DEFINED(D2F_DEBUG_MOVER)}
1017 e_WriteLog(Format(' remove1:(%d,%d)', [gx
, gy
]), MSG_NOTIFY
);
1019 remover(gy
*gw
+gx
, body
);
1025 // cycle with new rect, add body where it is necessary
1026 if not ((ngy0
>= gh
) or (ngy1
< 0)) and
1027 not ((ngx0
>= gw
) or (ngx1
< 0)) then
1029 if (ngx0
< 0) then ngx0
:= 0;
1030 if (ngy0
< 0) then ngy0
:= 0;
1031 if (ngx1
> gw
-1) then ngx1
:= gw
-1;
1032 if (ngy1
> gh
-1) then ngy1
:= gh
-1;
1033 {$IF DEFINED(D2F_DEBUG_MOVER)}
1034 e_WriteLog(Format(' norm ng:(%d,%d)-(%d,%d)', [ngx0
, ngy0
, ngx1
, ngy1
]), MSG_NOTIFY
);
1036 for gx
:= ngx0
to ngx1
do
1038 if (gx
< ogx0
) or (gx
> ogx1
) then
1040 // this column is completely outside of old rect
1041 for gy
:= ngy0
to ngy1
do
1043 {$IF DEFINED(D2F_DEBUG_MOVER)}
1044 e_WriteLog(Format(' insert0:(%d,%d)', [gx
, gy
]), MSG_NOTIFY
);
1046 inserter(gy
*gw
+gx
, body
);
1052 for gy
:= ngy0
to ngy1
do
1054 if (gy
< ogy0
) or (gy
> ogy1
) then
1056 {$IF DEFINED(D2F_DEBUG_MOVER)}
1057 e_WriteLog(Format(' insert1:(%d,%d)', [gx
, gy
]), MSG_NOTIFY
);
1059 inserter(gy
*gw
+gx
, body
);
1069 {$IF DEFINED(D2F_DEBUG_MOVER)}
1070 e_WriteLog(Format('proxy #%d: GRID OK: xg=%d;yg=%d;w=%d;h=%d;nx=%d;ny=%d og:(%d,%d)-(%d,%d); ng:(%d,%d)-(%d,%d)', [body
, x0
, y0
, pw
, ph
, nx
, ny
, ogx0
, ogy0
, ogx1
, ogy1
, ngx0
, ngy0
, ngx1
, ngy1
]), MSG_NOTIFY
);
1073 // update coordinates
1078 procedure TBodyGridBase
.resizeBody (body
: TBodyProxyId
; nw
, nh
: Integer);
1081 x0
, y0
, w
, h
: Integer;
1083 if (body
< 0) or (body
> High(mProxies
)) then exit
; // just in case
1084 // check if tile coords was changed
1085 px
:= @mProxies
[body
];
1090 {$IF DEFINED(D2F_DEBUG_MOVER)}
1091 e_WriteLog(Format('proxy #%d: RESIZE: xg=%d;yg=%d;w=%d;h=%d;nw=%d;nh=%d', [body
, x0
, y0
, w
, h
, nw
, nh
]), MSG_NOTIFY
);
1093 if ((x0
+w
) div mTileSize
<> (x0
+nw
) div mTileSize
) or
1094 ((y0
+h
) div mTileSize
<> (y0
+nh
) div mTileSize
) then
1096 // crossed tile boundary, do heavy work
1097 removeInternal(body
);
1100 insertInternal(body
);
1104 // nothing to do with the grid, just fix size
1111 // ////////////////////////////////////////////////////////////////////////// //
1112 // no callback: return `true` on the first hit
1113 function TBodyGridBase
.forEachAtPoint (x
, y
: Integer; cb
: TGridQueryCB
; tagmask
: Integer=-1; exittag
: PInteger=nil): ITP
;
1116 idx
, curci
: Integer;
1117 cc
: PGridCell
= nil;
1122 result
:= Default(ITP
);
1123 if (exittag
<> nil) then exittag
^ := 0;
1124 tagmask
:= tagmask
and TagFullMask
;
1125 if (tagmask
= 0) then exit
;
1127 {$IF DEFINED(D2F_DEBUG_XXQ)}
1128 if (assigned(cb
)) then e_WriteLog(Format('0: grid pointquery: (%d,%d)', [x
, y
]), MSG_NOTIFY
);
1131 // make coords (0,0)-based
1134 if (x
< 0) or (y
< 0) or (x
>= mWidth
*mTileSize
) or (y
>= mHeight
*mTileSize
) then exit
;
1136 curci
:= mGrid
[(y
div mTileSize
)*mWidth
+(x
div mTileSize
)];
1138 {$IF DEFINED(D2F_DEBUG_XXQ)}
1139 if (assigned(cb
)) then e_WriteLog(Format('1: grid pointquery: (%d,%d) (%d,%d) %d', [x
, y
, (x
div mTileSize
), (y
div mTileSize
), curci
]), MSG_NOTIFY
);
1146 // increase query counter
1148 if (mLastQuery
= 0) then
1150 // just in case of overflow
1152 for idx
:= 0 to High(mProxies
) do mProxies
[idx
].mQueryMark
:= 0;
1156 {$IF DEFINED(D2F_DEBUG_XXQ)}
1157 if (assigned(cb
)) then e_WriteLog(Format('2: grid pointquery: (%d,%d); lq=%u', [x
, y
, lq
]), MSG_NOTIFY
);
1160 while (curci
<> -1) do
1162 {$IF DEFINED(D2F_DEBUG_XXQ)}
1163 if (assigned(cb
)) then e_WriteLog(Format(' cell #%d', [curci
]), MSG_NOTIFY
);
1165 cc
:= @mCells
[curci
];
1166 for f
:= 0 to GridCellBucketSize
-1 do
1168 if (cc
.bodies
[f
] = -1) then break
;
1169 px
:= @mProxies
[cc
.bodies
[f
]];
1170 {$IF DEFINED(D2F_DEBUG_XXQ)}
1171 if (assigned(cb
)) then e_WriteLog(Format(' proxy #%d; qm:%u; tag:%08x; tagflag:%d %u', [cc
.bodies
[f
], px
.mQueryMark
, px
.mTag
, (px
.mTag
and tagmask
), LongWord(px
.mObj
)]), MSG_NOTIFY
);
1173 // shit. has to do it this way, so i can change tag in callback
1174 if (px
.mQueryMark
<> lq
) then
1176 px
.mQueryMark
:= lq
;
1178 if ((ptag
and TagDisabled
) = 0) and ((ptag
and tagmask
) <> 0) and
1179 (x
>= px
.mX
) and (y
>= px
.mY
) and (x
< px
.mX
+px
.mWidth
) and (y
< px
.mY
+px
.mHeight
) then
1181 if assigned(cb
) then
1183 if cb(px
.mObj
, ptag
) then
1186 if (exittag
<> nil) then exittag
^ := ptag
;
1193 if (exittag
<> nil) then exittag
^ := ptag
;
1204 // ////////////////////////////////////////////////////////////////////////// //
1205 // no callback: return `true` on the first hit
1206 function TBodyGridBase
.forEachInAABB (x
, y
, w
, h
: Integer; cb
: TGridQueryCB
; tagmask
: Integer=-1; allowDisabled
: Boolean=false): ITP
;
1214 cc
: PGridCell
= nil;
1221 result
:= Default(ITP
);
1222 if (w
< 1) or (h
< 1) then exit
;
1223 tagmask
:= tagmask
and TagFullMask
;
1224 if (tagmask
= 0) then exit
;
1234 //tsize := mTileSize;
1236 if (x
+w
<= 0) or (y
+h
<= 0) then exit
;
1237 if (x
>= gw
*tsize
) or (y
>= mHeight
*tsize
) then exit
;
1239 // increase query counter
1241 if (mLastQuery
= 0) then
1243 // just in case of overflow
1245 for idx
:= 0 to High(mProxies
) do mProxies
[idx
].mQueryMark
:= 0;
1247 //e_WriteLog(Format('grid: query #%d: (%d,%d)-(%dx%d)', [mLastQuery, minx, miny, maxx, maxy]), MSG_NOTIFY);
1251 for gy
:= y
div tsize
to (y
+h
-1) div tsize
do
1253 if (gy
< 0) then continue
;
1254 if (gy
>= mHeight
) then break
;
1255 for gx
:= x
div tsize
to (x
+w
-1) div tsize
do
1257 if (gx
< 0) then continue
;
1258 if (gx
>= gw
) then break
;
1260 curci
:= mGrid
[gy
*gw
+gx
];
1261 while (curci
<> -1) do
1263 cc
:= @mCells
[curci
];
1264 for f
:= 0 to GridCellBucketSize
-1 do
1266 if (cc
.bodies
[f
] = -1) then break
;
1267 px
:= @mProxies
[cc
.bodies
[f
]];
1268 // shit. has to do it this way, so i can change tag in callback
1269 if (px
.mQueryMark
= lq
) then continue
;
1270 px
.mQueryMark
:= lq
;
1272 if (not allowDisabled
) and ((ptag
and TagDisabled
) <> 0) then continue
;
1273 if ((ptag
and tagmask
) = 0) then continue
;
1274 if (x0
>= px
.mX
+px
.mWidth
) or (y0
>= px
.mY
+px
.mHeight
) then continue
;
1275 if (x0
+w
<= px
.mX
) or (y0
+h
<= px
.mY
) then continue
;
1276 if assigned(cb
) then
1278 if cb(px
.mObj
, ptag
) then begin result
:= px
.mObj
; exit
; end;
1293 // ////////////////////////////////////////////////////////////////////////// //
1294 // no callback: return `true` on the nearest hit
1295 function TBodyGridBase
.traceRay (const x0
, y0
, x1
, y1
: Integer; cb
: TGridRayQueryCB
; tagmask
: Integer=-1): ITP
;
1299 result
:= traceRay(ex
, ey
, x0
, y0
, x1
, y1
, cb
, tagmask
);
1303 // no callback: return `true` on the nearest hit
1304 // you are not supposed to understand this
1305 function TBodyGridBase
.traceRay (out ex
, ey
: Integer; const ax0
, ay0
, ax1
, ay1
: Integer; cb
: TGridRayQueryCB
; tagmask
: Integer=-1): ITP
;
1309 wx0
, wy0
, wx1
, wy1
: Integer; // window coordinates
1310 stx
, sty
: Integer; // "steps" for x and y axes
1311 dsx
, dsy
: Integer; // "lengthes" for x and y axes
1312 dx2
, dy2
: Integer; // "double lengthes" for x and y axes
1313 xd
, yd
: Integer; // current coord
1314 e
: Integer; // "error" (as in bresenham algo)
1317 xptr
, yptr
: PInteger;
1320 prevx
, prevy
: Integer;
1321 lastDistSq
: Integer;
1322 ccidx
, curci
: Integer;
1323 hasUntried
: Boolean;
1324 lastGA
: Integer = -1;
1327 wasHit
: Boolean = false;
1328 gw
, gh
, minx
, miny
, maxx
, maxy
: Integer;
1332 f
, ptag
, distSq
: Integer;
1333 x0
, y0
, x1
, y1
: Integer;
1334 swapped
: Boolean = false; // true: xd is yd, and vice versa
1335 // horizontal walker
1336 {$IFDEF GRID_USE_ORTHO_ACCEL}
1337 wklen
, wkstep
: Integer;
1342 xdist
, ydist
: Integer;
1344 result
:= Default(ITP
);
1345 lastObj
:= Default(ITP
);
1346 tagmask
:= tagmask
and TagFullMask
;
1347 ex
:= ax1
; // why not?
1348 ey
:= ay1
; // why not?
1349 if (tagmask
= 0) then exit
;
1351 if (ax0
= ax1
) and (ay0
= ay1
) then
1353 result
:= forEachAtPoint(ax0
, ay0
, nil, tagmask
, @ptag
);
1354 if (result
<> nil) then
1356 if assigned(cb
) and not cb(result
, ptag
, ax0
, ay0
, ax0
, ay0
) then result
:= Default(ITP
);
1361 lastDistSq
:= distanceSq(ax0
, ay0
, ax1
, ay1
)+1;
1370 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1371 if assigned(dbgRayTraceTileHitCB
) then e_WriteLog(Format('TRACING: (%d,%d)-(%d,%d) [(%d,%d)-(%d,%d)]; maxdistsq=%d', [ax0
, ay0
, ax1
, ay1
, minx
, miny
, maxx
, maxy
, lastDistSq
]), MSG_NOTIFY
);
1379 // offset query coords to (0,0)-based
1394 // from left to right
1395 if (x0
> wx1
) or (x1
< wx0
) then exit
; // out of screen
1396 stx
:= 1; // going right
1400 // from right to left
1401 if (x1
> wx1
) or (x0
< wx0
) then exit
; // out of screen
1402 stx
:= -1; // going left
1413 // from top to bottom
1414 if (y0
> wy1
) or (y1
< wy0
) then exit
; // out of screen
1415 sty
:= 1; // going down
1419 // from bottom to top
1420 if (y1
> wy1
) or (y0
< wy0
) then exit
; // out of screen
1421 sty
:= -1; // going up
1461 temp
:= dx2
*(wy0
-y0
)-dsx
;
1463 rem
:= temp
mod dy2
;
1464 if (xd
> wx1
) then exit
; // x is moved out of clipping rect, nothing to do
1465 if (xd
+1 >= wx0
) then
1469 if (rem
> 0) then begin Inc(xd
); e
+= dy2
; end;
1474 if (not xfixed
) and (x0
< wx0
) then
1477 temp
:= dy2
*(wx0
-x0
);
1479 rem
:= temp
mod dx2
;
1480 if (yd
> wy1
) or (yd
= wy1
) and (rem
>= dsx
) then exit
;
1483 if (rem
>= dsx
) then begin Inc(yd
); e
-= dx2
; end;
1489 temp
:= dx2
*(wy1
-y0
)+dsx
;
1490 term
:= x0
+temp
div dy2
;
1491 rem
:= temp
mod dy2
;
1492 if (rem
= 0) then Dec(term
);
1495 if (term
> wx1
) then term
:= wx1
; // clip at right
1497 Inc(term
); // draw last point
1498 //if (term = xd) then exit; // this is the only point, get out of here
1500 if (sty
= -1) then yd
:= -yd
;
1501 if (stx
= -1) then begin xd
:= -xd
; term
:= -term
; end;
1504 // first move, to skip starting point
1505 // DON'T DO THIS! loop will take care of that
1508 result
:= forEachAtPoint(ax0
, ay0
, nil, tagmask
, @ptag
);
1509 if (result
<> nil) then
1511 if assigned(cb
) then
1513 if cb(result
, ptag
, ax0
, ay0
, ax0
, ay0
) then
1532 prevx
:= xptr
^+minx
;
1533 prevy
:= yptr
^+miny
;
1536 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
1539 if (xd = term) then exit;
1542 {$IF DEFINED(D2F_DEBUG)}
1543 if (xptr
^ < 0) or (yptr
^ < 0) or (xptr
^ >= gw
*tsize
) and (yptr
^ >= gh
*tsize
) then raise Exception
.Create('raycaster internal error (0)');
1545 // DON'T DO THIS! loop will take care of that
1546 //lastGA := (yptr^ div tsize)*gw+(xptr^ div tsize);
1547 //ccidx := mGrid[lastGA];
1549 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1550 //if assigned(dbgRayTraceTileHitCB) then e_WriteLog('1:TRACING!', MSG_NOTIFY);
1553 //if (dbgShowTraceLog) then e_WriteLog(Format('raycast start: (%d,%d)-(%d,%d); xptr^=%d; yptr^=%d', [ax0, ay0, ax1, ay1, xptr^, yptr^]), MSG_NOTIFY);
1555 // increase query counter
1557 if (mLastQuery
= 0) then
1559 // just in case of overflow
1561 for f
:= 0 to High(mProxies
) do mProxies
[f
].mQueryMark
:= 0;
1565 {$IFDEF GRID_USE_ORTHO_ACCEL}
1566 // if this is strict horizontal/vertical trace, use optimized codepath
1567 if (ax0
= ax1
) or (ay0
= ay1
) then
1569 // horizontal trace: walk the whole tiles, calculating mindist once for each proxy in cell
1570 // stx < 0: going left, otherwise `stx` is > 0, and we're going right
1571 // vertical trace: walk the whole tiles, calculating mindist once for each proxy in cell
1572 // stx < 0: going up, otherwise `stx` is > 0, and we're going down
1573 hopt
:= (ay0
= ay1
); // horizontal?
1574 if (stx
< 0) then begin {wksign := -1;} wklen
:= -(term
-xd
); end else begin {wksign := 1;} wklen
:= term
-xd
; end;
1575 {$IF DEFINED(D2F_DEBUG)}
1576 if dbgShowTraceLog
then e_LogWritefln('optimized htrace; wklen=%d', [wklen
]);
1578 ga
:= (yptr
^ div tsize
)*gw
+(xptr
^ div tsize
);
1579 // one of those will never change
1584 {$IF DEFINED(D2F_DEBUG)}
1587 if (y
<> ay0
) then raise Exception
.Create('htrace fatal internal error');
1591 if (x
<> ax0
) then raise Exception
.Create('vtrace fatal internal error');
1594 while (wklen
> 0) do
1596 {$IF DEFINED(D2F_DEBUG)}
1597 if dbgShowTraceLog
then e_LogWritefln(' htrace; ga=%d; x=%d, y=%d; y=%d; y=%d', [ga
, xptr
^+minx
, yptr
^+miny
, y
, ay0
]);
1600 if (ga
<> lastGA
) then
1603 ccidx
:= mGrid
[lastGA
];
1604 // convert coords to map (to avoid ajdusting coords inside the loop)
1605 if hopt
then x
:= xptr
^+minx
else y
:= yptr
^+miny
;
1606 while (ccidx
<> -1) do
1608 cc
:= @mCells
[ccidx
];
1609 for f
:= 0 to GridCellBucketSize
-1 do
1611 if (cc
.bodies
[f
] = -1) then break
;
1612 px
:= @mProxies
[cc
.bodies
[f
]];
1614 if ((ptag
and TagDisabled
) = 0) and ((ptag
and tagmask
) <> 0) and (px
.mQueryMark
<> lq
) and
1615 // constant coord should be inside
1616 ((hopt
and (y
>= px
.mY
) and (y
< px
.mY
+px
.mHeight
)) or
1617 ((not hopt
) and (x
>= px
.mX
) and (x
< px
.mX
+px
.mWidth
))) then
1619 px
.mQueryMark
:= lq
; // mark as processed
1620 // inside the proxy?
1621 if (hopt
and (x
> px
.mX
) and (x
< px
.mX
+px
.mWidth
-1)) or
1622 ((not hopt
) and (y
> px
.mY
) and (y
< px
.mY
+px
.mHeight
-1)) then
1625 if assigned(cb
) then
1627 if cb(px
.mObj
, ptag
, x
, y
, x
, y
) then
1637 distSq
:= distanceSq(ax0
, ay0
, x
, y
);
1638 {$IF DEFINED(D2F_DEBUG)}
1639 if dbgShowTraceLog
then e_LogWritefln(' EMBEDDED hhit(%d): a=(%d,%d), h=(%d,%d), distsq=%d; lastsq=%d', [cc
.bodies
[f
], ax0
, ay0
, x
, y
, distSq
, lastDistSq
]);
1641 if (distSq
< lastDistSq
) then
1651 // remember this hitpoint if it is nearer than an old one
1661 if (x
< px
.mX
+px
.mWidth
-1) then continue
; // not on the right edge
1662 prevx
:= px
.mX
+px
.mWidth
;
1668 if (x
> px
.mX
) then continue
; // not on the left edge
1681 if (y
< px
.mY
+px
.mHeight
-1) then continue
; // not on the bottom edge
1682 prevy
:= px
.mY
+px
.mHeight
;
1688 if (y
> px
.mY
) then continue
; // not on the top edge
1693 if assigned(cb
) then
1695 if cb(px
.mObj
, ptag
, x
, y
, prevx
, prevy
) then
1705 distSq
:= distanceSq(ax0
, ay0
, prevx
, prevy
);
1706 {$IF DEFINED(D2F_DEBUG)}
1707 if dbgShowTraceLog
then e_LogWritefln(' hhit(%d): a=(%d,%d), h=(%d,%d), p=(%d,%d), distsq=%d; lastsq=%d', [cc
.bodies
[f
], ax0
, ay0
, x
, y
, prevx
, prevy
, distSq
, lastDistSq
]);
1709 if (distSq
< lastDistSq
) then
1712 lastDistSq
:= distSq
;
1723 if wasHit
and not assigned(cb
) then begin result
:= lastObj
; exit
; end;
1725 // skip to next tile
1731 wkstep
:= ((xptr
^ or (mTileSize
-1))+1)-xptr
^;
1732 {$IF DEFINED(D2F_DEBUG)}
1733 if dbgShowTraceLog
then e_LogWritefln(' right step: wklen=%d; wkstep=%d', [wklen
, wkstep
]);
1735 if (wkstep
>= wklen
) then break
;
1742 wkstep
:= xptr
^-((xptr
^ and (not (mTileSize
-1)))-1);
1743 {$IF DEFINED(D2F_DEBUG)}
1744 if dbgShowTraceLog
then e_LogWritefln(' left step: wklen=%d; wkstep=%d', [wklen
, wkstep
]);
1746 if (wkstep
>= wklen
) then break
;
1756 wkstep
:= ((yptr
^ or (mTileSize
-1))+1)-yptr
^;
1757 {$IF DEFINED(D2F_DEBUG)}
1758 if dbgShowTraceLog
then e_LogWritefln(' down step: wklen=%d; wkstep=%d', [wklen
, wkstep
]);
1760 if (wkstep
>= wklen
) then break
;
1767 wkstep
:= yptr
^-((yptr
^ and (not (mTileSize
-1)))-1);
1768 {$IF DEFINED(D2F_DEBUG)}
1769 if dbgShowTraceLog
then e_LogWritefln(' up step: wklen=%d; wkstep=%d', [wklen
, wkstep
]);
1771 if (wkstep
>= wklen
) then break
;
1778 // we can travel less than one cell
1779 if wasHit
and not assigned(cb
) then result
:= lastObj
else begin ex
:= ax1
; ey
:= ay1
; end;
1784 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1785 if assigned(dbgRayTraceTileHitCB
) then dbgRayTraceTileHitCB((xptr
^ div tsize
*tsize
)+minx
, (yptr
^ div tsize
*tsize
)+miny
);
1788 //e_LogWritefln('*********************', []);
1791 while (xd
<> term
) do
1794 {$IF DEFINED(D2F_DEBUG)}
1795 if (xptr
^ < 0) or (yptr
^ < 0) or (xptr
^ >= gw
*tsize
) and (yptr
^ >= gh
*tsize
) then raise Exception
.Create('raycaster internal error (0)');
1798 ga
:= (yptr
^ div tsize
)*gw
+(xptr
^ div tsize
);
1799 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1800 if assigned(dbgRayTraceTileHitCB
) then e_WriteLog(Format(' xd=%d; term=%d; gx=%d; gy=%d; ga=%d; lastga=%d', [xd
, term
, xptr
^, yptr
^, ga
, lastGA
]), MSG_NOTIFY
);
1802 if (ga
<> lastGA
) then
1805 {$IF DEFINED(D2F_DEBUG)}
1806 if assigned(dbgRayTraceTileHitCB
) then dbgRayTraceTileHitCB((xptr
^ div tsize
*tsize
)+minx
, (yptr
^ div tsize
*tsize
)+miny
);
1808 if (ccidx
<> -1) then
1810 // signal cell completion
1811 if assigned(cb
) then
1813 if cb(nil, 0, xptr
^+minx
, yptr
^+miny
, prevx
, prevy
) then begin result
:= lastObj
; exit
; end;
1822 ccidx
:= mGrid
[lastGA
];
1824 // has something to process in this tile?
1825 if (ccidx
<> -1) then
1829 hasUntried
:= false; // this will be set to `true` if we have some proxies we still want to process at the next step
1830 // convert coords to map (to avoid ajdusting coords inside the loop)
1833 // process cell list
1834 while (curci
<> -1) do
1836 cc
:= @mCells
[curci
];
1837 for f
:= 0 to GridCellBucketSize
-1 do
1839 if (cc
.bodies
[f
] = -1) then break
;
1840 px
:= @mProxies
[cc
.bodies
[f
]];
1842 if ((ptag
and TagDisabled
) = 0) and ((ptag
and tagmask
) <> 0) and (px
.mQueryMark
<> lq
) then
1844 // can we process this proxy?
1845 if (x
>= px
.mX
) and (y
>= px
.mY
) and (x
< px
.mX
+px
.mWidth
) and (y
< px
.mY
+px
.mHeight
) then
1847 px
.mQueryMark
:= lq
; // mark as processed
1848 if assigned(cb
) then
1850 if cb(px
.mObj
, ptag
, x
, y
, prevx
, prevy
) then
1858 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1859 distSq := distanceSq(ax0, ay0, prevx, prevy);
1860 if assigned(dbgRayTraceTileHitCB) then e_WriteLog(Format(' hit(%d): a=(%d,%d), h=(%d,%d), p=(%d,%d); distsq=%d; lastsq=%d', [cc.bodies[f], ax0, ay0, x, y, prevx, prevy, distSq, lastDistSq]), MSG_NOTIFY);
1861 if (distSq < lastDistSq) then
1864 lastDistSq := distSq;
1874 // remember this hitpoint if it is nearer than an old one
1875 distSq
:= distanceSq(ax0
, ay0
, prevx
, prevy
);
1876 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1877 if assigned(dbgRayTraceTileHitCB
) then e_WriteLog(Format(' hit(%d): a=(%d,%d), h=(%d,%d), p=(%d,%d); distsq=%d; lastsq=%d', [cc
.bodies
[f
], ax0
, ay0
, x
, y
, prevx
, prevy
, distSq
, lastDistSq
]), MSG_NOTIFY
);
1879 if (distSq
< lastDistSq
) then
1882 lastDistSq
:= distSq
;
1891 // this is possibly interesting proxy, set "has more to check" flag
1899 // still has something interesting in this cell?
1900 if not hasUntried
then
1902 // nope, don't process this cell anymore; signal cell completion
1904 if assigned(cb
) then
1906 if cb(nil, 0, x
, y
, prevx
, prevy
) then begin result
:= lastObj
; exit
; end;
1915 if (ccidx
= -1) then
1917 // move to cell edge, as we have nothing to trace here anymore
1918 if (stx
< 0) then xdist
:= xd
and (not (mTileSize
-1)) else xdist
:= xd
or (mTileSize
-1);
1919 if (sty
< 0) then ydist
:= yd
and (not (mTileSize
-1)) else ydist
:= yd
or (mTileSize
-1);
1920 //e_LogWritefln('0: swapped=%d; xd=%d; yd=%d; stx=%d; sty=%d; e=%d; dx2=%d; dy2=%d; term=%d; xdist=%d; ydist=%d', [swapped, xd, yd, stx, sty, e, dx2, dy2, term, xdist, ydist]);
1921 while (xd
<> xdist
) and (yd
<> ydist
) do
1925 if (e
>= 0) then begin yd
+= sty
; e
-= dx2
; end else e
+= dy2
;
1926 //e_LogWritefln(' xd=%d; yd=%d', [xd, yd]);
1927 if (xd
= term
) then break
;
1929 //e_LogWritefln('1: swapped=%d; xd=%d; yd=%d; stx=%d; sty=%d; e=%d; dx2=%d; dy2=%d; term=%d; xdist=%d; ydist=%d', [swapped, xd, yd, stx, sty, e, dx2, dy2, term, xdist, ydist]);
1930 if (xd
= term
) then break
;
1932 //putPixel(xptr^, yptr^);
1934 prevx
:= xptr
^+minx
;
1935 prevy
:= yptr
^+miny
;
1936 if (e
>= 0) then begin yd
+= sty
; e
-= dx2
; end else e
+= dy2
;
1939 // we can travel less than one cell
1940 if wasHit
and not assigned(cb
) then
1946 ex
:= ax1
; // why not?
1947 ey
:= ay1
; // why not?
1952 // ////////////////////////////////////////////////////////////////////////// //
1953 //FIXME! optimize this with real tile walking
1954 function TBodyGridBase
.forEachAlongLine (const x0
, y0
, x1
, y1
: Integer; cb
: TGridAlongQueryCB
; tagmask
: Integer=-1; log
: Boolean=false): ITP
;
1960 xerr
, yerr
: Integer;
1961 incx
, incy
: Integer;
1962 stepx
, stepy
: Integer;
1964 maxx
, maxy
: Integer;
1971 minx
, miny
: Integer;
1973 lastWasInGrid
: Boolean;
1979 result
:= Default(ITP
);
1980 tagmask
:= tagmask
and TagFullMask
;
1981 if (tagmask
= 0) or not assigned(cb
) then exit
;
1989 if (dx
> 0) then incx
:= 1 else if (dx
< 0) then incx
:= -1 else incx
:= 0;
1990 if (dy
> 0) then incy
:= 1 else if (dy
< 0) then incy
:= -1 else incy
:= 0;
1992 if (incx
= 0) and (incy
= 0) then exit
; // just incase
1997 if (dx
> dy
) then d
:= dx
else d
:= dy
;
1999 // `x` and `y` will be in grid coords
2003 // increase query counter
2005 if (mLastQuery
= 0) then
2007 // just in case of overflow
2009 for i
:= 0 to High(mProxies
) do mProxies
[i
].mQueryMark
:= 0;
2013 // cache various things
2014 //tsize := mTileSize;
2020 // setup distance and flags
2021 lastWasInGrid
:= (x
>= 0) and (y
>= 0) and (x
<= maxx
) and (y
<= maxy
);
2023 // setup starting tile ('cause we'll adjust tile vars only on tile edge crossing)
2024 if lastWasInGrid
then ccidx
:= mGrid
[(y
div tsize
)*gw
+(x
div tsize
)] else ccidx
:= -1;
2026 // it is slightly faster this way
2030 if (log
) then e_WriteLog(Format('tracing: (%d,%d)-(%d,%d)', [x
, y
, x1
-minx
, y1
-miny
]), MSG_NOTIFY
);
2040 // invariant: one of those always changed
2041 {$IF DEFINED(D2F_DEBUG)}
2042 if (xerr
< 0) and (yerr
< 0) then raise Exception
.Create('internal bug in grid raycaster (0)');
2044 if (xerr
>= 0) then begin xerr
-= d
; x
+= incx
; stepx
:= incx
; end else stepx
:= 0;
2045 if (yerr
>= 0) then begin yerr
-= d
; y
+= incy
; stepy
:= incy
; end else stepy
:= 0;
2046 // invariant: we always doing a step
2047 {$IF DEFINED(D2F_DEBUG)}
2048 if ((stepx
or stepy
) = 0) then raise Exception
.Create('internal bug in grid raycaster (1)');
2051 // check for crossing tile/grid boundary
2052 if (x
>= 0) and (y
>= 0) and (x
<= maxx
) and (y
<= maxy
) then
2054 // we're still in grid
2055 lastWasInGrid
:= true;
2056 // check for tile edge crossing
2057 if (stepx
< 0) and ((x
mod tsize
) = tsize
-1) then tbcross
:= true
2058 else if (stepx
> 0) and ((x
mod tsize
) = 0) then tbcross
:= true
2059 else if (stepy
< 0) and ((y
mod tsize
) = tsize
-1) then tbcross
:= true
2060 else if (stepy
> 0) and ((y
mod tsize
) = 0) then tbcross
:= true
2061 else tbcross
:= false;
2062 // crossed tile edge?
2065 // setup new cell index
2066 ccidx
:= mGrid
[(y
div tsize
)*gw
+(x
div tsize
)];
2067 if (log
) then e_WriteLog(Format(' stepped to new tile (%d,%d) -- (%d,%d)', [(x
div tsize
), (y
div tsize
), x
, y
]), MSG_NOTIFY
);
2070 if (ccidx
= -1) then
2072 // we have nothing interesting here anymore, jump directly to tile edge
2077 if (incy < 0) then tedist := y-(y and (not tsize)) else tedist := (y or (tsize-1))-y;
2078 if (tedist > 1) then
2080 if (log) then e_WriteLog(Format(' doing vertical jump from tile (%d,%d) - (%d,%d) by %d steps', [(x div tsize), (y div tsize), x, y, tedist]), MSG_NOTIFY);
2083 if (log) then e_WriteLog(Format(' jumped to tile (%d,%d) - (%d,%d) by %d steps', [(x div tsize), (y div tsize), x, y, tedist]), MSG_NOTIFY);
2086 else if (incy = 0) then
2089 if (incx < 0) then tedist := x-(x and (not tsize)) else tedist := (x or (tsize-1))-x;
2090 if (tedist > 1) then
2092 if (log) then e_WriteLog(Format(' doing horizontal jump from tile (%d,%d) - (%d,%d) by %d steps', [(x div tsize), (y div tsize), x, y, tedist]), MSG_NOTIFY);
2095 if (log) then e_WriteLog(Format(' jumped to tile (%d,%d) - (%d,%d) by %d steps', [(x div tsize), (y div tsize), x, y, tedist]), MSG_NOTIFY);
2101 // get minimal distance to tile edges
2102 if (incx < 0) then tedist := x-(x and (not tsize)) else if (incx > 0) then tedist := (x or (tsize+1))-x else tedist := 0;
2103 {$IF DEFINED(D2F_DEBUG)}
2104 if (tedist < 0) then raise Exception.Create('internal bug in grid raycaster (2.x)');
2106 if (incy < 0) then f := y-(y and (not tsize)) else if (incy > 0) then f := (y or (tsize+1))-y else f := 0;
2107 {$IF DEFINED(D2F_DEBUG)}
2108 if (f < 0) then raise Exception.Create('internal bug in grid raycaster (2.y)');
2110 if (tedist = 0) then tedist := f else if (f <> 0) then tedist := minInt(tedist, f);
2112 if (tedist > 1) then
2114 if (log) then e_WriteLog(Format(' doing jump from tile (%d,%d) - (%d,%d) by %d steps', [(x div tsize), (y div tsize), x, y, tedist]), MSG_NOTIFY);
2117 if (xerr >= 0) then begin x += incx*((xerr div d)+1); xerr := (xerr mod d)-d; end;
2118 if (yerr >= 0) then begin y += incy*((yerr div d)+1); yerr := (yerr mod d)-d; end;
2120 if (log) then e_WriteLog(Format(' jumped to tile (%d,%d) - (%d,%d) by %d steps', [(x div tsize), (y div tsize), x, y, tedist]), MSG_NOTIFY);
2128 if lastWasInGrid
then exit
; // oops, stepped out of the grid -- there is no way to return
2132 // has something to process in the current cell?
2133 if (ccidx
<> -1) then
2137 // convert coords to map (to avoid ajdusting coords inside the loop)
2140 // process cell list
2141 while (curci
<> -1) do
2143 cc
:= @mCells
[curci
];
2144 for f
:= 0 to GridCellBucketSize
-1 do
2146 if (cc
.bodies
[f
] = -1) then break
;
2147 px
:= @mProxies
[cc
.bodies
[f
]];
2149 if ((ptag
and TagDisabled
) = 0) and ((ptag
and tagmask
) <> 0) and (px
.mQueryMark
<> lq
) then
2151 px
.mQueryMark
:= lq
; // mark as processed
2152 if cb(px
.mObj
, ptag
) then begin result
:= px
.mObj
; exit
; end;
2158 ccidx
:= -1; // don't process this anymore
2159 // convert coords to grid