@flighthq/spatial 0.3.0-next.906.07cea63 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,5 @@
1
+ export * from './explainSpatialIndexing';
2
+ export * from './formatSpatialIndexingNotice';
1
3
  export * from './spatialIndex';
2
4
  export * from './uniformGrid';
3
5
  //# sourceMappingURL=contract.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../src/contract.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,eAAe,CAAC"}
1
+ {"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../src/contract.ts"],"names":[],"mappings":"AAAA,cAAc,0BAA0B,CAAC;AACzC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,eAAe,CAAC"}
package/dist/contract.js CHANGED
@@ -1,3 +1,5 @@
1
+ export * from './explainSpatialIndexing';
2
+ export * from './formatSpatialIndexingNotice';
1
3
  export * from './spatialIndex';
2
4
  export * from './uniformGrid';
3
5
  //# sourceMappingURL=contract.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"contract.js","sourceRoot":"","sources":["../src/contract.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,eAAe,CAAC"}
1
+ {"version":3,"file":"contract.js","sourceRoot":"","sources":["../src/contract.ts"],"names":[],"mappings":"AAAA,cAAc,0BAA0B,CAAC;AACzC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,gBAAgB,CAAC;AAC/B,cAAc,eAAe,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { SpatialIndex, SpatialIndexingExplanation, SpatialObjectId } from '@flighthq/types/contract';
2
+ export declare function explainSpatialIndexing(index: Readonly<SpatialIndex>, id: SpatialObjectId): SpatialIndexingExplanation;
3
+ //# sourceMappingURL=explainSpatialIndexing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"explainSpatialIndexing.d.ts","sourceRoot":"","sources":["../src/explainSpatialIndexing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,0BAA0B,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAY1G,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,QAAQ,CAAC,YAAY,CAAC,EAAE,EAAE,EAAE,eAAe,GAAG,0BAA0B,CAErH"}
@@ -0,0 +1,14 @@
1
+ // Reports how the index is currently holding `id`, as plain data. Pure: reads only, indexes nothing,
2
+ // never throws on an unknown id, and retains no reference to the backend. Import it to answer "why is
3
+ // this object not in my query results?" — `absent` means it was never inserted or was removed,
4
+ // `declined` means its bounds were non-finite or inverted and it is deliberately not held, `overflow`
5
+ // means it is held but cannot be usefully bucketed, and `cells` reports the bucket count the
6
+ // per-object bound caps.
7
+ //
8
+ // This is the pull half of the diagnostics convention, and the measurement seam a regression test
9
+ // asserts the cost bound against: `bucketCount` is the number that goes unbounded when the bound is
10
+ // removed, so a test can pin it without timing anything.
11
+ export function explainSpatialIndexing(index, id) {
12
+ return index.runtime.backend.explainSpatialIndexing(id);
13
+ }
14
+ //# sourceMappingURL=explainSpatialIndexing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"explainSpatialIndexing.js","sourceRoot":"","sources":["../src/explainSpatialIndexing.ts"],"names":[],"mappings":"AAEA,qGAAqG;AACrG,sGAAsG;AACtG,+FAA+F;AAC/F,sGAAsG;AACtG,6FAA6F;AAC7F,yBAAyB;AACzB,EAAE;AACF,kGAAkG;AAClG,oGAAoG;AACpG,yDAAyD;AACzD,MAAM,UAAU,sBAAsB,CAAC,KAA6B,EAAE,EAAmB;IACvF,OAAO,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,sBAAsB,CAAC,EAAE,CAAC,CAAC;AAC1D,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { SpatialIndexingNotice } from '@flighthq/types/contract';
2
+ export declare function formatSpatialIndexingNotice(notice: Readonly<SpatialIndexingNotice>): string;
3
+ //# sourceMappingURL=formatSpatialIndexingNotice.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formatSpatialIndexingNotice.d.ts","sourceRoot":"","sources":["../src/formatSpatialIndexingNotice.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AActE,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,QAAQ,CAAC,qBAAqB,CAAC,GAAG,MAAM,CAsB3F"}
@@ -0,0 +1,35 @@
1
+ import { MAX_INDEXED_CELLS_PER_OBJECT } from './uniformGrid';
2
+ // Renders an indexing notice as a caller-facing sentence, and is the only place in this package that
3
+ // holds one. Import it to turn the structured record a SpatialIndexingGuard receives into something a
4
+ // developer reads; leave it unimported and neither the text nor its cost reaches a bundle.
5
+ //
6
+ // The text lives here rather than inside an `enableSpatialGuards` that logs for you because
7
+ // `@flighthq/spatial` is a core-layer package and may not depend on `@flighthq/log` — the same shape
8
+ // `@flighthq/importdiagnostics` uses, where core carries the record and a separate module carries the
9
+ // words. Wiring the two together is three lines at the application layer, which can reach both:
10
+ //
11
+ // setSpatialIndexingGuard((notice) => logWarn({ message: formatSpatialIndexingNotice(notice) }, 'spatial'));
12
+ export function formatSpatialIndexingNotice(notice) {
13
+ if (notice.reason === 'invalid-cell-size') {
14
+ return `createUniformGridSpatialBackend(${notice.cellSize}): cellSize must be a positive finite number. ${notice.operation}SpatialObject(${notice.id}) used the bounded overflow path instead, so results remain correct but queries scan this object.`;
15
+ }
16
+ if (notice.reason === 'inverted-bounds') {
17
+ return `${notice.operation}SpatialObject(${notice.id}): minX/minY must not exceed maxX/maxY, so the object was not indexed and no query will return it. The operation returns false for this — normalize or correct the bounds upstream.`;
18
+ }
19
+ if (notice.reason === 'missing-id') {
20
+ if (notice.operation === 'remove') {
21
+ return `removeSpatialObject(${notice.id}): the id was not indexed, so removal was a no-op. Check the object's indexing lifecycle if this was unexpected.`;
22
+ }
23
+ return `updateSpatialObject(${notice.id}): the id was not indexed, so update used its documented insert behavior and left the object in '${notice.mode}' mode. Use insertSpatialObject for a new id, or check the object's indexing lifecycle.`;
24
+ }
25
+ if (notice.mode === 'declined') {
26
+ return `${notice.operation}SpatialObject(${notice.id}): the bounds are not finite, so the object was not indexed and no query will return it. The operation returns false for this — check the sentinel, and check what produced NaN/Infinity bounds upstream.`;
27
+ }
28
+ if (notice.mode === 'overflow') {
29
+ return `${notice.operation}SpatialObject(${notice.id}): the bounds span ${notice.wouldOccupyBucketCount} cells, over the ${MAX_INDEXED_CELLS_PER_OBJECT} per-object budget, so the object is held in the flat overflow list instead of the grid. Results are unaffected. If this is not a one-off outlier, the grid's cellSize is too small for the objects being indexed — size it to a typical object.`;
30
+ }
31
+ // `cells` and `absent` are ordinary outcomes no guard reports, so reaching here means a backend
32
+ // notified about something this text does not cover. Say exactly that rather than inventing advice.
33
+ return `${notice.operation}SpatialObject(${notice.id}): indexed as '${notice.mode}', which carries no caller-facing advice.`;
34
+ }
35
+ //# sourceMappingURL=formatSpatialIndexingNotice.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formatSpatialIndexingNotice.js","sourceRoot":"","sources":["../src/formatSpatialIndexingNotice.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,4BAA4B,EAAE,MAAM,eAAe,CAAC;AAE7D,qGAAqG;AACrG,sGAAsG;AACtG,2FAA2F;AAC3F,EAAE;AACF,4FAA4F;AAC5F,qGAAqG;AACrG,sGAAsG;AACtG,gGAAgG;AAChG,EAAE;AACF,+GAA+G;AAC/G,MAAM,UAAU,2BAA2B,CAAC,MAAuC;IACjF,IAAI,MAAM,CAAC,MAAM,KAAK,mBAAmB,EAAE,CAAC;QAC1C,OAAO,mCAAmC,MAAM,CAAC,QAAQ,iDAAiD,MAAM,CAAC,SAAS,iBAAiB,MAAM,CAAC,EAAE,mGAAmG,CAAC;IAC1P,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,KAAK,iBAAiB,EAAE,CAAC;QACxC,OAAO,GAAG,MAAM,CAAC,SAAS,iBAAiB,MAAM,CAAC,EAAE,qLAAqL,CAAC;IAC5O,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,KAAK,YAAY,EAAE,CAAC;QACnC,IAAI,MAAM,CAAC,SAAS,KAAK,QAAQ,EAAE,CAAC;YAClC,OAAO,uBAAuB,MAAM,CAAC,EAAE,kHAAkH,CAAC;QAC5J,CAAC;QACD,OAAO,uBAAuB,MAAM,CAAC,EAAE,oGAAoG,MAAM,CAAC,IAAI,yFAAyF,CAAC;IAClP,CAAC;IACD,IAAI,MAAM,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;QAC/B,OAAO,GAAG,MAAM,CAAC,SAAS,iBAAiB,MAAM,CAAC,EAAE,2MAA2M,CAAC;IAClQ,CAAC;IACD,IAAI,MAAM,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;QAC/B,OAAO,GAAG,MAAM,CAAC,SAAS,iBAAiB,MAAM,CAAC,EAAE,sBAAsB,MAAM,CAAC,sBAAsB,oBAAoB,4BAA4B,kPAAkP,CAAC;IAC5Y,CAAC;IACD,gGAAgG;IAChG,oGAAoG;IACpG,OAAO,GAAG,MAAM,CAAC,SAAS,iBAAiB,MAAM,CAAC,EAAE,kBAAkB,MAAM,CAAC,IAAI,2CAA2C,CAAC;AAC/H,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { clearSpatialIndex, createSpatialIndex, createUniformGridSpatialBackend, insertSpatialObject, querySpatialPairs, querySpatialPoint, querySpatialRay, querySpatialRegion, removeSpatialObject, updateSpatialObject, } from './contract';
1
+ export { MAX_INDEXED_CELLS_PER_OBJECT, clearSpatialIndex, createSpatialIndex, createUniformGridSpatialBackend, explainSpatialIndexing, formatSpatialIndexingNotice, insertSpatialObject, querySpatialPairs, querySpatialPoint, querySpatialRay, querySpatialRegion, removeSpatialObject, setSpatialIndexingGuard, updateSpatialObject, } from './contract';
2
2
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,+BAA+B,EAC/B,mBAAmB,EACnB,iBAAiB,EACjB,iBAAiB,EACjB,eAAe,EACf,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,4BAA4B,EAC5B,iBAAiB,EACjB,kBAAkB,EAClB,+BAA+B,EAC/B,sBAAsB,EACtB,2BAA2B,EAC3B,mBAAmB,EACnB,iBAAiB,EACjB,iBAAiB,EACjB,eAAe,EACf,kBAAkB,EAClB,mBAAmB,EACnB,uBAAuB,EACvB,mBAAmB,GACpB,MAAM,YAAY,CAAC"}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export { clearSpatialIndex, createSpatialIndex, createUniformGridSpatialBackend, insertSpatialObject, querySpatialPairs, querySpatialPoint, querySpatialRay, querySpatialRegion, removeSpatialObject, updateSpatialObject, } from './contract';
1
+ export { MAX_INDEXED_CELLS_PER_OBJECT, clearSpatialIndex, createSpatialIndex, createUniformGridSpatialBackend, explainSpatialIndexing, formatSpatialIndexingNotice, insertSpatialObject, querySpatialPairs, querySpatialPoint, querySpatialRay, querySpatialRegion, removeSpatialObject, setSpatialIndexingGuard, updateSpatialObject, } from './contract';
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,+BAA+B,EAC/B,mBAAmB,EACnB,iBAAiB,EACjB,iBAAiB,EACjB,eAAe,EACf,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,4BAA4B,EAC5B,iBAAiB,EACjB,kBAAkB,EAClB,+BAA+B,EAC/B,sBAAsB,EACtB,2BAA2B,EAC3B,mBAAmB,EACnB,iBAAiB,EACjB,iBAAiB,EACjB,eAAe,EACf,kBAAkB,EAClB,mBAAmB,EACnB,uBAAuB,EACvB,mBAAmB,GACpB,MAAM,YAAY,CAAC"}
@@ -1,11 +1,11 @@
1
1
  import type { SpatialAabb, SpatialIndex, SpatialIndexBackend, SpatialObjectId, SpatialPair } from '@flighthq/types/contract';
2
2
  export declare function clearSpatialIndex(index: Readonly<SpatialIndex>): void;
3
3
  export declare function createSpatialIndex(backend?: SpatialIndexBackend): SpatialIndex;
4
- export declare function insertSpatialObject(index: Readonly<SpatialIndex>, id: SpatialObjectId, bounds: Readonly<SpatialAabb>): void;
4
+ export declare function insertSpatialObject(index: Readonly<SpatialIndex>, id: SpatialObjectId, bounds: Readonly<SpatialAabb>): boolean;
5
5
  export declare function querySpatialPairs(index: Readonly<SpatialIndex>, out: SpatialPair[]): void;
6
6
  export declare function querySpatialPoint(index: Readonly<SpatialIndex>, x: number, y: number, out: SpatialObjectId[]): void;
7
7
  export declare function querySpatialRay(index: Readonly<SpatialIndex>, x: number, y: number, dx: number, dy: number, out: SpatialObjectId[]): void;
8
8
  export declare function querySpatialRegion(index: Readonly<SpatialIndex>, region: Readonly<SpatialAabb>, out: SpatialObjectId[]): void;
9
9
  export declare function removeSpatialObject(index: Readonly<SpatialIndex>, id: SpatialObjectId): void;
10
- export declare function updateSpatialObject(index: Readonly<SpatialIndex>, id: SpatialObjectId, bounds: Readonly<SpatialAabb>): void;
10
+ export declare function updateSpatialObject(index: Readonly<SpatialIndex>, id: SpatialObjectId, bounds: Readonly<SpatialAabb>): boolean;
11
11
  //# sourceMappingURL=spatial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Y,CAAC,EAC7B,MAAM,EAAE,QAAQ,CAAC,WAAW,CAAC,EAC7B,GAAG,EAAE,eAAe,EAAE,GACrB,IAAI,CAEN;AAGD,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,QAAQ,CAAC,YAAY,CAAC,EAAE,EAAE,EAAE,eAAe,GAAG,IAAI,CAE5F;AAMD,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,QAAQ,CAAC,YAAY,CAAC,EAC7B,EAAE,EAAE,eAAe,EACnB,MAAM,EAAE,QAAQ,CAAC,WAAW,CAAC,GAC5B,OAAO,CAET"}
@@ -15,9 +15,12 @@ export function createSpatialIndex(backend) {
15
15
  };
16
16
  }
