diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index a83e44809..b3e885a2d 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -9,9 +9,17 @@ "src/data/infrastructure.js", "src/data/localGeojsonCore.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/query.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -876,10 +884,18 @@ "src/ui/cockpitRollingValue.js", "src/ui/cockpitCamera.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/query.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -1012,10 +1028,18 @@ "src/styles/thermal.js", "src/ui/applicationShell.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/query.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/data/followed.js", "src/render/cesium/camera.js", "src/render/cesium/cameraControls.js", @@ -1288,10 +1312,18 @@ "src/scenes/director.js", "src/data/followed.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/query.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -1442,6 +1474,7 @@ "src/render/cesium/query.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -1453,6 +1486,7 @@ "src/data/aircraftMotionRegime.js", "src/data/iconSetPrimitive.js", "src/data/iconSet.js", + "src/geo/horizon.js", "src/data/iconSegment.js", "src/data/iconAtlas.js", "src/data/aircraftRecession.js", @@ -1541,6 +1575,7 @@ "src/render/cesium/query.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -1553,6 +1588,7 @@ "src/data/aircraftMotionRegime.js", "src/data/iconSetPrimitive.js", "src/data/iconSet.js", + "src/geo/horizon.js", "src/data/iconSegment.js", "src/data/iconAtlas.js", "src/data/aircraftRecession.js", @@ -1654,6 +1690,7 @@ "src/data/entityRecords.js", "src/data/iconSetPrimitive.js", "src/data/iconSet.js", + "src/geo/horizon.js", "src/data/iconSegment.js", "src/data/iconAtlas.js", "src/data/aircraftRecession.js", @@ -1699,6 +1736,7 @@ "src/queries/heights.js", "src/render/creditMarkup.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/frame.js", "src/render/cesium/follow.js", "src/render/cesium/cameraInput.js", @@ -1716,12 +1754,20 @@ "exports": ["./render/cesium/unbound"], "modules": [ "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/query.js", "src/render/cesium/drawHit.js", "src/queries/heights.js", "src/render/cesium/effects.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/camera.js", "src/render/camera/events.js", "src/geo/index.js", @@ -1805,6 +1851,7 @@ "src/render/cesium/credits.js", "src/render/creditMarkup.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/layers/firms/index.js", "src/layers/firms/ingestion.js", "src/layers/firms/lifecycle.js", @@ -1818,6 +1865,7 @@ "src/data/entityRecords.js", "src/data/iconSetPrimitive.js", "src/data/iconSet.js", + "src/geo/horizon.js", "src/data/iconSegment.js", "src/data/iconAtlas.js", "src/data/aircraftRecession.js", @@ -1881,10 +1929,18 @@ "src/layers/satellites/testing.js", "src/layers/satellites/tracking.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/query.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -1938,10 +1994,17 @@ "src/layers/launches/controls.js", "src/layers/launches/index.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/query.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -2013,10 +2076,17 @@ "src/layers/installations/controls.js", "src/geo/geodesic.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/query.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -2324,6 +2394,7 @@ "src/render/cesium/query.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -2344,6 +2415,7 @@ "src/layers/cctv/rendering.js", "src/data/iconSetPrimitive.js", "src/data/iconSet.js", + "src/geo/horizon.js", "src/data/iconSegment.js", "src/data/iconAtlas.js", "src/data/aircraftRecession.js", @@ -2395,9 +2467,17 @@ "modules": [ "src/layers/streetLevel/index.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/query.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/geo/index.js", "src/layers/streetLevel/credits.js", "src/render/creditMarkup.js", @@ -2577,10 +2657,18 @@ "src/layers/radio/navigation.js", "src/data/followed.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/query.js", "src/queries/heights.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -2737,6 +2825,13 @@ "src/maps/catalog.js", "src/maps/controller.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/query.js", "src/queries/heights.js", @@ -2744,6 +2839,7 @@ "src/render/cesium/credits.js", "src/render/cesium/tileRequests.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/cameraInput.js", "src/render/cesium/camera.js", "src/render/cesium/cameraControls.js", @@ -2960,6 +3056,7 @@ "src/render/creditMarkup.js", "src/render/rendererOf.js", "src/render/cesium/ports.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/query.js", "src/render/cesium/globe.js", "src/render/cesium/drawHit.js", @@ -3956,6 +4053,7 @@ "src/render/cesium/frame.js", "src/render/cesium/query.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/imagery.js", "src/maps/google3d.js", "src/render/cesium/cameraControls.js", @@ -4616,10 +4714,18 @@ "src/layers/firms/anchors.js", "src/locations.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/query.js", "src/render/cesium/drawHit.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/cameraControls.js", "src/render/cesium/cameraInput.js", "src/render/cesium/credits.js", @@ -4730,11 +4836,19 @@ "src/geo/index.js", "src/ui/navigationController.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/query.js", "src/queries/heights.js", "src/render/cesium/drawHit.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/cameraControls.js", "src/render/cesium/cameraInput.js", "src/render/cesium/credits.js", @@ -5267,9 +5381,17 @@ "src/cyberSonar.js", "src/celestialRing.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/query.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", "src/render/creditMarkup.js", @@ -5391,6 +5513,13 @@ "src/layers/transit/viewport.js", "src/geo/rectangle.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/frame.js", "src/render/cesium/camera.js", @@ -5401,6 +5530,7 @@ "src/render/cesium/credits.js", "src/render/creditMarkup.js", "src/render/cesium/draw.js", + "src/render/cesium/gpuIcons.js", "src/data/cameraSensitivity.js", "src/data/contactPlayback.js", "src/data/contactTrailRenderer.js", diff --git a/src/data/iconAtlas.js b/src/data/iconAtlas.js index 2b3e6ca4b..379f60d42 100644 --- a/src/data/iconAtlas.js +++ b/src/data/iconAtlas.js @@ -54,11 +54,21 @@ function createAtlas() { 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. */ ready(slot) { 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, * can ask for the frame that shows a newly loaded image. diff --git a/src/data/iconSegment.js b/src/data/iconSegment.js index 421311059..a5a4e58d3 100644 --- a/src/data/iconSegment.js +++ b/src/data/iconSegment.js @@ -9,7 +9,8 @@ * - lerp: straight from `base` to `base + U` between two fix times (the interpolation * 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 - * 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 * `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 COURSE0 = 19; // deg 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_T0 = 22; // s 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 - * 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 {number} row * @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) { const o = row * SEGMENT_STRIDE; @@ -135,6 +139,7 @@ export function writeArcSegment(out, row, segment) { out[o + TRACK] = (segment.trackDeg || 0) * DEG; out[o + OMEGA] = Math.abs(omega) < STRAIGHT_BELOW_RAD_PER_SEC ? 0 : omega; 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; 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; + 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.y = y; @@ -293,7 +311,7 @@ float iconSegmentParameter(vec4 seg3, vec4 seg4, float tau) { 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 low = vec3(seg0.w, seg1.xy); 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 heading = seg4.y + half_; p += axisU * (reach * sin(heading)) + axisV * (reach * cos(heading)); + p += cross(axisU, axisV) * (seg5.x * t); } return p; } diff --git a/src/data/iconSegment.test.mjs b/src/data/iconSegment.test.mjs index 0beec4b6e..82adf4161 100644 --- a/src/data/iconSegment.test.mjs +++ b/src/data/iconSegment.test.mjs @@ -245,3 +245,54 @@ test('a zero-rate glide holds the course however the segment turns', () => { writeCourseGlide(seg, 0, 90, 0, 0); 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); +}); diff --git a/src/data/iconSet.js b/src/data/iconSet.js index 1ac8b8c3c..811014610 100644 --- a/src/data/iconSet.js +++ b/src/data/iconSet.js @@ -14,6 +14,7 @@ * long the session runs. */ import * as Cesium from 'cesium'; +import { HORIZON_LIFT_M } from '../geo/horizon.js'; import { SEGMENT_STRIDE, segmentCourse, @@ -21,8 +22,11 @@ import { shiftSegmentTimes, } 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 HEIGHT = 1; @@ -36,6 +40,16 @@ const NEAR_DISTANCE = 8; const NEAR_VALUE = 9; const FAR_DISTANCE = 10; 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. */ export const ICON_SHOWN = 1; @@ -50,9 +64,9 @@ export const ICON_RECEDES = 4; */ export const ICON_CULL_LIFT = 8; /** 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; /** @@ -169,14 +183,14 @@ export function createIconSet({ capacity = 1024, epoch } = {}) { }, /** - * Move the epoch to `julianDate` once it is more than half an hour ahead, - * shifting every stored time. Call between frames, never while a caller holds + * Move the epoch to `julianDate` once it is more than half an hour away + * (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. * @returns {boolean} Whether it moved. */ rebase(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++) { shiftSegmentTimes(segments, row, -shift); expires[row] -= shift; @@ -231,6 +245,7 @@ export function createIconSet({ capacity = 1024, epoch } = {}) { style[o + FOCUS] = 1; style[o + IMAGE_FAR] = -1; style[o + IMAGE_NEAR] = -1; + style[o + DEPTH_TEST_DISTANCE] = ICON_ALWAYS_OVER_DEPTH; colors.fill(255, row * 4, row * 4 + 4); expires[row] = -Infinity; markRow(row); @@ -360,6 +375,57 @@ export function createIconSet({ capacity = 1024, epoch } = {}) { 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). */ setScaleByDistance(row, scalar) { const o = row * STYLE_STRIDE; diff --git a/src/data/iconSet.test.mjs b/src/data/iconSet.test.mjs index 84e11c48b..4a8e1859e 100644 --- a/src/data/iconSet.test.mjs +++ b/src/data/iconSet.test.mjs @@ -4,6 +4,7 @@ import * as Cesium from 'cesium'; import { createIconSet, DirtyRows, + ICON_ALWAYS_OVER_DEPTH, ICON_CULL_HEIGHT_M, ICON_CULL_LIFT, ICON_ROTATES, @@ -14,6 +15,7 @@ import { writeCourseGlide, writeHoldSegment, } from './iconSegment.js'; +import { liftedForHorizon } from '../geo/horizon.js'; function place(set, id, lon, course = 0) { 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]]); }); +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', () => { const set = createIconSet(); 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', ); }); + +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); +}); diff --git a/src/data/iconSetPrimitive.js b/src/data/iconSetPrimitive.js index 1d740815f..f64302ad4 100644 --- a/src/data/iconSetPrimitive.js +++ b/src/data/iconSetPrimitive.js @@ -39,6 +39,7 @@ const ATTRIBUTE_LOCATIONS = Object.freeze({ style2: 9, color: 10, pickColor: 11, + style3: 12, }); const VERTEX_SHADER = /* glsl */ ` @@ -52,6 +53,7 @@ in vec4 seg5; in vec4 style0; // width, height, scale, alpha in vec4 style1; // far image, near image, flags, focus 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 pickColor; @@ -63,10 +65,13 @@ uniform vec3 u_cameraUp; uniform vec4 u_recession; // limb distance, start ratio, strength, enabled uniform vec3 u_recessionFloors; // scale, alpha, combined alpha 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 vec4 v_color; out vec4 v_pickColor; +out float v_proxy; // The row's anchor in clip space before screen offsets, for effects that wrap // main() (cyber sonar) and must not change geometry or picks. @@ -99,15 +104,16 @@ void main() { v_pickColor = pickColor; v_uv = vec2(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 float flags = style1.z; 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 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); if (positionEC.z >= 0.0) return; // behind the camera @@ -131,12 +137,20 @@ void main() { } 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 vec4 rect = u_slots[int(slot)]; if (rect.z <= 0.0) return; // image not loaded yet 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)) { float course = radians(iconSegmentCourse(seg3, seg4, seg5, u_tau)); vec3 up = czm_geodeticSurfaceNormal(world, vec3(0.0), czm_ellipsoidInverseRadii * czm_ellipsoidInverseRadii); @@ -162,10 +176,13 @@ void main() { #ifdef LOG_DEPTH czm_vertexLogDepth(); #endif - // Depth test disabled at any distance: draw on the near plane, as a billboard - // with disableDepthTestDistance = Infinity. + // Depth test disabled within the row's distance (by default at any + // distance): draw on the near plane, as a billboard does inside its + // disableDepthTestDistance. 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; #ifdef LOG_DEPTH v_depthFromNearPlusOne = 1.0; @@ -183,10 +200,13 @@ uniform sampler2D u_atlas; in vec2 v_uv; in vec4 v_color; in vec4 v_pickColor; +in float v_proxy; void main() { vec4 color = czm_gammaCorrect(texture(u_atlas, v_uv)); 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; #ifdef OPAQUE if (color.a < 0.995) discard; @@ -208,16 +228,24 @@ const EARTH_BOUNDS = new Cesium.BoundingSphere( ); /** - * @param {{ set: object, renderTime: () => Cesium.JulianDate, - * requestRender?: () => void }} options `renderTime` gives the instant to draw - * at (the layer's delayed clock). `requestRender` asks for a frame when the - * atlas packs a newly loaded image, for a layer that does not render - * continuously. + * @param {{ set: object, renderTime: (frameState: object) => Cesium.JulianDate, + * requestRender?: () => void, cull?: () => boolean, + * pickObject?: (id: string, set: object, primitive: object) => object }} options + * `renderTime` gives the instant to draw at (the layer's delayed clock), from + * 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 { - constructor({ set, renderTime, requestRender }) { + constructor({ set, renderTime, requestRender, cull, pickObject }) { this.set = set; this.renderTime = renderTime; + this._cull = cull ?? (() => true); + this._pickObject = pickObject ?? null; + this._pickPass = 0; this._stopAtlasListener = requestRender ? iconAtlas.onChange(requestRender) : null; @@ -254,6 +282,8 @@ export class IconSetPrimitive { u_recessionFloors: () => primitive._recessionFloors, u_slots: () => primitive._slots, 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; this._syncAtlas(context); 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); if (this._generation !== set.generation) this._allocate(context); this._upload(context); @@ -364,7 +396,7 @@ export class IconSetPrimitive { strideInBytes: SEGMENT_BYTES, instanceDivisor: 1, }); - for (let i = 0; i < 3; i++) + for (let i = 0; i < 4; i++) attributes.push({ index: ATTRIBUTE_LOCATIONS[`style${i}`], vertexBuffer: buffers.style, @@ -448,17 +480,19 @@ export class IconSetPrimitive { }, }; handle = { - pickId: context.createPickId({ - id, - // Which set drew the pick: ownership for layers whose row ids are - // upstream ids a sibling may share. - iconSet: set, - get meta() { - const at = set.row(id); - return at >= 0 ? set.metaAt(at) : undefined; + pickId: context.createPickId( + this._pickObject?.(id, set, facade) ?? { + id, + // Which set drew the pick: ownership for layers whose row ids are + // upstream ids a sibling may share. + iconSet: set, + get meta() { + const at = set.row(id); + return at >= 0 ? set.metaAt(at) : undefined; + }, + primitive: facade, }, - primitive: facade, - }), + ), }; set.setHandle(row, handle); } diff --git a/src/data/infrastructure.test.mjs b/src/data/infrastructure.test.mjs index 333162c84..cf6bdd86f 100644 --- a/src/data/infrastructure.test.mjs +++ b/src/data/infrastructure.test.mjs @@ -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 sources = Object.keys(entry.modules).filter((id) => id.endsWith('.js')); assert.deepEqual(sources.map((id) => id.split('/').at(-1)).sort(), [ + 'aircraftRecession.js', 'camera.js', 'cameraControls.js', 'cameraInput.js', @@ -200,7 +201,13 @@ test('consumer build includes only infrastructure code and resolves assets under 'events.js', 'follow.js', 'frame.js', + 'gpuIcons.js', 'heights.js', + 'horizon.js', + 'iconAtlas.js', + 'iconSegment.js', + 'iconSet.js', + 'iconSetPrimitive.js', 'infrastructure.js', 'infrastructureData.js', 'infrastructureOverlayEntry.js', @@ -209,6 +216,7 @@ test('consumer build includes only infrastructure code and resolves assets under 'internals.js', 'localGeojsonCore.js', 'localGeojsonLod.js', + 'motionModel.js', 'pickRegistry.js', 'query.js', 'rendererOf.js', diff --git a/src/geo/horizon.js b/src/geo/horizon.js index f6c7cff57..a9ac89760 100644 --- a/src/geo/horizon.js +++ b/src/geo/horizon.js @@ -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 }; +} diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index a827adda5..cc18a85d5 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -18,6 +18,9 @@ * 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. * + * 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 * viewer with no renderer bound, when code first asks * `findDraw` for one (`rendererOf.js`). @@ -25,6 +28,7 @@ import * as Cesium from 'cesium'; import { provideUnboundDraw } from '../rendererOf.js'; import { listenerList, toCartesian, uncaught } from './common.js'; +import { createGpuIcons, GPU_ICON_CAPABILITIES } from './gpuIcons.js'; /** The contract's colour as Cesium's. */ 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 * sets by id, a version that changes with them, the scene's 3D tilesets and * the clamp-state watch the frame loop runs after each draw. - * @param {{scene: object, report: (error: unknown) => void}} options + * @param {{scene: object, report: (error: unknown) => void, + * capabilities?: ReadonlySet}} 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(); // Bumped on every change to the sets or what they hold. let setsVersion = 0; @@ -186,6 +196,12 @@ export function createCesiumDraw({ scene, report }) { const handle = { id: spec.id, 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(); for (const item of list) items.set(item.id, item); // Icons are changed where they are, when they can be. @@ -194,6 +210,11 @@ export function createCesiumDraw({ scene, report }) { requestRender(); }, 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. if (patchPoints(record, list) || patchLines(record, list)) { for (const item of list) items.set(item.id, item); @@ -214,12 +235,20 @@ export function createCesiumDraw({ scene, report }) { }, remove(ids) { for (const id of ids) items.delete(id); + if (record.gpu) { + record.gpu.drop(ids); + return patched(); + } if (syncIcons(record, [])) return patched(); rebuild(); requestRender(); }, clear() { items.clear(); + if (record.gpu) { + record.gpu.sync(); + return patched(); + } if (syncIcons(record, [])) return patched(); rebuild(); requestRender(); @@ -245,6 +274,7 @@ export function createCesiumDraw({ scene, report }) { // 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. if (pickable && spec.pickable === false) retire(record); + record.gpu?.restyle(); setsVersion += 1; showHosts(record); // No longer culled: what the cull hid comes back. @@ -274,11 +304,61 @@ export function createCesiumDraw({ scene, report }) { 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); setsVersion += 1; 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) { const id = { set: record.spec.id, @@ -424,6 +504,8 @@ export function createCesiumDraw({ scene, report }) { } function buildIcons(record) { + // A GPU host keeps drawing: what a rebuild changes, it reads live. + if (record.gpu) return; const host = new Cesium.BillboardCollection({ scene, blendOption: pointBlendOf(record.spec.blend), @@ -459,7 +541,11 @@ export function createCesiumDraw({ scene, report }) { position, width: item.size[0] * (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'], disableDepthTestDistance: item.disableDepthTest ?? 0, heightReference: heightReferenceOf(item.height, record.spec.clampTo), @@ -1348,6 +1434,12 @@ export function createCesiumDraw({ scene, report }) { let changed = false; for (const record of [...sets.values()]) 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 // they are; a set that cannot is rebuilt. const drawing = []; @@ -1374,6 +1466,12 @@ export function createCesiumDraw({ scene, report }) { afterRender() { watchClamp(); 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 diff --git a/src/render/cesium/gpuIcons.js b/src/render/cesium/gpuIcons.js new file mode 100644 index 000000000..28ea541ab --- /dev/null +++ b/src/render/cesium/gpuIcons.js @@ -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, + * 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 }; +} diff --git a/src/render/cesium/gpuIcons.test.mjs b/src/render/cesium/gpuIcons.test.mjs new file mode 100644 index 000000000..62303e262 --- /dev/null +++ b/src/render/cesium/gpuIcons.test.mjs @@ -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'); +}); diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js index cf7209dc4..ea8888b78 100644 --- a/src/render/cesium/harness.js +++ b/src/render/cesium/harness.js @@ -35,11 +35,17 @@ export const CESIUM_CHECKS = new Set([ 'credits.listenerRules', 'draw.atlas', 'draw.clampState', + 'draw.columns', + 'draw.columns.shown', 'draw.drillPick', 'draw.icons.distance', 'draw.icons.update', 'draw.ids', 'draw.models', + 'draw.motion', + 'draw.motion.arc', + 'draw.motion.climb', + 'draw.motion.live', 'draw.pick', 'draw.sets', '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. pointer: (r, type, x, y, extra) => pointerFeedOf(r)(type, x, y, extra), now: () => performance.now(), + // What a live motion clock reads. + wallTime: () => Date.now(), toEcef, tolerance: DEFAULT_TOLERANCE, flightPaths: 'endpoints', diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js index 7fb4056f7..80646da4a 100644 --- a/src/render/cesium/ports.js +++ b/src/render/cesium/ports.js @@ -17,6 +17,7 @@ import { createCesiumCamera } from './camera.js'; import { listenerList, toCartesian, uncaught } from './common.js'; import { createCesiumCredits } from './credits.js'; import { createCesiumDraw } from './draw.js'; +import { GPU_ICON_CAPABILITIES } from './gpuIcons.js'; import { createCesiumEffects } from './effects.js'; import { willDraw } from './frame.js'; import { createCesiumGlobe } from './globe.js'; @@ -58,6 +59,7 @@ const GLOBE_CAPABILITIES = [ export function cesiumCapabilities(scene, only) { const all = [ 'models', + ...GPU_ICON_CAPABILITIES, 'styles', 'bloom', 'sharpen', @@ -288,7 +290,7 @@ export function createCesiumPorts(widget, { capabilities, credentials = {} }) { // --- Draw ------------------------------------------------------------------ - const drawPart = createCesiumDraw({ scene, report }); + const drawPart = createCesiumDraw({ scene, report, capabilities }); const { port: draw, sets, tilesets } = drawPart; const cameraPart = createCesiumCamera({ scene, camera, report, widget }); @@ -415,6 +417,14 @@ export function createCesiumPorts(widget, { capabilities, credentials = {} }) { function iconState() { let loading = false; 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; if (!host || !host.show) continue; for (let i = 0; i < host.length; i++) { diff --git a/src/render/cesium/ports.test.mjs b/src/render/cesium/ports.test.mjs index e23b4c72c..041566b1c 100644 --- a/src/render/cesium/ports.test.mjs +++ b/src/render/cesium/ports.test.mjs @@ -10,6 +10,9 @@ import { updateCameraChanged } from './internals.js'; test('capabilities follow what the scene supports', () => { const effects = [ + 'columns', + 'motionSegments', + 'courseGlide', 'styles', 'bloom', 'sharpen',