DEADSOFTWARE

ooops
[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
28 const
29 GridTileSize = 32; // must be power of two!
31 type
32 TBodyProxyId = Integer;
34 generic TBodyGridBase<ITP> = class(TObject)
35 public
36 type TGridQueryCB = function (obj: ITP; tag: Integer): Boolean is nested; // return `true` to stop
37 type TGridRayQueryCB = function (obj: ITP; tag: Integer; x, y, prevx, prevy: 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;
43 private
44 const
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 = GridTileSize;
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 traceRayOld (const x0, y0, x1, y1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP; overload;
198 function traceRayOld (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
200 //WARNING: don't modify grid while any query is in progress (no checks are made!)
201 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
202 // cb with `(nil)` will be called before processing new tile
203 // no callback: return object of the nearest hit or nil
204 // if `inverted` is true, trace will register bodies *exluding* tagmask
205 // `cb` is used unconvetionally here: if it returns `false`, tracer will ignore the object
206 //WARNING: don't change tags in callbacks here!
207 function traceRay (const x0, y0, x1, y1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP; overload;
208 function traceRay (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
210 // return `false` if we're still inside at the end
211 // line should be either strict horizontal, or strict vertical, otherwise an exception will be thrown
212 // `true`: endpoint will point at the last "inside" pixel
213 // `false`: endpoint will be (ax1, ay1)
214 //WARNING: don't change tags in callbacks here!
215 function traceOrthoRayWhileIn (out ex, ey: Integer; ax0, ay0, ax1, ay1: Integer; tagmask: Integer=-1): Boolean;
217 //WARNING: don't modify grid while any query is in progress (no checks are made!)
218 // you can set enabled/disabled flag, tho (but iterator can still return objects disabled inside it)
219 // trace line along the grid, calling `cb` for all objects in passed cells, in no particular order
220 //WARNING: don't change tags in callbacks here!
221 function forEachAlongLine (ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1; log: Boolean=false): ITP;
223 // trace box with the given velocity; return object hit (if any)
224 // `cb` is used unconvetionally here: if it returns `false`, tracer will ignore the object
225 //WARNING: don't change tags in callbacks here!
226 function traceBox (out ex, ey: Integer; const ax0, ay0, aw, ah: Integer; const dx, dy: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
228 // debug
229 procedure forEachBodyCell (body: TBodyProxyId; cb: TCellQueryCB);
230 function forEachInCell (x, y: Integer; cb: TGridQueryCB): ITP;
231 procedure dumpStats ();
233 public
234 //WARNING! no sanity checks!
235 property proxyEnabled[pid: TBodyProxyId]: Boolean read getProxyEnabled write setProxyEnabled;
237 property gridX0: Integer read mMinX;
238 property gridY0: Integer read mMinY;
239 property gridWidth: Integer read getGridWidthPx; // in pixels
240 property gridHeight: Integer read getGridHeightPx; // in pixels
242 property proxy[idx: TBodyProxyId]: PBodyProxyRec read getProxyById;
243 end;
246 type
247 // common structure for all line tracers
248 TLineWalker = record
249 public
250 const TileSize = GridTileSize;
252 private
253 wx0, wy0, wx1, wy1: Integer; // window coordinates
254 stx, sty: Integer; // "steps" for x and y axes
255 dx2, dy2: Integer; // "double lengthes" for x and y axes
256 xd, yd: Integer; // current coord
257 e: Integer; // "error" (as in bresenham algo)
258 term: Integer; // end for xd (xd = term: done)
259 //xptr, yptr: PInteger;
260 xyswapped: Boolean; // true: xd is y
262 public
263 // call `setyp` after this
264 constructor Create (minx, miny, maxx, maxy: Integer);
266 procedure setClip (minx, miny, maxx, maxy: Integer); inline;
268 // this will use `w[xy][01]` to clip coords
269 // return `false` if the whole line was clipped away
270 // on `true`, you should process first point, and go on
271 function setup (x0, y0, x1, y1: Integer): Boolean;
273 // call this *after* doing a step
274 // WARNING! if you will do a step when this returns `true`, you will fall into limbo
275 function done (): Boolean; inline;
277 // as you will prolly call `done()` after doing a step anyway, this will do it for you
278 // move to next point, return `true` when the line is complete (i.e. you should stop)
279 function step (): Boolean; inline;
281 // move to next tile; return `true` if the line is complete (and walker state is undefined then)
282 function stepToNextTile (): Boolean; inline;
284 // hack for line-vs-aabb; NOT PROPERLY TESTED!
285 procedure getPrevXY (out ox, oy: Integer); inline;
287 // current coords
288 function x (): Integer; inline;
289 function y (): Integer; inline;
291 procedure getXY (out ox, oy: Integer); inline;
293 // move directions; always [-1..1] (can be zero!)
294 function dx (): Integer; inline;
295 function dy (): Integer; inline;
296 end;
299 // you are not supposed to understand this
300 // returns `true` if there is an intersection, and enter coords
301 // enter coords will be equal to (x0, y0) if starting point is inside the box
302 // if result is `false`, `inx` and `iny` are undefined
303 function lineAABBIntersects (x0, y0, x1, y1: Integer; bx, by, bw, bh: Integer; out inx, iny: Integer): Boolean;
305 // sweep two AABB's to see if and when they are overlapping
306 // returns `true` if collision was detected (but boxes doesn't overlap)
307 // u1 and u1 has no sense if no collision was detected
308 // u0 = normalized time of first collision (i.e. collision starts at myMove*u0)
309 // u1 = normalized time of second collision (i.e. collision stops after myMove*u1)
310 // hitedge for `it`: 0: top; 1: right; 2: bottom; 3: left
311 // enter/exit coords will form non-intersecting configuration (i.e. will be before/after the actual collision)
312 function sweepAABB (mex0, mey0, mew, meh: Integer; medx, medy: Integer; itx0, ity0, itw, ith: Integer;
313 u0: PSingle=nil; hitedge: PInteger=nil; u1: PSingle=nil): Boolean;
315 function distanceSq (x0, y0, x1, y1: Integer): Integer; inline;
317 procedure swapInt (var a: Integer; var b: Integer); inline;
318 //function minInt (a, b: Integer): Integer; inline;
319 //function maxInt (a, b: Integer): Integer; inline;
322 implementation
324 uses
325 SysUtils, e_log, g_console, utils;
328 // ////////////////////////////////////////////////////////////////////////// //
329 //procedure swapInt (var a: Integer; var b: Integer); inline; var t: Integer; begin t := a; a := b; b := t; end;
330 procedure swapInt (var a: Integer; var b: Integer); inline; begin a := a xor b; b := b xor a; a := a xor b; end;
331 //function minInt (a, b: Integer): Integer; inline; begin if (a < b) then result := a else result := b; end;
332 //function maxInt (a, b: Integer): Integer; inline; begin if (a > b) then result := a else result := b; end;
334 function distanceSq (x0, y0, x1, y1: Integer): Integer; inline; begin result := (x1-x0)*(x1-x0)+(y1-y0)*(y1-y0); end;
337 // ////////////////////////////////////////////////////////////////////////// //
338 constructor TLineWalker.Create (minx, miny, maxx, maxy: Integer);
339 begin
340 setClip(minx, miny, maxx, maxy);
341 end;
343 procedure TLineWalker.setClip (minx, miny, maxx, maxy: Integer); inline;
344 begin
345 // clip rectange
346 wx0 := minx;
347 wy0 := miny;
348 wx1 := maxx;
349 wy1 := maxy;
350 end;
352 function TLineWalker.done (): Boolean; inline; begin result := (xd = term); end;
354 function TLineWalker.step (): Boolean; inline;
355 begin
356 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
357 xd += stx;
358 result := (xd = term);
359 end;
361 function TLineWalker.stepToNextTile (): Boolean; inline;
362 var
363 ex, ey: Integer;
364 xwalk, ywalk, wklen: Integer; // to the respective edges
365 lstx, lsty, lterm: Integer;
366 le, ldx2, ldy2: Integer;
367 lxd, lyd: Integer;
368 f: Integer;
369 begin
370 result := false;
372 lstx := stx;
373 lsty := sty;
374 lterm := term;
375 lxd := xd;
377 // ortho?
378 if (lsty = 0) then
379 begin
380 // only xd
381 //assert(lsty <> 0);
382 if (lstx < 0) then
383 begin
384 // xd: to left edge
385 xd := (lxd and (not (TileSize-1)))-1;
386 result := (lxd <= lterm);
387 exit;
388 end
389 else
390 begin
391 // xd: to right edge
392 xd := (lxd or (TileSize-1))+1;
393 result := (lxd >= lterm);
394 exit;
395 end;
396 end;
398 // not ortho
399 //assert(lstx <> 0); // invariant
401 lyd := yd;
402 le := e;
403 ldx2 := dx2;
404 ldy2 := dy2;
406 // calculate xwalk
407 if (lstx < 0) then
408 begin
409 ex := (lxd and (not (TileSize-1)))-1;
410 xwalk := lxd-ex;
411 end
412 else
413 begin
414 ex := (lxd or (TileSize-1))+1;
415 xwalk := ex-lxd;
416 end;
418 // calculate ywalk
419 if (lsty < 0) then
420 begin
421 ey := (lyd and (not (TileSize-1)))-1;
422 ywalk := lyd-ey;
423 end
424 else
425 begin
426 ey := (lyd or (TileSize-1))+1;
427 ywalk := ey-lyd;
428 end;
430 while true do
431 begin
432 // in which dir we want to walk?
433 if (xwalk <= ywalk) then wklen := xwalk else wklen := ywalk;
434 // walk x
435 if (lstx < 0) then
436 begin
437 lxd -= wklen;
438 if (lxd <= lterm) then begin xd := lxd; result := true; exit; end;
439 end
440 else
441 begin
442 lxd += wklen;
443 if (lxd >= lterm) then begin xd := lxd; result := true; exit; end;
444 end;
445 // walk y
446 for f := 1 to wklen do if (le >= 0) then begin lyd += lsty; le -= ldx2; end else le += ldy2;
447 if (lxd = ex) or (lyd = ey) then break;
448 xwalk -= wklen; if (xwalk = 0) then xwalk := TileSize;
449 ywalk -= wklen; if (ywalk = 0) then ywalk := TileSize;
450 end;
451 //assert((xd div TileSize <> lxd div TileSize) or (yd div TileSize <> lyd div TileSize));
452 xd := lxd;
453 yd := lyd;
454 e := le;
455 end;
457 // NOT TESTED!
458 procedure TLineWalker.getPrevXY (out ox, oy: Integer); inline;
459 begin
460 //writeln('e=', e, '; dx2=', dx2, '; dy2=', dy2);
461 if xyswapped then
462 begin
463 if (e >= 0) then ox := yd-sty else ox := yd;
464 oy := xd-stx;
465 end
466 else
467 begin
468 if (e >= 0) then oy := yd-sty else oy := yd;
469 ox := xd-stx;
470 end;
471 end;
473 function TLineWalker.x (): Integer; inline; begin if xyswapped then result := yd else result := xd; end;
474 function TLineWalker.y (): Integer; inline; begin if xyswapped then result := xd else result := yd; end;
475 procedure TLineWalker.getXY (out ox, oy: Integer); inline; begin if xyswapped then begin ox := yd; oy := xd; end else begin ox := xd; oy := yd; end; end;
477 function TLineWalker.dx (): Integer; inline; begin if xyswapped then result := stx else result := sty; end;
478 function TLineWalker.dy (): Integer; inline; begin if xyswapped then result := sty else result := stx; end;
480 function TLineWalker.setup (x0, y0, x1, y1: Integer): Boolean;
481 procedure swapInt (var a: Integer; var b: Integer); inline; begin a := a xor b; b := b xor a; a := a xor b; end;
482 var
483 dsx, dsy: Integer; // "lengthes" for x and y axes
484 rem: Integer;
485 xfixed: Boolean;
486 temp: Integer;
487 begin
488 result := false;
489 xyswapped := false;
491 // horizontal setup
492 if (x0 < x1) then
493 begin
494 // from left to right
495 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
496 stx := 1; // going right
497 end
498 else
499 begin
500 // from right to left
501 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
502 stx := -1; // going left
503 x0 := -x0;
504 x1 := -x1;
505 wx0 := -wx0;
506 wx1 := -wx1;
507 swapInt(wx0, wx1);
508 end;
510 // vertical setup
511 if (y0 < y1) then
512 begin
513 // from top to bottom
514 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
515 sty := 1; // going down
516 end
517 else
518 begin
519 // from bottom to top
520 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
521 sty := -1; // going up
522 y0 := -y0;
523 y1 := -y1;
524 wy0 := -wy0;
525 wy1 := -wy1;
526 swapInt(wy0, wy1);
527 end;
529 dsx := x1-x0;
530 dsy := y1-y0;
532 if (dsx < dsy) then
533 begin
534 xyswapped := true;
535 //xptr := @yd;
536 //yptr := @xd;
537 swapInt(x0, y0);
538 swapInt(x1, y1);
539 swapInt(dsx, dsy);
540 swapInt(wx0, wy0);
541 swapInt(wx1, wy1);
542 swapInt(stx, sty);
543 end
544 else
545 begin
546 //xptr := @xd;
547 //yptr := @yd;
548 end;
550 dx2 := 2*dsx;
551 dy2 := 2*dsy;
552 xd := x0;
553 yd := y0;
554 e := 2*dsy-dsx;
555 term := x1;
557 xfixed := false;
558 if (y0 < wy0) then
559 begin
560 // clip at top
561 temp := dx2*(wy0-y0)-dsx;
562 xd += temp div dy2;
563 rem := temp mod dy2;
564 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
565 if (xd+1 >= wx0) then
566 begin
567 yd := wy0;
568 e -= rem+dsx;
569 //if (rem > 0) then begin Inc(xd); e += dy2; end; //BUGGY
570 if (xd < wx0) then begin xd += 1; e += dy2; end; //???
571 xfixed := true;
572 end;
573 end;
575 if (not xfixed) and (x0 < wx0) then
576 begin
577 // clip at left
578 temp := dy2*(wx0-x0);
579 yd += temp div dx2;
580 rem := temp mod dx2;
581 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
582 xd := wx0;
583 e += rem;
584 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
585 end;
587 if (y1 > wy1) then
588 begin
589 // clip at bottom
590 temp := dx2*(wy1-y0)+dsx;
591 term := x0+temp div dy2;
592 rem := temp mod dy2;
593 if (rem = 0) then Dec(term);
594 end;
596 if (term > wx1) then term := wx1; // clip at right
598 Inc(term); // draw last point (it is ok to inc here, as `term` sign will be changed later
599 //if (term = xd) then exit; // this is the only point, get out of here
601 if (sty = -1) then yd := -yd;
602 if (stx = -1) then begin xd := -xd; term := -term; end;
603 dx2 -= dy2;
605 result := true;
606 end;
609 // ////////////////////////////////////////////////////////////////////////// //
610 // you are not supposed to understand this
611 // returns `true` if there is an intersection, and enter coords
612 // enter coords will be equal to (x0, y0) if starting point is inside the box
613 // if result is `false`, `inx` and `iny` are undefined
614 function lineAABBIntersects (x0, y0, x1, y1: Integer; bx, by, bw, bh: Integer; out inx, iny: Integer): Boolean;
615 var
616 wx0, wy0, wx1, wy1: Integer; // window coordinates
617 stx, sty: Integer; // "steps" for x and y axes
618 dsx, dsy: Integer; // "lengthes" for x and y axes
619 dx2, dy2: Integer; // "double lengthes" for x and y axes
620 xd, yd: Integer; // current coord
621 e: Integer; // "error" (as in bresenham algo)
622 rem: Integer;
623 //!term: Integer;
624 d0, d1: PInteger;
625 xfixed: Boolean;
626 temp: Integer;
627 begin
628 result := false;
629 // why not
630 inx := x0;
631 iny := y0;
632 if (bw < 1) or (bh < 1) then exit; // impossible box
634 if (x0 = x1) and (y0 = y1) then
635 begin
636 // check this point
637 result := (x0 >= bx) and (y0 >= by) and (x0 < bx+bw) and (y0 < by+bh);
638 exit;
639 end;
641 // check if staring point is inside the box
642 if (x0 >= bx) and (y0 >= by) and (x0 < bx+bw) and (y0 < by+bh) then begin result := true; exit; end;
644 // clip rectange
645 wx0 := bx;
646 wy0 := by;
647 wx1 := bx+bw-1;
648 wy1 := by+bh-1;
650 // horizontal setup
651 if (x0 < x1) then
652 begin
653 // from left to right
654 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
655 stx := 1; // going right
656 end
657 else
658 begin
659 // from right to left
660 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
661 stx := -1; // going left
662 x0 := -x0;
663 x1 := -x1;
664 wx0 := -wx0;
665 wx1 := -wx1;
666 swapInt(wx0, wx1);
667 end;
669 // vertical setup
670 if (y0 < y1) then
671 begin
672 // from top to bottom
673 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
674 sty := 1; // going down
675 end
676 else
677 begin
678 // from bottom to top
679 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
680 sty := -1; // going up
681 y0 := -y0;
682 y1 := -y1;
683 wy0 := -wy0;
684 wy1 := -wy1;
685 swapInt(wy0, wy1);
686 end;
688 dsx := x1-x0;
689 dsy := y1-y0;
691 if (dsx < dsy) then
692 begin
693 d0 := @yd;
694 d1 := @xd;
695 swapInt(x0, y0);
696 swapInt(x1, y1);
697 swapInt(dsx, dsy);
698 swapInt(wx0, wy0);
699 swapInt(wx1, wy1);
700 swapInt(stx, sty);
701 end
702 else
703 begin
704 d0 := @xd;
705 d1 := @yd;
706 end;
708 dx2 := 2*dsx;
709 dy2 := 2*dsy;
710 xd := x0;
711 yd := y0;
712 e := 2*dsy-dsx;
713 //!term := x1;
715 xfixed := false;
716 if (y0 < wy0) then
717 begin
718 // clip at top
719 temp := dx2*(wy0-y0)-dsx;
720 xd += temp div dy2;
721 rem := temp mod dy2;
722 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
723 if (xd+1 >= wx0) then
724 begin
725 yd := wy0;
726 e -= rem+dsx;
727 //if (rem > 0) then begin Inc(xd); e += dy2; end; //BUGGY
728 if (xd < wx0) then begin xd += 1; e += dy2; end; //???
729 xfixed := true;
730 end;
731 end;
733 if (not xfixed) and (x0 < wx0) then
734 begin
735 // clip at left
736 temp := dy2*(wx0-x0);
737 yd += temp div dx2;
738 rem := temp mod dx2;
739 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
740 xd := wx0;
741 e += rem;
742 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
743 end;
745 (*
746 if (y1 > wy1) then
747 begin
748 // clip at bottom
749 temp := dx2*(wy1-y0)+dsx;
750 term := x0+temp div dy2;
751 rem := temp mod dy2;
752 if (rem = 0) then Dec(term);
753 end;
755 if (term > wx1) then term := wx1; // clip at right
757 Inc(term); // draw last point
758 //if (term = xd) then exit; // this is the only point, get out of here
759 *)
761 if (sty = -1) then yd := -yd;
762 if (stx = -1) then begin xd := -xd; {!term := -term;} end;
763 //!dx2 -= dy2;
765 inx := d0^;
766 iny := d1^;
767 result := true;
768 end;
771 // ////////////////////////////////////////////////////////////////////////// //
772 function sweepAABB (mex0, mey0, mew, meh: Integer; medx, medy: Integer; itx0, ity0, itw, ith: Integer;
773 u0: PSingle=nil; hitedge: PInteger=nil; u1: PSingle=nil): Boolean;
774 var
775 tin, tout: Single;
777 function axisOverlap (me0, me1, it0, it1, d, he0, he1: Integer): Boolean; inline;
778 var
779 t: Single;
780 begin
781 result := false;
783 if (me1 < it0) then
784 begin
785 if (d >= 0) then exit; // oops, no hit
786 t := (me1-it0+1)/d;
787 if (t > tin) then begin tin := t; hitedge^ := he1; end;
788 end
789 else if (it1 < me0) then
790 begin
791 if (d <= 0) then exit; // oops, no hit
792 t := (me0-it1-1)/d;
793 if (t > tin) then begin tin := t; hitedge^ := he0; end;
794 end;
796 if (d < 0) and (it1 > me0) then
797 begin
798 t := (me0-it1-1)/d;
799 if (t < tout) then tout := t;
800 end
801 else if (d > 0) and (me1 > it0) then
802 begin
803 t := (me1-it0+1)/d;
804 if (t < tout) then tout := t;
805 end;
807 result := true;
808 end;
810 var
811 mex1, mey1, itx1, ity1, vx, vy: Integer;
812 htt: Integer = -1;
813 begin
814 result := false;
815 if (u0 <> nil) then u0^ := -1.0;
816 if (u1 <> nil) then u1^ := -1.0;
817 if (hitedge = nil) then hitedge := @htt else hitedge^ := -1;
819 if (mew < 1) or (meh < 1) or (itw < 1) or (ith < 1) then exit;
821 mex1 := mex0+mew-1;
822 mey1 := mey0+meh-1;
823 itx1 := itx0+itw-1;
824 ity1 := ity0+ith-1;
826 // check if they are overlapping right now (SAT)
827 //if (mex1 >= itx0) and (mex0 <= itx1) and (mey1 >= ity0) and (mey0 <= ity1) then begin result := true; exit; end;
829 if (medx = 0) and (medy = 0) then exit; // both boxes are sationary
831 // treat b as stationary, so invert v to get relative velocity
832 vx := -medx;
833 vy := -medy;
835 tin := -100000000.0;
836 tout := 100000000.0;
838 if not axisOverlap(mex0, mex1, itx0, itx1, vx, 1, 3) then exit;
839 if not axisOverlap(mey0, mey1, ity0, ity1, vy, 2, 0) then exit;
841 if (u0 <> nil) then u0^ := tin;
842 if (u1 <> nil) then u1^ := tout;
844 if (tin <= tout) and (tin >= 0.0) and (tin <= 1.0) then
845 begin
846 result := true;
847 end;
848 end;
851 // ////////////////////////////////////////////////////////////////////////// //
852 procedure TBodyGridBase.TBodyProxyRec.setup (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer);
853 begin
854 mX := aX;
855 mY := aY;
856 mWidth := aWidth;
857 mHeight := aHeight;
858 mQueryMark := 0;
859 mObj := aObj;
860 mTag := aTag;
861 nextLink := -1;
862 end;
865 function TBodyGridBase.TBodyProxyRec.getTag (): Integer; inline;
866 begin
867 result := mTag and TagFullMask;
868 end;
870 procedure TBodyGridBase.TBodyProxyRec.setTag (v: Integer); inline;
871 begin
872 mTag := (mTag and TagDisabled) or (v and TagFullMask);
873 end;
875 function TBodyGridBase.TBodyProxyRec.getEnabled (): Boolean; inline;
876 begin
877 result := ((mTag and TagDisabled) = 0);
878 end;
880 procedure TBodyGridBase.TBodyProxyRec.setEnabled (v: Boolean); inline;
881 begin
882 if v then mTag := mTag and (not TagDisabled) else mTag := mTag or TagDisabled;
883 end;
885 function TBodyGridBase.TBodyProxyRec.getX1 (): Integer; inline;
886 begin
887 result := mX+mWidth-1;
888 end;
890 function TBodyGridBase.TBodyProxyRec.getY1 (): Integer; inline;
891 begin
892 result := mY+mHeight-1;
893 end;
896 // ////////////////////////////////////////////////////////////////////////// //
897 constructor TBodyGridBase.TAtPointEnumerator.Create (acells: TCellArray; aidx: Integer; agetpx: TGetProxyFn);
898 begin
899 mCells := acells;
900 curidx := aidx;
901 curbki := -1;
902 getpx := agetpx;
903 end;
906 function TBodyGridBase.TAtPointEnumerator.MoveNext (): Boolean; inline;
907 begin
908 while (curidx <> -1) do
909 begin
910 while (curbki < GridCellBucketSize) do
911 begin
912 Inc(curbki);
913 if (mCells[curidx].bodies[curbki] = -1) then break;
914 result := true;
915 exit;
916 end;
917 curidx := mCells[curidx].next;
918 curbki := -1;
919 end;
920 result := false;
921 end;
924 function TBodyGridBase.TAtPointEnumerator.getCurrent (): PBodyProxyRec; inline;
925 begin
926 result := getpx(mCells[curidx].bodies[curbki]);
927 end;
930 // ////////////////////////////////////////////////////////////////////////// //
931 constructor TBodyGridBase.Create (aMinPixX, aMinPixY, aPixWidth, aPixHeight: Integer{; aTileSize: Integer=GridDefaultTileSize});
932 var
933 idx: Integer;
934 begin
935 dbgShowTraceLog := false;
936 {$IF DEFINED(D2F_DEBUG)}
937 dbgRayTraceTileHitCB := nil;
938 {$ENDIF}
940 if aTileSize < 1 then aTileSize := 1;
941 if aTileSize > 8192 then aTileSize := 8192; // arbitrary limit
942 mTileSize := aTileSize;
944 if (aPixWidth < mTileSize) then aPixWidth := mTileSize;
945 if (aPixHeight < mTileSize) then aPixHeight := mTileSize;
946 mMinX := aMinPixX;
947 mMinY := aMinPixY;
948 mWidth := (aPixWidth+mTileSize-1) div mTileSize;
949 mHeight := (aPixHeight+mTileSize-1) div mTileSize;
950 SetLength(mGrid, mWidth*mHeight);
951 SetLength(mCells, mWidth*mHeight);
952 SetLength(mProxies, 8192);
953 mFreeCell := 0;
954 // init free list
955 for idx := 0 to High(mCells) do
956 begin
957 mCells[idx].bodies[0] := -1;
958 mCells[idx].bodies[GridCellBucketSize-1] := -1; // "has free room" flag
959 mCells[idx].next := idx+1;
960 end;
961 mCells[High(mCells)].next := -1; // last cell
962 // init grid
963 for idx := 0 to High(mGrid) do mGrid[idx] := -1;
964 // init proxies
965 for idx := 0 to High(mProxies) do mProxies[idx].nextLink := idx+1;
966 mProxies[High(mProxies)].nextLink := -1;
967 mLastQuery := 0;
968 mUsedCells := 0;
969 mProxyFree := 0;
970 mProxyCount := 0;
971 mProxyMaxCount := 0;
972 e_WriteLog(Format('created grid with size: %dx%d (tile size: %d); pix: %dx%d', [mWidth, mHeight, mTileSize, mWidth*mTileSize, mHeight*mTileSize]), MSG_NOTIFY);
973 end;
976 destructor TBodyGridBase.Destroy ();
977 begin
978 mCells := nil;
979 mGrid := nil;
980 mProxies := nil;
981 inherited;
982 end;
985 // ////////////////////////////////////////////////////////////////////////// //
986 procedure TBodyGridBase.dumpStats ();
987 var
988 idx, mcb, ccidx, cnt: Integer;
989 begin
990 mcb := 0;
991 for idx := 0 to High(mGrid) do
992 begin
993 ccidx := mGrid[idx];
994 cnt := 0;
995 while ccidx >= 0 do
996 begin
997 Inc(cnt);
998 ccidx := mCells[ccidx].next;
999 end;
1000 if (mcb < cnt) then mcb := cnt;
1001 end;
1002 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);
1003 end;
1006 procedure TBodyGridBase.forEachBodyCell (body: TBodyProxyId; cb: TCellQueryCB);
1007 var
1008 g, f, ccidx: Integer;
1009 cc: PGridCell;
1010 begin
1011 if (body < 0) or (body > High(mProxies)) or not assigned(cb) then exit;
1012 for g := 0 to High(mGrid) do
1013 begin
1014 ccidx := mGrid[g];
1015 while (ccidx <> -1) do
1016 begin
1017 cc := @mCells[ccidx];
1018 for f := 0 to GridCellBucketSize-1 do
1019 begin
1020 if (cc.bodies[f] = -1) then break;
1021 if (cc.bodies[f] = body) then cb((g mod mWidth)*mTileSize+mMinX, (g div mWidth)*mTileSize+mMinY);
1022 end;
1023 // next cell
1024 ccidx := cc.next;
1025 end;
1026 end;
1027 end;
1030 function TBodyGridBase.forEachInCell (x, y: Integer; cb: TGridQueryCB): ITP;
1031 var
1032 f, ccidx: Integer;
1033 cc: PGridCell;
1034 begin
1035 result := Default(ITP);
1036 if not assigned(cb) then exit;
1037 Dec(x, mMinX);
1038 Dec(y, mMinY);
1039 if (x < 0) or (y < 0) or (x >= mWidth*mTileSize) or (y > mHeight*mTileSize) then exit;
1040 ccidx := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
1041 while (ccidx <> -1) do
1042 begin
1043 cc := @mCells[ccidx];
1044 for f := 0 to GridCellBucketSize-1 do
1045 begin
1046 if (cc.bodies[f] = -1) then break;
1047 if cb(mProxies[cc.bodies[f]].mObj, mProxies[cc.bodies[f]].mTag) then begin result := mProxies[cc.bodies[f]].mObj; exit; end;
1048 end;
1049 // next cell
1050 ccidx := cc.next;
1051 end;
1052 end;
1055 // ////////////////////////////////////////////////////////////////////////// //
1056 function TBodyGridBase.getGridWidthPx (): Integer; inline; begin result := mWidth*mTileSize; end;
1057 function TBodyGridBase.getGridHeightPx (): Integer; inline; begin result := mHeight*mTileSize; end;
1060 function TBodyGridBase.insideGrid (x, y: Integer): Boolean; inline;
1061 begin
1062 // fix coords
1063 Dec(x, mMinX);
1064 Dec(y, mMinY);
1065 result := (x >= 0) and (y >= 0) and (x < mWidth*mTileSize) and (y < mHeight*mTileSize);
1066 end;
1069 function TBodyGridBase.getBodyXY (body: TBodyProxyId; out rx, ry: Integer): Boolean; inline;
1070 begin
1071 if (body >= 0) and (body < Length(mProxies)) then
1072 begin
1073 with mProxies[body] do begin rx := mX; ry := mY; end;
1074 result := true;
1075 end
1076 else
1077 begin
1078 rx := 0;
1079 ry := 0;
1080 result := false;
1081 end;
1082 end;
1085 function TBodyGridBase.getBodyWH (body: TBodyProxyId; out rw, rh: Integer): Boolean; inline;
1086 begin
1087 if (body >= 0) and (body < Length(mProxies)) then
1088 begin
1089 with mProxies[body] do begin rw := mWidth; rh := mHeight; end;
1090 result := true;
1091 end
1092 else
1093 begin
1094 rw := 0;
1095 rh := 0;
1096 result := false;
1097 end;
1098 end;
1101 function TBodyGridBase.getBodyDims (body: TBodyProxyId; out rx, ry, rw, rh: Integer): Boolean; inline;
1102 begin
1103 if (body >= 0) and (body < Length(mProxies)) then
1104 begin
1105 with mProxies[body] do begin rx := mX; ry := mY; rw := mWidth; rh := mHeight; end;
1106 result := true;
1107 end
1108 else
1109 begin
1110 rx := 0;
1111 ry := 0;
1112 rw := 0;
1113 rh := 0;
1114 result := false;
1115 end;
1116 end;
1120 // ////////////////////////////////////////////////////////////////////////// //
1121 function TBodyGridBase.getProxyEnabled (pid: TBodyProxyId): Boolean; inline;
1122 begin
1123 if (pid >= 0) and (pid < Length(mProxies)) then result := ((mProxies[pid].mTag and TagDisabled) = 0) else result := false;
1124 end;
1127 procedure TBodyGridBase.setProxyEnabled (pid: TBodyProxyId; val: Boolean); inline;
1128 begin
1129 if (pid >= 0) and (pid < Length(mProxies)) then
1130 begin
1131 if val then
1132 begin
1133 mProxies[pid].mTag := mProxies[pid].mTag and not TagDisabled;
1134 end
1135 else
1136 begin
1137 mProxies[pid].mTag := mProxies[pid].mTag or TagDisabled;
1138 end;
1139 end;
1140 end;
1143 function TBodyGridBase.getProxyById (idx: TBodyProxyId): PBodyProxyRec; inline;
1144 begin
1145 if (idx >= 0) and (idx < Length(mProxies)) then result := @mProxies[idx] else result := nil;
1146 end;
1149 // ////////////////////////////////////////////////////////////////////////// //
1150 function TBodyGridBase.allocCell (): Integer;
1151 var
1152 idx: Integer;
1153 pc: PGridCell;
1154 begin
1155 if (mFreeCell < 0) then
1156 begin
1157 // no free cells, want more
1158 mFreeCell := Length(mCells);
1159 SetLength(mCells, mFreeCell+32768); // arbitrary number
1160 for idx := mFreeCell to High(mCells) do
1161 begin
1162 mCells[idx].bodies[0] := -1;
1163 mCells[idx].bodies[GridCellBucketSize-1] := -1; // 'has free room' flag
1164 mCells[idx].next := idx+1;
1165 end;
1166 mCells[High(mCells)].next := -1; // last cell
1167 end;
1168 result := mFreeCell;
1169 pc := @mCells[result];
1170 mFreeCell := pc.next;
1171 pc.next := -1;
1172 Inc(mUsedCells);
1173 //e_WriteLog(Format('grid: allocated new cell #%d (total: %d)', [result, mUsedCells]), MSG_NOTIFY);
1174 end;
1177 procedure TBodyGridBase.freeCell (idx: Integer);
1178 begin
1179 if (idx >= 0) and (idx < Length(mCells)) then
1180 begin
1181 with mCells[idx] do
1182 begin
1183 bodies[0] := -1;
1184 bodies[GridCellBucketSize-1] := -1; // 'has free room' flag
1185 next := mFreeCell;
1186 end;
1187 mFreeCell := idx;
1188 Dec(mUsedCells);
1189 end;
1190 end;
1193 // ////////////////////////////////////////////////////////////////////////// //
1194 function TBodyGridBase.allocProxy (aX, aY, aWidth, aHeight: Integer; aObj: ITP; aTag: Integer): TBodyProxyId;
1195 var
1196 olen, idx: Integer;
1197 px: PBodyProxyRec;
1198 begin
1199 if (mProxyFree = -1) then
1200 begin
1201 // no free proxies, resize list
1202 olen := Length(mProxies);
1203 SetLength(mProxies, olen+8192); // arbitrary number
1204 for idx := olen to High(mProxies) do mProxies[idx].nextLink := idx+1;
1205 mProxies[High(mProxies)].nextLink := -1;
1206 mProxyFree := olen;
1207 end;
1208 // get one from list
1209 result := mProxyFree;
1210 px := @mProxies[result];
1211 mProxyFree := px.nextLink;
1212 px.setup(aX, aY, aWidth, aHeight, aObj, aTag);
1213 // add to used list
1214 px.nextLink := -1;
1215 // statistics
1216 Inc(mProxyCount);
1217 if (mProxyMaxCount < mProxyCount) then mProxyMaxCount := mProxyCount;
1218 end;
1220 procedure TBodyGridBase.freeProxy (body: TBodyProxyId);
1221 begin
1222 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1223 if (mProxyCount = 0) then raise Exception.Create('wutafuuuuu in grid (no allocated proxies, what i should free now?)');
1224 // add to free list
1225 mProxies[body].mObj := nil;
1226 mProxies[body].nextLink := mProxyFree;
1227 mProxyFree := body;
1228 Dec(mProxyCount);
1229 end;
1232 // ////////////////////////////////////////////////////////////////////////// //
1233 function TBodyGridBase.forGridRect (x, y, w, h: Integer; cb: TGridInternalCB; bodyId: TBodyProxyId): Boolean;
1234 var
1235 gx, gy: Integer;
1236 gw, gh: Integer;
1237 begin
1238 result := false;
1239 if (w < 1) or (h < 1) or not assigned(cb) then exit;
1240 // fix coords
1241 Dec(x, mMinX);
1242 Dec(y, mMinY);
1243 // go on
1244 if (x+w <= 0) or (y+h <= 0) then exit;
1245 gw := mWidth;
1246 gh := mHeight;
1247 //tsize := mTileSize;
1248 if (x >= gw*mTileSize) or (y >= gh*mTileSize) then exit;
1249 for gy := y div mTileSize to (y+h-1) div mTileSize do
1250 begin
1251 if (gy < 0) then continue;
1252 if (gy >= gh) then break;
1253 for gx := x div mTileSize to (x+w-1) div mTileSize do
1254 begin
1255 if (gx < 0) then continue;
1256 if (gx >= gw) then break;
1257 result := cb(gy*gw+gx, bodyId);
1258 if result then exit;
1259 end;
1260 end;
1261 end;
1264 // ////////////////////////////////////////////////////////////////////////// //
1265 function TBodyGridBase.inserter (grida: Integer; bodyId: TBodyProxyId): Boolean;
1266 var
1267 ccidx: Integer;
1268 pc: Integer;
1269 pi: PGridCell;
1270 f: Integer;
1271 begin
1272 result := false; // never stop
1273 // add body to the given grid cell
1274 pc := mGrid[grida];
1275 if (pc <> -1) then
1276 begin
1277 {$IF DEFINED(D2F_DEBUG)}
1278 ccidx := pc;
1279 while (ccidx <> -1) do
1280 begin
1281 pi := @mCells[ccidx];
1282 for f := 0 to GridCellBucketSize-1 do
1283 begin
1284 if (pi.bodies[f] = -1) then break;
1285 if (pi.bodies[f] = bodyId) then raise Exception.Create('trying to insert already inserted proxy');
1286 end;
1287 ccidx := pi.next;
1288 end;
1289 {$ENDIF}
1290 ccidx := pc;
1291 while (ccidx <> -1) do
1292 begin
1293 pi := @mCells[ccidx];
1294 // check "has room" flag
1295 if (pi.bodies[GridCellBucketSize-1] = -1) then
1296 begin
1297 // can add here
1298 for f := 0 to GridCellBucketSize-1 do
1299 begin
1300 if (pi.bodies[f] = -1) then
1301 begin
1302 pi.bodies[f] := bodyId;
1303 if (f+1 < GridCellBucketSize) then pi.bodies[f+1] := -1;
1304 exit;
1305 end;
1306 end;
1307 raise Exception.Create('internal error in grid inserter');
1308 end;
1309 // no room, go to next cell in list (if there is any)
1310 ccidx := pi.next;
1311 end;
1312 // no room in cells, add new cell to list
1313 end;
1314 // either no room, or no cell at all
1315 ccidx := allocCell();
1316 pi := @mCells[ccidx];
1317 pi.bodies[0] := bodyId;
1318 pi.bodies[1] := -1;
1319 pi.next := pc;
1320 mGrid[grida] := ccidx;
1321 end;
1323 procedure TBodyGridBase.insertInternal (body: TBodyProxyId);
1324 var
1325 px: PBodyProxyRec;
1326 begin
1327 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1328 px := @mProxies[body];
1329 forGridRect(px.mX, px.mY, px.mWidth, px.mHeight, inserter, body);
1330 end;
1333 // assume that we cannot have one object added to bucket twice
1334 function TBodyGridBase.remover (grida: Integer; bodyId: TBodyProxyId): Boolean;
1335 var
1336 f, c: Integer;
1337 pidx, ccidx: Integer;
1338 pc: PGridCell;
1339 begin
1340 result := false; // never stop
1341 // find and remove cell
1342 pidx := -1; // previous cell index
1343 ccidx := mGrid[grida]; // current cell index
1344 while (ccidx <> -1) do
1345 begin
1346 pc := @mCells[ccidx];
1347 for f := 0 to GridCellBucketSize-1 do
1348 begin
1349 if (pc.bodies[f] = bodyId) then
1350 begin
1351 // i found her!
1352 if (f = 0) and (pc.bodies[1] = -1) then
1353 begin
1354 // this cell contains no elements, remove it
1355 if (pidx = -1) then mGrid[grida] := pc.next else mCells[pidx].next := pc.next;
1356 freeCell(ccidx);
1357 exit;
1358 end;
1359 // remove element from bucket
1360 for c := f to GridCellBucketSize-2 do
1361 begin
1362 pc.bodies[c] := pc.bodies[c+1];
1363 if (pc.bodies[c] = -1) then break;
1364 end;
1365 pc.bodies[GridCellBucketSize-1] := -1; // "has free room" flag
1366 exit;
1367 end;
1368 end;
1369 pidx := ccidx;
1370 ccidx := pc.next;
1371 end;
1372 end;
1374 procedure TBodyGridBase.removeInternal (body: TBodyProxyId);
1375 var
1376 px: PBodyProxyRec;
1377 begin
1378 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1379 px := @mProxies[body];
1380 forGridRect(px.mX, px.mY, px.mWidth, px.mHeight, remover, body);
1381 end;
1384 // ////////////////////////////////////////////////////////////////////////// //
1385 function TBodyGridBase.insertBody (aObj: ITP; aX, aY, aWidth, aHeight: Integer; aTag: Integer=-1): TBodyProxyId;
1386 begin
1387 aTag := aTag and TagFullMask;
1388 result := allocProxy(aX, aY, aWidth, aHeight, aObj, aTag);
1389 insertInternal(result);
1390 end;
1393 procedure TBodyGridBase.removeBody (body: TBodyProxyId);
1394 begin
1395 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1396 removeInternal(body);
1397 freeProxy(body);
1398 end;
1401 // ////////////////////////////////////////////////////////////////////////// //
1402 procedure TBodyGridBase.moveResizeBody (body: TBodyProxyId; nx, ny, nw, nh: Integer);
1403 var
1404 px: PBodyProxyRec;
1405 x0, y0, w, h: Integer;
1406 begin
1407 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1408 px := @mProxies[body];
1409 x0 := px.mX;
1410 y0 := px.mY;
1411 w := px.mWidth;
1412 h := px.mHeight;
1413 {$IF DEFINED(D2F_DEBUG_MOVER)}
1414 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);
1415 {$ENDIF}
1416 if (nx = x0) and (ny = y0) and (nw = w) and (nh = h) then exit;
1417 // map -> grid
1418 Dec(x0, mMinX);
1419 Dec(y0, mMinY);
1420 Dec(nx, mMinX);
1421 Dec(ny, mMinY);
1422 // did any corner crossed tile boundary?
1423 if (x0 div mTileSize <> nx div mTileSize) or
1424 (y0 div mTileSize <> ny div mTileSize) or
1425 ((x0+w) div mTileSize <> (nx+nw) div mTileSize) or
1426 ((y0+h) div mTileSize <> (ny+nh) div mTileSize) then
1427 begin
1428 removeInternal(body);
1429 px.mX := nx+mMinX;
1430 px.mY := ny+mMinY;
1431 px.mWidth := nw;
1432 px.mHeight := nh;
1433 insertInternal(body);
1434 end
1435 else
1436 begin
1437 px.mX := nx+mMinX;
1438 px.mY := ny+mMinY;
1439 px.mWidth := nw;
1440 px.mHeight := nh;
1441 end;
1442 end;
1444 //TODO: optimize for horizontal/vertical moves
1445 procedure TBodyGridBase.moveBody (body: TBodyProxyId; nx, ny: Integer);
1446 var
1447 px: PBodyProxyRec;
1448 x0, y0: Integer;
1449 ogx0, ogx1, ogy0, ogy1: Integer; // old grid rect
1450 ngx0, ngx1, ngy0, ngy1: Integer; // new grid rect
1451 gx, gy: Integer;
1452 gw, gh: Integer;
1453 pw, ph: Integer;
1454 begin
1455 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1456 // check if tile coords was changed
1457 px := @mProxies[body];
1458 x0 := px.mX;
1459 y0 := px.mY;
1460 if (nx = x0) and (ny = y0) then exit;
1461 // map -> grid
1462 Dec(x0, mMinX);
1463 Dec(y0, mMinY);
1464 Dec(nx, mMinX);
1465 Dec(ny, mMinY);
1466 // check for heavy work
1467 pw := px.mWidth;
1468 ph := px.mHeight;
1469 ogx0 := x0 div mTileSize;
1470 ogy0 := y0 div mTileSize;
1471 ngx0 := nx div mTileSize;
1472 ngy0 := ny div mTileSize;
1473 ogx1 := (x0+pw-1) div mTileSize;
1474 ogy1 := (y0+ph-1) div mTileSize;
1475 ngx1 := (nx+pw-1) div mTileSize;
1476 ngy1 := (ny+ph-1) div mTileSize;
1477 {$IF DEFINED(D2F_DEBUG_MOVER)}
1478 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);
1479 {$ENDIF}
1480 if (ogx0 <> ngx0) or (ogy0 <> ngy0) or (ogx1 <> ngx1) or (ogy1 <> ngy1) then
1481 begin
1482 // crossed tile boundary, do heavy work
1483 gw := mWidth;
1484 gh := mHeight;
1485 // cycle with old rect, remove body where it is necessary
1486 // optimized for horizontal moves
1487 {$IF DEFINED(D2F_DEBUG_MOVER)}
1488 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);
1489 {$ENDIF}
1490 // remove stale marks
1491 if not ((ogy0 >= gh) or (ogy1 < 0)) and
1492 not ((ogx0 >= gw) or (ogx1 < 0)) then
1493 begin
1494 if (ogx0 < 0) then ogx0 := 0;
1495 if (ogy0 < 0) then ogy0 := 0;
1496 if (ogx1 > gw-1) then ogx1 := gw-1;
1497 if (ogy1 > gh-1) then ogy1 := gh-1;
1498 {$IF DEFINED(D2F_DEBUG_MOVER)}
1499 e_WriteLog(Format(' norm og:(%d,%d)-(%d,%d)', [ogx0, ogy0, ogx1, ogy1]), MSG_NOTIFY);
1500 {$ENDIF}
1501 for gx := ogx0 to ogx1 do
1502 begin
1503 if (gx < ngx0) or (gx > ngx1) then
1504 begin
1505 // this column is completely outside of new rect
1506 for gy := ogy0 to ogy1 do
1507 begin
1508 {$IF DEFINED(D2F_DEBUG_MOVER)}
1509 e_WriteLog(Format(' remove0:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1510 {$ENDIF}
1511 remover(gy*gw+gx, body);
1512 end;
1513 end
1514 else
1515 begin
1516 // heavy checks
1517 for gy := ogy0 to ogy1 do
1518 begin
1519 if (gy < ngy0) or (gy > ngy1) then
1520 begin
1521 {$IF DEFINED(D2F_DEBUG_MOVER)}
1522 e_WriteLog(Format(' remove1:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1523 {$ENDIF}
1524 remover(gy*gw+gx, body);
1525 end;
1526 end;
1527 end;
1528 end;
1529 end;
1530 // cycle with new rect, add body where it is necessary
1531 if not ((ngy0 >= gh) or (ngy1 < 0)) and
1532 not ((ngx0 >= gw) or (ngx1 < 0)) then
1533 begin
1534 if (ngx0 < 0) then ngx0 := 0;
1535 if (ngy0 < 0) then ngy0 := 0;
1536 if (ngx1 > gw-1) then ngx1 := gw-1;
1537 if (ngy1 > gh-1) then ngy1 := gh-1;
1538 {$IF DEFINED(D2F_DEBUG_MOVER)}
1539 e_WriteLog(Format(' norm ng:(%d,%d)-(%d,%d)', [ngx0, ngy0, ngx1, ngy1]), MSG_NOTIFY);
1540 {$ENDIF}
1541 for gx := ngx0 to ngx1 do
1542 begin
1543 if (gx < ogx0) or (gx > ogx1) then
1544 begin
1545 // this column is completely outside of old rect
1546 for gy := ngy0 to ngy1 do
1547 begin
1548 {$IF DEFINED(D2F_DEBUG_MOVER)}
1549 e_WriteLog(Format(' insert0:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1550 {$ENDIF}
1551 inserter(gy*gw+gx, body);
1552 end;
1553 end
1554 else
1555 begin
1556 // heavy checks
1557 for gy := ngy0 to ngy1 do
1558 begin
1559 if (gy < ogy0) or (gy > ogy1) then
1560 begin
1561 {$IF DEFINED(D2F_DEBUG_MOVER)}
1562 e_WriteLog(Format(' insert1:(%d,%d)', [gx, gy]), MSG_NOTIFY);
1563 {$ENDIF}
1564 inserter(gy*gw+gx, body);
1565 end;
1566 end;
1567 end;
1568 end;
1569 end;
1570 // done
1571 end
1572 else
1573 begin
1574 {$IF DEFINED(D2F_DEBUG_MOVER)}
1575 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);
1576 {$ENDIF}
1577 end;
1578 // update coordinates
1579 px.mX := nx+mMinX;
1580 px.mY := ny+mMinY;
1581 end;
1583 procedure TBodyGridBase.resizeBody (body: TBodyProxyId; nw, nh: Integer);
1584 var
1585 px: PBodyProxyRec;
1586 x0, y0, w, h: Integer;
1587 begin
1588 if (body < 0) or (body > High(mProxies)) then exit; // just in case
1589 // check if tile coords was changed
1590 px := @mProxies[body];
1591 x0 := px.mX-mMinX;
1592 y0 := px.mY-mMinY;
1593 w := px.mWidth;
1594 h := px.mHeight;
1595 {$IF DEFINED(D2F_DEBUG_MOVER)}
1596 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);
1597 {$ENDIF}
1598 if ((x0+w) div mTileSize <> (x0+nw) div mTileSize) or
1599 ((y0+h) div mTileSize <> (y0+nh) div mTileSize) then
1600 begin
1601 // crossed tile boundary, do heavy work
1602 removeInternal(body);
1603 px.mWidth := nw;
1604 px.mHeight := nh;
1605 insertInternal(body);
1606 end
1607 else
1608 begin
1609 // nothing to do with the grid, just fix size
1610 px.mWidth := nw;
1611 px.mHeight := nh;
1612 end;
1613 end;
1616 // ////////////////////////////////////////////////////////////////////////// //
1617 function TBodyGridBase.atCellInPoint (x, y: Integer): TAtPointEnumerator;
1618 var
1619 ccidx: Integer = -1;
1620 begin
1621 Dec(x, mMinX);
1622 Dec(y, mMinY);
1623 if (x >= 0) and (y >= 0) and (x < mWidth*mTileSize) and (y < mHeight*mTileSize) then ccidx := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
1624 result := TAtPointEnumerator.Create(mCells, ccidx, getProxyById);
1625 end;
1628 // ////////////////////////////////////////////////////////////////////////// //
1629 // no callback: return `true` on the first hit
1630 function TBodyGridBase.forEachAtPoint (x, y: Integer; cb: TGridQueryCB; tagmask: Integer=-1; exittag: PInteger=nil): ITP;
1631 var
1632 f: Integer;
1633 idx, curci: Integer;
1634 cc: PGridCell = nil;
1635 px: PBodyProxyRec;
1636 lq: LongWord;
1637 ptag: Integer;
1638 begin
1639 result := Default(ITP);
1640 if (exittag <> nil) then exittag^ := 0;
1641 tagmask := tagmask and TagFullMask;
1642 if (tagmask = 0) then exit;
1644 {$IF DEFINED(D2F_DEBUG_XXQ)}
1645 if (assigned(cb)) then e_WriteLog(Format('0: grid pointquery: (%d,%d)', [x, y]), MSG_NOTIFY);
1646 {$ENDIF}
1648 // make coords (0,0)-based
1649 Dec(x, mMinX);
1650 Dec(y, mMinY);
1651 if (x < 0) or (y < 0) or (x >= mWidth*mTileSize) or (y >= mHeight*mTileSize) then exit;
1653 curci := mGrid[(y div mTileSize)*mWidth+(x div mTileSize)];
1655 {$IF DEFINED(D2F_DEBUG_XXQ)}
1656 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);
1657 {$ENDIF}
1659 // restore coords
1660 Inc(x, mMinX);
1661 Inc(y, mMinY);
1663 // increase query counter
1664 Inc(mLastQuery);
1665 if (mLastQuery = 0) then
1666 begin
1667 // just in case of overflow
1668 mLastQuery := 1;
1669 for idx := 0 to High(mProxies) do mProxies[idx].mQueryMark := 0;
1670 end;
1671 lq := mLastQuery;
1673 {$IF DEFINED(D2F_DEBUG_XXQ)}
1674 if (assigned(cb)) then e_WriteLog(Format('2: grid pointquery: (%d,%d); lq=%u', [x, y, lq]), MSG_NOTIFY);
1675 {$ENDIF}
1677 while (curci <> -1) do
1678 begin
1679 {$IF DEFINED(D2F_DEBUG_XXQ)}
1680 if (assigned(cb)) then e_WriteLog(Format(' cell #%d', [curci]), MSG_NOTIFY);
1681 {$ENDIF}
1682 cc := @mCells[curci];
1683 for f := 0 to GridCellBucketSize-1 do
1684 begin
1685 if (cc.bodies[f] = -1) then break;
1686 px := @mProxies[cc.bodies[f]];
1687 {$IF DEFINED(D2F_DEBUG_XXQ)}
1688 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);
1689 {$ENDIF}
1690 // shit. has to do it this way, so i can change tag in callback
1691 if (px.mQueryMark <> lq) then
1692 begin
1693 px.mQueryMark := lq;
1694 ptag := px.mTag;
1695 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and
1696 (x >= px.mX) and (y >= px.mY) and (x < px.mX+px.mWidth) and (y < px.mY+px.mHeight) then
1697 begin
1698 if assigned(cb) then
1699 begin
1700 if cb(px.mObj, ptag) then
1701 begin
1702 result := px.mObj;
1703 if (exittag <> nil) then exittag^ := ptag;
1704 exit;
1705 end;
1706 end
1707 else
1708 begin
1709 result := px.mObj;
1710 if (exittag <> nil) then exittag^ := ptag;
1711 exit;
1712 end;
1713 end;
1714 end;
1715 end;
1716 curci := cc.next;
1717 end;
1718 end;
1721 // ////////////////////////////////////////////////////////////////////////// //
1722 // no callback: return `true` on the first hit
1723 function TBodyGridBase.forEachInAABB (x, y, w, h: Integer; cb: TGridQueryCB; tagmask: Integer=-1; allowDisabled: Boolean=false): ITP;
1724 var
1725 idx: Integer;
1726 gx, gy: Integer;
1727 curci: Integer;
1728 f: Integer;
1729 cc: PGridCell = nil;
1730 px: PBodyProxyRec;
1731 lq: LongWord;
1732 gw: Integer;
1733 x0, y0: Integer;
1734 ptag: Integer;
1735 begin
1736 result := Default(ITP);
1737 if (w < 1) or (h < 1) then exit;
1738 tagmask := tagmask and TagFullMask;
1739 if (tagmask = 0) then exit;
1741 x0 := x;
1742 y0 := y;
1744 // fix coords
1745 Dec(x, mMinX);
1746 Dec(y, mMinY);
1748 gw := mWidth;
1749 //tsize := mTileSize;
1751 if (x+w <= 0) or (y+h <= 0) then exit;
1752 if (x >= gw*mTileSize) or (y >= mHeight*mTileSize) then exit;
1754 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1755 mInQuery := true;
1757 // increase query counter
1758 Inc(mLastQuery);
1759 if (mLastQuery = 0) then
1760 begin
1761 // just in case of overflow
1762 mLastQuery := 1;
1763 for idx := 0 to High(mProxies) do mProxies[idx].mQueryMark := 0;
1764 end;
1765 //e_WriteLog(Format('grid: query #%d: (%d,%d)-(%dx%d)', [mLastQuery, minx, miny, maxx, maxy]), MSG_NOTIFY);
1766 lq := mLastQuery;
1768 // go on
1769 for gy := y div mTileSize to (y+h-1) div mTileSize do
1770 begin
1771 if (gy < 0) then continue;
1772 if (gy >= mHeight) then break;
1773 for gx := x div mTileSize to (x+w-1) div mTileSize do
1774 begin
1775 if (gx < 0) then continue;
1776 if (gx >= gw) then break;
1777 // process cells
1778 curci := mGrid[gy*gw+gx];
1779 while (curci <> -1) do
1780 begin
1781 cc := @mCells[curci];
1782 for f := 0 to GridCellBucketSize-1 do
1783 begin
1784 if (cc.bodies[f] = -1) then break;
1785 px := @mProxies[cc.bodies[f]];
1786 // shit. has to do it this way, so i can change tag in callback
1787 if (px.mQueryMark = lq) then continue;
1788 px.mQueryMark := lq;
1789 ptag := px.mTag;
1790 if (not allowDisabled) and ((ptag and TagDisabled) <> 0) then continue;
1791 if ((ptag and tagmask) = 0) then continue;
1792 if (x0 >= px.mX+px.mWidth) or (y0 >= px.mY+px.mHeight) then continue;
1793 if (x0+w <= px.mX) or (y0+h <= px.mY) then continue;
1794 if assigned(cb) then
1795 begin
1796 if cb(px.mObj, ptag) then begin result := px.mObj; mInQuery := false; exit; end;
1797 end
1798 else
1799 begin
1800 result := px.mObj;
1801 mInQuery := false;
1802 exit;
1803 end;
1804 end;
1805 curci := cc.next;
1806 end;
1807 end;
1808 end;
1810 mInQuery := false;
1811 end;
1814 // ////////////////////////////////////////////////////////////////////////// //
1815 function TBodyGridBase.forEachAlongLine (ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1; log: Boolean=false): ITP;
1816 var
1817 lw: TLineWalker;
1818 ccidx: Integer;
1819 cc: PGridCell;
1820 px: PBodyProxyRec;
1821 lq: LongWord;
1822 f, ptag: Integer;
1823 gw, gh, minx, miny: Integer;
1824 x0, y0: Integer;
1825 x1, y1: Integer;
1826 cx, cy: Integer;
1827 //px0, py0, px1, py1: Integer;
1828 begin
1829 log := false;
1830 result := Default(ITP);
1831 tagmask := tagmask and TagFullMask;
1832 if (tagmask = 0) or not assigned(cb) then exit;
1834 gw := mWidth;
1835 gh := mHeight;
1836 minx := mMinX;
1837 miny := mMinY;
1839 // make query coords (0,0)-based
1840 x0 := ax0-minx;
1841 y0 := ay0-miny;
1842 x1 := ax1-minx;
1843 y1 := ay1-miny;
1845 lw := TLineWalker.Create(0, 0, gw*mTileSize-1, gh*mTileSize-1);
1846 if not lw.setup(x0, y0, x1, y1) then exit; // out of screen
1848 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1849 mInQuery := true;
1851 // increase query counter
1852 Inc(mLastQuery);
1853 if (mLastQuery = 0) then
1854 begin
1855 // just in case of overflow
1856 mLastQuery := 1;
1857 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
1858 end;
1859 lq := mLastQuery;
1861 repeat
1862 lw.getXY(cx, cy);
1863 // check tile
1864 ccidx := mGrid[(cy div mTileSize)*gw+(cx div mTileSize)];
1865 // process cells
1866 while (ccidx <> -1) do
1867 begin
1868 cc := @mCells[ccidx];
1869 for f := 0 to GridCellBucketSize-1 do
1870 begin
1871 if (cc.bodies[f] = -1) then break;
1872 px := @mProxies[cc.bodies[f]];
1873 ptag := px.mTag;
1874 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
1875 begin
1876 px.mQueryMark := lq; // mark as processed
1877 if cb(px.mObj, ptag) then
1878 begin
1879 result := px.mObj;
1880 mInQuery := false;
1881 exit;
1882 end;
1883 end;
1884 end;
1885 // next cell
1886 ccidx := cc.next;
1887 end;
1888 // done processing cells, move to next tile
1889 until lw.stepToNextTile();
1891 mInQuery := false;
1892 end;
1895 // ////////////////////////////////////////////////////////////////////////// //
1896 // trace box with the given velocity; return object hit (if any)
1897 // `cb` is used unconvetionally here: if it returns `false`, tracer will ignore the object
1898 function TBodyGridBase.traceBox (out ex, ey: Integer; const ax0, ay0, aw, ah: Integer; const dx, dy: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
1899 var
1900 gx, gy: Integer;
1901 ccidx: Integer;
1902 cc: PGridCell;
1903 px: PBodyProxyRec;
1904 lq: LongWord;
1905 f, ptag: Integer;
1906 minu0: Single = 100000.0;
1907 u0: Single;
1908 cx0, cy0, cx1, cy1: Integer;
1909 hitpx: PBodyProxyRec = nil;
1910 begin
1911 result := Default(ITP);
1912 ex := ax0+dx;
1913 ey := ay0+dy;
1914 if (aw < 1) or (ah < 1) then exit;
1916 cx0 := nmin(ax0, ax0+dx);
1917 cy0 := nmin(ay0, ay0+dy);
1918 cx1 := nmax(ax0+aw-1, ax0+aw-1+dx);
1919 cy1 := nmax(ay0+ah-1, ay0+ah-1+dy);
1921 cx0 -= mMinX; cy0 -= mMinY;
1922 cx1 -= mMinX; cy1 -= mMinY;
1924 if (cx1 < 0) or (cy1 < 0) or (cx0 >= mWidth*mTileSize) or (cy0 >= mHeight*mTileSize) then exit;
1926 if (cx0 < 0) then cx0 := 0;
1927 if (cy0 < 0) then cy0 := 0;
1928 if (cx1 >= mWidth*mTileSize) then cx1 := mWidth*mTileSize-1;
1929 if (cy1 >= mHeight*mTileSize) then cy1 := mHeight*mTileSize-1;
1930 // just in case
1931 if (cx0 > cx1) or (cy0 > cy1) then exit;
1933 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
1934 mInQuery := true;
1936 // increase query counter
1937 Inc(mLastQuery);
1938 if (mLastQuery = 0) then
1939 begin
1940 // just in case of overflow
1941 mLastQuery := 1;
1942 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
1943 end;
1944 lq := mLastQuery;
1946 for gy := cy0 div mTileSize to cy1 div mTileSize do
1947 begin
1948 for gx := cx0 div mTileSize to cx1 div mTileSize do
1949 begin
1950 ccidx := mGrid[gy*mWidth+gx];
1951 while (ccidx <> -1) do
1952 begin
1953 cc := @mCells[ccidx];
1954 for f := 0 to GridCellBucketSize-1 do
1955 begin
1956 if (cc.bodies[f] = -1) then break;
1957 px := @mProxies[cc.bodies[f]];
1958 ptag := px.mTag;
1959 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
1960 begin
1961 px.mQueryMark := lq; // mark as processed
1962 if assigned(cb) then
1963 begin
1964 if not cb(px.mObj, ptag) then continue;
1965 end;
1966 if not sweepAABB(ax0, ay0, aw, ah, dx, dy, px.mX, px.mY, px.mWidth, px.mHeight, @u0) then continue;
1967 if (minu0 > u0) then
1968 begin
1969 hitpx := px;
1970 result := px.mObj;
1971 minu0 := u0;
1972 if (u0 = 0.0) then
1973 begin
1974 ex := ax0;
1975 ey := ay0;
1976 mInQuery := false;
1977 exit;
1978 end;
1979 end;
1980 end;
1981 end;
1982 // next cell
1983 ccidx := cc.next;
1984 end;
1985 end;
1986 end;
1988 if (minu0 <= 1.0) then
1989 begin
1990 ex := ax0+round(dx*minu0);
1991 ey := ay0+round(dy*minu0);
1992 // just in case, compensate for floating point inexactness
1993 if (ex >= hitpx.mX) and (ey >= hitpx.mY) and (ex < hitpx.mX+hitpx.mWidth) and (ey < hitpx.mY+hitpx.mHeight) then
1994 begin
1995 ex := ax0+trunc(dx*minu0);
1996 ey := ay0+trunc(dy*minu0);
1997 end;
1998 end;
2000 mInQuery := false;
2001 end;
2004 // ////////////////////////////////////////////////////////////////////////// //
2005 {.$DEFINE D2F_DEBUG_OTR}
2006 function TBodyGridBase.traceOrthoRayWhileIn (out ex, ey: Integer; ax0, ay0, ax1, ay1: Integer; tagmask: Integer=-1): Boolean;
2007 var
2008 ccidx: Integer;
2009 cc: PGridCell;
2010 px: PBodyProxyRec;
2011 ptag: Integer;
2012 minx, miny: Integer;
2013 f, c0, c1: Integer;
2014 x0, y0, x1, y1: Integer;
2015 celly0, celly1: Integer;
2016 dy: Integer;
2017 filled: array[0..mTileSize-1] of Byte;
2018 {$IF DEFINED(D2F_DEBUG_OTR)}
2019 s: AnsiString = '';
2020 {$ENDIF}
2021 begin
2022 result := false;
2023 ex := ax1;
2024 ey := ay1;
2025 if not ((ax0 = ax1) or (ay0 = ay1)) then raise Exception.Create('orthoray is not orthogonal');
2027 tagmask := tagmask and TagFullMask;
2028 if (tagmask = 0) then exit;
2030 if (forEachAtPoint(ax0, ay0, nil, tagmask) = nil) then exit;
2032 minx := mMinX;
2033 miny := mMinY;
2035 // offset query coords to (0,0)-based
2036 x0 := ax0-minx;
2037 y0 := ay0-miny;
2038 x1 := ax1-minx;
2039 y1 := ay1-miny;
2041 if (x0 = x1) then
2042 begin
2043 if (x0 < 0) or (x0 >= mWidth*mTileSize) then exit; // oops
2044 // vertical
2045 if (y0 < y1) then
2046 begin
2047 // down
2048 if (y1 < 0) or (y0 >= mHeight*mTileSize) then exit;
2049 //if (ay0 < 0) then ay0 := 0;
2050 if (y0 < 0) then exit;
2051 if (y1 >= mHeight*mTileSize) then y1 := mHeight*mTileSize-1;
2052 dy := 1;
2053 end
2054 else
2055 begin
2056 // up
2057 if (y0 < 0) or (y1 >= mHeight*mTileSize) then exit;
2058 //if (ay1 < 0) then ay1 := 0;
2059 if (y1 < 0) then exit;
2060 if (y0 >= mHeight*mTileSize) then y0 := mHeight*mTileSize-1;
2061 dy := -1;
2062 end;
2063 // check tile
2064 while true do
2065 begin
2066 ccidx := mGrid[(y0 div mTileSize)*mWidth+(x0 div mTileSize)];
2067 FillChar(filled, sizeof(filled), 0);
2068 celly0 := y0 and (not (mTileSize-1));
2069 celly1 := celly0+mTileSize-1;
2070 while (ccidx <> -1) do
2071 begin
2072 cc := @mCells[ccidx];
2073 for f := 0 to GridCellBucketSize-1 do
2074 begin
2075 if (cc.bodies[f] = -1) then break;
2076 px := @mProxies[cc.bodies[f]];
2077 ptag := px.mTag;
2078 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and
2079 (ax0 >= px.x0) and (ax0 <= px.x1) then
2080 begin
2081 // bound c0 and c1 to cell
2082 c0 := nclamp(px.y0-miny, celly0, celly1);
2083 c1 := nclamp(px.y1-miny, celly0, celly1);
2084 // fill the thing
2085 {$IF DEFINED(D2F_DEBUG_OTR)}
2086 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)]);
2087 {$ENDIF}
2088 //assert(c0 <= c1);
2089 FillChar(filled[c0-celly0], c1-c0+1, 1);
2090 end;
2091 end;
2092 // next cell
2093 ccidx := cc.next;
2094 end;
2095 {$IF DEFINED(D2F_DEBUG_OTR)}
2096 s := formatstrf(' x=%s; ay0=%s; ay1=%s; y0=%s; celly0=%s; celly1=%s; dy=%s; [', [ax0, ay0, ay1, y0, celly0, celly1, dy]);
2097 for f := 0 to High(filled) do if (filled[f] <> 0) then s += '1' else s += '0';
2098 s += ']';
2099 e_LogWriteln(s);
2100 {$ENDIF}
2101 // now go till we hit cell boundary or empty space
2102 if (dy < 0) then
2103 begin
2104 // up
2105 while (y0 >= celly0) and (filled[y0-celly0] <> 0) do
2106 begin
2107 {$IF DEFINED(D2F_DEBUG_OTR)}
2108 e_LogWritefln(' filled: cdy=%s; y0=%s; celly0=%s; ay0=%s; ay1=%s', [y0-celly0, y0, celly0, ay0, ay1]);
2109 {$ENDIF}
2110 Dec(y0);
2111 Dec(ay0);
2112 end;
2113 {$IF DEFINED(D2F_DEBUG_OTR)}
2114 e_LogWritefln(' span done: cdy=%s; y0=%s; celly0=%s; ay0=%s; ay1=%s', [y0-celly0, y0, celly0, ay0, ay1]);
2115 {$ENDIF}
2116 if (ay0 <= ay1) then begin ey := ay1; result := false; exit; end;
2117 if (y0 >= celly0) then begin ey := ay0+1; {assert(forEachAtPoint(ex, ey, nil, tagmask) <> nil);} result := true; exit; end;
2118 end
2119 else
2120 begin
2121 // down
2122 while (y0 <= celly1) and (filled[y0-celly0] <> 0) do begin Inc(y0); Inc(ay0); end;
2123 if (ay0 >= ay1) then begin ey := ay1; result := false; exit; end;
2124 if (y0 <= celly1) then begin ey := ay0-1; result := true; exit; end;
2125 end;
2126 end;
2127 end
2128 else
2129 begin
2130 // horizontal
2131 assert(false);
2132 end;
2133 end;
2136 // ////////////////////////////////////////////////////////////////////////// //
2137 function TBodyGridBase.traceRay (const x0, y0, x1, y1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
2138 var
2139 ex, ey: Integer;
2140 begin
2141 result := traceRay(ex, ey, x0, y0, x1, y1, cb, tagmask);
2142 end;
2145 // no callback: return `true` on the nearest hit
2146 // you are not supposed to understand this
2147 function TBodyGridBase.traceRay (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridQueryCB; tagmask: Integer=-1): ITP;
2148 var
2149 lw, sweepw: TLineWalker;
2150 ccidx: Integer;
2151 cc: PGridCell;
2152 px: PBodyProxyRec;
2153 lq: LongWord;
2154 f, ptag: Integer;
2155 gw, gh, minx, miny: Integer;
2156 x0, y0: Integer;
2157 x1, y1: Integer;
2158 cx, cy: Integer;
2159 px0, py0, px1, py1: Integer;
2160 lastDistSq, distSq, hx, hy: Integer;
2161 firstCell: Boolean = true;
2162 wasHit: Boolean;
2163 begin
2164 result := Default(ITP);
2165 tagmask := tagmask and TagFullMask;
2166 if (tagmask = 0) then exit;
2168 gw := mWidth;
2169 gh := mHeight;
2170 minx := mMinX;
2171 miny := mMinY;
2173 // make query coords (0,0)-based
2174 x0 := ax0-minx;
2175 y0 := ay0-miny;
2176 x1 := ax1-minx;
2177 y1 := ay1-miny;
2179 lw := TLineWalker.Create(0, 0, gw*mTileSize-1, gh*mTileSize-1);
2180 if not lw.setup(x0, y0, x1, y1) then exit; // out of screen
2182 sweepw := TLineWalker.Create(0, 0, 1, 1); // doesn't matter, just shut ups the compiler
2184 lastDistSq := distanceSq(ax0, ay0, ax1, ay1)+1;
2186 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
2187 mInQuery := true;
2189 // increase query counter
2190 Inc(mLastQuery);
2191 if (mLastQuery = 0) then
2192 begin
2193 // just in case of overflow
2194 mLastQuery := 1;
2195 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
2196 end;
2197 lq := mLastQuery;
2199 repeat
2200 lw.getXY(cx, cy);
2201 // check tile
2202 ccidx := mGrid[(cy div mTileSize)*gw+(cx div mTileSize)];
2203 // process cells
2204 wasHit := false;
2205 while (ccidx <> -1) do
2206 begin
2207 cc := @mCells[ccidx];
2208 for f := 0 to GridCellBucketSize-1 do
2209 begin
2210 if (cc.bodies[f] = -1) then break;
2211 px := @mProxies[cc.bodies[f]];
2212 ptag := px.mTag;
2213 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2214 begin
2215 px.mQueryMark := lq; // mark as processed
2216 if assigned(cb) then
2217 begin
2218 if not cb(px.mObj, ptag) then continue;
2219 end;
2220 // get adjusted proxy coords
2221 px0 := px.mX-minx;
2222 py0 := px.mY-miny;
2223 px1 := px0+px.mWidth-1;
2224 py1 := py0+px.mHeight-1;
2225 // inside?
2226 if firstCell and (x0 >= px0) and (y0 >= py0) and (x0 <= px1) and (y0 <= py1) then
2227 begin
2228 // oops
2229 ex := ax0;
2230 ey := ay0;
2231 result := px.mObj;
2232 mInQuery := false;
2233 exit;
2234 end;
2235 // do line-vs-aabb test
2236 sweepw.setClip(px0, py0, px1, py1);
2237 if sweepw.setup(x0, y0, x1, y1) then
2238 begin
2239 // hit detected
2240 sweepw.getPrevXY(hx, hy);
2241 distSq := distanceSq(x0, y0, hx, hy);
2242 if (distSq < lastDistSq) then
2243 begin
2244 lastDistSq := distSq;
2245 ex := hx+minx;
2246 ey := hy+miny;
2247 result := px.mObj;
2248 // if this is not a first cell, get outta here
2249 if not firstCell then begin mInQuery := false; exit; end;
2250 wasHit := true;
2251 end;
2252 end;
2253 end;
2254 end;
2255 // next cell
2256 ccidx := cc.next;
2257 end;
2258 // done processing cells; exit if we registered a hit
2259 // next cells can't have better candidates, obviously
2260 if wasHit then begin mInQuery := false; exit; end;
2261 firstCell := false;
2262 // move to next tile
2263 until lw.stepToNextTile();
2265 mInQuery := false;
2266 end;
2269 // ////////////////////////////////////////////////////////////////////////// //
2270 // no callback: return `true` on the nearest hit
2271 function TBodyGridBase.traceRayOld (const x0, y0, x1, y1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
2272 var
2273 ex, ey: Integer;
2274 begin
2275 result := traceRayOld(ex, ey, x0, y0, x1, y1, cb, tagmask);
2276 end;
2279 // no callback: return `true` on the nearest hit
2280 // you are not supposed to understand this
2281 function TBodyGridBase.traceRayOld (out ex, ey: Integer; const ax0, ay0, ax1, ay1: Integer; cb: TGridRayQueryCB; tagmask: Integer=-1): ITP;
2282 var
2283 wx0, wy0, wx1, wy1: Integer; // window coordinates
2284 stx, sty: Integer; // "steps" for x and y axes
2285 dsx, dsy: Integer; // "lengthes" for x and y axes
2286 dx2, dy2: Integer; // "double lengthes" for x and y axes
2287 xd, yd: Integer; // current coord
2288 e: Integer; // "error" (as in bresenham algo)
2289 rem: Integer;
2290 term: Integer;
2291 xptr, yptr: PInteger;
2292 xfixed: Boolean;
2293 temp: Integer;
2294 prevx, prevy: Integer;
2295 lastDistSq: Integer;
2296 ccidx, curci: Integer;
2297 hasUntried: Boolean;
2298 lastGA: Integer = -1;
2299 ga, x, y: Integer;
2300 lastObj: ITP;
2301 wasHit: Boolean = false;
2302 gw, gh, minx, miny, maxx, maxy: Integer;
2303 cc: PGridCell;
2304 px: PBodyProxyRec;
2305 lq: LongWord;
2306 f, ptag, distSq: Integer;
2307 x0, y0, x1, y1: Integer;
2308 //swapped: Boolean = false; // true: xd is yd, and vice versa
2309 // horizontal walker
2310 {$IFDEF GRID_USE_ORTHO_ACCEL}
2311 wklen, wkstep: Integer;
2312 //wksign: Integer;
2313 hopt: Boolean;
2314 {$ENDIF}
2315 // skipper
2316 xdist, ydist: Integer;
2317 begin
2318 result := Default(ITP);
2319 lastObj := Default(ITP);
2320 tagmask := tagmask and TagFullMask;
2321 ex := ax1; // why not?
2322 ey := ay1; // why not?
2323 if (tagmask = 0) then exit;
2325 if (ax0 = ax1) and (ay0 = ay1) then
2326 begin
2327 result := forEachAtPoint(ax0, ay0, nil, tagmask, @ptag);
2328 if (result <> nil) then
2329 begin
2330 if assigned(cb) and not cb(result, ptag, ax0, ay0, ax0, ay0) then result := Default(ITP);
2331 end;
2332 exit;
2333 end;
2335 lastDistSq := distanceSq(ax0, ay0, ax1, ay1)+1;
2337 gw := mWidth;
2338 gh := mHeight;
2339 minx := mMinX;
2340 miny := mMinY;
2341 maxx := gw*mTileSize-1;
2342 maxy := gh*mTileSize-1;
2344 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2345 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);
2346 {$ENDIF}
2348 x0 := ax0;
2349 y0 := ay0;
2350 x1 := ax1;
2351 y1 := ay1;
2353 // offset query coords to (0,0)-based
2354 Dec(x0, minx);
2355 Dec(y0, miny);
2356 Dec(x1, minx);
2357 Dec(y1, miny);
2359 // clip rectange
2360 wx0 := 0;
2361 wy0 := 0;
2362 wx1 := maxx;
2363 wy1 := maxy;
2365 // horizontal setup
2366 if (x0 < x1) then
2367 begin
2368 // from left to right
2369 if (x0 > wx1) or (x1 < wx0) then exit; // out of screen
2370 stx := 1; // going right
2371 end
2372 else
2373 begin
2374 // from right to left
2375 if (x1 > wx1) or (x0 < wx0) then exit; // out of screen
2376 stx := -1; // going left
2377 x0 := -x0;
2378 x1 := -x1;
2379 wx0 := -wx0;
2380 wx1 := -wx1;
2381 swapInt(wx0, wx1);
2382 end;
2384 // vertical setup
2385 if (y0 < y1) then
2386 begin
2387 // from top to bottom
2388 if (y0 > wy1) or (y1 < wy0) then exit; // out of screen
2389 sty := 1; // going down
2390 end
2391 else
2392 begin
2393 // from bottom to top
2394 if (y1 > wy1) or (y0 < wy0) then exit; // out of screen
2395 sty := -1; // going up
2396 y0 := -y0;
2397 y1 := -y1;
2398 wy0 := -wy0;
2399 wy1 := -wy1;
2400 swapInt(wy0, wy1);
2401 end;
2403 dsx := x1-x0;
2404 dsy := y1-y0;
2406 if (dsx < dsy) then
2407 begin
2408 //swapped := true;
2409 xptr := @yd;
2410 yptr := @xd;
2411 swapInt(x0, y0);
2412 swapInt(x1, y1);
2413 swapInt(dsx, dsy);
2414 swapInt(wx0, wy0);
2415 swapInt(wx1, wy1);
2416 swapInt(stx, sty);
2417 end
2418 else
2419 begin
2420 xptr := @xd;
2421 yptr := @yd;
2422 end;
2424 dx2 := 2*dsx;
2425 dy2 := 2*dsy;
2426 xd := x0;
2427 yd := y0;
2428 e := 2*dsy-dsx;
2429 term := x1;
2431 xfixed := false;
2432 if (y0 < wy0) then
2433 begin
2434 // clip at top
2435 temp := dx2*(wy0-y0)-dsx;
2436 xd += temp div dy2;
2437 rem := temp mod dy2;
2438 if (xd > wx1) then exit; // x is moved out of clipping rect, nothing to do
2439 if (xd+1 >= wx0) then
2440 begin
2441 yd := wy0;
2442 e -= rem+dsx;
2443 //if (rem > 0) then begin Inc(xd); e += dy2; end; //BUGGY
2444 if (xd < wx0) then begin xd += 1; e += dy2; end; //???
2445 xfixed := true;
2446 end;
2447 end;
2449 if (not xfixed) and (x0 < wx0) then
2450 begin
2451 // clip at left
2452 temp := dy2*(wx0-x0);
2453 yd += temp div dx2;
2454 rem := temp mod dx2;
2455 if (yd > wy1) or (yd = wy1) and (rem >= dsx) then exit;
2456 xd := wx0;
2457 e += rem;
2458 if (rem >= dsx) then begin Inc(yd); e -= dx2; end;
2459 end;
2461 if (y1 > wy1) then
2462 begin
2463 // clip at bottom
2464 temp := dx2*(wy1-y0)+dsx;
2465 term := x0+temp div dy2;
2466 rem := temp mod dy2;
2467 if (rem = 0) then Dec(term);
2468 end;
2470 if (term > wx1) then term := wx1; // clip at right
2472 Inc(term); // draw last point
2473 //if (term = xd) then exit; // this is the only point, get out of here
2475 if (sty = -1) then yd := -yd;
2476 if (stx = -1) then begin xd := -xd; term := -term; end;
2477 dx2 -= dy2;
2479 // first move, to skip starting point
2480 // DON'T DO THIS! loop will take care of that
2481 if (xd = term) then
2482 begin
2483 //FIXME!
2484 result := forEachAtPoint(ax0, ay0, nil, tagmask, @ptag);
2485 if (result <> nil) then
2486 begin
2487 if assigned(cb) then
2488 begin
2489 if cb(result, ptag, ax0, ay0, ax0, ay0) then
2490 begin
2491 ex := ax0;
2492 ey := ay0;
2493 end
2494 else
2495 begin
2496 result := nil;
2497 end;
2498 end
2499 else
2500 begin
2501 ex := ax0;
2502 ey := ay0;
2503 end;
2504 end;
2505 exit;
2506 end;
2508 prevx := xptr^+minx;
2509 prevy := yptr^+miny;
2510 (*
2511 // move coords
2512 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2513 xd += stx;
2514 // done?
2515 if (xd = term) then exit;
2516 *)
2518 {$IF DEFINED(D2F_DEBUG)}
2519 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*mTileSize) and (yptr^ >= gh*mTileSize) then raise Exception.Create('raycaster internal error (0)');
2520 {$ENDIF}
2521 // DON'T DO THIS! loop will take care of that
2522 //lastGA := (yptr^ div tsize)*gw+(xptr^ div tsize);
2523 //ccidx := mGrid[lastGA];
2525 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2526 //if assigned(dbgRayTraceTileHitCB) then e_WriteLog('1:TRACING!', MSG_NOTIFY);
2527 {$ENDIF}
2529 //if (dbgShowTraceLog) then e_WriteLog(Format('raycast start: (%d,%d)-(%d,%d); xptr^=%d; yptr^=%d', [ax0, ay0, ax1, ay1, xptr^, yptr^]), MSG_NOTIFY);
2531 if mInQuery then raise Exception.Create('recursive queries aren''t supported');
2532 mInQuery := true;
2534 // increase query counter
2535 Inc(mLastQuery);
2536 if (mLastQuery = 0) then
2537 begin
2538 // just in case of overflow
2539 mLastQuery := 1;
2540 for f := 0 to High(mProxies) do mProxies[f].mQueryMark := 0;
2541 end;
2542 lq := mLastQuery;
2544 {$IFDEF GRID_USE_ORTHO_ACCEL}
2545 // if this is strict horizontal/vertical trace, use optimized codepath
2546 if (ax0 = ax1) or (ay0 = ay1) then
2547 begin
2548 // horizontal trace: walk the whole tiles, calculating mindist once for each proxy in cell
2549 // stx < 0: going left, otherwise `stx` is > 0, and we're going right
2550 // vertical trace: walk the whole tiles, calculating mindist once for each proxy in cell
2551 // stx < 0: going up, otherwise `stx` is > 0, and we're going down
2552 hopt := (ay0 = ay1); // horizontal?
2553 if (stx < 0) then begin {wksign := -1;} wklen := -(term-xd); end else begin {wksign := 1;} wklen := term-xd; end;
2554 {$IF DEFINED(D2F_DEBUG)}
2555 if dbgShowTraceLog then e_LogWritefln('optimized htrace; wklen=%d', [wklen]);
2556 {$ENDIF}
2557 ga := (yptr^ div mTileSize)*gw+(xptr^ div mTileSize);
2558 // one of those will never change
2559 x := xptr^+minx;
2560 y := yptr^+miny;
2561 while (wklen > 0) do
2562 begin
2563 {$IF DEFINED(D2F_DEBUG)}
2564 if dbgShowTraceLog then e_LogWritefln(' htrace; ga=%d; x=%d, y=%d; y=%d; y=%d', [ga, xptr^+minx, yptr^+miny, y, ay0]);
2565 {$ENDIF}
2566 // new tile?
2567 if (ga <> lastGA) then
2568 begin
2569 lastGA := ga;
2570 ccidx := mGrid[lastGA];
2571 // convert coords to map (to avoid ajdusting coords inside the loop)
2572 if hopt then x := xptr^+minx else y := yptr^+miny;
2573 while (ccidx <> -1) do
2574 begin
2575 cc := @mCells[ccidx];
2576 for f := 0 to GridCellBucketSize-1 do
2577 begin
2578 if (cc.bodies[f] = -1) then break;
2579 px := @mProxies[cc.bodies[f]];
2580 ptag := px.mTag;
2581 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) and
2582 // constant coord should be inside
2583 ((hopt and (y >= px.y0) and (y <= px.y1)) or
2584 ((not hopt) and (x >= px.x0) and (x <= px.x1))) then
2585 begin
2586 px.mQueryMark := lq; // mark as processed
2587 // inside the proxy?
2588 if (hopt and (x > px.x0) and (x < px.x1)) or
2589 ((not hopt) and (y > px.y0) and (y < px.y1)) then
2590 begin
2591 // setup prev[xy]
2592 if assigned(cb) then
2593 begin
2594 if cb(px.mObj, ptag, x, y, x, y) then
2595 begin
2596 result := px.mObj;
2597 ex := x;
2598 ey := y;
2599 mInQuery := false;
2600 exit;
2601 end;
2602 end
2603 else
2604 begin
2605 distSq := distanceSq(ax0, ay0, x, y);
2606 {$IF DEFINED(D2F_DEBUG)}
2607 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]);
2608 {$ENDIF}
2609 if (distSq < lastDistSq) then
2610 begin
2611 ex := x;
2612 ey := y;
2613 result := px.mObj;
2614 mInQuery := false;
2615 exit;
2616 end;
2617 end;
2618 continue;
2619 end;
2620 // remember this hitpoint if it is nearer than an old one
2621 // setup prev[xy]
2622 if hopt then
2623 begin
2624 // horizontal trace
2625 prevy := y;
2626 y := yptr^+miny;
2627 if (stx < 0) then
2628 begin
2629 // going left
2630 if (x < px.x1) then continue; // not on the right edge
2631 x := px.x1;
2632 prevx := x+1;
2633 end
2634 else
2635 begin
2636 // going right
2637 if (x > px.x0) then continue; // not on the left edge
2638 x := px.x0;
2639 prevx := x-1;
2640 end;
2641 end
2642 else
2643 begin
2644 // vertical trace
2645 prevx := x;
2646 x := xptr^+minx;
2647 if (stx < 0) then
2648 begin
2649 // going up
2650 if (y < px.y1) then continue; // not on the bottom edge
2651 y := px.y1;
2652 prevy := x+1;
2653 end
2654 else
2655 begin
2656 // going down
2657 if (y > px.y0) then continue; // not on the top edge
2658 y := px.y0;
2659 prevy := y-1;
2660 end;
2661 end;
2662 if assigned(cb) then
2663 begin
2664 if cb(px.mObj, ptag, x, y, prevx, prevy) then
2665 begin
2666 result := px.mObj;
2667 ex := prevx;
2668 ey := prevy;
2669 mInQuery := false;
2670 exit;
2671 end;
2672 end
2673 else
2674 begin
2675 distSq := distanceSq(ax0, ay0, prevx, prevy);
2676 {$IF DEFINED(D2F_DEBUG)}
2677 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]);
2678 {$ENDIF}
2679 if (distSq < lastDistSq) then
2680 begin
2681 wasHit := true;
2682 lastDistSq := distSq;
2683 ex := prevx;
2684 ey := prevy;
2685 lastObj := px.mObj;
2686 end;
2687 end;
2688 end;
2689 end;
2690 // next cell
2691 ccidx := cc.next;
2692 end;
2693 if wasHit and not assigned(cb) then begin result := lastObj; mInQuery := false; exit; end;
2694 if assigned(cb) and cb(nil, 0, x, y, x, y) then begin result := lastObj; mInQuery := false; exit; end;
2695 end;
2696 // skip to next tile
2697 if hopt then
2698 begin
2699 if (stx > 0) then
2700 begin
2701 // to the right
2702 wkstep := ((xptr^ or (mTileSize-1))+1)-xptr^;
2703 {$IF DEFINED(D2F_DEBUG)}
2704 if dbgShowTraceLog then e_LogWritefln(' right step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2705 {$ENDIF}
2706 if (wkstep >= wklen) then break;
2707 Inc(xptr^, wkstep);
2708 Inc(ga);
2709 end
2710 else
2711 begin
2712 // to the left
2713 wkstep := xptr^-((xptr^ and (not (mTileSize-1)))-1);
2714 {$IF DEFINED(D2F_DEBUG)}
2715 if dbgShowTraceLog then e_LogWritefln(' left step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2716 {$ENDIF}
2717 if (wkstep >= wklen) then break;
2718 Dec(xptr^, wkstep);
2719 Dec(ga);
2720 end;
2721 end
2722 else
2723 begin
2724 if (stx > 0) then
2725 begin
2726 // to the down
2727 wkstep := ((yptr^ or (mTileSize-1))+1)-yptr^;
2728 {$IF DEFINED(D2F_DEBUG)}
2729 if dbgShowTraceLog then e_LogWritefln(' down step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2730 {$ENDIF}
2731 if (wkstep >= wklen) then break;
2732 Inc(yptr^, wkstep);
2733 Inc(ga, mWidth);
2734 end
2735 else
2736 begin
2737 // to the up
2738 wkstep := yptr^-((yptr^ and (not (mTileSize-1)))-1);
2739 {$IF DEFINED(D2F_DEBUG)}
2740 if dbgShowTraceLog then e_LogWritefln(' up step: wklen=%d; wkstep=%d', [wklen, wkstep]);
2741 {$ENDIF}
2742 if (wkstep >= wklen) then break;
2743 Dec(yptr^, wkstep);
2744 Dec(ga, mWidth);
2745 end;
2746 end;
2747 Dec(wklen, wkstep);
2748 end;
2749 // we can travel less than one cell
2750 if wasHit and not assigned(cb) then result := lastObj else begin ex := ax1; ey := ay1; end;
2751 mInQuery := false;
2752 exit;
2753 end;
2754 {$ENDIF}
2756 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2757 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div mTileSize*mTileSize)+minx, (yptr^ div mTileSize*mTileSize)+miny);
2758 {$ENDIF}
2760 //e_LogWritefln('*********************', []);
2761 ccidx := -1;
2762 // can omit checks
2763 while (xd <> term) do
2764 begin
2765 // check cell(s)
2766 {$IF DEFINED(D2F_DEBUG)}
2767 if (xptr^ < 0) or (yptr^ < 0) or (xptr^ >= gw*mTileSize) and (yptr^ >= gh*mTileSize) then raise Exception.Create('raycaster internal error (0)');
2768 {$ENDIF}
2769 // new tile?
2770 ga := (yptr^ div mTileSize)*gw+(xptr^ div mTileSize);
2771 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2772 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);
2773 {$ENDIF}
2774 if (ga <> lastGA) then
2775 begin
2776 // yes
2777 {$IF DEFINED(D2F_DEBUG)}
2778 if assigned(dbgRayTraceTileHitCB) then dbgRayTraceTileHitCB((xptr^ div mTileSize*mTileSize)+minx, (yptr^ div mTileSize*mTileSize)+miny);
2779 {$ENDIF}
2780 if (ccidx <> -1) then
2781 begin
2782 // signal cell completion
2783 if assigned(cb) then
2784 begin
2785 if cb(nil, 0, xptr^+minx, yptr^+miny, prevx, prevy) then begin result := lastObj; mInQuery := false; exit; end;
2786 end
2787 else if wasHit then
2788 begin
2789 result := lastObj;
2790 mInQuery := false;
2791 exit;
2792 end;
2793 end;
2794 lastGA := ga;
2795 ccidx := mGrid[lastGA];
2796 end;
2797 // has something to process in this tile?
2798 if (ccidx <> -1) then
2799 begin
2800 // process cell
2801 curci := ccidx;
2802 hasUntried := false; // this will be set to `true` if we have some proxies we still want to process at the next step
2803 // convert coords to map (to avoid ajdusting coords inside the loop)
2804 x := xptr^+minx;
2805 y := yptr^+miny;
2806 // process cell list
2807 while (curci <> -1) do
2808 begin
2809 cc := @mCells[curci];
2810 for f := 0 to GridCellBucketSize-1 do
2811 begin
2812 if (cc.bodies[f] = -1) then break;
2813 px := @mProxies[cc.bodies[f]];
2814 ptag := px.mTag;
2815 if ((ptag and TagDisabled) = 0) and ((ptag and tagmask) <> 0) and (px.mQueryMark <> lq) then
2816 begin
2817 // can we process this proxy?
2818 if (x >= px.mX) and (y >= px.mY) and (x < px.mX+px.mWidth) and (y < px.mY+px.mHeight) then
2819 begin
2820 px.mQueryMark := lq; // mark as processed
2821 if assigned(cb) then
2822 begin
2823 if cb(px.mObj, ptag, x, y, prevx, prevy) then
2824 begin
2825 result := px.mObj;
2826 ex := prevx;
2827 ey := prevy;
2828 mInQuery := false;
2829 exit;
2830 end;
2831 end
2832 else
2833 begin
2834 // remember this hitpoint if it is nearer than an old one
2835 distSq := distanceSq(ax0, ay0, prevx, prevy);
2836 {$IF DEFINED(D2F_DEBUG_RAYTRACE)}
2837 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);
2838 {$ENDIF}
2839 if (distSq < lastDistSq) then
2840 begin
2841 wasHit := true;
2842 lastDistSq := distSq;
2843 ex := prevx;
2844 ey := prevy;
2845 lastObj := px.mObj;
2846 end;
2847 end;
2848 end
2849 else
2850 begin
2851 // this is possibly interesting proxy, set "has more to check" flag
2852 hasUntried := true;
2853 end;
2854 end;
2855 end;
2856 // next cell
2857 curci := cc.next;
2858 end;
2859 // still has something interesting in this cell?
2860 if not hasUntried then
2861 begin
2862 // nope, don't process this cell anymore; signal cell completion
2863 ccidx := -1;
2864 if assigned(cb) then
2865 begin
2866 if cb(nil, 0, x, y, prevx, prevy) then begin result := lastObj; mInQuery := false; exit; end;
2867 end
2868 else if wasHit then
2869 begin
2870 result := lastObj;
2871 mInQuery := false;
2872 exit;
2873 end;
2874 end;
2875 end;
2876 if (ccidx = -1) then
2877 begin
2878 // move to cell edge, as we have nothing to trace here anymore
2879 if (stx < 0) then xdist := xd and (not (mTileSize-1)) else xdist := xd or (mTileSize-1);
2880 if (sty < 0) then ydist := yd and (not (mTileSize-1)) else ydist := yd or (mTileSize-1);
2881 //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]);
2882 while (xd <> xdist) and (yd <> ydist) do
2883 begin
2884 // step
2885 xd += stx;
2886 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2887 //e_LogWritefln(' xd=%d; yd=%d', [xd, yd]);
2888 if (xd = term) then break;
2889 end;
2890 //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]);
2891 if (xd = term) then break;
2892 end;
2893 //putPixel(xptr^, yptr^);
2894 // move coords
2895 prevx := xptr^+minx;
2896 prevy := yptr^+miny;
2897 if (e >= 0) then begin yd += sty; e -= dx2; end else e += dy2;
2898 xd += stx;
2899 end;
2900 // we can travel less than one cell
2901 if wasHit and not assigned(cb) then
2902 begin
2903 result := lastObj;
2904 end
2905 else
2906 begin
2907 ex := ax1; // why not?
2908 ey := ay1; // why not?
2909 end;
2911 mInQuery := false;
2912 end;
2915 end.