Merge branch 'sameh/renderer-sonar' into sameh/renderer-seam

This commit is contained in:
Sameh Khamis committed 2026-11-09 06:04:07 -08:00
commit 4fc7d66639
17 files changed
+1989 -1100

No files matched your search

+3 -1
View File
@@ -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",
@@ -3234,7 +3236,6 @@
"src/hudLayouts.js",
"src/hudLayoutPolicy.js",
"src/ui/radioPanelPlacement.js",
"src/cyberSonarGpu.js",
"src/render/cesium/iconSetPrimitive.js",
"src/data/iconSet.js",
"src/data/iconSegment.js",
@@ -3302,6 +3303,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",
+3
View File
@@ -18,6 +18,9 @@ import { cameraOf } from '../render/cesium/camera.js';
// panel, Import and others): a viewer with no renderer bound gets its globe
// port from here, as it gets its camera.
import '../render/cesium/globe.js';
// The application's data reaches `findEffects` (the cyber contact sweep):
// such a viewer gets its effects port from here too.
import '../render/cesium/effects.js';
import { annotationsFromParams, createView } from '../view/index.js';
const EMBED_VIEW_MESSAGE = 'gev:view';
+65
View File
@@ -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,
-304
View File
@@ -1,304 +0,0 @@
import * as Cesium from 'cesium';
import { IconSetPrimitive } from './render/cesium/iconSetPrimitive.js';
// Narrow, version-tested engine adapter. Cesium has no public custom shader
// option for native point/billboard collections. Do not patch its prototypes or
// access EntityCluster's private collections. An engine upgrade must revalidate
// this adapter; unsupported versions keep the original commands unchanged.
export const CYBER_SONAR_CESIUM_VERSION = '1.138.0';
// 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);
export function syncCyberSonarCommand(
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;
}
export function sonarVertexSource(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 float u_gevSonarSector;
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;
float floorValue = u_gevSonar.z;
float factor = floorValue + (1.0 - floorValue) * 0.46;
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;
factor = floorValue;
if (distanceSquared < radiusSquared * 0.000625) factor = 1.0;
else if (distanceSquared <= radiusSquared && delta <= u_gevSonarSector)
factor += (1.0 - floorValue) * min(1.0, (u_gevSonarSector - delta) / min(10.0, u_gevSonarSector * 0.42));
}
#ifdef SDF
factor = (1.0 + factor) * 0.5;
#else
if (u_gevSonarLabelBackground > 0.5) factor = (1.0 + factor) * 0.5;
#endif
float coverage = 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 * 0.28 + (vec3(0.62, 0.68, 0.72) + vec3(0.38, 0.16, 0.12) * coverage) * 0.72;
// 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;
}
// Use native batch bounds, never individual contacts, for idle render demand.
// Like Cesium's frustum builder, exclude the far plane (it fits multiple frusta).
export function isCyberSonarCommandVisible(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)
);
}
/** Work scales with draw commands, not the number of contacts in a collection.
* Source programs, colors, pick IDs, render states and other scenes stay owned
* by Cesium. Only this scene's rendered command slice receives derived shaders.
*/
export function createCyberSonarGpu(scene, readFrame) {
const root = scene.primitives;
const original = root.update;
const programs = new Map();
let commands = new WeakMap();
let disposed = false;
const stats = {
commands: 0,
visibleCommands: 0,
programs: 0,
supported: Cesium.VERSION === CYBER_SONAR_CESIUM_VERSION,
error: null,
};
const uniforms = new Cesium.Cartesian4();
const viewport = new Cesium.Cartesian2();
let sector = 24;
const sonarUniforms = {
u_gevSonar: () => uniforms,
u_gevSonarViewport: () => viewport,
u_gevSonarSector: () => sector,
};
const culling = new Cesium.CullingVolume();
const used = new Set();
const replaced = [];
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;
};
const wrapped = function (frameState) {
const start = frameState.commandList.length;
original.call(this, frameState);
stats.commands = 0;
stats.visibleCommands = 0;
if (
disposed ||
!stats.supported ||
!frameState.passes.render ||
frameState.passes.pick
)
return;
const frame = readFrame();
if (!frame.enabled) {
if (programs.size) release();
return;
}
viewport.x = scene.drawingBufferWidth;
viewport.y = scene.drawingBufferHeight;
uniforms.x = frame.angle;
uniforms.y =
(Math.min(viewport.x * 0.4, viewport.y * 0.52) * frame.range) / 100;
uniforms.z = frame.opacity / 100;
uniforms.w = frame.active ? 1 : 0;
sector = frame.sector;
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 = sonarVertexSource(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 viewer's 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 = syncCyberSonarCommand(
native,
record,
entry.program,
sonarUniforms,
labelBackground,
);
replaced.push(i, native);
frameState.commandList[i] = derived;
stats.commands++;
if (isCyberSonarCommandVisible(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];
stats.supported = false;
stats.commands = 0;
stats.visibleCommands = 0;
stats.error = String(error?.message || error);
release();
}
};
root.update = wrapped;
return {
stats,
destroy() {
if (disposed) return;
disposed = true;
if (root.update === wrapped && !root.isDestroyed?.())
root.update = original;
release();
},
};
}
-354
View File
@@ -1,354 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
createCyberSonarGpu,
sonarVertexSource,
CYBER_SONAR_CESIUM_VERSION,
isCyberSonarCommandVisible,
syncCyberSonarCommand,
} from './cyberSonarGpu.js';
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 = syncCyberSonarCommand(native, record, program, uniforms, 0);
const map = derived.uniformMap;
derived.dirty = false;
derived.lastDirtyTime = 7;
assert.equal(native.dirty, true);
assert.equal(
syncCyberSonarCommand(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;
syncCyberSonarCommand(native, record, program, uniforms, 0);
assert.equal(derived[key], value, key);
assert.equal(derived.dirty, true, key);
}
native.uniformMap.value = () => 2;
syncCyberSonarCommand(native, record, program, uniforms, 0);
assert.equal(map.value(), 2);
native.uniformMap = { replacement: () => 3 };
syncCyberSonarCommand(native, record, program, uniforms, 0);
assert.equal(map.value, undefined);
assert.equal(map.replacement(), 3);
assert.equal(map.u_gevSonar(), 42);
const nextProgram = {};
syncCyberSonarCommand(native, record, nextProgram, uniforms, 0);
assert.equal(derived.shaderProgram, nextProgram);
assert.equal(native.shaderProgram, undefined);
});
test('GPU shader transform is isolated, settings-driven, and precedes native fragment classification', () => {
assert.equal(
Cesium.VERSION,
CYBER_SONAR_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 = sonarVertexSource(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], /floorValue \+ \(1.0 - floorValue\) \* 0.46/);
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(
sonarVertexSource(
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(isCyberSonarCommandVisible(command, frame), true);
assert.equal(intersections, 5);
occluded = true;
assert.equal(isCyberSonarCommandVisible(command, frame), false);
frame.mode = Cesium.SceneMode.SCENE2D;
assert.equal(isCyberSonarCommandVisible(command, frame), true);
command.boundingVolume.intersectPlane = () => Cesium.Intersect.OUTSIDE;
assert.equal(isCyberSonarCommandVisible(command, frame), false);
command.cull = false;
assert.equal(isCyberSonarCommandVisible(command, frame), true);
assert.equal(isCyberSonarCommandVisible({}, frame), true);
});
test('adapter never walks contacts, touches other scenes, or transforms pick-only passes', () => {
let calls = 0;
const original = function (fs) {
assert.equal(this, root);
calls++;
fs.commandList.push({ owner: {}, id: 'terrain' });
};
const root = { update: original };
const other = { update: original };
const adapter = createCyberSonarGpu({ primitives: root }, () => ({
enabled: false,
}));
const frame = { commandList: [], passes: { render: true, pick: false } };
root.update(frame);
assert.equal(calls, 1);
assert.equal(frame.commandList[0].id, 'terrain');
assert.equal(other.update, original);
root.update({ commandList: [], passes: { render: false, pick: true } });
assert.equal(calls, 2);
adapter.destroy();
adapter.destroy();
assert.equal(root.update, original);
});
test('unknown native shaders fail closed without losing native commands', () => {
const points = new Cesium.PointPrimitiveCollection();
const command = {
owner: points,
uniformMap: {},
shaderProgram: {
vertexShaderSource: new Cesium.ShaderSource({
sources: ['void main() {}'],
}),
},
};
const root = {
update(fs) {
fs.commandList.push(command);
},
};
const adapter = createCyberSonarGpu(
{ primitives: root, drawingBufferWidth: 800, drawingBufferHeight: 600 },
() => ({
enabled: true,
active: true,
angle: 0,
range: 100,
opacity: 84,
sector: 24,
}),
);
const frame = { commandList: [], passes: { render: true } };
root.update(frame);
assert.equal(frame.commandList[0], command);
assert.equal(adapter.stats.supported, false);
assert.match(adapter.stats.error, /Unsupported native contact shader/);
assert.equal(adapter.stats.programs, 0);
adapter.destroy();
points.destroy();
});
test('program swaps, layer removal and late shader failure release only adapter 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() {}'],
}),
},
});
let nativeCommands = [native];
let enabled = true;
const root = {
update(frame) {
frame.commandList.push(...nativeCommands);
},
};
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;
};
const adapter = createCyberSonarGpu(
{ primitives: root, drawingBufferWidth: 800, drawingBufferHeight: 600 },
() => ({
enabled,
active: true,
angle: 0,
range: 100,
opacity: 84,
sector: 24,
}),
);
const draw = () => {
const frame = { commandList: [], passes: { render: true } };
root.update(frame);
return frame.commandList;
};
try {
const first = draw()[0];
assert.notEqual(first, native);
first.dirty = false;
assert.equal(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 = 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(adapter.stats.programs, 1);
nativeCommands = [];
draw();
assert.equal(created[1].destroyed, true);
assert.equal(
adapter.stats.programs,
0,
'disabled layers retain no adapter program',
);
nativeCommands = [native];
draw();
enabled = false;
assert.equal(draw()[0], native);
assert.equal(
created[2].destroyed,
true,
'theme/cockpit exit releases the derived program',
);
enabled = true;
nativeCommands = [native, unknown];
assert.deepEqual(
draw(),
nativeCommands,
'a later failure rolls back earlier replacements in the same slice',
);
assert.equal(created[3].destroyed, true);
assert.equal(adapter.stats.supported, false);
assert.equal(adapter.stats.programs, 0);
assert.equal(adapter.stats.commands, 0);
assert.equal(adapter.stats.visibleCommands, 0);
assert.deepEqual(draw(), nativeCommands);
assert.equal(
created.length,
4,
'unsupported draws do not retry compilation',
);
} finally {
adapter.destroy();
Cesium.ShaderProgram.fromCache = fromCache;
points.destroy();
}
});
test('disposal does not overwrite a successor update owner', () => {
const root = { update() {} };
const adapter = createCyberSonarGpu({ primitives: root }, () => ({
enabled: false,
}));
const successor = () => {};
root.update = successor;
adapter.destroy();
assert.equal(root.update, successor);
});
+131 -189
View File
@@ -1,211 +1,153 @@
import * as Cesium from 'cesium';
import { createCyberSonarGpu } from './cyberSonarGpu.js';
/**
* The Cyber contact sweep on the map's markers, through the renderer's
* `effects.screenModulation` (`src/render/contract/effects.d.ts`). This
* keeps the sweep's clock and settings; the renderer shades the markers.
*
* Each tick, before the renderer decides whether to draw: a change of the
* theme, the sweep, its settings or the map's size sets the sector at once;
* while sweeping, the sector moves to the current angle on every tick that
* draws anyway, and at least at the renderer's `sonarCadenceHz` (which then
* asks for a frame). Out of the theme the sector is cleared.
*
* A renderer without the capability, or one that does not list the pass
* once a sector is set, leaves markers as they are: the document's
* `cyberSonarGpu` says `unsupported`, so the HUD overlays skip their own
* sweep too, and the sonar status says so.
*
* The frame and effects ports are looked up once, when the scene is made:
* bind the renderer to the viewer before creating it.
*/
import {
applyCyberSonarPrimitive,
createCyberSonarSampler,
isCyberContactThemeActive,
isCyberContactSonarActive,
CYBER_SONAR_RENDER_INTERVAL_MS,
cyberSonarSector,
isCyberMapThemeActive,
isCyberSonarActive,
readCyberSonarSettings,
cyberSonarAngleDeg,
syncCyberSonarAnimation,
CYBER_SONAR_RENDER_INTERVAL_MS,
} from './cyberSonar.js';
import {
canvasOf,
findEffects,
findFrame,
rendererOf,
} from './render/rendererOf.js';
const alive = (value) => value && !value.isDestroyed?.();
const diagnostics = new WeakMap();
export const getCyberSonarSceneDiagnostics = (viewer) => ({
...diagnostics.get(viewer),
});
/** Sweep updates per second when the renderer's quality has no setting. */
export const CYBER_SONAR_DEFAULT_CADENCE_HZ =
1000 / CYBER_SONAR_RENDER_INTERVAL_MS;
const UNSUPPORTED_MESSAGE =
'Contact GPU unavailable. Native contacts remain visible.';
export function visitCyberSonarModels(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++)
visitCyberSonarModels(primitive.get(i), visit, visible);
} else if (primitive instanceof Cesium.Model) {
visit(primitive, primitive, 'model', visible && primitive.ready);
}
}
/** Native dots, icons and glyphs use GPU draw-command treatment. Models retain
* their existing reversible CPU color treatment without walking native records.
/**
* @param {object} viewer The scene object the renderer is bound to.
* @param {{subscribe?: Function}} [manager] Layer visibility changes ask
* for a frame, so markers shown or hidden draw with the sweep.
* @returns {() => void} Clears the sector and lets go.
*/
export function createCyberSonarScene(viewer, manager) {
const scene = viewer?.scene;
if (
!scene?.postUpdate?.addEventListener ||
!scene?.preRender?.addEventListener
)
return () => {};
const tracked = new Map();
const matrix = new Cesium.Matrix4();
const position = new Cesium.Cartesian3();
let epoch = 0,
timer = null,
disposed = false;
let sampler, width, height, active, count;
const stats = { contacts: 0, updateMs: 0, frames: 0 };
const root = globalThis.document?.documentElement;
const gpu = createCyberSonarGpu(scene, () => ({
...readCyberSonarSettings(),
enabled: isCyberContactThemeActive(),
active: isCyberContactSonarActive(),
angle: cyberSonarAngleDeg(performance.now()),
}));
stats.gpu = gpu.stats;
let gpuSupported = gpu.stats.supported;
diagnostics.set(viewer, stats);
const restore = (visual, state) => {
if (!alive(state.owner)) return;
for (const key of state.keys)
applyCyberSonarPrimitive(visual, 1, false, undefined, key);
const frame = findFrame(viewer);
if (!frame) return () => {};
const effects = findEffects(viewer);
const doc = globalThis.document;
const root = doc?.documentElement;
let failed = typeof effects?.screenModulation !== 'function';
let current = null;
let key = null;
let lastSetAt = Number.NEGATIVE_INFINITY;
let interval = CYBER_SONAR_RENDER_INTERVAL_MS;
let disposed = false;
const readCadence = () => {
const hz = Number(rendererOf(viewer)?.quality?.get?.()?.sonarCadenceHz);
interval = 1000 / (hz > 0 ? hz : CYBER_SONAR_DEFAULT_CADENCE_HZ);
};
const visit = (visual, owner, kind, visible) => {
let state = tracked.get(visual);
if (!visible) {
if (state) {
restore(visual, state);
tracked.delete(visual);
}
return;
}
let p = visual.position;
if (kind === 'model')
p = Cesium.Matrix4.getTranslation(visual.modelMatrix, position);
else if (
p &&
owner.modelMatrix &&
!Cesium.Matrix4.equals(owner.modelMatrix, Cesium.Matrix4.IDENTITY)
)
p = Cesium.Matrix4.multiplyByPoint(owner.modelMatrix, p, position);
if (!p) return;
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;
if (!state) {
state = {
owner,
keys:
kind === 'label'
? ['fillColor', 'outlineColor', 'backgroundColor']
: kind === 'marker' && visual.outlineColor
? ['color', 'outlineColor']
: ['color'],
epoch,
};
tracked.set(visual, state);
}
state.epoch = epoch;
const factor = active
? sampler.at((x + 1) * width * 0.5, (1 - y) * height * 0.5)
: sampler.neutral;
for (const key of state.keys) {
if (key === 'outlineColor' && visual.outlineWidth === 0) continue;
if (key === 'backgroundColor' && !visual.showBackground) continue;
applyCyberSonarPrimitive(
visual,
kind === 'label' ? sampler.label(factor) : factor,
true,
sampler,
key,
kind === 'model',
);
}
count++;
};
const update = () => {
if (disposed) return;
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
if (!isCyberContactThemeActive()) {
for (const [visual, state] of tracked) restore(visual, state);
tracked.clear();
stats.contacts = 0;
stats.updateMs = 0;
return;
}
const started = performance.now();
width = scene.canvas.clientWidth;
height = scene.canvas.clientHeight;
sampler = createCyberSonarSampler(width, height, started);
active = isCyberContactSonarActive();
Cesium.Matrix4.multiply(
scene.camera.frustum.projectionMatrix,
scene.camera.viewMatrix,
matrix,
);
epoch++;
count = 0;
visitCyberSonarModels(scene.primitives, visit);
for (const [visual, state] of tracked)
if (state.epoch !== epoch) {
restore(visual, state);
tracked.delete(visual);
}
stats.contacts = count;
stats.updateMs = performance.now() - started;
stats.frames++;
// No contacts, no scanner-owned render demand. In continuous scenes the
// next rendered frame cancels this timer; parked scenes refresh at fleet
// cadence. Idle update-only ticks must not continually postpone the timer.
};
let removeRender;
// Aircraft fleet writers run in preRender, while tracked models and entity
// visualizers update earlier. Compose AFTER all those owners and BEFORE
// Cesium uploads primitive attributes for this draw. Requeue at postUpdate
// so writers installed later (enable/re-enable/track) cannot overwrite sonar.
// This only reorders one callback; the contact walk runs once per actual draw.
const removeUpdate = scene.postUpdate.addEventListener(() => {
if (isCyberSonarActive()) syncCyberSonarAnimation();
const supportChanged = gpuSupported !== gpu.stats.supported;
gpuSupported = gpu.stats.supported;
const support = gpu.stats.supported ? 'supported' : 'unsupported';
const publish = () => {
const support = failed ? 'unsupported' : 'supported';
if (root?.dataset && root.dataset.cyberSonarGpu !== support)
root.dataset.cyberSonarGpu = support;
// Shader setup runs after preRender's model tint. If it fails while the
// scene is parked (including Sonar OFF/reduced motion), draw once more so
// the now-unsupported contact path restores models before becoming idle.
if (supportChanged) scene.requestRender();
const status = globalThis.document?.getElementById?.('cyber-sonar-status');
const message = gpu.stats.supported
? ''
: 'Contact GPU unavailable. Native contacts remain visible.';
const status = doc?.getElementById?.('cyber-sonar-status');
const message = failed ? UNSUPPORTED_MESSAGE : '';
if (status && status.textContent !== message) status.textContent = message;
removeRender?.();
removeRender = scene.preRender.addEventListener(update);
});
const removePostRender = scene.postRender?.addEventListener(() => {
if (timer !== null) clearTimeout(timer);
timer = null;
if (isCyberContactSonarActive() && (count || gpu.stats.visibleCommands))
timer = setTimeout(() => {
timer = null;
if (!disposed && isCyberContactSonarActive()) scene.requestRender();
}, CYBER_SONAR_RENDER_INTERVAL_MS);
};
/** The renderer cannot draw the pass: markers stay as they are. */
const fail = () => {
if (failed) return;
failed = true;
const had = current;
current = null;
key = null;
if (had) effects.screenModulation(null);
publish();
};
const set = (sector, at) => {
const had = current;
// Before the call: its change listeners read `current`.
current = sector;
lastSetAt = at;
effects.screenModulation(sector);
// A first sector set but not listed is unsupported; a pass that stops
// later is caught by the change listener.
if (
sector &&
!had &&
!effects.diagnostics().passes.includes('screenModulation')
)
fail();
};
const offTick = frame.on('preUpdate', (t) => {
if (disposed) return;
// The HUD's own sweep keeps its clock whether or not markers are shaded.
const active = isCyberSonarActive();
if (active) syncCyberSonarAnimation();
if (failed) return;
const theme = isCyberMapThemeActive();
const sweeping = theme && active;
if (!theme) {
if (current) set(null, lastSetAt);
key = null;
return;
}
const canvas = canvasOf(viewer);
// The sector is in CSS pixels.
const width = canvas?.clientWidth ?? 0;
const height = canvas?.clientHeight ?? 0;
const settings = readCyberSonarSettings(root);
const next = `${sweeping}|${settings.range}|${settings.opacity}|${settings.sector}|${width}|${height}`;
const now = performance.now();
if (
next === key &&
!(sweeping && (now - lastSetAt >= interval || t.rendering))
)
return;
key = next;
readCadence();
set(cyberSonarSector(width, height, now, { sweeping, root }), now);
});
const offChange = failed
? null
: effects.on('change', (diagnostics) => {
if (current && !diagnostics.passes.includes('screenModulation')) fail();
});
const unsubscribe = manager?.subscribe?.((change) => {
if (change.type !== 'visibility') return;
scene.requestRender();
if (change.type === 'visibility') frame.requestRender('cyber-sonar');
});
publish();
return () => {
if (disposed) return;
disposed = true;
removeUpdate();
removeRender?.();
removePostRender?.();
gpu.destroy();
if (root?.dataset) delete root.dataset.cyberSonarGpu;
offTick();
offChange?.();
unsubscribe?.();
if (timer !== null) clearTimeout(timer);
for (const [visual, state] of tracked) restore(visual, state);
tracked.clear();
diagnostics.delete(viewer);
const had = current;
current = null;
if (had) effects.screenModulation(null);
if (root?.dataset) delete root.dataset.cyberSonarGpu;
};
}
+282 -240
View File
@@ -1,19 +1,16 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
CYBER_SONAR_RENDER_INTERVAL_MS,
applyCyberSonarSettings,
createCyberSonarSampler,
cyberSonarIntensityAtScreenPoint,
applyCyberSonarPrimitive,
applyCyberSonarSettings,
cyberSonarSector,
isCyberContactSonarActive,
isCyberSonarActive,
} from './cyberSonar.js';
import {
createCyberSonarScene,
visitCyberSonarModels,
getCyberSonarSceneDiagnostics,
} from './cyberSonarScene.js';
import { createCyberSonarScene } from './cyberSonarScene.js';
import { bindRenderer } from './render/rendererOf.js';
test('frame sampler matches reference without per-contact settings access', () => {
let reads = 0;
@@ -47,44 +44,7 @@ test('frame sampler matches reference without per-contact settings access', () =
);
});
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 = [];
visitCyberSonarModels(root, (...v) => seen.push(v));
assert.equal(seen.length, 0);
delete cluster._billboardCollection;
root.destroy();
});
test('models retain render-pass alpha and owner refresh survives teardown', () => {
const frame = createCyberSonarSampler(1000, 800, 0);
const model = { color: new Cesium.Color(1, 0.5, 0.2, 1) };
applyCyberSonarPrimitive(model, 0.5, true, frame, 'color', true);
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;
applyCyberSonarPrimitive(model, 1, false);
assert.equal(model.color, owner);
const unset = {};
applyCyberSonarPrimitive(unset, 0.5, true, frame, 'color', true);
applyCyberSonarPrimitive(unset, 1, false);
assert.equal(unset.color, undefined);
});
test('removed CSS mode cannot disable GPU contacts; unsupported adapters fail closed', () => {
test('removed CSS mode cannot disable GPU contacts; unsupported renderers fail closed', () => {
const root = { dataset: { uiTheme: 'cyber' }, style: { setProperty() {} } };
const options = {
root,
@@ -106,209 +66,291 @@ test('removed CSS mode cannot disable GPU contacts; unsupported adapters fail cl
assert.equal(isCyberContactSonarActive(options), false);
});
test('native owner colors remain untouched and scene teardown releases listeners', () => {
const previous = globalThis.document;
test('the sector is the sweep the HUD shows, in CSS pixels and radians', () => {
const root = {
dataset: {
cyberSonarOpacity: '62',
cyberSonarSector: '40',
cyberSonarRange: '110',
},
};
const s = cyberSonarSector(1000, 800, 1300, { root });
assert.deepEqual(s.center, { x: 500, y: 400 });
assert.ok(Math.abs(s.angle - Math.PI / 2) < 1e-9, 'a quarter period');
assert.ok(Math.abs(s.width - (40 * Math.PI) / 180) < 1e-12);
assert.ok(Math.abs(s.radius - 440) < 1e-9);
assert.equal(s.floor, 0.62);
assert.equal(s.strength, 0.72);
assert.equal(s.color, '#ffd6d6');
const rest = cyberSonarSector(1000, 800, 1300, { root, sweeping: false });
assert.equal(rest.radius, 0);
assert.ok(Math.abs(rest.floor - (0.62 + 0.38 * 0.46)) < 1e-12);
});
/**
* A document with the Cyber HUD shown, and a renderer fake bound to a
* viewer: its frame's preUpdate is ticked by hand and its effects record
* each sector.
*/
function fixture({ modulation = true, lists = true, cadenceHz } = {}) {
const previous = {
document: globalThis.document,
matchMedia: globalThis.matchMedia,
};
const root = { dataset: { uiTheme: 'cyber', cyberSonar: 'on' } };
let cockpit = false;
const status = { textContent: '' };
const state = { cockpit: false, reducedMotion: false };
globalThis.document = {
documentElement: root,
body: { classList: { contains: () => cockpit } },
getElementById: () => ({ classList: { contains: () => true } }),
body: { classList: { contains: () => state.cockpit } },
getElementById: (id) =>
id === 'cyber-sonar-status'
? status
: { classList: { contains: () => true } },
};
const primitives = new Cesium.PrimitiveCollection();
const points = primitives.add(new Cesium.PointPrimitiveCollection());
const point = points.add({ color: new Cesium.Color(0.3, 0.7, 0.5, 0.8) });
const original = primitives.update;
const scene = {
primitives,
postUpdate: new Cesium.Event(),
preRender: new Cesium.Event(),
postRender: new Cesium.Event(),
canvas: { clientWidth: 1000, clientHeight: 800 },
camera: {
frustum: { projectionMatrix: Cesium.Matrix4.IDENTITY },
viewMatrix: Cesium.Matrix4.IDENTITY,
globalThis.matchMedia = () => ({ matches: state.reducedMotion });
const ticks = new Set();
const changes = new Set();
const sets = [];
const requests = [];
let drawing = null;
const effects = {
diagnostics: () => ({
style: null,
passes: drawing && lists ? ['screenModulation'] : [],
}),
on(event, cb) {
changes.add(cb);
return () => changes.delete(cb);
},
requestRender() {},
};
const viewer = { scene };
const dispose = createCyberSonarScene(viewer);
try {
for (const enabled of ['on', 'off', 'on']) {
root.dataset.cyberSonar = enabled;
for (const opacity of [35, 84, 100]) {
root.dataset.cyberSonarOpacity = String(opacity);
point.color = new Cesium.Color(0.6, 0.4, 0.2, 0.7);
scene.postUpdate.raiseEvent();
scene.preRender.raiseEvent();
assert.equal(point.color.alpha, 0.7);
assert.equal(point.color.red, 0.6);
}
}
const previousTimeout = globalThis.setTimeout;
const previousClear = globalThis.clearTimeout;
let timers = 0;
globalThis.setTimeout = () => {
timers++;
return 1;
if (modulation)
effects.screenModulation = (sector) => {
const was = effects.diagnostics().passes.length;
drawing = sector;
sets.push(sector);
if (effects.diagnostics().passes.length !== was)
for (const cb of [...changes]) cb(effects.diagnostics());
};
globalThis.clearTimeout = () => {};
try {
const gpu = getCyberSonarSceneDiagnostics(viewer).gpu;
gpu.commands = 6;
gpu.visibleCommands = 0;
scene.postRender.raiseEvent();
assert.equal(timers, 0, 'culled batches must not schedule a sonar draw');
gpu.visibleCommands = 1;
scene.postRender.raiseEvent();
assert.equal(timers, 1, 'a visible batch keeps the sweep moving');
root.dataset.cyberSonar = 'off';
scene.postRender.raiseEvent();
assert.equal(timers, 1, 'OFF does not schedule contact draws');
} finally {
globalThis.setTimeout = previousTimeout;
globalThis.clearTimeout = previousClear;
}
cockpit = true;
scene.postUpdate.raiseEvent();
scene.preRender.raiseEvent();
root.dataset.uiTheme = 'tactical';
scene.postUpdate.raiseEvent();
scene.preRender.raiseEvent();
const canvas = { clientWidth: 1000, clientHeight: 800 };
const viewer = {};
const unbind = bindRenderer(viewer, {
canvas,
effects,
quality: { get: () => (cadenceHz ? { sonarCadenceHz: cadenceHz } : {}) },
frame: {
on(phase, cb) {
assert.equal(phase, 'preUpdate');
ticks.add(cb);
return () => ticks.delete(cb);
},
requestRender: (reason) => requests.push(reason),
},
});
return {
root,
status,
state,
sets,
requests,
canvas,
viewer,
ticks,
changes,
effects,
tick(rendering = false) {
for (const cb of [...ticks]) cb({ rendering });
},
restore() {
unbind();
globalThis.document = previous.document;
globalThis.matchMedia = previous.matchMedia;
},
};
}
test('a renderer without the capability leaves markers alone and says so', () => {
const f = fixture({ modulation: false });
try {
const dispose = createCyberSonarScene(f.viewer);
assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported');
assert.match(f.status.textContent, /Native contacts remain visible/);
f.tick(true);
assert.equal(f.changes.size, 0);
dispose();
dispose();
assert.equal(primitives.update, original);
assert.equal(scene.postUpdate.numberOfListeners, 0);
assert.equal(scene.preRender.numberOfListeners, 0);
assert.equal(scene.postRender.numberOfListeners, 0);
assert.equal(root.dataset.cyberSonarGpu, undefined);
assert.equal(f.ticks.size, 0);
assert.equal(f.root.dataset.cyberSonarGpu, undefined);
} finally {
dispose();
primitives.destroy();
globalThis.document = previous;
f.restore();
}
});
for (const reducedMotion of [false, true]) {
test(`shader failure requests one parked restoration draw with ${reducedMotion ? 'reduced motion' : 'Sonar OFF'}`, () => {
const previousDocument = globalThis.document;
const previousMatchMedia = globalThis.matchMedia;
const previousTimeout = globalThis.setTimeout;
const previousClear = globalThis.clearTimeout;
const root = {
dataset: { uiTheme: 'cyber', cyberSonar: reducedMotion ? 'on' : 'off' },
};
const status = { textContent: '' };
globalThis.document = {
documentElement: root,
body: { classList: { contains: () => false } },
getElementById: (id) =>
id === 'cyber-sonar-status'
? status
: { classList: { contains: () => true } },
};
globalThis.matchMedia = () => ({ matches: reducedMotion });
let scheduled = 0;
globalThis.setTimeout = () => {
scheduled++;
return 1;
};
globalThis.clearTimeout = () => {};
// A model-shaped fixture exercises the actual scene walk without loading a
// glTF or allocating a WebGL context. Rendering remains the browser gate.
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 },
});
const primitives = new Cesium.PrimitiveCollection({
destroyPrimitives: false,
});
primitives.add(model);
const points = new Cesium.PointPrimitiveCollection();
const nativeCommand = {
owner: points,
uniformMap: {},
shaderProgram: {
vertexShaderSource: new Cesium.ShaderSource({
sources: ['void main() {}'],
}),
},
};
primitives.update = (frame) => frame.commandList.push(nativeCommand);
let requests = 0;
const scene = {
primitives,
postUpdate: new Cesium.Event(),
preRender: new Cesium.Event(),
postRender: new Cesium.Event(),
canvas: { clientWidth: 1000, clientHeight: 800 },
drawingBufferWidth: 1000,
drawingBufferHeight: 800,
camera: {
frustum: { projectionMatrix: Cesium.Matrix4.IDENTITY },
viewMatrix: Cesium.Matrix4.IDENTITY,
},
requestRender() {
requests++;
},
};
const viewer = { scene };
const dispose = createCyberSonarScene(viewer);
try {
scene.postUpdate.raiseEvent();
scene.preRender.raiseEvent();
assert.notDeepEqual(
model.color,
nativeColor,
'Cyber neutral treatment precedes shader compilation',
);
const frame = { commandList: [], passes: { render: true } };
primitives.update(frame);
assert.equal(getCyberSonarSceneDiagnostics(viewer).gpu.supported, false);
assert.equal(frame.commandList[0], nativeCommand);
scene.postRender.raiseEvent();
assert.equal(
scheduled,
0,
'inactive sweep has no timer to perform recovery',
);
scene.postUpdate.raiseEvent();
assert.equal(root.dataset.cyberSonarGpu, 'unsupported');
assert.match(status.textContent, /Native contacts remain visible/);
assert.equal(
requests,
1,
'support loss explicitly wakes the parked scene',
);
scene.preRender.raiseEvent();
assert.deepEqual(
model.color,
nativeColor,
'the requested draw restores native model color',
);
assert.equal(getCyberSonarSceneDiagnostics(viewer).contacts, 0);
scene.postRender.raiseEvent();
for (let i = 0; i < 3; i++) scene.postUpdate.raiseEvent();
assert.equal(
requests,
1,
'unsupported idle ticks do not create a render loop',
);
assert.equal(scheduled, 0);
dispose();
scene.postUpdate.raiseEvent();
assert.equal(requests, 1, 'disposed callbacks cannot wake the scene');
} finally {
dispose();
points.destroy();
primitives.destroy();
globalThis.document = previousDocument;
globalThis.matchMedia = previousMatchMedia;
globalThis.setTimeout = previousTimeout;
globalThis.clearTimeout = previousClear;
}
});
}
test('the HUD sweep keeps its clock while markers cannot be shaded', () => {
const f = fixture({ modulation: false });
const animation = {
animationName: 'cyber-sonar-sweep',
playState: 'running',
startTime: 500,
effect: { updateTiming() {} },
};
f.root.querySelector = (selector) =>
selector === '.hud-sonar'
? { isConnected: true, getAnimations: () => [animation] }
: null;
try {
const dispose = createCyberSonarScene(f.viewer);
f.tick(false);
assert.equal(animation.startTime, 0);
assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported');
dispose();
} finally {
f.restore();
}
});
test('the sweep sets its sector on drawing ticks and at the cadence, and changes at once', () => {
const f = fixture();
const now = performance.now;
let clock = 1000;
performance.now = () => clock;
try {
const dispose = createCyberSonarScene(f.viewer);
assert.equal(f.root.dataset.cyberSonarGpu, 'supported');
assert.equal(f.status.textContent, '');
f.tick();
assert.equal(f.sets.length, 1, 'the theme sets a sector');
assert.deepEqual(f.sets[0], cyberSonarSector(1000, 800, 1000));
clock += 10;
f.tick(false);
assert.equal(f.sets.length, 1, 'an idle tick before the cadence sets none');
f.tick(true);
assert.equal(f.sets.length, 2, 'a tick that draws moves the angle');
assert.deepEqual(f.sets[1], cyberSonarSector(1000, 800, 1010));
clock += CYBER_SONAR_RENDER_INTERVAL_MS;
f.tick(false);
assert.equal(f.sets.length, 3, 'the cadence moves it on an idle tick');
f.canvas.clientWidth = 600;
f.tick(false);
assert.equal(f.sets.length, 4, 'a resize sets it at once');
assert.deepEqual(f.sets[3].center, { x: 300, y: 400 });
f.root.dataset.cyberSonar = 'off';
f.tick(false);
assert.equal(f.sets[4].radius, 0, 'Sonar OFF rests every contact');
clock += 1000;
f.tick(true);
f.tick(false);
assert.equal(f.sets.length, 5, 'at rest only changes set it');
f.root.dataset.cyberSonarOpacity = '50';
f.tick(false);
assert.equal(f.sets.length, 6);
assert.equal(f.sets[5].floor, 0.5 + 0.5 * 0.46);
f.state.cockpit = true;
f.tick(false);
assert.equal(f.sets[6], null, 'out of the map theme it clears');
f.tick(true);
assert.equal(f.sets.length, 7, 'cleared once');
f.state.cockpit = false;
f.root.dataset.cyberSonar = 'on';
f.state.reducedMotion = true;
f.tick(false);
assert.equal(f.sets[7].radius, 0, 'reduced motion rests the sweep');
f.state.reducedMotion = false;
f.root.dataset.uiTheme = 'tactical';
f.tick(false);
assert.equal(f.sets[8], null, 'another HUD style clears it');
f.tick(true);
assert.equal(f.sets.length, 9);
f.root.dataset.uiTheme = 'cyber';
f.tick(false);
assert.ok(f.sets[9]?.radius > 0, 'back in Cyber it sweeps at once');
assert.deepEqual(f.requests, [], 'the scene itself never asks for frames');
dispose();
assert.equal(f.sets[10], null, 'disposal clears it');
assert.equal(f.ticks.size, 0);
assert.equal(f.changes.size, 0);
assert.equal(f.root.dataset.cyberSonarGpu, undefined);
dispose();
assert.equal(f.sets.length, 11);
} finally {
performance.now = now;
f.restore();
}
});
test('the renderer cadence paces the idle sweep', () => {
const f = fixture({ cadenceHz: 4 });
const now = performance.now;
let clock = 0;
performance.now = () => clock;
try {
const dispose = createCyberSonarScene(f.viewer);
f.tick();
clock += CYBER_SONAR_RENDER_INTERVAL_MS;
f.tick();
assert.equal(f.sets.length, 1, '4 Hz waits 250 ms');
clock += 250 - CYBER_SONAR_RENDER_INTERVAL_MS;
f.tick();
assert.equal(f.sets.length, 2);
dispose();
} finally {
performance.now = now;
f.restore();
}
});
test('a sector the renderer does not list is unsupported: cleared, and the sweep stops', () => {
const f = fixture({ lists: false });
try {
const dispose = createCyberSonarScene(f.viewer);
f.tick(true);
assert.equal(f.sets.length, 2);
assert.equal(f.sets[1], null, 'cleared again');
assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported');
assert.match(f.status.textContent, /Native contacts remain visible/);
f.tick(true);
assert.equal(f.sets.length, 2, 'never set again');
dispose();
assert.equal(f.sets.length, 2);
} finally {
f.restore();
}
});
test('a pass the renderer stops drawing on its own stops the sweep', () => {
const f = fixture();
try {
const dispose = createCyberSonarScene(f.viewer);
f.tick(true);
assert.equal(f.sets.length, 1);
for (const cb of [...f.changes]) cb({ style: null, passes: [] });
assert.equal(f.root.dataset.cyberSonarGpu, 'unsupported');
assert.equal(f.sets.at(-1), null);
const count = f.sets.length;
f.tick(true);
assert.equal(f.sets.length, count);
dispose();
} finally {
f.restore();
}
});
test('layer visibility changes ask for a frame', () => {
const f = fixture();
let listener = null;
const manager = {
subscribe(cb) {
listener = cb;
return () => (listener = null);
},
};
try {
const dispose = createCyberSonarScene(f.viewer, manager);
listener({ type: 'visibility' });
listener({ type: 'data' });
assert.deepEqual(f.requests, ['cyber-sonar']);
dispose();
assert.equal(listener, null);
} finally {
f.restore();
}
});
+40 -3
View File
@@ -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,
});
+44
View File
@@ -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');
});
+3
View File
@@ -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',
+5 -1
View File
@@ -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<string>} [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),
];
+1
View File
@@ -19,6 +19,7 @@ test('capabilities follow what the scene supports', () => {
'styles',
'bloom',
'sharpen',
'screenModulation',
'photoreal',
'terrain',
'imageryOnTiles',
+672
View File
@@ -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<typeof normalizeSector>} 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;
},
};
}
+608
View File
@@ -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();
});
-2
View File
@@ -4,8 +4,6 @@
"src/app/embed.js",
"src/app/scene.js",
"src/app/viewer.js",
"src/cyberSonarGpu.js",
"src/cyberSonarScene.js",
"src/data/geoImportPins.js",
"src/layers/weather/shellRendering.js",
"src/layers/wind/gpuRendering.js",
+125
View File
@@ -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',
+7 -6
View File
@@ -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', () => {