@margoengine/tilemap 0.1.0 → 1.0.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 +201 -201
- package/NOTICE +4 -4
- package/README.md +388 -294
- package/dist/grid-search-B0VbYKpe.js +98 -0
- package/dist/grid-search.d.ts +33 -0
- package/dist/hpa.d.ts +87 -0
- package/dist/hpa.js +239 -0
- package/dist/iso-C2Hwh5Gr.js +4 -4
- package/dist/objects-BK2mewd1.js +4 -4
- package/dist/path.d.ts +15 -1
- package/dist/path.js +90 -118
- package/dist/plane.js +3 -3
- package/dist/replan.d.ts +58 -0
- package/dist/replan.js +114 -0
- package/dist/src-CJvCfCkX.js +4 -4
- package/package.json +98 -90
package/README.md
CHANGED
|
@@ -1,294 +1,388 @@
|
|
|
1
|
-
# @margoengine/tilemap
|
|
2
|
-
|
|
3
|
-
Import `margoengine/tilemap` from the `margoengine` package, or `@margoengine/tilemap` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
|
|
4
|
-
|
|
5
|
-
The 2D tile map format every other piece builds on: `TileMapData` holds the tile size, tilesets with per-tile properties, animation and collision shapes, tile layers as `Uint32Array` with Tiled's flip bits, object layers, parallax, offset, opacity and custom properties. The root entry has the types, small helpers and the `TileMap` renderer; auto-tiling and the Tiled importer are their own entries. `TileMap` draws orthogonal maps; `GridTileMap` of the `iso` entry draws isometric, staggered and hexagonal ones. (`@margoengine/tiles` is OGC 3D Tiles; this package is unrelated.)
|
|
6
|
-
|
|
7
|
-
```ts
|
|
8
|
-
import {createTileLayer, encodeTile, FLIP_H, tileAt, validateTileMap, type TileMapData} from 'margoengine/tilemap';
|
|
9
|
-
const ground = createTileLayer('ground', 2, 2, Uint32Array.of(1, encodeTile(2, FLIP_H), 0, 1));
|
|
10
|
-
const map: TileMapData = {
|
|
11
|
-
width: 2, height: 2, tileWidth: 16, tileHeight: 16, layers: [ground],
|
|
12
|
-
tilesets: [{name: 'grass', firstGid: 1, tileWidth: 16, tileHeight: 16, tileCount: 2, columns: 2,
|
|
13
|
-
image: {source: 'grass.png', width: 32, height: 16}, tiles: [{id: 1, properties: {solid: true}}]}],
|
|
14
|
-
};
|
|
15
|
-
validateTileMap(map);
|
|
16
|
-
console.log(tileAt(ground, 1, 0)); // 2147483650: tile 2, mirrored left to right
|
|
17
|
-
```
|
|
18
|
-
|
|
19
|
-
Layer values keep the low 28 bits for the global tile id (0 is empty) and the top bits for `FLIP_H`, `FLIP_V` and `FLIP_D`, exactly as Tiled stores them, so imported data is used as is. `decodeTile` and `encodeTile` split and join them; `tilesetForGid` and `tileDefForGid` find the tileset and the per-tile entry; `validateTileMap` throws a `TypeError` or `RangeError` that names the field.
|
|
20
|
-
|
|
21
|
-
## Drawing a map
|
|
22
|
-
|
|
23
|
-
`TileMap` draws the tile layers with exact pixels: one instanced draw per visible 64 x 64 chunk per tileset, texels read with no filtering. Pass each tileset's atlas by name, as pixels, an `ImageBitmap`, a `GPUTexture` or a function.
|
|
24
|
-
|
|
25
|
-
```ts
|
|
26
|
-
import {EngineKernel} from 'margoengine/core';
|
|
27
|
-
import {createTileLayer, TileMap, type TileMapData} from 'margoengine/tilemap';
|
|
28
|
-
const canvas = document.querySelector('canvas')!;
|
|
29
|
-
const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [320, 180]});
|
|
30
|
-
const map: TileMapData = {
|
|
31
|
-
width: 2, height: 1, tileWidth: 16, tileHeight: 16,
|
|
32
|
-
layers: [createTileLayer('ground', 2, 1, Uint32Array.of(1, 2))],
|
|
33
|
-
tilesets: [{name: 'grass', firstGid: 1, tileWidth: 16, tileHeight: 16, tileCount: 2, columns: 2}],
|
|
34
|
-
};
|
|
35
|
-
const image = await createImageBitmap(await (await fetch('grass.png')).blob());
|
|
36
|
-
const tiles = TileMap.attach(engine, {map, atlases: {grass: image}, camera: {x: 0, y: 0, zoom: 1}});
|
|
37
|
-
tiles.setTile('ground', 1, 0, 1); // only this cell's chunk goes up again
|
|
38
|
-
engine.render({delta: 1 / 60});
|
|
39
|
-
console.log(tiles.stats.draws); // 1
|
|
40
|
-
tiles.visible = false; // draws nothing and costs no draw calls, uploads or target clears
|
|
41
|
-
engine.render({delta: 1 / 60});
|
|
42
|
-
console.log(tiles.stats.draws); // 0
|
|
43
|
-
tiles.visible = true; // draws exactly as before
|
|
44
|
-
```
|
|
45
|
-
|
|
46
|
-
| Option | Default | What it does |
|
|
47
|
-
| --- | --- | --- |
|
|
48
|
-
| `map` | required | The `TileMapData`. `setMap` swaps it |
|
|
49
|
-
| `atlases` | required | Tileset name to atlas. `setAtlas` swaps one |
|
|
50
|
-
| `camera` | `{x: 0, y: 0, zoom: 1}` | Map point at the top left and target pixels per map pixel, read each frame |
|
|
51
|
-
| `snap` | `true` | Rounds each layer's top left to a whole pixel, read each frame |
|
|
52
|
-
| `mapLayers` | every tile layer | Names of the tile layers to draw |
|
|
53
|
-
| `parallax` | `true` | Scrolls each layer by its own `parallax`; false when the camera carries it |
|
|
54
|
-
| `target` | the frame's colour target | Draw into this texture, or a function returning one |
|
|
55
|
-
| `clear` | the map's `backgroundColor`, else transparent | With `target`: colour to clear to, false draws over it |
|
|
56
|
-
| `order` | `10` | Frame-graph order |
|
|
57
|
-
| `layers` | `1` | Render-layer bits |
|
|
58
|
-
| `name` | `tilemap-1`, ... | Plugin name, unique per scene |
|
|
59
|
-
|
|
60
|
-
The `visible` property (default `true`) can be set at any time: a hidden map draws nothing, so with a `target` that target is not cleared either; setting it back to true draws the same pixels. It does not change the map's own layer `visible` flags.
|
|
61
|
-
|
|
62
|
-
### Atlases and targets across a device restore
|
|
63
|
-
|
|
64
|
-
Pass a `GPUTexture` atlas as a function of the device: the map calls it once per device, so after a driver reset or
|
|
65
|
-
`rebootDevice()` the tiles come back by themselves.
|
|
66
|
-
|
|
67
|
-
```ts
|
|
68
|
-
import {EngineKernel} from 'margoengine/core';
|
|
69
|
-
import {createTileLayer, TileMap} from 'margoengine/tilemap';
|
|
70
|
-
const engine = await EngineKernel.create(document.querySelector('canvas')!, {exactSize: [64, 32]});
|
|
71
|
-
const tiles = TileMap.attach(engine, {
|
|
72
|
-
map: {
|
|
73
|
-
width: 2, height: 1, tileWidth: 2, tileHeight: 2,
|
|
74
|
-
layers: [createTileLayer('ground', 2, 1, Uint32Array.of(1, 2))],
|
|
75
|
-
tilesets: [{name: 'grass', firstGid: 1, tileWidth: 2, tileHeight: 2, tileCount: 2, columns: 2}],
|
|
76
|
-
},
|
|
77
|
-
atlases: {
|
|
78
|
-
grass: (device: GPUDevice) => {
|
|
79
|
-
const texture = device.createTexture({
|
|
80
|
-
size: [4, 2], format: 'rgba8unorm', usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
|
|
81
|
-
});
|
|
82
|
-
device.queue.writeTexture({texture}, new Uint8Array(32).fill(255), {bytesPerRow: 16}, [4, 2]);
|
|
83
|
-
return texture;
|
|
84
|
-
},
|
|
85
|
-
},
|
|
86
|
-
});
|
|
87
|
-
engine.render({delta: 1 / 60});
|
|
88
|
-
console.log(tiles.stats.draws); // 1
|
|
89
|
-
```
|
|
90
|
-
|
|
91
|
-
A plain `GPUTexture` (atlas, image or `target`) belongs to the device that made it. After a device restore the map
|
|
92
|
-
drops it, reports it once through `engine.onError` (`MargoError` `'state'`, help `borrowed-lost`) and skips what it
|
|
93
|
-
drew while the rest of the frame goes on, until `setAtlas`, `setImage` or `setTarget` hands in one made on
|
|
94
|
-
`engine.gpu`, for example from your own plugin's `onDeviceRestored(engine)`. `GridTileMap` and `ObjectTileMap` follow
|
|
95
|
-
the same rule.
|
|
96
|
-
|
|
97
|
-
To draw into a compositor layer of `margoengine/pixel`, pass `target: layer.target, camera: layer.camera, parallax: false, mapLayers: ['ground']`, with one `TileMap` per layer that scrolls on its own.
|
|
98
|
-
|
|
99
|
-
Tiles animate by their `animation` steps on the `time` clock (milliseconds; each frame adds its delta), which changes a small lookup and no cells. A tile larger than the cell sits on the cell's bottom left, as in Tiled. Layer `offset`, `opacity`, `tint`, `visible` and `parallax` and tileset `margin`, `spacing` and `tileOffset` are honoured. Overlapping oversize tiles of different tilesets draw tileset by tileset. Object layers are data only: draw tile objects with `margoengine/sprites`. Image collection tilesets (`columns: 0`) must be packed into one atlas first. After writing into `layer.data` yourself, call `invalidate(layer)`.
|
|
100
|
-
|
|
101
|
-
## Isometric, staggered and hexagonal maps
|
|
102
|
-
|
|
103
|
-
`margoengine/tilemap/iso` places cells the way Tiled does for every `orientation`: isometric diamonds, staggered
|
|
104
|
-
diamonds whose rows (or columns) are pushed half a cell, and hexagons with flat sides of `hexSideLength`. `GridTileMap`
|
|
105
|
-
draws them with exact texels, the cells in view back to front so tiles taller than their cell (walls, trees) cover the
|
|
106
|
-
cells behind them. `margoengine/tilemap/hex` adds cube coordinates for distances, rings and lines.
|
|
107
|
-
|
|
108
|
-
```ts
|
|
109
|
-
import { EngineKernel } from 'margoengine/core';
|
|
110
|
-
import { createTileLayer, type TileMapData } from 'margoengine/tilemap';
|
|
111
|
-
import { cellCenter, GridTileMap, pixelToCell } from 'margoengine/tilemap/iso';
|
|
112
|
-
import { hexDistance, hexRing } from 'margoengine/tilemap/hex';
|
|
113
|
-
|
|
114
|
-
const engine = await EngineKernel.create(document.querySelector('canvas')!, { exactSize: [160, 90] });
|
|
115
|
-
// Two 16 x 8 diamond tiles: grass and stone.
|
|
116
|
-
const data = new Uint8Array(32 * 8 * 4);
|
|
117
|
-
for (let y = 0; y < 8; y++)
|
|
118
|
-
for (let x = 0; x < 32; x++)
|
|
119
|
-
if (Math.abs((x % 16) + 0.5 - 8) / 8 + Math.abs(y + 0.5 - 4) / 4 <= 1)
|
|
120
|
-
data.set(x < 16 ? [70, 160, 60, 255] : [150, 150, 160, 255], (y * 32 + x) * 4);
|
|
121
|
-
const map: TileMapData = {
|
|
122
|
-
orientation: 'isometric', width: 8, height: 8, tileWidth: 16, tileHeight: 8,
|
|
123
|
-
layers: [createTileLayer('ground', 8, 8, new Uint32Array(64).map((_, i) => 1 + ((i >> 3) % 2)))],
|
|
124
|
-
tilesets: [{ name: 'floor', firstGid: 1, tileWidth: 16, tileHeight: 8, tileCount: 2, columns: 2 }],
|
|
125
|
-
};
|
|
126
|
-
GridTileMap.attach(engine, { map, atlases: { floor: { width: 32, height: 8, data } }, camera: { x: -16, y: -10, zoom: 1 } });
|
|
127
|
-
engine.start();
|
|
128
|
-
|
|
129
|
-
console.log(pixelToCell(map, ...cellCenter(map, 3, 5))); // [3, 5]
|
|
130
|
-
const hexes: TileMapData = { ...map, orientation: 'hexagonal', hexSideLength: 4, staggerAxis: 'y', staggerIndex: 'odd' };
|
|
131
|
-
console.log(hexDistance(hexes, [0, 0], [3, 2]), hexRing(hexes, 4, 4, 1).length); // 4 6
|
|
132
|
-
```
|
|
133
|
-
|
|
134
|
-
| Function | What it gives |
|
|
135
|
-
| --- | --- |
|
|
136
|
-
| `cellBox(map, x, y)` | The cell's bounding box `{x, y, width, height}` in map pixels |
|
|
137
|
-
| `cellCenter`, `cellPolygon` | The cell's centre; its outline, 4 corners (6 for hexagons), clockwise from the top |
|
|
138
|
-
| `pixelToCell(map, px, py)` | The cell under a map pixel, for picking; cells outside the map are returned too |
|
|
139
|
-
| `cellNeighbors(map, x, y)` | The cells that share an edge: 4, or 6 on hexagonal maps |
|
|
140
|
-
| `mapPixelSize(map)`, `paintOrder(map)` | The box around all cells; every cell index back to front |
|
|
141
|
-
| `visibleCells(map, layer, [left, top, right, bottom])` | The cells whose boxes reach a view, in paint order |
|
|
142
|
-
| `cellToCube`, `cubeToCell`, `hexDistance`, `hexLine`, `hexRing`, `roundCube` (`/hex`) | Cube coordinates `q + r + s = 0` of hexagonal and staggered maps |
|
|
143
|
-
|
|
144
|
-
`GridTileMap` takes the options of `TileMap` (`map`, `atlases`, `camera`, `snap`, `mapLayers`, `parallax`, `target`,
|
|
145
|
-
`clear`, `order`, `layers`, `name`) and draws any orientation, `TileMap` included; `setMap`, `setAtlas`, `time`,
|
|
146
|
-
`stats` and `dispose` (or `using`) work the same. `TileMap` itself refuses a map that is not orthogonal.
|
|
147
|
-
|
|
148
|
-
- Tiles larger than the cell sit on the cell box's bottom left, as Tiled's format describes; flips work as on
|
|
149
|
-
orthogonal maps, and on hexagonal maps `FLIP_D` turns a tile 60 degrees clockwise and `HEX_ROTATE_120` 120.
|
|
150
|
-
- It writes the cells in view each frame (12 words each), so its cost follows the view, not the map; one draw per run
|
|
151
|
-
of tiles from one tileset in paint order. Cells are read every frame: writes into `layer.data` show on the next one.
|
|
152
|
-
- WebGPU only, exact texels on a single-sample target, like `TileMap`.
|
|
153
|
-
|
|
154
|
-
## Pathfinding
|
|
155
|
-
|
|
156
|
-
`margoengine/tilemap/path` finds ways across a map: `findPath` gives a cheapest path from one cell to another by A*,
|
|
157
|
-
and `flowField` gives every cell its cost to the nearest goal and the next cell toward it, for many units heading to
|
|
158
|
-
the same places. Costs come from the map's tile properties with `tileCosts`, or from any array.
|
|
159
|
-
|
|
160
|
-
```ts
|
|
161
|
-
import { createTileLayer, type TileMapData } from 'margoengine/tilemap';
|
|
162
|
-
import { findPath, flowField, followFlow, tileCosts } from 'margoengine/tilemap/path';
|
|
163
|
-
|
|
164
|
-
const map: TileMapData = {
|
|
165
|
-
width: 5, height: 3, tileWidth: 16, tileHeight: 16,
|
|
166
|
-
tilesets: [{ name: 'ground', firstGid: 1, tileWidth: 16, tileHeight: 16, tileCount: 3, columns: 3,
|
|
167
|
-
tiles: [{ id: 1, properties: { cost: 5 } }, { id: 2, properties: { solid: true } }] }],
|
|
168
|
-
// Grass (1), a swamp column (2) and one wall (3).
|
|
169
|
-
layers: [createTileLayer('ground', 5, 3, Uint32Array.of(1, 1, 2, 1, 1, 1, 3, 2, 1, 1, 1, 1, 1, 1, 1))],
|
|
170
|
-
};
|
|
171
|
-
const grid = tileCosts(map);
|
|
172
|
-
const path = findPath(grid, [0, 0], [4, 0]);
|
|
173
|
-
// Round the wall and down past the swamp: (0,0) (0,1) (0,2) (1,2) (2,2), then two corner steps up to (4,0).
|
|
174
|
-
console.log(path?.cells.length, path?.cost.toFixed(2)); // 7 6.83
|
|
175
|
-
const field = flowField(grid, [[4, 0]], { diagonal: 'never' });
|
|
176
|
-
console.log(followFlow(field, 0, 2).length); // 7
|
|
177
|
-
```
|
|
178
|
-
|
|
179
|
-
| Piece | What it does |
|
|
180
|
-
| --- | --- |
|
|
181
|
-
| `findPath(grid, start, goal, options)` | `{cells, cost}` from start to goal, both cells included, or null when there is no way |
|
|
182
|
-
| `flowField(grid, goals, options)` | `{width, height, distance, next}`: each cell's cost to the nearest goal and its next cell (`y * width + x`, -1 at goals and where none is reached) |
|
|
183
|
-
| `followFlow(field, x, y)` | The cells from (`x`, `y`) along a field to its goal |
|
|
184
|
-
| `tileCosts(map, {layers, property, solid, fallback, empty})` | A cost grid from tile properties: `solid: true` blocks (default property names `'solid'` and `'cost'`), a numeric `cost` sets the price, other tiles cost `fallback` (1), cells with no tile `empty` (`fallback`). A cell takes its highest layer cost |
|
|
185
|
-
|
|
186
|
-
A grid is `{width, height, cost, layout?}`; a step costs the cell it enters times its length, and a cost of 0, below 0
|
|
187
|
-
or Infinity blocks the cell. Options: `diagonal` (`'no-corners'` default: corner steps only when both cells beside them
|
|
188
|
-
are open; `'always'`; `'never'`)
|
|
189
|
-
|
|
190
|
-
- On staggered and hexagonal maps (`layout` set, as `tileCosts` does) steps go to the cells that share an edge and
|
|
191
|
-
`diagonal` does not apply; orthogonal and isometric maps step along rows and columns.
|
|
192
|
-
- A* estimates with the octile (or hex) distance times the lowest cost on the grid, so paths are cheapest ones; equal
|
|
193
|
-
ones are broken by the order cells were found, the same every run.
|
|
194
|
-
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
`
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
import {
|
|
205
|
-
|
|
206
|
-
const
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
`
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
```
|
|
259
|
-
import {
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
`
|
|
1
|
+
# @margoengine/tilemap
|
|
2
|
+
|
|
3
|
+
Import `margoengine/tilemap` from the `margoengine` package, or `@margoengine/tilemap` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
|
|
4
|
+
|
|
5
|
+
The 2D tile map format every other piece builds on: `TileMapData` holds the tile size, tilesets with per-tile properties, animation and collision shapes, tile layers as `Uint32Array` with Tiled's flip bits, object layers, parallax, offset, opacity and custom properties. The root entry has the types, small helpers and the `TileMap` renderer; auto-tiling and the Tiled importer are their own entries. `TileMap` draws orthogonal maps; `GridTileMap` of the `iso` entry draws isometric, staggered and hexagonal ones. (`@margoengine/tiles` is OGC 3D Tiles; this package is unrelated.)
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import {createTileLayer, encodeTile, FLIP_H, tileAt, validateTileMap, type TileMapData} from 'margoengine/tilemap';
|
|
9
|
+
const ground = createTileLayer('ground', 2, 2, Uint32Array.of(1, encodeTile(2, FLIP_H), 0, 1));
|
|
10
|
+
const map: TileMapData = {
|
|
11
|
+
width: 2, height: 2, tileWidth: 16, tileHeight: 16, layers: [ground],
|
|
12
|
+
tilesets: [{name: 'grass', firstGid: 1, tileWidth: 16, tileHeight: 16, tileCount: 2, columns: 2,
|
|
13
|
+
image: {source: 'grass.png', width: 32, height: 16}, tiles: [{id: 1, properties: {solid: true}}]}],
|
|
14
|
+
};
|
|
15
|
+
validateTileMap(map);
|
|
16
|
+
console.log(tileAt(ground, 1, 0)); // 2147483650: tile 2, mirrored left to right
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Layer values keep the low 28 bits for the global tile id (0 is empty) and the top bits for `FLIP_H`, `FLIP_V` and `FLIP_D`, exactly as Tiled stores them, so imported data is used as is. `decodeTile` and `encodeTile` split and join them; `tilesetForGid` and `tileDefForGid` find the tileset and the per-tile entry; `validateTileMap` throws a `TypeError` or `RangeError` that names the field.
|
|
20
|
+
|
|
21
|
+
## Drawing a map
|
|
22
|
+
|
|
23
|
+
`TileMap` draws the tile layers with exact pixels: one instanced draw per visible 64 x 64 chunk per tileset, texels read with no filtering. Pass each tileset's atlas by name, as pixels, an `ImageBitmap`, a `GPUTexture` or a function.
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import {EngineKernel} from 'margoengine/core';
|
|
27
|
+
import {createTileLayer, TileMap, type TileMapData} from 'margoengine/tilemap';
|
|
28
|
+
const canvas = document.querySelector('canvas')!;
|
|
29
|
+
const engine = await EngineKernel.create(canvas, {backend: 'webgpu', exactSize: [320, 180]});
|
|
30
|
+
const map: TileMapData = {
|
|
31
|
+
width: 2, height: 1, tileWidth: 16, tileHeight: 16,
|
|
32
|
+
layers: [createTileLayer('ground', 2, 1, Uint32Array.of(1, 2))],
|
|
33
|
+
tilesets: [{name: 'grass', firstGid: 1, tileWidth: 16, tileHeight: 16, tileCount: 2, columns: 2}],
|
|
34
|
+
};
|
|
35
|
+
const image = await createImageBitmap(await (await fetch('grass.png')).blob());
|
|
36
|
+
const tiles = TileMap.attach(engine, {map, atlases: {grass: image}, camera: {x: 0, y: 0, zoom: 1}});
|
|
37
|
+
tiles.setTile('ground', 1, 0, 1); // only this cell's chunk goes up again
|
|
38
|
+
engine.render({delta: 1 / 60});
|
|
39
|
+
console.log(tiles.stats.draws); // 1
|
|
40
|
+
tiles.visible = false; // draws nothing and costs no draw calls, uploads or target clears
|
|
41
|
+
engine.render({delta: 1 / 60});
|
|
42
|
+
console.log(tiles.stats.draws); // 0
|
|
43
|
+
tiles.visible = true; // draws exactly as before
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
| Option | Default | What it does |
|
|
47
|
+
| --- | --- | --- |
|
|
48
|
+
| `map` | required | The `TileMapData`. `setMap` swaps it |
|
|
49
|
+
| `atlases` | required | Tileset name to atlas. `setAtlas` swaps one |
|
|
50
|
+
| `camera` | `{x: 0, y: 0, zoom: 1}` | Map point at the top left and target pixels per map pixel, read each frame |
|
|
51
|
+
| `snap` | `true` | Rounds each layer's top left to a whole pixel, read each frame |
|
|
52
|
+
| `mapLayers` | every tile layer | Names of the tile layers to draw |
|
|
53
|
+
| `parallax` | `true` | Scrolls each layer by its own `parallax`; false when the camera carries it |
|
|
54
|
+
| `target` | the frame's colour target | Draw into this texture, or a function returning one |
|
|
55
|
+
| `clear` | the map's `backgroundColor`, else transparent | With `target`: colour to clear to, false draws over it |
|
|
56
|
+
| `order` | `10` | Frame-graph order |
|
|
57
|
+
| `layers` | `1` | Render-layer bits |
|
|
58
|
+
| `name` | `tilemap-1`, ... | Plugin name, unique per scene |
|
|
59
|
+
|
|
60
|
+
The `visible` property (default `true`) can be set at any time: a hidden map draws nothing, so with a `target` that target is not cleared either; setting it back to true draws the same pixels. It does not change the map's own layer `visible` flags.
|
|
61
|
+
|
|
62
|
+
### Atlases and targets across a device restore
|
|
63
|
+
|
|
64
|
+
Pass a `GPUTexture` atlas as a function of the device: the map calls it once per device, so after a driver reset or
|
|
65
|
+
`rebootDevice()` the tiles come back by themselves.
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
import {EngineKernel} from 'margoengine/core';
|
|
69
|
+
import {createTileLayer, TileMap} from 'margoengine/tilemap';
|
|
70
|
+
const engine = await EngineKernel.create(document.querySelector('canvas')!, {exactSize: [64, 32]});
|
|
71
|
+
const tiles = TileMap.attach(engine, {
|
|
72
|
+
map: {
|
|
73
|
+
width: 2, height: 1, tileWidth: 2, tileHeight: 2,
|
|
74
|
+
layers: [createTileLayer('ground', 2, 1, Uint32Array.of(1, 2))],
|
|
75
|
+
tilesets: [{name: 'grass', firstGid: 1, tileWidth: 2, tileHeight: 2, tileCount: 2, columns: 2}],
|
|
76
|
+
},
|
|
77
|
+
atlases: {
|
|
78
|
+
grass: (device: GPUDevice) => {
|
|
79
|
+
const texture = device.createTexture({
|
|
80
|
+
size: [4, 2], format: 'rgba8unorm', usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
|
|
81
|
+
});
|
|
82
|
+
device.queue.writeTexture({texture}, new Uint8Array(32).fill(255), {bytesPerRow: 16}, [4, 2]);
|
|
83
|
+
return texture;
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
engine.render({delta: 1 / 60});
|
|
88
|
+
console.log(tiles.stats.draws); // 1
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
A plain `GPUTexture` (atlas, image or `target`) belongs to the device that made it. After a device restore the map
|
|
92
|
+
drops it, reports it once through `engine.onError` (`MargoError` `'state'`, help `borrowed-lost`) and skips what it
|
|
93
|
+
drew while the rest of the frame goes on, until `setAtlas`, `setImage` or `setTarget` hands in one made on
|
|
94
|
+
`engine.gpu`, for example from your own plugin's `onDeviceRestored(engine)`. `GridTileMap` and `ObjectTileMap` follow
|
|
95
|
+
the same rule.
|
|
96
|
+
|
|
97
|
+
To draw into a compositor layer of `margoengine/pixel`, pass `target: layer.target, camera: layer.camera, parallax: false, mapLayers: ['ground']`, with one `TileMap` per layer that scrolls on its own.
|
|
98
|
+
|
|
99
|
+
Tiles animate by their `animation` steps on the `time` clock (milliseconds; each frame adds its delta), which changes a small lookup and no cells. A tile larger than the cell sits on the cell's bottom left, as in Tiled. Layer `offset`, `opacity`, `tint`, `visible` and `parallax` and tileset `margin`, `spacing` and `tileOffset` are honoured. Overlapping oversize tiles of different tilesets draw tileset by tileset. Object layers are data only: draw tile objects with `margoengine/sprites`. Image collection tilesets (`columns: 0`) must be packed into one atlas first. After writing into `layer.data` yourself, call `invalidate(layer)`.
|
|
100
|
+
|
|
101
|
+
## Isometric, staggered and hexagonal maps
|
|
102
|
+
|
|
103
|
+
`margoengine/tilemap/iso` places cells the way Tiled does for every `orientation`: isometric diamonds, staggered
|
|
104
|
+
diamonds whose rows (or columns) are pushed half a cell, and hexagons with flat sides of `hexSideLength`. `GridTileMap`
|
|
105
|
+
draws them with exact texels, the cells in view back to front so tiles taller than their cell (walls, trees) cover the
|
|
106
|
+
cells behind them. `margoengine/tilemap/hex` adds cube coordinates for distances, rings and lines.
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
import { EngineKernel } from 'margoengine/core';
|
|
110
|
+
import { createTileLayer, type TileMapData } from 'margoengine/tilemap';
|
|
111
|
+
import { cellCenter, GridTileMap, pixelToCell } from 'margoengine/tilemap/iso';
|
|
112
|
+
import { hexDistance, hexRing } from 'margoengine/tilemap/hex';
|
|
113
|
+
|
|
114
|
+
const engine = await EngineKernel.create(document.querySelector('canvas')!, { exactSize: [160, 90] });
|
|
115
|
+
// Two 16 x 8 diamond tiles: grass and stone.
|
|
116
|
+
const data = new Uint8Array(32 * 8 * 4);
|
|
117
|
+
for (let y = 0; y < 8; y++)
|
|
118
|
+
for (let x = 0; x < 32; x++)
|
|
119
|
+
if (Math.abs((x % 16) + 0.5 - 8) / 8 + Math.abs(y + 0.5 - 4) / 4 <= 1)
|
|
120
|
+
data.set(x < 16 ? [70, 160, 60, 255] : [150, 150, 160, 255], (y * 32 + x) * 4);
|
|
121
|
+
const map: TileMapData = {
|
|
122
|
+
orientation: 'isometric', width: 8, height: 8, tileWidth: 16, tileHeight: 8,
|
|
123
|
+
layers: [createTileLayer('ground', 8, 8, new Uint32Array(64).map((_, i) => 1 + ((i >> 3) % 2)))],
|
|
124
|
+
tilesets: [{ name: 'floor', firstGid: 1, tileWidth: 16, tileHeight: 8, tileCount: 2, columns: 2 }],
|
|
125
|
+
};
|
|
126
|
+
GridTileMap.attach(engine, { map, atlases: { floor: { width: 32, height: 8, data } }, camera: { x: -16, y: -10, zoom: 1 } });
|
|
127
|
+
engine.start();
|
|
128
|
+
|
|
129
|
+
console.log(pixelToCell(map, ...cellCenter(map, 3, 5))); // [3, 5]
|
|
130
|
+
const hexes: TileMapData = { ...map, orientation: 'hexagonal', hexSideLength: 4, staggerAxis: 'y', staggerIndex: 'odd' };
|
|
131
|
+
console.log(hexDistance(hexes, [0, 0], [3, 2]), hexRing(hexes, 4, 4, 1).length); // 4 6
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
| Function | What it gives |
|
|
135
|
+
| --- | --- |
|
|
136
|
+
| `cellBox(map, x, y)` | The cell's bounding box `{x, y, width, height}` in map pixels |
|
|
137
|
+
| `cellCenter`, `cellPolygon` | The cell's centre; its outline, 4 corners (6 for hexagons), clockwise from the top |
|
|
138
|
+
| `pixelToCell(map, px, py)` | The cell under a map pixel, for picking; cells outside the map are returned too |
|
|
139
|
+
| `cellNeighbors(map, x, y)` | The cells that share an edge: 4, or 6 on hexagonal maps |
|
|
140
|
+
| `mapPixelSize(map)`, `paintOrder(map)` | The box around all cells; every cell index back to front |
|
|
141
|
+
| `visibleCells(map, layer, [left, top, right, bottom])` | The cells whose boxes reach a view, in paint order |
|
|
142
|
+
| `cellToCube`, `cubeToCell`, `hexDistance`, `hexLine`, `hexRing`, `roundCube` (`/hex`) | Cube coordinates `q + r + s = 0` of hexagonal and staggered maps |
|
|
143
|
+
|
|
144
|
+
`GridTileMap` takes the options of `TileMap` (`map`, `atlases`, `camera`, `snap`, `mapLayers`, `parallax`, `target`,
|
|
145
|
+
`clear`, `order`, `layers`, `name`) and draws any orientation, `TileMap` included; `setMap`, `setAtlas`, `time`,
|
|
146
|
+
`stats` and `dispose` (or `using`) work the same. `TileMap` itself refuses a map that is not orthogonal.
|
|
147
|
+
|
|
148
|
+
- Tiles larger than the cell sit on the cell box's bottom left, as Tiled's format describes; flips work as on
|
|
149
|
+
orthogonal maps, and on hexagonal maps `FLIP_D` turns a tile 60 degrees clockwise and `HEX_ROTATE_120` 120.
|
|
150
|
+
- It writes the cells in view each frame (12 words each), so its cost follows the view, not the map; one draw per run
|
|
151
|
+
of tiles from one tileset in paint order. Cells are read every frame: writes into `layer.data` show on the next one.
|
|
152
|
+
- WebGPU only, exact texels on a single-sample target, like `TileMap`.
|
|
153
|
+
|
|
154
|
+
## Pathfinding
|
|
155
|
+
|
|
156
|
+
`margoengine/tilemap/path` finds ways across a map: `findPath` gives a cheapest path from one cell to another by A*,
|
|
157
|
+
and `flowField` gives every cell its cost to the nearest goal and the next cell toward it, for many units heading to
|
|
158
|
+
the same places. Costs come from the map's tile properties with `tileCosts`, or from any array.
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
import { createTileLayer, type TileMapData } from 'margoengine/tilemap';
|
|
162
|
+
import { findPath, flowField, followFlow, tileCosts } from 'margoengine/tilemap/path';
|
|
163
|
+
|
|
164
|
+
const map: TileMapData = {
|
|
165
|
+
width: 5, height: 3, tileWidth: 16, tileHeight: 16,
|
|
166
|
+
tilesets: [{ name: 'ground', firstGid: 1, tileWidth: 16, tileHeight: 16, tileCount: 3, columns: 3,
|
|
167
|
+
tiles: [{ id: 1, properties: { cost: 5 } }, { id: 2, properties: { solid: true } }] }],
|
|
168
|
+
// Grass (1), a swamp column (2) and one wall (3).
|
|
169
|
+
layers: [createTileLayer('ground', 5, 3, Uint32Array.of(1, 1, 2, 1, 1, 1, 3, 2, 1, 1, 1, 1, 1, 1, 1))],
|
|
170
|
+
};
|
|
171
|
+
const grid = tileCosts(map);
|
|
172
|
+
const path = findPath(grid, [0, 0], [4, 0]);
|
|
173
|
+
// Round the wall and down past the swamp: (0,0) (0,1) (0,2) (1,2) (2,2), then two corner steps up to (4,0).
|
|
174
|
+
console.log(path?.cells.length, path?.cost.toFixed(2)); // 7 6.83
|
|
175
|
+
const field = flowField(grid, [[4, 0]], { diagonal: 'never' });
|
|
176
|
+
console.log(followFlow(field, 0, 2).length); // 7
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
| Piece | What it does |
|
|
180
|
+
| --- | --- |
|
|
181
|
+
| `findPath(grid, start, goal, options)` | `{cells, cost, searched, scanned}` from start to goal, both cells included, or null when there is no way; `searched` cells were expanded, `scanned` passed over by jumps |
|
|
182
|
+
| `flowField(grid, goals, options)` | `{width, height, distance, next}`: each cell's cost to the nearest goal and its next cell (`y * width + x`, -1 at goals and where none is reached) |
|
|
183
|
+
| `followFlow(field, x, y)` | The cells from (`x`, `y`) along a field to its goal |
|
|
184
|
+
| `tileCosts(map, {layers, property, solid, fallback, empty})` | A cost grid from tile properties: `solid: true` blocks (default property names `'solid'` and `'cost'`), a numeric `cost` sets the price, other tiles cost `fallback` (1), cells with no tile `empty` (`fallback`). A cell takes its highest layer cost |
|
|
185
|
+
|
|
186
|
+
A grid is `{width, height, cost, layout?}`; a step costs the cell it enters times its length, and a cost of 0, below 0
|
|
187
|
+
or Infinity blocks the cell. Options: `diagonal` (`'no-corners'` default: corner steps only when both cells beside them
|
|
188
|
+
are open; `'always'`; `'never'`), `maxCells` (1,000,000) and `jumpPoints` (false).
|
|
189
|
+
|
|
190
|
+
- On staggered and hexagonal maps (`layout` set, as `tileCosts` does) steps go to the cells that share an edge and
|
|
191
|
+
`diagonal` does not apply; orthogonal and isometric maps step along rows and columns.
|
|
192
|
+
- A* estimates with the octile (or hex) distance times the lowest cost on the grid, so paths are cheapest ones; equal
|
|
193
|
+
ones are broken by the order cells were found, the same every run.
|
|
194
|
+
- `jumpPoints: true` runs jump point search (Harabor and Grastien, "Online Graph Pruning for Pathfinding on Grid
|
|
195
|
+
Maps", AAAI 2011, https://doi.org/10.1609/aaai.v25i1.7994, with the no-corner-cutting rules of their "Improving Jump
|
|
196
|
+
Point Search", ICAPS 2014, https://doi.org/10.1609/icaps.v24i1.13633) where it is exact: an orthogonal or isometric
|
|
197
|
+
grid whose open cells all cost the same, with `diagonal: 'no-corners'`. Elsewhere `findPath` is plain A* and returns
|
|
198
|
+
the same result as without it. From each expanded cell the search runs straight and diagonally until a cell where a
|
|
199
|
+
cheapest path may turn, and queues only those. Costs equal plain A*'s (600 random walled grids in
|
|
200
|
+
`test/path.test.js`); where several paths tie the cells may differ. Across an open 200 x 200 grid it expands 3 cells
|
|
201
|
+
against plain A*'s 9,679 (scanning 40,479), and past a wall across the room 6 against 27,208 (scanning 40,449).
|
|
202
|
+
|
|
203
|
+
```js
|
|
204
|
+
import { findPath } from 'margoengine/tilemap/path';
|
|
205
|
+
const width = 200, height = 200;
|
|
206
|
+
const cost = new Float64Array(width * height).fill(1);
|
|
207
|
+
for (let y = 11; y < height; y++) cost[y * width + 100] = Infinity; // a wall with a gap at the top
|
|
208
|
+
const grid = { width, height, cost };
|
|
209
|
+
const plain = findPath(grid, [10, 190], [190, 190])!;
|
|
210
|
+
const jump = findPath(grid, [10, 190], [190, 190], { jumpPoints: true })!;
|
|
211
|
+
console.log(plain.cost.toFixed(2), jump.cost.toFixed(2)); // 435.73 435.73
|
|
212
|
+
console.log(plain.searched, jump.searched); // 27208 6
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
- Both run on the calling thread and allocate a few arrays of the grid's size per call.
|
|
216
|
+
|
|
217
|
+
### Replanning as the map changes
|
|
218
|
+
|
|
219
|
+
`margoengine/tilemap/replan` keeps a search to one goal alive, for a unit that finds walls on its way or a map the
|
|
220
|
+
player edits. Change `grid.cost`, tell `update` which cells changed and ask for the path again: the cost is the one a
|
|
221
|
+
fresh `findPath` would give, and only the cells the change can matter to are expanded. It is D* Lite (Koenig and
|
|
222
|
+
Likhachev, "D* Lite", AAAI 2002, https://cdn.aaai.org/AAAI/2002/AAAI02-072.pdf, the optimized version).
|
|
223
|
+
|
|
224
|
+
```js
|
|
225
|
+
import { findPath } from 'margoengine/tilemap/path';
|
|
226
|
+
import { PathReplanner } from 'margoengine/tilemap/replan';
|
|
227
|
+
const width = 200, height = 200;
|
|
228
|
+
const cost = new Float64Array(width * height).fill(1);
|
|
229
|
+
for (let y = 11; y < height; y++) cost[y * width + 100] = Infinity; // a wall with a gap at the top
|
|
230
|
+
const grid = { width, height, cost };
|
|
231
|
+
const plan = new PathReplanner(grid, [190, 190]);
|
|
232
|
+
const first = plan.findPath([10, 190])!;
|
|
233
|
+
console.log(first.cost.toFixed(2), first.searched); // 435.73 27046
|
|
234
|
+
const [x, y] = first.cells[5]; // a wall appears ahead of the unit
|
|
235
|
+
cost[y * width + x] = Infinity;
|
|
236
|
+
const next = plan.update([[x, y]]).findPath(first.cells[4])!;
|
|
237
|
+
console.log(next.searched, findPath(grid, first.cells[4], [190, 190])!.searched); // 92 27207
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
| Piece | What it does |
|
|
241
|
+
| --- | --- |
|
|
242
|
+
| `new PathReplanner(grid, goal, {diagonal, maxCells, minCost})` | A replanner for one goal over a `CostGrid`, square or hexagonal. `maxCells` (1,000,000) limits one call, and the next call carries on. `minCost` (default the lowest cost at the start) is the lowest cost a cell will ever have; a change below it starts the search afresh |
|
|
243
|
+
| `update(cells)` | Names every cell whose cost changed since the last call, as `[x, y]` pairs |
|
|
244
|
+
| `findPath(start)` | `{cells, cost, searched, scanned}` from `start` to the goal, or null; `searched` counts the cells this call expanded |
|
|
245
|
+
|
|
246
|
+
- The first call costs about what A* costs. Later calls are cheap when the changes are near the unit; a change near the
|
|
247
|
+
goal that touches most cells' distances can cost more than a fresh search.
|
|
248
|
+
- It holds about 40 bytes a cell for as long as it lives. One goal each: use `flowField` for many units to one place on
|
|
249
|
+
a map that does not change.
|
|
250
|
+
|
|
251
|
+
### Long paths on large maps
|
|
252
|
+
|
|
253
|
+
`margoengine/tilemap/hpa` cuts the grid into clusters and searches a small graph of the steps between them, then fills
|
|
254
|
+
in only the clusters the path crosses. Build it once and ask it many times. It follows HPA* (Botea, Mueller and
|
|
255
|
+
Schaeffer, "Near Optimal Hierarchical Path-Finding", Journal of Game Development 1(1), 2004,
|
|
256
|
+
https://webdocs.cs.ualberta.ca/~mmueller/ps/hpastar.pdf), with its own choice of transitions, which gives a bound.
|
|
257
|
+
|
|
258
|
+
```js
|
|
259
|
+
import { findPath } from 'margoengine/tilemap/path';
|
|
260
|
+
import { PathHierarchy } from 'margoengine/tilemap/hpa';
|
|
261
|
+
const width = 200, height = 200;
|
|
262
|
+
const cost = new Float64Array(width * height).fill(1);
|
|
263
|
+
for (let y = 11; y < height; y++) cost[y * width + 100] = Infinity;
|
|
264
|
+
const grid = { width, height, cost };
|
|
265
|
+
const graph = new PathHierarchy(grid); // clusters of 16, detour 3
|
|
266
|
+
const full = findPath(grid, [10, 190], [190, 190])!;
|
|
267
|
+
const path = graph.findPath([10, 190], [190, 190])!;
|
|
268
|
+
console.log(path.cost.toFixed(2), path.searched, full.searched); // 435.73 4503 27208
|
|
269
|
+
cost[5 * width + 100] = Infinity; // a change rebuilds the clusters around it
|
|
270
|
+
graph.update([[100, 5]]);
|
|
271
|
+
console.log(graph.findPath([10, 190], [190, 190]) !== null); // true
|
|
272
|
+
```
|
|
273
|
+
|
|
274
|
+
| Piece | What it does |
|
|
275
|
+
| --- | --- |
|
|
276
|
+
| `new PathHierarchy(grid, {diagonal, maxCells, cluster, detour})` | The graph of a `CostGrid`, square or hexagonal. `cluster` (16) is a cluster's side; `detour` (3) is how many steps a border crossing may lie from a transition, 0 for every crossing |
|
|
277
|
+
| `findPath(start, goal, {smooth})` | `{cells, cost, searched, scanned}` or null. `smooth` (true) searches the path again in short stretches and keeps what is cheaper |
|
|
278
|
+
| `update(cells)` | Names every changed cell; the clusters around them are rebuilt before the next query |
|
|
279
|
+
| `nodes` | The graph's nodes as cells, for drawing it and judging its size |
|
|
280
|
+
|
|
281
|
+
- A path is found whenever one exists.
|
|
282
|
+
- The cost is exactly the cheapest with `detour: 0`. Otherwise it is above the cheapest by at most
|
|
283
|
+
`(2 * detour + 1) * L * highest` for each cluster border a cheapest path crosses, where `highest` is the dearest open
|
|
284
|
+
cell and `L` is sqrt(2) with corner steps, 1 without them and on hexagonal and staggered maps. Typical paths are far
|
|
285
|
+
closer: 200 long queries on a 256 x 256 map with one cell in five walled cost 0.6% more in total than the cheapest
|
|
286
|
+
(the worst 3.5% more) and expanded 438,469 cells and nodes against A*'s 964,285.
|
|
287
|
+
- Building searches each cluster once from each of its nodes, so it costs more than one query; a larger `detour` makes
|
|
288
|
+
fewer nodes (on that map 9,382 at 0, 4,022 at 3).
|
|
289
|
+
|
|
290
|
+
## Field of view and fog of war
|
|
291
|
+
|
|
292
|
+
`margoengine/tilemap/fov` works out which cells a viewer sees by shadowcasting, and `FogOfWar` keeps what is seen now
|
|
293
|
+
apart from what was seen before, for strategy maps and dungeon crawlers. Which tiles block sight comes from their
|
|
294
|
+
`opaque: true` property with `tileOpacity`, or from any array.
|
|
295
|
+
|
|
296
|
+
```ts
|
|
297
|
+
import { createTileLayer, type TileMapData } from 'margoengine/tilemap';
|
|
298
|
+
import { FOG_EXPLORED, FogOfWar, fieldOfView, tileOpacity } from 'margoengine/tilemap/fov';
|
|
299
|
+
|
|
300
|
+
const map: TileMapData = {
|
|
301
|
+
width: 7, height: 5, tileWidth: 16, tileHeight: 16,
|
|
302
|
+
tilesets: [{ name: 'dungeon', firstGid: 1, tileWidth: 16, tileHeight: 16, tileCount: 2, columns: 2,
|
|
303
|
+
tiles: [{ id: 1, properties: { opaque: true } }] }],
|
|
304
|
+
// Floor (1) with one pillar (2) at (2, 2).
|
|
305
|
+
layers: [createTileLayer('ground', 7, 5, new Uint32Array(35).map((_, i) => (i === 16 ? 2 : 1)))],
|
|
306
|
+
};
|
|
307
|
+
const sight = tileOpacity(map);
|
|
308
|
+
const seen = fieldOfView(sight, 0, 2);
|
|
309
|
+
// The pillar's shadow widens behind it: (3, 2) to (6, 2), and (5, 1), (6, 1), (5, 3), (6, 3) at its edges.
|
|
310
|
+
console.log(seen.reduce((n, v) => n + v, 0)); // 27
|
|
311
|
+
const fog = new FogOfWar(sight);
|
|
312
|
+
fog.update([{ x: 0, y: 2, radius: 3 }]).update([{ x: 6, y: 2, radius: 3 }]);
|
|
313
|
+
console.log(fog.state(0, 2) === FOG_EXPLORED); // true
|
|
314
|
+
const { width, height, data } = fog.image(); // one RGBA pixel per cell, to stretch over the map as a fog texture
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
| Piece | What it does |
|
|
318
|
+
| --- | --- |
|
|
319
|
+
| `fieldOfView(grid, x, y, {radius, into})` | A `width * height` mask, 1 where the viewer at (`x`, `y`) sees the cell; `into` adds the cells to a mask you pass, to join viewers |
|
|
320
|
+
| `FogOfWar(grid, explored?)` | `update(viewers)` refreshes `visible` from `{x, y, radius?}` viewers and adds it to `explored`; `state(x, y)` is `FOG_VISIBLE`, `FOG_EXPLORED` or `FOG_UNSEEN`; `image(colors)` gives RGBA per cell (default unseen black, explored black at alpha 128, visible clear) |
|
|
321
|
+
| `tileOpacity(map, {layers, property})` | A sight grid from tile properties: a cell blocks when any of its tiles has `opaque: true` (`property`, default `'opaque'`) |
|
|
322
|
+
|
|
323
|
+
A grid is `{width, height, opaque, orientation?}`. Sight lines leave the centre of the viewer's cell and walls are whole
|
|
324
|
+
squares: a cell is seen when a fan of sight lines wider than a point reaches it, blocking cells that are reached are
|
|
325
|
+
seen too, and two walls that touch at a corner close the gap between them. `radius` (default Infinity) keeps the cells
|
|
326
|
+
whose centre is within it.
|
|
327
|
+
|
|
328
|
+
- Orthogonal and isometric maps only; staggered and hexagonal grids are refused.
|
|
329
|
+
- Sight is not symmetric: a cell seen from here may not see back, because sight starts at a centre and ends anywhere in
|
|
330
|
+
a cell.
|
|
331
|
+
- `FogOfWar` reads `grid.opaque` on every `update`, so changing it (an opened door) counts on the next one. Save
|
|
332
|
+
`explored` and pass it back to the constructor to restore a game.
|
|
333
|
+
|
|
334
|
+
## Auto-tiling
|
|
335
|
+
|
|
336
|
+
`margoengine/tilemap/autotile` picks the tile for each cell from its neighbours with rule sets written as data: 16 tiles for the four edge neighbours (`cardinal`), or 47 for all eight (`blob`; corners count only when both edges beside them are filled). Terrain sets match the terrain at a tile's four corners instead. Both are deterministic.
|
|
337
|
+
|
|
338
|
+
```ts
|
|
339
|
+
import {autotileGrid, BLOB_MASKS} from 'margoengine/tilemap/autotile';
|
|
340
|
+
const filled = [1, 1, 0, 1, 1, 1, 0, 1, 1]; // 3 x 3, 1 = ground
|
|
341
|
+
const tiles = BLOB_MASKS.map((_, i) => i); // tile id for each of the 47 cases
|
|
342
|
+
const cells = autotileGrid(filled, 3, 3, {mode: 'blob', tiles}, {firstGid: 1});
|
|
343
|
+
console.log(cells.length); // 9 global tile values, 0 where nothing is drawn
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
`autotile(layer, rules)` does the same on a `TileLayer`; `resolveTerrain(vertices, width, height, set)` and `verticesFromCells` handle corner terrain.
|
|
347
|
+
|
|
348
|
+
## Tiled import
|
|
349
|
+
|
|
350
|
+
`margoengine/tilemap/tiled` reads a Tiled map saved as JSON (`.tmj`, or `.json`) into `TileMapData`. It takes the text, UTF-8 bytes or the parsed object. Tile layers may be CSV (an array), base64, or base64 with zlib or gzip compression; infinite maps are joined into one layer per Tiled layer; group layers pass their offset, opacity, visibility and parallax to their children. An external tileset (`.tsj`) is loaded through `options.resolve`, which receives the path written in the map. Image layers, text and object templates are skipped with a call to `onWarning`. Isometric, staggered and hexagonal maps keep their `orientation`, `staggerAxis`, `staggerIndex` and `hexSideLength`, and hexagonal ones keep Tiled's 120 degree turn bit (`HEX_ROTATE_120`); oblique maps and infinite maps that are not orthogonal are refused.
|
|
351
|
+
|
|
352
|
+
```ts
|
|
353
|
+
import { parseTiled } from 'margoengine/tilemap/tiled';
|
|
354
|
+
const map = await parseTiled({
|
|
355
|
+
orientation: 'orthogonal', width: 2, height: 1, tilewidth: 16, tileheight: 16,
|
|
356
|
+
tilesets: [{ firstgid: 1, name: 'grass', tilewidth: 16, tileheight: 16, tilecount: 2, columns: 2, image: 'grass.png', imagewidth: 32, imageheight: 16 }],
|
|
357
|
+
layers: [{ type: 'tilelayer', name: 'ground', width: 2, height: 1, data: [1, 2] }],
|
|
358
|
+
});
|
|
359
|
+
console.log(map.layers[0].type); // 'tile'
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
Bad input throws a `MapImportError` with a `code` (`syntax`, `truncated`, `missing`, `unsupported`, `limit` or `aborted`) and a message that names the fix; a compressed layer cannot expand past its declared size, and a layer past 16,777,216 cells is refused. `fromTMX(map)` converts what `parseTMX` of `margoengine/loaders` returns into the same `TileMapData`. Pass `signal` to stop an import.
|
|
363
|
+
|
|
364
|
+
## LDtk import
|
|
365
|
+
|
|
366
|
+
`margoengine/tilemap/ldtk` reads an LDtk project saved as JSON (`.ldtk`). It takes the text, UTF-8 bytes or the parsed object and returns each level of every world as a `TileMapData` with its entities, IntGrid values and fields.
|
|
367
|
+
|
|
368
|
+
```ts
|
|
369
|
+
import { parseLDtk } from 'margoengine/tilemap/ldtk';
|
|
370
|
+
const project = parseLDtk({
|
|
371
|
+
jsonVersion: '1.5.3',
|
|
372
|
+
defs: { tilesets: [{ uid: 1, identifier: 'Grass', relPath: 'grass.png', pxWid: 32, pxHei: 16, tileGridSize: 16, __cWid: 2, __cHei: 1 }] },
|
|
373
|
+
levels: [{ identifier: 'Start', pxWid: 32, pxHei: 16, layerInstances: [
|
|
374
|
+
{ __identifier: 'Ground', __type: 'Tiles', __gridSize: 16, __tilesetDefUid: 1, gridTiles: [{ px: [16, 0], t: 1, f: 0 }] },
|
|
375
|
+
] }],
|
|
376
|
+
});
|
|
377
|
+
console.log(project.levels[0].map.layers[0].type); // 'tile'
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
Layers come back to front, with `__opacity`, `visible` and the total pixel offset. A cell holds one tile, so tiles LDtk rules stack on one cell become extra layers named `Ground#2`, `Ground#3`. When layers have different grids the map's tile size is their common divisor. Entity layers become object layers, and `entities` lists each one with its pivot, tags and fields. `.ldtkl` separate level files are refused with a `MapImportError` (the same codes as Tiled); off-grid tiles and tiles with their own alpha go through `onWarning`. Pass `signal` to stop an import.
|
|
381
|
+
|
|
382
|
+
Apache-2.0. Optional, tree-shakable package; core peer: ^1.0.0.
|
|
383
|
+
|
|
384
|
+
Build and unit tests: npm test --workspace @margoengine/tilemap
|
|
385
|
+
|
|
386
|
+
## Film time
|
|
387
|
+
|
|
388
|
+
`TileMap`, `GridTileMap` and `ObjectTileMap` move their tile animation clock (`time`, in milliseconds) with `advanceTime(delta)` in the frame update, so `seek` from `@margoengine/cutscene/seek` starts a film scene on the tile frames a continuous run shows.
|