17
17
  // Adds an object to the index under `id` with its current bounds. The bounds are copied; the caller
18
- // may reuse its own value afterward.
18
+ // may reuse its own value afterward. Returns false when the bounds cannot be indexed at all
19
+ // (non-finite or inverted) — the object is then absent from every query rather than present at a
20
+ // nonsense position. Oversized-but-valid bounds return true and stay fully queryable; the backend
21
+ // decides how to hold them. explainSpatialIndexing reports which happened.
19
22
  export function insertSpatialObject(index, id, bounds) {
20
- index.runtime.backend.insertSpatialObject(id, bounds);
23
+ return index.runtime.backend.insertSpatialObject(id, bounds);
21
24
  }
22
25
  // Fills `out` (cleared first) with every deduplicated candidate pair — each unordered pair at most
23
26
  // once, never an object with itself. A pair is a broadphase candidate: the two objects are close
@@ -43,8 +46,11 @@ export function removeSpatialObject(index, id) {
43
46
  index.runtime.backend.removeSpatialObject(id);
44
47
  }
45
48
  // Moves an already-inserted object to new bounds. Inserting a not-yet-present id behaves as insert.
49
+ // Returns the same sentinel as insertSpatialObject. A declined update removes the object rather than
50
+ // leaving it at its old bounds, so a caller that ignores the sentinel can never read a stale position
51
+ // as a current one.
46
52
  export function updateSpatialObject(index, id, bounds) {
47
- index.runtime.backend.updateSpatialObject(id, bounds);
53
+ return index.runtime.backend.updateSpatialObject(id, bounds);
48
54
  }
