Files
planet/docs/technical/en/earth-frontend-context.md
T
rayd1o 5bfc790dec
ci / backend (push) Has been cancelled
ci / frontend (push) Has been cancelled
release / images (push) Has been cancelled
ci / delivery (push) Has been cancelled
release: bump version to 0.75.0
2026-09-23 21:20:12 +08:00

56 KiB
Raw Blame History

Earth Frontend Context

Surface texture provenance

On 2026-09-21, assets/8k_earth_daymap.jpg was replaced with an 8192×4096 Web derivative of the paired Natural Earth I raster. Its loading path and rendering code remain unchanged. The source is a 16200×8100 EPSG:4326 image; the previous JPEG is preserved byte-for-byte under resources/earth/archive/2026-09-21/. Source/license records, the catalogue versus embedded-version discrepancy, SHA256 hashes, JPEG parameters, and recalculated world-file metadata live in resources/earth/natural-earth-1/. Large originals remain in Git-ignored downloads/earth/, outside the frontend release bundle.

The base-map selector defaults to Original basemap, listed first and saves the source chosen in the display menu. Natural Earth I remains available alongside “Original basemap”, a byte-identical copy of the September 21, 2026 archive; NASA 21K is source archive material only, while runtime delivery stays at one 8K texture. A new source replaces the old GPU texture only after successful loading and releases the old one then; failures retain the old texture and stale responses cannot overwrite the current source. This is a source switch, not an additional rendering layer. The physical texture is JPEG sRGB, does not bake political borders, and detailed boundary alignment is not yet validated. The starfield is restored byte-for-byte to commit 83a10a6c: celestial.js matches that commit, skyTint and skyBrightness are removed, and brightStarOpacity is back to 0.88; star density and color are no longer calibrated. The HD overlay uses a white MeshBasicMaterial with opacity 1 and toneMapped:false, with texture-colors.js centralizing sRGB read/write. The 0.128 path uses encoding plus LinearTosRGB; the 0.160.1 path uses colorSpace plus the normal colorspace fragment. There is no Phong white-light or colored twilight overlay, blue night tint, cameraBoost, or shoulder curve; daylight neutral scaling keeps brightness at or below the source maximum, and dark mode only applies neutral scaling. The original texture asset is unchanged. Natural Earth is intrinsically pale; this does not claim missing detail was restored. Earth still supports the Three 0.128 import-map runtime and frontend package Three 0.160.1 runtime, and WebGL1 derivatives remain enabled for fwidth.

Day/night shading uses a narrow smooth transition centered on the solar horizon (normal dot product ±0.12). The day side is capped at the source brightness; night-side linear illumination is 0.24, rising smoothly to at most 0.60 in source shadows to retain dark ocean and forest detail. Shading uses a neutral scalar without added exposure, colored veils, rendering passes, or textures.

Basemaps and TV channels share hud-select-menu.js for the HUD popover, list, selection mark, keyboard navigation, and positioning; tv-source-menu.js only adapts channel copy. Basemaps disable search, pagination, and counts. The trigger owner identifies popover clicks as internal to the mobile drawer. This document describes the current real structure of the Earth display frontend. The focus is on helping future changes to the HUD, layers, media panel, real terrain, and BGP visualization avoid repeating past structural and state-sync pitfalls.

Related references:

Current Goal

The Earth frontend is not an ordinary admin page — it is an independent large-screen display frontend. Current product goals:

  • Maintain the spatial depth and readability of the globe view
  • Keep HUD, layers, media panel, BGP, satellites, cables, and similar elements in a unified interaction model
  • Clearly represent states like loading, enabled, hidden, and locked

Current Entry Point

React route entry:

The current approach is simple:

  • The React page only provides a full-screen iframe
  • The actual Earth application runs at:

Earth frontend is essentially a standalone static application under public/earth.

Current File Layers

1. Page Entry and Structure

Responsibilities:

  • Base HUD DOM
  • Layer panel
  • Media panel
  • Toolbar
  • Settings dialog
  • Legacy element ID compatibility

2. Main Runtime

Responsibilities:

  • Globe initialization
  • Three.js scene assembly
  • Data loading and refresh
  • Layer module integration
  • Earth-level state synchronization

Earth treats /ws earth_updates as refresh hints only; real data is fetched again from /api/v1/visualization/.... Backend database-driven refresh now has the listener clear cache and broadcast directly instead of going through the default earth_refresh job queue. After database_changed, the frontend applies the per-layer clear_then_reload, reload, or delta strategy. clear_then_reload must clear Three.js objects before a no-store refetch, and summary is only a consistency check, not a reason to skip a layer reload when the count is 0. See Data Jobs and Outbox Architecture for the technical pipeline and Business Architecture and Data Flows for business data flows.

3. Earth Control Layer

Responsibilities:

  • Toolbar interaction
  • Layer panel interaction
  • Rotation / zoom / layout
  • HUD panel drag
  • Layer toggle state machine
  • Earth settings read, persist, and reset

This is currently the most critical UI control entry point for the Earth frontend.

Earth settings are now grouped by data-settings-tab and data-settings-tab-panel. Desktop and mobile share the same category semantics: Runtime, Display, Panels, Motion, Shortcuts, and System. When adding a setting, first choose its category, then add the DOM, persistence field, and restore logic; do not keep growing one long undifferentiated panel.

Earth runs inside an independent iframe / static application, so it cannot directly reuse React Admin's react-i18next context. public/earth uses its own i18n.js runtime to read and write the global planet-locale, while keeping the legacy docs-lang in sync. This keeps Docs, the console, and Earth on the same language preference. The language switch belongs in the Settings System tab, and desktop/mobile both use the same data-earth-locale buttons; do not put language selection into layer, display, or runtime-mode settings.

