mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
Draw Flights and Military 3D models through draw-port model sets
The two aircraft layers' fleet and tracked models are now draw-port models sets made each layer lifetime, re-posed and restyled in place, instead of Cesium models in a collection of their own. Model records are plain data; picks name the set and the contact, readiness comes from the set's ready event, the IR boost restyles in place (unlit, white tint, full blend), and the drawn scale comes from the camera pose and pixel floor. Fleet writes go out together at the end of each tick, before the icons they replace, and a failed write hands the contacts back to their icons. A model that has not loaded is rewritten every few seconds so the renderer can retry it, which replaces the tracked model's load-failure budget. Models load off the tile-contended job queue, as before. aircraftModelLayer.js, modelRecord.js and the flights and military lifecycle and testing files, plus flights rendering.js, come off the Cesium allow-list.
This commit is contained in:
1 parent
eed3b83858
commit
abe9f97768
28 files changed
+1310
-1255
No files matched your search
+463
-466
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,275 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createAircraftModels } from './aircraftModelLayer.js';
|
||||
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import { fromDegrees } from '../geo/ellipsoid.js';
|
||||
|
||||
const POLICY = {
|
||||
MODEL_ALT_CEIL_M: 800_000,
|
||||
MODEL_MAX: 40,
|
||||
MODEL_MAX_ALL: 350,
|
||||
COCKPIT_MODEL_MAX: 60,
|
||||
MODEL_PROX_ADD_M: 150_000,
|
||||
MODEL_PROX_KEEP_M: 185_000,
|
||||
MODEL_ALL_ADD_M: 400_000,
|
||||
MODEL_ALL_KEEP_M: 450_000,
|
||||
MODEL_MIN_PX: 24,
|
||||
TRACKED_MODEL_MIN_PX: 48,
|
||||
TRACKED_MODEL_MAX_PX: 600,
|
||||
MODEL_HEADING_OFFSET_DEG: 0,
|
||||
FLEET_DR_INTERVAL_MS: 80,
|
||||
};
|
||||
|
||||
const SPEC = {
|
||||
url: 'plane.glb',
|
||||
scale: 1,
|
||||
bellyM: 3,
|
||||
nativeRadiusM: 20,
|
||||
blendAmount: 0.9,
|
||||
};
|
||||
|
||||
/**
|
||||
* A fleet of airborne contacts at `positions` (icao → ECEF), drawn by a
|
||||
* models layer over a fake draw port whose fleet set can be told to fail a
|
||||
* write. The eye sits above them at 30 km.
|
||||
*/
|
||||
function fleetFixture(positions) {
|
||||
const base = fakeDrawPort();
|
||||
const removes = [];
|
||||
let failNextUpsert = false;
|
||||
const draw = {
|
||||
...base,
|
||||
models(spec) {
|
||||
const set = base.models(spec);
|
||||
return {
|
||||
...set,
|
||||
get show() {
|
||||
return set.show;
|
||||
},
|
||||
set show(value) {
|
||||
set.show = value;
|
||||
},
|
||||
id: set.id,
|
||||
upsert(items) {
|
||||
if (failNextUpsert && spec.id.includes('-models:')) {
|
||||
failNextUpsert = false;
|
||||
throw new Error('simulated write failure');
|
||||
}
|
||||
return set.upsert(items);
|
||||
},
|
||||
remove(ids) {
|
||||
removes.push([...ids]);
|
||||
return set.remove(ids);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
const eye = fromDegrees(-97.71, 30.21, 30_000);
|
||||
const viewer = {};
|
||||
bindRenderer(viewer, {
|
||||
draw,
|
||||
camera: {
|
||||
pose: () => ({
|
||||
position: eye,
|
||||
direction: { x: 0, y: 0, z: -1 },
|
||||
up: { x: 0, y: 1, z: 0 },
|
||||
right: { x: 1, y: 0, z: 0 },
|
||||
fovy: Math.PI / 3,
|
||||
aspectRatio: 1,
|
||||
height: 30_000,
|
||||
}),
|
||||
},
|
||||
});
|
||||
const shown = new Map([...positions.keys()].map((id) => [id, true]));
|
||||
const icons = {
|
||||
show: true,
|
||||
setId: 'flights-icons:1',
|
||||
ids: () => [...positions.keys()],
|
||||
has: (id) => positions.has(id),
|
||||
position: (id) => positions.get(id),
|
||||
course: () => 90,
|
||||
alpha: () => 1,
|
||||
focus: () => 1,
|
||||
setShown: (id, value) => shown.set(id, value),
|
||||
flush() {},
|
||||
};
|
||||
const state = {
|
||||
_viewer: viewer,
|
||||
_icons: icons,
|
||||
_models: new Map(),
|
||||
_modelSets: null,
|
||||
_trackedIcao: null,
|
||||
_trackedModel: null,
|
||||
_models3dEnabled: true,
|
||||
_models3dMode: 'proximity',
|
||||
_cockpitContactMode: false,
|
||||
_irBoost: false,
|
||||
_lastFleetTickMs: 0,
|
||||
_lastModelCapWarnMs: 0,
|
||||
records: {
|
||||
data: new Map(
|
||||
[...positions.keys()].map((id) => [id, { klass: 'airliner' }]),
|
||||
),
|
||||
},
|
||||
};
|
||||
let now = 1_000_000;
|
||||
const parts = {
|
||||
icons: {
|
||||
_displayMs: () => now,
|
||||
_syncImageSwitch() {},
|
||||
_replanExpired() {},
|
||||
_focusIcons() {},
|
||||
_occluder: () => null,
|
||||
_aboveHorizon: () => true,
|
||||
},
|
||||
motion: { _displayTimeAt: () => null },
|
||||
tracking: {
|
||||
_refreshCockpitNearContacts() {},
|
||||
_trackedModelRegimeActive: () => false,
|
||||
},
|
||||
};
|
||||
const models = createAircraftModels({
|
||||
state,
|
||||
services: {
|
||||
aircraftPresentation: { isTr3b: () => false },
|
||||
camera: { trackedModelScaleForPixelCap: ({ baseScale }) => baseScale },
|
||||
focus: { focusNowMs: () => now, getFocusTarget: () => null },
|
||||
},
|
||||
parts,
|
||||
resolveAsset: (url) => url,
|
||||
logLabel: 'Test',
|
||||
setPrefix: 'flights',
|
||||
policy: POLICY,
|
||||
modelSpec: () => SPEC,
|
||||
modelColor: () => ({ red: 1, green: 1, blue: 1, alpha: 1 }),
|
||||
});
|
||||
models._createModelSets(viewer);
|
||||
const fleetId = models._modelSetIds()[0];
|
||||
return {
|
||||
models,
|
||||
state,
|
||||
draw: base,
|
||||
fleet: () => base.set(fleetId),
|
||||
fleetId,
|
||||
removes,
|
||||
shown,
|
||||
failNextUpsert: () => (failNextUpsert = true),
|
||||
/** One fleet tick, past the tick interval. */
|
||||
tick() {
|
||||
now += 1000;
|
||||
models._fleetTick();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const near = (k) => fromDegrees(-97.71 + k * 0.01, 30.21, 10_000);
|
||||
const far = (k) => fromDegrees(-90 + k * 0.01, 30.21, 10_000);
|
||||
|
||||
test('the fleet tick hands contacts to ready models and back without a gap', () => {
|
||||
const positions = new Map([
|
||||
['a1', near(1)],
|
||||
['a2', near(2)],
|
||||
]);
|
||||
const f = fleetFixture(positions);
|
||||
f.tick();
|
||||
assert.deepEqual([...f.fleet().items.keys()].sort(), ['a1', 'a2']);
|
||||
assert.equal(
|
||||
f.shown.get('a1'),
|
||||
true,
|
||||
'icons carry contacts until models load',
|
||||
);
|
||||
f.draw.ready(f.fleetId, 'a1');
|
||||
f.tick();
|
||||
assert.equal(f.shown.get('a1'), false, 'a ready, placed model takes over');
|
||||
assert.equal(f.fleet().items.get('a1').show, true);
|
||||
assert.equal(
|
||||
f.shown.get('a2'),
|
||||
true,
|
||||
'a model still loading leaves its icon',
|
||||
);
|
||||
});
|
||||
|
||||
test('contacts leaving the model band are released in one write', () => {
|
||||
const positions = new Map([
|
||||
['a1', near(1)],
|
||||
['a2', near(2)],
|
||||
['a3', near(3)],
|
||||
]);
|
||||
const f = fleetFixture(positions);
|
||||
f.tick();
|
||||
for (const id of ['a1', 'a2', 'a3']) f.draw.ready(f.fleetId, id);
|
||||
f.tick();
|
||||
positions.set('a2', far(2));
|
||||
positions.set('a3', far(3));
|
||||
f.removes.length = 0;
|
||||
f.tick();
|
||||
assert.deepEqual(
|
||||
f.removes,
|
||||
[['a2', 'a3']],
|
||||
'one remove for every evicted model',
|
||||
);
|
||||
assert.deepEqual([...f.fleet().items.keys()], ['a1']);
|
||||
assert.equal(
|
||||
f.shown.get('a2'),
|
||||
true,
|
||||
'a released model hands back to its icon',
|
||||
);
|
||||
assert.equal(f.shown.get('a3'), true);
|
||||
});
|
||||
|
||||
test('a failed fleet write leaves the icons in charge and is sent again', () => {
|
||||
const positions = new Map([['a1', near(1)]]);
|
||||
const f = fleetFixture(positions);
|
||||
f.tick();
|
||||
f.draw.ready(f.fleetId, 'a1');
|
||||
const realWarn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
f.failNextUpsert();
|
||||
f.tick();
|
||||
} finally {
|
||||
console.warn = realWarn;
|
||||
}
|
||||
assert.equal(f.shown.get('a1'), true, 'the contact keeps its icon');
|
||||
assert.equal(
|
||||
f.fleet().items.get('a1').show,
|
||||
false,
|
||||
'the set still has the hidden model',
|
||||
);
|
||||
assert.equal(f.models._modelOwnsVisual('a1'), false);
|
||||
f.tick();
|
||||
assert.equal(
|
||||
f.fleet().items.get('a1').show,
|
||||
true,
|
||||
'the next tick sends it again',
|
||||
);
|
||||
assert.equal(f.shown.get('a1'), false);
|
||||
});
|
||||
|
||||
test('a model that has not loaded is written again for the renderer to retry', () => {
|
||||
const positions = new Map([['a1', near(1)]]);
|
||||
const f = fleetFixture(positions);
|
||||
const realNow = Date.now;
|
||||
let clock = 50_000_000;
|
||||
Date.now = () => clock;
|
||||
try {
|
||||
f.tick();
|
||||
const writes = f.fleet().writes;
|
||||
f.tick();
|
||||
assert.equal(
|
||||
f.fleet().writes,
|
||||
writes,
|
||||
'an unchanged loading model is not rewritten every tick',
|
||||
);
|
||||
clock += 5_000;
|
||||
f.tick();
|
||||
assert.equal(
|
||||
f.fleet().writes,
|
||||
writes + 1,
|
||||
'but it is rewritten every few seconds',
|
||||
);
|
||||
} finally {
|
||||
Date.now = realNow;
|
||||
}
|
||||
});
|
||||
@@ -5,10 +5,8 @@ import { readLayerSource } from '../testSupport/readLayerSource.mjs';
|
||||
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js';
|
||||
|
||||
/**
|
||||
* Every aircraft model drawn in the scene skips Cesium's dynamic environment
|
||||
* map (a sky render and GPU readback per model). The preload calls only warm
|
||||
* the glTF cache and are never added to the scene, so they are left out:
|
||||
* drawn models are the calls that set a minimum pixel size.
|
||||
* Every aircraft model drawn in the scene skips the renderer's dynamic
|
||||
* environment map (a sky render and GPU readback per model).
|
||||
*/
|
||||
const SOURCES = [
|
||||
{
|
||||
@@ -28,18 +26,15 @@ test('the shared option turns the dynamic environment map off', () => {
|
||||
|
||||
for (const { name, source } of SOURCES) {
|
||||
test(`${name}: every drawn aircraft model skips the dynamic environment map`, () => {
|
||||
const calls = [
|
||||
...source.matchAll(/(?:fromGltfAsync|loadModel)\(\{([\s\S]*?)\}\)/g),
|
||||
]
|
||||
.map((match) => match[1])
|
||||
.filter((options) => /\bminimumPixelSize:/.test(options));
|
||||
assert.ok(calls.length >= 1, `expected drawn model calls in ${name}`);
|
||||
for (const [index, options] of calls.entries())
|
||||
assert.match(
|
||||
options,
|
||||
/\benvironmentMapOptions:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\b/,
|
||||
`${name} model call ${index + 1} must pass AIRCRAFT_ENVIRONMENT_MAP_OPTIONS`,
|
||||
);
|
||||
// Its models are draw-port items; every item it builds (fleet, tracked
|
||||
// and the tracked preload) carries the shared option.
|
||||
assert.doesNotMatch(source, /fromGltfAsync|loadModel\(/);
|
||||
const items = [...source.matchAll(/\burl: (?:record\.url|preloadUrl),/g)];
|
||||
assert.ok(items.length >= 2, `expected model items in ${name}`);
|
||||
const flags = [
|
||||
...source.matchAll(/\benvironmentMap:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\.enabled\b/g),
|
||||
];
|
||||
assert.equal(flags.length, items.length, `${name} model items must pass AIRCRAFT_ENVIRONMENT_MAP_OPTIONS`);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,11 @@ import assert from 'node:assert/strict';
|
||||
* regression would silently revert. These assertions pin the decisions.
|
||||
*/
|
||||
|
||||
const DRAW_MODELS_SOURCE = readFileSync(
|
||||
new URL('../render/cesium/drawModels.js', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
const LAYERS = [
|
||||
{ name: 'flights', path: new URL('./flights.js', import.meta.url) },
|
||||
{ name: 'militaryFlights', path: new URL('./militaryFlights.js', import.meta.url) },
|
||||
@@ -29,8 +34,11 @@ for (const layer of LAYERS) {
|
||||
const source = readLayerSource(layer.path);
|
||||
|
||||
test(`${layer.name}: every GLB creation bypasses the tile-contended frame-spread queue`, () => {
|
||||
const calls = [...source.matchAll(/Cesium\.Model\.fromGltfAsync\(\{([\s\S]*?)\}\)/g)];
|
||||
assert.ok(calls.length >= 3, `expected fleet, tracked, and preload model calls; found ${calls.length}`);
|
||||
// The fleet and tracked models are draw-port models sets; the Cesium
|
||||
// draw port creates every model off the frame-spread queue.
|
||||
assert.match(source, /\.models\(\{\s*id:/, 'the layer draws its models as draw-port models sets');
|
||||
const calls = [...DRAW_MODELS_SOURCE.matchAll(/Cesium\.Model\.fromGltfAsync\(\{([\s\S]*?)\}\)/g)];
|
||||
assert.ok(calls.length >= 1, 'the draw port creates models');
|
||||
for (const [index, call] of calls.entries()) {
|
||||
assert.match(call[1], /\basynchronous:\s*false\b/,
|
||||
`Model.fromGltfAsync call ${index + 1} must keep bounded GLB readiness independent of tile jobs`);
|
||||
|
||||
@@ -40,6 +40,8 @@ export const _driveFleetModelHandoffForTest =
|
||||
flightsLayer.testing._driveFleetModelHandoffForTest;
|
||||
export const _ensureFleetModelForTest =
|
||||
flightsLayer.testing._ensureFleetModelForTest;
|
||||
export const _trackedModelForTest = flightsLayer.testing._trackedModelForTest;
|
||||
export const _modelSetIdsForTest = flightsLayer.testing._modelSetIdsForTest;
|
||||
export const _iconForTest = flightsLayer.testing._iconForTest;
|
||||
export const _setIconForTest = flightsLayer.testing._setIconForTest;
|
||||
export const _floorGroundedIconsForTest =
|
||||
|
||||
@@ -32,6 +32,10 @@ export const _driveFleetModelHandoffForTest =
|
||||
militaryFlightsLayer.testing._driveFleetModelHandoffForTest;
|
||||
export const _ensureFleetModelForTest =
|
||||
militaryFlightsLayer.testing._ensureFleetModelForTest;
|
||||
export const _trackedModelForTest =
|
||||
militaryFlightsLayer.testing._trackedModelForTest;
|
||||
export const _modelSetIdsForTest =
|
||||
militaryFlightsLayer.testing._modelSetIdsForTest;
|
||||
export const _iconForTest = militaryFlightsLayer.testing._iconForTest;
|
||||
export const _setIconForTest = militaryFlightsLayer.testing._setIconForTest;
|
||||
export const mapAnalystRecord = militaryFlightsLayer.mapAnalystRecord;
|
||||
|
||||
+97
-37
@@ -1,47 +1,71 @@
|
||||
/**
|
||||
* @module modelRecord
|
||||
* @description A layer's own record of one 3D model it draws, held in the
|
||||
* layer's maps under the contact's id, so the layer reads what it pushed back
|
||||
* from itself instead of from the renderer's object.
|
||||
* @description A layer's own record of one 3D model it draws through a draw
|
||||
* port `models` set, held in the layer's maps under the contact's id, so the
|
||||
* layer reads what it pushed (and what the set told it) back from itself.
|
||||
*
|
||||
* Write `show` and the placement with {@link showModel} and {@link placeModel};
|
||||
* read them from the record. What the renderer measures (`ready`,
|
||||
* `computedScale`) is still read from `record.model`. Colour stays out: the
|
||||
* cyber-sonar theme writes it too and reads the live value.
|
||||
* Write `show` and the placement with {@link showModel} and
|
||||
* {@link placeModel}; the set's `ready` event sets `ready`. The placement is
|
||||
* kept as the column-major frame the model is posed in, the same frame a
|
||||
* renderer builds from the item's position and heading, so anchors on the
|
||||
* model can be read from it.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { eastNorthUp } from '../geo/frames.js';
|
||||
|
||||
/**
|
||||
* @typedef {object} ModelRecord
|
||||
* @property {Cesium.Model} model
|
||||
* @property {string|null} id The item's id in its set, where the record
|
||||
* does not live under it in a map (the tracked model).
|
||||
* @property {string|null} url The model asset the layer sends.
|
||||
* @property {boolean} ready Whether the set reported the model loaded and
|
||||
* posed (`ready`).
|
||||
* @property {boolean} show Whether the layer last showed the model.
|
||||
* @property {Cesium.Matrix4} matrix Where the layer last placed it.
|
||||
* @property {string|null} specKey The model spec it was loaded for; a class
|
||||
* change reloads.
|
||||
* @property {boolean|null} irBoost The IR boost it was loaded with; a flip
|
||||
* reloads.
|
||||
* @property {boolean} placed Whether the layer has placed it yet.
|
||||
* @property {Float64Array} matrix Where the layer last placed it: the
|
||||
* east-north-up frame at its position turned by its heading, column-major.
|
||||
* @property {{x:number,y:number,z:number}} position Where it is placed.
|
||||
* @property {number} heading Radians, as the item's `orientation.heading`.
|
||||
* @property {string|null} specKey The model spec it was admitted for; a
|
||||
* class change readmits.
|
||||
* @property {number} bellyM Metres from the model origin to its belly, to sit
|
||||
* it on the ground.
|
||||
* @property {number} scale The `scale` the layer last sent.
|
||||
* @property {number} minPixelSize The `minPixelSize` the layer last sent.
|
||||
* @property {number[]|null} tint The `tint` the layer last sent.
|
||||
* @property {string|null} sent The item last sent, as a key, or null.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A record for a model the layer just made, from the options it made it with
|
||||
* (Cesium's defaults when none: shown, at the identity).
|
||||
* @param {Cesium.Model} model
|
||||
* @param {{specKey?: string, irBoost?: boolean, bellyM?: number}} [fields]
|
||||
* A record for a model the layer just admitted.
|
||||
* @param {{id?: string|null, url?: string|null, specKey?: string,
|
||||
* bellyM?: number, scale?: number, minPixelSize?: number}} [fields]
|
||||
* @returns {ModelRecord}
|
||||
*/
|
||||
export function createModelRecord(
|
||||
model,
|
||||
{ specKey = null, irBoost = null, bellyM = 0 } = {},
|
||||
) {
|
||||
export function createModelRecord({
|
||||
id = null,
|
||||
url = null,
|
||||
specKey = null,
|
||||
bellyM = 0,
|
||||
scale = 1,
|
||||
minPixelSize = 0,
|
||||
} = {}) {
|
||||
const matrix = new Float64Array(16);
|
||||
matrix[0] = matrix[5] = matrix[10] = matrix[15] = 1;
|
||||
return {
|
||||
model,
|
||||
show: model.show ?? true,
|
||||
matrix: Cesium.Matrix4.clone(model.modelMatrix ?? Cesium.Matrix4.IDENTITY),
|
||||
id,
|
||||
url,
|
||||
ready: false,
|
||||
show: false,
|
||||
placed: false,
|
||||
matrix,
|
||||
position: { x: 0, y: 0, z: 0 },
|
||||
heading: 0,
|
||||
specKey,
|
||||
irBoost,
|
||||
bellyM,
|
||||
scale,
|
||||
minPixelSize,
|
||||
tint: null,
|
||||
sent: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -52,21 +76,57 @@ export function createModelRecord(
|
||||
*/
|
||||
export function showModel(record, show) {
|
||||
record.show = show;
|
||||
record.model.show = show;
|
||||
}
|
||||
|
||||
/**
|
||||
* Place a model and record where. The matrix is copied into both, so a shared
|
||||
* scratch can be passed and reused straight after.
|
||||
* Place a model at `position` turned by `heading` (radians clockwise from
|
||||
* north about the local up, as `orientation.heading`), and record its frame.
|
||||
* @param {ModelRecord} record
|
||||
* @param {Cesium.Matrix4} matrix
|
||||
* @param {{x:number,y:number,z:number}} position ECEF; copied.
|
||||
* @param {number} heading
|
||||
*/
|
||||
export function placeModel(record, matrix) {
|
||||
Cesium.Matrix4.clone(matrix, record.matrix);
|
||||
const model = record.model;
|
||||
// Cesium clones the model's own matrix each frame, so write into it in place.
|
||||
if (model.modelMatrix) Cesium.Matrix4.clone(matrix, model.modelMatrix);
|
||||
else model.modelMatrix = Cesium.Matrix4.clone(matrix);
|
||||
export function placeModel(record, position, heading) {
|
||||
record.position.x = position.x;
|
||||
record.position.y = position.y;
|
||||
record.position.z = position.z;
|
||||
record.heading = heading;
|
||||
record.placed = true;
|
||||
headingFrame(record.position, heading, record.matrix);
|
||||
}
|
||||
|
||||
/**
|
||||
* The east-north-up frame at `origin` turned by `heading` about its up axis,
|
||||
* as a column-major 4x4: a heading of 0 keeps local x east, and a positive
|
||||
* heading turns it clockwise seen from above.
|
||||
* @param {{x:number,y:number,z:number}} origin
|
||||
* @param {number} heading Radians.
|
||||
* @param {Float64Array|number[]} out
|
||||
* @returns {Float64Array|number[]} `out`.
|
||||
*/
|
||||
export function headingFrame(origin, heading, out) {
|
||||
const enu = eastNorthUp(origin);
|
||||
const c = Math.cos(heading);
|
||||
const s = Math.sin(heading);
|
||||
const e = enu.x;
|
||||
const n = enu.y;
|
||||
const u = enu.z;
|
||||
out[0] = e.x * c - n.x * s;
|
||||
out[1] = e.y * c - n.y * s;
|
||||
out[2] = e.z * c - n.z * s;
|
||||
out[3] = 0;
|
||||
out[4] = e.x * s + n.x * c;
|
||||
out[5] = e.y * s + n.y * c;
|
||||
out[6] = e.z * s + n.z * c;
|
||||
out[7] = 0;
|
||||
out[8] = u.x;
|
||||
out[9] = u.y;
|
||||
out[10] = u.z;
|
||||
out[11] = 0;
|
||||
out[12] = origin.x;
|
||||
out[13] = origin.y;
|
||||
out[14] = origin.z;
|
||||
out[15] = 1;
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -75,5 +135,5 @@ export function placeModel(record, matrix) {
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function modelIsRendering(record) {
|
||||
return !!record && record.model.ready === true && record.show === true;
|
||||
return !!record && record.ready === true && record.show === true;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
createModelRecord,
|
||||
headingFrame,
|
||||
modelIsRendering,
|
||||
placeModel,
|
||||
showModel,
|
||||
} from './modelRecord.js';
|
||||
|
||||
test('a placed model has the frame the Cesium renderer poses it in', () => {
|
||||
for (const [lon, lat, height] of [
|
||||
[-97.7, 30.2, 300],
|
||||
[10, -60, 1000],
|
||||
[179, 89.9, 0],
|
||||
])
|
||||
for (const heading of [0, 0.5, 2, 4, -1]) {
|
||||
const at = Cesium.Cartesian3.fromDegrees(lon, lat, height);
|
||||
const expected = Cesium.Transforms.headingPitchRollToFixedFrame(
|
||||
at,
|
||||
new Cesium.HeadingPitchRoll(heading, 0, 0),
|
||||
Cesium.Ellipsoid.WGS84,
|
||||
undefined,
|
||||
new Cesium.Matrix4(),
|
||||
);
|
||||
const frame = headingFrame(
|
||||
{ x: at.x, y: at.y, z: at.z },
|
||||
heading,
|
||||
new Float64Array(16),
|
||||
);
|
||||
for (let i = 0; i < 16; i++)
|
||||
assert.ok(
|
||||
Math.abs(frame[i] - expected[i]) < (i >= 12 ? 1e-6 : 1e-12),
|
||||
`${lon},${lat} @ ${heading}: element ${i}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('a record renders only once ready and shown', () => {
|
||||
const record = createModelRecord({ specKey: 'a@1', bellyM: 2 });
|
||||
assert.equal(record.ready, false);
|
||||
assert.equal(modelIsRendering(record), false);
|
||||
showModel(record, true);
|
||||
assert.equal(modelIsRendering(record), false);
|
||||
record.ready = true;
|
||||
assert.equal(modelIsRendering(record), true);
|
||||
const at = { x: 1, y: 2, z: 6_400_000 };
|
||||
placeModel(record, at, 0.3);
|
||||
at.x = 99;
|
||||
assert.equal(record.position.x, 1, 'the position is copied');
|
||||
assert.equal(record.matrix[12], 1);
|
||||
assert.equal(record.heading, 0.3);
|
||||
assert.equal(modelIsRendering(null), false);
|
||||
});
|
||||
@@ -34,6 +34,8 @@ import flightsLayer, {
|
||||
_trackedBillboardColorForTest as flightsTrackedBillboardColor,
|
||||
_driveFleetModelHandoffForTest as flightsDriveFleetModel,
|
||||
_ensureFleetModelForTest as flightsEnsureFleetModel,
|
||||
_trackedModelForTest as flightsTrackedModel,
|
||||
_modelSetIdsForTest as flightsModelSetIds,
|
||||
_iconForTest as flightsIcon,
|
||||
_setIconForTest as flightsSetIcon,
|
||||
} from './flights.js';
|
||||
@@ -44,11 +46,15 @@ import militaryFlightsLayer, {
|
||||
_trackedBillboardColorForTest as militaryTrackedBillboardColor,
|
||||
_driveFleetModelHandoffForTest as militaryDriveFleetModel,
|
||||
_ensureFleetModelForTest as militaryEnsureFleetModel,
|
||||
_trackedModelForTest as militaryTrackedModel,
|
||||
_modelSetIdsForTest as militaryModelSetIds,
|
||||
_iconForTest as militaryIcon,
|
||||
_setIconForTest as militarySetIcon,
|
||||
} from './militaryFlights.js';
|
||||
import { clearTr3bRegistry, setTr3b } from './tr3bRegistry.js';
|
||||
import { reportMeshFloorCell, _clearMeshFloorCellsForTest } from './groundFloor.js';
|
||||
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
|
||||
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
|
||||
|
||||
// Sample altitudes are expressed RELATIVE to the band rather than as absolute
|
||||
// offsets. The thresholds have already been retuned once (1_000_000 → 150_000
|
||||
@@ -156,10 +162,13 @@ if (typeof globalThis.window === 'undefined') {
|
||||
globalThis.window = { dispatchEvent() { return true; }, addEventListener() {}, removeEventListener() {} };
|
||||
}
|
||||
|
||||
/** A viewer stub whose camera altitude the test can move between evaluations. */
|
||||
/** A viewer stub whose camera altitude the test can move between evaluations.
|
||||
* Its renderer has a fake draw port (`viewer.draw`) the layer's model sets
|
||||
* are made on, and a query port whose height samples are `sampleHeight`'s. */
|
||||
function viewerAtHeight(height, { tilesLoaded = true, sampleHeight = () => undefined } = {}) {
|
||||
const tileset = { show: true, tilesLoaded };
|
||||
return {
|
||||
const draw = fakeDrawPort();
|
||||
const viewer = {
|
||||
camera: {
|
||||
positionCartographic: { height },
|
||||
positionWC: Cesium.Cartesian3.fromDegrees(-97.71, 30.21, 5000),
|
||||
@@ -172,9 +181,25 @@ function viewerAtHeight(height, { tilesLoaded = true, sampleHeight = () => undef
|
||||
sampleHeight,
|
||||
},
|
||||
tileset,
|
||||
draw,
|
||||
trackedEntity: undefined,
|
||||
entities: { remove() {} },
|
||||
};
|
||||
return bindFakeCesiumCamera(viewer, {
|
||||
draw,
|
||||
query: { sampleHeightNow: () => sampleHeight() },
|
||||
canvas: viewer.scene.canvas,
|
||||
});
|
||||
}
|
||||
|
||||
/** The layer's fleet or tracked models set in the viewer's fake draw port. */
|
||||
function modelSet(fixture, viewer, which) {
|
||||
return viewer.draw.set(fixture.modelSetIds()[which]);
|
||||
}
|
||||
|
||||
/** Where a model record places its model (its placement's translation). */
|
||||
function placedAt(record) {
|
||||
return new Cesium.Cartesian3(record.matrix[12], record.matrix[13], record.matrix[14]);
|
||||
}
|
||||
|
||||
/** A billboard with a real position, so the tracked-model driver has somewhere
|
||||
@@ -208,13 +233,6 @@ function iconView(icao24, readIcon, setIcon) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Records what the driver hands to the scene, so a test can assert that a
|
||||
* failing loader never put a model up. */
|
||||
function recordingModelCollection() {
|
||||
const added = [];
|
||||
return { added, add(m) { added.push(m); }, remove() {}, isDestroyed() { return false; } };
|
||||
}
|
||||
|
||||
const LAYERS = [
|
||||
{
|
||||
name: 'flights',
|
||||
@@ -223,9 +241,11 @@ const LAYERS = [
|
||||
driveTrackedModel: flightsDriveTrackedModel,
|
||||
driveFleetModel: flightsDriveFleetModel,
|
||||
ensureFleetModel: flightsEnsureFleetModel,
|
||||
trackedModel: flightsTrackedModel,
|
||||
modelSetIds: flightsModelSetIds,
|
||||
trackedBillboardColor: flightsTrackedBillboardColor,
|
||||
bellyM: 6.719,
|
||||
seed({ viewer, tracked = true, icao24 = ICAO, modelCollection = null, onGround = false, models = [] }) {
|
||||
seed({ viewer, tracked = true, icao24 = ICAO, onGround = false, models = [] }) {
|
||||
const billboard = contactBillboard();
|
||||
_setTrackedFlightRefreshStateForTest({
|
||||
icao24,
|
||||
@@ -235,7 +255,7 @@ const LAYERS = [
|
||||
viewer,
|
||||
tracked,
|
||||
models,
|
||||
modelCollection,
|
||||
draw: viewer.draw,
|
||||
meta: { callsign: 'TEST123 ', altitude: 10_668, klass: 'airliner', onGround },
|
||||
});
|
||||
return iconView(icao24, flightsIcon, flightsSetIcon);
|
||||
@@ -248,9 +268,11 @@ const LAYERS = [
|
||||
driveTrackedModel: militaryDriveTrackedModel,
|
||||
driveFleetModel: militaryDriveFleetModel,
|
||||
ensureFleetModel: militaryEnsureFleetModel,
|
||||
trackedModel: militaryTrackedModel,
|
||||
modelSetIds: militaryModelSetIds,
|
||||
trackedBillboardColor: militaryTrackedBillboardColor,
|
||||
bellyM: 5.631 * 0.8,
|
||||
seed({ viewer, tracked = true, icao24 = ICAO, modelCollection = null, onGround = false, models = [] }) {
|
||||
seed({ viewer, tracked = true, icao24 = ICAO, onGround = false, models = [] }) {
|
||||
const billboard = contactBillboard();
|
||||
_setTrackedMilitaryRefreshStateForTest({
|
||||
icao24,
|
||||
@@ -260,7 +282,7 @@ const LAYERS = [
|
||||
viewer,
|
||||
tracked,
|
||||
models,
|
||||
modelCollection,
|
||||
draw: viewer.draw,
|
||||
meta: { callsign: 'TEST123 ', altitudeFt: 35_000, klass: 'fastjet', onGround },
|
||||
});
|
||||
return iconView(icao24, militaryIcon, militarySetIcon);
|
||||
@@ -269,44 +291,26 @@ const LAYERS = [
|
||||
];
|
||||
|
||||
for (const fixture of LAYERS) {
|
||||
test(`${fixture.name}: production fleet loader admits a HIDDEN primitive and fails back to 2D`, async () => {
|
||||
test(`${fixture.name}: production fleet admission keeps the model HIDDEN until it is ready and placed`, () => {
|
||||
clearTr3bRegistry();
|
||||
fixture.layer.stopTracking();
|
||||
fixture.layer.setParams({ models3d: true });
|
||||
|
||||
const realFrom = Cesium.Model.fromGltfAsync;
|
||||
const viewer = viewerAtHeight(30_000, { tilesLoaded: false });
|
||||
const position = Cesium.Cartesian3.fromDegrees(-97.71, 30.21, 10_668);
|
||||
const loadedCollection = recordingModelCollection();
|
||||
const loadingModel = {
|
||||
modelMatrix: Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY),
|
||||
ready: false,
|
||||
show: true,
|
||||
scale: 1,
|
||||
destroy() {},
|
||||
};
|
||||
|
||||
try {
|
||||
const loadingIcao = fixture.name === 'flights' ? 'a0f201' : 'b0f201';
|
||||
Cesium.Model.fromGltfAsync = () => Promise.resolve(loadingModel);
|
||||
const billboard = fixture.seed({
|
||||
viewer,
|
||||
tracked: false,
|
||||
icao24: loadingIcao,
|
||||
onGround: true,
|
||||
modelCollection: loadedCollection,
|
||||
});
|
||||
const admitted = await fixture.ensureFleetModel(loadingIcao);
|
||||
assert.equal(admitted, loadingModel, 'the production fleet loader admits the resolved primitive');
|
||||
assert.equal(loadedCollection.added.length, 1, 'the production loader adds it once');
|
||||
assert.equal(loadingModel.ready, false);
|
||||
// Cesium 1.138's Model.update has no `show` guard — PrimitiveCollection
|
||||
// updates every member unconditionally and `_ready` flips in afterRender —
|
||||
// so hiding an admitted primitive costs its load nothing, and it is the
|
||||
// only thing that keeps Cesium's default show=true from claiming the
|
||||
// visual at the identity matrix before the first tick places it.
|
||||
assert.equal(loadingModel.show, false, 'admission hides the primitive until it is placed');
|
||||
assert.equal(loadingModel.scale, 1, 'and never touches its scale to do it');
|
||||
const admitted = fixture.ensureFleetModel(loadingIcao);
|
||||
assert.ok(admitted, 'the production fleet admission records a model');
|
||||
assert.equal(admitted.ready, false, 'nothing has loaded yet');
|
||||
assert.equal(admitted.show, false, 'admission records the model hidden until it is placed');
|
||||
assert.equal(billboard.show, true, 'the 2D billboard owns the cold loading state');
|
||||
|
||||
const nearby = fixture.layer.getNearby(billboard.position, 1_000, 50)
|
||||
@@ -316,35 +320,64 @@ for (const fixture of LAYERS) {
|
||||
'fleet proximity stays at the billboard rather than the unplaced model');
|
||||
|
||||
fixture.driveFleetModel({ icao24: loadingIcao, position, course: 92 });
|
||||
assert.equal(loadingModel.show, false);
|
||||
assert.equal(loadingModel.scale, 1);
|
||||
const fleet = modelSet(fixture, viewer, 'fleet');
|
||||
const item = fleet.items.get(loadingIcao);
|
||||
assert.ok(item, 'the model set loads the contact from its first write');
|
||||
assert.equal(item.show, false, 'and draws nothing while there is no safe placement');
|
||||
assert.equal(admitted.show, false);
|
||||
assert.equal(billboard.show, true, 'cold terrain preserves the same visible 2D owner');
|
||||
|
||||
const failedIcao = fixture.name === 'flights' ? 'a0f202' : 'b0f202';
|
||||
const failedCollection = recordingModelCollection();
|
||||
Cesium.Model.fromGltfAsync = () => Promise.reject(new Error('simulated fleet GLB failure'));
|
||||
const failedBillboard = fixture.seed({
|
||||
viewer,
|
||||
tracked: false,
|
||||
icao24: failedIcao,
|
||||
onGround: true,
|
||||
modelCollection: failedCollection,
|
||||
});
|
||||
const failedModel = await fixture.ensureFleetModel(failedIcao);
|
||||
assert.equal(failedModel, null, 'a rejected fleet GLB is never admitted');
|
||||
assert.equal(failedCollection.added.length, 0);
|
||||
assert.equal(failedBillboard.show, true,
|
||||
'fleet load rejection leaves the 2D owner visible');
|
||||
assert.ok(fixture.layer.getNearby(failedBillboard.position, 1_000, 50)
|
||||
.some((object) => object.icao24 === failedIcao),
|
||||
'fleet load rejection leaves the contact in the billboard proximity cohort');
|
||||
// A load that never finishes (a missing or broken GLB) never fires
|
||||
// `ready`, so the billboard stays the visual for as long as it lasts.
|
||||
viewer.draw.ready(fleet.spec.id, 'someone-else');
|
||||
assert.equal(admitted.ready, false, 'another item loading does not ready this one');
|
||||
fixture.driveFleetModel({ icao24: loadingIcao, position, course: 92 });
|
||||
assert.equal(billboard.show, true, 'an unready model leaves the 2D owner visible');
|
||||
assert.ok(fixture.layer.getNearby(billboard.position, 1_000, 50)
|
||||
.some((object) => object.icao24 === loadingIcao),
|
||||
'an unready model leaves the contact in the billboard proximity cohort');
|
||||
|
||||
viewer.draw.ready(fleet.spec.id, loadingIcao);
|
||||
assert.equal(admitted.ready, true, "the set's ready marks the contact's model loaded");
|
||||
} finally {
|
||||
Cesium.Model.fromGltfAsync = realFrom;
|
||||
fixture.layer.setParams({ models3d: false });
|
||||
fixture.layer.stopTracking();
|
||||
}
|
||||
});
|
||||
|
||||
test(`${fixture.name}: the IR boost restyles a drawn model in place, flat white and unlit`, () => {
|
||||
clearTr3bRegistry();
|
||||
fixture.layer.stopTracking();
|
||||
fixture.layer.setParams({ models3d: true, irBoost: false });
|
||||
const viewer = viewerAtHeight(30_000);
|
||||
const position = Cesium.Cartesian3.fromDegrees(-97.71, 30.21, 10_668);
|
||||
const icao24 = fixture.name === 'flights' ? 'a0f301' : 'b0f301';
|
||||
try {
|
||||
fixture.seed({ viewer, tracked: false, icao24 });
|
||||
const record = fixture.ensureFleetModel(icao24);
|
||||
const fleet = modelSet(fixture, viewer, 'fleet');
|
||||
viewer.draw.ready(fleet.spec.id, icao24);
|
||||
fixture.driveFleetModel({ icao24, position, course: 92 });
|
||||
const normal = fleet.items.get(icao24);
|
||||
assert.equal(normal.shading, 'pbr');
|
||||
assert.equal(normal.show, true);
|
||||
assert.ok(normal.colorBlend.amount < 1, 'the asset keeps a hint of its own colour');
|
||||
|
||||
fixture.layer.setParams({ irBoost: true });
|
||||
fixture.driveFleetModel({ icao24, position, course: 92 });
|
||||
const boosted = fleet.items.get(icao24);
|
||||
assert.notEqual(boosted, normal, 'the boost writes the item again');
|
||||
assert.equal(boosted.shading, 'unlit');
|
||||
assert.deepEqual(boosted.tint, [1, 1, 1, 1]);
|
||||
assert.deepEqual(boosted.colorBlend, { mode: 'mix', amount: 1 });
|
||||
assert.equal(fixture.ensureFleetModel(icao24), record, 'the same model restyles; nothing reloads');
|
||||
assert.equal(boosted.url, normal.url);
|
||||
} finally {
|
||||
fixture.layer.setParams({ models3d: false, irBoost: false });
|
||||
fixture.layer.stopTracking();
|
||||
}
|
||||
});
|
||||
|
||||
test(`${fixture.name}: grounded fleet handoff waits through terrain load and keeps one visual owner`, () => {
|
||||
clearTr3bRegistry();
|
||||
fixture.layer.stopTracking();
|
||||
@@ -397,7 +430,7 @@ for (const fixture of LAYERS) {
|
||||
assert.equal(model.show, true);
|
||||
assert.equal(billboard.show, false);
|
||||
assert.ok(model.show || billboard.show, 'successful handoff keeps a visible owner');
|
||||
const placed = Cesium.Matrix4.getTranslation(model.modelMatrix, new Cesium.Cartesian3());
|
||||
const placed = placedAt(model);
|
||||
const placedHeight = Cesium.Cartographic.fromCartesian(placed).height;
|
||||
assert.ok(Math.abs(placedHeight - (sampledHeight + fixture.bellyM)) < 0.001,
|
||||
`placement uses the exact ${fixture.bellyM} m asset-measured belly offset`);
|
||||
@@ -422,7 +455,7 @@ for (const fixture of LAYERS) {
|
||||
assert.equal(model.show, true, 'no 3D→2D pop while the resample is backing off');
|
||||
assert.equal(billboard.show, false);
|
||||
assert.equal(sampleCalls, 1, 'and the hold costs no extra synchronous sample');
|
||||
const held = Cesium.Matrix4.getTranslation(model.modelMatrix, new Cesium.Cartesian3());
|
||||
const held = placedAt(model);
|
||||
assert.ok(Math.abs(Cesium.Cartographic.fromCartesian(held).height
|
||||
- (sampledHeight + fixture.bellyM)) < 0.001,
|
||||
'the hold places the model on the last MEASURED floor, not on the feed altitude');
|
||||
@@ -491,7 +524,7 @@ for (const fixture of LAYERS) {
|
||||
};
|
||||
/** Height (m) the model's matrix currently places it at. */
|
||||
const placedHeightM = () => Cesium.Cartographic.fromCartesian(
|
||||
Cesium.Matrix4.getTranslation(model.modelMatrix, new Cesium.Cartesian3()),
|
||||
placedAt(model),
|
||||
).height;
|
||||
|
||||
const LAT = 30.21;
|
||||
@@ -594,12 +627,11 @@ for (const fixture of LAYERS) {
|
||||
}
|
||||
});
|
||||
|
||||
test(`${fixture.name}: grounded tracked model waits for a valid terrain snap with no visual gap`, async () => {
|
||||
test(`${fixture.name}: grounded tracked model waits for a valid terrain snap with no visual gap`, () => {
|
||||
clearTr3bRegistry();
|
||||
fixture.layer.stopTracking();
|
||||
fixture.layer.setParams({ models3d: false });
|
||||
|
||||
const realFrom = Cesium.Model.fromGltfAsync;
|
||||
const realNow = Date.now;
|
||||
let now = 3_000_000;
|
||||
Date.now = () => now;
|
||||
@@ -609,30 +641,25 @@ for (const fixture of LAYERS) {
|
||||
tilesLoaded: false,
|
||||
sampleHeight: () => { sampleCalls++; return sampledHeight; },
|
||||
});
|
||||
const collection = recordingModelCollection();
|
||||
const model = {
|
||||
modelMatrix: Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY),
|
||||
ready: false,
|
||||
show: true,
|
||||
scale: 1,
|
||||
destroy() {},
|
||||
};
|
||||
Cesium.Model.fromGltfAsync = () => Promise.resolve(model);
|
||||
const icao24 = fixture.name === 'flights' ? 'a0f001' : 'b0f001';
|
||||
|
||||
try {
|
||||
const billboard = fixture.seed({
|
||||
viewer,
|
||||
modelCollection: collection,
|
||||
onGround: true,
|
||||
icao24: fixture.name === 'flights' ? 'a0f001' : 'b0f001',
|
||||
icao24,
|
||||
});
|
||||
|
||||
fixture.driveTrackedModel();
|
||||
await Promise.resolve(); await Promise.resolve();
|
||||
assert.equal(collection.added.length, 1, 'the loaded primitive enters the scene once');
|
||||
assert.equal(model.ready, false, 'the production loader is still awaiting GPU readiness');
|
||||
assert.equal(model.show, false, 'the loading primitive is admitted hidden, not zero-scaled');
|
||||
assert.equal(model.scale, 1, 'its scale is left to the pixel-cap driver');
|
||||
const model = fixture.trackedModel();
|
||||
const tracked = modelSet(fixture, viewer, 'tracked');
|
||||
assert.ok(model, 'the driver records the tracked model');
|
||||
assert.deepEqual([...tracked.items.keys()], [icao24],
|
||||
'the tracked set loads the one model for the contact');
|
||||
assert.equal(model.ready, false, 'the model is still loading');
|
||||
assert.equal(model.show, false, 'the loading model is drawn hidden, not zero-scaled');
|
||||
assert.equal(tracked.items.get(icao24).show, false);
|
||||
const baseScale = model.scale;
|
||||
assert.equal(fixture.trackedBillboardColor().alpha, 1,
|
||||
'the tracked billboard remains opaque while the model lacks safe placement');
|
||||
assert.equal(sampleCalls, 0, 'cold tiles do not force a synchronous sample');
|
||||
@@ -672,12 +699,14 @@ for (const fixture of LAYERS) {
|
||||
assert.equal(fixture.trackedBillboardColor().alpha, 1,
|
||||
'the billboard retains ownership until GPU readiness too');
|
||||
|
||||
model.ready = true;
|
||||
assert.equal(model.scale, baseScale, 'its scale is left to the pixel-cap driver');
|
||||
viewer.draw.ready(tracked.spec.id, icao24);
|
||||
fixture.driveTrackedModel();
|
||||
assert.equal(model.show, true, 'the model appears only after its snapped matrix is written');
|
||||
assert.equal(tracked.items.get(icao24).show, true);
|
||||
assert.equal(fixture.trackedBillboardColor().alpha, 0,
|
||||
'the billboard becomes transparent only when the model actually owns the visual');
|
||||
const placed = Cesium.Matrix4.getTranslation(model.modelMatrix, new Cesium.Cartesian3());
|
||||
const placed = placedAt(model);
|
||||
const placedHeight = Cesium.Cartographic.fromCartesian(placed).height;
|
||||
assert.ok(Math.abs(placedHeight - (sampledHeight + fixture.bellyM)) < 0.001,
|
||||
`tracked placement uses the exact ${fixture.bellyM} m asset-measured belly offset`);
|
||||
@@ -710,7 +739,6 @@ for (const fixture of LAYERS) {
|
||||
assert.equal(fixture.trackedBillboardColor().alpha, 1,
|
||||
'there is no invisible-owner gap while the replacement snap is unavailable');
|
||||
} finally {
|
||||
Cesium.Model.fromGltfAsync = realFrom;
|
||||
Date.now = realNow;
|
||||
fixture.layer.stopTracking();
|
||||
}
|
||||
@@ -833,132 +861,9 @@ for (const fixture of LAYERS) {
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 3. Bounded on-demand loading
|
||||
//
|
||||
// The tracked regime is default-on and its driver runs every scene.preUpdate.
|
||||
// A missing or corrupt GLB — or a dead network — used to leave the driver in a
|
||||
// load→reject loop at frame rate for as long as the contact stayed selected,
|
||||
// because the catch cleared only the in-flight flag. These pin the bound.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Drive N frames of the production tracked-model driver, letting each
|
||||
* rejected load settle, with a fake clock the backoff can be walked past. */
|
||||
async function driveFrames(fixture, count, clock) {
|
||||
for (let i = 0; i < count; i++) {
|
||||
fixture.driveTrackedModel();
|
||||
await Promise.resolve(); await Promise.resolve(); // let the rejection settle
|
||||
clock.advance(2000); // past the retry backoff, so only the LATCH can stop it
|
||||
}
|
||||
}
|
||||
|
||||
for (const fixture of LAYERS) {
|
||||
test(`${fixture.name}: a rejecting GLB loader is bounded, not a per-frame retry loop`, async () => {
|
||||
clearTr3bRegistry();
|
||||
fixture.layer.setParams({ models3d: false });
|
||||
|
||||
const realFrom = Cesium.Model.fromGltfAsync;
|
||||
const realNow = Date.now;
|
||||
let now = 1_000_000;
|
||||
const clock = { advance(ms) { now += ms; } };
|
||||
Date.now = () => now;
|
||||
let attempts = 0;
|
||||
const requested = [];
|
||||
Cesium.Model.fromGltfAsync = ({ url }) => {
|
||||
attempts++; requested.push(url);
|
||||
return Promise.reject(new Error('simulated missing GLB'));
|
||||
};
|
||||
// The give-up path warns once by design; keep the run's output clean.
|
||||
const realWarn = console.warn;
|
||||
const warnings = [];
|
||||
console.warn = (...args) => { warnings.push(args.join(' ')); };
|
||||
|
||||
try {
|
||||
const collection = recordingModelCollection();
|
||||
const viewer = viewerAtHeight(30_000); // well inside the regime
|
||||
const billboard = fixture.seed({ viewer, modelCollection: collection });
|
||||
assert.equal(fixture.regimeActive(), true, 'the regime is open, so the driver will try to load');
|
||||
|
||||
await driveFrames(fixture, 12, clock);
|
||||
const settled = attempts;
|
||||
assert.ok(settled > 0, 'it must actually try');
|
||||
assert.ok(settled <= 3,
|
||||
`a failing asset must give up within 3 attempts per selection, got ${settled}`);
|
||||
|
||||
// Many more frames must produce NO further attempts — this is the loop bound.
|
||||
await driveFrames(fixture, 25, clock);
|
||||
assert.equal(attempts, settled,
|
||||
'once latched, further frames must not re-ask for the same failed asset');
|
||||
|
||||
// Nothing was ever handed to the scene, so the billboard stayed the visual.
|
||||
assert.equal(collection.added.length, 0, 'a failed load never puts a model up');
|
||||
assert.equal(fixture.trackedBillboardColor().alpha, 1,
|
||||
'a rejected tracked model leaves the tracked billboard opaque');
|
||||
assert.equal(billboard.show, true,
|
||||
'a rejected model never creates a frame with both visual representations hidden');
|
||||
|
||||
// Exactly one operator-facing warning, and it names the asset.
|
||||
assert.equal(warnings.length, 1, 'the give-up is announced once, not per frame');
|
||||
assert.ok(warnings[0].includes(requested[0]), `the warning names the asset: ${warnings[0]}`);
|
||||
|
||||
// A NEW selection gets a fresh budget — the latch is per contact.
|
||||
fixture.layer.stopTracking();
|
||||
fixture.seed({ viewer, icao24: 'def456', modelCollection: collection });
|
||||
await driveFrames(fixture, 3, clock);
|
||||
assert.ok(attempts > settled, 'selecting another contact restores the retry budget');
|
||||
} finally {
|
||||
Cesium.Model.fromGltfAsync = realFrom;
|
||||
Date.now = realNow;
|
||||
console.warn = realWarn;
|
||||
fixture.layer.stopTracking();
|
||||
}
|
||||
});
|
||||
|
||||
test(`${fixture.name}: the failure latch clears on a same-icao re-track too`, async () => {
|
||||
clearTr3bRegistry();
|
||||
fixture.layer.setParams({ models3d: false });
|
||||
|
||||
const realFrom = Cesium.Model.fromGltfAsync;
|
||||
const realNow = Date.now;
|
||||
const realWarn = console.warn;
|
||||
let now = 2_000_000;
|
||||
const clock = { advance(ms) { now += ms; } };
|
||||
Date.now = () => now;
|
||||
let attempts = 0;
|
||||
Cesium.Model.fromGltfAsync = () => { attempts++; return Promise.reject(new Error('simulated missing GLB')); };
|
||||
console.warn = () => {};
|
||||
|
||||
try {
|
||||
const collection = recordingModelCollection();
|
||||
const viewer = viewerAtHeight(30_000);
|
||||
fixture.seed({ viewer, modelCollection: collection });
|
||||
await driveFrames(fixture, 12, clock);
|
||||
const latched = attempts;
|
||||
await driveFrames(fixture, 10, clock);
|
||||
assert.equal(attempts, latched, 'latched for this selection');
|
||||
|
||||
// Deselect and re-select the SAME contact through the production path.
|
||||
fixture.layer.stopTracking();
|
||||
fixture.seed({ viewer, modelCollection: collection });
|
||||
await driveFrames(fixture, 3, clock);
|
||||
assert.ok(attempts > latched,
|
||||
're-tracking the same contact is a new selection and gets its retries back');
|
||||
} finally {
|
||||
Cesium.Model.fromGltfAsync = realFrom;
|
||||
Date.now = realNow;
|
||||
console.warn = realWarn;
|
||||
fixture.layer.stopTracking();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('both layers gate the tracked-model load and record its failures', async () => {
|
||||
test('both layers reset the per-selection tracked-model state', async () => {
|
||||
for (const name of ['flights.js', 'militaryFlights.js']) {
|
||||
const source = readLayerSource(new URL(`./${name}`, import.meta.url));
|
||||
assert.match(source, /!(?:(?:flightState|state)\.)?_trackedModel\s*&&\s*!(?:(?:flightState|state)\.)?_trackedModelLoading\s*&&\s*(?:parts\.\w+\.)?_trackedModelLoadAllowed\(\s*,?\s*\)/,
|
||||
`${name}: the driver asks permission before starting another tracked-model load`);
|
||||
assert.match(source, /(?:parts\.\w+\.)?_noteTrackedModelLoadFailure\(\s*trackedSpec\.url,\s*err,?\s*\)/,
|
||||
`${name}: a rejected load is recorded against this selection, not silently retried`);
|
||||
// The reset must be reachable from the real teardown, not only a test seam.
|
||||
assert.match(source, /(?:parts\.\w+\.)?_releaseTrackedModel\(\s*,?\s*\);\n\s*(?:parts\.\w+\.)?_resetTrackedSelectionState\(\s*,?\s*\);/,
|
||||
`${name}: deselect clears the per-selection latches in the production path`);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { findCamera, findFrame } from '../../render/rendererOf.js';
|
||||
import { PLANE_MODEL_URL } from './policy.js';
|
||||
|
||||
export function createLifecycle({
|
||||
@@ -33,7 +33,7 @@ export function createLifecycle({
|
||||
* Initialize the flights layer.
|
||||
* Creates the icon set and its primitive, resets all state, and installs the
|
||||
* click-to-track handler on the scene canvas.
|
||||
* @param {Cesium.Viewer} viewer - The CesiumJS viewer instance.
|
||||
* @param {object} viewer - The viewer.
|
||||
*/
|
||||
init(viewer) {
|
||||
if (flightState._viewer)
|
||||
@@ -46,33 +46,11 @@ export function createLifecycle({
|
||||
flightState._focusEvidenceIds.clear();
|
||||
flightState._viewer = viewer;
|
||||
registerSpriteSet('flights', parts.icons._createIcons(viewer));
|
||||
flightState._modelCollection = new Cesium.PrimitiveCollection();
|
||||
viewer.scene.primitives.add(flightState._modelCollection);
|
||||
// Warm the glTF cache so the tracked plane's model instantiates instantly when first needed
|
||||
// (keeps the retained instance referenced; never rendered). Captured against this epoch so a
|
||||
// destroy/re-init mid-load doesn't flip the flag for a torn-down lifecycle.
|
||||
if (!flightState._preloadModel) {
|
||||
const epoch = flightState._modelEpoch;
|
||||
Cesium.Model.fromGltfAsync({
|
||||
url: resolveAsset(PLANE_MODEL_URL),
|
||||
asynchronous: false,
|
||||
})
|
||||
.then((m) => {
|
||||
if (epoch === flightState._modelEpoch) {
|
||||
flightState._preloadModel = m;
|
||||
flightState._planeModelLoaded = true;
|
||||
} else {
|
||||
try {
|
||||
m.destroy();
|
||||
} catch {
|
||||
/* gone */
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
/* tracked plane just stays a billboard a beat longer */
|
||||
});
|
||||
}
|
||||
// The models' draw sets; a hidden item keeps the tracked asset loaded so
|
||||
// the tracked plane's model draws as soon as it is wanted.
|
||||
parts.rendering._createModelSets(viewer, {
|
||||
preloadUrl: resolveAsset(PLANE_MODEL_URL),
|
||||
});
|
||||
flightState._grounded.clear();
|
||||
flightState._floorPinned.clear();
|
||||
flightState._iconFocusActive = 0;
|
||||
@@ -127,13 +105,12 @@ export function createLifecycle({
|
||||
|
||||
/**
|
||||
* Show the icons and re-install the click handler.
|
||||
* @param {Cesium.Viewer} viewer
|
||||
* @param {object} viewer
|
||||
*/
|
||||
enable(viewer) {
|
||||
if (flightState._icons) flightState._icons.show = true;
|
||||
holdContinuousRender('flights'); // per-frame animator (perf wave 2)
|
||||
if (flightState._modelCollection)
|
||||
flightState._modelCollection.show = true;
|
||||
parts.rendering._setModelsShown(true);
|
||||
parts.tracking._setCockpitContactMode(
|
||||
document.body.classList.contains('cockpit-mode'),
|
||||
);
|
||||
@@ -155,26 +132,25 @@ export function createLifecycle({
|
||||
'flights',
|
||||
(pickedId) => flightState._icons?.has(pickedId) === true,
|
||||
);
|
||||
if (!flightState._preRenderRemove && viewer?.scene) {
|
||||
flightState._preRenderRemove = viewer.scene.preRender.addEventListener(
|
||||
parts.rendering._fleetTick,
|
||||
const frame = findFrame(viewer);
|
||||
if (!flightState._preRenderRemove && frame) {
|
||||
flightState._preRenderRemove = frame.on('preRender', () =>
|
||||
parts.rendering._fleetTick(),
|
||||
);
|
||||
}
|
||||
if (!flightState._trackedModelPreUpdateRemove && viewer?.scene) {
|
||||
flightState._trackedModelPreUpdateRemove =
|
||||
viewer.scene.preUpdate.addEventListener(
|
||||
parts.rendering._updateTrackedModel,
|
||||
);
|
||||
if (!flightState._trackedModelPreUpdateRemove && frame) {
|
||||
flightState._trackedModelPreUpdateRemove = frame.on('preUpdate', () =>
|
||||
parts.rendering._updateTrackedModel(),
|
||||
);
|
||||
}
|
||||
if (!flightState._moveEndRemove && viewer?.camera) {
|
||||
const camera = findCamera(viewer);
|
||||
if (!flightState._moveEndRemove && camera) {
|
||||
// A settled camera move (voice fly-to, fast pan release) runs the fleet
|
||||
// pass on the very next preRender rather than up to FLEET_DR_INTERVAL_MS
|
||||
// later, so the model handoff and focus land with the camera.
|
||||
flightState._moveEndRemove = viewer.camera.moveEnd.addEventListener(
|
||||
() => {
|
||||
flightState._lastFleetTickMs = 0;
|
||||
},
|
||||
);
|
||||
flightState._moveEndRemove = camera.on('moveEnd', () => {
|
||||
flightState._lastFleetTickMs = 0;
|
||||
});
|
||||
}
|
||||
restoreSpriteOrderOnEnable('flights', viewer);
|
||||
},
|
||||
@@ -182,7 +158,7 @@ export function createLifecycle({
|
||||
/**
|
||||
* Hide all flight icons and tear down click/keyboard handlers.
|
||||
* Also clears any active flight tracking so the camera is released.
|
||||
* @param {Cesium.Viewer} viewer
|
||||
* @param {object} viewer
|
||||
*/
|
||||
disable(viewer) {
|
||||
parts.controller._abortActiveUpdates();
|
||||
@@ -190,8 +166,7 @@ export function createLifecycle({
|
||||
if (flightState._icons) flightState._icons.show = false;
|
||||
releaseContinuousRender('flights');
|
||||
parts.rendering._releaseModels();
|
||||
if (flightState._modelCollection)
|
||||
flightState._modelCollection.show = false;
|
||||
parts.rendering._setModelsShown(false);
|
||||
parts.tracking._clearTracking();
|
||||
parts.tracking._destroyTrail();
|
||||
// Remove click handler + keydown listener while disabled to avoid
|
||||
@@ -221,7 +196,7 @@ export function createLifecycle({
|
||||
/**
|
||||
* Fully tear down the flights layer — remove primitives, handlers,
|
||||
* tracked entities, and clear all internal state maps.
|
||||
* @param {Cesium.Viewer} viewer
|
||||
* @param {object} viewer
|
||||
*/
|
||||
destroy(viewer) {
|
||||
flightState.lifetime.abort();
|
||||
@@ -265,22 +240,7 @@ export function createLifecycle({
|
||||
}
|
||||
parts.rendering._releaseModels();
|
||||
parts.icons._disposeIcons();
|
||||
if (flightState._modelCollection) {
|
||||
viewer.scene.primitives.remove(flightState._modelCollection); // removing destroys it + its models
|
||||
flightState._modelCollection = null;
|
||||
}
|
||||
flightState._modelEpoch += 1; // invalidate any in-flight load from this lifecycle (settles post-destroy)
|
||||
flightState._modelPending.clear();
|
||||
flightState._modelGen.clear();
|
||||
if (flightState._preloadModel) {
|
||||
try {
|
||||
flightState._preloadModel.destroy();
|
||||
} catch {
|
||||
/* gone */
|
||||
}
|
||||
flightState._preloadModel = null;
|
||||
}
|
||||
flightState._planeModelLoaded = false;
|
||||
parts.rendering._disposeModelSets();
|
||||
flightState._grounded.clear();
|
||||
flightState._floorPinned.clear();
|
||||
flightState._iconFocusActive = 0;
|
||||
|
||||
@@ -469,7 +469,7 @@ export function createMotion({
|
||||
* is what you can see drifts below the aircraft and only converges as the coarse floor
|
||||
* cell warms ("the buoy"), sometimes never.
|
||||
*
|
||||
* It reads `modelMatrix`, which `_updateTrackedModel` already wrote this frame — no
|
||||
* It reads the placement `_updateTrackedModel` already recorded this frame — no
|
||||
* sampling, no `_modelDisplayPosition` call from postRender, and no new dead reckoning,
|
||||
* so the follow-camera anti-jitter contract on the entity record's `displayPosition` is untouched.
|
||||
*/
|
||||
@@ -485,9 +485,7 @@ export function createMotion({
|
||||
return modelVisualAnchor(
|
||||
flightState._trackedModel.matrix,
|
||||
spec.visualCenterNative,
|
||||
Number.isFinite(flightState._trackedModel.model.computedScale)
|
||||
? flightState._trackedModel.model.computedScale
|
||||
: spec.scale,
|
||||
parts.rendering._modelDrawnScale(flightState._trackedModel, spec),
|
||||
flightState._trackedVisualPos,
|
||||
);
|
||||
}
|
||||
@@ -497,8 +495,8 @@ export function createMotion({
|
||||
/** Trail endpoint for the rendered tracked owner. Brackets/readouts stay on
|
||||
* the visual centre; only the trail moves to the model's lower-centre hardpoint. */
|
||||
/** The tracked model's rendered bounding radius (m), or 0 when no model of this
|
||||
* contact is drawing. Carries Cesium's effective `computedScale`, which may be
|
||||
* above `scale` to satisfy minimumPixelSize — the trail head has to be judged
|
||||
* contact is drawing. Carries the scale it is drawn at, which may be
|
||||
* above `scale` to satisfy its pixel floor — the trail head has to be judged
|
||||
* against the size the operator SEES, not the nominal one. */
|
||||
/** World-space origin of the tracked model, or null when no model of this
|
||||
* contact is drawing. This is the centre the rendered bounding sphere is
|
||||
@@ -527,10 +525,10 @@ export function createMotion({
|
||||
const spec = parts.rendering._modelSpec(
|
||||
flightState.records.data.get(flightState._trackedIcao)?.klass,
|
||||
);
|
||||
const scale = Number.isFinite(flightState._trackedModel.model.computedScale)
|
||||
? flightState._trackedModel.model.computedScale
|
||||
: spec.scale;
|
||||
return spec.nativeRadiusM * scale;
|
||||
return (
|
||||
spec.nativeRadiusM *
|
||||
parts.rendering._modelDrawnScale(flightState._trackedModel, spec)
|
||||
);
|
||||
}
|
||||
|
||||
function _trackedTrailCached() {
|
||||
@@ -547,9 +545,7 @@ export function createMotion({
|
||||
return modelAnchorWorld(
|
||||
flightState._trackedModel.matrix,
|
||||
spec.trailAnchorNative,
|
||||
Number.isFinite(flightState._trackedModel.model.computedScale)
|
||||
? flightState._trackedModel.model.computedScale
|
||||
: spec.scale,
|
||||
parts.rendering._modelDrawnScale(flightState._trackedModel, spec),
|
||||
flightState._trackedTrailPos,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -105,7 +105,11 @@ export const MODEL_COLOR_BLEND_AMOUNT = 0.94;
|
||||
|
||||
export const MODEL_BELLY_OFFSET_NATIVE = 6.719;
|
||||
|
||||
/** The tracked contact's tint, and its billboard once a model takes over. */
|
||||
export const TRACKED_CYAN = Cesium.Color.CYAN;
|
||||
export const CYAN_TRANSPARENT = Cesium.Color.CYAN.withAlpha(0);
|
||||
/** An ordinary fleet contact's tint. */
|
||||
export const FLEET_TINT = Cesium.Color.WHITE;
|
||||
|
||||
export const COCKPIT_CONTACT_SIZE_PX = 6;
|
||||
|
||||
@@ -281,19 +285,6 @@ export const ENRICH_AMBIENT_PER_SWEEP = 150;
|
||||
|
||||
export const DR_CORRECTION_MS = 900;
|
||||
|
||||
/** Bounded on-demand loading for the tracked model. The tracked regime is
|
||||
* DEFAULT-ON and its driver runs every `scene.preUpdate`, so a missing or
|
||||
* corrupt GLB — or a dead network — would otherwise spin load→reject at frame
|
||||
* rate for as long as the contact stays selected. Failures are counted PER
|
||||
* SELECTION: a short backoff absorbs a transient blip, then the layer stops
|
||||
* asking until the operator selects something else. The billboard is the
|
||||
* visual throughout (the handoff only fades it once a model actually renders),
|
||||
* so a latched failure degrades to exactly the pre-3D presentation. */
|
||||
|
||||
export const TRACKED_MODEL_MAX_LOAD_FAILS = 3;
|
||||
|
||||
export const TRACKED_MODEL_RETRY_BACKOFF_MS = 1500;
|
||||
|
||||
/** @constant {number} Cap on NEW cells the display corridors may add to one
|
||||
* poll's warm/sample batch — a view full of ground traffic must not balloon
|
||||
* it. Cells the poll already collected are free (deduped before budgeting). */
|
||||
@@ -422,18 +413,3 @@ export const FLOOR_EASE_EPSILON_M = 0.02;
|
||||
* airborne long enough to have gone anywhere. */
|
||||
|
||||
export const FLOOR_SEED_GRACE_MS = 90_000;
|
||||
|
||||
/** Flip the whole 3D fleet's boost state by dropping models so the eligibility
|
||||
* pass reloads them with creation-time boost options (both directions — a
|
||||
* boosted model must not stay flat white back in Normal). Destroying 350
|
||||
* GPU-backed models synchronously inside the style handler stalls the render
|
||||
* thread (review P1; same failure the cockpit path documents), so the release
|
||||
* is BATCHED through the fleet tick: each tick drops a bounded slice, showing
|
||||
* each plane's billboard first (gap-proof per plane, no double-image window).
|
||||
* Models are tagged with the boost state they loaded under, so queue entries
|
||||
* whose model already matches the current state (rapid style cycling, or a
|
||||
* reload that already happened) are skipped. In-flight loads are invalidated
|
||||
* immediately (cheap gen bumps); the tracked model is a single primitive and
|
||||
* reloads synchronously. */
|
||||
|
||||
export const IR_RELOAD_BATCH = 40;
|
||||
@@ -433,6 +433,8 @@ export function createQueries({
|
||||
|
||||
const result = [];
|
||||
const ids = icons.ids();
|
||||
/** One camera and viewport for every model's drawn scale. */
|
||||
let view = null;
|
||||
for (let i = start; i < ids.length; i += stride) {
|
||||
const icao24 = ids[i];
|
||||
if (
|
||||
@@ -478,9 +480,11 @@ export function createQueries({
|
||||
? modelVisualAnchor(
|
||||
record.matrix,
|
||||
spec.visualCenterNative,
|
||||
Number.isFinite(record.model.computedScale)
|
||||
? record.model.computedScale
|
||||
: spec.scale,
|
||||
parts.rendering._modelDrawnScale(
|
||||
record,
|
||||
spec,
|
||||
(view ??= parts.rendering._drawnScaleView()),
|
||||
),
|
||||
object._weldPos || (object._weldPos = new Cesium.Cartesian3()),
|
||||
)
|
||||
: icons.position(icao24, t, object._iconPos);
|
||||
|
||||
@@ -5,11 +5,23 @@ import { createQueries } from './queries.js';
|
||||
import { createRendering } from './rendering.js';
|
||||
import { createIcons } from './icons.js';
|
||||
import { createContactIcons } from '../../data/aircraftIconLayer.js';
|
||||
import {
|
||||
createModelRecord,
|
||||
placeModel,
|
||||
showModel,
|
||||
} from '../../data/modelRecord.js';
|
||||
import { createModelRecord, showModel } from '../../data/modelRecord.js';
|
||||
|
||||
/** A model record in a given load and show state, placed at `at` unturned. */
|
||||
function modelRecord({ ready, show, at = null }) {
|
||||
const record = createModelRecord({});
|
||||
record.ready = ready;
|
||||
record.show = show;
|
||||
if (at) placeAt(record, at);
|
||||
return record;
|
||||
}
|
||||
|
||||
/** Place a record at `at` with no turn, as a test of where it reads. */
|
||||
function placeAt(record, at) {
|
||||
record.matrix = Float64Array.from(Cesium.Matrix4.fromTranslation(at));
|
||||
record.position = { x: at.x, y: at.y, z: at.z };
|
||||
record.placed = true;
|
||||
}
|
||||
|
||||
function fixture() {
|
||||
const info = {
|
||||
@@ -115,12 +127,10 @@ test('candidate collection resolves models once and keeps handoffs live', (t) =>
|
||||
const get = t.mock.method(f.flightState._models, 'get');
|
||||
const [candidate] = f.queries.getDetectableObjects();
|
||||
assert.equal(get.mock.callCount(), 1);
|
||||
const record = createModelRecord({
|
||||
const record = modelRecord({
|
||||
ready: false,
|
||||
show: true,
|
||||
modelMatrix: Cesium.Matrix4.fromTranslation(
|
||||
new Cesium.Cartesian3(10, 20, 30),
|
||||
),
|
||||
at: new Cesium.Cartesian3(10, 20, 30),
|
||||
});
|
||||
f.parts.rendering._modelSpec = () => ({
|
||||
visualCenterNative: Cesium.Cartesian3.ZERO,
|
||||
@@ -129,13 +139,10 @@ test('candidate collection resolves models once and keeps handoffs live', (t) =>
|
||||
f.flightState._models.set('abc123', record);
|
||||
f.show(false);
|
||||
assert.deepEqual(f.queries.getDetectableObjects(), []);
|
||||
record.model.ready = true;
|
||||
record.ready = true;
|
||||
assert.equal(f.queries.getDetectableObjects()[0], candidate);
|
||||
assert.deepEqual(candidate.position, new Cesium.Cartesian3(10, 20, 30));
|
||||
placeModel(
|
||||
record,
|
||||
Cesium.Matrix4.fromTranslation(new Cesium.Cartesian3(40, 50, 60)),
|
||||
);
|
||||
placeAt(record, new Cesium.Cartesian3(40, 50, 60));
|
||||
f.queries.getDetectableObjects();
|
||||
assert.deepEqual(candidate.position, new Cesium.Cartesian3(40, 50, 60));
|
||||
showModel(record, false);
|
||||
@@ -151,7 +158,7 @@ test('candidate collection resolves models once and keeps handoffs live', (t) =>
|
||||
test('tracked ownership and live anchors remain independent of fleet models', () => {
|
||||
const f = fixture();
|
||||
f.flightState._trackedIcao = 'abc123';
|
||||
f.flightState._trackedModel = createModelRecord({ ready: true, show: true });
|
||||
f.flightState._trackedModel = modelRecord({ ready: true, show: true });
|
||||
f.parts.rendering._modelSpec = () => ({});
|
||||
let anchor = new Cesium.Cartesian3(10, 20, 30);
|
||||
f.parts.motion._trackedVisualCached = () => anchor;
|
||||
@@ -163,16 +170,16 @@ test('tracked ownership and live anchors remain independent of fleet models', ()
|
||||
assert.equal(f.queries.getDetectableObjects()[0].position, anchor);
|
||||
for (const tracked of [
|
||||
null,
|
||||
createModelRecord({ ready: false, show: true }),
|
||||
createModelRecord({ ready: true, show: false }),
|
||||
modelRecord({ ready: false, show: true }),
|
||||
modelRecord({ ready: true, show: false }),
|
||||
]) {
|
||||
f.flightState._trackedModel = tracked;
|
||||
assert.equal(
|
||||
f.parts.rendering._modelOwnsVisual('abc123', createModelRecord({ ready: true, show: true })),
|
||||
f.parts.rendering._modelOwnsVisual('abc123', modelRecord({ ready: true, show: true })),
|
||||
false,
|
||||
);
|
||||
}
|
||||
f.flightState._trackedModel = createModelRecord({ ready: true, show: true });
|
||||
f.flightState._trackedModel = modelRecord({ ready: true, show: true });
|
||||
f.parts.tracking._trackedModelRegimeActive = () => false;
|
||||
assert.equal(f.parts.rendering._modelOwnsVisual('abc123', null), false);
|
||||
});
|
||||
@@ -1,10 +1,11 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { civilAircraftModelSpec } from './modelSpec.js';
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import { isEmergency } from '../../data/aircraftEmergency.js';
|
||||
import {
|
||||
MIL_TINT,
|
||||
EMERGENCY_TINT,
|
||||
FLEET_TINT,
|
||||
TRACKED_CYAN,
|
||||
GROUND_SCALE,
|
||||
COCKPIT_CIVILIAN_COLOR,
|
||||
} from './policy.js';
|
||||
@@ -36,7 +37,7 @@ export function createRendering({
|
||||
info = flightState.records.data.get(icao24),
|
||||
) {
|
||||
if (_isEmergency(icao24, info)) return EMERGENCY_TINT;
|
||||
return isMilitaryIcao(icao24) ? MIL_TINT : Cesium.Color.WHITE;
|
||||
return isMilitaryIcao(icao24) ? MIL_TINT : FLEET_TINT;
|
||||
}
|
||||
|
||||
/** Cockpit far-contact dot tint: the emergency red outranks the category tint. */
|
||||
@@ -78,7 +79,7 @@ export function createRendering({
|
||||
/** Model tint, mirroring the billboard color rules. */
|
||||
|
||||
function _modelColor(icao24) {
|
||||
if (icao24 === flightState._trackedIcao) return Cesium.Color.CYAN;
|
||||
if (icao24 === flightState._trackedIcao) return TRACKED_CYAN;
|
||||
return _fleetBillboardColor(icao24);
|
||||
}
|
||||
|
||||
@@ -88,31 +89,28 @@ export function createRendering({
|
||||
parts,
|
||||
resolveAsset,
|
||||
logLabel: 'Data:Flights',
|
||||
setPrefix: 'flights',
|
||||
policy,
|
||||
modelSpec: _modelSpec,
|
||||
modelColor: _modelColor,
|
||||
// About to render in 3D: jump the ambient type-enrichment backlog.
|
||||
onModelEligible: (icao24) =>
|
||||
parts.enrichment._requestTypeEnrichment(icao24, true),
|
||||
afterReplan: (renderTime, t, nowMs, camera) =>
|
||||
parts.icons._floorGroundedIcons(renderTime, t, nowMs, camera.positionWC),
|
||||
afterReplan: (renderTime, t, nowMs, eye) =>
|
||||
parts.icons._floorGroundedIcons(renderTime, t, nowMs, eye),
|
||||
});
|
||||
|
||||
/**
|
||||
* Sample the rendered mesh under the collected floor cells (see
|
||||
* meshFloorSampler.js), leaving this layer's own icons and models out of
|
||||
* the probe so it cannot land on an aircraft instead of the pavement.
|
||||
* meshFloorSampler.js), leaving this layer's own icons out of the probe so
|
||||
* it cannot land on an aircraft instead of the pavement.
|
||||
*/
|
||||
function _sampleMeshFloor(points, viewerLat, viewerLon) {
|
||||
services.meshFloor.sampleMeshFloorCells(
|
||||
flightState._viewer?.scene,
|
||||
points,
|
||||
{
|
||||
excludeObjects: [
|
||||
...parts.icons._iconIds(),
|
||||
...[...flightState._models.values()].map((record) => record.model),
|
||||
flightState._trackedModel?.model,
|
||||
].filter(Boolean),
|
||||
excludeObjects: parts.icons._iconIds(),
|
||||
viewerLat,
|
||||
viewerLon,
|
||||
},
|
||||
|
||||
@@ -30,32 +30,16 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._groundSnap = createGroundSnap();
|
||||
|
||||
flightState._scratchGroundCarto = new Cesium.Cartographic();
|
||||
/** The fleet and tracked model draw sets of this layer lifetime
|
||||
* (`_createModelSets`), or null. */
|
||||
|
||||
flightState._scratchGroundPos = new Cesium.Cartesian3();
|
||||
flightState._modelSets = null;
|
||||
|
||||
/** @type {Cesium.PrimitiveCollection|null} */
|
||||
|
||||
flightState._modelCollection = null;
|
||||
|
||||
/** @type {Map<string, Cesium.Model>} icao24 → model */
|
||||
/** @type {Map<string, import('../../data/modelRecord.js').ModelRecord>}
|
||||
* icao24 → the fleet model admitted for it (loading or drawn). */
|
||||
|
||||
flightState._models = new Map();
|
||||
|
||||
/** @type {Set<string>} icao24 currently loading (async) */
|
||||
|
||||
flightState._modelPending = new Set();
|
||||
|
||||
/** @type {Map<string, number>} icao24 → load generation; bumped on release to invalidate
|
||||
* an in-flight load (so a track/untrack/remove during fromGltfAsync can't add a stale model). */
|
||||
|
||||
flightState._modelGen = new Map();
|
||||
|
||||
/** Lifecycle epoch; bumped on destroy so an in-flight load from a PREVIOUS init can't settle
|
||||
* against a new lifecycle's globals (which destroy cleared). Captured by _ensureModel. */
|
||||
|
||||
flightState._modelEpoch = 0;
|
||||
|
||||
/** DEFAULT-ON in PROXIMITY (owner directive 2026-08-22). A fresh boot never runs
|
||||
* layer-state restoration, so this initializer — not the codec — is what the app
|
||||
* actually starts with; it must stay in lockstep with the `models3d` default in
|
||||
@@ -69,22 +53,6 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._lastModelCapWarnMs = 0;
|
||||
// throttle the "more planes in view than the cap" console notice
|
||||
// The tracked entity's billboard goes transparent (rather than hidden) once the model takes
|
||||
// over, so it keeps supplying a bounding sphere for follow-camera framing. We only drop its
|
||||
// alpha after the GLB is preloaded so the model is ready to render the instant the billboard
|
||||
// fades — no gap, no double-image. Preloaded once at init; the instance is retained (not
|
||||
// destroyed) purely to keep Cesium's glTF cache warm for fast tracked-model instantiation.
|
||||
|
||||
flightState._planeModelLoaded = false;
|
||||
|
||||
/** @type {Cesium.Model|null} retained preload that keeps the glTF cache warm */
|
||||
|
||||
flightState._preloadModel = null;
|
||||
|
||||
flightState._scratchModelHpr = new Cesium.HeadingPitchRoll(0, 0, 0);
|
||||
|
||||
flightState._scratchModelMtx = new Cesium.Matrix4();
|
||||
|
||||
flightState._scratchModelBS = new Cesium.BoundingSphere(
|
||||
new Cesium.Cartesian3(),
|
||||
1.0,
|
||||
@@ -148,19 +116,13 @@ export function createFlightState({ source, services }) {
|
||||
/** The FollowTarget the camera follows the tracked aircraft with. */
|
||||
flightState._followTarget = null;
|
||||
|
||||
/** @type {Cesium.Model|null} Standalone 3D model for the tracked aircraft. Deliberately NOT a
|
||||
/** @type {import('../../data/modelRecord.js').ModelRecord|null} Standalone 3D model for the tracked aircraft. Deliberately NOT a
|
||||
* graphic on _trackedEntity: a model graphic reports PENDING until its glTF loads, and the
|
||||
* tracked entity must stay a plain, always-ready billboard. The model rides in _modelCollection
|
||||
* tracked entity must stay a plain, always-ready billboard. The model rides in its own draw set
|
||||
* and is driven per-frame, fully decoupled from the camera, which follows its own target. */
|
||||
|
||||
flightState._trackedModel = null;
|
||||
|
||||
/** Bumped on untrack/teardown so an in-flight tracked-model load resolves into a no-op. */
|
||||
|
||||
flightState._trackedModelGen = 0;
|
||||
|
||||
flightState._trackedModelLoading = false;
|
||||
|
||||
/** @type {(() => void)|null} Unsubscribes the scene click. */
|
||||
|
||||
flightState._clickSubscription = null;
|
||||
@@ -379,12 +341,6 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._trackedZoomLatchIcao = null;
|
||||
|
||||
flightState._trackedModelFailIcao = null;
|
||||
|
||||
flightState._trackedModelFailCount = 0;
|
||||
|
||||
flightState._trackedModelRetryAtMs = 0;
|
||||
|
||||
/** @type {Cesium.Cartographic} Scratch for the grounded display-floor read. */
|
||||
|
||||
flightState._scratchDisplayCarto = new Cesium.Cartographic();
|
||||
@@ -428,21 +384,5 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._irBoost = false;
|
||||
|
||||
/** Boosted models render UNLIT (owner cockpit-FLIR field rounds, 2026-08-16):
|
||||
* the white tint alone is applied to the MATERIAL, so Cesium still
|
||||
* sun-shades it — near-horizon viewing shows a plane's SIDE, ~90° to a high
|
||||
* sun, so it rendered near-BLACK in FLIR/NVG while sun-lit neighbors glowed.
|
||||
* LightingModel.UNLIT emits the flat white directly, orientation be damned.
|
||||
* CRITICAL (field-verified via scene.pick): assigning customShader to an
|
||||
* already-READY model is a silent no-op — the property sets but the shader
|
||||
* program never rebuilds. The boost therefore flips by RELEASE-AND-RELOAD
|
||||
* (see setParams), so every boosted model gets the shader AT CREATION.
|
||||
* One shared shader instance — stateless, safe across models. */
|
||||
|
||||
flightState._IR_UNLIT_SHADER = new Cesium.CustomShader({
|
||||
lightingModel: Cesium.LightingModel.UNLIT,
|
||||
});
|
||||
|
||||
flightState._irReloadQueue = null;
|
||||
return flightState;
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { CYAN_TRANSPARENT } from './policy.js';
|
||||
import { CYAN_TRANSPARENT, TRACKED_CYAN } from './policy.js';
|
||||
import { createModelRecord } from '../../data/modelRecord.js';
|
||||
import {
|
||||
aircraftIconTestSeams,
|
||||
@@ -15,7 +14,7 @@ export function createTesting({
|
||||
}) {
|
||||
const { _seedIconForTest, _iconForTest, _setIconForTest } =
|
||||
aircraftIconTestSeams(flightState, parts, 'flights');
|
||||
/** Test seam for the display-floor clamp (unit-tested against real Cesium math
|
||||
/** Test seam for the display-floor clamp (unit-tested against real ellipsoid math
|
||||
* with seeded mesh cells — the drift mechanism is otherwise only reachable
|
||||
* through a live poll + render loop). */
|
||||
|
||||
@@ -46,21 +45,49 @@ export function createTesting({
|
||||
/**
|
||||
* Seed only the mutable state needed to exercise tracked-card refreshes through
|
||||
* the production poll reconciler. Tests still call `flightsLayer.update()`;
|
||||
* this seam avoids constructing the browser-only Cesium layer lifecycle.
|
||||
* this seam avoids constructing the browser-only layer lifecycle.
|
||||
* @param {object} state
|
||||
* @param {string} state.icao24
|
||||
* @param {object} state.entity
|
||||
* @param {object} state.meta
|
||||
* @param {{position?: Cesium.Cartesian3, show?: boolean}} [state.icon]
|
||||
* @param {{position?: {x: number, y: number, z: number}, show?: boolean}} [state.icon]
|
||||
* Where the contact's icon is held, and whether it is shown.
|
||||
* @param {{show?: boolean}} [state.iconLayer] Layer visibility.
|
||||
* @param {object} state.viewer
|
||||
* @param {Array<Object>} [state.history=[]]
|
||||
* @param {boolean} [state.tracked=true]
|
||||
* @param {Iterable<[string, object]>} [state.models=[]] - Fleet 3D models keyed
|
||||
* by icao24, for the icon-hidden/model-shown handoff state.
|
||||
* by icao24, for the icon-hidden/model-shown handoff state: each object
|
||||
* becomes the contact's model record (`ready`, `show`, and a placement
|
||||
* `modelMatrix` when given), so the test reads what the layer writes back.
|
||||
* @param {object|null} [state.draw] A draw port the layer's model sets are
|
||||
* made on (a test double); none keeps the records only.
|
||||
*/
|
||||
|
||||
/** Turn a test's model fields into the contact's model record, in place. */
|
||||
function _modelRecordForTest(fields, klass) {
|
||||
const spec = parts.rendering._modelSpec(klass);
|
||||
const base = createModelRecord({
|
||||
specKey: parts.rendering._specKeyFor(klass),
|
||||
bellyM: spec.bellyM,
|
||||
scale: spec.scale,
|
||||
});
|
||||
for (const key of Object.keys(base))
|
||||
if (!(key in fields)) fields[key] = base[key];
|
||||
fields.ready = fields.ready === true;
|
||||
fields.show = fields.show ?? true;
|
||||
if (fields.modelMatrix) {
|
||||
fields.matrix = Float64Array.from(fields.modelMatrix);
|
||||
fields.position = {
|
||||
x: fields.matrix[12],
|
||||
y: fields.matrix[13],
|
||||
z: fields.matrix[14],
|
||||
};
|
||||
fields.placed = true;
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
function _setTrackedFlightRefreshStateForTest({
|
||||
icao24,
|
||||
entity,
|
||||
@@ -71,10 +98,11 @@ export function createTesting({
|
||||
history = [],
|
||||
tracked = true,
|
||||
models = [],
|
||||
modelCollection = null,
|
||||
draw = null,
|
||||
}) {
|
||||
flightState._viewer = viewer;
|
||||
flightState._modelCollection = modelCollection;
|
||||
parts.rendering._disposeModelSets();
|
||||
if (draw) parts.rendering._createModelSets(viewer, { draw });
|
||||
flightState._icons = createContactIcons();
|
||||
flightState._icons.show = iconLayer?.show ?? true;
|
||||
flightState._grounded.clear();
|
||||
@@ -82,7 +110,7 @@ export function createTesting({
|
||||
_seedIconForTest(icao24, icon, tracked);
|
||||
flightState._models.clear();
|
||||
for (const [key, model] of models)
|
||||
flightState._models.set(key, createModelRecord(model));
|
||||
flightState._models.set(key, _modelRecordForTest(model, meta?.klass));
|
||||
flightState._detectionObjects = new Map();
|
||||
flightState.records.data = new Map([[icao24, meta]]);
|
||||
flightState._positionHistory = new Map([[icao24, history]]);
|
||||
@@ -93,7 +121,6 @@ export function createTesting({
|
||||
flightState._trackedEntity = tracked ? entity : null;
|
||||
flightState._trackedModel = null;
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
flightState._trackedModelLoading = false;
|
||||
// NOTE: deliberately does NOT reset the per-selection latches. They are
|
||||
// production state owned by the tracking lifecycle (_resetTrackedSelectionState),
|
||||
// and clearing them here would mask exactly the deselect→re-track hole this
|
||||
@@ -175,7 +202,7 @@ export function createTesting({
|
||||
}
|
||||
|
||||
/** Run one frame of the production tracked-model driver (normally a
|
||||
* `scene.preUpdate` listener) so tests can pin its bounded load retries. */
|
||||
* `preUpdate` listener). */
|
||||
|
||||
function _updateTrackedModelForTest() {
|
||||
return parts.rendering._updateTrackedModel();
|
||||
@@ -186,7 +213,7 @@ export function createTesting({
|
||||
function _trackedBillboardColorForTest() {
|
||||
return parts.rendering._modelOwnsVisual(flightState._trackedIcao)
|
||||
? CYAN_TRANSPARENT
|
||||
: Cesium.Color.CYAN;
|
||||
: TRACKED_CYAN;
|
||||
}
|
||||
|
||||
/** Drive the exact fleet icon-to-model handoff used by `_fleetTick`. */
|
||||
@@ -200,18 +227,31 @@ export function createTesting({
|
||||
);
|
||||
}
|
||||
|
||||
/** Exercise the exact asynchronous fleet loader and return its admitted model. */
|
||||
/** Exercise the exact fleet admission and return the admitted model's record. */
|
||||
|
||||
async function _ensureFleetModelForTest(icao24) {
|
||||
await parts.rendering._ensureModel(icao24);
|
||||
return flightState._models.get(icao24)?.model ?? null;
|
||||
function _ensureFleetModelForTest(icao24) {
|
||||
parts.rendering._ensureModel(icao24);
|
||||
return flightState._models.get(icao24) ?? null;
|
||||
}
|
||||
|
||||
/** The tracked model's record, or null. */
|
||||
|
||||
function _trackedModelForTest() {
|
||||
return flightState._trackedModel;
|
||||
}
|
||||
|
||||
/** The fleet and tracked model sets' ids, or null without sets. */
|
||||
|
||||
function _modelSetIdsForTest() {
|
||||
const [fleet, tracked] = parts.rendering._modelSetIds();
|
||||
return fleet ? { fleet, tracked } : null;
|
||||
}
|
||||
/** Run the fleet tick's grounded floor pass once, at `renderTime`. */
|
||||
|
||||
function _floorGroundedIconsForTest(renderTime, cameraPosition) {
|
||||
parts.icons._floorGroundedIcons(
|
||||
renderTime,
|
||||
Cesium.JulianDate.toDate(renderTime).getTime(),
|
||||
parts.motion._fixEpochMs({ time: renderTime }),
|
||||
Date.now(),
|
||||
cameraPosition,
|
||||
);
|
||||
@@ -235,5 +275,7 @@ export function createTesting({
|
||||
_driveFleetModelHandoffForTest,
|
||||
_iconForTest,
|
||||
_ensureFleetModelForTest,
|
||||
_trackedModelForTest,
|
||||
_modelSetIdsForTest,
|
||||
};
|
||||
}
|
||||
@@ -24,8 +24,6 @@ import {
|
||||
} from '../../data/trackingClickGesture.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import {
|
||||
TRACKED_MODEL_MAX_LOAD_FAILS,
|
||||
TRACKED_MODEL_RETRY_BACKOFF_MS,
|
||||
TRAIL_MAX_POINTS,
|
||||
RENDER_DELAY_SEC,
|
||||
TRAIL_COLOR,
|
||||
@@ -36,8 +34,8 @@ import { roundHeadingDegrees } from '../../data/headingDegrees.js';
|
||||
import { entityRecord } from '../../data/entityRecords.js';
|
||||
|
||||
/**
|
||||
* The icao a pick carries: a draw-set item's id (the icon sets' rows), a
|
||||
* string pick id, or a model primitive's id.
|
||||
* The icao a pick carries: a draw-set item's id (the icon and model sets'
|
||||
* rows), a string pick id, or a primitive's id.
|
||||
*/
|
||||
function aircraftPickId(picked) {
|
||||
const id = picked?.id;
|
||||
@@ -223,7 +221,7 @@ export function createTracking({
|
||||
// aircraft silhouette until a ready model takes over; far contacts are pips.
|
||||
// Never destroy on entry: tearing down hundreds of live glTF instances
|
||||
// synchronously blocked Chrome's renderer into Page Unresponsive.
|
||||
if (flightState._modelCollection) flightState._modelCollection.show = true;
|
||||
parts.rendering._setModelsShown(true);
|
||||
flightState._trail?.setVisible(!next);
|
||||
for (const icao24 of flightState._icons?.ids() ?? [])
|
||||
parts.icons._applyIconPresentation(icao24);
|
||||
@@ -240,8 +238,8 @@ export function createTracking({
|
||||
_setCockpitContactMode(active);
|
||||
}
|
||||
|
||||
/** Clear every per-SELECTION tracked-model latch: the zoom hysteresis band and
|
||||
* the load-failure bound. Called from each path that changes which contact is
|
||||
/** Clear the per-SELECTION tracked-model latch: the zoom hysteresis band.
|
||||
* Called from each path that changes which contact is
|
||||
* selected — deselect, re-track, cross-layer handoff, init, destroy.
|
||||
*
|
||||
* This must live in the production lifecycle, not only in the predicate's
|
||||
@@ -249,44 +247,11 @@ export function createTracking({
|
||||
* icao (Contacts re-entry, a cross-layer round trip back to the original
|
||||
* layer) never makes `_trackedIcao` *observably* change, so the guard never
|
||||
* fires. Without the reset, a contact dropped inside the hysteresis band comes
|
||||
* back as a MODEL above the ENTER ceiling, and a contact whose GLB had already
|
||||
* failed out would never get its retries back. */
|
||||
* back as a MODEL above the ENTER ceiling. */
|
||||
|
||||
function _resetTrackedSelectionState() {
|
||||
flightState._trackedZoomLatched = false;
|
||||
flightState._trackedZoomLatchIcao = null;
|
||||
flightState._trackedModelFailIcao = null;
|
||||
flightState._trackedModelFailCount = 0;
|
||||
flightState._trackedModelRetryAtMs = 0;
|
||||
}
|
||||
|
||||
/** Whether the driver may start another tracked-model load this frame. */
|
||||
|
||||
function _trackedModelLoadAllowed(nowMs = Date.now()) {
|
||||
if (flightState._trackedModelFailIcao !== flightState._trackedIcao)
|
||||
return true; // untried selection
|
||||
if (flightState._trackedModelFailCount >= TRACKED_MODEL_MAX_LOAD_FAILS)
|
||||
return false;
|
||||
return nowMs >= flightState._trackedModelRetryAtMs;
|
||||
}
|
||||
|
||||
/** Record a rejected tracked-model load and arm the backoff / give-up latch. */
|
||||
|
||||
function _noteTrackedModelLoadFailure(url, err) {
|
||||
if (flightState._trackedModelFailIcao !== flightState._trackedIcao) {
|
||||
flightState._trackedModelFailIcao = flightState._trackedIcao;
|
||||
flightState._trackedModelFailCount = 0;
|
||||
}
|
||||
flightState._trackedModelFailCount += 1;
|
||||
flightState._trackedModelRetryAtMs =
|
||||
Date.now() + TRACKED_MODEL_RETRY_BACKOFF_MS;
|
||||
if (flightState._trackedModelFailCount >= TRACKED_MODEL_MAX_LOAD_FAILS) {
|
||||
console.warn(
|
||||
`[Data:Flights] tracked 3D model gave up after ${flightState._trackedModelFailCount} failed loads of ${url} — ` +
|
||||
'this contact stays 2D until another is selected',
|
||||
err,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -662,7 +627,7 @@ export function createTracking({
|
||||
flightState._trackedEntity = null;
|
||||
}
|
||||
parts.rendering._releaseTrackedModel();
|
||||
_resetTrackedSelectionState(); // the zoom band + load-failure budget belong to the selection we just dropped
|
||||
_resetTrackedSelectionState(); // the zoom band belongs to the selection we just dropped
|
||||
flightState._trackedIcao = null;
|
||||
// Hand the contact back to its icon only now: settling floors a grounded
|
||||
// contact, and while it still read as tracked its tracked model owned the
|
||||
@@ -821,8 +786,7 @@ export function createTracking({
|
||||
if (isTr3b(id)) {
|
||||
// Drop the 3D handoff for this contact — the fleet tick now skips it, so
|
||||
// an already-loaded model would otherwise linger with the billboard hidden.
|
||||
if (flightState._models.has(id) || flightState._modelPending.has(id))
|
||||
parts.rendering._releaseModel(id);
|
||||
if (flightState._models.has(id)) parts.rendering._releaseModel(id);
|
||||
if (flightState._icons?.has(id) && id !== flightState._trackedIcao)
|
||||
flightState._icons.setShown(id, true);
|
||||
if (id === flightState._trackedIcao) {
|
||||
@@ -903,7 +867,7 @@ export function createTracking({
|
||||
const iconCourse = icons.course(icao24, t);
|
||||
flightState._displayCourse.set(icao24, iconCourse);
|
||||
flightState._trackedIcao = icao24;
|
||||
_resetTrackedSelectionState(); // fresh selection: enter at the ENTER ceiling, full load-retry budget
|
||||
_resetTrackedSelectionState(); // fresh selection: enter at the ENTER ceiling
|
||||
flightState._cachedDRFrame = -1;
|
||||
flightState._lastTrackedRotation =
|
||||
screenProjectedRotation(
|
||||
@@ -940,7 +904,7 @@ export function createTracking({
|
||||
// resolves into an aircraft.
|
||||
//
|
||||
// The billboard stays SHOWN at all times and is hidden by going TRANSPARENT (alpha 0), not by
|
||||
// show=false: it drops its alpha only once the model GLB is preloaded (_planeModelLoaded), so
|
||||
// show=false: it drops its alpha only once the tracked model is drawing, so
|
||||
// there's neither a billboard+model double-image nor a gap. The camera follows its own target
|
||||
// through the camera port, so nothing here frames the camera.
|
||||
// The tracked entity is a PURE BILLBOARD — no label or model graphic. The 3D model for the
|
||||
@@ -1185,17 +1149,11 @@ export function createTracking({
|
||||
// any pick carrying its icao) — same no-op as the 2D tracked-entity click
|
||||
// above. H1: the model used to have no pick id, so this fell through to
|
||||
// "empty space" and deselected the very plane being tracked.
|
||||
if (flightState._trackedIcao) {
|
||||
const rawPick = aircraftPickId(picked);
|
||||
if (
|
||||
(flightState._trackedModel &&
|
||||
picked.primitive === flightState._trackedModel.model) ||
|
||||
rawPick === flightState._trackedIcao
|
||||
)
|
||||
return;
|
||||
}
|
||||
|
||||
// Its models are draw-set items keyed by icao, like its icons.
|
||||
const pickedIcao = aircraftPickId(picked);
|
||||
if (flightState._trackedIcao && pickedIcao === flightState._trackedIcao)
|
||||
return;
|
||||
|
||||
if (pickedIcao && flightState._icons?.has(pickedIcao)) {
|
||||
_cancelPendingTrackingRestore();
|
||||
_trackFlight(pickedIcao, { origin: 'user' });
|
||||
@@ -1233,8 +1191,6 @@ export function createTracking({
|
||||
_setCockpitContactMode,
|
||||
_applyCockpitState,
|
||||
_resetTrackedSelectionState,
|
||||
_trackedModelLoadAllowed,
|
||||
_noteTrackedModelLoadFailure,
|
||||
_trackedModelRegimeActive,
|
||||
_syncTracked2dRotation,
|
||||
_appendTrailFix,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { findCamera, findFrame } from '../../render/rendererOf.js';
|
||||
import { JET_MODEL_URL } from './policy.js';
|
||||
|
||||
export function createLifecycle({
|
||||
@@ -31,7 +31,7 @@ export function createLifecycle({
|
||||
/**
|
||||
* Initialize the layer: create the icon set and its primitive, reset all state,
|
||||
* and install the click-to-track handler.
|
||||
* @param {Cesium.Viewer} viewer - The Cesium viewer instance
|
||||
* @param {object} viewer - The Cesium viewer instance
|
||||
*/
|
||||
init(viewer) {
|
||||
if (flightState._viewer)
|
||||
@@ -43,33 +43,11 @@ export function createLifecycle({
|
||||
clearFocusTarget('militaryFlights');
|
||||
flightState._viewer = viewer;
|
||||
registerSpriteSet('military', parts.icons._createIcons(viewer));
|
||||
flightState._modelCollection = new Cesium.PrimitiveCollection();
|
||||
viewer.scene.primitives.add(flightState._modelCollection);
|
||||
// Warm the glTF cache so the tracked plane's model instantiates instantly when first needed
|
||||
// (keeps the retained instance referenced; never rendered). Captured against this epoch so a
|
||||
// destroy/re-init mid-load doesn't flip the flag for a torn-down lifecycle.
|
||||
if (!flightState._preloadModel) {
|
||||
const epoch = flightState._modelEpoch;
|
||||
Cesium.Model.fromGltfAsync({
|
||||
url: resolveAsset(JET_MODEL_URL),
|
||||
asynchronous: false,
|
||||
})
|
||||
.then((m) => {
|
||||
if (epoch === flightState._modelEpoch) {
|
||||
flightState._preloadModel = m;
|
||||
flightState._planeModelLoaded = true;
|
||||
} else {
|
||||
try {
|
||||
m.destroy();
|
||||
} catch {
|
||||
/* gone */
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
/* tracked plane just stays an icon a beat longer */
|
||||
});
|
||||
}
|
||||
// The models' draw sets; a hidden item keeps the tracked asset loaded so
|
||||
// the tracked plane's model draws as soon as it is wanted.
|
||||
parts.rendering._createModelSets(viewer, {
|
||||
preloadUrl: resolveAsset(JET_MODEL_URL),
|
||||
});
|
||||
flightState._iconFocusActive = 0;
|
||||
flightState._detectionObjects = new Map();
|
||||
flightState.records.data = new Map();
|
||||
@@ -107,13 +85,12 @@ export function createLifecycle({
|
||||
|
||||
/**
|
||||
* Show the layer and re-install the click handler.
|
||||
* @param {Cesium.Viewer} viewer - The Cesium viewer instance
|
||||
* @param {object} viewer - The Cesium viewer instance
|
||||
*/
|
||||
enable(viewer) {
|
||||
if (flightState._icons) flightState._icons.show = true;
|
||||
holdContinuousRender('military'); // per-frame animator (perf wave 2)
|
||||
if (flightState._modelCollection)
|
||||
flightState._modelCollection.show = true;
|
||||
parts.rendering._setModelsShown(true);
|
||||
parts.tracking._setCockpitContactMode(
|
||||
document.body.classList.contains('cockpit-mode'),
|
||||
);
|
||||
@@ -137,26 +114,25 @@ export function createLifecycle({
|
||||
);
|
||||
// The flights layer suppresses its military duplicates while we render them
|
||||
setMilitaryLayerActive(true);
|
||||
if (!flightState._preRenderRemove && viewer?.scene) {
|
||||
flightState._preRenderRemove = viewer.scene.preRender.addEventListener(
|
||||
parts.rendering._fleetTick,
|
||||
const frame = findFrame(viewer);
|
||||
if (!flightState._preRenderRemove && frame) {
|
||||
flightState._preRenderRemove = frame.on('preRender', () =>
|
||||
parts.rendering._fleetTick(),
|
||||
);
|
||||
}
|
||||
if (!flightState._trackedModelPreUpdateRemove && viewer?.scene) {
|
||||
flightState._trackedModelPreUpdateRemove =
|
||||
viewer.scene.preUpdate.addEventListener(
|
||||
parts.rendering._updateTrackedModel,
|
||||
);
|
||||
if (!flightState._trackedModelPreUpdateRemove && frame) {
|
||||
flightState._trackedModelPreUpdateRemove = frame.on('preUpdate', () =>
|
||||
parts.rendering._updateTrackedModel(),
|
||||
);
|
||||
}
|
||||
if (!flightState._moveEndRemove && viewer?.camera) {
|
||||
const camera = findCamera(viewer);
|
||||
if (!flightState._moveEndRemove && camera) {
|
||||
// A settled camera move (voice fly-to, fast pan release) runs the fleet
|
||||
// pass on the very next preRender rather than up to FLEET_DR_INTERVAL_MS
|
||||
// later, so the model handoff and focus land with the camera.
|
||||
flightState._moveEndRemove = viewer.camera.moveEnd.addEventListener(
|
||||
() => {
|
||||
flightState._lastFleetTickMs = 0;
|
||||
},
|
||||
);
|
||||
flightState._moveEndRemove = camera.on('moveEnd', () => {
|
||||
flightState._lastFleetTickMs = 0;
|
||||
});
|
||||
}
|
||||
restoreSpriteOrder(viewer);
|
||||
},
|
||||
@@ -164,7 +140,7 @@ export function createLifecycle({
|
||||
/**
|
||||
* Hide the layer, clear any active tracking, and remove input handlers
|
||||
* so clicks do not get intercepted while the layer is off.
|
||||
* @param {Cesium.Viewer} viewer - The Cesium viewer instance
|
||||
* @param {object} viewer - The Cesium viewer instance
|
||||
*/
|
||||
disable(viewer) {
|
||||
parts.controller._abortActiveUpdates();
|
||||
@@ -172,8 +148,7 @@ export function createLifecycle({
|
||||
if (flightState._icons) flightState._icons.show = false;
|
||||
releaseContinuousRender('military');
|
||||
parts.rendering._releaseModels();
|
||||
if (flightState._modelCollection)
|
||||
flightState._modelCollection.show = false;
|
||||
parts.rendering._setModelsShown(false);
|
||||
parts.tracking._clearTracking();
|
||||
parts.tracking._destroyTrail();
|
||||
// Remove click handler + keydown listener while disabled to avoid
|
||||
@@ -205,7 +180,7 @@ export function createLifecycle({
|
||||
/**
|
||||
* Tear down the layer: clear tracking, remove handlers, remove the icon
|
||||
* primitive from the scene, and release all state.
|
||||
* @param {Cesium.Viewer} viewer - The Cesium viewer instance
|
||||
* @param {object} viewer - The Cesium viewer instance
|
||||
*/
|
||||
destroy(viewer) {
|
||||
flightState.lifetime.abort();
|
||||
@@ -243,22 +218,7 @@ export function createLifecycle({
|
||||
}
|
||||
parts.rendering._releaseModels();
|
||||
parts.icons._disposeIcons();
|
||||
if (flightState._modelCollection) {
|
||||
viewer.scene.primitives.remove(flightState._modelCollection); // removing destroys it + its models
|
||||
flightState._modelCollection = null;
|
||||
}
|
||||
flightState._modelEpoch += 1; // invalidate any in-flight load from this lifecycle (settles post-destroy)
|
||||
flightState._modelPending.clear();
|
||||
flightState._modelGen.clear();
|
||||
if (flightState._preloadModel) {
|
||||
try {
|
||||
flightState._preloadModel.destroy();
|
||||
} catch {
|
||||
/* gone */
|
||||
}
|
||||
flightState._preloadModel = null;
|
||||
}
|
||||
flightState._planeModelLoaded = false;
|
||||
parts.rendering._disposeModelSets();
|
||||
flightState._iconFocusActive = 0;
|
||||
flightState._detectionObjects.clear();
|
||||
flightState.records.data.clear();
|
||||
|
||||
@@ -330,7 +330,7 @@ export function createMotion({
|
||||
* The position the tracked aircraft is VISUALLY at this frame — the translation its 3D
|
||||
* model is actually rendering with when the model owns the visual, otherwise the cached
|
||||
* dead-reckoned position. Mirror of flights.js; see that copy for the full rationale.
|
||||
* Reads the modelMatrix the tracked-model update already wrote this frame: no sampling,
|
||||
* Reads the placement the tracked-model update already recorded this frame: no sampling,
|
||||
* no `_modelDisplayPosition` from postRender, and the entity record's `displayPosition` keeps its
|
||||
* follow-camera anti-jitter contract untouched.
|
||||
*/
|
||||
@@ -346,9 +346,7 @@ export function createMotion({
|
||||
return modelVisualAnchor(
|
||||
flightState._trackedModel.matrix,
|
||||
spec.visualCenterNative,
|
||||
Number.isFinite(flightState._trackedModel.model.computedScale)
|
||||
? flightState._trackedModel.model.computedScale
|
||||
: spec.scale,
|
||||
parts.rendering._modelDrawnScale(flightState._trackedModel, spec),
|
||||
flightState._trackedVisualPos,
|
||||
);
|
||||
}
|
||||
@@ -356,8 +354,8 @@ export function createMotion({
|
||||
}
|
||||
|
||||
/** The tracked model's rendered bounding radius (m), or 0 when no model of this
|
||||
* contact is drawing. Carries Cesium's effective `computedScale`, which may be
|
||||
* above `scale` to satisfy minimumPixelSize — the trail head has to be judged
|
||||
* contact is drawing. Carries the scale it is drawn at, which may be
|
||||
* above `scale` to satisfy its pixel floor — the trail head has to be judged
|
||||
* against the size the operator SEES, not the nominal one. */
|
||||
/** World-space origin of the tracked model, or null when no model of this
|
||||
* contact is drawing. This is the centre the rendered bounding sphere is
|
||||
@@ -386,10 +384,10 @@ export function createMotion({
|
||||
const spec = parts.rendering._modelSpec(
|
||||
flightState.records.data.get(flightState._trackedIcao)?.klass,
|
||||
);
|
||||
const scale = Number.isFinite(flightState._trackedModel.model.computedScale)
|
||||
? flightState._trackedModel.model.computedScale
|
||||
: spec.scale;
|
||||
return spec.nativeRadiusM * scale;
|
||||
return (
|
||||
spec.nativeRadiusM *
|
||||
parts.rendering._modelDrawnScale(flightState._trackedModel, spec)
|
||||
);
|
||||
}
|
||||
|
||||
/** Trail endpoint for the rendered tracked owner. Brackets/readouts stay on
|
||||
@@ -409,9 +407,7 @@ export function createMotion({
|
||||
return modelAnchorWorld(
|
||||
flightState._trackedModel.matrix,
|
||||
spec.trailAnchorNative,
|
||||
Number.isFinite(flightState._trackedModel.model.computedScale)
|
||||
? flightState._trackedModel.model.computedScale
|
||||
: spec.scale,
|
||||
parts.rendering._modelDrawnScale(flightState._trackedModel, spec),
|
||||
flightState._trackedTrailPos,
|
||||
);
|
||||
}
|
||||
@@ -527,11 +523,7 @@ export function createMotion({
|
||||
flightState._viewer?.scene,
|
||||
points,
|
||||
{
|
||||
excludeObjects: [
|
||||
...parts.icons._iconIds(),
|
||||
...[...flightState._models.values()].map((record) => record.model),
|
||||
flightState._trackedModel?.model,
|
||||
].filter(Boolean),
|
||||
excludeObjects: parts.icons._iconIds(),
|
||||
viewerLat,
|
||||
viewerLon,
|
||||
},
|
||||
|
||||
@@ -229,25 +229,3 @@ export const COURSE_SLEW_DT_MAX_SEC = 0.25;
|
||||
// camera, and trail head never visibly jump — with zero steady-state lag. --
|
||||
|
||||
export const DR_CORRECTION_MS = 900;
|
||||
|
||||
/** Bounded on-demand loading for the tracked model (mirror of flights.js). The
|
||||
* tracked regime is DEFAULT-ON and its driver runs every `scene.preUpdate`, so
|
||||
* a missing or corrupt GLB — or a dead network — would otherwise spin
|
||||
* load→reject at frame rate for as long as the contact stays selected.
|
||||
* Failures are counted PER SELECTION: a short backoff absorbs a transient
|
||||
* blip, then the layer stops asking until the operator selects something else.
|
||||
* The billboard is the visual throughout (the handoff only fades it once a
|
||||
* model actually renders), so a latched failure degrades to exactly the
|
||||
* pre-3D presentation. */
|
||||
|
||||
export const TRACKED_MODEL_MAX_LOAD_FAILS = 3;
|
||||
|
||||
export const TRACKED_MODEL_RETRY_BACKOFF_MS = 1500;
|
||||
|
||||
/** Boost flip = BATCHED release through the fleet tick (mirror of flights.js —
|
||||
* destroying the whole fleet synchronously in the style handler stalls the
|
||||
* render thread). Models tagged with their load-time boost state; stale queue
|
||||
* entries skip; in-flight loads invalidated immediately; tracked reloads
|
||||
* synchronously (single primitive). */
|
||||
|
||||
export const IR_RELOAD_BATCH = 40;
|
||||
@@ -440,6 +440,8 @@ export function createQueries({
|
||||
|
||||
const result = [];
|
||||
const ids = icons.ids();
|
||||
/** One camera and viewport for every model's drawn scale. */
|
||||
let view = null;
|
||||
for (let i = start; i < ids.length; i += stride) {
|
||||
const icao24 = ids[i];
|
||||
if (
|
||||
@@ -481,9 +483,11 @@ export function createQueries({
|
||||
? modelVisualAnchor(
|
||||
record.matrix,
|
||||
spec.visualCenterNative,
|
||||
Number.isFinite(record.model.computedScale)
|
||||
? record.model.computedScale
|
||||
: spec.scale,
|
||||
parts.rendering._modelDrawnScale(
|
||||
record,
|
||||
spec,
|
||||
(view ??= parts.rendering._drawnScaleView()),
|
||||
),
|
||||
object._weldPos || (object._weldPos = new Cesium.Cartesian3()),
|
||||
)
|
||||
: icons.position(icao24, t, object._iconPos);
|
||||
|
||||
@@ -132,6 +132,7 @@ export function createRendering({
|
||||
parts,
|
||||
resolveAsset,
|
||||
logLabel: 'Data:Military',
|
||||
setPrefix: 'military',
|
||||
policy,
|
||||
modelSpec: _modelSpec,
|
||||
modelColor: _modelColor,
|
||||
|
||||
@@ -27,32 +27,16 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._groundSnap = createGroundSnap();
|
||||
|
||||
flightState._scratchGroundCarto = new Cesium.Cartographic();
|
||||
/** The fleet and tracked model draw sets of this layer lifetime
|
||||
* (`_createModelSets`), or null. */
|
||||
|
||||
flightState._scratchGroundPos = new Cesium.Cartesian3();
|
||||
flightState._modelSets = null;
|
||||
|
||||
/** @type {Cesium.PrimitiveCollection|null} */
|
||||
|
||||
flightState._modelCollection = null;
|
||||
|
||||
/** @type {Map<string, Cesium.Model>} icao24 → model */
|
||||
/** @type {Map<string, import('../../data/modelRecord.js').ModelRecord>}
|
||||
* icao24 → the fleet model admitted for it (loading or drawn). */
|
||||
|
||||
flightState._models = new Map();
|
||||
|
||||
/** @type {Set<string>} icao24 currently loading (async) */
|
||||
|
||||
flightState._modelPending = new Set();
|
||||
|
||||
/** @type {Map<string, number>} icao24 → load generation; bumped on release to invalidate
|
||||
* an in-flight load (so a track/untrack/remove during fromGltfAsync can't add a stale model). */
|
||||
|
||||
flightState._modelGen = new Map();
|
||||
|
||||
/** Lifecycle epoch; bumped on destroy so an in-flight load from a PREVIOUS init can't settle
|
||||
* against a new lifecycle's globals (which destroy cleared). Captured by _ensureModel. */
|
||||
|
||||
flightState._modelEpoch = 0;
|
||||
|
||||
/** DEFAULT-ON in PROXIMITY (owner directive 2026-08-22). A fresh boot never runs
|
||||
* layer-state restoration, so this initializer — not the codec — is what the app
|
||||
* actually starts with; it must stay in lockstep with the `models3d` default in
|
||||
@@ -66,22 +50,6 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._lastModelCapWarnMs = 0;
|
||||
// throttle the "more planes in view than the cap" console notice
|
||||
// The tracked entity's billboard goes transparent (rather than hidden) once the model takes
|
||||
// over, so it keeps supplying a bounding sphere for follow-camera framing. We only drop its
|
||||
// alpha after the GLB is preloaded so the model is ready to render the instant the billboard
|
||||
// fades — no gap, no double-image. Preloaded once at init; the instance is retained (not
|
||||
// destroyed) purely to keep Cesium's glTF cache warm for fast tracked-model instantiation.
|
||||
|
||||
flightState._planeModelLoaded = false;
|
||||
|
||||
/** @type {Cesium.Model|null} retained preload that keeps the glTF cache warm */
|
||||
|
||||
flightState._preloadModel = null;
|
||||
|
||||
flightState._scratchModelHpr = new Cesium.HeadingPitchRoll(0, 0, 0);
|
||||
|
||||
flightState._scratchModelMtx = new Cesium.Matrix4();
|
||||
|
||||
flightState._scratchModelBS = new Cesium.BoundingSphere(
|
||||
new Cesium.Cartesian3(),
|
||||
1.0,
|
||||
@@ -124,16 +92,12 @@ export function createFlightState({ source, services }) {
|
||||
/** The FollowTarget the camera follows the tracked aircraft with. */
|
||||
flightState._followTarget = null;
|
||||
|
||||
/** @type {Cesium.Model|null} Standalone 3D model for the tracked aircraft — NOT a graphic on
|
||||
/** @type {import('../../data/modelRecord.js').ModelRecord|null} Standalone 3D model for the tracked aircraft — NOT a graphic on
|
||||
* _trackedEntity, which stays a plain, always-ready billboard (a model graphic reports PENDING
|
||||
* until loaded); the camera follows its own target. */
|
||||
|
||||
flightState._trackedModel = null;
|
||||
|
||||
flightState._trackedModelGen = 0;
|
||||
|
||||
flightState._trackedModelLoading = false;
|
||||
|
||||
/** @type {(() => void)|null} Unsubscribes the aircraft-selection click. */
|
||||
|
||||
flightState._clickSubscription = null;
|
||||
@@ -315,30 +279,12 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._trackedZoomLatchIcao = null;
|
||||
|
||||
flightState._trackedModelFailIcao = null;
|
||||
|
||||
flightState._trackedModelFailCount = 0;
|
||||
|
||||
flightState._trackedModelRetryAtMs = 0;
|
||||
|
||||
/** IR hot-target mode — mirror of flights.js: under the luminance-mapped
|
||||
* NVG/FLIR post-styles every model renders flat white (hottest); the dominant
|
||||
* amber/tracked tint restores on style exit. */
|
||||
|
||||
flightState._irBoost = false;
|
||||
|
||||
/** Boosted models render UNLIT — mirror of flights.js (owner cockpit-FLIR
|
||||
* field rounds): material-stage tint still sun-shades, so side-on planes
|
||||
* read near-black under a high sun; UNLIT emits flat white regardless.
|
||||
* customShader on a READY model is a silent no-op (field-verified), so the
|
||||
* boost flips by release-and-reload — creation-time options carry it. */
|
||||
|
||||
flightState._IR_UNLIT_SHADER = new Cesium.CustomShader({
|
||||
lightingModel: Cesium.LightingModel.UNLIT,
|
||||
});
|
||||
|
||||
flightState._irReloadQueue = null;
|
||||
|
||||
/** @type {Cesium.Cartographic} Scratch for _trailFloorPosition (per-frame safe). */
|
||||
|
||||
flightState._scratchTrailCarto = new Cesium.Cartographic();
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { AMBER_TRANSPARENT, TRACKED_ICON_COLOR } from './policy.js';
|
||||
import { createModelRecord } from '../../data/modelRecord.js';
|
||||
import {
|
||||
@@ -23,16 +22,44 @@ export function createTesting({
|
||||
* @param {string} state.icao24
|
||||
* @param {object} state.entity
|
||||
* @param {object} state.meta
|
||||
* @param {{position?: Cesium.Cartesian3, show?: boolean}} [state.icon]
|
||||
* @param {{position?: {x: number, y: number, z: number}, show?: boolean}} [state.icon]
|
||||
* Where the contact's icon is held, and whether it is shown.
|
||||
* @param {{show?: boolean}} [state.iconLayer] Layer visibility.
|
||||
* @param {object} state.viewer
|
||||
* @param {Array<Object>} [state.history=[]]
|
||||
* @param {boolean} [state.tracked=true]
|
||||
* @param {Iterable<[string, object]>} [state.models=[]] - Fleet 3D models keyed
|
||||
* by icao24, for the icon-hidden/model-shown handoff state.
|
||||
* by icao24, for the icon-hidden/model-shown handoff state: each object
|
||||
* becomes the contact's model record (`ready`, `show`, and a placement
|
||||
* `modelMatrix` when given), so the test reads what the layer writes back.
|
||||
* @param {object|null} [state.draw] A draw port the layer's model sets are
|
||||
* made on (a test double); none keeps the records only.
|
||||
*/
|
||||
|
||||
/** Turn a test's model fields into the contact's model record, in place. */
|
||||
function _modelRecordForTest(fields, klass) {
|
||||
const spec = parts.rendering._modelSpec(klass);
|
||||
const base = createModelRecord({
|
||||
specKey: parts.rendering._specKeyFor(klass),
|
||||
bellyM: spec.bellyM,
|
||||
scale: spec.scale,
|
||||
});
|
||||
for (const key of Object.keys(base))
|
||||
if (!(key in fields)) fields[key] = base[key];
|
||||
fields.ready = fields.ready === true;
|
||||
fields.show = fields.show ?? true;
|
||||
if (fields.modelMatrix) {
|
||||
fields.matrix = Float64Array.from(fields.modelMatrix);
|
||||
fields.position = {
|
||||
x: fields.matrix[12],
|
||||
y: fields.matrix[13],
|
||||
z: fields.matrix[14],
|
||||
};
|
||||
fields.placed = true;
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
function _setTrackedMilitaryRefreshStateForTest({
|
||||
icao24,
|
||||
entity,
|
||||
@@ -43,16 +70,17 @@ export function createTesting({
|
||||
history = [],
|
||||
tracked = true,
|
||||
models = [],
|
||||
modelCollection = null,
|
||||
draw = null,
|
||||
}) {
|
||||
flightState._viewer = viewer;
|
||||
flightState._modelCollection = modelCollection;
|
||||
parts.rendering._disposeModelSets();
|
||||
if (draw) parts.rendering._createModelSets(viewer, { draw });
|
||||
flightState._icons = createContactIcons();
|
||||
flightState._icons.show = iconLayer?.show ?? true;
|
||||
_seedIconForTest(icao24, icon, tracked);
|
||||
flightState._models.clear();
|
||||
for (const [key, model] of models)
|
||||
flightState._models.set(key, createModelRecord(model));
|
||||
flightState._models.set(key, _modelRecordForTest(model, meta?.klass));
|
||||
flightState._detectionObjects = new Map();
|
||||
flightState.records.data = new Map([[icao24, meta]]);
|
||||
flightState._positionHistory = new Map([[icao24, history]]);
|
||||
@@ -63,7 +91,6 @@ export function createTesting({
|
||||
flightState._trackedEntity = tracked ? entity : null;
|
||||
flightState._trackedModel = null;
|
||||
parts.tracking._cancelPendingTrackingRestore();
|
||||
flightState._trackedModelLoading = false;
|
||||
// NOTE: deliberately does NOT reset the per-selection latches. They are
|
||||
// production state owned by the tracking lifecycle (_resetTrackedSelectionState),
|
||||
// and clearing them here would mask exactly the deselect→re-track hole this
|
||||
@@ -128,7 +155,7 @@ export function createTesting({
|
||||
}
|
||||
|
||||
/** Run one frame of the production tracked-model driver (normally a
|
||||
* `scene.preUpdate` listener) so tests can pin its bounded load retries. */
|
||||
* `preUpdate` listener). */
|
||||
|
||||
function _updateTrackedModelForTest() {
|
||||
return parts.rendering._updateTrackedModel();
|
||||
@@ -153,11 +180,24 @@ export function createTesting({
|
||||
);
|
||||
}
|
||||
|
||||
/** Exercise the exact asynchronous fleet loader and return its admitted model. */
|
||||
/** Exercise the exact fleet admission and return the admitted model's record. */
|
||||
|
||||
async function _ensureFleetModelForTest(icao24) {
|
||||
await parts.rendering._ensureModel(icao24);
|
||||
return flightState._models.get(icao24)?.model ?? null;
|
||||
function _ensureFleetModelForTest(icao24) {
|
||||
parts.rendering._ensureModel(icao24);
|
||||
return flightState._models.get(icao24) ?? null;
|
||||
}
|
||||
|
||||
/** The tracked model's record, or null. */
|
||||
|
||||
function _trackedModelForTest() {
|
||||
return flightState._trackedModel;
|
||||
}
|
||||
|
||||
/** The fleet and tracked model sets' ids, or null without sets. */
|
||||
|
||||
function _modelSetIdsForTest() {
|
||||
const [fleet, tracked] = parts.rendering._modelSetIds();
|
||||
return fleet ? { fleet, tracked } : null;
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -174,5 +214,7 @@ export function createTesting({
|
||||
_iconForTest,
|
||||
_setIconForTest,
|
||||
_ensureFleetModelForTest,
|
||||
_trackedModelForTest,
|
||||
_modelSetIdsForTest,
|
||||
};
|
||||
}
|
||||
@@ -22,8 +22,6 @@ import {
|
||||
} from '../../data/trackingClickGesture.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import {
|
||||
TRACKED_MODEL_MAX_LOAD_FAILS,
|
||||
TRACKED_MODEL_RETRY_BACKOFF_MS,
|
||||
TRAIL_MAX_POINTS,
|
||||
RENDER_DELAY_SEC,
|
||||
TRAIL_COLOR,
|
||||
@@ -36,8 +34,8 @@ import { roundHeadingDegrees } from '../../data/headingDegrees.js';
|
||||
import { entityRecord } from '../../data/entityRecords.js';
|
||||
|
||||
/**
|
||||
* The icao a pick carries: a draw-set item's id (the icon sets' rows), a
|
||||
* string pick id, or a model primitive's id.
|
||||
* The icao a pick carries: a draw-set item's id (the icon and model sets'
|
||||
* rows), a string pick id, or a primitive's id.
|
||||
*/
|
||||
function aircraftPickId(picked) {
|
||||
const id = picked?.id;
|
||||
@@ -210,7 +208,7 @@ export function createTracking({
|
||||
// The collection stays visible in cockpit. Near AIR contacts retain their
|
||||
// aircraft silhouette until a ready model takes over; far contacts are pips.
|
||||
// Never bulk-destroy here: that stalls the renderer exactly as cockpit begins.
|
||||
if (flightState._modelCollection) flightState._modelCollection.show = true;
|
||||
parts.rendering._setModelsShown(true);
|
||||
flightState._trail?.setVisible(!next);
|
||||
const icons = flightState._icons;
|
||||
for (const icao24 of icons?.ids() ?? [])
|
||||
@@ -314,8 +312,7 @@ export function createTracking({
|
||||
.toLowerCase();
|
||||
if (!id) return false;
|
||||
if (isTr3b(id)) {
|
||||
if (flightState._models.has(id) || flightState._modelPending.has(id))
|
||||
parts.rendering._releaseModel(id);
|
||||
if (flightState._models.has(id)) parts.rendering._releaseModel(id);
|
||||
if (flightState._icons?.has(id) && id !== flightState._trackedIcao)
|
||||
flightState._icons.setShown(id, true);
|
||||
if (id === flightState._trackedIcao) {
|
||||
@@ -341,8 +338,8 @@ export function createTracking({
|
||||
}
|
||||
}
|
||||
|
||||
/** Clear every per-SELECTION tracked-model latch: the zoom hysteresis band and
|
||||
* the load-failure bound. Called from each path that changes which contact is
|
||||
/** Clear the per-SELECTION tracked-model latch: the zoom hysteresis band.
|
||||
* Called from each path that changes which contact is
|
||||
* selected — deselect, re-track, cross-layer handoff, init, destroy.
|
||||
*
|
||||
* This must live in the production lifecycle, not only in the predicate's
|
||||
@@ -350,44 +347,11 @@ export function createTracking({
|
||||
* icao (Contacts re-entry, a cross-layer round trip back to this layer) never
|
||||
* makes `_trackedIcao` *observably* change, so the guard never fires. Without
|
||||
* the reset, a contact dropped inside the hysteresis band comes back as a
|
||||
* MODEL above the ENTER ceiling, and a contact whose GLB had already failed
|
||||
* out would never get its retries back. Mirror of flights.js. */
|
||||
* MODEL above the ENTER ceiling. Mirror of flights.js. */
|
||||
|
||||
function _resetTrackedSelectionState() {
|
||||
flightState._trackedZoomLatched = false;
|
||||
flightState._trackedZoomLatchIcao = null;
|
||||
flightState._trackedModelFailIcao = null;
|
||||
flightState._trackedModelFailCount = 0;
|
||||
flightState._trackedModelRetryAtMs = 0;
|
||||
}
|
||||
|
||||
/** Whether the driver may start another tracked-model load this frame. */
|
||||
|
||||
function _trackedModelLoadAllowed(nowMs = Date.now()) {
|
||||
if (flightState._trackedModelFailIcao !== flightState._trackedIcao)
|
||||
return true; // untried selection
|
||||
if (flightState._trackedModelFailCount >= TRACKED_MODEL_MAX_LOAD_FAILS)
|
||||
return false;
|
||||
return nowMs >= flightState._trackedModelRetryAtMs;
|
||||
}
|
||||
|
||||
/** Record a rejected tracked-model load and arm the backoff / give-up latch. */
|
||||
|
||||
function _noteTrackedModelLoadFailure(url, err) {
|
||||
if (flightState._trackedModelFailIcao !== flightState._trackedIcao) {
|
||||
flightState._trackedModelFailIcao = flightState._trackedIcao;
|
||||
flightState._trackedModelFailCount = 0;
|
||||
}
|
||||
flightState._trackedModelFailCount += 1;
|
||||
flightState._trackedModelRetryAtMs =
|
||||
Date.now() + TRACKED_MODEL_RETRY_BACKOFF_MS;
|
||||
if (flightState._trackedModelFailCount >= TRACKED_MODEL_MAX_LOAD_FAILS) {
|
||||
console.warn(
|
||||
`[Data:Military] tracked 3D model gave up after ${flightState._trackedModelFailCount} failed loads of ${url} — ` +
|
||||
'this contact stays 2D until another is selected',
|
||||
err,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -797,7 +761,7 @@ export function createTracking({
|
||||
flightState._trackedEntity = null;
|
||||
}
|
||||
parts.rendering._releaseTrackedModel();
|
||||
_resetTrackedSelectionState(); // the zoom band + load-failure budget belong to the selection we just dropped
|
||||
_resetTrackedSelectionState(); // the zoom band belongs to the selection we just dropped
|
||||
flightState._trackedIcao = null;
|
||||
// Hand the contact back to its icon only now, once it no longer reads as
|
||||
// tracked (the settle plans it as a fleet contact).
|
||||
@@ -860,7 +824,7 @@ export function createTracking({
|
||||
const iconCourse = icons.course(icao24, t);
|
||||
flightState._displayCourse.set(icao24, iconCourse);
|
||||
flightState._trackedIcao = icao24;
|
||||
_resetTrackedSelectionState(); // fresh selection: enter at the ENTER ceiling, full load-retry budget
|
||||
_resetTrackedSelectionState(); // fresh selection: enter at the ENTER ceiling
|
||||
flightState._cachedDRFrame = -1;
|
||||
flightState._lastTrackedRotation =
|
||||
screenProjectedRotation(
|
||||
@@ -899,7 +863,7 @@ export function createTracking({
|
||||
// resolves into an aircraft.
|
||||
//
|
||||
// The billboard stays SHOWN at all times and is hidden by going TRANSPARENT (alpha 0), not by
|
||||
// show=false: it drops its alpha only once the model GLB is preloaded (_planeModelLoaded), so
|
||||
// show=false: it drops its alpha only once the tracked model is drawing, so
|
||||
// there's neither a billboard+model double-image nor a gap. The camera follows its own target
|
||||
// through the camera port, so nothing here frames the camera.
|
||||
// The tracked entity is a PURE BILLBOARD — no label or model graphic. The tracked plane's 3D
|
||||
@@ -1094,17 +1058,11 @@ export function createTracking({
|
||||
// any pick carrying its icao) — same no-op as the 2D tracked-entity click
|
||||
// above. H1: the model used to have no pick id, so this fell through to
|
||||
// "empty space" and deselected the very plane being tracked.
|
||||
if (flightState._trackedIcao) {
|
||||
const rawPick = aircraftPickId(picked);
|
||||
if (
|
||||
(flightState._trackedModel &&
|
||||
picked.primitive === flightState._trackedModel.model) ||
|
||||
rawPick === flightState._trackedIcao
|
||||
)
|
||||
return;
|
||||
}
|
||||
|
||||
// Its models are draw-set items keyed by icao, like its icons.
|
||||
const pickedIcao = aircraftPickId(picked);
|
||||
if (flightState._trackedIcao && pickedIcao === flightState._trackedIcao)
|
||||
return;
|
||||
|
||||
if (pickedIcao && flightState._icons?.has(pickedIcao)) {
|
||||
_cancelPendingTrackingRestore();
|
||||
_trackFlight(pickedIcao, { origin: 'user' });
|
||||
@@ -1147,8 +1105,6 @@ export function createTracking({
|
||||
_refreshTr3bContact,
|
||||
_refreshTr3bForStyle,
|
||||
_resetTrackedSelectionState,
|
||||
_trackedModelLoadAllowed,
|
||||
_noteTrackedModelLoadFailure,
|
||||
_trackedModelRegimeActive,
|
||||
_syncTracked2dRotation,
|
||||
_trailFloorPosition,
|
||||
|
||||
@@ -212,6 +212,9 @@ export function createModelSets({
|
||||
show: false,
|
||||
// All textures before ready, so a settled capture is the whole model.
|
||||
incrementallyLoadTextures: false,
|
||||
// Off the frame-spread job queue that photoreal tiles contend for, so
|
||||
// a model's readiness stays bounded while tiles stream.
|
||||
asynchronous: false,
|
||||
id: entry.pickId,
|
||||
}).then(
|
||||
(model) => {
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
"src/cockpitCloudEffects.js",
|
||||
"src/cyberSonarGpu.js",
|
||||
"src/cyberSonarScene.js",
|
||||
"src/data/aircraftModelLayer.js",
|
||||
"src/data/aircraftMotionRegime.js",
|
||||
"src/data/cctvGizmo.js",
|
||||
"src/data/detection.js",
|
||||
@@ -18,7 +17,6 @@
|
||||
"src/data/iconSet.js",
|
||||
"src/data/iconSetPrimitive.js",
|
||||
"src/data/localGeojsonCore.js",
|
||||
"src/data/modelRecord.js",
|
||||
"src/data/motionModel.js",
|
||||
"src/input/dispatcher.js",
|
||||
"src/input/sensorPick.js",
|
||||
@@ -27,25 +25,20 @@
|
||||
"src/layers/firms/rendering.js",
|
||||
"src/layers/flights/enrichment.js",
|
||||
"src/layers/flights/evidence.js",
|
||||
"src/layers/flights/lifecycle.js",
|
||||
"src/layers/flights/motion.js",
|
||||
"src/layers/flights/policy.js",
|
||||
"src/layers/flights/queries.js",
|
||||
"src/layers/flights/rendering.js",
|
||||
"src/layers/flights/state.js",
|
||||
"src/layers/flights/testing.js",
|
||||
"src/layers/flights/tracking.js",
|
||||
"src/layers/ghostMaps/index.js",
|
||||
"src/layers/installations/rendering.js",
|
||||
"src/layers/launches/launchPad.js",
|
||||
"src/layers/launches/orbitRendering.js",
|
||||
"src/layers/launches/rendering.js",
|
||||
"src/layers/military/lifecycle.js",
|
||||
"src/layers/military/motion.js",
|
||||
"src/layers/military/policy.js",
|
||||
"src/layers/military/queries.js",
|
||||
"src/layers/military/state.js",
|
||||
"src/layers/military/testing.js",
|
||||
"src/layers/military/tracking.js",
|
||||
"src/layers/radio/rendering.js",
|
||||
"src/layers/recentImagery/rendering.js",
|
||||
|
||||
Reference in new issue
Block a user