diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index eb808bebd..4b54e2670 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1047,6 +1047,7 @@ "src/ui/applicationShell.js", "src/sky/starrySky.js", "src/render/cesium/effects.js", + "src/render/cesium/screenModulation.js", "src/render/cesium/globe.js", "src/render/baseTilesets.js", "src/render/cesium/imagery.js", @@ -1851,6 +1852,7 @@ "src/render/cesium/drawHit.js", "src/queries/heights.js", "src/render/cesium/effects.js", + "src/render/cesium/screenModulation.js", "src/render/cesium/draw.js", "src/render/cesium/drawQuads.js", "src/render/cesium/drawMeshes.js", @@ -3302,6 +3304,7 @@ "src/render/cesium/quality.js", "src/render/cesium/credits.js", "src/render/cesium/effects.js", + "src/render/cesium/screenModulation.js", "src/render/cesium/common.js", "src/render/cesium/camera.js", "src/render/cesium/cameraControls.js", diff --git a/src/cyberSonar.js b/src/cyberSonar.js index e4148a43c..e50369908 100644 --- a/src/cyberSonar.js +++ b/src/cyberSonar.js @@ -206,6 +206,71 @@ export function createCyberSonarSampler( }; } +// The contact tint: a cool grey outside the sector, warm inside it, each +// mixed in at this strength over the contact's own colour. +const CYBER_SONAR_DIM_RGB = [0.62, 0.68, 0.72]; +const CYBER_SONAR_LIT_RGB = [1, 0.84, 0.84]; +const CYBER_SONAR_TINT_STRENGTH = 0.72; +/** How far toward the warm tint contacts sit while the sweep is off. */ +const CYBER_SONAR_NEUTRAL_COVERAGE = 0.46; + +const hexOf = (rgb) => + `#${rgb + .map((c) => + Math.round(clamp01(c) * 255) + .toString(16) + .padStart(2, '0'), + ) + .join('')}`; + +/** + * The renderer's screen modulation sector for the Cyber contact sweep over + * a `width` x `height` CSS-pixel map: the same band `createCyberSonarSampler` + * samples. Not sweeping (Sonar OFF, reduced motion), a radius of 0 holds + * every contact at the neutral level the sweep rests at. + * @param {number} width + * @param {number} height + * @param {number} nowMs + * @param {{sweeping?: boolean, root?: object}} [options] + * @returns {import('./render/contract/effects').ModulationSector} + */ +export function cyberSonarSector( + width, + height, + nowMs, + { sweeping = true, root = globalThis.document?.documentElement } = {}, +) { + const settings = readCyberSonarSettings(root); + const floor = settings.opacity / 100; + const center = { x: width / 2, y: height / 2 }; + const widthRad = (settings.sector * Math.PI) / 180; + if (!sweeping) { + const coverage = floor >= 0.9999 ? 1 : CYBER_SONAR_NEUTRAL_COVERAGE; + return { + center, + angle: 0, + width: widthRad, + radius: 0, + floor: floor + (1 - floor) * CYBER_SONAR_NEUTRAL_COVERAGE, + strength: CYBER_SONAR_TINT_STRENGTH, + color: hexOf( + CYBER_SONAR_DIM_RGB.map( + (c, i) => c + (CYBER_SONAR_LIT_RGB[i] - c) * coverage, + ), + ), + }; + } + return { + center, + angle: (cyberSonarAngleDeg(nowMs) * Math.PI) / 180, + width: widthRad, + radius: (Math.min(width * 0.4, height * 0.52) * settings.range) / 100, + floor, + strength: CYBER_SONAR_TINT_STRENGTH, + color: hexOf(CYBER_SONAR_LIT_RGB), + }; +} + /** Remaining delay before the next contact-projection refresh is due. */ export function cyberSonarFrameDelay( lastPaintAt, diff --git a/src/render/cesium/effects.js b/src/render/cesium/effects.js index 9fe3342ea..50fe7ce0d 100644 --- a/src/render/cesium/effects.js +++ b/src/render/cesium/effects.js @@ -18,12 +18,17 @@ * * Building the port changes nothing in the scene; the first `bloom` call * takes the scene's bloom stage, and disposal gives it back as it was. - * There is no `screenModulation`: GEV's sweep shades each icon and label - * in its own shader, not the frame. + * `screenModulation` is no stage: it shades each marker in its own shader + * (`screenModulation.js`), so the map, lines and shapes draw as they are. + * Like the rest, it changes nothing in the scene until a sector is set. */ import * as Cesium from 'cesium'; import { provideUnboundEffects } from '../rendererOf.js'; import { listenerList, uncaught } from './common.js'; +import { + createCesiumScreenModulation, + screenModulationSupported, +} from './screenModulation.js'; /** Below this a style, bloom or sharpen draws nothing, so it runs no pass. */ const OFF = 0.001; @@ -136,6 +141,20 @@ export function createCesiumEffects( let disposed = false; const started = performance.now(); + /** Whether the modulation pass drew when listeners last heard. */ + let modulationListed = false; + const modulation = capabilities.has('screenModulation') + ? createCesiumScreenModulation(scene, { + frame, + // The pass stopped drawing on its own (a shader it cannot take). + onChange: () => { + if (gone() || modulation.draws() === modulationListed) return; + modulationListed = modulation.draws(); + listeners.fire(port.diagnostics()); + }, + }) + : null; + // Disposed, or the scene went first and took its stages with it. const gone = () => disposed || scene.isDestroyed?.() === true; @@ -332,6 +351,7 @@ export function createCesiumEffects( ? ['bloom'] : []), ...(sharpenStage?.enabled ? ['sharpen'] : []), + ...(modulation?.draws() ? ['screenModulation'] : []), ], }), on(event, cb) { @@ -340,6 +360,17 @@ export function createCesiumEffects( }, }; + if (modulation) + port.screenModulation = (sector) => { + if (gone()) return; + modulation.set(sector ?? null); + // Its own render demand: a sweep moving where nothing is shaded asks + // for no frame. Listeners hear when the pass starts or stops. + if (modulation.draws() === modulationListed) return; + modulationListed = modulation.draws(); + listeners.fire(port.diagnostics()); + }; + function assignParams(record, params) { for (const [key, value] of Object.entries(params ?? {})) { if (!(key in record.values)) continue; @@ -356,6 +387,7 @@ export function createCesiumEffects( disposed = true; stopClock(); listeners.clear(); + modulation?.dispose(); // A destroyed scene took its stages with it. if (scene.isDestroyed?.()) { styles.clear(); @@ -419,7 +451,12 @@ provideUnboundEffects((viewer) => { ) return null; return createCesiumEffects(scene, { - capabilities: new Set(['styles', 'bloom', 'sharpen']), + capabilities: new Set([ + 'styles', + 'bloom', + 'sharpen', + ...(screenModulationSupported() ? ['screenModulation'] : []), + ]), frame: sceneFrame(scene), report: uncaught, }); diff --git a/src/render/cesium/effects.test.mjs b/src/render/cesium/effects.test.mjs index f6b1bde51..c9f8a5dc8 100644 --- a/src/render/cesium/effects.test.mjs +++ b/src/render/cesium/effects.test.mjs @@ -388,3 +388,47 @@ test('a destroyed scene is let go of without touching it', () => { releaseUnboundEffects(viewer, effects); assert.equal(findEffects(viewer), null); }); + +test('screenModulation lists its pass while a sector is set, with change events', () => { + const none = fixture(); + assert.equal(none.effects.screenModulation, undefined, 'not without it'); + none.dispose(); + const event = () => ({ addEventListener: () => () => {} }); + const scene = { + postProcessStages: { add() {}, remove() {}, bloom: { uniforms: {} } }, + primitives: { update() {} }, + postUpdate: event(), + preRender: event(), + postRender: event(), + }; + const requests = []; + const part = createCesiumEffects(scene, { + capabilities: new Set(['screenModulation']), + frame: { requestRender: (reason) => requests.push(reason) }, + report: (error) => { + throw error; + }, + }); + const heard = []; + part.port.on('change', (d) => heard.push(d.passes)); + const sector = { + center: { x: 10, y: 10 }, + angle: 0, + width: 0.4, + radius: 100, + floor: 0.5, + strength: 0.5, + color: '#fff', + }; + part.port.screenModulation(sector); + assert.deepEqual(part.port.diagnostics().passes, ['screenModulation']); + part.port.screenModulation({ ...sector, angle: 1 }); + assert.deepEqual(heard, [['screenModulation']], 'heard once, as it starts'); + part.port.screenModulation(null); + assert.deepEqual(part.port.diagnostics().passes, []); + assert.deepEqual(heard, [['screenModulation'], []]); + assert.deepEqual(requests, ['effects-modulation', 'effects-modulation']); + part.port.screenModulation(sector); + part.dispose(); + assert.equal(scene.primitives.update.name, 'update', 'given back'); +}); diff --git a/src/render/cesium/harness.js b/src/render/cesium/harness.js index d6af0ab17..dedc020e7 100644 --- a/src/render/cesium/harness.js +++ b/src/render/cesium/harness.js @@ -65,7 +65,10 @@ export const CESIUM_CHECKS = new Set([ 'draw.shapes.drapedRotation', 'effects.crossfade', 'effects.defineStyle', + 'effects.screenModulation', + 'effects.screenModulation.pixels', 'effects.styles', + 'effects.withoutScreenModulation', 'effects.withoutStyles', 'frame.demand', 'frame.order', diff --git a/src/render/cesium/ports.js b/src/render/cesium/ports.js index e91b3ef44..2a115b3f7 100644 --- a/src/render/cesium/ports.js +++ b/src/render/cesium/ports.js @@ -23,6 +23,7 @@ import { willDraw } from './frame.js'; import { createCesiumGlobe } from './globe.js'; import { createCesiumQuery, queryCapabilities } from './query.js'; import { createCesiumQuality } from './quality.js'; +import { screenModulationSupported } from './screenModulation.js'; import { atEndOfTick, billboardLoadError, @@ -54,7 +55,8 @@ const GLOBE_CAPABILITIES = [ * to those it lists. Depth picks, height samples and ray casts all need * depth textures, which `sampleHeightSupported` and `pickPositionSupported` * report. Styles, bloom and sharpen are post-process stages every scene - * runs. + * runs; the screen modulation runs on the Cesium version it was tested + * against. * @param {object} scene * @param {Iterable} [only] * @returns {string[]} @@ -70,6 +72,8 @@ export function cesiumCapabilities(scene, only) { 'styles', 'bloom', 'sharpen', + // The marker sweep's command swap is tested against one Cesium version. + ...(screenModulationSupported() ? ['screenModulation'] : []), ...GLOBE_CAPABILITIES, ...queryCapabilities(scene), ]; diff --git a/src/render/cesium/ports.test.mjs b/src/render/cesium/ports.test.mjs index 17528f40f..722b96208 100644 --- a/src/render/cesium/ports.test.mjs +++ b/src/render/cesium/ports.test.mjs @@ -19,6 +19,7 @@ test('capabilities follow what the scene supports', () => { 'styles', 'bloom', 'sharpen', + 'screenModulation', 'photoreal', 'terrain', 'imageryOnTiles', diff --git a/src/render/cesium/screenModulation.js b/src/render/cesium/screenModulation.js new file mode 100644 index 000000000..45c2c4bff --- /dev/null +++ b/src/render/cesium/screenModulation.js @@ -0,0 +1,672 @@ +/** + * @module render/cesium/screenModulation + * @description The Cesium effects port's `screenModulation` + * (`src/render/contract/effects.d.ts`): a sweeping band over the drawn + * markers. It is not a full-screen stage, since the map, lines and shapes + * must draw as they are: each marker is shaded by where its anchor is on + * screen. + * + * - Points, billboards (labels among them) and icon sets: their draw + * commands in this scene's command list are swapped, as the scene's + * primitives update, for derived commands whose vertex shader runs the + * native one and then scales the colour by the band. `gl_Position` is + * left alone, so geometry and picks are unchanged (pick passes keep the + * native commands). Cesium has no public shader hook for these + * collections, so the swap is tested against one Cesium version + * (`SCREEN_MODULATION_CESIUM_VERSION`); on any other, or once a native + * shader it does not know turns up, it draws nothing and the pass is not + * listed. + * - Models: their colour is set each drawn frame, after every owner has + * written its own (the walk is the last `preRender` listener), and the + * owner's colour is given back when the sector goes. + * + * The band: full at `angle`, fading over the last part of `width` (at most + * 10 degrees, at most 42% of it) clockwise from there, and full inside a + * small disc at `center` (2.5% of `radius`). A marker's colour is pulled by + * `strength` toward a cool grey outside the band and toward `color` inside + * it; at a radius of 0 every marker is pulled toward `color`. Labels keep + * half of what the band takes away, and their backgrounds keep their + * colour. + * + * Render demand: a set asks for a frame, except one that changes nothing + * drawn: the same sector again, or one that only moves the angle (of a + * sweeping band) while the last drawn frame had no shaded marker in view. + * The sweep then needs no frames of its own; a frame drawn for anything + * else draws the latest sector. + */ +import * as Cesium from 'cesium'; +import { IconSetPrimitive } from './iconSetPrimitive.js'; + +/** The Cesium version the command swap is tested against. */ +export const SCREEN_MODULATION_CESIUM_VERSION = '1.138.0'; + +/** Whether this Cesium can draw the pass at all. */ +export const screenModulationSupported = () => + Cesium.VERSION === SCREEN_MODULATION_CESIUM_VERSION; + +/** The colour markers outside the band are pulled toward. */ +const DIM_TINT = Object.freeze([0.62, 0.68, 0.72]); +const FEATHER_DEG = 10; +const FEATHER_SHARE = 0.42; +/** The full disc at the centre, as a share of the radius. */ +const CORE_SHARE = 0.025; +const DEG = 180 / Math.PI; + +const clamp01 = (value) => Math.min(1, Math.max(0, value)); +const finite = (value, fallback = 0) => + Number.isFinite(Number(value)) ? Number(value) : fallback; + +/** + * A contract sector as the pass uses it: degrees, the colour as channels. + * @param {import('../contract/effects').ModulationSector} sector + */ +export function normalizeSector(sector) { + const color = + Cesium.Color.fromCssColorString(String(sector.color ?? '')) ?? + Cesium.Color.WHITE; + return { + cx: finite(sector.center?.x), + cy: finite(sector.center?.y), + angle: (((finite(sector.angle) * DEG) % 360) + 360) % 360, + width: Math.max(0, finite(sector.width) * DEG), + radius: Math.max(0, finite(sector.radius)), + floor: clamp01(finite(sector.floor, 1)), + strength: clamp01(finite(sector.strength)), + rgb: [color.red, color.green, color.blue], + }; +} + +/** Whether two normalized sectors differ in more than their angle. */ +const differsBeyondAngle = (a, b) => + !a || + !b || + a.cx !== b.cx || + a.cy !== b.cy || + a.width !== b.width || + a.radius !== b.radius || + a.floor !== b.floor || + a.strength !== b.strength || + a.rgb.some((c, i) => c !== b.rgb[i]); + +/** + * The band's factor and tint at CSS pixels, for what is shaded on the CPU + * (models). The GPU pass computes the same in its vertex shader. + * @param {ReturnType} s + */ +export function sectorSampler(s) { + const radiusSquared = s.radius * s.radius; + const feather = Math.min(FEATHER_DEG, s.width * FEATHER_SHARE); + const sweeping = s.radius > 0; + return { + floor: s.floor, + /** Equal for samplers that tint alike (the angle aside). */ + key: `${s.floor}|${s.strength}|${s.rgb.join(',')}|${sweeping}`, + at(x, y) { + if (!Number.isFinite(x) || !Number.isFinite(y)) return 1; + if (!sweeping) return s.floor; + const dx = x - s.cx; + const dy = y - s.cy; + const distanceSquared = dx * dx + dy * dy; + if (distanceSquared > radiusSquared) return s.floor; + if (distanceSquared < radiusSquared * CORE_SHARE * CORE_SHARE) return 1; + const delta = (((Math.atan2(dx, -dy) * DEG - s.angle) % 360) + 360) % 360; + if (delta > s.width) return s.floor; + return ( + s.floor + + (1 - s.floor) * Math.min(1, (s.width - delta) / (feather || 1)) + ); + }, + /** How far toward `color` (from the grey) a factor tints. */ + coverage(factor) { + if (!sweeping || s.floor >= 0.9999) return 1; + return clamp01((factor - s.floor) / (1 - s.floor)); + }, + tint(base, factor, out) { + const c = this.coverage(factor); + const k = s.strength; + out.red = + base.red * (1 - k) + (DIM_TINT[0] + (s.rgb[0] - DIM_TINT[0]) * c) * k; + out.green = + base.green * (1 - k) + (DIM_TINT[1] + (s.rgb[1] - DIM_TINT[1]) * c) * k; + out.blue = + base.blue * (1 - k) + (DIM_TINT[2] + (s.rgb[2] - DIM_TINT[2]) * c) * k; + return out; + }, + }; +} + +// Follow every public DrawCommand setter, including pick/shadow/culling flags. +// Copying native.dirty would keep derived pipelines dirty forever: the scene +// consumes our command, so it never clears that flag on the native command. +const commandProperties = Object.entries( + Object.getOwnPropertyDescriptors(Cesium.DrawCommand.prototype), +) + .filter( + ([key, descriptor]) => + descriptor.set && key !== 'shaderProgram' && key !== 'uniformMap', + ) + .map(([key]) => key); + +/** + * The derived command for `native`, kept in `record` across frames: every + * native field followed, its own program and the pass's uniforms. + */ +export function syncModulatedCommand( + native, + record, + program, + uniforms, + labelBackground, +) { + if (!record.command) { + record.command = new Cesium.DrawCommand(); + record.uniformMap = { + ...uniforms, + u_gevSonarLabelBackground: () => record.labelBackground, + }; + } + const command = record.command; + record.labelBackground = labelBackground; + // Uniform values (angle/viewport/etc.) change through stable callbacks, not + // new maps/functions. Owner callback replacement and removal still propagate. + for (const key in record.uniformMap) { + if ( + !(key in uniforms) && + key !== 'u_gevSonarLabelBackground' && + !(key in native.uniformMap) + ) { + delete record.uniformMap[key]; + command.dirty = true; + } + } + for (const key in native.uniformMap) { + if (record.uniformMap[key] !== native.uniformMap[key]) { + record.uniformMap[key] = native.uniformMap[key]; + command.dirty = true; + } + } + for (const key of commandProperties) command[key] = native[key]; + command.shaderProgram = program; + command.uniformMap = record.uniformMap; + return command; +} + +/** + * The native vertex shader with the band applied after it, or null for a + * shader the pass does not know. + * @param {object} source A Cesium ShaderSource. + * @param {'point'|'billboard'|'icon'} kind + */ +export function modulationVertexSource(source, kind) { + const text = source.sources.join('\n'); + const attribute = + kind === 'point' ? 'positionHighAndSize' : 'positionHighAndScale'; + const lowAttribute = + kind === 'point' ? 'positionLowAndOutline' : 'positionLowAndRotation'; + // Icon sets move rows on the GPU, so their shader publishes the anchor itself. + const anchorSource = + kind === 'icon' + ? 'iconAnchorClip' + : `czm_modelViewProjectionRelativeToEye * czm_translateRelativeToEye(${attribute}.xyz, ${lowAttribute}.xyz)`; + if ( + (kind === 'icon' + ? !text.includes('iconAnchorClip') + : !text.includes(attribute) || !text.includes(lowAttribute)) || + !text.includes('v_color') || + !/void\s+main\s*\(\s*\)/.test(text) + ) + return null; + const next = source.clone(); + next.sources = [ + text.replace(/void\s+main\s*\(\s*\)/, 'void gev_sonar_main()'), + ` +uniform vec4 u_gevSonar; // angle, radius, opacity floor, sweep enabled +uniform vec2 u_gevSonarViewport; +uniform vec2 u_gevSonarCenter; +uniform float u_gevSonarSector; +uniform vec4 u_gevSonarTint; // colour, strength +uniform float u_gevSonarLabelBackground; +void main() { + gev_sonar_main(); + // All corners/glyphs share the contact anchor, before native screen offsets. + // Leave gl_Position untouched so appearance never changes geometry or picks. + vec4 anchor = ${anchorSource}; + if (anchor.w <= 0.0) return; + vec2 pixel = anchor.xy / anchor.w * u_gevSonarViewport * 0.5 - u_gevSonarCenter; + float floorValue = u_gevSonar.z; + float factor = floorValue; + if (u_gevSonar.w > 0.5) { + float distanceSquared = dot(pixel, pixel); + float radiusSquared = u_gevSonar.y * u_gevSonar.y; + float delta = mod(degrees(atan(pixel.x, pixel.y)) - u_gevSonar.x + 360.0, 360.0); + if (delta > 359.9999) delta = 0.0; + if (distanceSquared < radiusSquared * ${(CORE_SHARE * CORE_SHARE).toFixed(6)}) factor = 1.0; + else if (distanceSquared <= radiusSquared && delta <= u_gevSonarSector) + factor += (1.0 - floorValue) * min(1.0, (u_gevSonarSector - delta) / max(min(${FEATHER_DEG.toFixed(1)}, u_gevSonarSector * ${FEATHER_SHARE}), 1e-4)); + } + #ifdef SDF + factor = (1.0 + factor) * 0.5; + #else + if (u_gevSonarLabelBackground > 0.5) factor = (1.0 + factor) * 0.5; + #endif + float coverage = (u_gevSonar.w < 0.5 || floorValue >= 0.9999) ? 1.0 : clamp((factor - floorValue) / (1.0 - floorValue), 0.0, 1.0); + if (u_gevSonarLabelBackground < 0.5) + v_color.rgb = v_color.rgb * (1.0 - u_gevSonarTint.a) + mix(vec3(${DIM_TINT.join(', ')}), u_gevSonarTint.rgb, coverage) * u_gevSonarTint.a; + // Apply before native fragment pass classification, never after main(). + v_color.a *= factor; + ${kind === 'point' ? 'v_outlineColor.a *= factor;' : kind === 'icon' ? '' : '#ifdef SDF\n v_outlineColor.a *= factor;\n #endif'} +} +`, + ]; + return next; +} + +/** + * Whether a command's batch may be in view: its bounds against the frame's + * culling planes (the far plane left out, as Cesium's frustum builder does, + * since a batch fits several frusta) and the horizon. + */ +export function isModulatedCommandVisible(command, frameState, culling) { + const bounds = command.boundingVolume; + if (!bounds || !command.cull) return true; + culling ??= new Cesium.CullingVolume( + frameState.cullingVolume.planes.slice(0, 5), + ); + if (culling.computeVisibility(bounds) === Cesium.Intersect.OUTSIDE) + return false; + return !( + frameState.mode === Cesium.SceneMode.SCENE3D && + frameState.occluder && + command.occlude && + bounds.isOccluded(frameState.occluder) + ); +} + +const alive = (value) => value && !value.isDestroyed?.(); + +/** + * Calls `visit(model, visible)` for each model under `primitive`, nested + * collections included, without walking the markers of any collection. + */ +export function visitModels(primitive, visit, visible = true) { + if (!alive(primitive)) return; + visible = visible && primitive.show !== false; + if (primitive instanceof Cesium.PrimitiveCollection) { + for (let i = 0; i < primitive.length; i++) + visitModels(primitive.get(i), visit, visible); + } else if (primitive instanceof Cesium.Model) { + visit(primitive, visible && primitive.ready); + } +} + +const sameColor = (a, b) => + a && + b && + a.red === b.red && + a.green === b.green && + a.blue === b.blue && + a.alpha === b.alpha; + +/** + * Model colours set by the pass, each over its owner's: a colour the owner + * writes since is the new base, and the owner's comes back on restore. + */ +export function createModelTint() { + const states = new Map(); + return { + get size() { + return states.size; + }, + /** Shades `model` by `factor` (models stay opaque: RGB dims, not alpha). */ + apply(model, factor, sampler) { + const current = model.color; + let state = states.get(model); + const owns = state && sameColor(current, state.applied); + if (!owns) { + const base = current + ? Cesium.Color.clone(current) + : new Cesium.Color(1, 1, 1, 1); + state = { + base, + undefinedBase: current === undefined, + applied: null, + factor: Number.NaN, + key: null, + }; + states.set(model, state); + } else if ( + Math.abs(factor - state.factor) <= 0.002 && + state.key === sampler.key + ) { + return; + } + const next = sampler.tint(state.base, factor, new Cesium.Color()); + next.red *= factor; + next.green *= factor; + next.blue *= factor; + // Keep models in their owner's opaque/translucent render pass. + next.alpha = state.base.alpha; + model.color = next; + // Cesium copies on set; compare against what it holds. + state.applied = Cesium.Color.clone(model.color ?? next); + state.factor = factor; + state.key = sampler.key; + }, + /** Gives `model` its owner's colour back, unless the owner wrote since. */ + restore(model) { + const state = states.get(model); + if (!state) return; + states.delete(model); + if (!alive(model)) return; + if (sameColor(model.color, state.applied)) + model.color = state.undefinedBase ? undefined : state.base; + }, + restoreAll() { + for (const model of [...states.keys()]) this.restore(model); + }, + keys: () => states.keys(), + }; +} + +/** + * @param {object} scene A Cesium scene. + * @param {{ + * frame: {requestRender: (reason?: string) => void}, + * onChange: () => void, + * }} options `onChange` runs when whether the pass draws changes on its own + * (a native shader it cannot take turns up). + */ +export function createCesiumScreenModulation(scene, { frame, onChange }) { + let sector = null; + let sampler = null; + let disposed = false; + let installed = null; + /** Whether the last drawn frame modulated a marker in view. */ + let lastVisible = false; + const stats = { + commands: 0, + visibleCommands: 0, + models: 0, + programs: 0, + supported: screenModulationSupported(), + error: null, + }; + + const uniforms = new Cesium.Cartesian4(); + const viewport = new Cesium.Cartesian2(); + const center = new Cesium.Cartesian2(); + const tint = new Cesium.Cartesian4(); + let width = 24; + const passUniforms = { + u_gevSonar: () => uniforms, + u_gevSonarViewport: () => viewport, + u_gevSonarCenter: () => center, + u_gevSonarSector: () => width, + u_gevSonarTint: () => tint, + }; + + const draws = () => !disposed && stats.supported && sector !== null; + + /** Installs the command swap and the model walk on first use. */ + function install() { + const root = scene.primitives; + const original = root.update; + const programs = new Map(); + let commands = new WeakMap(); + const culling = new Cesium.CullingVolume(); + const used = new Set(); + const replaced = []; + const models = createModelTint(); + const matrix = new Cesium.Matrix4(); + const position = new Cesium.Cartesian3(); + + const release = () => { + for (const { program } of programs.values()) + if (!program.isDestroyed()) program.destroy(); + programs.clear(); + commands = new WeakMap(); + used.clear(); + replaced.length = 0; + stats.programs = 0; + }; + + function fail(error) { + stats.supported = false; + stats.commands = 0; + stats.visibleCommands = 0; + stats.error = String(error?.message || error); + release(); + // The frame drawing now has shaded models; the next one gives them back. + frame.requestRender('effects-modulation'); + onChange(); + } + + const wrapped = function (frameState) { + const start = frameState.commandList.length; + original.call(this, frameState); + stats.commands = 0; + stats.visibleCommands = 0; + if (!frameState.passes.render || frameState.passes.pick) return; + if (!draws()) { + if (programs.size) release(); + return; + } + const ratioX = + scene.drawingBufferWidth / (scene.canvas?.clientWidth || 1) || 1; + const ratioY = + scene.drawingBufferHeight / (scene.canvas?.clientHeight || 1) || 1; + viewport.x = scene.drawingBufferWidth; + viewport.y = scene.drawingBufferHeight; + center.x = sector.cx * ratioX - viewport.x / 2; + center.y = viewport.y / 2 - sector.cy * ratioY; + uniforms.x = sector.angle; + uniforms.y = sector.radius * ratioX; + uniforms.z = sector.floor; + uniforms.w = sector.radius > 0 ? 1 : 0; + width = sector.width; + tint.x = sector.rgb[0]; + tint.y = sector.rgb[1]; + tint.z = sector.rgb[2]; + tint.w = sector.strength; + used.clear(); + replaced.length = 0; + if (frameState.cullingVolume) + for (let i = 0; i < 5; i++) + culling.planes[i] = frameState.cullingVolume.planes[i]; + try { + for (let i = start; i < frameState.commandList.length; i++) { + const native = frameState.commandList[i]; + const kind = + native.owner instanceof Cesium.PointPrimitiveCollection + ? 'point' + : native.owner instanceof Cesium.BillboardCollection + ? 'billboard' + : native.owner instanceof IconSetPrimitive + ? 'icon' + : null; + if (!kind || !native.shaderProgram || !native.uniformMap) continue; + const source = native.shaderProgram; + // Label backgrounds are non-SDF billboard batches. The version-tested + // engine pick association distinguishes them without enumerating + // labels or reaching into EntityCluster. One representative per draw + // batch; Cesium's label glyph/background collections are homogeneous. + const labelBackground = + kind === 'billboard' && + !source.vertexShaderSource.defines.includes('SDF') && + native.owner.length > 0 && + native.owner.get(0).pickPrimitive instanceof Cesium.Label + ? 1 + : 0; + let entry = programs.get(source); + if (!entry) { + const vertex = modulationVertexSource( + source.vertexShaderSource, + kind, + ); + if (!vertex) throw new Error('Unsupported native contact shader'); + const attributes = Object.fromEntries( + Object.entries(source.vertexAttributes).map(([name, value]) => [ + name, + value.index, + ]), + ); + const program = Cesium.ShaderProgram.fromCache({ + context: frameState.context, + vertexShaderSource: vertex, + fragmentShaderSource: source.fragmentShaderSource, + attributeLocations: attributes, + }); + // Compile while errors can still leave the whole native command + // slice intact, rather than stopping the render loop at draw time. + try { + void program.allUniforms; + } catch (error) { + program.destroy(); + throw error; + } + programs.set(source, (entry = { program })); + } + used.add(source); + let record = commands.get(native); + if (!record) commands.set(native, (record = {})); + const derived = syncModulatedCommand( + native, + record, + entry.program, + passUniforms, + labelBackground, + ); + replaced.push(i, native); + frameState.commandList[i] = derived; + stats.commands++; + if (isModulatedCommandVisible(native, frameState, culling)) + stats.visibleCommands++; + } + for (const [source, entry] of programs) + if (!used.has(source)) { + if (!entry.program.isDestroyed()) entry.program.destroy(); + programs.delete(source); + } + stats.programs = programs.size; + } catch (error) { + // Recover the original commands already replaced in this slice. + for (let i = 0; i < replaced.length; i += 2) + frameState.commandList[replaced[i]] = replaced[i + 1]; + fail(error); + } + }; + root.update = wrapped; + + let epoch = 0; + const epochs = new WeakMap(); + const shadeModels = () => { + if (!draws()) { + models.restoreAll(); + stats.models = 0; + return; + } + const cssWidth = scene.canvas?.clientWidth ?? 0; + const cssHeight = scene.canvas?.clientHeight ?? 0; + Cesium.Matrix4.multiply( + scene.camera.frustum.projectionMatrix, + scene.camera.viewMatrix, + matrix, + ); + epoch++; + let count = 0; + visitModels(scene.primitives, (model, visible) => { + if (!visible) { + models.restore(model); + return; + } + const p = Cesium.Matrix4.getTranslation(model.modelMatrix, position); + const w = + matrix[3] * p.x + matrix[7] * p.y + matrix[11] * p.z + matrix[15]; + const x = + (matrix[0] * p.x + matrix[4] * p.y + matrix[8] * p.z + matrix[12]) / + w; + const y = + (matrix[1] * p.x + matrix[5] * p.y + matrix[9] * p.z + matrix[13]) / + w; + if (w <= 0 || Math.abs(x) > 1.1 || Math.abs(y) > 1.1) return; + epochs.set(model, epoch); + models.apply( + model, + sampler.at((x + 1) * cssWidth * 0.5, (1 - y) * cssHeight * 0.5), + sampler, + ); + count++; + }); + // Out of view or gone since the last frame: the owner's colour back. + for (const model of [...models.keys()]) + if (epochs.get(model) !== epoch) models.restore(model); + stats.models = count; + }; + + // Owners write model colours in preRender (some after this was + // installed): shade after all of them and before the draw uploads, + // by taking the last preRender place again at every postUpdate. + let offShade = null; + const offUpdate = scene.postUpdate.addEventListener(() => { + offShade?.(); + offShade = scene.preRender.addEventListener(shadeModels); + }); + const offRendered = scene.postRender.addEventListener(() => { + lastVisible = draws() && (stats.visibleCommands > 0 || stats.models > 0); + }); + + return { + models, + dispose() { + offUpdate(); + offShade?.(); + offRendered(); + if (root.update === wrapped && !root.isDestroyed?.()) + root.update = original; + release(); + models.restoreAll(); + }, + }; + } + + return { + stats, + draws, + /** + * Sets or clears the sector. + * @param {import('../contract/effects').ModulationSector | null} next + */ + set(next) { + if (disposed || scene.isDestroyed?.()) return; + const previous = sector; + sector = next ? normalizeSector(next) : null; + sampler = sector ? sectorSampler(sector) : null; + if (sector && !installed && stats.supported) installed = install(); + if (!sector) { + lastVisible = false; + installed?.models.restoreAll(); + stats.models = 0; + if (previous) frame.requestRender('effects-modulation'); + return; + } + // The angle moves only a band that sweeps, and only shaded markers. + if ( + differsBeyondAngle(previous, sector) || + (lastVisible && sector.radius > 0 && sector.angle !== previous.angle) + ) + frame.requestRender('effects-modulation'); + }, + dispose() { + if (disposed) return; + disposed = true; + const had = sector; + sector = null; + if (installed && !scene.isDestroyed?.()) { + installed.dispose(); + // The last shaded frame is still on screen. + if (had) frame.requestRender('effects-modulation'); + } + installed = null; + }, + }; +} diff --git a/src/render/cesium/screenModulation.test.mjs b/src/render/cesium/screenModulation.test.mjs new file mode 100644 index 000000000..62927bbe2 --- /dev/null +++ b/src/render/cesium/screenModulation.test.mjs @@ -0,0 +1,608 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { + SCREEN_MODULATION_CESIUM_VERSION, + createCesiumScreenModulation, + createModelTint, + isModulatedCommandVisible, + modulationVertexSource, + normalizeSector, + sectorSampler, + syncModulatedCommand, + visitModels, +} from './screenModulation.js'; +import { createCyberSonarSampler, cyberSonarSector } from '../../cyberSonar.js'; + +const sweep = (extra = {}) => ({ + center: { x: 500, y: 400 }, + angle: 0, + width: (24 * Math.PI) / 180, + radius: 400, + floor: 0.84, + strength: 0.72, + color: '#ffd6d6', + ...extra, +}); + +test('stable commands reuse uniforms and derived pipelines while all native fields remain live', () => { + const native = new Cesium.DrawCommand({ + count: 6, + uniformMap: { value: () => 1 }, + }); + const record = {}, + program = {}, + uniforms = { u_gevSonar: () => 42 }; + const derived = syncModulatedCommand(native, record, program, uniforms, 0); + const map = derived.uniformMap; + derived.dirty = false; + derived.lastDirtyTime = 7; + assert.equal(native.dirty, true); + assert.equal( + syncModulatedCommand(native, record, program, uniforms, 1), + derived, + ); + assert.equal( + derived.dirty, + false, + 'stale native dirty flag must not rebuild pipelines', + ); + assert.equal(derived.lastDirtyTime, 7); + assert.equal(derived.uniformMap, map); + assert.equal(map.u_gevSonarLabelBackground(), 1); + for (const [key, value] of Object.entries({ + count: 12, + offset: 2, + instanceCount: 3, + pickId: 'pick', + pass: Cesium.Pass.TRANSLUCENT, + cull: false, + occlude: false, + castShadows: true, + receiveShadows: true, + pickOnly: true, + renderState: {}, + vertexArray: {}, + modelMatrix: Cesium.Matrix4.IDENTITY, + framebuffer: {}, + })) { + derived.dirty = false; + native[key] = value; + syncModulatedCommand(native, record, program, uniforms, 0); + assert.equal(derived[key], value, key); + assert.equal(derived.dirty, true, key); + } + native.uniformMap.value = () => 2; + syncModulatedCommand(native, record, program, uniforms, 0); + assert.equal(map.value(), 2); + native.uniformMap = { replacement: () => 3 }; + syncModulatedCommand(native, record, program, uniforms, 0); + assert.equal(map.value, undefined); + assert.equal(map.replacement(), 3); + assert.equal(map.u_gevSonar(), 42); + const nextProgram = {}; + syncModulatedCommand(native, record, nextProgram, uniforms, 0); + assert.equal(derived.shaderProgram, nextProgram); + assert.equal(native.shaderProgram, undefined); +}); + +test('the shader transform runs the native shader first, keeps geometry, and shades before fragment classification', () => { + assert.equal( + Cesium.VERSION, + SCREEN_MODULATION_CESIUM_VERSION, + 'engine upgrades require GPU revalidation', + ); + for (const [kind, attr, low] of [ + ['point', 'positionHighAndSize', 'positionLowAndOutline'], + ['billboard', 'positionHighAndScale', 'positionLowAndRotation'], + ]) { + const source = new Cesium.ShaderSource({ + defines: ['SDF'], + sources: [ + `in vec4 ${attr}; in vec4 ${low}; out vec4 v_color; void main() { v_color=vec4(1.); }`, + ], + }); + const original = source.sources[0]; + const next = modulationVertexSource(source, kind); + assert.equal(source.sources[0], original); + assert.notEqual(next, source); + assert.deepEqual(next.defines, ['SDF']); + assert.match(next.sources[0], /void gev_sonar_main/); + assert.match(next.sources[1], /v_color.a \*= factor/); + assert.match(next.sources[1], /u_gevSonarSector/); + assert.match(next.sources[1], /u_gevSonarCenter/); + assert.match(next.sources[1], /u_gevSonarTint/); + assert.ok( + next.sources[1].includes( + `czm_translateRelativeToEye(${attr}.xyz, ${low}.xyz)`, + ), + ); + assert.match(next.sources[1], /anchor.xy \/ anchor.w/); + assert.doesNotMatch(next.sources[1], /gl_Position\s*[=/]/); + } + assert.equal( + modulationVertexSource( + new Cesium.ShaderSource({ sources: ['void main() {}'] }), + 'point', + ), + null, + ); +}); + +test('render demand follows batch bounds, including horizon culling, without far-plane rejection', () => { + const planes = Array.from( + { length: 6 }, + (_, i) => new Cesium.Cartesian4(1, 0, 0, i), + ); + const frame = { + cullingVolume: { planes }, + mode: Cesium.SceneMode.SCENE3D, + occluder: {}, + }; + let intersections = 0; + let occluded = false; + const command = { + cull: true, + occlude: true, + boundingVolume: { + intersectPlane(plane) { + intersections++; + return plane.distance === 5 + ? Cesium.Intersect.OUTSIDE + : Cesium.Intersect.INSIDE; + }, + isOccluded() { + return occluded; + }, + }, + }; + assert.equal(isModulatedCommandVisible(command, frame), true); + assert.equal(intersections, 5); + occluded = true; + assert.equal(isModulatedCommandVisible(command, frame), false); + frame.mode = Cesium.SceneMode.SCENE2D; + assert.equal(isModulatedCommandVisible(command, frame), true); + command.boundingVolume.intersectPlane = () => Cesium.Intersect.OUTSIDE; + assert.equal(isModulatedCommandVisible(command, frame), false); + command.cull = false; + assert.equal(isModulatedCommandVisible(command, frame), true); + assert.equal(isModulatedCommandVisible({}, frame), true); +}); + +test('the CPU sampler of a sector matches the sweep it was made from', () => { + const values = { + cyberSonarOpacity: '62', + cyberSonarSector: '40', + cyberSonarRange: '110', + }; + const root = { dataset: values }; + for (const now of [0, 1234, 4100]) { + const reference = createCyberSonarSampler(1000, 800, now, root); + const sampler = sectorSampler( + normalizeSector(cyberSonarSector(1000, 800, now, { root })), + ); + for (let x = 0; x < 1000; x += 33) + for (let y = 0; y < 800; y += 31) + assert.ok( + Math.abs(sampler.at(x, y) - reference.at(x, y)) < 1e-9, + `${now} ${x},${y}`, + ); + for (const factor of [reference.floor, 0.9, 1]) { + const base = { red: 0.3, green: 0.6, blue: 0.9 }; + const a = reference.tint(base, factor, {}); + const b = sampler.tint(base, factor, {}); + for (const c of ['red', 'green', 'blue']) + assert.ok(Math.abs(a[c] - b[c]) < 0.003, `${factor} ${c}`); + } + } + // At rest the sweep holds every contact at the neutral level and tint. + const rest = sectorSampler( + normalizeSector(cyberSonarSector(1000, 800, 0, { root, sweeping: false })), + ); + const reference = createCyberSonarSampler(1000, 800, 0, root); + assert.ok(Math.abs(rest.at(10, 10) - reference.neutral) < 1e-9); + const base = { red: 0.3, green: 0.6, blue: 0.9 }; + const a = reference.tint(base, reference.neutral, {}); + const b = rest.tint(base, rest.at(10, 10), {}); + for (const c of ['red', 'green', 'blue']) + assert.ok(Math.abs(a[c] - b[c]) < 0.003, c); +}); + +test('model walk never enumerates native contact or EntityCluster records', () => { + const root = new Cesium.PrimitiveCollection(); + const points = root.add(new Cesium.PointPrimitiveCollection()); + points.add(); + points.get = () => { + throw new Error('must not enumerate contacts'); + }; + const cluster = root.add(new Cesium.EntityCluster()); + Object.defineProperty(cluster, '_billboardCollection', { + get() { + throw new Error('must not access cluster internals'); + }, + configurable: true, + }); + const seen = []; + visitModels(root, (...v) => seen.push(v)); + assert.equal(seen.length, 0); + delete cluster._billboardCollection; + root.destroy(); +}); + +test('models keep their render-pass alpha, and an owner colour written since survives restore', () => { + const sampler = sectorSampler(normalizeSector(sweep())); + const tint = createModelTint(); + const model = { color: new Cesium.Color(1, 0.5, 0.2, 1) }; + tint.apply(model, 0.5, sampler); + assert.equal(model.color.alpha, 1); + assert.ok(model.color.red < 1); + const owner = new Cesium.Color(0.2, 0.3, 0.4, 0.7); + model.color = owner; + tint.restore(model); + assert.equal(model.color, owner); + const shaded = { color: new Cesium.Color(0.2, 0.4, 0.8, 1) }; + tint.apply(shaded, 0.9, sampler); + tint.restore(shaded); + assert.deepEqual(shaded.color, new Cesium.Color(0.2, 0.4, 0.8, 1)); + const unset = {}; + tint.apply(unset, 0.5, sampler); + tint.restore(unset); + assert.equal(unset.color, undefined); +}); + +/** A scene of Cesium events, a primitives root and a frame port fake. */ +function fixture({ commands = [] } = {}) { + const primitives = new Cesium.PrimitiveCollection({ + destroyPrimitives: false, + }); + primitives.update = (frameState) => frameState.commandList.push(...commands); + const original = primitives.update; + const scene = { + primitives, + postUpdate: new Cesium.Event(), + preRender: new Cesium.Event(), + postRender: new Cesium.Event(), + canvas: { clientWidth: 1000, clientHeight: 800 }, + drawingBufferWidth: 2000, + drawingBufferHeight: 1600, + camera: { + frustum: { projectionMatrix: Cesium.Matrix4.IDENTITY }, + viewMatrix: Cesium.Matrix4.IDENTITY, + }, + }; + const requests = []; + let changes = 0; + const part = createCesiumScreenModulation(scene, { + frame: { requestRender: (reason) => requests.push(reason) }, + onChange: () => changes++, + }); + const draw = (passes = { render: true }) => { + scene.postUpdate.raiseEvent(); + scene.preRender.raiseEvent(); + const frameState = { commandList: [], passes }; + primitives.update(frameState); + scene.postRender.raiseEvent(); + return frameState.commandList; + }; + return { + scene, + primitives, + original, + part, + requests, + changes: () => changes, + draw, + }; +} + +test('setting nothing changes nothing in the scene', () => { + const f = fixture(); + assert.equal(f.primitives.update, f.original); + assert.equal(f.scene.postUpdate.numberOfListeners, 0); + assert.equal(f.part.draws(), false); + f.part.set(null); + assert.deepEqual(f.requests, []); + f.part.dispose(); + f.primitives.destroy(); +}); + +test('a set asks for a frame; moving the angle asks only while a shaded marker was in view', () => { + const points = new Cesium.PointPrimitiveCollection(); + const native = new Cesium.DrawCommand({ + owner: points, + uniformMap: {}, + shaderProgram: { + vertexShaderSource: new Cesium.ShaderSource({ + sources: [ + 'in vec4 positionHighAndSize; in vec4 positionLowAndOutline; out vec4 v_color; void main() {}', + ], + }), + vertexAttributes: {}, + fragmentShaderSource: new Cesium.ShaderSource({ + sources: ['void main() {}'], + }), + }, + cull: false, + }); + const commands = []; + const f = fixture({ commands }); + const fromCache = Cesium.ShaderProgram.fromCache; + Cesium.ShaderProgram.fromCache = () => ({ + allUniforms: {}, + isDestroyed: () => false, + destroy() {}, + }); + try { + f.part.set(sweep()); + assert.equal(f.part.draws(), true); + assert.deepEqual(f.requests, ['effects-modulation'], 'a first set asks'); + f.draw(); + f.part.set(sweep({ angle: 0.5 })); + assert.equal(f.requests.length, 1, 'nothing shaded: the angle asks none'); + f.part.set(sweep({ angle: 0.5, radius: 300 })); + assert.equal(f.requests.length, 2, 'anything else asks'); + commands.push(native); + const drawn = f.draw(); + assert.notEqual(drawn[0], native, 'the marker draws shaded'); + f.part.set(sweep({ angle: 1, radius: 300 })); + assert.equal(f.requests.length, 3, 'a marker in view: the angle asks'); + f.part.set(sweep({ angle: 1, radius: 300 })); + assert.equal(f.requests.length, 3, 'the same sector again asks none'); + f.part.set(sweep({ angle: 1, radius: 0 })); + assert.equal(f.requests.length, 4, 'resting the sweep asks'); + f.draw(); + f.part.set(sweep({ angle: 2, radius: 0 })); + assert.equal(f.requests.length, 4, 'a resting angle asks none'); + f.part.set(sweep({ angle: 1, radius: 300 })); + assert.equal(f.requests.length, 5); + assert.deepEqual( + f.draw({ render: false, pick: true }), + [native], + 'pick passes keep the native command', + ); + f.part.set(null); + assert.equal(f.requests.length, 6, 'clearing asks'); + assert.equal(f.part.draws(), false); + assert.deepEqual(f.draw(), [native], 'cleared: native commands'); + f.part.set(null); + assert.equal(f.requests.length, 6, 'clearing nothing asks none'); + f.part.set(sweep()); + f.part.dispose(); + assert.equal( + f.requests.length, + 8, + 'disposal draws the markers as they are', + ); + } finally { + Cesium.ShaderProgram.fromCache = fromCache; + f.part.dispose(); + assert.equal(f.primitives.update, f.original); + assert.equal(f.scene.postUpdate.numberOfListeners, 0); + assert.equal(f.scene.preRender.numberOfListeners, 0); + assert.equal(f.scene.postRender.numberOfListeners, 0); + points.destroy(); + f.primitives.destroy(); + } +}); + +test('the band is placed in drawing-buffer pixels from CSS pixels', () => { + const points = new Cesium.PointPrimitiveCollection(); + let uniforms = null; + const native = new Cesium.DrawCommand({ + owner: points, + uniformMap: {}, + shaderProgram: { + vertexShaderSource: new Cesium.ShaderSource({ + sources: [ + 'in vec4 positionHighAndSize; in vec4 positionLowAndOutline; out vec4 v_color; void main() {}', + ], + }), + vertexAttributes: {}, + fragmentShaderSource: new Cesium.ShaderSource({ + sources: ['void main() {}'], + }), + }, + cull: false, + }); + const f = fixture({ commands: [native] }); + const fromCache = Cesium.ShaderProgram.fromCache; + Cesium.ShaderProgram.fromCache = () => ({ + allUniforms: {}, + isDestroyed: () => false, + destroy() {}, + }); + try { + f.part.set( + sweep({ + center: { x: 600, y: 300 }, + angle: Math.PI / 2, + radius: 200, + floor: 0.5, + color: '#ff0000', + strength: 0.25, + }), + ); + uniforms = f.draw()[0].uniformMap; + const read = (name) => uniforms[name](); + assert.deepEqual( + [read('u_gevSonarCenter').x, read('u_gevSonarCenter').y], + [200, 200], + 'the centre offset, y up, at two buffer pixels per CSS pixel', + ); + const u = read('u_gevSonar'); + assert.deepEqual([u.x, u.y, u.z, u.w], [90, 400, 0.5, 1]); + assert.ok(Math.abs(read('u_gevSonarSector') - 24) < 1e-9); + const tint = read('u_gevSonarTint'); + assert.deepEqual([tint.x, tint.y, tint.z, tint.w], [1, 0, 0, 0.25]); + f.scene.canvas = { clientWidth: 500, clientHeight: 400 }; + f.draw(); + assert.deepEqual( + [read('u_gevSonarCenter').x, read('u_gevSonarCenter').y], + [1400, -400], + 'a resized canvas keeps the centre where the app put it', + ); + f.part.set(sweep({ radius: 0 })); + f.draw(); + assert.equal(read('u_gevSonar').w, 0, 'a radius of 0 holds the floor'); + } finally { + Cesium.ShaderProgram.fromCache = fromCache; + f.part.dispose(); + points.destroy(); + f.primitives.destroy(); + } +}); + +test('an unknown native shader stops the pass, keeps native commands and gives models back', () => { + const points = new Cesium.PointPrimitiveCollection(); + const command = { + owner: points, + uniformMap: {}, + shaderProgram: { + vertexShaderSource: new Cesium.ShaderSource({ + sources: ['void main() {}'], + }), + }, + }; + const f = fixture({ commands: [command] }); + const nativeColor = new Cesium.Color(0.2, 0.4, 0.8, 1); + const model = Object.create(Cesium.Model.prototype, { + ready: { value: true }, + show: { value: true }, + color: { value: nativeColor.clone(), writable: true }, + modelMatrix: { value: Cesium.Matrix4.IDENTITY }, + }); + f.primitives.add(model); + try { + f.part.set(sweep({ radius: 0 })); + const before = f.requests.length; + f.scene.postUpdate.raiseEvent(); + f.scene.preRender.raiseEvent(); + assert.notDeepEqual(model.color, nativeColor, 'the model is shaded'); + const frameState = { commandList: [], passes: { render: true } }; + f.primitives.update(frameState); + assert.equal(frameState.commandList[0], command); + assert.equal(f.part.stats.supported, false); + assert.match(f.part.stats.error, /Unsupported native contact shader/); + assert.equal(f.part.draws(), false); + assert.equal(f.changes(), 1, 'listeners hear the pass stop'); + assert.equal(f.requests.length, before + 1, 'one frame to give back'); + f.scene.postRender.raiseEvent(); + f.draw(); + assert.deepEqual(model.color, nativeColor, 'the model is given back'); + f.part.set(sweep({ angle: 2 })); + f.draw(); + assert.equal(f.part.stats.programs, 0, 'no retry'); + } finally { + f.part.dispose(); + points.destroy(); + f.primitives.destroy(); + } +}); + +test('program swaps, layer removal and late shader failure release only the pass resources', () => { + const points = new Cesium.PointPrimitiveCollection(); + const source = () => ({ + vertexShaderSource: new Cesium.ShaderSource({ + sources: [ + 'in vec4 positionHighAndSize; in vec4 positionLowAndOutline; out vec4 v_color; void main() {}', + ], + }), + vertexAttributes: {}, + fragmentShaderSource: new Cesium.ShaderSource({ + sources: ['void main() {}'], + }), + }); + const native = new Cesium.DrawCommand({ + owner: points, + uniformMap: {}, + shaderProgram: source(), + cull: false, + vertexArray: { generation: 1 }, + pickId: 'native-pick', + }); + const unknown = new Cesium.DrawCommand({ + owner: points, + uniformMap: {}, + shaderProgram: { + vertexShaderSource: new Cesium.ShaderSource({ + sources: ['void main() {}'], + }), + }, + }); + const commands = [native]; + const f = fixture({ commands }); + const fromCache = Cesium.ShaderProgram.fromCache; + const created = []; + Cesium.ShaderProgram.fromCache = () => { + const program = { + allUniforms: {}, + destroyed: false, + isDestroyed() { + return this.destroyed; + }, + destroy() { + assert.equal(this.destroyed, false); + this.destroyed = true; + }, + }; + created.push(program); + return program; + }; + try { + f.part.set(sweep()); + const first = f.draw()[0]; + assert.notEqual(first, native); + first.dirty = false; + assert.equal(f.draw()[0], first); + assert.equal(first.dirty, false); + assert.equal(created.length, 1, 'stable draws reuse the program'); + const buffer = { generation: 2 }; + native.vertexArray = buffer; + native.shaderProgram = source(); + const swapped = f.draw()[0]; + assert.equal(swapped, first); + assert.equal(swapped.vertexArray, buffer); + assert.equal(swapped.pickId, 'native-pick'); + assert.equal(swapped.shaderProgram, created[1]); + assert.equal(created[0].destroyed, true); + assert.equal(f.part.stats.programs, 1); + commands.length = 0; + f.draw(); + assert.equal(created[1].destroyed, true); + assert.equal(f.part.stats.programs, 0, 'removed layers keep no program'); + commands.push(native); + f.draw(); + f.part.set(null); + assert.equal(f.draw()[0], native); + assert.equal(created[2].destroyed, true, 'clearing releases the program'); + f.part.set(sweep()); + commands.push(unknown); + assert.deepEqual( + f.draw(), + commands, + 'a later failure rolls back earlier replacements in the same slice', + ); + assert.equal(created[3].destroyed, true); + assert.equal(f.part.stats.supported, false); + assert.equal(f.part.stats.programs, 0); + assert.equal(f.part.stats.commands, 0); + assert.equal(f.part.stats.visibleCommands, 0); + assert.deepEqual(f.draw(), commands); + assert.equal(created.length, 4, 'unsupported draws do not recompile'); + } finally { + f.part.dispose(); + Cesium.ShaderProgram.fromCache = fromCache; + points.destroy(); + f.primitives.destroy(); + } +}); + +test('disposal does not overwrite a successor update owner', () => { + const f = fixture(); + f.part.set(sweep()); + const successor = () => {}; + f.primitives.update = successor; + f.part.dispose(); + assert.equal(f.primitives.update, successor); + f.primitives.destroy(); +}); diff --git a/src/render/conformance/checks/ports.js b/src/render/conformance/checks/ports.js index 06b52b18d..450abc3d2 100644 --- a/src/render/conformance/checks/ports.js +++ b/src/render/conformance/checks/ports.js @@ -951,6 +951,131 @@ export function portChecks() { }, { capability: 'screenModulation' }, ), + check( + 'effects.screenModulation.pixels', + 'a marker in the band draws, one outside it dims to the floor, a radius of 0 dims every one', + async (h, r) => { + await overAustin(h, r); + const set = r.draw.icons({ id: 'conf:swept-pixels' }); + const pos = h.toEcef({ + lon: AUSTIN.lon + 0.004, + lat: AUSTIN.lat, + height: 0, + }); + const icon = { id: 'one', pos, image: DOT, size: [24, 24] }; + let s = null; + // The patch of the frame around the icon, once what is set has drawn. + const patch = async () => { + await drawn(h, r, 3); + await settled(r); + r.frame.renderNow(); + return r.readPixels({ + crop: { + x: Math.round(s.x) - 6, + y: Math.round(s.y) - 6, + width: 13, + height: 13, + }, + }).data; + }; + // How many pixels of `a` differ clearly from `b`. + const differ = (a, b) => { + let n = 0; + for (let i = 0; i < a.length; i += 4) + if ( + Math.abs(a[i] - b[i]) + + Math.abs(a[i + 1] - b[i + 1]) + + Math.abs(a[i + 2] - b[i + 2]) > + 90 + ) + n++; + return n; + }; + // The sweep stands 100 px left of the icon. Pointing right, the + // band's middle on the icon's bearing, it covers it; pointing left, + // not. + const sector = (extra) => ({ + center: { x: s.x - 100, y: s.y }, + angle: Math.PI / 2 - 0.3, + width: 0.6, + radius: 400, + floor: 0, + strength: 0, + color: '#ffffff', + ...extra, + }); + try { + set.set([icon]); + await drawn(h, r); + await settled(r); + s = r.query.project(pos); + ok(s, 'the icon projects'); + const shown = await patch(); + set.set([]); + const empty = await patch(); + const drawnPixels = differ(shown, empty); + if (drawnPixels < 20) + return { skip: 'this renderer draws no icon pixels' }; + set.set([icon]); + r.effects.screenModulation(sector()); + ok( + differ(await patch(), empty) >= drawnPixels * 0.8, + 'in the band the icon draws', + ); + r.effects.screenModulation(sector({ angle: Math.PI * 1.5 })); + ok( + differ(await patch(), empty) <= drawnPixels * 0.1, + 'outside the band it dims to a floor of 0', + ); + r.effects.screenModulation(sector({ radius: 0 })); + ok( + differ(await patch(), empty) <= drawnPixels * 0.1, + 'a radius of 0 dims it to the floor', + ); + r.effects.screenModulation(sector({ radius: 0, floor: 1 })); + ok( + differ(await patch(), empty) >= drawnPixels * 0.8, + 'at a floor of 1 nothing dims', + ); + r.effects.screenModulation(sector({ strength: 1, color: '#ff0000' })); + const tinted = await patch(); + let red = 0; + for (let i = 0; i < tinted.length; i += 4) + if (tinted[i] > 180 && tinted[i + 1] < 90 && tinted[i + 2] < 90) + red++; + ok(red >= drawnPixels * 0.5, 'a strength of 1 draws it in `color`'); + r.effects.screenModulation(null); + ok( + differ(await patch(), shown) <= drawnPixels * 0.1, + 'cleared, it draws as before', + ); + } finally { + r.effects.screenModulation(null); + set.dispose(); + } + }, + { capability: 'screenModulation' }, + ), + check( + 'effects.withoutScreenModulation', + 'without screenModulation the effects port has no such member', + async (h) => { + const r = await h.create({ + viewport: SCRIPT_VIEWPORT, + capabilities: CAPABILITIES.filter((c) => c !== 'screenModulation'), + }); + if (!r) return { skip: 'this harness cannot drop capabilities' }; + try { + equal(r.effects.screenModulation, undefined, 'no member'); + ok( + !r.effects.diagnostics().passes.includes('screenModulation'), + 'no pass', + ); + } finally { + r.destroy(); + } + }, + ), check( 'draw.motion', 'icons move by their segments on the set\u2019s motion clock', diff --git a/src/render/stub/stub.test.mjs b/src/render/stub/stub.test.mjs index 09b34b0fd..1b31f60c0 100644 --- a/src/render/stub/stub.test.mjs +++ b/src/render/stub/stub.test.mjs @@ -19,12 +19,13 @@ test('the stub passes the conformance suite', async () => { const skipped = report.results .filter((r) => r.status === 'skip') .map((r) => r.id); - // Its camera takes no user gestures: the drag and wheel scripts are for - // a camera that does (a controller over it, say). - assert.deepEqual( - skipped, - CAMERA_SCRIPTS.filter(usesInput).map((s) => `camera.trace.${s.name}`), - ); + // It draws only models into pixels, so the sweep's pixels go unread; its + // camera takes no user gestures: the drag and wheel scripts are for a + // camera that does (a controller over it, say). + assert.deepEqual(skipped, [ + 'effects.screenModulation.pixels', + ...CAMERA_SCRIPTS.filter(usesInput).map((s) => `camera.trace.${s.name}`), + ]); }); test('a frame runs the contract’s steps in order', () => {