The news category selector in Display reuses the same chip-selector pattern as Cruise Modules. It only filters news categories for the current browser on the Earth frontend. It does not toggle layers, basemap, boundaries, TV, data points, BGP, vessels, satellites, or compute centers; those remain owned by the layer panel, media panel, and admin configuration. controls.js persists only shared.newsCategoryFilters and broadcasts earth:news-category-filters-change; news.js sends the selected categories and current locale to /api/v1/news/earth-feed?categories=...&locale=..., so Web and UE clients share the same backend category filtering path.

In English mode, Earth news must render only English title/summary text. Chinese source items without en-US localization are filtered from the visible cards/ticker/cruise until the backend enrichment finishes, and source/feed labels fall back to English-safe names instead of rendering Chinese labels.

The news panel, ticker, and news cruise must consume items / cruise_items from the same /api/v1/news/earth-feed response instead of keeping separate regional caches. news.js builds a refresh request key from region, category, source, and limit; only concurrent requests with the same key reuse the promise, and stale responses from an older region are dropped by token. Source filtering is also region-scoped: when the user moves from Asia Pacific to Europe or another region, source IDs saved for the old region must not be appended to the next fetch. After the new payload arrives, the saved source list is intersected with the available sources; if the intersection is empty, the current region falls back to all available sources. This keeps the ticker, panel, and cruise cards aligned after region switches.

Shortcut configuration is a device-local preference owned by controls.js: read, capture, enable/disable, and reset all stay in the Earth frontend. It should not be written to backend user settings and should not affect other browsers. New shortcuts must provide a default key, display label, disabled/enabled state, and reset path instead of being hard-coded only in a keydown handler.

4. UI and Status Messages

Responsibilities:

  • Loading panel
  • Status message
  • Tooltip / error / cleanup logic

5. Motion Capture Control Adapter

Responsibilities:

  • Act as the Motion Provider manager for both browser_camera and motion_agent.
  • Use browser getUserMedia plus local MediaPipe recognition by default; advanced setups can connect to the local Motion Capture Agent WebSocket.
  • Handle browser camera permission/secure-context errors, plus Agent disconnects, reconnects, status, and heartbeat messages.
  • Filter low-confidence and overly repeated gesture events.
  • Map rotate_left, rotate_right, rotate_up, rotate_down, zoom_in, zoom_out, focus_prev, focus_next, layer_prev, layer_next, and confirm to the action entry points exposed by main.js.
  • Parse skeleton debug events and dispatch earth:motion-debug-frame.

Gesture recognition may run locally in the browser or inside the local Agent, but neither path sends realtime camera frames to the SaaS cloud. main.js exposes rotation, zoom, target focus, layer switching, and confirm entry points, plus a window.__planetEarth.motion debug entry. The adapter starts only when ?motion=1 is present, browser local storage contains planet-earth-motion-control-enabled=true, or Earth settings enable Motion Debug Mode. shared.motionEnabledGestures stores the user-approved gesture whitelist; the browser filters locally, and Motion Agent mode also synchronizes it through set_enabled_gestures.

motion-debug-panel.js owns the debug panel. It listens for earth:motion-debug-frame and draws normalized skeleton joints and bones on a canvas. The Browser Camera provider also emits earth:motion-debug-video-source with the local <video> element so the panel can show a local preview behind the skeleton; shared.motionDebugSkeletonOnly switches the panel back to skeleton-only rendering. Stop Matching Gestures dispatches earth:motion-recognition-pause, which suppresses gesture execution while video and skeleton drawing continue. Unmatched skeletons are red; matched gestures turn green and display the gesture name. Settings are persisted under shared.motionDebugEnabled, shared.motionProvider, shared.motionDebugSkeletonOnly, and shared.motionEnabledGestures in planet.earth.settings.v2; the switch, provider selector, and gesture whitelist reserve data-gatekeeper-permission="earth.motion_debug".

The Browser Camera provider's gesture pipeline lives in recognizeGesture() inside motion-browser-provider.js. Detectors are evaluated in this order, first match wins:

  1. getZoomTrend (trend zoom) — derived from the per-frame change in Math.abs(rightWrist.x - leftWrist.x). Both wrists must cross the noise floor (ZOOM_TREND_MIN_WRIST_DELTA = 0.010) and stay within ZOOM_TREND_HEIGHT_TOLERANCE of each other vertically. Growing span → zoom_in, shrinking span → zoom_out. Trend has highest priority so mid-motion frames cannot be hijacked by the layer/focus/rotate detectors.
  2. getZoomHoldPose (sustained zoom) — after motion stops, keeps emitting zoom_in while the wrists stay at chest level or above with span > ZOOM_HOLD_SPREAD_FACTOR × shoulderWidth (default 1.30), and zoom_out while elbows sit visibly outward and span < ZOOM_HOLD_CLOSE_FACTOR × shoulderWidth (default 0.85).
  3. layer / focus — left-wrist raise + vertical motion fires layer_prev/next; head tilt fires focus_prev/next.
  4. getRightArmPattern (single-arm rotate) — only considered when both !isZoomCandidatePose(...) and isLeftArmAtRest(...) hold. isLeftArmAtRest requires the left wrist to hang clearly below the shoulder line (≥ 0.13) and both left elbow and left wrist to stay near the body — any ambiguous left-arm posture (mid-spread, raised, held at chest) blocks single-arm rotate.

