diff --git a/src/data/aircraftModelLayer.js b/src/data/aircraftModelLayer.js index 82abcf057..b010d1e3a 100644 --- a/src/data/aircraftModelLayer.js +++ b/src/data/aircraftModelLayer.js @@ -1,6 +1,8 @@ -import * as Cesium from 'cesium'; import { selectModelEligible } from './modelEligibility.js'; -import { aircraftTreatmentAlpha } from './aircraftRecession.js'; +import { + aircraftTreatmentAlpha, + DEFAULT_AIRCRAFT_RECESSION_PARAMS, +} from './aircraftRecession.js'; import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js'; import { createModelRecord, @@ -8,12 +10,66 @@ import { placeModel, showModel, } from './modelRecord.js'; +import { modelDrawnScale } from './modelVisualAnchor.js'; +import { findCamera, findDraw, rendererOf } from '../render/rendererOf.js'; +import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; +import { + distance, + distanceSquared, + dot, + RADIANS_PER_DEGREE, + sub, +} from '../geo/vector.js'; + +/** A white tint: what an IR-boosted model draws with. */ +const WHITE = Object.freeze([1, 1, 1, 1]); + +/** Id of the hidden item that keeps the tracked asset loaded. */ +const PRELOAD_ID = '~preload'; + +/** Where the preload item waits, unshown. */ +const NOWHERE = Object.freeze({ x: 0, y: 0, z: 0 }); + +/** How often (ms) a model that has not loaded is written again, so a + * renderer that retries failed loads on write (as the Cesium one does) + * gets the chance even for a parked contact whose item never changes. */ +const UNREADY_REWRITE_MS = 5000; + +/** A colour as the draw contract's `[r, g, b, a]`, from `{red, green, blue, alpha}`. */ +function rgba(color) { + if (!color) return null; + if (typeof color === 'string' || Array.isArray(color)) return color; + return [color.red, color.green, color.blue, color.alpha ?? 1]; +} + +/** + * Whether `point` is inside the eye's view cone (`pose`), a metre's slack: + * the camera's culling volume against a one-metre sphere. + */ +function inView(pose, point) { + const v = sub(point, pose.position); + const depth = dot(v, pose.direction); + if (depth < -1) return false; + const tanY = Math.tan(pose.fovy / 2); + const tanX = tanY * pose.aspectRatio; + return ( + Math.abs(dot(v, pose.right)) <= Math.max(0, depth) * tanX + 1 && + Math.abs(dot(v, pose.up)) <= Math.max(0, depth) * tanY + 1 + ); +} /** * An aircraft layer's 3D models: the fleet regime and its gap-proof handoff * from the icon set (`createAircraftIcons`), the standalone tracked model, and * the ~12 Hz fleet tick that drives both. Shared by the flights and military * layers, which differ only in the options below. + * + * The models are two `models` sets of the renderer's draw port, made for each + * layer lifetime (`_createModelSets`): the fleet's, one item per modelled + * contact, and the tracked contact's (with a hidden item that keeps the + * tracked asset loaded). Each item is re-posed and restyled in place; the + * layer keeps its own record of each (`modelRecord.js`), and a set's `ready` + * says when a model has loaded. Picks name the set and the contact's id. * @param {object} options * @param {object} options.state The layer state. * @param {object} options.services @@ -21,17 +77,20 @@ import { * `tracking` are read at call time. * @param {(url: string) => string} options.resolveAsset * @param {string} options.logLabel Console prefix, e.g. `Data:Flights`. + * @param {string} options.setPrefix The draw sets' id prefix, e.g. `flights`. * @param {object} options.policy The layer's model budgets, radii, pixel - * bounds, heading offset, IR reload batch and fleet tick interval. + * bounds, heading offset and fleet tick interval. * @param {(klass: string) => object} options.modelSpec The class's GLB, scale, * geometry and tint blend; `headingOffsetDeg` overrides the policy's. - * @param {(icao24: string) => Cesium.Color} options.modelColor Model tint, - * including the tracked contact's. + * @param {(icao24: string) => object} options.modelColor Model tint + * (`{red, green, blue, alpha}`), including the tracked contact's. * @param {(icao24: string) => void} [options.onModelEligible] Runs when a * contact is about to render in 3D. - * @param {(renderTime: Cesium.JulianDate, t: number, nowMs: number, - * camera: Cesium.Camera) => void} [options.afterReplan] The layer's own pass - * in the fleet tick, after expired rows are re-planned. + * @param {(renderTime: object, t: number, nowMs: number, eye: object|null) + * => void} [options.afterReplan] The layer's own pass in the fleet tick, + * after expired rows are re-planned: the display instant (as the layer's + * motion keeps it, and epoch ms), the focus clock and the eye (ECEF), or + * null without a camera. */ export function createAircraftModels({ state, @@ -39,6 +98,7 @@ export function createAircraftModels({ parts, resolveAsset, logLabel, + setPrefix, policy, modelSpec: _modelSpec, modelColor: _modelColor, @@ -48,12 +108,107 @@ export function createAircraftModels({ const { isTr3b } = services.aircraftPresentation; const { trackedModelScaleForPixelCap } = services.camera; const { focusNowMs, getFocusTarget } = services.focus; - const { applyAircraftModelTreatment } = services.recession; + const writeEpsilon = DEFAULT_AIRCRAFT_RECESSION_PARAMS.writeEpsilon; + let instances = 0; + /** The fleet items this tick wrote, sent together when it ends. */ + let pendingItems = []; + /** The ground sample's exclusions, kept while the sets they name live. */ + let exclusions = null; + + /** The camera's pose, or null without a camera to ask. */ + function _pose() { + try { + return findCamera(state._viewer)?.pose() ?? null; + } catch { + return null; + } + } + + /** The renderer canvas's CSS size, and drawing-buffer pixels per CSS + * pixel; zero sizes without a renderer. */ + function _viewport() { + const renderer = rendererOf(state._viewer); + const canvas = renderer?.canvas; + return { + width: Number(canvas?.clientWidth) || 0, + height: Number(canvas?.clientHeight) || 0, + pixelRatio: renderer?.quality?.get?.()?.pixelRatio ?? 1, + }; + } /** The model heading offset a class's GLB needs. */ const _headingOffsetDeg = (klass) => _modelSpec(klass).headingOffsetDeg ?? policy.MODEL_HEADING_OFFSET_DEG; + /** A course (degrees) as the class's model heading (radians). */ + const _modelHeading = (course, klass) => + ((course || 0) + _headingOffsetDeg(klass)) * RADIANS_PER_DEGREE; + + /** + * Make this lifetime's model sets on the viewer's draw port (none on a + * renderer that draws no models: the layer stays icons). `draw` stands in + * for the viewer's (tests). + * @param {object} viewer + * @param {{preloadUrl?: string, draw?: object}} [options] + */ + function _createModelSets(viewer, { preloadUrl, draw } = {}) { + _disposeModelSets(); + const port = draw ?? findDraw(viewer); + if (typeof port?.models !== 'function') return; + const n = ++instances; + const fleet = port.models({ id: `${setPrefix}-models:${n}` }); + const tracked = port.models({ id: `${setPrefix}-tracked-model:${n}` }); + const offs = [ + fleet.on('ready', (id) => { + const record = state._models.get(id); + if (record) record.ready = true; + }), + tracked.on('ready', (id) => { + if (id === state._trackedIcao && state._trackedModel) + state._trackedModel.ready = true; + }), + ]; + state._modelSets = { fleet, tracked, offs }; + // A hidden item keeps the tracked asset loaded, so the tracked model + // draws as soon as it is wanted. + if (preloadUrl) + tracked.upsert([ + { + id: PRELOAD_ID, + pos: NOWHERE, + url: preloadUrl, + orientation: { heading: 0, pitch: 0, roll: 0 }, + environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled, + show: false, + pickable: false, + }, + ]); + } + + /** Let this lifetime's model sets go. */ + function _disposeModelSets() { + const sets = state._modelSets; + if (!sets) return; + state._modelSets = null; + for (const off of sets.offs) off(); + sets.fleet.dispose(); + sets.tracked.dispose(); + } + + /** Show or hide every model (the layer shown or hidden). */ + function _setModelsShown(show) { + const sets = state._modelSets; + if (!sets) return; + sets.fleet.show = show; + sets.tracked.show = show; + } + + /** The model sets' ids (picks, height samples); empty without sets. */ + function _modelSetIds() { + const sets = state._modelSets; + return sets ? [sets.fleet.id, sets.tracked.id] : []; + } + /** The FLEET's 3D-model regime: models3d enabled AND the camera zoomed in past the altitude * ceiling. Since 2026-08-22 the toggle DEFAULTS ON in `proximity`, which is itself the * budget: models only appear below MODEL_ALT_CEIL_M and only for the nearest MODEL_MAX in @@ -63,9 +218,9 @@ export function createAircraftModels({ * and it takes its own default-on, hysteretic zoom regime * (`_trackedModelRegimeActive`). */ - function _modelRegimeActive() { + function _modelRegimeActive(pose = _pose()) { if (!state._models3dEnabled) return false; - const h = state._viewer?.camera?.positionCartographic?.height ?? Infinity; + const h = pose?.height ?? Infinity; return h < policy.MODEL_ALT_CEIL_M; } @@ -100,45 +255,23 @@ export function createAircraftModels({ : policy.MODEL_PROX_KEEP_M; } - /** World model matrix from a position + course heading (pitch/roll 0; ENU frame). Writes into - * `result` (a shared scratch by default) and returns it. Push it with `placeModel`, which copies - * it into the model's record and its own matrix, so models never share one mutable matrix - * object. `Model.modelMatrix` is a plain field (not a cloning setter); Cesium - * clones it per frame in updateModelMatrix(). Sharing a single scratch made every model render at - * the LAST-written transform — all stacked on one plane — and, once the tracked model wrote the - * scratch every frame, the stack point oscillated frame-to-frame: the "flickering like mad" bug. */ - - function _modelMatrix( - pos, - headingDeg, - result = state._scratchModelMtx, - offsetDeg = policy.MODEL_HEADING_OFFSET_DEG, - ) { - state._scratchModelHpr.heading = Cesium.Math.toRadians( - (headingDeg || 0) + offsetDeg, - ); - state._scratchModelHpr.pitch = 0; - state._scratchModelHpr.roll = 0; - return Cesium.Transforms.headingPitchRollToFixedFrame( - pos, - state._scratchModelHpr, - Cesium.Ellipsoid.WGS84, - undefined, - result, - ); - } - - /** Everything scene.sampleHeight must NOT hit when snapping a grounded model: the - * vertical pick ray at a plane's own lat/lon otherwise lands on its (or a parked - * neighbor's) billboard/model instead of the tile skin. Cesium's ray-pick exclusion - * matches picked-object IDs, and every icon AND model in this layer carries its - * icao as `id`, so the icao strings cover both; the tracked entity is excluded as the - * object itself. Built lazily — only when a sample actually fires (one-shot). */ + /** What a grounded model's ground sample sees through: the vertical sample + * at a plane's own lat/lon otherwise lands on its (or a parked neighbour's) + * icon or model instead of the tile skin. The query port sees through + * every draw set not drawn as ground; these are named for clarity. */ function _groundSampleExclusions() { - const out = parts.icons._iconIds(); - if (state._trackedEntity) out.push(state._trackedEntity); - return out; + const modelSets = state._modelSets; + const iconSetId = state._icons?.setId ?? null; + if ( + exclusions?.modelSets !== modelSets || + exclusions.iconSetId !== iconSetId + ) { + const sets = [..._modelSetIds()]; + if (iconSetId) sets.push(iconSetId); + exclusions = { modelSets, iconSetId, value: { sets } }; + } + return exclusions.value; } /** Position a 3D MODEL renders at. Airborne planes use their dead-reckoned position @@ -146,7 +279,7 @@ export function createAircraftModels({ * the photoreal tile skin in ellipsoid heights (buried ~100+ m at inland airports, * hovering ~30 m at sea-level ones), and unlike the ground billboards a depth-tested * model can't hide behind disableDepthTestDistance. So a modeled grounded plane rides - * a ONE-SHOT cached scene.sampleHeight of the skin at its lat/lon (groundSnap.js, + * a ONE-SHOT cached height sample of the skin at its lat/lon (groundSnap.js, * CCTV-B9b discipline: never per-frame; taxiing >50 m retires the cached value to a * bounded last-known and resamples), plus * the belly offset so it sits on its gear rather than sinking to the model-origin @@ -157,72 +290,121 @@ export function createAircraftModels({ * groundSnap's drift bound instead — a taxiing aircraft does not pop back to 2D * because a resample is mid-backoff. */ - function _modelDisplayPosition(icao24, pos, result) { + function _modelDisplayPosition(icao24, pos) { const meta = state.records.data.get(icao24); if (!meta || !meta.onGround) return pos; const h = state._groundSnap.heightFor( state._viewer, icao24, pos, - _groundSampleExclusions, + _groundSampleExclusions(), ); if (h == null) return null; - const carto = Cesium.Cartographic.fromCartesian( - pos, - Cesium.Ellipsoid.WGS84, - state._scratchGroundCarto, - ); - carto.height = h + _modelSpec(meta.klass).bellyM; - return Cesium.Cartesian3.fromRadians( - carto.longitude, - carto.latitude, - carto.height, - Cesium.Ellipsoid.WGS84, - result, - ); + const at = toLonLatH(pos); + if (!at) return null; + return fromDegrees(at.lon, at.lat, h + _modelSpec(meta.klass).bellyM); + } + + /** How a contact's model draws now: the IR boost's flat white, or its tint. */ + function _shadingOf() { + return state._irBoost ? 'unlit' : 'pbr'; + } + + /** The tint a record sends: `base` at `alpha`, kept while within the + * write epsilon; a missing colour or alpha leaves it as it is. */ + function _treat(record, { base, alpha }) { + if (!base || !Number.isFinite(alpha)) return; + const tint = record.tint; + if ( + tint && + tint[0] === base[0] && + tint[1] === base[1] && + tint[2] === base[2] && + Math.abs(tint[3] - alpha) <= writeEpsilon + ) + return; + record.tint = [base[0], base[1], base[2], alpha]; + } + + /** The record's item, as its set draws it. */ + function _itemOf(id, record, spec) { + const boost = state._irBoost === true; + return { + id, + pos: { x: record.position.x, y: record.position.y, z: record.position.z }, + url: record.url, + orientation: { heading: record.heading, pitch: 0, roll: 0 }, + scale: record.scale, + minPixelSize: record.minPixelSize, + shading: _shadingOf(), + tint: record.tint ?? WHITE, + // The code-side tint dominates every approved model; the IR boost + // removes the remaining diffuse hint with flat unlit white. + colorBlend: { mode: 'mix', amount: boost ? 1 : spec.blendAmount }, + environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled, + show: record.show, + }; + } + + /** Send a record's item when anything it draws changed. */ + function _send(set, id, record, spec, out) { + if (!set) return; + const p = record.position; + const t = record.tint ?? WHITE; + // A model still loading is rewritten now and then, for the renderer's retry. + const loading = record.ready + ? '' + : Math.floor(Date.now() / UNREADY_REWRITE_MS); + const key = `${record.url}|${p.x},${p.y},${p.z}|${record.heading}|${record.scale}|${record.minPixelSize}|${t[0]},${t[1]},${t[2]},${t[3]}|${state._irBoost === true}|${spec.blendAmount}|${record.show}|${loading}`; + if (key === record.sent) return; + record.sent = key; + const item = _itemOf(id, record, spec); + if (out) out.push(item); + else set.upsert([item]); } /** Atomically hand one fleet contact from its icon to a safely placed, * ready 3D model. Missing/loading models and unresolved terrain always leave * the icon owning the visual, so no render frame can hide both. * `beforeShow` runs only on the committing path — the per-tick model treatment - * belongs to a model that is about to draw, not to one still waiting. */ + * belongs to a model that is about to draw, not to one still waiting. + * `out` collects the items to write (the tick writes them together). */ - function _driveFleetModelHandoff(icao24, record, pos, course, beforeShow) { + function _driveFleetModelHandoff( + icao24, + record, + pos, + course, + beforeShow, + out, + ) { const icons = state._icons; if (!record) { icons.setShown(icao24, true); return false; } - const displayPos = _modelDisplayPosition( - icao24, - pos, - state._scratchGroundPos, - ); + const klass = state.records.data.get(icao24)?.klass; + const spec = _modelSpec(klass); + const set = state._modelSets?.fleet ?? null; + const displayPos = _modelDisplayPosition(icao24, pos); if (!displayPos) { showModel(record, false); // no ground evidence → nothing safe to place a depth-tested model at + _send(set, icao24, record, spec, out); icons.setShown(icao24, true); return false; } - // The matrix is written BEFORE the readiness test on purpose: a model can flip - // `ready` during scene update after this tick, and a first rendered frame on a - // stale load-start matrix is the one-frame jump this ordering prevents. - placeModel( - record, - _modelMatrix( - displayPos, - course, - undefined, - _headingOffsetDeg(state.records.data.get(icao24)?.klass), - ), - ); - if (!record.model.ready) { + // Placed BEFORE the readiness test on purpose: a model can turn ready + // between ticks, and its first drawn frame must be at this placement. + placeModel(record, displayPos, _modelHeading(course, klass)); + if (!record.ready) { showModel(record, false); // not loaded yet → keep the 2D icon, no half-model flash + _send(set, icao24, record, spec, out); icons.setShown(icao24, true); return false; } beforeShow?.(); - if (!record.show) showModel(record, true); + showModel(record, true); + _send(set, icao24, record, spec, out); icons.setShown(icao24, false); // hand off ONLY once the model renders return true; } @@ -232,19 +414,16 @@ export function createAircraftModels({ * this contact, and therefore whether the display floor should stand aside. * * Model EXISTENCE is not ownership. A fleet model that is still loading, or has - * no resolved ground to stand on, stays hidden while `bb.show` stays true (the - * gap-proof handoff: "hand off ONLY once the model renders"), and a tracked model + * no resolved ground to stand on, stays hidden while the icon stays shown + * (the gap-proof handoff: "hand off ONLY once the model renders"), and a tracked model * is retained but hidden whenever the model regime is off — 3D disabled, camera * zoomed past the ceiling, or cockpit mode. Gating on `has()`/existence therefore * suppressed the clamp in exactly the states where the BILLBOARD is the visual, * putting the burial straight back. * - * Cesium's own default `show === true` is the reason admission clears it - * explicitly: a fleet model registered in `_models` the instant its glTF resolves - * would otherwise claim ownership — at the identity matrix — for the frames - * between admission and the next fleet tick, while the BILLBOARD was still the - * visual. Ownership means actually rendering, and every site that sets `show` - * true does so only after committing a matrix. + * Admission records a model hidden, so a fleet model admitted but not yet + * placed cannot claim ownership, and every site that shows one does so only + * after placing it. * * The two halves: * - Fleet: the rendering test alone. Safe for the ground snap either way, @@ -280,12 +459,40 @@ export function createAircraftModels({ // A model is the visual only once it actually draws, loaded AND shown // (`modelIsRendering`). `show` is sufficient evidence of a safe placement // because only ONE site ever sets it true for a fleet model - // (`_driveFleetModelHandoff`, after the matrix is committed) and one for the + // (`_driveFleetModelHandoff`, after it is placed) and one for the // tracked model (`_updateTrackedModel`, likewise); everything else — // admission, an unresolved ground, a not-yet-ready glTF, the limb cull, a // regime exit — only ever clears it. - /** Spec identity for a LOADED model: URL and scale together (same-URL classes + /** + * The scale a record's model is drawn at, by the draw contract's pixel + * rule (its `minPixelSize` at its distance from the eye). + * @param {import('./modelRecord.js').ModelRecord} record + * @param {object} spec The class spec (`nativeRadiusM`). + * @param {{pose: object|null, width: number, height: number, + * pixelRatio: number}} [view] + * One frame's camera and viewport, for a pass over many. + * @returns {number} + */ + function _modelDrawnScale(record, spec, view = _drawnScaleView()) { + return modelDrawnScale({ + scale: record.scale, + minPixelSize: record.minPixelSize, + radiusM: spec.nativeRadiusM, + center: record.position, + pose: view.pose, + viewportHeightPx: view.height, + viewportWidthPx: view.width, + pixelRatio: view.pixelRatio, + }); + } + + /** One frame's camera and viewport for `_modelDrawnScale`. */ + function _drawnScaleView() { + return { pose: _pose(), ..._viewport() }; + } + + /** Spec identity for an admitted model: URL and scale together (same-URL classes * differ by scale — airliner vs quadjet both ship airplane.glb). */ const _specKeyFor = (klass) => { @@ -294,22 +501,16 @@ export function createAircraftModels({ }; /** Class-change model sync (enrichment AND poll-path klass updates): when the - * aircraft's live model or in-flight load no longer matches its class's spec, - * drop it so the eligibility pass reloads the right asset at the right scale. - * Gap-proof: the fleet billboard is re-shown BEFORE the release so the - * contact never goes invisible for the tick gap; _releaseModel's generation - * bump also invalidates any pending load. The tracked standalone model gets - * the same rule (its billboard entity is always the fallback visual). */ + * aircraft's model no longer matches its class's spec, drop it so the + * eligibility pass admits the right asset at the right scale. Gap-proof: the + * fleet icon is re-shown with the release, so the contact never goes + * invisible for the tick gap. The tracked standalone model gets the same + * rule (its billboard entity is always the fallback visual). */ function _syncModelToClass(icao24) { const key = _specKeyFor(state.records.data.get(icao24)?.klass); const current = state._models.get(icao24); - if ( - (current && current.specKey !== key) || - (!current && state._modelPending.has(icao24)) - ) { - _releaseModel(icao24); - } + if (current && current.specKey !== key) _releaseModel(icao24); if ( icao24 === state._trackedIcao && state._trackedModel && @@ -319,179 +520,60 @@ export function createAircraftModels({ } } + /** The IR boost flipped: every model restyles in place on its next write + * (shading and tint can change live). */ function _reloadModelsForIrBoost() { - state._irReloadQueue = [...state._models.keys()]; - for (const icao of state._modelPending) { - if (!state._models.has(icao)) - state._modelGen.set(icao, (state._modelGen.get(icao) || 0) + 1); - } - _releaseTrackedModel(); + for (const record of state._models.values()) record.tint = null; + if (state._trackedModel) state._trackedModel.tint = null; + state._lastFleetTickMs = 0; } - function _drainIrReloadQueue() { - if (!state._irReloadQueue) return; - const batch = state._irReloadQueue.splice(0, policy.IR_RELOAD_BATCH); - for (const icao of batch) { - const record = state._models.get(icao); - if (!record || record.irBoost === state._irBoost) continue; // already right state - _releaseModel(icao); - } - if (state._irReloadQueue.length === 0) state._irReloadQueue = null; - } + /** Admit a fleet model for an aircraft; the icon shows until it is ready. */ - /** Lazily create the glTF model for an aircraft (fire-and-forget; billboard shows until ready). */ - - async function _ensureModel(icao24) { + function _ensureModel(icao24) { // Never model the TRACKED aircraft — it owns a separate entity billboard, and the fleet // tick skips it, so a model here would be orphaned + double-rendered. if (icao24 === state._trackedIcao) return; onModelEligible(icao24); - if (state._models.has(icao24) || state._modelPending.has(icao24)) return; - // Count PENDING loads in the cap so a zoomed-in tick can't fire 100s of concurrent loads - // (the cap is rechecked post-await too, before the add). Mode-aware so 'all' can reach MAX_ALL. - if (state._models.size + state._modelPending.size >= _modelCap()) return; - const epoch = state._modelEpoch; // lifecycle token: if destroy() bumps it, this load is dead - const gen = state._modelGen.get(icao24) || 0; // capture; if it changes during the load, we're stale - state._modelPending.add(icao24); - let model = null; - // Spec identity captured at load START — if enrichment reclassifies the - // aircraft mid-load, the post-await admission below rejects the stale asset. - // Boost state likewise: the creation options bake it in, so a mid-load - // toggle must reject too (the reload queue only covers ADMITTED models). - const specKey = _specKeyFor(state.records.data.get(icao24)?.klass); - const loadIrBoost = state._irBoost; - try { - const spec = _modelSpec(state.records.data.get(icao24)?.klass); - model = await Cesium.Model.fromGltfAsync({ - url: resolveAsset(spec.url), - asynchronous: false, - environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, - minimumPixelSize: policy.MODEL_MIN_PX, - scale: spec.scale, - color: state._irBoost ? Cesium.Color.WHITE : _modelColor(icao24), - colorBlendMode: Cesium.ColorBlendMode.MIX, - // Launch presentation keeps the code-side tint dominant for every approved - // model; IR boost removes the remaining diffuse hint with flat UNLIT white. - colorBlendAmount: state._irBoost ? 1.0 : spec.blendAmount, - customShader: state._irBoost ? state._IR_UNLIT_SHADER : undefined, - id: icao24, // so scene.pick returns the icao for click-to-track - }); - } catch { - // asset/decode fail — stay an icon. Only touch this lifecycle's state if still current - // (a destroy/re-init may have swapped the globals while this load was in flight). - if (epoch === state._modelEpoch) { - state._modelPending.delete(icao24); - _cleanupModelGen(icao24); - } - return; - } - // A load from a PREVIOUS lifecycle (destroy→init happened mid-load) must NOT mutate the new - // epoch's _modelPending/_modelGen or add to the new collection — just drop its model. - if (epoch !== state._modelEpoch) { - try { - model.destroy(); - } catch { - /* gone */ - } - return; - } - state._modelPending.delete(icao24); - // Post-await admission: reject (and DESTROY the loaded model) if anything changed during the - // load — a release bumped the generation (track/untrack/remove), the layer toggled off / was - // torn down, the aircraft is gone or now tracked, a model already exists, or the cap filled. - // Recheck the shared Display 3D toggle and altitude ceiling after the async - // load. Cockpit uses the same OFF / Proximity / All contract as map Display. - const stale = - (state._modelGen.get(icao24) || 0) !== gen || - !_modelRegimeActive() || - !state._modelCollection || - state._modelCollection.isDestroyed() || - !state.records.data.has(icao24) || - icao24 === state._trackedIcao || - state._models.has(icao24) || - state._models.size >= _modelCap() || - // Class reclassified mid-load → this GLB/scale is for the OLD class. - _specKeyFor(state.records.data.get(icao24)?.klass) !== specKey || - // IR boost flipped mid-load → this model baked the wrong shader/tint. - state._irBoost !== loadIrBoost; - if (stale) { - try { - model.destroy(); - } catch { - /* already gone */ - } - _cleanupModelGen(icao24); // bound the map - return; - } - // Keep the pick identity explicit on the resolved primitive. This also - // protects injected/custom loaders that do not copy the creation option. - model.id = icao24; - const record = createModelRecord(model, { - specKey, // class-change sync compares against this - irBoost: loadIrBoost, // boost-flip reload queue compares against this + if (state._models.has(icao24)) return; + // Without model sets (the renderer draws none) the icon stays. + if (!state._modelSets) return; + if (state._models.size >= _modelCap()) return; + if (!_modelRegimeActive() || !state.records.data.has(icao24)) return; + const klass = state.records.data.get(icao24)?.klass; + const spec = _modelSpec(klass); + const record = createModelRecord({ + specKey: _specKeyFor(klass), // class-change sync compares against this + bellyM: spec.bellyM, + scale: spec.scale, + minPixelSize: policy.MODEL_MIN_PX, }); - // Admitted, not yet the visual. Cesium's default is show=true, which would let - // an unplaced primitive claim ownership from the icon for the frames - // between admission and the next fleet tick (and draw at the identity matrix, - // i.e. the Earth's centre). The handoff turns it on once it has a matrix. - showModel(record, false); - state._modelCollection.add(model); + record.url = resolveAsset(spec.url); + record.tint = state._irBoost ? WHITE : rgba(_modelColor(icao24)); + // Admitted, not yet the visual: the handoff places and shows it, and the + // set loads it from its first write. state._models.set(icao24, record); - state._planeModelLoaded = true; // GLB is cached now — the tracked entity's model can fade in its billboard } - /** Remove the 3D model for ONE aircraft (removal / military-suppression / track handoff). - * Bumps the load generation so any in-flight load for this icao is rejected on completion. */ + /** Remove the 3D model for ONE aircraft (removal / military-suppression / track handoff). */ function _releaseModel(icao24) { - const record = state._models.get(icao24); - const pending = state._modelPending.has(icao24); - // Only bump the generation when there's something to invalidate (an in-flight load or a - // live model) — so removing never-modeled aircraft doesn't grow _modelGen. - if (record || pending) { - state._modelGen.set(icao24, (state._modelGen.get(icao24) || 0) + 1); - } - if (record) { - if (state._modelCollection && !state._modelCollection.isDestroyed()) { - try { - state._modelCollection.remove(record.model); - } catch { - /* gone */ - } - } - state._models.delete(icao24); - _showReleasedIcon(icao24); - } - // Do NOT clear _modelPending here — the in-flight load's OWN post-await removes it. Keeping - // it (a) prevents a duplicate load from starting and (b) keeps the bumped gen entry alive so - // the resolving load's gen-check still rejects it. - _cleanupModelGen(icao24); + _releaseModelsOf([icao24]); } - /** Drop an icao's generation entry once nothing references it (no live model, no in-flight - * load) — keeps _modelGen bounded. Shared by _releaseModel + both _ensureModel exit paths. */ + /** Remove several aircraft's 3D models in one write (the eligibility pass). */ - function _cleanupModelGen(icao24) { - if (!state._modelPending.has(icao24) && !state._models.has(icao24)) - state._modelGen.delete(icao24); + function _releaseModelsOf(ids) { + const gone = ids.filter((icao24) => state._models.delete(icao24)); + if (!gone.length) return; + state._modelSets?.fleet.remove(gone); + for (const icao24 of gone) _showReleasedIcon(icao24); } /** Remove all live models (toggle-off / zoom-out); billboards take back over next tick. */ function _releaseModels() { - state._irReloadQueue = null; // a full release supersedes any pending boost-flip drain - // Invalidate in-flight loads so a completion after this bulk release can't add a model. - for (const icao of state._modelPending) - state._modelGen.set(icao, (state._modelGen.get(icao) || 0) + 1); - if (state._modelCollection && !state._modelCollection.isDestroyed()) { - for (const record of state._models.values()) { - try { - state._modelCollection.remove(record.model); - } catch { - /* gone */ - } - } - } + if (state._models.size) state._modelSets?.fleet.clear(); for (const icao24 of state._models.keys()) _showReleasedIcon(icao24); state._models.clear(); } @@ -505,21 +587,26 @@ export function createAircraftModels({ icons.setShown(icao24, true); } - /** Destroy the standalone tracked-aircraft model and invalidate any in-flight load. */ + /** Drop the standalone tracked-aircraft model. */ function _releaseTrackedModel() { - state._trackedModelGen++; - state._trackedModelLoading = false; - if (state._trackedModel) { - if (state._modelCollection && !state._modelCollection.isDestroyed()) { - try { - state._modelCollection.remove(state._trackedModel.model); - } catch { - /* gone */ - } - } - state._trackedModel = null; - } + const record = state._trackedModel; + if (!record) return; + state._trackedModel = null; + if (record.id) state._modelSets?.tracked.remove([record.id]); + } + + /** Hide the tracked model, writing it once. */ + function _hideTrackedModel() { + const record = state._trackedModel; + if (!record) return; + showModel(record, false); + _send( + state._modelSets?.tracked, + record.id, + record, + _modelSpec(state.records.data.get(record.id)?.klass), + ); } /** Per-frame driver for the standalone tracked model. Runs every preUpdate (not the 80 ms fleet @@ -531,10 +618,9 @@ export function createAircraftModels({ const active = state._trackedIcao && parts.tracking._trackedModelRegimeActive() && - state._modelCollection && - !state._modelCollection.isDestroyed(); + state._modelSets; if (!active) { - if (state._trackedModel) showModel(state._trackedModel, false); + _hideTrackedModel(); return; } // Ask the frame-cached source directly. If the entity callback already ran, @@ -543,164 +629,56 @@ export function createAircraftModels({ // readout consumers then reuse that exact cached position. const pos = parts.motion._trackedDisplayPosition(state._trackedIcao) || - parts.icons._iconPosition(state._trackedIcao, new Cesium.Cartesian3()); + parts.icons._iconPosition(state._trackedIcao); if (!pos) { - if (state._trackedModel) showModel(state._trackedModel, false); + _hideTrackedModel(); return; } - if ( - !state._trackedModel && - !state._trackedModelLoading && - parts.tracking._trackedModelLoadAllowed() - ) { - state._trackedModelLoading = true; - const gen = state._trackedModelGen; - const trackedSpec = _modelSpec( - state.records.data.get(state._trackedIcao)?.klass, - ); - const trackedKey = _specKeyFor( - state.records.data.get(state._trackedIcao)?.klass, - ); - const trackedIrBoost = state._irBoost; - Cesium.Model.fromGltfAsync({ - url: resolveAsset(trackedSpec.url), - asynchronous: false, - environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, - minimumPixelSize: policy.TRACKED_MODEL_MIN_PX, - scale: trackedSpec.scale, - color: state._irBoost - ? Cesium.Color.WHITE - : _modelColor(state._trackedIcao), - colorBlendMode: Cesium.ColorBlendMode.MIX, - // The tracked aircraft uses the same dominant light tint as the fleet; - // IR boost removes the remaining diffuse hint with flat UNLIT white. - colorBlendAmount: state._irBoost ? 1.0 : trackedSpec.blendAmount, - customShader: state._irBoost ? state._IR_UNLIT_SHADER : undefined, - // Pick id (H1): without it, clicking the very plane being tracked read as - // EMPTY SPACE (scene.pick → primitive with no id) → an unintended - // deselect. With the icao, the click handler recognizes it as ours. - id: state._trackedIcao, - }) - .then((m) => { - // Untracked / re-tracked / torn down during the load → drop it. - if ( - gen !== state._trackedModelGen || - !state._modelCollection || - state._modelCollection.isDestroyed() - ) { - try { - m.destroy(); - } catch { - /* gone */ - } - return; - } - // Class reclassified OR boost flipped mid-load (no release ran — - // _trackedModel was still null): drop the stale asset; driver reloads. - if ( - _specKeyFor(state.records.data.get(state._trackedIcao)?.klass) !== - trackedKey || - state._irBoost !== trackedIrBoost - ) { - try { - m.destroy(); - } catch { - /* gone */ - } - state._trackedModelLoading = false; - return; - } - // Assign after resolution as well as in the creation options so the - // standalone primitive always exposes the tracked aircraft pick id. - m.id = state._trackedIcao; - const record = createModelRecord(m, { - specKey: trackedKey, // class-change sync compares against this - irBoost: trackedIrBoost, - }); - showModel(record, false); // admitted, not yet the visual — the driver shows it once placed - // Seed the world transform before the primitive enters the scene. A model - // can become ready+shown between render phases; leaving Cesium's identity - // default here produces a one-frame jump to the Earth's center. - const currentPos = - parts.motion._trackedDisplayCached() || - parts.icons._iconPosition( - state._trackedIcao, - new Cesium.Cartesian3(), - ); - if (currentPos) { - const displayPos = _modelDisplayPosition( - state._trackedIcao, - currentPos, - state._scratchGroundPos, - ); - if (displayPos) - placeModel( - record, - _modelMatrix( - displayPos, - parts.motion._trackedDisplayCourse(), - undefined, - trackedSpec.headingOffsetDeg ?? - policy.MODEL_HEADING_OFFSET_DEG, - ), - ); - } - state._trackedModel = record; - state._trackedModelLoading = false; - // A good load retires this selection's failure budget — a contact that - // recovers after a transient blip is not one attempt from giving up. - state._trackedModelFailIcao = null; - state._trackedModelFailCount = 0; - state._trackedModelRetryAtMs = 0; - state._modelCollection.add(m); - state._planeModelLoaded = true; // GLB cached — the tracked billboard can fade out once the model is up - }) - .catch((err) => { - if (gen !== state._trackedModelGen) return; // superseded load — not this selection's failure - state._trackedModelLoading = false; - parts.tracking._noteTrackedModelLoadFailure(trackedSpec.url, err); - }); - return; // billboard carries the visual until the model is ready + const icao24 = state._trackedIcao; + const klass = state.records.data.get(icao24)?.klass; + const spec = _modelSpec(klass); + if (state._trackedModel && state._trackedModel.id !== icao24) + _releaseTrackedModel(); + if (!state._trackedModel) { + const record = createModelRecord({ + specKey: _specKeyFor(klass), // class-change sync compares against this + bellyM: spec.bellyM, + scale: spec.scale, + minPixelSize: policy.TRACKED_MODEL_MIN_PX, + }); + record.id = icao24; + record.url = resolveAsset(spec.url); + state._trackedModel = record; } - if (state._trackedModel) { - // Keep the transform current while GPU resources are still loading. Cesium - // can flip ready during scene update after this callback; waiting for ready - // here would let that first rendered frame use a stale load-start matrix. - const displayPos = _modelDisplayPosition( - state._trackedIcao, - pos, - state._scratchGroundPos, - ); - if (!displayPos) { - showModel(state._trackedModel, false); // no ground evidence → the icon carries it - return; - } - const spec = _modelSpec( - state.records.data.get(state._trackedIcao)?.klass, - ); - placeModel( - state._trackedModel, - _modelMatrix( - displayPos, - parts.motion._trackedDisplayCourse(), - undefined, - spec.headingOffsetDeg ?? policy.MODEL_HEADING_OFFSET_DEG, - ), - ); - if (!state._trackedModel.model.ready) return; - state._trackedModel.model.scale = trackedModelScaleForPixelCap({ + const record = state._trackedModel; + // The tracked aircraft uses the same dominant light tint as the fleet; + // the IR boost removes the remaining diffuse hint with flat white. + if (!record.tint) + record.tint = state._irBoost ? WHITE : rgba(_modelColor(icao24)); + // Placed while it loads too: its first drawn frame is at this placement. + const displayPos = _modelDisplayPosition(icao24, pos); + if (!displayPos) { + _hideTrackedModel(); // no ground evidence → the icon carries it + return; + } + placeModel( + record, + displayPos, + _modelHeading(parts.motion._trackedDisplayCourse(), klass), + ); + if (record.ready) { + const pose = _pose(); + record.scale = trackedModelScaleForPixelCap({ baseScale: spec.scale, nativeRadiusM: spec.nativeRadiusM, - rangeM: Cesium.Cartesian3.distance( - state._viewer.camera.positionWC, - displayPos, - ), - viewportHeightPx: state._viewer.scene.canvas.clientHeight, - fovyRad: state._viewer.camera.frustum.fovy, + rangeM: pose?.position ? distance(pose.position, displayPos) : NaN, + viewportHeightPx: _viewport().height, + fovyRad: pose?.fovy, maximumPixelSize: policy.TRACKED_MODEL_MAX_PX, }); - showModel(state._trackedModel, true); } + showModel(record, record.ready); + _send(state._modelSets.tracked, icao24, record, spec); } /** @@ -709,8 +687,8 @@ export function createAircraftModels({ * only re-plans icons whose regime ended, runs the layer's own pass after * that (flights floors grounded contacts), advances focus de-emphasis while * a target exists, and drives the 3D-model handoff inside the model regime. - * Driven by scene.preRender: what it writes is flushed to the draw set - * before the frame draws, as the 3D models it shows and hides are. + * Driven before each frame draws: what it writes is flushed to the draw + * sets before the frame draws, as the 3D models it shows and hides are. * @returns {void} */ @@ -718,6 +696,28 @@ export function createAircraftModels({ try { _fleetPass(); } finally { + // The models first, then the icons they take over from, so a pass + // that stopped part way never flushes an icon hidden for a model it + // did not write. + if (pendingItems.length) { + const items = pendingItems; + pendingItems = []; + try { + state._modelSets?.fleet.upsert(items); + } catch (error) { + // Nothing of these reached the set: send them again next tick, and + // let their icons carry the contacts meanwhile. + for (const item of items) { + const record = state._models.get(item.id); + if (record) { + record.sent = null; + showModel(record, false); + } + _showReleasedIcon(item.id); + } + console.warn(`[${logLabel}] fleet model write failed`, error); + } + } state._icons?.flush(); } } @@ -725,33 +725,29 @@ export function createAircraftModels({ function _fleetPass() { const icons = state._icons; if (!state._viewer || !icons || !icons.show) return; - const camera = state._viewer.camera; const nowMs = focusNowMs(Date.now()); if (nowMs - state._lastFleetTickMs < policy.FLEET_DR_INTERVAL_MS) return; state._lastFleetTickMs = nowMs; + const pose = _pose(); // Every contact in this pass shares the same delayed display instant. const t = parts.icons._displayMs(); + + if (state._cockpitContactMode) parts.tracking._refreshCockpitNearContacts(); + parts.icons._syncImageSwitch(); + parts.icons._replanExpired(t); const renderTime = parts.motion._displayTimeAt( t, state._scratchFleetRenderTime, ); - - _drainIrReloadQueue(); // bounded per-tick slice of any pending boost-flip reload - if (state._cockpitContactMode) parts.tracking._refreshCockpitNearContacts(); - parts.icons._syncImageSwitch(); - parts.icons._replanExpired(t); - afterReplan(renderTime, t, nowMs, camera); + afterReplan(renderTime, t, nowMs, pose?.position ?? null); const focusTarget = getFocusTarget(); parts.icons._focusIcons(t, nowMs, focusTarget); // 3D model regime: only when enabled AND the camera is zoomed in past the altitude ceiling. // Drop all models the moment we leave it (toggled off / zoomed out) so icons resume. - const useModels = _modelRegimeActive(); - // Drop live models AND invalidate in-flight loads on leaving the regime (else a load that - // resolves after zoom-out could briefly add a model outside the 3D-model regime). - if (!useModels && (state._models.size || state._modelPending.size)) - _releaseModels(); + const useModels = _modelRegimeActive(pose); + if (!useModels && state._models.size) _releaseModels(); if (!useModels) return; // 3D-model eligibility: by DISTANCE (the mode's add/keep band), with ON-SCREEN PRIORITY under the @@ -764,16 +760,11 @@ export function createAircraftModels({ // with off-screen retained models. Pure-distance let off-screen planes eat the cap; pure-frustum // filtering dropped near off-screen planes entirely. This does both right. const cap = _modelCap(); - const camPos = camera.positionWC; + const camPos = pose.position; const addM = _modelAddDistM(); const addDistSq = addM * addM; const keepM = _modelKeepDistM(); const keepDistSq = keepM * keepM; - const cull = camera.frustum.computeCullingVolume( - camPos, - camera.directionWC, - camera.upWC, - ); // Candidates = planes within the KEEP radius, nearest first, each tagged with on-screen-ness. const cand = []; for (const icao of icons.ids()) { @@ -788,15 +779,10 @@ export function createAircraftModels({ // ground or in the air — no distinction"). The cap + nearest-first ordering // below already bound airport clusters; grounded placement is handled by the // one-shot ground snap in _modelDisplayPosition. - const position = icons.position(icao, t, state._scratchModelBS.center); - const d2 = Cesium.Cartesian3.distanceSquared(camPos, position); + const position = icons.position(icao, t); + const d2 = distanceSquared(camPos, position); if (d2 > keepDistSq) continue; // beyond the keep radius → never eligible - cand.push([ - icao, - d2, - cull.computeVisibility(state._scratchModelBS) !== - Cesium.Intersect.OUTSIDE, - ]); + cand.push([icao, d2, inView(pose, position)]); } cand.sort((a, b) => a[1] - b[1]); // nearest first if (cand.length > cap && nowMs - state._lastModelCapWarnMs > 5000) { @@ -815,7 +801,7 @@ export function createAircraftModels({ if (icao !== state._trackedIcao && !modelEligible.has(icao)) toRelease.push(icao); } - for (const icao of toRelease) _releaseModel(icao); + _releaseModelsOf(toRelease); // 3D model takes over from the icon for eligible planes. GAP-PROOF: the icon stays shown // until the model is actually READY to render, so a plane is never both iconless AND @@ -823,66 +809,77 @@ export function createAircraftModels({ // regardless so it's framed the instant it becomes ready. Converted TR-3Bs stay 2D on // purpose: the Easter egg IS the triangle, and there is no GLB for it. const occluder = parts.icons._occluder(); + const items = pendingItems; for (const icao24 of modelEligible) { if (isTr3b(icao24)) continue; if (!icons.has(icao24)) continue; - const position = icons.position(icao24, t, state._scratchFleetPos); + const position = icons.position(icao24, t); if (!parts.icons._aboveHorizon(position, occluder)) { - // A model that crossed the limb would keep rendering through the - // hidden globe at its last matrix; the icon's own cull is on the GPU. + // A model that crossed the limb would keep drawing through the + // hidden globe; the icon's own cull is on the GPU. const hidden = state._models.get(icao24); - if (hidden?.show) showModel(hidden, false); + if (hidden?.show) { + showModel(hidden, false); + _send( + state._modelSets?.fleet, + icao24, + hidden, + _modelSpec(state.records.data.get(icao24)?.klass), + items, + ); + } continue; } _ensureModel(icao24); const record = state._models.get(icao24); - const cameraDistanceM = Cesium.Cartesian3.distance(camPos, position); + const cameraDistanceM = distance(camPos, position); _driveFleetModelHandoff( icao24, record, position, icons.course(icao24, t), () => { - applyAircraftModelTreatment({ - model: record.model, + _treat(record, { // IR boost must survive the per-tick treatment write — otherwise // any alpha change would repaint the ordinary tint over the hot // white. Boosted models also skip the recession fade: hot targets // stay full-strength at any range (icons keep their normal // fade — full-opacity glyph walls read as overwhelming). - baseColor: state._irBoost - ? Cesium.Color.WHITE - : _modelColor(icao24), + base: state._irBoost ? WHITE : rgba(_modelColor(icao24)), alpha: state._irBoost ? 1 : aircraftTreatmentAlpha({ baseAlpha: icons.alpha(icao24), focusFactor: icons.focus(icao24), cameraDistanceM, - cameraHeightM: camera.positionCartographic?.height, + cameraHeightM: pose.height, }), }); }, + items, ); } } return { + _createModelSets, + _disposeModelSets, + _setModelsShown, + _modelSetIds, _modelRegimeActive, _modelCap, _modelAddDistM, _modelKeepDistM, - _modelMatrix, _groundSampleExclusions, _modelDisplayPosition, _driveFleetModelHandoff, _modelOwnsVisual, + _modelDrawnScale, + _drawnScaleView, _specKeyFor, _syncModelToClass, _reloadModelsForIrBoost, - _drainIrReloadQueue, _ensureModel, _releaseModel, - _cleanupModelGen, _releaseModels, _showReleasedIcon, _releaseTrackedModel, diff --git a/src/data/aircraftModelLayer.test.mjs b/src/data/aircraftModelLayer.test.mjs new file mode 100644 index 000000000..6d0822ec1 --- /dev/null +++ b/src/data/aircraftModelLayer.test.mjs @@ -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; + } +}); diff --git a/src/data/aircraftModelLighting.test.mjs b/src/data/aircraftModelLighting.test.mjs index 28725e895..963aaefbd 100644 --- a/src/data/aircraftModelLighting.test.mjs +++ b/src/data/aircraftModelLighting.test.mjs @@ -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`); }); } diff --git a/src/data/cockpitModels.test.mjs b/src/data/cockpitModels.test.mjs index 336d29a03..cd8bda61b 100644 --- a/src/data/cockpitModels.test.mjs +++ b/src/data/cockpitModels.test.mjs @@ -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`); diff --git a/src/data/flights.js b/src/data/flights.js index 8c56fb38e..db72045b6 100644 --- a/src/data/flights.js +++ b/src/data/flights.js @@ -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 = diff --git a/src/data/militaryFlights.js b/src/data/militaryFlights.js index dd7d8c902..ea4dff7be 100644 --- a/src/data/militaryFlights.js +++ b/src/data/militaryFlights.js @@ -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; diff --git a/src/data/modelRecord.js b/src/data/modelRecord.js index c10fc524f..92b1c3ddb 100644 --- a/src/data/modelRecord.js +++ b/src/data/modelRecord.js @@ -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; } diff --git a/src/data/modelRecord.test.mjs b/src/data/modelRecord.test.mjs new file mode 100644 index 000000000..a2ed8f930 --- /dev/null +++ b/src/data/modelRecord.test.mjs @@ -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); +}); diff --git a/src/data/trackedModelRegime.test.mjs b/src/data/trackedModelRegime.test.mjs index ba7c97681..8b1bc0585 100644 --- a/src/data/trackedModelRegime.test.mjs +++ b/src/data/trackedModelRegime.test.mjs @@ -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`); diff --git a/src/layers/flights/lifecycle.js b/src/layers/flights/lifecycle.js index 34c421553..0875b014b 100644 --- a/src/layers/flights/lifecycle.js +++ b/src/layers/flights/lifecycle.js @@ -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; diff --git a/src/layers/flights/motion.js b/src/layers/flights/motion.js index a9dfb1f5d..21e0323fc 100644 --- a/src/layers/flights/motion.js +++ b/src/layers/flights/motion.js @@ -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, ); } diff --git a/src/layers/flights/policy.js b/src/layers/flights/policy.js index dbe001624..af594df02 100644 --- a/src/layers/flights/policy.js +++ b/src/layers/flights/policy.js @@ -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; diff --git a/src/layers/flights/queries.js b/src/layers/flights/queries.js index e041613e6..53c10afc0 100644 --- a/src/layers/flights/queries.js +++ b/src/layers/flights/queries.js @@ -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); diff --git a/src/layers/flights/queries.test.mjs b/src/layers/flights/queries.test.mjs index b4d2a696c..77d2dd492 100644 --- a/src/layers/flights/queries.test.mjs +++ b/src/layers/flights/queries.test.mjs @@ -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); }); diff --git a/src/layers/flights/rendering.js b/src/layers/flights/rendering.js index 283110cdc..8568f18ab 100644 --- a/src/layers/flights/rendering.js +++ b/src/layers/flights/rendering.js @@ -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, }, diff --git a/src/layers/flights/state.js b/src/layers/flights/state.js index 0383db1e6..028b72810 100644 --- a/src/layers/flights/state.js +++ b/src/layers/flights/state.js @@ -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} icao24 → model */ + /** @type {Map} + * icao24 → the fleet model admitted for it (loading or drawn). */ flightState._models = new Map(); - /** @type {Set} icao24 currently loading (async) */ - - flightState._modelPending = new Set(); - - /** @type {Map} 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; } diff --git a/src/layers/flights/testing.js b/src/layers/flights/testing.js index a9191d283..c03d5e0fb 100644 --- a/src/layers/flights/testing.js +++ b/src/layers/flights/testing.js @@ -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} [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, }; } diff --git a/src/layers/flights/tracking.js b/src/layers/flights/tracking.js index 272eb1f7a..89d798805 100644 --- a/src/layers/flights/tracking.js +++ b/src/layers/flights/tracking.js @@ -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, diff --git a/src/layers/military/lifecycle.js b/src/layers/military/lifecycle.js index 0aa49546b..3226bbea3 100644 --- a/src/layers/military/lifecycle.js +++ b/src/layers/military/lifecycle.js @@ -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(); diff --git a/src/layers/military/motion.js b/src/layers/military/motion.js index 0afafdbe1..86f3104cd 100644 --- a/src/layers/military/motion.js +++ b/src/layers/military/motion.js @@ -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, }, diff --git a/src/layers/military/policy.js b/src/layers/military/policy.js index 3dba916a3..a2560eb40 100644 --- a/src/layers/military/policy.js +++ b/src/layers/military/policy.js @@ -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; diff --git a/src/layers/military/queries.js b/src/layers/military/queries.js index ec7527d09..19c1b2ddf 100644 --- a/src/layers/military/queries.js +++ b/src/layers/military/queries.js @@ -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); diff --git a/src/layers/military/rendering.js b/src/layers/military/rendering.js index bc98a2c91..9f60e505b 100644 --- a/src/layers/military/rendering.js +++ b/src/layers/military/rendering.js @@ -132,6 +132,7 @@ export function createRendering({ parts, resolveAsset, logLabel: 'Data:Military', + setPrefix: 'military', policy, modelSpec: _modelSpec, modelColor: _modelColor, diff --git a/src/layers/military/state.js b/src/layers/military/state.js index 7ee9638d2..ca2eca5e0 100644 --- a/src/layers/military/state.js +++ b/src/layers/military/state.js @@ -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} icao24 → model */ + /** @type {Map} + * icao24 → the fleet model admitted for it (loading or drawn). */ flightState._models = new Map(); - /** @type {Set} icao24 currently loading (async) */ - - flightState._modelPending = new Set(); - - /** @type {Map} 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(); diff --git a/src/layers/military/testing.js b/src/layers/military/testing.js index 45f7d2125..e25f5b626 100644 --- a/src/layers/military/testing.js +++ b/src/layers/military/testing.js @@ -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} [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, }; } diff --git a/src/layers/military/tracking.js b/src/layers/military/tracking.js index c6e789a9a..30b849ee6 100644 --- a/src/layers/military/tracking.js +++ b/src/layers/military/tracking.js @@ -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, diff --git a/src/render/cesium/drawModels.js b/src/render/cesium/drawModels.js index 818fb16a4..f61e017e2 100644 --- a/src/render/cesium/drawModels.js +++ b/src/render/cesium/drawModels.js @@ -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) => { diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index a1343fc31..008beb61b 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -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",