mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
Give layers a draw port through the viewer they hold
The Cesium draw sets move out of the shared ports into their own module, so they can be built over a viewer no renderer is bound to. findDraw and drawOf find a viewer's draw port as findCamera finds its camera: the bound renderer's, or one built over a caller's own viewer once the Cesium adapter's draw module (exported as ./render/cesium/draw) has loaded. A renderer bound later releases a built port: its sets keep drawing.
This commit is contained in:
1 parent
b3dfcddcde
commit
99ad51048f
8 files changed
+807
-489
No files matched your search
@@ -0,0 +1,567 @@
|
||||
/**
|
||||
* @module render/cesium/draw
|
||||
* @description The Cesium renderer's draw port
|
||||
* (`src/render/contract/draw.d.ts`): batched sets of items, each set one
|
||||
* primitive collection in the scene, rebuilt when its items change. Every
|
||||
* item carries a pick id `{set, id, meta, lodGroup}`, which the query port
|
||||
* (`ports.js`) reads picks back through.
|
||||
*
|
||||
* Built over a scene by `createCesiumPorts`, and on its own over a Cesium
|
||||
* viewer with no renderer bound, when code first asks
|
||||
* `findDraw` for one (`rendererOf.js`).
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { provideUnboundDraw } from '../rendererOf.js';
|
||||
import { listenerList, toCartesian, uncaught } from './common.js';
|
||||
// A caller loads this module for a viewer of its own; what draws there
|
||||
// flies through `cameraOf` too, so the camera factory comes with it.
|
||||
import './camera.js';
|
||||
|
||||
/** The contract's colour as Cesium's. */
|
||||
export function toColor(color, alpha = 1) {
|
||||
if (color === undefined || color === null)
|
||||
return Cesium.Color.WHITE.withAlpha(alpha);
|
||||
const c =
|
||||
typeof color === 'string'
|
||||
? Cesium.Color.fromCssColorString(color)
|
||||
: new Cesium.Color(color[0], color[1], color[2], color[3] ?? 1);
|
||||
return c.withAlpha(c.alpha * alpha);
|
||||
}
|
||||
|
||||
/** An image reference as something a billboard takes. */
|
||||
export function toImage(image) {
|
||||
if (typeof image === 'string') return image;
|
||||
if (image?.svg)
|
||||
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(image.svg)}`;
|
||||
if (image?.canvas) return image.canvas;
|
||||
throw new Error('the Cesium renderer takes URL, SVG and canvas images only');
|
||||
}
|
||||
|
||||
const ANCHORS = {
|
||||
center: Cesium.VerticalOrigin.CENTER,
|
||||
bottom: Cesium.VerticalOrigin.BOTTOM,
|
||||
top: Cesium.VerticalOrigin.TOP,
|
||||
};
|
||||
|
||||
/**
|
||||
* The draw port over `scene`, and what the other ports read of it: the live
|
||||
* sets by id, a version that changes with them, the scene's 3D tilesets and
|
||||
* the clamp-state watch the frame loop runs after each draw.
|
||||
* @param {{scene: object, report: (error: unknown) => void}} options
|
||||
*/
|
||||
export function createCesiumDraw({ scene, report }) {
|
||||
const sets = new Map();
|
||||
// Bumped on every change to the sets or what they hold.
|
||||
let setsVersion = 0;
|
||||
// A viewer can be destroyed before the layers drawing on it
|
||||
// let their sets go; those calls then have nothing left to do.
|
||||
const live = () => !scene.isDestroyed?.();
|
||||
const requestRender = () => {
|
||||
if (live()) scene.requestRender();
|
||||
};
|
||||
|
||||
function makeSet(kind, spec, build) {
|
||||
if (sets.has(spec.id)) throw new Error(`a set with id ${spec.id} is live`);
|
||||
const items = new Map();
|
||||
const listeners = { ready: listenerList(report) };
|
||||
const record = { kind, spec, items, listeners, host: null, pickIds: [] };
|
||||
// Each build records its items' pick ids, for height queries to see
|
||||
// through.
|
||||
const rebuild = () => {
|
||||
record.pickIds = [];
|
||||
build(record);
|
||||
setsVersion += 1;
|
||||
};
|
||||
record.rebuild = rebuild;
|
||||
const handle = {
|
||||
id: spec.id,
|
||||
set(list) {
|
||||
items.clear();
|
||||
for (const item of list) items.set(item.id, item);
|
||||
rebuild();
|
||||
requestRender();
|
||||
},
|
||||
upsert(list) {
|
||||
for (const item of list) items.set(item.id, item);
|
||||
rebuild();
|
||||
requestRender();
|
||||
},
|
||||
remove(ids) {
|
||||
for (const id of ids) items.delete(id);
|
||||
rebuild();
|
||||
requestRender();
|
||||
},
|
||||
clear() {
|
||||
items.clear();
|
||||
rebuild();
|
||||
requestRender();
|
||||
},
|
||||
setOptions(options) {
|
||||
Object.assign(spec, options);
|
||||
setsVersion += 1;
|
||||
if (record.host) record.host.show = spec.show !== false;
|
||||
requestRender();
|
||||
},
|
||||
size: () => items.size,
|
||||
get show() {
|
||||
return spec.show !== false;
|
||||
},
|
||||
set show(value) {
|
||||
spec.show = value;
|
||||
if (record.host) record.host.show = value;
|
||||
requestRender();
|
||||
},
|
||||
on(event, cb) {
|
||||
return listeners[event]?.on(cb) ?? (() => {});
|
||||
},
|
||||
dispose() {
|
||||
if (record.host && !record.host.isDestroyed?.() && live())
|
||||
scene.primitives.remove(record.host);
|
||||
record.host = null;
|
||||
// A newer set under the same id is not this handle's to remove.
|
||||
if (sets.get(spec.id) === record) sets.delete(spec.id);
|
||||
setsVersion += 1;
|
||||
requestRender();
|
||||
},
|
||||
};
|
||||
sets.set(spec.id, record);
|
||||
setsVersion += 1;
|
||||
return handle;
|
||||
}
|
||||
|
||||
function pickId(record, item) {
|
||||
const id = {
|
||||
set: record.spec.id,
|
||||
id: item.id,
|
||||
meta: item.meta,
|
||||
lodGroup: item.lodGroup,
|
||||
};
|
||||
record.pickIds.push(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
function replaceHost(record, host) {
|
||||
if (record.host) scene.primitives.remove(record.host);
|
||||
record.host = host;
|
||||
host.show = record.spec.show !== false;
|
||||
scene.primitives.add(host);
|
||||
}
|
||||
|
||||
// Atlases icons name images from, by id: `{atlas, slot}` reads the slot
|
||||
// when its set is built, and registering an atlas again rebuilds the icon
|
||||
// sets that drew from it.
|
||||
const atlases = new Map();
|
||||
|
||||
/**
|
||||
* An icon's image: an atlas slot read through its atlas, or undefined
|
||||
* while its atlas or slot is not registered (it draws once it is).
|
||||
*/
|
||||
function iconImage(record, image) {
|
||||
if (typeof image?.atlas !== 'string') return image;
|
||||
record.atlases.add(image.atlas);
|
||||
return atlases.get(image.atlas)?.[image.slot];
|
||||
}
|
||||
|
||||
function buildIcons(record) {
|
||||
const host = new Cesium.BillboardCollection({ scene });
|
||||
record.atlases = new Set();
|
||||
for (const item of record.items.values()) {
|
||||
const image = iconImage(record, item.image);
|
||||
if (image === undefined) continue;
|
||||
// A generated image is one texture under its key, however many icons
|
||||
// draw it.
|
||||
const keyed = image?.canvas && typeof image.key === 'string';
|
||||
const position = toCartesian(item.pos);
|
||||
const options = {
|
||||
position,
|
||||
...(keyed ? {} : { image: toImage(image) }),
|
||||
width: item.size[0] * (item.scale ?? 1),
|
||||
height: item.size[1] * (item.scale ?? 1),
|
||||
color: toColor(item.color, item.alpha ?? 1),
|
||||
verticalOrigin: ANCHORS[item.anchor ?? 'center'],
|
||||
disableDepthTestDistance: item.disableDepthTest ?? 0,
|
||||
show: item.show !== false,
|
||||
id: pickId(record, item),
|
||||
};
|
||||
if (item.rotationMode === 'screen') options.rotation = item.rotation ?? 0;
|
||||
if (item.rotationMode === 'course') {
|
||||
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(position);
|
||||
options.alignedAxis = Cesium.Matrix4.multiplyByPointAsVector(
|
||||
enu,
|
||||
Cesium.Cartesian3.UNIT_Y,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
options.rotation = -Cesium.Math.toRadians(item.course ?? 0);
|
||||
}
|
||||
const billboard = host.add(options);
|
||||
if (keyed) billboard.setImage(image.key, image.canvas);
|
||||
}
|
||||
replaceHost(record, host);
|
||||
}
|
||||
|
||||
function buildPoints(record) {
|
||||
const host = new Cesium.PointPrimitiveCollection();
|
||||
for (const item of record.items.values())
|
||||
host.add({
|
||||
position: toCartesian(item.pos),
|
||||
pixelSize: item.pixelSize,
|
||||
color: toColor(item.color),
|
||||
outlineColor: toColor(item.outlineColor ?? [0, 0, 0, 0]),
|
||||
outlineWidth: item.outlineWidth ?? 0,
|
||||
disableDepthTestDistance: item.disableDepthTest ?? 0,
|
||||
show: item.show !== false,
|
||||
id: pickId(record, item),
|
||||
});
|
||||
replaceHost(record, host);
|
||||
}
|
||||
|
||||
function lineMaterial(style) {
|
||||
switch (style.kind) {
|
||||
case 'solid':
|
||||
return Cesium.Material.fromType('Color', {
|
||||
color: toColor(style.color),
|
||||
});
|
||||
case 'glow':
|
||||
return Cesium.Material.fromType('PolylineGlow', {
|
||||
color: toColor(style.color),
|
||||
glowPower: style.power,
|
||||
taperPower: style.taper ?? 1,
|
||||
});
|
||||
case 'dash':
|
||||
return Cesium.Material.fromType('PolylineDash', {
|
||||
color: toColor(style.color),
|
||||
gapColor: toColor(style.gapColor ?? [0, 0, 0, 0]),
|
||||
dashLength: style.length,
|
||||
...(style.pattern16 !== undefined
|
||||
? { dashPattern: style.pattern16 }
|
||||
: {}),
|
||||
});
|
||||
case 'arrow':
|
||||
return Cesium.Material.fromType('PolylineArrow', {
|
||||
color: toColor(style.color),
|
||||
});
|
||||
default:
|
||||
throw new Error(`the Cesium renderer has no ${style.kind} lines`);
|
||||
}
|
||||
}
|
||||
|
||||
function linePositions(item) {
|
||||
const flat = item.positions instanceof Float64Array;
|
||||
const points = [];
|
||||
const n = flat ? item.positions.length / 3 : item.positions.length;
|
||||
for (let i = 0; i < n; i++)
|
||||
points.push(
|
||||
flat
|
||||
? new Cesium.Cartesian3(
|
||||
item.positions[i * 3],
|
||||
item.positions[i * 3 + 1],
|
||||
item.positions[i * 3 + 2],
|
||||
)
|
||||
: toCartesian(item.positions[i]),
|
||||
);
|
||||
if (item.mode !== 'geodesic') return points;
|
||||
const dense = [];
|
||||
for (let i = 0; i + 1 < points.length; i++) {
|
||||
const a = Cesium.Cartographic.fromCartesian(points[i]);
|
||||
const b = Cesium.Cartographic.fromCartesian(points[i + 1]);
|
||||
const geodesic = new Cesium.EllipsoidGeodesic(a, b);
|
||||
for (let k = 0; k < 64; k++) {
|
||||
const s = k / 64;
|
||||
const at = geodesic.interpolateUsingFraction(s);
|
||||
dense.push(
|
||||
Cesium.Cartesian3.fromRadians(
|
||||
at.longitude,
|
||||
at.latitude,
|
||||
a.height + (b.height - a.height) * s,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
dense.push(points.at(-1));
|
||||
return dense;
|
||||
}
|
||||
|
||||
function buildLines(record) {
|
||||
const host = new Cesium.PolylineCollection();
|
||||
for (const item of record.items.values()) {
|
||||
if (item.mode === 'draped')
|
||||
throw new Error('the Cesium renderer has no draped lines');
|
||||
host.add({
|
||||
positions: linePositions(item),
|
||||
width: item.widthPx,
|
||||
material: lineMaterial(item.style),
|
||||
show: item.show !== false,
|
||||
id: pickId(record, item),
|
||||
});
|
||||
}
|
||||
replaceHost(record, host);
|
||||
}
|
||||
|
||||
const heightOf = (pos) =>
|
||||
'x' in pos
|
||||
? Cesium.Cartographic.fromCartesian(toCartesian(pos)).height
|
||||
: (pos.height ?? 0);
|
||||
|
||||
function shapeGeometry(item) {
|
||||
const g = item.geometry;
|
||||
const extrudedHeight = item.extrudeHeight;
|
||||
switch (g.kind) {
|
||||
case 'polygon': {
|
||||
const [outer, ...holes] = g.rings.map((ring) => ring.map(toCartesian));
|
||||
const hierarchy = new Cesium.PolygonHierarchy(
|
||||
outer,
|
||||
holes.map((h) => new Cesium.PolygonHierarchy(h)),
|
||||
);
|
||||
return {
|
||||
fill: new Cesium.PolygonGeometry({
|
||||
polygonHierarchy: hierarchy,
|
||||
height: g.perPositionHeight ? undefined : heightOf(g.rings[0][0]),
|
||||
extrudedHeight,
|
||||
perPositionHeight: g.perPositionHeight,
|
||||
}),
|
||||
ring: outer,
|
||||
};
|
||||
}
|
||||
case 'ellipse':
|
||||
return {
|
||||
fill: new Cesium.EllipseGeometry({
|
||||
center: toCartesian(g.center),
|
||||
semiMajorAxis: g.semiMajor,
|
||||
semiMinorAxis: g.semiMinor,
|
||||
rotation: g.rotation ?? 0,
|
||||
height: heightOf(g.center),
|
||||
extrudedHeight,
|
||||
}),
|
||||
};
|
||||
case 'rectangle':
|
||||
return {
|
||||
fill: new Cesium.RectangleGeometry({
|
||||
rectangle: Cesium.Rectangle.fromDegrees(
|
||||
g.rect.west,
|
||||
g.rect.south,
|
||||
g.rect.east,
|
||||
g.rect.north,
|
||||
),
|
||||
height: g.height ?? 0,
|
||||
extrudedHeight,
|
||||
}),
|
||||
};
|
||||
case 'box': {
|
||||
const d = g.dimensions;
|
||||
return {
|
||||
fill: Cesium.BoxGeometry.fromDimensions({
|
||||
dimensions: new Cesium.Cartesian3(d.x, d.y, d.z),
|
||||
}),
|
||||
modelMatrix: Cesium.Transforms.eastNorthUpToFixedFrame(
|
||||
toCartesian(g.center),
|
||||
),
|
||||
};
|
||||
}
|
||||
default:
|
||||
throw new Error(`the Cesium renderer has no ${g.kind} shapes`);
|
||||
}
|
||||
}
|
||||
|
||||
function buildShapes(record) {
|
||||
const host = new Cesium.PrimitiveCollection();
|
||||
const outlines = new Cesium.PolylineCollection();
|
||||
for (const item of record.items.values()) {
|
||||
if (item.show === false) continue;
|
||||
if (
|
||||
item.fill &&
|
||||
typeof item.fill === 'object' &&
|
||||
!Array.isArray(item.fill)
|
||||
)
|
||||
throw new Error('the Cesium renderer fills shapes with colours only');
|
||||
const shape = shapeGeometry(item);
|
||||
const id = pickId(record, item);
|
||||
const solid =
|
||||
item.extrudeHeight !== undefined || item.geometry.kind === 'box';
|
||||
if (item.fill && !item.outlineOnly) {
|
||||
const color = toColor(item.fill);
|
||||
host.add(
|
||||
new Cesium.Primitive({
|
||||
geometryInstances: new Cesium.GeometryInstance({
|
||||
geometry: shape.fill,
|
||||
modelMatrix: shape.modelMatrix,
|
||||
attributes: {
|
||||
color: Cesium.ColorGeometryInstanceAttribute.fromColor(color),
|
||||
},
|
||||
id,
|
||||
}),
|
||||
appearance: new Cesium.PerInstanceColorAppearance({
|
||||
translucent: color.alpha < 1,
|
||||
closed: solid,
|
||||
// Flat shapes unlit: lit, their two triangles shade apart.
|
||||
flat: !solid,
|
||||
}),
|
||||
asynchronous: false,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (item.outline && shape.ring)
|
||||
outlines.add({
|
||||
positions: [...shape.ring, shape.ring[0]],
|
||||
width: item.outlineWidth ?? 1,
|
||||
material: Cesium.Material.fromType('Color', {
|
||||
color: toColor(item.outline),
|
||||
}),
|
||||
id,
|
||||
});
|
||||
}
|
||||
host.add(outlines);
|
||||
replaceHost(record, host);
|
||||
}
|
||||
|
||||
function buildModels(record) {
|
||||
const host = new Cesium.PrimitiveCollection();
|
||||
replaceHost(record, host);
|
||||
// A model counts as loading until it is ready or fails, not when added;
|
||||
// each model settles once, and a failure is kept for `whenSettled`.
|
||||
host.loading = record.items.size;
|
||||
host.failed = 0;
|
||||
for (const item of record.items.values()) {
|
||||
let settled = false;
|
||||
const settle = (failed) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
host.loading -= 1;
|
||||
if (failed) host.failed += 1;
|
||||
scene.requestRender();
|
||||
};
|
||||
const o = item.orientation;
|
||||
const modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(
|
||||
toCartesian(item.pos),
|
||||
new Cesium.HeadingPitchRoll(o.heading, o.pitch, o.roll),
|
||||
);
|
||||
Cesium.Model.fromGltfAsync({
|
||||
url: item.url,
|
||||
modelMatrix,
|
||||
scale: item.scale ?? 1,
|
||||
minimumPixelSize: item.minPixelSize ?? 0,
|
||||
// All textures before ready, so a settled capture is the whole model.
|
||||
incrementallyLoadTextures: false,
|
||||
id: pickId(record, item),
|
||||
}).then(
|
||||
(model) => {
|
||||
// Rebuilt, disposed, or the renderer is gone.
|
||||
if (record.host !== host || host.isDestroyed())
|
||||
return model.destroy();
|
||||
host.add(model);
|
||||
model.readyEvent.addEventListener(() => {
|
||||
settle(false);
|
||||
record.listeners.ready.fire(item.id);
|
||||
});
|
||||
model.errorEvent.addEventListener(() => settle(true));
|
||||
scene.requestRender();
|
||||
},
|
||||
() => settle(true),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** The 3D tilesets in the scene, shown or not. */
|
||||
function tilesets() {
|
||||
const found = [];
|
||||
const primitives = scene.primitives;
|
||||
const n = primitives?.length ?? 0;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const primitive = primitives.get(i);
|
||||
if (primitive instanceof Cesium.Cesium3DTileset) found.push(primitive);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Cesium port draws clamped items where it is given them; it does not
|
||||
* drape them onto 3D tiles yet, so over shown tiles it is `overlay`.
|
||||
* Terrain and the ellipsoid always take draped items.
|
||||
*/
|
||||
const clampState = () =>
|
||||
tilesets().some((tileset) => tileset.show) ? 'overlay' : 'draped';
|
||||
const clampListeners = listenerList(report);
|
||||
// The state last told, while anyone listens; measured after each drawn
|
||||
// frame, when what the base holds can have changed.
|
||||
let toldClamp = null;
|
||||
function watchClamp() {
|
||||
if (clampListeners.size === 0) return;
|
||||
const state = clampState();
|
||||
if (state === toldClamp) return;
|
||||
toldClamp = state;
|
||||
clampListeners.fire(state);
|
||||
}
|
||||
|
||||
const draw = {
|
||||
icons: (spec) => makeSet('icons', { ...spec }, buildIcons),
|
||||
points: (spec) => makeSet('points', { ...spec }, buildPoints),
|
||||
lines: (spec) => makeSet('lines', { ...spec }, buildLines),
|
||||
shapes: (spec) => makeSet('shapes', { ...spec }, buildShapes),
|
||||
models: (spec) => makeSet('models', { ...spec }, buildModels),
|
||||
clampState,
|
||||
on(event, cb) {
|
||||
if (event !== 'clampState') return () => {};
|
||||
if (clampListeners.size === 0) toldClamp = clampState();
|
||||
return clampListeners.on(cb);
|
||||
},
|
||||
atlas(id, images) {
|
||||
atlases.set(id, { ...images });
|
||||
let rebuilt = false;
|
||||
for (const record of [...sets.values()])
|
||||
if (record.kind === 'icons' && record.atlases?.has(id)) {
|
||||
record.rebuild();
|
||||
rebuilt = true;
|
||||
}
|
||||
if (rebuilt) scene.requestRender();
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
port: draw,
|
||||
sets,
|
||||
version: () => setsVersion,
|
||||
tilesets,
|
||||
watchClamp,
|
||||
/**
|
||||
* Let go of the sets; with `removeHosts`, take what they draw out of
|
||||
* the scene too (a scene the port does not own outlives it).
|
||||
*/
|
||||
dispose({ removeHosts = false } = {}) {
|
||||
clampListeners.clear();
|
||||
// Late model loads find no host and destroy themselves.
|
||||
for (const record of sets.values()) {
|
||||
if (removeHosts && record.host && !scene.isDestroyed?.())
|
||||
scene.primitives.remove(record.host);
|
||||
record.host = null;
|
||||
}
|
||||
sets.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// A Cesium viewer with no renderer bound to it gets a
|
||||
// draw port over its scene when code first asks `findDraw` for one. A
|
||||
// renderer bound later supersedes it: released, its sets keep drawing until
|
||||
// their owners dispose them; gone with the viewer, it lets them go.
|
||||
provideUnboundDraw((viewer) => {
|
||||
const scene = viewer.scene;
|
||||
// By shape, not `instanceof`: the viewer may come from another
|
||||
// copy of Cesium.
|
||||
if (
|
||||
typeof scene?.primitives?.add !== 'function' ||
|
||||
typeof scene.postRender?.addEventListener !== 'function' ||
|
||||
typeof scene.requestRender !== 'function'
|
||||
)
|
||||
return null;
|
||||
const part = createCesiumDraw({ scene, report: uncaught });
|
||||
const off = scene.postRender.addEventListener(() => part.watchClamp());
|
||||
return {
|
||||
port: part.port,
|
||||
dispose() {
|
||||
off();
|
||||
part.dispose({ removeHosts: true });
|
||||
},
|
||||
release() {
|
||||
off();
|
||||
},
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import test from 'node:test';
|
||||
import { bindRenderer, drawOf, findDraw } from '../rendererOf.js';
|
||||
import './draw.js';
|
||||
|
||||
/** A scene with what the draw port touches: primitives and its events. */
|
||||
function fakeScene() {
|
||||
const added = [];
|
||||
const postRender = new Cesium.Event();
|
||||
const preRender = new Cesium.Event();
|
||||
return {
|
||||
added,
|
||||
postRender,
|
||||
preRender,
|
||||
camera: { positionWC: new Cesium.Cartesian3(2e7, 0, 0) },
|
||||
primitives: {
|
||||
add: (primitive) => (added.push(primitive), primitive),
|
||||
remove: (primitive) => {
|
||||
const at = added.indexOf(primitive);
|
||||
if (at >= 0) added.splice(at, 1);
|
||||
return at >= 0;
|
||||
},
|
||||
length: 0,
|
||||
},
|
||||
destroyed: false,
|
||||
requestRender() {
|
||||
if (this.destroyed) throw new Error('This object was destroyed');
|
||||
},
|
||||
isDestroyed() {
|
||||
return this.destroyed;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('a viewer of its own, with no renderer bound, draws through a built port', () => {
|
||||
const scene = fakeScene();
|
||||
const viewer = { scene, isDestroyed: () => destroyed };
|
||||
let destroyed = false;
|
||||
const draw = drawOf(viewer);
|
||||
assert.equal(findDraw(viewer), draw, 'one per viewer');
|
||||
const set = draw.points({ id: 'mine' });
|
||||
set.set([{ id: 'a', pos: { lon: 0, lat: 0 }, pixelSize: 4, color: '#fff' }]);
|
||||
assert.equal(scene.added.length, 1, 'drawn into the viewer’s scene');
|
||||
assert.equal(scene.added[0].get(0).id.set, 'mine');
|
||||
|
||||
// A renderer bound later answers new callers; the sets keep drawing.
|
||||
const unbind = bindRenderer(viewer, { draw: { id: 'renderer' } });
|
||||
assert.equal(findDraw(viewer).id, 'renderer');
|
||||
assert.equal(scene.added.length, 1);
|
||||
set.dispose();
|
||||
assert.equal(scene.added.length, 0);
|
||||
unbind();
|
||||
|
||||
// Gone with its viewer, a built port lets go; a set its layer disposes
|
||||
// after that has nothing left to do.
|
||||
const again = drawOf(viewer);
|
||||
assert.notEqual(again, draw);
|
||||
const late = again.points({ id: 'left' });
|
||||
late.set([]);
|
||||
destroyed = true;
|
||||
scene.destroyed = true;
|
||||
assert.equal(findDraw(viewer), null);
|
||||
late.dispose();
|
||||
});
|
||||
|
||||
test('nothing to draw into, no port', () => {
|
||||
assert.equal(findDraw({ scene: {} }), null);
|
||||
assert.throws(() => drawOf({}), /no renderer to draw with/);
|
||||
});
|
||||
+7
-488
@@ -17,6 +17,7 @@ import { heightsFor } from '../../queries/heights.js';
|
||||
import { createCesiumCamera } from './camera.js';
|
||||
import { listenerList, toCartesian, uncaught } from './common.js';
|
||||
import { createCesiumCredits } from './credits.js';
|
||||
import { createCesiumDraw } from './draw.js';
|
||||
import { createCesiumEffects } from './effects.js';
|
||||
import { createCesiumGlobe } from './globe.js';
|
||||
import { createCesiumQuality } from './quality.js';
|
||||
@@ -31,32 +32,7 @@ import {
|
||||
} from './internals.js';
|
||||
|
||||
export { listenerList, toCartesian };
|
||||
|
||||
/** The contract's colour as Cesium's. */
|
||||
export function toColor(color, alpha = 1) {
|
||||
if (color === undefined || color === null)
|
||||
return Cesium.Color.WHITE.withAlpha(alpha);
|
||||
const c =
|
||||
typeof color === 'string'
|
||||
? Cesium.Color.fromCssColorString(color)
|
||||
: new Cesium.Color(color[0], color[1], color[2], color[3] ?? 1);
|
||||
return c.withAlpha(c.alpha * alpha);
|
||||
}
|
||||
|
||||
/** An image reference as something a billboard takes. */
|
||||
export function toImage(image) {
|
||||
if (typeof image === 'string') return image;
|
||||
if (image?.svg)
|
||||
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(image.svg)}`;
|
||||
if (image?.canvas) return image.canvas;
|
||||
throw new Error('the Cesium renderer takes URL, SVG and canvas images only');
|
||||
}
|
||||
|
||||
const ANCHORS = {
|
||||
center: Cesium.VerticalOrigin.CENTER,
|
||||
bottom: Cesium.VerticalOrigin.BOTTOM,
|
||||
top: Cesium.VerticalOrigin.TOP,
|
||||
};
|
||||
export { toColor, toImage } from './draw.js';
|
||||
|
||||
const scratchPosition0 = new Cesium.Cartesian3();
|
||||
const scratchPosition1 = new Cesium.Cartesian3();
|
||||
@@ -145,7 +121,6 @@ export function cesiumCapabilities(scene, only) {
|
||||
export function createCesiumPorts(widget, { capabilities, credentials = {} }) {
|
||||
const scene = widget.scene;
|
||||
const camera = scene.camera;
|
||||
const sets = new Map();
|
||||
|
||||
// An error listener's own throw is uncaught, never reported again.
|
||||
const rendererListeners = {
|
||||
@@ -380,460 +355,8 @@ export function createCesiumPorts(widget, { capabilities, credentials = {} }) {
|
||||
|
||||
// --- Draw ------------------------------------------------------------------
|
||||
|
||||
function makeSet(kind, spec, build) {
|
||||
if (sets.has(spec.id)) throw new Error(`a set with id ${spec.id} is live`);
|
||||
const items = new Map();
|
||||
const listeners = { ready: listenerList(report) };
|
||||
const record = { kind, spec, items, listeners, host: null, pickIds: [] };
|
||||
// Each build records its items' pick ids, for height queries to see
|
||||
// through.
|
||||
const rebuild = () => {
|
||||
record.pickIds = [];
|
||||
build(record);
|
||||
setsVersion += 1;
|
||||
};
|
||||
record.rebuild = rebuild;
|
||||
const handle = {
|
||||
id: spec.id,
|
||||
set(list) {
|
||||
items.clear();
|
||||
for (const item of list) items.set(item.id, item);
|
||||
rebuild();
|
||||
scene.requestRender();
|
||||
},
|
||||
upsert(list) {
|
||||
for (const item of list) items.set(item.id, item);
|
||||
rebuild();
|
||||
scene.requestRender();
|
||||
},
|
||||
remove(ids) {
|
||||
for (const id of ids) items.delete(id);
|
||||
rebuild();
|
||||
scene.requestRender();
|
||||
},
|
||||
clear() {
|
||||
items.clear();
|
||||
rebuild();
|
||||
scene.requestRender();
|
||||
},
|
||||
setOptions(options) {
|
||||
Object.assign(spec, options);
|
||||
setsVersion += 1;
|
||||
if (record.host) record.host.show = spec.show !== false;
|
||||
scene.requestRender();
|
||||
},
|
||||
size: () => items.size,
|
||||
get show() {
|
||||
return spec.show !== false;
|
||||
},
|
||||
set show(value) {
|
||||
spec.show = value;
|
||||
if (record.host) record.host.show = value;
|
||||
scene.requestRender();
|
||||
},
|
||||
on(event, cb) {
|
||||
return listeners[event]?.on(cb) ?? (() => {});
|
||||
},
|
||||
dispose() {
|
||||
if (record.host && !record.host.isDestroyed?.())
|
||||
scene.primitives.remove(record.host);
|
||||
record.host = null;
|
||||
// A newer set under the same id is not this handle's to remove.
|
||||
if (sets.get(spec.id) === record) sets.delete(spec.id);
|
||||
setsVersion += 1;
|
||||
scene.requestRender();
|
||||
},
|
||||
};
|
||||
sets.set(spec.id, record);
|
||||
setsVersion += 1;
|
||||
return handle;
|
||||
}
|
||||
|
||||
function pickId(record, item) {
|
||||
const id = {
|
||||
set: record.spec.id,
|
||||
id: item.id,
|
||||
meta: item.meta,
|
||||
lodGroup: item.lodGroup,
|
||||
};
|
||||
record.pickIds.push(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
function replaceHost(record, host) {
|
||||
if (record.host) scene.primitives.remove(record.host);
|
||||
record.host = host;
|
||||
host.show = record.spec.show !== false;
|
||||
scene.primitives.add(host);
|
||||
}
|
||||
|
||||
// Atlases icons name images from, by id: `{atlas, slot}` reads the slot
|
||||
// when its set is built, and registering an atlas again rebuilds the icon
|
||||
// sets that drew from it.
|
||||
const atlases = new Map();
|
||||
|
||||
/**
|
||||
* An icon's image: an atlas slot read through its atlas, or undefined
|
||||
* while its atlas or slot is not registered (it draws once it is).
|
||||
*/
|
||||
function iconImage(record, image) {
|
||||
if (typeof image?.atlas !== 'string') return image;
|
||||
record.atlases.add(image.atlas);
|
||||
return atlases.get(image.atlas)?.[image.slot];
|
||||
}
|
||||
|
||||
function buildIcons(record) {
|
||||
const host = new Cesium.BillboardCollection({ scene });
|
||||
record.atlases = new Set();
|
||||
for (const item of record.items.values()) {
|
||||
const image = iconImage(record, item.image);
|
||||
if (image === undefined) continue;
|
||||
// A generated image is one texture under its key, however many icons
|
||||
// draw it.
|
||||
const keyed = image?.canvas && typeof image.key === 'string';
|
||||
const position = toCartesian(item.pos);
|
||||
const options = {
|
||||
position,
|
||||
...(keyed ? {} : { image: toImage(image) }),
|
||||
width: item.size[0] * (item.scale ?? 1),
|
||||
height: item.size[1] * (item.scale ?? 1),
|
||||
color: toColor(item.color, item.alpha ?? 1),
|
||||
verticalOrigin: ANCHORS[item.anchor ?? 'center'],
|
||||
disableDepthTestDistance: item.disableDepthTest ?? 0,
|
||||
show: item.show !== false,
|
||||
id: pickId(record, item),
|
||||
};
|
||||
if (item.rotationMode === 'screen') options.rotation = item.rotation ?? 0;
|
||||
if (item.rotationMode === 'course') {
|
||||
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(position);
|
||||
options.alignedAxis = Cesium.Matrix4.multiplyByPointAsVector(
|
||||
enu,
|
||||
Cesium.Cartesian3.UNIT_Y,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
options.rotation = -Cesium.Math.toRadians(item.course ?? 0);
|
||||
}
|
||||
const billboard = host.add(options);
|
||||
if (keyed) billboard.setImage(image.key, image.canvas);
|
||||
}
|
||||
replaceHost(record, host);
|
||||
}
|
||||
|
||||
function buildPoints(record) {
|
||||
const host = new Cesium.PointPrimitiveCollection();
|
||||
for (const item of record.items.values())
|
||||
host.add({
|
||||
position: toCartesian(item.pos),
|
||||
pixelSize: item.pixelSize,
|
||||
color: toColor(item.color),
|
||||
outlineColor: toColor(item.outlineColor ?? [0, 0, 0, 0]),
|
||||
outlineWidth: item.outlineWidth ?? 0,
|
||||
disableDepthTestDistance: item.disableDepthTest ?? 0,
|
||||
show: item.show !== false,
|
||||
id: pickId(record, item),
|
||||
});
|
||||
replaceHost(record, host);
|
||||
}
|
||||
|
||||
function lineMaterial(style) {
|
||||
switch (style.kind) {
|
||||
case 'solid':
|
||||
return Cesium.Material.fromType('Color', {
|
||||
color: toColor(style.color),
|
||||
});
|
||||
case 'glow':
|
||||
return Cesium.Material.fromType('PolylineGlow', {
|
||||
color: toColor(style.color),
|
||||
glowPower: style.power,
|
||||
taperPower: style.taper ?? 1,
|
||||
});
|
||||
case 'dash':
|
||||
return Cesium.Material.fromType('PolylineDash', {
|
||||
color: toColor(style.color),
|
||||
gapColor: toColor(style.gapColor ?? [0, 0, 0, 0]),
|
||||
dashLength: style.length,
|
||||
...(style.pattern16 !== undefined
|
||||
? { dashPattern: style.pattern16 }
|
||||
: {}),
|
||||
});
|
||||
case 'arrow':
|
||||
return Cesium.Material.fromType('PolylineArrow', {
|
||||
color: toColor(style.color),
|
||||
});
|
||||
default:
|
||||
throw new Error(`the Cesium renderer has no ${style.kind} lines`);
|
||||
}
|
||||
}
|
||||
|
||||
function linePositions(item) {
|
||||
const flat = item.positions instanceof Float64Array;
|
||||
const points = [];
|
||||
const n = flat ? item.positions.length / 3 : item.positions.length;
|
||||
for (let i = 0; i < n; i++)
|
||||
points.push(
|
||||
flat
|
||||
? new Cesium.Cartesian3(
|
||||
item.positions[i * 3],
|
||||
item.positions[i * 3 + 1],
|
||||
item.positions[i * 3 + 2],
|
||||
)
|
||||
: toCartesian(item.positions[i]),
|
||||
);
|
||||
if (item.mode !== 'geodesic') return points;
|
||||
const dense = [];
|
||||
for (let i = 0; i + 1 < points.length; i++) {
|
||||
const a = Cesium.Cartographic.fromCartesian(points[i]);
|
||||
const b = Cesium.Cartographic.fromCartesian(points[i + 1]);
|
||||
const geodesic = new Cesium.EllipsoidGeodesic(a, b);
|
||||
for (let k = 0; k < 64; k++) {
|
||||
const s = k / 64;
|
||||
const at = geodesic.interpolateUsingFraction(s);
|
||||
dense.push(
|
||||
Cesium.Cartesian3.fromRadians(
|
||||
at.longitude,
|
||||
at.latitude,
|
||||
a.height + (b.height - a.height) * s,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
dense.push(points.at(-1));
|
||||
return dense;
|
||||
}
|
||||
|
||||
function buildLines(record) {
|
||||
const host = new Cesium.PolylineCollection();
|
||||
for (const item of record.items.values()) {
|
||||
if (item.mode === 'draped')
|
||||
throw new Error('the Cesium renderer has no draped lines');
|
||||
host.add({
|
||||
positions: linePositions(item),
|
||||
width: item.widthPx,
|
||||
material: lineMaterial(item.style),
|
||||
show: item.show !== false,
|
||||
id: pickId(record, item),
|
||||
});
|
||||
}
|
||||
replaceHost(record, host);
|
||||
}
|
||||
|
||||
const heightOf = (pos) =>
|
||||
'x' in pos
|
||||
? Cesium.Cartographic.fromCartesian(toCartesian(pos)).height
|
||||
: (pos.height ?? 0);
|
||||
|
||||
function shapeGeometry(item) {
|
||||
const g = item.geometry;
|
||||
const extrudedHeight = item.extrudeHeight;
|
||||
switch (g.kind) {
|
||||
case 'polygon': {
|
||||
const [outer, ...holes] = g.rings.map((ring) => ring.map(toCartesian));
|
||||
const hierarchy = new Cesium.PolygonHierarchy(
|
||||
outer,
|
||||
holes.map((h) => new Cesium.PolygonHierarchy(h)),
|
||||
);
|
||||
return {
|
||||
fill: new Cesium.PolygonGeometry({
|
||||
polygonHierarchy: hierarchy,
|
||||
height: g.perPositionHeight ? undefined : heightOf(g.rings[0][0]),
|
||||
extrudedHeight,
|
||||
perPositionHeight: g.perPositionHeight,
|
||||
}),
|
||||
ring: outer,
|
||||
};
|
||||
}
|
||||
case 'ellipse':
|
||||
return {
|
||||
fill: new Cesium.EllipseGeometry({
|
||||
center: toCartesian(g.center),
|
||||
semiMajorAxis: g.semiMajor,
|
||||
semiMinorAxis: g.semiMinor,
|
||||
rotation: g.rotation ?? 0,
|
||||
height: heightOf(g.center),
|
||||
extrudedHeight,
|
||||
}),
|
||||
};
|
||||
case 'rectangle':
|
||||
return {
|
||||
fill: new Cesium.RectangleGeometry({
|
||||
rectangle: Cesium.Rectangle.fromDegrees(
|
||||
g.rect.west,
|
||||
g.rect.south,
|
||||
g.rect.east,
|
||||
g.rect.north,
|
||||
),
|
||||
height: g.height ?? 0,
|
||||
extrudedHeight,
|
||||
}),
|
||||
};
|
||||
case 'box': {
|
||||
const d = g.dimensions;
|
||||
return {
|
||||
fill: Cesium.BoxGeometry.fromDimensions({
|
||||
dimensions: new Cesium.Cartesian3(d.x, d.y, d.z),
|
||||
}),
|
||||
modelMatrix: Cesium.Transforms.eastNorthUpToFixedFrame(
|
||||
toCartesian(g.center),
|
||||
),
|
||||
};
|
||||
}
|
||||
default:
|
||||
throw new Error(`the Cesium renderer has no ${g.kind} shapes`);
|
||||
}
|
||||
}
|
||||
|
||||
function buildShapes(record) {
|
||||
const host = new Cesium.PrimitiveCollection();
|
||||
const outlines = new Cesium.PolylineCollection();
|
||||
for (const item of record.items.values()) {
|
||||
if (item.show === false) continue;
|
||||
if (
|
||||
item.fill &&
|
||||
typeof item.fill === 'object' &&
|
||||
!Array.isArray(item.fill)
|
||||
)
|
||||
throw new Error('the Cesium renderer fills shapes with colours only');
|
||||
const shape = shapeGeometry(item);
|
||||
const id = pickId(record, item);
|
||||
const solid =
|
||||
item.extrudeHeight !== undefined || item.geometry.kind === 'box';
|
||||
if (item.fill && !item.outlineOnly) {
|
||||
const color = toColor(item.fill);
|
||||
host.add(
|
||||
new Cesium.Primitive({
|
||||
geometryInstances: new Cesium.GeometryInstance({
|
||||
geometry: shape.fill,
|
||||
modelMatrix: shape.modelMatrix,
|
||||
attributes: {
|
||||
color: Cesium.ColorGeometryInstanceAttribute.fromColor(color),
|
||||
},
|
||||
id,
|
||||
}),
|
||||
appearance: new Cesium.PerInstanceColorAppearance({
|
||||
translucent: color.alpha < 1,
|
||||
closed: solid,
|
||||
// Flat shapes unlit: lit, their two triangles shade apart.
|
||||
flat: !solid,
|
||||
}),
|
||||
asynchronous: false,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (item.outline && shape.ring)
|
||||
outlines.add({
|
||||
positions: [...shape.ring, shape.ring[0]],
|
||||
width: item.outlineWidth ?? 1,
|
||||
material: Cesium.Material.fromType('Color', {
|
||||
color: toColor(item.outline),
|
||||
}),
|
||||
id,
|
||||
});
|
||||
}
|
||||
host.add(outlines);
|
||||
replaceHost(record, host);
|
||||
}
|
||||
|
||||
function buildModels(record) {
|
||||
const host = new Cesium.PrimitiveCollection();
|
||||
replaceHost(record, host);
|
||||
// A model counts as loading until it is ready or fails, not when added;
|
||||
// each model settles once, and a failure is kept for `whenSettled`.
|
||||
host.loading = record.items.size;
|
||||
host.failed = 0;
|
||||
for (const item of record.items.values()) {
|
||||
let settled = false;
|
||||
const settle = (failed) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
host.loading -= 1;
|
||||
if (failed) host.failed += 1;
|
||||
scene.requestRender();
|
||||
};
|
||||
const o = item.orientation;
|
||||
const modelMatrix = Cesium.Transforms.headingPitchRollToFixedFrame(
|
||||
toCartesian(item.pos),
|
||||
new Cesium.HeadingPitchRoll(o.heading, o.pitch, o.roll),
|
||||
);
|
||||
Cesium.Model.fromGltfAsync({
|
||||
url: item.url,
|
||||
modelMatrix,
|
||||
scale: item.scale ?? 1,
|
||||
minimumPixelSize: item.minPixelSize ?? 0,
|
||||
// All textures before ready, so a settled capture is the whole model.
|
||||
incrementallyLoadTextures: false,
|
||||
id: pickId(record, item),
|
||||
}).then(
|
||||
(model) => {
|
||||
// Rebuilt, disposed, or the renderer is gone.
|
||||
if (record.host !== host || host.isDestroyed())
|
||||
return model.destroy();
|
||||
host.add(model);
|
||||
model.readyEvent.addEventListener(() => {
|
||||
settle(false);
|
||||
record.listeners.ready.fire(item.id);
|
||||
});
|
||||
model.errorEvent.addEventListener(() => settle(true));
|
||||
scene.requestRender();
|
||||
},
|
||||
() => settle(true),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** The 3D tilesets in the scene, shown or not. */
|
||||
function tilesets() {
|
||||
const found = [];
|
||||
const primitives = scene.primitives;
|
||||
const n = primitives?.length ?? 0;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const primitive = primitives.get(i);
|
||||
if (primitive instanceof Cesium.Cesium3DTileset) found.push(primitive);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Cesium port draws clamped items where it is given them; it does not
|
||||
* drape them onto 3D tiles yet, so over shown tiles it is `overlay`.
|
||||
* Terrain and the ellipsoid always take draped items.
|
||||
*/
|
||||
const clampState = () =>
|
||||
tilesets().some((tileset) => tileset.show) ? 'overlay' : 'draped';
|
||||
const clampListeners = listenerList(report);
|
||||
// The state last told, while anyone listens; measured after each drawn
|
||||
// frame, when what the base holds can have changed.
|
||||
let toldClamp = null;
|
||||
function watchClamp() {
|
||||
if (clampListeners.size === 0) return;
|
||||
const state = clampState();
|
||||
if (state === toldClamp) return;
|
||||
toldClamp = state;
|
||||
clampListeners.fire(state);
|
||||
}
|
||||
|
||||
const draw = {
|
||||
icons: (spec) => makeSet('icons', { ...spec }, buildIcons),
|
||||
points: (spec) => makeSet('points', { ...spec }, buildPoints),
|
||||
lines: (spec) => makeSet('lines', { ...spec }, buildLines),
|
||||
shapes: (spec) => makeSet('shapes', { ...spec }, buildShapes),
|
||||
models: (spec) => makeSet('models', { ...spec }, buildModels),
|
||||
clampState,
|
||||
on(event, cb) {
|
||||
if (event !== 'clampState') return () => {};
|
||||
if (clampListeners.size === 0) toldClamp = clampState();
|
||||
return clampListeners.on(cb);
|
||||
},
|
||||
atlas(id, images) {
|
||||
atlases.set(id, { ...images });
|
||||
let rebuilt = false;
|
||||
for (const record of [...sets.values()])
|
||||
if (record.kind === 'icons' && record.atlases?.has(id)) {
|
||||
record.rebuild();
|
||||
rebuilt = true;
|
||||
}
|
||||
if (rebuilt) scene.requestRender();
|
||||
},
|
||||
};
|
||||
const drawPart = createCesiumDraw({ scene, report });
|
||||
const { port: draw, sets, tilesets, watchClamp } = drawPart;
|
||||
|
||||
const cameraPart = createCesiumCamera({ scene, camera, report, widget });
|
||||
const cameraPort = cameraPart.port;
|
||||
@@ -937,13 +460,12 @@ export function createCesiumPorts(widget, { capabilities, credentials = {} }) {
|
||||
// What height queries see through, by their items' pick ids: the sets not
|
||||
// drawn as ground, and the sets a caller excludes. Built once per change
|
||||
// to the sets, not per query.
|
||||
let setsVersion = 0;
|
||||
const seeThroughCache = new Map();
|
||||
let seeThroughVersion = -1;
|
||||
function seeThrough(exclude, { allSets = false } = {}) {
|
||||
if (seeThroughVersion !== setsVersion) {
|
||||
if (seeThroughVersion !== drawPart.version()) {
|
||||
seeThroughCache.clear();
|
||||
seeThroughVersion = setsVersion;
|
||||
seeThroughVersion = drawPart.version();
|
||||
}
|
||||
const key = `${allSets}\u0000${exclude?.join('\u0000') ?? ''}`;
|
||||
let out = seeThroughCache.get(key);
|
||||
@@ -1438,16 +960,13 @@ export function createCesiumPorts(widget, { capabilities, credentials = {} }) {
|
||||
// A listener that disposes the renderer stops the rest of its event.
|
||||
for (const list of Object.values(rendererListeners)) list.clear();
|
||||
for (const list of Object.values(frameListeners)) list.clear();
|
||||
clampListeners.clear();
|
||||
drawPart.dispose();
|
||||
cameraPart.dispose();
|
||||
creditsPart.dispose();
|
||||
effectsPart.dispose();
|
||||
globePart.dispose();
|
||||
qualityPart.dispose();
|
||||
for (const done of [...pendingRenders]) done();
|
||||
// Late model loads find no host and destroy themselves.
|
||||
for (const record of sets.values()) record.host = null;
|
||||
sets.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -63,6 +63,8 @@ const unboundEffects = unboundPorts('effects');
|
||||
const unboundGlobes = unboundPorts('globe');
|
||||
/** Credits ports are `{port, dispose, release}`: see `bindRenderer`. */
|
||||
const unboundCredits = unboundPorts('credits');
|
||||
/** Draw ports are `{port, dispose, release}`, as credits ports are. */
|
||||
const unboundDraws = unboundPorts('draw');
|
||||
|
||||
/**
|
||||
* Provide the factory `cameraOf` builds a camera port with for a scene
|
||||
@@ -85,6 +87,18 @@ export function provideUnboundCredits(build) {
|
||||
unboundCredits.provide(build);
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide the factory `findDraw` builds a draw port with for a scene object
|
||||
* no renderer is bound to, as `provideUnboundCredits` does: a bound
|
||||
* renderer releases it, and the sets made through it keep drawing until
|
||||
* their owners dispose them.
|
||||
* @param {(host: object) => ({port: object, dispose: () => void,
|
||||
* release: () => void} | null)} build
|
||||
*/
|
||||
export function provideUnboundDraw(build) {
|
||||
unboundDraws.provide(build);
|
||||
}
|
||||
|
||||
/**
|
||||
* Provide the factory `findEffects` builds an effects port with for a
|
||||
* scene object no renderer is bound to, as `provideUnboundCamera` does.
|
||||
@@ -123,7 +137,8 @@ export function releaseUnboundEffects(host, port) {
|
||||
* A credits port `findCredits` built is released, not disposed: the
|
||||
* credits added through it stay shown until their own Off. A globe port
|
||||
* `findGlobe` built is released too: its imagery stays drawn, following the
|
||||
* base, until its callers remove it.
|
||||
* base, until its callers remove it. So is a draw port `findDraw` built: its
|
||||
* sets keep drawing until disposed.
|
||||
* @param {object} host The scene object callers hold.
|
||||
* @param {object} renderer
|
||||
* @returns {() => void} Unbinds, if the binding is still this one.
|
||||
@@ -135,6 +150,7 @@ export function bindRenderer(host, renderer) {
|
||||
unboundEffects.drop(host);
|
||||
unboundGlobes.supersede(host);
|
||||
unboundCredits.supersede(host);
|
||||
unboundDraws.supersede(host);
|
||||
renderers.set(host, renderer);
|
||||
return () => {
|
||||
if (renderers.get(host) === renderer) renderers.delete(host);
|
||||
@@ -196,6 +212,47 @@ export function findCredits(host) {
|
||||
return unboundCredits.find(host);
|
||||
}
|
||||
|
||||
/**
|
||||
* The draw port of the renderer bound to `host`; with no renderer bound,
|
||||
* one built over `host` by the provided factory and kept with it while
|
||||
* `host` lives, as `findCamera` does.
|
||||
*
|
||||
* This is how a layer that is handed the scene object (a viewer) draws:
|
||||
* it asks once, as it starts (`init`), and keeps the sets it makes; it
|
||||
* reaches the camera through `cameraOf` the same way. A layer whose
|
||||
* package is exported must tell a caller whose viewer has no renderer and
|
||||
* no adapter factory loaded that it cannot draw, rather than do nothing
|
||||
* (`drawOf`).
|
||||
*
|
||||
* A port built for a viewer with no renderer is released when a renderer
|
||||
* is bound to it later: the sets already made through it keep drawing
|
||||
* until disposed, but the renderer's own ports (its picks, height queries,
|
||||
* `whenSettled`) do not see them. Bind the renderer before anything draws.
|
||||
* @param {object|null|undefined} host
|
||||
* @returns {import('./contract/draw').DrawPort | null}
|
||||
*/
|
||||
export function findDraw(host) {
|
||||
return unboundDraws.find(host);
|
||||
}
|
||||
|
||||
/**
|
||||
* `findDraw`, for code that cannot start without one.
|
||||
* @param {object} host
|
||||
* @returns {import('./contract/draw').DrawPort}
|
||||
* @throws When there is no draw port for `host`.
|
||||
*/
|
||||
export function drawOf(host) {
|
||||
const draw = findDraw(host);
|
||||
if (draw) return draw;
|
||||
throw new Error(
|
||||
host?.isDestroyed?.()
|
||||
? 'This scene has been destroyed'
|
||||
: 'This scene has no renderer to draw with: bind one, or load the ' +
|
||||
"Cesium adapter's draw port (render/cesium/draw.js) for a viewer " +
|
||||
'with no renderer bound',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `findCamera`, for code that needs the camera.
|
||||
* @param {object} host
|
||||
|
||||
@@ -3,11 +3,14 @@ import test from 'node:test';
|
||||
import {
|
||||
bindRenderer,
|
||||
cameraOf,
|
||||
drawOf,
|
||||
findCamera,
|
||||
findCredits,
|
||||
findDraw,
|
||||
findEffects,
|
||||
provideUnboundCamera,
|
||||
provideUnboundCredits,
|
||||
provideUnboundDraw,
|
||||
provideUnboundEffects,
|
||||
rendererOf,
|
||||
} from './rendererOf.js';
|
||||
@@ -165,3 +168,36 @@ test('with no renderer bound, findEffects builds one effects port per scene unti
|
||||
assert.equal(findEffects(gone), null);
|
||||
assert.equal(built[2].disposed, 1, 'let go with its scene');
|
||||
});
|
||||
|
||||
test('with no renderer bound, findDraw builds one draw port per scene; a renderer releases it', (t) => {
|
||||
t.after(() => provideUnboundDraw(null));
|
||||
const built = [];
|
||||
provideUnboundDraw((host) => {
|
||||
if (!host.scene) return null;
|
||||
const entry = { port: { id: built.length }, disposed: 0, released: 0 };
|
||||
entry.dispose = () => (entry.disposed += 1);
|
||||
entry.release = () => (entry.released += 1);
|
||||
built.push(entry);
|
||||
return entry;
|
||||
});
|
||||
const viewer = { scene: {} };
|
||||
assert.equal(findDraw(viewer), built[0].port);
|
||||
assert.equal(drawOf(viewer), built[0].port, 'kept, not rebuilt');
|
||||
assert.equal(findDraw({}), null, 'nothing to build over');
|
||||
assert.throws(() => drawOf({}), /no renderer to draw with/);
|
||||
assert.equal(findDraw(null), null);
|
||||
|
||||
const draw = { icons() {} };
|
||||
const unbind = bindRenderer(viewer, { draw });
|
||||
assert.equal(drawOf(viewer), draw);
|
||||
assert.equal(built[0].disposed, 0, 'its sets keep drawing until disposed');
|
||||
assert.equal(built[0].released, 1);
|
||||
unbind();
|
||||
|
||||
let destroyed = false;
|
||||
const gone = { scene: {}, isDestroyed: () => destroyed };
|
||||
const port = findDraw(gone);
|
||||
destroyed = true;
|
||||
assert.throws(() => drawOf(gone), /destroyed/);
|
||||
assert.equal(built.find((entry) => entry.port === port).disposed, 1);
|
||||
});
|
||||
@@ -8,6 +8,10 @@
|
||||
* Likewise an entry that reaches a caller of `findEffects` must load
|
||||
* `render/cesium/effects.js`, which provides the effects factory, and one
|
||||
* that reaches a caller of `findGlobe` must load `render/cesium/globe.js`.
|
||||
* An entry that reaches a caller of `findDraw` or `drawOf` loads
|
||||
* `render/cesium/draw.js` the same way, unless it is Cesium-free: then it
|
||||
* is listed in `DRAW_FROM_CALLER`, and a caller handing it a viewer of
|
||||
* their own loads the package's `./render/cesium/draw` export once.
|
||||
*
|
||||
* The graph is every static import, re-export and literal dynamic import of
|
||||
* the entry's module and those it reaches, read by the parsers the Cesium
|
||||
@@ -29,6 +33,7 @@ const BRIDGE = 'src/render/rendererOf.js';
|
||||
const FACTORY = 'src/render/cesium/camera.js';
|
||||
const EFFECTS_FACTORY = 'src/render/cesium/effects.js';
|
||||
const GLOBE_FACTORY = 'src/render/cesium/globe.js';
|
||||
const DRAW_FACTORY = 'src/render/cesium/draw.js';
|
||||
|
||||
/**
|
||||
* Entries that take their Cesium code injected: the module named here is
|
||||
@@ -49,6 +54,14 @@ const INJECTED = {
|
||||
*/
|
||||
const FALLS_BACK = new Set(['src/data/followed.js']);
|
||||
|
||||
/**
|
||||
* Cesium-free entries that draw through `drawOf`: their own modules cannot
|
||||
* load the Cesium adapter (the Cesium ratchet), so a viewer with no
|
||||
* renderer bound draws once its owner has loaded `./render/cesium/draw`;
|
||||
* until then `drawOf` throws, naming it, rather than draw nothing.
|
||||
*/
|
||||
const DRAW_FROM_CALLER = new Set([]);
|
||||
|
||||
const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
|
||||
|
||||
/** The browser module an export resolves to, or null for Node-only ones. */
|
||||
@@ -206,3 +219,34 @@ test('every public entry that reaches a findGlobe caller loads the unbound globe
|
||||
// Only the application reaches one today, through no public entry.
|
||||
checkLookupFactory('findGlobe', GLOBE_FACTORY, { reached: false });
|
||||
});
|
||||
|
||||
test('every public entry that reaches a findDraw caller loads the unbound draw factory, or its caller can', () => {
|
||||
const missing = [];
|
||||
const callsFindDraw = (file) =>
|
||||
!file.startsWith('src/render/') &&
|
||||
/\.(m?js|vue)$/.test(file) &&
|
||||
/\b(findDraw|drawOf)\(/.test(readFileSync(path.join(root, file), 'utf8'));
|
||||
assert.equal(
|
||||
pkg.exports['./render/cesium/draw'],
|
||||
`./${DRAW_FACTORY}`,
|
||||
'the factory loads through this export',
|
||||
);
|
||||
for (const [key, declaration] of Object.entries(pkg.exports)) {
|
||||
const target = browserTarget(declaration);
|
||||
if (typeof target !== 'string' || !target.startsWith('./src/')) continue;
|
||||
const entry = path.normalize(target.slice(2));
|
||||
if (![...reachable(entry)].some(callsFindDraw)) continue;
|
||||
const carrier = INJECTED[key];
|
||||
const loads = (file) => reachable(file, { eager: true }).has(DRAW_FACTORY);
|
||||
if (DRAW_FROM_CALLER.has(key)) {
|
||||
assert.ok(!loads(entry), `${key} loads the factory: unlist it`);
|
||||
continue;
|
||||
}
|
||||
if (!loads(entry) && !(carrier && loads(carrier))) missing.push(key);
|
||||
}
|
||||
assert.deepEqual(
|
||||
missing,
|
||||
[],
|
||||
`These entries can reach findDraw without ${DRAW_FACTORY}; import it, or list a Cesium-free entry in DRAW_FROM_CALLER.`,
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user