Two non-obvious decisions worth preserving:

  • Mirror-safe: all zoom checks use Math.abs(rightWrist.x - leftWrist.x) and never rely on per-side x direction. getUserMedia returns the raw camera feed without horizontal flip, so a subject's anatomical left arm appears on the image right. A direction-based detector (e.g. "left wrist moves left, right wrist moves right") inverts on non-mirrored feeds — span-based detection is invariant.
  • Continuous vs. discrete: rotate, layer, focus, and confirm go through applyPoseLatch, which emits each gesture once until the pose returns to neutral (one wave = one rotation step). Zoom intentionally bypasses the latch and re-matches every frame; downstream GESTURE_POLICIES.zoom_in/out.cooldownMs = 120 rate-limits to ~8 emits/sec, so holding a spread pose keeps zooming in until the user changes their pose. Do not reuse the latch for zoom — that semantic difference is the point.

presentation-controller.js is the new Presentation layer. In the first stage only Motion uses it: motion-cruise-adapter.js uses a persistent presentation that reuses the cruise fixed-card placement and connector, but mouse movement does not auto-hide the card. The connector recalculates source and target anchors every frame so dragged cards, globe rotation, and moving targets stay connected. BGP/News still use the existing CruiseSequencer auto-advance path to preserve the old cruise experience.

6. Globe and Terrain

Responsibilities:

  • Globe sphere, cloud layer, atmosphere
  • Real terrain mesh
  • Terrain tile fetch, decode, displacement, and shading
  • Whole-globe land/ocean and border base overlays

The Earth surface is a stack of near-concentric shells, not a single mesh. The base sphere and HD texture overlay in earth.js, plus the land/ocean base in country-boundaries.js, need explicit radius separation. At far zoom, GPU depth precision drops; neighboring shells that are too close can z-fight and show black flicker blocks or snow. The current stable spacing is landAltitudeOffset = 0.32 and EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48 for the HD texture shell. Country borders, coastlines, claim lines, and country hover lines must use that same HD texture shell radius so they do not drift relative to the texture while the globe rotates. When adding or adjusting whole-globe surface overlays, update Earth Render Layer Order and verify at 50% zoom.

7. Layer Modules

  • satellites.js
  • cables.js
  • vessels.js
  • bgp.js
  • bgp-cruise-adapter.js
  • compute-centers.js renders supercomputer and GPU-cluster markers. The backend renders compute centers only from source-provided coordinates or compute_center_locations dimension-table coordinates during startup; manual candidate collection can query ROR and Nominatim/OpenStreetMap, and the layer keeps the ? badge for unconfirmed positions while the details card shows precision, confidence, source notes, and verification date.
  • country-boundaries.js

Each module is responsible for its own:

  • Data fetching
  • Three.js mesh creation and update
  • State tracking (loaded, visible, hover, locked)
  • Self-cleanup (dispose on scene destroy)

tv.js owns the live / aggregation-news tabs inside media-panel. Toolbar open and tab-switch actions write back through earth:tv-visibility-change and earth:tv-tab-change: panel visibility remains viewport-scoped at views.<scope>.panelVisibility.media-panel, while the active tab is stored at shared.mediaPanelActiveTab. Refreshing the page therefore restores the user's last live/news state. Temporary hides from closeTransientMobileOverlays() carry persist:false and do not overwrite the preference.

tv-source-menu.js reuses HUD and legend-list styling in a popover with search, a scrolling list, and a fixed count footer. tv.js requests 50 entries from /api/v1/tv/streams and caches channel details; search runs against the complete backend catalog, and pagination uses next_offset. Cancellation and a request generation counter prevent stale results from replacing a newer search. Catalog refresh uses selected_id to restore a channel outside the first page.

tv-playback-policy.js owns live recovery decisions: all non-fatal HLS events remain with the player, while fatal network/media failures receive at most three recovery attempts. Switching requires automatic fallback to be enabled, no explicit user channel selection, and an embeddable backup. Async callbacks in tv.js verify player identity and channel; native video errors no longer bypass HLS recovery. tv_streams.py replaces the old bundled CCTV-4 CDRM URL, including saved copies, with WCETV's America-edition HLS stream, names the edition explicitly, and preserves custom streams. An HTTP success does not establish video decodability.

Sources with verified CORS support may explicitly set use_proxy:false for direct browser playback without segment forwarding. Other sources continue to use the TV proxy by default. The bundled WCETV source uses direct playback.

Source information reuses createHUDPanel and its existing 0.22-second CSS transition. The shared controller measures content into --hud-body-content-height, avoiding the non-interpolable change from max-height: none to zero. ResizeObserver updates content measurements and compensates the top position of upward-expanding dragged panels during animation, keeping their bottom edge fixed without disabling the body transition. The shell's top transition is paused during compensation to prevent drift from double interpolation.

brand.js manages Earth HUD brand resources. Static assets provide the default brand; runtime overrides come from /api/v1/earth/brand, and uploaded images are served from /earth-brand-assets/.... The frontend must treat logo/title images and text fallback separately: if an image fails, show the text title; if text fields are empty, rely on backend defaults so the HUD brand area never renders blank. The console Earth Content page owns saving and resetting brand configuration; the Earth frontend only consumes it.

about.js manages the About card inside Earth settings. Frontend defaults remain as a fallback, while runtime content is loaded from /api/v1/earth/about. If the request fails or fields are missing, the renderer must fall back per field so the settings page never renders an empty card. Admin exposes an Earth Content About tab; saving uses PUT /api/v1/earth/about, and restoring defaults uses DELETE /api/v1/earth/about.