49
55
  // The default uniform-grid cell size when createSpatialIndex is called without an explicit backend —
50
56
  // a middle-of-the-road choice; a workload with a known typical object size should pass its own grid.
@@ -1 +1 @@
1
- {"version":3,"file":"spatialIndex.js","sourceRoot":"","sources":["../src/spatialIndex.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,+BAA+B,EAAE,MAAM,eAAe,CAAC;AAEhE,gFAAgF;AAChF,MAAM,UAAU,iBAAiB,CAAC,KAA6B;IAC7D,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,iBAAiB,EAAE,CAAC;AAC5C,CAAC;AAED,yFAAyF;AACzF,kGAAkG;AAClG,mGAAmG;AACnG,4DAA4D;AAC5D,MAAM,UAAU,kBAAkB,CAAC,OAA6B;IAC9D,OAAO;QACL,OAAO,EAAE;YACP,OAAO,EAAE,OAAO,IAAI,+BAA+B,CAAC,yBAAyB,CAAC;SAC/E;KACF,CAAC;AACJ,CAAC;AAED,oGAAoG;AACpG,qCAAqC;AACrC,MAAM,UAAU,mBAAmB,CACjC,KAA6B,EAC7B,EAAmB,EACnB,MAA6B;IAE7B,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,mBAAmB,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;AACxD,CAAC;AAED,mGAAmG;AACnG,iGAAiG;AACjG,8FAA8F;AAC9F,MAAM,UAAU,iBAAiB,CAAC,KAA6B,EAAE,GAAkB;IACjF,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,iBAAiB,CAAC,GAAG,CAAC,CAAC;AAC/C,CAAC;AAED,qFAAqF;AACrF,MAAM,UAAU,iBAAiB,CAAC,KAA6B,EAAE,CAAS,EAAE,CAAS,EAAE,GAAsB;IAC3G,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AACrD,CAAC;AAED,iGAAiG;AACjG,kGAAkG;AAClG,MAAM,UAAU,eAAe,CAC7B,KAA6B,EAC7B,CAAS,EACT,CAAS,EACT,EAAU,EACV,EAAU,EACV,GAA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;AACtG,oBAAoB;AACpB,MAAM,UAAU,mBAAmB,CACjC,KAA6B,EAC7B,EAAmB,EACnB,MAA6B;IAE7B,OAAO,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,mBAAmB,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;AAC/D,CAAC;AAED,qGAAqG;AACrG,qGAAqG;AACrG,MAAM,yBAAyB,GAAG,GAAG,CAAC"}
@@ -1,3 +1,5 @@
1
- import type { SpatialIndexBackend } from '@flighthq/types/contract';
1
+ import type { SpatialIndexBackend, SpatialIndexingGuard } from '@flighthq/types/contract';
2
+ export declare const MAX_INDEXED_CELLS_PER_OBJECT = 1024;
2
3
  export declare function createUniformGridSpatialBackend(cellSize: number): SpatialIndexBackend;
4
+ export declare function setSpatialIndexingGuard(guard: SpatialIndexingGuard | null): void;
3
5
  //# sourceMappingURL=uniformGrid.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"uniformGrid.d.ts","sourceRoot":"","sources":["../src/uniformGrid.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAGV,mBAAmB,EAGpB,MAAM,0BAA0B,CAAC;AASlC,wBAAgB,+BAA+B,CAAC,QAAQ,EAAE,MAAM,GAAG,mBAAmB,CA0CrF"}
1
+ {"version":3,"file":"uniformGrid.d.ts","sourceRoot":"","sources":["../src/uniformGrid.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAGV,mBAAmB,EAGnB,oBAAoB,EAMrB,MAAM,0BAA0B,CAAC;AAiBlC,eAAO,MAAM,4BAA4B,OAAO,CAAC;AAejD,wBAAgB,+BAA+B,CAAC,QAAQ,EAAE,MAAM,GAAG,mBAAmB,CAkDrF;AAKD,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,oBAAoB,GAAG,IAAI,GAAG,IAAI,CAEhF"}
@@ -1,39 +1,70 @@
1
1
  import { containsRectanglePointXY, intersectsRectangle } from '@flighthq/geometry/contract';
2
+ // The per-object cell budget. An object whose AABB covers more cells than this is held in the flat
3
+ // overflow list instead of being written into every cell it spans.
4
+ //
5
+ // This bound is what makes insert cost independent of object size. Without it the cell walk is
6
+ // proportional to extent ÷ cellSize *squared*, so cost is set by the largest object rather than by
7
+ // the object count: measured on this grid at one cell per unit, a 200-unit box costs 40k cell writes
8
+ // (~28 ms) and a 2000-unit box costs 4M (~4.7 s), while an AABB a trillion units wide — reachable
9
+ // from any diverging simulation — never returns at all. A hang is worse than a throw because it is
10
+ // uncatchable and takes the caller with it.
11
+ //
12
+ // Overflow is not a degraded result: an object that spans a thousand cells is a co-occupant of nearly
13
+ // everything, so the cell index tells the queries almost nothing and a linear scan answers the same
14
+ // question at a bounded cost. 1024 cells is a 32×32 block — an object 32× the cell size on each axis,
15
+ // far past the "cell size ≈ typical object size" the grid is built around. An object over the budget
16
+ // is a signal the cell size is wrong for the workload, which the indexing guard reports.
17
+ export const MAX_INDEXED_CELLS_PER_OBJECT = 1024;
2
18
  // Builds a uniform-grid (spatial-hash) backend: an object's AABB is mapped to the rectangular block
3
19
  // of fixed-size cells it covers, and each cell holds the ids overlapping it. Co-located objects share
4
20
  // a cell, so candidate pairs and region/point/ray hits are found by looking only at the relevant
5
21
  // cells instead of scanning every object. `cellSize` is the world-space side length of one cell; a
6
- // good value is roughly the size of a typical object (too small over-spans large objects across many
7
- // cells, too large lumps unrelated objects together). No import-time side effect — the caller
8
- // constructs a grid explicitly, and createSpatialIndex uses this as its default index.
22
+ // good value is a positive finite number roughly the size of a typical object (too small over-spans
23
+ // large objects across many cells, too large lumps unrelated objects together). An invalid size uses
24
+ // the bounded overflow path to keep results correct and reports through the indexing guard. No
25
+ // import-time side effect — the caller constructs a grid explicitly, and createSpatialIndex uses
26
+ // this as its default index.
27
+ //
28
+ // Object size does not set the cost: an AABB spanning more than MAX_INDEXED_CELLS_PER_OBJECT cells
29
+ // goes to a flat overflow list that every query scans, and non-finite or inverted bounds are declined
30
+ // outright with a false sentinel. Both are visible through explainSpatialIndexing.
9
31
  export function createUniformGridSpatialBackend(cellSize) {
10
32
  const grid = {
11
33
  cellSize,
12
34
  cells: new Map(),
13
35
  bounds: new Map(),
36
+ overflow: new Set(),
37
+ declined: new Map(),
14
38
  minCellX: 0,
15
39
  minCellY: 0,
16
40
  maxCellX: 0,
17
41
  maxCellY: 0,
18
- empty: true,
19
42
  seen: new Set(),
43
+ pairIds: [],
20
44
  };
21
45
  return {
22
46
  insertSpatialObject(id, bounds) {
23
- _insertIntoGrid(grid, id, bounds);
47
+ return _insertIntoGrid(grid, id, bounds, 'insert');
24
48
  },
25
49
  updateSpatialObject(id, bounds) {
26
- _removeFromGrid(grid, id);
27
- _insertIntoGrid(grid, id, bounds);
50
+ return _updateGridObject(grid, id, bounds);
28
51
  },
29
52
  removeSpatialObject(id) {
53
+ const wasMissing = !grid.bounds.has(id) && !grid.declined.has(id);
30
54
  _removeFromGrid(grid, id);
55
+ if (wasMissing)
56
+ _reportGridIndexing(grid, id, 'absent', 'remove', 'missing-id', 0);
31
57
  },
32
58
  clearSpatialIndex() {
33
59
  grid.cells.clear();
34
60
  grid.bounds.clear();
61
+ grid.overflow.clear();
62
+ grid.declined.clear();
35
63
  grid.seen.clear();
36
- grid.empty = true;
64
+ grid.pairIds.length = 0;
65
+ },
66
+ explainSpatialIndexing(id) {
67
+ return _explainGridIndexing(grid, id);
37
68
  },
38
69
  querySpatialPairs(out) {
39
70
  _queryGridPairs(grid, out);
@@ -49,6 +80,12 @@ export function createUniformGridSpatialBackend(cellSize) {
49
80
  },
50
81
  };
51
82
  }
83
+ // Installs the indexing guard consulted for invalid configuration or bounds, missing-id operations,
84
+ // and overflow routing; null uninstalls it. Module-scoped rather than per-grid: it is a development
85
+ // diagnostic, and an application debugging an index wants it on for every grid at once.
86
+ export function setSpatialIndexingGuard(guard) {
87
+ _indexingGuard = guard;
88
+ }
52
89
  // Maps a world coordinate to its cell index along one axis. Uses floor so negative coordinates map
53
90
  // to consistently decreasing cell indices (world 0 is the boundary between cell -1 and cell 0).
54
91
  function _cellIndex(coord, cellSize) {
@@ -61,23 +98,79 @@ function _cellKey(cx, cy) {
61
98
  }
62
99
  // Fills a scratch RectangleLike (x/y/width/height) from a SpatialAabb (min/max corners) so the
63
100
  // geometry rectangle-overlap and point-containment helpers can be reused instead of re-deriving the
64
- // AABB math here. Assumes a normalized AABB (max >= min); a flipped AABB yields a negative extent,
65
- // which the geometry helpers still normalize internally.
101
+ // AABB math here. Stored AABBs are normalized because insert declines inverted bounds.
66
102
  function _fillRectFromAabb(out, aabb) {
67
103
  out.x = aabb.minX;
68
104
  out.y = aabb.minY;
69
105
  out.width = aabb.maxX - aabb.minX;
70
106
  out.height = aabb.maxY - aabb.minY;
71
107
  }
72
- // Adds an object to every cell its AABB covers, storing a private copy of the bounds and expanding
73
- // the occupied cell range. The caller may safely mutate or reuse the passed bounds afterward.
74
- function _insertIntoGrid(grid, id, bounds) {
108
+ // Reports how `id` is currently held. Pure: reads only, allocates only the returned record.
109
+ function _explainGridIndexing(grid, id) {
110
+ const declineReason = grid.declined.get(id);
111
+ if (declineReason !== undefined)
112
+ return { bucketCount: 0, id, mode: 'declined', reason: declineReason };
113
+ if (grid.overflow.has(id))
114
+ return { bucketCount: 0, id, mode: 'overflow', reason: null };
115
+ const bounds = grid.bounds.get(id);
116
+ if (bounds === undefined)
117
+ return { bucketCount: 0, id, mode: 'absent', reason: null };
118
+ return { bucketCount: _spannedCellCount(grid.cellSize, bounds), id, mode: 'cells', reason: null };
119
+ }
120
+ // Adds an object to the index, storing a private copy of the bounds; the caller may safely mutate or
121
+ // reuse the passed bounds afterward. Returns false only for bounds that cannot be indexed at all.
122
+ //
123
+ // Five outcomes, and which one applies is decided *before* any cell is touched — that ordering is
124
+ // the whole point, since deciding afterward would mean walking the cells to find out they were too
125
+ // many:
126
+ // - non-finite bounds are declined. There is no cell range to compute, and storing them would let a
127
+ // NaN leak into every later overlap test, so the object is left out of the index entirely and the
128
+ // caller gets a false sentinel rather than an exception or a silent no-op.
129
+ // - inverted bounds are likewise declined because min/max corners do not describe an AABB.
130
+ // - a non-positive or non-finite cell size routes valid objects to overflow, preserving query
131
+ // correctness through the bounded flat scan while the indexing guard reports the configuration.
132
+ // - bounds spanning more than MAX_INDEXED_CELLS_PER_OBJECT cells go to the overflow list, which
133
+ // every query scans. Bounded by the object count instead of the object's size.
134
+ // - everything else takes the ordinary path: one entry in each cell it covers.
135
+ function _insertIntoGrid(grid, id, bounds, operation) {
136
+ if (!Number.isFinite(bounds.minX) ||
137
+ !Number.isFinite(bounds.minY) ||
138
+ !Number.isFinite(bounds.maxX) ||
139
+ !Number.isFinite(bounds.maxY)) {
140
+ grid.declined.set(id, 'non-finite-bounds');
141
+ _reportGridIndexing(grid, id, 'declined', operation, 'non-finite-bounds', 0);
142
+ return false;
143
+ }
144
+ if (bounds.maxX < bounds.minX || bounds.maxY < bounds.minY) {
145
+ grid.declined.set(id, 'inverted-bounds');
146
+ _reportGridIndexing(grid, id, 'declined', operation, 'inverted-bounds', 0);
147
+ return false;
148
+ }
75
149
  const cs = grid.cellSize;
76
- const cx0 = _cellIndex(bounds.minX, cs);
77
- const cx1 = _cellIndex(bounds.maxX, cs);
78
- const cy0 = _cellIndex(bounds.minY, cs);
79
- const cy1 = _cellIndex(bounds.maxY, cs);
80
- grid.bounds.set(id, { minX: bounds.minX, minY: bounds.minY, maxX: bounds.maxX, maxY: bounds.maxY });
150
+ const copy = { minX: bounds.minX, minY: bounds.minY, maxX: bounds.maxX, maxY: bounds.maxY };
151
+ if (!(cs > 0 && Number.isFinite(cs))) {
152
+ grid.bounds.set(id, copy);
153
+ grid.overflow.add(id);
154
+ _reportGridIndexing(grid, id, 'overflow', operation, 'invalid-cell-size', 0);
155
+ return true;
156
+ }
157
+ const spanned = _spannedCellCount(cs, copy);
158
+ // Written as a negated `<=` so an unrepresentable span falls to overflow rather than through to a
159
+ // loop that cannot index it.
160
+ if (!(spanned <= MAX_INDEXED_CELLS_PER_OBJECT)) {
161
+ grid.bounds.set(id, copy);
162
+ grid.overflow.add(id);
163
+ _reportGridIndexing(grid, id, 'overflow', operation, null, spanned);
164
+ return true;
165
+ }
166
+ const cx0 = _cellIndex(copy.minX, cs);
167
+ const cx1 = _cellIndex(copy.maxX, cs);
168
+ const cy0 = _cellIndex(copy.minY, cs);
169
+ const cy1 = _cellIndex(copy.maxY, cs);
170
+ // Whether a cell range exists yet, read *before* this object's cells are added. A first celled
171
+ // object seeds the range; a later one widens it.
172
+ const hadCells = grid.cells.size !== 0;
173
+ grid.bounds.set(id, copy);
81
174
  for (let cy = cy0; cy <= cy1; cy++) {
82
175
  for (let cx = cx0; cx <= cx1; cx++) {
83
176
  const key = _cellKey(cx, cy);
@@ -89,12 +182,11 @@ function _insertIntoGrid(grid, id, bounds) {
89
182
  cell.ids.add(id);
90
183
  }
91
184
  }
92
- if (grid.empty) {
185
+ if (!hadCells) {
93
186
  grid.minCellX = cx0;
94
187
  grid.maxCellX = cx1;
95
188
  grid.minCellY = cy0;
96
189
  grid.maxCellY = cy1;
97
- grid.empty = false;
98
190
  }
99
191
  else {
100
192
  if (cx0 < grid.minCellX)
@@ -106,6 +198,44 @@ function _insertIntoGrid(grid, id, bounds) {
106
198
  if (cy1 > grid.maxCellY)
107
199
  grid.maxCellY = cy1;
108
200
  }
201
+ return true;
202
+ }
203
+ // Updates an object's private AABB copy without touching its cell sets when both the old and new
204
+ // bounds take the ordinary indexing path and cover exactly the same cells. Small per-frame movement
205
+ // usually stays inside this range, so its dominant cost becomes four field writes instead of a
206
+ // remove-and-reinsert walk. Every mode or range transition keeps using the shared slow path below.
207
+ function _updateGridObject(grid, id, bounds) {
208
+ const wasMissing = !grid.bounds.has(id) && !grid.declined.has(id);
209
+ const previous = grid.bounds.get(id);
210
+ if (previous !== undefined &&
211
+ !grid.overflow.has(id) &&
212
+ Number.isFinite(bounds.minX) &&
213
+ Number.isFinite(bounds.minY) &&
214
+ Number.isFinite(bounds.maxX) &&
215
+ Number.isFinite(bounds.maxY) &&
216
+ bounds.minX <= bounds.maxX &&
217
+ bounds.minY <= bounds.maxY) {
218
+ const cs = grid.cellSize;
219
+ const spanned = _spannedCellCount(cs, bounds);
220
+ if (spanned <= MAX_INDEXED_CELLS_PER_OBJECT &&
221
+ _cellIndex(previous.minX, cs) === _cellIndex(bounds.minX, cs) &&
222
+ _cellIndex(previous.minY, cs) === _cellIndex(bounds.minY, cs) &&
223
+ _cellIndex(previous.maxX, cs) === _cellIndex(bounds.maxX, cs) &&
224
+ _cellIndex(previous.maxY, cs) === _cellIndex(bounds.maxY, cs)) {
225
+ previous.minX = bounds.minX;
226
+ previous.minY = bounds.minY;
227
+ previous.maxX = bounds.maxX;
228
+ previous.maxY = bounds.maxY;
229
+ return true;
230
+ }
231
+ }
232
+ _removeFromGrid(grid, id);
233
+ const inserted = _insertIntoGrid(grid, id, bounds, 'update');
234
+ if (wasMissing) {
235
+ const explanation = _explainGridIndexing(grid, id);
236
+ _reportGridIndexing(grid, id, explanation.mode, 'update', 'missing-id', 0);
237
+ }
238
+ return inserted;
109
239
  }
110
240
  // Reports whether an AABB contains the point (`x`,`y`), reusing the geometry rectangle helper.
111
241
  function _isSpatialAabbContainsPoint(aabb, x, y) {
@@ -165,11 +295,18 @@ function _rayBoxEntryT(ox, oy, dx, dy, minX, minY, maxX, maxY) {
165
295
  }
166
296
  // Removes an object from every cell its stored AABB covered and drops now-empty cells. The occupied
167
297
  // cell range is intentionally not shrunk (only reset when the grid fully empties). A no-op for an
168
- // unknown id.
298
+ // unknown id. Overflowed and declined ids leave through their own sets without a cell walk — remove
299
+ // re-derives the cell range from the stored bounds, so an overflowed object taking the ordinary path
300
+ // here would reintroduce exactly the unbounded walk the insert bound removed.
169
301
  function _removeFromGrid(grid, id) {
302
+ grid.declined.delete(id);
170
303
  const bounds = grid.bounds.get(id);
171
304
  if (bounds === undefined)
172
305
  return;
306
+ if (grid.overflow.delete(id)) {
307
+ grid.bounds.delete(id);
308
+ return;
309
+ }
173
310
  const cs = grid.cellSize;
174
311
  const cx0 = _cellIndex(bounds.minX, cs);
175
312
  const cx1 = _cellIndex(bounds.maxX, cs);
@@ -187,8 +324,30 @@ function _removeFromGrid(grid, id) {
187
324
  }
188
325
  }
189
326
  grid.bounds.delete(id);
190
- if (grid.bounds.size === 0)
191
- grid.empty = true;
327
+ }
328
+ // Appends the pairs involving overflowed objects. An overflowed object occupies no cell, so the cell
329
+ // walk in _queryGridPairs can never emit a pair for it and no dedup against that walk is needed. Its
330
+ // pairs are enumerated here instead: against every other indexed object, which is what "spans nearly
331
+ // the whole world" already means. Unlike the cell path these are filtered by a real AABB overlap test
332
+ // rather than emitted as bare locality candidates — the result stays a superset of the true overlaps
333
+ // either way, and an object this large would otherwise nominate every other object every frame.
334
+ function _queryGridOverflowPairs(grid, out) {
335
+ for (const id of grid.overflow) {
336
+ const bounds = grid.bounds.get(id);
337
+ if (bounds === undefined)
338
+ continue;
339
+ for (const [otherId, otherBounds] of grid.bounds) {
340
+ if (otherId === id)
341
+ continue;
342
+ // Each overflow×overflow pair would otherwise be emitted from both sides; taking it only from
343
+ // the lower id emits it once. An overflow×celled pair reaches this test from one side only.
344
+ if (grid.overflow.has(otherId) && otherId < id)
345
+ continue;
346
+ if (!_isSpatialAabbOverlapping(bounds, otherBounds))
347
+ continue;
348
+ out.push(id < otherId ? { a: id, b: otherId } : { a: otherId, b: id });
349
+ }
350
+ }
192
351
  }
193
352
  // Enumerates candidate pairs. Within each cell every co-occupant pair is a candidate, but a pair may
194
353
  // share several cells; to emit it exactly once, a pair is emitted only from its canonical cell — the
@@ -198,11 +357,14 @@ function _removeFromGrid(grid, id) {
198
357
  function _queryGridPairs(grid, out) {
199
358
  out.length = 0;
200
359
  const cs = grid.cellSize;
360
+ const list = grid.pairIds;
201
361
  for (const cell of grid.cells.values()) {
202
362
  const ids = cell.ids;
203
363
  if (ids.size < 2)
204
364
  continue;
205
- const list = [...ids];
365
+ list.length = 0;
366
+ for (const id of ids)
367
+ list.push(id);
206
368
  for (let i = 0; i < list.length; i++) {
207
369
  for (let j = i + 1; j < list.length; j++) {
208
370
  let a = list[i];
@@ -223,16 +385,30 @@ function _queryGridPairs(grid, out) {
223
385
  }
224
386
  }
225
387
  }
388
+ if (grid.overflow.size !== 0)
389
+ _queryGridOverflowPairs(grid, out);
390
+ }
391
+ function _reportGridIndexing(grid, id, mode, operation, reason, wouldOccupyBucketCount) {
392
+ if (_indexingGuard === null)
393
+ return;
394
+ _indexingGuard({ cellSize: grid.cellSize, id, mode, operation, reason, wouldOccupyBucketCount });
226
395
  }
227
396
  // Gathers the ids in the cell containing the point, then confirms each against its real bounds. A
228
- // single cell holds each id at most once, so no dedup pass is needed.
397
+ // single cell holds each id at most once, so no dedup pass is needed. Overflowed objects hold no cell
398
+ // and are tested directly; they cannot collide with the cell gather, so no dedup is needed there
399
+ // either.
229
400
  function _queryGridPoint(grid, x, y, out) {
230
401
  out.length = 0;
231
402
  const cs = grid.cellSize;
232
403
  const cell = grid.cells.get(_cellKey(_cellIndex(x, cs), _cellIndex(y, cs)));
233
- if (cell === undefined)
234
- return;
235
- for (const id of cell.ids) {
404
+ if (cell !== undefined) {
405
+ for (const id of cell.ids) {
406
+ const bounds = grid.bounds.get(id);
407
+ if (bounds !== undefined && _isSpatialAabbContainsPoint(bounds, x, y))
408
+ out.push(id);
409
+ }
410
+ }
411
+ for (const id of grid.overflow) {
236
412
  const bounds = grid.bounds.get(id);
237
413
  if (bounds !== undefined && _isSpatialAabbContainsPoint(bounds, x, y))
238
414
  out.push(id);
@@ -244,8 +420,6 @@ function _queryGridPoint(grid, x, y, out) {
244
420
  // point query at the origin. An empty grid returns nothing.
245
421
  function _queryGridRay(grid, ox, oy, dx, dy, out) {
246
422
  out.length = 0;
247
- if (grid.empty)
248
- return;
249
423
  const cs = grid.cellSize;
250
424
  const seen = grid.seen;
251
425
  seen.clear();
@@ -253,6 +427,23 @@ function _queryGridRay(grid, ox, oy, dx, dy, out) {
253
427
  _queryGridPoint(grid, ox, oy, out);
254
428
  return;
255
429
  }
430
+ // Overflowed objects are outside the cell range the DDA walks — deliberately, so one huge AABB
431
+ // cannot stretch that range and make every ray traverse it — so they are slab-tested directly.
432
+ for (const id of grid.overflow) {
433
+ const bounds = grid.bounds.get(id);
434
+ if (bounds !== undefined &&
435
+ _rayBoxEntryT(ox, oy, dx, dy, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY) >= 0) {
436
+ out.push(id);
437
+ }
438
+ }
439
+ // The cell range describes the CELLS, so the cells decide whether it means anything. Reading a
440
+ // separately-maintained `empty` flag here was the defect: it was set from `bounds.size`, which counts
441
+ // overflowed objects too, so removing the last CELLED object while any overflowed object remained
442
+ // left the flag false and the min/max range stale — and this walk then stepped across that stale
443
+ // range, unbounded, with no cells left to find. Deriving the fact removes the class: there is no
444
+ // longer a flag that can disagree with the structure it describes, at any transition.
445
+ if (grid.cells.size === 0)
446
+ return;
256
447
  const boxMinX = grid.minCellX * cs;
257
448
  const boxMinY = grid.minCellY * cs;
258
449
  const boxMaxX = (grid.maxCellX + 1) * cs;
@@ -316,12 +507,25 @@ function _queryGridRay(grid, ox, oy, dx, dy, out) {
316
507
  }
317
508
  // Gathers the ids in every cell the region covers (deduplicated via the reused scratch set), then
318
509
  // confirms each against the region's real bounds — so a false cell-mate whose bounds miss the region
319
- // is dropped.
510
+ // is dropped. Overflowed objects hold no cell and are tested directly.
511
+ //
512
+ // The region is caller-supplied, so it carries the same unbounded-walk hazard the insert bound closes
513
+ // and needs its own guard: a query region wider than the world costs extent ÷ cellSize squared cell
514
+ // lookups against a grid that may hold one object. When the region spans more cells than the grid has
515
+ // occupied, walking the objects is both cheaper and exact, so the walk flips — a region query is
516
+ // never more expensive than a full scan.
320
517
  function _queryGridRegion(grid, region, out) {
321
518
  out.length = 0;
322
519
  const cs = grid.cellSize;
323
520
  const seen = grid.seen;
324
521
  seen.clear();
522
+ if (!(_spannedCellCount(cs, region) <= grid.cells.size)) {
523
+ for (const [id, bounds] of grid.bounds) {
524
+ if (_isSpatialAabbOverlapping(bounds, region))
525
+ out.push(id);
526
+ }
527
+ return;
528
+ }
325
529
  const cx0 = _cellIndex(region.minX, cs);
326
530
  const cx1 = _cellIndex(region.maxX, cs);
327
531
  const cy0 = _cellIndex(region.minY, cs);
@@ -341,7 +545,26 @@ function _queryGridRegion(grid, region, out) {
341
545
  }
342
546
  }
343
547
  }
548
+ for (const id of grid.overflow) {
549
+ const bounds = grid.bounds.get(id);
550
+ if (bounds !== undefined && _isSpatialAabbOverlapping(bounds, region))
551
+ out.push(id);
552
+ }
553
+ }
554
+ // How many cells an AABB's span covers, as a count rather than a walk — the number the per-object
555
+ // budget is compared against, computed before any cell is touched. Returns NaN for bounds or a cell
556
+ // size that make the cell indices non-finite; callers test it with a negated `<=` so NaN falls to the
557
+ // bounded path rather than through it.
558
+ function _spannedCellCount(cellSize, aabb) {
559
+ const cx0 = _cellIndex(aabb.minX, cellSize);
560
+ const cx1 = _cellIndex(aabb.maxX, cellSize);
561
+ const cy0 = _cellIndex(aabb.minY, cellSize);
562
+ const cy1 = _cellIndex(aabb.maxY, cellSize);
563
+ return (cx1 - cx0 + 1) * (cy1 - cy0 + 1);
344
564
  }
565
+ // Diagnostics seam filled by setSpatialIndexingGuard. Caller-facing text stays in the separate
566
+ // formatSpatialIndexingNotice module, so production pays only the null checks at noteworthy sites.
567
+ let _indexingGuard = null;
345
568
  // Reused scratch rectangles for the geometry overlap/containment helpers. Only ever read+written
346
569
  // within a single non-nested helper call, so sharing them across the module allocates nothing per
347
570
  // query without aliasing hazard.