Draw moving icon sets on the GPU through the Cesium draw port

An icon set whose items move along motion segments, glide their course,
recede toward the limb, pick through a larger proxy or switch images by
drawn size, or that takes columns, now draws as one instanced
IconSetPrimitive in place of its billboards. The set switches the first time
an item needs it (or columns arrive) and stays switched; a course blend
alone switches it only when everything it holds can go. The Cesium ports
advertise columns, motionSegments and courseGlide.

GPU sets refuse loudly what billboards draw and they do not: clamped
heights, fadeByDistance, displayRange, offsets, anchors other than the
centre, axis and screen rotations, opaque and additive blends, images other
than URLs and SVG, and more images than the shared atlas has room for. A
refused write changes nothing.

The shared icon columns gain an image switch size, a pick proxy and a
per-row depth-test distance (defaulting to always over depth, as before),
arcs gain a climb rate, and the epoch rebases in both directions. Rows keep
asking for frames while they move, turn or blend; a write that moves a row
as it already moves (a restyle, a focus change) leaves its segment alone.
Billboard icons now fade with focus as GPU ones do.

Conformance gains columns and motion checks for the Cesium adapter.
This commit is contained in:
Sameh Khamis committed 2026-11-07 00:38:20 -08:00
1 parent f0427fc63e
commit bb85e0fa74
15 files changed
+1675 -39

No files matched your search