oobe.js manages the first-run Earth initialization guide. OOBE visibility must be driven by /api/v1/earth/oobe-status and its ready field, not by localStorage. localStorage may only store a short-lived "skip on this browser" flag; if the backend reports ready: true, logout, cleared browser storage, or a different browser must not show OOBE again. Desktop uses a dark starfield scrim and glass startup panel, while mobile uses a bottom sheet and respects prefers-reduced-motion.

The Admin Earth Content page must preserve runtime semantics:

  • Brand: brand preview should use the same dark starfield background, size, spacing, logo/title rendering, and text fallback as the Earth HUD top-left brand block, not a generic form preview.
  • About: configures the About card in Earth settings, including logo, kicker, title, version, description, and metadata items. Earth runtime reads /earth/about and falls back to defaults on failure.
  • Boundary Precision: build boundary, refresh status, and restore defaults belong inside this section, not in the global page toolbar.
  • TV: the list distinguishes built-in, collected, and custom sources. Card state represents enabled, disabled, draft, or error. Built-in sources cannot be deleted; collected and custom sources can. A new live source only enters draft state after the plus button is clicked; save persists it into the list, while cancel destroys the draft.
  • Basemap, Layer Resources, 3D Models, and News Anchor Strategy: if backend capability is not available yet, the console should show an explicit pending state instead of mixing those items into TV or brand configuration.

TV preview should reuse the Earth runtime live-card structure and state labels as closely as possible so built-in markers, live loading state, stream source, region, and language match what users see on Earth.

The compute-center layer row has a notification badge for GeoJSON unresolved records. The badge means "no trustworthy coordinates, cannot render on the globe"; it is different from the ? marker drawn on already positioned but unconfirmed compute centers. Clicking the badge opens a fixed info card beside the layer panel. Row-level 采集 fetches candidates only. Header-level 一键采用 processes the queue top-to-bottom, saves the highest-confidence valid candidate, removes successful rows, renumbers the list, and dispatches earth:compute-center-unresolved-count-change so the badge updates immediately. When the batch ends, earth:compute-center-location-saved refreshes the real layer.

Location candidate state in the details card is cached in info-card.js by entityType:entityId. If the user closes the details card or unresolved queue and reopens the same compute center / BGP collector, previously collected candidates and status text are restored. Header-level 一键采用 prefers cached candidates, avoiding repeated online geocoding or LLM factcheck calls. After a location is saved, that entity's candidate list is cleared to a "refreshing layer" status so stale candidates do not keep misleading the user.

runUnresolvedComputeCenterBatch() owns a queue of entity contexts rather than panel DOM. locationCollectStateCache retains candidates, progress, and save results so rebuilt cards can hydrate the current state. earth:compute-center-location-batch-change updates the badge, savedCandidate excludes completed entries, and a ✓ entry remains after completion. Queue state lives only in the current Earth page: refresh, close, or route navigation interrupts unfinished work, while saved coordinates remain authoritative in the backend.

The 预览 / 保存 buttons on each candidate row use a single delegated click handler per candidate root (the [data-collect-cache-key] block in the details card, or [data-unresolved-item] in the unresolved queue), guarded by a data-candidate-actions-bound flag so it cannot be double-bound. Direct pointerup / click listeners on individual buttons and overlapping delegated handlers were removed. Candidate objects are no longer JSON-stringified into an HTML attribute and parsed back; buttons only carry data-candidate-index, and the handler resolves the candidate object from a module-level Map keyed by cache-key. This removes the entire class of failures caused by HTML entity escaping of & / < / " in candidate fields. Clicking 预览 dispatches earth:preview-location-candidate; main.js's previewLocationCandidate() calls showComputeCenterLocationPreview(), which attaches a hollow breathing-ring sprite pair at the candidate coordinates (visually mirroring the BGP event ring) and focuses the camera on the candidate. Previewing another candidate replaces the ring; saving clears it and spawnSavedComputeCenterLocation() immediately spawns the formal compute-center interactable. Note that main.js has no module-level earth variable — every location-save / preview handler must call const earth = getEarth(); first, otherwise the event handler throws a ReferenceError that the surrounding .catch swallows, producing the failure mode where the button "does nothing".

The earth:compute-center-location-saved reconciliation pipeline is deliberately silent on background-refresh failures. spawnComputeCenterAfterLocationSave() already presents the success toast and locked state; refreshComputeCentersAfterLocationSave() only reloads backend data when the scene is ready and no longer emits its own 已保存 toast. handleComputeCenterLocationSaved() runs refresh in the background after a successful spawn; only when spawn returns null (scene not ready) or throws does refresh take over the success toast. A refresh error is only console.warn'd — it must never surface as a 保存失败 message, because the save itself succeeded and the refresh is a follow-up sync.

AIS Vessel Layer

The vessel layer uses /api/v1/vessels/snapshot for a global current-state snapshot. Earth sends the global bbox [-180,-85.05112878,180,85.05112878], the current zoom, and limit=3000 when the layer opens. It does not repeatedly refetch by camera viewport, and globe rotation or zoom does not reconnect a vessel WebSocket subscription.

The backend snapshot endpoint still requires bbox, but the Earth runtime treats it as the global current-state entry point. It reads vessel_current_state, returning one latest point per MMSI within the freshness window, and no longer scans or aggregates historical ais_raw_observations for the display layer. Raw AIS history remains available for tracks, audit, and situational analysis.

Vessel markers are rendered through createInteractableLayer() as batched THREE.Points, with cluster and avoidance explicitly disabled. Dense waterways may overlap. Dragging or inertial rotation skips hover picking; normal hover uses screen-space nearest-point picking. Do not reconnect vessels to dynamic screen clustering or per-frame Points rebuilds, because those interaction costs are what make a 3000-marker layer feel heavy.

