Add ground fills to the globe contract

engine.ground draws sets of polygons (with holes), discs, cells and
corridors draped on the surface, with fill and outline colours, order and
picks, written in bulk and committed. Every engine implements it:

- Cesium batches each set into one GroundPrimitive for fills and one
  GroundPolylinePrimitive for outlines and pixel corridors, classified
  against terrain and 3D tiles; sets that are not pickable stay out of the
  pick pass.
- Navara draws them in one screen pass after tone mapping that finds each
  pixel's ground from the scene depth and tests the items in its screen
  cell; long rings are split into edge bins. Measured at Dubai against
  SDK vector layers, the pass matched Cesium's frame time up to 10,000
  polygons with a few megabytes instead of 70 to 146, drew exact colours
  and outlines, and hid reliably across an engine switch, where vector
  layers hidden with update({ show: false }) never hid. Dense corridors
  remain its limit (10,000 cost 135 ms a frame).
- The fake engine keeps the same registry and CPU picks.

The contract suite checks it on both engines (Cesium 66/66, Navara 69/69).
Earthquakes and fire perimeters have unwired ground prototypes whose
drawing matches today's Cesium one (0.998 on Cesium, 0.976 on Navara).
docs/GLOBE-PRIMITIVES.md describes the primitives and when to use each.
This commit is contained in:
German Khokhlov committed 2026-11-07 05:14:42 +04:00
1 parent 6dc643182e
commit 974a0b6361
27 files changed
+5256 -685

No files matched your search

