@margoengine/tiles 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/README.md CHANGED
@@ -1,307 +1,438 @@
1
- # @margoengine/tiles
2
-
3
- Import `margoengine/tiles` from the `margoengine` package, or `@margoengine/tiles` 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
- Streaming [OGC 3D Tiles 1.1](https://docs.ogc.org/cs/22-025r4/22-025r4.html) for engineering, GIS and digital-twin scenes: city models, photogrammetry, BIM and scanned sites far bigger than memory. Tiles load by screen-space error as the camera moves, coarse first, from a priority queue with a concurrency limit, and are evicted least recently used past a memory budget. glTF and b3dm tiles are drawn by [`@margoengine/gltf/pbr`](../gltf/README.md), pnts tiles by [`@margoengine/points`](../points/README.md); both are optional peers loaded with `import()` on the first tile that needs them. Core is not changed, and an app that does not import this package ships none of it.
6
-
7
- ## Quick start
8
-
9
- ```ts
10
- import { Engine } from 'margoengine/core';
11
- import { TilesRenderer } from 'margoengine/tiles';
12
-
13
- const canvas = document.querySelector('canvas')!;
14
- const engine = await Engine.create(canvas, { camera: { position: [0, 400, 600], target: [0, 0, 0], far: 50_000 } });
15
-
16
- // A real sample city (examples/assets/3d-tiles in this repository); give your own tileset's URL.
17
- // The tileset's centre lands at the world origin, x east, y up, -z north (the default 'enu' frame).
18
- const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithRequestVolume/city/tileset.json', {
19
- maximumScreenSpaceError: 16, // pixels; lower is sharper and loads more
20
- memoryBudget: 256 * 1024 * 1024, // bytes of tile content kept
21
- });
22
- tiles.tileset.on('progress', ({ queued, loading, ready }) => console.log(`${ready} ready, ${loading + queued} to go`));
23
- tiles.tileset.on('error', ({ error }) => console.warn(error.message)); // MargoError, code 'failed', names the fix
24
-
25
- // Place a marker by longitude, latitude (degrees) and height (metres).
26
- console.log(tiles.cartographicToWorld(-75.6, 40.04, 120));
27
- engine.start();
28
- ```
29
-
30
- The renderer updates selection every frame from `engine.camera`. `tiles.dispose()` (or `using tiles = ...`) aborts every request and frees every tile.
31
-
32
- ## What it reads
33
-
34
- | Part of the specification | Support |
35
- | --- | --- |
36
- | Tileset JSON | `asset`, `geometricError`, `root`, `children`, `transform` (composed in float64), `refine` (inherited), `content` / `contents` (several per tile), `viewerRequestVolume`, `content.boundingVolume`, `properties`, `extensionsRequired` (unknown required extensions fail with code `unsupported`) |
37
- | Bounding volumes | `box`, `region` (always in EPSG:4979, ignores transforms), `sphere`; S2 cells (`3DTILES_bounding_volume_S2`, explicit and implicit) with `s2` from `margoengine/tiles/s2` |
38
- | Refinement | `REPLACE` (children drawn only once every visible child is ready, so no holes and no overlap) and `ADD` |
39
- | Implicit tiling | `QUADTREE` and `OCTREE`, `subtreeLevels`, `availableLevels` (or the 1.0 extension's `maximumLevel`), binary and JSON subtree files, constant and bitstream availability, child subtrees, `{level}` `{x}` `{y}` `{z}` templates |
40
- | External tilesets | content that is tileset JSON becomes the tile's child; its transforms continue from the tile |
41
- | Content | glTF and GLB, b3dm (with `RTC_CENTER` and the batch table), pnts (`POSITION`, `POSITION_QUANTIZED`, `RGBA`, `RGB`, `RGB565`, `NORMAL`, `NORMAL_OCT16P`, `BATCH_ID`, `CONSTANT_RGBA`, Draco-compressed with `dracoPoints` from `margoengine/tiles/metadata`), cmpt (nested), i3dm (`POSITION`, `POSITION_QUANTIZED`, `NORMAL_UP` / `NORMAL_RIGHT` and their oct-encoded forms, `SCALE`, `SCALE_NON_UNIFORM`, `EAST_NORTH_UP`, `RTC_CENTER`, embedded or external glTF; drawn with `i3dm` from `margoengine/tiles/i3dm`), glTF with Gaussian splats (`KHR_gaussian_splatting`, SPZ-compressed or not; drawn with `splats` from `margoengine/tiles/splats`) |
42
- | Metadata | `schema` / `schemaUri`, `metadata` on the tileset, tiles and contents, `groups`; `tileset.properties(entity)` fills in schema defaults; glTF `EXT_structural_metadata` property tables and `EXT_mesh_features` feature IDs with `readStructuralMetadata` from `margoengine/tiles/metadata` |
43
-
44
- ## Selection
45
-
46
- Each update measures every visible tile's screen-space error, `geometricError x screenHeight / (2 x distance x tan(fov / 2))` (perspective) or `geometricError x screenHeight / orthographicHeight`, and refines while it is above `maximumScreenSpaceError`. Tiles outside the camera frustum (or a `viewerRequestVolume` the camera is outside) are skipped. An empty tile always refines. Requests are prioritised in two groups: tiles that fill holes (REPLACE parents still standing in for children, ADD parents) first, coarsest first, then the final tiles nearest first. Requests no longer wanted are dropped from the queue or aborted in flight. With `skipLevelOfDetail`, parents whose error is more than `skipScreenSpaceErrorFactor` times the target are not loaded at all, so a close view fills in at full detail sooner.
47
-
48
- ## Options
49
-
50
- `TilesRenderer.load(engine, url, options)` and `Tileset.load(url, options)`:
51
-
52
- | Option | Default | Meaning |
53
- | --- | --- | --- |
54
- | `maximumScreenSpaceError` | `16` | Pixels of error allowed before refining. |
55
- | `maxConcurrentRequests` | `6` | Requests in flight at once. |
56
- | `memoryBudget` | 512 MiB | Bytes of ready tiles kept: GPU bytes in `TilesRenderer` (see `budget`), file bytes in `Tileset`. Past it, the least recently used tiles outside the view are evicted; if the view alone needs more, only hole-filling loads start (`tileset.overBudget` is then true). |
57
- | `skipLevelOfDetail` | `false` | Skip loading far-too-coarse parents (see Selection). |
58
- | `skipScreenSpaceErrorFactor` | `16` | How coarse a parent may be before it is skipped. |
59
- | `boundingVolumes` | none | Bounding volume extensions to read: `[s2]` from `margoengine/tiles/s2`. A tileset that requires S2 without it fails with code `unsupported`. |
60
- | `fetch` | `globalThis.fetch` | Your own fetch: auth headers, an offline cache, tests. |
61
- | `signal` | none | `AbortSignal` for the load and every later request. |
62
- | `frame` (renderer) | `'enu'` | `'enu'`, `'local'` or a 4x4 matrix; see below. |
63
- | `origin` (renderer) | none | A floating origin (`FloatingOrigin` from `margoengine/cameras/origin`). |
64
- | `loadModel` (renderer) | gltf/pbr's `parseGLTFAsync` | Your own glTF loader. |
65
- | `budget` (renderer) | `'gpu'` | What `memoryBudget` counts: `'gpu'` the GPU memory each tile's model takes (vertex, index and uv buffers, textures with their mip chains or KTX2 levels, i3dm instance rows, point and splat buffers), so the cache limit matches what the device holds; `'content'` the bytes of each tile's file, as `Tileset` alone counts. |
66
- | `pointBudget` (renderer) | 2,000,000 | Budget of the points plugin made for pnts tiles. |
67
- | `i3dm` (renderer) | none | The i3dm drawer from `margoengine/tiles/i3dm`; without it an i3dm tile fails with code `unsupported`. |
68
- | `dracoPoints` (renderer) | none | The Draco pnts decoder from `margoengine/tiles/metadata`; without it a Draco pnts tile fails with code `unsupported`. |
69
- | `splats` (renderer) | none | The Gaussian splat drawer from `margoengine/tiles/splats`; without it a glTF tile holding `KHR_gaussian_splatting` fails with code `unsupported`. |
70
-
71
- ## Coordinates and precision
72
-
73
- 3D Tiles positions are ECEF metres (EPSG:4978): millions of metres from the earth's centre, where float32 keeps only about half a metre. Everything here stays float64 until the last step. The renderer's `frame` maps tileset coordinates to the engine's world: by default the east-north-up frame at the centre of the root volume becomes the world origin, with x east, y up and -z north (glTF's y-up), and glTF tile content gets the specification's y-up to z-up turn first. Each tile model's root mesh gets one float64 matrix, `frame x tile transform x RTC_CENTER x (y-up to z-up)`, split into translation, rotation and scale. A city 50 km across then sits within 25 km of the origin, where float32 still resolves 2 mm.
74
-
75
- For a continent or the whole globe, add a floating origin: the renderer places every tile root through it, and it rebases the camera and all placed roots together when the camera wanders, so float32 values stay small wherever you are.
76
-
77
- ```ts
78
- import { Engine } from 'margoengine/core';
79
- import { FloatingOrigin } from 'margoengine/cameras/origin';
80
- import { TilesRenderer } from 'margoengine/tiles';
81
-
82
- const engine = await Engine.create(document.querySelector('canvas')!);
83
- const origin = FloatingOrigin.attach(engine);
84
- const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithRequestVolume/city/tileset.json', { origin });
85
- origin.lookAt(tiles.cartographicToWorld(-75.613, 40.038, 300), tiles.cartographicToWorld(-75.613, 40.042, 0));
86
- ```
87
-
88
- `toWorld(ecef)`, `toTileset(world)` and `cartographicToWorld(lon, lat, height)` convert points; the WGS84 helpers (`cartographicToEcef`, `ecefToCartographic`, `eastNorthUpToEcef`) are exported too.
89
-
90
- ## Instanced content (i3dm)
91
-
92
- Trees, poles and street furniture often come as i3dm: one glTF and a transform per instance. Pass the drawer from `margoengine/tiles/i3dm` and each glTF primitive draws every instance of its tile in one instanced draw (gltf/pbr's `PBRInstances`). Tilesets without i3dm never load this module.
93
-
94
- ```ts
95
- import { Engine } from 'margoengine/core';
96
- import { TilesRenderer } from 'margoengine/tiles';
97
- import { i3dm } from 'margoengine/tiles/i3dm';
98
-
99
- const engine = await Engine.create(document.querySelector('canvas')!);
100
- // 25 trees as i3dm, a real sample (examples/assets/3d-tiles in this repository).
101
- const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithTreeBillboards/tileset.json', { i3dm });
102
- engine.start();
103
- ```
104
-
105
- Each instance is placed as the specification says: tile transform x `RTC_CENTER` x instance (position, `NORMAL_RIGHT` and `NORMAL_UP` as the x and y axes, or the east-north-up frame at the instance with `EAST_NORTH_UP`, then the scale) x the glTF's y-up to z-up turn. All of it is float64; the model root sits at the mean instance position, so the float32 instance rows stay within the tile's own size. An external glTF (`gltfFormat` 0) is fetched with the tileset's `fetch`, relative to the tile's content URL. `instanceMatrices` and `instanceCenter` are exported for your own renderer.
106
-
107
- ## Metadata and Draco points
108
-
109
- `margoengine/tiles/metadata` reads the binary metadata of 3D Tiles 1.1 content and decodes Draco-compressed point clouds. Tilesets without them never load it.
110
-
111
- ```ts
112
- import { Engine } from 'margoengine/core';
113
- import { TilesRenderer } from 'margoengine/tiles';
114
- import { dracoPoints, readStructuralMetadata } from 'margoengine/tiles/metadata';
115
-
116
- const engine = await Engine.create(document.querySelector('canvas')!);
117
- // Draco-compressed pnts (3DTILES_draco_point_compression) decode in workers, with Draco's own decoder, on first use.
118
- const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithRequestVolume/city/tileset.json', { dracoPoints });
119
- engine.start();
120
-
121
- // Feature properties of a glTF tile (EXT_structural_metadata and EXT_mesh_features); here a real Cesium sample.
122
- const gltf = await (await fetch('3d-tiles/EXT_structural_metadata/ComplexTypes/ComplexTypes.gltf')).arrayBuffer();
123
- const metadata = readStructuralMetadata(new Uint8Array(gltf));
124
- // A picked vertex (mesh 0, primitive 0, vertex 5, say from a raycast hit) leads to its feature and its properties.
125
- const feature = metadata.feature(0, 0, 5);
126
- console.log(feature?.id, feature?.properties);
127
- console.log(metadata.propertyTables[0].get(1, 'example_variable_length_ARRAY_STRING')); // ['One', 'Two']
128
- ```
129
-
130
- `readStructuralMetadata(bytes)` takes a GLB, glTF JSON (data URIs, or `buffer: (index, uri) => bytes` for external buffers) or a tile's `content.gltf`. Property tables read every type of the 3D Tiles Metadata binary table format: `SCALAR`, `VECn`, `MATn` (column-major), `STRING`, `BOOLEAN` (bits) and `ENUM` (as the value's name), fixed and variable-length arrays with any offset type, `normalized` integers, then `offset` and `scale` (the table's override first), and `noData` read as the `default`. `table.get(row, name)` and `table.row(row)` read one feature; a row out of range reads as `undefined`. Feature ID sets come per mesh primitive, with their IDs per vertex for attribute and implicit sets. A malformed table throws a `TypeError` or `RangeError` naming it; nothing reads out of bounds.
131
-
132
- `dracoPoints(content)` turns Draco pnts into ordinary point content: `POSITION`, `RGBA` or `RGB`, `NORMAL` and `BATCH_ID` from the Draco buffer, and the batch table properties the extension names. For your own renderer, call it from the `Tileset` content factory; a third argument takes any decoder with `decode(bytes)`.
133
-
134
- ## Gaussian splat tiles
135
-
136
- Photoreal captures are now published as 3D Tiles whose glTF content holds Gaussian splats (`KHR_gaussian_splatting`, often with the SPZ payload of the draft `KHR_gaussian_splatting_compression_spz_2`, declared through `3DTILES_content_gltf`). Pass the drawer from `margoengine/tiles/splats`: gltf/pbr reads each tile's splats and meshes, and [`@margoengine/splats`](../splats/README.md) draws them. Tilesets without splats never load this module.
137
-
138
- ```ts
139
- import { Engine } from 'margoengine/core';
140
- import { TilesRenderer } from 'margoengine/tiles';
141
- import { splats } from 'margoengine/tiles/splats';
142
-
143
- const engine = await Engine.create(document.querySelector('canvas')!, { camera: { position: [170, 40, 250], target: [50, -50, 50] } });
144
- // CesiumJS's real sh_unit_cube: 27 splats with SH degree 3 in an SPZ payload (examples/assets/3d-tiles in this repository).
145
- const tiles = await TilesRenderer.load(engine, '3d-tiles/GaussianSplats/sh_unit_cube/tileset.json', { splats });
146
- engine.start();
147
- ```
148
-
149
- Every visible tile's splats go into one cloud, so splats of neighbouring and overlapping tiles sort together rather than tile by tile; the cloud is rebuilt after an update that changed which tiles show (one rebuild for a whole REPLACE swap, so no frame shows both levels or neither) and when a floating origin moves. Each primitive is placed by `frame x tile transform x RTC x y-up to z-up x node` in float64: shapes and harmonics are turned by the linear part, and the translation is added in float64 when the cloud is built, so splats keep float32 precision at the tile's own size even at ECEF distances. Tiles with different harmonic degrees merge at the highest one. Past 3,000,000 visible splats a second cloud starts (`SPLATS_PER_CLOUD`), and those two sort apart. `placeSplats`, `mergePlaced` and `TileSplats` are exported for your own renderer.
150
-
151
- ## S2 cells
152
-
153
- Global datasets often bound their tiles with S2 cells (`3DTILES_bounding_volume_S2`): a cell of S2's cube-face hierarchy, by its token, extruded along the ellipsoid normals between two heights. Pass `s2` from `margoengine/tiles/s2`; tilesets without S2 never load it.
154
-
155
- ```ts
156
- import { Tileset } from 'margoengine/tiles';
157
- import { parseS2Token, s2, s2Bounds } from 'margoengine/tiles/s2';
158
-
159
- // The extension's own example: the S2 cell "89c6c7" over Philadelphia's Center City, from the ground to 1 km.
160
- const volume = { token: '89c6c7', minimumHeight: 0, maximumHeight: 1000 };
161
- console.log(parseS2Token(volume.token)); // { face: 4, level: 10, i: ..., j: ... }
162
- console.log(s2Bounds(volume).radius.toFixed(0), 'm bounding radius');
163
-
164
- const json = { asset: { version: '1.1' }, geometricError: 100, extensionsRequired: ['3DTILES_bounding_volume_S2'],
165
- root: { geometricError: 0, boundingVolume: { extensions: { '3DTILES_bounding_volume_S2': volume } } } };
166
- const tileset = await Tileset.load(URL.createObjectURL(new Blob([JSON.stringify(json)])), { boundingVolumes: [s2] });
167
- console.log(tileset.root.bounds.center);
168
- ```
169
-
170
- Each cell becomes an oriented box in ECEF (east, north and up at the cell's centre) around a 17 x 17 grid of points on its bottom and top surfaces, grown by the curvature between those points, so it holds the whole volume; the tile transform is ignored, as the extension says. Tokens, the Hilbert order on each face (odd faces mirrored) and the quadratic projection follow the extension and the S2 cell hierarchy guide. With implicit tiling a quadtree tile (level, x, y) is the S2 cell at (x, y) on its parent's (i, j) grid, and an octree tile also takes its slab of the heights. `parseS2Token`, `s2Token`, `s2LonLat` and `s2CellBounds` are exported.
171
-
172
- ## Terrain and imagery
173
-
174
- `margoengine/tiles/terrain` streams quantized-mesh terrain (the format Cesium terrain servers publish) draped with map imagery, so a globe works without a photogrammetry dataset. `terrain(layerUrl)` reads the layer's `layer.json` and returns a tileset URL and a fetch for the renderer: the layer's two geographic root tiles become an implicit quadtree each, and every terrain tile becomes, on request, a b3dm mesh with skirts, RTC-centred in float64, with its imagery tile as an unlit texture. Selection, streaming, the memory budget and a floating origin are then the renderer's own.
175
-
176
- ```ts
177
- import { Engine } from 'margoengine/core';
178
- import { TilesRenderer } from 'margoengine/tiles';
179
- import { terrain, terrainFrame } from 'margoengine/tiles/terrain';
180
-
181
- const engine = await Engine.create(document.querySelector('canvas')!, {
182
- camera: { position: [0, 8_000_000, 22_000_000], target: [0, 0, 0], near: 100_000, far: 100_000_000 },
183
- });
184
- // A real two-level quantized-mesh layer from CesiumJS's test data (examples/assets/terrain in this repository).
185
- // Add imagery: { url: 'https://your.tile.server/{z}/{x}/{y}.png' } to drape XYZ map tiles you may use.
186
- const source = await terrain('terrain/QuantizedMeshWithOctVertexNormals/layer.json');
187
- const tiles = await TilesRenderer.load(engine, source.url, { fetch: source.fetch, frame: 'local' });
188
- engine.start();
189
- // Close to the ground, centre the world on your area instead: frame: terrainFrame(86.925, 27.988) (degrees).
190
- console.log(terrainFrame(86.925, 27.988).length); // 16
191
- ```
192
-
193
- `parseQuantizedMesh(bytes)` decodes a tile (header, vertices, triangles, edges, oct normals, water mask, metadata); a cut tile throws a `RangeError`. Imagery is `EPSG:3857` with `xyz` rows by default (`projection`, `scheme`, `maximumLevel`, `mimeType` change it); each terrain tile takes the deepest imagery tile that holds it whole, at most one level deeper than the terrain. Without `imagery` the terrain draws lit, in grey, with the tile's normals or ones made from its triangles. Pass `fetch` to `terrain` for headers such as an access token.
194
-
195
- ## Height under a place: `@margoengine/tiles/height`
196
-
197
- `tilesHeightQuery(engine, tiles)` returns `(longitude, latitude) => height`: radians in, metres above the WGS84
198
- ellipsoid out, from a ray straight down the local vertical against the tiles drawn now (the bvh `Raycaster`, an
199
- optional peer). It reads the current selection on each call, so it follows streaming, and gives undefined where no
200
- drawn tile lies. Rays start at `top` (9000 m) and look down to `bottom` (12000 m below the ellipsoid). It is the
201
- `heightAt` the geospatial camera takes for clearance and walking over tiles.
202
-
203
- ```ts
204
- import {Engine} from 'margoengine/core';
205
- import {TilesRenderer} from 'margoengine/tiles';
206
- import {tilesHeightQuery} from 'margoengine/tiles/height';
207
- import {GeospatialControls} from 'margoengine/controls/geospatial';
208
- import {degToRad} from 'margoengine/math/geo';
209
-
210
- const engine = await Engine.create(document.querySelector('canvas')!);
211
- const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithRequestVolume/city/tileset.json');
212
- const heightAt = tilesHeightQuery(engine, tiles);
213
- // The camera works in the tileset's frame and keeps clear of the tiles it stands over.
214
- const camera = new GeospatialControls(engine, undefined, {
215
- frame: tiles,
216
- heightAt,
217
- view: {longitude: degToRad(-75.6), latitude: degToRad(40.04), range: 800, pitch: degToRad(35)},
218
- });
219
- console.log(heightAt(degToRad(-75.6), degToRad(40.04))); // undefined until a tile there is drawn
220
- ```
221
-
222
- ## Orthographic cameras
223
-
224
- Maps and plan views use an orthographic camera, such as `CameraProjection` from `margoengine/cameras`. The renderer reads it from `engine.camera.matrix` with no extra call: when the clip w row is constant, the screen-space error becomes `geometricError x screenHeight / orthographicHeight`, the world height the view shows (converted to tileset units through the frame), so zooming in refines and moving the camera along its axis does not.
225
-
226
- ```ts
227
- import { Engine } from 'margoengine/core';
228
- import { CameraProjection } from 'margoengine/cameras';
229
- import { TilesRenderer } from 'margoengine/tiles';
230
-
231
- const canvas = document.querySelector('canvas')!;
232
- const engine = await Engine.create(canvas, { camera: { position: [0, 2000, 0.01], target: [0, 0, 0], far: 50_000 } });
233
- // A plan view 600 m tall: tiles refine for 600 m on screen, whatever the eye height.
234
- const projection = CameraProjection.attach(engine, { mode: 'orthographic', height: 600 });
235
- const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithRequestVolume/city/tileset.json');
236
- tiles.tileset.on('progress', ({ ready }) => console.log(`${ready} tiles ready`));
237
- engine.start();
238
- // Later, zoom in four times: the next frame's selection refines for 150 m on screen.
239
- projection.height = 150;
240
- ```
241
-
242
- `TilesRenderer.orthographicHeight(matrix)` returns the view height of an orthographic view-projection matrix and undefined for a perspective one (and for core's all-zero matrix before the first frame).
243
-
244
- ## Hosted tilesets: sign-in and credits
245
-
246
- `margoengine/tiles/ion` signs in to token-based tile services and lists the credits they require on screen. `ionAsset(id, { accessToken })` asks Cesium ion for the asset's endpoint and returns its URL, a `fetch` that sends the asset's own short-lived token as a bearer header to that host only (asking ion again once when it answers 401) and its attributions. `hostedTileset(url, { query, headers })` signs any other service: Google's photorealistic 3D Tiles take `{ query: { key } }`, and the `session` a tile URL hands out goes on to the tiles it links (`carry`). `TileCredits.follow(tiles, { credits, element })` keeps an element's text to what the view needs: the service's attributions, then the glTF `asset.copyright` of the tiles drawn now, split on semicolons, most frequent first.
247
-
248
- ```ts
249
- import { Engine } from 'margoengine/core';
250
- import { TilesRenderer } from 'margoengine/tiles';
251
- import { TileCredits, hostedTileset, ionAsset } from 'margoengine/tiles/ion';
252
-
253
- const engine = await Engine.create(document.querySelector('canvas')!, {
254
- camera: { position: [0, 400, 600], target: [0, 0, 0], far: 50_000 },
255
- });
256
- // Your Cesium ion token and asset ID (from ion's asset page); without one, a keyed stand-in on this page's server.
257
- const ionToken = '';
258
- const source = ionToken
259
- ? await ionAsset(96188, { accessToken: ionToken })
260
- : hostedTileset(new URL('3d-tiles/TilesetWithRequestVolume/city/tileset.json', location.href), {
261
- query: { key: 'your-api-key' },
262
- });
263
- const tiles = await TilesRenderer.load(engine, source.url, { fetch: source.fetch });
264
- const credits = TileCredits.follow(tiles, {
265
- credits: source.credits,
266
- element: document.body.appendChild(document.createElement('div')),
267
- });
268
- engine.start();
269
- console.log(credits.text()); // the service's attributions, then the drawn tiles' copyright
270
- ```
271
-
272
- A terrain asset works the same way: `terrain(source.url, { fetch: source.fetch })`. `credits.text(separator, true)` leaves out what ion marks `collapsible` (it may sit behind a credits button); `credits.html()` gives the service's own HTML (ion's links and logos) as it sent it, with the tiles' copyright escaped, for an app that trusts the service with its markup. Tokens go in headers, never in URLs the signing adds (a `query` you give is yours). An asset ion only points at (`externalType`, such as Bing imagery) throws code `unsupported`; a refused token or a missing asset throws code `failed`, naming the fix.
273
-
274
- ## Without the engine
275
-
276
- `Tileset` is engine-free: give it a view each frame and a content factory, and it does the rest. This is how the tests drive it, and how to stream tiles into your own renderer or a server-side job.
277
-
278
- ```ts
279
- import { Tileset, type TileRenderable } from 'margoengine/tiles';
280
-
281
- const tileset = await Tileset.load('3d-tiles/TilesetWithRequestVolume/city/tileset.json', {
282
- content: (content, tile, signal): TileRenderable => ({ bytes: content.byteLength, visible: false, dispose() {} }),
283
- });
284
- const frame = tileset.update({ position: [1_215_000, -4_736_000, 4_081_000], screenHeight: 1080, fov: 60 });
285
- for (const tile of frame.selected) console.log(tile.id, tile.screenSpaceError.toFixed(1));
286
- ```
287
-
288
- `update(view)` returns the tiles drawn this update. Events: `tileload`, `tileunload`, `error`, `progress` (queued, loading, ready, failed, selected, bytes) and `idle` (the view is complete). `tileset.retry()` forgets failed loads after the network or the file is fixed; failed tiles never stop the rest of the tileset, and a REPLACE parent keeps covering a failed child.
289
-
290
- The content parsers (`parseB3dm`, `parsePnts`, `parseI3dm`, `parseCmpt`, `parseContent`, `parseSubtree`) are exported for tools. Truncated or corrupt input throws a `TypeError` or `RangeError` naming the problem; it never reads out of bounds.
291
-
292
- ## Limits
293
-
294
- - i3dm batch tables are read (`content.batchTable`) but per-instance picking and per-instance colours are not wired to them; an i3dm external glTF resolves against the tile's first content URL.
295
- - S2 boxes are boxes: near a face cell's corners a box holds more than the cell (selection may load a tile slightly early); the pinned CesiumJS ImplicitHeightSemantics standard-data sample expands 21 cells and contains 45,738 independently calculated WGS84 points at its published heights. It has no content meshes. Binary per-tile height metadata does not tighten the inherited root slab (0..10,000 m instead of 1,000..5,000 m here); production-world rendering is unproved. Other faces and octrees retain the specification/generated controls. Fetch required data with `node scripts/reference-rendering/fetch-skip-assets.mjs`, then run `npm test --workspace @margoengine/tiles`.
296
- - Terrain: only `EPSG:4326` `tms` layers; tile availability from `layer.json` `available` (a layer without it, such as one using `metadataAvailability`, is assumed whole up to `maxzoom`, and a missing tile fails while its parent stays); one imagery tile per terrain tile, so near the poles and for very coarse terrain the imagery is a level coarser than it could be; every region spans -500 to 9,000 m, so selection boxes are taller than the ground; water mask and metadata are read but not drawn.
297
- - Splat tiles: the visible cloud is rebuilt on the CPU and uploaded again when the visible tiles change, which costs time in proportion to the visible splats (not measured); splats do not write depth or receive lighting (see `@margoengine/splats`); the renderer's `loadModel` is not used for splat tiles; a glTF tile with external buffers is not read.
298
- - Metadata: feature ID textures are named, not read (sample the texture yourself); property textures, property attributes and a `schemaUri` schema in glTF are not read; 64-bit integers become doubles (exact to 2^53); feature IDs of a Draco-compressed glTF primitive are not read; picking a vertex is yours (a raycast hit), the tables then give its feature.
299
- - Draco pnts decode with `@margoengine/decoders/draco-points`: in Web Workers in a browser, in the calling thread in Node.
300
- - A tile whose glTF requires KHR_techniques_webgl (archived GLSL shaders, such as the billboard level of Cesium's TilesetWithTreeBillboards) fails with code `unsupported`, as glTF says a loader must; the rest of the tileset draws.
301
- - `budget: 'gpu'` counts gltf/pbr models exactly from their arrays and images (Khronos BoomBox: within 0.1% of what the device allocated); points, i3dm rows and splats by their buffer layouts; a custom `loadModel` whose models have no `primitives` is counted by file size. Uniform buffers, pipelines and the engine's own targets are not tile memory and are not counted.
302
- - Hosted tilesets: an ion token is asked for again only after a 401, once per expiry; requests to other hosts (a tile URL on another server) go unsigned; the credits are counted from glTF `asset.copyright` only (b3dm, i3dm and glTF content), so pnts tiles and imagery name none; nothing here draws a logo.
303
- - Orthographic cameras are told apart by the clip w row of `camera.matrix`: a projection that mixes the two (clip w that varies only a little with depth) is read as perspective, and before the first frame the renderer selects as perspective.
304
-
305
- ### Scenes
306
-
307
- `TilesRenderer.load` remembers the scene that is active when you call it, before its first await, and attaches the renderer there. The tile models, point anchors and instances it makes later (after fetches and imports) belong to the renderer's own scene, not to the default scene that is active again by then.
1
+ # @margoengine/tiles
2
+
3
+ Import `margoengine/tiles` from the `margoengine` package, or `@margoengine/tiles` 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
+ Streaming [OGC 3D Tiles 1.1](https://docs.ogc.org/cs/22-025r4/22-025r4.html) for engineering, GIS and digital-twin scenes: city models, photogrammetry, BIM and scanned sites far bigger than memory. Tiles load by screen-space error as the camera moves, coarse first, from a priority queue with a concurrency limit, and are evicted least recently used past a memory budget. glTF and b3dm tiles are drawn by [`@margoengine/gltf/pbr`](../gltf/README.md), pnts tiles by [`@margoengine/points`](../points/README.md); both are optional peers loaded with `import()` on the first tile that needs them. Core is not changed, and an app that does not import this package ships none of it.
6
+
7
+ ## Quick start
8
+
9
+ ```ts
10
+ import { Engine } from 'margoengine/core';
11
+ import { TilesRenderer } from 'margoengine/tiles';
12
+
13
+ const canvas = document.querySelector('canvas')!;
14
+ const engine = await Engine.create(canvas, { camera: { position: [0, 400, 600], target: [0, 0, 0], far: 50_000 } });
15
+
16
+ // A real sample city (examples/assets/3d-tiles in this repository); give your own tileset's URL.
17
+ // The tileset's centre lands at the world origin, x east, y up, -z north (the default 'enu' frame).
18
+ const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithRequestVolume/city/tileset.json', {
19
+ maximumScreenSpaceError: 16, // pixels; lower is sharper and loads more
20
+ memoryBudget: 256 * 1024 * 1024, // bytes of tile content kept
21
+ });
22
+ tiles.tileset.on('progress', ({ queued, loading, ready }) => console.log(`${ready} ready, ${loading + queued} to go`));
23
+ tiles.tileset.on('error', ({ error }) => console.warn(error.message)); // MargoError, code 'failed', names the fix
24
+
25
+ // Place a marker by longitude, latitude (degrees) and height (metres).
26
+ console.log(tiles.cartographicToWorld(-75.6, 40.04, 120));
27
+ engine.start();
28
+ ```
29
+
30
+ The renderer updates selection every frame from `engine.camera`. `tiles.dispose()` (or `using tiles = ...`) aborts every request and frees every tile.
31
+
32
+ ## What it reads
33
+
34
+ | Part of the specification | Support |
35
+ | --- | --- |
36
+ | Tileset JSON | `asset`, `geometricError`, `root`, `children`, `transform` (composed in float64), `refine` (inherited), `content` / `contents` (several per tile), `viewerRequestVolume`, `content.boundingVolume`, `properties`, `extensionsRequired` (unknown required extensions fail with code `unsupported`) |
37
+ | Bounding volumes | `box`, `region` (always in EPSG:4979, ignores transforms), `sphere`; S2 cells (`3DTILES_bounding_volume_S2`, explicit and implicit) with `s2` from `margoengine/tiles/s2` |
38
+ | Refinement | `REPLACE` (children drawn only once every visible child is ready, so no holes and no overlap) and `ADD` |
39
+ | Implicit tiling | `QUADTREE` and `OCTREE`, `subtreeLevels`, `availableLevels` (or the 1.0 extension's `maximumLevel`), binary and JSON subtree files, constant and bitstream availability, child subtrees, `{level}` `{x}` `{y}` `{z}` templates |
40
+ | External tilesets | content that is tileset JSON becomes the tile's child; its transforms continue from the tile |
41
+ | Content | glTF and GLB, b3dm (with `RTC_CENTER` and the batch table), pnts (`POSITION`, `POSITION_QUANTIZED`, `RGBA`, `RGB`, `RGB565`, `NORMAL`, `NORMAL_OCT16P`, `BATCH_ID`, `CONSTANT_RGBA`, Draco-compressed with `dracoPoints` from `margoengine/tiles/metadata`), cmpt (nested), i3dm (`POSITION`, `POSITION_QUANTIZED`, `NORMAL_UP` / `NORMAL_RIGHT` and their oct-encoded forms, `SCALE`, `SCALE_NON_UNIFORM`, `EAST_NORTH_UP`, `RTC_CENTER`, embedded or external glTF; drawn with `i3dm` from `margoengine/tiles/i3dm`), glTF with Gaussian splats (`KHR_gaussian_splatting`, SPZ-compressed or not; drawn with `splats` from `margoengine/tiles/splats`) |
42
+ | Metadata | `schema` / `schemaUri`, `metadata` on the tileset, tiles and contents, `groups`; `tileset.properties(entity)` fills in schema defaults; glTF `EXT_structural_metadata` property tables and `EXT_mesh_features` feature IDs with `readStructuralMetadata` from `margoengine/tiles/metadata` |
43
+
44
+ ## Selection
45
+
46
+ Each update measures every visible tile's screen-space error, `geometricError x screenHeight / (2 x distance x tan(fov / 2))` (perspective) or `geometricError x screenHeight / orthographicHeight`, and refines while it is above `maximumScreenSpaceError`. Tiles outside the camera frustum (or a `viewerRequestVolume` the camera is outside) are skipped. An empty tile always refines. Requests are prioritised in two groups: tiles that fill holes (REPLACE parents still standing in for children, ADD parents) first, coarsest first, then the final tiles nearest first. Requests no longer wanted are dropped from the queue or aborted in flight. With `skipLevelOfDetail`, parents whose error is more than `skipScreenSpaceErrorFactor` times the target are not loaded at all, so a close view fills in at full detail sooner.
47
+
48
+ ## Options
49
+
50
+ `TilesRenderer.load(engine, url, options)` and `Tileset.load(url, options)`:
51
+
52
+ | Option | Default | Meaning |
53
+ | --- | --- | --- |
54
+ | `maximumScreenSpaceError` | `16` | Pixels of error allowed before refining. |
55
+ | `maxConcurrentRequests` | `6` | Requests in flight at once. |
56
+ | `memoryBudget` | 512 MiB | Bytes of ready tiles kept: GPU bytes in `TilesRenderer` (see `budget`), file bytes in `Tileset`. Past it, the least recently used tiles outside the view are evicted; if the view alone needs more, only hole-filling loads start (`tileset.overBudget` is then true). |
57
+ | `skipLevelOfDetail` | `false` | Skip loading far-too-coarse parents (see Selection). |
58
+ | `skipScreenSpaceErrorFactor` | `16` | How coarse a parent may be before it is skipped. |
59
+ | `boundingVolumes` | none | Bounding volume extensions to read: `[s2]` from `margoengine/tiles/s2`. A tileset that requires S2 without it fails with code `unsupported`. |
60
+ | `fetch` | `globalThis.fetch` | Your own fetch: auth headers, an offline cache, tests. |
61
+ | `signal` | none | `AbortSignal` for the load and every later request. |
62
+ | `frame` (renderer) | `'enu'` | `'enu'`, `'local'` or a 4x4 matrix; see below. |
63
+ | `origin` (renderer) | none | A floating origin (`FloatingOrigin` from `margoengine/cameras/origin`). |
64
+ | `loadModel` (renderer) | gltf/pbr's `parseGLTFAsync` | Your own glTF loader. |
65
+ | `budget` (renderer) | `'gpu'` | What `memoryBudget` counts: `'gpu'` the GPU memory each tile's model takes (vertex, index and uv buffers, textures with their mip chains or KTX2 levels, i3dm instance rows, point and splat buffers), so the cache limit matches what the device holds; `'content'` the bytes of each tile's file, as `Tileset` alone counts. |
66
+ | `pointBudget` (renderer) | 2,000,000 | Budget of the points plugin made for pnts tiles. |
67
+ | `i3dm` (renderer) | none | The i3dm drawer from `margoengine/tiles/i3dm`; without it an i3dm tile fails with code `unsupported`. |
68
+ | `dracoPoints` (renderer) | none | The Draco pnts decoder from `margoengine/tiles/metadata`; without it a Draco pnts tile fails with code `unsupported`. |
69
+ | `splats` (renderer) | none | The Gaussian splat drawer from `margoengine/tiles/splats`; without it a glTF tile holding `KHR_gaussian_splatting` fails with code `unsupported`. |
70
+
71
+ ## Coordinates and precision
72
+
73
+ 3D Tiles positions are ECEF metres (EPSG:4978): millions of metres from the earth's centre, where float32 keeps only about half a metre. Everything here stays float64 until the last step. The renderer's `frame` maps tileset coordinates to the engine's world: by default the east-north-up frame at the centre of the root volume becomes the world origin, with x east, y up and -z north (glTF's y-up), and glTF tile content gets the specification's y-up to z-up turn first. Each tile model's root mesh gets one float64 matrix, `frame x tile transform x RTC_CENTER x (y-up to z-up)`, split into translation, rotation and scale. A city 50 km across then sits within 25 km of the origin, where float32 still resolves 2 mm.
74
+
75
+ For a continent or the whole globe, add a floating origin: the renderer places every tile root through it, and it rebases the camera and all placed roots together when the camera wanders, so float32 values stay small wherever you are.
76
+
77
+ ```ts
78
+ import { Engine } from 'margoengine/core';
79
+ import { FloatingOrigin } from 'margoengine/cameras/origin';
80
+ import { TilesRenderer } from 'margoengine/tiles';
81
+
82
+ const engine = await Engine.create(document.querySelector('canvas')!);
83
+ const origin = FloatingOrigin.attach(engine);
84
+ const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithRequestVolume/city/tileset.json', { origin });
85
+ origin.lookAt(tiles.cartographicToWorld(-75.613, 40.038, 300), tiles.cartographicToWorld(-75.613, 40.042, 0));
86
+ ```
87
+
88
+ `toWorld(ecef)`, `toTileset(world)` and `cartographicToWorld(lon, lat, height)` convert points; the WGS84 helpers (`cartographicToEcef`, `ecefToCartographic`, `eastNorthUpToEcef`) are exported too.
89
+
90
+ ## Instanced content (i3dm)
91
+
92
+ Trees, poles and street furniture often come as i3dm: one glTF and a transform per instance. Pass the drawer from `margoengine/tiles/i3dm` and each glTF primitive draws every instance of its tile in one instanced draw (gltf/pbr's `PBRInstances`). Tilesets without i3dm never load this module.
93
+
94
+ ```ts
95
+ import { Engine } from 'margoengine/core';
96
+ import { TilesRenderer } from 'margoengine/tiles';
97
+ import { i3dm } from 'margoengine/tiles/i3dm';
98
+
99
+ const engine = await Engine.create(document.querySelector('canvas')!);
100
+ // 25 trees as i3dm, a real sample (examples/assets/3d-tiles in this repository).
101
+ const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithTreeBillboards/tileset.json', { i3dm });
102
+ engine.start();
103
+ ```
104
+
105
+ Each instance is placed as the specification says: tile transform x `RTC_CENTER` x instance (position, `NORMAL_RIGHT` and `NORMAL_UP` as the x and y axes, or the east-north-up frame at the instance with `EAST_NORTH_UP`, then the scale) x the glTF's y-up to z-up turn. All of it is float64; the model root sits at the mean instance position, so the float32 instance rows stay within the tile's own size. An external glTF (`gltfFormat` 0) is fetched with the tileset's `fetch`, relative to the tile's content URL. `instanceMatrices` and `instanceCenter` are exported for your own renderer.
106
+
107
+ ## Metadata and Draco points
108
+
109
+ `margoengine/tiles/metadata` reads the binary metadata of 3D Tiles 1.1 content and decodes Draco-compressed point clouds. Tilesets without them never load it.
110
+
111
+ ```ts
112
+ import { Engine } from 'margoengine/core';
113
+ import { TilesRenderer } from 'margoengine/tiles';
114
+ import { dracoPoints, readStructuralMetadata } from 'margoengine/tiles/metadata';
115
+
116
+ const engine = await Engine.create(document.querySelector('canvas')!);
117
+ // Draco-compressed pnts (3DTILES_draco_point_compression) decode in workers, with Draco's own decoder, on first use.
118
+ const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithRequestVolume/city/tileset.json', { dracoPoints });
119
+ engine.start();
120
+
121
+ // Feature properties of a glTF tile (EXT_structural_metadata and EXT_mesh_features); here a real Cesium sample.
122
+ const gltf = await (await fetch('3d-tiles/EXT_structural_metadata/ComplexTypes/ComplexTypes.gltf')).arrayBuffer();
123
+ const metadata = readStructuralMetadata(new Uint8Array(gltf));
124
+ // A picked vertex (mesh 0, primitive 0, vertex 5, say from a raycast hit) leads to its feature and its properties.
125
+ const feature = metadata.feature(0, 0, 5);
126
+ console.log(feature?.id, feature?.properties);
127
+ console.log(metadata.propertyTables[0].get(1, 'example_variable_length_ARRAY_STRING')); // ['One', 'Two']
128
+ ```
129
+
130
+ `readStructuralMetadata(bytes)` takes a GLB, glTF JSON (data URIs, or `buffer: (index, uri) => bytes` for external buffers) or a tile's `content.gltf`. Property tables read every type of the 3D Tiles Metadata binary table format: `SCALAR`, `VECn`, `MATn` (column-major), `STRING`, `BOOLEAN` (bits) and `ENUM` (as the value's name), fixed and variable-length arrays with any offset type, `normalized` integers, then `offset` and `scale` (the table's override first), and `noData` read as the `default`. `table.get(row, name)` and `table.row(row)` read one feature; a row out of range reads as `undefined`. Feature ID sets come per mesh primitive, with their IDs per vertex for attribute and implicit sets. A malformed table throws a `TypeError` or `RangeError` naming it; nothing reads out of bounds.
131
+
132
+ `dracoPoints(content)` turns Draco pnts into ordinary point content: `POSITION`, `RGBA` or `RGB`, `NORMAL` and `BATCH_ID` from the Draco buffer, and the batch table properties the extension names. For your own renderer, call it from the `Tileset` content factory; a third argument takes any decoder with `decode(bytes)`.
133
+
134
+ ## Gaussian splat tiles
135
+
136
+ Photoreal captures are now published as 3D Tiles whose glTF content holds Gaussian splats (`KHR_gaussian_splatting`, often with the SPZ payload of the draft `KHR_gaussian_splatting_compression_spz_2`, declared through `3DTILES_content_gltf`). Pass the drawer from `margoengine/tiles/splats`: gltf/pbr reads each tile's splats and meshes, and [`@margoengine/splats`](../splats/README.md) draws them. Tilesets without splats never load this module.
137
+
138
+ ```ts
139
+ import { Engine } from 'margoengine/core';
140
+ import { TilesRenderer } from 'margoengine/tiles';
141
+ import { splats } from 'margoengine/tiles/splats';
142
+
143
+ const engine = await Engine.create(document.querySelector('canvas')!, { camera: { position: [170, 40, 250], target: [50, -50, 50] } });
144
+ // CesiumJS's real sh_unit_cube: 27 splats with SH degree 3 in an SPZ payload (examples/assets/3d-tiles in this repository).
145
+ const tiles = await TilesRenderer.load(engine, '3d-tiles/GaussianSplats/sh_unit_cube/tileset.json', { splats });
146
+ engine.start();
147
+ ```
148
+
149
+ Every visible tile's splats go into one cloud, so splats of neighbouring and overlapping tiles sort together rather than tile by tile; the cloud is rebuilt after an update that changed which tiles show (one rebuild for a whole REPLACE swap, so no frame shows both levels or neither) and when a floating origin moves. Each primitive is placed by `frame x tile transform x RTC x y-up to z-up x node` in float64: shapes and harmonics are turned by the linear part, and the translation is added in float64 when the cloud is built, so splats keep float32 precision at the tile's own size even at ECEF distances. Tiles with different harmonic degrees merge at the highest one. Past 3,000,000 visible splats a second cloud starts (`SPLATS_PER_CLOUD`), and those two sort apart. `placeSplats`, `mergePlaced` and `TileSplats` are exported for your own renderer.
150
+
151
+ ## S2 cells
152
+
153
+ Global datasets often bound their tiles with S2 cells (`3DTILES_bounding_volume_S2`): a cell of S2's cube-face hierarchy, by its token, extruded along the ellipsoid normals between two heights. Pass `s2` from `margoengine/tiles/s2`; tilesets without S2 never load it.
154
+
155
+ ```ts
156
+ import { Tileset } from 'margoengine/tiles';
157
+ import { parseS2Token, s2, s2Bounds } from 'margoengine/tiles/s2';
158
+
159
+ // The extension's own example: the S2 cell "89c6c7" over Philadelphia's Center City, from the ground to 1 km.
160
+ const volume = { token: '89c6c7', minimumHeight: 0, maximumHeight: 1000 };
161
+ console.log(parseS2Token(volume.token)); // { face: 4, level: 10, i: ..., j: ... }
162
+ console.log(s2Bounds(volume).radius.toFixed(0), 'm bounding radius');
163
+
164
+ const json = { asset: { version: '1.1' }, geometricError: 100, extensionsRequired: ['3DTILES_bounding_volume_S2'],
165
+ root: { geometricError: 0, boundingVolume: { extensions: { '3DTILES_bounding_volume_S2': volume } } } };
166
+ const tileset = await Tileset.load(URL.createObjectURL(new Blob([JSON.stringify(json)])), { boundingVolumes: [s2] });
167
+ console.log(tileset.root.bounds.center);
168
+ ```
169
+
170
+ Each cell becomes an oriented box in ECEF (east, north and up at the cell's centre) around a 17 x 17 grid of points on its bottom and top surfaces, grown by the curvature between those points, so it holds the whole volume; the tile transform is ignored, as the extension says. Tokens, the Hilbert order on each face (odd faces mirrored) and the quadratic projection follow the extension and the S2 cell hierarchy guide. With implicit tiling a quadtree tile (level, x, y) is the S2 cell at (x, y) on its parent's (i, j) grid, and an octree tile also takes its slab of the heights. `parseS2Token`, `s2Token`, `s2LonLat` and `s2CellBounds` are exported.
171
+
172
+ ## Terrain and imagery
173
+
174
+ `margoengine/tiles/terrain` streams quantized-mesh terrain (the format Cesium terrain servers publish) draped with map imagery, so a globe works without a photogrammetry dataset. `terrain(layerUrl)` reads the layer's `layer.json` and returns a tileset URL and a fetch for the renderer: the layer's two geographic root tiles become an implicit quadtree each, and every terrain tile becomes, on request, a b3dm mesh with skirts, RTC-centred in float64, with its imagery tile as an unlit texture. Selection, streaming, the memory budget and a floating origin are then the renderer's own.
175
+
176
+ ```ts
177
+ import { Engine } from 'margoengine/core';
178
+ import { TilesRenderer } from 'margoengine/tiles';
179
+ import { terrain, terrainFrame } from 'margoengine/tiles/terrain';
180
+
181
+ const engine = await Engine.create(document.querySelector('canvas')!, {
182
+ camera: { position: [0, 8_000_000, 22_000_000], target: [0, 0, 0], near: 100_000, far: 100_000_000 },
183
+ });
184
+ // A real two-level quantized-mesh layer from CesiumJS's test data (examples/assets/terrain in this repository).
185
+ // Add imagery: { url: 'https://your.tile.server/{z}/{x}/{y}.png' } to drape XYZ map tiles you may use.
186
+ const source = await terrain('terrain/QuantizedMeshWithOctVertexNormals/layer.json');
187
+ const tiles = await TilesRenderer.load(engine, source.url, { fetch: source.fetch, frame: 'local' });
188
+ engine.start();
189
+ // Close to the ground, centre the world on your area instead: frame: terrainFrame(86.925, 27.988) (degrees).
190
+ console.log(terrainFrame(86.925, 27.988).length); // 16
191
+ ```
192
+
193
+ `parseQuantizedMesh(bytes)` decodes a tile (header, vertices, triangles, edges, oct normals, water mask, metadata); a cut tile throws a `RangeError`. Imagery is `EPSG:3857` with `xyz` rows by default (`projection`, `scheme`, `maximumLevel`, `mimeType` change it); each terrain tile takes the deepest imagery tile that holds it whole, at most one level deeper than the terrain. Without `imagery` the terrain draws lit, in grey, with the tile's normals or ones made from its triangles. Pass `fetch` to `terrain` for headers such as an access token.
194
+
195
+ ## Styling: `@margoengine/tiles/style`
196
+
197
+ `TilesStyle` compiles an OGC 3D Tiles style (`color`, `show`, `pointSize`, `defines` and `meta`) once and applies it to
198
+ every tile as it loads. Expressions are interpreted, never run as JavaScript: `${name}` reads a feature property,
199
+ `color()`, `rgb()`, `vec2` to `vec4`, math, strings and `regExp` work as the Styling specification says, and a
200
+ `{conditions}` list takes the first condition that holds.
201
+
202
+ ```ts
203
+ import { Engine } from 'margoengine/core';
204
+ import { TilesRenderer } from 'margoengine/tiles';
205
+ import { TilesStyle } from 'margoengine/tiles/style';
206
+
207
+ const engine = await Engine.create(document.querySelector('canvas')!, {
208
+ camera: { position: [0, 400, 600], target: [0, 0, 0], far: 50_000 },
209
+ });
210
+ const style = new TilesStyle({
211
+ defines: { tall: '${Height} > 10' }, // a define reads like a property in the other expressions
212
+ color: { conditions: [['${tall}', 'color("#d86f45")'], ['true', 'color("white", 0.8)']] },
213
+ show: '${id} !== 3',
214
+ meta: { label: '"Building " + ${id}' },
215
+ });
216
+ console.log(style.evaluate({ id: 4, Height: 12 })); // color [0.847, 0.435, 0.271, 1], show true, meta.label 'Building 4'
217
+ // The sample city's b3dm batch tables hold id, Longitude, Latitude and Height for every building.
218
+ const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithRequestVolume/city/tileset.json', {
219
+ decorate: style.decorate,
220
+ });
221
+ engine.start();
222
+ ```
223
+
224
+ - `decorate` reads b3dm batch properties, pnts `BATCH_ID` and the point semantics (`POSITION`, `POSITION_ABSOLUTE`,
225
+ `COLOR`, `NORMAL`), i3dm `BATCH_ID` and structural metadata (feature ID attributes and implicit sets). Its saved
226
+ arrays count against the tile's memory budget and go with the tile on eviction.
227
+ - Colours are sRGB in expressions and multiply each vertex's authored colour in linear light; `show: false` discards
228
+ the vertex in every surface pass (points get size 0, instances a degenerate transform that keeps their picking id).
229
+ - `evaluate(properties)` takes an object or a lookup `(name) => value`; with no properties it styles the single
230
+ implicit feature. An expression that yields the wrong type throws a `MargoError` `invalid`; a `conditions` list
231
+ where nothing matches leaves `color` undefined (white).
232
+ - Your own content binds without the renderer: `bindModel(model, properties)` (a glTF PBR model, per vertex; bind
233
+ before any deformation), `bindPoints(cloud, properties)` and `bindInstances(instances, properties)` each return a
234
+ binding whose `update(style)` restyles live and whose `dispose()` (or `using`) puts back the authored data. A
235
+ disposed binding refuses `update`.
236
+
237
+ ## Map imagery: `@margoengine/tiles/imagery`
238
+
239
+ `terrainImagery(layerUrl, {imagery})` loads quantized-mesh terrain like `terrain()` and drapes it with any number of
240
+ ordered map layers: Web Map Service (`wms`), Web Map Tile Service (`wmts`) and XYZ or TMS tiles (`xyz`). Each terrain
241
+ tile's drape is composited from every layer, reprojected scanline by scanline between geographic (`EPSG:4326`) and Web
242
+ Mercator (`EPSG:3857`), then laid over the layers below by its `opacity`.
243
+
244
+ ```ts
245
+ import { Engine } from 'margoengine/core';
246
+ import { TilesRenderer } from 'margoengine/tiles';
247
+ import { terrainImagery, terrainRectangle, wms, wmsURL, wmts, wmtsURL, xyz } from 'margoengine/tiles/imagery';
248
+
249
+ const roads = { url: 'https://maps.example.com/wms', layers: 'roads', version: '1.3.0' as const, crs: 'EPSG:4326' as const };
250
+ const ortho = { url: 'https://maps.example.com/wmts', layer: 'ortho', matrixSet: 'WebMercatorQuad' };
251
+ // The URLs a terrain tile asks for (west, south, east, north in radians):
252
+ const tile = terrainRectangle(1, 0, 0, 'EPSG:4326');
253
+ console.log(wmsURL(roads, tile)); // ...REQUEST=GetMap&LAYERS=roads&CRS=EPSG%3A4326&BBOX=-90%2C-180%2C0%2C-90...
254
+ console.log(wmtsURL(ortho, '3', 2, 5)); // ...REQUEST=GetTile&...&TILEMATRIX=3&TILEROW=5&TILECOL=2
255
+
256
+ const engine = await Engine.create(document.querySelector('canvas')!, {
257
+ camera: { position: [0, 8_000_000, 22_000_000], target: [0, 0, 0], near: 100_000, far: 100_000_000 },
258
+ });
259
+ using source = await terrainImagery('terrain/QuantizedMeshWithOctVertexNormals/layer.json', {
260
+ imagery: [
261
+ xyz({ url: 'imagery/{z}/{x}/{y}.png', scheme: 'xyz', maximumLevel: 2 }),
262
+ { ...wms({ ...roads, size: 256 }), opacity: 0.6, show: false }, // a layer you can switch on later
263
+ { ...wmts(ortho), show: false },
264
+ ],
265
+ imagerySize: 256,
266
+ maximumCachedBytes: 32 * 1024 * 1024,
267
+ });
268
+ console.log(source.projection, source.maximumLevel); // the layer's projection and deepest level
269
+ const tiles = await TilesRenderer.load(engine, source.url, { fetch: source.fetch, frame: 'local' });
270
+ engine.start();
271
+ ```
272
+
273
+ - `wms` speaks 1.1.1 and 1.3.0 with the version's own CRS key and axis order (`CRS:84`, `EPSG:4326` or `EPSG:3857`);
274
+ `parameters` adds or replaces query keys, case-insensitively, and the rest of the service URL is kept.
275
+ - `wmts` uses key-value requests, or a ResourceURL template when `url` holds `{TileMatrix}`, `{TileCol}` or `{TileRow}`
276
+ (other `{Dimension}`s come from `parameters`). Without `matrices` it assumes the global pyramid of the projection at
277
+ 256 pixels a tile, level z having 2^z tiles a side (twice that wide for `EPSG:4326`); give `matrices` (`id`, `width`,
278
+ `height`, `tileWidth`, `tileHeight`, `resolution`, `topLeft`) or `matrixLabels` for a service that differs, and a
279
+ level with neither throws a `RangeError`.
280
+ - `xyz` fills `{z}`, `{x}` and `{y}`; `scheme: 'tms'` counts rows from the south. `tileSize` defaults to 256 and
281
+ `maximumLevel` to 19.
282
+ - The terrain may be geographic or Mercator, with `available` ranges or `metadataAvailability` (tile availability read
283
+ from the tiles themselves); Mercator branches expand lazily so latitude bounds stay exact at every level. Every
284
+ request goes through `fetch` (add access headers there) and `signal`; `dispose()`, or `using`, cancels them and frees
285
+ the decoded staging cache.
286
+
287
+ ## Per-vertex and per-texel properties: `@margoengine/tiles/properties`
288
+
289
+ `readPropertyMetadata(asset)` reads `EXT_structural_metadata` property attributes (values per vertex) and property
290
+ textures (values per texel) from a loaded glTF asset, without creating engine objects; `loadPropertyMetadata(asset)`
291
+ also fetches an external schema and the property images, keeping the PNG channels exactly as stored.
292
+
293
+ ```ts
294
+ import { GLTFAsset } from 'margoengine/gltf/pbr';
295
+ import { loadPropertyMetadata } from 'margoengine/tiles/properties';
296
+
297
+ // A CC0 sample: a box whose texture holds two temperatures and an insulation value per texel.
298
+ const url = '3d-tiles/EXT_structural_metadata/SimplePropertyTexture/SimplePropertyTexture.gltf';
299
+ const doc = await (await fetch(url)).json();
300
+ const asset = new GLTFAsset(doc, []);
301
+ const controller = new AbortController();
302
+ const metadata = await loadPropertyMetadata(asset, {
303
+ baseURL: new URL(url, location.href).href,
304
+ signal: controller.signal,
305
+ maximumBytes: 16 * 1024 * 1024,
306
+ });
307
+ const texture = metadata.primitives[0][0].textures[0];
308
+ console.log(texture.class, texture.row([0.25, 0.25])); // 'buildingComponents', {insideTemperature: 20, ...}
309
+ // What a ray hit on triangle 0 of mesh 0, primitive 0, reads at its barycentric coordinates:
310
+ console.log(metadata.sample(0, 0, 0, [1 / 3, 1 / 3, 1 / 3]));
311
+ ```
312
+
313
+ - `PropertyAttributes.get(vertex, name)` and `row(vertex)` return a value after `noData`, `default`, normalization,
314
+ `offset` and `scale`; a row out of range gives undefined. `PropertyTextures.get(uv, name)` and `row(uv)` read the
315
+ nearest stored texel (encoded integers and floats are never interpolated) with glTF wrapping, the property's UV set
316
+ and `KHR_texture_transform`.
317
+ - `sample(mesh, primitive, triangle, barycoord)` interpolates each texture's own coordinate set at a triangle hit and
318
+ returns one record per property texture.
319
+ - Images come from `image(texture)` in `readPropertyMetadata` (RGBA8 pixels per glTF texture); for an asset decoded by a
320
+ codec whose float cache loses raw sentinel bits, `accessor(index)` returns the original packed bytes.
321
+ - Limits: fixed-size numeric, enum and boolean properties only (strings and variable arrays go in property tables);
322
+ decoded attribute bytes up to `maximumDecodedBytes` (default four times the asset's byte limit) and each schema or
323
+ image resource up to `maximumBytes` (default 64 MiB). Loading honours `signal`; relative resources need `baseURL` in
324
+ Node.
325
+
326
+ ## Height under a place: `@margoengine/tiles/height`
327
+
328
+ `tilesHeightQuery(engine, tiles)` returns `(longitude, latitude) => height`: radians in, metres above the WGS84
329
+ ellipsoid out, from a ray straight down the local vertical against the tiles drawn now (the bvh `Raycaster`, an
330
+ optional peer). It reads the current selection on each call, so it follows streaming, and gives undefined where no
331
+ drawn tile lies. Rays start at `top` (9000 m) and look down to `bottom` (12000 m below the ellipsoid). It is the
332
+ `heightAt` the geospatial camera takes for clearance and walking over tiles.
333
+
334
+ ```ts
335
+ import {Engine} from 'margoengine/core';
336
+ import {TilesRenderer} from 'margoengine/tiles';
337
+ import {tilesHeightQuery} from 'margoengine/tiles/height';
338
+ import {GeospatialControls} from 'margoengine/controls/geospatial';
339
+ import {degToRad} from 'margoengine/math/geo';
340
+
341
+ const engine = await Engine.create(document.querySelector('canvas')!);
342
+ const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithRequestVolume/city/tileset.json');
343
+ const heightAt = tilesHeightQuery(engine, tiles);
344
+ // The camera works in the tileset's frame and keeps clear of the tiles it stands over.
345
+ const camera = new GeospatialControls(engine, undefined, {
346
+ frame: tiles,
347
+ heightAt,
348
+ view: {longitude: degToRad(-75.6), latitude: degToRad(40.04), range: 800, pitch: degToRad(35)},
349
+ });
350
+ console.log(heightAt(degToRad(-75.6), degToRad(40.04))); // undefined until a tile there is drawn
351
+ ```
352
+
353
+ ## Orthographic cameras
354
+
355
+ Maps and plan views use an orthographic camera, such as `CameraProjection` from `margoengine/cameras`. The renderer reads it from `engine.camera.matrix` with no extra call: when the clip w row is constant, the screen-space error becomes `geometricError x screenHeight / orthographicHeight`, the world height the view shows (converted to tileset units through the frame), so zooming in refines and moving the camera along its axis does not.
356
+
357
+ ```ts
358
+ import { Engine } from 'margoengine/core';
359
+ import { CameraProjection } from 'margoengine/cameras';
360
+ import { TilesRenderer } from 'margoengine/tiles';
361
+
362
+ const canvas = document.querySelector('canvas')!;
363
+ const engine = await Engine.create(canvas, { camera: { position: [0, 2000, 0.01], target: [0, 0, 0], far: 50_000 } });
364
+ // A plan view 600 m tall: tiles refine for 600 m on screen, whatever the eye height.
365
+ const projection = CameraProjection.attach(engine, { mode: 'orthographic', height: 600 });
366
+ const tiles = await TilesRenderer.load(engine, '3d-tiles/TilesetWithRequestVolume/city/tileset.json');
367
+ tiles.tileset.on('progress', ({ ready }) => console.log(`${ready} tiles ready`));
368
+ engine.start();
369
+ // Later, zoom in four times: the next frame's selection refines for 150 m on screen.
370
+ projection.height = 150;
371
+ ```
372
+
373
+ `TilesRenderer.orthographicHeight(matrix)` returns the view height of an orthographic view-projection matrix and undefined for a perspective one (and for core's all-zero matrix before the first frame).
374
+
375
+ ## Hosted tilesets: sign-in and credits
376
+
377
+ `margoengine/tiles/ion` signs in to token-based tile services and lists the credits they require on screen. `ionAsset(id, { accessToken })` asks Cesium ion for the asset's endpoint and returns its URL, a `fetch` that sends the asset's own short-lived token as a bearer header to that host only (asking ion again once when it answers 401) and its attributions. `hostedTileset(url, { query, headers })` signs any other service: Google's photorealistic 3D Tiles take `{ query: { key } }`, and the `session` a tile URL hands out goes on to the tiles it links (`carry`). `TileCredits.follow(tiles, { credits, element })` keeps an element's text to what the view needs: the service's attributions, then the glTF `asset.copyright` of the tiles drawn now, split on semicolons, most frequent first.
378
+
379
+ ```ts
380
+ import { Engine } from 'margoengine/core';
381
+ import { TilesRenderer } from 'margoengine/tiles';
382
+ import { TileCredits, hostedTileset, ionAsset } from 'margoengine/tiles/ion';
383
+
384
+ const engine = await Engine.create(document.querySelector('canvas')!, {
385
+ camera: { position: [0, 400, 600], target: [0, 0, 0], far: 50_000 },
386
+ });
387
+ // Your Cesium ion token and asset ID (from ion's asset page); without one, a keyed stand-in on this page's server.
388
+ const ionToken = '';
389
+ const source = ionToken
390
+ ? await ionAsset(96188, { accessToken: ionToken })
391
+ : hostedTileset(new URL('3d-tiles/TilesetWithRequestVolume/city/tileset.json', location.href), {
392
+ query: { key: 'your-api-key' },
393
+ });
394
+ const tiles = await TilesRenderer.load(engine, source.url, { fetch: source.fetch });
395
+ const credits = TileCredits.follow(tiles, {
396
+ credits: source.credits,
397
+ element: document.body.appendChild(document.createElement('div')),
398
+ });
399
+ engine.start();
400
+ console.log(credits.text()); // the service's attributions, then the drawn tiles' copyright
401
+ ```
402
+
403
+ A terrain asset works the same way: `terrain(source.url, { fetch: source.fetch })`. `credits.text(separator, true)` leaves out what ion marks `collapsible` (it may sit behind a credits button); `credits.html()` gives the service's own HTML (ion's links and logos) as it sent it, with the tiles' copyright escaped, for an app that trusts the service with its markup. Tokens go in headers, never in URLs the signing adds (a `query` you give is yours). An asset ion only points at (`externalType`, such as Bing imagery) throws code `unsupported`; a refused token or a missing asset throws code `failed`, naming the fix.
404
+
405
+ ## Without the engine
406
+
407
+ `Tileset` is engine-free: give it a view each frame and a content factory, and it does the rest. This is how the tests drive it, and how to stream tiles into your own renderer or a server-side job.
408
+
409
+ ```ts
410
+ import { Tileset, type TileRenderable } from 'margoengine/tiles';
411
+
412
+ const tileset = await Tileset.load('3d-tiles/TilesetWithRequestVolume/city/tileset.json', {
413
+ content: (content, tile, signal): TileRenderable => ({ bytes: content.byteLength, visible: false, dispose() {} }),
414
+ });
415
+ const frame = tileset.update({ position: [1_215_000, -4_736_000, 4_081_000], screenHeight: 1080, fov: 60 });
416
+ for (const tile of frame.selected) console.log(tile.id, tile.screenSpaceError.toFixed(1));
417
+ ```
418
+
419
+ `update(view)` returns the tiles drawn this update. Events: `tileload`, `tileunload`, `error`, `progress` (queued, loading, ready, failed, selected, bytes) and `idle` (the view is complete). `tileset.retry()` forgets failed loads after the network or the file is fixed; failed tiles never stop the rest of the tileset, and a REPLACE parent keeps covering a failed child.
420
+
421
+ The content parsers (`parseB3dm`, `parsePnts`, `parseI3dm`, `parseCmpt`, `parseContent`, `parseSubtree`) are exported for tools. Truncated or corrupt input throws a `TypeError` or `RangeError` naming the problem; it never reads out of bounds.
422
+
423
+ ## Limits
424
+
425
+ - i3dm batch tables are read (`content.batchTable`) but per-instance picking and per-instance colours are not wired to them; an i3dm external glTF resolves against the tile's first content URL.
426
+ - S2 boxes are boxes: near a face cell's corners a box holds more than the cell (selection may load a tile slightly early); the pinned CesiumJS ImplicitHeightSemantics standard-data sample expands 21 cells and contains 45,738 independently calculated WGS84 points at its published heights. It has no content meshes. Binary per-tile height metadata does not tighten the inherited root slab (0..10,000 m instead of 1,000..5,000 m here); production-world rendering is unproved. Other faces and octrees retain the specification/generated controls. Fetch required data with `node scripts/reference-rendering/fetch-skip-assets.mjs`, then run `npm test --workspace @margoengine/tiles`.
427
+ - Terrain: only `EPSG:4326` `tms` layers; tile availability from `layer.json` `available` (a layer without it, such as one using `metadataAvailability`, is assumed whole up to `maxzoom`, and a missing tile fails while its parent stays); one imagery tile per terrain tile, so near the poles and for very coarse terrain the imagery is a level coarser than it could be; every region spans -500 to 9,000 m, so selection boxes are taller than the ground; water mask and metadata are read but not drawn.
428
+ - Splat tiles: the visible cloud is rebuilt on the CPU and uploaded again when the visible tiles change, which costs time in proportion to the visible splats (not measured); splats do not write depth or receive lighting (see `@margoengine/splats`); the renderer's `loadModel` is not used for splat tiles; a glTF tile with external buffers is not read.
429
+ - Metadata: feature ID textures are named, not read (sample the texture yourself); property textures, property attributes and a `schemaUri` schema in glTF are not read; 64-bit integers become doubles (exact to 2^53); feature IDs of a Draco-compressed glTF primitive are not read; picking a vertex is yours (a raycast hit), the tables then give its feature.
430
+ - Draco pnts decode with `@margoengine/decoders/draco-points`: in Web Workers in a browser, in the calling thread in Node.
431
+ - A tile whose glTF requires KHR_techniques_webgl (archived GLSL shaders, such as the billboard level of Cesium's TilesetWithTreeBillboards) fails with code `unsupported`, as glTF says a loader must; the rest of the tileset draws.
432
+ - `budget: 'gpu'` counts gltf/pbr models exactly from their arrays and images (Khronos BoomBox: within 0.1% of what the device allocated); points, i3dm rows and splats by their buffer layouts; a custom `loadModel` whose models have no `primitives` is counted by file size. Uniform buffers, pipelines and the engine's own targets are not tile memory and are not counted.
433
+ - Hosted tilesets: an ion token is asked for again only after a 401, once per expiry; requests to other hosts (a tile URL on another server) go unsigned; the credits are counted from glTF `asset.copyright` only (b3dm, i3dm and glTF content), so pnts tiles and imagery name none; nothing here draws a logo.
434
+ - Orthographic cameras are told apart by the clip w row of `camera.matrix`: a projection that mixes the two (clip w that varies only a little with depth) is read as perspective, and before the first frame the renderer selects as perspective.
435
+
436
+ ### Scenes
437
+
438
+ `TilesRenderer.load` remembers the scene that is active when you call it, before its first await, and attaches the renderer there. The tile models, point anchors and instances it makes later (after fetches and imports) belong to the renderer's own scene, not to the default scene that is active again by then.