@vim3d/tiles 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ Copyright (c) 2013, Dan Lynch
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+ * Redistributions of source code must retain the above copyright
7
+ notice, this list of conditions and the following disclaimer.
8
+ * Redistributions in binary form must reproduce the above copyright
9
+ notice, this list of conditions and the following disclaimer in the
10
+ documentation and/or other materials provided with the distribution.
11
+ * Neither the name of the <organization> nor the
12
+ names of its contributors may be used to endorse or promote products
13
+ derived from this software without specific prior written permission.
14
+
15
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
16
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18
+ DISCLAIMED. IN NO EVENT SHALL Dan Lynch BE LIABLE FOR ANY
19
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
24
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,3 +1,228 @@
1
- # Temporary Holding Version
1
+ # @vim3d/tiles
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An opt-in loader for streaming spatial data. It walks a [v1 tileset](TILESET.md)
4
+ and requests only tiles needed for the current view, plus available coarser
5
+ levels as fallbacks. It does not depend on a renderer.
6
+
7
+ ```ts
8
+ import { geoJSONDecoder, TileLoader, type TileView } from '@vim3d/tiles';
9
+
10
+ const loader = await TileLoader.open('https://example.com/acme/map/v1/tileset.json', {
11
+ decode: geoJSONDecoder(),
12
+ maxConcurrent: 4,
13
+ cacheSize: 64,
14
+ onChange: tiles => {
15
+ // Replace the rendered tile set. Use tile.data and loader.manifest.origin
16
+ // with @vim3d/geojson's toScenePoints, toSceneCurves or toSceneFills.
17
+ },
18
+ onError: (error, tile) => console.error(tile.id, error),
19
+ });
20
+
21
+ function renderView(view: TileView) {
22
+ loader.updateView(view); // Call when the camera or viewport changes.
23
+ }
24
+ ```
25
+
26
+ - Pass the camera's inward-facing frustum planes in tileset scene coordinates,
27
+ and a `maxScreenSpaceError` in pixels. A perspective view takes
28
+ `pixelsPerMetreAtUnitDistance = viewportHeight / (2 * tan(verticalFov / 2))`
29
+ and the camera position; an orthographic view takes
30
+ `pixelsPerMetre = viewportHeight / visibleWorldHeight`. Use the effective
31
+ field of view or visible height after zoom. An empty plane list disables
32
+ frustum culling.
33
+ - `TileLoader.open` fetches and validates a manifest; pass an absolute HTTP(S)
34
+ URL and optionally a `signal` for that request. If you already have the
35
+ manifest JSON, use `new TileLoader(json, manifestUrl, options)`.
36
+ Pass `fetch` to override the transport, or `decode(response, context)` to
37
+ interpret other payload formats. The default GeoJSON decoder uses
38
+ `@vim3d/geojson`; pass resampling options to `geoJSONDecoder(options)`.
39
+ - `loader.visible` and `onChange` give the complete renderable set, not a
40
+ partial update. A parent stays visible until its visible child branches have
41
+ coverage. Obsolete work is aborted; custom decoders should honor
42
+ `context.signal`. Failed tiles are retried on leaving and re-entering
43
+ selection, not on every frame.
44
+ - The cache keeps the least recently used inactive tiles up to `cacheSize`
45
+ entries total. Visible tiles and detail tiles waiting for sibling coverage are
46
+ pinned and may exceed that limit. Pass `updateView(undefined)` to clear the
47
+ view, or `dispose()` to abort outstanding work and release the cache. The host
48
+ owns any geometry or other renderer resources it creates.
49
+
50
+ ## Standard sources without a tileset manifest
51
+
52
+ ```ts
53
+ import { socrataGeoJSON, TileLoader } from '@vim3d/tiles';
54
+
55
+ const reader = socrataGeoJSON('https://example.com/resource/abcd-1234.geojson', {
56
+ geomField: 'the_geom',
57
+ idField: 'objectid',
58
+ attribution: 'Example dataset',
59
+ properties: zoom => zoom < 14 ? ['name'] : ['name', 'height'],
60
+ maxFeatures: zoom => zoom < 14 ? 500 : 2500,
61
+ });
62
+ const loader = TileLoader.fromSource(reader, { lon: -122.42, lat: 37.78, elevation: 0 }, {
63
+ onChange: tiles => { /* Render each tile.data FeatureCollection. */ },
64
+ });
65
+ loader.updateSourceView([{ bbox: [-122.43, 37.77, -122.41, 37.79], zoom: 13 }]);
66
+ ```
67
+
68
+ Pass the current WGS84 `[west, south, east, north]` bbox and optional zoom, or multiple
69
+ tile bboxes (split views crossing the antimeridian). Each loaded result has its
70
+ `query`; the manifest origin is available for projection, but source views
71
+ don't use the v1 manifest tree or scene-space tile bounds. The loader aborts
72
+ obsolete queries and deduplicates stable IDs across visible results, keeping
73
+ the first copy. Pass `[]` to clear the view. Each reader exposes its
74
+ `attribution` and a `query(bbox, { signal, zoom, fetch })` async iterable.
75
+ Iterate with `for await` to get one batch at a time without buffering a full
76
+ query. Use `idField` for IDs stored in properties; use sources with IDs stable
77
+ across views. Built-in readers reject features without a usable ID.
78
+
79
+ For serialized bindings, `createReader(config)` uses the same options with
80
+ `kind` (`flatgeobuf`, `pmtiles`, `ogc-features`, or `socrata`) and a `url` string.
81
+ It accepts numeric limits and arrays of properties or layers, but not
82
+ functions. The caller uses `bounds` and `origin` for view planning and passes
83
+ only selected bboxes to the reader. Optional `minZoom` and `maxZoom` constrain
84
+ the reader's level of detail.
85
+
86
+ - `flatGeobuf(url)` uses the file's spatial index and HTTP byte ranges. Use an
87
+ indexed WGS84 file.
88
+ - `pmTiles(url)` decodes MVT from the overlapping XYZ tiles, at the requested
89
+ zoom clamped to the archive. If zoom is omitted, it chooses a zoom based on
90
+ the bbox's Web Mercator extent. Tune `maxTiles` (default 64) and optionally
91
+ select MVT layers for decoding. MVT is tile-granular, so a fetched tile can
92
+ contain features outside the view. Use IDs stable across tiles within each
93
+ layer; MVT IDs are namespaced by layer, and duplicate clipped pieces are not
94
+ merged.
95
+ - `ogcApiFeatures(itemsUrl)` sends `bbox` on the first request and follows
96
+ same-collection `next` links as provided by the service. An unsuccessful page
97
+ fails the query. Use `properties` only if the service supports that parameter.
98
+ - `socrataGeoJSON(resourceUrl)` supports DataSF's spatial `.geojson` datasets.
99
+ It combines the bbox intersection with any existing `$where` and pages with
100
+ `$limit` and `$offset`. Set `geomField` if the geometry column isn't
101
+ `the_geom`.
102
+
103
+ The two API readers default to 1,000 features per page and at most 10,000 per
104
+ query; set a smaller `maxFeatures` or attribute selection for overview zooms.
105
+ They use zoom 0 for level-of-detail options when no zoom is supplied, unless
106
+ the reader is configured with a higher `minZoom`.
107
+ The binary readers require HTTP 206 and `Content-Range` (expose it via CORS
108
+ on cross-origin hosts); they never fall back to downloading the full file.
109
+
110
+ ## Terrarium elevation
111
+
112
+ `readTerrarium(config, { signal, fetch? })` reads the Terrarium XYZ PNG
113
+ tiles needed by a bounded elevation grid:
114
+
115
+ ```ts
116
+ import { readTerrarium } from '@vim3d/tiles';
117
+
118
+ const dem = await readTerrarium({
119
+ url: 'https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png',
120
+ bbox: [-122.43, 37.77, -122.39, 37.80],
121
+ zoom: 12,
122
+ origin: { lat: 37.79, lon: -122.41, elevation: 0 },
123
+ }, { signal: AbortSignal.timeout(30_000) });
124
+ const ground = dem.height(100, -50);
125
+ ```
126
+
127
+ `bbox` is a local WGS84 rectangle `[west, south, east, north]`, projected into
128
+ its enclosing metric scene rectangle. Split requests crossing the antimeridian.
129
+ For an existing metric view, supply `sceneBounds` instead. Returned `bounds`
130
+ and input `sceneBounds` use `[minX, minZ, maxX, maxZ]` in metres (+X east,
131
+ −Z north). Grid spacing defaults to at most 40 m, and adjacent pixels are
132
+ bilinearly sampled across tile seams. `height(x, z)` samples the same
133
+ triangles as the returned Vim3D `grid`. It returns `null` outside coverage;
134
+ tile request or decoding failures reject the read rather than inventing heights.
135
+
136
+ The returned `datum` is the source DEM height sampled at the scene origin.
137
+ Grid and sampler heights are metres **relative to that sample** (+Y up), not
138
+ WGS84 ellipsoid elevations. No vertical datum conversion is performed. The
139
+ origin's ellipsoid elevation is used only in the horizontal coordinate transform.
140
+
141
+ The reader deduplicates tile requests and rejects a grid that needs more than
142
+ 24 tiles (including the datum and interpolation neighbors); use `maxTiles`
143
+ to lower the budget. The grid is limited to 1,000,000 samples. Tile URLs must use
144
+ HTTPS and contain all three XYZ tokens. Redirects are disabled, and responses
145
+ are capped at 1 MiB and checked for a non-interlaced 256×256 PNG header and
146
+ valid chunk framing before decoding.
147
+
148
+ ### Bind elevation in a scene
149
+
150
+ Declare a `source:tiles` and wire its `source` port as with other tile sources:
151
+
152
+ ```vim3d
153
+ node /geo/dem source:tiles
154
+ set config {"kind":"terrarium","url":"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png","bbox":[-122.43,37.77,-122.39,37.80],"zoom":12,"origin":{"lat":37.79,"lon":-122.41,"elevation":0}}
155
+ node /geo/elevation geo:terrarium
156
+ node /geo/ground geo:heightfield
157
+ add geo
158
+ name terrain
159
+ connect /geo/dem/source /geo/elevation/source
160
+ connect /geo/elevation/grid /geo/ground/grid
161
+ connect /geo/ground/geometry /obj/terrain/geometry
162
+ ```
163
+
164
+ For a custom host, create an `ElevationSources` per scene. Pass
165
+ `{ contexts: elevation.contexts(existingContexts) }` to `compileScene` or
166
+ `fromStorageGraph`, and then await `elevation.load(compiledScene, { signal })`
167
+ before evaluating or starting a player. To combine with feature tile builders,
168
+ pass `builders.contexts(existingContexts)` into `elevation.contexts`.
169
+ The DEM is fetched once per bound source for the declared bbox, not recomputed
170
+ per frame or expanded with camera movement. Its grid also works with
171
+ `geo:height-sample` and `geo:drape`. The CLI supports the binding in
172
+ `eval`, `render`, and the default Three.js `view` (not `view --blocks`).
173
+
174
+ ## Camera-driven query tiles
175
+
176
+ `openQueryTiles(config, reader, options)` takes a standard reader and a
177
+ serializable `QueryTileSourceConfig` with WGS84 bounds and an origin. Call
178
+ `loader.updateView(view)` to query only visible cells in an implicit quadtree.
179
+ The loader aborts obsolete queries, deduplicates stable feature IDs within
180
+ each tile, and stops reading at the feature limit. An overview covering the
181
+ entire extent does not fetch detail. If a view exceeds the visible-tile
182
+ budget, the loader tries coarser cells within the configured zoom range.
183
+ `elevationBounds` gives the min/max WGS84 ellipsoid heights in metres for culling.
184
+
185
+ ## Three.js player
186
+
187
+ For a scene with `source:tiles`, register tile builders with
188
+ `new TileBuilders()` from `@vim3d/tiles/builders.js` and call
189
+ `builders.register('geo:buildings', build, props)`. Pass
190
+ `{ contexts: builders.contexts(existingContexts) }` to both `compileScene`
191
+ and `fromStorageGraph`. Built-in geo registration supplies `source:tiles`;
192
+ the registry adds the builder's object input `source` without replacing an
193
+ existing static evaluator or its other inputs. A node wired only for streaming
194
+ skips static evaluation unless another node uses its outputs; its tiles are
195
+ built by the registered builder. Wire the two ports in the scene:
196
+
197
+ ```
198
+ connect /geo/parcels/source /geo/buildings/source
199
+ ```
200
+
201
+ After the player starts, call `attachTileBuilders(player, scene, builders)`
202
+ from the Three.js entry. It resolves the reader for each wired source and
203
+ passes `build({ id, source, features }, { origin, props })` the tile ID,
204
+ source URL, tile features and builder node props. Return a fresh Three.js
205
+ object or a promise for one. The adapter owns the returned render resources.
206
+ It exposes a detach function and also detaches when the player is disposed
207
+ or the optional `signal` aborts.
208
+
209
+ Import `attachThreeTiles` from `@vim3d/tiles/three` (native ESM:
210
+ `@vim3d/tiles/esm/three.js`). This optional entry uses the player's render
211
+ camera and viewport, including camera-only redraws. Install `three` when
212
+ using this entry; the main entry does not import it.
213
+
214
+ ```ts
215
+ const attachment = await attachThreeTiles(player, manifestUrl, {
216
+ decode: geoJSONDecoder(),
217
+ createGroup: ({ data }, origin) => buildTileGroup(data, origin),
218
+ });
219
+ ```
220
+
221
+ Return a fresh Three.js group per tile from `createGroup` and keep its resource
222
+ references stable. The attachment mounts visible groups, keeps cached groups
223
+ detached, and disposes their geometry, materials and textures after no mounted
224
+ or cached tile group uses them. It does not invoke custom object disposers.
225
+ Visible tile groups participate in player
226
+ bounds and shadow fitting. If a custom renderer does not implement
227
+ `getSize`, pass `getViewportHeight` in pixels. Call `attachment.dispose()`
228
+ to detach early; disposing the player also cleans it up.
package/TILESET.md ADDED
@@ -0,0 +1,51 @@
1
+ # Publishing a v1 tileset
2
+
3
+ Publish a small JSON manifest and a separate file per tile. Example:
4
+
5
+ ```json
6
+ {
7
+ "version": 1,
8
+ "origin": { "lat": 40, "lon": -75, "elevation": 0 },
9
+ "root": {
10
+ "id": "0",
11
+ "bounds": [-512, -15, -512, 512, 180, 512],
12
+ "geometricError": 32,
13
+ "url": "tiles/0.geojson",
14
+ "children": [
15
+ {
16
+ "id": "0/nw",
17
+ "bounds": [-512, -15, -512, 0, 180, 0],
18
+ "geometricError": 0,
19
+ "url": "tiles/0/nw.geojson"
20
+ },
21
+ {
22
+ "id": "0/ne",
23
+ "bounds": [0, -15, -512, 512, 180, 0],
24
+ "geometricError": 0,
25
+ "url": "tiles/0/ne.geojson"
26
+ }
27
+ ]
28
+ }
29
+ }
30
+ ```
31
+
32
+ - **Coordinates:** The origin is WGS84 in degrees, with ellipsoid elevation
33
+ in metres. All bounds are `[minX,minY,minZ,maxX,maxY,maxZ]` in the same local
34
+ frame (+X east, +Y up, −Z north, metres). Include the full rendered extent
35
+ (e.g. extruded height and road width), and enclose all child bounds.
36
+ - **Hierarchy:** IDs are unique and stable. A node has at most four children.
37
+ Leaves need a URL; internal nodes can omit it to serve only as an index.
38
+ Error is nonnegative in metres, never increases toward the leaves, and
39
+ represents the approximation error of that LOD. A parent's payload is the
40
+ coarse representation of the same content as its children combined. Omit
41
+ empty quadrants. Assign or clip features crossing tile boundaries so that
42
+ overlapping tiles do not draw duplicate geometry.
43
+ - **Payloads:** For the built-in decoder, serve WGS84 GeoJSON FeatureCollections
44
+ with longitude first. Preserve feature IDs, source properties needed to build
45
+ geometry, and attribution. Keep payloads small and independently usable.
46
+ - **Hosting:** Use HTTPS, e.g. `https://example.com/acme/map/v1/tileset.json`.
47
+ Tile URLs are HTTP(S), resolved against the manifest's final URL after
48
+ redirects. Serve the manifest as `application/json` and GeoJSON tiles as
49
+ `application/geo+json`. Both need CORS headers for cross-origin viewers.
50
+ Compress responses and publish tiles before exposing the manifest. Use
51
+ versioned or content-addressed URLs for immutable, long-cache tile responses.
package/builders.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { type CompiledScene, type ContextValues, type ExtensionContextDefinition, type ExtensionPropDefinition } from '@vim3d/core';
2
+ import type { Feature } from '@vim3d/geojson';
3
+ import type { Object3D } from 'three';
4
+ import type { TileOrigin } from './manifest.js';
5
+ export type TileBuilder = (tile: {
6
+ readonly id: string;
7
+ readonly source: string;
8
+ readonly features: readonly Feature[];
9
+ }, ctx: {
10
+ readonly origin: TileOrigin;
11
+ readonly props: ContextValues;
12
+ }) => Object3D | Promise<Object3D>;
13
+ export interface TileBuilderRegistration {
14
+ readonly type: string;
15
+ readonly build: TileBuilder;
16
+ readonly props?: readonly ExtensionPropDefinition[];
17
+ }
18
+ export declare class TileBuilders {
19
+ private readonly builders;
20
+ constructor(registrations?: readonly TileBuilderRegistration[]);
21
+ register(type: string, build: TileBuilder, props?: readonly ExtensionPropDefinition[]): void;
22
+ contexts(base?: readonly ExtensionContextDefinition[]): readonly ExtensionContextDefinition[];
23
+ bindings({ graph }: CompiledScene): {
24
+ config: unknown;
25
+ props: Readonly<Record<string, import("@vim3d/core").ContextValue>>;
26
+ build: TileBuilder;
27
+ }[];
28
+ }
package/builders.js ADDED
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TileBuilders = void 0;
4
+ const core_1 = require("@vim3d/core");
5
+ function extraProps(props, existing) {
6
+ return props.filter(prop => !existing.some(base => base.name === prop.name))
7
+ .map(prop => prop.required ? { ...prop, required: false } : prop);
8
+ }
9
+ class TileBuilders {
10
+ builders = new Map();
11
+ constructor(registrations = []) {
12
+ for (const { type, build, props } of registrations)
13
+ this.register(type, build, props);
14
+ }
15
+ register(type, build, props = []) {
16
+ if (typeof build !== 'function')
17
+ throw new TypeError('Missing tile builder for ' + type);
18
+ if (this.builders.has(type))
19
+ throw new Error('Duplicate tile builder: ' + type);
20
+ this.builders.set(type, { type, build, props });
21
+ }
22
+ contexts(base = []) {
23
+ if (!this.builders.size)
24
+ return base;
25
+ const geo = base.find(context => context.name === 'geo' && context.stage === 'geo');
26
+ const builtinGeo = core_1.BUILTIN_CONTEXTS.find(context => context.name === 'geo');
27
+ const types = new Map(geo?.nodeTypes.map(node => [node.type, node]));
28
+ const augmentNodeTypes = new Map(geo?.augmentNodeTypes?.map(node => [node.type, node]));
29
+ for (const { type, props } of this.builders.values()) {
30
+ const node = types.get(type);
31
+ const source = { name: 'source', type: 'object' };
32
+ const builtin = builtinGeo.nodeTypes.find(node => node.type === type);
33
+ if (builtin) {
34
+ const extra = augmentNodeTypes.get(type);
35
+ const inputs = extra?.inputs ?? [];
36
+ const existingProps = [...builtin.props, ...extra?.props ?? []];
37
+ augmentNodeTypes.set(type, {
38
+ type,
39
+ inputs: [...inputs, ...(![...builtin.inputs, ...inputs].some(input => input.name === source.name) ? [source] : [])],
40
+ props: [...extra?.props ?? [], ...extraProps(props, existingProps)],
41
+ });
42
+ continue;
43
+ }
44
+ types.set(type, {
45
+ type, props: node ? [...node.props, ...extraProps(props, node.props)] : props,
46
+ inputs: [...(node?.inputs.filter(port => port.name !== source.name) ?? []), source],
47
+ outputs: node?.outputs ?? [],
48
+ evaluate: node?.evaluate ?? (() => ({})),
49
+ });
50
+ }
51
+ return [...base.filter(context => context !== geo), {
52
+ name: 'geo', stage: 'geo', nodeTypes: [...types.values()], augmentNodeTypes: [...augmentNodeTypes.values()],
53
+ }];
54
+ }
55
+ bindings({ graph }) {
56
+ const nodes = new Map(graph.nodes.map(node => [node.name, node]));
57
+ return graph.edges.flatMap(({ src, dst }) => {
58
+ if (src.port !== 'source' || dst.port !== 'source')
59
+ return [];
60
+ const source = nodes.get(src.node);
61
+ if (source?.type !== 'source:tiles')
62
+ return [];
63
+ const builder = nodes.get(dst.node);
64
+ if (builder.type === 'geo:terrarium')
65
+ return [];
66
+ const registration = this.builders.get(builder.type);
67
+ if (!registration)
68
+ throw new Error('No tile builder registered for ' + builder.type);
69
+ const config = source.props.find(prop => prop.name === 'config')?.value;
70
+ const props = Object.fromEntries(builder.props.map(({ name, value }) => [name, value]));
71
+ for (const prop of registration.props ?? []) {
72
+ if (prop.required && !Object.hasOwn(props, prop.name)) {
73
+ throw new Error('Missing required tile builder prop: ' + builder.type + '/' + prop.name);
74
+ }
75
+ }
76
+ return [{ config, props, build: registration.build }];
77
+ });
78
+ }
79
+ }
80
+ exports.TileBuilders = TileBuilders;
@@ -0,0 +1,8 @@
1
+ import type { CompiledScene, ExtensionContextDefinition } from '@vim3d/core';
2
+ import type { SourceReadOptions } from './source.js';
3
+ /** One scene's bounded DEM bindings, resolved before synchronous frame evaluation. */
4
+ export declare class ElevationSources {
5
+ private loaded;
6
+ contexts(base?: readonly ExtensionContextDefinition[]): readonly ExtensionContextDefinition[];
7
+ load({ graph }: CompiledScene, options: SourceReadOptions): Promise<void>;
8
+ }
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ElevationSources = void 0;
4
+ const terrarium_js_1 = require("./terrarium.js");
5
+ /** One scene's bounded DEM bindings, resolved before synchronous frame evaluation. */
6
+ class ElevationSources {
7
+ loaded = new Map();
8
+ contexts(base = []) {
9
+ const geo = base.find(context => context.name === 'geo' && context.stage === 'geo');
10
+ const terrain = {
11
+ type: 'geo:terrarium',
12
+ props: [],
13
+ inputs: [{ name: 'source', type: 'object' }],
14
+ outputs: [{ name: 'grid', type: 'object' }],
15
+ evaluate: ({ path }) => {
16
+ const elevation = this.loaded.get(path);
17
+ if (!elevation)
18
+ throw new Error('Load the bound Terrarium elevation source before evaluating this scene');
19
+ return { grid: elevation.grid };
20
+ },
21
+ };
22
+ return [...base.filter(context => context !== geo), {
23
+ name: 'geo', stage: 'geo', nodeTypes: [...geo?.nodeTypes ?? [], terrain], augmentNodeTypes: geo?.augmentNodeTypes,
24
+ }];
25
+ }
26
+ async load({ graph }, options) {
27
+ const nodes = new Map(graph.nodes.map(node => [node.name, node]));
28
+ const sources = new Map(graph.edges.filter(edge => edge.dst.port === 'source').map(edge => [edge.dst.node, edge.src]));
29
+ const requests = new Map();
30
+ const bindings = graph.nodes.filter(node => node.type === 'geo:terrarium').map(node => {
31
+ const link = sources.get(node.name);
32
+ const source = link && nodes.get(link.node);
33
+ const config = source?.props.find(prop => prop.name === 'config')?.value;
34
+ if (link?.port !== 'source' || source?.type !== 'source:tiles' || !config || typeof config !== 'object' ||
35
+ !('kind' in config) || config.kind !== 'terrarium') {
36
+ throw new TypeError(node.name + ': connect a source:tiles node with kind "terrarium"');
37
+ }
38
+ return { path: decodeURIComponent(node.name), source: source.name, config: config };
39
+ });
40
+ this.loaded = new Map(await Promise.all(bindings.map(async ({ path, source, config }) => {
41
+ let request = requests.get(source);
42
+ if (!request)
43
+ requests.set(source, request = (0, terrarium_js_1.readTerrarium)(config, options));
44
+ return [path, await request];
45
+ })));
46
+ }
47
+ }
48
+ exports.ElevationSources = ElevationSources;
@@ -0,0 +1,76 @@
1
+ import { BUILTIN_CONTEXTS } from '@vim3d/core';
2
+ function extraProps(props, existing) {
3
+ return props.filter(prop => !existing.some(base => base.name === prop.name))
4
+ .map(prop => prop.required ? { ...prop, required: false } : prop);
5
+ }
6
+ export class TileBuilders {
7
+ builders = new Map();
8
+ constructor(registrations = []) {
9
+ for (const { type, build, props } of registrations)
10
+ this.register(type, build, props);
11
+ }
12
+ register(type, build, props = []) {
13
+ if (typeof build !== 'function')
14
+ throw new TypeError('Missing tile builder for ' + type);
15
+ if (this.builders.has(type))
16
+ throw new Error('Duplicate tile builder: ' + type);
17
+ this.builders.set(type, { type, build, props });
18
+ }
19
+ contexts(base = []) {
20
+ if (!this.builders.size)
21
+ return base;
22
+ const geo = base.find(context => context.name === 'geo' && context.stage === 'geo');
23
+ const builtinGeo = BUILTIN_CONTEXTS.find(context => context.name === 'geo');
24
+ const types = new Map(geo?.nodeTypes.map(node => [node.type, node]));
25
+ const augmentNodeTypes = new Map(geo?.augmentNodeTypes?.map(node => [node.type, node]));
26
+ for (const { type, props } of this.builders.values()) {
27
+ const node = types.get(type);
28
+ const source = { name: 'source', type: 'object' };
29
+ const builtin = builtinGeo.nodeTypes.find(node => node.type === type);
30
+ if (builtin) {
31
+ const extra = augmentNodeTypes.get(type);
32
+ const inputs = extra?.inputs ?? [];
33
+ const existingProps = [...builtin.props, ...extra?.props ?? []];
34
+ augmentNodeTypes.set(type, {
35
+ type,
36
+ inputs: [...inputs, ...(![...builtin.inputs, ...inputs].some(input => input.name === source.name) ? [source] : [])],
37
+ props: [...extra?.props ?? [], ...extraProps(props, existingProps)],
38
+ });
39
+ continue;
40
+ }
41
+ types.set(type, {
42
+ type, props: node ? [...node.props, ...extraProps(props, node.props)] : props,
43
+ inputs: [...(node?.inputs.filter(port => port.name !== source.name) ?? []), source],
44
+ outputs: node?.outputs ?? [],
45
+ evaluate: node?.evaluate ?? (() => ({})),
46
+ });
47
+ }
48
+ return [...base.filter(context => context !== geo), {
49
+ name: 'geo', stage: 'geo', nodeTypes: [...types.values()], augmentNodeTypes: [...augmentNodeTypes.values()],
50
+ }];
51
+ }
52
+ bindings({ graph }) {
53
+ const nodes = new Map(graph.nodes.map(node => [node.name, node]));
54
+ return graph.edges.flatMap(({ src, dst }) => {
55
+ if (src.port !== 'source' || dst.port !== 'source')
56
+ return [];
57
+ const source = nodes.get(src.node);
58
+ if (source?.type !== 'source:tiles')
59
+ return [];
60
+ const builder = nodes.get(dst.node);
61
+ if (builder.type === 'geo:terrarium')
62
+ return [];
63
+ const registration = this.builders.get(builder.type);
64
+ if (!registration)
65
+ throw new Error('No tile builder registered for ' + builder.type);
66
+ const config = source.props.find(prop => prop.name === 'config')?.value;
67
+ const props = Object.fromEntries(builder.props.map(({ name, value }) => [name, value]));
68
+ for (const prop of registration.props ?? []) {
69
+ if (prop.required && !Object.hasOwn(props, prop.name)) {
70
+ throw new Error('Missing required tile builder prop: ' + builder.type + '/' + prop.name);
71
+ }
72
+ }
73
+ return [{ config, props, build: registration.build }];
74
+ });
75
+ }
76
+ }
@@ -0,0 +1,44 @@
1
+ import { readTerrarium } from './terrarium.js';
2
+ /** One scene's bounded DEM bindings, resolved before synchronous frame evaluation. */
3
+ export class ElevationSources {
4
+ loaded = new Map();
5
+ contexts(base = []) {
6
+ const geo = base.find(context => context.name === 'geo' && context.stage === 'geo');
7
+ const terrain = {
8
+ type: 'geo:terrarium',
9
+ props: [],
10
+ inputs: [{ name: 'source', type: 'object' }],
11
+ outputs: [{ name: 'grid', type: 'object' }],
12
+ evaluate: ({ path }) => {
13
+ const elevation = this.loaded.get(path);
14
+ if (!elevation)
15
+ throw new Error('Load the bound Terrarium elevation source before evaluating this scene');
16
+ return { grid: elevation.grid };
17
+ },
18
+ };
19
+ return [...base.filter(context => context !== geo), {
20
+ name: 'geo', stage: 'geo', nodeTypes: [...geo?.nodeTypes ?? [], terrain], augmentNodeTypes: geo?.augmentNodeTypes,
21
+ }];
22
+ }
23
+ async load({ graph }, options) {
24
+ const nodes = new Map(graph.nodes.map(node => [node.name, node]));
25
+ const sources = new Map(graph.edges.filter(edge => edge.dst.port === 'source').map(edge => [edge.dst.node, edge.src]));
26
+ const requests = new Map();
27
+ const bindings = graph.nodes.filter(node => node.type === 'geo:terrarium').map(node => {
28
+ const link = sources.get(node.name);
29
+ const source = link && nodes.get(link.node);
30
+ const config = source?.props.find(prop => prop.name === 'config')?.value;
31
+ if (link?.port !== 'source' || source?.type !== 'source:tiles' || !config || typeof config !== 'object' ||
32
+ !('kind' in config) || config.kind !== 'terrarium') {
33
+ throw new TypeError(node.name + ': connect a source:tiles node with kind "terrarium"');
34
+ }
35
+ return { path: decodeURIComponent(node.name), source: source.name, config: config };
36
+ });
37
+ this.loaded = new Map(await Promise.all(bindings.map(async ({ path, source, config }) => {
38
+ let request = requests.get(source);
39
+ if (!request)
40
+ requests.set(source, request = readTerrarium(config, options));
41
+ return [path, await request];
42
+ })));
43
+ }
44
+ }