+14 -4
View File
@@ -5,12 +5,13 @@
// engine clock's frame latch on viewer.clock.onTick (clock.js), attached at
// creation so it runs before onTick listeners added later. Mover sets and
// lines join the scene in one engine-owned collection each, with the first
// set or line.
// set or line; ground sets join scene.groundPrimitives the same way.
import { createCesiumCamera } from './camera.js';
import { createCesiumClock } from './clock.js';
import { createCesiumCredits } from './credits.js';
import { createCesiumFrames } from './frames.js';
import { createCesiumGround } from './ground.js';
import { createCesiumInput } from './input.js';
import { createCesiumLines } from './lines.js';
import { createCesiumMaps } from './maps.js';
@@ -31,9 +32,10 @@ import { createCesiumSurface } from './surface.js';
* appClock?: import('../../time/clock.js').AppClock,
* moverFactories?: object,
* lineFactories?: object,
* groundFactories?: object,
* }} [options] `requestRender` defaults to the render governor; `appClock`
* to the page's app clock; the `create*`/`load*` options and the mover and
* line factories (movers.js, lines.js) are test seams.
* line and ground factories (movers.js, lines.js, ground.js) are test seams.
*
* `render.setContinuous` takes a hold on the app's singleton renderGovernor
* (src/renderGovernor.js), which governs the one viewer it was installed on;
@@ -54,9 +56,16 @@ export function createCesiumEngine(viewer, options = {}) {
requestRender,
...(options.lineFactories ? { factories: options.lineFactories } : {}),
});
// Picks name the mover set or line they hit, with its pickId.
const ground = createCesiumGround(viewer, {
requestRender,
...(options.groundFactories ? { factories: options.groundFactories } : {}),
});
// Picks name the mover set, line or ground set they hit, with its pickId.
const picker = createCesiumPicker(viewer, {
identify: (picked) => movers.identify(picked) ?? lines.identify(picked),
identify: (picked) =>
movers.identify(picked) ??
lines.identify(picked) ??
ground.identify(picked),
});
const parts = {
camera: createCesiumCamera(viewer),
@@ -66,6 +75,7 @@ export function createCesiumEngine(viewer, options = {}) {
clock: createCesiumClock(viewer, options),
movers,
lines,
ground,
render,
// Mover sets in a surface `exclude` are hidden for the sample.
surface: createCesiumSurface(viewer, {
+294
View File
@@ -0,0 +1,294 @@
// engine.ground on Cesium: each set is a PrimitiveCollection placed by
// `order` inside one engine-owned collection in scene.groundPrimitives
// (added with the first set), so a rebuild keeps its place. A commit
// rebuilds the set as at most two batches: one GroundPrimitive of every
// fill (polygons, discs as EllipseGeometry, cells as RectangleGeometry,
// metre corridors as CorridorGeometry) and one GroundPolylinePrimitive of
// every outline and pixel corridor, over the fills, both with per-instance
// colours and the set's classificationType. Cesium builds them in workers;
// the engine keeps requesting frames until they are drawn. A set made
// without pickable stays out of the pick pass (a GroundPrimitive with
// allowPicking false still writes its stencil there and hides what lies
// under it); identify() names a picked item.
import * as Cesium from 'cesium';
import { areaRings, createGroundRegistry } from '../ground.js';
// Read when a set is made: no module reads Cesium while it loads.
const classificationOf = (drape) =>
({
both: Cesium.ClassificationType.BOTH,
terrain: Cesium.ClassificationType.TERRAIN,
tiles: Cesium.ClassificationType.CESIUM_3D_TILE,
})[drape];
// Outline rings of a disc, in Cesium's own ellipse granularity (1°, at
// least 64 points round).
const DISC_OUTLINE_SEGMENTS = 128;
// Cesium's GroundPrimitive and GroundPolylinePrimitive, out of the pick pass
// unless asked to pick.
function pickPassAware(Base) {
return class extends Base {
constructor(options) {
super(options);
this.gevPickable = options.allowPicking === true;
}
update(frameState) {
if (frameState.passes.pick && !this.gevPickable) return;
super.update(frameState);
}
};
}
// Made on first use: no module reads Cesium while it loads.
let groundClasses = null;
const classes = () =>
(groundClasses ??= {
fills: pickPassAware(Cesium.GroundPrimitive),
lines: pickPassAware(Cesium.GroundPolylinePrimitive),
});
const DEFAULT_FACTORIES = {
fills: (options) => new (classes().fills)(options),
lines: (options) => new (classes().lines)(options),
};
const colorOf = (rgba) => new Cesium.Color(rgba[0], rgba[1], rgba[2], rgba[3]);
function positionsOf(flat) {
const positions = [];
for (let index = 0; index < flat.length; index += 2)
positions.push(Cesium.Cartesian3.fromDegrees(flat[index], flat[index + 1]));
return positions;
}
const longitude = (degrees) => degrees - 360 * Math.round(degrees / 360);
/** The fill geometry of one item of a set of `kind` (pure, for tests). */
export function fillGeometry(kind, item) {
const vertexFormat = Cesium.PerInstanceColorAppearance.FLAT_VERTEX_FORMAT;
if (kind === 'disc')
return new Cesium.EllipseGeometry({
center: Cesium.Cartesian3.fromDegrees(item.center[0], item.center[1]),
semiMajorAxis: item.radiusM,
semiMinorAxis: item.radiusM,
vertexFormat,
});
if (kind === 'cell') {
const { west, south, east, north } = item.bounds;
return new Cesium.RectangleGeometry({
rectangle: Cesium.Rectangle.fromDegrees(
longitude(west),
south,
longitude(east),
north,
),
vertexFormat,
});
}
if (kind === 'corridor')
return new Cesium.CorridorGeometry({
positions: positionsOf(item.path),
width: item.widthM,
vertexFormat,
});
const [outer, ...holes] = item.rings.map(positionsOf);
return new Cesium.PolygonGeometry({
polygonHierarchy: new Cesium.PolygonHierarchy(
outer,
holes.map((hole) => new Cesium.PolygonHierarchy(hole)),
),
vertexFormat,
});
}
/**
* The geometry instances of a commit: `fills` for the GroundPrimitive,
* `lines` for the GroundPolylinePrimitive. Instance ids name the set and
* item ({ gevGroundSet, instance }).
*/
export function groundInstances(options, items) {
const fills = [];
const lines = [];
items.forEach((item, instance) => {
const id = { gevGroundSet: options.id, instance };
const attributes = (rgba) => ({
color: Cesium.ColorGeometryInstanceAttribute.fromColor(colorOf(rgba)),
});
if (options.kind === 'corridor') {
if (item.widthM)
fills.push(
new Cesium.GeometryInstance({
geometry: fillGeometry('corridor', item),
id,
attributes: attributes(item.fill),
}),
);
else
lines.push(
new Cesium.GeometryInstance({
geometry: new Cesium.GroundPolylineGeometry({
positions: positionsOf(item.path),
width: item.widthPx,
}),
id,
attributes: attributes(item.fill),
}),
);
return;
}
if (item.fill)
fills.push(
new Cesium.GeometryInstance({
geometry: fillGeometry(options.kind, item),
id,
attributes: attributes(item.fill),
}),
);
if (item.outline)
for (const ring of areaRings(options.kind, item, {
discSegments: DISC_OUTLINE_SEGMENTS,
}))
lines.push(
new Cesium.GeometryInstance({
geometry: new Cesium.GroundPolylineGeometry({
positions: positionsOf(ring),
width: item.outline.widthPx,
loop: true,
}),
id,
attributes: attributes(item.outline.color),
}),
);
});
return { fills, lines };
}
/**
* @param {Cesium.Viewer} viewer
* @param {{ requestRender?: (reason: string) => void, factories?: object }} [options]
* `factories` (the fill and line primitives) is a test seam.
* @returns {{ ground: import('../contract.js').GlobeGround,
* identify: (picked: object) => ({ owner: string, instance: number, id: any, pickable: boolean } | null),
* destroy: () => void }}
*/
export function createCesiumGround(
viewer,
{ requestRender = () => viewer.scene.requestRender(), factories = {} } = {},
) {
const make = { ...DEFAULT_FACTORIES, ...factories };
const { scene } = viewer;
let root = null;
const ordered = [];
const building = new Set();
let removeWatch = null;
// Frames until every committed primitive has been built and drawn.
const watch = () => {
if (removeWatch || !scene.postRender) return;
removeWatch = scene.postRender.addEventListener(() => {
for (const primitive of building)
if (primitive.ready || primitive.isDestroyed?.())
building.delete(primitive);
if (building.size) requestRender('ground-build');
else {
removeWatch();
removeWatch = null;
requestRender('ground-ready');
}
});
};
const rootCollection = () => {
if (!root) {
root = new Cesium.PrimitiveCollection({ destroyPrimitives: true });
scene.groundPrimitives.add(root);
}
return root;
};
const registry = createGroundRegistry((options) => {
const slot = new Cesium.PrimitiveCollection({ destroyPrimitives: true });
const at = ordered.filter((entry) => entry.order <= options.order).length;
ordered.splice(at, 0, { order: options.order, slot });
rootCollection().add(slot, at);
let drawn = [];
const classificationType = classificationOf(options.drape);
const allowPicking = options.pickable;
return {
commit(items) {
for (const primitive of drawn) building.delete(primitive);
slot.removeAll();
drawn = [];
const { fills, lines } = groundInstances(options, items);
if (fills.length)
drawn.push(
make.fills({
geometryInstances: fills,
appearance: new Cesium.PerInstanceColorAppearance({
flat: true,
translucent: true,
}),
classificationType,
allowPicking,
}),
);
if (lines.length)
drawn.push(
make.lines({
geometryInstances: lines,
appearance: new Cesium.PolylineColorAppearance(),
classificationType,
allowPicking,
}),
);
for (const primitive of drawn) {
primitive.gevGroundSet = options.id;
slot.add(primitive);
building.add(primitive);
}
watch();
requestRender('ground');
},
show(visible) {
slot.show = visible;
requestRender('ground');
},
ready: () => drawn.every((primitive) => primitive.ready === true),
destroy() {
for (const primitive of drawn) building.delete(primitive);
drawn = [];
ordered.splice(
ordered.findIndex((entry) => entry.slot === slot),
1,
);
root.remove(slot);
requestRender('ground');
},
};
});
return {
ground: registry.ground,
/** The live ground item a Cesium pick names, with its pickId, or null. */
identify(picked) {
const owner = picked?.id?.gevGroundSet;
const state = owner === undefined ? null : registry.live.get(owner);
if (!state) return null;
const { instance } = picked.id;
const pickId = state.items[instance]?.pickId;
return {
owner,
instance,
id: pickId,
pickable: state.options.pickable && pickId !== undefined,
};
},
destroy() {
registry.destroyAll();
removeWatch?.();
removeWatch = null;
building.clear();
if (root) {
scene.groundPrimitives.remove(root);
root = null;
}
},
};
}
+159
View File
@@ -0,0 +1,159 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { normalizeGroundItem } from '../ground.js';
import { createCesiumGround, groundInstances } from './ground.js';
import { createFakeViewer } from './testing/fakeViewer.mjs';
const items = (kind, list) =>
list.map((item, index) => normalizeGroundItem(kind, item, index));
test('fills batch into GroundPrimitive instances, outlines into ground polylines', () => {
const options = { id: 'zones', kind: 'polygon' };
const { fills, lines } = groundInstances(
options,
items('polygon', [
{
rings: [
[
[0, 0],
[1, 0],
[1, 1],
],
[
[0.6, 0.2],
[0.8, 0.2],
[0.8, 0.4],
],
],
fill: [1, 0, 0, 0.5],
outline: { color: [1, 1, 1, 1], widthPx: 2 },
},
{
rings: [
[
[2, 0],
[3, 0],
[3, 1],
],
],
outline: { color: [0, 0, 1, 1], widthPx: 3 },
},
]),
);
assert.equal(fills.length, 1, 'an item without a fill adds none');
assert.ok(fills[0].geometry instanceof Cesium.PolygonGeometry);
assert.deepEqual(fills[0].id, { gevGroundSet: 'zones', instance: 0 });
assert.equal(lines.length, 3, 'one outline per ring');
assert.ok(lines[0].geometry instanceof Cesium.GroundPolylineGeometry);
assert.equal(lines[0].geometry.loop, true);
assert.equal(lines[0].geometry.width, 2);
assert.deepEqual(lines[2].id, { gevGroundSet: 'zones', instance: 1 });
const corridors = groundInstances(
{ id: 'roads', kind: 'corridor' },
items('corridor', [
{
positions: [
[0, 0],
[1, 0],
],
color: [1, 1, 1, 1],
widthPx: 4,
},
{
positions: [
[0, 1],
[1, 1],
],
color: [1, 1, 1, 1],
widthM: 30,
},
]),
);
assert.ok(corridors.fills[0].geometry instanceof Cesium.CorridorGeometry);
assert.equal(corridors.lines[0].geometry.width, 4);
const shapes = groundInstances(
{ id: 'shapes', kind: 'disc' },
items('disc', [{ center: [0, 0], radiusM: 500, fill: [1, 1, 1, 1] }]),
);
assert.ok(shapes.fills[0].geometry instanceof Cesium.EllipseGeometry);
});
test('sets join scene.groundPrimitives in order and rebuild on commit', () => {
const viewer = createFakeViewer();
const added = [];
viewer.scene.groundPrimitives = {
add: (value) => added.push(value),
remove: (value) => added.splice(added.indexOf(value), 1),
};
const made = [];
const fake = (type) => (options) => {
const primitive = {
type,
options,
ready: false,
destroy() {},
isDestroyed: () => false,
};
made.push(primitive);
return primitive;
};
const renders = [];
const part = createCesiumGround(viewer, {
requestRender: (reason) => renders.push(reason),
factories: { fills: fake('fills'), lines: fake('lines') },
});
const high = part.ground.createSet({ id: 'high', kind: 'cell', order: 2 });
const low = part.ground.createSet({
id: 'low',
kind: 'cell',
pickable: true,
drape: 'tiles',
});
assert.equal(added.length, 1, 'one engine collection');
const root = added[0];
low.replace([
{
west: 0,
south: 0,
east: 1,
north: 1,
fill: [1, 0, 0, 1],
outline: { color: [1, 1, 1, 1], widthPx: 2 },
pickId: 'cell-1',
},
]);
low.commit();
assert.equal(root.length, 2);
assert.equal(root.get(0).get(0), made[0], 'the lower order first');
assert.deepEqual(
made.map(({ type }) => type),
['fills', 'lines'],
);
const [fills] = made;
assert.equal(
fills.options.classificationType,
Cesium.ClassificationType.CESIUM_3D_TILE,
);
assert.equal(fills.options.allowPicking, true);
assert.equal(low.ready(), false, 'built in workers');
fills.ready = true;
made[1].ready = true;
assert.equal(low.ready(), true);
assert.deepEqual(
part.identify({ id: { gevGroundSet: 'low', instance: 0 } }),
{ owner: 'low', instance: 0, id: 'cell-1', pickable: true },
);
high.replace([
{ west: 0, south: 0, east: 1, north: 1, fill: [1, 1, 1, 1], pickId: 'x' },
]);
high.commit();
assert.equal(made.at(-1).options.allowPicking, false);
assert.equal(
part.identify({ id: { gevGroundSet: 'high', instance: 0 } }).pickable,
false,
);
assert.equal(part.identify({ id: 'entity' }), null);
part.destroy();
assert.equal(added.length, 0);
});