@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 +24 -0
- package/README.md +227 -2
- package/TILESET.md +51 -0
- package/builders.d.ts +28 -0
- package/builders.js +80 -0
- package/elevation-source.d.ts +8 -0
- package/elevation-source.js +48 -0
- package/esm/builders.js +76 -0
- package/esm/elevation-source.js +44 -0
- package/esm/feature-api.js +93 -0
- package/esm/flatgeobuf.js +59 -0
- package/esm/geojson.js +10 -0
- package/esm/index.js +10 -0
- package/esm/loader.js +236 -0
- package/esm/manifest.js +83 -0
- package/esm/package.json +3 -0
- package/esm/pmtiles.js +94 -0
- package/esm/query-tiles.js +140 -0
- package/esm/source-config.js +12 -0
- package/esm/source.js +86 -0
- package/esm/terrarium.js +171 -0
- package/esm/three.js +265 -0
- package/esm/view.js +30 -0
- package/feature-api.d.ts +7 -0
- package/feature-api.js +97 -0
- package/flatgeobuf.d.ts +3 -0
- package/flatgeobuf.js +62 -0
- package/geojson.d.ts +3 -0
- package/geojson.js +13 -0
- package/index.d.ts +19 -0
- package/index.js +27 -0
- package/loader.d.ts +73 -0
- package/loader.js +240 -0
- package/manifest.d.ts +21 -0
- package/manifest.js +86 -0
- package/package.json +45 -4
- package/pmtiles.d.ts +13 -0
- package/pmtiles.js +99 -0
- package/query-tiles.d.ts +23 -0
- package/query-tiles.js +144 -0
- package/source-config.d.ts +26 -0
- package/source-config.js +15 -0
- package/source.d.ts +42 -0
- package/source.js +97 -0
- package/terrarium.d.ts +27 -0
- package/terrarium.js +178 -0
- package/three.d.ts +43 -0
- package/three.js +270 -0
- package/view.d.ts +24 -0
- package/view.js +35 -0
package/terrarium.js
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.terrariumHeight = terrariumHeight;
|
|
7
|
+
exports.readTerrarium = readTerrarium;
|
|
8
|
+
const core_1 = require("@vim3d/core");
|
|
9
|
+
const buffer_1 = require("buffer");
|
|
10
|
+
const browser_js_1 = __importDefault(require("pngjs/browser.js"));
|
|
11
|
+
const source_js_1 = require("./source.js");
|
|
12
|
+
const rad = Math.PI / 180;
|
|
13
|
+
const size = 256;
|
|
14
|
+
const maxTileBytes = 1024 * 1024;
|
|
15
|
+
const pngSignature = buffer_1.Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
|
16
|
+
function terrariumHeight(r, g, b) {
|
|
17
|
+
return r * 256 + g + b / 256 - 32768;
|
|
18
|
+
}
|
|
19
|
+
function pixel(lat, lon, tiles) {
|
|
20
|
+
return [(lon + 180) / 360 * tiles * size - 0.5,
|
|
21
|
+
(1 - Math.asinh(Math.tan(lat * rad)) / Math.PI) / 2 * tiles * size - 0.5];
|
|
22
|
+
}
|
|
23
|
+
async function readTerrariumPng(response) {
|
|
24
|
+
const reader = response.body?.getReader();
|
|
25
|
+
if (!reader)
|
|
26
|
+
throw new Error('Terrarium tile has no response body');
|
|
27
|
+
const chunks = [];
|
|
28
|
+
let length = 0;
|
|
29
|
+
try {
|
|
30
|
+
if (Number(response.headers.get('content-length')) > maxTileBytes)
|
|
31
|
+
throw new Error('Terrarium tile exceeds 1 MiB');
|
|
32
|
+
for (;;) {
|
|
33
|
+
const chunk = await reader.read();
|
|
34
|
+
if (chunk.done)
|
|
35
|
+
break;
|
|
36
|
+
length += chunk.value.byteLength;
|
|
37
|
+
if (length > maxTileBytes)
|
|
38
|
+
throw new Error('Terrarium tile exceeds 1 MiB');
|
|
39
|
+
chunks.push(chunk.value);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
await reader.cancel().catch(() => { });
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
reader.releaseLock();
|
|
48
|
+
}
|
|
49
|
+
const bytes = buffer_1.Buffer.concat(chunks, length);
|
|
50
|
+
if (length < 33 || !bytes.subarray(0, 8).equals(pngSignature) || bytes.readUInt32BE(8) !== 13 ||
|
|
51
|
+
bytes.toString('ascii', 12, 16) !== 'IHDR' || bytes.readUInt32BE(16) !== size ||
|
|
52
|
+
bytes.readUInt32BE(20) !== size || bytes[28] !== 0) {
|
|
53
|
+
throw new Error('Expected non-interlaced 256x256 Terrarium PNG tiles');
|
|
54
|
+
}
|
|
55
|
+
for (let offset = 33; offset <= length - 12;) {
|
|
56
|
+
const chunkLength = bytes.readUInt32BE(offset);
|
|
57
|
+
const kind = bytes.toString('ascii', offset + 4, offset + 8);
|
|
58
|
+
if (kind === 'IHDR' || chunkLength > length - offset - 12)
|
|
59
|
+
throw new Error('Invalid Terrarium PNG chunk');
|
|
60
|
+
if (kind === 'IEND') {
|
|
61
|
+
if (chunkLength !== 0 || offset + 12 !== length)
|
|
62
|
+
throw new Error('Invalid Terrarium PNG chunk');
|
|
63
|
+
return browser_js_1.default.PNG.sync.read(bytes).data;
|
|
64
|
+
}
|
|
65
|
+
offset += chunkLength + 12;
|
|
66
|
+
}
|
|
67
|
+
throw new Error('Invalid Terrarium PNG chunk');
|
|
68
|
+
}
|
|
69
|
+
function rectangle(bounds) {
|
|
70
|
+
return Array.isArray(bounds) && bounds.length === 4 && Array.from(bounds).every(Number.isFinite) &&
|
|
71
|
+
bounds[0] < bounds[2] && bounds[1] < bounds[3];
|
|
72
|
+
}
|
|
73
|
+
function projectBounds(origin, [west, south, east, north]) {
|
|
74
|
+
const longitudes = [west, east];
|
|
75
|
+
// East and north are proportional to sin and cos of the longitude offset, respectively.
|
|
76
|
+
for (let lon = origin.lon + Math.ceil((west - origin.lon) / 90) * 90; lon < east; lon += 90) {
|
|
77
|
+
if (lon > west)
|
|
78
|
+
longitudes.push(lon);
|
|
79
|
+
}
|
|
80
|
+
const points = longitudes.flatMap(lon => {
|
|
81
|
+
const latitudes = [south, north];
|
|
82
|
+
if (south < 0 && north > 0)
|
|
83
|
+
latitudes.push(0);
|
|
84
|
+
const stationary = Math.atan2(-Math.cos(origin.lat * rad), Math.sin(origin.lat * rad) * Math.cos((lon - origin.lon) * rad)) / rad;
|
|
85
|
+
const lat = stationary + Math.ceil((south - stationary) / 180) * 180;
|
|
86
|
+
if (lat > south && lat < north)
|
|
87
|
+
latitudes.push(lat);
|
|
88
|
+
return latitudes.map(latitude => (0, core_1.geodeticToScene)(origin, latitude, lon));
|
|
89
|
+
});
|
|
90
|
+
return [Math.min(...points.map(p => p[0])), Math.min(...points.map(p => p[2])),
|
|
91
|
+
Math.max(...points.map(p => p[0])), Math.max(...points.map(p => p[2]))];
|
|
92
|
+
}
|
|
93
|
+
/** Read a bounded Terrarium XYZ view and sample its triangulated height grid. */
|
|
94
|
+
async function readTerrarium(config, { signal, fetch: fetchTile = globalThis.fetch, }) {
|
|
95
|
+
const { url: template, bbox, sceneBounds, origin, zoom, spacing = 40, maxTiles = 24 } = config;
|
|
96
|
+
const maxLatitude = 85.0511287798066;
|
|
97
|
+
if (typeof template !== 'string' || !template.startsWith('https://') || !['{x}', '{y}', '{z}'].every(token => template.includes(token))) {
|
|
98
|
+
throw new Error('Terrain URL must be an HTTPS Terrarium template with {z}, {x}, and {y}');
|
|
99
|
+
}
|
|
100
|
+
if (!Number.isSafeInteger(zoom) || zoom < 0 || zoom > 24)
|
|
101
|
+
throw new RangeError('Expected a Terrarium zoom from 0 to 24');
|
|
102
|
+
if (!origin || ![origin.lat, origin.lon, origin.elevation].every(Number.isFinite) ||
|
|
103
|
+
Math.abs(origin.lat) > maxLatitude || Math.abs(origin.lon) > 180)
|
|
104
|
+
throw new RangeError('Invalid Terrarium scene origin');
|
|
105
|
+
if (!Number.isFinite(spacing) || spacing <= 0)
|
|
106
|
+
throw new RangeError('Invalid Terrarium grid spacing');
|
|
107
|
+
(0, source_js_1.positiveInteger)(maxTiles, 'maxTiles');
|
|
108
|
+
if (maxTiles > 24)
|
|
109
|
+
throw new RangeError('Terrarium maxTiles cannot exceed 24');
|
|
110
|
+
let bounds;
|
|
111
|
+
if (sceneBounds !== undefined) {
|
|
112
|
+
if (bbox !== undefined || !rectangle(sceneBounds))
|
|
113
|
+
throw new RangeError('Expected nonempty metric Terrarium bounds');
|
|
114
|
+
bounds = [...sceneBounds];
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
if (!rectangle(bbox) || bbox[0] < -180 || bbox[2] > 180 || bbox[1] < -maxLatitude || bbox[3] > maxLatitude) {
|
|
118
|
+
throw new RangeError('Expected nonempty WGS84 Terrarium bounds within Web Mercator');
|
|
119
|
+
}
|
|
120
|
+
bounds = projectBounds(origin, bbox);
|
|
121
|
+
}
|
|
122
|
+
if (!rectangle(bounds))
|
|
123
|
+
throw new RangeError('Terrarium bounds cannot form a local scene grid');
|
|
124
|
+
const [minX, minZ, maxX, maxZ] = bounds;
|
|
125
|
+
signal.throwIfAborted();
|
|
126
|
+
const tiles = 2 ** zoom;
|
|
127
|
+
const columns = Math.max(2, Math.ceil((maxX - minX) / spacing) + 1);
|
|
128
|
+
const rows = Math.max(2, Math.ceil((maxZ - minZ) / spacing) + 1);
|
|
129
|
+
if (columns * rows > 1_000_000)
|
|
130
|
+
throw new RangeError('Terrarium grid exceeds 1,000,000 samples');
|
|
131
|
+
const dx = (maxX - minX) / (columns - 1), dz = (maxZ - minZ) / (rows - 1);
|
|
132
|
+
const samples = Array.from({ length: columns * rows }, (_, i) => {
|
|
133
|
+
const col = i % columns, row = Math.floor(i / columns);
|
|
134
|
+
const x = col === columns - 1 ? maxX : minX + col * dx;
|
|
135
|
+
const z = row === rows - 1 ? maxZ : minZ + row * dz;
|
|
136
|
+
const loc = (0, core_1.sceneToGeodetic)(origin, [x, 0, z]);
|
|
137
|
+
return pixel(loc.lat, loc.lon, tiles);
|
|
138
|
+
});
|
|
139
|
+
const reference = pixel(origin.lat, origin.lon, tiles);
|
|
140
|
+
const indices = new Map();
|
|
141
|
+
const tileIndex = (x, y) => [
|
|
142
|
+
((Math.floor(x / size) % tiles) + tiles) % tiles, Math.max(0, Math.min(tiles - 1, Math.floor(y / size))),
|
|
143
|
+
];
|
|
144
|
+
const include = ([x, y]) => {
|
|
145
|
+
for (const i of [Math.floor(x), Math.floor(x) + 1])
|
|
146
|
+
for (const j of [Math.floor(y), Math.floor(y) + 1]) {
|
|
147
|
+
const index = tileIndex(i, j);
|
|
148
|
+
indices.set(index.join('/'), index);
|
|
149
|
+
}
|
|
150
|
+
if (indices.size > maxTiles)
|
|
151
|
+
throw new Error(`Terrain view exceeds the ${maxTiles}-tile budget`);
|
|
152
|
+
};
|
|
153
|
+
for (const coords of samples)
|
|
154
|
+
include(coords);
|
|
155
|
+
include(reference);
|
|
156
|
+
const sources = new Map(await Promise.all([...indices.entries()].map(async ([key, [x, y]]) => {
|
|
157
|
+
const url = template.replaceAll('{z}', String(zoom)).replaceAll('{x}', String(x)).replaceAll('{y}', String(y));
|
|
158
|
+
const response = await fetchTile(url, { signal, redirect: 'error' });
|
|
159
|
+
if (!response.ok)
|
|
160
|
+
throw new Error('Terrarium tile request failed: ' + response.status + ' ' + key);
|
|
161
|
+
return [key, await readTerrariumPng(response)];
|
|
162
|
+
})));
|
|
163
|
+
const value = (x, y) => {
|
|
164
|
+
const rgba = sources.get(tileIndex(x, y).join('/'));
|
|
165
|
+
const i = (((y % size + size) % size) * size + (x % size + size) % size) * 4;
|
|
166
|
+
return terrariumHeight(rgba[i], rgba[i + 1], rgba[i + 2]);
|
|
167
|
+
};
|
|
168
|
+
const height = ([px, py]) => {
|
|
169
|
+
const x = Math.floor(px), y = Math.floor(py), u = px - x, v = py - y;
|
|
170
|
+
return (value(x, y) * (1 - u) + value(x + 1, y) * u) * (1 - v) +
|
|
171
|
+
(value(x, y + 1) * (1 - u) + value(x + 1, y + 1) * u) * v;
|
|
172
|
+
};
|
|
173
|
+
const datum = height(reference);
|
|
174
|
+
const grid = { columns, rows, extent: bounds,
|
|
175
|
+
heights: samples.map(p => Math.round((height(p) - datum) * 100) / 100) };
|
|
176
|
+
const field = new core_1.Heightfield(grid);
|
|
177
|
+
return { bounds, grid, height: (x, z) => field.sampleHeight(x, z), datum, tileCount: indices.size };
|
|
178
|
+
}
|
package/three.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { type Camera, Group, type Scene, Vector2 } from 'three';
|
|
2
|
+
import type { CompiledScene } from '@vim3d/core';
|
|
3
|
+
import type { TileBuilders } from './builders.js';
|
|
4
|
+
import { type LoadedTile, TileLoader, type TileLoaderOptions } from './loader.js';
|
|
5
|
+
import type { TileOrigin } from './manifest.js';
|
|
6
|
+
import { type QueryLoaderOptions, type QueryTile, type QueryTileSourceConfig } from './query-tiles.js';
|
|
7
|
+
import type { TileSourceReader } from './source.js';
|
|
8
|
+
export interface ThreeTilePlayer {
|
|
9
|
+
readonly adapter: {
|
|
10
|
+
readonly scene: Scene;
|
|
11
|
+
addBoundsObject(object: Group): () => void;
|
|
12
|
+
refitShadows(): void;
|
|
13
|
+
};
|
|
14
|
+
readonly renderer: {
|
|
15
|
+
getSize?: (target: Vector2) => Vector2;
|
|
16
|
+
};
|
|
17
|
+
getRenderCamera(): Camera | undefined;
|
|
18
|
+
addRenderHook(hook: {
|
|
19
|
+
beforeRender(): void;
|
|
20
|
+
dispose(): void;
|
|
21
|
+
}): () => void;
|
|
22
|
+
redraw(): void;
|
|
23
|
+
}
|
|
24
|
+
interface GroupOptions<T> {
|
|
25
|
+
/** Return a fresh group with stable resource references; the attachment owns its geometry, materials and textures. */
|
|
26
|
+
readonly createGroup: (entry: LoadedTile<T>, origin: TileOrigin) => Group | Promise<Group>;
|
|
27
|
+
readonly maxScreenSpaceError?: number;
|
|
28
|
+
readonly getViewportHeight?: () => number;
|
|
29
|
+
readonly signal?: AbortSignal;
|
|
30
|
+
}
|
|
31
|
+
export interface ThreeTilesOptions<T> extends Omit<TileLoaderOptions<T>, 'onChange' | 'onEvict' | 'onDispose'>, GroupOptions<T> {
|
|
32
|
+
}
|
|
33
|
+
export interface ThreeQueryTilesOptions extends Omit<QueryLoaderOptions, 'onChange' | 'onEvict' | 'onDispose'>, GroupOptions<QueryTile> {
|
|
34
|
+
}
|
|
35
|
+
export interface ThreeTilesAttachment<T> {
|
|
36
|
+
readonly loader: TileLoader<T>;
|
|
37
|
+
dispose(): void;
|
|
38
|
+
}
|
|
39
|
+
export declare function attachTileBuilders(player: ThreeTilePlayer, scene: CompiledScene, builders: TileBuilders, options?: Omit<ThreeQueryTilesOptions, 'createGroup'>): () => void;
|
|
40
|
+
/** Streams tiles into a Vim3DPlayer without adding Three.js to the main tiles entry. */
|
|
41
|
+
export declare function attachThreeTiles<T>(player: ThreeTilePlayer, manifestUrl: string | URL, options: ThreeTilesOptions<T>): Promise<ThreeTilesAttachment<T>>;
|
|
42
|
+
export declare function attachThreeQueryTiles(player: ThreeTilePlayer, config: QueryTileSourceConfig, reader: TileSourceReader, options: ThreeQueryTilesOptions): ThreeTilesAttachment<QueryTile>;
|
|
43
|
+
export {};
|
package/three.js
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.attachTileBuilders = attachTileBuilders;
|
|
4
|
+
exports.attachThreeTiles = attachThreeTiles;
|
|
5
|
+
exports.attachThreeQueryTiles = attachThreeQueryTiles;
|
|
6
|
+
const three_1 = require("three");
|
|
7
|
+
const loader_js_1 = require("./loader.js");
|
|
8
|
+
const query_tiles_js_1 = require("./query-tiles.js");
|
|
9
|
+
const source_config_js_1 = require("./source-config.js");
|
|
10
|
+
function attachTileBuilders(player, scene, builders, options = {}) {
|
|
11
|
+
const attachments = [];
|
|
12
|
+
const dispose = () => {
|
|
13
|
+
for (const attachment of attachments.splice(0))
|
|
14
|
+
attachment.dispose();
|
|
15
|
+
};
|
|
16
|
+
try {
|
|
17
|
+
for (const { config, props, build } of builders.bindings(scene)) {
|
|
18
|
+
(0, query_tiles_js_1.validateTileSource)(config);
|
|
19
|
+
const reader = (0, source_config_js_1.createReader)(config);
|
|
20
|
+
attachments.push(attachThreeQueryTiles(player, config, reader, {
|
|
21
|
+
...options,
|
|
22
|
+
createGroup({ tile, data }, origin) {
|
|
23
|
+
const result = build({ id: tile.id, source: data.sourceId, features: data.features }, { origin, props });
|
|
24
|
+
const wrap = (object) => {
|
|
25
|
+
const group = new three_1.Group();
|
|
26
|
+
group.name = tile.id;
|
|
27
|
+
group.add(object);
|
|
28
|
+
return group;
|
|
29
|
+
};
|
|
30
|
+
return 'then' in result ? Promise.resolve(result).then(wrap) : wrap(result);
|
|
31
|
+
},
|
|
32
|
+
}));
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
dispose();
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
return dispose;
|
|
40
|
+
}
|
|
41
|
+
function visitResources(object, visit) {
|
|
42
|
+
// Sprites share a Three.js-owned quad.
|
|
43
|
+
if (object.geometry && !object.isSprite)
|
|
44
|
+
visit(object.geometry);
|
|
45
|
+
if (object.isInstancedMesh && object.morphTexture)
|
|
46
|
+
visit(object.morphTexture);
|
|
47
|
+
if (object.isBatchedMesh) {
|
|
48
|
+
for (const texture of [object._matricesTexture, object._indirectTexture, object._colorsTexture]) {
|
|
49
|
+
if (texture)
|
|
50
|
+
visit(texture);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const visitTextures = (value) => {
|
|
54
|
+
if (Array.isArray(value)) {
|
|
55
|
+
for (const item of value) {
|
|
56
|
+
if (item?.isTexture === true)
|
|
57
|
+
visit(item);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
else if (value && typeof value === 'object' && 'isTexture' in value && value.isTexture === true) {
|
|
61
|
+
visit(value);
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
if (!object.material)
|
|
65
|
+
return;
|
|
66
|
+
for (const material of Array.isArray(object.material) ? object.material : [object.material]) {
|
|
67
|
+
visit(material);
|
|
68
|
+
for (const value of Object.values(material))
|
|
69
|
+
visitTextures(value);
|
|
70
|
+
if ('uniforms' in material) {
|
|
71
|
+
for (const uniform of Object.values(material.uniforms)) {
|
|
72
|
+
visitTextures(uniform.value);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
class TileResources {
|
|
78
|
+
references = new Map();
|
|
79
|
+
track(group) {
|
|
80
|
+
const resources = new Set();
|
|
81
|
+
const instances = [];
|
|
82
|
+
group.traverse(node => {
|
|
83
|
+
const object = node;
|
|
84
|
+
visitResources(object, resource => resources.add(resource));
|
|
85
|
+
if (object.isInstancedMesh)
|
|
86
|
+
instances.push(object);
|
|
87
|
+
});
|
|
88
|
+
for (const resource of resources) {
|
|
89
|
+
this.references.set(resource, (this.references.get(resource) ?? 0) + 1);
|
|
90
|
+
}
|
|
91
|
+
return () => {
|
|
92
|
+
// The renderer frees per-instance attributes in response to this event.
|
|
93
|
+
for (const instance of instances)
|
|
94
|
+
three_1.EventDispatcher.prototype.dispatchEvent.call(instance, { type: 'dispose' });
|
|
95
|
+
for (const resource of resources) {
|
|
96
|
+
const count = this.references.get(resource);
|
|
97
|
+
if (count > 1)
|
|
98
|
+
this.references.set(resource, count - 1);
|
|
99
|
+
else {
|
|
100
|
+
this.references.delete(resource);
|
|
101
|
+
resource.dispose();
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/** Streams tiles into a Vim3DPlayer without adding Three.js to the main tiles entry. */
|
|
108
|
+
async function attachThreeTiles(player, manifestUrl, options) {
|
|
109
|
+
const start = prepareAttachment(player, options, options.onError);
|
|
110
|
+
return start(await loader_js_1.TileLoader.open(manifestUrl, { ...options, ...start.callbacks }));
|
|
111
|
+
}
|
|
112
|
+
function attachThreeQueryTiles(player, config, reader, options) {
|
|
113
|
+
const start = prepareAttachment(player, options, options.onError);
|
|
114
|
+
return start((0, query_tiles_js_1.openQueryTiles)(config, reader, { ...options, ...start.callbacks }));
|
|
115
|
+
}
|
|
116
|
+
function prepareAttachment(player, options, onError) {
|
|
117
|
+
const maxScreenSpaceError = options.maxScreenSpaceError ?? 16;
|
|
118
|
+
if (!Number.isFinite(maxScreenSpaceError) || maxScreenSpaceError < 0) {
|
|
119
|
+
throw new RangeError('maxScreenSpaceError must be finite and nonnegative');
|
|
120
|
+
}
|
|
121
|
+
const root = new three_1.Group();
|
|
122
|
+
root.name = '@tiles';
|
|
123
|
+
const groups = new Map();
|
|
124
|
+
let visible = new Set();
|
|
125
|
+
const resources = new TileResources();
|
|
126
|
+
let disposed = false;
|
|
127
|
+
let redrawQueued = false;
|
|
128
|
+
let loader;
|
|
129
|
+
const requestRedraw = () => {
|
|
130
|
+
player.adapter.refitShadows();
|
|
131
|
+
if (!redrawQueued) {
|
|
132
|
+
redrawQueued = true;
|
|
133
|
+
queueMicrotask(() => {
|
|
134
|
+
redrawQueued = false;
|
|
135
|
+
if (!disposed)
|
|
136
|
+
player.redraw();
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
const callbacks = {
|
|
141
|
+
onChange: entries => {
|
|
142
|
+
for (const entry of visible) {
|
|
143
|
+
if (!entries.includes(entry))
|
|
144
|
+
groups.get(entry)?.group?.removeFromParent();
|
|
145
|
+
}
|
|
146
|
+
visible = new Set(entries);
|
|
147
|
+
for (const entry of entries) {
|
|
148
|
+
const tracked = groups.get(entry);
|
|
149
|
+
if (!tracked) {
|
|
150
|
+
const pending = {};
|
|
151
|
+
groups.set(entry, pending);
|
|
152
|
+
const accept = (group) => {
|
|
153
|
+
const release = resources.track(group);
|
|
154
|
+
if (disposed || groups.get(entry) !== pending) {
|
|
155
|
+
release();
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
pending.group = group;
|
|
159
|
+
pending.release = release;
|
|
160
|
+
if (visible.has(entry))
|
|
161
|
+
root.add(group);
|
|
162
|
+
};
|
|
163
|
+
const fail = (error) => {
|
|
164
|
+
if (disposed || groups.get(entry) !== pending)
|
|
165
|
+
return;
|
|
166
|
+
groups.delete(entry);
|
|
167
|
+
onError?.(error, entry.tile);
|
|
168
|
+
};
|
|
169
|
+
try {
|
|
170
|
+
const result = options.createGroup(entry, loader.manifest.origin);
|
|
171
|
+
if ('then' in result)
|
|
172
|
+
void Promise.resolve(result).then(group => {
|
|
173
|
+
accept(group);
|
|
174
|
+
if (!disposed && visible.has(entry))
|
|
175
|
+
requestRedraw();
|
|
176
|
+
}).catch(fail);
|
|
177
|
+
else
|
|
178
|
+
accept(result);
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
fail(error);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
else if (tracked.group && tracked.group.parent !== root)
|
|
185
|
+
root.add(tracked.group);
|
|
186
|
+
}
|
|
187
|
+
requestRedraw();
|
|
188
|
+
},
|
|
189
|
+
onEvict: entry => {
|
|
190
|
+
const tracked = groups.get(entry);
|
|
191
|
+
if (!tracked)
|
|
192
|
+
return;
|
|
193
|
+
groups.delete(entry);
|
|
194
|
+
tracked.group?.removeFromParent();
|
|
195
|
+
tracked.release?.();
|
|
196
|
+
},
|
|
197
|
+
onDispose: () => detach(true),
|
|
198
|
+
};
|
|
199
|
+
const size = new three_1.Vector2();
|
|
200
|
+
const viewProjection = new three_1.Matrix4();
|
|
201
|
+
const lastProjection = new three_1.Matrix4();
|
|
202
|
+
const lastWorld = new three_1.Matrix4();
|
|
203
|
+
const frustum = new three_1.Frustum();
|
|
204
|
+
let lastCamera;
|
|
205
|
+
let lastHeight;
|
|
206
|
+
const beforeRender = () => {
|
|
207
|
+
const camera = player.getRenderCamera();
|
|
208
|
+
const height = options.getViewportHeight?.() ?? player.renderer.getSize?.(size).y;
|
|
209
|
+
const perspective = camera && 'isPerspectiveCamera' in camera && camera.isPerspectiveCamera === true;
|
|
210
|
+
const orthographic = camera && 'isOrthographicCamera' in camera && camera.isOrthographicCamera === true;
|
|
211
|
+
if (!camera?.isCamera || !(perspective || orthographic) ||
|
|
212
|
+
!Number.isFinite(height) || height <= 0) {
|
|
213
|
+
if (lastCamera)
|
|
214
|
+
loader.updateView(undefined);
|
|
215
|
+
lastCamera = undefined;
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
camera.updateWorldMatrix(true, false);
|
|
219
|
+
if (camera === lastCamera && height === lastHeight && lastProjection.equals(camera.projectionMatrix)
|
|
220
|
+
&& lastWorld.equals(camera.matrixWorld))
|
|
221
|
+
return;
|
|
222
|
+
lastCamera = camera;
|
|
223
|
+
lastHeight = height;
|
|
224
|
+
lastProjection.copy(camera.projectionMatrix);
|
|
225
|
+
lastWorld.copy(camera.matrixWorld);
|
|
226
|
+
frustum.setFromProjectionMatrix(viewProjection.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse), camera.coordinateSystem, camera.reversedDepth);
|
|
227
|
+
const pixels = height * Math.abs(camera.projectionMatrix.elements[5]) * 0.5;
|
|
228
|
+
loader.updateView({
|
|
229
|
+
frustum: frustum.planes.map(({ normal: { x, y, z }, constant }) => [x, y, z, constant]),
|
|
230
|
+
projection: perspective
|
|
231
|
+
? { type: 'perspective', position: new three_1.Vector3().setFromMatrixPosition(camera.matrixWorld).toArray(), pixelsPerMetreAtUnitDistance: pixels }
|
|
232
|
+
: { type: 'orthographic', pixelsPerMetre: pixels },
|
|
233
|
+
maxScreenSpaceError,
|
|
234
|
+
});
|
|
235
|
+
};
|
|
236
|
+
let removeHook;
|
|
237
|
+
let removeBounds;
|
|
238
|
+
const detach = (redraw) => {
|
|
239
|
+
if (disposed)
|
|
240
|
+
return;
|
|
241
|
+
disposed = true;
|
|
242
|
+
options.signal?.removeEventListener('abort', abort);
|
|
243
|
+
removeHook?.();
|
|
244
|
+
removeBounds?.();
|
|
245
|
+
root.removeFromParent();
|
|
246
|
+
visible.clear();
|
|
247
|
+
loader.dispose();
|
|
248
|
+
if (redraw) {
|
|
249
|
+
player.adapter.refitShadows();
|
|
250
|
+
player.redraw();
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
const abort = () => detach(true);
|
|
254
|
+
return Object.assign((value) => {
|
|
255
|
+
loader = value;
|
|
256
|
+
try {
|
|
257
|
+
options.signal?.throwIfAborted();
|
|
258
|
+
options.signal?.addEventListener('abort', abort, { once: true });
|
|
259
|
+
removeHook = player.addRenderHook({ beforeRender, dispose: () => detach(false) });
|
|
260
|
+
player.adapter.scene.add(root);
|
|
261
|
+
removeBounds = player.adapter.addBoundsObject(root);
|
|
262
|
+
player.redraw();
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
detach(false);
|
|
266
|
+
throw error;
|
|
267
|
+
}
|
|
268
|
+
return { loader, dispose: () => detach(true) };
|
|
269
|
+
}, { callbacks });
|
|
270
|
+
}
|
package/view.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { TileBounds, TileNode, Vec3 } from './manifest.js';
|
|
2
|
+
export type FrustumPlane = readonly [number, number, number, number];
|
|
3
|
+
export type TileProjection = {
|
|
4
|
+
readonly type: 'perspective';
|
|
5
|
+
readonly position: Vec3;
|
|
6
|
+
readonly pixelsPerMetreAtUnitDistance: number;
|
|
7
|
+
} | {
|
|
8
|
+
readonly type: 'orthographic';
|
|
9
|
+
readonly pixelsPerMetre: number;
|
|
10
|
+
};
|
|
11
|
+
export interface TileView {
|
|
12
|
+
/** Inward-facing planes [a, b, c, d]; points with ax + by + cz + d >= 0 are inside. */
|
|
13
|
+
readonly frustum: readonly FrustumPlane[];
|
|
14
|
+
readonly projection: TileProjection;
|
|
15
|
+
readonly maxScreenSpaceError: number;
|
|
16
|
+
}
|
|
17
|
+
export interface TilePlan {
|
|
18
|
+
readonly tile: TileNode;
|
|
19
|
+
readonly children: readonly TilePlan[];
|
|
20
|
+
readonly depth: number;
|
|
21
|
+
}
|
|
22
|
+
export declare function intersects(bounds: TileBounds, planes: readonly FrustumPlane[]): boolean;
|
|
23
|
+
export declare function screenSpaceError(tile: TileNode, projection: TileProjection): number;
|
|
24
|
+
export declare function planView(tile: TileNode, view: TileView, depth?: number): TilePlan | undefined;
|
package/view.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.intersects = intersects;
|
|
4
|
+
exports.screenSpaceError = screenSpaceError;
|
|
5
|
+
exports.planView = planView;
|
|
6
|
+
function intersects(bounds, planes) {
|
|
7
|
+
return planes.every(([a, b, c, d]) => a * bounds[a < 0 ? 0 : 3] + b * bounds[b < 0 ? 1 : 4]
|
|
8
|
+
+ c * bounds[c < 0 ? 2 : 5] + d >= 0);
|
|
9
|
+
}
|
|
10
|
+
function screenSpaceError(tile, projection) {
|
|
11
|
+
if (tile.geometricError === 0)
|
|
12
|
+
return 0;
|
|
13
|
+
if (projection.type === 'orthographic')
|
|
14
|
+
return tile.geometricError * projection.pixelsPerMetre;
|
|
15
|
+
const [x, y, z] = projection.position;
|
|
16
|
+
const [minX, minY, minZ, maxX, maxY, maxZ] = tile.bounds;
|
|
17
|
+
const distance = Math.hypot(Math.max(minX - x, 0, x - maxX), Math.max(minY - y, 0, y - maxY), Math.max(minZ - z, 0, z - maxZ));
|
|
18
|
+
return tile.geometricError * projection.pixelsPerMetreAtUnitDistance / distance;
|
|
19
|
+
}
|
|
20
|
+
function planView(tile, view, depth = 0) {
|
|
21
|
+
if (!intersects(tile.bounds, view.frustum))
|
|
22
|
+
return undefined;
|
|
23
|
+
const children = [];
|
|
24
|
+
if (tile.children?.length && (!tile.url || screenSpaceError(tile, view.projection) > view.maxScreenSpaceError)) {
|
|
25
|
+
for (const child of tile.children) {
|
|
26
|
+
const visible = planView(child, view, depth + 1);
|
|
27
|
+
if (visible)
|
|
28
|
+
children.push(visible);
|
|
29
|
+
}
|
|
30
|
+
if (children.length === 0)
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
if (tile.url || children.length > 0)
|
|
34
|
+
return { tile, children, depth };
|
|
35
|
+
}
|