DEADSOFTWARE

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