AISStream and BarentsWatch share the /ws vessels delta channel. Earth subscribes with scope: "global" on its existing WebSocket, without changing subscriptions as the camera moves. The backend coalesces notifications by MMSI for one second, then reads confirmed vessel_current_state rows. Frames contain at most 1000 items; further frames carry the remaining vessels rather than truncating them. Raw source messages must not overwrite confirmed client positions. Deleting current-state rows also produces MMSI-based remove notifications.

The frontend coalesces short bursts per MMSI and uses Interactable.updateItems() to update position and color buffers in place. Heading-bucket changes touch only affected buckets, growing capacity when needed. Existing marker identities, selections, and materials survive. Initial entry, reconnects, deletion hints, and the minute reconciliation still use snapshots without first clearing the layer. A bounded snapshot must not treat truncated vessels as deleted, and older responses must not overwrite newer stream updates or removals received while the request was in flight. Snapshots include query-start generated_at; it is compared with stream frame time to prevent stale cached snapshots from rolling back new vessels or removals.

Ordinary vessel writes use the delta strategy on earth_updates; while the dedicated channel is connected, they no longer request whole-layer reloads. Deletion or disconnected reconciliation uses reload while reusing existing objects. Hiding the layer unsubscribes and clears queued changes. Tracks, conflicts, and audit data continue through the single-vessel historical APIs.

The legacy /api/v1/visualization/geo/vessels route has been removed. Frontend code should keep using PATHS.vesselsApi and can verify the current-state path through diagnostics.source == "vessel_current_state".