+130
View File
@@ -9,9 +9,17 @@
"src/data/infrastructure.js", "src/data/infrastructure.js",
"src/data/localGeojsonCore.js", "src/data/localGeojsonCore.js",
"src/render/cesium/camera.js", "src/render/cesium/camera.js",
"src/data/iconSetPrimitive.js",
"src/data/aircraftRecession.js",
"src/data/iconAtlas.js",
"src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js",
"src/data/motionModel.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
@@ -876,10 +884,18 @@
"src/ui/cockpitRollingValue.js", "src/ui/cockpitRollingValue.js",
"src/ui/cockpitCamera.js", "src/ui/cockpitCamera.js",
"src/render/cesium/camera.js", "src/render/cesium/camera.js",
"src/data/iconSetPrimitive.js",
"src/data/aircraftRecession.js",
"src/data/motionModel.js",
"src/data/iconAtlas.js",
"src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
@@ -1012,10 +1028,18 @@
"src/styles/thermal.js", "src/styles/thermal.js",
"src/ui/applicationShell.js", "src/ui/applicationShell.js",
"src/render/cesium/effects.js", "src/render/cesium/effects.js",
"src/data/iconSetPrimitive.js",
"src/data/aircraftRecession.js",
"src/data/motionModel.js",
"src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js",
"src/data/iconAtlas.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/data/followed.js", "src/data/followed.js",
"src/render/cesium/camera.js", "src/render/cesium/camera.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
@@ -1288,10 +1312,18 @@
"src/scenes/director.js", "src/scenes/director.js",
"src/data/followed.js", "src/data/followed.js",
"src/render/cesium/camera.js", "src/render/cesium/camera.js",
"src/data/iconSetPrimitive.js",
"src/data/aircraftRecession.js",
"src/data/motionModel.js",
"src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js",
"src/data/iconAtlas.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
@@ -1442,6 +1474,7 @@
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
@@ -1453,6 +1486,7 @@
"src/data/aircraftMotionRegime.js", "src/data/aircraftMotionRegime.js",
"src/data/iconSetPrimitive.js", "src/data/iconSetPrimitive.js",
"src/data/iconSet.js", "src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js", "src/data/iconSegment.js",
"src/data/iconAtlas.js", "src/data/iconAtlas.js",
"src/data/aircraftRecession.js", "src/data/aircraftRecession.js",
@@ -1541,6 +1575,7 @@
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
@@ -1553,6 +1588,7 @@
"src/data/aircraftMotionRegime.js", "src/data/aircraftMotionRegime.js",
"src/data/iconSetPrimitive.js", "src/data/iconSetPrimitive.js",
"src/data/iconSet.js", "src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js", "src/data/iconSegment.js",
"src/data/iconAtlas.js", "src/data/iconAtlas.js",
"src/data/aircraftRecession.js", "src/data/aircraftRecession.js",
@@ -1654,6 +1690,7 @@
"src/data/entityRecords.js", "src/data/entityRecords.js",
"src/data/iconSetPrimitive.js", "src/data/iconSetPrimitive.js",
"src/data/iconSet.js", "src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js", "src/data/iconSegment.js",
"src/data/iconAtlas.js", "src/data/iconAtlas.js",
"src/data/aircraftRecession.js", "src/data/aircraftRecession.js",
@@ -1699,6 +1736,7 @@
"src/queries/heights.js", "src/queries/heights.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/follow.js", "src/render/cesium/follow.js",
"src/render/cesium/cameraInput.js", "src/render/cesium/cameraInput.js",
@@ -1716,12 +1754,20 @@
"exports": ["./render/cesium/unbound"], "exports": ["./render/cesium/unbound"],
"modules": [ "modules": [
"src/render/cesium/unbound.js", "src/render/cesium/unbound.js",
"src/data/iconSetPrimitive.js",
"src/data/aircraftRecession.js",
"src/data/motionModel.js",
"src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js",
"src/data/iconAtlas.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/render/cesium/drawHit.js", "src/render/cesium/drawHit.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/effects.js", "src/render/cesium/effects.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/camera.js", "src/render/cesium/camera.js",
"src/render/camera/events.js", "src/render/camera/events.js",
"src/geo/index.js", "src/geo/index.js",
@@ -1805,6 +1851,7 @@
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/layers/firms/index.js", "src/layers/firms/index.js",
"src/layers/firms/ingestion.js", "src/layers/firms/ingestion.js",
"src/layers/firms/lifecycle.js", "src/layers/firms/lifecycle.js",
@@ -1818,6 +1865,7 @@
"src/data/entityRecords.js", "src/data/entityRecords.js",
"src/data/iconSetPrimitive.js", "src/data/iconSetPrimitive.js",
"src/data/iconSet.js", "src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js", "src/data/iconSegment.js",
"src/data/iconAtlas.js", "src/data/iconAtlas.js",
"src/data/aircraftRecession.js", "src/data/aircraftRecession.js",
@@ -1881,10 +1929,18 @@
"src/layers/satellites/testing.js", "src/layers/satellites/testing.js",
"src/layers/satellites/tracking.js", "src/layers/satellites/tracking.js",
"src/render/cesium/camera.js", "src/render/cesium/camera.js",
"src/data/iconSetPrimitive.js",
"src/data/aircraftRecession.js",
"src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js",
"src/data/motionModel.js",
"src/data/iconAtlas.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
@@ -1938,10 +1994,17 @@
"src/layers/launches/controls.js", "src/layers/launches/controls.js",
"src/layers/launches/index.js", "src/layers/launches/index.js",
"src/render/cesium/camera.js", "src/render/cesium/camera.js",
"src/data/iconSetPrimitive.js",
"src/data/aircraftRecession.js",
"src/data/motionModel.js",
"src/data/iconAtlas.js",
"src/data/iconSet.js",
"src/data/iconSegment.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
@@ -2013,10 +2076,17 @@
"src/layers/installations/controls.js", "src/layers/installations/controls.js",
"src/geo/geodesic.js", "src/geo/geodesic.js",
"src/render/cesium/camera.js", "src/render/cesium/camera.js",
"src/data/iconSetPrimitive.js",
"src/data/aircraftRecession.js",
"src/data/iconAtlas.js",
"src/data/motionModel.js",
"src/data/iconSet.js",
"src/data/iconSegment.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
@@ -2324,6 +2394,7 @@
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
@@ -2344,6 +2415,7 @@
"src/layers/cctv/rendering.js", "src/layers/cctv/rendering.js",
"src/data/iconSetPrimitive.js", "src/data/iconSetPrimitive.js",
"src/data/iconSet.js", "src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js", "src/data/iconSegment.js",
"src/data/iconAtlas.js", "src/data/iconAtlas.js",
"src/data/aircraftRecession.js", "src/data/aircraftRecession.js",
@@ -2395,9 +2467,17 @@
"modules": [ "modules": [
"src/layers/streetLevel/index.js", "src/layers/streetLevel/index.js",
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/data/iconSetPrimitive.js",
"src/data/aircraftRecession.js",
"src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js",
"src/data/motionModel.js",
"src/data/iconAtlas.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/geo/index.js", "src/geo/index.js",
"src/layers/streetLevel/credits.js", "src/layers/streetLevel/credits.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
@@ -2577,10 +2657,18 @@
"src/layers/radio/navigation.js", "src/layers/radio/navigation.js",
"src/data/followed.js", "src/data/followed.js",
"src/render/cesium/camera.js", "src/render/cesium/camera.js",
"src/data/iconSetPrimitive.js",
"src/data/aircraftRecession.js",
"src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js",
"src/data/motionModel.js",
"src/data/iconAtlas.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
@@ -2737,6 +2825,13 @@
"src/maps/catalog.js", "src/maps/catalog.js",
"src/maps/controller.js", "src/maps/controller.js",
"src/render/cesium/globe.js", "src/render/cesium/globe.js",
"src/data/iconSetPrimitive.js",
"src/data/aircraftRecession.js",
"src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js",
"src/data/motionModel.js",
"src/data/iconAtlas.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/queries/heights.js", "src/queries/heights.js",
@@ -2744,6 +2839,7 @@
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/cesium/tileRequests.js", "src/render/cesium/tileRequests.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/cameraInput.js", "src/render/cesium/cameraInput.js",
"src/render/cesium/camera.js", "src/render/cesium/camera.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
@@ -2960,6 +3056,7 @@
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
"src/render/rendererOf.js", "src/render/rendererOf.js",
"src/render/cesium/ports.js", "src/render/cesium/ports.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/render/cesium/globe.js", "src/render/cesium/globe.js",
"src/render/cesium/drawHit.js", "src/render/cesium/drawHit.js",
@@ -3956,6 +4053,7 @@
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/imagery.js", "src/render/cesium/imagery.js",
"src/maps/google3d.js", "src/maps/google3d.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
@@ -4616,10 +4714,18 @@
"src/layers/firms/anchors.js", "src/layers/firms/anchors.js",
"src/locations.js", "src/locations.js",
"src/render/cesium/camera.js", "src/render/cesium/camera.js",
"src/data/iconSetPrimitive.js",
"src/data/aircraftRecession.js",
"src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js",
"src/data/motionModel.js",
"src/data/iconAtlas.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/render/cesium/drawHit.js", "src/render/cesium/drawHit.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
"src/render/cesium/cameraInput.js", "src/render/cesium/cameraInput.js",
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
@@ -4730,11 +4836,19 @@
"src/geo/index.js", "src/geo/index.js",
"src/ui/navigationController.js", "src/ui/navigationController.js",
"src/render/cesium/camera.js", "src/render/cesium/camera.js",
"src/data/iconSetPrimitive.js",
"src/data/aircraftRecession.js",
"src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js",
"src/data/motionModel.js",
"src/data/iconAtlas.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/drawHit.js", "src/render/cesium/drawHit.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
"src/render/cesium/cameraInput.js", "src/render/cesium/cameraInput.js",
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
@@ -5267,9 +5381,17 @@
"src/cyberSonar.js", "src/cyberSonar.js",
"src/celestialRing.js", "src/celestialRing.js",
"src/render/cesium/camera.js", "src/render/cesium/camera.js",
"src/data/iconSetPrimitive.js",
"src/data/aircraftRecession.js",
"src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js",
"src/data/motionModel.js",
"src/data/iconAtlas.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
@@ -5391,6 +5513,13 @@
"src/layers/transit/viewport.js", "src/layers/transit/viewport.js",
"src/geo/rectangle.js", "src/geo/rectangle.js",
"src/render/rendererOf.js", "src/render/rendererOf.js",
"src/data/iconSetPrimitive.js",
"src/data/aircraftRecession.js",
"src/data/iconSet.js",
"src/geo/horizon.js",
"src/data/iconSegment.js",
"src/data/motionModel.js",
"src/data/iconAtlas.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/camera.js", "src/render/cesium/camera.js",
@@ -5401,6 +5530,7 @@
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/gpuIcons.js",
"src/data/cameraSensitivity.js", "src/data/cameraSensitivity.js",
"src/data/contactPlayback.js", "src/data/contactPlayback.js",
"src/data/contactTrailRenderer.js", "src/data/contactTrailRenderer.js",
+10
View File
@@ -54,11 +54,21 @@ function createAtlas() {
return slot; return slot;
}, },
/** Whether `url` at `sizePx` already has a slot. */
has(url, sizePx) {
return slotOfKey.has(`${sizePx}|${url}`);
},
/** Whether a slot's image is packed and drawable. */ /** Whether a slot's image is packed and drawable. */
ready(slot) { ready(slot) {
return atlas.rects[slot * 4 + 2] > 0; return atlas.rects[slot * 4 + 2] > 0;
}, },
/** Whether a slot's image failed to load, or had no room to pack. */
failed(slot) {
return entries[slot]?.failed === true;
},
/** /**
* Call `listener` after every repack, so the renderer, drawing on demand, * Call `listener` after every repack, so the renderer, drawing on demand,
* can ask for the frame that shows a newly loaded image. * can ask for the frame that shows a newly loaded image.
+23 -4
View File
@@ -9,7 +9,8 @@
* - lerp: straight from `base` to `base + U` between two fix times (the interpolation * - lerp: straight from `base` to `base + U` between two fix times (the interpolation
* between two known fixes), course affine in the fraction; * between two known fixes), course affine in the fraction;
* - arc: a constant-rate turn from a fix in its east/north plane (`U`, `V`), with the * - arc: a constant-rate turn from a fix in its east/north plane (`U`, `V`), with the
* elapsed time clamped (warm-up before the first fix, coast after the last). * elapsed time clamped (warm-up before the first fix, coast after the last),
* climbing along the fix's up axis (`U × V`) at a constant rate.
* *
* The arc uses `cos a − cos(a+b) = 2 sin(b/2) sin(a+b/2)`, so its offset is * The arc uses `cos a − cos(a+b) = 2 sin(b/2) sin(a+b/2)`, so its offset is
* `v·t·sinc(ωt/2)·(sin, cos)(a + ωt/2)`: no cancellation in float32 and no branch * `v·t·sinc(ωt/2)·(sin, cos)(a + ωt/2)`: no cancellation in float32 and no branch
@@ -43,6 +44,7 @@ const TRACK = 17; // rad, clockwise from north
const OMEGA = 18; // rad/s const OMEGA = 18; // rad/s
const COURSE0 = 19; // deg const COURSE0 = 19; // deg
const COURSE_SLOPE = 20; // lerp: deg per unit fraction const COURSE_SLOPE = 20; // lerp: deg per unit fraction
const CLIMB = 20; // arc: m/s along the fix's up axis (U × V)
const SLEW_OFFSET = 21; // deg still to glide at SLEW_T0 const SLEW_OFFSET = 21; // deg still to glide at SLEW_T0
const SLEW_T0 = 22; // s const SLEW_T0 = 22; // s
const SLEW_RATE = 23; // deg/s; negative holds the course at the glide's start const SLEW_RATE = 23; // deg/s; negative holds the course at the glide's start
@@ -107,11 +109,13 @@ export function writeLerpSegment(out, row, segment) {
/** /**
* Turn at a constant rate from `fix` (at `t0`) in its east/north plane, with the * Turn at a constant rate from `fix` (at `t0`) in its east/north plane, with the
* elapsed time clamped to `[minDt, maxDt]`. * elapsed time clamped to `[minDt, maxDt]`, climbing along the fix's up axis at
* `climbMps` (default 0).
* @param {Float32Array} out * @param {Float32Array} out
* @param {number} row * @param {number} row
* @param {{fix: Cesium.Cartesian3, t0: number, minDt: number, maxDt: number, * @param {{fix: Cesium.Cartesian3, t0: number, minDt: number, maxDt: number,
* speedMps: number, trackDeg: number, turnRateDps: number}} segment * speedMps: number, trackDeg: number, turnRateDps: number,
* climbMps?: number}} segment
*/ */
export function writeArcSegment(out, row, segment) { export function writeArcSegment(out, row, segment) {
const o = row * SEGMENT_STRIDE; const o = row * SEGMENT_STRIDE;
@@ -135,6 +139,7 @@ export function writeArcSegment(out, row, segment) {
out[o + TRACK] = (segment.trackDeg || 0) * DEG; out[o + TRACK] = (segment.trackDeg || 0) * DEG;
out[o + OMEGA] = Math.abs(omega) < STRAIGHT_BELOW_RAD_PER_SEC ? 0 : omega; out[o + OMEGA] = Math.abs(omega) < STRAIGHT_BELOW_RAD_PER_SEC ? 0 : omega;
out[o + COURSE0] = norm360(segment.trackDeg || 0); out[o + COURSE0] = norm360(segment.trackDeg || 0);
out[o + CLIMB] = segment.climbMps || 0;
} }
/** /**
@@ -266,6 +271,19 @@ export function segmentPosition(
x += seg[o + AXIS_U] * e + seg[o + AXIS_V] * n; x += seg[o + AXIS_U] * e + seg[o + AXIS_V] * n;
y += seg[o + AXIS_U + 1] * e + seg[o + AXIS_V + 1] * n; y += seg[o + AXIS_U + 1] * e + seg[o + AXIS_V + 1] * n;
z += seg[o + AXIS_U + 2] * e + seg[o + AXIS_V + 2] * n; z += seg[o + AXIS_U + 2] * e + seg[o + AXIS_V + 2] * n;
const climb = seg[o + CLIMB] * dt;
if (climb !== 0) {
// Up is east × north.
const ux = seg[o + AXIS_U];
const uy = seg[o + AXIS_U + 1];
const uz = seg[o + AXIS_U + 2];
const vx = seg[o + AXIS_V];
const vy = seg[o + AXIS_V + 1];
const vz = seg[o + AXIS_V + 2];
x += (uy * vz - uz * vy) * climb;
y += (uz * vx - ux * vz) * climb;
z += (ux * vy - uy * vx) * climb;
}
} }
result.x = x; result.x = x;
result.y = y; result.y = y;
@@ -293,7 +311,7 @@ float iconSegmentParameter(vec4 seg3, vec4 seg4, float tau) {
return 0.0; return 0.0;
} }
vec3 iconSegmentPosition(vec4 seg0, vec4 seg1, vec4 seg2, vec4 seg3, vec4 seg4, float tau) { vec3 iconSegmentPosition(vec4 seg0, vec4 seg1, vec4 seg2, vec4 seg3, vec4 seg4, vec4 seg5, float tau) {
vec3 high = seg0.xyz; vec3 high = seg0.xyz;
vec3 low = vec3(seg0.w, seg1.xy); vec3 low = vec3(seg0.w, seg1.xy);
vec3 axisU = vec3(seg1.zw, seg2.x); vec3 axisU = vec3(seg1.zw, seg2.x);
@@ -309,6 +327,7 @@ vec3 iconSegmentPosition(vec4 seg0, vec4 seg1, vec4 seg2, vec4 seg3, vec4 seg4,
float reach = seg4.x * t * iconSinc(half_); float reach = seg4.x * t * iconSinc(half_);
float heading = seg4.y + half_; float heading = seg4.y + half_;
p += axisU * (reach * sin(heading)) + axisV * (reach * cos(heading)); p += axisU * (reach * sin(heading)) + axisV * (reach * cos(heading));
p += cross(axisU, axisV) * (seg5.x * t);
} }
return p; return p;
} }
+51
View File
@@ -245,3 +245,54 @@ test('a zero-rate glide holds the course however the segment turns', () => {
writeCourseGlide(seg, 0, 90, 0, 0); writeCourseGlide(seg, 0, 90, 0, 0);
assert.ok(courseGap(segmentCourse(seg, 0, 20), 90) < 1e-4, 'arc turn held'); assert.ok(courseGap(segmentCourse(seg, 0, 20), 90) < 1e-4, 'arc turn held');
}); });
test('an arc climbs along the fix’s up axis at its climb rate, inside its clamped time', () => {
const seg = new Float32Array(SEGMENT_STRIDE);
writeArcSegment(seg, 0, {
fix,
t0: 100,
minDt: -10,
maxDt: 20,
speedMps: 200,
trackDeg: 90,
turnRateDps: 3,
climbMps: 15,
});
const up = Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal(fix);
for (const [tau, dt] of [
[108, 8],
[130, 20],
[80, -10],
]) {
const flat = productionArc(fix, 200, 90, 3, dt).position;
const want = Cesium.Cartesian3.add(
flat,
Cesium.Cartesian3.multiplyByScalar(up, 15 * dt, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const at = segmentPosition(seg, 0, tau);
assert.ok(
Cesium.Cartesian3.distance(at, want) < 0.05,
`at ${dt} s: ${Cesium.Cartesian3.distance(at, want)} m off`,
);
}
// The climb does not turn the course.
assert.ok(courseGap(segmentCourse(seg, 0, 108), 90 + 3 * 8) < 1e-3);
});
test('an arc written without a climb stays in its tangent plane', () => {
const seg = new Float32Array(SEGMENT_STRIDE);
seg.fill(7);
writeArcSegment(seg, 0, {
fix,
t0: 0,
minDt: 0,
maxDt: 30,
speedMps: 100,
trackDeg: 0,
turnRateDps: 0,
});
const at = segmentPosition(seg, 0, 30);
const want = productionArc(fix, 100, 0, 0, 30).position;
assert.ok(Cesium.Cartesian3.distance(at, want) < 0.05);
});
+73 -7
View File
@@ -14,6 +14,7 @@
* long the session runs. * long the session runs.
*/ */
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { HORIZON_LIFT_M } from '../geo/horizon.js';
import { import {
SEGMENT_STRIDE, SEGMENT_STRIDE,
segmentCourse, segmentCourse,
@@ -21,8 +22,11 @@ import {
shiftSegmentTimes, shiftSegmentTimes,
} from './iconSegment.js'; } from './iconSegment.js';
/** Floats per row of style: size, scale, alpha, atlas slots, flags, focus, near/far scaler. */ /**
export const STYLE_STRIDE = 12; * Floats per row of style: size, scale, alpha, atlas slots, flags, focus,
* near/far scaler, near-image switch, pick proxy and depth-test distance.
*/
export const STYLE_STRIDE = 16;
const WIDTH = 0; const WIDTH = 0;
const HEIGHT = 1; const HEIGHT = 1;
@@ -36,6 +40,16 @@ const NEAR_DISTANCE = 8;
const NEAR_VALUE = 9; const NEAR_VALUE = 9;
const FAR_DISTANCE = 10; const FAR_DISTANCE = 10;
const FAR_VALUE = 11; const FAR_VALUE = 11;
const IMAGE_SWITCH = 12;
const PROXY_WIDTH = 13;
const PROXY_HEIGHT = 14;
const DEPTH_TEST_DISTANCE = 15;
/**
* A depth-test distance at or past this draws over depth at any distance
* (Infinity, which a float column does not carry through every GPU).
*/
export const ICON_ALWAYS_OVER_DEPTH = 1e30;
/** Row flags, combined in the style's flags float. */ /** Row flags, combined in the style's flags float. */
export const ICON_SHOWN = 1; export const ICON_SHOWN = 1;
@@ -50,9 +64,9 @@ export const ICON_RECEDES = 4;
*/ */
export const ICON_CULL_LIFT = 8; export const ICON_CULL_LIFT = 8;
/** The ellipsoid height a CULL_LIFT row is raised to for the horizon test. */ /** The ellipsoid height a CULL_LIFT row is raised to for the horizon test. */
export const ICON_CULL_HEIGHT_M = 12; export const ICON_CULL_HEIGHT_M = HORIZON_LIFT_M;
/** Move the epoch forward once render times pass this many seconds. */ /** Move the epoch once render times are this many seconds from it. */
const REBASE_AFTER_SEC = 1800; const REBASE_AFTER_SEC = 1800;
/** /**
@@ -169,14 +183,14 @@ export function createIconSet({ capacity = 1024, epoch } = {}) {
}, },
/** /**
* Move the epoch to `julianDate` once it is more than half an hour ahead, * Move the epoch to `julianDate` once it is more than half an hour away
* shifting every stored time. Call between frames, never while a caller holds * (ahead, or behind on a clock set back), shifting every stored time. Call between frames, never while a caller holds
* times in the old base. * times in the old base.
* @returns {boolean} Whether it moved. * @returns {boolean} Whether it moved.
*/ */
rebase(julianDate) { rebase(julianDate) {
const shift = set.seconds(julianDate); const shift = set.seconds(julianDate);
if (shift < REBASE_AFTER_SEC) return false; if (Math.abs(shift) < REBASE_AFTER_SEC) return false;
for (let row = 0; row < count; row++) { for (let row = 0; row < count; row++) {
shiftSegmentTimes(segments, row, -shift); shiftSegmentTimes(segments, row, -shift);
expires[row] -= shift; expires[row] -= shift;
@@ -231,6 +245,7 @@ export function createIconSet({ capacity = 1024, epoch } = {}) {
style[o + FOCUS] = 1; style[o + FOCUS] = 1;
style[o + IMAGE_FAR] = -1; style[o + IMAGE_FAR] = -1;
style[o + IMAGE_NEAR] = -1; style[o + IMAGE_NEAR] = -1;
style[o + DEPTH_TEST_DISTANCE] = ICON_ALWAYS_OVER_DEPTH;
colors.fill(255, row * 4, row * 4 + 4); colors.fill(255, row * 4, row * 4 + 4);
expires[row] = -Infinity; expires[row] = -Infinity;
markRow(row); markRow(row);
@@ -360,6 +375,57 @@ export function createIconSet({ capacity = 1024, epoch } = {}) {
return style[row * STYLE_STRIDE + IMAGE_NEAR]; return style[row * STYLE_STRIDE + IMAGE_NEAR];
}, },
/**
* Draw the near image once the icon is wider than `px` CSS pixels on
* screen; 0 (the default) switches past the renderer's own device-pixel
* threshold.
*/
setImageSwitch(row, px) {
writeStyle(row, IMAGE_SWITCH, px);
},
imageSwitch(row) {
return style[row * STYLE_STRIDE + IMAGE_SWITCH];
},
/**
* An invisible pick target of `width × height` CSS pixels, picked
* wherever it or the icon covers; 0 × 0 (the default) picks the icon's
* drawn pixels only.
*/
setPickProxy(row, width, height) {
const o = row * STYLE_STRIDE;
if (
style[o + PROXY_WIDTH] === Math.fround(width) &&
style[o + PROXY_HEIGHT] === Math.fround(height)
)
return;
style[o + PROXY_WIDTH] = width;
style[o + PROXY_HEIGHT] = height;
set.dirty.style.mark(row);
},
pickProxyWidth(row) {
return style[row * STYLE_STRIDE + PROXY_WIDTH];
},
pickProxyHeight(row) {
return style[row * STYLE_STRIDE + PROXY_HEIGHT];
},
/**
* Draw over depth within `metres` of the eye, as a billboard's
* `disableDepthTestDistance`: 0 tests depth everywhere, Infinity (the
* default) never does.
*/
setDepthTestDistance(row, metres) {
writeStyle(
row,
DEPTH_TEST_DISTANCE,
metres >= ICON_ALWAYS_OVER_DEPTH ? ICON_ALWAYS_OVER_DEPTH : metres,
);
},
depthTestDistance(row) {
return style[row * STYLE_STRIDE + DEPTH_TEST_DISTANCE];
},
/** Size by camera distance, as Cesium's NearFarScalar (unset: 1 everywhere). */ /** Size by camera distance, as Cesium's NearFarScalar (unset: 1 everywhere). */
setScaleByDistance(row, scalar) { setScaleByDistance(row, scalar) {
const o = row * STYLE_STRIDE; const o = row * STYLE_STRIDE;
+85
View File
@@ -4,6 +4,7 @@ import * as Cesium from 'cesium';
import { import {
createIconSet, createIconSet,
DirtyRows, DirtyRows,
ICON_ALWAYS_OVER_DEPTH,
ICON_CULL_HEIGHT_M, ICON_CULL_HEIGHT_M,
ICON_CULL_LIFT, ICON_CULL_LIFT,
ICON_ROTATES, ICON_ROTATES,
@@ -14,6 +15,7 @@ import {
writeCourseGlide, writeCourseGlide,
writeHoldSegment, writeHoldSegment,
} from './iconSegment.js'; } from './iconSegment.js';
import { liftedForHorizon } from '../geo/horizon.js';
function place(set, id, lon, course = 0) { function place(set, id, lon, course = 0) {
const row = set.add(id, { id }); const row = set.add(id, { id });
@@ -228,6 +230,21 @@ test('rebasing moves the epoch without moving any row', () => {
assert.deepEqual(set.dirty.segments.runs(set.count), [[0, 0]]); assert.deepEqual(set.dirty.segments.runs(set.count), [[0, 0]]);
}); });
test('a clock set back more than half an hour moves the epoch back too', () => {
const epoch = Cesium.JulianDate.fromIso8601('2026-11-03T12:00:00Z');
const set = createIconSet({ epoch });
const row = place(set, 'a', 4);
const before = set.position(row, 0);
const earlier = (s) =>
Cesium.JulianDate.addSeconds(epoch, s, new Cesium.JulianDate());
assert.equal(set.rebase(earlier(-1000)), false);
assert.equal(set.rebase(earlier(-86400)), true);
assert.equal(set.seconds(earlier(-86400)), 0);
assert.ok(
Cesium.Cartesian3.distance(set.position(row, 86400), before) < 0.01,
);
});
test('a cull-lift row is judged at no lower than the cull height above the ellipsoid', () => { test('a cull-lift row is judged at no lower than the cull height above the ellipsoid', () => {
const set = createIconSet(); const set = createIconSet();
const row = set.add('a'); const row = set.add('a');
@@ -249,3 +266,71 @@ test('a cull-lift row is judged at no lower than the cull height above the ellip
'a contact floored higher keeps its own height', 'a contact floored higher keeps its own height',
); );
}); });
test('the Cesium-free horizon lift judges the point a cull-lift row is judged at', () => {
const set = createIconSet();
const row = set.add('a');
set.setFlag(row, ICON_CULL_LIFT, true);
for (const [lon, lat, h] of [
[4.05, 51.93, -40],
[4.05, 51.93, 3],
[-84.43, 33.64, 11.9],
[139.7, 35.6, 500],
[0, 89.5, -10],
]) {
const p = Cesium.Cartesian3.fromDegrees(lon, lat, h);
const lifted = liftedForHorizon(p);
assert.ok(
Cesium.Cartesian3.distance(set.cullPoint(row, p), lifted) < 1e-6,
`${lon}, ${lat}, ${h} m`,
);
}
});
test('a new row draws over depth everywhere, with no proxy and the default image switch', () => {
const set = createIconSet();
const row = set.add('a');
assert.equal(set.depthTestDistance(row), Math.fround(ICON_ALWAYS_OVER_DEPTH));
assert.equal(set.pickProxyWidth(row), 0);
assert.equal(set.pickProxyHeight(row), 0);
assert.equal(set.imageSwitch(row), 0);
});
test('the switch, proxy and depth-test columns mark the row only when they change', () => {
const set = createIconSet();
const row = set.add('a');
settle(set);
set.setImageSwitch(row, 40);
set.setPickProxy(row, 30, 20);
set.setDepthTestDistance(row, 5000);
assert.deepEqual(set.dirty.style.runs(set.count), [[0, 0]]);
assert.equal(set.imageSwitch(row), 40);
assert.equal(set.pickProxyWidth(row), 30);
assert.equal(set.pickProxyHeight(row), 20);
assert.equal(set.depthTestDistance(row), 5000);
settle(set);
set.setImageSwitch(row, 40);
set.setPickProxy(row, 30, 20);
set.setDepthTestDistance(row, 5000);
assert.ok(set.dirty.style.empty, 'unchanged writes leave it clean');
set.setDepthTestDistance(row, Infinity);
assert.equal(
set.depthTestDistance(row),
Math.fround(ICON_ALWAYS_OVER_DEPTH),
'Infinity is carried as the always-over-depth value',
);
});
test('removing a row moves its switch, proxy and depth-test columns too', () => {
const set = createIconSet({ capacity: 4 });
set.add('a');
const b = set.add('b');
set.setPickProxy(b, 44, 33);
set.setDepthTestDistance(b, 0);
set.remove('a');
const moved = set.row('b');
assert.equal(moved, 0);
assert.equal(set.pickProxyWidth(moved), 44);
assert.equal(set.pickProxyHeight(moved), 33);
assert.equal(set.depthTestDistance(moved), 0);
});
+58 -24
View File
@@ -39,6 +39,7 @@ const ATTRIBUTE_LOCATIONS = Object.freeze({
style2: 9, style2: 9,
color: 10, color: 10,
pickColor: 11, pickColor: 11,
style3: 12,
}); });
const VERTEX_SHADER = /* glsl */ ` const VERTEX_SHADER = /* glsl */ `
@@ -52,6 +53,7 @@ in vec4 seg5;
in vec4 style0; // width, height, scale, alpha in vec4 style0; // width, height, scale, alpha
in vec4 style1; // far image, near image, flags, focus in vec4 style1; // far image, near image, flags, focus
in vec4 style2; // scale by distance (near, near value, far, far value) in vec4 style2; // scale by distance (near, near value, far, far value)
in vec4 style3; // near-image switch (CSS px), pick proxy size (CSS px), depth-test distance
in vec4 color; in vec4 color;
in vec4 pickColor; in vec4 pickColor;
@@ -63,10 +65,13 @@ uniform vec3 u_cameraUp;
uniform vec4 u_recession; // limb distance, start ratio, strength, enabled uniform vec4 u_recession; // limb distance, start ratio, strength, enabled
uniform vec3 u_recessionFloors; // scale, alpha, combined alpha uniform vec3 u_recessionFloors; // scale, alpha, combined alpha
uniform vec4 u_slots[${MAX_ICON_SLOTS}]; uniform vec4 u_slots[${MAX_ICON_SLOTS}];
uniform float u_cull; // 1: hide rows past the ellipsoid's horizon
uniform float u_pickPass; // 1 while drawing for a pick
out vec2 v_uv; out vec2 v_uv;
out vec4 v_color; out vec4 v_color;
out vec4 v_pickColor; out vec4 v_pickColor;
out float v_proxy;
// The row's anchor in clip space before screen offsets, for effects that wrap // The row's anchor in clip space before screen offsets, for effects that wrap
// main() (cyber sonar) and must not change geometry or picks. // main() (cyber sonar) and must not change geometry or picks.
@@ -99,15 +104,16 @@ void main() {
v_pickColor = pickColor; v_pickColor = pickColor;
v_uv = vec2(0.0); v_uv = vec2(0.0);
v_color = vec4(0.0); v_color = vec4(0.0);
v_proxy = 0.0;
gl_Position = vec4(0.0, 0.0, 2.0, 1.0); // outside the clip volume: not drawn gl_Position = vec4(0.0, 0.0, 2.0, 1.0); // outside the clip volume: not drawn
float flags = style1.z; float flags = style1.z;
if (!iconFlag(flags, 1.0)) return; if (!iconFlag(flags, 1.0)) return;
vec3 rte = iconSegmentPosition(seg0, seg1, seg2, seg3, seg4, u_tau); vec3 rte = iconSegmentPosition(seg0, seg1, seg2, seg3, seg4, seg5, u_tau);
vec3 world = u_cameraPosition + rte; vec3 world = u_cameraPosition + rte;
vec3 cullPoint = iconFlag(flags, ${ICON_CULL_LIFT.toFixed(1)}) ? iconCullPoint(world) : world; vec3 cullPoint = iconFlag(flags, ${ICON_CULL_LIFT.toFixed(1)}) ? iconCullPoint(world) : world;
if (occludedByEllipsoid(cullPoint)) return; if (u_cull > 0.5 && occludedByEllipsoid(cullPoint)) return;
vec4 positionEC = czm_modelViewRelativeToEye * vec4(rte, 1.0); vec4 positionEC = czm_modelViewRelativeToEye * vec4(rte, 1.0);
if (positionEC.z >= 0.0) return; // behind the camera if (positionEC.z >= 0.0) return; // behind the camera
@@ -131,12 +137,20 @@ void main() {
} }
float glyphPx = style0.x * scale * distanceScale * czm_pixelRatio; float glyphPx = style0.x * scale * distanceScale * czm_pixelRatio;
float slot = glyphPx > ${NEAR_IMAGE_PX.toFixed(1)} ? style1.y : style1.x; bool nearImage = style3.x > 0.0
? glyphPx / czm_pixelRatio > style3.x
: glyphPx > ${NEAR_IMAGE_PX.toFixed(1)};
float slot = nearImage ? style1.y : style1.x;
if (slot < 0.0) return; // no image set if (slot < 0.0) return; // no image set
vec4 rect = u_slots[int(slot)]; vec4 rect = u_slots[int(slot)];
if (rect.z <= 0.0) return; // image not loaded yet if (rect.z <= 0.0) return; // image not loaded yet
vec2 halfSize = style0.xy * (scale * distanceScale * 0.5) * corner; vec2 halfSize = style0.xy * (scale * distanceScale * 0.5) * corner;
// A pick proxy: picked over the larger of it and the drawn icon.
if (u_pickPass > 0.5 && style3.y > 0.0 && style3.z > 0.0) {
halfSize = max(abs(halfSize), style3.yz * 0.5) * corner;
v_proxy = 1.0;
}
if (iconFlag(flags, 2.0)) { if (iconFlag(flags, 2.0)) {
float course = radians(iconSegmentCourse(seg3, seg4, seg5, u_tau)); float course = radians(iconSegmentCourse(seg3, seg4, seg5, u_tau));
vec3 up = czm_geodeticSurfaceNormal(world, vec3(0.0), czm_ellipsoidInverseRadii * czm_ellipsoidInverseRadii); vec3 up = czm_geodeticSurfaceNormal(world, vec3(0.0), czm_ellipsoidInverseRadii * czm_ellipsoidInverseRadii);
@@ -162,10 +176,13 @@ void main() {
#ifdef LOG_DEPTH #ifdef LOG_DEPTH
czm_vertexLogDepth(); czm_vertexLogDepth();
#endif #endif
// Depth test disabled at any distance: draw on the near plane, as a billboard // Depth test disabled within the row's distance (by default at any
// with disableDepthTestDistance = Infinity. // distance): draw on the near plane, as a billboard does inside its
// disableDepthTestDistance.
float zclip = gl_Position.z / gl_Position.w; float zclip = gl_Position.z / gl_Position.w;
if (zclip >= -1.0 && zclip <= 1.0) { bool overDepth = style3.w >= 1.0e30 || // ICON_ALWAYS_OVER_DEPTH
distanceSq < style3.w * style3.w;
if (overDepth && zclip >= -1.0 && zclip <= 1.0) {
gl_Position.z = -gl_Position.w; gl_Position.z = -gl_Position.w;
#ifdef LOG_DEPTH #ifdef LOG_DEPTH
v_depthFromNearPlusOne = 1.0; v_depthFromNearPlusOne = 1.0;
@@ -183,10 +200,13 @@ uniform sampler2D u_atlas;
in vec2 v_uv; in vec2 v_uv;
in vec4 v_color; in vec4 v_color;
in vec4 v_pickColor; in vec4 v_pickColor;
in float v_proxy;
void main() { void main() {
vec4 color = czm_gammaCorrect(texture(u_atlas, v_uv)); vec4 color = czm_gammaCorrect(texture(u_atlas, v_uv));
color *= czm_gammaCorrect(v_color); color *= czm_gammaCorrect(v_color);
// A pick proxy is picked wherever it covers, drawn or not.
if (v_proxy > 0.5) color = vec4(1.0);
if (color.a < 0.005) discard; if (color.a < 0.005) discard;
#ifdef OPAQUE #ifdef OPAQUE
if (color.a < 0.995) discard; if (color.a < 0.995) discard;
@@ -208,16 +228,24 @@ const EARTH_BOUNDS = new Cesium.BoundingSphere(
); );
/** /**
* @param {{ set: object, renderTime: () => Cesium.JulianDate, * @param {{ set: object, renderTime: (frameState: object) => Cesium.JulianDate,
* requestRender?: () => void }} options `renderTime` gives the instant to draw * requestRender?: () => void, cull?: () => boolean,
* at (the layer's delayed clock). `requestRender` asks for a frame when the * pickObject?: (id: string, set: object, primitive: object) => object }} options
* atlas packs a newly loaded image, for a layer that does not render * `renderTime` gives the instant to draw at (the layer's delayed clock), from
* continuously. * the frame being drawn. `requestRender` asks for a frame when the atlas packs
* a newly loaded image, for a layer that does not render continuously.
* `cull` says whether rows past the ellipsoid's horizon are hidden (by
* default always). `pickObject` builds a row's pick object around the
* `primitive` drill picks hide it by (by default `{ id, iconSet, meta,
* primitive }`).
*/ */
export class IconSetPrimitive { export class IconSetPrimitive {
constructor({ set, renderTime, requestRender }) { constructor({ set, renderTime, requestRender, cull, pickObject }) {
this.set = set; this.set = set;
this.renderTime = renderTime; this.renderTime = renderTime;
this._cull = cull ?? (() => true);
this._pickObject = pickObject ?? null;
this._pickPass = 0;
this._stopAtlasListener = requestRender this._stopAtlasListener = requestRender
? iconAtlas.onChange(requestRender) ? iconAtlas.onChange(requestRender)
: null; : null;
@@ -254,6 +282,8 @@ export class IconSetPrimitive {
u_recessionFloors: () => primitive._recessionFloors, u_recessionFloors: () => primitive._recessionFloors,
u_slots: () => primitive._slots, u_slots: () => primitive._slots,
u_atlas: () => primitive._texture, u_atlas: () => primitive._texture,
u_cull: () => (primitive._cull() ? 1 : 0),
u_pickPass: () => primitive._pickPass,
}; };
} }
@@ -272,7 +302,9 @@ export class IconSetPrimitive {
const context = frameState.context; const context = frameState.context;
this._syncAtlas(context); this._syncAtlas(context);
if (!this._texture) return; if (!this._texture) return;
const renderTime = this.renderTime(); // Read as the commands run, which they do right after this update.
this._pickPass = frameState.passes.pick ? 1 : 0;
const renderTime = this.renderTime(frameState);
set.rebase(renderTime); set.rebase(renderTime);
if (this._generation !== set.generation) this._allocate(context); if (this._generation !== set.generation) this._allocate(context);
this._upload(context); this._upload(context);
@@ -364,7 +396,7 @@ export class IconSetPrimitive {
strideInBytes: SEGMENT_BYTES, strideInBytes: SEGMENT_BYTES,
instanceDivisor: 1, instanceDivisor: 1,
}); });
for (let i = 0; i < 3; i++) for (let i = 0; i < 4; i++)
attributes.push({ attributes.push({
index: ATTRIBUTE_LOCATIONS[`style${i}`], index: ATTRIBUTE_LOCATIONS[`style${i}`],
vertexBuffer: buffers.style, vertexBuffer: buffers.style,
@@ -448,17 +480,19 @@ export class IconSetPrimitive {
}, },
}; };
handle = { handle = {
pickId: context.createPickId({ pickId: context.createPickId(
id, this._pickObject?.(id, set, facade) ?? {
// Which set drew the pick: ownership for layers whose row ids are id,
// upstream ids a sibling may share. // Which set drew the pick: ownership for layers whose row ids are
iconSet: set, // upstream ids a sibling may share.
get meta() { iconSet: set,
const at = set.row(id); get meta() {
return at >= 0 ? set.metaAt(at) : undefined; const at = set.row(id);
return at >= 0 ? set.metaAt(at) : undefined;
},
primitive: facade,
}, },
primitive: facade, ),
}),
}; };
set.setHandle(row, handle); set.setHandle(row, handle);
} }
+8
View File
@@ -186,6 +186,7 @@ test('consumer build includes only infrastructure code and resolves assets under
const entry = output.find((item) => item.type === 'chunk' && item.isEntry); const entry = output.find((item) => item.type === 'chunk' && item.isEntry);
const sources = Object.keys(entry.modules).filter((id) => id.endsWith('.js')); const sources = Object.keys(entry.modules).filter((id) => id.endsWith('.js'));
assert.deepEqual(sources.map((id) => id.split('/').at(-1)).sort(), [ assert.deepEqual(sources.map((id) => id.split('/').at(-1)).sort(), [
'aircraftRecession.js',
'camera.js', 'camera.js',
'cameraControls.js', 'cameraControls.js',
'cameraInput.js', 'cameraInput.js',
@@ -200,7 +201,13 @@ test('consumer build includes only infrastructure code and resolves assets under
'events.js', 'events.js',
'follow.js', 'follow.js',
'frame.js', 'frame.js',
'gpuIcons.js',
'heights.js', 'heights.js',
'horizon.js',
'iconAtlas.js',
'iconSegment.js',
'iconSet.js',
'iconSetPrimitive.js',
'infrastructure.js', 'infrastructure.js',
'infrastructureData.js', 'infrastructureData.js',
'infrastructureOverlayEntry.js', 'infrastructureOverlayEntry.js',
@@ -209,6 +216,7 @@ test('consumer build includes only infrastructure code and resolves assets under
'internals.js', 'internals.js',
'localGeojsonCore.js', 'localGeojsonCore.js',
'localGeojsonLod.js', 'localGeojsonLod.js',
'motionModel.js',
'pickRegistry.js', 'pickRegistry.js',
'query.js', 'query.js',
'rendererOf.js', 'rendererOf.js',
+21
View File
@@ -32,3 +32,24 @@ export function horizonFrom(eye) {
}, },
}; };
} }
/**
* How high above the ellipsoid a point near sea level is judged, at least,
* by a horizon test that lifts it: sea level sits at the geoid, below the
* ellipsoid across much of the ocean, and would read as past the limb.
*/
export const HORIZON_LIFT_M = 12;
/**
* `p` (ECEF) raised along its geocentric direction to at least `minHeightM`
* above the ellipsoid, the point a lifted horizon test judges (as the default
* renderer's GPU icons compute it).
*/
export function liftedForHorizon(p, minHeightM = HORIZON_LIFT_M) {
const o = WGS84.oneOverRadii;
const radius = Math.hypot(p.x, p.y, p.z);
const scaled = Math.hypot(p.x * o.x, p.y * o.y, p.z * o.z);
const height = radius * (1 - 1 / scaled);
const k = Math.max(0, minHeightM - height) / radius;
return { x: p.x + p.x * k, y: p.y + p.y * k, z: p.z + p.z * k };
}
+101 -3
View File
@@ -18,6 +18,9 @@
* draped lines of a set made with `pickable: false` stay out of the pick * draped lines of a set made with `pickable: false` stay out of the pick
* pass, so they never hide the ground geometry drawn under them from picks. * pass, so they never hide the ground geometry drawn under them from picks.
* *
* Icon sets whose items move, glide, recede, pick by proxy or switch images
* by size, or that take columns, draw on the GPU instead (`gpuIcons.js`).
*
* Built over a scene by `createCesiumPorts`, and on its own over a Cesium * Built over a scene by `createCesiumPorts`, and on its own over a Cesium
* viewer with no renderer bound, when code first asks * viewer with no renderer bound, when code first asks
* `findDraw` for one (`rendererOf.js`). * `findDraw` for one (`rendererOf.js`).
@@ -25,6 +28,7 @@
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { provideUnboundDraw } from '../rendererOf.js'; import { provideUnboundDraw } from '../rendererOf.js';
import { listenerList, toCartesian, uncaught } from './common.js'; import { listenerList, toCartesian, uncaught } from './common.js';
import { createGpuIcons, GPU_ICON_CAPABILITIES } from './gpuIcons.js';
/** The contract's colour as Cesium's. */ /** The contract's colour as Cesium's. */
export function toColor(color, alpha = 1) { export function toColor(color, alpha = 1) {
@@ -134,9 +138,15 @@ const ANCHORS = {
* The draw port over `scene`, and what the other ports read of it: the live * 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 * 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. * the clamp-state watch the frame loop runs after each draw.
* @param {{scene: object, report: (error: unknown) => void}} options * @param {{scene: object, report: (error: unknown) => void,
* capabilities?: ReadonlySet<string>}} options `capabilities` gate the
* GPU icon sets' members (by default they all are).
*/ */
export function createCesiumDraw({ scene, report }) { export function createCesiumDraw({
scene,
report,
capabilities = new Set(GPU_ICON_CAPABILITIES),
}) {
const sets = new Map(); const sets = new Map();
// Bumped on every change to the sets or what they hold. // Bumped on every change to the sets or what they hold.
let setsVersion = 0; let setsVersion = 0;
@@ -186,6 +196,12 @@ export function createCesiumDraw({ scene, report }) {
const handle = { const handle = {
id: spec.id, id: spec.id,
set(list) { set(list) {
if (onGpu(record, list, true)) {
items.clear();
for (const item of list) items.set(item.id, item);
record.gpu.sync();
return patched();
}
items.clear(); items.clear();
for (const item of list) items.set(item.id, item); for (const item of list) items.set(item.id, item);
// Icons are changed where they are, when they can be. // Icons are changed where they are, when they can be.
@@ -194,6 +210,11 @@ export function createCesiumDraw({ scene, report }) {
requestRender(); requestRender();
}, },
upsert(list) { upsert(list) {
if (onGpu(record, list)) {
for (const item of list) items.set(item.id, item);
record.gpu.write(list);
return patched();
}
// Items that only change how they look are changed where they are. // Items that only change how they look are changed where they are.
if (patchPoints(record, list) || patchLines(record, list)) { if (patchPoints(record, list) || patchLines(record, list)) {
for (const item of list) items.set(item.id, item); for (const item of list) items.set(item.id, item);
@@ -214,12 +235,20 @@ export function createCesiumDraw({ scene, report }) {
}, },
remove(ids) { remove(ids) {
for (const id of ids) items.delete(id); for (const id of ids) items.delete(id);
if (record.gpu) {
record.gpu.drop(ids);
return patched();
}
if (syncIcons(record, [])) return patched(); if (syncIcons(record, [])) return patched();
rebuild(); rebuild();
requestRender(); requestRender();
}, },
clear() { clear() {
items.clear(); items.clear();
if (record.gpu) {
record.gpu.sync();
return patched();
}
if (syncIcons(record, [])) return patched(); if (syncIcons(record, [])) return patched();
rebuild(); rebuild();
requestRender(); requestRender();
@@ -245,6 +274,7 @@ export function createCesiumDraw({ scene, report }) {
// A set that stops picking lets its old ground go now: still drawn // A set that stops picking lets its old ground go now: still drawn
// while the new builds, it would keep hiding the ground from picks. // while the new builds, it would keep hiding the ground from picks.
if (pickable && spec.pickable === false) retire(record); if (pickable && spec.pickable === false) retire(record);
record.gpu?.restyle();
setsVersion += 1; setsVersion += 1;
showHosts(record); showHosts(record);
// No longer culled: what the cull hid comes back. // No longer culled: what the cull hid comes back.
@@ -274,11 +304,61 @@ export function createCesiumDraw({ scene, report }) {
requestRender(); requestRender();
}, },
}; };
// `columns`: column updates of an icon set, on the GPU.
if (kind === 'icons' && capabilities.has('columns'))
handle.setColumns = (columns) => {
onGpu(record, [], false, true);
record.gpu.columns(columns);
patched();
};
sets.set(spec.id, record); sets.set(spec.id, record);
setsVersion += 1; setsVersion += 1;
return handle; return handle;
} }
const gpu = createGpuIcons({
scene,
capabilities,
toColor,
imageOf: (record, image) => iconImage(record, image),
peekImage: (image) => atlases.get(image.atlas)?.[image.slot],
requestRender,
});
/**
* Whether an icon set draws `list` on the GPU: it already does, or the
* items (or `force`, for columns) need it to, when its billboards give way
* to a GPU host in their place. Refuses, changing nothing, what the GPU
* cannot draw: of `list`, and, unless `replacing` them, of the items the
* set already holds.
*/
function onGpu(record, list, replacing = false, force = false) {
if (record.kind !== 'icons') return false;
const wanted = record.gpu || force ? 'needs' : gpu.wants(list);
if (!wanted) return false;
if (wanted === 'prefers') {
// Only a course blend: on the GPU if all of it can be, else billboards.
try {
gpu.check(list, record.spec);
if (!replacing) gpu.check(record.items.values(), record.spec);
} catch {
return false;
}
}
gpu.check(list, record.spec);
if (record.gpu) return true;
if (!replacing) gpu.check(record.items.values(), record.spec);
record.gpu = gpu.attach(record);
record.billboards = null;
record.billboardHost = null;
record.placed = [];
// Icons on the GPU stay out of offscreen passes: height queries never
// see them, so there is nothing to see through.
record.pickIds = [];
replaceHost(record, record.gpu.host);
return true;
}
function pickId(record, item) { function pickId(record, item) {
const id = { const id = {
set: record.spec.id, set: record.spec.id,
@@ -424,6 +504,8 @@ export function createCesiumDraw({ scene, report }) {
} }
function buildIcons(record) { function buildIcons(record) {
// A GPU host keeps drawing: what a rebuild changes, it reads live.
if (record.gpu) return;
const host = new Cesium.BillboardCollection({ const host = new Cesium.BillboardCollection({
scene, scene,
blendOption: pointBlendOf(record.spec.blend), blendOption: pointBlendOf(record.spec.blend),
@@ -459,7 +541,11 @@ export function createCesiumDraw({ scene, report }) {
position, position,
width: item.size[0] * (item.scale ?? 1), width: item.size[0] * (item.scale ?? 1),
height: item.size[1] * (item.scale ?? 1), height: item.size[1] * (item.scale ?? 1),
color: toColor(item.color, item.alpha ?? 1), // Focus emphasis as the GPU icons draw it: a fade, at most to none.
color: toColor(
item.color,
(item.alpha ?? 1) * Math.min(1, Math.max(0, item.focus ?? 1)),
),
verticalOrigin: ANCHORS[item.anchor ?? 'center'], verticalOrigin: ANCHORS[item.anchor ?? 'center'],
disableDepthTestDistance: item.disableDepthTest ?? 0, disableDepthTestDistance: item.disableDepthTest ?? 0,
heightReference: heightReferenceOf(item.height, record.spec.clampTo), heightReference: heightReferenceOf(item.height, record.spec.clampTo),
@@ -1348,6 +1434,12 @@ export function createCesiumDraw({ scene, report }) {
let changed = false; let changed = false;
for (const record of [...sets.values()]) for (const record of [...sets.values()])
if (record.kind === 'icons' && record.atlases?.has(id)) { if (record.kind === 'icons' && record.atlases?.has(id)) {
if (record.gpu) {
record.gpu.reatlas(id);
setsVersion += 1;
changed = true;
continue;
}
// Its icons that draw from the atlas take their new images where // Its icons that draw from the atlas take their new images where
// they are; a set that cannot is rebuilt. // they are; a set that cannot is rebuilt.
const drawing = []; const drawing = [];
@@ -1374,6 +1466,12 @@ export function createCesiumDraw({ scene, report }) {
afterRender() { afterRender() {
watchClamp(); watchClamp();
swapReady(); swapReady();
// Rows moving on a live clock draw on in the frames that follow.
for (const record of sets.values())
if (record.gpu?.animating()) {
requestRender();
break;
}
}, },
/** /**
* Let go of the sets; with `removeHosts`, take what they draw out of * Let go of the sets; with `removeHosts`, take what they draw out of
+543
View File
@@ -0,0 +1,543 @@
/**
* @module render/cesium/gpuIcons
* @description The Cesium draw port's GPU icon sets: an icon set whose items
* move (`motionSegments`), glide their course (`courseGlide`,
* `courseBlendMs`), recede toward the limb, pick through a larger proxy,
* switch images by drawn size, or that takes columns (`columns`), draws as
* one instanced primitive (`IconSetPrimitive`) over an icon set's typed
* columns (`iconSet.js`) instead of a billboard collection. Each item is one
* row; the GPU moves it along its segment on the set's motion clock, so a
* row is written only when its item changes.
*
* What these sets draw as billboards do not: an icon set becomes one when
* an item first needs it (or it first takes columns), and stays one; a
* course blend alone moves it only when all of it can move. They refuse
* loudly what billboards draw and they do not: clamped heights,
* `fadeByDistance`, `displayRange`, pixel and eye offsets, anchors other
* than the centre, axis and screen rotations, opaque and additive blends,
* and images other than URLs, SVG and atlas slots of those. Their images
* are rasterised square, at the item's larger side, into the icon atlas
* every GPU icon set shares, and refused when it has no room left for them.
*
* Choices the contract leaves open, taken conservatively:
* - `horizonCull` judges each row no lower than `ICON_CULL_HEIGHT_M` above
* the ellipsoid, as the layers drawing their own icon sets do for sea
* level and grounded contacts below it (`ICON_CULL_LIFT`).
* - A row's course is its motion's (`hold.courseDeg`, `lerp.course0Deg`,
* the arc's track), else the item's `course`.
* - Rows draw in the order they were added; removing one moves the last
* into its place.
* - `Columns.dirty` runs include their `end`, and are trusted only when the
* ids are those of the last columns, row for row.
* - A `lerp` whose `t1` is not after `t0` steps from `from` to `to` 1 ms
* after `t0`.
* - A course blend eases from the course shown when its course changes;
* writes keeping that course (and columns of neither position nor
* course) let it go on rather than start over.
*/
import * as Cesium from 'cesium';
import {
createIconSet,
ICON_CULL_LIFT,
ICON_RECEDES,
ICON_ROTATES,
} from '../../data/iconSet.js';
import {
segmentCourse,
writeArcSegment,
writeCourseGlide,
writeHoldSegment,
writeLerpSegment,
} from '../../data/iconSegment.js';
import { IconSetPrimitive } from '../../data/iconSetPrimitive.js';
import { iconAtlas, MAX_ICON_SLOTS } from '../../data/iconAtlas.js';
import { norm180 } from '../../data/motionModel.js';
import { toCartesian } from './common.js';
/** The capabilities GPU icon sets bring. */
export const GPU_ICON_CAPABILITIES = Object.freeze([
'columns',
'motionSegments',
'courseGlide',
]);
const nonZero = (v) =>
Boolean(v) && (v.x !== 0 || v.y !== 0 || (v.z ?? 0) !== 0);
/** Whether a curve is one (as the billboards read it). */
const isCurve = (curve) => Boolean(curve) && curve.far > curve.near;
/** An image's atlas URL: itself, or SVG as a data URL; else null. */
function imageUrl(image) {
if (typeof image === 'string') return image;
if (typeof image?.svg === 'string')
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(image.svg)}`;
return null;
}
/** What a row's segment and course easing are written from. */
function motionOf(item) {
return {
pos: item.pos ? { ...item.pos } : undefined,
course: item.course,
motion: item.motion ? { ...item.motion } : undefined,
courseGlide: item.courseGlide ? { ...item.courseGlide } : undefined,
courseBlendMs: item.courseBlendMs,
};
}
/** Whether two plain records hold the same values, nested ones included. */
function sameFields(a, b) {
if (a === b) return true;
if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false;
const keys = Object.keys(a);
if (keys.length !== Object.keys(b).length) return false;
for (const key of keys) if (!sameFields(a[key], b[key])) return false;
return true;
}
/** Whether two `motionOf`s write the same segment. */
const sameMotion = (a, b) => Boolean(a) && sameFields(a, b);
/** The square raster size an item's images take in the atlas. */
function rasterPxOf(item) {
const [width = 0, height = 0] = item.size ?? [];
return Math.max(1, Math.round(Math.max(width, height)));
}
/**
* @param {{scene: object, capabilities: ReadonlySet<string>,
* toColor: (color: unknown) => Cesium.Color,
* imageOf: (record: object, image: unknown) => unknown,
* peekImage: (ref: {atlas: string, slot: string}) => unknown,
* requestRender: () => void}} options `imageOf` reads an atlas slot
* through the draw port's atlases (undefined while it is not registered),
* noting that the set draws from it; `peekImage` only reads it.
*/
export function createGpuIcons({
scene,
capabilities,
toColor,
imageOf,
peekImage,
requestRender,
}) {
const can = (capability) => capabilities.has(capability);
/**
* Whether drawing these items needs a GPU icon set ('needs'), would only
* draw them better on one ('prefers': a course blend, which billboards
* draw as a snap), or neither (false).
*/
function wants(items) {
let prefers = false;
for (const item of items) {
if (
(item.motion && can('motionSegments')) ||
(item.courseGlide && can('courseGlide')) ||
item.recede ||
item.pickProxy ||
item.imageLod
)
return 'needs';
if (item.courseBlendMs > 0) prefers = true;
}
return prefers ? 'prefers' : false;
}
/** Refuse what a GPU icon set cannot draw, before anything changes. */
function check(items, spec = {}) {
if (spec.blend === 'opaque' || spec.blend === 'additive')
throw new Error(
`the Cesium renderer's GPU icons have no ${spec.blend} blend`,
);
// Atlas slots these items would take anew: they must all fit.
const fresh = new Set();
for (const item of items) {
const refuse = (what) => {
throw new Error(`the Cesium renderer's GPU icons have no ${what}`);
};
if (item.height !== undefined && item.height !== 'absolute')
refuse('clamped heights');
if (item.fadeByDistance) refuse('fadeByDistance');
if (item.displayRange) refuse('displayRange');
if (nonZero(item.pixelOffset)) refuse('pixelOffset');
if (nonZero(item.eyeOffset)) refuse('eyeOffset');
if (item.anchor !== undefined && item.anchor !== 'center')
refuse('anchors but the centre');
if (item.rotationMode === 'axis') refuse('axis rotation');
if (item.rotationMode === 'screen' && (item.rotation ?? 0) !== 0)
refuse('screen rotation');
for (const given of [item.image, item.imageLod?.near]) {
// An atlas slot as what it holds now (none yet draws once it does).
const image =
typeof given?.atlas === 'string' ? peekImage(given) : given;
if (
image !== undefined &&
typeof image !== 'string' &&
typeof image?.svg !== 'string'
)
refuse('images but URLs and SVG');
const url = imageUrl(image);
const px = rasterPxOf(item);
if (url !== null && !iconAtlas.has(url, px)) fresh.add(`${px}|${url}`);
}
}
if (iconAtlas.size + fresh.size > MAX_ICON_SLOTS)
throw new Error(
`the Cesium renderer's GPU icons have no room for ${fresh.size} more images (at most ${MAX_ICON_SLOTS} in all)`,
);
}
/**
* Draw `record`'s icons on the GPU from now on: its icon set, the
* primitive drawing it, and the writes that keep it in step with the
* record's items.
*/
function attach(record) {
const spec = record.spec;
const scratch = new Cesium.JulianDate();
// The motion clock's time now, and in the frame being drawn.
function clockTime(frameState, result = scratch) {
const clock = spec.motionClock;
if (clock?.kind === 'scene')
return Cesium.JulianDate.clone(
frameState?.time ?? scene.frameState?.time ?? Cesium.JulianDate.now(),
result,
);
return Cesium.JulianDate.addSeconds(
Cesium.JulianDate.now(result),
-(clock?.delayMs ?? 0) / 1000,
result,
);
}
// Its epoch starts at the clock, and the primitive keeps it near it.
const set = createIconSet({ epoch: clockTime() });
const msScratch = new Cesium.JulianDate();
const tauOf = (ms) =>
set.seconds(Cesium.JulianDate.fromDate(new Date(ms), msScratch));
const host = new IconSetPrimitive({
set,
renderTime: (frameState) =>
clockTime(frameState, new Cesium.JulianDate()),
requestRender,
cull: () => spec.horizonCull === true,
// Picked as the draw port's other items are: `{set, id, meta,
// lodGroup}` as the item now is, hidden row by row for drill picks.
pickObject: (id, _set, primitive) => ({
primitive,
id: {
set: spec.id,
id,
get meta() {
return record.items.get(id)?.meta;
},
get lodGroup() {
return record.items.get(id)?.lodGroup;
},
},
}),
});
record.atlases ??= new Set();
// Until when (epoch ms on the motion clock) a row may still move or turn.
let movingUntil = -Infinity;
const clockMs = () => Cesium.JulianDate.toDate(clockTime()).getTime();
// Each row's course blend, by id: {target, from, t0 (epoch ms), rate}.
const blends = new Map();
// What each row's segment was last written from, by id.
const written = new Map();
// The ids of the last columns, while no other write came after them.
let columnIds = null;
// Written in full on the first write.
let fresh = true;
/** An image as its atlas slot, or -1 while it is not registered. */
function slotOf(image, sizePx) {
const resolved = imageOf(record, image);
if (resolved === undefined) return -1;
const url = imageUrl(resolved);
if (url !== null) return iconAtlas.slot(url, sizePx);
throw new Error(
"the Cesium renderer's GPU icons have no images but URLs and SVG",
);
}
/** The course a row's motion (else its item) gives. */
function courseOf(item) {
const motion = can('motionSegments') ? item.motion : undefined;
if (motion?.kind === 'hold') return motion.courseDeg ?? item.course ?? 0;
if (motion?.kind === 'lerp') return motion.course0Deg ?? item.course ?? 0;
return item.course ?? 0;
}
/** Write a row's segment; when it stops moving, epoch ms (-Infinity: holds). */
function writeMotion(row, item) {
const seg = set.segments;
const motion = can('motionSegments') ? item.motion : undefined;
const pos = toCartesian(item.pos);
switch (motion?.kind) {
case 'lerp': {
const t0 = tauOf(motion.t0);
// Not after t0: a step 1 ms after it.
const t1 = Math.max(tauOf(motion.t1), t0 + 0.001);
writeLerpSegment(seg, row, {
from: toCartesian(motion.from),
to: toCartesian(motion.to),
t0,
t1,
course0Deg: courseOf(item),
courseSlopeDeg: motion.courseSlopeDeg ?? 0,
});
return Math.max(motion.t1, motion.t0 + 1);
}
case 'arc': {
const t0 = tauOf(motion.t0);
writeArcSegment(seg, row, {
fix: toCartesian(motion.fix),
t0,
minDt: motion.minDtS,
maxDt: motion.maxDtS,
speedMps: motion.speedMps,
trackDeg: motion.trackDeg,
turnRateDps: motion.turnRateDps,
climbMps: motion.climbMps ?? 0,
});
return motion.t0 + motion.maxDtS * 1000;
}
default:
writeHoldSegment(seg, row, pos, courseOf(item));
return -Infinity;
}
}
/**
* Draw an item as its row (added when it has none). With `motion` false
* (a column change of neither position nor course) its segment and
* course easing are kept as they are.
*/
function writeRow(item, { motion = true } = {}) {
let row = set.row(item.id);
const added = row < 0;
if (added) row = set.add(item.id);
const tau = set.seconds(clockTime());
// The course on screen before this write, to ease from.
const shownCourse =
added || set.expires(row) === -Infinity ? null : set.course(row, tau);
const [width = 0, height = 0] = item.size ?? [];
const rasterPx = rasterPxOf(item);
const far = slotOf(item.image, rasterPx);
const near = item.imageLod ? slotOf(item.imageLod.near, rasterPx) : far;
set.setImage(row, far, near);
// A switch at 0 px or less is near at any size.
set.setImageSwitch(
row,
item.imageLod ? Math.max(item.imageLod.switchPx, 1e-3) : 0,
);
set.setSize(row, width, height);
set.setScale(row, item.scale ?? 1);
set.setAlpha(row, item.alpha ?? 1);
set.setColor(row, toColor(item.color));
set.setFocus(row, item.focus ?? 1);
set.setScaleByDistance(
row,
isCurve(item.scaleByDistance) ? item.scaleByDistance : undefined,
);
set.setFlag(row, ICON_ROTATES, item.rotationMode === 'course');
set.setFlag(row, ICON_RECEDES, item.recede === true);
set.setFlag(row, ICON_CULL_LIFT, spec.horizonCull === true);
set.setPickProxy(
row,
item.pickProxy?.size?.[0] ?? 0,
item.pickProxy?.size?.[1] ?? 0,
);
set.setDepthTestDistance(row, item.disableDepthTest ?? 0);
set.setShown(row, item.show !== false);
if (!motion && !added) return;
// A write moving it as it already moves (a restyle, a focus change)
// keeps its segment and course easing as they are.
const from = motionOf(item);
if (!added && sameMotion(written.get(item.id), from)) return;
written.set(item.id, from);
let end = writeMotion(row, item);
const glide = can('courseGlide') ? item.courseGlide : undefined;
if (glide) {
writeCourseGlide(
set.segments,
row,
glide.fromCourseDeg,
tauOf(glide.t0),
glide.rateDps,
);
// Turning at most half a turn at its rate.
if (glide.rateDps > 0)
end = Math.max(end, glide.t0 + (180 / glide.rateDps) * 1000);
} else if (item.courseBlendMs > 0 && shownCourse !== null) {
const target = segmentCourse(set.segments, row, tau);
const now = clockMs();
let blend = blends.get(item.id);
// The same course as the blend under way heads for: it goes on.
if (!blend || blend.target !== target) {
// Over `courseBlendMs`: at the rate that closes the gap in that time.
const gap = Math.abs(norm180(shownCourse - target));
blend =
gap > 0
? {
target,
from: shownCourse,
t0: now,
rate: gap / (item.courseBlendMs / 1000),
until: now + item.courseBlendMs,
}
: null;
if (blend) blends.set(item.id, blend);
else blends.delete(item.id);
}
if (blend) {
writeCourseGlide(
set.segments,
row,
blend.from,
tauOf(blend.t0),
blend.rate,
);
end = Math.max(end, blend.until);
}
} else blends.delete(item.id);
set.segmentWritten(row);
if (end > movingUntil) movingUntil = end;
}
/** Bring the rows in line with every item. */
function sync() {
fresh = false;
columnIds = null;
// Every row is written anew.
movingUntil = -Infinity;
written.clear();
for (let row = set.count - 1; row >= 0; row--) {
const id = set.idAt(row);
if (!record.items.has(id)) {
set.remove(id);
blends.delete(id);
written.delete(id);
}
}
for (const item of record.items.values()) writeRow(item);
}
return {
host,
set,
sync,
/** Rows for these items, already in the record's. */
write(items) {
if (fresh) return sync();
columnIds = null;
for (const item of items) writeRow(record.items.get(item.id) ?? item);
},
/** Rows of items gone from the record's. */
drop(ids) {
if (fresh) return sync();
columnIds = null;
for (const id of ids) {
set.remove(id);
blends.delete(id);
written.delete(id);
}
if (record.items.size === 0) movingUntil = -Infinity;
},
/**
* Columns as rows, as the contract's `Columns`: each column's value
* merged into its row's item (added when it has none), and the rows
* not in `ids` removed.
*/
columns(columns) {
if (fresh) sync();
const ids = columns.ids.map(String);
const n = ids.length;
const same =
columnIds !== null &&
columnIds.length === n &&
ids.every((id, i) => columnIds[i] === id);
if (!same) {
const keep = new Set(ids);
for (const id of [...record.items.keys()])
if (!keep.has(id)) {
record.items.delete(id);
set.remove(id);
blends.delete(id);
written.delete(id);
}
}
const runs =
same && columns.dirty ? columns.dirty : [{ start: 0, end: n - 1 }];
const {
positions: p,
courses,
shown,
scales,
alphas,
colors,
meta,
} = columns;
// Neither moved nor turned: segments and course easing stay.
const motion = Boolean(p || courses);
for (const run of runs)
for (
let i = Math.max(0, run.start);
i <= Math.min(n - 1, run.end);
i++
) {
const id = ids[i];
const item = { ...(record.items.get(id) ?? { id }) };
if (p) item.pos = { x: p[i * 3], y: p[i * 3 + 1], z: p[i * 3 + 2] };
if (courses) item.course = courses[i];
if (shown) item.show = shown[i] !== 0;
if (scales) item.scale = scales[i];
if (alphas) item.alpha = alphas[i];
if (colors)
item.color = [0, 1, 2, 3].map((k) => colors[i * 4 + k] / 255);
if (meta) item.meta = meta[i];
record.items.set(id, item);
writeRow(item, { motion });
}
columnIds = ids;
},
/** After `setOptions`: the cull lift follows `horizonCull`. */
restyle() {
for (let row = 0; row < set.count; row++)
set.setFlag(row, ICON_CULL_LIFT, spec.horizonCull === true);
},
/** Rewrite the rows drawing from atlas `id`. */
reatlas(id) {
const drawing = [];
for (const item of record.items.values())
if (item.image?.atlas === id || item.imageLod?.near?.atlas === id)
drawing.push(item);
if (fresh) return sync();
for (const item of drawing) writeRow(item);
},
/** Whether a live-clock row is still moving: frames should keep coming. */
animating() {
if (spec.motionClock?.kind === 'scene' || spec.show === false)
return false;
return set.count > 0 && clockMs() < movingUntil;
},
/** The images shown rows draw: `failed`, `loading` or `settled`. */
imageState() {
let loading = false;
for (let row = 0; row < set.count; row++) {
if (!set.shown(row)) continue;
for (const slot of [set.imageFar(row), set.imageNear(row)]) {
if (slot < 0) continue;
if (iconAtlas.failed(slot)) return 'failed';
if (!iconAtlas.ready(slot)) loading = true;
}
}
return loading ? 'loading' : 'settled';
},
};
}
return { wants, check, attach };
}
+550
View File
@@ -0,0 +1,550 @@
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import test from 'node:test';
import { createCesiumDraw } from './draw.js';
import { drawHitOf } from './drawHit.js';
import { IconSetPrimitive } from '../../data/iconSetPrimitive.js';
import {
ICON_CULL_LIFT,
ICON_RECEDES,
ICON_ROTATES,
} from '../../data/iconSet.js';
import { motionPosition } from '../stub/motion.js';
/** A scene with what the draw port touches, and a frame time to set. */
function fakeScene() {
const added = [];
return {
added,
renders: 0,
camera: { positionWC: new Cesium.Cartesian3(2e7, 0, 0) },
frameState: { time: Cesium.JulianDate.now() },
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,
},
requestRender() {
this.renders += 1;
},
isDestroyed: () => false,
};
}
function drawOver(options = {}) {
const scene = fakeScene();
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
...options,
});
return { scene, part, draw: part.port };
}
const AT = Cesium.Cartesian3.fromDegrees(4.1, 51.95, 2);
const ecef = (c) => ({ x: c.x, y: c.y, z: c.z });
const distance = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
const julian = (ms) => Cesium.JulianDate.fromDate(new Date(ms));
/** The record's icon set, and where a row is drawn at epoch ms `ms`. */
function rows(part, id) {
const set = part.sets.get(id).gpu.set;
return {
set,
position: (rowId, ms) =>
set.position(set.row(rowId), set.seconds(julian(ms))),
course: (rowId, ms) => set.course(set.row(rowId), set.seconds(julian(ms))),
};
}
const icon = (id, extra = {}) => ({
id,
pos: ecef(AT),
image: 'ship.png',
size: [32, 32],
...extra,
});
test('a moving item takes its icon set onto the GPU, in its billboards’ place', () => {
const { scene, part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:switch', horizonCull: true });
set.set([icon('a')]);
assert.ok(scene.added[0] instanceof Cesium.BillboardCollection);
set.upsert([icon('b', { motion: { kind: 'hold', courseDeg: 30 } })]);
assert.equal(scene.added.length, 1, 'one host');
const host = scene.added[0];
assert.ok(host instanceof IconSetPrimitive, 'drawn by the GPU icon set');
assert.equal(host.drawSetId, 'gpu:switch', 'named for sprite ordering');
const { set: rowsOf, course } = rows(part, 'gpu:switch');
assert.equal(rowsOf.count, 2, 'the items it had are rows too');
assert.equal(set.size(), 2);
assert.equal(course('b', Date.now()), 30);
// It stays on the GPU: still items draw as holds where they are.
set.set([icon('c')]);
assert.equal(scene.added[0], host);
assert.equal(rowsOf.count, 1);
assert.ok(distance(rows(part, 'gpu:switch').position('c', 0), AT) < 0.01);
set.remove(['c']);
assert.equal(rowsOf.count, 0);
set.dispose();
assert.equal(scene.added.length, 0, 'disposed: gone from the scene');
});
test('segments draw where the contract’s motion puts them, on the scene clock', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:motion', motionClock: { kind: 'scene' } });
// Near the set's epoch (now), as live times are: segment times are float32.
const t0 = Date.now();
const fix = ecef(Cesium.Cartesian3.fromDegrees(4.1, 51.95, 12000));
const to = ecef(Cesium.Cartesian3.fromDegrees(4.3, 51.95, 12000));
const motions = {
lerp: { kind: 'lerp', from: fix, to, t0, t1: t0 + 10000 },
arc: {
kind: 'arc',
fix,
t0,
speedMps: 150,
trackDeg: 20,
turnRateDps: 3,
climbMps: 12,
minDtS: -10,
maxDtS: 20,
},
straight: {
kind: 'arc',
fix,
t0,
speedMps: 200,
trackDeg: 90,
turnRateDps: 0,
climbMps: -5,
minDtS: 0,
maxDtS: 10,
},
hold: { kind: 'hold', courseDeg: 45 },
};
set.set(
Object.entries(motions).map(([id, motion]) => ({
...icon(id),
pos: fix,
motion,
})),
);
const { position } = rows(part, 'gpu:motion');
for (const dt of [-30000, -5000, 0, 2500, 8000, 15000, 60000])
for (const [id, motion] of Object.entries(motions)) {
const want = motionPosition(motion, fix, t0 + dt);
const off = distance(position(id, t0 + dt), want);
assert.ok(off < 0.1, `${id} at ${dt} ms: ${off} m off`);
}
});
test('a set’s motion clock is the frame’s scene time, or wall time less its delay', () => {
const { scene, part, draw } = drawOver();
const live = draw.icons({
id: 'gpu:live',
motionClock: { kind: 'live', delayMs: 2000 },
});
live.set([icon('a', { motion: { kind: 'hold' } })]);
const host = part.sets.get('gpu:live').host;
const lag =
Date.now() - Cesium.JulianDate.toDate(host.renderTime({})).getTime();
assert.ok(Math.abs(lag - 2000) < 50, `lags ${lag} ms`);
const sceneSet = draw.icons({
id: 'gpu:scene',
motionClock: { kind: 'scene' },
});
sceneSet.set([icon('a', { motion: { kind: 'hold' } })]);
const frameState = { time: julian(Date.UTC(2020, 0, 1)) };
const sceneHost = part.sets.get('gpu:scene').host;
assert.ok(
Cesium.JulianDate.equals(sceneHost.renderTime(frameState), frameState.time),
);
assert.equal(scene.frameState.time instanceof Cesium.JulianDate, true);
});
test('rows moving on a live clock keep frames coming until their segments end', () => {
const { scene, part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:animate' });
const now = Date.now();
const to = ecef(Cesium.Cartesian3.fromDegrees(4.2, 51.95, 2));
set.set([
icon('a', {
motion: { kind: 'lerp', from: ecef(AT), to, t0: now, t1: now + 60000 },
}),
]);
const before = scene.renders;
part.afterRender();
assert.equal(scene.renders, before + 1, 'still moving: another frame');
set.set([icon('a', { motion: { kind: 'hold' } })]);
const held = scene.renders;
part.afterRender();
assert.equal(scene.renders, held, 'held: no frames asked for');
// A scene clock moves with the scene's own time.
set.setOptions({ motionClock: { kind: 'scene' } });
set.set([
icon('a', {
motion: { kind: 'lerp', from: ecef(AT), to, t0: now, t1: now + 60000 },
}),
]);
const onScene = scene.renders;
part.afterRender();
assert.equal(scene.renders, onScene);
});
test('an item’s look goes into its row: size, scale, tint, focus, flags, proxy, depth and images', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:look', horizonCull: true });
set.set([
icon('a', {
motion: { kind: 'hold', courseDeg: 10 },
size: [20, 24],
scale: 1.5,
alpha: 0.5,
color: [1, 0, 0, 1],
focus: 0.25,
recede: true,
rotationMode: 'course',
pickProxy: { size: [48, 40] },
disableDepthTest: Infinity,
scaleByDistance: { near: 1000, nearValue: 3, far: 8e6, farValue: 0.5 },
imageLod: { near: 'ship-large.png', switchPx: 60 },
}),
icon('b', { motion: { kind: 'hold' }, show: false }),
]);
const { set: s } = rows(part, 'gpu:look');
const a = s.row('a');
assert.equal(s.width(a), 20);
assert.equal(s.height(a), 24);
assert.equal(s.scale(a), 1.5);
assert.equal(s.alpha(a), 0.5);
assert.ok(Cesium.Color.equals(s.color(a), Cesium.Color.RED));
assert.equal(s.focus(a), 0.25);
assert.equal(s.flags(a) & ICON_ROTATES, ICON_ROTATES);
assert.equal(s.flags(a) & ICON_RECEDES, ICON_RECEDES);
assert.equal(s.flags(a) & ICON_CULL_LIFT, ICON_CULL_LIFT, 'culled lifted');
assert.equal(s.pickProxyWidth(a), 48);
assert.equal(s.pickProxyHeight(a), 40);
assert.ok(s.depthTestDistance(a) >= 1e30, 'over depth everywhere');
assert.equal(s.scaleByDistance(a).nearValue, 3);
assert.equal(s.imageSwitch(a), 60);
assert.notEqual(s.imageNear(a), s.imageFar(a), 'a near image of its own');
assert.equal(s.shown(a), true);
const b = s.row('b');
assert.equal(s.shown(b), false);
assert.equal(s.depthTestDistance(b), 0, 'depth-tested by default');
assert.equal(s.flags(b) & ICON_ROTATES, 0, 'upright by default');
assert.equal(s.focus(b), 1);
assert.equal(s.imageNear(b), s.imageFar(b));
// The cull lift follows the set's horizon cull.
set.setOptions({ horizonCull: false });
assert.equal(s.flags(a) & ICON_CULL_LIFT, 0);
assert.equal(part.sets.get('gpu:look').host._cull(), false);
set.setOptions({ horizonCull: true });
assert.equal(s.flags(a) & ICON_CULL_LIFT, ICON_CULL_LIFT);
assert.equal(part.sets.get('gpu:look').host._cull(), true);
});
test('a row picks as a draw-set item, with the meta its item has now', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:pick' });
set.set([icon('a', { motion: { kind: 'hold' }, meta: { n: 1 } })]);
const host = part.sets.get('gpu:pick').host;
const facade = { show: true };
const picked = host._pickObject('a', null, facade);
assert.equal(picked.primitive, facade, 'drill picks hide it by its facade');
assert.deepEqual(drawHitOf(picked), {
set: 'gpu:pick',
id: 'a',
meta: { n: 1 },
surface: false,
});
set.upsert([
icon('a', { motion: { kind: 'hold' }, meta: { n: 2 }, lodGroup: 'g' }),
]);
assert.deepEqual(drawHitOf(picked).meta, { n: 2 });
assert.equal(drawHitOf(picked).lodGroup, 'g');
});
test('a course glides at its rate with courseGlide, and eases over courseBlendMs without it', () => {
const t0 = Date.now();
const glideItem = (rateDps) =>
icon('a', {
motion: { kind: 'hold', courseDeg: 90 },
rotationMode: 'course',
courseGlide: { fromCourseDeg: 0, t0, rateDps },
});
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:glide' });
set.set([glideItem(10)]);
const { course } = rows(part, 'gpu:glide');
assert.ok(Math.abs(course('a', t0 + 3000) - 30) < 0.01, 'at 10°/s');
assert.ok(Math.abs(course('a', t0 + 20000) - 90) < 0.01, 'then on course');
set.set([glideItem(0)]);
assert.ok(Math.abs(course('a', t0 + 20000) - 0) < 0.01, '0°/s holds');
// Without the capability: the blend over courseBlendMs instead.
const without = drawOver({
capabilities: new Set(['motionSegments', 'columns']),
});
const blended = without.draw.icons({ id: 'gpu:blend' });
const blend = (courseDeg) =>
icon('a', {
motion: { kind: 'hold', courseDeg },
courseBlendMs: 2000,
courseGlide: { fromCourseDeg: 180, t0, rateDps: 1 },
});
blended.set([blend(0)]);
const r = rows(without.part, 'gpu:blend');
assert.ok(
Math.abs(r.course('a', Date.now())) < 0.01,
'new: on course at once, its glide ignored',
);
blended.upsert([blend(60)]);
const at = Date.now();
assert.ok(Math.abs(r.course('a', at + 1000) - 30) < 1, 'halfway at 1 s');
assert.ok(Math.abs(r.course('a', at + 2500) - 60) < 0.01, 'there by 2 s');
});
test('without motionSegments, motion is ignored: billboards at the item’s place', () => {
const { scene, draw } = drawOver({ capabilities: new Set() });
const set = draw.icons({ id: 'gpu:none' });
set.set([icon('a', { motion: { kind: 'hold' } })]);
assert.ok(scene.added[0] instanceof Cesium.BillboardCollection);
assert.equal(set.setColumns, undefined, 'no columns either');
});
test('GPU icon sets refuse what they cannot draw, changing nothing', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:refuse' });
set.set([icon('a', { motion: { kind: 'hold' } })]);
for (const extra of [
{ height: 'clampGround' },
{ fadeByDistance: { near: 1, nearValue: 1, far: 2, farValue: 0 } },
{ displayRange: [0, 10] },
{ pixelOffset: { x: 1, y: 0 } },
{ eyeOffset: { x: 0, y: 0, z: 5 } },
{ anchor: 'bottom' },
{ rotationMode: 'axis' },
{ rotationMode: 'screen', rotation: 1 },
{ image: { blob: {} } },
])
assert.throws(
() => set.upsert([icon('b', { motion: { kind: 'hold' }, ...extra })]),
/GPU icons have no/,
JSON.stringify(extra),
);
assert.equal(set.size(), 1);
assert.equal(rows(part, 'gpu:refuse').set.count, 1);
// A billboard set refuses to move over when what it holds cannot.
const billboards = draw.icons({ id: 'gpu:stay' });
billboards.set([icon('a', { anchor: 'bottom' })]);
assert.throws(
() => billboards.upsert([icon('b', { motion: { kind: 'hold' } })]),
/anchors/,
);
assert.equal(part.sets.get('gpu:stay').gpu, undefined);
assert.equal(billboards.size(), 1);
});
test('columns update rows by index: positions, courses, shown, scales, tints and meta', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:columns' });
const b = ecef(Cesium.Cartesian3.fromDegrees(4.2, 51.9, 2));
set.set([icon('a', { meta: 1 }), icon('b', { pos: b, meta: 2 })]);
assert.ok(part.sets.get('gpu:columns').gpu === undefined, 'billboards');
set.setColumns({
ids: ['a', 'b'],
positions: new Float64Array([b.x, b.y, b.z, AT.x, AT.y, AT.z]),
courses: new Float32Array([15, 25]),
shown: new Uint8Array([1, 0]),
scales: new Float32Array([2, 3]),
alphas: new Float32Array([0.5, 1]),
colors: new Uint8Array([255, 0, 0, 255, 0, 0, 255, 255]),
meta: [{ k: 'a' }, { k: 'b' }],
});
const r = rows(part, 'gpu:columns');
const now = Date.now();
assert.ok(distance(r.position('a', now), b) < 0.01, 'a moved to b');
assert.ok(distance(r.position('b', now), AT) < 0.01, 'b moved to a');
assert.equal(r.course('a', now), 15);
assert.equal(r.set.shown(r.set.row('b')), false);
assert.equal(r.set.scale(r.set.row('b')), 3);
assert.equal(r.set.alpha(r.set.row('a')), 0.5);
assert.ok(
Cesium.Color.equals(r.set.color(r.set.row('b')), Cesium.Color.BLUE),
);
const host = part.sets.get('gpu:columns').host;
assert.deepEqual(drawHitOf(host._pickObject('b', null, {})).meta, {
k: 'b',
});
assert.equal(r.set.width(r.set.row('a')), 32, 'the item’s look is kept');
// Dirty runs, for the same ids, rewrite only those rows (end included).
const scales = new Float32Array([4, 5]);
set.setColumns({ ids: ['a', 'b'], scales, dirty: [{ start: 1, end: 1 }] });
assert.equal(r.set.scale(r.set.row('a')), 2, 'not in the run: as it was');
assert.equal(r.set.scale(r.set.row('b')), 5);
// New ids: rows not named go, new ones come (drawn once they have a look).
set.setColumns({
ids: ['b', 'c'],
positions: new Float64Array([AT.x, AT.y, AT.z, b.x, b.y, b.z]),
dirty: [{ start: 0, end: 0 }],
});
assert.equal(set.size(), 2);
assert.equal(r.set.row('a'), -1, 'a went');
assert.ok(distance(r.position('c', now), b) < 0.01, 'c written in full');
assert.equal(r.set.imageFar(r.set.row('c')), -1, 'no image: not drawn');
});
test('a row hidden by its column keeps its segment, and shows where it would be', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:shown', motionClock: { kind: 'scene' } });
const t0 = Date.now();
const to = ecef(Cesium.Cartesian3.fromDegrees(4.3, 51.95, 2));
const motion = { kind: 'lerp', from: ecef(AT), to, t0, t1: t0 + 10000 };
set.set([icon('m', { motion })]);
set.setColumns({ ids: ['m'], shown: new Uint8Array([0]) });
const r = rows(part, 'gpu:shown');
assert.equal(r.set.shown(0), false);
set.setColumns({ ids: ['m'], shown: new Uint8Array([1]) });
const want = motionPosition(motion, ecef(AT), t0 + 7000);
assert.ok(distance(r.position('m', t0 + 7000), want) < 0.1);
});
test('re-registering an atlas rewrites the GPU rows drawing from it', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:atlas' });
set.set([
icon('a', {
motion: { kind: 'hold' },
image: { atlas: 'ships', slot: 'x' },
}),
]);
const r = rows(part, 'gpu:atlas');
assert.equal(r.set.imageFar(0), -1, 'not registered yet: not drawn');
const before = part.version();
draw.atlas('ships', { x: 'ship-x.png' });
assert.ok(r.set.imageFar(0) >= 0, 'drawn once it is');
assert.ok(part.version() > before);
});
test('held rows still turning keep frames coming until their course settles', () => {
const { scene, part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:turning' });
const now = Date.now();
set.set([
icon('a', {
motion: { kind: 'hold', courseDeg: 90 },
rotationMode: 'course',
courseGlide: { fromCourseDeg: 0, t0: now, rateDps: 10 },
}),
]);
const before = scene.renders;
part.afterRender();
assert.equal(scene.renders, before + 1, 'gliding: another frame');
// A glide long since over: settled, no frames.
set.set([
icon('a', {
motion: { kind: 'hold', courseDeg: 90 },
rotationMode: 'course',
courseGlide: { fromCourseDeg: 0, t0: now - 60000, rateDps: 10 },
}),
]);
const settled = scene.renders;
part.afterRender();
assert.equal(scene.renders, settled);
// A course blend under way: frames until it ends.
set.set([
icon('a', { motion: { kind: 'hold', courseDeg: 0 }, courseBlendMs: 2000 }),
]);
set.upsert([
icon('a', { motion: { kind: 'hold', courseDeg: 50 }, courseBlendMs: 2000 }),
]);
const blending = scene.renders;
part.afterRender();
assert.equal(scene.renders, blending + 1, 'blending: another frame');
});
test('a course blend goes on through writes that keep its course, columns that only hide included', () => {
const { part, draw } = drawOver({
capabilities: new Set(['motionSegments', 'columns']),
});
const set = draw.icons({ id: 'gpu:blend-keep' });
const item = (courseDeg) =>
icon('a', { motion: { kind: 'hold', courseDeg }, courseBlendMs: 2000 });
set.set([item(0)]);
set.upsert([item(60)]);
const at = Date.now();
const r = rows(part, 'gpu:blend-keep');
const halfway = r.course('a', at + 1000);
// The same course again, then a column that only hides and shows it.
set.upsert([{ ...item(60), alpha: 0.5 }]);
set.setColumns({ ids: ['a'], shown: new Uint8Array([1]) });
assert.ok(
Math.abs(r.course('a', at + 1000) - halfway) < 1,
'not restarted from where it is now',
);
assert.ok(Math.abs(r.course('a', at + 2500) - 60) < 0.01, 'there by 2 s');
});
test('an icon set refuses, changing nothing, images the shared atlas has no room for', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:atlas-room' });
set.set([icon('a', { motion: { kind: 'hold' } })]);
const many = Array.from({ length: 80 }, (_, i) =>
icon(`m${i}`, { image: `room-${i}.png`, motion: { kind: 'hold' } }),
);
assert.throws(() => set.upsert(many), /no room for/);
assert.equal(set.size(), 1);
assert.equal(rows(part, 'gpu:atlas-room').set.count, 1);
});
test('focus fades a billboard icon as it fades a GPU one', () => {
const { scene, draw } = drawOver();
const set = draw.icons({ id: 'gpu:focus-billboard' });
set.set([icon('a', { focus: 0.25, alpha: 0.8 })]);
const billboards = scene.added[0];
assert.ok(billboards instanceof Cesium.BillboardCollection);
assert.ok(Math.abs(billboards.get(0).color.alpha - 0.2) < 1e-6);
set.upsert([icon('a', { focus: 3 })]);
assert.equal(billboards.get(0).color.alpha, 1, 'at most no fade');
});
test('a course blend alone moves a set onto the GPU only when all of it can go', () => {
const { scene, part, draw } = drawOver();
const stays = draw.icons({ id: 'gpu:blend-stays' });
stays.set([icon('a', { anchor: 'bottom', courseBlendMs: 500 })]);
assert.equal(part.sets.get('gpu:blend-stays').gpu, undefined, 'billboards');
const goes = draw.icons({ id: 'gpu:blend-goes' });
goes.set([icon('a', { courseBlendMs: 500 })]);
assert.ok(part.sets.get('gpu:blend-goes').gpu, 'on the GPU');
// A blend GPU icons do not draw is refused, not ignored.
const additive = draw.icons({ id: 'gpu:additive', blend: 'additive' });
assert.throws(
() => additive.set([icon('a', { motion: { kind: 'hold' } })]),
/additive blend/,
);
assert.ok(scene.added.length >= 2);
});
test('a write that moves a row as it already moves keeps its segment', () => {
const { part, draw } = drawOver();
const set = draw.icons({ id: 'gpu:keep-segment' });
const item = icon('a', { motion: { kind: 'hold', courseDeg: 40 } });
set.set([item]);
const { set: rowsSet } = rows(part, 'gpu:keep-segment');
rowsSet.dirty.segments.clear();
rowsSet.dirty.style.clear();
set.upsert([{ ...item, focus: 0.5, motion: { ...item.motion } }]);
assert.ok(rowsSet.dirty.segments.empty, 'no segment written');
assert.ok(!rowsSet.dirty.style.empty, 'its focus is');
set.upsert([{ ...item, motion: { kind: 'hold', courseDeg: 41 } }]);
assert.ok(!rowsSet.dirty.segments.empty, 'a new course is');
});
+8
View File
@@ -35,11 +35,17 @@ export const CESIUM_CHECKS = new Set([
'credits.listenerRules', 'credits.listenerRules',
'draw.atlas', 'draw.atlas',
'draw.clampState', 'draw.clampState',
'draw.columns',
'draw.columns.shown',
'draw.drillPick', 'draw.drillPick',
'draw.icons.distance', 'draw.icons.distance',
'draw.icons.update', 'draw.icons.update',
'draw.ids', 'draw.ids',
'draw.models', 'draw.models',
'draw.motion',
'draw.motion.arc',
'draw.motion.climb',
'draw.motion.live',
'draw.pick', 'draw.pick',
'draw.sets', 'draw.sets',
'effects.crossfade', 'effects.crossfade',
@@ -137,6 +143,8 @@ export function createCesiumHarness({ name = 'cesium', model } = {}) {
// no real pointer can (a click with no press), so not DOM events. // no real pointer can (a click with no press), so not DOM events.
pointer: (r, type, x, y, extra) => pointerFeedOf(r)(type, x, y, extra), pointer: (r, type, x, y, extra) => pointerFeedOf(r)(type, x, y, extra),
now: () => performance.now(), now: () => performance.now(),
// What a live motion clock reads.
wallTime: () => Date.now(),
toEcef, toEcef,
tolerance: DEFAULT_TOLERANCE, tolerance: DEFAULT_TOLERANCE,
flightPaths: 'endpoints', flightPaths: 'endpoints',
+11 -1
View File
@@ -17,6 +17,7 @@ import { createCesiumCamera } from './camera.js';
import { listenerList, toCartesian, uncaught } from './common.js'; import { listenerList, toCartesian, uncaught } from './common.js';
import { createCesiumCredits } from './credits.js'; import { createCesiumCredits } from './credits.js';
import { createCesiumDraw } from './draw.js'; import { createCesiumDraw } from './draw.js';
import { GPU_ICON_CAPABILITIES } from './gpuIcons.js';
import { createCesiumEffects } from './effects.js'; import { createCesiumEffects } from './effects.js';
import { willDraw } from './frame.js'; import { willDraw } from './frame.js';
import { createCesiumGlobe } from './globe.js'; import { createCesiumGlobe } from './globe.js';
@@ -58,6 +59,7 @@ const GLOBE_CAPABILITIES = [
export function cesiumCapabilities(scene, only) { export function cesiumCapabilities(scene, only) {
const all = [ const all = [
'models', 'models',
...GPU_ICON_CAPABILITIES,
'styles', 'styles',
'bloom', 'bloom',
'sharpen', 'sharpen',
@@ -288,7 +290,7 @@ export function createCesiumPorts(widget, { capabilities, credentials = {} }) {
// --- Draw ------------------------------------------------------------------ // --- Draw ------------------------------------------------------------------
const drawPart = createCesiumDraw({ scene, report }); const drawPart = createCesiumDraw({ scene, report, capabilities });
const { port: draw, sets, tilesets } = drawPart; const { port: draw, sets, tilesets } = drawPart;
const cameraPart = createCesiumCamera({ scene, camera, report, widget }); const cameraPart = createCesiumCamera({ scene, camera, report, widget });
@@ -415,6 +417,14 @@ export function createCesiumPorts(widget, { capabilities, credentials = {} }) {
function iconState() { function iconState() {
let loading = false; let loading = false;
for (const record of sets.values()) { for (const record of sets.values()) {
// GPU icons read their images from the shared icon atlas.
if (record.gpu) {
if (!record.host?.show) continue;
const state = record.gpu.imageState();
if (state === 'failed') return 'failed';
if (state === 'loading') loading = true;
continue;
}
const host = record.kind === 'icons' && record.host; const host = record.kind === 'icons' && record.host;
if (!host || !host.show) continue; if (!host || !host.show) continue;
for (let i = 0; i < host.length; i++) { for (let i = 0; i < host.length; i++) {
+3
View File
@@ -10,6 +10,9 @@ import { updateCameraChanged } from './internals.js';
test('capabilities follow what the scene supports', () => { test('capabilities follow what the scene supports', () => {
const effects = [ const effects = [
'columns',
'motionSegments',
'courseGlide',
'styles', 'styles',
'bloom', 'bloom',
'sharpen', 'sharpen',