DEADSOFTWARE

grid: `traceBox()` API; `sweepAABB()` API
[d2df-sdl.git] / src / game / g_grid.pas
1 (* Copyright (C) DooM 2D:Forever Developers
2 *
3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation, either version 3 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *)
16 // 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}
22 {$ENDIF}
23 {.$DEFINE GRID_USE_ORTHO_ACCEL}
24 unit g_grid;
26 interface
29 type
30 TBodyProxyId = Integer;
32 generic TBodyGridBase<ITP> = class(TObject)
33 public
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
37 type TCellQueryCB = procedure (x, y: Integer) is nested; // top-left cell corner coords
39 const TagDisabled = $40000000;
40 const TagFullMask = $3fffffff;
42 private
43 const
44 GridDefaultTileSize = 32; // must be power of two!
45 GridCellBucketSize = 8; // WARNING! can't be less than 2!
47 public
48 type
49 PBodyProxyRec = ^TBodyProxyRec;
50 TBodyProxyRec = record
51 private
52 mX, mY, mWidth, mHeight: Integer; // aabb
53 mQueryMark: LongWord; // was this object visited at this query?
54 mObj: ITP;
55 mTag: Integer; // `TagDisabled` set: disabled ;-)
56 nextLink: TBodyProxyId; // next free or nothing
58 private
59 procedure setup (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer);
61 function getTag (): Integer; inline;
62 procedure setTag (v: Integer); inline;
64 function getEnabled (): Boolean; inline;
65 procedure setEnabled (v: Boolean); inline;
67 function getX1 (): Integer; inline;
68 function getY1 (): Integer; inline;
70 public
71 property x: Integer read mX;
72 property y: Integer read mY;
73 property width: Integer read mWidth;
74 property height: Integer read mHeight;
75 property tag: Integer read getTag write setTag;
76 property enabled: Boolean read getEnabled write setEnabled;
77 property obj: ITP read mObj;
79 property x0: Integer read mX;
80 property y0: Integer read mY;
81 property x1: Integer read getX1;
82 property y1: Integer read getY1;
83 end;
85 private
86 type
87 PGridCell = ^TGridCell;
88 TGridCell = record
89 bodies: array [0..GridCellBucketSize-1] of Integer; // -1: end of list
90 next: Integer; // in this cell; index in mCells
91 end;
93 TCellArray = array of TGridCell;
95 TGridInternalCB = function (grida: Integer; bodyId: TBodyProxyId): Boolean of object; // return `true` to stop
97 private
98 //mTileSize: Integer;
99 const mTileSize = GridDefaultTileSize;
100 type TGetProxyFn = function (pxidx: Integer): PBodyProxyRec of object;
102 public
103 const tileSize = mTileSize;
105 type
106 TAtPointEnumerator = record
107 private
108 mCells: TCellArray;
109 curidx, curbki: Integer;
110 getpx: TGetProxyFn;
111 public
112 constructor Create (acells: TCellArray; aidx: Integer; agetpx: TGetProxyFn);
113 function MoveNext (): Boolean; inline;
114 function getCurrent (): PBodyProxyRec; inline;
115 property Current: PBodyProxyRec read getCurrent;
116 end;
118 private
119 mMinX, mMinY: Integer; // so grids can start at any origin
120 mWidth, mHeight: Integer; // in tiles
121 mGrid: array of Integer; // mWidth*mHeight, index in mCells
122 mCells: TCellArray; // cell pool
123 mFreeCell: Integer; // first free cell index or -1
124 mLastQuery: LongWord;
125 mUsedCells: Integer;
126 mProxies: array of TBodyProxyRec;
127 mProxyFree: TBodyProxyId; // free
128 mProxyCount: Integer; // currently used
129 mProxyMaxCount: Integer;
130 mInQuery: Boolean;
132 public
133 dbgShowTraceLog: Boolean;
134 {$IF DEFINED(D2F_DEBUG)}
135 dbgRayTraceTileHitCB: TCellQueryCB;
136 {$ENDIF}
138 private
139 function allocCell (): Integer;
140 procedure freeCell (idx: Integer); // `next` is simply overwritten
142 function allocProxy (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer): TBodyProxyId;
143 procedure freeProxy (body: TBodyProxyId);
145 procedure insertInternal (body: TBodyProxyId);
146 procedure removeInternal (body: TBodyProxyId);
148 function forGridRect (x, y, w, h: Integer; cb: TGridInternalCB; bodyId: TBodyProxyId): Boolean;
150 function inserter (grida: Integer; bodyId: TBodyProxyId): Boolean;
151 function remover (grida: Integer; bodyId: TBodyProxyId): Boolean;
153 function getProxyEnabled (pid: TBodyProxyId): Boolean; inline;
154 procedure setProxyEnabled (pid: TBodyProxyId; val: Boolean); inline;
156 function getGridWidthPx (): Integer; inline;
157 function getGridHeightPx (): Integer; inline;
159 function getProxyById (idx: TBodyProxyId): PBodyProxyRec; inline;
161 public
162 constructor Create (aMinPixX, aMinPixY, aPixWidth, aPixHeight: Integer{; aTileSize: Integer=GridDefaultTileSize});
163 destructor Destroy (); override;
165 function insertBody (aObj: ITP; ax, ay, aWidth, aHeight: Integer; aTag: Integer=-1): TBodyProxyId;
166 procedure removeBody (body: TBodyProxyId); // WARNING! this WILL destroy proxy!
168 procedure moveBody (body: TBodyProxyId; nx, ny: Integer);
169 procedure resizeBody (body: TBodyProxyId; nw, nh: Integer);
170 procedure moveResizeBody (body: TBodyProxyId; nx, ny, nw, nh: Integer);
172 function insideGrid (x, y: Integer): Boolean; inline;
174 // `false` if `body` is surely invalid
175 function getBodyXY (body: TBodyProxyId; out rx, ry: Integer): Boolean; inline;
176 function getBodyWH (body: TBodyProxyId; out rw, rh: Integer): Boolean; inline;
177 function getBodyDims (body: TBodyProxyId; out rx, ry, rw, rh: Integer): Boolean; inline;
179 //WARNING: don't modify grid while any query is in progress (no checks are made!)
180 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
181 // no callback: return `true` on the first hit
182 function forEachInAABB (x, y, w, h: Integer; cb: TGridQueryCB; tagmask: Integer=-1; allowDisabled: Boolean=false): ITP;
184 //WARNING: don't modify grid while any query is in progress (no checks are made!)
185 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
186 // no callback: return object on the first hit or nil
187 function forEachAtPoint (x, y: Integer; cb: TGridQueryCB; tagmask: Integer=-1; exittag: PInteger=nil): ITP;
189 function atCellInPoint (x, y: Integer): TAtPointEnumerator;
191 //WARNING: don't modify grid while any query is in progress (no checks are made!)
192 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
193 // cb with `(nil)` will be called before processing new tile
194 // no callback: return object of the nearest hit or nil
195 // if `inverted` is true, trace will register bodies *exluding* tagmask
196 //WARNING: don't change tags in callbacks here!
197 function traceRay (const x0, y0, x1, y1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP; overload;
198 function traceRay (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
200 // return `false` if we're still inside at the end
201 // line should be either strict horizontal, or strict vertical, otherwise an exception will be thrown
202 // `true`: endpoint will point at the last "inside" pixel
203 // `false`: endpoint will be (ax1, ay1)
204 function traceOrthoRayWhileIn (out ex, ey: Integer; ax0, ay0, ax1, ay1: Integer; tagmask: Integer=-1): Boolean;
206 //WARNING: don't modify grid while any query is in progress (no checks are made!)
207 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
208 // trace line along the grid, calling `cb` for all objects in passed cells, in no particular order
209 //WARNING: don't change tags in callbacks here!
210 function forEachAlongLine (ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1; log: Boolean=false): ITP;
212 // trace box with the given velocity; return object hit (if any)
213 // `cb` is used unconvetionally here: if it returns `false`, tracer will ignore the object
214 function traceBox (out ex, ey: Integer; const ax0, ay0, aw, ah: Integer; const dx, dy: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
216 // debug
217 procedure forEachBodyCell (body: TBodyProxyId; cb: TCellQueryCB);
218 function forEachInCell (x, y: Integer; cb: TGridQueryCB): ITP;
219 procedure dumpStats ();
221 public
222 //WARNING! no sanity checks!
223 property proxyEnabled[pid: TBodyProxyId]: Boolean read getProxyEnabled write setProxyEnabled;
225 property gridX0: Integer read mMinX;
226 property gridY0: Integer read mMinY;
227 property gridWidth: Integer read getGridWidthPx; // in pixels
228 property gridHeight: Integer read getGridHeightPx; // in pixels
230 property proxy[idx: TBodyProxyId]: PBodyProxyRec read getProxyById;
231 end;
234 // you are not supposed to understand this
235 // returns `true` if there is an intersection, and enter coords
236 // enter coords will be equal to (x0, y0) if starting point is inside the box
237 // if result is `false`, `inx` and `iny` are undefined
238 function lineAABBIntersects (x0, y0, x1, y1: Integer; bx, by, bw, bh: Integer; out inx, iny: Integer): Boolean;
240 // sweep two AABB's to see if and when they are overlapping
241 // returns `true` if collision was detected (or boxes overlaps)
242 // u0 = normalized time of first collision (i.e. collision starts at myMove*u0)
243 // u1 = normalized time of second collision (i.e. collision stops after myMove*u1)
244 // if no collision was detected:
245 // u1 < 0: no collision at all
246 // u1 >= 0: boxes are overlapping at the start; u0 has no meaning, u1 is exit time, hitedge is undefined
247 // hitedge for `it`: 0: top; 1: right; 2: bottom; 3: left
248 // enter/exit coords will form non-intersecting configuration (i.e. will be before/after the actual collision)
249 function sweepAABB (mex0, mey0, mew, meh: Integer; medx, medy: Integer; itx0, ity0, itw, ith: Integer;
250 u0: PSingle=nil; hitedge: PInteger=nil; u1: PSingle=nil): Boolean;
252 function distanceSq (x0, y0, x1, y1: Integer): Integer; inline;
254 procedure swapInt (var a: Integer; var b: Integer); inline;
255 function minInt (a, b: Integer): Integer; inline;
256 function maxInt (a, b: Integer): Integer; inline;
259 implementation
261 uses
262 SysUtils, e_log, g_console, utils;
265 // ////////////////////////////////////////////////////////////////////////// //
266 procedure swapInt (var a: Integer; var b: Integer); inline; var t: Integer; begin t := a; a := b; b := t; end;
267 function minInt (a, b: Integer): Integer; inline; begin if (a < b) then result := a else result := b; end;
268 function maxInt (a, b: Integer): Integer; inline; begin if (a > b) then result := a else result := b; end;
270 function distanceSq (x0, y0, x1, y1: Integer): Integer; inline; begin result := (x1-x0)*(x1-x0)+(y1-y0)*(y1-y0); end;
273 // ////////////////////////////////////////////////////////////////////////// //
274 // you are not supposed to understand this
275 // returns `true` if there is an intersection, and enter coords
276 // enter coords will be equal to (x0, y0) if starting point is inside the box
277 // if result is `false`, `inx` and `iny` are undefined
278 function lineAABBIntersects (x0, y0, x1, y1: Integer; bx, by, bw, bh: Integer; out inx, iny: Integer): Boolean;
279 var
280 wx0, wy0, wx1, wy1: Integer; // window coordinates
281 stx, sty: Integer; // "steps" for x and y axes
282 dsx, dsy: Integer; // "lengthes" for x and y axes
283 dx2, dy2: Integer; // "double lengthes" for x and y axes
284 xd, yd: Integer; // current coord
285 e: Integer; // "error" (as in bresenham algo)
286 rem: Integer;
287 //!term: Integer;
288 d0, d1: PInteger;
289 xfixed: Boolean;
290 temp: Integer;
291 begin
292 result := false;
293 // why not
294 inx := x0;
295 iny := y0;
296 if (bw < 1) or (bh < 1) then exit; // impossible box
298 if (x0 = x1) and (y0 = y1) then
299 begin
300 // check this point
301 result := (x0 >= bx) and (y0 >= by) and (x0 < bx+bw) and (y0 < by+bh);
302 exit;
303 end;
305 // check if staring point is inside the box
306 if (x0 >= bx) and (y0 >= by) and (x0 < bx+bw) and (y0 < by+bh) then begin result := true; exit; end;
308 // clip rectange
309 wx0 := bx;
310 wy0 := by;
311 wx1 := bx+bw-1;
312 wy1 := by+bh-1;
314 // horizontal setup
315 if (x0 < x1) then
316 begin
317 // from left to right
318 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
319 stx := 1; // going right
320 end
321 else
322 begin
323 // from right to left
324 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
325 stx := -1; // going left
326 x0 := -x0;
327 x1 := -x1;
328 wx0 := -wx0;
329 wx1 := -wx1;
330 swapInt(wx0, wx1);
331 end;
333 // vertical setup
334 if (y0 < y1) then
335 begin
336 // from top to bottom
337 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
338 sty := 1; // going down
339 end
340 else
341 begin
342 // from bottom to top
343 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
344 sty := -1; // going up
345 y0 := -y0;
346 y1 := -y1;
347 wy0 := -wy0;
348 wy1 := -wy1;
349 swapInt(wy0, wy1);
350 end;
352 dsx := x1-x0;
353 dsy := y1-y0;
355 if (dsx < dsy) then
356 begin
357 d0 := @yd;
358 d1 := @xd;
359 swapInt(x0, y0);
360 swapInt(x1, y1);
361 swapInt(dsx, dsy);
362 swapInt(wx0, wy0);
363 swapInt(wx1, wy1);
364 swapInt(stx, sty);
365 end
366 else
367 begin
368 d0 := @xd;
369 d1 := @yd;
370 end;
372 dx2 := 2*dsx;
373 dy2 := 2*dsy;
374 xd := x0;
375 yd := y0;
376 e := 2*dsy-dsx;
377 //!term := x1;
379 xfixed := false;
380 if (y0 < wy0) then
381 begin
382 // clip at top
383 temp := dx2*(wy0-y0)-dsx;
384 xd += temp div dy2;
385 rem := temp mod dy2;
386 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
387 if (xd+1 >= wx0) then
388 begin
389 yd := wy0;
390 e -= rem+dsx;
391 if (rem > 0) then begin Inc(xd); e += dy2; end;
392 xfixed := true;
393 end;
394 end;
396 if (not xfixed) and (x0 < wx0) then
397 begin
398 // clip at left
399 temp := dy2*(wx0-x0);
400 yd += temp div dx2;
401 rem := temp mod dx2;
402 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
403 xd := wx0;
404 e += rem;
405 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
406 end;
408 (*
409 if (y1 > wy1) then
410 begin
411 // clip at bottom
412 temp := dx2*(wy1-y0)+dsx;
413 term := x0+temp div dy2;
414 rem := temp mod dy2;
415 if (rem = 0) then Dec(term);
416 end;
418 if (term > wx1) then term := wx1; // clip at right
420 Inc(term); // draw last point
421 //if (term = xd) then exit; // this is the only point, get out of here
422 *)
424 if (sty = -1) then yd := -yd;
425 if (stx = -1) then begin xd := -xd; {!term := -term;} end;
426 //!dx2 -= dy2;
428 inx := d0^;
429 iny := d1^;
430 result := true;
431 end;
434 // ////////////////////////////////////////////////////////////////////////// //
435 function sweepAABB (mex0, mey0, mew, meh: Integer; medx, medy: Integer; itx0, ity0, itw, ith: Integer;
436 u0: PSingle=nil; hitedge: PInteger=nil; u1: PSingle=nil): Boolean;
437 var
438 tin, tout: Single;
440 function axisOverlap (me0, me1, it0, it1, d, he0, he1: Integer): Boolean; inline;
441 var
442 t: Single;
443 begin
444 result := false;
446 if (me1 < it0) then
447 begin
448 if (d >= 0) then exit; // oops, no hit
449 t := (me1-it0+1)/d;
450 if (t > tin) then begin tin := t; hitedge^ := he1; end;
451 end
452 else if (it1 < me0) then
453 begin
454 if (d <= 0) then exit; // oops, no hit
455 t := (me0-it1-1)/d;
456 if (t > tin) then begin tin := t; hitedge^ := he0; end;
457 end;
459 if (d < 0) and (it1 > me0) then
460 begin
461 t := (me0-it1-1)/d;
462 if (t < tout) then tout := t;
463 end
464 else if (d > 0) and (me1 > it0) then
465 begin
466 t := (me1-it0+1)/d;
467 if (t < tout) then tout := t;
468 end;
470 result := true;
471 end;
473 var
474 mex1, mey1, itx1, ity1, vx, vy: Integer;
475 htt: Integer = -1;
476 begin
477 result := false;
478 if (u0 <> nil) then u0^ := -1.0;
479 if (u1 <> nil) then u1^ := -1.0;
480 if (hitedge = nil) then hitedge := @htt else hitedge^ := -1;
482 if (mew < 1) or (meh < 1) or (itw < 1) or (ith < 1) then exit;
484 mex1 := mex0+mew-1;
485 mey1 := mey0+meh-1;
486 itx1 := itx0+itw-1;
487 ity1 := ity0+ith-1;
489 // check if they are overlapping right now (SAT)
490 //if (mex1 >= itx0) and (mex0 <= itx1) and (mey1 >= ity0) and (mey0 <= ity1) then begin result := true; exit; end;
492 if (medx = 0) and (medy = 0) then exit; // both boxes are sationary
494 // treat b as stationary, so invert v to get relative velocity
495 vx := -medx;
496 vy := -medy;
498 tin := -100000000.0;
499 tout := 100000000.0;
501 if not axisOverlap(mex0, mex1, itx0, itx1, vx, 1, 3) then exit;
502 if not axisOverlap(mey0, mey1, ity0, ity1, vy, 2, 0) then exit;
504 if (u0 <> nil) then u0^ := tin;
505 if (u1 <> nil) then u1^ := tout;
507 if (tin <= tout) and (tin >= 0.0) and (tin <= 1.0) then
508 begin
509 result := true;
510 end;
511 end;
514 // ////////////////////////////////////////////////////////////////////////// //
515 procedure TBodyGridBase.TBodyProxyRec.setup (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer);
516 begin
517 mX := aX;
518 mY := aY;
519 mWidth := aWidth;
520 mHeight := aHeight;
521 mQueryMark := 0;
522 mObj := aObj;
523 mTag := aTag;
524 nextLink := -1;
525 end;
528 function TBodyGridBase.TBodyProxyRec.getTag (): Integer; inline;
529 begin
530 result := mTag and TagFullMask;
531 end;
533 procedure TBodyGridBase.TBodyProxyRec.setTag (v: Integer); inline;
534 begin
535 mTag := (mTag and TagDisabled) or (v and TagFullMask);
536 end;
538 function TBodyGridBase.TBodyProxyRec.getEnabled (): Boolean; inline;
539 begin
540 result := ((mTag and TagDisabled) = 0);
541 end;
543 procedure TBodyGridBase.TBodyProxyRec.setEnabled (v: Boolean); inline;
544 begin
545 if v then mTag := mTag and (not TagDisabled) else mTag := mTag or TagDisabled;
546 end;
548 function TBodyGridBase.TBodyProxyRec.getX1 (): Integer; inline;
549 begin
550 result := mX+mWidth-1;
551 end;
553 function TBodyGridBase.TBodyProxyRec.getY1 (): Integer; inline;
554 begin
555 result := mY+mHeight-1;
556 end;
559 // ////////////////////////////////////////////////////////////////////////// //
560 constructor TBodyGridBase.TAtPointEnumerator.Create (acells: TCellArray; aidx: Integer; agetpx: TGetProxyFn);
561 begin
562 mCells := acells;
563 curidx := aidx;
564 curbki := -1;
565 getpx := agetpx;
566 end;
569 function TBodyGridBase.TAtPointEnumerator.MoveNext (): Boolean; inline;
570 begin
571 while (curidx <> -1) do
572 begin
573 while (curbki < GridCellBucketSize) do
574 begin
575 Inc(curbki);
576 if (mCells[curidx].bodies[curbki] = -1) then break;
577 result := true;
578 exit;
579 end;
580 curidx := mCells[curidx].next;
581 curbki := -1;
582 end;
583 result := false;
584 end;
587 function TBodyGridBase.TAtPointEnumerator.getCurrent (): PBodyProxyRec; inline;
588 begin
589 result := getpx(mCells[curidx].bodies[curbki]);
590 end;
593 // ////////////////////////////////////////////////////////////////////////// //
594 constructor TBodyGridBase.Create (aMinPixX, aMinPixY, aPixWidth, aPixHeight: Integer{; aTileSize: Integer=GridDefaultTileSize});
595 var
596 idx: Integer;
597 begin
598 dbgShowTraceLog := false;
599 {$IF DEFINED(D2F_DEBUG)}
600 dbgRayTraceTileHitCB := nil;
601 {$ENDIF}
603 if aTileSize < 1 then aTileSize := 1;
604 if aTileSize > 8192 then aTileSize := 8192; // arbitrary limit
605 mTileSize := aTileSize;
607 if (aPixWidth < mTileSize) then aPixWidth := mTileSize;
608 if (aPixHeight < mTileSize) then aPixHeight := mTileSize;
609 mMinX := aMinPixX;
610 mMinY := aMinPixY;
611 mWidth := (aPixWidth+mTileSize-1) div mTileSize;
612 mHeight := (aPixHeight+mTileSize-1) div mTileSize;
613 SetLength(mGrid, mWidth*mHeight);
614 SetLength(mCells, mWidth*mHeight);
615 SetLength(mProxies, 8192);
616 mFreeCell := 0;
617 // init free list
618 for idx := 0 to High(mCells) do
619 begin
620 mCells[idx].bodies[0] := -1;
621 mCells[idx].bodies[GridCellBucketSize-1] := -1; // "has free room" flag
622 mCells[idx].next := idx+1;
623 end;
624 mCells[High(mCells)].next := -1; // last cell
625 // init grid
626 for idx := 0 to High(mGrid) do mGrid[idx] := -1;
627 // init proxies
628 for idx := 0 to High(mProxies) do mProxies[idx].nextLink := idx+1;
629 mProxies[High(mProxies)].nextLink := -1;
630 mLastQuery := 0;
631 mUsedCells := 0;
632 mProxyFree := 0;
633 mProxyCount := 0;
634 mProxyMaxCount := 0;
635 e_WriteLog(Format('created grid with size: %dx%d (tile size: %d); pix: %dx%d', [mWidth, mHeight, mTileSize, mWidth*mTileSize, mHeight*mTileSize]), MSG_NOTIFY);
636 end;
639 destructor TBodyGridBase.Destroy ();
640 begin
641 mCells := nil;
642 mGrid := nil;
643 mProxies := nil;
644 inherited;
645 end;
648 // ////////////////////////////////////////////////////////////////////////// //
649 procedure TBodyGridBase.dumpStats ();
650 var
651 idx, mcb, cidx, cnt: Integer;
652 begin
653 mcb := 0;
654 for idx := 0 to High(mGrid) do
655 begin
656 cidx := mGrid[idx];
657 cnt := 0;
658 while cidx >= 0 do
659 begin
660 Inc(cnt);
661 cidx := mCells[cidx].next;
662 end;
663 if (mcb < cnt) then mcb := cnt;
664 end;
665 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);
666 end;
669 procedure TBodyGridBase.forEachBodyCell (body: TBodyProxyId; cb: TCellQueryCB);
670 var
671 g, f, cidx: Integer;
672 cc: PGridCell;
673 begin
674 if (body < 0) or (body > High(mProxies)) or not assigned(cb) then exit;
675 for g := 0 to High(mGrid) do
676 begin
677 cidx := mGrid[g];
678 while (cidx <> -1) do
679 begin
680 cc := @mCells[cidx];
681 for f := 0 to GridCellBucketSize-1 do
682 begin
683 if (cc.bodies[f] = -1) then break;
684 if (cc.bodies[f] = body) then cb((g mod mWidth)*mTileSize+mMinX, (g div mWidth)*mTileSize+mMinY);
685 end;
686 // next cell
687 cidx := cc.next;
688 end;
689 end;
690 end;
693 function TBodyGridBase.forEachInCell (x, y: Integer; cb: TGridQueryCB): ITP;
694 var
695 f, cidx: Integer;
696 cc: PGridCell;
697 begin
698 result := Default(ITP);
699 if not assigned(cb) then exit;
700 Dec(x, mMinX);
701 Dec(y, mMinY);
702 if (x < 0) or (y < 0) or (x >= mWidth*mTileSize) or (y > mHeight*mTileSize) then exit;
703 cidx := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
704 while (cidx <> -1) do
705 begin
706 cc := @mCells[cidx];
707 for f := 0 to GridCellBucketSize-1 do
708 begin
709 if (cc.bodies[f] = -1) then break;
710 if cb(mProxies[cc.bodies[f]].mObj, mProxies[cc.bodies[f]].mTag) then begin result := mProxies[cc.bodies[f]].mObj; exit; end;
711 end;
712 // next cell
713 cidx := cc.next;
714 end;
715 end;
718 // ////////////////////////////////////////////////////////////////////////// //
719 function TBodyGridBase.getGridWidthPx (): Integer; inline; begin result := mWidth*mTileSize; end;
720 function TBodyGridBase.getGridHeightPx (): Integer; inline; begin result := mHeight*mTileSize; end;
723 function TBodyGridBase.insideGrid (x, y: Integer): Boolean; inline;
724 begin
725 // fix coords
726 Dec(x, mMinX);
727 Dec(y, mMinY);
728 result := (x >= 0) and (y >= 0) and (x < mWidth*mTileSize) and (y < mHeight*mTileSize);
729 end;
732 function TBodyGridBase.getBodyXY (body: TBodyProxyId; out rx, ry: Integer): Boolean; inline;
733 begin
734 if (body >= 0) and (body < Length(mProxies)) then
735 begin
736 with mProxies[body] do begin rx := mX; ry := mY; end;
737 result := true;
738 end
739 else
740 begin
741 rx := 0;
742 ry := 0;
743 result := false;
744 end;
745 end;
748 function TBodyGridBase.getBodyWH (body: TBodyProxyId; out rw, rh: Integer): Boolean; inline;
749 begin
750 if (body >= 0) and (body < Length(mProxies)) then
751 begin
752 with mProxies[body] do begin rw := mWidth; rh := mHeight; end;
753 result := true;
754 end
755 else
756 begin
757 rw := 0;
758 rh := 0;
759 result := false;
760 end;
761 end;
764 function TBodyGridBase.getBodyDims (body: TBodyProxyId; out rx, ry, rw, rh: Integer): Boolean; inline;
765 begin
766 if (body >= 0) and (body < Length(mProxies)) then
767 begin
768 with mProxies[body] do begin rx := mX; ry := mY; rw := mWidth; rh := mHeight; end;
769 result := true;
770 end
771 else
772 begin
773 rx := 0;
774 ry := 0;
775 rw := 0;
776 rh := 0;
777 result := false;
778 end;
779 end;
783 // ////////////////////////////////////////////////////////////////////////// //
784 function TBodyGridBase.getProxyEnabled (pid: TBodyProxyId): Boolean; inline;
785 begin
786 if (pid >= 0) and (pid < Length(mProxies)) then result := ((mProxies[pid].mTag and TagDisabled) = 0) else result := false;
787 end;
790 procedure TBodyGridBase.setProxyEnabled (pid: TBodyProxyId; val: Boolean); inline;
791 begin
792 if (pid >= 0) and (pid < Length(mProxies)) then
793 begin
794 if val then
795 begin
796 mProxies[pid].mTag := mProxies[pid].mTag and not TagDisabled;
797 end
798 else
799 begin
800 mProxies[pid].mTag := mProxies[pid].mTag or TagDisabled;
801 end;
802 end;
803 end;
806 function TBodyGridBase.getProxyById (idx: TBodyProxyId): PBodyProxyRec; inline;
807 begin
808 if (idx >= 0) and (idx < Length(mProxies)) then result := @mProxies[idx] else result := nil;
809 end;
812 // ////////////////////////////////////////////////////////////////////////// //
813 function TBodyGridBase.allocCell (): Integer;
814 var
815 idx: Integer;
816 pc: PGridCell;
817 begin
818 if (mFreeCell < 0) then
819 begin
820 // no free cells, want more
821 mFreeCell := Length(mCells);
822 SetLength(mCells, mFreeCell+32768); // arbitrary number
823 for idx := mFreeCell to High(mCells) do
824 begin
825 mCells[idx].bodies[0] := -1;
826 mCells[idx].bodies[GridCellBucketSize-1] := -1; // 'has free room' flag
827 mCells[idx].next := idx+1;
828 end;
829 mCells[High(mCells)].next := -1; // last cell
830 end;
831 result := mFreeCell;
832 pc := @mCells[result];
833 mFreeCell := pc.next;
834 pc.next := -1;
835 Inc(mUsedCells);
836 //e_WriteLog(Format('grid: allocated new cell #%d (total: %d)', [result, mUsedCells]), MSG_NOTIFY);
837 end;
840 procedure TBodyGridBase.freeCell (idx: Integer);
841 begin
842 if (idx >= 0) and (idx < Length(mCells)) then
843 begin
844 with mCells[idx] do
845 begin
846 bodies[0] := -1;
847 bodies[GridCellBucketSize-1] := -1; // 'has free room' flag
848 next := mFreeCell;
849 end;
850 mFreeCell := idx;
851 Dec(mUsedCells);
852 end;
853 end;
856 // ////////////////////////////////////////////////////////////////////////// //
857 function TBodyGridBase.allocProxy (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer): TBodyProxyId;
858 var
859 olen, idx: Integer;
860 px: PBodyProxyRec;
861 begin
862 if (mProxyFree = -1) then
863 begin
864 // no free proxies, resize list
865 olen := Length(mProxies);
866 SetLength(mProxies, olen+8192); // arbitrary number
867 for idx := olen to High(mProxies) do mProxies[idx].nextLink := idx+1;
868 mProxies[High(mProxies)].nextLink := -1;
869 mProxyFree := olen;
870 end;
871 // get one from list
872 result := mProxyFree;
873 px := @mProxies[result];
874 mProxyFree := px.nextLink;
875 px.setup(aX, aY, aWidth, aHeight, aObj, aTag);
876 // add to used list
877 px.nextLink := -1;
878 // statistics
879 Inc(mProxyCount);
880 if (mProxyMaxCount < mProxyCount) then mProxyMaxCount := mProxyCount;
881 end;
883 procedure TBodyGridBase.freeProxy (body: TBodyProxyId);
884 begin
885 if (body < 0) or (body > High(mProxies)) then exit; // just in case
886 if (mProxyCount = 0) then raise Exception.Create('wutafuuuuu in grid (no allocated proxies, what i should free now?)');
887 // add to free list
888 mProxies[body].mObj := nil;
889 mProxies[body].nextLink := mProxyFree;
890 mProxyFree := body;
891 Dec(mProxyCount);
892 end;
895 // ////////////////////////////////////////////////////////////////////////// //
896 function TBodyGridBase.forGridRect (x, y, w, h: Integer; cb: TGridInternalCB; bodyId: TBodyProxyId): Boolean;
897 const
898 tsize = mTileSize;
899 var
900 gx, gy: Integer;
901 gw, gh: Integer;
902 begin
903 result := false;
904 if (w < 1) or (h < 1) or not assigned(cb) then exit;
905 // fix coords
906 Dec(x, mMinX);
907 Dec(y, mMinY);
908 // go on
909 if (x+w <= 0) or (y+h <= 0) then exit;
910 gw := mWidth;
911 gh := mHeight;
912 //tsize := mTileSize;
913 if (x >= gw*tsize) or (y >= gh*tsize) then exit;
914 for gy := y div tsize to (y+h-1) div tsize do
915 begin
916 if (gy < 0) then continue;
917 if (gy >= gh) then break;
918 for gx := x div tsize to (x+w-1) div tsize do
919 begin
920 if (gx < 0) then continue;
921 if (gx >= gw) then break;
922 result := cb(gy*gw+gx, bodyId);
923 if result then exit;
924 end;
925 end;
926 end;
929 // ////////////////////////////////////////////////////////////////////////// //
930 function TBodyGridBase.inserter (grida: Integer; bodyId: TBodyProxyId): Boolean;
931 var
932 cidx: Integer;
933 pc: Integer;
934 pi: PGridCell;
935 f: Integer;
936 begin
937 result := false; // never stop
938 // add body to the given grid cell
939 pc := mGrid[grida];
940 if (pc <> -1) then
941 begin
942 {$IF DEFINED(D2F_DEBUG)}
943 cidx := pc;
944 while (cidx <> -1) do
945 begin
946 pi := @mCells[cidx];
947 for f := 0 to GridCellBucketSize-1 do
948 begin
949 if (pi.bodies[f] = -1) then break;
950 if (pi.bodies[f] = bodyId) then raise Exception.Create('trying to insert already inserted proxy');
951 end;
952 cidx := pi.next;
953 end;
954 {$ENDIF}
955 cidx := pc;
956 while (cidx <> -1) do
957 begin
958 pi := @mCells[cidx];
959 // check "has room" flag
960 if (pi.bodies[GridCellBucketSize-1] = -1) then
961 begin
962 // can add here
963 for f := 0 to GridCellBucketSize-1 do
964 begin
965 if (pi.bodies[f] = -1) then
966 begin
967 pi.bodies[f] := bodyId;
968 if (f+1 < GridCellBucketSize) then pi.bodies[f+1] := -1;
969 exit;
970 end;
971 end;
972 raise Exception.Create('internal error in grid inserter');
973 end;
974 // no room, go to next cell in list (if there is any)
975 cidx := pi.next;
976 end;
977 // no room in cells, add new cell to list
978 end;
979 // either no room, or no cell at all
980 cidx := allocCell();
981 pi := @mCells[cidx];
982 pi.bodies[0] := bodyId;
983 pi.bodies[1] := -1;
984 pi.next := pc;
985 mGrid[grida] := cidx;
986 end;
988 procedure TBodyGridBase.insertInternal (body: TBodyProxyId);
989 var
990 px: PBodyProxyRec;
991 begin
992 if (body < 0) or (body > High(mProxies)) then exit; // just in case
993 px := @mProxies[body];
994 forGridRect(px.mX, px.mY, px.mWidth, px.mHeight, inserter, body);
995 end;
998 // assume that we cannot have one object added to bucket twice
999 function TBodyGridBase.remover (grida: Integer; bodyId: TBodyProxyId): Boolean;
1000 var
1001 f, c: Integer;
1002 pidx, cidx: Integer;
1003 pc: PGridCell;
1004 begin
1005 result := false; // never stop
1006 // find and remove cell
1007 pidx := -1; // previous cell index
1008 cidx := mGrid[grida]; // current cell index
1009 while (cidx <> -1) do
1010 begin
1011 pc := @mCells[cidx];
1012 for f := 0 to GridCellBucketSize-1 do
1013 begin
1014 if (pc.bodies[f] = bodyId) then
1015 begin
1016 // i found her!
1017 if (f = 0) and (pc.bodies[1] = -1) then
1018 begin
1019 // this cell contains no elements, remove it
1020 if (pidx = -1) then mGrid[grida] := pc.next else mCells[pidx].next := pc.next;
1021 freeCell(cidx);
1022 exit;
1023 end;
1024 // remove element from bucket
1025 for c := f to GridCellBucketSize-2 do
1026 begin
1027 pc.bodies[c] := pc.bodies[c+1];
1028 if (pc.bodies[c] = -1) then break;
1029 end;
1030 pc.bodies[GridCellBucketSize-1] := -1; // "has free room" flag
1031 exit;
1032 end;
1033 end;
1034 pidx := cidx;
1035 cidx := pc.next;
1036 end;
1037 end;
1039 procedure TBodyGridBase.removeInternal (body: TBodyProxyId);
1040 var
1041 px: PBodyProxyRec;
1042 begin
1043 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1044 px := @mProxies[body];
1045 forGridRect(px.mX, px.mY, px.mWidth, px.mHeight, remover, body);
1046 end;
1049 // ////////////////////////////////////////////////////////////////////////// //
1050 function TBodyGridBase.insertBody (aObj: ITP; aX, aY, aWidth, aHeight: Integer; aTag: Integer=-1): TBodyProxyId;
1051 begin
1052 aTag := aTag and TagFullMask;
1053 result := allocProxy(aX, aY, aWidth, aHeight, aObj, aTag);
1054 insertInternal(result);
1055 end;
1058 procedure TBodyGridBase.removeBody (body: TBodyProxyId);
1059 begin
1060 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1061 removeInternal(body);
1062 freeProxy(body);
1063 end;
1066 // ////////////////////////////////////////////////////////////////////////// //
1067 procedure TBodyGridBase.moveResizeBody (body: TBodyProxyId; nx, ny, nw, nh: Integer);
1068 var
1069 px: PBodyProxyRec;
1070 x0, y0, w, h: Integer;
1071 begin
1072 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1073 px := @mProxies[body];
1074 x0 := px.mX;
1075 y0 := px.mY;
1076 w := px.mWidth;
1077 h := px.mHeight;
1078 {$IF DEFINED(D2F_DEBUG_MOVER)}
1079 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);
1080 {$ENDIF}
1081 if (nx = x0) and (ny = y0) and (nw = w) and (nh = h) then exit;
1082 // map -> grid
1083 Dec(x0, mMinX);
1084 Dec(y0, mMinY);
1085 Dec(nx, mMinX);
1086 Dec(ny, mMinY);
1087 // did any corner crossed tile boundary?
1088 if (x0 div mTileSize <> nx div mTileSize) or
1089 (y0 div mTileSize <> ny div mTileSize) or
1090 ((x0+w) div mTileSize <> (nx+nw) div mTileSize) or
1091 ((y0+h) div mTileSize <> (ny+nh) div mTileSize) then
1092 begin
1093 removeInternal(body);
1094 px.mX := nx+mMinX;
1095 px.mY := ny+mMinY;
1096 px.mWidth := nw;
1097 px.mHeight := nh;
1098 insertInternal(body);
1099 end
1100 else
1101 begin
1102 px.mX := nx+mMinX;
1103 px.mY := ny+mMinY;
1104 px.mWidth := nw;
1105 px.mHeight := nh;
1106 end;
1107 end;
1109 //TODO: optimize for horizontal/vertical moves
1110 procedure TBodyGridBase.moveBody (body: TBodyProxyId; nx, ny: Integer);
1111 var
1112 px: PBodyProxyRec;
1113 x0, y0: Integer;
1114 ogx0, ogx1, ogy0, ogy1: Integer; // old grid rect
1115 ngx0, ngx1, ngy0, ngy1: Integer; // new grid rect
1116 gx, gy: Integer;
1117 gw, gh: Integer;
1118 pw, ph: Integer;
1119 begin
1120 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1121 // check if tile coords was changed
1122 px := @mProxies[body];
1123 x0 := px.mX;
1124 y0 := px.mY;
1125 if (nx = x0) and (ny = y0) then exit;
1126 // map -> grid
1127 Dec(x0, mMinX);
1128 Dec(y0, mMinY);
1129 Dec(nx, mMinX);
1130 Dec(ny, mMinY);
1131 // check for heavy work
1132 pw := px.mWidth;
1133 ph := px.mHeight;
1134 ogx0 := x0 div mTileSize;
1135 ogy0 := y0 div mTileSize;
1136 ngx0 := nx div mTileSize;
1137 ngy0 := ny div mTileSize;
1138 ogx1 := (x0+pw-1) div mTileSize;
1139 ogy1 := (y0+ph-1) div mTileSize;
1140 ngx1 := (nx+pw-1) div mTileSize;
1141 ngy1 := (ny+ph-1) div mTileSize;
1142 {$IF DEFINED(D2F_DEBUG_MOVER)}
1143 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);
1144 {$ENDIF}
1145 if (ogx0 <> ngx0) or (ogy0 <> ngy0) or (ogx1 <> ngx1) or (ogy1 <> ngy1) then
1146 begin
1147 // crossed tile boundary, do heavy work
1148 gw := mWidth;
1149 gh := mHeight;
1150 // cycle with old rect, remove body where it is necessary
1151 // optimized for horizontal moves
1152 {$IF DEFINED(D2F_DEBUG_MOVER)}
1153 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);
1154 {$ENDIF}
1155 // remove stale marks
1156 if not ((ogy0 >= gh) or (ogy1 < 0)) and
1157 not ((ogx0 >= gw) or (ogx1 < 0)) then
1158 begin
1159 if (ogx0 < 0) then ogx0 := 0;
1160 if (ogy0 < 0) then ogy0 := 0;
1161 if (ogx1 > gw-1) then ogx1 := gw-1;
1162 if (ogy1 > gh-1) then ogy1 := gh-1;
1163 {$IF DEFINED(D2F_DEBUG_MOVER)}
1164 e_WriteLog(Format(' norm og:(%d,%d)-(%d,%d)', [ogx0, ogy0, ogx1, ogy1]), MSG_NOTIFY);
1165 {$ENDIF}
1166 for gx := ogx0 to ogx1 do
1167 begin
1168 if (gx < ngx0) or (gx > ngx1) then
1169 begin
1170 // this column is completely outside of new rect
1171 for gy := ogy0 to ogy1 do
1172 begin
1173 {$IF DEFINED(D2F_DEBUG_MOVER)}
1174 e_WriteLog(Format(' remove0:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1175 {$ENDIF}
1176 remover(gy*gw+gx, body);
1177 end;
1178 end
1179 else
1180 begin
1181 // heavy checks
1182 for gy := ogy0 to ogy1 do
1183 begin
1184 if (gy < ngy0) or (gy > ngy1) then
1185 begin
1186 {$IF DEFINED(D2F_DEBUG_MOVER)}
1187 e_WriteLog(Format(' remove1:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1188 {$ENDIF}
1189 remover(gy*gw+gx, body);
1190 end;
1191 end;
1192 end;
1193 end;
1194 end;
1195 // cycle with new rect, add body where it is necessary
1196 if not ((ngy0 >= gh) or (ngy1 < 0)) and
1197 not ((ngx0 >= gw) or (ngx1 < 0)) then
1198 begin
1199 if (ngx0 < 0) then ngx0 := 0;
1200 if (ngy0 < 0) then ngy0 := 0;
1201 if (ngx1 > gw-1) then ngx1 := gw-1;
1202 if (ngy1 > gh-1) then ngy1 := gh-1;
1203 {$IF DEFINED(D2F_DEBUG_MOVER)}
1204 e_WriteLog(Format(' norm ng:(%d,%d)-(%d,%d)', [ngx0, ngy0, ngx1, ngy1]), MSG_NOTIFY);
1205 {$ENDIF}
1206 for gx := ngx0 to ngx1 do
1207 begin
1208 if (gx < ogx0) or (gx > ogx1) then
1209 begin
1210 // this column is completely outside of old rect
1211 for gy := ngy0 to ngy1 do
1212 begin
1213 {$IF DEFINED(D2F_DEBUG_MOVER)}
1214 e_WriteLog(Format(' insert0:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1215 {$ENDIF}
1216 inserter(gy*gw+gx, body);
1217 end;
1218 end
1219 else
1220 begin
1221 // heavy checks
1222 for gy := ngy0 to ngy1 do
1223 begin
1224 if (gy < ogy0) or (gy > ogy1) then
1225 begin
1226 {$IF DEFINED(D2F_DEBUG_MOVER)}
1227 e_WriteLog(Format(' insert1:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1228 {$ENDIF}
1229 inserter(gy*gw+gx, body);
1230 end;
1231 end;
1232 end;
1233 end;
1234 end;
1235 // done
1236 end
1237 else
1238 begin
1239 {$IF DEFINED(D2F_DEBUG_MOVER)}
1240 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);
1241 {$ENDIF}
1242 end;
1243 // update coordinates
1244 px.mX := nx+mMinX;
1245 px.mY := ny+mMinY;
1246 end;
1248 procedure TBodyGridBase.resizeBody (body: TBodyProxyId; nw, nh: Integer);
1249 var
1250 px: PBodyProxyRec;
1251 x0, y0, w, h: Integer;
1252 begin
1253 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1254 // check if tile coords was changed
1255 px := @mProxies[body];
1256 x0 := px.mX-mMinX;
1257 y0 := px.mY-mMinY;
1258 w := px.mWidth;
1259 h := px.mHeight;
1260 {$IF DEFINED(D2F_DEBUG_MOVER)}
1261 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);
1262 {$ENDIF}
1263 if ((x0+w) div mTileSize <> (x0+nw) div mTileSize) or
1264 ((y0+h) div mTileSize <> (y0+nh) div mTileSize) then
1265 begin
1266 // crossed tile boundary, do heavy work
1267 removeInternal(body);
1268 px.mWidth := nw;
1269 px.mHeight := nh;
1270 insertInternal(body);
1271 end
1272 else
1273 begin
1274 // nothing to do with the grid, just fix size
1275 px.mWidth := nw;
1276 px.mHeight := nh;
1277 end;
1278 end;
1281 // ////////////////////////////////////////////////////////////////////////// //
1282 function TBodyGridBase.atCellInPoint (x, y: Integer): TAtPointEnumerator;
1283 var
1284 cidx: Integer = -1;
1285 begin
1286 Dec(x, mMinX);
1287 Dec(y, mMinY);
1288 if (x >= 0) and (y >= 0) and (x < mWidth*mTileSize) and (y < mHeight*mTileSize) then cidx := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
1289 result := TAtPointEnumerator.Create(mCells, cidx, getProxyById);
1290 end;
1293 // ////////////////////////////////////////////////////////////////////////// //
1294 // no callback: return `true` on the first hit
1295 function TBodyGridBase.forEachAtPoint (x, y: Integer; cb: TGridQueryCB; tagmask: Integer=-1; exittag: PInteger=nil): ITP;
1296 var
1297 f: Integer;
1298 idx, curci: Integer;
1299 cc: PGridCell = nil;
1300 px: PBodyProxyRec;
1301 lq: LongWord;
1302 ptag: Integer;
1303 begin
1304 result := Default(ITP);
1305 if (exittag <> nil) then exittag^ := 0;
1306 tagmask := tagmask and TagFullMask;
1307 if (tagmask = 0) then exit;
1309 {$IF DEFINED(D2F_DEBUG_XXQ)}
1310 if (assigned(cb)) then e_WriteLog(Format('0: grid pointquery: (%d,%d)', [x, y]), MSG_NOTIFY);
1311 {$ENDIF}
1313 // make coords (0,0)-based
1314 Dec(x, mMinX);
1315 Dec(y, mMinY);
1316 if (x < 0) or (y < 0) or (x >= mWidth*mTileSize) or (y >= mHeight*mTileSize) then exit;
1318 curci := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
1320 {$IF DEFINED(D2F_DEBUG_XXQ)}
1321 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);
1322 {$ENDIF}
1324 // restore coords
1325 Inc(x, mMinX);
1326 Inc(y, mMinY);
1328 // increase query counter
1329 Inc(mLastQuery);
1330 if (mLastQuery = 0) then
1331 begin
1332 // just in case of overflow
1333 mLastQuery := 1;
1334 for idx := 0 to High(mProxies) do mProxies[idx].mQueryMark := 0;
1335 end;
1336 lq := mLastQuery;
1338 {$IF DEFINED(D2F_DEBUG_XXQ)}
1339 if (assigned(cb)) then e_WriteLog(Format('2: grid pointquery: (%d,%d); lq=%u', [x, y, lq]), MSG_NOTIFY);
1340 {$ENDIF}
1342 while (curci <> -1) do
1343 begin
1344 {$IF DEFINED(D2F_DEBUG_XXQ)}
1345 if (assigned(cb)) then e_WriteLog(Format(' cell #%d', [curci]), MSG_NOTIFY);
1346 {$ENDIF}
1347 cc := @mCells[curci];
1348 for f := 0 to GridCellBucketSize-1 do
1349 begin
1350 if (cc.bodies[f] = -1) then break;
1351 px := @mProxies[cc.bodies[f]];
1352 {$IF DEFINED(D2F_DEBUG_XXQ)}
1353 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);
1354 {$ENDIF}
1355 // shit. has to do it this way, so i can change tag in callback
1356 if (px.mQueryMark <> lq) then
1357 begin
1358 px.mQueryMark := lq;
1359 ptag := px.mTag;
1360 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and
1361 (x >= px.mX) and (y >= px.mY) and (x < px.mX+px.mWidth) and (y < px.mY+px.mHeight) then
1362 begin
1363 if assigned(cb) then
1364 begin
1365 if cb(px.mObj, ptag) then
1366 begin
1367 result := px.mObj;
1368 if (exittag <> nil) then exittag^ := ptag;
1369 exit;
1370 end;
1371 end
1372 else
1373 begin
1374 result := px.mObj;
1375 if (exittag <> nil) then exittag^ := ptag;
1376 exit;
1377 end;
1378 end;
1379 end;
1380 end;
1381 curci := cc.next;
1382 end;
1383 end;
1386 // ////////////////////////////////////////////////////////////////////////// //
1387 // no callback: return `true` on the first hit
1388 function TBodyGridBase.forEachInAABB (x, y, w, h: Integer; cb: TGridQueryCB; tagmask: Integer=-1; allowDisabled: Boolean=false): ITP;
1389 const
1390 tsize = mTileSize;
1391 var
1392 idx: Integer;
1393 gx, gy: Integer;
1394 curci: Integer;
1395 f: Integer;
1396 cc: PGridCell = nil;
1397 px: PBodyProxyRec;
1398 lq: LongWord;
1399 gw: Integer;
1400 x0, y0: Integer;
1401 ptag: Integer;
1402 begin
1403 result := Default(ITP);
1404 if (w < 1) or (h < 1) then exit;
1405 tagmask := tagmask and TagFullMask;
1406 if (tagmask = 0) then exit;
1408 x0 := x;
1409 y0 := y;
1411 // fix coords
1412 Dec(x, mMinX);
1413 Dec(y, mMinY);
1415 gw := mWidth;
1416 //tsize := mTileSize;
1418 if (x+w <= 0) or (y+h <= 0) then exit;
1419 if (x >= gw*tsize) or (y >= mHeight*tsize) then exit;
1421 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1422 mInQuery := true;
1424 // increase query counter
1425 Inc(mLastQuery);
1426 if (mLastQuery = 0) then
1427 begin
1428 // just in case of overflow
1429 mLastQuery := 1;
1430 for idx := 0 to High(mProxies) do mProxies[idx].mQueryMark := 0;
1431 end;
1432 //e_WriteLog(Format('grid: query #%d: (%d,%d)-(%dx%d)', [mLastQuery, minx, miny, maxx, maxy]), MSG_NOTIFY);
1433 lq := mLastQuery;
1435 // go on
1436 for gy := y div tsize to (y+h-1) div tsize do
1437 begin
1438 if (gy < 0) then continue;
1439 if (gy >= mHeight) then break;
1440 for gx := x div tsize to (x+w-1) div tsize do
1441 begin
1442 if (gx < 0) then continue;
1443 if (gx >= gw) then break;
1444 // process cells
1445 curci := mGrid[gy*gw+gx];
1446 while (curci <> -1) do
1447 begin
1448 cc := @mCells[curci];
1449 for f := 0 to GridCellBucketSize-1 do
1450 begin
1451 if (cc.bodies[f] = -1) then break;
1452 px := @mProxies[cc.bodies[f]];
1453 // shit. has to do it this way, so i can change tag in callback
1454 if (px.mQueryMark = lq) then continue;
1455 px.mQueryMark := lq;
1456 ptag := px.mTag;
1457 if (not allowDisabled) and ((ptag and TagDisabled) <> 0) then continue;
1458 if ((ptag and tagmask) = 0) then continue;
1459 if (x0 >= px.mX+px.mWidth) or (y0 >= px.mY+px.mHeight) then continue;
1460 if (x0+w <= px.mX) or (y0+h <= px.mY) then continue;
1461 if assigned(cb) then
1462 begin
1463 if cb(px.mObj, ptag) then begin result := px.mObj; mInQuery := false; exit; end;
1464 end
1465 else
1466 begin
1467 result := px.mObj;
1468 mInQuery := false;
1469 exit;
1470 end;
1471 end;
1472 curci := cc.next;
1473 end;
1474 end;
1475 end;
1477 mInQuery := false;
1478 end;
1481 // ////////////////////////////////////////////////////////////////////////// //
1482 // no callback: return `true` on the nearest hit
1483 function TBodyGridBase.traceRay (const x0, y0, x1, y1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
1484 var
1485 ex, ey: Integer;
1486 begin
1487 result := traceRay(ex, ey, x0, y0, x1, y1, cb, tagmask);
1488 end;
1491 // no callback: return `true` on the nearest hit
1492 // you are not supposed to understand this
1493 function TBodyGridBase.traceRay (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
1494 const
1495 tsize = mTileSize;
1496 var
1497 wx0, wy0, wx1, wy1: Integer; // window coordinates
1498 stx, sty: Integer; // "steps" for x and y axes
1499 dsx, dsy: Integer; // "lengthes" for x and y axes
1500 dx2, dy2: Integer; // "double lengthes" for x and y axes
1501 xd, yd: Integer; // current coord
1502 e: Integer; // "error" (as in bresenham algo)
1503 rem: Integer;
1504 term: Integer;
1505 xptr, yptr: PInteger;
1506 xfixed: Boolean;
1507 temp: Integer;
1508 prevx, prevy: Integer;
1509 lastDistSq: Integer;
1510 ccidx, curci: Integer;
1511 hasUntried: Boolean;
1512 lastGA: Integer = -1;
1513 ga, x, y: Integer;
1514 lastObj: ITP;
1515 wasHit: Boolean = false;
1516 gw, gh, minx, miny, maxx, maxy: Integer;
1517 cc: PGridCell;
1518 px: PBodyProxyRec;
1519 lq: LongWord;
1520 f, ptag, distSq: Integer;
1521 x0, y0, x1, y1: Integer;
1522 //swapped: Boolean = false; // true: xd is yd, and vice versa
1523 // horizontal walker
1524 {$IFDEF GRID_USE_ORTHO_ACCEL}
1525 wklen, wkstep: Integer;
1526 //wksign: Integer;
1527 hopt: Boolean;
1528 {$ENDIF}
1529 // skipper
1530 xdist, ydist: Integer;
1531 begin
1532 result := Default(ITP);
1533 lastObj := Default(ITP);
1534 tagmask := tagmask and TagFullMask;
1535 ex := ax1; // why not?
1536 ey := ay1; // why not?
1537 if (tagmask = 0) then exit;
1539 if (ax0 = ax1) and (ay0 = ay1) then
1540 begin
1541 result := forEachAtPoint(ax0, ay0, nil, tagmask, @ptag);
1542 if (result <> nil) then
1543 begin
1544 if assigned(cb) and not cb(result, ptag, ax0, ay0, ax0, ay0) then result := Default(ITP);
1545 end;
1546 exit;
1547 end;
1549 lastDistSq := distanceSq(ax0, ay0, ax1, ay1)+1;
1551 gw := mWidth;
1552 gh := mHeight;
1553 minx := mMinX;
1554 miny := mMinY;
1555 maxx := gw*tsize-1;
1556 maxy := gh*tsize-1;
1558 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1559 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);
1560 {$ENDIF}
1562 x0 := ax0;
1563 y0 := ay0;
1564 x1 := ax1;
1565 y1 := ay1;
1567 // offset query coords to (0,0)-based
1568 Dec(x0, minx);
1569 Dec(y0, miny);
1570 Dec(x1, minx);
1571 Dec(y1, miny);
1573 // clip rectange
1574 wx0 := 0;
1575 wy0 := 0;
1576 wx1 := maxx;
1577 wy1 := maxy;
1579 // horizontal setup
1580 if (x0 < x1) then
1581 begin
1582 // from left to right
1583 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
1584 stx := 1; // going right
1585 end
1586 else
1587 begin
1588 // from right to left
1589 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
1590 stx := -1; // going left
1591 x0 := -x0;
1592 x1 := -x1;
1593 wx0 := -wx0;
1594 wx1 := -wx1;
1595 swapInt(wx0, wx1);
1596 end;
1598 // vertical setup
1599 if (y0 < y1) then
1600 begin
1601 // from top to bottom
1602 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
1603 sty := 1; // going down
1604 end
1605 else
1606 begin
1607 // from bottom to top
1608 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
1609 sty := -1; // going up
1610 y0 := -y0;
1611 y1 := -y1;
1612 wy0 := -wy0;
1613 wy1 := -wy1;
1614 swapInt(wy0, wy1);
1615 end;
1617 dsx := x1-x0;
1618 dsy := y1-y0;
1620 if (dsx < dsy) then
1621 begin
1622 //swapped := true;
1623 xptr := @yd;
1624 yptr := @xd;
1625 swapInt(x0, y0);
1626 swapInt(x1, y1);
1627 swapInt(dsx, dsy);
1628 swapInt(wx0, wy0);
1629 swapInt(wx1, wy1);
1630 swapInt(stx, sty);
1631 end
1632 else
1633 begin
1634 xptr := @xd;
1635 yptr := @yd;
1636 end;
1638 dx2 := 2*dsx;
1639 dy2 := 2*dsy;
1640 xd := x0;
1641 yd := y0;
1642 e := 2*dsy-dsx;
1643 term := x1;
1645 xfixed := false;
1646 if (y0 < wy0) then
1647 begin
1648 // clip at top
1649 temp := dx2*(wy0-y0)-dsx;
1650 xd += temp div dy2;
1651 rem := temp mod dy2;
1652 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
1653 if (xd+1 >= wx0) then
1654 begin
1655 yd := wy0;
1656 e -= rem+dsx;
1657 if (rem > 0) then begin Inc(xd); e += dy2; end;
1658 xfixed := true;
1659 end;
1660 end;
1662 if (not xfixed) and (x0 < wx0) then
1663 begin
1664 // clip at left
1665 temp := dy2*(wx0-x0);
1666 yd += temp div dx2;
1667 rem := temp mod dx2;
1668 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
1669 xd := wx0;
1670 e += rem;
1671 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
1672 end;
1674 if (y1 > wy1) then
1675 begin
1676 // clip at bottom
1677 temp := dx2*(wy1-y0)+dsx;
1678 term := x0+temp div dy2;
1679 rem := temp mod dy2;
1680 if (rem = 0) then Dec(term);
1681 end;
1683 if (term > wx1) then term := wx1; // clip at right
1685 Inc(term); // draw last point
1686 //if (term = xd) then exit; // this is the only point, get out of here
1688 if (sty = -1) then yd := -yd;
1689 if (stx = -1) then begin xd := -xd; term := -term; end;
1690 dx2 -= dy2;
1692 // first move, to skip starting point
1693 // DON'T DO THIS! loop will take care of that
1694 if (xd = term) then
1695 begin
1696 //FIXME!
1697 result := forEachAtPoint(ax0, ay0, nil, tagmask, @ptag);
1698 if (result <> nil) then
1699 begin
1700 if assigned(cb) then
1701 begin
1702 if cb(result, ptag, ax0, ay0, ax0, ay0) then
1703 begin
1704 ex := ax0;
1705 ey := ay0;
1706 end
1707 else
1708 begin
1709 result := nil;
1710 end;
1711 end
1712 else
1713 begin
1714 ex := ax0;
1715 ey := ay0;
1716 end;
1717 end;
1718 exit;
1719 end;
1721 prevx := xptr^+minx;
1722 prevy := yptr^+miny;
1723 (*
1724 // move coords
1725 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
1726 xd += stx;
1727 // done?
1728 if (xd = term) then exit;
1729 *)
1731 {$IF DEFINED(D2F_DEBUG)}
1732 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*tsize) and (yptr^ >= gh*tsize) then raise Exception.Create('raycaster internal error (0)');
1733 {$ENDIF}
1734 // DON'T DO THIS! loop will take care of that
1735 //lastGA := (yptr^ div tsize)*gw+(xptr^ div tsize);
1736 //ccidx := mGrid[lastGA];
1738 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1739 //if assigned(dbgRayTraceTileHitCB) then e_WriteLog('1:TRACING!', MSG_NOTIFY);
1740 {$ENDIF}
1742 //if (dbgShowTraceLog) then e_WriteLog(Format('raycast start: (%d,%d)-(%d,%d); xptr^=%d; yptr^=%d', [ax0, ay0, ax1, ay1, xptr^, yptr^]), MSG_NOTIFY);
1744 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1745 mInQuery := true;
1747 // increase query counter
1748 Inc(mLastQuery);
1749 if (mLastQuery = 0) then
1750 begin
1751 // just in case of overflow
1752 mLastQuery := 1;
1753 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
1754 end;
1755 lq := mLastQuery;
1757 {$IFDEF GRID_USE_ORTHO_ACCEL}
1758 // if this is strict horizontal/vertical trace, use optimized codepath
1759 if (ax0 = ax1) or (ay0 = ay1) then
1760 begin
1761 // horizontal trace: walk the whole tiles, calculating mindist once for each proxy in cell
1762 // stx < 0: going left, otherwise `stx` is > 0, and we're going right
1763 // vertical trace: walk the whole tiles, calculating mindist once for each proxy in cell
1764 // stx < 0: going up, otherwise `stx` is > 0, and we're going down
1765 hopt := (ay0 = ay1); // horizontal?
1766 if (stx < 0) then begin {wksign := -1;} wklen := -(term-xd); end else begin {wksign := 1;} wklen := term-xd; end;
1767 {$IF DEFINED(D2F_DEBUG)}
1768 if dbgShowTraceLog then e_LogWritefln('optimized htrace; wklen=%d', [wklen]);
1769 {$ENDIF}
1770 ga := (yptr^ div tsize)*gw+(xptr^ div tsize);
1771 // one of those will never change
1772 x := xptr^+minx;
1773 y := yptr^+miny;
1774 while (wklen > 0) do
1775 begin
1776 {$IF DEFINED(D2F_DEBUG)}
1777 if dbgShowTraceLog then e_LogWritefln(' htrace; ga=%d; x=%d, y=%d; y=%d; y=%d', [ga, xptr^+minx, yptr^+miny, y, ay0]);
1778 {$ENDIF}
1779 // new tile?
1780 if (ga <> lastGA) then
1781 begin
1782 lastGA := ga;
1783 ccidx := mGrid[lastGA];
1784 // convert coords to map (to avoid ajdusting coords inside the loop)
1785 if hopt then x := xptr^+minx else y := yptr^+miny;
1786 while (ccidx <> -1) do
1787 begin
1788 cc := @mCells[ccidx];
1789 for f := 0 to GridCellBucketSize-1 do
1790 begin
1791 if (cc.bodies[f] = -1) then break;
1792 px := @mProxies[cc.bodies[f]];
1793 ptag := px.mTag;
1794 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) and
1795 // constant coord should be inside
1796 ((hopt and (y >= px.y0) and (y <= px.y1)) or
1797 ((not hopt) and (x >= px.x0) and (x <= px.x1))) then
1798 begin
1799 px.mQueryMark := lq; // mark as processed
1800 // inside the proxy?
1801 if (hopt and (x > px.x0) and (x < px.x1)) or
1802 ((not hopt) and (y > px.y0) and (y < px.y1)) then
1803 begin
1804 // setup prev[xy]
1805 if assigned(cb) then
1806 begin
1807 if cb(px.mObj, ptag, x, y, x, y) then
1808 begin
1809 result := px.mObj;
1810 ex := x;
1811 ey := y;
1812 mInQuery := false;
1813 exit;
1814 end;
1815 end
1816 else
1817 begin
1818 distSq := distanceSq(ax0, ay0, x, y);
1819 {$IF DEFINED(D2F_DEBUG)}
1820 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]);
1821 {$ENDIF}
1822 if (distSq < lastDistSq) then
1823 begin
1824 ex := x;
1825 ey := y;
1826 result := px.mObj;
1827 mInQuery := false;
1828 exit;
1829 end;
1830 end;
1831 continue;
1832 end;
1833 // remember this hitpoint if it is nearer than an old one
1834 // setup prev[xy]
1835 if hopt then
1836 begin
1837 // horizontal trace
1838 prevy := y;
1839 y := yptr^+miny;
1840 if (stx < 0) then
1841 begin
1842 // going left
1843 if (x < px.x1) then continue; // not on the right edge
1844 x := px.x1;
1845 prevx := x+1;
1846 end
1847 else
1848 begin
1849 // going right
1850 if (x > px.x0) then continue; // not on the left edge
1851 x := px.x0;
1852 prevx := x-1;
1853 end;
1854 end
1855 else
1856 begin
1857 // vertical trace
1858 prevx := x;
1859 x := xptr^+minx;
1860 if (stx < 0) then
1861 begin
1862 // going up
1863 if (y < px.y1) then continue; // not on the bottom edge
1864 y := px.y1;
1865 prevy := x+1;
1866 end
1867 else
1868 begin
1869 // going down
1870 if (y > px.y0) then continue; // not on the top edge
1871 y := px.y0;
1872 prevy := y-1;
1873 end;
1874 end;
1875 if assigned(cb) then
1876 begin
1877 if cb(px.mObj, ptag, x, y, prevx, prevy) then
1878 begin
1879 result := px.mObj;
1880 ex := prevx;
1881 ey := prevy;
1882 mInQuery := false;
1883 exit;
1884 end;
1885 end
1886 else
1887 begin
1888 distSq := distanceSq(ax0, ay0, prevx, prevy);
1889 {$IF DEFINED(D2F_DEBUG)}
1890 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]);
1891 {$ENDIF}
1892 if (distSq < lastDistSq) then
1893 begin
1894 wasHit := true;
1895 lastDistSq := distSq;
1896 ex := prevx;
1897 ey := prevy;
1898 lastObj := px.mObj;
1899 end;
1900 end;
1901 end;
1902 end;
1903 // next cell
1904 ccidx := cc.next;
1905 end;
1906 if wasHit and not assigned(cb) then begin result := lastObj; mInQuery := false; exit; end;
1907 if assigned(cb) and cb(nil, 0, x, y, x, y) then begin result := lastObj; mInQuery := false; exit; end;
1908 end;
1909 // skip to next tile
1910 if hopt then
1911 begin
1912 if (stx > 0) then
1913 begin
1914 // to the right
1915 wkstep := ((xptr^ or (mTileSize-1))+1)-xptr^;
1916 {$IF DEFINED(D2F_DEBUG)}
1917 if dbgShowTraceLog then e_LogWritefln(' right step: wklen=%d; wkstep=%d', [wklen, wkstep]);
1918 {$ENDIF}
1919 if (wkstep >= wklen) then break;
1920 Inc(xptr^, wkstep);
1921 Inc(ga);
1922 end
1923 else
1924 begin
1925 // to the left
1926 wkstep := xptr^-((xptr^ and (not (mTileSize-1)))-1);
1927 {$IF DEFINED(D2F_DEBUG)}
1928 if dbgShowTraceLog then e_LogWritefln(' left step: wklen=%d; wkstep=%d', [wklen, wkstep]);
1929 {$ENDIF}
1930 if (wkstep >= wklen) then break;
1931 Dec(xptr^, wkstep);
1932 Dec(ga);
1933 end;
1934 end
1935 else
1936 begin
1937 if (stx > 0) then
1938 begin
1939 // to the down
1940 wkstep := ((yptr^ or (mTileSize-1))+1)-yptr^;
1941 {$IF DEFINED(D2F_DEBUG)}
1942 if dbgShowTraceLog then e_LogWritefln(' down step: wklen=%d; wkstep=%d', [wklen, wkstep]);
1943 {$ENDIF}
1944 if (wkstep >= wklen) then break;
1945 Inc(yptr^, wkstep);
1946 Inc(ga, mWidth);
1947 end
1948 else
1949 begin
1950 // to the up
1951 wkstep := yptr^-((yptr^ and (not (mTileSize-1)))-1);
1952 {$IF DEFINED(D2F_DEBUG)}
1953 if dbgShowTraceLog then e_LogWritefln(' up step: wklen=%d; wkstep=%d', [wklen, wkstep]);
1954 {$ENDIF}
1955 if (wkstep >= wklen) then break;
1956 Dec(yptr^, wkstep);
1957 Dec(ga, mWidth);
1958 end;
1959 end;
1960 Dec(wklen, wkstep);
1961 end;
1962 // we can travel less than one cell
1963 if wasHit and not assigned(cb) then result := lastObj else begin ex := ax1; ey := ay1; end;
1964 mInQuery := false;
1965 exit;
1966 end;
1967 {$ENDIF}
1969 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1970 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div tsize*tsize)+minx, (yptr^ div tsize*tsize)+miny);
1971 {$ENDIF}
1973 //e_LogWritefln('*********************', []);
1974 ccidx := -1;
1975 // can omit checks
1976 while (xd <> term) do
1977 begin
1978 // check cell(s)
1979 {$IF DEFINED(D2F_DEBUG)}
1980 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*tsize) and (yptr^ >= gh*tsize) then raise Exception.Create('raycaster internal error (0)');
1981 {$ENDIF}
1982 // new tile?
1983 ga := (yptr^ div tsize)*gw+(xptr^ div tsize);
1984 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
1985 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);
1986 {$ENDIF}
1987 if (ga <> lastGA) then
1988 begin
1989 // yes
1990 {$IF DEFINED(D2F_DEBUG)}
1991 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div tsize*tsize)+minx, (yptr^ div tsize*tsize)+miny);
1992 {$ENDIF}
1993 if (ccidx <> -1) then
1994 begin
1995 // signal cell completion
1996 if assigned(cb) then
1997 begin
1998 if cb(nil, 0, xptr^+minx, yptr^+miny, prevx, prevy) then begin result := lastObj; mInQuery := false; exit; end;
1999 end
2000 else if wasHit then
2001 begin
2002 result := lastObj;
2003 mInQuery := false;
2004 exit;
2005 end;
2006 end;
2007 lastGA := ga;
2008 ccidx := mGrid[lastGA];
2009 end;
2010 // has something to process in this tile?
2011 if (ccidx <> -1) then
2012 begin
2013 // process cell
2014 curci := ccidx;
2015 hasUntried := false; // this will be set to `true` if we have some proxies we still want to process at the next step
2016 // convert coords to map (to avoid ajdusting coords inside the loop)
2017 x := xptr^+minx;
2018 y := yptr^+miny;
2019 // process cell list
2020 while (curci <> -1) do
2021 begin
2022 cc := @mCells[curci];
2023 for f := 0 to GridCellBucketSize-1 do
2024 begin
2025 if (cc.bodies[f] = -1) then break;
2026 px := @mProxies[cc.bodies[f]];
2027 ptag := px.mTag;
2028 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2029 begin
2030 // can we process this proxy?
2031 if (x >= px.mX) and (y >= px.mY) and (x < px.mX+px.mWidth) and (y < px.mY+px.mHeight) then
2032 begin
2033 px.mQueryMark := lq; // mark as processed
2034 if assigned(cb) then
2035 begin
2036 if cb(px.mObj, ptag, x, y, prevx, prevy) then
2037 begin
2038 result := px.mObj;
2039 ex := prevx;
2040 ey := prevy;
2041 mInQuery := false;
2042 exit;
2043 end;
2044 end
2045 else
2046 begin
2047 // remember this hitpoint if it is nearer than an old one
2048 distSq := distanceSq(ax0, ay0, prevx, prevy);
2049 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2050 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);
2051 {$ENDIF}
2052 if (distSq < lastDistSq) then
2053 begin
2054 wasHit := true;
2055 lastDistSq := distSq;
2056 ex := prevx;
2057 ey := prevy;
2058 lastObj := px.mObj;
2059 end;
2060 end;
2061 end
2062 else
2063 begin
2064 // this is possibly interesting proxy, set "has more to check" flag
2065 hasUntried := true;
2066 end;
2067 end;
2068 end;
2069 // next cell
2070 curci := cc.next;
2071 end;
2072 // still has something interesting in this cell?
2073 if not hasUntried then
2074 begin
2075 // nope, don't process this cell anymore; signal cell completion
2076 ccidx := -1;
2077 if assigned(cb) then
2078 begin
2079 if cb(nil, 0, x, y, prevx, prevy) then begin result := lastObj; mInQuery := false; exit; end;
2080 end
2081 else if wasHit then
2082 begin
2083 result := lastObj;
2084 mInQuery := false;
2085 exit;
2086 end;
2087 end;
2088 end;
2089 if (ccidx = -1) then
2090 begin
2091 // move to cell edge, as we have nothing to trace here anymore
2092 if (stx < 0) then xdist := xd and (not (mTileSize-1)) else xdist := xd or (mTileSize-1);
2093 if (sty < 0) then ydist := yd and (not (mTileSize-1)) else ydist := yd or (mTileSize-1);
2094 //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]);
2095 while (xd <> xdist) and (yd <> ydist) do
2096 begin
2097 // step
2098 xd += stx;
2099 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2100 //e_LogWritefln(' xd=%d; yd=%d', [xd, yd]);
2101 if (xd = term) then break;
2102 end;
2103 //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]);
2104 if (xd = term) then break;
2105 end;
2106 //putPixel(xptr^, yptr^);
2107 // move coords
2108 prevx := xptr^+minx;
2109 prevy := yptr^+miny;
2110 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2111 xd += stx;
2112 end;
2113 // we can travel less than one cell
2114 if wasHit and not assigned(cb) then
2115 begin
2116 result := lastObj;
2117 end
2118 else
2119 begin
2120 ex := ax1; // why not?
2121 ey := ay1; // why not?
2122 end;
2124 mInQuery := false;
2125 end;
2128 // ////////////////////////////////////////////////////////////////////////// //
2129 //FIXME! optimize this with real tile walking
2130 function TBodyGridBase.forEachAlongLine (ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1; log: Boolean=false): ITP;
2131 const
2132 tsize = mTileSize;
2133 var
2134 wx0, wy0, wx1, wy1: Integer; // window coordinates
2135 stx, sty: Integer; // "steps" for x and y axes
2136 dsx, dsy: Integer; // "lengthes" for x and y axes
2137 dx2, dy2: Integer; // "double lengthes" for x and y axes
2138 xd, yd: Integer; // current coord
2139 e: Integer; // "error" (as in bresenham algo)
2140 rem: Integer;
2141 term: Integer;
2142 xptr, yptr: PInteger;
2143 xfixed: Boolean;
2144 temp: Integer;
2145 ccidx, curci: Integer;
2146 lastGA: Integer = -1;
2147 ga: Integer;
2148 gw, gh, minx, miny, maxx, maxy: Integer;
2149 cc: PGridCell;
2150 px: PBodyProxyRec;
2151 lq: LongWord;
2152 f, ptag: Integer;
2153 x0, y0, x1, y1: Integer;
2154 //swapped: Boolean = false; // true: xd is yd, and vice versa
2155 // horizontal walker
2156 {$IFDEF GRID_USE_ORTHO_ACCEL}
2157 wklen, wkstep: Integer;
2158 //wksign: Integer;
2159 hopt: Boolean;
2160 {$ENDIF}
2161 // skipper
2162 xdist, ydist: Integer;
2163 begin
2164 log := false;
2165 result := Default(ITP);
2166 tagmask := tagmask and TagFullMask;
2167 if (tagmask = 0) or not assigned(cb) then exit;
2169 if (ax0 = ax1) and (ay0 = ay1) then
2170 begin
2171 result := forEachAtPoint(ax0, ay0, cb, tagmask, @ptag);
2172 exit;
2173 end;
2175 gw := mWidth;
2176 gh := mHeight;
2177 minx := mMinX;
2178 miny := mMinY;
2179 maxx := gw*tsize-1;
2180 maxy := gh*tsize-1;
2182 x0 := ax0;
2183 y0 := ay0;
2184 x1 := ax1;
2185 y1 := ay1;
2187 // offset query coords to (0,0)-based
2188 Dec(x0, minx);
2189 Dec(y0, miny);
2190 Dec(x1, minx);
2191 Dec(y1, miny);
2193 // clip rectange
2194 wx0 := 0;
2195 wy0 := 0;
2196 wx1 := maxx;
2197 wy1 := maxy;
2199 // horizontal setup
2200 if (x0 < x1) then
2201 begin
2202 // from left to right
2203 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
2204 stx := 1; // going right
2205 end
2206 else
2207 begin
2208 // from right to left
2209 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
2210 stx := -1; // going left
2211 x0 := -x0;
2212 x1 := -x1;
2213 wx0 := -wx0;
2214 wx1 := -wx1;
2215 swapInt(wx0, wx1);
2216 end;
2218 // vertical setup
2219 if (y0 < y1) then
2220 begin
2221 // from top to bottom
2222 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
2223 sty := 1; // going down
2224 end
2225 else
2226 begin
2227 // from bottom to top
2228 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
2229 sty := -1; // going up
2230 y0 := -y0;
2231 y1 := -y1;
2232 wy0 := -wy0;
2233 wy1 := -wy1;
2234 swapInt(wy0, wy1);
2235 end;
2237 dsx := x1-x0;
2238 dsy := y1-y0;
2240 if (dsx < dsy) then
2241 begin
2242 //swapped := true;
2243 xptr := @yd;
2244 yptr := @xd;
2245 swapInt(x0, y0);
2246 swapInt(x1, y1);
2247 swapInt(dsx, dsy);
2248 swapInt(wx0, wy0);
2249 swapInt(wx1, wy1);
2250 swapInt(stx, sty);
2251 end
2252 else
2253 begin
2254 xptr := @xd;
2255 yptr := @yd;
2256 end;
2258 dx2 := 2*dsx;
2259 dy2 := 2*dsy;
2260 xd := x0;
2261 yd := y0;
2262 e := 2*dsy-dsx;
2263 term := x1;
2265 xfixed := false;
2266 if (y0 < wy0) then
2267 begin
2268 // clip at top
2269 temp := dx2*(wy0-y0)-dsx;
2270 xd += temp div dy2;
2271 rem := temp mod dy2;
2272 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
2273 if (xd+1 >= wx0) then
2274 begin
2275 yd := wy0;
2276 e -= rem+dsx;
2277 if (rem > 0) then begin Inc(xd); e += dy2; end;
2278 xfixed := true;
2279 end;
2280 end;
2282 if (not xfixed) and (x0 < wx0) then
2283 begin
2284 // clip at left
2285 temp := dy2*(wx0-x0);
2286 yd += temp div dx2;
2287 rem := temp mod dx2;
2288 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
2289 xd := wx0;
2290 e += rem;
2291 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
2292 end;
2294 if (y1 > wy1) then
2295 begin
2296 // clip at bottom
2297 temp := dx2*(wy1-y0)+dsx;
2298 term := x0+temp div dy2;
2299 rem := temp mod dy2;
2300 if (rem = 0) then Dec(term);
2301 end;
2303 if (term > wx1) then term := wx1; // clip at right
2305 Inc(term); // draw last point
2306 //if (term = xd) then exit; // this is the only point, get out of here
2308 if (sty = -1) then yd := -yd;
2309 if (stx = -1) then begin xd := -xd; term := -term; end;
2310 dx2 -= dy2;
2312 // first move, to skip starting point
2313 // DON'T DO THIS! loop will take care of that
2314 if (xd = term) then
2315 begin
2316 result := forEachAtPoint(ax0, ay0, cb, tagmask, @ptag);
2317 exit;
2318 end;
2320 (*
2321 // move coords
2322 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2323 xd += stx;
2324 // done?
2325 if (xd = term) then exit;
2326 *)
2328 {$IF DEFINED(D2F_DEBUG)}
2329 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*tsize) and (yptr^ >= gh*tsize) then raise Exception.Create('raycaster internal error (0)');
2330 {$ENDIF}
2331 // DON'T DO THIS! loop will take care of that
2332 //lastGA := (yptr^ div tsize)*gw+(xptr^ div tsize);
2333 //ccidx := mGrid[lastGA];
2335 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
2336 mInQuery := true;
2338 // increase query counter
2339 Inc(mLastQuery);
2340 if (mLastQuery = 0) then
2341 begin
2342 // just in case of overflow
2343 mLastQuery := 1;
2344 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
2345 end;
2346 lq := mLastQuery;
2348 {$IFDEF GRID_USE_ORTHO_ACCEL}
2349 // if this is strict horizontal/vertical trace, use optimized codepath
2350 if (ax0 = ax1) or (ay0 = ay1) then
2351 begin
2352 // horizontal trace: walk the whole tiles, calculating mindist once for each proxy in cell
2353 // stx < 0: going left, otherwise `stx` is > 0, and we're going right
2354 // vertical trace: walk the whole tiles, calculating mindist once for each proxy in cell
2355 // stx < 0: going up, otherwise `stx` is > 0, and we're going down
2356 hopt := (ay0 = ay1); // horizontal?
2357 if (stx < 0) then begin {wksign := -1;} wklen := -(term-xd); end else begin {wksign := 1;} wklen := term-xd; end;
2358 {$IF DEFINED(D2F_DEBUG)}
2359 if dbgShowTraceLog then e_LogWritefln('optimized htrace; wklen=%d', [wklen]);
2360 {$ENDIF}
2361 ga := (yptr^ div tsize)*gw+(xptr^ div tsize);
2362 while (wklen > 0) do
2363 begin
2364 {$IF DEFINED(D2F_DEBUG)}
2365 if dbgShowTraceLog then e_LogWritefln(' htrace; ga=%d; x=%d, y=%d; ay0=%d', [ga, xptr^+minx, yptr^+miny, ay0]);
2366 {$ENDIF}
2367 // new tile?
2368 if (ga <> lastGA) then
2369 begin
2370 lastGA := ga;
2371 ccidx := mGrid[lastGA];
2372 // convert coords to map (to avoid ajdusting coords inside the loop)
2373 while (ccidx <> -1) do
2374 begin
2375 cc := @mCells[ccidx];
2376 for f := 0 to GridCellBucketSize-1 do
2377 begin
2378 if (cc.bodies[f] = -1) then break;
2379 px := @mProxies[cc.bodies[f]];
2380 ptag := px.mTag;
2381 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2382 begin
2383 px.mQueryMark := lq; // mark as processed
2384 if assigned(cb) then
2385 begin
2386 if cb(px.mObj, ptag) then begin result := px.mObj; mInQuery := false; exit; end;
2387 end
2388 else
2389 begin
2390 result := px.mObj;
2391 mInQuery := false;
2392 exit;
2393 end;
2394 end;
2395 end;
2396 // next cell
2397 ccidx := cc.next;
2398 end;
2399 end;
2400 // skip to next tile
2401 if hopt then
2402 begin
2403 if (stx > 0) then
2404 begin
2405 // to the right
2406 wkstep := ((xptr^ or (mTileSize-1))+1)-xptr^;
2407 {$IF DEFINED(D2F_DEBUG)}
2408 if dbgShowTraceLog then e_LogWritefln(' right step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2409 {$ENDIF}
2410 if (wkstep >= wklen) then break;
2411 Inc(xptr^, wkstep);
2412 Inc(ga);
2413 end
2414 else
2415 begin
2416 // to the left
2417 wkstep := xptr^-((xptr^ and (not (mTileSize-1)))-1);
2418 {$IF DEFINED(D2F_DEBUG)}
2419 if dbgShowTraceLog then e_LogWritefln(' left step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2420 {$ENDIF}
2421 if (wkstep >= wklen) then break;
2422 Dec(xptr^, wkstep);
2423 Dec(ga);
2424 end;
2425 end
2426 else
2427 begin
2428 if (stx > 0) then
2429 begin
2430 // to the down
2431 wkstep := ((yptr^ or (mTileSize-1))+1)-yptr^;
2432 {$IF DEFINED(D2F_DEBUG)}
2433 if dbgShowTraceLog then e_LogWritefln(' down step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2434 {$ENDIF}
2435 if (wkstep >= wklen) then break;
2436 Inc(yptr^, wkstep);
2437 Inc(ga, mWidth);
2438 end
2439 else
2440 begin
2441 // to the up
2442 wkstep := yptr^-((yptr^ and (not (mTileSize-1)))-1);
2443 {$IF DEFINED(D2F_DEBUG)}
2444 if dbgShowTraceLog then e_LogWritefln(' up step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2445 {$ENDIF}
2446 if (wkstep >= wklen) then break;
2447 Dec(yptr^, wkstep);
2448 Dec(ga, mWidth);
2449 end;
2450 end;
2451 Dec(wklen, wkstep);
2452 end;
2453 mInQuery := false;
2454 exit;
2455 end;
2456 {$ENDIF}
2458 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2459 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div tsize*tsize)+minx, (yptr^ div tsize*tsize)+miny);
2460 {$ENDIF}
2462 ccidx := -1;
2463 // can omit checks
2464 while (xd <> term) do
2465 begin
2466 // check cell(s)
2467 {$IF DEFINED(D2F_DEBUG)}
2468 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*tsize) and (yptr^ >= gh*tsize) then raise Exception.Create('raycaster internal error (0)');
2469 {$ENDIF}
2470 // new tile?
2471 ga := (yptr^ div tsize)*gw+(xptr^ div tsize);
2472 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2473 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);
2474 {$ENDIF}
2475 if (ga <> lastGA) then
2476 begin
2477 // yes
2478 {$IF DEFINED(D2F_DEBUG)}
2479 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div tsize*tsize)+minx, (yptr^ div tsize*tsize)+miny);
2480 {$ENDIF}
2481 lastGA := ga;
2482 ccidx := mGrid[lastGA];
2483 end;
2484 // has something to process in this tile?
2485 if (ccidx <> -1) then
2486 begin
2487 // process cell
2488 curci := ccidx;
2489 // process cell list
2490 while (curci <> -1) do
2491 begin
2492 cc := @mCells[curci];
2493 for f := 0 to GridCellBucketSize-1 do
2494 begin
2495 if (cc.bodies[f] = -1) then break;
2496 px := @mProxies[cc.bodies[f]];
2497 ptag := px.mTag;
2498 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2499 begin
2500 px.mQueryMark := lq; // mark as processed
2501 if assigned(cb) then
2502 begin
2503 if cb(px.mObj, ptag) then begin result := px.mObj; mInQuery := false; exit; end;
2504 end
2505 else
2506 begin
2507 result := px.mObj;
2508 mInQuery := false;
2509 exit;
2510 end;
2511 end;
2512 end;
2513 // next cell
2514 curci := cc.next;
2515 end;
2516 // nothing more interesting in this cell
2517 ccidx := -1;
2518 end;
2519 // move to cell edge, as we have nothing to trace here anymore
2520 if (stx < 0) then xdist := xd and (not (mTileSize-1)) else xdist := xd or (mTileSize-1);
2521 if (sty < 0) then ydist := yd and (not (mTileSize-1)) else ydist := yd or (mTileSize-1);
2522 //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]);
2523 while (xd <> xdist) and (yd <> ydist) do
2524 begin
2525 // step
2526 xd += stx;
2527 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2528 //e_LogWritefln(' xd=%d; yd=%d', [xd, yd]);
2529 if (xd = term) then break;
2530 end;
2531 //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]);
2532 if (xd = term) then break;
2533 //putPixel(xptr^, yptr^);
2534 // move coords
2535 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2536 xd += stx;
2537 end;
2539 mInQuery := false;
2540 end;
2543 // ////////////////////////////////////////////////////////////////////////// //
2544 // trace box with the given velocity; return object hit (if any)
2545 // `cb` is used unconvetionally here: if it returns `false`, tracer will ignore the object
2546 function TBodyGridBase.traceBox (out ex, ey: Integer; const ax0, ay0, aw, ah: Integer; const dx, dy: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
2547 var
2548 gx, gy: Integer;
2549 cidx: Integer;
2550 cc: PGridCell;
2551 px: PBodyProxyRec;
2552 lq: LongWord;
2553 f, ptag: Integer;
2554 minu0: Single = 100000.0;
2555 u0: Single;
2556 hedge: Integer;
2557 cx0, cy0, cx1, cy1: Integer;
2558 begin
2559 result := Default(ITP);
2560 ex := ax0+dx;
2561 ey := ay0+dy;
2562 if (aw < 1) or (ah < 1) then exit;
2564 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
2565 mInQuery := true;
2567 cx0 := nmin(ax0, ax0+dx);
2568 cy0 := nmin(ay0, ay0+dy);
2569 cx1 := nmax(ax0+aw-1, ax0+aw-1+dx);
2570 cy1 := nmax(ay0+ah-1, ay0+ah-1+dy);
2572 cx0 -= mMinX; cy0 -= mMinY;
2573 cx1 -= mMinX; cy1 -= mMinY;
2575 if (cx1 < 0) or (cy1 < 0) or (cx0 >= mWidth*mTileSize) or (cy0 >= mHeight*mTileSize) then exit;
2577 if (cx0 < 0) then cx0 := 0;
2578 if (cy0 < 0) then cy0 := 0;
2579 if (cx1 >= mWidth*mTileSize) then cx1 := mWidth*mTileSize-1;
2580 if (cy1 >= mHeight*mTileSize) then cy1 := mHeight*mTileSize-1;
2581 // just in case
2582 if (cx0 > cx1) or (cy0 > cy1) then exit;
2584 // increase query counter
2585 Inc(mLastQuery);
2586 if (mLastQuery = 0) then
2587 begin
2588 // just in case of overflow
2589 mLastQuery := 1;
2590 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
2591 end;
2592 lq := mLastQuery;
2594 gy := cy0;
2595 while (gy <= cy1) do
2596 begin
2597 gx := cx0;
2598 while (gx <= cx1) do
2599 begin
2600 cidx := mGrid[(gy div mTileSize)*mWidth+(gx div mTileSize)];
2601 while (cidx <> -1) do
2602 begin
2603 cc := @mCells[cidx];
2604 for f := 0 to GridCellBucketSize-1 do
2605 begin
2606 if (cc.bodies[f] = -1) then break;
2607 px := @mProxies[cc.bodies[f]];
2608 ptag := px.mTag;
2609 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2610 begin
2611 px.mQueryMark := lq; // mark as processed
2612 if assigned(cb) then
2613 begin
2614 if not cb(px.mObj, ptag) then continue;
2615 end;
2616 if not sweepAABB(cx0+mMinX, cy0+mMinY, aw, ah, dx, dy, px.mX, px.mY, px.mWidth, px.mHeight, @u0, @hedge) then
2617 begin
2618 continue;
2619 end;
2620 if (minu0 > u0) then
2621 begin
2622 result := px.mObj;
2623 minu0 := u0;
2624 if (u0 = 0.0) then
2625 begin
2626 ex := cx0+mMinX;
2627 ey := cy0+mMinY;
2628 mInQuery := false;
2629 exit;
2630 end;
2631 end;
2632 end;
2633 end;
2634 // next cell
2635 cidx := cc.next;
2636 end;
2637 Inc(gx, mTileSize);
2638 end;
2639 Inc(gy, mTileSize);
2640 end;
2642 if (minu0 <= 1.0) then
2643 begin
2644 ex := ax0+trunc(dx*minu0);
2645 ey := ay0+trunc(dy*minu0);
2646 end;
2648 mInQuery := false;
2649 end;
2652 // ////////////////////////////////////////////////////////////////////////// //
2653 {.$DEFINE D2F_DEBUG_OTR}
2654 function TBodyGridBase.traceOrthoRayWhileIn (out ex, ey: Integer; ax0, ay0, ax1, ay1: Integer; tagmask: Integer=-1): Boolean;
2655 var
2656 ccidx: Integer;
2657 cc: PGridCell;
2658 px: PBodyProxyRec;
2659 ptag: Integer;
2660 minx, miny: Integer;
2661 f, c0, c1: Integer;
2662 x0, y0, x1, y1: Integer;
2663 celly0, celly1: Integer;
2664 dy: Integer;
2665 filled: array[0..mTileSize-1] of Byte;
2666 {$IF DEFINED(D2F_DEBUG_OTR)}
2667 s: AnsiString = '';
2668 {$ENDIF}
2669 begin
2670 result := false;
2671 ex := ax1;
2672 ey := ay1;
2673 if not ((ax0 = ax1) or (ay0 = ay1)) then raise Exception.Create('orthoray is not orthogonal');
2675 tagmask := tagmask and TagFullMask;
2676 if (tagmask = 0) then exit;
2678 if (forEachAtPoint(ax0, ay0, nil, tagmask) = nil) then exit;
2680 minx := mMinX;
2681 miny := mMinY;
2683 // offset query coords to (0,0)-based
2684 x0 := ax0-minx;
2685 y0 := ay0-miny;
2686 x1 := ax1-minx;
2687 y1 := ay1-miny;
2689 if (x0 = x1) then
2690 begin
2691 if (x0 < 0) or (x0 >= mWidth*mTileSize) then exit; // oops
2692 // vertical
2693 if (y0 < y1) then
2694 begin
2695 // down
2696 if (y1 < 0) or (y0 >= mHeight*mTileSize) then exit;
2697 //if (ay0 < 0) then ay0 := 0;
2698 if (y0 < 0) then exit;
2699 if (y1 >= mHeight*mTileSize) then y1 := mHeight*mTileSize-1;
2700 dy := 1;
2701 end
2702 else
2703 begin
2704 // up
2705 if (y0 < 0) or (y1 >= mHeight*mTileSize) then exit;
2706 //if (ay1 < 0) then ay1 := 0;
2707 if (y1 < 0) then exit;
2708 if (y0 >= mHeight*mTileSize) then y0 := mHeight*mTileSize-1;
2709 dy := -1;
2710 end;
2711 // check tile
2712 while true do
2713 begin
2714 ccidx := mGrid[(y0 div mTileSize)*mWidth+(x0 div mTileSize)];
2715 FillChar(filled, sizeof(filled), 0);
2716 celly0 := y0 and (not (mTileSize-1));
2717 celly1 := celly0+mTileSize-1;
2718 while (ccidx <> -1) do
2719 begin
2720 cc := @mCells[ccidx];
2721 for f := 0 to GridCellBucketSize-1 do
2722 begin
2723 if (cc.bodies[f] = -1) then break;
2724 px := @mProxies[cc.bodies[f]];
2725 ptag := px.mTag;
2726 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and
2727 (ax0 >= px.x0) and (ax0 <= px.x1) then
2728 begin
2729 // bound c0 and c1 to cell
2730 c0 := nclamp(px.y0-miny, celly0, celly1);
2731 c1 := nclamp(px.y1-miny, celly0, celly1);
2732 // fill the thing
2733 {$IF DEFINED(D2F_DEBUG_OTR)}
2734 e_LogWritefln('**px.y0=%s; px.y1=%s; c0=%s; c1=%s; celly0=%s; celly1=%s; [%s..%s]', [px.y0-miny, px.y1-miny, c0, c1, celly0, celly1, c0-celly0, (c0-celly0)+(c1-c0)]);
2735 {$ENDIF}
2736 //assert(c0 <= c1);
2737 FillChar(filled[c0-celly0], c1-c0+1, 1);
2738 end;
2739 end;
2740 // next cell
2741 ccidx := cc.next;
2742 end;
2743 {$IF DEFINED(D2F_DEBUG_OTR)}
2744 s := formatstrf(' x=%s; ay0=%s; ay1=%s; y0=%s; celly0=%s; celly1=%s; dy=%s; [', [ax0, ay0, ay1, y0, celly0, celly1, dy]);
2745 for f := 0 to High(filled) do if (filled[f] <> 0) then s += '1' else s += '0';
2746 s += ']';
2747 e_LogWriteln(s);
2748 {$ENDIF}
2749 // now go till we hit cell boundary or empty space
2750 if (dy < 0) then
2751 begin
2752 // up
2753 while (y0 >= celly0) and (filled[y0-celly0] <> 0) do
2754 begin
2755 {$IF DEFINED(D2F_DEBUG_OTR)}
2756 e_LogWritefln(' filled: cdy=%s; y0=%s; celly0=%s; ay0=%s; ay1=%s', [y0-celly0, y0, celly0, ay0, ay1]);
2757 {$ENDIF}
2758 Dec(y0);
2759 Dec(ay0);
2760 end;
2761 {$IF DEFINED(D2F_DEBUG_OTR)}
2762 e_LogWritefln(' span done: cdy=%s; y0=%s; celly0=%s; ay0=%s; ay1=%s', [y0-celly0, y0, celly0, ay0, ay1]);
2763 {$ENDIF}
2764 if (ay0 <= ay1) then begin ey := ay1; result := false; exit; end;
2765 if (y0 >= celly0) then begin ey := ay0+1; {assert(forEachAtPoint(ex, ey, nil, tagmask) <> nil);} result := true; exit; end;
2766 end
2767 else
2768 begin
2769 // down
2770 while (y0 <= celly1) and (filled[y0-celly0] <> 0) do begin Inc(y0); Inc(ay0); end;
2771 if (ay0 >= ay1) then begin ey := ay1; result := false; exit; end;
2772 if (y0 <= celly1) then begin ey := ay0-1; result := true; exit; end;
2773 end;
2774 end;
2775 end
2776 else
2777 begin
2778 // horizontal
2779 assert(false);
2780 end;
2781 end;
2784 end.