The new layer API family is /api/v1/layers/*, which separates map rendering payloads from aggregate panel statistics. Layer requests must include bbox, zoom, and a bounded limit; responses include visible_count, returned_count, and diagnostics, where degraded, truncated, and limit_clamped are the frontend signals for fallback UI. Right-side aggregate panels should not sum the layer response. They should read /api/v1/data-products or /api/v1/data-products/{product_id}/status, because those statistics stay global and do not change with the viewport.

Vessel color and vessel type text must use the same normalized classification. vessels.js derives type from both vessel_type_name and the AIS numeric vessel_type code; that type drives marker color. It also derives vessel_type_display, which main.js uses for the info card, hover summary, and search result subtitle. Do not make the info card read only the raw vessel_type_name, because AISStream can provide a numeric type while the raw name is still Other.

AISStream PositionReport messages commonly carry live position and MetaData.ShipName, while vessel type usually comes from lower-frequency ShipStaticData.Type. The backend normalizes MetaData.ShipName into the vessel name and maps numeric type codes into Cargo / Tanker / Passenger / Fishing / Military where available. Missing type detail should wait for a static AIS message or the planned vessel profile enrichment; the frontend should not invent a more specific type.

9. Cruise Mode

The cruise sequencer handles generic logic: current target, queue order, camera focus, and dwell / hide / switch. Business modules supply target queues and content — they should not contain camera control logic.

10. Constants

All material, layer, satellite, BGP, cable, terrain, celestial, and other style parameters are maintained here. Do not scatter magic numbers in module files.

Render hot paths

cable-batches.js batches the complete cable and landing-point sets. cables.js still owns original business objects, picking, occlusion, and selection state. Do not make these interaction proxies draw individually again or return a render batch as the detail-card business object.

Satellite breathing runs in vertex shaders. satellite-position-worker.js moves full SGP4 position and initial trail calculations off the main thread; the main thread applies snapshots to interaction coordinates and render buffers. satellite-propagation.js supplies the same mathematics to the Worker, predicted orbits, and synchronous fallback. Reload, clear, and altitude changes must terminate prior work so stale snapshots cannot resurrect cleared layers.

The i18n.js MutationObserver translates only added subtrees, changed text, or changed attributes. Local clocks, status labels, and download progress must not synchronize all locale controls. Global locale synchronization belongs to initialization, locale changes, or subtrees containing new locale controls.

Current Style Layers

CSS files in frontend/public/earth/css/ each correspond to a specific component scope. Do not write global Earth styles into base.css unless they genuinely apply to everything.

Current Layer Toggle State Semantics

data-status-target

Layer toggle buttons use data-status-target attributes to link button state to layer state. The state machine in controls.js handles:

  • loading: showing the loading indicator
  • enabled: layer is active
  • hidden: layer is hidden
  • error: layer failed to load

This is the canonical way to synchronize button visual state with actual layer state. Do not maintain separate boolean flags for button display.

Terrain should not block startup when it is not the restored visible layer. After deferred layer visibility settings are applied, controls.js schedules scheduleTerrainPrefetch() only when HD texture is enabled, terrain is not ready, and no prefetch is already running. The prefetch uses setTimeout plus requestIdleCallback so cloud, HD texture, and startup layer work keep first-screen priority.

Current Settings Persistence

Earth settings are stored in localStorage. The key is typically a namespaced string defined in constants.js. controls.js handles read, write, and reset.

Settings that affect visual layers and surface interaction (terrain opacity, day/night mode, satellite display style, satellite idle breathing, real satellite altitude, track display, hover tooltip mode, etc.) are read during initialization and applied immediately.

Language preference is the exception: Earth language is not a private planet.earth.settings.v2 field. It shares planet-locale with Docs/Admin. When language changes, i18n.js updates document.documentElement.lang, translates static and dynamically inserted DOM, synchronizes language button state, and passes the current locale to news requests. The news module refreshes after a language change so an English UI does not reuse a Chinese news payload.

The surface hover tooltip preference is persisted by controls.js as shared.surfaceHoverInfoMode, while main.js composes the actual tooltip in the globe-surface hover branch. Country shows country details only when a country polygon is hit and stays silent over ocean; Position shows latitude, longitude, and sampled terrain elevation and clears country-boundary hover; Full shows country + position on land and position over ocean.

The real satellite altitude preference is persisted by controls.js, while the rendering state lives in satellites.js. When enabled, the real radius from SGP4 is compressed logarithmically into the current Earth visual radius range. When disabled, satellite dots, trails, and predicted orbits all return to the legacy same-sphere display. Toggling this setting must refresh satellite positions and clear trail buffers so a trail never mixes both height models. maxRealAltitudeOffset = 25 is a visual cap tuned for the current camera and earthRadius = 100: GEO / MEO remain clearly higher than LEO, but the highest orbits stay within about 25% beyond the globe radius so selection targets, red trails, and the globe do not feel disconnected.

SGP4 propagation returns an inertial-frame position, so it must not be drawn directly as Earth-fixed longitude / latitude. satellites.js uses gstime to convert ECI/TEME positions to ECF, then maps that result into the same Three.js axes as latLonToVector3(). Satellite dots and short trails use Earth-fixed coordinates for each sample time, representing the object's current position relative to the globe surface. The locked predicted orbit uses the gstime from the lock moment for the whole future orbit, projecting the inertial orbit plane onto the current globe pose; that keeps the line closed and keeps the visual orbit inclination aligned with the details card. Fallback predicted orbits must also use a real RAAN + inclination orbital-plane formula, not treat inclination as a constant latitude.

Boundary precision is stored separately by country-boundaries.js under planet.earth.boundaries.highPrecisionEnabled. When high precision is off, Earth keeps using the bundled low-precision countries-admin0.min.geojson fallback even if high-precision manifest/PMTiles files exist locally. When high precision is on but the artifact is missing, the Earth toolbar settings call /api/v1/earth/boundaries/build and poll progress. After success, reloadCountryBoundaries() hot-swaps the boundary layer without refreshing the page. Boundary hover is independent from interactable hover: a country polygon remains highlighted whenever the surface coordinate is inside it, while the tooltip can still prioritize a satellite, vessel, BGP marker, or other interactable.

Current Terrain Pipeline

  1. terrain.js creates a sphere geometry with enough segments
  2. On load, fetches Terrarium-format elevation tiles from the backend
  3. Decodes R/G/B into elevation values
  4. Displaces vertex positions radially based on elevation
  5. Applies a vertex alpha that fades terrain edges at coastlines
  6. Terrain writes to the scene as a mesh above the HD texture layer

When HD texture is off, terrain is temporarily hidden and its state is remembered. When HD texture comes back on, terrain restores its prior visibility.

Terrain tile fetching is batched. terrain.js deduplicates required Terrarium tile keys and sends chunks sized by TERRAIN_CONFIG.batchRequestSize to /api/v1/visualization/terrain/terrarium/batch. The backend proxies S3 Terrarium tiles with an in-memory LRU cache, per-batch deduplication, and bounded concurrency. The single tile endpoint remains for fallback paths and browser cache semantics.

Current High-Frequency Risk Points

1. Visual State and Business State Out of Sync

The most common class of Earth bugs:

  • Button shows "loaded," but layer has no objects rendered
  • Button shows "hidden," but objects are still visible
  • Loading ended, but button still looks like it hasn't

All future changes must prioritize checking state sync.

2. HUD Layout: Check Structure First, Not CSS Patches

Earth HUD has repeatedly experienced:

  • Panel compressed to a sliver
  • Markdown content clipped
  • Tabs/iframe content consumed by overflow: hidden

Inspection order:

  1. Who is responsible for height
  2. Who is responsible for scrolling
  3. Which layer is doing the clipping

Do not immediately add overflow: hidden or extra wrapper layers.

3. Transitional Paths Must Be Closed Off

Earth has gone through multiple rounds of HUD, toolbar, and media panel refactoring, making it easy to accumulate:

  • Old helpers
  • Old classes
  • Old fallback logic
  • Deprecated variants

After each major feature is complete, do a cleanup pass.

4. Cruise Mode and Business Events Must Not Be Deeply Coupled

The correct boundary:

  • The generic cruise layer only knows:
    • Current target
    • Queue order
    • Camera focus
    • Dwell / hide / switch
  • Business modules only supply:
    • Target queues
    • Focus coordinates
    • Card content
    • Highlight / layer side effects

If future cable, satellite, or news cruise is added, do not copy a new set of main.js state variables. Instead reuse:

View Control Feedback

controls.js owns the Earth zoom state, and every zoom entry point must ultimately call setZoomLevel() to write the camera distance. Do not write camera.position.z from other modules, or the zoom percentage, drag sensitivity, and Interactable clustering thresholds will diverge again.

globe-navigation.js maps zoom to sqrt(R² + (D₀² - R²) / zoom²) with minimum surface clearance and the matching inverse. The 100% camera pose remains unchanged; 500% stays outside the globe. Mouse and single-touch dragging use ray/sphere intersections and quaternion rotation to keep the grabbed surface under the pointer, without an empirical sensitivity multiplier or frame-by-frame catch-up. Auto-rotation is suspended during dragging and pinching. Release inertia follows the measured axis; paused releases and cancellation do not fling. Returning from a pinch to one finger rebases the grab point. Click suppression uses displacement from pointer-down, including slow drags.

Interactable clustering is selected per layer through cluster.strategy. stable-spherical uses discrete zoom bands and local 3D bucket clustering, so BGP, compute centers, and Earth interactables do not regroup while the globe rotates inside the same band. dynamic-screen keeps projection-based clustering, and none disables it. Vessels explicitly disable clustering and avoidance so incremental updates do not rebuild cluster topology. Stable cluster dots stay rigidly aligned to their 3D centroid projection and do not participate in 2D avoidance. See Earth Interactable Clustering for strategy configuration and tuning.

Wheel input has two paths. Traditional mouse wheels keep the 10% step and short animation, using wheelZoomTarget as the logical base for continuous wheel input. Trackpads and high-precision wheels use the pixel delta for continuous zoom and call setZoomLevel() directly instead of passing through the 10% stepped animation. The trackpad path also filters a short-window, old-direction residual delta after a real direction change so inertia tails do not pull a just-reversed zoom back in the previous direction.

The gesture capsule updates at most once every 90ms and fades after 760ms. It is view feedback, not data loading progress, and should not be written into layer loading state.

main.js only calls setZoomLevel() and showZoomStatusCapsule() for pinch zoom and motion zoom. Mouse wheel and zoom-button capsule feedback should stay in controls.js so the same zoom feedback does not spread across modules.

For future Earth changes:

  1. First identify what you're changing:
    • Three.js rendering layer
    • HUD structure layer
    • Layer state layer
    • Panel content layer
  2. If involving layer buttons, connect to the unified state machine
  3. If involving visibility toggle, check whether tooltip / legend / info-card / lock all close together
  4. If involving panel layout, check structure before touching CSS

Current Boundary with the Console Frontend

The Earth frontend and the console frontend are not the same UI system:

  • Console frontend: React + Tactile UI / Radix primitives / lucide workbench
  • Earth frontend: native HUD + Three.js display under public/earth

Therefore:

  • Earth should not directly reuse Ant Table / AppLayout semantics
  • The console should not copy Earth HUD animations and glass-layer design language

For console structure, see:

Spatial compute cards

compute-topic.js owns periods, measures, participants, and evidence. compute_catalog.py supplies canonical names, picker groups, and regional label anchors for 45 currently registered participants. Unknown historical values remain missing. APIs are no longer limited to CN/US. Group labels never become overlapping statistical denominators, and regional coordinates must not become facility locations.

Earth's existing Roboto Condensed face is now served locally from assets/fonts/, with its source and license in that directory and the shared declaration in css/fonts.css. The remote Google Fonts stylesheet no longer blocks the page; font family and weights are preserved.

spatial-callouts.js delegates layout to spatial-callout-controller.js and reuses CalloutConnector with stable region IDs. Layout is event-driven and retains valid old rectangles while work is pending; the projected source line follows the globe continuously. The layout reference is the direction of the actual source exit point, so a card stays near the object side instead of being pulled from a top-left geographic point to an opposite corner. Neighboring same-sector placements, shorter connectors, and fewer crossings are preferred; the solver may exchange free positions for at most three rounds rather than relayout everything each frame. In fullscreen Earth, nearby foreground positions are allowed so cards of normal size do not cross the whole globe merely to avoid it. In slow mode, sustained direction drift or connector crossings must persist for 1.8 seconds before proposing a joint reflow. Automatic proposals are at least 8 seconds apart and need an improvement of at least 18% plus a minimum absolute gain. Manual/inertial input retains the 72ms/12px response budget. Expansion and manual placement grant 12 seconds of reading time; hover, keyboard focus and dragging continue to lock a card, while residual pointer focus does not lock it forever. Manual placement is a preference: after its hold, automatic repair requires at least 45 degrees of source direction change. Restored positions are not permanent pins. Rear connectors retain the globe-outline cue without changing card identity. Local position/size persistence and reset-to-auto are part of the controller. A ResizeObserver handles resizing and collapse; configuration and source windows retain shared drag handles.

Object presentation is shared through PresentationController and the new object-callout anchor/layout path. A click on a BGP, compute, vessel, satellite, or cable object draws the connector before placing the adjacent card. The source anchor begins at the actual click or original region label, then follows a visible highlight geometry sample as rotation approaches occlusion. The stable layoutReferencePoint is derived from the actual connector exit direction, so packDirectionalEdgeCallouts keeps cards on the corresponding screen edge and leaves the globe's center open; a card may move inward only when that edge lane is unavailable, and it may never cover its own connector exit point. The bounded joint assignment considers up to 24 beam states and 32 candidates, avoids existing HUD rectangles, then allows at most three safe exchanges to reduce directional crossings; the previous solver remains a fallback and the work is not a full relayout every frame. A slow source-direction gate also checks whether the actual card target reverses more than 90 degrees from the source before committing a change. Manual drag and hover locks take priority. The source point itself remains a per-frame visual connection target; fixed objects track live positions while cards remain draggable. Rear-side objects retain a globe-outline direction cue, a subdued connector, and a hollow source point; these are orientation guides rather than geographic points. Country candidates are capped at 96 with a hard limit of 128 and cached, so GeoJSON is not scanned every frame. Compute cards keep their original point independent from dynamic source-point movement, and the shared card endpoint slides along the obstacle perimeter. Cable presentation prefers the true ray-hit local point, then samples highlighted geometry by cableId. Mobile keeps the existing mini popup and opens drawer details. A stale asynchronous presentation must never dismiss a newer selection.

configVisible and cardsEnabled are separate. X/Escape closes only configuration; disabling the switch releases connectors and restores the previous map query/layer state. Configuration and source windows bind HUD typography directly so reparenting cannot enlarge their text. The main card presents the selected compute metric as a large share percentage or an absolute value with unit, observation year, historical context, and source entry. Missing comparable data is explicit; no empty trend chart is rendered without observations. Facility records and coverage remain complete in the expanded auxiliary area, where sample counts are evidence context rather than a compute value or global coverage rate. Long lists open only when needed. Mobile preserves the same single metric meaning in its accordion. Local position/size persistence and reset-to-auto remain available. Stable DOM, dimensions, and reading state survive updates, and stale responses cannot re-enable cards.

Motion presentation uses the shared main.js input state. Sustained drift or crossings trigger a joint assignment, rather than each card competing independently for leftover slots. callout-region-path.js provides the short connection and terminal stub used both for rendering and intersection scoring. Candidate paths are precomputed and layout states are cloned only after pruning. Existing cards remain visible during planning; queued reflows survive frame throttling.

The shared CalloutConnector calculates polyline length from its points instead of reading getTotalLength() after each SVG write, avoiding repeated synchronous layout during motion. Initial draw animation is retained, so existing cruise presentations receive the same optimization.

On mobile, compute uses a compact regional overview in the existing drawer. Rows are an in-place accordion: tapping the same header collapses it, tapping another collapses the previous row, and at most one expanded card is shown. The expanded card keeps trends, region members, facilities, media, and sources; there is no region subpage, while Settings remains a separate on-demand page. The shared HUD collapsible panel animation is reused and respects reduced motion. Summary loading remains active when map cards are off; enabling cards shares the map loading event and cancels stale requests. Drawer handlers use composedPath() so inner HTML replacement cannot collapse the active row. Facility names remain in a scroll region capped at 240px, with left-aligned wrapping rows and at least 42px touch height.

/series retains source-backed annual observations; the default primary metric is global compute-device scale split into basic, intelligent, and supercomputer capacity for 2020–2023. Reviewed absolute observations are 302 for 2022 (caict2023) and 435 for 2023 (caict2024); Japan's global share is 6%/5%/4%/4% for 2020–2023. Product groups APAC excluding China and Other do not map directly to report Japan or “other”; Europe remains null until membership aligns with the report. Bilateral share keeps a fixed US + China denominator. Missing primary values may show the latest reported year (currently 2023), while an explicit 2026 selection stays missing. Unconfirmed comparability does not produce year-over-year change. /facilities filters and counts unique canonical country codes in successful collection snapshots; coverage counts remain auxiliary, and are not capacity or a global coverage rate. compute_catalog.py groups China, US, Europe, APAC excluding China, and Other, covering 45 canonical country codes; these display groups never become statistical denominators. earth_geography_policy.py shares display ownership with map policy, grouping Taiwan/Hong Kong/Macao source subdivisions under China while retaining source_country. API review metadata is reviewed_at=2026-09-22 with the matching version date. An independent Epoch share mode is not implemented. Innovation differences are supplied only when both CN and US are selected.

Boundary surface attachment

Normal borders, coastlines, claim lines, highlights and landing points use earth-surface.js to share the HD sphere UV-triangle surface. Borders draw after the texture but before landing points. Highlight lines are always transparent-queue objects with depth testing, preventing through-globe display or overpainting markers. Geometry is computed and cached at construction, not reprojected per frame. See the render-layer specification.

News ticker edge fading

A separate pseudo-element paints the ticker background and horizontal rules, fading to full transparency outside the text bounds. The shell has no rectangular backdrop filter, box shadow, or text mask. The region label sizes to its content and the scrolling text follows directly without fading. Alert states change only the gradient rule color so they cannot reintroduce rectangular shadow edges.

Compute cards directly reuse the shared .hud-panel background, border, shadow, and glass treatment. Summary, essentials, and detail areas add no separate black surface. Their headers share inset spacing with the layer panel through .hud-panel__header--inset / .layer-panel-header; primary numbers remain prominent and essential information stays visible.

Saved placement restoration migrates legacy central positions: only old central coordinate locks without the current position marker return to automatic layout, retaining dimensions. Existing edge positions are preserved and versioned. New drags save positionVersion=2 and continue to honor deliberate placement. The existing storage key is retained instead of clearing every personalized position.

First frame and spatial card entrance

earth-runtime-plugin.mjs bundles local Earth modules into content-hashed entries and shared chunks for both development and production. The existing import map still pins third-party versions; relative assets and workers retain the /earth/js/ base. earth-preload.js requests the selected full-size map early. earth-texture-image.js decodes an ImageBitmap asynchronously and transfers that same image to Three.js without resampling or changing texture color/sampling settings. Replaced and destroyed textures release their bitmaps. The full-resolution surface precedes independent concurrent data layers; data refresh retains it. Versioned boundary geometry, picking indexes and claim lines use HTTP caching and parallel requests. The live player engine is imported on demand; media and realtime connections start after the surface frame.

The root attributes data-earth-first-frame-ms and data-earth-surface-ready-ms record navigation-to-render timings. Measure cold and warm caches separately; local warm results are not a guarantee for all first-visit networks.

Positioned cards stay hidden while the shared connector draws for 420 ms, then fade in using the HUD 180 ms opacity timing. Targets remain fixed during drawing; subsequent motion does not replay entrance. Reduced-motion preferences skip this animation.

Object clicks, search focus and gesture confirmation share PresentationController. Cable selection updates selection/legend state without independently opening the card. InfoCard reveal callbacks are versioned so staging or hiding invalidates older callbacks. Connector completion gates card reveal; cancelled cruises no longer hide a newer selection. Object details reuse the regional-card edge candidates and collision scoring, with dimensions measured while staged. Selecting a mobile search result collapses the search drawer so the focused object, connector and compact card remain visible.