diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 95226cd3d..a60549f29 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -17,6 +17,7 @@ "src/geo/horizon.js", "src/data/iconSegment.js", "src/data/motionModel.js", + "src/geo/julian.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", "src/render/cesium/draw.js", @@ -882,6 +883,7 @@ "src/ui/cockpit.js", "src/ui/cockpitBriefing.js", "src/geo/index.js", + "src/geo/julian.js", "src/ui/cockpitBriefPages.js", "src/ui/cockpitContextState.js", "src/ui/cockpitInstrumentState.js", @@ -1047,6 +1049,7 @@ "src/data/iconSetPrimitive.js", "src/data/aircraftRecession.js", "src/data/motionModel.js", + "src/geo/julian.js", "src/data/iconSet.js", "src/geo/horizon.js", "src/data/iconSegment.js", @@ -1478,6 +1481,7 @@ "src/data/modelVisualAnchor.js", "src/data/aircraftModelLighting.js", "src/data/motionModel.js", + "src/geo/julian.js", "src/data/renderAltitude.js", "src/data/routePlausible.js", "src/geoDistance.js", @@ -1589,6 +1593,7 @@ "src/data/modelVisualAnchor.js", "src/data/aircraftModelLighting.js", "src/data/motionModel.js", + "src/geo/julian.js", "src/data/renderAltitude.js", "src/data/trackedModelRegime.js", "src/data/trackingClickGesture.js", @@ -1691,9 +1696,12 @@ "src/data/layerStateTokenReservations.json", "src/data/modelVisualAnchor.js", "src/data/modelRecord.js", + "src/geo/frames.js", + "src/geo/ellipsoid.js", "src/data/entityRecords.js", "src/data/aircraftModelLighting.js", "src/data/motionModel.js", + "src/geo/julian.js", "src/geo/vector.js", "src/data/renderAltitude.js", "src/data/routePlausible.js", @@ -1798,6 +1806,7 @@ "src/data/iconSetPrimitive.js", "src/data/aircraftRecession.js", "src/data/motionModel.js", + "src/geo/julian.js", "src/data/iconSet.js", "src/geo/horizon.js", "src/data/iconSegment.js", @@ -1886,6 +1895,7 @@ "src/layers/firms/anchors.js", "src/layers/firms/cards.js", "src/geo/index.js", + "src/geo/julian.js", "src/render/rendererOf.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", @@ -1961,6 +1971,7 @@ "modules": [ "src/data/satelliteClass.js", "src/geo/index.js", + "src/geo/julian.js", "src/data/satellitePass.js", "src/sources/tle.js", "src/layers/satellites/catalog.js", @@ -2053,6 +2064,7 @@ "src/data/iconSetPrimitive.js", "src/data/aircraftRecession.js", "src/data/motionModel.js", + "src/geo/julian.js", "src/data/iconAtlas.js", "src/data/iconSet.js", "src/data/iconSegment.js", @@ -2140,6 +2152,7 @@ "src/data/aircraftRecession.js", "src/data/iconAtlas.js", "src/data/motionModel.js", + "src/geo/julian.js", "src/data/iconSet.js", "src/data/iconSegment.js", "src/render/cesium/frame.js", @@ -2234,6 +2247,7 @@ "src/render/camera/poseSignature.js", "src/data/militaryAwarenessEngine.js", "src/geo/index.js", + "src/geo/julian.js", "src/data/installationNames.js", "src/layers/awareness/controls.js", "src/layers/awareness/dependencies.js", @@ -2302,6 +2316,7 @@ "src/layers/traffic/animation.js", "src/layers/traffic/controls.js", "src/geo/index.js", + "src/geo/julian.js", "src/layers/traffic/flow.js", "src/layers/traffic/flowDecode.js", "src/layers/traffic/flowSource.js", @@ -2457,6 +2472,7 @@ "src/layers/cctv/ground.js", "src/layers/cctv/headingConfidence.js", "src/geo/index.js", + "src/geo/julian.js", "src/layers/cctv/health.js", "src/layers/cctv/hover.js", "src/layers/cctv/index.js", @@ -2555,6 +2571,7 @@ "src/geo/horizon.js", "src/data/iconSegment.js", "src/data/motionModel.js", + "src/geo/julian.js", "src/data/iconAtlas.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", @@ -2658,6 +2675,7 @@ "src/layers/alpr/index.js", "src/data/followed.js", "src/geo/index.js", + "src/geo/julian.js", "src/layers/alpr/model.js", "src/layers/alpr/policy.js", "src/layers/alpr/presentation.js", @@ -2734,6 +2752,7 @@ "src/layers/radio/catalogModel.js", "src/layers/radio/categories.js", "src/geo/index.js", + "src/geo/julian.js", "src/layers/radio/clustering.js", "src/layers/radio/controls.js", "src/layers/radio/index.js", @@ -2915,6 +2934,7 @@ "src/i18n/marker.js", "src/maps/availability.js", "src/geo/index.js", + "src/geo/julian.js", "src/maps/catalog.js", "src/maps/controller.js", "src/render/cesium/globe.js", @@ -3084,6 +3104,7 @@ ], "modules": [ "src/geo/index.js", + "src/geo/julian.js", "src/geo/vector.js", "src/geo/ellipsoid.js", "src/geo/frames.js", @@ -4142,6 +4163,7 @@ "src/data/aircraftIconLayer.js", "src/data/aircraftModelLayer.js", "src/data/aircraftMotionRegime.js", + "src/geo/julian.js", "src/data/iconSetPrimitive.js", "src/data/iconSet.js", "src/data/iconSegment.js", @@ -4835,6 +4857,7 @@ "src/geo/horizon.js", "src/data/iconSegment.js", "src/data/motionModel.js", + "src/geo/julian.js", "src/data/iconAtlas.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", @@ -5512,6 +5535,7 @@ "src/geo/horizon.js", "src/data/iconSegment.js", "src/data/motionModel.js", + "src/geo/julian.js", "src/data/iconAtlas.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", @@ -5640,6 +5664,7 @@ "src/layers/transit/rendering.js", "src/layers/transit/selection.js", "src/geo/index.js", + "src/geo/julian.js", "src/layers/transit/state.js", "src/layers/transit/testing.js", "src/layers/transit/viewport.js", @@ -5869,6 +5894,7 @@ "modules": [ "src/layers/ghostMaps/index.js", "src/geo/index.js", + "src/geo/julian.js", "src/layers/ghostMaps/catalog.js", "src/layers/ghostMaps/records.js", "src/layers/ghostMaps/kml.js", @@ -6166,6 +6192,7 @@ "exports": ["./agent/world-packet"], "modules": [ "src/geo/index.js", + "src/geo/julian.js", "src/geo/vector.js", "src/geo/ellipsoid.js", "src/geo/frames.js", @@ -6195,6 +6222,7 @@ "exports": ["./geo"], "modules": [ "src/geo/index.js", + "src/geo/julian.js", "src/geo/vector.js", "src/geo/ellipsoid.js", "src/geo/frames.js", @@ -6221,6 +6249,7 @@ "src/render/conformance/checks/ports.js", "src/render/stub/math.js", "src/geo/index.js", + "src/geo/julian.js", "src/geo/vector.js", "src/geo/ellipsoid.js", "src/geo/frames.js", diff --git a/src/data/aircraftMotionRegime.js b/src/data/aircraftMotionRegime.js index 948b46474..ecb2f4a5d 100644 --- a/src/data/aircraftMotionRegime.js +++ b/src/data/aircraftMotionRegime.js @@ -1,4 +1,12 @@ -import * as Cesium from 'cesium'; +import { fromDegrees } from '../geo/ellipsoid.js'; +import { + julianFromEpochMs, + julianLessThan, + julianLessThanOrEquals, + julianToEpochMs, + secondsDifference, +} from '../geo/julian.js'; +import { clone, distance } from '../geo/vector.js'; import { courseBetweenCartesians, speedRamp, @@ -26,28 +34,26 @@ export function fixTrackDeg(fix, info, fields) { } /** - * The instant `epochMs` as a JulianDate (into `result` when given), for + * The instant `epochMs` as a Julian date (into `result` when given), for * `aircraftMotionRegime`'s `renderTime`. */ export function julianAt(epochMs, result) { - return Cesium.JulianDate.fromDate(new Date(epochMs), result); + return julianFromEpochMs(epochMs, result); } /** A history fix's time in epoch ms: its `epochMs`, else its `time`'s. */ export function fixEpochMs(fix) { - return Number.isFinite(fix.epochMs) - ? fix.epochMs - : Cesium.JulianDate.toDate(fix.time).getTime(); + return Number.isFinite(fix.epochMs) ? fix.epochMs : julianToEpochMs(fix.time); } /** A feed fix's ECEF position, from its degrees and render altitude. */ export function fixPosition(lonDeg, latDeg, heightM) { - return Cesium.Cartesian3.fromDegrees(lonDeg, latDeg, heightM); + return fromDegrees(lonDeg, latDeg, heightM); } /** A copy of a fix position, for a trail that keeps it. */ export function copyPosition(position) { - return Cesium.Cartesian3.clone(position); + return clone(position); } /** @@ -58,7 +64,7 @@ export function historyFix(epochMs, position, velocity, track) { return { time: julianAt(epochMs), epochMs, - position: Cesium.Cartesian3.clone(position), + position: clone(position), velocity, track, }; @@ -110,7 +116,7 @@ export function createMotionRegime() { * * @param {Array} history Non-empty, oldest first. * @param {object|undefined} info The contact's record. - * @param {Cesium.JulianDate} renderTime + * @param {{dayNumber: number, secondsOfDay: number}} renderTime A Julian date (geo/julian). * @param {AircraftRecordFields} fields * @param {object} result From `createMotionRegime`; returned filled in. */ @@ -125,12 +131,12 @@ export function aircraftMotionRegime( const a = history[i - 1]; const b = history[i]; if ( - !Cesium.JulianDate.lessThanOrEquals(a.time, renderTime) || - !Cesium.JulianDate.lessThanOrEquals(renderTime, b.time) + !julianLessThanOrEquals(a.time, renderTime) || + !julianLessThanOrEquals(renderTime, b.time) ) continue; - const span = Cesium.JulianDate.secondsDifference(b.time, a.time); - const chordLenM = Cesium.Cartesian3.distance(a.position, b.position); + const span = secondsDifference(b.time, a.time); + const chordLenM = distance(a.position, b.position); const speed = span > 0 ? chordLenM / span : (info && info[fields.speed]) || 0; const fallbackTrack = (info && info[fields.track]) || 0; @@ -149,7 +155,7 @@ export function aircraftMotionRegime( return result; } const newest = history[history.length - 1]; - const warming = Cesium.JulianDate.lessThan(renderTime, history[0].time); + const warming = julianLessThan(renderTime, history[0].time); result.kind = 'fix'; result.fix = warming ? history[0] : newest; result.speed = fixSpeedMps(result.fix, info, fields); @@ -166,7 +172,7 @@ export function aircraftMotionRegime( // allocating a Date per aircraft on every 12 Hz fleet tick. fixEpochMs: Number.isFinite(newest.epochMs) ? newest.epochMs - : Cesium.JulianDate.toDate(newest.time).getTime(), + : julianToEpochMs(newest.time), lastContactEpochMs: info?.lastContactEpochMs, // Permit one minute of contact grace but cap any cached-feed drift // at five minutes. Source backoff is exposed separately as a STALE cue. diff --git a/src/data/infrastructure.test.mjs b/src/data/infrastructure.test.mjs index c058e89e6..97f27ad9d 100644 --- a/src/data/infrastructure.test.mjs +++ b/src/data/infrastructure.test.mjs @@ -216,9 +216,9 @@ test('consumer build includes only infrastructure code and resolves assets under 'input.js', 'inputOwnership.js', 'internals.js', + 'julian.js', 'localGeojsonCore.js', 'localGeojsonLod.js', - 'motionModel.js', 'pickRegistry.js', 'polyline.js', 'query.js', diff --git a/src/data/motionModel.js b/src/data/motionModel.js index 00520658c..e0ee99245 100644 --- a/src/data/motionModel.js +++ b/src/data/motionModel.js @@ -6,41 +6,34 @@ * Turn-rate estimation + constant-rate-turn arc integration are adapted from * skylight (https://github.com/cpaczek/skylight, MIT) shared/src/aim.ts. */ -import * as Cesium from 'cesium'; -import { norm180, norm360 } from '../geo/vector.js'; +import { fromRadians, toCartographicRadians } from '../geo/ellipsoid.js'; +import { eastNorthUp, framePoint } from '../geo/frames.js'; +import { + julianFromEpochMs, + julianToEpochMs, + secondsDifference, +} from '../geo/julian.js'; +import { copyInto, norm180, norm360, vec } from '../geo/vector.js'; const DEG = Math.PI / 180; -const _mmCarto = new Cesium.Cartographic(); -const _mmCandidateCarto = new Cesium.Cartographic(); /** * Lift a repeated grounded fix to a newly resolved render floor without * manufacturing a new source timestamp or changing its reported lat/lon. * Airborne fixes and downward candidates are deliberately left untouched. * - * @param {{position: Cesium.Cartesian3}|null} newest - * @param {Cesium.Cartesian3|null} candidatePosition + * @param {{position: {x: number, y: number, z: number}}|null} newest + * @param {{x: number, y: number, z: number}|null} candidatePosition ECEF. * @param {boolean} onGround * @returns {boolean} True when the stored position was lifted. */ export function liftRepeatedGroundFix(newest, candidatePosition, onGround) { if (!onGround || !newest?.position || !candidatePosition) return false; - const stored = Cesium.Cartographic.fromCartesian( - newest.position, - Cesium.Ellipsoid.WGS84, - _mmCarto, - ); - const candidate = Cesium.Cartographic.fromCartesian( - candidatePosition, - Cesium.Ellipsoid.WGS84, - _mmCandidateCarto, - ); + const stored = toCartographicRadians(newest.position); + const candidate = toCartographicRadians(candidatePosition); if (!stored || !candidate || candidate.height <= stored.height) return false; - Cesium.Cartesian3.fromRadians( - stored.longitude, - stored.latitude, - candidate.height, - Cesium.Ellipsoid.WGS84, + copyInto( + fromRadians(stored.lon, stored.lat, candidate.height), newest.position, ); return true; @@ -60,16 +53,12 @@ export function courseBetweenCartesians(from, to, minChordM = 25) { const dy = to.y - from.y; const dz = to.z - from.z; if (dx * dx + dy * dy + dz * dz < minChordM * minChordM) return null; - const carto = Cesium.Cartographic.fromCartesian( - from, - Cesium.Ellipsoid.WGS84, - _mmCarto, - ); + const carto = toCartographicRadians(from); if (!carto) return null; - const sLat = Math.sin(carto.latitude); - const cLat = Math.cos(carto.latitude); - const sLon = Math.sin(carto.longitude); - const cLon = Math.cos(carto.longitude); + const sLat = Math.sin(carto.lat); + const cLat = Math.cos(carto.lat); + const sLon = Math.sin(carto.lon); + const cLon = Math.cos(carto.lon); const e = -sLon * dx + cLon * dy; const n = -sLat * cLon * dx - sLat * sLon * dy + cLat * dz; if (e * e + n * n < 1) return null; // < 1 m horizontal — vertical-only motion @@ -260,7 +249,7 @@ export function turnRateFromFixHistory(history) { for (const s of history) { if (!Number.isFinite(s.track)) continue; samples.push({ - tSec: Cesium.JulianDate.secondsDifference(s.time, t0), + tSec: secondsDifference(s.time, t0), trackDeg: s.track, speedMps: s.velocity, }); @@ -430,8 +419,6 @@ export function arcOffsetEnu(speedMps, trackDeg, turnRateDps, dtSec, result) { } const _forwardFixArc = { east: 0, north: 0, endCourseDeg: 0 }; -const _forwardFixEnu = new Cesium.Matrix4(); -const _forwardFixOffset = new Cesium.Cartesian3(); /** * Create a forward-only synthetic fix when a repeated position epoch carries @@ -440,11 +427,11 @@ const _forwardFixOffset = new Cesium.Cartesian3(); * kinematics. This prevents a late course change from reprojecting the entire * stale interval and snapping the rendered contact by kilometres. * - * @param {{time: Cesium.JulianDate, epochMs?: number, position: Cesium.Cartesian3, + * @param {{time: object, epochMs?: number, position: {x: number, y: number, z: number}, * velocity?: number, track?: number}} newest Existing immutable history fix. * @param {{epochMs: number, velocity: number, track: number, turnRateDps?: number}} next * New kinematics and the wall/source epoch at which they become authoritative. - * @returns {{time: Cesium.JulianDate, epochMs: number, position: Cesium.Cartesian3, + * @returns {{time: object, epochMs: number, position: {x: number, y: number, z: number}, * velocity: number, track: number}|null} Forward synthetic fix, or null. */ export function synthesizeForwardKinematicsFix(newest, next = {}) { @@ -452,7 +439,7 @@ export function synthesizeForwardKinematicsFix(newest, next = {}) { return null; const startEpochMs = Number.isFinite(newest.epochMs) ? newest.epochMs - : Cesium.JulianDate.toDate(newest.time).getTime(); + : julianToEpochMs(newest.time); if (!Number.isFinite(startEpochMs) || next.epochMs <= startEpochMs) return null; @@ -468,24 +455,12 @@ export function synthesizeForwardKinematicsFix(newest, next = {}) { dtSec, _forwardFixArc, ); - Cesium.Cartesian3.fromElements( - _forwardFixArc.east, - _forwardFixArc.north, - 0, - _forwardFixOffset, - ); - const enu = Cesium.Transforms.eastNorthUpToFixedFrame( - newest.position, - Cesium.Ellipsoid.WGS84, - _forwardFixEnu, - ); - const position = Cesium.Matrix4.multiplyByPoint( - enu, - _forwardFixOffset, - new Cesium.Cartesian3(), + const position = framePoint( + eastNorthUp(newest.position), + vec(_forwardFixArc.east, _forwardFixArc.north, 0), ); return { - time: Cesium.JulianDate.fromDate(new Date(next.epochMs)), + time: julianFromEpochMs(next.epochMs), epochMs: next.epochMs, position, velocity: Number.isFinite(next.velocity) diff --git a/src/geo/celestial.js b/src/geo/celestial.js index cf4942185..7ac616f95 100644 --- a/src/geo/celestial.js +++ b/src/geo/celestial.js @@ -17,6 +17,14 @@ * throws. */ import { frameVector } from './frames.js'; +import { + SECONDS_PER_DAY, + addSeconds, + computeTaiMinusUtc, + julianFromEpochMs as julianDateFromEpochMs, + taiDate, + totalDays, +} from './julian.js'; import { RADIANS_PER_DEGREE, TWO_PI, vec, zeroToTwoPi } from './vector.js'; // --------------------------------------------------------------------------- @@ -24,187 +32,8 @@ import { RADIANS_PER_DEGREE, TWO_PI, vec, zeroToTwoPi } from './vector.js'; const PI = Math.PI; const RADIANS_PER_ARCSECOND = RADIANS_PER_DEGREE / 3600.0; -const SECONDS_PER_MILLISECOND = 0.001; -const SECONDS_PER_MINUTE = 60.0; -const SECONDS_PER_HOUR = 3600.0; -const SECONDS_PER_DAY = 86400.0; const DAYS_PER_JULIAN_CENTURY = 36525.0; -// --------------------------------------------------------------------------- -// Julian dates (Core/JulianDate.js). A date is `{dayNumber, secondsOfDay}`, -// in TAI unless a comment says otherwise, as Cesium keeps them. - -function setComponents(wholeDays, secondsOfDay, julianDate) { - const extraDays = (secondsOfDay / SECONDS_PER_DAY) | 0; - wholeDays += extraDays; - secondsOfDay -= SECONDS_PER_DAY * extraDays; - - if (secondsOfDay < 0) { - wholeDays--; - secondsOfDay += SECONDS_PER_DAY; - } - - julianDate.dayNumber = wholeDays; - julianDate.secondsOfDay = secondsOfDay; - return julianDate; -} - -const taiDate = (dayNumber, secondsOfDay) => - setComponents(dayNumber, secondsOfDay, {}); - -const addSeconds = (julianDate, seconds, result) => - setComponents( - julianDate.dayNumber, - julianDate.secondsOfDay + seconds, - result, - ); - -const totalDays = (julianDate) => - julianDate.dayNumber + julianDate.secondsOfDay / SECONDS_PER_DAY; - -function secondsDifference(left, right) { - const dayDifference = (left.dayNumber - right.dayNumber) * SECONDS_PER_DAY; - return dayDifference + (left.secondsOfDay - right.secondsOfDay); -} - -function compare(left, right) { - const julianDayNumberDifference = left.dayNumber - right.dayNumber; - if (julianDayNumberDifference !== 0) return julianDayNumberDifference; - return left.secondsOfDay - right.secondsOfDay; -} - -/** `JulianDate.leapSeconds`: the TAI instant of each leap second, and TAI−UTC from it. */ -const LEAP_SECONDS = [ - [2441317, 43210.0, 10], // January 1, 1972 00:00:00 UTC - [2441499, 43211.0, 11], // July 1, 1972 00:00:00 UTC - [2441683, 43212.0, 12], // January 1, 1973 00:00:00 UTC - [2442048, 43213.0, 13], // January 1, 1974 00:00:00 UTC - [2442413, 43214.0, 14], // January 1, 1975 00:00:00 UTC - [2442778, 43215.0, 15], // January 1, 1976 00:00:00 UTC - [2443144, 43216.0, 16], // January 1, 1977 00:00:00 UTC - [2443509, 43217.0, 17], // January 1, 1978 00:00:00 UTC - [2443874, 43218.0, 18], // January 1, 1979 00:00:00 UTC - [2444239, 43219.0, 19], // January 1, 1980 00:00:00 UTC - [2444786, 43220.0, 20], // July 1, 1981 00:00:00 UTC - [2445151, 43221.0, 21], // July 1, 1982 00:00:00 UTC - [2445516, 43222.0, 22], // July 1, 1983 00:00:00 UTC - [2446247, 43223.0, 23], // July 1, 1985 00:00:00 UTC - [2447161, 43224.0, 24], // January 1, 1988 00:00:00 UTC - [2447892, 43225.0, 25], // January 1, 1990 00:00:00 UTC - [2448257, 43226.0, 26], // January 1, 1991 00:00:00 UTC - [2448804, 43227.0, 27], // July 1, 1992 00:00:00 UTC - [2449169, 43228.0, 28], // July 1, 1993 00:00:00 UTC - [2449534, 43229.0, 29], // July 1, 1994 00:00:00 UTC - [2450083, 43230.0, 30], // January 1, 1996 00:00:00 UTC - [2450630, 43231.0, 31], // July 1, 1997 00:00:00 UTC - [2451179, 43232.0, 32], // January 1, 1999 00:00:00 UTC - [2453736, 43233.0, 33], // January 1, 2006 00:00:00 UTC - [2454832, 43234.0, 34], // January 1, 2009 00:00:00 UTC - [2456109, 43235.0, 35], // July 1, 2012 00:00:00 UTC - [2457204, 43236.0, 36], // July 1, 2015 00:00:00 UTC - [2457754, 43237.0, 37], // January 1, 2017 00:00:00 UTC -].map(([dayNumber, secondsOfDay, offset]) => - Object.freeze({ julianDate: taiDate(dayNumber, secondsOfDay), offset }), -); - -/** Core/binarySearch.js over the leap-second table. */ -function searchLeapSeconds(julianDate) { - let low = 0; - let high = LEAP_SECONDS.length - 1; - while (low <= high) { - const i = ~~((low + high) / 2); - const comparison = compare(LEAP_SECONDS[i].julianDate, julianDate); - if (comparison < 0) { - low = i + 1; - continue; - } - if (comparison > 0) { - high = i - 1; - continue; - } - return i; - } - return ~(high + 1); -} - -/** `convertUtcToTai`: shifts a UTC date to TAI in place. */ -function convertUtcToTai(julianDate) { - // Even though julianDate is in UTC, Cesium treats it as TAI to search. - let index = searchLeapSeconds(julianDate); - if (index < 0) index = ~index; - if (index >= LEAP_SECONDS.length) index = LEAP_SECONDS.length - 1; - - let offset = LEAP_SECONDS[index].offset; - if (index > 0) { - const difference = secondsDifference( - LEAP_SECONDS[index].julianDate, - julianDate, - ); - if (difference > offset) { - index--; - offset = LEAP_SECONDS[index].offset; - } - } - - addSeconds(julianDate, offset, julianDate); -} - -/** `JulianDate.computeTaiMinusUtc`. */ -function computeTaiMinusUtc(julianDate) { - let index = searchLeapSeconds(julianDate); - if (index < 0) { - index = ~index; - --index; - if (index < 0) index = 0; - } - return LEAP_SECONDS[index].offset; -} - -/** - * `JulianDate.fromDate(new Date(ms))`: the TAI Julian date of a UTC epoch - * millisecond (Seidelmann 1992, Explanatory Supplement p. 604). - */ -function julianDateFromEpochMs(ms) { - const date = new Date(ms); - if (!Number.isFinite(date.getTime())) - throw new RangeError(`not a representable time: ${ms}`); - const year = date.getUTCFullYear(); - const month = date.getUTCMonth() + 1; - const day = date.getUTCDate(); - let hour = date.getUTCHours(); - const minute = date.getUTCMinutes(); - const second = date.getUTCSeconds(); - const millisecond = date.getUTCMilliseconds(); - - const a = ((month - 14) / 12) | 0; - const b = year + 4800 + a; - let dayNumber = - (((1461 * b) / 4) | 0) + - (((367 * (month - 2 - 12 * a)) / 12) | 0) - - (((3 * (((b + 100) / 100) | 0)) / 4) | 0) + - day - - 32075; - - // Julian dates are noon-based. - hour = hour - 12; - if (hour < 0) hour += 24; - - let secondsOfDay = - second + - (hour * SECONDS_PER_HOUR + - minute * SECONDS_PER_MINUTE + - millisecond * SECONDS_PER_MILLISECOND); - - if (secondsOfDay >= 43200.0) dayNumber -= 1; - - // The JulianDate constructor: split a fractional day number (none here). - const wholeDays = dayNumber | 0; - secondsOfDay = secondsOfDay + (dayNumber - wholeDays) * SECONDS_PER_DAY; - const julianDate = setComponents(wholeDays, secondsOfDay, {}); - convertUtcToTai(julianDate); - return julianDate; -} - // --------------------------------------------------------------------------- // Matrices diff --git a/src/geo/index.js b/src/geo/index.js index 803693642..c064bd24c 100644 --- a/src/geo/index.js +++ b/src/geo/index.js @@ -9,4 +9,5 @@ export * from './vector.js'; export * from './ellipsoid.js'; export * from './frames.js'; export * from './celestial.js'; +export * from './julian.js'; export * from './quaternion.js'; diff --git a/src/geo/julian.js b/src/geo/julian.js new file mode 100644 index 000000000..33a979c27 --- /dev/null +++ b/src/geo/julian.js @@ -0,0 +1,291 @@ +/** + * @module geo/julian + * @description Julian dates as Cesium 1.138's `JulianDate` keeps them, on + * plain `{dayNumber, secondsOfDay}` objects in TAI, so code that times + * motion on them needs no engine. The arithmetic, the UTC to TAI shift + * through the leap-second table and the conversion back to epoch + * milliseconds follow `Core/JulianDate.js` step for step, so a date made + * here and one made by `JulianDate` are the same numbers and either + * module's functions take either. Do not "simplify" them. + */ + +export const SECONDS_PER_DAY = 86400.0; +const SECONDS_PER_MILLISECOND = 0.001; +const SECONDS_PER_MINUTE = 60.0; +const SECONDS_PER_HOUR = 3600.0; + +/** `setComponents`: normalise whole days and seconds into `julianDate`. */ +function setComponents(wholeDays, secondsOfDay, julianDate) { + const extraDays = (secondsOfDay / SECONDS_PER_DAY) | 0; + wholeDays += extraDays; + secondsOfDay -= SECONDS_PER_DAY * extraDays; + + if (secondsOfDay < 0) { + wholeDays--; + secondsOfDay += SECONDS_PER_DAY; + } + + julianDate.dayNumber = wholeDays; + julianDate.secondsOfDay = secondsOfDay; + return julianDate; +} + +/** A TAI date from its components, normalised. */ +export const taiDate = (dayNumber, secondsOfDay) => + setComponents(dayNumber, secondsOfDay, {}); + +/** `JulianDate.clone`: undefined for none, as Cesium's. */ +export function cloneJulian(julianDate, result) { + if (julianDate === undefined || julianDate === null) return undefined; + const out = result ?? {}; + out.dayNumber = julianDate.dayNumber; + out.secondsOfDay = julianDate.secondsOfDay; + return out; +} + +/** `JulianDate.addSeconds`, into `result` (a new date when omitted). */ +export const addSeconds = (julianDate, seconds, result) => + setComponents( + julianDate.dayNumber, + julianDate.secondsOfDay + seconds, + result ?? {}, + ); + +/** `JulianDate.totalDays`. */ +export const totalDays = (julianDate) => + julianDate.dayNumber + julianDate.secondsOfDay / SECONDS_PER_DAY; + +/** `JulianDate.secondsDifference`: `left` minus `right`, seconds. */ +export function secondsDifference(left, right) { + const dayDifference = (left.dayNumber - right.dayNumber) * SECONDS_PER_DAY; + return dayDifference + (left.secondsOfDay - right.secondsOfDay); +} + +/** `JulianDate.compare`: negative when `left` is earlier. */ +export function compareJulian(left, right) { + const julianDayNumberDifference = left.dayNumber - right.dayNumber; + if (julianDayNumberDifference !== 0) return julianDayNumberDifference; + return left.secondsOfDay - right.secondsOfDay; +} + +/** `JulianDate.lessThan`. */ +export const julianLessThan = (left, right) => compareJulian(left, right) < 0; + +/** `JulianDate.lessThanOrEquals`. */ +export const julianLessThanOrEquals = (left, right) => + compareJulian(left, right) <= 0; + +/** `JulianDate.leapSeconds`: the TAI instant of each leap second, and TAI−UTC from it. */ +const LEAP_SECONDS = [ + [2441317, 43210.0, 10], // January 1, 1972 00:00:00 UTC + [2441499, 43211.0, 11], // July 1, 1972 00:00:00 UTC + [2441683, 43212.0, 12], // January 1, 1973 00:00:00 UTC + [2442048, 43213.0, 13], // January 1, 1974 00:00:00 UTC + [2442413, 43214.0, 14], // January 1, 1975 00:00:00 UTC + [2442778, 43215.0, 15], // January 1, 1976 00:00:00 UTC + [2443144, 43216.0, 16], // January 1, 1977 00:00:00 UTC + [2443509, 43217.0, 17], // January 1, 1978 00:00:00 UTC + [2443874, 43218.0, 18], // January 1, 1979 00:00:00 UTC + [2444239, 43219.0, 19], // January 1, 1980 00:00:00 UTC + [2444786, 43220.0, 20], // July 1, 1981 00:00:00 UTC + [2445151, 43221.0, 21], // July 1, 1982 00:00:00 UTC + [2445516, 43222.0, 22], // July 1, 1983 00:00:00 UTC + [2446247, 43223.0, 23], // July 1, 1985 00:00:00 UTC + [2447161, 43224.0, 24], // January 1, 1988 00:00:00 UTC + [2447892, 43225.0, 25], // January 1, 1990 00:00:00 UTC + [2448257, 43226.0, 26], // January 1, 1991 00:00:00 UTC + [2448804, 43227.0, 27], // July 1, 1992 00:00:00 UTC + [2449169, 43228.0, 28], // July 1, 1993 00:00:00 UTC + [2449534, 43229.0, 29], // July 1, 1994 00:00:00 UTC + [2450083, 43230.0, 30], // January 1, 1996 00:00:00 UTC + [2450630, 43231.0, 31], // July 1, 1997 00:00:00 UTC + [2451179, 43232.0, 32], // January 1, 1999 00:00:00 UTC + [2453736, 43233.0, 33], // January 1, 2006 00:00:00 UTC + [2454832, 43234.0, 34], // January 1, 2009 00:00:00 UTC + [2456109, 43235.0, 35], // July 1, 2012 00:00:00 UTC + [2457204, 43236.0, 36], // July 1, 2015 00:00:00 UTC + [2457754, 43237.0, 37], // January 1, 2017 00:00:00 UTC +].map(([dayNumber, secondsOfDay, offset]) => + Object.freeze({ julianDate: taiDate(dayNumber, secondsOfDay), offset }), +); + +/** Core/binarySearch.js over the leap-second table. */ +function searchLeapSeconds(julianDate) { + let low = 0; + let high = LEAP_SECONDS.length - 1; + while (low <= high) { + const i = ~~((low + high) / 2); + const comparison = compareJulian(LEAP_SECONDS[i].julianDate, julianDate); + if (comparison < 0) { + low = i + 1; + continue; + } + if (comparison > 0) { + high = i - 1; + continue; + } + return i; + } + return ~(high + 1); +} + +/** `convertUtcToTai`: shifts a UTC date to TAI in place. */ +function convertUtcToTai(julianDate) { + // Even though julianDate is in UTC, Cesium treats it as TAI to search. + let index = searchLeapSeconds(julianDate); + if (index < 0) index = ~index; + if (index >= LEAP_SECONDS.length) index = LEAP_SECONDS.length - 1; + + let offset = LEAP_SECONDS[index].offset; + if (index > 0) { + const difference = secondsDifference( + LEAP_SECONDS[index].julianDate, + julianDate, + ); + if (difference > offset) { + index--; + offset = LEAP_SECONDS[index].offset; + } + } + + addSeconds(julianDate, offset, julianDate); +} + +/** + * `convertTaiToUtc`: the UTC date of a TAI one, into `result`; undefined + * during a leap second, which UTC cannot name. + */ +function convertTaiToUtc(julianDate, result) { + let index = searchLeapSeconds(julianDate); + if (index < 0) index = ~index; + + // All times before our first leap second get the first offset. + if (index === 0) + return addSeconds(julianDate, -LEAP_SECONDS[0].offset, result); + + // All times after our leap second get the last offset. + if (index >= LEAP_SECONDS.length) + return addSeconds(julianDate, -LEAP_SECONDS[index - 1].offset, result); + + const difference = secondsDifference( + LEAP_SECONDS[index].julianDate, + julianDate, + ); + + // The date is in the leap-second table. + if (difference === 0) + return addSeconds(julianDate, -LEAP_SECONDS[index].offset, result); + + // During the moment of a leap second there is no UTC. + if (difference <= 1.0) return undefined; + + return addSeconds(julianDate, -LEAP_SECONDS[--index].offset, result); +} + +/** `JulianDate.computeTaiMinusUtc`. */ +export function computeTaiMinusUtc(julianDate) { + let index = searchLeapSeconds(julianDate); + if (index < 0) { + index = ~index; + --index; + if (index < 0) index = 0; + } + return LEAP_SECONDS[index].offset; +} + +/** + * `JulianDate.fromDate(new Date(ms), result)`: the TAI Julian date of a UTC + * epoch millisecond (Seidelmann 1992, Explanatory Supplement p. 604). + * @param {number} ms + * @param {object} [result] + */ +export function julianFromEpochMs(ms, result) { + const date = new Date(ms); + if (!Number.isFinite(date.getTime())) + throw new RangeError(`not a representable time: ${ms}`); + const year = date.getUTCFullYear(); + const month = date.getUTCMonth() + 1; + const day = date.getUTCDate(); + let hour = date.getUTCHours(); + const minute = date.getUTCMinutes(); + const second = date.getUTCSeconds(); + const millisecond = date.getUTCMilliseconds(); + + const a = ((month - 14) / 12) | 0; + const b = year + 4800 + a; + let dayNumber = + (((1461 * b) / 4) | 0) + + (((367 * (month - 2 - 12 * a)) / 12) | 0) - + (((3 * (((b + 100) / 100) | 0)) / 4) | 0) + + day - + 32075; + + // Julian dates are noon-based. + hour = hour - 12; + if (hour < 0) hour += 24; + + const secondsOfDay = + second + + (hour * SECONDS_PER_HOUR + + minute * SECONDS_PER_MINUTE + + millisecond * SECONDS_PER_MILLISECOND); + + if (secondsOfDay >= 43200.0) dayNumber -= 1; + + const out = setComponents(dayNumber, secondsOfDay, result ?? {}); + convertUtcToTai(out); + return out; +} + +/** `JulianDate.now(result)`: the current system time. */ +export const julianNow = (result) => julianFromEpochMs(Date.now(), result); + +const scratchUtc = {}; + +/** + * `JulianDate.toDate(julianDate).getTime()`: UTC epoch milliseconds, a + * leap second read as the second before it, as Cesium's. + * @param {{dayNumber: number, secondsOfDay: number}} julianDate + * @returns {number} + */ +export function julianToEpochMs(julianDate) { + let thisUtc = convertTaiToUtc(julianDate, scratchUtc); + if (thisUtc === undefined) { + // During a leap second: convert the second before it. + addSeconds(julianDate, -1, scratchUtc); + thisUtc = convertTaiToUtc(scratchUtc, scratchUtc); + } + + let julianDayNumber = thisUtc.dayNumber; + const secondsOfDay = thisUtc.secondsOfDay; + + if (secondsOfDay >= 43200.0) julianDayNumber += 1; + + // Algorithm from page 604 of the Explanatory Supplement to the + // Astronomical Almanac (Seidelmann 1992). + let L = (julianDayNumber + 68569) | 0; + const N = ((4 * L) / 146097) | 0; + L = (L - (((146097 * N + 3) / 4) | 0)) | 0; + const I = ((4000 * (L + 1)) / 1461001) | 0; + L = (L - (((1461 * I) / 4) | 0) + 31) | 0; + const J = ((80 * L) / 2447) | 0; + const day = (L - (((2447 * J) / 80) | 0)) | 0; + L = (J / 11) | 0; + const month = (J + 2 - 12 * L) | 0; + const year = (100 * (N - 49) + I + L) | 0; + + let hour = (secondsOfDay / SECONDS_PER_HOUR) | 0; + let remainingSeconds = secondsOfDay - hour * SECONDS_PER_HOUR; + const minute = (remainingSeconds / SECONDS_PER_MINUTE) | 0; + remainingSeconds = remainingSeconds - minute * SECONDS_PER_MINUTE; + const second = remainingSeconds | 0; + const millisecond = (remainingSeconds - second) / SECONDS_PER_MILLISECOND; + + // Julian dates are noon-based. + hour += 12; + if (hour > 23) hour -= 24; + + // `toGregorianDate` adds a leap second back and `toDate` takes it off + // again, so the second before it stands for it. + return Date.UTC(year, month - 1, day, hour, minute, second, millisecond); +} diff --git a/src/geo/julian.test.mjs b/src/geo/julian.test.mjs new file mode 100644 index 000000000..88bf142f1 --- /dev/null +++ b/src/geo/julian.test.mjs @@ -0,0 +1,102 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import * as Cesium from 'cesium'; +import { + addSeconds, + cloneJulian, + compareJulian, + computeTaiMinusUtc, + julianFromEpochMs, + julianLessThan, + julianLessThanOrEquals, + julianNow, + julianToEpochMs, + secondsDifference, + totalDays, +} from './julian.js'; + +const { JulianDate } = Cesium; + +// Leap-second edges, the noon split, a far past and present-day instants. +const TIMES = [ + 0, + Date.UTC(1971, 11, 31, 23, 59, 59, 999), + Date.UTC(1972, 0, 1), + Date.UTC(2016, 11, 31, 23, 59, 59, 500), + Date.UTC(2017, 0, 1), + Date.UTC(2017, 0, 1, 0, 0, 0, 1), + Date.UTC(2026, 10, 7, 11, 59, 59, 999), + Date.UTC(2026, 10, 7, 12), + Date.UTC(2026, 10, 7, 12, 0, 0, 1), + Date.UTC(2026, 10, 7, 18, 31, 7, 123), + Date.UTC(1950, 5, 1, 3, 4, 5, 6), + 1_789_123_456_789, +]; + +const parts = (date) => [date.dayNumber, date.secondsOfDay]; + +test('dates from epoch ms are JulianDate.fromDate, bit for bit', () => { + for (const ms of TIMES) { + const theirs = JulianDate.fromDate(new Date(ms)); + assert.deepEqual(parts(julianFromEpochMs(ms)), parts(theirs), `${ms}`); + const result = {}; + assert.equal(julianFromEpochMs(ms, result), result); + } +}); + +test('epoch ms back from a date is JulianDate.toDate, its leap seconds included', () => { + for (const ms of TIMES) { + const date = JulianDate.fromDate(new Date(ms)); + assert.equal(julianToEpochMs(date), JulianDate.toDate(date).getTime()); + // A round trip is Cesium's too, sub-millisecond rounding included. + assert.equal( + julianToEpochMs(julianFromEpochMs(ms)), + JulianDate.toDate(date).getTime(), + ); + } + // Inside the 2016 leap second (TAI 23:59:60 UTC). + const leap = JulianDate.addSeconds( + JulianDate.fromDate(new Date(Date.UTC(2017, 0, 1))), + -0.5, + new JulianDate(), + ); + assert.equal(julianToEpochMs(leap), JulianDate.toDate(leap).getTime()); + // Fractional seconds a date carries after arithmetic. + for (const seconds of [-3.7, -0.0004, 0.25, 1.333, 86399.9]) { + const date = JulianDate.addSeconds( + JulianDate.fromDate(new Date(TIMES[9])), + seconds, + new JulianDate(), + ); + assert.equal(julianToEpochMs(date), JulianDate.toDate(date).getTime()); + } +}); + +test('arithmetic and comparison are JulianDate’s, on either kind of date', () => { + const a = julianFromEpochMs(TIMES[7]); + const b = JulianDate.fromDate(new Date(TIMES[9])); + for (const seconds of [-90000, -1.5, 0, 0.001, 43200, 172800.25]) { + assert.deepEqual( + parts(addSeconds(a, seconds)), + parts(JulianDate.addSeconds(a, seconds, new JulianDate())), + ); + } + assert.equal(secondsDifference(b, a), JulianDate.secondsDifference(b, a)); + assert.equal(compareJulian(a, b), JulianDate.compare(a, b)); + assert.equal(julianLessThan(a, b), true); + assert.equal(julianLessThan(a, a), false); + assert.equal(julianLessThanOrEquals(a, cloneJulian(a)), true); + assert.equal(totalDays(a), JulianDate.totalDays(a)); + assert.equal(computeTaiMinusUtc(a), JulianDate.computeTaiMinusUtc(a)); + assert.equal(cloneJulian(undefined), undefined); + const into = {}; + assert.equal(cloneJulian(a, into), into); + assert.deepEqual(parts(into), parts(a)); +}); + +test('now is the system time', () => { + const before = Date.now(); + const now = julianToEpochMs(julianNow()); + // A millisecond's round trip may round down by one, as Cesium's does. + assert.ok(now >= before - 1 && now <= Date.now()); +}); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 008beb61b..72dba8e52 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/aircraftMotionRegime.js", "src/data/cctvGizmo.js", "src/data/detection.js", "src/data/focusDeemphasis.js", @@ -17,7 +16,6 @@ "src/data/iconSet.js", "src/data/iconSetPrimitive.js", "src/data/localGeojsonCore.js", - "src/data/motionModel.js", "src/input/dispatcher.js", "src/input/sensorPick.js", "src/layers/cctv/projection.js",