@codexo/exojs-tilemap-physics 0.16.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Codexo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,166 @@
1
+ # @codexo/exojs-tilemap-physics
2
+
3
+ Static physics colliders from ExoJS tilemap collision geometry.
4
+
5
+ > A peer-dependency library on top of `@codexo/exojs`, `@codexo/exojs-tilemap`
6
+ > and `@codexo/exojs-physics` — construct its API directly. Importing it
7
+ > registers nothing.
8
+
9
+ `@codexo/exojs-tilemap` never imports physics and `@codexo/exojs-physics` never
10
+ imports tilemap; this package is the seam between them, so both stay usable on
11
+ their own.
12
+
13
+ ## Installation
14
+
15
+ ```sh
16
+ npm install @codexo/exojs @codexo/exojs-tilemap @codexo/exojs-physics @codexo/exojs-tilemap-physics
17
+ ```
18
+
19
+ ## Tile layers
20
+
21
+ `TileColliderStreamer` keeps a physics world's static tile colliders in sync
22
+ with a `TileLayer`: one static body per chunk-sized partition of the layer,
23
+ rebuilt when that partition is edited, destroyed when its chunk is evicted.
24
+
25
+ ```ts
26
+ import { PhysicsWorld } from '@codexo/exojs-physics';
27
+ import { TileColliderStreamer } from '@codexo/exojs-tilemap-physics';
28
+
29
+ const world = new PhysicsWorld({ gravity: { x: 0, y: 1600 } });
30
+ const colliders = new TileColliderStreamer(world, groundLayer);
31
+
32
+ scene.systems.add({
33
+ update: delta => {
34
+ colliders.sync();
35
+ world.step(delta.seconds);
36
+ },
37
+ });
38
+ ```
39
+
40
+ `sync()` is cheap to call every frame: with no change since the last call it
41
+ returns immediately and does no work. It observes the layer through its public
42
+ revision counters, so it works with `ChunkStreamer`, a hand-rolled loader, or a
43
+ bounded layer that is fully resident.
44
+
45
+ Call `destroy()` to remove every body the bridge created. Bodies it did not
46
+ create are untouched.
47
+
48
+ ## Collision authored per cell
49
+
50
+ Some editors author collision per grid cell rather than per tile - LDtk's
51
+ `IntGrid` is the common case. Pass a `cells` source and the bridge covers the
52
+ whole bounded layer, including partitions that hold no tiles at all:
53
+
54
+ ```ts
55
+ import { createLdtkIntGridCellSource } from '@codexo/exojs-ldtk';
56
+
57
+ const colliders = new TileColliderStreamer(world, collisionLayer, {
58
+ cells: createLdtkIntGridCellSource(collisionLayer),
59
+ material: ({ type }) => (type === 'Water' ? { isSensor: true } : null),
60
+ });
61
+ ```
62
+
63
+ A cell source is a plain `(tx, ty) => string | null`, so a procedural or
64
+ hand-rolled grid works the same way. The returned string is a classification,
65
+ never a meaning: it is the merge key for adjacent cells and it is what the
66
+ `material` resolver sees. Nothing in this package knows what `Solid` or `Water`
67
+ are supposed to do.
68
+
69
+ The source is sampled while a partition is built and is expected to answer
70
+ identically for the lifetime of the bridge. Changing what it returns does not
71
+ invalidate colliders that already exist - rebuild by recreating the bridge.
72
+
73
+ ## Object layers
74
+
75
+ An object layer is static data with no residency, so it gets a one-shot build:
76
+
77
+ ```ts
78
+ import { buildObjectLayerColliders } from '@codexo/exojs-tilemap-physics';
79
+
80
+ const built = buildObjectLayerColliders(world, triggersLayer, {
81
+ isSensor: true,
82
+ });
83
+
84
+ for (const { object, body } of built) {
85
+ // `object` is the source object: name, type, custom properties.
86
+ }
87
+ ```
88
+
89
+ ## Geometry mapping
90
+
91
+ | Source | Collider |
92
+ | -------------------------------------------------- | ---------------------------------------------------- |
93
+ | Merged whole-cell region (`regionMode: 'boxes'`) | one box per merged rectangle |
94
+ | Merged whole-cell region (`regionMode: 'outline'`) | one closed chain per boundary loop |
95
+ | Rectangle | box |
96
+ | Ellipse | capsule along the major axis, or a circle when round |
97
+ | Convex polygon | one polygon |
98
+ | Concave polygon | several convex polygons on the same body |
99
+ | Polyline | open chain; closed chain when its endpoints coincide |
100
+ | Point | nothing |
101
+
102
+ An ellipse maps to the capsule with the minor semi-axis as its radius and the
103
+ difference of the semi-axes as its spine. That capsule contains the ellipse and
104
+ is contained in the circumscribed circle, so it covers the source without a
105
+ tuning constant, and degenerates to a circle when the ellipse is round.
106
+
107
+ ## Region modes
108
+
109
+ `regionMode: 'boxes'` (the default) keeps merged rectangles as solid boxes. The
110
+ region has an interior, so point queries, overlaps and sensors behave, and a
111
+ body that starts inside solid tiles is pushed out. Where the merge cannot merge
112
+ — neighbouring cells with different collision semantics, staircase profiles,
113
+ partial cells — adjacent boxes share an internal edge that a body sliding across
114
+ can catch on.
115
+
116
+ `regionMode: 'outline'` traces the boundary of each solid region into closed
117
+ one-sided chains, which have no internal edges at all. It removes intra-chunk
118
+ seams between adjacent cells that resolve to the same collision semantics;
119
+ boundaries between regions with different resolved semantics remain separate, as
120
+ do chunk boundaries. The trade-off is that a chain is a boundary, not an area:
121
+ queries inside the region find nothing, and a body spawned inside it falls
122
+ through.
123
+
124
+ ## Materials
125
+
126
+ Friction, restitution, density, the sensor flag and the collision filter are
127
+ call-level defaults, optionally overridden per object:
128
+
129
+ ```ts
130
+ new TileColliderStreamer(world, groundLayer, {
131
+ friction: 0.8,
132
+ material: ({ type }) => (type === 'ice' ? { friction: 0.02 } : null),
133
+ });
134
+ ```
135
+
136
+ The resolver is a build-time mapping, not a live rule: it runs only while a
137
+ chunk is being built or rebuilt. Changing what it would return has no effect
138
+ until the layer itself changes. An unrecognised `type` is not an error — it
139
+ reaches the resolver like any other and falls back to the defaults.
140
+
141
+ In `outline` mode the resolved material also decides what may share a boundary:
142
+ cells whose colliders would be indistinguishable are traced into one chain, and
143
+ cells that resolve differently keep their own.
144
+
145
+ ## Things to know before shipping a level
146
+
147
+ - **Merging never crosses a chunk boundary.** A solid run spanning two chunks is
148
+ at least two rectangles. That is what makes the result independent of the
149
+ order chunks were loaded in.
150
+ - **A dynamic body resting on an evicted chunk falls.** Eviction is the chunk
151
+ source's decision; widen its unload radius if that matters.
152
+ - **Order is stable, part counts are not.** For a given layer and resident chunk
153
+ set the colliders are identical regardless of load order, and `bodies()`
154
+ iterates in `(cy, cx)` chunk order. The number of convex parts a concave
155
+ polygon decomposes into, and the exact rectangle decomposition of a merged
156
+ region, are not contractual.
157
+
158
+ ## Core compatibility
159
+
160
+ | `@codexo/exojs-tilemap-physics` | `@codexo/exojs` |
161
+ | ------------------------------- | --------------- |
162
+ | 0.15.x | 0.15.x |
163
+
164
+ ## License
165
+
166
+ MIT © Codexo
@@ -0,0 +1,98 @@
1
+ import { PhysicsBody, type PhysicsWorld } from '@codexo/exojs-physics';
2
+ import type { TileCellSource, TileLayer, TileMapObject } from '@codexo/exojs-tilemap';
3
+ import type { ColliderDefaults, TileRegionMode } from './types';
4
+ /** Options for a {@link TileColliderStreamer}. All optional. */
5
+ export interface TileColliderOptions extends ColliderDefaults {
6
+ /** How solid whole-cell regions are represented. Default `'boxes'`. */
7
+ regionMode?: TileRegionMode;
8
+ /**
9
+ * Merge adjacent whole-cell boxes sharing a `type` into larger rectangles.
10
+ * Default `true`. Merging never crosses a chunk boundary.
11
+ */
12
+ merge?: boolean;
13
+ /** Drop a source shape before any collider is built for it. */
14
+ accept?: (object: TileMapObject, tx: number, ty: number) => boolean;
15
+ /**
16
+ * Per-cell collision classification, for layers whose collision is authored
17
+ * per cell rather than per tile. On a bounded layer this makes the bridge
18
+ * cover the whole layer, including partitions that hold no tiles at all.
19
+ *
20
+ * Sampled while a partition is built and expected to answer identically for
21
+ * the lifetime of this bridge: changing what it returns does not invalidate
22
+ * colliders that already exist. Rebuild by recreating the bridge.
23
+ */
24
+ cells?: TileCellSource | undefined;
25
+ }
26
+ /**
27
+ * Keeps a physics world's static tile colliders in sync with a
28
+ * {@link TileLayer}: one static body per chunk-sized partition of the layer,
29
+ * rebuilt when that partition changes, destroyed when it is evicted.
30
+ *
31
+ * The bridge owns every body it creates and nothing else. It observes the layer
32
+ * through its public revision counters, so it works with any chunk source -
33
+ * {@link import('@codexo/exojs-tilemap').ChunkStreamer}, a hand-rolled loader,
34
+ * or a fully resident bounded layer.
35
+ *
36
+ * Tick it from your update loop:
37
+ *
38
+ * ```ts
39
+ * const colliders = new TileColliderStreamer(world, layer);
40
+ * scene.systems.add({ update: () => colliders.sync() });
41
+ * ```
42
+ *
43
+ * Two consequences worth knowing before shipping a level:
44
+ *
45
+ * - Whole-cell merging never crosses a partition boundary, so a solid run
46
+ * spanning two of them is at least two rectangles. This is what makes the
47
+ * result independent of the order chunks were loaded in.
48
+ * - A dynamic body resting on a chunk that gets evicted falls. Eviction is the
49
+ * chunk source's decision; widen its unload radius if that matters.
50
+ * - With {@link TileColliderOptions.cells}, a bounded layer's partitions are
51
+ * all covered, resident or not - collision authored per cell does not depend
52
+ * on tiles being placed.
53
+ */
54
+ export declare class TileColliderStreamer {
55
+ private readonly _world;
56
+ private readonly _layer;
57
+ private readonly _options;
58
+ private readonly _defaults;
59
+ private readonly _regionMode;
60
+ private readonly _built;
61
+ private readonly _seen;
62
+ private _layerRevision;
63
+ private _offsetX;
64
+ private _offsetY;
65
+ private _destroyed;
66
+ constructor(world: PhysicsWorld, layer: TileLayer, options?: TileColliderOptions);
67
+ /** Number of bodies currently owned by this bridge. */
68
+ get bodyCount(): number;
69
+ /**
70
+ * The bodies this bridge owns, in `(cy, cx)` partition order - independent of
71
+ * the order the chunks became resident in.
72
+ */
73
+ bodies(): IterableIterator<PhysicsBody>;
74
+ /**
75
+ * Bring the world's tile colliders up to date with the layer: build bodies
76
+ * for newly resident chunks, rebuild edited ones, destroy evicted ones.
77
+ *
78
+ * Cheap to call every frame. With no change since the last call it performs
79
+ * no work and allocates nothing. No-op once {@link destroy}ed or once the
80
+ * layer is destroyed.
81
+ */
82
+ sync(): void;
83
+ /**
84
+ * Destroy every body this bridge created and stop responding to
85
+ * {@link sync}. Bodies it did not create are untouched. Idempotent.
86
+ */
87
+ destroy(): void;
88
+ private _clear;
89
+ /**
90
+ * Reconcile one build block against what was built for it before. Skips
91
+ * without sampling anything when neither the backing chunk nor its revision
92
+ * moved - which is what keeps an empty cell-only block from re-walking its
93
+ * cells on every unrelated layer change.
94
+ */
95
+ private _syncBlock;
96
+ private _buildBlock;
97
+ }
98
+ //# sourceMappingURL=TileColliderStreamer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TileColliderStreamer.d.ts","sourceRoot":"","sources":["../../src/TileColliderStreamer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,KAAK,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EAAqB,cAAc,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAKzG,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEhE,gEAAgE;AAChE,MAAM,WAAW,mBAAoB,SAAQ,gBAAgB;IAC3D,uEAAuE;IACvE,UAAU,CAAC,EAAE,cAAc,CAAC;IAC5B;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,+DAA+D;IAC/D,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,aAAa,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,OAAO,CAAC;IACpE;;;;;;;;OAQG;IACH,KAAK,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;CACpC;AAgCD;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,qBAAa,oBAAoB;IAC/B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAe;IACtC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAY;IACnC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAsB;IAC/C,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAmB;IAC7C,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAiB;IAE7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiC;IACxD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAqB;IAE3C,OAAO,CAAC,cAAc,CAAM;IAC5B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,UAAU,CAAS;gBAER,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,SAAS,EAAE,OAAO,GAAE,mBAAwB;IAU3F,uDAAuD;IACvD,IAAW,SAAS,IAAI,MAAM,CAQ7B;IAED;;;OAGG;IACK,MAAM,IAAI,gBAAgB,CAAC,WAAW,CAAC;IAQ/C;;;;;;;OAOG;IACI,IAAI,IAAI,IAAI;IAkDnB;;;OAGG;IACI,OAAO,IAAI,IAAI;IAMtB,OAAO,CAAC,MAAM;IASd;;;;;OAKG;IACH,OAAO,CAAC,UAAU;IAqBlB,OAAO,CAAC,WAAW;CAsCpB"}
@@ -0,0 +1,191 @@
1
+ import { resolveDefaults } from "./material.js";
2
+ import { buildTileColliders } from "./buildColliders.js";
3
+ import { PhysicsBody } from "@codexo/exojs-physics";
4
+ import { buildTileCollisionGeometry } from "@codexo/exojs-tilemap";
5
+
6
+ //#region src/TileColliderStreamer.ts
7
+ const chunkKey = (cx, cy) => `${cx},${cy}`;
8
+ /**
9
+ * Tile extent of a build block along one axis. Edge blocks of a bounded layer
10
+ * are clipped, matching the dimensions the layer gives an edge chunk, so a
11
+ * cell-only block never walks cells outside the layer.
12
+ */
13
+ const blockExtent = (chunkExtent, layerExtent, start) => layerExtent === void 0 ? chunkExtent : Math.min(chunkExtent, layerExtent - start);
14
+ /**
15
+ * Keeps a physics world's static tile colliders in sync with a
16
+ * {@link TileLayer}: one static body per chunk-sized partition of the layer,
17
+ * rebuilt when that partition changes, destroyed when it is evicted.
18
+ *
19
+ * The bridge owns every body it creates and nothing else. It observes the layer
20
+ * through its public revision counters, so it works with any chunk source -
21
+ * {@link import('@codexo/exojs-tilemap').ChunkStreamer}, a hand-rolled loader,
22
+ * or a fully resident bounded layer.
23
+ *
24
+ * Tick it from your update loop:
25
+ *
26
+ * ```ts
27
+ * const colliders = new TileColliderStreamer(world, layer);
28
+ * scene.systems.add({ update: () => colliders.sync() });
29
+ * ```
30
+ *
31
+ * Two consequences worth knowing before shipping a level:
32
+ *
33
+ * - Whole-cell merging never crosses a partition boundary, so a solid run
34
+ * spanning two of them is at least two rectangles. This is what makes the
35
+ * result independent of the order chunks were loaded in.
36
+ * - A dynamic body resting on a chunk that gets evicted falls. Eviction is the
37
+ * chunk source's decision; widen its unload radius if that matters.
38
+ * - With {@link TileColliderOptions.cells}, a bounded layer's partitions are
39
+ * all covered, resident or not - collision authored per cell does not depend
40
+ * on tiles being placed.
41
+ */
42
+ var TileColliderStreamer = class {
43
+ _world;
44
+ _layer;
45
+ _options;
46
+ _defaults;
47
+ _regionMode;
48
+ _built = /* @__PURE__ */ new Map();
49
+ _seen = /* @__PURE__ */ new Set();
50
+ _layerRevision = -1;
51
+ _offsetX;
52
+ _offsetY;
53
+ _destroyed = false;
54
+ constructor(world, layer, options = {}) {
55
+ this._world = world;
56
+ this._layer = layer;
57
+ this._options = options;
58
+ this._defaults = resolveDefaults(options);
59
+ this._regionMode = options.regionMode ?? "boxes";
60
+ this._offsetX = layer.offsetX;
61
+ this._offsetY = layer.offsetY;
62
+ }
63
+ /** Number of bodies currently owned by this bridge. */
64
+ get bodyCount() {
65
+ let count = 0;
66
+ for (const entry of this._built.values()) if (entry.body !== null) count++;
67
+ return count;
68
+ }
69
+ /**
70
+ * The bodies this bridge owns, in `(cy, cx)` partition order - independent of
71
+ * the order the chunks became resident in.
72
+ */
73
+ *bodies() {
74
+ const ordered = [...this._built.values()].sort((a, b) => a.cy - b.cy || a.cx - b.cx);
75
+ for (const entry of ordered) if (entry.body !== null) yield entry.body;
76
+ }
77
+ /**
78
+ * Bring the world's tile colliders up to date with the layer: build bodies
79
+ * for newly resident chunks, rebuild edited ones, destroy evicted ones.
80
+ *
81
+ * Cheap to call every frame. With no change since the last call it performs
82
+ * no work and allocates nothing. No-op once {@link destroy}ed or once the
83
+ * layer is destroyed.
84
+ */
85
+ sync() {
86
+ if (this._destroyed || this._layer.destroyed) return;
87
+ const layer = this._layer;
88
+ const offsetChanged = layer.offsetX !== this._offsetX || layer.offsetY !== this._offsetY;
89
+ if (!offsetChanged && layer.revision === this._layerRevision) return;
90
+ if (offsetChanged) {
91
+ this._clear();
92
+ this._offsetX = layer.offsetX;
93
+ this._offsetY = layer.offsetY;
94
+ }
95
+ const seen = this._seen;
96
+ seen.clear();
97
+ for (const chunk of layer.loadedChunks()) this._syncBlock(chunk.cx, chunk.cy, chunk);
98
+ if (this._options.cells !== void 0) {
99
+ const range = layer.chunkRange();
100
+ if (range !== null) for (let cy = range.minCy; cy <= range.maxCy; cy++) for (let cx = range.minCx; cx <= range.maxCx; cx++) this._syncBlock(cx, cy, layer.getChunk(cx, cy) ?? null);
101
+ }
102
+ for (const [key, entry] of this._built) {
103
+ if (seen.has(key)) continue;
104
+ if (entry.body !== null) this._world.destroyBody(entry.body);
105
+ this._built.delete(key);
106
+ }
107
+ this._layerRevision = layer.revision;
108
+ }
109
+ /**
110
+ * Destroy every body this bridge created and stop responding to
111
+ * {@link sync}. Bodies it did not create are untouched. Idempotent.
112
+ */
113
+ destroy() {
114
+ if (this._destroyed) return;
115
+ this._destroyed = true;
116
+ this._clear();
117
+ }
118
+ _clear() {
119
+ for (const entry of this._built.values()) if (entry.body !== null) this._world.destroyBody(entry.body);
120
+ this._built.clear();
121
+ this._layerRevision = -1;
122
+ }
123
+ /**
124
+ * Reconcile one build block against what was built for it before. Skips
125
+ * without sampling anything when neither the backing chunk nor its revision
126
+ * moved - which is what keeps an empty cell-only block from re-walking its
127
+ * cells on every unrelated layer change.
128
+ */
129
+ _syncBlock(cx, cy, chunk) {
130
+ const key = chunkKey(cx, cy);
131
+ if (this._seen.has(key)) return;
132
+ this._seen.add(key);
133
+ const entry = this._built.get(key);
134
+ const revision = chunk?.revision ?? -1;
135
+ if (entry?.chunk === chunk && entry.revision === revision) return;
136
+ if (entry?.body != null) this._world.destroyBody(entry.body);
137
+ this._built.set(key, {
138
+ cx,
139
+ cy,
140
+ chunk,
141
+ revision,
142
+ body: this._buildBlock(cx, cy, chunk)
143
+ });
144
+ }
145
+ _buildBlock(cx, cy, chunk) {
146
+ const layer = this._layer;
147
+ const options = this._options;
148
+ const startTx = cx * layer.chunkWidth;
149
+ const startTy = cy * layer.chunkHeight;
150
+ const width = chunk?.width ?? blockExtent(layer.chunkWidth, layer.width, startTx);
151
+ const height = chunk?.height ?? blockExtent(layer.chunkHeight, layer.height, startTy);
152
+ const geometry = buildTileCollisionGeometry(layer, {
153
+ region: {
154
+ x: startTx,
155
+ y: startTy,
156
+ width,
157
+ height
158
+ },
159
+ ...options.merge !== void 0 && { merge: options.merge },
160
+ ...options.accept !== void 0 && { accept: options.accept },
161
+ ...options.cells !== void 0 && { cells: options.cells }
162
+ });
163
+ if (geometry.rects.length === 0 && geometry.shapes.length === 0) return null;
164
+ const x = startTx * layer.tileWidth + layer.offsetX;
165
+ const y = startTy * layer.tileHeight + layer.offsetY;
166
+ const colliders = buildTileColliders(geometry, {
167
+ x,
168
+ y,
169
+ tileWidth: layer.tileWidth,
170
+ tileHeight: layer.tileHeight,
171
+ layerOffsetX: layer.offsetX,
172
+ layerOffsetY: layer.offsetY,
173
+ regionMode: this._regionMode,
174
+ defaults: this._defaults,
175
+ material: options.material
176
+ });
177
+ if (colliders.length === 0) return null;
178
+ return this._world.add(new PhysicsBody({
179
+ type: "static",
180
+ position: {
181
+ x,
182
+ y
183
+ },
184
+ colliders
185
+ }));
186
+ }
187
+ };
188
+
189
+ //#endregion
190
+ export { TileColliderStreamer };
191
+ //# sourceMappingURL=TileColliderStreamer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TileColliderStreamer.js","names":[],"sources":["../../src/TileColliderStreamer.ts"],"sourcesContent":["import { PhysicsBody, type PhysicsWorld } from '@codexo/exojs-physics';\nimport type { ReadonlyTileChunk, TileCellSource, TileLayer, TileMapObject } from '@codexo/exojs-tilemap';\nimport { buildTileCollisionGeometry } from '@codexo/exojs-tilemap';\n\nimport { buildTileColliders } from './buildColliders';\nimport { resolveDefaults, type ResolvedMaterial } from './material';\nimport type { ColliderDefaults, TileRegionMode } from './types';\n\n/** Options for a {@link TileColliderStreamer}. All optional. */\nexport interface TileColliderOptions extends ColliderDefaults {\n /** How solid whole-cell regions are represented. Default `'boxes'`. */\n regionMode?: TileRegionMode;\n /**\n * Merge adjacent whole-cell boxes sharing a `type` into larger rectangles.\n * Default `true`. Merging never crosses a chunk boundary.\n */\n merge?: boolean;\n /** Drop a source shape before any collider is built for it. */\n accept?: (object: TileMapObject, tx: number, ty: number) => boolean;\n /**\n * Per-cell collision classification, for layers whose collision is authored\n * per cell rather than per tile. On a bounded layer this makes the bridge\n * cover the whole layer, including partitions that hold no tiles at all.\n *\n * Sampled while a partition is built and expected to answer identically for\n * the lifetime of this bridge: changing what it returns does not invalidate\n * colliders that already exist. Rebuild by recreating the bridge.\n */\n cells?: TileCellSource | undefined;\n}\n\n/**\n * One collision build block: the deterministic spatial partition this bridge\n * may own a body for. A partition is not the same thing as tile residency - a\n * cell source covers partitions that hold no {@link ReadonlyTileChunk} at all,\n * and nothing here makes a non-resident chunk look resident.\n *\n * An entry with `body === null` is a cached empty result, not an absence: it\n * is what keeps an unrelated layer revision from re-walking every cell of\n * every empty partition.\n */\ninterface BlockEntry {\n readonly cx: number;\n readonly cy: number;\n /** The chunk the body was built from; `null` for a cell-only partition. A re-adopted chunk is a new one. */\n readonly chunk: ReadonlyTileChunk | null;\n readonly revision: number;\n /** `null` when the partition holds no collision geometry at all. */\n readonly body: PhysicsBody | null;\n}\n\nconst chunkKey = (cx: number, cy: number): string => `${cx},${cy}`;\n\n/**\n * Tile extent of a build block along one axis. Edge blocks of a bounded layer\n * are clipped, matching the dimensions the layer gives an edge chunk, so a\n * cell-only block never walks cells outside the layer.\n */\nconst blockExtent = (chunkExtent: number, layerExtent: number | undefined, start: number): number =>\n layerExtent === undefined ? chunkExtent : Math.min(chunkExtent, layerExtent - start);\n\n/**\n * Keeps a physics world's static tile colliders in sync with a\n * {@link TileLayer}: one static body per chunk-sized partition of the layer,\n * rebuilt when that partition changes, destroyed when it is evicted.\n *\n * The bridge owns every body it creates and nothing else. It observes the layer\n * through its public revision counters, so it works with any chunk source -\n * {@link import('@codexo/exojs-tilemap').ChunkStreamer}, a hand-rolled loader,\n * or a fully resident bounded layer.\n *\n * Tick it from your update loop:\n *\n * ```ts\n * const colliders = new TileColliderStreamer(world, layer);\n * scene.systems.add({ update: () => colliders.sync() });\n * ```\n *\n * Two consequences worth knowing before shipping a level:\n *\n * - Whole-cell merging never crosses a partition boundary, so a solid run\n * spanning two of them is at least two rectangles. This is what makes the\n * result independent of the order chunks were loaded in.\n * - A dynamic body resting on a chunk that gets evicted falls. Eviction is the\n * chunk source's decision; widen its unload radius if that matters.\n * - With {@link TileColliderOptions.cells}, a bounded layer's partitions are\n * all covered, resident or not - collision authored per cell does not depend\n * on tiles being placed.\n */\nexport class TileColliderStreamer {\n private readonly _world: PhysicsWorld;\n private readonly _layer: TileLayer;\n private readonly _options: TileColliderOptions;\n private readonly _defaults: ResolvedMaterial;\n private readonly _regionMode: TileRegionMode;\n\n private readonly _built = new Map<string, BlockEntry>();\n private readonly _seen = new Set<string>();\n\n private _layerRevision = -1;\n private _offsetX: number;\n private _offsetY: number;\n private _destroyed = false;\n\n public constructor(world: PhysicsWorld, layer: TileLayer, options: TileColliderOptions = {}) {\n this._world = world;\n this._layer = layer;\n this._options = options;\n this._defaults = resolveDefaults(options);\n this._regionMode = options.regionMode ?? 'boxes';\n this._offsetX = layer.offsetX;\n this._offsetY = layer.offsetY;\n }\n\n /** Number of bodies currently owned by this bridge. */\n public get bodyCount(): number {\n let count = 0;\n\n for (const entry of this._built.values()) {\n if (entry.body !== null) count++;\n }\n\n return count;\n }\n\n /**\n * The bodies this bridge owns, in `(cy, cx)` partition order - independent of\n * the order the chunks became resident in.\n */\n public *bodies(): IterableIterator<PhysicsBody> {\n const ordered = [...this._built.values()].sort((a, b) => a.cy - b.cy || a.cx - b.cx);\n\n for (const entry of ordered) {\n if (entry.body !== null) yield entry.body;\n }\n }\n\n /**\n * Bring the world's tile colliders up to date with the layer: build bodies\n * for newly resident chunks, rebuild edited ones, destroy evicted ones.\n *\n * Cheap to call every frame. With no change since the last call it performs\n * no work and allocates nothing. No-op once {@link destroy}ed or once the\n * layer is destroyed.\n */\n public sync(): void {\n if (this._destroyed || this._layer.destroyed) return;\n\n const layer = this._layer;\n const offsetChanged = layer.offsetX !== this._offsetX || layer.offsetY !== this._offsetY;\n\n if (!offsetChanged && layer.revision === this._layerRevision) return;\n\n if (offsetChanged) {\n // Geometry is emitted in layer pixel space, so a moved layer invalidates\n // every collider - and moving a layer does not bump its revision.\n this._clear();\n this._offsetX = layer.offsetX;\n this._offsetY = layer.offsetY;\n }\n\n const seen = this._seen;\n\n seen.clear();\n\n for (const chunk of layer.loadedChunks()) {\n this._syncBlock(chunk.cx, chunk.cy, chunk);\n }\n\n // A cell source covers the layer, not its residency: every partition of a\n // bounded layer is a build block, whether or not tiles were ever placed in\n // it. Without this the canonical case - collision authored per cell on a\n // layer that renders nothing - would produce no bodies at all.\n if (this._options.cells !== undefined) {\n const range = layer.chunkRange();\n\n if (range !== null) {\n for (let cy = range.minCy; cy <= range.maxCy; cy++) {\n for (let cx = range.minCx; cx <= range.maxCx; cx++) {\n this._syncBlock(cx, cy, layer.getChunk(cx, cy) ?? null);\n }\n }\n }\n }\n\n for (const [key, entry] of this._built) {\n if (seen.has(key)) continue;\n\n if (entry.body !== null) this._world.destroyBody(entry.body);\n this._built.delete(key);\n }\n\n this._layerRevision = layer.revision;\n }\n\n /**\n * Destroy every body this bridge created and stop responding to\n * {@link sync}. Bodies it did not create are untouched. Idempotent.\n */\n public destroy(): void {\n if (this._destroyed) return;\n this._destroyed = true;\n this._clear();\n }\n\n private _clear(): void {\n for (const entry of this._built.values()) {\n if (entry.body !== null) this._world.destroyBody(entry.body);\n }\n\n this._built.clear();\n this._layerRevision = -1;\n }\n\n /**\n * Reconcile one build block against what was built for it before. Skips\n * without sampling anything when neither the backing chunk nor its revision\n * moved - which is what keeps an empty cell-only block from re-walking its\n * cells on every unrelated layer change.\n */\n private _syncBlock(cx: number, cy: number, chunk: ReadonlyTileChunk | null): void {\n const key = chunkKey(cx, cy);\n\n if (this._seen.has(key)) return;\n\n this._seen.add(key);\n\n const entry = this._built.get(key);\n const revision = chunk?.revision ?? -1;\n\n if (entry?.chunk === chunk && entry.revision === revision) {\n return;\n }\n\n if (entry?.body != null) {\n this._world.destroyBody(entry.body);\n }\n\n this._built.set(key, { cx, cy, chunk, revision, body: this._buildBlock(cx, cy, chunk) });\n }\n\n private _buildBlock(cx: number, cy: number, chunk: ReadonlyTileChunk | null): PhysicsBody | null {\n const layer = this._layer;\n const options = this._options;\n const startTx = cx * layer.chunkWidth;\n const startTy = cy * layer.chunkHeight;\n const width = chunk?.width ?? blockExtent(layer.chunkWidth, layer.width, startTx);\n const height = chunk?.height ?? blockExtent(layer.chunkHeight, layer.height, startTy);\n const geometry = buildTileCollisionGeometry(layer, {\n region: { x: startTx, y: startTy, width, height },\n ...(options.merge !== undefined && { merge: options.merge }),\n ...(options.accept !== undefined && { accept: options.accept }),\n ...(options.cells !== undefined && { cells: options.cells }),\n });\n\n if (geometry.rects.length === 0 && geometry.shapes.length === 0) {\n return null;\n }\n\n const x = startTx * layer.tileWidth + layer.offsetX;\n const y = startTy * layer.tileHeight + layer.offsetY;\n const colliders = buildTileColliders(geometry, {\n x,\n y,\n tileWidth: layer.tileWidth,\n tileHeight: layer.tileHeight,\n layerOffsetX: layer.offsetX,\n layerOffsetY: layer.offsetY,\n regionMode: this._regionMode,\n defaults: this._defaults,\n material: options.material,\n });\n\n if (colliders.length === 0) {\n return null;\n }\n\n return this._world.add(new PhysicsBody({ type: 'static', position: { x, y }, colliders }));\n }\n}\n"],"mappings":";;;;;;AAmDA,MAAM,YAAY,IAAY,OAAuB,GAAG,GAAG,GAAG;;;;;;AAO9D,MAAM,eAAe,aAAqB,aAAiC,UACzE,gBAAgB,SAAY,cAAc,KAAK,IAAI,aAAa,cAAc,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BrF,IAAa,uBAAb,MAAkC;CAChC,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAEjB,AAAiB,yBAAS,IAAI,IAAwB;CACtD,AAAiB,wBAAQ,IAAI,IAAY;CAEzC,AAAQ,iBAAiB;CACzB,AAAQ;CACR,AAAQ;CACR,AAAQ,aAAa;CAErB,AAAO,YAAY,OAAqB,OAAkB,UAA+B,CAAC,GAAG;EAC3F,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,WAAW;EAChB,KAAK,YAAY,gBAAgB,OAAO;EACxC,KAAK,cAAc,QAAQ,cAAc;EACzC,KAAK,WAAW,MAAM;EACtB,KAAK,WAAW,MAAM;CACxB;;CAGA,IAAW,YAAoB;EAC7B,IAAI,QAAQ;EAEZ,KAAK,MAAM,SAAS,KAAK,OAAO,OA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Q,MAAM;EAC5D,CAAC;EAED,IAAI,SAAS,MAAM,WAAW,KAAK,SAAS,OAAO,WAAW,GAC5D,OAAO;EAGT,MAAM,IAAI,UAAU,MAAM,YAAY,MAAM;EAC5C,MAAM,IAAI,UAAU,MAAM,aAAa,MAAM;EAC7C,MAAM,YAAY,mBAAmB,UAAU;GAC7C;GACA;GACA,WAAW,MAAM;GACjB,YAAY,MAAM;GAClB,cAAc,MAAM;GACpB,cAAc,MAAM;GACpB,YAAY,KAAK;GACjB,UAAU,KAAK;GACf,UAAU,QAAQ;EACpB,CAAC;EAED,IAAI,UAAU,WAAW,GACvB,OAAO;EAGT,OAAO,KAAK,OAAO,IAAI,IAAI,YAAY;GAAE,MAAM;GAAU,UAAU;IAAE;IAAG;GAAE;GAAG;EAAU,CAAC,CAAC;CAC3F;AACF"}
@@ -0,0 +1,53 @@
1
+ import { type PointLike } from '@codexo/exojs';
2
+ import { type ColliderOptions } from '@codexo/exojs-physics';
3
+ import { ObjectKind, type TileCollisionGeometry, type TileMapObject } from '@codexo/exojs-tilemap';
4
+ import { type ResolvedMaterial } from './material';
5
+ import type { TileColliderMaterialResolver, TileRegionMode } from './types';
6
+ /** Placement of one piece of geometry in the owning body's local space. */
7
+ export interface ColliderPlacement {
8
+ readonly x: number;
9
+ readonly y: number;
10
+ readonly tileWidth: number;
11
+ readonly tileHeight: number;
12
+ readonly layerOffsetX: number;
13
+ readonly layerOffsetY: number;
14
+ }
15
+ /** Everything a build needs beyond the geometry itself. */
16
+ export interface ColliderBuildOptions extends ColliderPlacement {
17
+ readonly regionMode: TileRegionMode;
18
+ readonly defaults: ResolvedMaterial;
19
+ readonly material: TileColliderMaterialResolver | undefined;
20
+ }
21
+ /**
22
+ * The fields an object-layer object and a per-tile collision shape share -
23
+ * enough to pick a shape. Both are structurally assignable to it.
24
+ */
25
+ export interface CollisionGeometry {
26
+ readonly kind: ObjectKind;
27
+ readonly x: number;
28
+ readonly y: number;
29
+ readonly width: number;
30
+ readonly height: number;
31
+ readonly rotation: number;
32
+ readonly points?: readonly PointLike[];
33
+ }
34
+ /**
35
+ * Map one piece of collision geometry to the colliders that represent it, in
36
+ * the owning body's local space.
37
+ *
38
+ * A concave polygon becomes several convex colliders on the same body; a
39
+ * polygon the decomposition rejects is skipped with a warning rather than
40
+ * failing the whole build, because level geometry is content, not code.
41
+ */
42
+ export declare const collidersForGeometry: (geometry: CollisionGeometry, material: ResolvedMaterial, originX: number, originY: number, label: string) => ColliderOptions[];
43
+ declare const objectLabel: (object: TileMapObject) => string;
44
+ export { objectLabel };
45
+ /**
46
+ * Turn extracted tile-collision geometry into the colliders of a single body
47
+ * placed at `(options.x, options.y)` in layer pixel space.
48
+ *
49
+ * Order is contractual: merged regions first in the order the extraction emits
50
+ * them, then per-tile shapes in tile walk order.
51
+ */
52
+ export declare const buildTileColliders: (geometry: TileCollisionGeometry, options: ColliderBuildOptions) => ColliderOptions[];
53
+ //# sourceMappingURL=buildColliders.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buildColliders.d.ts","sourceRoot":"","sources":["../../src/buildColliders.ts"],"names":[],"mappings":"AAAA,OAAO,EAAU,KAAK,SAAS,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAmD,KAAK,eAAe,EAAyB,MAAM,uBAAuB,CAAC;AACrI,OAAO,EAAE,UAAU,EAAE,KAAK,qBAAqB,EAAmD,KAAK,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAEpJ,OAAO,EAAe,KAAK,gBAAgB,EAAmB,MAAM,YAAY,CAAC;AAEjF,OAAO,KAAK,EAAE,4BAA4B,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAS5E,2EAA2E;AAC3E,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,UAAU,EAAE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