mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-18 01:02:23 +00:00
Draw the aircraft family, Wildlife Sightings and the Cockpit through the contract
The layers that still had one Cesium and one Navara implementation, or
drew on Cesium only, now draw through engine.movers, engine.lines and
engine.camera on both engines, and application code holds the engine
instead of guessing it from a viewer.
- Aircraft family: flights, military and local ADS-B share one display
(src/layers/aircraft/render/display.js). The Cesium and Navara
renderers are gone. Where they differed, the display follows Cesium:
- attach and visibility tracking, live disableDepthTestDistance
changes, the tracked glyph's distance scale, model ids that change,
local ADS-B markers hidden until shown and its UAT ring as a point;
- the trail head's hidden alpha is 0.45, the contract's
depthFailAlpha scaled by the head's 0.9.
The tracked glyph stays over the fleet, as on Navara. The movers
contract reports readiness per model and reads model axes as the
glTF's own on every engine. Cesium's follow takes any native target
through a proxy entity in the ENU frame and mirrors its readout fields.
- Wildlife Sightings draws badges and the density glow as sprite sets
and its privacy cells as line outlines (no fill yet). It takes clicks
from engine.input and its card anchors to the engine's canvas and
camera, so the layer is in both engines' catalogs again and a switch
keeps the session's layer set.
- Cockpit: cockpitHost takes the engine only. The ridden aircraft is the
engine follow's target, hidden through its sprite; only the Cesium
Viewer's stock double-click is still routed around.
- About forty camera, navigation, share-link, HUD, voice, detection and
layer-lifecycle callers take the engine. isGlobeEngine and
engineFromViewer calls outside src/globe fall from 51 to 14.
The coupling baseline drops accordingly: layer renderer lines from
5239/12331 to 4546/11106 (Cesium/Navara), `viewer` lines from 2424 to
2209, Cesium-importing files from 69 to 66.
This commit is contained in:
1 parent
48988015f1
commit
35e70ec280
145 files changed
+4716
-4212
No files matched your search
@@ -1,425 +0,0 @@
|
||||
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../../data/aircraftModelLighting.js';
|
||||
// The aircraft renderer on Cesium (contract: ./contract.js): the Cesium
|
||||
// objects the aircraft layers draw with — the fleet BillboardCollection and its sprite-order slot, the model
|
||||
// PrimitiveCollection and its glTF loads, the tracked Entity (billboard with
|
||||
// per-frame CallbackProperties, followed through viewer.trackedEntity and
|
||||
// the one exact tracked frame), the trail entity and its live head
|
||||
// segment, and the camera/frame reads. Nothing here decides anything: the
|
||||
// layer's logic decides, this draws.
|
||||
|
||||
import * as Cesium from 'cesium';
|
||||
import { createTrail } from '../../../data/trailRenderer.js';
|
||||
import {
|
||||
registerSpriteCollection,
|
||||
restoreSpriteOrder,
|
||||
restoreSpriteOrderOnEnable,
|
||||
} from '../../../data/spriteOrder.js';
|
||||
import { horizonOccluder } from '../../../data/iconOrientation.js';
|
||||
import { engineFromViewer } from '../../../globe/cesium/engineFromViewer.js';
|
||||
import { applyTrackedCameraFrame } from '../../../globe/cesium/follow.js';
|
||||
|
||||
// The model shader of the IR boost: boosted
|
||||
// models render UNLIT so a side-lit airframe does not go black in FLIR/NVG.
|
||||
// Assigning a customShader to a ready model is a silent no-op, so the layer
|
||||
// reloads boosted models and the shader is set at creation. One stateless
|
||||
// instance, shared.
|
||||
let unlitShader = null;
|
||||
const irUnlitShader = () =>
|
||||
(unlitShader ??= new Cesium.CustomShader({
|
||||
lightingModel: Cesium.LightingModel.UNLIT,
|
||||
}));
|
||||
|
||||
// A colour from the layer (an Rgba or a Cesium.Color) as a Cesium.Color, for
|
||||
// the entity properties that keep what they are given. Constants convert
|
||||
// once.
|
||||
const cesiumColors = new WeakMap();
|
||||
function cesiumColor(color) {
|
||||
if (color instanceof Cesium.Color) return color;
|
||||
let converted = cesiumColors.get(color);
|
||||
if (!converted) {
|
||||
converted = new Cesium.Color(
|
||||
color.red,
|
||||
color.green,
|
||||
color.blue,
|
||||
color.alpha,
|
||||
);
|
||||
if (Object.isFrozen(color)) cesiumColors.set(color, converted);
|
||||
}
|
||||
return converted;
|
||||
}
|
||||
|
||||
const cesiumNearFar = (scalar) =>
|
||||
scalar instanceof Cesium.NearFarScalar
|
||||
? scalar
|
||||
: new Cesium.NearFarScalar(
|
||||
scalar.near,
|
||||
scalar.nearValue,
|
||||
scalar.far,
|
||||
scalar.farValue,
|
||||
);
|
||||
|
||||
/**
|
||||
* @param {object} options
|
||||
* @param {Cesium.Viewer} options.viewer
|
||||
* @param {object} [options.engine] The globe engine (default: the viewer's).
|
||||
* @param {string} options.spriteLayer The fleet's slot in data/spriteOrder.
|
||||
* @param {number} [options.headingOffsetDeg=0] Model nose vs Cesium heading 0.
|
||||
* @param {{ billboardCollection?: object, modelCollection?: object }} [options.adopt]
|
||||
* Drive existing collections instead of creating them (test fakes; a
|
||||
* layer that keeps its own model collection, local ADS-B).
|
||||
* @param {(options: object) => Promise<object>} [options.loadModel] The glTF
|
||||
* loader (test seam; Cesium.Model.fromGltfAsync).
|
||||
* @returns {import('./contract.js').AircraftRenderer}
|
||||
*/
|
||||
export function createAircraftCesiumRenderer({
|
||||
viewer,
|
||||
engine = null,
|
||||
spriteLayer,
|
||||
headingOffsetDeg = 0,
|
||||
adopt = null,
|
||||
loadModel = (options) => Cesium.Model.fromGltfAsync(options),
|
||||
}) {
|
||||
let billboards = adopt?.billboardCollection ?? null;
|
||||
let models = adopt?.modelCollection ?? null;
|
||||
const scratchHpr = new Cesium.HeadingPitchRoll(0, 0, 0);
|
||||
const scratchSphere = new Cesium.BoundingSphere(new Cesium.Cartesian3(), 1.0);
|
||||
// The frame's culling volume and one tester over it (no closure per call).
|
||||
let cullingVolume = null;
|
||||
const inFrustum = (position) => {
|
||||
Cesium.Cartesian3.clone(position, scratchSphere.center);
|
||||
return (
|
||||
cullingVolume.computeVisibility(scratchSphere) !==
|
||||
Cesium.Intersect.OUTSIDE
|
||||
);
|
||||
};
|
||||
const scratchSize = {
|
||||
width: undefined,
|
||||
height: undefined,
|
||||
scale: undefined,
|
||||
scaleByDistance: undefined,
|
||||
};
|
||||
|
||||
const scene = () => viewer?.scene;
|
||||
const camera = () => viewer?.camera;
|
||||
|
||||
const view = {
|
||||
get camera() {
|
||||
return camera();
|
||||
},
|
||||
get scene() {
|
||||
return scene();
|
||||
},
|
||||
get surfaceOwner() {
|
||||
return viewer;
|
||||
},
|
||||
get surfaceScene() {
|
||||
return viewer?.scene;
|
||||
},
|
||||
frameNumber: () => viewer?.scene?.frameState?.frameNumber ?? -1,
|
||||
viewportHeightPx: () => viewer.scene.canvas.clientHeight,
|
||||
// The tester stays valid until the next frustumTester() call.
|
||||
frustumTester() {
|
||||
const cam = viewer.camera;
|
||||
cullingVolume = cam.frustum.computeCullingVolume(
|
||||
cam.positionWC,
|
||||
cam.directionWC,
|
||||
cam.upWC,
|
||||
);
|
||||
return inFrustum;
|
||||
},
|
||||
horizon: () => horizonOccluder(viewer.camera),
|
||||
worldToWindow: (position, result) =>
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
viewer.scene,
|
||||
position,
|
||||
result,
|
||||
),
|
||||
requestRender: () => viewer?.scene?.requestRender?.(),
|
||||
on(event, listener) {
|
||||
const source =
|
||||
event === 'moveEnd'
|
||||
? viewer?.camera?.moveEnd
|
||||
: event === 'preRender'
|
||||
? viewer?.scene?.preRender
|
||||
: event === 'preUpdate'
|
||||
? viewer?.scene?.preUpdate
|
||||
: null;
|
||||
return source ? source.addEventListener(listener) : null;
|
||||
},
|
||||
isDestroyed: () => !viewer || viewer.isDestroyed?.() === true,
|
||||
// Evidence capture (qa-focus-evidence): Cesium's own render loop off,
|
||||
// then its pending-loop latch closed so manual renders start at once.
|
||||
holdFrames() {
|
||||
viewer.useDefaultRenderLoop = false;
|
||||
},
|
||||
closeFrameLatch() {
|
||||
if (viewer?._cesiumWidget)
|
||||
viewer._cesiumWidget._renderLoopRunning = false;
|
||||
},
|
||||
releaseFrames() {
|
||||
if (viewer) viewer.useDefaultRenderLoop = true;
|
||||
},
|
||||
};
|
||||
|
||||
const fleet = {
|
||||
attach() {
|
||||
billboards = new Cesium.BillboardCollection();
|
||||
viewer.scene.primitives.add(billboards);
|
||||
registerSpriteCollection(spriteLayer, billboards);
|
||||
models = new Cesium.PrimitiveCollection();
|
||||
viewer.scene.primitives.add(models);
|
||||
},
|
||||
// `owner`: the viewer the layer's destroy() was given (the same one).
|
||||
detach(owner) {
|
||||
const host = owner ?? viewer;
|
||||
if (billboards) {
|
||||
host.scene.primitives.remove(billboards);
|
||||
billboards = null;
|
||||
}
|
||||
if (models) {
|
||||
host.scene.primitives.remove(models); // removing destroys it + its models
|
||||
models = null;
|
||||
}
|
||||
},
|
||||
attached: () => !!billboards,
|
||||
visible: () => !!billboards && billboards.show,
|
||||
setVisible(visible) {
|
||||
if (billboards) billboards.show = visible;
|
||||
},
|
||||
add: (spec) => billboards.add(spec),
|
||||
remove: (sprite) => billboards.remove(sprite),
|
||||
restoreOrder: () => restoreSpriteOrder(viewer),
|
||||
restoreOrderOnEnable: () => restoreSpriteOrderOnEnable(spriteLayer, viewer),
|
||||
};
|
||||
|
||||
const modelSet = {
|
||||
live: () => !!models && !models.isDestroyed(),
|
||||
setVisible(visible) {
|
||||
if (models) models.show = visible;
|
||||
},
|
||||
loadFleet: ({
|
||||
url,
|
||||
minimumPixelSize,
|
||||
scale,
|
||||
color,
|
||||
blendAmount,
|
||||
unlit,
|
||||
id,
|
||||
}) =>
|
||||
loadModel({
|
||||
url,
|
||||
asynchronous: false,
|
||||
environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
|
||||
minimumPixelSize,
|
||||
scale,
|
||||
color,
|
||||
colorBlendMode: Cesium.ColorBlendMode.MIX,
|
||||
colorBlendAmount: blendAmount,
|
||||
customShader: unlit ? irUnlitShader() : undefined,
|
||||
id, // so scene.pick returns the icao for click-to-track
|
||||
}),
|
||||
loadTracked: ({
|
||||
url,
|
||||
minimumPixelSize,
|
||||
scale,
|
||||
color,
|
||||
blendAmount,
|
||||
unlit,
|
||||
id,
|
||||
}) =>
|
||||
loadModel({
|
||||
url,
|
||||
asynchronous: false,
|
||||
environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
|
||||
minimumPixelSize,
|
||||
scale,
|
||||
color,
|
||||
colorBlendMode: Cesium.ColorBlendMode.MIX,
|
||||
colorBlendAmount: blendAmount,
|
||||
customShader: unlit ? irUnlitShader() : undefined,
|
||||
// Pick id (H1): clicking the tracked plane's own model must read as
|
||||
// that plane, not as empty space.
|
||||
id,
|
||||
}),
|
||||
// Warms Cesium's glTF cache (the retained instance is never drawn).
|
||||
preload: (url) =>
|
||||
loadModel({
|
||||
url,
|
||||
asynchronous: false,
|
||||
}),
|
||||
add: (model) => models.add(model),
|
||||
remove(model) {
|
||||
if (models && !models.isDestroyed()) {
|
||||
try {
|
||||
models.remove(model);
|
||||
} catch {
|
||||
/* gone */
|
||||
}
|
||||
}
|
||||
},
|
||||
destroy(model) {
|
||||
try {
|
||||
model.destroy();
|
||||
} catch {
|
||||
/* gone */
|
||||
}
|
||||
},
|
||||
/**
|
||||
* World transform from a position and a course (pitch/roll 0, ENU frame),
|
||||
* written into the model's OWN modelMatrix: Model.modelMatrix is a plain
|
||||
* field Cesium clones per frame, so models never share one mutable
|
||||
* matrix (a shared scratch stacked every model on the last-written
|
||||
* plane: the "flickering like mad" bug). `offsetDeg`: this model's nose
|
||||
* offset when the layer's models differ (default: the layer's).
|
||||
*/
|
||||
setPose(model, position, headingDeg, offsetDeg = headingOffsetDeg) {
|
||||
scratchHpr.heading = Cesium.Math.toRadians((headingDeg || 0) + offsetDeg);
|
||||
scratchHpr.pitch = 0;
|
||||
scratchHpr.roll = 0;
|
||||
return Cesium.Transforms.headingPitchRollToFixedFrame(
|
||||
position,
|
||||
scratchHpr,
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
undefined,
|
||||
model.modelMatrix,
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
const tracked = {
|
||||
/**
|
||||
* The tracked aircraft as an Entity: a pure billboard (no model or label
|
||||
* graphic, so viewer.trackedEntity always has a ready bounding sphere),
|
||||
* in the ENU tracking frame the close-range camera guard also uses.
|
||||
* Cesium generates its id: an explicit one would throw when a re-init
|
||||
* briefly overlaps collections.
|
||||
*/
|
||||
create(spec) {
|
||||
return viewer.entities.add({
|
||||
position: new Cesium.CallbackProperty(() => spec.position(), false),
|
||||
trackingReferenceFrame: Cesium.TrackingReferenceFrame.ENU,
|
||||
billboard: {
|
||||
image: spec.image,
|
||||
width: spec.width,
|
||||
height: spec.height,
|
||||
scale: spec.scale,
|
||||
color: new Cesium.CallbackProperty(
|
||||
() => cesiumColor(spec.color()),
|
||||
false,
|
||||
),
|
||||
sizeInMeters: false,
|
||||
scaleByDistance: cesiumNearFar(spec.scaleByDistance),
|
||||
alignedAxis: Cesium.Cartesian3.ZERO,
|
||||
disableDepthTestDistance: spec.disableDepthTestDistance,
|
||||
rotation: new Cesium.CallbackProperty(() => spec.rotation(), false),
|
||||
},
|
||||
});
|
||||
},
|
||||
remove(handle) {
|
||||
viewer.entities.remove(handle);
|
||||
},
|
||||
isLive: (handle) => !!viewer?.entities?.contains?.(handle),
|
||||
setImage(handle, image) {
|
||||
if (handle?.billboard) handle.billboard.image = image;
|
||||
},
|
||||
setViewFrom(handle, offset) {
|
||||
handle.viewFrom = new Cesium.Cartesian3(offset.x, offset.y, offset.z);
|
||||
},
|
||||
/**
|
||||
* The tracked billboard's drawn size inputs, at the viewer's time. The
|
||||
* result is reused (read it before the next call).
|
||||
*/
|
||||
billboardSize(handle) {
|
||||
const billboard = handle?.billboard;
|
||||
if (!billboard) return null;
|
||||
const time = viewer.clock.currentTime;
|
||||
scratchSize.width = billboard.width?.getValue(time);
|
||||
scratchSize.height = billboard.height?.getValue(time);
|
||||
scratchSize.scale = billboard.scale?.getValue(time);
|
||||
scratchSize.scaleByDistance = billboard.scaleByDistance?.getValue(time);
|
||||
return scratchSize;
|
||||
},
|
||||
};
|
||||
|
||||
const follow = {
|
||||
// Cancel any flight first: Cesium applies the entity's viewFrom on the
|
||||
// first frame only from an idle camera.
|
||||
start(handle) {
|
||||
viewer.camera.cancelFlight();
|
||||
viewer.trackedEntity = handle;
|
||||
return applyTrackedCameraFrame(viewer, handle, handle.viewFrom) || null;
|
||||
},
|
||||
refocus(handle) {
|
||||
viewer.camera.cancelFlight();
|
||||
viewer.trackedEntity = handle;
|
||||
return applyTrackedCameraFrame(viewer, handle, handle.viewFrom) || null;
|
||||
},
|
||||
// Releasing trackedEntity leaves the camera where the follow put it.
|
||||
release() {
|
||||
if (viewer) viewer.trackedEntity = undefined;
|
||||
},
|
||||
isFollowing: (handle) => !!viewer && viewer.trackedEntity === handle,
|
||||
current: () => viewer?.trackedEntity,
|
||||
onChanged: (listener) =>
|
||||
viewer.trackedEntityChanged.addEventListener(listener),
|
||||
};
|
||||
|
||||
const trails = {
|
||||
create: ({ color, width }) => createTrail(viewer, { color, width }),
|
||||
/**
|
||||
* The live head segment: last fix → the dead-reckoned aircraft, updated
|
||||
* per frame through a CallbackProperty (entity polylines update cheaply,
|
||||
* the trail body rebuilds on setPositions). The 'gev-trail' id namespace
|
||||
* is claimed by trailRenderer's pick owner.
|
||||
*/
|
||||
createHead({ id, show, positions, color, width }) {
|
||||
if (!viewer) return null;
|
||||
return viewer.entities.add({
|
||||
id,
|
||||
show,
|
||||
polyline: {
|
||||
positions: new Cesium.CallbackProperty(() => positions(), false),
|
||||
width,
|
||||
material: Cesium.Color.fromCssColorString(color).withAlpha(0.9),
|
||||
// The head never vanishes into the mesh (dimmed when occluded).
|
||||
depthFailMaterial:
|
||||
Cesium.Color.fromCssColorString(color).withAlpha(0.45),
|
||||
arcType: Cesium.ArcType.GEODESIC,
|
||||
},
|
||||
});
|
||||
},
|
||||
removeHead(head) {
|
||||
if (head && viewer && !viewer.isDestroyed()) {
|
||||
try {
|
||||
viewer.entities.remove(head);
|
||||
} catch {
|
||||
/* already gone */
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
kind: 'cesium',
|
||||
get engine() {
|
||||
return engine ?? engineFromViewer(viewer);
|
||||
},
|
||||
viewer,
|
||||
view,
|
||||
fleet,
|
||||
models: modelSet,
|
||||
tracked,
|
||||
follow,
|
||||
trails,
|
||||
/**
|
||||
* Everything a vertical surface probe must not hit: Cesium excludes
|
||||
* picked objects, and the layer's billboards and models are its own.
|
||||
*/
|
||||
surfaceExclusions: ({ sprites = [], models: modelHandles = [] }) =>
|
||||
[...sprites, ...modelHandles].filter(Boolean),
|
||||
destroy() {
|
||||
billboards = null;
|
||||
models = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,324 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { createAircraftCesiumRenderer } from './cesium.js';
|
||||
import { CYAN, nearFarScale, rgbaFromCss } from '../../shared/color.js';
|
||||
|
||||
/** A viewer with what the renderer touches: primitives, entities, camera. */
|
||||
function stubViewer() {
|
||||
const added = [];
|
||||
const removed = [];
|
||||
const camera = {
|
||||
positionWC: Cesium.Cartesian3.fromDegrees(-73.78, 40.0, 50_000),
|
||||
directionWC: Cesium.Cartesian3.normalize(
|
||||
Cesium.Cartesian3.negate(
|
||||
Cesium.Cartesian3.fromDegrees(-73.78, 40.0, 50_000),
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
upWC: Cesium.Cartesian3.UNIT_Z,
|
||||
frustum: new Cesium.PerspectiveFrustum({ fov: 1, aspectRatio: 1.5 }),
|
||||
moveEnd: new Cesium.Event(),
|
||||
cancelled: 0,
|
||||
cancelFlight() {
|
||||
this.cancelled += 1;
|
||||
},
|
||||
};
|
||||
camera.frustum.near = 1;
|
||||
camera.frustum.far = 1e8;
|
||||
const viewer = {
|
||||
camera,
|
||||
scene: {
|
||||
primitives: {
|
||||
add: (p) => added.push(p) && p,
|
||||
remove: (p) => removed.push(p),
|
||||
},
|
||||
preRender: new Cesium.Event(),
|
||||
preUpdate: new Cesium.Event(),
|
||||
canvas: { clientHeight: 800 },
|
||||
frameState: { frameNumber: 42 },
|
||||
screenSpaceCameraController: {},
|
||||
requestRender() {},
|
||||
},
|
||||
entities: new Cesium.EntityCollection(),
|
||||
clock: { currentTime: Cesium.JulianDate.now() },
|
||||
trackedEntity: undefined,
|
||||
trackedEntityChanged: new Cesium.Event(),
|
||||
isDestroyed: () => false,
|
||||
};
|
||||
return { viewer, added, removed };
|
||||
}
|
||||
|
||||
const renderer = (viewer, options = {}) =>
|
||||
createAircraftCesiumRenderer({
|
||||
viewer,
|
||||
spriteLayer: 'flights',
|
||||
headingOffsetDeg: 180,
|
||||
...options,
|
||||
});
|
||||
|
||||
test('the Cesium aircraft renderer reports its kind', () => {
|
||||
const { viewer } = stubViewer();
|
||||
assert.equal(renderer(viewer).kind, 'cesium');
|
||||
});
|
||||
|
||||
test('the fleet is one BillboardCollection and one model collection, in that order', () => {
|
||||
const { viewer, added, removed } = stubViewer();
|
||||
const r = renderer(viewer);
|
||||
assert.equal(r.fleet.attached(), false);
|
||||
r.fleet.attach();
|
||||
assert.ok(added[0] instanceof Cesium.BillboardCollection);
|
||||
assert.ok(added[1] instanceof Cesium.PrimitiveCollection);
|
||||
assert.equal(r.fleet.visible(), true);
|
||||
const sprite = r.fleet.add({
|
||||
position: geo.cartesian3.fromDegrees(0, 0, 1000),
|
||||
color: rgbaFromCss('#FFB800').withAlpha(0.5),
|
||||
scaleByDistance: nearFarScale(1000, 3, 8_000_000, 0.5),
|
||||
id: 'abc123',
|
||||
});
|
||||
assert.ok(sprite instanceof Cesium.Billboard);
|
||||
assert.equal(sprite.id, 'abc123');
|
||||
r.fleet.setVisible(false);
|
||||
assert.equal(r.fleet.visible(), false);
|
||||
r.models.setVisible(false);
|
||||
assert.equal(added[1].show, false);
|
||||
assert.equal(r.models.live(), true);
|
||||
r.fleet.detach();
|
||||
assert.deepEqual(removed, [added[0], added[1]]);
|
||||
assert.equal(r.fleet.attached(), false);
|
||||
});
|
||||
|
||||
test('a model pose is the old heading-pitch-roll frame with the nose offset', () => {
|
||||
const { viewer } = stubViewer();
|
||||
const r = renderer(viewer);
|
||||
const model = { modelMatrix: new Cesium.Matrix4() };
|
||||
const position = geo.cartesian3.fromDegrees(-97.7, 30.2, 3000);
|
||||
const written = r.models.setPose(model, position, 75);
|
||||
assert.equal(written, model.modelMatrix, 'written into the model own matrix');
|
||||
const expected = Cesium.Transforms.headingPitchRollToFixedFrame(
|
||||
position,
|
||||
new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(75 + 180), 0, 0),
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
);
|
||||
assert.deepEqual(
|
||||
[...Cesium.Matrix4.toArray(model.modelMatrix)],
|
||||
[...Cesium.Matrix4.toArray(expected)],
|
||||
);
|
||||
});
|
||||
|
||||
test('a model pose takes a per-model nose offset (military per-class specs)', () => {
|
||||
const { viewer } = stubViewer();
|
||||
const r = renderer(viewer);
|
||||
const model = { modelMatrix: new Cesium.Matrix4() };
|
||||
const position = geo.cartesian3.fromDegrees(-97.7, 30.2, 3000);
|
||||
r.models.setPose(model, position, 75, 90);
|
||||
const expected = Cesium.Transforms.headingPitchRollToFixedFrame(
|
||||
position,
|
||||
new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(75 + 90), 0, 0),
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
);
|
||||
assert.deepEqual(
|
||||
[...Cesium.Matrix4.toArray(model.modelMatrix)],
|
||||
[...Cesium.Matrix4.toArray(expected)],
|
||||
);
|
||||
});
|
||||
|
||||
test('model loads carry the layer spec; the IR boost loads an UNLIT model', async () => {
|
||||
const { viewer } = stubViewer();
|
||||
const r = renderer(viewer);
|
||||
const calls = [];
|
||||
const realFrom = Cesium.Model.fromGltfAsync;
|
||||
Cesium.Model.fromGltfAsync = (options) => {
|
||||
calls.push(options);
|
||||
return Promise.resolve({ options });
|
||||
};
|
||||
try {
|
||||
const spec = {
|
||||
url: '/models/airplane.glb',
|
||||
minimumPixelSize: 24,
|
||||
scale: 1,
|
||||
color: CYAN,
|
||||
blendAmount: 0.94,
|
||||
unlit: false,
|
||||
id: 'abc123',
|
||||
};
|
||||
await r.models.loadFleet(spec);
|
||||
await r.models.loadTracked({ ...spec, unlit: true, minimumPixelSize: 40 });
|
||||
await r.models.preload('/models/airplane.glb');
|
||||
} finally {
|
||||
Cesium.Model.fromGltfAsync = realFrom;
|
||||
}
|
||||
assert.equal(calls.length, 3);
|
||||
for (const call of calls) assert.equal(call.asynchronous, false);
|
||||
assert.deepEqual(calls[0].environmentMapOptions, { enabled: false });
|
||||
assert.deepEqual(calls[1].environmentMapOptions, { enabled: false });
|
||||
assert.equal(calls[0].colorBlendMode, Cesium.ColorBlendMode.MIX);
|
||||
assert.equal(calls[0].colorBlendAmount, 0.94);
|
||||
assert.equal(calls[0].customShader, undefined);
|
||||
assert.equal(calls[0].id, 'abc123');
|
||||
assert.equal(calls[1].minimumPixelSize, 40);
|
||||
assert.equal(calls[1].customShader.lightingModel, Cesium.LightingModel.UNLIT);
|
||||
assert.deepEqual(Object.keys(calls[2]).sort(), ['asynchronous', 'url']);
|
||||
});
|
||||
|
||||
test('the frustum and horizon tests are the Cesium ones', () => {
|
||||
const { viewer } = stubViewer();
|
||||
const r = renderer(viewer);
|
||||
const inFrustum = r.view.frustumTester();
|
||||
const below = Cesium.Cartesian3.fromDegrees(-73.78, 40.0, 0);
|
||||
const behind = Cesium.Cartesian3.fromDegrees(106.22, -40.0, 0);
|
||||
const aboveCamera = Cesium.Cartesian3.fromDegrees(-73.78, 40.0, 200_000);
|
||||
assert.equal(inFrustum(below), true);
|
||||
assert.equal(inFrustum(aboveCamera), false);
|
||||
assert.equal(r.view.horizon().isPointVisible(below), true);
|
||||
assert.equal(r.view.horizon().isPointVisible(behind), false);
|
||||
assert.equal(r.view.frameNumber(), 42);
|
||||
assert.equal(r.view.viewportHeightPx(), 800);
|
||||
});
|
||||
|
||||
test('the tracked aircraft is an ENU-framed billboard entity with live callbacks', () => {
|
||||
const { viewer } = stubViewer();
|
||||
const r = renderer(viewer);
|
||||
let position = geo.cartesian3.fromDegrees(-97.7, 30.2, 3000);
|
||||
let color = CYAN;
|
||||
const handle = r.tracked.create({
|
||||
position: () => position,
|
||||
image: 'data:image/png;base64,',
|
||||
width: 28,
|
||||
height: 28,
|
||||
scale: 1.2,
|
||||
color: () => color,
|
||||
scaleByDistance: nearFarScale(1000, 3.0, 8000000, 0.5),
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
rotation: () => 0.25,
|
||||
});
|
||||
assert.ok(handle instanceof Cesium.Entity);
|
||||
assert.equal(r.tracked.isLive(handle), true);
|
||||
const time = viewer.clock.currentTime;
|
||||
assert.equal(
|
||||
handle.trackingReferenceFrame,
|
||||
Cesium.TrackingReferenceFrame.ENU,
|
||||
);
|
||||
assert.equal(handle.position.getValue(time), position);
|
||||
const billboardColor = handle.billboard.color.getValue(time);
|
||||
assert.ok(billboardColor instanceof Cesium.Color);
|
||||
assert.ok(billboardColor.equals(Cesium.Color.CYAN));
|
||||
color = CYAN.withAlpha(0);
|
||||
assert.equal(handle.billboard.color.getValue(time).alpha, 0);
|
||||
assert.equal(handle.billboard.rotation.getValue(time), 0.25);
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.equals(
|
||||
handle.billboard.alignedAxis.getValue(time),
|
||||
Cesium.Cartesian3.ZERO,
|
||||
),
|
||||
);
|
||||
assert.ok(
|
||||
handle.billboard.scaleByDistance.getValue(time) instanceof
|
||||
Cesium.NearFarScalar,
|
||||
);
|
||||
assert.deepEqual(r.tracked.billboardSize(handle), {
|
||||
width: 28,
|
||||
height: 28,
|
||||
scale: 1.2,
|
||||
scaleByDistance: new Cesium.NearFarScalar(1000, 3.0, 8000000, 0.5),
|
||||
});
|
||||
r.tracked.setViewFrom(handle, { x: 0, y: -2400, z: 1650 });
|
||||
assert.ok(handle.viewFrom.getValue(time) instanceof Cesium.Cartesian3);
|
||||
position = geo.cartesian3.fromDegrees(-97.6, 30.2, 3000);
|
||||
assert.equal(handle.position.getValue(time), position);
|
||||
r.tracked.remove(handle);
|
||||
assert.equal(r.tracked.isLive(handle), false);
|
||||
});
|
||||
|
||||
test('follow tracks the handle after cancelling a flight; release leaves the camera', () => {
|
||||
const { viewer } = stubViewer();
|
||||
const r = renderer(viewer);
|
||||
const handle = r.tracked.create({
|
||||
position: () => geo.cartesian3.fromDegrees(-97.7, 30.2, 3000),
|
||||
image: 'x',
|
||||
width: 28,
|
||||
height: 28,
|
||||
scale: 1,
|
||||
color: () => CYAN,
|
||||
scaleByDistance: nearFarScale(1000, 3.0, 8000000, 0.5),
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
rotation: () => 0,
|
||||
});
|
||||
r.tracked.setViewFrom(handle, { x: 0, y: -2400, z: 1650 });
|
||||
const changes = [];
|
||||
const remove = r.follow.onChanged(() => changes.push(r.follow.current()));
|
||||
viewer.trackedEntityChanged.raiseEvent(); // the viewer raises on assignment
|
||||
const stop = r.follow.start(handle);
|
||||
assert.equal(viewer.camera.cancelled, 1);
|
||||
assert.equal(viewer.trackedEntity, handle);
|
||||
assert.equal(r.follow.isFollowing(handle), true);
|
||||
assert.equal(typeof stop, 'function', 'the one exact tracked frame');
|
||||
stop();
|
||||
r.follow.release();
|
||||
assert.equal(viewer.trackedEntity, undefined);
|
||||
assert.equal(r.follow.isFollowing(handle), false);
|
||||
remove();
|
||||
assert.equal(changes.length, 1);
|
||||
});
|
||||
|
||||
test('the trail head is a geodesic entity polyline in the trail namespace', () => {
|
||||
const { viewer } = stubViewer();
|
||||
const r = renderer(viewer);
|
||||
const ends = [
|
||||
geo.cartesian3.fromDegrees(0, 0, 1000),
|
||||
geo.cartesian3.fromDegrees(0.1, 0, 1000),
|
||||
];
|
||||
const head = r.trails.createHead({
|
||||
id: 'gev-trail:fl-head-1',
|
||||
show: true,
|
||||
positions: () => ends,
|
||||
color: '#00d4ff',
|
||||
width: 2.5,
|
||||
});
|
||||
const time = viewer.clock.currentTime;
|
||||
assert.equal(head.id, 'gev-trail:fl-head-1');
|
||||
assert.equal(head.polyline.positions.getValue(time), ends);
|
||||
assert.equal(head.polyline.arcType.getValue(time), Cesium.ArcType.GEODESIC);
|
||||
const base = Cesium.Color.fromCssColorString('#00d4ff');
|
||||
assert.ok(
|
||||
head.polyline.material.getValue(time).color.equals(base.withAlpha(0.9)),
|
||||
);
|
||||
assert.ok(
|
||||
head.polyline.depthFailMaterial
|
||||
.getValue(time)
|
||||
.color.equals(base.withAlpha(0.45)),
|
||||
);
|
||||
r.trails.removeHead(head);
|
||||
assert.equal(viewer.entities.contains(head), false);
|
||||
});
|
||||
|
||||
test('an adopted (test) collection is driven as the fleet', () => {
|
||||
const { viewer } = stubViewer();
|
||||
const removed = [];
|
||||
const billboardCollection = {
|
||||
show: true,
|
||||
remove: (sprite) => removed.push(sprite),
|
||||
};
|
||||
const modelCollection = {
|
||||
added: [],
|
||||
add(model) {
|
||||
this.added.push(model);
|
||||
},
|
||||
remove() {},
|
||||
isDestroyed: () => false,
|
||||
};
|
||||
const r = renderer(viewer, {
|
||||
adopt: { billboardCollection, modelCollection },
|
||||
});
|
||||
assert.equal(r.fleet.visible(), true);
|
||||
r.fleet.remove('sprite');
|
||||
assert.deepEqual(removed, ['sprite']);
|
||||
r.models.add('model');
|
||||
assert.deepEqual(modelCollection.added, ['model']);
|
||||
assert.deepEqual(
|
||||
r.surfaceExclusions({ sprites: ['a'], models: ['b', null] }),
|
||||
['a', 'b'],
|
||||
);
|
||||
});
|
||||
@@ -1,14 +1,13 @@
|
||||
// The aircraft renderer: what the aircraft layers' logic (flights now,
|
||||
// military and local ADS-B after it) asks of an engine to draw a fleet of
|
||||
// aircraft, its 3D models, the tracked aircraft, its trail, and to follow it.
|
||||
// render/cesium.js implements it over Cesium (the objects the layers used
|
||||
// to build themselves, one for one); render/navara.js implements it on the
|
||||
// Navara engine over engine.movers / engine.lines / engine.camera.follow.
|
||||
// Nothing here imports an engine.
|
||||
// The aircraft renderer: what the aircraft layers' logic (flights, military
|
||||
// and local ADS-B) asks of an engine to draw a fleet of aircraft, its 3D
|
||||
// models, the tracked aircraft, its trail, and to follow it. One
|
||||
// implementation, render/display.js, draws it on every engine through the
|
||||
// globe engine contract (engine.movers / engine.lines /
|
||||
// engine.camera.follow). Nothing here imports an engine.
|
||||
//
|
||||
// The logic holds HANDLES and writes plain fields on them; the field names
|
||||
// are Cesium's (the extraction is a pure move), and an engine other than
|
||||
// Cesium implements them as setters:
|
||||
// are Cesium's (the layers were written against its objects), and the
|
||||
// display implements them as setters:
|
||||
//
|
||||
// SpriteHandle (fleet.add) — one aircraft glyph:
|
||||
// position (Cartesian3), show, rotation (screen angle, rad),
|
||||
@@ -19,9 +18,10 @@
|
||||
// scaleByDistance as the engine's own copy). The logic may keep its own
|
||||
// bookkeeping fields on a handle (prefixed _gev).
|
||||
// ModelHandle (models.load*) — one glTF instance:
|
||||
// show, ready (read-only), scale, computedScale (read-only: scale after
|
||||
// minimumPixelSize), color, id, modelMatrix (16 numbers, column-major,
|
||||
// written by models.setPose and read for anchors), sceneGraph? (Cesium).
|
||||
// show, ready (read-only: placed, and its model loaded), scale,
|
||||
// computedScale (read-only: scale after minimumPixelSize), color, id,
|
||||
// modelMatrix (16 numbers, column-major, the model frame: written by
|
||||
// models.setPose and read for anchors).
|
||||
// TrackedHandle (tracked.create) — the selected aircraft's glyph and the
|
||||
// follow target: viewFrom (ENU offset, read), and the annotation fields
|
||||
// the shell reads: gevSelectionOrigin, gevTrackedId, gevLabelModel,
|
||||
@@ -33,9 +33,9 @@
|
||||
// camera-shaped (positionWC, positionCartographic, directionWC, upWC,
|
||||
// rightWC, heading, pitch, roll, frustum.fovy) and `scene` scene-shaped
|
||||
// ({ camera, canvas.clientHeight, frameState.frameNumber }) for the shared
|
||||
// helpers that take them (iconOrientation, focusDeemphasis); on Navara
|
||||
// they are adapters over engine.camera.pose(), with the engine registered
|
||||
// for the scene (engineFromViewer) so projections go through its projector.
|
||||
// helpers that take them (iconOrientation, focusDeemphasis): adapters over
|
||||
// engine.camera.pose(), with the engine registered for the scene
|
||||
// (engineFromViewer) so projections go through its projector.
|
||||
|
||||
/**
|
||||
* @typedef {object} AircraftView
|
||||
@@ -51,10 +51,10 @@
|
||||
* @property {() => void} requestRender
|
||||
* @property {(event: 'preRender'|'preUpdate'|'moveEnd', listener: Function) => () => void} on
|
||||
* @property {object} surfaceOwner What groundSnap/meshFloor sample through
|
||||
* (a viewer registered with its engine, or the engine).
|
||||
* (the engine).
|
||||
* @property {object} surfaceScene What sampleMeshFloorCells takes.
|
||||
* @property {() => void} holdFrames Evidence capture: stop the engine's own
|
||||
* frame loop (QA only).
|
||||
* frame loop (QA only; the contract has no frame hold, so it holds none).
|
||||
* @property {() => void} closeFrameLatch Evidence capture, one task later:
|
||||
* let manual renders start without waiting for the loop's next frame.
|
||||
* @property {() => void} releaseFrames
|
||||
@@ -62,9 +62,7 @@
|
||||
|
||||
/**
|
||||
* @typedef {object} AircraftRenderer
|
||||
* @property {'cesium'|'navara'} kind
|
||||
* @property {object|null} engine The globe engine (null in unit tests that
|
||||
* drive a bare viewer).
|
||||
* @property {object} engine The globe engine.
|
||||
* @property {AircraftView} view
|
||||
* @property {object} fleet attach(), detach(), attached(), visible(),
|
||||
* setVisible(bool), add(spec) → SpriteHandle, remove(sprite),
|
||||
@@ -73,18 +71,20 @@
|
||||
* loadTracked(spec), preload(url) → Promise<ModelHandle>, add(model),
|
||||
* remove(model), destroy(model), setPose(model, position, headingDeg,
|
||||
* offsetDeg?) (offsetDeg: the model's nose offset, default the layer's).
|
||||
* spec: { url, minimumPixelSize, scale, color, blendAmount, unlit, id }.
|
||||
* spec: { url, minimumPixelSize, scale, radiusM, color, blendAmount,
|
||||
* unlit, id }.
|
||||
* @property {object} tracked create(spec) → TrackedHandle, remove(handle),
|
||||
* isLive(handle), setImage(handle, image), setViewFrom(handle, enu),
|
||||
* billboardSize(handle) → { width, height, scale, scaleByDistance } | null.
|
||||
* spec: { image, width, height, scale, scaleByDistance,
|
||||
* disableDepthTestDistance, position(), color() → colour, rotation() }.
|
||||
* @property {object} follow start(handle) → stop, refocus(handle) → stop,
|
||||
* release(), isFollowing(handle), current(), onChanged(listener) → remove.
|
||||
* release(), isFollowing(handle), current() (the tracked handle, or what
|
||||
* another layer follows), onChanged(listener) → remove.
|
||||
* @property {object} trails create({ color, width }) → Trail,
|
||||
* createHead({ id, show, positions() → Cartesian3[], color, width }) →
|
||||
* TrailHead, removeHead(head).
|
||||
* @property {(objects: { sprites: Iterable, models: Iterable }) => object[]} surfaceExclusions
|
||||
* What a vertical surface probe must not hit: the layer's own drawings.
|
||||
* What a vertical surface probe must not hit: the layer's own mover sets.
|
||||
* @property {() => void} destroy
|
||||
*/
|
||||
@@ -1,9 +1,9 @@
|
||||
// The aircraft renderer on the Navara engine (contract: ./contract.js),
|
||||
// built only on the engine contract: engine.movers (the fleet glyphs, the
|
||||
// tracked glyph, the 3D models), engine.lines (the trail and its live head),
|
||||
// The aircraft display (contract: ./contract.js): what the aircraft layers
|
||||
// (flights, military, local ADS-B) draw, on any globe engine, through the
|
||||
// engine contract only: engine.movers (the fleet glyphs, the tracked glyph,
|
||||
// the 3D models), engine.lines (the trail and its live head),
|
||||
// engine.camera.follow (the follow camera), engine.projector and
|
||||
// engine.camera.pose() (the view the logic reads). No three, no Cesium: the
|
||||
// engine draws. Loaded only through the Navara mode's import().
|
||||
// engine.camera.pose() (the view the logic reads). The engine draws.
|
||||
//
|
||||
// Handles keep the Cesium field vocabulary the logic writes (contract.js) as
|
||||
// setters that write the engine's instance stores; the writes of a frame are
|
||||
@@ -11,10 +11,10 @@
|
||||
// microtask for writes outside a frame), so a fleet tick draws in its frame.
|
||||
//
|
||||
// Sprites go in banks: one mover set per distance scale and depth mode the
|
||||
// handles ask for (flights: one), growing by doubling. Models go in banks per
|
||||
// glTF and look (url, minimum pixels, blend, unlit). The glyph atlas holds
|
||||
// every aircraftIcon() kind at the fleet and tracked raster sizes, drawn
|
||||
// once from the same SVGs Cesium's billboards load.
|
||||
// handles ask for (flights: one), growing by doubling; the tracked glyph has
|
||||
// its own, drawn over the fleet. Models go in banks per glTF and look (url,
|
||||
// minimum pixels, blend, unlit). The glyph atlas holds every aircraftIcon()
|
||||
// kind at the fleet and tracked raster sizes, drawn once from the same SVGs.
|
||||
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import {
|
||||
@@ -29,21 +29,23 @@ import {
|
||||
createMoverBank,
|
||||
StoredColor,
|
||||
writeFields,
|
||||
} from '../../shared/render/navaraMoverBank.js';
|
||||
} from '../../shared/render/moverBank.js';
|
||||
|
||||
const BASE_SIZE_PX = 20;
|
||||
|
||||
/**
|
||||
* The model frame → glTF scene axes on Navara: Cesium's own glTF axis
|
||||
* correction, Y_UP_TO_Z_UP × Z_UP_TO_X_UP (data/modelVisualAnchor.js).
|
||||
* Navara's glTF loader is three's GLTFLoader, which keeps the scene Y-up,
|
||||
* so Z_UP_TO_X_UP alone would draw every model 90° off its heading.
|
||||
* The model frame → the glTF's own axes (the movers' orientation): Cesium's
|
||||
* glTF axis correction, Y_UP_TO_Z_UP × Z_UP_TO_X_UP (data/modelVisualAnchor.js),
|
||||
* column-major. setPose keeps modelMatrix in the model frame, as the layers'
|
||||
* anchors read it.
|
||||
*/
|
||||
// Cesium's Axis.Y_UP_TO_Z_UP × Axis.Z_UP_TO_X_UP, column-major.
|
||||
const NAVARA_GLTF_AXIS = [0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1];
|
||||
const ATLAS_PAD = 2;
|
||||
const GLTF_AXIS = [0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1];
|
||||
// The trail's alpha where it passes the depth test and where the scene hides
|
||||
// it (as data/trailRenderer.js draws track histories), and the live head's.
|
||||
const TRAIL_ALPHA = 0.85;
|
||||
const TRAIL_OCCLUDED_ALPHA = 0.4;
|
||||
const HEAD_ALPHA = 0.9;
|
||||
const HEAD_OCCLUDED_ALPHA = 0.45;
|
||||
const MIN_SEGMENT_DISTANCE_SQ = 0.01;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -81,8 +83,7 @@ const scalarKey = (scalar) =>
|
||||
|
||||
// Follow handle → the tracked handle it follows, for every aircraft layer on
|
||||
// the engine: a layer whose follow another aircraft layer took reads the
|
||||
// new owner's tracked handle (its gevSelectionOrigin), as Cesium's
|
||||
// viewer.trackedEntity gives it the other layer's entity.
|
||||
// new owner's tracked handle (its gevSelectionOrigin).
|
||||
const FOLLOWED_TRACKED = new WeakMap();
|
||||
// The tracked handle whose follow is being started (any aircraft layer):
|
||||
// the engine raises followChanged inside follow(), before the follow
|
||||
@@ -90,12 +91,12 @@ const FOLLOWED_TRACKED = new WeakMap();
|
||||
let followStarting = null;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The renderer
|
||||
// The display
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* @param {import('../../../globe/contract.js').GlobeEngine} engine
|
||||
* @param {object} options
|
||||
* @param {import('../../../globe/contract.js').GlobeEngine} options.engine
|
||||
* @param {string} options.layerId Names the layer's mover sets and lines.
|
||||
* @param {number} [options.order=0] Draw order of the layer's sprites.
|
||||
* @param {number} [options.headingOffsetDeg=0] Model nose vs heading 0.
|
||||
@@ -103,14 +104,19 @@ let followStarting = null;
|
||||
* Test seam: the glyph atlas.
|
||||
* @returns {import('./contract.js').AircraftRenderer}
|
||||
*/
|
||||
export function createAircraftNavaraRenderer({
|
||||
export function createAircraftDisplay(
|
||||
engine,
|
||||
layerId,
|
||||
order = 0,
|
||||
headingOffsetDeg = 0,
|
||||
drawAtlas = drawAircraftIconAtlas,
|
||||
}) {
|
||||
{
|
||||
layerId,
|
||||
order = 0,
|
||||
headingOffsetDeg = 0,
|
||||
drawAtlas = drawAircraftIconAtlas,
|
||||
},
|
||||
) {
|
||||
if (!engine?.movers || !engine?.lines)
|
||||
throw new TypeError('The aircraft display needs a globe engine');
|
||||
let destroyed = false;
|
||||
let attached = false;
|
||||
const removers = [];
|
||||
const iconCells = aircraftIconCells();
|
||||
const defaultIcon = [...iconCells.keys()][0];
|
||||
@@ -150,10 +156,11 @@ export function createAircraftNavaraRenderer({
|
||||
removers.push(layerView.destroy);
|
||||
const { view, freshCamera } = layerView;
|
||||
|
||||
// --- fleet sprites ---------------------------------------------------------
|
||||
// --- sprites: the fleet and the tracked glyph -------------------------------
|
||||
let atlas = null;
|
||||
let fleetVisible = true;
|
||||
const spriteBanks = new Map();
|
||||
let spriteBankSeq = 0;
|
||||
const unbanked = new Set(); // sprites added before the atlas
|
||||
const spriteWrite = (sprite, set, index) => {
|
||||
writeFields(set, index, {
|
||||
@@ -166,20 +173,23 @@ export function createAircraftNavaraRenderer({
|
||||
});
|
||||
set.set(index, { pickId: sprite.id });
|
||||
};
|
||||
// One bank per role (fleet, tracked), distance scale and depth mode.
|
||||
const spriteBankFor = (sprite) => {
|
||||
if (!atlas) return null;
|
||||
const { tracked } = sprite;
|
||||
const depth = depthKey(sprite.disableDepthTestDistance);
|
||||
const key = `${scalarKey(sprite.scaleByDistance)}|${JSON.stringify(depth)}`;
|
||||
const key = `${tracked ? 'tracked' : 'fleet'}|${scalarKey(sprite.scaleByDistance)}|${JSON.stringify(depth)}`;
|
||||
let bank = spriteBanks.get(key);
|
||||
if (!bank) {
|
||||
const scalar = sprite.scaleByDistance;
|
||||
const index = spriteBanks.size;
|
||||
const index = spriteBankSeq++;
|
||||
bank = createMoverBank(engine, {
|
||||
options: (capacity, generation) => ({
|
||||
id: `${layerId}-sprites-${index}-${generation}`,
|
||||
id: `${layerId}-${tracked ? 'tracked' : 'sprites'}-${index}-${generation}`,
|
||||
kind: 'sprite',
|
||||
capacity,
|
||||
order,
|
||||
// The tracked glyph over the fleet.
|
||||
order: tracked ? order + 0.5 : order,
|
||||
depthTest: depth,
|
||||
pickable: true,
|
||||
sprite: {
|
||||
@@ -193,12 +203,13 @@ export function createAircraftNavaraRenderer({
|
||||
write: spriteWrite,
|
||||
onCommit,
|
||||
});
|
||||
bank.setVisible(fleetVisible);
|
||||
bank.setVisible(tracked || fleetVisible);
|
||||
spriteBanks.set(key, bank);
|
||||
}
|
||||
return bank;
|
||||
};
|
||||
const placeSprite = (sprite) => {
|
||||
if (!sprite.live) return;
|
||||
const bank = spriteBankFor(sprite);
|
||||
if (!bank) {
|
||||
unbanked.add(sprite);
|
||||
@@ -213,9 +224,7 @@ export function createAircraftNavaraRenderer({
|
||||
atlas = drawn;
|
||||
const waiting = [...unbanked];
|
||||
unbanked.clear();
|
||||
for (const sprite of waiting) if (sprite.live) placeSprite(sprite);
|
||||
for (const sprite of trackedSprites)
|
||||
if (sprite.live) placeTracked(sprite);
|
||||
for (const sprite of waiting) placeSprite(sprite);
|
||||
engine.render.request(layerId);
|
||||
})
|
||||
.catch((error) =>
|
||||
@@ -223,11 +232,11 @@ export function createAircraftNavaraRenderer({
|
||||
);
|
||||
|
||||
class Sprite {
|
||||
constructor(spec, bankFor) {
|
||||
constructor(spec, tracked = false) {
|
||||
this.gevBank = null;
|
||||
this.gevIndex = -1;
|
||||
this.live = true;
|
||||
this.bankFor = bankFor;
|
||||
this.tracked = tracked;
|
||||
this._position = geo.cartesian3.clone(
|
||||
spec.position ?? geo.cartesian3.ZERO,
|
||||
);
|
||||
@@ -242,8 +251,8 @@ export function createAircraftNavaraRenderer({
|
||||
this._scaleByDistance = spec.scaleByDistance
|
||||
? { ...spec.scaleByDistance }
|
||||
: undefined;
|
||||
this.disableDepthTestDistance = spec.disableDepthTestDistance ?? 0;
|
||||
this.id = spec.id;
|
||||
this._disableDepthTestDistance = spec.disableDepthTestDistance ?? 0;
|
||||
this._id = spec.id;
|
||||
this.alignedAxis = spec.alignedAxis;
|
||||
this.sizeInMeters = false;
|
||||
}
|
||||
@@ -256,6 +265,18 @@ export function createAircraftNavaraRenderer({
|
||||
this.gevBank?.update(this, fields);
|
||||
}
|
||||
|
||||
get id() {
|
||||
return this._id;
|
||||
}
|
||||
|
||||
set id(value) {
|
||||
this._id = value;
|
||||
if (this.gevBank?.set) {
|
||||
this.gevBank.set.set(this.gevIndex, { pickId: value });
|
||||
this.gevBank.touch();
|
||||
}
|
||||
}
|
||||
|
||||
get position() {
|
||||
return this._position;
|
||||
}
|
||||
@@ -311,6 +332,7 @@ export function createAircraftNavaraRenderer({
|
||||
this.write(spriteScaleField);
|
||||
}
|
||||
|
||||
// Glyphs are square: the width sizes them.
|
||||
get height() {
|
||||
return this._height;
|
||||
}
|
||||
@@ -358,25 +380,49 @@ export function createAircraftNavaraRenderer({
|
||||
if (scalarKey(next) === scalarKey(this._scaleByDistance)) return;
|
||||
this._scaleByDistance = next;
|
||||
// Another distance scale is another set.
|
||||
if (this.gevBank) this.bankFor(this);
|
||||
if (this.gevBank) placeSprite(this);
|
||||
}
|
||||
|
||||
get disableDepthTestDistance() {
|
||||
return this._disableDepthTestDistance;
|
||||
}
|
||||
|
||||
set disableDepthTestDistance(value) {
|
||||
const next = value ?? 0;
|
||||
if (next === this._disableDepthTestDistance) return;
|
||||
this._disableDepthTestDistance = next;
|
||||
// Another depth mode is another set.
|
||||
if (this.gevBank) placeSprite(this);
|
||||
}
|
||||
}
|
||||
|
||||
const fleetBanks = () =>
|
||||
[...spriteBanks.entries()]
|
||||
.filter(([key]) => key.startsWith('fleet|'))
|
||||
.map(([, bank]) => bank);
|
||||
|
||||
const fleet = {
|
||||
attach() {},
|
||||
detach() {
|
||||
for (const bank of spriteBanks.values()) bank.destroy();
|
||||
spriteBanks.clear();
|
||||
unbanked.clear();
|
||||
attach() {
|
||||
attached = !destroyed;
|
||||
},
|
||||
attached: () => !destroyed,
|
||||
visible: () => !destroyed && fleetVisible,
|
||||
detach() {
|
||||
attached = false;
|
||||
for (const [key, bank] of [...spriteBanks])
|
||||
if (key.startsWith('fleet|')) {
|
||||
bank.destroy();
|
||||
spriteBanks.delete(key);
|
||||
}
|
||||
for (const sprite of unbanked)
|
||||
if (!sprite.tracked) unbanked.delete(sprite);
|
||||
},
|
||||
attached: () => attached && !destroyed,
|
||||
visible: () => attached && !destroyed && fleetVisible,
|
||||
setVisible(visible) {
|
||||
fleetVisible = visible;
|
||||
for (const bank of spriteBanks.values()) bank.setVisible(visible);
|
||||
for (const bank of fleetBanks()) bank.setVisible(visible);
|
||||
},
|
||||
add(spec) {
|
||||
const sprite = new Sprite(spec, (s) => placeSprite(s));
|
||||
const sprite = new Sprite(spec);
|
||||
placeSprite(sprite);
|
||||
return sprite;
|
||||
},
|
||||
@@ -386,6 +432,7 @@ export function createAircraftNavaraRenderer({
|
||||
unbanked.delete(sprite);
|
||||
sprite.gevBank?.remove(sprite);
|
||||
},
|
||||
// Draw order is each set's `order` (the layer's data/spriteOrder slot).
|
||||
restoreOrder() {},
|
||||
restoreOrderOnEnable() {},
|
||||
};
|
||||
@@ -447,18 +494,19 @@ export function createAircraftNavaraRenderer({
|
||||
this._show = true;
|
||||
this._scale = spec.scale ?? 1;
|
||||
this._color = new StoredColor(spec.color);
|
||||
this.id = spec.id;
|
||||
this._id = spec.id;
|
||||
this.modelMatrix = geo.matrix4.create();
|
||||
this.translation = geo.cartesian3.create();
|
||||
this.orientation = geo.quaternion.create(0, 0, 0, 1);
|
||||
this.radiusM = spec.radiusM ?? 1;
|
||||
}
|
||||
|
||||
/** Placed, and the engine has loaded what this instance draws. */
|
||||
get ready() {
|
||||
return this.placed && Boolean(this.gevBank?.ready());
|
||||
return this.placed && Boolean(this.gevBank?.set?.ready(this.gevIndex));
|
||||
}
|
||||
|
||||
/** The scale drawn: Cesium's minimumPixelSize kept on the CPU. */
|
||||
/** The scale drawn: minimumPixelSize kept on the CPU. */
|
||||
get computedScale() {
|
||||
const minimum = this.spec.minimumPixelSize ?? 0;
|
||||
if (!(minimum > 0)) return this._scale;
|
||||
@@ -479,6 +527,18 @@ export function createAircraftNavaraRenderer({
|
||||
return pixels < minimum ? this._scale * (minimum / pixels) : this._scale;
|
||||
}
|
||||
|
||||
get id() {
|
||||
return this._id;
|
||||
}
|
||||
|
||||
set id(value) {
|
||||
this._id = value;
|
||||
if (this.gevBank?.set) {
|
||||
this.gevBank.set.set(this.gevIndex, { pickId: value });
|
||||
this.gevBank.touch();
|
||||
}
|
||||
}
|
||||
|
||||
get show() {
|
||||
return this._show;
|
||||
}
|
||||
@@ -508,14 +568,14 @@ export function createAircraftNavaraRenderer({
|
||||
}
|
||||
|
||||
const models = {
|
||||
live: () => !destroyed,
|
||||
live: () => attached && !destroyed,
|
||||
setVisible(visible) {
|
||||
modelsVisible = visible;
|
||||
for (const bank of modelBanks.values()) bank.setVisible(visible);
|
||||
},
|
||||
loadFleet: (spec) => Promise.resolve(new ModelHandle(spec)),
|
||||
loadTracked: (spec) => Promise.resolve(new ModelHandle(spec)),
|
||||
// The engine loads each glTF once per bank; nothing to warm.
|
||||
// The engine loads each glTF itself; nothing to warm.
|
||||
preload: (url) => Promise.resolve({ url, destroy() {} }),
|
||||
add(model) {
|
||||
modelBankFor(model).add(model);
|
||||
@@ -526,9 +586,10 @@ export function createAircraftNavaraRenderer({
|
||||
destroy(model) {
|
||||
model?.gevBank?.remove(model);
|
||||
},
|
||||
/** The same HPR frame as Cesium (modelMatrix); the instance turned by
|
||||
* Navara's glTF axes (NAVARA_GLTF_AXIS). `offsetDeg`: this model's
|
||||
* nose offset when the layer's models differ (default: the layer's). */
|
||||
/** The heading-pitch-roll frame (modelMatrix, the model frame); the
|
||||
* instance turned to the glTF's own axes (GLTF_AXIS). `offsetDeg`: this
|
||||
* model's nose offset when the layer's models differ (default: the
|
||||
* layer's). */
|
||||
setPose(model, position, headingDeg, offsetDeg = headingOffsetDeg) {
|
||||
scratchHpr.heading = geo.math.toRadians((headingDeg || 0) + offsetDeg);
|
||||
geo.transforms.headingPitchRollToFixedFrame(
|
||||
@@ -540,7 +601,7 @@ export function createAircraftNavaraRenderer({
|
||||
);
|
||||
geo.matrix4.multiplyTransformation(
|
||||
model.modelMatrix,
|
||||
NAVARA_GLTF_AXIS,
|
||||
GLTF_AXIS,
|
||||
scratchCorrected,
|
||||
);
|
||||
geo.quaternion.fromRotationMatrix(
|
||||
@@ -564,37 +625,19 @@ export function createAircraftNavaraRenderer({
|
||||
|
||||
// --- the tracked glyph -----------------------------------------------------
|
||||
const trackedSprites = new Set();
|
||||
let trackedBank = null;
|
||||
const trackedBankFor = () => {
|
||||
if (!atlas) return null;
|
||||
trackedBank ??= createMoverBank(engine, {
|
||||
options: (capacity, generation) => ({
|
||||
id: `${layerId}-tracked-${generation}`,
|
||||
kind: 'sprite',
|
||||
capacity: Math.max(capacity, 4),
|
||||
order: order + 0.5,
|
||||
depthTest: 'always',
|
||||
pickable: true,
|
||||
sprite: {
|
||||
atlas,
|
||||
sizePx: BASE_SIZE_PX,
|
||||
scaleByDistance: [1000, 3.0, 8000000, 0.5],
|
||||
},
|
||||
}),
|
||||
write: spriteWrite,
|
||||
onCommit,
|
||||
});
|
||||
return trackedBank;
|
||||
};
|
||||
const placeTracked = (sprite) => trackedBankFor()?.add(sprite);
|
||||
let trackedSeq = 0;
|
||||
// Each frame (before drawing): the tracked glyphs read their callbacks.
|
||||
// A followed glyph takes the position its follow centred this frame
|
||||
// (Cesium's follow reads it before the frame's events).
|
||||
removers.push(
|
||||
engine.frames.preRender.addEventListener(() =>
|
||||
inFrameDo(() => {
|
||||
for (const sprite of trackedSprites) {
|
||||
const { spec } = sprite;
|
||||
const position = spec.position();
|
||||
const position = sprite.gevFollowSampled
|
||||
? sprite.gevFollowSample
|
||||
: spec.position();
|
||||
sprite.gevFollowSampled = false;
|
||||
if (position) sprite.position = position;
|
||||
sprite.rotation = spec.rotation();
|
||||
sprite.color = spec.color();
|
||||
@@ -614,24 +657,26 @@ export function createAircraftNavaraRenderer({
|
||||
scale: spec.scale,
|
||||
color: spec.color(),
|
||||
rotation: spec.rotation(),
|
||||
scaleByDistance: spec.scaleByDistance,
|
||||
disableDepthTestDistance: spec.disableDepthTestDistance,
|
||||
id: `${layerId}-tracked-${++trackedSeq}`,
|
||||
},
|
||||
() => {},
|
||||
true,
|
||||
);
|
||||
// The tracked glyph's distance scale is its bank's (as Cesium's).
|
||||
sprite._scaleByDistance = spec.scaleByDistance;
|
||||
sprite.spec = spec;
|
||||
sprite.resumeAircraftFollow = () => follow.start(sprite);
|
||||
sprite.viewFrom = null;
|
||||
sprite.gevFollowSample = geo.cartesian3.create();
|
||||
sprite.gevFollowSampled = false;
|
||||
trackedSprites.add(sprite);
|
||||
placeTracked(sprite);
|
||||
placeSprite(sprite);
|
||||
return sprite;
|
||||
},
|
||||
remove(handle) {
|
||||
if (!handle) return;
|
||||
handle.live = false;
|
||||
trackedSprites.delete(handle);
|
||||
unbanked.delete(handle);
|
||||
handle.gevBank?.remove(handle);
|
||||
if (
|
||||
handle.gevFollowHandle &&
|
||||
@@ -658,22 +703,30 @@ export function createAircraftNavaraRenderer({
|
||||
};
|
||||
|
||||
// --- follow ---------------------------------------------------------------
|
||||
const ownFollows = FOLLOWED_TRACKED; // follow handle → tracked handle
|
||||
// The follow carries the tracked readout's card as plain data (the
|
||||
// handle's annotation fields, read when the card paints).
|
||||
const followOf = (handle) => {
|
||||
const card = {
|
||||
id: handle.gevTrackedId,
|
||||
model: () => handle.gevLabelModel,
|
||||
position: () => handle.gevDisplayPosition?.() ?? handle.spec.position(),
|
||||
};
|
||||
return engine.camera.follow({
|
||||
const followOf = (handle) =>
|
||||
engine.camera.follow({
|
||||
native: handle,
|
||||
position: () => handle.spec.position(),
|
||||
position() {
|
||||
const position = handle.spec.position();
|
||||
if (position) {
|
||||
geo.cartesian3.clone(position, handle.gevFollowSample);
|
||||
handle.gevFollowSampled = true;
|
||||
}
|
||||
return position;
|
||||
},
|
||||
viewFrom: () => handle.viewFrom,
|
||||
label: card,
|
||||
label:
|
||||
typeof handle.gevTrackedId === 'string'
|
||||
? {
|
||||
id: handle.gevTrackedId,
|
||||
model: () => handle.gevLabelModel,
|
||||
position: () =>
|
||||
handle.gevDisplayPosition?.() ?? handle.spec.position(),
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
};
|
||||
const follow = {
|
||||
start(handle) {
|
||||
const outer = followStarting;
|
||||
@@ -685,9 +738,9 @@ export function createAircraftNavaraRenderer({
|
||||
followStarting = outer;
|
||||
}
|
||||
handle.gevFollowHandle = followHandle;
|
||||
ownFollows.set(followHandle, handle);
|
||||
// Cesium returns the one-frame camera framing's disposer; the engine's
|
||||
// follow frames itself.
|
||||
FOLLOWED_TRACKED.set(followHandle, handle);
|
||||
// The engine's follow frames itself (Cesium's one exact tracked frame
|
||||
// included) and ends with it: nothing for the caller to stop.
|
||||
return () => {};
|
||||
},
|
||||
refocus(handle) {
|
||||
@@ -699,17 +752,35 @@ export function createAircraftNavaraRenderer({
|
||||
isFollowing: (handle) =>
|
||||
Boolean(handle?.gevFollowHandle) &&
|
||||
engine.camera.following() === handle.gevFollowHandle,
|
||||
// What is followed: an aircraft layer's tracked handle, else what the
|
||||
// follow is of (another layer's entity), else the follow itself.
|
||||
current() {
|
||||
if (followStarting) return followStarting;
|
||||
const handle = engine.camera.following();
|
||||
return handle ? (ownFollows.get(handle) ?? handle) : undefined;
|
||||
return handle
|
||||
? (FOLLOWED_TRACKED.get(handle) ?? handle.native ?? handle)
|
||||
: undefined;
|
||||
},
|
||||
onChanged: (listener) =>
|
||||
engine.camera.followChanged.addEventListener(listener),
|
||||
};
|
||||
|
||||
// --- trails ----------------------------------------------------------------
|
||||
// The layer's lines and heads, released with the display.
|
||||
const lines = new Set();
|
||||
const heads = new Set();
|
||||
let lineSeq = 0;
|
||||
const lineOf = (options) => {
|
||||
const line = engine.lines.createLine(options);
|
||||
lines.add(line);
|
||||
return line;
|
||||
};
|
||||
const dropLine = (line) => {
|
||||
if (line && lines.delete(line)) line.destroy();
|
||||
};
|
||||
const samePositions = (a, b) =>
|
||||
a.length === b.length &&
|
||||
a.every((position, index) => geo.cartesian3.equals(position, b[index]));
|
||||
const trails = {
|
||||
create({ color, width = 2.5 }) {
|
||||
const [r, g, b] = rgbaFromCss(color).rgba();
|
||||
@@ -718,7 +789,7 @@ export function createAircraftNavaraRenderer({
|
||||
let visible = true;
|
||||
let current = [];
|
||||
const ensure = () =>
|
||||
(line ??= engine.lines.createLine({
|
||||
(line ??= lineOf({
|
||||
id,
|
||||
widthPx: width,
|
||||
color: [r, g, b, TRAIL_ALPHA],
|
||||
@@ -727,6 +798,8 @@ export function createAircraftNavaraRenderer({
|
||||
pickId: id,
|
||||
}));
|
||||
return {
|
||||
// Fewer than 2 distinct positions draw nothing; consecutive
|
||||
// near-duplicates are dropped.
|
||||
setPositions(cartesians) {
|
||||
if (destroyed) return;
|
||||
const positions = [];
|
||||
@@ -754,28 +827,37 @@ export function createAircraftNavaraRenderer({
|
||||
line?.setPositions(current);
|
||||
},
|
||||
destroy() {
|
||||
line?.destroy();
|
||||
dropLine(line);
|
||||
line = null;
|
||||
},
|
||||
};
|
||||
},
|
||||
// The live head segment: its positions are read each frame while shown.
|
||||
createHead({ id, show, positions, color, width = 2.5 }) {
|
||||
if (destroyed) return null;
|
||||
const [r, g, b] = rgbaFromCss(color).rgba();
|
||||
const line = engine.lines.createLine({
|
||||
const line = lineOf({
|
||||
id: `${id}`,
|
||||
widthPx: width,
|
||||
color: [r, g, b, 0.9],
|
||||
depthFailAlpha: 0.5,
|
||||
color: [r, g, b, HEAD_ALPHA],
|
||||
depthFailAlpha: HEAD_OCCLUDED_ALPHA / HEAD_ALPHA,
|
||||
arc: 'geodesic',
|
||||
pickId: id,
|
||||
});
|
||||
let shown = show !== false;
|
||||
line.show(shown);
|
||||
// Written only when they move: each write requests a render.
|
||||
let drawn = [];
|
||||
const remove = engine.frames.preRender.addEventListener(() => {
|
||||
if (!shown) return;
|
||||
line.setPositions(positions());
|
||||
const next = (positions() ?? []).map((position) =>
|
||||
geo.cartesian3.clone(position),
|
||||
);
|
||||
if (samePositions(next, drawn)) return;
|
||||
drawn = next;
|
||||
line.setPositions(next);
|
||||
});
|
||||
return {
|
||||
const head = {
|
||||
id,
|
||||
get show() {
|
||||
return shown;
|
||||
@@ -785,10 +867,13 @@ export function createAircraftNavaraRenderer({
|
||||
line.show(shown);
|
||||
},
|
||||
remove() {
|
||||
if (!heads.delete(head)) return;
|
||||
remove();
|
||||
line.destroy();
|
||||
dropLine(line);
|
||||
},
|
||||
};
|
||||
heads.add(head);
|
||||
return head;
|
||||
},
|
||||
removeHead(head) {
|
||||
head?.remove();
|
||||
@@ -796,7 +881,6 @@ export function createAircraftNavaraRenderer({
|
||||
};
|
||||
|
||||
return {
|
||||
kind: 'navara',
|
||||
engine,
|
||||
view,
|
||||
fleet,
|
||||
@@ -806,41 +890,45 @@ export function createAircraftNavaraRenderer({
|
||||
trails,
|
||||
/** The atlas is drawn (tests, QA). */
|
||||
whenReady: () => atlasReady,
|
||||
/** A vertical surface probe skips the layer's own mover sets (by id). */
|
||||
/** A vertical surface probe skips the layer's own mover sets. */
|
||||
surfaceExclusions: () =>
|
||||
[...spriteBanks.values(), ...modelBanks.values(), trackedBank]
|
||||
.map((bank) => bank?.set?.id)
|
||||
[...spriteBanks.values(), ...modelBanks.values()]
|
||||
.map((bank) => bank.set)
|
||||
.filter(Boolean),
|
||||
destroy() {
|
||||
if (destroyed) return;
|
||||
flush();
|
||||
destroyed = true;
|
||||
attached = false;
|
||||
for (const remove of removers.splice(0)) remove?.();
|
||||
fleet.detach();
|
||||
for (const bank of spriteBanks.values()) bank.destroy();
|
||||
spriteBanks.clear();
|
||||
unbanked.clear();
|
||||
for (const bank of modelBanks.values()) bank.destroy();
|
||||
modelBanks.clear();
|
||||
trackedBank?.destroy();
|
||||
trackedBank = null;
|
||||
trackedSprites.clear();
|
||||
for (const head of [...heads]) head.remove();
|
||||
for (const line of [...lines]) dropLine(line);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The Navara registry factory (src/app/layers/renderers.js) of one aircraft
|
||||
* layer: its sprite slot (data/spriteOrder's order on Cesium) and its
|
||||
* model's nose offset.
|
||||
* The registry factory of one aircraft layer (src/app/layers/renderers.js
|
||||
* and the Navara mode register the same one): its sprite slot
|
||||
* (data/spriteOrder's order) and its model's nose offset. `drawAtlas` is a
|
||||
* test seam.
|
||||
* @param {string} layerId
|
||||
* @param {number} headingOffsetDeg
|
||||
*/
|
||||
export function aircraftLayerNavaraRenderer(layerId, headingOffsetDeg) {
|
||||
export function aircraftLayerDisplay(layerId, headingOffsetDeg) {
|
||||
/** @param {import('../../../globe/contract.js').GlobeEngine} engine */
|
||||
return (engine) =>
|
||||
createAircraftNavaraRenderer({
|
||||
engine,
|
||||
return (engine, { drawAtlas } = {}) =>
|
||||
createAircraftDisplay(engine, {
|
||||
layerId,
|
||||
order: SPRITE_LAYER_ORDER.indexOf(layerId),
|
||||
headingOffsetDeg,
|
||||
...(drawAtlas ? { drawAtlas } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,854 @@
|
||||
// The aircraft display on the engine contract, on the fake engine and on the
|
||||
// Cesium engine (real Cesium collections, billboards, models and
|
||||
// polylines over a stub scene: they draw nothing but hold what the engine
|
||||
// writes): the fleet's sprite sets, handle writes committed once per frame,
|
||||
// the tracked glyph's per-frame callbacks, the follow and its readout label,
|
||||
// model poses, loads and readiness, the view, the trail lines and teardown.
|
||||
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { createFakeEngine } from '../../../globe/testing/fakeEngine.js';
|
||||
import { createCesiumMoversEngine } from '../../../testSupport/cesiumMoversEngine.mjs';
|
||||
import { aircraftIcon, TRACKED_ICON_PX } from '../../../data/aircraftIcons.js';
|
||||
import { CYAN, WHITE, nearFarScale, rgbaFromCss } from '../../shared/color.js';
|
||||
import {
|
||||
aircraftAtlasLayout,
|
||||
aircraftIconCells,
|
||||
aircraftLayerDisplay,
|
||||
createAircraftDisplay,
|
||||
} from './display.js';
|
||||
|
||||
const layout = aircraftAtlasLayout();
|
||||
const drawAtlas = async () => ({
|
||||
canvas: { width: layout.width, height: layout.height },
|
||||
cells: layout.cells,
|
||||
});
|
||||
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
const AXIS = Cesium.Matrix4.multiplyTransformation(
|
||||
Cesium.Axis.Y_UP_TO_Z_UP,
|
||||
Cesium.Axis.Z_UP_TO_X_UP,
|
||||
new Cesium.Matrix4(),
|
||||
);
|
||||
const SCALE_BY_DISTANCE = nearFarScale(1000, 3.0, 8000000, 0.5);
|
||||
|
||||
function fakeHarness() {
|
||||
const engine = createFakeEngine();
|
||||
return {
|
||||
name: 'the fake engine',
|
||||
engine,
|
||||
frame: () => engine.fake.frame(),
|
||||
destroy: () => engine.destroy(),
|
||||
};
|
||||
}
|
||||
|
||||
function cesiumHarness() {
|
||||
const { engine, ...rest } = createCesiumMoversEngine();
|
||||
return {
|
||||
name: 'the Cesium engine',
|
||||
cesium: true,
|
||||
engine,
|
||||
...rest,
|
||||
destroy: () => engine.destroy(),
|
||||
};
|
||||
}
|
||||
|
||||
const HARNESSES = [fakeHarness, cesiumHarness];
|
||||
|
||||
async function setup(makeHarness, options = {}) {
|
||||
const harness = makeHarness();
|
||||
harness.engine.camera.setView({
|
||||
destination: geo.cartesian3.fromDegrees(-97.7, 30.2, 50_000),
|
||||
});
|
||||
const display = createAircraftDisplay(harness.engine, {
|
||||
layerId: 'flights',
|
||||
order: 8,
|
||||
headingOffsetDeg: 180,
|
||||
drawAtlas,
|
||||
...options,
|
||||
});
|
||||
await display.whenReady();
|
||||
display.fleet.attach();
|
||||
return { ...harness, display };
|
||||
}
|
||||
|
||||
const setsOf = (engine, prefix) =>
|
||||
engine.movers.list().filter(({ id }) => id.startsWith(prefix));
|
||||
|
||||
const near = (actual, expected, label, tolerance = 1e-6) =>
|
||||
assert.ok(
|
||||
Math.abs(actual - expected) < tolerance,
|
||||
`${label}: ${actual} vs ${expected}`,
|
||||
);
|
||||
|
||||
const fleetSpec = (overrides = {}) => ({
|
||||
position: geo.cartesian3.fromDegrees(-97.7, 30.2, 3000),
|
||||
image: aircraftIcon('helicopter'),
|
||||
width: 20,
|
||||
height: 20,
|
||||
scale: 1.5,
|
||||
rotation: 0.3,
|
||||
color: rgbaFromCss('#FFB800'),
|
||||
scaleByDistance: SCALE_BY_DISTANCE,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
id: 'abc123',
|
||||
show: true,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const trackedSpec = (state) => ({
|
||||
position: () => state.position,
|
||||
image: aircraftIcon('airliner', TRACKED_ICON_PX),
|
||||
width: 28,
|
||||
height: 28,
|
||||
scale: 1.2,
|
||||
color: () => state.color,
|
||||
scaleByDistance: SCALE_BY_DISTANCE,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
rotation: () => 0.25,
|
||||
});
|
||||
|
||||
test('the display needs a globe engine', () => {
|
||||
assert.throws(() => createAircraftDisplay(null, { layerId: 'x' }), TypeError);
|
||||
});
|
||||
|
||||
test('the atlas has every glyph at the fleet and tracked sizes', () => {
|
||||
const cells = aircraftIconCells();
|
||||
for (const key of cells.values())
|
||||
assert.ok(layout.cells[key], `${key} in the atlas`);
|
||||
for (const [, [u0, v0, u1, v1]] of Object.entries(layout.cells))
|
||||
assert.ok(u0 >= 0 && v0 >= 0 && u1 <= 1 && v1 <= 1 && u1 > u0 && v1 > v0);
|
||||
assert.equal(
|
||||
cells.get(aircraftIcon('quadjet', TRACKED_ICON_PX)),
|
||||
`quadjet@${TRACKED_ICON_PX}`,
|
||||
);
|
||||
});
|
||||
|
||||
test("a layer's factory puts its sprites in its data/spriteOrder slot", async () => {
|
||||
const engine = createFakeEngine();
|
||||
const display = aircraftLayerDisplay('military', 90)(engine, { drawAtlas });
|
||||
await display.whenReady();
|
||||
display.fleet.attach();
|
||||
display.fleet.add(fleetSpec());
|
||||
await Promise.resolve();
|
||||
const [listed] = setsOf(engine, 'military-sprites');
|
||||
assert.equal(engine.fake.moverSet(listed.id).options.order, 8);
|
||||
display.destroy();
|
||||
engine.destroy();
|
||||
});
|
||||
|
||||
for (const makeHarness of HARNESSES) {
|
||||
const { name } = makeHarness();
|
||||
|
||||
test(`fleet sprites draw as the layer asked, written once per frame (${name})`, async () => {
|
||||
const h = await setup(makeHarness);
|
||||
const { engine, display } = h;
|
||||
assert.equal(display.fleet.attached(), true);
|
||||
assert.equal(display.fleet.visible(), true);
|
||||
const spec = fleetSpec();
|
||||
const sprite = display.fleet.add(spec);
|
||||
assert.equal(sprite.id, 'abc123');
|
||||
assert.equal(sprite.width, 20);
|
||||
await settle();
|
||||
const [listed] = setsOf(engine, 'flights-sprites');
|
||||
assert.equal(listed.count, 1);
|
||||
if (h.cesium) {
|
||||
const collection = h.primitive(listed.id);
|
||||
assert.ok(collection instanceof Cesium.BillboardCollection);
|
||||
const billboard = collection.get(0);
|
||||
assert.ok(Cesium.Cartesian3.equals(billboard.position, spec.position));
|
||||
assert.equal(billboard.id, 'abc123');
|
||||
near(billboard.scale, 1.5, 'scale');
|
||||
near(billboard.rotation, 0.3, 'rotation');
|
||||
assert.equal(billboard.width, 20);
|
||||
assert.equal(billboard.height, 20);
|
||||
assert.equal(
|
||||
billboard.disableDepthTestDistance,
|
||||
Number.POSITIVE_INFINITY,
|
||||
);
|
||||
assert.ok(
|
||||
Cesium.NearFarScalar.equals(
|
||||
billboard.scaleByDistance,
|
||||
new Cesium.NearFarScalar(1000, 3, 8000000, 0.5),
|
||||
),
|
||||
);
|
||||
assert.ok(
|
||||
billboard.color.equalsEpsilon(
|
||||
Cesium.Color.fromCssColorString('#FFB800'),
|
||||
1e-6,
|
||||
),
|
||||
);
|
||||
assert.equal(billboard.show, true);
|
||||
} else {
|
||||
const set = engine.fake.moverSet(listed.id);
|
||||
assert.equal(set.options.depthTest, 'always');
|
||||
assert.deepEqual(
|
||||
set.options.sprite.scaleByDistance,
|
||||
[1000, 3, 8000000, 0.5],
|
||||
);
|
||||
assert.equal(set.options.sprite.sizePx, 20);
|
||||
assert.equal(set.options.order, 8);
|
||||
assert.equal(set.options.pickable, true);
|
||||
const { store } = set;
|
||||
assert.equal(store.positions[0], spec.position.x);
|
||||
assert.equal(store.pickIds[0], 'abc123');
|
||||
assert.equal(store.cellKeys[store.cells[0]], 'helicopter@64');
|
||||
near(store.scales[0], 1.5, 'scale');
|
||||
near(store.rotations[0], 0.3, 'rotation');
|
||||
near(store.colors[1], 184 / 255, 'green');
|
||||
}
|
||||
// Writes inside a frame listener commit at its end, once.
|
||||
const commits = h.cesium
|
||||
? null
|
||||
: () => engine.fake.moverSet(listed.id).commits;
|
||||
const before = commits?.();
|
||||
const remove = display.view.on('preRender', () => {
|
||||
sprite.color = WHITE.withAlpha(0.45);
|
||||
sprite.scale = 2;
|
||||
sprite.width = 24;
|
||||
sprite.image = aircraftIcon('helicopter', TRACKED_ICON_PX);
|
||||
sprite.show = false;
|
||||
});
|
||||
h.frame();
|
||||
remove();
|
||||
if (commits) assert.equal(commits(), before + 1);
|
||||
assert.equal(sprite.color.alpha, 0.45);
|
||||
if (h.cesium) {
|
||||
const billboard = h.primitive(listed.id).get(0);
|
||||
near(billboard.color.alpha, 0.45, 'alpha');
|
||||
near(billboard.scale, 2.4, 'scale × width/20');
|
||||
assert.equal(billboard.show, false);
|
||||
} else {
|
||||
const { store } = engine.fake.moverSet(listed.id);
|
||||
near(store.colors[3], 0.45, 'alpha');
|
||||
near(store.scales[0], 2.4, 'scale × width/20');
|
||||
assert.equal(
|
||||
store.cellKeys[store.cells[0]],
|
||||
`helicopter@${TRACKED_ICON_PX}`,
|
||||
);
|
||||
assert.equal(store.shows[0], 0);
|
||||
}
|
||||
// Removal moves the last sprite into the hole.
|
||||
const other = display.fleet.add(
|
||||
fleetSpec({ image: aircraftIcon('light'), id: 'def456' }),
|
||||
);
|
||||
display.fleet.remove(sprite);
|
||||
await settle();
|
||||
assert.equal(setsOf(engine, 'flights-sprites')[0].count, 1);
|
||||
assert.equal(other.gevIndex, 0);
|
||||
if (h.cesium) assert.equal(h.primitive(listed.id).get(0).id, 'def456');
|
||||
else
|
||||
assert.equal(engine.fake.moverSet(listed.id).store.pickIds[0], 'def456');
|
||||
// Another depth mode is another set.
|
||||
other.disableDepthTestDistance = 0;
|
||||
await settle();
|
||||
assert.equal(setsOf(engine, 'flights-sprites').length, 2);
|
||||
display.fleet.setVisible(false);
|
||||
await settle();
|
||||
assert.equal(display.fleet.visible(), false);
|
||||
assert.ok(setsOf(engine, 'flights-sprites').every(({ count }) => !count));
|
||||
display.fleet.detach();
|
||||
assert.equal(display.fleet.attached(), false);
|
||||
assert.equal(setsOf(engine, 'flights-sprites').length, 0);
|
||||
display.destroy();
|
||||
assert.equal(engine.movers.list().length, 0, 'no set left behind');
|
||||
h.destroy();
|
||||
});
|
||||
|
||||
test(`a model pose is the heading-pitch-roll frame with the nose offset; the instance turns the glTF's own axes (${name})`, async () => {
|
||||
const h = await setup(makeHarness);
|
||||
const { engine, display } = h;
|
||||
const model = await display.models.loadFleet({
|
||||
url: '/models/airplane.glb',
|
||||
minimumPixelSize: 24,
|
||||
scale: 1,
|
||||
radiusM: 34.41,
|
||||
color: WHITE,
|
||||
blendAmount: 0.94,
|
||||
unlit: false,
|
||||
id: 'abc123',
|
||||
});
|
||||
model.show = false;
|
||||
display.models.add(model);
|
||||
const position = geo.cartesian3.fromDegrees(-97.7, 30.2, 3000);
|
||||
const written = display.models.setPose(model, position, 75);
|
||||
assert.equal(written, model.modelMatrix, 'the model own matrix');
|
||||
const expected = Cesium.Transforms.headingPitchRollToFixedFrame(
|
||||
position,
|
||||
new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(75 + 180), 0, 0),
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
);
|
||||
for (let index = 0; index < 16; index++)
|
||||
near(model.modelMatrix[index], expected[index], `modelMatrix ${index}`);
|
||||
// What draws: the model frame × Cesium's glTF axis correction, which
|
||||
// Cesium's own Model applied to the model frame (the movers load the
|
||||
// glTF uncorrected).
|
||||
const drawn = Cesium.Matrix4.multiplyTransformation(
|
||||
expected,
|
||||
AXIS,
|
||||
new Cesium.Matrix4(),
|
||||
);
|
||||
await settle();
|
||||
const [listed] = setsOf(engine, 'flights-models');
|
||||
assert.equal(listed.count, 1);
|
||||
if (h.cesium) {
|
||||
const [instance] = h.loads;
|
||||
for (let index = 0; index < 12; index++)
|
||||
near(instance.modelMatrix[index], drawn[index], `drawn ${index}`);
|
||||
assert.equal(instance.show, false, 'admitted hidden');
|
||||
assert.equal(instance.id, 'abc123');
|
||||
assert.equal(model.ready, false, 'until the model has loaded');
|
||||
instance.ready = true;
|
||||
assert.equal(model.ready, true);
|
||||
} else {
|
||||
const q = Cesium.Quaternion.fromRotationMatrix(
|
||||
Cesium.Matrix4.getMatrix3(drawn, new Cesium.Matrix3()),
|
||||
);
|
||||
const { store, options } = engine.fake.moverSet(listed.id);
|
||||
assert.equal(options.model.minimumPixelSize, 24);
|
||||
assert.deepEqual(options.model.colorBlend, { mode: 'mix', amount: 0.94 });
|
||||
for (const [k, value] of ['x', 'y', 'z', 'w'].entries())
|
||||
near(store.orientations[k], q[value], value, 1e-9);
|
||||
assert.equal(store.shows[0], 0, 'admitted hidden');
|
||||
assert.equal(model.ready, true, 'the fake engine draws at once');
|
||||
}
|
||||
model.show = true;
|
||||
await settle();
|
||||
if (h.cesium) assert.equal(h.loads[0].show, true);
|
||||
else
|
||||
assert.equal(
|
||||
engine.fake.moverSet(listed.id).store.shows[0],
|
||||
1,
|
||||
'shown once placed',
|
||||
);
|
||||
assert.ok(model.computedScale >= model.scale);
|
||||
// A per-model nose offset (military per-class specs).
|
||||
display.models.setPose(model, position, 75, 90);
|
||||
const offset = Cesium.Transforms.headingPitchRollToFixedFrame(
|
||||
position,
|
||||
new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(75 + 90), 0, 0),
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
);
|
||||
for (let index = 0; index < 16; index++)
|
||||
near(model.modelMatrix[index], offset[index], `offset ${index}`);
|
||||
display.models.setVisible(false);
|
||||
await settle();
|
||||
assert.equal(setsOf(engine, 'flights-models')[0].count, 0);
|
||||
assert.equal(display.models.live(), true);
|
||||
display.destroy();
|
||||
assert.equal(display.models.live(), false);
|
||||
assert.equal(engine.movers.list().length, 0);
|
||||
h.destroy();
|
||||
});
|
||||
|
||||
test(`the tracked glyph reads its callbacks every frame; the follow centres it and carries its readout label (${name})`, async () => {
|
||||
const h = await setup(makeHarness);
|
||||
const { engine, display } = h;
|
||||
const state = {
|
||||
position: geo.cartesian3.fromDegrees(-97.7, 30.2, 3000),
|
||||
color: CYAN,
|
||||
};
|
||||
const handle = display.tracked.create(trackedSpec(state));
|
||||
handle.gevTrackedId = 'flights:abc123';
|
||||
handle.gevLabelModel = { title: 'DAL123' };
|
||||
handle.gevDisplayPosition = () => state.position;
|
||||
assert.equal(display.tracked.isLive(handle), true);
|
||||
assert.deepEqual(display.tracked.billboardSize(handle), {
|
||||
width: 28,
|
||||
height: 28,
|
||||
scale: 1.2,
|
||||
scaleByDistance: { ...SCALE_BY_DISTANCE },
|
||||
});
|
||||
display.tracked.setViewFrom(handle, { x: 0, y: -2400, z: 1650 });
|
||||
assert.deepEqual(
|
||||
[handle.viewFrom.x, handle.viewFrom.y, handle.viewFrom.z],
|
||||
[0, -2400, 1650],
|
||||
);
|
||||
h.frame();
|
||||
await settle();
|
||||
const [listed] = setsOf(engine, 'flights-tracked');
|
||||
assert.equal(listed.count, 1);
|
||||
const read = () => {
|
||||
if (h.cesium) {
|
||||
const billboard = h.primitive(listed.id).get(0);
|
||||
return {
|
||||
x: billboard.position.x,
|
||||
alpha: billboard.color.alpha,
|
||||
rotation: billboard.rotation,
|
||||
id: billboard.id,
|
||||
};
|
||||
}
|
||||
const { store } = engine.fake.moverSet(listed.id);
|
||||
return {
|
||||
x: store.positions[0],
|
||||
alpha: store.colors[3],
|
||||
rotation: store.rotations[0],
|
||||
id: store.pickIds[0],
|
||||
};
|
||||
};
|
||||
assert.equal(read().id, handle.id);
|
||||
near(read().rotation, 0.25, 'rotation');
|
||||
if (h.cesium) {
|
||||
const billboard = h.primitive(listed.id).get(0);
|
||||
assert.equal(
|
||||
billboard.disableDepthTestDistance,
|
||||
Number.POSITIVE_INFINITY,
|
||||
);
|
||||
assert.equal(billboard.width, 20);
|
||||
near(billboard.scale, 1.2 * (28 / 20), 'scale × width/20');
|
||||
}
|
||||
state.position = geo.cartesian3.fromDegrees(-97.6, 30.2, 3000);
|
||||
state.color = CYAN.withAlpha(0);
|
||||
h.frame();
|
||||
assert.equal(read().x, state.position.x, 'the position, per frame');
|
||||
assert.equal(read().alpha, 0, 'the colour, per frame');
|
||||
|
||||
const stop = display.follow.start(handle);
|
||||
assert.equal(typeof stop, 'function');
|
||||
const following = engine.camera.following();
|
||||
assert.equal(following, handle.gevFollowHandle);
|
||||
assert.equal(following.native, handle, 'cockpit follows the glyph');
|
||||
assert.equal(following.label.id, 'flights:abc123');
|
||||
assert.equal(following.label.model(), handle.gevLabelModel);
|
||||
assert.equal(display.follow.isFollowing(handle), true);
|
||||
assert.equal(display.follow.current(), handle);
|
||||
if (h.cesium) {
|
||||
const proxy = h.viewer.trackedEntity;
|
||||
assert.ok(proxy instanceof Cesium.Entity);
|
||||
assert.equal(
|
||||
proxy.trackingReferenceFrame,
|
||||
Cesium.TrackingReferenceFrame.ENU,
|
||||
);
|
||||
assert.equal(proxy.gevTrackedId, 'flights:abc123');
|
||||
const time = h.viewer.clock.currentTime;
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.equals(proxy.viewFrom.getValue(time), {
|
||||
x: 0,
|
||||
y: -2400,
|
||||
z: 1650,
|
||||
}),
|
||||
);
|
||||
}
|
||||
// The glyph draws where the follow centred in its frame.
|
||||
const centred = state.position;
|
||||
assert.equal(following.target(), centred);
|
||||
state.position = geo.cartesian3.fromDegrees(-97.5, 30.2, 3000);
|
||||
if (h.cesium) {
|
||||
h.frame();
|
||||
assert.equal(read().x, centred.x, "the follow's sample");
|
||||
h.frame();
|
||||
} else h.frame();
|
||||
assert.equal(read().x, state.position.x);
|
||||
|
||||
display.follow.release();
|
||||
assert.equal(engine.camera.following(), null);
|
||||
assert.equal(display.follow.current(), undefined);
|
||||
assert.equal(display.follow.isFollowing(handle), false);
|
||||
if (h.cesium) assert.equal(h.viewer.trackedEntity, undefined);
|
||||
handle.resumeAircraftFollow();
|
||||
assert.equal(display.follow.current(), handle);
|
||||
display.tracked.remove(handle);
|
||||
assert.equal(engine.camera.following(), null);
|
||||
assert.equal(display.tracked.isLive(handle), false);
|
||||
await settle();
|
||||
assert.equal(setsOf(engine, 'flights-tracked')[0].count, 0);
|
||||
display.destroy();
|
||||
h.destroy();
|
||||
});
|
||||
|
||||
test(`a tracked glyph hidden through its follow's target stays hidden, as the Cockpit rides it (${name})`, async () => {
|
||||
const h = await setup(makeHarness);
|
||||
const { engine, display } = h;
|
||||
const state = {
|
||||
position: geo.cartesian3.fromDegrees(-97.7, 30.2, 3000),
|
||||
color: CYAN,
|
||||
};
|
||||
const handle = display.tracked.create(trackedSpec(state));
|
||||
display.tracked.setViewFrom(handle, { x: 0, y: -2400, z: 1650 });
|
||||
display.follow.start(handle);
|
||||
h.frame();
|
||||
await settle();
|
||||
const [listed] = setsOf(engine, 'flights-tracked');
|
||||
const drawn = () =>
|
||||
h.cesium
|
||||
? h.primitive(listed.id).get(0).show
|
||||
: engine.fake.moverSet(listed.id).store.shows[0] === 1;
|
||||
assert.equal(drawn(), true);
|
||||
// The Cockpit hides what the engine follows, then releases the follow.
|
||||
const ridden = engine.camera.following().native;
|
||||
assert.equal(ridden, handle);
|
||||
ridden.show = false;
|
||||
engine.camera.following().stop();
|
||||
state.position = geo.cartesian3.fromDegrees(-97.6, 30.2, 3000);
|
||||
h.frame();
|
||||
await settle();
|
||||
assert.equal(drawn(), false, 'not drawn while ridden');
|
||||
// Another distance scale moves it to another set, still hidden.
|
||||
handle.scaleByDistance = nearFarScale(1000, 2.0, 8000000, 0.5);
|
||||
await settle();
|
||||
const moved = setsOf(engine, 'flights-tracked').find(
|
||||
({ count }) => count === 1,
|
||||
);
|
||||
const shownIn = (set) =>
|
||||
h.cesium
|
||||
? h.primitive(set.id).get(0).show
|
||||
: engine.fake.moverSet(set.id).store.shows[0] === 1;
|
||||
assert.equal(shownIn(moved), false);
|
||||
ridden.show = true;
|
||||
ridden.resumeAircraftFollow();
|
||||
h.frame();
|
||||
await settle();
|
||||
assert.equal(shownIn(moved), true, 'drawn again on exit');
|
||||
assert.equal(display.follow.current(), handle);
|
||||
display.destroy();
|
||||
h.destroy();
|
||||
});
|
||||
|
||||
test(`another layer's follow reads as what it follows (${name})`, async () => {
|
||||
const h = await setup(makeHarness);
|
||||
const { engine, display } = h;
|
||||
const changes = [];
|
||||
const remove = display.follow.onChanged(() =>
|
||||
changes.push(display.follow.current()),
|
||||
);
|
||||
const native = h.cesium
|
||||
? new Cesium.Entity({
|
||||
position: geo.cartesian3.fromDegrees(0, 0, 400_000),
|
||||
viewFrom: new Cesium.Cartesian3(0, -900, 400),
|
||||
})
|
||||
: { gevSelectionOrigin: 'user' };
|
||||
if (h.cesium) {
|
||||
native.gevSelectionOrigin = 'user';
|
||||
h.viewer.entities.add(native);
|
||||
}
|
||||
engine.camera.follow({
|
||||
native,
|
||||
position: () => geo.cartesian3.fromDegrees(0, 0, 400_000),
|
||||
viewFrom: { x: 0, y: -900, z: 400 },
|
||||
});
|
||||
assert.equal(display.follow.current(), native);
|
||||
assert.equal(display.follow.current().gevSelectionOrigin, 'user');
|
||||
assert.deepEqual(changes, [native]);
|
||||
display.follow.release();
|
||||
assert.equal(engine.camera.following(), null);
|
||||
remove();
|
||||
display.destroy();
|
||||
h.destroy();
|
||||
});
|
||||
|
||||
test(`trails are geodesic lines in the trail pick namespace; the head follows each frame (${name})`, async () => {
|
||||
const h = await setup(makeHarness);
|
||||
const { engine, display } = h;
|
||||
const trail = display.trails.create({ color: '#00d4ff', width: 2.5 });
|
||||
const a = geo.cartesian3.fromDegrees(0, 0, 1000);
|
||||
const b = geo.cartesian3.fromDegrees(0.1, 0, 1000);
|
||||
trail.setPositions([a, a, b]);
|
||||
const [body] = engine.lines.list();
|
||||
assert.match(body.id, /^gev-trail:flights-/);
|
||||
assert.equal(body.points, 2, 'near-duplicates dropped');
|
||||
const base = Cesium.Color.fromCssColorString('#00d4ff');
|
||||
const alphas = (id) => {
|
||||
if (h.cesium) {
|
||||
const primitive = h.primitive(id);
|
||||
assert.equal(primitive.allowPicking, true);
|
||||
assert.equal(
|
||||
primitive.geometryInstances.geometry._arcType,
|
||||
Cesium.ArcType.GEODESIC,
|
||||
);
|
||||
assert.equal(primitive.geometryInstances.id, id);
|
||||
return [
|
||||
primitive.appearance.material.uniforms.color.alpha,
|
||||
primitive.depthFailAppearance.material.uniforms.color.alpha,
|
||||
];
|
||||
}
|
||||
const { options } = engine.fake.line(id);
|
||||
assert.equal(options.arc, 'geodesic');
|
||||
assert.equal(options.pickId, id);
|
||||
return [options.color[3], options.color[3] * options.depthFailAlpha];
|
||||
};
|
||||
// 0.85 where it passes the depth test, 0.4 where the scene hides it.
|
||||
const [bodyAlpha, bodyHidden] = alphas(body.id);
|
||||
near(bodyAlpha, 0.85, 'trail alpha');
|
||||
near(bodyHidden, 0.4, 'trail occluded alpha');
|
||||
if (h.cesium) {
|
||||
const { color } = h.primitive(body.id).appearance.material.uniforms;
|
||||
near(color.red, base.red, 'trail red');
|
||||
}
|
||||
trail.setPositions([a]);
|
||||
assert.equal(engine.lines.list()[0].points, 0, 'one point draws nothing');
|
||||
trail.setVisible(false);
|
||||
assert.equal(engine.lines.list()[0].shown, false);
|
||||
trail.setVisible(true);
|
||||
let ends = [a, b];
|
||||
const head = display.trails.createHead({
|
||||
id: 'gev-trail:fl-head-1',
|
||||
show: true,
|
||||
positions: () => ends,
|
||||
color: '#00d4ff',
|
||||
width: 2.5,
|
||||
});
|
||||
assert.equal(head.id, 'gev-trail:fl-head-1');
|
||||
h.frame();
|
||||
const headLine = engine.lines
|
||||
.list()
|
||||
.find(({ id }) => id === 'gev-trail:fl-head-1');
|
||||
assert.equal(headLine.points, 2);
|
||||
// 0.9 where it passes the depth test, 0.45 where the scene hides it.
|
||||
const [headAlpha, headHidden] = alphas(headLine.id);
|
||||
near(headAlpha, 0.9, 'head alpha');
|
||||
near(headHidden, 0.45, 'head occluded alpha');
|
||||
head.show = false;
|
||||
assert.equal(head.show, false);
|
||||
ends = [];
|
||||
h.frame();
|
||||
assert.equal(
|
||||
engine.lines.list().find(({ id }) => id === headLine.id).points,
|
||||
2,
|
||||
'a hidden head is not read',
|
||||
);
|
||||
display.trails.removeHead(head);
|
||||
trail.destroy();
|
||||
assert.equal(engine.lines.list().length, 0);
|
||||
// The display releases what the layer left.
|
||||
display.trails.createHead({
|
||||
id: 'gev-trail:fl-head-2',
|
||||
positions: () => [a, b],
|
||||
color: '#00d4ff',
|
||||
});
|
||||
display.trails.create({ color: '#00d4ff' }).setPositions([a, b]);
|
||||
assert.equal(engine.lines.list().length, 2);
|
||||
display.destroy();
|
||||
assert.equal(engine.lines.list().length, 0);
|
||||
h.frame();
|
||||
h.destroy();
|
||||
});
|
||||
|
||||
test(`the view: camera, frustum, horizon, frame number and viewport (${name})`, async () => {
|
||||
const h = await setup(makeHarness);
|
||||
const { engine, display } = h;
|
||||
engine.camera.setView({
|
||||
destination: geo.cartesian3.fromDegrees(-73.78, 40.0, 50_000),
|
||||
});
|
||||
const { view } = display;
|
||||
near(view.camera.positionCartographic.height, 50_000, 'height', 1);
|
||||
const inFrustum = view.frustumTester();
|
||||
const below = geo.cartesian3.fromDegrees(-73.78, 40.0, 0);
|
||||
const behind = geo.cartesian3.fromDegrees(106.22, -40.0, 0);
|
||||
const aboveCamera = geo.cartesian3.fromDegrees(-73.78, 40.0, 200_000);
|
||||
assert.equal(inFrustum(below), true);
|
||||
assert.equal(inFrustum(aboveCamera), false);
|
||||
assert.equal(view.horizon().isPointVisible(below), true);
|
||||
assert.equal(view.horizon().isPointVisible(behind), false);
|
||||
const screen = view.worldToWindow(below);
|
||||
const { width, height } = engine.host.size();
|
||||
near(screen.x, width / 2, 'centre x', 1);
|
||||
near(screen.y, height / 2, 'centre y', 1);
|
||||
assert.equal(view.viewportHeightPx(), height);
|
||||
const frame = view.frameNumber();
|
||||
h.frame();
|
||||
assert.equal(view.frameNumber(), frame + 1);
|
||||
let moved = 0;
|
||||
const remove = view.on('preUpdate', () => moved++);
|
||||
h.frame();
|
||||
remove();
|
||||
h.frame();
|
||||
assert.equal(moved, 1);
|
||||
display.destroy();
|
||||
h.destroy();
|
||||
});
|
||||
|
||||
test(`the surface probe skips the layer's own mover sets (${name})`, async () => {
|
||||
const h = await setup(makeHarness);
|
||||
const { engine, display } = h;
|
||||
display.fleet.add(fleetSpec());
|
||||
const model = await display.models.loadFleet({
|
||||
url: '/models/airplane.glb',
|
||||
id: 'abc123',
|
||||
});
|
||||
display.models.add(model);
|
||||
await settle();
|
||||
const excluded = display.surfaceExclusions({
|
||||
sprites: [],
|
||||
models: [model],
|
||||
});
|
||||
assert.deepEqual(
|
||||
excluded.map((set) => set.id).sort(),
|
||||
engine.movers
|
||||
.list()
|
||||
.map(({ id }) => id)
|
||||
.sort(),
|
||||
);
|
||||
// The engine's surface takes them (Cesium: hidden for the sample).
|
||||
assert.doesNotThrow(() =>
|
||||
engine.surface.sampleHeight(
|
||||
geo.cartographic.fromDegrees(-97.7, 30.2, 0),
|
||||
excluded,
|
||||
),
|
||||
);
|
||||
display.destroy();
|
||||
h.destroy();
|
||||
});
|
||||
}
|
||||
|
||||
test('the bank grows past its capacity without losing sprites', async () => {
|
||||
const { engine, display, destroy } = await setup(fakeHarness);
|
||||
for (let index = 0; index < 1500; index++)
|
||||
display.fleet.add({
|
||||
position: geo.cartesian3.fromDegrees(index * 0.01, 0, 1000),
|
||||
image: aircraftIcon('airliner'),
|
||||
id: `a${index}`,
|
||||
scaleByDistance: SCALE_BY_DISTANCE,
|
||||
});
|
||||
await Promise.resolve();
|
||||
const sets = setsOf(engine, 'flights-sprites');
|
||||
assert.equal(sets.length, 1);
|
||||
assert.equal(sets[0].count, 1500);
|
||||
assert.ok(sets[0].capacity >= 1500);
|
||||
const { store } = engine.fake.moverSet(sets[0].id);
|
||||
assert.equal(store.pickIds[1499], 'a1499');
|
||||
display.destroy();
|
||||
destroy();
|
||||
});
|
||||
|
||||
test('sprites added before the atlas draw once it is', async () => {
|
||||
const engine = createFakeEngine();
|
||||
let finish;
|
||||
const display = createAircraftDisplay(engine, {
|
||||
layerId: 'flights',
|
||||
drawAtlas: () => new Promise((resolve) => (finish = resolve)),
|
||||
});
|
||||
display.fleet.attach();
|
||||
const sprite = display.fleet.add(fleetSpec());
|
||||
await Promise.resolve();
|
||||
assert.equal(setsOf(engine, 'flights-sprites').length, 0);
|
||||
sprite.scale = 2;
|
||||
finish(await drawAtlas());
|
||||
await display.whenReady();
|
||||
await Promise.resolve();
|
||||
const [listed] = setsOf(engine, 'flights-sprites');
|
||||
assert.equal(listed.count, 1);
|
||||
near(engine.fake.moverSet(listed.id).store.scales[0], 2, 'latest scale');
|
||||
display.destroy();
|
||||
engine.destroy();
|
||||
});
|
||||
|
||||
test('unchanged sprite style does not upload or request another frame', async () => {
|
||||
const { engine, display, destroy } = await setup(fakeHarness);
|
||||
const sprite = display.fleet.add({
|
||||
id: 'same',
|
||||
position: geo.cartesian3.fromDegrees(0, 0, 1000),
|
||||
image: aircraftIcon('light'),
|
||||
});
|
||||
await Promise.resolve();
|
||||
const [listed] = setsOf(engine, 'flights-sprites');
|
||||
const part = engine.fake.moverSet(listed.id);
|
||||
const before = part.commits;
|
||||
const color = sprite.color;
|
||||
for (let n = 0; n < 1000; n++) {
|
||||
sprite.show = true;
|
||||
sprite.rotation = 0;
|
||||
sprite.scale = 1;
|
||||
sprite.width = 20;
|
||||
sprite.color = WHITE;
|
||||
}
|
||||
await Promise.resolve();
|
||||
assert.equal(part.commits, before);
|
||||
assert.equal(sprite.color, color);
|
||||
display.destroy();
|
||||
destroy();
|
||||
});
|
||||
|
||||
test('reused sprite field records are copied, including a mutated color getter', async () => {
|
||||
const { engine, display, destroy } = await setup(fakeHarness);
|
||||
const a = display.fleet.add({
|
||||
id: 'a',
|
||||
position: geo.cartesian3.fromDegrees(0, 0, 1000),
|
||||
image: aircraftIcon('light'),
|
||||
});
|
||||
const b = display.fleet.add({
|
||||
id: 'b',
|
||||
position: a.position,
|
||||
image: aircraftIcon('light'),
|
||||
});
|
||||
await Promise.resolve();
|
||||
const [listed] = setsOf(engine, 'flights-sprites');
|
||||
const { store } = engine.fake.moverSet(listed.id);
|
||||
const position = geo.cartesian3.create(7, 8, 9);
|
||||
a.position = position;
|
||||
position.x = 20;
|
||||
b.position = position;
|
||||
a.color.alpha = 0.25;
|
||||
// eslint-disable-next-line no-self-assign
|
||||
a.color = a.color;
|
||||
b.color = WHITE.withAlpha(0.75);
|
||||
await Promise.resolve();
|
||||
assert.deepEqual([...store.positions.subarray(0, 6)], [7, 8, 9, 20, 8, 9]);
|
||||
assert.equal(store.colors[3], 0.25);
|
||||
assert.equal(store.colors[7], 0.75);
|
||||
display.destroy();
|
||||
destroy();
|
||||
});
|
||||
|
||||
test("model loads on Cesium carry the layer's look; the IR boost is unlit; readiness is per model", async () => {
|
||||
const h = await setup(cesiumHarness);
|
||||
const { display, loads } = h;
|
||||
const spec = {
|
||||
url: '/models/airplane.glb',
|
||||
minimumPixelSize: 24,
|
||||
scale: 1,
|
||||
color: CYAN,
|
||||
blendAmount: 0.94,
|
||||
unlit: false,
|
||||
id: 'abc123',
|
||||
};
|
||||
const position = geo.cartesian3.fromDegrees(-97.7, 30.2, 3000);
|
||||
const fleet = await display.models.loadFleet(spec);
|
||||
const second = await display.models.loadFleet({ ...spec, id: 'def456' });
|
||||
const boosted = await display.models.loadTracked({
|
||||
...spec,
|
||||
unlit: true,
|
||||
minimumPixelSize: 40,
|
||||
id: 'ghi789',
|
||||
});
|
||||
for (const model of [fleet, second, boosted]) {
|
||||
display.models.add(model);
|
||||
display.models.setPose(model, position, 10);
|
||||
}
|
||||
await settle();
|
||||
assert.equal(loads.length, 3, 'one Cesium model per instance');
|
||||
const [first, other, unlit] = loads;
|
||||
for (const { options } of loads) {
|
||||
assert.equal(options.asynchronous, false);
|
||||
assert.deepEqual(options.environmentMapOptions, { enabled: false });
|
||||
assert.equal(options.url, '/models/airplane.glb');
|
||||
assert.equal(options.colorBlendMode, Cesium.ColorBlendMode.MIX);
|
||||
assert.equal(options.colorBlendAmount, 0.94);
|
||||
assert.equal(options.allowPicking, true);
|
||||
}
|
||||
assert.equal(first.options.minimumPixelSize, 24);
|
||||
assert.equal(first.options.customShader, undefined);
|
||||
assert.equal(unlit.options.minimumPixelSize, 40);
|
||||
assert.equal(
|
||||
unlit.options.customShader.lightingModel,
|
||||
Cesium.LightingModel.UNLIT,
|
||||
);
|
||||
assert.equal(first.id, 'abc123', 'picks name the aircraft');
|
||||
assert.equal(unlit.id, 'ghi789');
|
||||
assert.ok(first.color.equalsEpsilon(Cesium.Color.CYAN, 1e-6));
|
||||
// Readiness is each model's own: one loading model leaves the others up.
|
||||
first.ready = true;
|
||||
unlit.ready = true;
|
||||
assert.equal(fleet.ready, true);
|
||||
assert.equal(second.ready, false);
|
||||
assert.equal(boosted.ready, true);
|
||||
other.ready = true;
|
||||
assert.equal(second.ready, true);
|
||||
// A removed model's place goes to the last one, ready with its model.
|
||||
display.models.remove(fleet);
|
||||
await settle();
|
||||
assert.equal(second.gevIndex, 0);
|
||||
assert.equal(second.ready, true);
|
||||
display.destroy();
|
||||
h.destroy();
|
||||
});
|
||||
@@ -1,357 +0,0 @@
|
||||
// The aircraft renderer on the engine contract (Navara's), over the fake
|
||||
// engine: the contract's members, sprite banks with the glyph atlas, handle
|
||||
// writes committed once per frame, the tracked glyph's per-frame callbacks,
|
||||
// the follow and its readout label, model poses and the trail lines.
|
||||
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import * as geo from '../../../geo/index.js';
|
||||
import { createFakeEngine } from '../../../globe/testing/fakeEngine.js';
|
||||
import { aircraftIcon, TRACKED_ICON_PX } from '../../../data/aircraftIcons.js';
|
||||
import { CYAN, WHITE, nearFarScale, rgbaFromCss } from '../../shared/color.js';
|
||||
import {
|
||||
aircraftAtlasLayout,
|
||||
aircraftIconCells,
|
||||
createAircraftNavaraRenderer,
|
||||
} from './navara.js';
|
||||
|
||||
const layout = aircraftAtlasLayout();
|
||||
const drawAtlas = async () => ({
|
||||
canvas: { width: layout.width, height: layout.height },
|
||||
cells: layout.cells,
|
||||
});
|
||||
|
||||
async function setup() {
|
||||
const engine = createFakeEngine();
|
||||
const renderer = createAircraftNavaraRenderer({
|
||||
engine,
|
||||
layerId: 'flights',
|
||||
order: 8,
|
||||
headingOffsetDeg: 180,
|
||||
drawAtlas,
|
||||
});
|
||||
await renderer.whenReady();
|
||||
return { engine, renderer };
|
||||
}
|
||||
|
||||
const setsOf = (engine, prefix) =>
|
||||
engine.movers.list().filter(({ id }) => id.startsWith(prefix));
|
||||
|
||||
test('the Navara aircraft renderer reports its kind', async () => {
|
||||
const { engine, renderer } = await setup();
|
||||
assert.equal(renderer.kind, 'navara');
|
||||
renderer.destroy();
|
||||
engine.destroy();
|
||||
});
|
||||
|
||||
test('the atlas has every glyph at the fleet and tracked sizes', () => {
|
||||
const cells = aircraftIconCells();
|
||||
for (const key of cells.values())
|
||||
assert.ok(layout.cells[key], `${key} in the atlas`);
|
||||
for (const [, [u0, v0, u1, v1]] of Object.entries(layout.cells))
|
||||
assert.ok(u0 >= 0 && v0 >= 0 && u1 <= 1 && v1 <= 1 && u1 > u0 && v1 > v0);
|
||||
assert.equal(
|
||||
cells.get(aircraftIcon('quadjet', TRACKED_ICON_PX)),
|
||||
`quadjet@${TRACKED_ICON_PX}`,
|
||||
);
|
||||
});
|
||||
|
||||
test('fleet sprites write the mover store, once per frame', async () => {
|
||||
const { engine, renderer } = await setup();
|
||||
const position = geo.cartesian3.fromDegrees(-97.7, 30.2, 3000);
|
||||
const sprite = renderer.fleet.add({
|
||||
position,
|
||||
image: aircraftIcon('helicopter'),
|
||||
width: 20,
|
||||
height: 20,
|
||||
scale: 1.5,
|
||||
rotation: 0.3,
|
||||
color: rgbaFromCss('#FFB800'),
|
||||
scaleByDistance: nearFarScale(1000, 3.0, 8000000, 0.5),
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
id: 'abc123',
|
||||
show: true,
|
||||
});
|
||||
await Promise.resolve();
|
||||
const [listed] = setsOf(engine, 'flights-sprites');
|
||||
const set = engine.fake.moverSet(listed.id);
|
||||
assert.equal(set.options.depthTest, 'always');
|
||||
assert.deepEqual(set.options.sprite.scaleByDistance, [1000, 3, 8000000, 0.5]);
|
||||
assert.equal(set.options.sprite.sizePx, 20);
|
||||
assert.equal(set.options.order, 8);
|
||||
const { store } = set;
|
||||
assert.equal(store.count, 1);
|
||||
assert.equal(store.positions[0], position.x);
|
||||
assert.equal(store.pickIds[0], 'abc123');
|
||||
assert.equal(store.cellKeys[store.cells[0]], 'helicopter@64');
|
||||
assert.ok(Math.abs(store.scales[0] - 1.5) < 1e-6);
|
||||
assert.ok(Math.abs(store.rotations[0] - 0.3) < 1e-6);
|
||||
assert.ok(Math.abs(store.colors[1] - 184 / 255) < 1e-6);
|
||||
// Writes inside a frame listener commit at its end, once.
|
||||
const before = set.commits;
|
||||
const remove = renderer.view.on('preRender', () => {
|
||||
sprite.color = WHITE.withAlpha(0.45);
|
||||
sprite.scale = 2;
|
||||
sprite.width = 24;
|
||||
sprite.image = aircraftIcon('helicopter', TRACKED_ICON_PX);
|
||||
sprite.show = false;
|
||||
});
|
||||
engine.fake.frame();
|
||||
remove();
|
||||
assert.equal(engine.fake.moverSet(listed.id).commits, before + 1);
|
||||
assert.ok(Math.abs(store.colors[3] - 0.45) < 1e-6);
|
||||
assert.ok(Math.abs(store.scales[0] - 2.4) < 1e-6, 'scale × width/20');
|
||||
assert.equal(store.cellKeys[store.cells[0]], `helicopter@${TRACKED_ICON_PX}`);
|
||||
assert.equal(store.shows[0], 0);
|
||||
assert.equal(sprite.color.alpha, 0.45);
|
||||
// Removal moves the last sprite into the hole.
|
||||
const other = renderer.fleet.add({
|
||||
position,
|
||||
image: aircraftIcon('light'),
|
||||
id: 'def456',
|
||||
scaleByDistance: nearFarScale(1000, 3.0, 8000000, 0.5),
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
});
|
||||
renderer.fleet.remove(sprite);
|
||||
await Promise.resolve();
|
||||
assert.equal(store.count, 1);
|
||||
assert.equal(store.pickIds[0], 'def456');
|
||||
assert.equal(other.gevIndex, 0);
|
||||
renderer.fleet.setVisible(false);
|
||||
await Promise.resolve();
|
||||
assert.equal(store.count, 0);
|
||||
assert.equal(renderer.fleet.visible(), false);
|
||||
renderer.destroy();
|
||||
assert.equal(setsOf(engine, 'flights').length, 0, 'no set left behind');
|
||||
engine.destroy();
|
||||
});
|
||||
|
||||
test('the bank grows past its capacity without losing sprites', async () => {
|
||||
const { engine, renderer } = await setup();
|
||||
const sprites = [];
|
||||
for (let index = 0; index < 1500; index++)
|
||||
sprites.push(
|
||||
renderer.fleet.add({
|
||||
position: geo.cartesian3.fromDegrees(index * 0.01, 0, 1000),
|
||||
image: aircraftIcon('airliner'),
|
||||
id: `a${index}`,
|
||||
scaleByDistance: nearFarScale(1000, 3.0, 8000000, 0.5),
|
||||
}),
|
||||
);
|
||||
await Promise.resolve();
|
||||
const sets = setsOf(engine, 'flights-sprites');
|
||||
assert.equal(sets.length, 1);
|
||||
assert.equal(sets[0].count, 1500);
|
||||
assert.ok(sets[0].capacity >= 1500);
|
||||
const { store } = engine.fake.moverSet(sets[0].id);
|
||||
assert.equal(store.pickIds[1499], 'a1499');
|
||||
renderer.destroy();
|
||||
engine.destroy();
|
||||
});
|
||||
|
||||
test('the tracked glyph reads its callbacks every frame; follow carries its readout label', async () => {
|
||||
const { engine, renderer } = await setup();
|
||||
let position = geo.cartesian3.fromDegrees(-97.7, 30.2, 3000);
|
||||
let color = CYAN;
|
||||
const handle = renderer.tracked.create({
|
||||
position: () => position,
|
||||
image: aircraftIcon('airliner', TRACKED_ICON_PX),
|
||||
width: 28,
|
||||
height: 28,
|
||||
scale: 1,
|
||||
color: () => color,
|
||||
scaleByDistance: nearFarScale(1000, 3.0, 8000000, 0.5),
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
rotation: () => 0.5,
|
||||
});
|
||||
handle.gevTrackedId = 'flights:abc123';
|
||||
handle.gevLabelModel = { title: 'DAL123' };
|
||||
handle.gevDisplayPosition = () => position;
|
||||
renderer.tracked.setViewFrom(handle, { x: 0, y: -2400, z: 1650 });
|
||||
engine.fake.frame();
|
||||
const [listed] = setsOf(engine, 'flights-tracked');
|
||||
const { store } = engine.fake.moverSet(listed.id);
|
||||
assert.equal(store.pickIds[0], handle.id);
|
||||
assert.ok(Math.abs(store.rotations[0] - 0.5) < 1e-6);
|
||||
position = geo.cartesian3.fromDegrees(-97.6, 30.2, 3000);
|
||||
color = CYAN.withAlpha(0);
|
||||
engine.fake.frame();
|
||||
assert.equal(
|
||||
store.positions[0],
|
||||
position.x,
|
||||
'the position callback, per frame',
|
||||
);
|
||||
assert.equal(store.colors[3], 0, 'the colour callback, per frame');
|
||||
|
||||
const stop = renderer.follow.start(handle);
|
||||
assert.equal(typeof stop, 'function');
|
||||
const following = engine.camera.following();
|
||||
assert.equal(following, handle.gevFollowHandle);
|
||||
assert.equal(
|
||||
following.native,
|
||||
handle,
|
||||
'cockpit follows the rendered aircraft',
|
||||
);
|
||||
assert.equal(following.label.id, 'flights:abc123');
|
||||
assert.equal(following.label.model(), handle.gevLabelModel);
|
||||
assert.equal(renderer.follow.isFollowing(handle), true);
|
||||
assert.equal(renderer.follow.current(), handle);
|
||||
renderer.follow.release();
|
||||
assert.equal(engine.camera.following(), null);
|
||||
assert.equal(renderer.follow.current(), undefined);
|
||||
handle.resumeAircraftFollow();
|
||||
assert.equal(renderer.follow.current(), handle);
|
||||
renderer.tracked.remove(handle);
|
||||
assert.equal(engine.camera.following(), null);
|
||||
assert.equal(renderer.tracked.isLive(handle), false);
|
||||
renderer.destroy();
|
||||
engine.destroy();
|
||||
});
|
||||
|
||||
test("a model pose is the Cesium model frame, turned to Navara's glTF axes", async () => {
|
||||
const { engine, renderer } = await setup();
|
||||
const model = await renderer.models.loadFleet({
|
||||
url: '/models/airplane.glb',
|
||||
minimumPixelSize: 24,
|
||||
scale: 1,
|
||||
radiusM: 34.41,
|
||||
color: WHITE,
|
||||
blendAmount: 0.94,
|
||||
unlit: false,
|
||||
id: 'abc123',
|
||||
});
|
||||
model.show = false;
|
||||
renderer.models.add(model);
|
||||
const position = geo.cartesian3.fromDegrees(-97.7, 30.2, 3000);
|
||||
renderer.models.setPose(model, position, 75);
|
||||
// modelMatrix is Cesium's (what the trail anchors read).
|
||||
const expected = Cesium.Transforms.headingPitchRollToFixedFrame(
|
||||
position,
|
||||
new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(75 + 180), 0, 0),
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
);
|
||||
for (let index = 0; index < 16; index++)
|
||||
assert.ok(Math.abs(model.modelMatrix[index] - expected[index]) < 1e-6);
|
||||
// The instance orientation: modelMatrix × Cesium's glTF axis correction
|
||||
// (Y_UP_TO_Z_UP × Z_UP_TO_X_UP; Navara's loader keeps the glTF Y-up).
|
||||
const corrected = Cesium.Matrix4.multiplyTransformation(
|
||||
expected,
|
||||
Cesium.Matrix4.multiplyTransformation(
|
||||
Cesium.Axis.Y_UP_TO_Z_UP,
|
||||
Cesium.Axis.Z_UP_TO_X_UP,
|
||||
new Cesium.Matrix4(),
|
||||
),
|
||||
new Cesium.Matrix4(),
|
||||
);
|
||||
const q = Cesium.Quaternion.fromRotationMatrix(
|
||||
Cesium.Matrix4.getMatrix3(corrected, new Cesium.Matrix3()),
|
||||
);
|
||||
await Promise.resolve();
|
||||
const [listed] = setsOf(engine, 'flights-models');
|
||||
const set = engine.fake.moverSet(listed.id);
|
||||
assert.equal(set.options.model.minimumPixelSize, 24);
|
||||
assert.deepEqual(set.options.model.colorBlend, { mode: 'mix', amount: 0.94 });
|
||||
const { store } = set;
|
||||
for (const [k, value] of ['x', 'y', 'z', 'w'].entries())
|
||||
assert.ok(
|
||||
Math.abs(store.orientations[k] - q[value]) < 1e-9,
|
||||
`${value}: ${[...store.orientations.slice(0, 4)]} vs ${[q.x, q.y, q.z, q.w]}`,
|
||||
);
|
||||
assert.equal(store.shows[0], 0, 'admitted hidden');
|
||||
model.show = true;
|
||||
await Promise.resolve();
|
||||
assert.equal(store.shows[0], 1);
|
||||
assert.equal(model.ready, true, 'the fake engine draws at once');
|
||||
assert.ok(model.computedScale >= model.scale);
|
||||
renderer.destroy();
|
||||
engine.destroy();
|
||||
});
|
||||
|
||||
test('trails are engine lines in the trail pick namespace; the head follows each frame', async () => {
|
||||
const { engine, renderer } = await setup();
|
||||
const trail = renderer.trails.create({ color: '#00d4ff', width: 2.5 });
|
||||
const a = geo.cartesian3.fromDegrees(0, 0, 1000);
|
||||
const b = geo.cartesian3.fromDegrees(0.1, 0, 1000);
|
||||
trail.setPositions([a, a, b]);
|
||||
const lines = engine.lines.list();
|
||||
assert.equal(lines.length, 1);
|
||||
const line = engine.fake.line(lines[0].id);
|
||||
assert.match(lines[0].id, /^gev-trail:/);
|
||||
assert.equal(line.options.pickId, lines[0].id);
|
||||
assert.ok(Math.abs(line.options.color[3] - 0.85) < 1e-9);
|
||||
assert.equal(line.options.arc, 'geodesic');
|
||||
let ends = [a, b];
|
||||
const head = renderer.trails.createHead({
|
||||
id: 'gev-trail:fl-head-1',
|
||||
show: true,
|
||||
positions: () => ends,
|
||||
color: '#00d4ff',
|
||||
width: 2.5,
|
||||
});
|
||||
engine.fake.frame();
|
||||
assert.equal(engine.lines.list().length, 2);
|
||||
head.show = false;
|
||||
ends = [];
|
||||
renderer.trails.removeHead(head);
|
||||
trail.destroy();
|
||||
assert.equal(engine.lines.list().length, 0);
|
||||
renderer.destroy();
|
||||
engine.destroy();
|
||||
});
|
||||
|
||||
test('unchanged sprite style does not upload or request another frame', async () => {
|
||||
const { engine, renderer } = await setup();
|
||||
const sprite = renderer.fleet.add({
|
||||
id: 'same',
|
||||
position: geo.cartesian3.fromDegrees(0, 0, 1000),
|
||||
image: aircraftIcon('light'),
|
||||
});
|
||||
await Promise.resolve();
|
||||
const [listed] = setsOf(engine, 'flights-sprites');
|
||||
const part = engine.fake.moverSet(listed.id);
|
||||
const before = part.commits;
|
||||
const color = sprite.color;
|
||||
for (let n = 0; n < 1000; n++) {
|
||||
sprite.show = true;
|
||||
sprite.rotation = 0;
|
||||
sprite.scale = 1;
|
||||
sprite.width = 20;
|
||||
sprite.color = WHITE;
|
||||
}
|
||||
await Promise.resolve();
|
||||
assert.equal(part.commits, before);
|
||||
assert.equal(sprite.color, color);
|
||||
renderer.destroy();
|
||||
engine.destroy();
|
||||
});
|
||||
|
||||
test('reused sprite field records are copied, including a mutated color getter', async () => {
|
||||
const { engine, renderer } = await setup();
|
||||
const a = renderer.fleet.add({
|
||||
id: 'a',
|
||||
position: geo.cartesian3.fromDegrees(0, 0, 1000),
|
||||
image: aircraftIcon('light'),
|
||||
});
|
||||
const b = renderer.fleet.add({
|
||||
id: 'b',
|
||||
position: a.position,
|
||||
image: aircraftIcon('light'),
|
||||
});
|
||||
await Promise.resolve();
|
||||
const [listed] = setsOf(engine, 'flights-sprites');
|
||||
const { store } = engine.fake.moverSet(listed.id);
|
||||
const position = geo.cartesian3.create(7, 8, 9);
|
||||
a.position = position;
|
||||
position.x = 20;
|
||||
b.position = position;
|
||||
a.color.alpha = 0.25;
|
||||
a.color = a.color;
|
||||
b.color = WHITE.withAlpha(0.75);
|
||||
await Promise.resolve();
|
||||
assert.deepEqual([...store.positions.subarray(0, 6)], [7, 8, 9, 20, 8, 9]);
|
||||
assert.equal(store.colors[3], 0.25);
|
||||
assert.equal(store.colors[7], 0.75);
|
||||
renderer.destroy();
|
||||
engine.destroy();
|
||||
});
|
||||
Reference in new issue
Block a user