@@ -464,6 +429,7 @@ function renderDefaultCardContent(content, config, data) {
let html = '';
for (const field of config.fields) {
+ if (field.omitIfSameAs && data[field.key] === data[field.omitIfSameAs]) continue;
const value = formatInfoCardValue(field, data[field.key]);
const sourceLabel = getFieldSourceLabel(data, field.key);
html += `
@@ -479,10 +445,10 @@ function renderDefaultCardContent(content, config, data) {
}
if (['supercomputer', 'gpu_cluster'].includes(config.className) && data.metadata?.compute_contract === 'v1') {
const metadata = data.metadata;
- const fields = [['精度 / 测量', `${metadata.precision || '—'} / ${metadata.measurement || '—'}`], ['来源状态', metadata.status || '—']];
+ const fields = [['精度 / 测量', `${metadata.precision || '—'} / ${metadata.measurement || '—'}`]];
html += fields.map(([label, value]) => `
`).join('');
if (/^https?:\/\//i.test(metadata.source_url || '')) {
- html += `
`;
}
}
@@ -504,7 +470,7 @@ function renderDefaultCardContent(content, config, data) {
function buildLocationCollectContext(config, data) {
if (!data || typeof data !== 'object') return null;
if (data.metadata?.anonymous || data.historical_snapshot) return null;
- if (config.className === 'supercomputer' || config.className === 'gpu_cluster') {
+ if (isComputeSiteType(config.className)) {
if (!data.source_id) return null;
return {
entityType: 'compute_center',
@@ -1226,14 +1192,7 @@ function renderVesselEnrichmentSection(enrichment) {
if (!enrichment || typeof enrichment !== 'object') return '';
const profile = enrichment.profile;
const media = enrichment.media;
- if (!profile && !media) {
- return `
-
- `;
- }
+ if (!profile && !media) return '';
let inner = '';
if (profile?.payload && typeof profile.payload === 'object') {
inner += renderEnrichmentPayloadRows(profile.payload);
@@ -1249,9 +1208,7 @@ function renderVesselEnrichmentSection(enrichment) {
}
inner += renderEnrichmentMeta('媒体', media);
}
- if (!inner) {
- inner = `
${escapeInfoCardHtml(infoText('船舶资料'))}
@@ -1279,9 +1236,6 @@ function renderEnrichmentMeta(label, record) {
const parts = [];
if (record.source) parts.push(infoText(`来源 ${record.source}`));
if (record.fetched_at) parts.push(infoText(`更新 ${record.fetched_at}`));
- if (record.confidence !== null && record.confidence !== undefined) {
- parts.push(infoText(`置信 ${Number(record.confidence).toFixed(2)}`));
- }
if (!parts.length) return '';
return `
${escapeInfoCardHtml(infoText(label))}: ${escapeInfoCardHtml(parts.join(' · '))}
`;
}
@@ -1299,6 +1253,9 @@ function getMobilePopupTitle(type, data) {
case 'compute_center_unresolved': return infoText('待定位算力中心');
case 'supercomputer': return data.name || infoText('超算');
case 'gpu_cluster': return data.name || infoText('GPU集群');
+ case 'data_center':
+ case 'cloud_center':
+ case 'edge_node': return data.name || infoText(COMPUTE_SITE_TYPES[type].label);
case 'vessel': return data.name || infoText('船只');
default: return infoText('详情');
}
@@ -1315,6 +1272,9 @@ function getMobilePopupSubtitle(type, data) {
case 'compute_center_unresolved': return infoText(`${data?.totalCount || 0} 个待定位`);
case 'supercomputer': return localizeCountryName(data.country) || infoText('超级计算机');
case 'gpu_cluster': return localizeCountryName(data.country) || infoText('GPU集群');
+ case 'data_center':
+ case 'cloud_center':
+ case 'edge_node': return localizeCountryName(data.country) || infoText(COMPUTE_SITE_TYPES[type].label);
case 'vessel': return data.vessel_type || infoText('AIS 船只');
default: return '';
}
@@ -1513,10 +1473,9 @@ const CARD_CONFIG = {
className: 'cable',
fields: [
{ key: 'name', label: '名称' },
- { key: 'owner', label: '所有者' },
{ key: 'status', label: '状态' },
{ key: 'length', label: '长度' },
- { key: 'coords', label: '经纬度' },
+ { key: 'owner', label: '所有者' },
{ key: 'rfs', label: '投入使用' }
]
},
@@ -1538,15 +1497,12 @@ const CARD_CONFIG = {
className: 'satellite',
fields: [
{ key: 'name', label: '名称' },
- { key: 'norad_id', label: 'NORAD ID' },
{ key: 'constellation', label: '星座/分组' },
- { key: 'footprint_capability', label: '覆盖能力' },
- { key: 'current_display', label: '当前显示' },
- { key: 'footprint_model', label: '覆盖模型' },
- { key: 'inclination', label: '倾角', unit: '°' },
- { key: 'period', label: '周期', unit: '分钟' },
+ { key: 'norad_id', label: 'NORAD ID' },
{ key: 'perigee', label: '近地点高度', unit: 'km' },
- { key: 'apogee', label: '远地点高度', unit: 'km' }
+ { key: 'apogee', label: '远地点高度', unit: 'km' },
+ { key: 'inclination', label: '倾角', unit: '°' },
+ { key: 'period', label: '周期', unit: '分钟' }
]
},
bgp: {
@@ -1557,24 +1513,24 @@ const CARD_CONFIG = {
{ key: 'anomaly_type', label: '事件类型' },
{ key: 'severity', label: '严重度' },
{ key: 'status', label: '状态' },
- { key: 'route_change', label: '事件特征' },
- { key: 'prefix', label: '前缀' },
- { key: 'as_path_display', label: '传播路径' },
+ { key: 'impacted_scope', label: '影响区域' },
+ { key: 'created_at', label: '事件时间' },
+ { key: 'summary', label: '摘要' },
{ key: 'origin_asn', label: '涉及 ASN' },
- { key: 'new_origin_asn', label: '关联 ASN' },
+ { key: 'prefix', label: '前缀' },
{ key: 'confidence', label: '置信度' },
+ { key: 'new_origin_asn', label: '关联 ASN' },
+ { key: 'route_change', label: '事件特征' },
+ { key: 'as_path_display', label: '传播路径' },
{ key: 'collector', label: '主观测站' },
{ key: 'observed_by', label: '观测范围' },
- { key: 'impacted_scope', label: '影响区域' },
- { key: 'related_cables', label: '附近基础设施' },
- { key: 'related_satellites', label: '附近卫星' },
{ key: 'location', label: '观测位置' },
- { key: 'created_at', label: '事件时间' },
- { key: 'summary', label: '摘要' }
+ { key: 'related_cables', label: '附近基础设施' },
+ { key: 'related_satellites', label: '附近卫星' }
]
},
news: {
- icon: '📰',
+ icon: NEWS_CARD_ICON,
title: '新闻事件详情',
className: 'news',
fields: [
@@ -1582,7 +1538,6 @@ const CARD_CONFIG = {
{ key: 'published_at_display', label: '发布时间' },
{ key: 'location_label', label: '发生地' },
{ key: 'region_label', label: '区域' },
- { key: 'feed_name', label: '聚合源' },
{ key: 'summary', label: '摘要' },
{ key: 'url', label: '原文链接' }
]
@@ -1593,20 +1548,19 @@ const CARD_CONFIG = {
className: 'bgp',
fields: [
{ key: 'collector', label: '采集器' },
+ { key: 'status', label: '状态' },
{ key: 'location', label: '观测位置' },
{ key: 'anomaly_count', label: '当前事件数' },
- { key: 'observation_count', label: '观测事件数' },
+ { key: 'latest_observed_at', label: '最近活跃时间' },
{ key: 'recent_24h_observation_count', label: '近24h事件数' },
- { key: 'recent_7d_observation_count', label: '近7d事件数' },
+ { key: 'latest_event_type', label: '最近事件类型' },
{ key: 'prefix_count', label: '观测前缀数' },
{ key: 'origin_asn_count', label: '观测 ASN 数' },
{ key: 'top_event_types', label: '主要事件类型' },
- { key: 'coverage_halo', label: '日常活跃度' },
- { key: 'related_satellites', label: '附近卫星' },
- { key: 'latest_event_type', label: '最近事件类型' },
- { key: 'latest_observed_at', label: '最近活跃时间' },
+ { key: 'recent_7d_observation_count', label: '近7d事件数' },
+ { key: 'observation_count', label: '观测事件数' },
{ key: 'baseline_scope', label: '日常覆盖范围' },
- { key: 'status', label: '状态' }
+ { key: 'related_satellites', label: '附近卫星' }
]
},
compute_center_unresolved: {
@@ -1621,25 +1575,19 @@ const CARD_CONFIG = {
className: 'supercomputer',
fields: [
{ key: 'name', label: '名称' },
- { key: 'site_type_label', label: '类型' },
- { key: 'rank', label: '排名' },
{ key: 'capacity', label: '实测算力' },
- { key: 'vendor', label: '厂商' },
- { key: 'operator', label: '运营方' },
+ { key: 'rank', label: '排名' },
{ key: 'cores', label: '核心数' },
{ key: 'power', label: '功耗', unit: 'kW' },
+ { key: 'operator', label: '运营方' },
{ key: 'country', label: '国家' },
{ key: 'city', label: '城市' },
+ { key: 'vendor', label: '厂商' },
+ { key: 'site_type_label', label: '类型' },
+ { key: 'updated_at', label: '更新时间' },
{ key: 'location_precision_label', label: '位置精度' },
- { key: 'location_source_label', label: '位置来源' },
- { key: 'location_confidence', label: '位置置信度' },
{ key: 'location_status_label', label: '核验状态' },
- { key: 'estimated_reason', label: '解析依据' },
- { key: 'location_source_note', label: '位置来源说明' },
- { key: 'matched_location_name', label: '匹配的位置名称' },
- { key: 'location_verified_at', label: '位置核验时间' },
- { key: 'source', label: '来源' },
- { key: 'updated_at', label: '更新时间' }
+ { key: 'source', label: '来源' }
]
},
gpu_cluster: {
@@ -1648,41 +1596,53 @@ const CARD_CONFIG = {
className: 'gpu_cluster',
fields: [
{ key: 'name', label: '名称' },
- { key: 'site_type_label', label: '类型' },
{ key: 'capacity', label: '估算算力' },
- { key: 'gpu_count', label: 'GPU 数量' },
{ key: 'gpu_type', label: 'GPU 型号' },
- { key: 'vendor', label: '芯片/平台' },
+ { key: 'gpu_count', label: 'GPU 数量' },
{ key: 'operator', label: '运营方' },
{ key: 'country', label: '国家' },
{ key: 'city', label: '城市' },
+ { key: 'vendor', label: '芯片/平台', omitIfSameAs: 'gpu_type' },
+ { key: 'site_type_label', label: '类型' },
+ { key: 'updated_at', label: '更新时间' },
{ key: 'location_precision_label', label: '位置精度' },
- { key: 'location_source_label', label: '位置来源' },
- { key: 'location_confidence', label: '位置置信度' },
{ key: 'location_status_label', label: '核验状态' },
- { key: 'estimated_reason', label: '解析依据' },
- { key: 'location_source_note', label: '位置来源说明' },
- { key: 'matched_location_name', label: '匹配的位置名称' },
- { key: 'location_verified_at', label: '位置核验时间' },
- { key: 'source', label: '来源' },
- { key: 'updated_at', label: '更新时间' }
+ { key: 'source', label: '来源' }
]
},
+ ...Object.fromEntries(['data_center', 'cloud_center', 'edge_node'].map(type => [type, {
+ ...COMPUTE_SITE_TYPES[type],
+ className: type,
+ fields: [
+ { key: 'name', label: '名称' },
+ { key: 'capacity', label: '算力' },
+ { key: 'power', label: '功耗', unit: 'kW' },
+ { key: 'operator', label: '运营方' },
+ { key: 'country', label: '国家' },
+ { key: 'city', label: '城市' },
+ { key: 'site_type_label', label: '类型' },
+ { key: 'vendor', label: '厂商' },
+ { key: 'updated_at', label: '更新时间' },
+ { key: 'location_precision_label', label: '位置精度' },
+ { key: 'location_status_label', label: '核验状态' },
+ { key: 'source', label: '来源' },
+ ],
+ }])),
vessel: {
icon: '🚢',
title: '船只详情',
className: 'vessel',
fields: [
{ key: 'name', label: '名称' },
- { key: 'mmsi', label: 'MMSI' },
- { key: 'imo', label: 'IMO' },
- { key: 'flag', label: '旗帜' },
{ key: 'vessel_type', label: '船型' },
+ { key: 'status', label: '状态' },
{ key: 'speed', label: '当前航速', unit: 'kn' },
{ key: 'course', label: '航向', unit: '°' },
- { key: 'status', label: '状态' },
- { key: 'length', label: '船长', unit: 'm' },
- { key: 'received_at', label: '更新时间' }
+ { key: 'received_at', label: '更新时间' },
+ { key: 'flag', label: '旗帜' },
+ { key: 'mmsi', label: 'MMSI' },
+ { key: 'imo', label: 'IMO' },
+ { key: 'length', label: '船长', unit: 'm' }
]
},
earth_interactable: {
@@ -1691,14 +1651,13 @@ const CARD_CONFIG = {
className: 'earth_interactable',
fields: [
{ key: 'label', label: '名称' },
+ { key: 'description', label: '说明' },
+ { key: 'status', label: '状态' },
{ key: 'kind', label: '类型' },
- { key: 'id', label: '标识' },
{ key: 'latitude', label: '纬度' },
{ key: 'longitude', label: '经度' },
- { key: 'description', label: '说明' },
- { key: 'source', label: '来源' },
- { key: 'status', label: '状态' },
- { key: 'updated_at', label: '更新时间' }
+ { key: 'updated_at', label: '更新时间' },
+ { key: 'source', label: '来源' }
]
}
};
@@ -1772,7 +1731,7 @@ function setupInfoCardDrag(panel) {
};
handle.addEventListener('pointerdown', (event) => {
- if (event.target.closest('.hud-panel-close, .info-card-close')) return;
+ if (event.target.closest('button, a, .hud-panel-close, .info-card-close')) return;
event.preventDefault();
isDragging = true;
activePointerId = event.pointerId;
@@ -1830,6 +1789,8 @@ function mountCard() {
const card = panel.querySelector('#info-card');
const content = panel.querySelector('#info-card-content');
+ desktopCardImage = mountCardImage(content, card.querySelector(".info-card-header"));
+
// Prevent pointer events from reaching the earth canvas
const stopEvent = (event) => { event.stopPropagation(); };
[
@@ -1970,15 +1931,7 @@ function hidePanel() {
);
}
-// No-op: event binding now happens lazily in mountCard()
-export function initInfoCard() {}
-export function setInfoCardNoBorder(noBorder = true) {
- const card = document.getElementById('info-card');
- if (card) {
- card.classList.toggle('no-border', noBorder);
- }
-}
export function isInfoCardSticky() {
return getPanel()?.dataset.sticky === 'true';
@@ -2001,7 +1954,6 @@ export function showInfoCard(type, data, options = {}) {
}
if (document.body.classList.contains('layout-mode-mobile')) {
- currentType = type;
pendingMobileDetailState = { type, config, data };
ensureMobileDetailsListener();
@@ -2031,6 +1983,11 @@ export function showInfoCard(type, data, options = {}) {
renderedMobileDetailKey = getMobileDetailRenderKey(type, data);
}
+ if (content) {
+ mobileCardImage ||= mountCardImage(content, document.getElementById('mobile-info-card-title')?.closest('.earth-mobile-detail-header'));
+ void mobileCardImage.show(cardImageIdentity(type, data));
+ }
+
// Show the floating mini popup near the touch point (requires coordinates)
if (options.x != null && options.y != null) {
ensurePopupClickHandler();
@@ -2044,8 +2001,6 @@ export function showInfoCard(type, data, options = {}) {
}
mountCard();
-
- currentType = type;
const card = document.getElementById('info-card');
const icon = document.getElementById('info-card-icon');
const title = document.getElementById('info-card-title');
@@ -2063,10 +2018,13 @@ export function showInfoCard(type, data, options = {}) {
} else {
renderDefaultCardContent(content, config, data);
}
+ void desktopCardImage.show(cardImageIdentity(type, data));
showPanel(options.x, options.y, options);
}
export function hideInfoCard() {
+ desktopCardImage?.hide();
+ mobileCardImage?.hide();
stopTypewriterAnimation();
if (document.body.classList.contains('layout-mode-mobile')) {
hideMobilePopup();
@@ -2074,15 +2032,9 @@ export function hideInfoCard() {
window.dispatchEvent(
new CustomEvent('earth:info-card-visibility-change', { detail: { visible: false } })
);
- currentType = null;
pendingMobileDetailState = null;
renderedMobileDetailKey = null;
return;
}
hidePanel();
- currentType = null;
-}
-
-export function getCurrentType() {
- return currentType;
}
diff --git a/frontend/public/earth/js/interactable.js b/frontend/public/earth/js/interactable.js
index 680a4e42..fce9590e 100644
--- a/frontend/public/earth/js/interactable.js
+++ b/frontend/public/earth/js/interactable.js
@@ -1,3 +1,5 @@
+import { globeZoomForDistance } from "./globe-navigation.js";
+import { createClusterPresentation } from "./cluster-presentation.js";
import { isSurfaceAnchorVisible, SURFACE_ANCHOR_OCCLUSION_GLSL } from "./surface-marker-occlusion.js";
import { drawMarkerBadge } from "./marker-badges.js";
import * as THREE from "three";
@@ -5,54 +7,30 @@ import * as THREE from "three";
import { CONFIG } from "./constants.js";
import { getSurfaceMarkerCameraScale, latLonToVector3 } from "./utils.js";
+// Focused markers must win across interactable layers, not only within their
+// own point batch. The shared value keeps a selected icon visible when it
+// overlaps another surface icon.
+const INTERACTABLE_FOCUS_RENDER_ORDER = 100;
+
const assetImageCache = new Map();
+const projectedTextureUrls = new WeakMap();
const assetImageLoadPromises = new Map();
const surfaceAvoidanceBuckets = new Map();
const interactableLayerControllers = new Map();
const DEFAULT_AVOIDANCE_PRECISION = 4;
const POINT_BUCKET_MIN_CAPACITY = 32;
-const COMPACT_DOT_ZOOM_THRESHOLD = 1.7;
-const COMPACT_DOT_POINT_SIZE = 12;
-const COMPACT_DOT_RADIUS_RATIO = 0.26;
-const CLUSTER_OVERLAP_FACTOR = 0.9;
const CLUSTER_MIN_COUNT = 2;
const CLUSTER_MAX_MARKERS_PER_DOT = 14;
-const CLUSTER_MAX_POINT_SIZE = 32;
-const CLUSTER_SEED_DISTANCE_FACTOR = 1.8;
-const CLUSTER_TRANSITION_MS = 220;
-const CLUSTER_BAND_HYSTERESIS = 0.08;
+const CLUSTER_DISTANCE = 15;
+const CLUSTER_EXPANSION_HYSTERESIS = 0.08;
const CLUSTER_DISABLE_ABOVE_ZOOM = 2.5;
-const CLUSTER_STRATEGY_DYNAMIC_SCREEN = "dynamic-screen";
-const CLUSTER_STRATEGY_STABLE_SPHERICAL = "stable-spherical";
-const CLUSTER_STRATEGY_NONE = "none";
-const CLUSTER_ZOOM_BANDS = Object.freeze([
- Object.freeze({
- maxZoom: 2.0,
- referenceZoom: 1.0,
- overlapFactor: 0.9,
- maxDiameterPx: 96,
- }),
- Object.freeze({
- maxZoom: 3.0,
- referenceZoom: 2.0,
- overlapFactor: 0.45,
- maxDiameterPx: 72,
- }),
- Object.freeze({
- maxZoom: Number.POSITIVE_INFINITY,
- referenceZoom: 3.0,
- overlapFactor: 0.2,
- maxDiameterPx: 48,
- }),
-]);
-const SPHERICAL_CLUSTER_BANDS = Object.freeze([
- Object.freeze({ key: "far", maxZoom: 1.7, distance: 15 }),
- Object.freeze({ key: "mid", maxZoom: 2.6, distance: 8 }),
- Object.freeze({ key: "near", maxZoom: 3.5, distance: 4 }),
- Object.freeze({ key: "detail", maxZoom: Number.POSITIVE_INFINITY, distance: 0 }),
-]);
-let compactDotsEnabled = false;
-let screenAvoidanceRevision = 0;
+let clusterPresentation = null;
+export function updateInteractableClusters(camera, selectedMarker = null) { updateClusterPresentation(camera, selectedMarker); }
+export function resolveInteractableMarker(marker) {
+ return interactableLayerControllers.get(marker?.userData?.icon_layer_id)?.resolveMarker(marker) || marker;
+}
+export function clearInteractableClusters() { clusterPresentation?.destroy(); clusterPresentation = null; }
+
// Named overlap profiles. Layers that should be recognized as sharing a place
// must reference the SAME profile. The profile records overlap metadata only;
@@ -73,16 +51,25 @@ export const SURFACE_AVOIDANCE_PROFILES = Object.freeze({
precision: DEFAULT_AVOIDANCE_PRECISION,
}),
});
+const parsedColors = new Map();
function colorToRgbArray(colorValue, fallback = "#ffffff") {
- const color = new THREE.Color(colorValue || fallback);
- return [color.r, color.g, color.b];
+ const value = colorValue || fallback;
+ // CSS strings/numbers are immutable; caller-owned Color objects may change.
+ const cacheable = typeof value === "string" || typeof value === "number";
+ if (cacheable && parsedColors.has(value)) return parsedColors.get(value);
+ const color = new THREE.Color(value);
+ const rgb = [color.r, color.g, color.b];
+ if (cacheable) {
+ if (parsedColors.size >= 256) parsedColors.delete(parsedColors.keys().next().value);
+ parsedColors.set(value, rgb);
+ }
+ return rgb;
}
function normalizeAvoidanceConfig(avoidance) {
if (avoidance === false || avoidance === null || avoidance === undefined) {
return {
enabled: false,
- screen: false,
precision: DEFAULT_AVOIDANCE_PRECISION,
};
}
@@ -92,161 +79,25 @@ function normalizeAvoidanceConfig(avoidance) {
const config = {
enabled: true,
precision: DEFAULT_AVOIDANCE_PRECISION,
- screen: false,
...customConfig,
};
config.enabled = config.enabled !== false;
- config.screen = false;
return config;
}
function normalizeClusterConfig(cluster, avoidanceConfig) {
- if (cluster === false || cluster === null) {
- return {
- enabled: false,
- strategy: CLUSTER_STRATEGY_NONE,
- overlapFactor: CLUSTER_OVERLAP_FACTOR,
- minCount: CLUSTER_MIN_COUNT,
- maxMarkersPerDot: CLUSTER_MAX_MARKERS_PER_DOT,
- bands: SPHERICAL_CLUSTER_BANDS,
- transitionMs: CLUSTER_TRANSITION_MS,
- bandHysteresis: CLUSTER_BAND_HYSTERESIS,
- disableAboveZoom: CLUSTER_DISABLE_ABOVE_ZOOM,
- };
- }
-
- const customConfig = typeof cluster === "object" ? cluster : {};
- const requestedStrategy = String(customConfig.strategy || "").trim();
- const enabled = customConfig.enabled ?? avoidanceConfig.enabled;
- const strategy =
- enabled === false
- ? CLUSTER_STRATEGY_NONE
- : [
- CLUSTER_STRATEGY_DYNAMIC_SCREEN,
- CLUSTER_STRATEGY_STABLE_SPHERICAL,
- CLUSTER_STRATEGY_NONE,
- ].includes(requestedStrategy)
- ? requestedStrategy
- : CLUSTER_STRATEGY_DYNAMIC_SCREEN;
+ const customConfig = typeof cluster === "object" && cluster ? cluster : {};
return {
- enabled: enabled !== false && strategy !== CLUSTER_STRATEGY_NONE,
- strategy,
- overlapFactor: Number.isFinite(Number(customConfig.overlapFactor))
- ? Number(customConfig.overlapFactor)
- : CLUSTER_OVERLAP_FACTOR,
+ enabled: cluster !== false && cluster !== null &&
+ (customConfig.enabled ?? avoidanceConfig.enabled),
minCount: Math.max(2, Math.round(Number(customConfig.minCount ?? CLUSTER_MIN_COUNT))),
- maxMarkersPerDot: Math.max(
- 2,
- Math.round(Number(customConfig.maxMarkersPerDot ?? CLUSTER_MAX_MARKERS_PER_DOT)),
- ),
- bands: normalizeSphericalClusterBands(customConfig.bands),
- transitionMs: Math.max(
- 0,
- Math.round(Number(customConfig.transitionMs ?? CLUSTER_TRANSITION_MS)),
- ),
- bandHysteresis: Math.max(
- 0,
- Number(customConfig.bandHysteresis ?? CLUSTER_BAND_HYSTERESIS),
- ),
- disableAboveZoom:
- customConfig.disableAboveZoom === false || customConfig.disableAboveZoom === null
- ? Number.POSITIVE_INFINITY
- : Number.isFinite(Number(customConfig.disableAboveZoom))
- ? Number(customConfig.disableAboveZoom)
- : CLUSTER_DISABLE_ABOVE_ZOOM,
+ maxMarkersPerDot: Math.max(2, Math.round(Number(customConfig.maxMarkersPerDot ?? CLUSTER_MAX_MARKERS_PER_DOT))),
+ distance: Math.max(0, Number(customConfig.distance ?? CLUSTER_DISTANCE)),
+ expansionHysteresis: Math.max(0, Number(customConfig.expansionHysteresis ?? CLUSTER_EXPANSION_HYSTERESIS)),
+ disableAboveZoom: Number(customConfig.disableAboveZoom ?? CLUSTER_DISABLE_ABOVE_ZOOM),
};
}
-function normalizeSphericalClusterBands(bands) {
- if (!Array.isArray(bands) || bands.length === 0) return SPHERICAL_CLUSTER_BANDS;
- const normalizedBands = bands
- .map((band, index) => {
- const maxZoom = Number(band?.maxZoom);
- const distance = Number(band?.distance);
- return {
- key: String(band?.key || `band-${index}`),
- maxZoom: Number.isFinite(maxZoom) ? maxZoom : Number.POSITIVE_INFINITY,
- distance: Number.isFinite(distance) ? Math.max(0, distance) : 0,
- };
- })
- .sort((a, b) => a.maxZoom - b.maxZoom);
- return normalizedBands.length > 0 ? normalizedBands : SPHERICAL_CLUSTER_BANDS;
-}
-
-function getClusterPointSize(count) {
- const safeCount = Math.max(2, Number(count) || 2);
- return Math.min(
- CLUSTER_MAX_POINT_SIZE,
- COMPACT_DOT_POINT_SIZE + Math.log2(safeCount) * 5.5,
- );
-}
-
-function getClusterZoomBand(zoom) {
- return (
- CLUSTER_ZOOM_BANDS.find((band) => zoom <= band.maxZoom) ||
- CLUSTER_ZOOM_BANDS[CLUSTER_ZOOM_BANDS.length - 1]
- );
-}
-
-function getSphericalClusterBand(config, zoom, previousBandKey = null) {
- const bands = config?.bands || SPHERICAL_CLUSTER_BANDS;
- const previousIndex = previousBandKey
- ? bands.findIndex((band) => band.key === previousBandKey)
- : -1;
- const hysteresis = Number(config?.bandHysteresis) || 0;
- if (previousIndex >= 0 && hysteresis > 0) {
- const previousBand = bands[previousIndex];
- const lowerBoundary =
- previousIndex > 0 ? bands[previousIndex - 1].maxZoom : Number.NEGATIVE_INFINITY;
- const upperBoundary = previousBand.maxZoom;
- if (zoom > lowerBoundary - hysteresis && zoom <= upperBoundary + hysteresis) {
- return previousBand;
- }
- }
- return bands.find((band) => zoom <= band.maxZoom) || bands[bands.length - 1];
-}
-
-function getNowMs() {
- return typeof performance !== "undefined" && typeof performance.now === "function"
- ? performance.now()
- : Date.now();
-}
-
-function easeOutCubic(value) {
- const t = Math.max(0, Math.min(1, value));
- return 1 - Math.pow(1 - t, 3);
-}
-
-function getTransitionProgress(startedAt, durationMs) {
- if (!startedAt || !durationMs || durationMs <= 0) return 1;
- return easeOutCubic((getNowMs() - startedAt) / durationMs);
-}
-
-function getNominalGlobePixelsPerWorldUnit(camera, referenceZoom) {
- if (!camera) return 1;
- const viewportHeight = window.innerHeight || 1;
- const fovRad = ((camera.fov || 75) * Math.PI) / 180;
- const distance = Math.max(
- 1,
- Number.isFinite(referenceZoom) && referenceZoom > 0
- ? CONFIG.defaultCameraZ / referenceZoom
- : camera.position?.length?.() || CONFIG.defaultCameraZ,
- );
- return viewportHeight / (2 * Math.tan(fovRad / 2) * distance);
-}
-
-function getAngularRadiusFromPixels(pixelRadius, worldRadius, camera, referenceZoom) {
- const globeRadiusPx = Math.max(
- 1,
- worldRadius * getNominalGlobePixelsPerWorldUnit(camera, referenceZoom),
- );
- return Math.max(0, pixelRadius) / globeRadiusPx;
-}
-
-function getClusterOverlapFactorForBand(band, baseFactor = CLUSTER_OVERLAP_FACTOR) {
- return Math.min(baseFactor, band.overlapFactor);
-}
-
function getSphericalBucketKey(latIndex, lonIndex) {
return `${latIndex}:${lonIndex}`;
}
@@ -325,23 +176,6 @@ function createCanvas(width, height) {
return canvas;
}
-export function getInteractableCompactDotsEnabled() {
- return compactDotsEnabled;
-}
-
-export function setInteractableCompactDotsEnabled(enabled) {
- compactDotsEnabled = Boolean(enabled);
- invalidateScreenAvoidance();
- interactableLayerControllers.forEach((controller) => {
- controller.refreshVisuals?.();
- });
- return compactDotsEnabled;
-}
-
-function invalidateScreenAvoidance() {
- screenAvoidanceRevision += 1;
-}
-
function getAvoidanceKey(item, position, basePosition, config) {
if (typeof config?.getKey === "function") {
const key = config.getKey(item, position, basePosition);
@@ -368,7 +202,6 @@ function getAvoidanceKey(item, position, basePosition, config) {
}
function notifyAvoidancePositionChanged(layerIds) {
- invalidateScreenAvoidance();
layerIds.forEach((layerId) => {
interactableLayerControllers.get(layerId)?.refreshPositions?.();
});
@@ -448,95 +281,12 @@ function getMarkerStaticAvoidancePosition(marker) {
);
}
-function collectClusterUpdates(camera) {
- if (!camera) return [];
- const updates = [];
- interactableLayerControllers.forEach((controller) => {
- const update = controller.collectClusterEntries?.(camera);
- if (!update) return;
- if (Array.isArray(update)) {
- updates.push({
- strategy: CLUSTER_STRATEGY_DYNAMIC_SCREEN,
- entries: update,
- records: [],
- });
- return;
- }
- updates.push(update);
- });
- return updates;
-}
-
-function findScreenClusterGroups(entries) {
- const unvisited = new Set(entries);
- const groups = [];
-
- entries.forEach((seed) => {
- if (!unvisited.has(seed)) return;
-
- const groupEntries = [seed];
- unvisited.delete(seed);
-
- let changed = true;
- while (changed) {
- changed = false;
- const candidates = [...unvisited].sort((a, b) => {
- const distanceA = getAngularDistance(seed, a);
- const distanceB = getAngularDistance(seed, b);
- return distanceA - distanceB || a.stableId.localeCompare(b.stableId);
- });
-
- for (const candidate of candidates) {
- const overlapFactor = Math.min(
- seed.overlapFactor || CLUSTER_OVERLAP_FACTOR,
- candidate.overlapFactor || CLUSTER_OVERLAP_FACTOR,
- );
- const seedDistance = getAngularDistance(seed, candidate);
- const seedLimit =
- (seed.angularRadius + candidate.angularRadius) *
- CLUSTER_SEED_DISTANCE_FACTOR;
- if (seedDistance > seedLimit) continue;
-
- const overlapsGroup = groupEntries.some((entry) => {
- const distance = getAngularDistance(candidate, entry);
- return distance <= (candidate.angularRadius + entry.angularRadius) * overlapFactor;
- });
- if (!overlapsGroup) continue;
-
- const maxAngularDiameter = Math.max(
- seed.maxAngularDiameter,
- candidate.maxAngularDiameter,
- );
- const staysLocal = groupEntries.every(
- (entry) => getAngularDistance(candidate, entry) <= maxAngularDiameter,
- );
- if (!staysLocal) {
- continue;
- }
-
- groupEntries.push(candidate);
- unvisited.delete(candidate);
- changed = true;
- }
- }
-
- if (groupEntries.length >= CLUSTER_MIN_COUNT) {
- groups.push(groupEntries.sort((a, b) => a.stableId.localeCompare(b.stableId)));
- return;
- }
-
- groupEntries.forEach((entry) => unvisited.add(entry));
- });
-
- return groups;
-}
-
function getAngularDistance(entryA, entryB) {
const dot = entryA.direction.dot(entryB.direction);
return Math.acos(Math.min(1, Math.max(-1, dot)));
}
-function splitLargeScreenClusterGroup(groupEntries) {
+function splitLargeClusterGroup(groupEntries) {
const maxMarkersPerDot = groupEntries.reduce(
(maxCount, entry) => Math.min(maxCount, entry.maxMarkersPerDot || CLUSTER_MAX_MARKERS_PER_DOT),
Number.POSITIVE_INFINITY,
@@ -554,13 +304,13 @@ function splitLargeScreenClusterGroup(groupEntries) {
return chunks;
}
-function computeSphericalClusterRecords(entries, config, band) {
- if (!entries.length || !band || band.distance <= 0) return [];
+function computeSphericalClusterRecords(entries, config) {
+ if (!entries.length || config.distance <= 0) return [];
const radius =
entries.find((entry) => Number.isFinite(entry.radiusWorld))?.radiusWorld ||
CONFIG.earthRadius;
- const angularThreshold = Math.max(0.00001, band.distance / Math.max(1, radius));
+ const angularThreshold = Math.max(0.00001, config.distance / Math.max(1, radius));
const lonBucketCount = Math.max(1, Math.ceil((Math.PI * 2) / angularThreshold));
const buckets = new Map();
const entryState = entries.map((entry) => {
@@ -620,8 +370,8 @@ function computeSphericalClusterRecords(entries, config, band) {
});
return groups
- .flatMap(splitLargeScreenClusterGroup)
- .map(createScreenClusterRecord)
+ .flatMap(splitLargeClusterGroup)
+ .map(createClusterRecord)
.filter(Boolean);
}
@@ -635,7 +385,7 @@ function compareEntriesByStableGeography(a, b) {
return a.stableId.localeCompare(b.stableId);
}
-function createScreenClusterRecord(groupEntries) {
+function createClusterRecord(groupEntries) {
const sortedEntries = [...groupEntries].sort((a, b) => a.stableId.localeCompare(b.stableId));
const anchorEntry = sortedEntries[0];
const clusterPosition = new THREE.Vector3();
@@ -654,60 +404,24 @@ function createScreenClusterRecord(groupEntries) {
: CONFIG.earthRadius;
clusterPosition.normalize().multiplyScalar(altitudeRadius);
- const center = { x: 0, y: 0 };
- sortedEntries.forEach((entry) => {
- center.x += entry.x;
- center.y += entry.y;
- });
- center.x /= sortedEntries.length;
- center.y /= sortedEntries.length;
const clusterId = getClusterRecordId(sortedEntries);
return {
clusterId,
markers: sortedEntries.map((entry) => entry.marker),
owner: anchorEntry.controller,
position: clusterPosition,
- pointSize: getClusterPointSize(sortedEntries.length),
- anchorStableId: anchorEntry.stableId,
- clusterZoomBand: anchorEntry.clusterBandKey || anchorEntry.clusterZoomBand,
- screenX: center.x,
- screenY: center.y,
- transitionStartedAt: getNowMs(),
};
}
-function recomputeScreenAvoidance(camera) {
+function updateClusterPresentation(camera, selectedMarker) {
if (!camera) return;
const controllersToRebuild = new Set();
interactableLayerControllers.forEach((controller) => {
controller.beginClusterUpdate?.();
});
- const updates = collectClusterUpdates(camera);
- const dynamicEntries = updates
- .filter((update) => update.strategy === CLUSTER_STRATEGY_DYNAMIC_SCREEN)
- .flatMap((update) => update.entries || [])
- .sort((a, b) => a.stableId.localeCompare(b.stableId));
- const stableRecords = updates
- .filter((update) => update.strategy === CLUSTER_STRATEGY_STABLE_SPHERICAL)
- .flatMap((update) => update.records || []);
- const entries = dynamicEntries;
-
- entries.forEach((entry) => {
- const basePosition = getMarkerStaticAvoidancePosition(entry.marker);
- if (basePosition instanceof THREE.Vector3) {
- entry.marker.position.copy(basePosition);
- }
- entry.marker.userData.icon_screen_avoidance_count = 1;
- entry.marker.userData.icon_screen_avoidance_index = 0;
- entry.marker.userData.icon_screen_clustered = false;
- });
-
- findScreenClusterGroups(entries)
- .flatMap(splitLargeScreenClusterGroup)
- .map(createScreenClusterRecord)
- .filter(Boolean)
- .concat(stableRecords)
- .forEach((record) => {
+ const records = [...interactableLayerControllers.values()]
+ .flatMap(controller => controller.collectClusterRecords(camera));
+ records.forEach((record) => {
record.owner.addOwnedCluster?.(record);
record.markers.forEach((marker) => {
const owner = interactableLayerControllers.get(marker.userData?.icon_layer_id);
@@ -720,6 +434,14 @@ function recomputeScreenAvoidance(camera) {
controllersToRebuild.add(controller);
}
});
+ if (!clusterPresentation) clusterPresentation = createClusterPresentation({
+ getOwner: marker => interactableLayerControllers.get(marker.userData?.icon_layer_id),
+ onHiddenChange: owner => owner?.rebuildPointLayers(),
+ });
+ const stackCandidates = [...interactableLayerControllers.values()]
+ .flatMap(controller => controller.getPresentationMarkers());
+ clusterPresentation.update(records, camera,
+ globeZoomForDistance(camera.position.length(), CONFIG.earthRadius, CONFIG.defaultCameraZ), stackCandidates, selectedMarker);
controllersToRebuild.forEach((controller) => controller.rebuildPointLayers?.(camera));
}
@@ -795,11 +517,10 @@ export function createInteractableLayer(options = {}) {
const markers = [];
const pointObjects = [];
const markerById = new Map();
+ let currentMarkers = new WeakSet();
const pointSlots = new WeakMap();
- const clusterPointObjects = [];
const textureCache = new Map();
let pointsGroup = null;
- let clusterGroup = null;
let hoverOverlay = null;
let lockedOverlay = null;
let visible = false;
@@ -810,8 +531,8 @@ export function createInteractableLayer(options = {}) {
let visualStateVersion = 0;
let clusterTopologyRevision = 0;
let lastStableClusterKey = "";
- let lastStableClusterBandKey = "";
let stableClusterRecords = [];
+ let detailClusterMode = false;
const ownedClusterRecords = [];
const scratchDirection = new THREE.Vector3();
const scratchCameraLocal = new THREE.Vector3();
@@ -841,10 +562,6 @@ export function createInteractableLayer(options = {}) {
Math.abs(iconAnchor.y - 0.5) > 0.001;
const avoidanceConfig = normalizeAvoidanceConfig(avoidance);
const clusterConfig = normalizeClusterConfig(cluster, avoidanceConfig);
- const clusterWorldScratch = new THREE.Vector3();
- const clusterProjectedScratch = new THREE.Vector3();
- const clusterCameraLocalScratch = new THREE.Vector3();
- const clusterDirectionScratch = new THREE.Vector3();
function invalidateVisualState() {
visualStateVersion += 1;
@@ -854,7 +571,7 @@ export function createInteractableLayer(options = {}) {
function invalidateClusterTopology() {
clusterTopologyRevision += 1;
lastStableClusterKey = "";
- lastStableClusterBandKey = "";
+ lastClusterSignature = "";
}
function refreshViewportSize() {
@@ -1029,79 +746,7 @@ export function createInteractableLayer(options = {}) {
});
}
- function createCompactDotTexture(marker, state = "normal") {
- const kind = marker?.userData?.icon_kind || "default";
- const color = state === "normal" ? "#ffffff" : getMarkerColor(marker);
- const textureKey = `compact-dot:${state}:${kind}:${color}`;
- if (textureCache.has(textureKey)) return textureCache.get(textureKey);
-
- const canvas = document.createElement("canvas");
- canvas.width = atlasCellSize;
- canvas.height = atlasCellSize;
- const context = canvas.getContext("2d");
- const center = atlasCellSize / 2;
- const radius = atlasCellSize * COMPACT_DOT_RADIUS_RATIO;
- context.clearRect(0, 0, canvas.width, canvas.height);
- context.fillStyle = color;
- context.shadowColor = color;
- context.shadowBlur = atlasCellSize * 0.08;
- context.beginPath();
- context.arc(center, center, radius, 0, Math.PI * 2);
- context.fill();
-
- const texture = new THREE.CanvasTexture(canvas);
- texture.generateMipmaps = false;
- texture.minFilter = THREE.LinearFilter;
- texture.magFilter = THREE.LinearFilter;
- texture.needsUpdate = true;
- textureCache.set(textureKey, texture);
- return texture;
- }
-
- function getClusterMajorityColor(clusterMarkers) {
- const colorCounts = new Map();
- clusterMarkers.forEach((marker) => {
- const color = getMarkerColor(marker);
- colorCounts.set(color, (colorCounts.get(color) || 0) + 1);
- });
- return [...colorCounts.entries()]
- .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0]?.[0] ||
- colors.normal ||
- "#ffffff";
- }
-
- function createClusterTexture(clusterMarkers) {
- const color = getClusterMajorityColor(clusterMarkers);
- const textureKey = `cluster-dot:${color}`;
- if (textureCache.has(textureKey)) return textureCache.get(textureKey);
-
- const canvas = document.createElement("canvas");
- canvas.width = atlasCellSize;
- canvas.height = atlasCellSize;
- const context = canvas.getContext("2d");
- const center = atlasCellSize / 2;
- const radius = atlasCellSize * COMPACT_DOT_RADIUS_RATIO;
- context.clearRect(0, 0, canvas.width, canvas.height);
- context.fillStyle = color;
- context.shadowColor = color;
- context.shadowBlur = atlasCellSize * 0.08;
- context.beginPath();
- context.arc(center, center, radius, 0, Math.PI * 2);
- context.fill();
-
- const texture = new THREE.CanvasTexture(canvas);
- texture.generateMipmaps = false;
- texture.minFilter = THREE.LinearFilter;
- texture.magFilter = THREE.LinearFilter;
- texture.needsUpdate = true;
- textureCache.set(textureKey, texture);
- return texture;
- }
-
- function createOverlayTexture(marker, state, compactDotMode = false) {
- if (compactDotMode) {
- return createCompactDotTexture(marker, state);
- }
+ function createOverlayTexture(marker, state) {
const kind = marker?.userData?.icon_kind || "default";
const rotationBin = getRotationBin(marker);
const color = getMarkerColor(marker);
@@ -1135,15 +780,33 @@ export function createInteractableLayer(options = {}) {
function getCameraZoom(camera) {
if (!camera?.position?.z) return CONFIG.defaultViewZoom;
- return CONFIG.defaultCameraZ / camera.position.z;
+ return globeZoomForDistance(camera.position.length(), CONFIG.earthRadius, CONFIG.defaultCameraZ);
}
- function shouldUseCompactDots(camera) {
- return compactDotsEnabled && getCameraZoom(camera) <= COMPACT_DOT_ZOOM_THRESHOLD;
+ function itemKey(item) {
+ const value = getItemId(item);
+ if (typeof value !== "string" && typeof value !== "number") return null;
+ if (typeof value === "number" && !Number.isFinite(value)) return null;
+ const key = String(value).trim();
+ return key && key !== "-" ? key : null;
+ }
+
+ function indexMarker(marker) {
+ currentMarkers.add(marker);
+ const key = itemKey(marker.userData);
+ marker.userData.icon_item_id = key;
+ if (key === null) return;
+ // An ambiguous key cannot identify a replacement after a data refresh.
+ if (markerById.has(key)) {
+ const previous = markerById.get(key);
+ if (previous) previous.userData.icon_item_id = null;
+ marker.userData.icon_item_id = null;
+ markerById.set(key, null);
+ } else markerById.set(key, marker);
}
function getMarkerStableId(marker, fallbackIndex = 0) {
- const itemId = getItemId(marker?.userData || {});
+ const itemId = itemKey(marker?.userData || {});
if (itemId !== undefined && itemId !== null && String(itemId).trim() !== "") {
return String(itemId);
}
@@ -1161,130 +824,33 @@ export function createInteractableLayer(options = {}) {
});
}
- function collectClusterEntries(camera) {
- if (!visible || !clusterConfig.enabled || !camera || markers.length === 0) {
- return null;
- }
- const cameraScale = getCameraScale(camera);
+ function collectClusterRecords(camera) {
+ if (!visible || !clusterConfig.enabled || !camera || markers.length === 0) return [];
const zoom = getCameraZoom(camera);
- if (zoom > clusterConfig.disableAboveZoom) {
- lastStableClusterBandKey = "";
- return {
- strategy: CLUSTER_STRATEGY_DYNAMIC_SCREEN,
- entries: [],
- records: [],
- };
- }
- const clusterZoomBand = getClusterZoomBand(zoom);
- const sphericalBand = getSphericalClusterBand(
- clusterConfig,
- zoom,
- lastStableClusterBandKey,
- );
- if (clusterConfig.strategy === CLUSTER_STRATEGY_STABLE_SPHERICAL && sphericalBand?.key) {
- lastStableClusterBandKey = sphericalBand.key;
- }
- const stableSpherical = clusterConfig.strategy === CLUSTER_STRATEGY_STABLE_SPHERICAL;
- const visualPointSize = shouldUseCompactDots(camera)
- ? COMPACT_DOT_POINT_SIZE
- : pointSize;
- const width = window.innerWidth || 1;
- const height = window.innerHeight || 1;
+ if (zoom > clusterConfig.disableAboveZoom) detailClusterMode = true;
+ else if (zoom < clusterConfig.disableAboveZoom * (1 - clusterConfig.expansionHysteresis)) detailClusterMode = false;
- clusterCameraLocalScratch.copy(camera.position);
- group.parent?.worldToLocal?.(clusterCameraLocalScratch);
- clusterCameraLocalScratch.normalize();
- group.updateMatrixWorld?.(true);
-
- const entries = markers
- .map((marker, index) => {
- if (!isItemVisible(marker.userData)) return null;
- const basePosition = marker.userData?.icon_base_position || marker.position;
- if (!(basePosition instanceof THREE.Vector3)) return null;
- const direction = clusterDirectionScratch.copy(basePosition).normalize().clone();
- if (!stableSpherical) {
- if (clusterCameraLocalScratch.dot(clusterDirectionScratch) <= 0) return null;
-
- clusterWorldScratch.copy(basePosition);
- group.localToWorld(clusterWorldScratch);
- clusterProjectedScratch.copy(clusterWorldScratch).project(camera);
- if (clusterProjectedScratch.z < -1 || clusterProjectedScratch.z > 1) {
- return null;
- }
- }
-
- const pointSizeMultiplier = getPointSizeMultiplier(marker) * cameraScale;
- const sizePx = visualPointSize * pointSizeMultiplier;
- const screenX =
- (stableSpherical ? 0 : (clusterProjectedScratch.x * 0.5 + 0.5) * width) +
- (0.5 - iconAnchor.x) * sizePx;
- const screenY =
- (stableSpherical ? 0 : (-clusterProjectedScratch.y * 0.5 + 0.5) * height) +
- (0.5 - iconAnchor.y) * sizePx;
- const nominalRadiusPx = Math.max(8, visualPointSize * 0.5);
- const angularRadius = getAngularRadiusFromPixels(
- nominalRadiusPx,
- basePosition.length(),
- camera,
- clusterZoomBand.referenceZoom,
- );
- const maxAngularDiameter = getAngularRadiusFromPixels(
- Math.max(clusterZoomBand.maxDiameterPx, nominalRadiusPx * 6),
- basePosition.length(),
- camera,
- clusterZoomBand.referenceZoom,
- );
- return {
+ // Geographic membership is cached across camera motion and zoom; only
+ // data/filter changes invalidate it. The presentation owns the one tween.
+ const stableKey = `${id}:${clusterTopologyRevision}`;
+ if (stableKey !== lastStableClusterKey) {
+ const entries = markers.flatMap((marker, index) => {
+ if (!isItemVisible(marker.userData)) return [];
+ const position = getMarkerStaticAvoidancePosition(marker);
+ if (!(position instanceof THREE.Vector3)) return [];
+ return [{
marker,
stableId: `${id}:${getMarkerStableId(marker, index)}`,
controller,
- x: screenX,
- y: screenY,
- radiusPx: Math.max(8, sizePx * 0.5),
- direction,
- angularRadius,
- maxAngularDiameter,
- overlapFactor: getClusterOverlapFactorForBand(
- clusterZoomBand,
- clusterConfig.overlapFactor,
- ),
+ direction: position.clone().normalize(),
+ radiusWorld: position.length(),
maxMarkersPerDot: clusterConfig.maxMarkersPerDot,
- clusterZoomBand: clusterZoomBand.referenceZoom,
- clusterBandKey: sphericalBand?.key || String(clusterZoomBand.referenceZoom),
- radiusWorld: basePosition.length(),
- };
- })
- .filter(Boolean)
- .sort((a, b) => a.stableId.localeCompare(b.stableId));
-
- if (clusterConfig.strategy !== CLUSTER_STRATEGY_STABLE_SPHERICAL) {
- return {
- strategy: CLUSTER_STRATEGY_DYNAMIC_SCREEN,
- entries,
- records: [],
- };
- }
-
- const stableKey = [
- id,
- sphericalBand?.key || "unknown",
- sphericalBand?.distance ?? 0,
- clusterTopologyRevision,
- entries.length,
- ].join(":");
- if (stableKey !== lastStableClusterKey) {
- stableClusterRecords = computeSphericalClusterRecords(
- entries,
- clusterConfig,
- sphericalBand,
- );
+ }];
+ }).sort((a, b) => a.stableId.localeCompare(b.stableId));
+ stableClusterRecords = computeSphericalClusterRecords(entries, clusterConfig);
lastStableClusterKey = stableKey;
}
- return {
- strategy: CLUSTER_STRATEGY_STABLE_SPHERICAL,
- entries: [],
- records: stableClusterRecords,
- };
+ return stableClusterRecords.map(record => ({ ...record, expanded: detailClusterMode }));
}
function addOwnedCluster(record) {
@@ -1301,7 +867,7 @@ export function createInteractableLayer(options = {}) {
function getClusterSignature() {
return ownedClusterRecords
.map((record) =>
- `${record.clusterId}:${record.anchorStableId}:${record.clusterZoomBand}:${record.pointSize.toFixed(1)}`,
+ record.clusterId,
)
.join("|");
}
@@ -1315,17 +881,6 @@ export function createInteractableLayer(options = {}) {
return true;
}
- function hasActiveRenderTransitions() {
- if (clusterConfig.transitionMs <= 0) return false;
- const now = getNowMs();
- return pointObjects
- .concat(clusterPointObjects)
- .some((points) => {
- const startedAt = points.userData?.transitionStartedAt;
- return startedAt && now - startedAt < clusterConfig.transitionMs;
- });
- }
-
function disposePointsGroup() {
if (pointsGroup?.parent) {
pointsGroup.parent.remove(pointsGroup);
@@ -1339,29 +894,14 @@ export function createInteractableLayer(options = {}) {
pointObjects.length = 0;
}
- function disposeClusterGroup() {
- if (clusterGroup?.parent) {
- clusterGroup.parent.remove(clusterGroup);
- }
- clusterPointObjects.forEach((points) => {
- points.geometry?.dispose?.();
- points.material?.dispose?.();
- });
- clusterGroup = null;
- clusterPointObjects.length = 0;
- }
-
function rebuildPointLayers(camera = null) {
disposePointsGroup();
- disposeClusterGroup();
buildPoints(camera);
- buildClusters();
if (pointsGroup) pointsGroup.visible = visible;
- if (clusterGroup) clusterGroup.visible = visible;
invalidateVisualState();
}
- function updatePointColors(points, compactDotMode) {
+ function updatePointColors(points) {
const bucketMarkers = points.userData?.markers || [];
const colorAttribute = points.geometry?.getAttribute("color");
if (!colorAttribute?.array) return;
@@ -1369,7 +909,7 @@ export function createInteractableLayer(options = {}) {
let lastChanged = -1;
bucketMarkers.forEach((marker, index) => {
const pointColor =
- compactDotMode || icon.colorable !== false
+ icon.colorable !== false
? getMarkerColor(marker)
: "#ffffff";
const [r, g, b] = colorToRgbArray(pointColor);
@@ -1384,7 +924,7 @@ export function createInteractableLayer(options = {}) {
if (firstChanged >= 0) markAttributeRange(colorAttribute, firstChanged * 3, (lastChanged - firstChanged + 1) * 3);
}
- function addPointBucket(bucketKey, bucketMarkers, compactDotMode = false) {
+ function addPointBucket(bucketKey, bucketMarkers) {
const count = bucketMarkers.length;
const positions = new Float32Array(count * 3);
const colorValues = new Float32Array(count * 3);
@@ -1408,11 +948,9 @@ export function createInteractableLayer(options = {}) {
const material = applyIconAnchor(
new THREE.PointsMaterial({
- map: compactDotMode
- ? createCompactDotTexture(bucketMarkers[0])
- : createPointTexture(bucketKey, bucketMarkers),
+ map: createPointTexture(bucketKey, bucketMarkers),
size:
- (compactDotMode ? COMPACT_DOT_POINT_SIZE : pointSize) *
+ pointSize *
getPointSizeMultiplier(bucketMarkers[0]),
sizeAttenuation: false,
vertexColors: true,
@@ -1433,7 +971,6 @@ export function createInteractableLayer(options = {}) {
bucketKey,
markers: bucketMarkers,
pointSizeMultiplier: getPointSizeMultiplier(bucketMarkers[0]),
- transitionStartedAt: getNowMs(),
};
pointObjects.push(points);
pointsGroup.add(points);
@@ -1443,7 +980,6 @@ export function createInteractableLayer(options = {}) {
function buildPoints(camera = null) {
refreshViewportSize();
- const compactDotMode = camera ? shouldUseCompactDots(camera) : false;
pointsGroup = new THREE.Group();
pointsGroup.visible = visible;
pointsGroup.renderOrder = renderOrder;
@@ -1452,7 +988,7 @@ export function createInteractableLayer(options = {}) {
const buckets = new Map();
markers
- .filter((marker) => !marker.userData?.icon_cluster_hidden && isItemVisible(marker.userData))
+ .filter((marker) => !marker.userData?.icon_cluster_hidden && !marker.userData?.icon_presentation_hidden && isItemVisible(marker.userData))
.forEach((marker) => {
const key = getBucketKey(marker);
if (!buckets.has(key)) {
@@ -1462,70 +998,12 @@ export function createInteractableLayer(options = {}) {
});
buckets.forEach((bucketMarkers, bucketKey) => {
- addPointBucket(bucketKey, bucketMarkers, compactDotMode);
+ addPointBucket(bucketKey, bucketMarkers);
});
group.add(pointsGroup);
}
- function buildClusters() {
- if (ownedClusterRecords.length === 0) return;
-
- clusterGroup = new THREE.Group();
- clusterGroup.visible = visible;
- clusterGroup.renderOrder = renderOrder + 0.05;
- clusterGroup.userData = { type: `${id}_clusters`, id };
-
- ownedClusterRecords.forEach((record) => {
- if (!(record.position instanceof THREE.Vector3) || record.markers.length < 2) return;
- const geometry = new THREE.BufferGeometry();
- geometry.setAttribute(
- "position",
- new THREE.BufferAttribute(
- new Float32Array([
- record.position.x,
- record.position.y,
- record.position.z,
- ]),
- 3,
- ),
- );
- geometry.computeBoundingSphere();
-
- const material = applyIconAnchor(
- new THREE.PointsMaterial({
- map: createClusterTexture(record.markers),
- size: record.pointSize,
- sizeAttenuation: false,
- transparent: true,
- opacity: baseOpacity,
- depthWrite,
- depthTest,
- alphaTest,
- }),
- );
- const points = new THREE.Points(geometry, material);
- points.renderOrder = renderOrder + 0.05;
- points.frustumCulled = false;
- points.userData = {
- type: `${id}_cluster`,
- id,
- clusterId: record.clusterId,
- markers: record.markers,
- clusterPointSize: record.pointSize,
- transitionStartedAt: record.transitionStartedAt || getNowMs(),
- };
- clusterPointObjects.push(points);
- clusterGroup.add(points);
- });
-
- if (clusterGroup.children.length > 0) {
- group.add(clusterGroup);
- } else {
- clusterGroup = null;
- }
- }
-
function ensureOverlay(kind) {
const existing = kind === "locked" ? lockedOverlay : hoverOverlay;
if (existing) return existing;
@@ -1548,7 +1026,9 @@ export function createInteractableLayer(options = {}) {
}),
);
const overlay = new THREE.Points(geometry, material);
- overlay.renderOrder = renderOrder + (kind === "locked" ? 0.2 : 0.1);
+ overlay.renderOrder = kind === "locked"
+ ? Math.max(renderOrder + 0.2, INTERACTABLE_FOCUS_RENDER_ORDER)
+ : Math.max(renderOrder + 0.1, INTERACTABLE_FOCUS_RENDER_ORDER - 0.1);
overlay.frustumCulled = false;
overlay.visible = false;
overlay.userData = { type: `${id}_${kind}_overlay`, id };
@@ -1562,21 +1042,21 @@ export function createInteractableLayer(options = {}) {
return overlay;
}
- function updateOverlay(overlay, marker, state, nextOpacity, sizeMultiplier = 1, compactDotMode = false) {
+ function updateOverlay(overlay, marker, state, nextOpacity, sizeMultiplier = 1) {
if (!overlay) return;
- if (!marker || !isItemVisible(marker.userData)) {
+ if (!marker || marker.userData.icon_cluster_hidden || marker.userData.icon_presentation_hidden || !isItemVisible(marker.userData)) {
overlay.visible = false;
return;
}
- const texture = createOverlayTexture(marker, state, compactDotMode);
+ const texture = createOverlayTexture(marker, state);
if (overlay.material.map !== texture) {
overlay.material.map = texture;
overlay.material.needsUpdate = true;
}
overlay.material.opacity = nextOpacity;
overlay.material.size =
- (compactDotMode ? COMPACT_DOT_POINT_SIZE : pointSize) *
+ pointSize *
getPointSizeMultiplier(marker) *
sizeMultiplier;
const positionAttribute = overlay.geometry.getAttribute("position");
@@ -1587,7 +1067,6 @@ export function createInteractableLayer(options = {}) {
function clearRenderObjects() {
disposePointsGroup();
- disposeClusterGroup();
hoverOverlay?.geometry?.dispose?.();
hoverOverlay?.material?.dispose?.();
hoverOverlay?.parent?.remove?.(hoverOverlay);
@@ -1618,21 +1097,20 @@ export function createInteractableLayer(options = {}) {
}
function refreshVisuals() {
- invalidateScreenAvoidance();
invalidateVisualState();
invalidateClusterTopology();
- if (!pointsGroup && !clusterGroup) return;
+ if (!pointsGroup) return;
rebuildPointLayers();
group.visible = visible;
}
function setData(items = []) {
- invalidateScreenAvoidance();
invalidateVisualState();
invalidateClusterTopology();
unregisterLayerAvoidance(id);
markers.length = 0;
markerById.clear();
+ currentMarkers = new WeakSet();
clearRenderObjects();
disposeGroupChildren(group);
@@ -1653,12 +1131,14 @@ export function createInteractableLayer(options = {}) {
icon_layer_id: id,
icon_kind: kind,
icon_base_position: position.clone(),
+ icon_presentation_hidden: false,
+ icon_presentation_screen: null,
icon_avoidance_key: avoidanceKey,
state: "normal",
};
marker.userData.legend_filtered = !isItemVisible(marker.userData);
markers.push(marker);
- markerById.set(String(getItemId(marker.userData)), marker);
+ indexMarker(marker);
});
registerLayerAvoidance(id, markers, avoidanceConfig);
@@ -1706,7 +1186,7 @@ export function createInteractableLayer(options = {}) {
pointSlots.set(marker, { points, index });
});
if (bucketMarkers.length) markAttributeRange(positions, 0, bucketMarkers.length * 3);
- updatePointColors(points, false);
+ updatePointColors(points);
}
function updateItems(items, { replace = false } = {}) {
@@ -1722,17 +1202,19 @@ export function createInteractableLayer(options = {}) {
const incomingIds = new Set();
const radius = CONFIG.earthRadius + altitudeOffset;
for (const item of items) {
- const itemId = String(getItemId(item) ?? "");
+ const itemId = itemKey(item);
if (!itemId) continue;
const position = normalizePosition(getPosition(item), radius);
if (!position) continue;
incomingIds.add(itemId);
+ if (markerById.has(itemId) && markerById.get(itemId) === null) continue;
let marker = markerById.get(itemId);
const previousBucket = marker ? getBucketKey(marker) : null;
const previousVisible = marker ? isItemVisible(marker.userData) : false;
if (!marker) {
marker = new THREE.Object3D();
markers.push(marker);
+ currentMarkers.add(marker);
markerById.set(itemId, marker);
}
marker.position.copy(position);
@@ -1742,6 +1224,7 @@ export function createInteractableLayer(options = {}) {
type: objectType,
icon_layer_id: id,
icon_kind: getKind(item),
+ icon_item_id: itemId,
icon_base_position: position,
state: marker.userData.state || "normal",
};
@@ -1756,11 +1239,12 @@ export function createInteractableLayer(options = {}) {
if (replace) {
let writeIndex = 0;
for (const marker of markers) {
- const itemId = String(getItemId(marker.userData));
+ const itemId = itemKey(marker.userData);
if (incomingIds.has(itemId)) markers[writeIndex++] = marker;
else {
affectedBuckets.add(getBucketKey(marker));
markerById.delete(itemId);
+ currentMarkers.delete(marker);
}
}
markers.length = writeIndex;
@@ -1794,7 +1278,7 @@ export function createInteractableLayer(options = {}) {
let replaced = false;
const nextItems = markers.map((marker) => {
const markerItem = marker.userData || {};
- if (String(getItemId(markerItem)) !== String(itemId)) return { ...markerItem };
+ if (itemKey(markerItem) !== String(itemId).trim()) return { ...markerItem };
replaced = true;
return { ...markerItem, ...item };
});
@@ -1811,7 +1295,7 @@ export function createInteractableLayer(options = {}) {
}
const nextItems = markers
.map((marker) => ({ ...(marker.userData || {}) }))
- .filter((item) => String(getItemId(item)) !== String(itemId));
+ .filter((item) => itemKey(item) !== String(itemId).trim());
if (nextItems.length === markers.length) return false;
rebuildFromMarkerData(nextItems);
return true;
@@ -1854,12 +1338,12 @@ export function createInteractableLayer(options = {}) {
}
function clearData(parent) {
- invalidateScreenAvoidance();
invalidateVisualState();
invalidateClusterTopology();
unregisterLayerAvoidance(id);
markers.length = 0;
markerById.clear();
+ currentMarkers = new WeakSet();
clearRenderObjects();
disposeGroupChildren(group);
if (parent && group.parent === parent) {
@@ -1876,16 +1360,12 @@ export function createInteractableLayer(options = {}) {
function setVisible(nextVisible) {
visible = Boolean(nextVisible);
- invalidateScreenAvoidance();
invalidateVisualState();
invalidateClusterTopology();
group.visible = visible;
if (pointsGroup) {
pointsGroup.visible = visible;
}
- if (clusterGroup) {
- clusterGroup.visible = visible;
- }
}
function setMarkerState(marker, state = "normal") {
@@ -1897,12 +1377,10 @@ export function createInteractableLayer(options = {}) {
function updateVisualState(focusType, focusObject, camera) {
refreshViewportSize();
- recomputeScreenAvoidance(camera);
const hasFocus = focusType === objectType && focusObject;
if (!visible || markers.length === 0 || !pointsGroup) {
if (lastVisualStateKey !== "hidden") {
if (pointsGroup) pointsGroup.visible = false;
- if (clusterGroup) clusterGroup.visible = false;
if (hoverOverlay) hoverOverlay.visible = false;
if (lockedOverlay) lockedOverlay.visible = false;
lastVisualStateKey = "hidden";
@@ -1911,7 +1389,6 @@ export function createInteractableLayer(options = {}) {
}
pointsGroup.visible = true;
- if (clusterGroup) clusterGroup.visible = true;
const lockedKey = hasFocus
? focusObject?.userData?.mmsi || focusObject?.uuid || "locked"
: "none";
@@ -1923,60 +1400,33 @@ export function createInteractableLayer(options = {}) {
].join(":");
const cameraScale = getCameraScale(camera);
- const compactDotMode = shouldUseCompactDots(camera);
const scaleKey = usesDistanceScaling ? cameraScale.toFixed(3) : "fixed";
- const nextStateKey = `${stateKey}:${scaleKey}:${compactDotMode ? "dots" : "icons"}`;
+ const nextStateKey = `${stateKey}:${scaleKey}`;
- if (
- nextStateKey === lastVisualStateKey &&
- !(pulse.enabled && hasFocus) &&
- !dynamicVisuals &&
- !hasActiveRenderTransitions()
- ) return;
+ const batchChanged = nextStateKey !== lastVisualStateKey || dynamicVisuals;
+ if (!batchChanged && !(pulse.enabled && hasFocus)) return;
lastVisualStateKey = nextStateKey;
- pointObjects.forEach((points) => {
+ // Pulsing changes only the selected overlay. Static batches still refresh
+ // for selection, data, filter, camera-scale or explicit visual changes.
+ if (batchChanged) pointObjects.forEach((points) => {
const sampleMarker = points.userData?.markers?.[0];
- const nextTexture = compactDotMode
- ? createCompactDotTexture(sampleMarker)
- : createPointTexture(points.userData?.bucketKey, points.userData?.markers || []);
+ const nextTexture = createPointTexture(points.userData?.bucketKey, points.userData?.markers || []);
if (points.material.map !== nextTexture) {
points.material.map = nextTexture;
points.material.needsUpdate = true;
}
- updatePointColors(points, compactDotMode);
+ updatePointColors(points);
points.visible = visible && points.userData.markers.length > 0;
- const transitionProgress = getTransitionProgress(
- points.userData?.transitionStartedAt,
- clusterConfig.transitionMs,
- );
- const transitionScale = 0.82 + transitionProgress * 0.18;
points.material.opacity =
getPointOpacity?.(sampleMarker) ??
- (hasFocus ? dimmedOpacity : baseOpacity) * transitionProgress;
+ (hasFocus ? dimmedOpacity : baseOpacity);
points.material.size =
- (compactDotMode ? COMPACT_DOT_POINT_SIZE : pointSize) *
+ pointSize *
getPointSizeMultiplier(sampleMarker) *
cameraScale *
- (hasFocus ? dimmedScale : 1) *
- transitionScale;
+ (hasFocus ? dimmedScale : 1);
});
- clusterPointObjects.forEach((points) => {
- points.visible = visible;
- const transitionProgress = getTransitionProgress(
- points.userData?.transitionStartedAt,
- clusterConfig.transitionMs,
- );
- const transitionScale = 0.68 + transitionProgress * 0.32;
- const pulseScale = 1 + Math.sin(Date.now() / 260) * 0.018;
- points.material.opacity = (hasFocus ? dimmedOpacity : baseOpacity) * transitionProgress;
- points.material.size =
- (points.userData?.clusterPointSize || COMPACT_DOT_POINT_SIZE) *
- (hasFocus ? dimmedScale : 1) *
- transitionScale *
- pulseScale;
- });
-
const hoverMarker = markers.find(
(marker) => marker.userData?.state === "hover" && marker !== focusObject,
);
@@ -1986,7 +1436,6 @@ export function createInteractableLayer(options = {}) {
"hover",
hoverOpacity,
hoverScale * cameraScale,
- compactDotMode,
);
const lockedPulse =
pulse.enabled && hasFocus
@@ -1998,7 +1447,6 @@ export function createInteractableLayer(options = {}) {
"locked",
lockedOpacity,
lockedScale * lockedPulse * cameraScale,
- compactDotMode,
);
}
@@ -2022,60 +1470,10 @@ export function createInteractableLayer(options = {}) {
const radiusSq = radiusPx * radiusPx;
const intersections = [];
const cameraScale = getCameraScale(camera);
- const compactDotMode = shouldUseCompactDots(camera);
- const visualPointSize = compactDotMode ? COMPACT_DOT_POINT_SIZE : pointSize;
-
- clusterPointObjects.forEach((clusterPoints) => {
- const clusterMarkers = clusterPoints.userData?.markers || [];
- const positionAttribute = clusterPoints.geometry?.getAttribute("position");
- if (!positionAttribute || clusterMarkers.length === 0) return;
-
- scratchDirection
- .set(
- positionAttribute.getX(0),
- positionAttribute.getY(0),
- positionAttribute.getZ(0),
- )
- .normalize();
- scratchWorldPosition.set(positionAttribute.getX(0), positionAttribute.getY(0), positionAttribute.getZ(0));
- if (usesSurfaceAnchorOcclusion
- ? !isSurfaceAnchorVisible(scratchWorldPosition, scratchCameraPositionLocal, CONFIG.earthRadius)
- : scratchCameraLocal.dot(scratchDirection) <= frontFacingDotThreshold) return;
-
- scratchWorldPosition.set(
- positionAttribute.getX(0),
- positionAttribute.getY(0),
- positionAttribute.getZ(0),
- );
- earth.localToWorld(scratchWorldPosition);
- scratchScreenPosition.copy(scratchWorldPosition).project(camera);
- if (scratchScreenPosition.z < -1 || scratchScreenPosition.z > 1) {
- return;
- }
-
- const screenX = (scratchScreenPosition.x * 0.5 + 0.5) * width;
- const screenY = (-scratchScreenPosition.y * 0.5 + 0.5) * height;
- const deltaX = screenX - pointerX;
- const deltaY = screenY - pointerY;
- const clusterPointSize =
- clusterPoints.userData?.clusterPointSize || COMPACT_DOT_POINT_SIZE;
- const clusterRadius = Math.max(radiusPx, clusterPointSize * 0.9);
- const distancePxSq = deltaX * deltaX + deltaY * deltaY;
- if (distancePxSq > clusterRadius * clusterRadius) return;
-
- intersections.push({
- cluster: true,
- clusterCount: clusterMarkers.length,
- clusterMarkers,
- object: null,
- point: scratchWorldPosition.clone(),
- distance: camera.position.distanceTo(scratchWorldPosition),
- distancePxSq,
- });
- });
+ const visualPointSize = pointSize;
markers.forEach((marker) => {
- if (marker.userData?.icon_cluster_hidden || !isItemVisible(marker.userData)) return;
+ if (marker.userData?.icon_cluster_hidden || marker.userData?.icon_presentation_hidden || !isItemVisible(marker.userData)) return;
scratchDirection.copy(marker.position).normalize();
if (usesSurfaceAnchorOcclusion
? !isSurfaceAnchorVisible(marker.position, scratchCameraPositionLocal, CONFIG.earthRadius)
@@ -2125,11 +1523,29 @@ export function createInteractableLayer(options = {}) {
if (lockedOverlay) lockedOverlay.visible = false;
}
+ function getMarkerImage(marker) {
+ const color = icon.colorable === false ? "#ffffff" : getMarkerColor(marker);
+ const image = drawIconTexture(`projected:${getBucketKey(marker)}:${color}`, {
+ marker, color, rotationBin:getRotationBin(marker), glow:false, state:"normal",
+ }).image;
+ if (!projectedTextureUrls.has(image)) projectedTextureUrls.set(image, image.toDataURL());
+ return projectedTextureUrls.get(image);
+ }
+
const controller = {
+ group,
+ isMarkerVisible: marker => visible && markers.includes(marker) && isItemVisible(marker.userData),
+ getMarkerColor,
+ getMarkerSize: (marker, camera) => pointSize * getPointSizeMultiplier(marker) * getCameraScale(camera),
+ getMarkerImage,
+ resolveMarker: marker => currentMarkers.has(marker) ? marker
+ : marker?.userData?.icon_item_id === null ? null : markerById.get(itemKey(marker?.userData)),
+ getPresentationMarkers: () => visible && clusterConfig.enabled
+ ? markers.filter(marker => isItemVisible(marker.userData)) : [],
refreshPositions,
refreshVisuals,
beginClusterUpdate,
- collectClusterEntries,
+ collectClusterRecords,
addOwnedCluster,
markMarkerClustered,
commitClusterUpdate,
@@ -2141,6 +1557,7 @@ export function createInteractableLayer(options = {}) {
group,
markers,
getMarkers: () => markers,
+ getMarkerImage,
getCount: () => markers.length,
refreshFilter,
isVisible: () => visible,
diff --git a/frontend/public/earth/js/interactive-picking.js b/frontend/public/earth/js/interactive-picking.js
new file mode 100644
index 00000000..f3f543f3
--- /dev/null
+++ b/frontend/public/earth/js/interactive-picking.js
@@ -0,0 +1,29 @@
+// Shared screen-pick ordering for surface icon layers.
+// Smaller screen distance wins; the priority only resolves a true overlap.
+export const INTERACTIVE_PICK_PRIORITY = Object.freeze({
+ earth_interactable: 50,
+ compute_center: 40,
+ bgp: 30,
+ bgp_collector: 20,
+ vessel: 10,
+});
+
+export function pickNearestInteractiveHit(groups = []) {
+ const candidates = [];
+ groups.forEach(({ type, hits = [] }) => {
+ hits.forEach((hit) => {
+ if (!hit?.object || hit.cluster) return;
+ candidates.push({
+ type,
+ hit,
+ object: hit.object,
+ distancePxSq: Number.isFinite(hit.distancePxSq) ? hit.distancePxSq : Infinity,
+ priority: INTERACTIVE_PICK_PRIORITY[type] || 0,
+ });
+ });
+ });
+ candidates.sort((left, right) =>
+ left.distancePxSq - right.distancePxSq || right.priority - left.priority,
+ );
+ return candidates[0] || null;
+}
diff --git a/frontend/public/earth/js/interactive-picking.test.js b/frontend/public/earth/js/interactive-picking.test.js
new file mode 100644
index 00000000..7f95c912
--- /dev/null
+++ b/frontend/public/earth/js/interactive-picking.test.js
@@ -0,0 +1,25 @@
+import { expect, test } from "bun:test";
+import { pickNearestInteractiveHit } from "./interactive-picking.js";
+
+const hit = (object, distancePxSq, cluster = false) => ({ object, distancePxSq, cluster });
+
+test("screen distance wins across icon layers", () => {
+ expect(pickNearestInteractiveHit([
+ { type: "bgp_collector", hits: [hit("rrc26", 64)] },
+ { type: "compute_center", hits: [hit("gpu", 9)] },
+ ]).object).toBe("gpu");
+});
+
+test("render priority resolves an exact overlap without letting the lower collector steal it", () => {
+ expect(pickNearestInteractiveHit([
+ { type: "bgp_collector", hits: [hit("rrc22", 16)] },
+ { type: "compute_center", hits: [hit("gpu", 16)] },
+ ]).object).toBe("gpu");
+});
+
+test("cluster hits are ignored while pointer eligibility remains true for real markers", () => {
+ expect(pickNearestInteractiveHit([
+ { type: "compute_center", hits: [hit("cluster", 1, true)] },
+ { type: "bgp_collector", hits: [hit("rrc22", 9)] },
+ ]).object).toBe("rrc22");
+});
diff --git a/frontend/public/earth/js/legend-filters.js b/frontend/public/earth/js/legend-filters.js
index 9d8c80d7..7b515b36 100644
--- a/frontend/public/earth/js/legend-filters.js
+++ b/frontend/public/earth/js/legend-filters.js
@@ -1,3 +1,4 @@
+import { normalizeComputeSiteType } from "./compute-site-types.js";
const hiddenByMode = new Map();
export const LEGEND_FILTER_EVENT = "earth:legend-filter-change";
export function isLegendItemEnabled(mode, key) {
@@ -33,7 +34,7 @@ export function isVesselLegendVisible(data) {
export function revealLegendObject(type, data = {}) {
if (type === "cable") setLegendItemEnabled("cables", data.name || "未知线缆", true);
if (type === "landing_point") (data.cableNames || []).forEach(name => setLegendItemEnabled("cables", name, true));
- if (type === "compute_center") setLegendItemEnabled("computeCenters", data.site_type === "supercomputer" ? "supercomputer" : "gpu_cluster", true);
+ if (type === "compute_center") setLegendItemEnabled("computeCenters", normalizeComputeSiteType(data.site_type), true);
if (type === "vessel") vesselLegendKeys(data).forEach(key => setLegendItemEnabled("vessels", key, true));
if (type === "bgp") setLegendItemEnabled("bgp", `event:${data.icon_kind || data.severity || "medium"}`, true);
if (type === "bgp_collector") setLegendItemEnabled("bgp", collectorLegendKey(data.icon_kind || data.activity?.tier), true);
diff --git a/frontend/public/earth/js/main.js b/frontend/public/earth/js/main.js
index c08345ae..af0c8833 100644
--- a/frontend/public/earth/js/main.js
+++ b/frontend/public/earth/js/main.js
@@ -1,3 +1,10 @@
+import { bgpEventIdentity } from "./bgp-identity.js";
+import { normalizeComputeSiteType } from "./compute-site-types.js";
+import { createFrameProfile } from "./frame-profile.js";
+import { createFrameStageRunner } from "./frame-stages.js";
+import { initNewsRegionCards } from "./news-region-cards.js";
+import { createSpatialCallouts, createCalloutGroups } from "./spatial-callouts.js";
+import { updateInteractableClusters, clearInteractableClusters } from "./interactable.js";
import { LEGEND_FILTER_EVENT, revealLegendObject } from "./legend-filters.js";
import { applyCableLegendFilter } from "./cables.js";
import { applyComputeCenterLegendFilter } from "./compute-centers.js";
@@ -6,6 +13,7 @@ import { applyBGPLegendFilter } from "./bgp.js";
import { applyCountryBoundaryLegendFilter } from "./country-boundaries.js";
import { isSatelliteCategoryVisible, updateSatelliteLabels } from "./satellites.js";
import { beginFrameStats, finishFrameStats } from "./frame-stats.js";
+import { pickNearestInteractiveHit } from "./interactive-picking.js";
import { createScreenSpaceDrag, globeDragRotationFactor } from "./globe-navigation.js";
import * as THREE from "three";
@@ -43,6 +51,7 @@ import {
import { vector3ToLatLon, screenToEarthCoords } from "./utils.js";
import {
showStatusMessage,
+ showSelectionStatus,
queueStatusMessage,
updateCoordinatesDisplay,
updateEarthStats,
@@ -129,7 +138,8 @@ import {
getSatelliteAt,
selectSatellite,
getSatellitePoints,
- getSatellitePresentationInfo,
+ getSatelliteRenderMetrics,
+ getSatelliteConstellationLabel,
setSatelliteRingState,
updateLockedRingPosition,
updateHoverRingPosition,
@@ -179,7 +189,6 @@ import {
formatBGPRouteChange,
formatBGPTopEventTypes,
formatBGPScope,
- formatBGPCollectorCoverageHalo,
formatBGPSeverityLabel,
formatBGPStatusLabel,
showBGPEventOverlay,
@@ -191,8 +200,6 @@ import {
clearComputeCenterLocationPreview,
formatComputeCenterCapacity,
formatComputeCenterLocationPrecision,
- formatComputeCenterLocationConfidence,
- formatComputeCenterLocationSource,
formatComputeCenterNeedsConfirmation,
formatComputeCenterTypeLabel,
formatComputeCenterUpdatedAt,
@@ -292,7 +299,6 @@ import { createMotionCruiseAdapter } from "./motion-cruise-adapter.js";
import { PresentationController } from "./presentation-controller.js";
import {
getComputeCenterLocationBatchState,
- initInfoCard,
showInfoCard,
hideInfoCard,
isInfoCardSticky,
@@ -365,10 +371,6 @@ let lockedSatelliteIndex = null;
let lockedObject = null;
let lockedObjectType = null;
let dragStartTime = 0;
-let isLongDrag = false;
-let lastSatClickTime = 0;
-let lastSatClickIndex = 0;
-let lastSatClickPos = { x: 0, y: 0 };
let lastBGPClickTime = 0;
let lastBGPClickCollector = null;
let lastBGPClickType = null;
@@ -390,6 +392,29 @@ let sceneLights = null;
let cruisePollTimerId = null;
let calloutConnector = null;
let computeTopic = null;
+let newsRegionCards = null;
+let regionCallouts = null;
+const frameStages = createFrameStageRunner();
+let geometryProfileAt = 0;
+const frameProfile = createFrameProfile(new URLSearchParams(window.location.search).has("profileFrames"),
+ stages => {
+ document.documentElement.dataset.earthFrameProfile = JSON.stringify(stages);
+ if (performance.now() - geometryProfileAt > 5000) {
+ geometryProfileAt = performance.now();
+ const lines = [];
+ scene?.traverseVisible(object => {
+ if (object.isLine && object.geometry?.attributes.position) lines.push({
+ name:object.name || object.userData?.type || "line",
+ vertices:object.geometry.index?.count || object.geometry.attributes.position.count,
+ });
+ });
+ document.documentElement.dataset.earthLineMetrics = JSON.stringify(lines.sort((a,b)=>b.vertices-a.vertices).slice(0,8));
+ }
+ document.documentElement.dataset.earthRenderMetrics = JSON.stringify({
+ ...renderer?.info.render,satellites:getSatelliteRenderMetrics(),zoom:getZoomLevel(),
+ width:renderer?.domElement.width,height:renderer?.domElement.height,
+ });
+ });
let cruiseBGPAdapter = null;
let cruiseNewsAdapter = null;
let cruiseSequencer = null;
@@ -553,6 +578,7 @@ function publishWebGLGpuDiagnostics(activeRenderer) {
const diagnostics = getWebGLGpuDiagnostics(activeRenderer);
if (!diagnostics) return;
window.__planetEarthGpu = diagnostics;
+ document.documentElement.dataset.earthGpuRenderer = diagnostics.renderer;
console.info("[智能星球] WebGL GPU diagnostics", diagnostics);
window.dispatchEvent(new CustomEvent(WEBGL_GPU_DIAGNOSTICS_EVENT, { detail: diagnostics }));
}
@@ -561,13 +587,15 @@ function syncRendererViewport() {
if (!camera || !renderer) return;
camera.aspect = getViewportAspect();
camera.updateProjectionMatrix();
+ const pixelRatio = window.devicePixelRatio || 1;
+ if (renderer.getPixelRatio() !== pixelRatio) renderer.setPixelRatio(pixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
}
function isEventOnHud(event) {
const target = event?.target;
if (!(target instanceof Element)) return false;
- return HUD_INTERACTIVE_SELECTORS.some((selector) => target.closest(selector));
+ return Boolean(target.closest(".map-clusters")) || HUD_INTERACTIVE_SELECTORS.some((selector) => target.closest(selector));
}
function clearDocumentSelection() {
@@ -715,7 +743,8 @@ function isSameBGPMarker(marker1, marker2) {
if (type1 !== type2) return false;
if (type1 === "bgp") {
- return marker1.userData?.id === marker2.userData?.id;
+ const identity = bgpEventIdentity(marker1.userData);
+ return identity !== null && identity === bgpEventIdentity(marker2.userData);
}
if (type1 === "bgp_collector") {
return marker1.userData?.collector === marker2.userData?.collector;
@@ -935,18 +964,14 @@ function getFirstObjectIntersection(intersections) {
return intersections.find((hit) => !hit?.cluster && hit?.object)?.object || null;
}
-function getPrimaryClusterHit(...intersectionGroups) {
- return intersectionGroups
- .flat()
- .filter((hit) => hit?.cluster && Number(hit.clusterCount) > 1)
- .sort((a, b) => a.distancePxSq - b.distancePxSq)[0] || null;
-}
-
-function getClusterBriefHtml(hit) {
- const count = Number(hit?.clusterCount || hit?.clusterMarkers?.length || 0);
- const title = isEnglishEarthLocale() ? `${count} objects` : `共 ${count} 个对象`;
- const hint = isEnglishEarthLocale() ? "Zoom in to inspect individual markers" : "放大后可查看单个图标";
- return `
${title}${hint}`;
+function pickInteractiveIcon({ bgpAnomalyIntersects = [], bgpCollectorIntersects = [], computeCenterIntersects = [], vesselIntersects = [], earthInteractableIntersects = [] } = {}) {
+ return pickNearestInteractiveHit([
+ { type: "bgp", hits: bgpAnomalyIntersects },
+ { type: "bgp_collector", hits: bgpCollectorIntersects },
+ { type: "compute_center", hits: computeCenterIntersects },
+ { type: "vessel", hits: vesselIntersects },
+ { type: "earth_interactable", hits: earthInteractableIntersects },
+ ]);
}
function getPrimaryBGPHoverTarget(bgpAnomalyIntersects, bgpCollectorIntersects) {
@@ -1199,7 +1224,8 @@ function getMotionCableCandidates() {
function getMotionFocusKey(candidate) {
if (!candidate) return "";
- if (candidate.type === "satellite") return `satellite:${candidate.index}`;
+ if (candidate.type === "satellite") return `satellite:${candidate.object?.properties?.norad_cat_id ?? candidate.object?.properties?.norad_id ?? candidate.index}`;
+ if (candidate.type === "bgp") return `bgp:${bgpEventIdentity(candidate.object?.userData) ?? candidate.object?.uuid}`;
if (candidate.type === "cable") return `cable:${candidate.object?.userData?.cableId || candidate.object?.userData?.name || ""}`;
return `${candidate.type}:${candidate.object?.userData?.id || candidate.object?.userData?.collector || candidate.object?.userData?.mmsi || candidate.object?.userData?.name || ""}`;
}
@@ -1543,7 +1569,7 @@ export async function applyMotionFocus(direction = "next") {
applyMotionFocusVisual(candidate);
await presentMotionCandidate(candidate);
showStatusMessage(
- earthMessage("status.motionSwitchedTo", { label: getMotionCandidateLabel(candidate) }),
+ earthMessage("status.motionSwitchedTo", { label: getInteractionCandidateLabel(candidate) }),
"info",
);
return true;
@@ -1618,7 +1644,7 @@ function getMotionCandidateFocusCoords(candidate) {
return null;
}
-function getMotionCandidateLabel(candidate) {
+function getInteractionCandidateLabel(candidate) {
if (!candidate) return "目标";
if (candidate.type === "satellite") return candidate.object?.properties?.name || "卫星";
return (
@@ -1669,7 +1695,7 @@ function dismissMotionPresentationsForConfirmation() {
presentationController?.dismiss?.("motion_confirm");
}
-function confirmMotionCandidate(candidate, { showMotionStatus = true } = {}) {
+function confirmInteractionCandidate(candidate, { showConfirmationFeedback = true } = {}) {
const earth = getEarth();
if (!candidate || !earth) return false;
interruptCruisePresentation();
@@ -1743,16 +1769,13 @@ function confirmMotionCandidate(candidate, { showMotionStatus = true } = {}) {
motionFocusedCandidate = candidate;
const presentation = presentSelectedObject(candidate);
- if (showMotionStatus) {
+ if (showConfirmationFeedback) {
presentation.then(presented => {
if (presented) window.dispatchEvent(new CustomEvent("earth:open-details-tab"));
});
}
- if (showMotionStatus) {
- showStatusMessage(
- earthMessage("status.motionConfirmed", { label: getMotionCandidateLabel(candidate) }),
- "info",
- );
+ if (showConfirmationFeedback) {
+ showSelectionStatus(getInteractionCandidateLabel(candidate));
}
return true;
}
@@ -1760,6 +1783,7 @@ function confirmMotionCandidate(candidate, { showMotionStatus = true } = {}) {
function showCableInfo(cable, coords) {
setLegendMode("cables");
showInfoCard("cable", {
+ source_id: cable.userData.source_id,
name: cable.userData.name,
owner: cable.userData.owner,
status: cable.userData.status,
@@ -1782,24 +1806,14 @@ function showSatelliteInfo(props, coords) {
props?.mean_motion,
props?.eccentricity,
);
- const presentation = getSatellitePresentationInfo(props);
-
- let footprintModel = "不适用";
- if (presentation.footprintPolicy === "starlink_ground_footprint") {
- footprintModel = "Starlink 单星地表覆盖";
- } else if (presentation.footprintPolicy === "iridium_coverage_ring") {
- footprintModel = "Iridium 外圈半透明覆盖";
- }
+ const constellationLabel = getSatelliteConstellationLabel(props);
setLegendItems("satellites", getSatelliteLegendItems());
setLegendMode("satellites");
showInfoCard("satellite", {
name: props?.name || "-",
norad_id: props?.norad_cat_id,
- constellation: presentation.constellationLabel,
- footprint_capability: presentation.footprintCapabilityLabel,
- current_display: presentation.presentationModeLabel,
- footprint_model: footprintModel,
+ constellation: constellationLabel,
inclination: props?.inclination ? props.inclination.toFixed(2) : "-",
period,
perigee: altitudeRange?.perigee ?? "-",
@@ -1842,9 +1856,7 @@ function getSatelliteBriefHtml(props) {
}
function showComputeCenterInfo(marker, coords) {
- const siteType = marker.userData?.site_type === "supercomputer"
- ? "supercomputer"
- : "gpu_cluster";
+ const siteType = normalizeComputeSiteType(marker.userData?.site_type);
setLegendMode("computeCenters");
const ud = marker.userData || {};
showInfoCard(siteType, {
@@ -1867,14 +1879,8 @@ function showComputeCenterInfo(marker, coords) {
location_precision: ud.location_precision,
location_precision_label: formatComputeCenterLocationPrecision(ud),
location_source: ud.location_source,
- location_source_label: formatComputeCenterLocationSource(ud),
location_status_label: formatComputeCenterNeedsConfirmation(ud),
needs_confirmation: ud.needs_confirmation === true,
- estimated_reason: ud.estimated_reason || "-",
- location_confidence: formatComputeCenterLocationConfidence(ud),
- location_source_note: ud.location_source_note || "-",
- matched_location_name: ud.matched_location_name || "-",
- location_verified_at: ud.location_verified_at || "-",
source: ud.source || "-",
updated_at: formatComputeCenterUpdatedAt(ud.updated_at),
}, coords);
@@ -1984,6 +1990,7 @@ function showBGPInfo(marker, coords) {
? marker.userData.summary
: buildBGPIncidentNarrative(marker, impactedRegions);
showInfoCard("bgp", {
+ incident_key: marker.userData.incident_key,
anomaly_type: formatBGPAnomalyTypeLabel(
marker.userData.incident_type || marker.userData.anomaly_type,
),
@@ -2056,7 +2063,6 @@ function showBGPCollectorInfo(marker, coords) {
prefix_count: marker.userData.prefix_count ?? 0,
origin_asn_count: marker.userData.origin_asn_count ?? 0,
top_event_types: formatBGPTopEventTypes(marker.userData.top_event_types),
- coverage_halo: formatBGPCollectorCoverageHalo(marker.userData),
related_satellites: "-",
latest_event_type: marker.userData.latest_event_type || "-",
latest_observed_at: formatBGPObservedTime(marker.userData.latest_observed_at),
@@ -2176,6 +2182,7 @@ function showLandingPointInfo(point, coords) {
showInfoCard(
"landing_point",
{
+ source_id: point?.userData?.source_id,
name: point?.userData?.name || "-",
country: point?.userData?.country || "-",
status: point?.userData?.status || "-",
@@ -2208,6 +2215,7 @@ async function focusSearchCable(cable) {
lockedObjectType = "cable";
handleCableClick(cable);
presentSelectedObject({ type: "cable", object: cable });
+ showSelectionStatus(cable.userData.name);
}
async function focusSearchLandingPoint(point) {
@@ -2235,10 +2243,7 @@ async function focusSearchLandingPoint(point) {
});
applyLandingPointVisualState(relatedCableNames, relatedCableNames.length === 0, camera);
presentSelectedObject({ type: "landing_point", object: point });
- showStatusMessage(
- earthMessage("status.located", { target: "登陆点", name: point.userData?.name || "未知登陆点" }),
- "info",
- );
+ showSelectionStatus(point.userData?.name || "未知登陆点");
}
async function focusSearchSatellite(index) {
@@ -2272,13 +2277,7 @@ async function focusSearchSatellite(index) {
}
}
presentSelectedObject({ type: "satellite", object: sat, index });
- showStatusMessage(
- earthMessage("status.located", {
- target: "卫星",
- name: sat.properties.name || sat.properties.norad_cat_id || "未知卫星",
- }),
- "info",
- );
+ showSelectionStatus(sat.properties.name || sat.properties.norad_cat_id || "未知卫星");
}
async function focusSearchBGPMarker(marker) {
@@ -2302,13 +2301,7 @@ async function focusSearchBGPMarker(marker) {
showBGPEventOverlay(marker, earth);
applyBGPEventSatelliteHighlights(marker);
presentSelectedObject({ type: "bgp", object: marker });
- showStatusMessage(
- earthMessage("status.located", {
- target: "BGP 事件",
- name: marker.userData?.collector || "未知观测站",
- }),
- "info",
- );
+ showSelectionStatus(marker.userData?.collector || "未知观测站");
return;
}
@@ -2318,13 +2311,7 @@ async function focusSearchBGPMarker(marker) {
lockedObjectType = "bgp_collector";
showBGPCollectorCoverageOverlay(marker, earth);
presentSelectedObject({ type: "bgp_collector", object: marker });
- showStatusMessage(
- earthMessage("status.located", {
- target: "观测站",
- name: marker.userData?.collector || "未知观测站",
- }),
- "info",
- );
+ showSelectionStatus(marker.userData?.collector || "未知观测站");
}
}
@@ -2345,13 +2332,7 @@ async function focusSearchComputeCenter(marker) {
lockedObject = marker;
lockedObjectType = "compute_center";
presentSelectedObject({ type: "compute_center", object: marker });
- showStatusMessage(
- earthMessage("status.located", {
- target: "算力中心",
- name: marker.userData?.name || "未知节点",
- }),
- "info",
- );
+ showSelectionStatus(marker.userData?.name || "未知节点");
}
async function previewLocationCandidate(detail) {
@@ -2437,13 +2418,7 @@ async function focusSearchVessel(marker) {
showVesselTrack(marker, getEarth()).catch((error) => {
console.warn("船只轨迹加载失败:", error);
});
- showStatusMessage(
- earthMessage("status.located", {
- target: "船只",
- name: marker.userData?.name || marker.userData?.mmsi || "未知船只",
- }),
- "info",
- );
+ showSelectionStatus(marker.userData?.name || marker.userData?.mmsi || "未知船只");
}
function resolveEarthSearchResults(query) {
@@ -2515,8 +2490,8 @@ function resolveEarthSearchResults(query) {
typeLabel: "卫星",
title: props?.name || `NORAD ${props?.norad_cat_id || index}`,
subtitle: props?.norad_cat_id
- ? `NORAD ${props.norad_cat_id} · ${getSatellitePresentationInfo(props).constellationLabel}`
- : `${getSatellitePresentationInfo(props).constellationLabel} · 在轨卫星`,
+ ? `NORAD ${props.norad_cat_id} · ${getSatelliteConstellationLabel(props)}`
+ : `${getSatelliteConstellationLabel(props)} · 在轨卫星`,
score,
entity: { index },
});
@@ -2861,7 +2836,7 @@ function presentSelectedObject(candidate) {
document.body.classList.contains("layout-mode-mobile") ? "earth-mobile-popup" : "info-panel",
);
const sourceProvider = createObjectCalloutAnchor(candidate, {
- getEarth, getCamera: () => camera, getCablesById, getSatellitePoints, getSatellitePositions,
+ getEarth, getCamera: () => camera, getCablesById, getSatellitePoints, getSatellitePositions, getSatelliteData,
getObstacles: () => {
const target = targetProvider();
if (!target || target.hidden) return [];
@@ -3759,13 +3734,6 @@ function getBGPRelatedCableNames(marker) {
return names;
}
-function getBGPInfrastructureSummary(marker) {
- return {
- cableCount: getBGPRelatedCableNames(marker).length,
- regionCount: getBGPRelatedRegions(marker).length,
- };
-}
-
function buildBGPIncidentNarrative(marker, impactedRegions) {
const eventLabel = formatBGPAnomalyTypeLabel(
marker.userData.incident_type || marker.userData.anomaly_type,
@@ -4196,6 +4164,7 @@ async function ensureSatellitesEnabled() {
return 0;
}
+ reconcileSelectedSatellite();
updateSatelliteToggleUi(true, loadResult.count);
setLegendItems("satellites", getSatelliteLegendItems());
refreshLegend();
@@ -4367,7 +4336,6 @@ export function init() {
});
syncRendererViewport();
renderer.setClearColor(0x02040a, 1);
- renderer.setPixelRatio(window.devicePixelRatio);
publishWebGLGpuDiagnostics(renderer);
const container = document.getElementById("container");
@@ -4377,15 +4345,22 @@ export function init() {
}
sceneLights = addLights();
- initInfoCard();
let topicRequest = 0;
let topicPreviousVisibility = null;
- computeTopic = initComputeTopic({
+ const regionCardRoot = document.createElement("section");
+ regionCardRoot.id = "earth-region-callouts";
+ document.body.append(regionCardRoot);
+ regionCallouts = createCalloutGroups(createSpatialCallouts({
+ root: regionCardRoot,
getSpatialContext: () => ({
earth: getEarth(), camera, isDragging,
activeTouchPoints: activeTouchPoints.size,
hasActiveGlobeInertia: hasActiveGlobeInertia(),
}),
+ }));
+ newsRegionCards = initNewsRegionCards({ rootParent: regionCardRoot, spatial: regionCallouts.scope("news") });
+ computeTopic = initComputeTopic({
+ spatial: regionCallouts.scope("compute"), rootParent: regionCardRoot,
setMapQuery(query) {
const requestId = ++topicRequest;
if (query && topicPreviousVisibility === null) topicPreviousVisibility = getShowComputeCenters();
@@ -4422,7 +4397,16 @@ export function init() {
bindListener(window, "earth:compute-topic-data", (event) => {
computeTopic?.receiveFacilities(event.detail);
});
- cleanupFns.push(() => { setComputeTopicQuery(null); computeTopic?.destroy(); computeTopic = null; });
+ cleanupFns.push(() => {
+ setComputeTopicQuery(null); computeTopic?.destroy(); computeTopic = null;
+ newsRegionCards?.destroy(); newsRegionCards = null;
+ regionCallouts?.destroy(); regionCallouts = null; regionCardRoot.remove();
+ });
+ bindListener(window, "earth:cluster-open", () => { interruptCruisePresentation(); setAutoRotate(false); clearTransientHoverState(); hideTooltip(); });
+ bindListener(window, "earth:spiderfy-select", ({ detail }) => {
+ const marker = detail?.marker;
+ if (marker && !marker.userData.legend_filtered) confirmInteractionCandidate({ type:marker.userData.type, object:marker, screen:detail.screen });
+ });
initLegend();
bindListener(window, LEGEND_FILTER_EVENT, ({ detail }) => {
const handlers = {
@@ -4596,12 +4580,12 @@ export function applyMotionConfirm() {
refreshMotionFocusCandidates({ force: true });
candidate = getCurrentMotionConfirmationCandidate();
}
- if (candidate && confirmMotionCandidate(candidate)) {
+ if (candidate && confirmInteractionCandidate(candidate)) {
return true;
}
if (lockedObject || lockedSatellite) {
window.dispatchEvent(new CustomEvent("earth:open-details-tab"));
- showStatusMessage(earthMessage("status.motionConfirmCurrent"), "info");
+ showSelectionStatus(getInteractionCandidateLabel({ type: lockedObjectType, object: lockedObject || lockedSatellite }));
return true;
}
showStatusMessage(earthMessage("status.motionSelectTargetFirst"), "info");
@@ -4710,6 +4694,21 @@ function getInitialSatelliteLoadLimit() {
return configuredInitial;
}
+function reconcileSelectedSatellite() {
+ hoveredSatelliteIndex = null;
+ setHoveredSatelliteIndex(null);
+ if (lockedObjectType !== "satellite" || !lockedSatellite) return;
+ const norad = lockedSatellite.properties?.norad_cat_id ?? lockedSatellite.properties?.norad_id;
+ const index = norad == null ? -1 : getSatelliteData().findIndex(item =>
+ String(item.properties?.norad_cat_id ?? item.properties?.norad_id) === String(norad));
+ if (index < 0) { clearLockedObjectAndInfo(); return; }
+ lockedSatellite = selectSatellite(index);
+ lockedObject = lockedSatellite;
+ lockedSatelliteIndex = index;
+ setLockedSatelliteIndex(index);
+ showPredictedOrbit(lockedSatellite);
+}
+
function shouldHydrateFullSatelliteSet(loadResult) {
if (!SATELLITE_CONFIG.hydrateFullAfterInitialLoad) return false;
if (!loadResult || loadResult.requestedLimit === null) return false;
@@ -4720,6 +4719,7 @@ async function hydrateAllSatellitesInBackground(guardFn) {
try {
const loadResult = await loadSatellites({ limit: null, cacheBust: true });
if (!guardFn()) return;
+ reconcileSelectedSatellite();
updateSatelliteToggleUi(true, loadResult.count);
setLegendItems("satellites", getSatelliteLegendItems());
refreshLegend();
@@ -5778,12 +5778,6 @@ function onMouseMove(event) {
}
if (isDragging) {
- if (Date.now() - dragStartTime > 500) {
- isLongDrag = true;
- }
- if (pointerDragDistance > DRAG_POINTER_THRESHOLD_PX) {
- isLongDrag = true;
- }
const factor = getDragRotationFactor();
const deltaX = (event.clientX - previousMousePosition.x) * factor;
@@ -5814,35 +5808,45 @@ function onMouseMove(event) {
const vesselPick = getVesselHoverIntersections();
const vesselIntersects = vesselPick.intersects;
const earthInteractableIntersects = getEarthInteractablePointerIntersections();
+ const satIntersects = getSatellitePointerIntersections(event);
+ const interactivePick = pickInteractiveIcon({
+ bgpAnomalyIntersects,
+ bgpCollectorIntersects,
+ computeCenterIntersects,
+ vesselIntersects,
+ earthInteractableIntersects,
+ });
+ if (renderer?.domElement) {
+ renderer.domElement.style.cursor =
+ interactivePick || satIntersects?.length || cableIntersects?.length
+ ? "pointer"
+ : "default";
+ }
let hoveredSat = null;
let hoveredSatIndexFromIntersect = null;
- const satIntersects = getSatellitePointerIntersections(event);
if (satIntersects.length > 0) {
const satIndex = satIntersects[0].index;
hoveredSatIndexFromIntersect = satIndex;
hoveredSat = selectSatellite(satIndex);
}
- const hoveredBGPMarker = getPrimaryBGPHoverTarget(
- bgpAnomalyIntersects,
- bgpCollectorIntersects,
- );
- const hoveredClusterHit = getPrimaryClusterHit(
- bgpAnomalyIntersects,
- bgpCollectorIntersects,
- computeCenterIntersects,
- earthInteractableIntersects,
- );
+ const hoveredBGPMarker =
+ interactivePick?.type === "bgp" || interactivePick?.type === "bgp_collector"
+ ? getPrimaryBGPHoverTarget(bgpAnomalyIntersects, bgpCollectorIntersects)
+ : null;
+
if (hoveredBGP && !isSameBGPMarker(hoveredBGP, hoveredBGPMarker)) {
clearTransientHoverState();
}
- const hoveredComputeCenterMarker = getFirstObjectIntersection(computeCenterIntersects);
+ const hoveredComputeCenterMarker =
+ interactivePick?.type === "compute_center" ? interactivePick.object : null;
const hoveredVesselMarker =
- vesselPick.checked && vesselIntersects.length > 0 ? vesselIntersects[0].object : null;
- const hoveredEarthInteractableMarker = getFirstObjectIntersection(earthInteractableIntersects);
+ interactivePick?.type === "vessel" && vesselPick.checked ? interactivePick.object : null;
+ const hoveredEarthInteractableMarker =
+ interactivePick?.type === "earth_interactable" ? interactivePick.object : null;
const earthPoint = screenToEarthCoords(
event.clientX,
event.clientY,
@@ -5910,20 +5914,6 @@ function onMouseMove(event) {
let objectTooltipShown = false;
if (
- hoveredClusterHit &&
- !hoveredBGPMarker &&
- !hoveredComputeCenterMarker &&
- lockedObjectType !== "bgp" &&
- lockedObjectType !== "bgp_collector" &&
- lockedObjectType !== "compute_center"
- ) {
- showTooltip(
- event.clientX + TOOLTIP_CURSOR_OFFSET,
- event.clientY + TOOLTIP_CURSOR_OFFSET,
- getClusterBriefHtml(hoveredClusterHit),
- );
- objectTooltipShown = true;
- } else if (
hoveredBGPMarker &&
getShowBGP() &&
lockedObjectType !== "bgp" &&
@@ -6077,7 +6067,6 @@ function onMouseDown(event) {
const earth = getEarth();
isDragging = true;
dragStartTime = Date.now();
- isLongDrag = false;
previousMousePosition = { x: event.clientX, y: event.clientY };
dragStartPointer = { ...previousMousePosition };
inertialVelocity = { x: 0, y: 0 };
@@ -6200,7 +6189,6 @@ function onPointerUp(event) {
if (activeDragPointerId === event.pointerId) {
if (pointerDragDistance > DRAG_POINTER_THRESHOLD_PX) {
suppressNextClick = true;
- isLongDrag = true;
}
renderer?.domElement?.releasePointerCapture?.(event.pointerId);
activeDragPointerId = null;
@@ -6232,233 +6220,98 @@ function onClick(event) {
updatePointerFromEvent(event);
invalidateToolInfoCardRestore("scene_click");
- if (isMotionPresentationActive()) {
- presentationController?.dismiss?.("replace");
- }
+ if (isMotionPresentationActive()) presentationController?.dismiss?.("replace");
const cableIntersects = getShowCables()
- ? intersectVisibleCables(interactionRaycaster, getCableLines(), earth, camera, CONFIG.earthRadius) : [];
- const bgpAnomalyIntersects = getShowBGP()
- ? getBGPEventPointerIntersections()
- : [];
- const bgpCollectorIntersects = getShowBGP()
- ? getBGPCollectorPointerIntersections()
+ ? intersectVisibleCables(interactionRaycaster, getCableLines(), earth, camera, CONFIG.earthRadius)
: [];
+ const bgpAnomalyIntersects = getShowBGP() ? getBGPEventPointerIntersections() : [];
+ const bgpCollectorIntersects = getShowBGP() ? getBGPCollectorPointerIntersections() : [];
const computeCenterIntersects = getShowComputeCenters()
- ? getComputeCenterPointerIntersections()
- : [];
- const vesselIntersects = getShowVessels()
- ? getVesselPointerIntersections()
- : [];
+ ? getComputeCenterPointerIntersections() : [];
+ const vesselIntersects = getShowVessels() ? getVesselPointerIntersections() : [];
const earthInteractableIntersects = getEarthInteractablePointerIntersections();
const satIntersects = getSatellitePointerIntersections(event);
+ const interactivePick = pickInteractiveIcon({
+ bgpAnomalyIntersects,
+ bgpCollectorIntersects,
+ computeCenterIntersects,
+ vesselIntersects,
+ earthInteractableIntersects,
+ });
- const clickedBGPMarker = getShowBGP()
- ? getPrimaryBGPClickTarget(event, bgpAnomalyIntersects, bgpCollectorIntersects)
- : null;
- const clickedComputeCenterMarker = getFirstObjectIntersection(computeCenterIntersects);
- const clickedVesselMarker = vesselIntersects.length > 0
- ? vesselIntersects[0].object
- : null;
- const clickedEarthInteractableMarker = getFirstObjectIntersection(earthInteractableIntersects);
-
- if (clickedBGPMarker?.userData?.type === "bgp") {
- interruptCruisePresentation();
- clearLockedObject();
-
- const clickedMarker = clickedBGPMarker;
- setBGPMarkerState(clickedMarker, "locked");
-
- lockedObject = clickedMarker;
- lockedObjectType = "bgp";
- lastBGPClickTime = Date.now();
- lastBGPClickCollector = clickedMarker.userData?.collector || null;
- lastBGPClickType = "bgp";
- lastBGPClickPos = { x: event.clientX, y: event.clientY };
- setAutoRotate(false);
- showBGPEventOverlay(clickedMarker, earth);
- applyBGPEventSatelliteHighlights(clickedMarker);
- const incidentSummary = getBGPInfrastructureSummary(clickedMarker);
- presentSelectedObject({ type: "bgp", object: clickedMarker });
- showStatusMessage(
- earthMessage("status.bgpSelected", {
- collector: clickedMarker.userData.collector,
- regionCount: incidentSummary.regionCount,
- cableCount: incidentSummary.cableCount,
- }),
- "info",
- );
- return;
- }
-
- if (clickedBGPMarker?.userData?.type === "bgp_collector") {
- interruptCruisePresentation();
- clearLockedObject();
-
- const clickedMarker = clickedBGPMarker;
- setBGPMarkerState(clickedMarker, "locked");
-
- lockedObject = clickedMarker;
- lockedObjectType = "bgp_collector";
- lastBGPClickTime = Date.now();
- lastBGPClickCollector = clickedMarker.userData?.collector || null;
- lastBGPClickType = "bgp_collector";
- lastBGPClickPos = { x: event.clientX, y: event.clientY };
- setAutoRotate(false);
- showBGPCollectorCoverageOverlay(clickedMarker, earth);
- clickedMarker.userData.related_satellite_count = 0;
- presentSelectedObject({ type: "bgp_collector", object: clickedMarker });
- showStatusMessage(
- earthMessage("status.selected", { target: "观测站", name: clickedMarker.userData.collector }),
- "info",
- );
- return;
- }
-
- if (clickedComputeCenterMarker?.userData?.type === "compute_center") {
- interruptCruisePresentation();
- clearLockedObject();
-
- const clickedMarker = clickedComputeCenterMarker;
- setComputeCenterMarkerState(clickedMarker, "locked");
- lockedObject = clickedMarker;
- lockedObjectType = "compute_center";
- setAutoRotate(false);
- presentSelectedObject({ type: "compute_center", object: clickedMarker });
- showStatusMessage(
- earthMessage("status.selected", {
- target: "算力中心",
- name: clickedMarker.userData?.name || "未知节点",
- }),
- "info",
- );
- return;
- }
-
- if (clickedVesselMarker?.userData?.type === "vessel") {
- interruptCruisePresentation();
- clearLockedObject();
-
- const clickedMarker = clickedVesselMarker;
- setVesselMarkerState(clickedMarker, "locked");
- lockedObject = clickedMarker;
- lockedObjectType = "vessel";
- setAutoRotate(false);
- presentSelectedObject({ type: "vessel", object: clickedMarker });
- showVesselTrack(clickedMarker, earth).catch((error) => {
- console.warn("船只轨迹加载失败:", error);
- });
- showStatusMessage(
- earthMessage("status.selected", {
- target: "船只",
- name: clickedMarker.userData?.name || clickedMarker.userData?.mmsi,
- }),
- "info",
- );
- return;
- }
-
- if (clickedEarthInteractableMarker?.userData?.type === "earth_interactable") {
- const clickedMarker = clickedEarthInteractableMarker;
- if (confirmMotionCandidate({
- type: "earth_interactable",
- object: clickedMarker,
+ if (interactivePick) {
+ let marker = interactivePick.object;
+ let type = interactivePick.type;
+ if (type === "bgp" || type === "bgp_collector") {
+ marker = getPrimaryBGPClickTarget(event, bgpAnomalyIntersects, bgpCollectorIntersects);
+ type = marker?.userData?.type || type;
+ }
+ if (marker && confirmInteractionCandidate({
+ type,
+ object: marker,
screen: { x: event.clientX, y: event.clientY },
- distancePxSq: 0,
- }, { showMotionStatus: false })) {
- showStatusMessage(
- earthMessage("status.selected", {
- target: "交互点",
- name: clickedMarker.userData?.label || clickedMarker.userData?.name || clickedMarker.userData?.id || "未知目标",
- }),
- "info",
- );
+ distancePxSq: interactivePick.distancePxSq,
+ }, { showConfirmationFeedback: false })) {
+ showSelectionStatus(getInteractionCandidateLabel({ type, object: marker }));
}
return;
}
if (cableIntersects.length > 0 && getShowCables()) {
- interruptCruisePresentation();
- clearLockedObject();
-
const clickedCable = cableIntersects[0].object;
- const cableId = clickedCable.userData.cableId;
- setCableState(cableId, CABLE_STATE.LOCKED);
-
- lockedObject = clickedCable;
- lockedObjectType = "cable";
- setAutoRotate(false);
- handleCableClick(clickedCable);
- presentSelectedObject({ type: "cable", object: clickedCable,
- localAnchor: clickedCable.worldToLocal(cableIntersects[0].point.clone()) });
+ const localAnchor = clickedCable.worldToLocal(cableIntersects[0].point.clone());
+ confirmInteractionCandidate({
+ type: "cable",
+ object: clickedCable,
+ localAnchor,
+ screen: { x: event.clientX, y: event.clientY },
+ distancePxSq: cableIntersects[0].distancePxSq || 0,
+ }, { showConfirmationFeedback: false });
+ showSelectionStatus(clickedCable.userData.name);
return;
}
if (satIntersects.length > 0) {
- const now = Date.now();
- const clickX = event.clientX;
- const clickY = event.clientY;
-
- const frontFacingSats = satIntersects;
- if (frontFacingSats.length === 0) return;
-
- let selectedIndex = frontFacingSats[0].index;
- if (
- frontFacingSats.length > 1 &&
- now - lastSatClickTime < 500 &&
- Math.abs(clickX - lastSatClickPos.x) < 30 &&
- Math.abs(clickY - lastSatClickPos.y) < 30
- ) {
- const currentIdx = frontFacingSats.findIndex(
- (sat) => sat.index === lastSatClickIndex,
- );
- selectedIndex =
- frontFacingSats[(currentIdx + 1) % frontFacingSats.length].index;
- }
-
- lastSatClickTime = now;
- lastSatClickIndex = selectedIndex;
- lastSatClickPos = { x: clickX, y: clickY };
-
- const sat = selectSatellite(selectedIndex);
- if (!sat?.properties) return;
- confirmMotionCandidate({
+ const hit = satIntersects[0];
+ const candidate = {
type: "satellite",
- index: selectedIndex,
- object: sat,
+ index: hit.index,
+ object: getSatelliteAt(hit.index),
screen: { x: event.clientX, y: event.clientY },
- distancePxSq: 0,
- }, { showMotionStatus: false });
- showStatusMessage(earthMessage("status.selected", { name: sat.properties.name }), "info");
+ distancePxSq: hit.distancePxSq,
+ };
+ if (confirmInteractionCandidate(candidate, { showConfirmationFeedback: false })) {
+ showSelectionStatus(getInteractionCandidateLabel(candidate));
+ }
return;
}
- if (!isLongDrag) {
- if (isCruiseModeActive()) {
- interruptCruisePresentation({ resetLoop: true });
- clearLockedObject();
- hideInfoCard();
- setAutoRotate(true);
- return;
- }
-
- interruptCruisePresentation({ resetLoop: true });
- clearLockedObject();
- hideInfoCard();
- setAutoRotate(true);
- }
+ if (isCruiseModeActive()) interruptCruisePresentation({ resetLoop: true });
+ clearLockedObject();
+ hideInfoCard();
+ setAutoRotate(true);
}
function animate() {
if (destroyed) return;
- const statsStart = beginFrameStats();
-
animationFrameId = requestAnimationFrame(animate);
+ const frameNow = performance.now();
+ const stage = (name, update) => {
+ if (!frameProfile) return frameStages.run(name, update, frameNow, lockedObject);
+ const startedAt = performance.now();
+ const completed = frameStages.run(name, update, frameNow, lockedObject);
+ frameProfile.record(name, performance.now() - startedAt);
+ return completed;
+ };
+ let statsStart = frameNow, earth = null, deltaTime = 0, hasInertia = false;
+ stage("frame-stats-start", () => { statsStart = beginFrameStats(); });
+ stage("frame-context", () => {
+ earth = getEarth(); deltaTime = clock.getDelta() * 1000;
+ hasInertia = hasActiveGlobeInertia();
+ });
- const earth = getEarth();
- const deltaTime = clock.getDelta() * 1000;
- const hasInertia = hasActiveGlobeInertia();
-
+ stage("globe-motion", () => {
if (getAutoRotate() && getRotationMode() === ROTATION_MODE.ROTATE && earth && !isDragging && activeTouchPoints.size === 0 && !hasInertia) {
earth.rotateY(getAutoRotationSpeed() * (deltaTime / 16));
@@ -6507,21 +6360,26 @@ function animate() {
// transform (earth rotation is updated above but scene.updateMatrixWorld()
// only runs inside renderer.render(), which hasn't been called yet).
earth?.updateMatrixWorld(true);
- computeTopic?.updateFrame(deltaTime, performance.now());
- refreshMotionFocusCandidates();
+ });
+ stage("news-cards", () => newsRegionCards?.updateFrame(frameNow));
+ stage("region-card-layout", () => regionCallouts?.update(deltaTime, frameNow));
+ stage("motion-focus", () => refreshMotionFocusCandidates());
- applyCableVisualState();
- const activeCruiseMarker =
+ stage("cable-visuals", () => applyCableVisualState());
+ let activeCruiseMarker = null;
+ stage("cruise-focus", () => { activeCruiseMarker =
isCruiseModeActive() && isCruisePresentationPinned()
? getCurrentCruiseBGPMarker()
: getRotationMode() === ROTATION_MODE.MOTION && motionSharedCruiseSequencer?.isPresentationPinned?.()
? getCurrentMotionSharedCruiseBGPMarker()
- : null;
- updateBGPVisualState(lockedObjectType, lockedObject, camera, activeCruiseMarker);
- updateComputeCenterVisualState(lockedObjectType, lockedObject, camera);
- updateVesselVisualState(lockedObjectType, lockedObject, camera);
- updateEarthInteractableVisualState(lockedObjectType, lockedObject, camera);
+ : null; });
+ stage("surface-clusters", () => updateInteractableClusters(camera, lockedObject));
+ stage("bgp-visuals", () => updateBGPVisualState(lockedObjectType, lockedObject, camera, activeCruiseMarker));
+ stage("compute-visuals", () => updateComputeCenterVisualState(lockedObjectType, lockedObject, camera));
+ stage("vessel-visuals", () => updateVesselVisualState(lockedObjectType, lockedObject, camera));
+ stage("custom-marker-visuals", () => updateEarthInteractableVisualState(lockedObjectType, lockedObject, camera));
+ stage("landing-point-selection", () => {
if (lockedObjectType === "cable" && lockedObject) {
applyLandingPointVisualState(lockedObject.userData.name, false, camera);
} else if (
@@ -6539,39 +6397,43 @@ function animate() {
resetLandingPointVisualState(camera);
}
- updateSatellitePositions(deltaTime);
- updateBreathingPhase(deltaTime);
- updateSatelliteIdleBreathingVisual(
+ });
+ stage("satellite-positions", () => updateSatellitePositions(deltaTime));
+ stage("satellite-breathing", () => updateBreathingPhase(deltaTime));
+ stage("satellite-idle", () => updateSatelliteIdleBreathingVisual(
!isDragging &&
!hasActiveGlobeInertia() &&
activeTouchPoints.size === 0 &&
!pinchGesture,
- );
- updateSatellitePointSize();
- updateSatelliteLabels(renderer);
- updateRelatedSatelliteHighlights();
+ ));
+ stage("satellite-size", () => updateSatellitePointSize());
+ stage("satellite-labels", () => updateSatelliteLabels(renderer));
+ stage("satellite-relations", () => updateRelatedSatelliteHighlights());
+ stage("celestial-lighting", () => {
updateCelestialLayer(new Date(), camera);
const currentSunDirection = getSunDirection();
setEarthSunDirection(currentSunDirection);
setSatelliteSunDirection(currentSunDirection);
- updateMobileCenterCountryHighlight({
+ });
+ stage("mobile-country-highlight", () => updateMobileCenterCountryHighlight({
camera,
earth: getEarthSurfacePickTarget() || earth,
renderer,
- now: performance.now(),
- });
- updateCountryBoundaryTiles({
+ now: frameNow,
+ }));
+ stage("country-boundaries", () => updateCountryBoundaryTiles({
camera,
earth: getEarthSurfacePickTarget() || earth,
renderer,
viewZoom: getZoomLevel(),
- });
- updateNewsViewFocus(getCurrentViewCenterCoords());
+ }));
+ stage("news-view", () => updateNewsViewFocus(getCurrentViewCenterCoords()));
+ stage("satellite-selection", () => {
const satPositions = getSatellitePositions();
if (
lockedObjectType === "satellite" &&
lockedSatelliteIndex !== null &&
- satPositions?.[lockedSatelliteIndex]
+ satPositions?.[lockedSatelliteIndex]?.current?.lengthSq() > 0
) {
updateLockedRingPosition(satPositions[lockedSatelliteIndex].current);
} else if (
@@ -6581,10 +6443,12 @@ function animate() {
updateHoverRingPosition(satPositions[hoveredSatelliteIndex].current);
}
- repositionCruiseConnector();
- repositionMotionConnector();
- renderer.render(scene, camera);
- finishFrameStats(statsStart, renderer);
+ });
+ stage("cruise-connector", () => repositionCruiseConnector());
+ stage("motion-connector", () => repositionMotionConnector());
+ const rendered = stage("scene-render", () => renderer.render(scene, camera));
+ if (rendered) stage("frame-stats", () => finishFrameStats(statsStart, renderer));
+ frameProfile?.flush(frameNow);
const timing = document.documentElement.dataset;
if (!timing.earthFirstFrameMs) timing.earthFirstFrameMs = performance.now().toFixed(1);
if (!timing.earthSurfaceReadyMs && isEarthTextureReady()) {
@@ -6600,6 +6464,8 @@ function animate() {
export function destroy() {
if (destroyed) return;
destroyed = true;
+ frameStages.clear();
+ clearInteractableClusters();
screenSpaceDrag.stop();
screenSpaceInertia = false;
stopVesselRealtime();
diff --git a/frontend/public/earth/js/marker-badges.test.js b/frontend/public/earth/js/marker-badges.test.js
index 41ed762c..63af8242 100644
--- a/frontend/public/earth/js/marker-badges.test.js
+++ b/frontend/public/earth/js/marker-badges.test.js
@@ -1,7 +1,7 @@
-import { expect, test } from 'bun:test';
+import { expect, test, spyOn } from 'bun:test';
import * as THREE from 'three';
import { markerBadgePalette } from './marker-badges.js';
-import { createInteractableLayer, getInteractableCompactDotsEnabled, setInteractableCompactDotsEnabled } from './interactable.js';
+import { createInteractableLayer } from './interactable.js';
test('reference teal, purple and amber palettes retain their exact plate, rim and ink colors', () => {
expect(markerBadgePalette('#14b8a6')).toEqual({ top: '#14b8a6', bottom: '#0d9488', border: '#5eead4', ink: '#042f2e' });
@@ -9,9 +9,8 @@ test('reference teal, purple and amber palettes retain their exact plate, rim an
expect(markerBadgePalette('#f59e0b').border).toBe('#fef3c7');
});
-test('compact dots are optional; complete badges keep marker identity, anchors and batched rendering', () => {
+test('modern badges retain complete glyphs and stable identities', () => {
const previousDocument = globalThis.document, previousWindow = globalThis.window;
- const previousCompact = getInteractableCompactDotsEnabled();
const canvases = [];
globalThis.window = { innerWidth: 1280, innerHeight: 720, devicePixelRatio: 1 };
globalThis.document = { createElement() {
@@ -26,7 +25,6 @@ test('compact dots are optional; complete badges keep marker identity, anchors a
} };
let layer;
try {
- setInteractableCompactDotsEnabled(false);
layer = createInteractableLayer({ id: 'badge-regression', pointSize: 36, cluster: false,
colors: { normal: '#14b8a6' }, icon: { badge: { color: '#14b8a6' }, colorable: false, draw(context) { context.fillRect(-10, -10, 20, 20); } },
getPosition: item => ({ latitude: item.latitude, longitude: item.longitude }),
@@ -52,18 +50,66 @@ test('compact dots are optional; complete badges keep marker identity, anchors a
earth.updateMatrixWorld(true);
const badgeTexture = points.material.map;
expect(badgeTexture.image.trace.some(call => call[0] === 'roundRect')).toBe(true);
- setInteractableCompactDotsEnabled(true);
layer.updateVisualState(null, null, camera);
let dotTexture;
layer.group.traverse(object => { if (object.isPoints && object.userData.markers?.length) dotTexture = object.material.map; });
- expect(dotTexture.image.trace.some(call => call[0] === 'roundRect')).toBe(false);
+ expect(dotTexture.image.trace.some(call => call[0] === 'roundRect')).toBe(true);
expect(layer.getMarkers()[0]).toBe(marker);
expect(marker.position.distanceTo(anchor)).toBe(0);
layer.setMarkerState(marker, 'locked');
expect(marker.userData.state).toBe('locked');
} finally {
layer?.clearData();
- setInteractableCompactDotsEnabled(previousCompact);
globalThis.document = previousDocument; globalThis.window = previousWindow;
}
});
+
+
+test('projected BGP symbols bake the same category color as GPU vertex colors', () => {
+ const oldDocument=globalThis.document,oldWindow=globalThis.window;
+ const colors=[];
+ globalThis.window={innerWidth:1280,innerHeight:720,devicePixelRatio:1};
+ globalThis.document={createElement:()=>({width:128,height:128,toDataURL:()=>"image",getContext:()=>new Proxy({}, {get:()=>()=>{}})})};
+ let layer;
+ try {
+ layer=createInteractableLayer({id:"bgp-tint-test",objectType:"bgp",cluster:false,
+ colors:{byKind:{high:"#f97316",critical:"#f43f5e"}},getKind:item=>item.severity,
+ getPosition:item=>({latitude:0,longitude:0}),icon:{draw(_ctx,options){colors.push(options.color);}}});
+ layer.setData([{id:1,severity:"high"},{id:2,severity:"critical"}]);
+ colors.length=0;
+ layer.getMarkers().forEach(marker=>layer.getMarkerImage(marker));
+ expect(colors).toEqual(["#f97316","#f43f5e"]);
+ } finally {layer?.clearData();globalThis.document=oldDocument;globalThis.window=oldWindow;}
+});
+
+
+test('selected pulses do not refresh unchanged batches; state changes still do', () => {
+ const oldDocument=globalThis.document,oldWindow=globalThis.window;
+ globalThis.window={innerWidth:1280,innerHeight:720,devicePixelRatio:1};
+ globalThis.document={createElement:()=>({width:128,height:128,getContext:()=>new Proxy({}, {get:()=>()=>{}})})};
+ let layer,now=0,otherReads=0;
+ const clock=spyOn(Date,'now').mockImplementation(()=>now);
+ try {
+ layer=createInteractableLayer({id:'pulse-batch-test',objectType:'test',cluster:false,
+ getPosition:item=>item,getBucketKey:marker=>String(marker.userData.id),
+ getPointSizeMultiplier:marker=>{if(marker.userData.id===2)otherReads++;return 1;},
+ pulse:{enabled:true,amplitude:.1,speed:.001},icon:{draw(){}}});
+ const earth=new THREE.Object3D(),camera=new THREE.PerspectiveCamera(75,1,.1,5000);
+ camera.position.z=350;camera.updateMatrixWorld();
+ layer.attach(earth);layer.setVisible(true);layer.setData([{id:1,latitude:0,longitude:-90},{id:2,latitude:1,longitude:-90}]);
+ const [selected,other]=layer.getMarkers();selected.userData.pulseOffset=0;
+ layer.setMarkerState(selected,'locked');layer.updateVisualState('test',selected,camera);
+ const lockedOverlay = layer.group.children.find(node => node.userData?.type === 'pulse-batch-test_locked_overlay');
+ expect(lockedOverlay?.renderOrder).toBeGreaterThanOrEqual(100);
+ const baseline=otherReads;
+ const sizes=[];layer.group.traverse(node=>{if(node.isPoints)sizes.push(node.material.size)});
+ now=500;layer.updateVisualState('test',selected,camera);
+ const pulsed=[];layer.group.traverse(node=>{if(node.isPoints)pulsed.push(node.material.size)});
+ expect(pulsed).not.toEqual(sizes);expect(otherReads).toBe(baseline);
+ layer.setMarkerState(other,'hover');layer.updateVisualState('test',selected,camera);
+ expect(otherReads).toBeGreaterThan(baseline);
+ layer.setMarkerState(selected,'normal');layer.updateVisualState(null,null,camera);
+ const batches=[];layer.group.traverse(node=>{if(node.userData.markers?.length)batches.push(node)});
+ expect(batches.every(node=>node.material.opacity===.88)).toBe(true);
+ } finally {layer?.clearData();clock.mockRestore();globalThis.document=oldDocument;globalThis.window=oldWindow;}
+});
diff --git a/frontend/public/earth/js/marker-stack.js b/frontend/public/earth/js/marker-stack.js
new file mode 100644
index 00000000..4948fa43
--- /dev/null
+++ b/frontend/public/earth/js/marker-stack.js
@@ -0,0 +1,44 @@
+import { coLocatedGroups } from "./cluster-motion.js";
+
+const STACK_MIN_STEP_PX = 8;
+const STACK_STEP_SIZE_RATIO = 0.25;
+const STACK_MAX_SPREAD_PX = 24;
+
+export function markerPresentationId(marker) {
+ const data = marker?.userData;
+ // Selection also includes GeoJSON satellites and cable lines. Only markers
+ // owned by an interactable layer participate in surface stack focus.
+ if (!data?.icon_layer_id) return null;
+ const identity = Object.hasOwn(data, "icon_item_id")
+ ? data.icon_item_id ?? marker.uuid
+ : data.id ?? data.source_id ?? data.collector ?? marker.uuid;
+ return `${data.icon_layer_id}:${identity}`;
+}
+
+// Only real, near-identical geographic anchors share a stack. City buckets
+// and screen-space overlap must never pull different locations into one group.
+export function markerStackGroups(markers) {
+ return coLocatedGroups(markers.map(marker => ({
+ marker,
+ id: markerPresentationId(marker),
+ lat: Number(marker.userData.displayLatitude ?? marker.userData.latitude),
+ lon: Number(marker.userData.displayLongitude ?? marker.userData.longitude),
+ }))).map(group => group.map(entry => entry.marker));
+}
+
+export function markerStackLayout(entries) {
+ const ordered = [...entries].sort((a, b) => a.id.localeCompare(b.id));
+ const focused = ordered.findIndex(entry => entry.selected);
+ if (focused >= 0) ordered.push(...ordered.splice(focused, 1));
+ // Expose an edge for small stacks while bounding the whole stack, even if
+ // many records share one coordinate. The front icon stays on its own anchor.
+ const step = Math.min(
+ Math.max(STACK_MIN_STEP_PX, ...ordered.map(entry => entry.size * STACK_STEP_SIZE_RATIO)),
+ STACK_MAX_SPREAD_PX / Math.max(1, ordered.length - 1),
+ );
+ return new Map(ordered.map((entry, index) => [entry.id, {
+ x: (index - ordered.length + 1) * step,
+ y: (index - ordered.length + 1) * step,
+ zIndex: entry.selected ? 1000 : 10 + index,
+ }]));
+}
diff --git a/frontend/public/earth/js/marker-stack.test.js b/frontend/public/earth/js/marker-stack.test.js
new file mode 100644
index 00000000..b2c82ffd
--- /dev/null
+++ b/frontend/public/earth/js/marker-stack.test.js
@@ -0,0 +1,56 @@
+import { expect, test } from "bun:test";
+import { markerStackGroups, markerStackLayout, markerPresentationId } from "./marker-stack.js";
+
+const marker = (layer, id, latitude, longitude, key = "city") => ({
+ userData: { icon_layer_id: layer, id, latitude, longitude, icon_avoidance_key: key },
+});
+
+test("only near-identical coordinates stack across layers", () => {
+ const compute = marker("compute", 1, 50.11, 8.68);
+ const bgp = marker("bgp", 2, 50.11002, 8.68002);
+ const nearby = marker("compute", 3, 50.112, 8.682);
+ const remote = marker("bgp", 4, 60, 10);
+ // All share the old coarse city key: it must no longer join them.
+ expect(markerStackGroups([compute, bgp, nearby, remote])).toEqual([[bgp, compute]]);
+});
+
+test("overlapping screen rectangles and a chain of neighboring cities never form a stack", () => {
+ const points = [marker("bgp",1,52.37,4.90),marker("compute",2,50.11,8.68),marker("compute",3,48.86,2.35)];
+ points.forEach((point,index)=>{point.screen={x:100+index*10,y:100+index*10,size:36};});
+ expect(markerStackGroups(points)).toEqual([]);
+ points.forEach(point=>{point.screen={x:100,y:100,size:36};});
+ expect(markerStackGroups(points)).toEqual([]);
+});
+
+test("compact slots expose edges; selection comes forward and clearing restores exact slots", () => {
+ const entries = ["compute:a", "bgp:b", "compute:c"].map(id => ({id, size:36}));
+ const original = markerStackLayout(entries);
+ expect(markerStackLayout([...entries].reverse())).toEqual(original);
+ const offsets = [...original.values()];
+ for(let i=1;i
({...entry,selected:entry.id === "bgp:b"}));
+ expect(markerStackLayout(selected).get("bgp:b")).toEqual({x:0,y:0,zIndex:1000});
+ expect(markerStackLayout(selected.map(entry=>({...entry,selected:false})))).toEqual(original);
+});
+
+test("stack extent is bounded and never replaces real projections with an averaged screen position", () => {
+ for(const count of [2,3,4,14,50]) {
+ const entries = Array.from({length:count},(_,index)=>({id:String(index).padStart(2,"0"),size:36,x:600+index/100,y:400}));
+ const saved=JSON.stringify(entries);
+ const offsets=markerStackLayout(entries);
+ for(const offset of offsets.values()) {
+ expect(Math.abs(offset.x)).toBeLessThanOrEqual(24);
+ expect(Math.abs(offset.y)).toBeLessThanOrEqual(24);
+ }
+ expect(offsets.get(entries.at(-1).id)).toMatchObject({x:0,y:0});
+ expect(JSON.stringify(entries)).toBe(saved);
+ }
+});
+
+
+test("non-surface selections never enter marker-stack identity or throw in the frame loop",()=>{
+ expect(markerPresentationId({properties:{name:"STARLINK-2507"}})).toBe(null);
+ expect(markerPresentationId({userData:{cableId:"EIG"}})).toBe(null);
+ expect(markerPresentationId(null)).toBe(null);
+ expect(markerPresentationId(marker("compute",1,50,10))).toBe("compute:1");
+});
diff --git a/frontend/public/earth/js/news-cruise-adapter.js b/frontend/public/earth/js/news-cruise-adapter.js
index e4cf7885..1fcda548 100644
--- a/frontend/public/earth/js/news-cruise-adapter.js
+++ b/frontend/public/earth/js/news-cruise-adapter.js
@@ -2,7 +2,7 @@ import { CALLOUT_DRAW_MS } from "./callout-reveal.js";
import * as THREE from "three";
import { CONFIG, CONNECTOR_CONFIG, CRUISE_CONFIG } from "./constants.js";
-import { showInfoCard, hideInfoCard } from "./info-card.js";
+import { showInfoCard, hideInfoCard, waitForNewsCardTyping } from "./info-card.js";
import { latLonToVector3 } from "./utils.js";
import { formatLocaleDateTime, getEarthLocale, hasCjkText } from "./i18n.js";
import {
@@ -19,11 +19,8 @@ import {
getNewsDisplaySummary,
getNewsDisplayTitle,
getNewsCategoryLabel,
- getNewsFetchChannelLabel,
- getNewsFeedLabel,
getNewsLocationSourceLabel,
getNewsRegionDisplayLabel,
- getNewsSourceTypeLabel,
getNewsSourceNameLabel,
} from "./news-locale.js";
@@ -77,7 +74,7 @@ function getCardPlacement() {
getComputedStyle(document.documentElement).getPropertyValue("--hud-scale"),
) || 1;
const estimatedCardHeight = Math.min(420 * hudScale, window.innerHeight * 0.7);
- const estimatedCardWidth = Math.min(300 * hudScale, window.innerWidth - 32);
+ const estimatedCardWidth = Math.min(340 * hudScale, window.innerWidth - 32);
return {
x: window.innerWidth * CRUISE_CONFIG.cardAnchorXRatio - estimatedCardWidth * 0.5,
@@ -87,15 +84,13 @@ function getCardPlacement() {
};
}
-function mapNewsItemToCruiseEvent(item) {
+export function mapNewsItemToCruiseEvent(item, { requireCoordinates = true } = {}) {
const latitude = Number(item?.latitude);
const longitude = Number(item?.longitude);
- if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) {
+ if (requireCoordinates && (!Number.isFinite(latitude) || !Number.isFinite(longitude))) {
return null;
}
- const rawFeedName = item.feed_name || "";
- const sourceType = item.source_type || (String(rawFeedName).startsWith("Global Monitor /") ? "aggregated" : "rss");
const regionLabel = getNewsRegionDisplayLabel(item.region, item.display_region);
const locationLabel = getEarthLocale() === "en-US" && hasCjkText(item.location_label)
? regionLabel
@@ -108,10 +103,6 @@ function mapNewsItemToCruiseEvent(item) {
title: getNewsDisplayTitle(item),
summary: getNewsDisplaySummary(item),
source: getNewsSourceNameLabel({ id: item.source_id, name: item.source || "" }),
- feedName: getNewsFeedLabel(rawFeedName),
- rawFeedName,
- feedSourceTypeLabel: getNewsSourceTypeLabel(sourceType),
- fetchChannelLabel: getNewsFetchChannelLabel(rawFeedName, sourceType),
categoryLabel: getNewsCategoryLabel(item.category),
region: item.region || "global",
regionLabel,
@@ -292,9 +283,6 @@ export function createNewsCruiseAdapter({ camera, earth, connector, focusView })
title: item.title,
summary: item.summary || item.title || "",
source: item.source,
- feedName: item.rawFeedName || item.feedName,
- feedSourceTypeLabel: item.feedSourceTypeLabel,
- fetchChannelLabel: item.fetchChannelLabel,
categoryLabel: item.categoryLabel,
regionLabel: item.regionLabel,
publishedAtDisplay: item.publishedAtDisplay,
@@ -342,9 +330,6 @@ export function createNewsCruiseAdapter({ camera, earth, connector, focusView })
title: item.title,
summary: item.summary || item.title || "",
source: item.source,
- feedName: item.rawFeedName || item.feedName,
- feedSourceTypeLabel: item.feedSourceTypeLabel,
- fetchChannelLabel: item.fetchChannelLabel,
categoryLabel: item.categoryLabel,
regionLabel: item.regionLabel,
publishedAtDisplay: item.publishedAtDisplay,
@@ -354,8 +339,10 @@ export function createNewsCruiseAdapter({ camera, earth, connector, focusView })
absolute: true,
anchorStable: true,
});
+ context.setPresentationVisible?.(true);
await context.nextFrame();
- return context.isCurrent();
+ // The sequencer starts its dwell only after presentItem completes.
+ return waitForNewsCardTyping(context);
},
async hidePresentation({ context }) {
clearSelectedNewsItem();
diff --git a/frontend/public/earth/js/news-region-cards.js b/frontend/public/earth/js/news-region-cards.js
new file mode 100644
index 00000000..74424d2e
--- /dev/null
+++ b/frontend/public/earth/js/news-region-cards.js
@@ -0,0 +1,174 @@
+import { createTypewriter } from "./typewriter.js";
+import { CRUISE_CONFIG } from "./constants.js";
+import { getEarthLocale } from "./i18n.js";
+import { createHUDPanel } from "./hud-panels.js";
+import { renderNewsCardContent, NEWS_CARD_ICON } from "./info-card.js";
+import { mapNewsItemToCruiseEvent } from "./news-cruise-adapter.js";
+import { getNewsRegionLabel } from "./news-locale.js";
+import { getCruiseNewsItems, getNewsPayload, ensureNewsPanelReady } from "./news.js";
+import { NEWS_CARD_REGIONS, createRegionalNewsRotation } from "./news-region-model.js";
+
+const STORAGE_KEY = "planet.earth.news-region-cards.v1";
+const text = (zh,en) => getEarthLocale() === "en-US" ? en : zh;
+const iconButton = (action,icon,label) => ``;
+
+export function initNewsRegionCards({ rootParent, spatial }) {
+ const root = document.createElement("section");
+ root.id = "news-region-workspace";
+ root.setAttribute("aria-label", text("区域新闻卡片","Regional news cards"));
+ rootParent.append(root);
+ const model = createRegionalNewsRotation(CRUISE_CONFIG.dwellMs);
+ const cards = new Map();
+ let enabled = false, lastTick = -Infinity, mobile = null, destroyed = false;
+ try { enabled = localStorage.getItem(STORAGE_KEY) === "true"; } catch { /* Optional preference. */ }
+ const toggles = [...document.querySelectorAll("[data-news-region-cards]")];
+ const isMobile = () => document.body.classList.contains("layout-mode-mobile");
+
+ function renderStory(region, force = false) {
+ const card = cards.get(region.key), snapshot = model.snapshot(region.key);
+ const data = snapshot.item ? mapNewsItemToCruiseEvent(snapshot.item, {requireCoordinates:false}) : null;
+ const signature = JSON.stringify([getEarthLocale(),data]);
+ if (force || card.signature !== signature) {
+ card.signature = signature;
+ card.title.textContent = data?.title || getNewsRegionLabel(region.key);
+ card.region.textContent = getNewsRegionLabel(region.key);
+ card.writer.stop();card.typing=false;model.restart(region.key);
+ if (data) {
+ renderNewsCardContent(card.content, data, {
+ compact:true,
+ typewriter(target,summary) {
+ card.typing=true;
+ card.writer.start(target,summary,{maxDurationMs:4000,
+ isPaused:()=>!enabled || document.hidden || card.panel.isCollapsed() || (mobile
+ ? !root.getClientRects().length || document.getElementById("mobile-drawer-shell")?.getAttribute("aria-hidden") === "true"
+ : card.element.dataset.calloutPhase !== "visible"),
+ onComplete:()=>{card.typing=false;model.restart(region.key);},
+ });
+ },
+ });
+ } else {
+ card.content.textContent = getNewsPayload()
+ ? text("当前区域暂无可用新闻","No available news in this region")
+ : text("正在准备全球态势新闻…","Preparing regional news…");
+ }
+ card.content.scrollTop = 0;
+ card.animation?.cancel();
+ if (card.signature && !window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
+ card.animation = card.content.animate([{opacity:0},{opacity:1}], {duration:180,easing:"ease"});
+ }
+ const url = String(snapshot.item?.url || "");
+ card.source.hidden = !/^https?:\/\//i.test(url);
+ if (!card.source.hidden) card.source.href = url; else card.source.removeAttribute("href");
+ card.source.textContent = text("阅读原文 ↗","Read source ↗");
+ }
+ card.count.textContent = snapshot.count ? `${snapshot.index+1} / ${snapshot.count}` : "0 / 0";
+ card.previous.disabled = card.next.disabled = snapshot.count < 2;
+ card.play.disabled = snapshot.count < 2;
+ card.play.setAttribute("aria-pressed",String(snapshot.paused));
+ card.play.title = snapshot.paused ? text("继续轮播","Resume rotation") : text("暂停轮播","Pause rotation");
+ card.play.setAttribute("aria-label",card.play.title);
+ card.play.querySelector("span").textContent = snapshot.paused ? "play_arrow" : "pause";
+ }
+
+ function createCard(region) {
+ const element=document.createElement("article");
+ element.className="hud-panel info-card news news-region-card";
+ element.dataset.region=region.key;
+ element.innerHTML=`${NEWS_CARD_ICON}${iconButton("card-collapse","expand_less",text("折叠","Collapse"))}
`;
+ const card={ element, hovered:false, signature:null, typing:false, writer:createTypewriter(),
+ title:element.querySelector("h3"), region:element.querySelector(".news-region-card__region"), content:element.querySelector(".news-region-card__content"),
+ count:element.querySelector(".news-region-card__count"),source:element.querySelector("a"),
+ previous:element.querySelector('[data-action="news-prev"]'),next:element.querySelector('[data-action="news-next"]'),play:element.querySelector('[data-action="news-play"]'),
+ };
+ card.panel=createHUDPanel({panel:element,header:element.querySelector("header"),body:element.querySelector(".news-region-card__body"),collapseBtn:element.querySelector('[data-action="card-collapse"]'),expandLabel:text("展开新闻","Expand news"),collapseLabel:text("折叠新闻","Collapse news")});
+ element.addEventListener("pointerenter",()=>{card.hovered=true;});
+ element.addEventListener("pointerleave",()=>{card.hovered=false;});
+ element.addEventListener("click",event=>{
+ const action=event.target.closest("[data-action]")?.dataset.action;
+ if(action === "news-prev") model.step(region.key,-1);
+ else if(action === "news-next") model.step(region.key);
+ else if(action === "news-play") model.togglePaused(region.key);
+ else if(action === "card-collapse") {
+ card.panel.setCollapsed(!card.panel.isCollapsed());
+ spatial.invalidate();
+ return;
+ }
+ else return;
+ renderStory(region);
+ });
+ cards.set(region.key,card);root.append(element);
+ }
+ NEWS_CARD_REGIONS.forEach(createCard);
+
+ function syncLayout() {
+ mobile=isMobile();
+ const parent=mobile ? document.getElementById("mobile-news-region-cards") : rootParent;
+ if(parent && root.parentElement !== parent) parent.append(root);
+ root.hidden=!enabled;
+ if(!enabled) cards.forEach(card=>{card.writer.stop();card.typing=false;card.signature=null;});
+ root.classList.toggle("is-mobile",mobile);
+ spatial.set(enabled && !mobile ? NEWS_CARD_REGIONS.map(region=>({
+ key:`news:${region.key}`,anchor:region.anchor,element:cards.get(region.key).element,
+ })) : []);
+ model.resetClocks(performance.now());
+ toggles.forEach(button=>{
+ button.setAttribute("aria-pressed",String(enabled));
+ button.title=enabled ? text("隐藏区域新闻卡片","Hide regional news cards") : text("显示区域新闻卡片","Show regional news cards");
+ button.setAttribute("aria-label",button.title);
+ });
+ }
+ function syncItems() {
+ if(destroyed) return;
+ model.setItems(getCruiseNewsItems());
+ if(enabled) NEWS_CARD_REGIONS.forEach(region=>renderStory(region));
+ }
+ async function toggle() {
+ enabled=!enabled;
+ try {localStorage.setItem(STORAGE_KEY,String(enabled));} catch { /* Optional preference. */ }
+ syncLayout();
+ if(enabled) {
+ syncItems();
+ await ensureNewsPanelReady().catch(()=>{});
+ syncItems();
+ }
+ }
+ const visibility=()=>model.resetClocks(performance.now());
+ const locale=()=>{
+ syncLayout();
+ root.setAttribute("aria-label",text("区域新闻卡片","Regional news cards"));
+ for(const region of NEWS_CARD_REGIONS) {
+ const card=cards.get(region.key);
+ for(const [button,label] of [[card.previous,text("上一条新闻","Previous story")],[card.next,text("下一条新闻","Next story")]]) {
+ button.title=label;button.setAttribute("aria-label",label);
+ }
+ renderStory(region,true);
+ }
+ };
+ const layoutObserver=new MutationObserver(()=>{if(mobile !== isMobile()) syncLayout();});
+ layoutObserver.observe(document.body,{attributes:true,attributeFilter:["class"]});
+ toggles.forEach(button=>button.addEventListener("click",toggle));
+ window.addEventListener("earth:news-payload-updated",syncItems);
+ window.addEventListener("earth:locale-change",locale);
+ document.addEventListener("visibilitychange",visibility);
+ syncLayout();syncItems();
+ return {
+ updateFrame(now) {
+ if(!enabled || document.hidden || now-lastTick<200) return;
+ lastTick=now;
+ const held=new Set();
+ const visible=root.getClientRects().length>0;
+ for(const [key,card] of cards) if(!visible || card.typing || card.hovered || card.element.contains(document.activeElement) ||
+ card.panel.isCollapsed() || (!mobile && card.element.dataset.calloutPhase !== "visible")) held.add(key);
+ for(const key of model.tick(now,held)) renderStory(NEWS_CARD_REGIONS.find(region=>region.key === key));
+ },
+ destroy() {
+ destroyed=true;spatial.destroy();layoutObserver.disconnect();
+ cards.forEach(card=>{card.writer.stop();card.animation?.cancel();card.panel.destroy();});cards.clear();
+ toggles.forEach(button=>button.removeEventListener("click",toggle));
+ window.removeEventListener("earth:news-payload-updated",syncItems);
+ window.removeEventListener("earth:locale-change",locale);
+ document.removeEventListener("visibilitychange",visibility);
+ root.remove();
+ },
+ };
+}
diff --git a/frontend/public/earth/js/news-region-model.js b/frontend/public/earth/js/news-region-model.js
new file mode 100644
index 00000000..f3f0c01b
--- /dev/null
+++ b/frontend/public/earth/js/news-region-model.js
@@ -0,0 +1,52 @@
+export const NEWS_CARD_REGIONS = Object.freeze([
+ { key: "americas", anchor: { latitude: 37.0902, longitude: -95.7129 } },
+ { key: "europe", anchor: { latitude: 50.1109, longitude: 8.6821 } },
+ { key: "middle-east-africa", anchor: { latitude: 25.2048, longitude: 55.2708 } },
+ { key: "asia-pacific", anchor: { latitude: 1.3521, longitude: 103.8198 } },
+]);
+
+export function createRegionalNewsRotation(intervalMs) {
+ const states = new Map(NEWS_CARD_REGIONS.map(({key}) => [key, {
+ items: [], index: 0, paused: false, remaining: intervalMs, clock: null,
+ }]));
+ const current = state => state.items[state.index] || null;
+ function setItems(items) {
+ for (const [key, state] of states) {
+ const oldId = current(state)?.id;
+ const unique = new Map();
+ for (const item of items) if (item.region === key && item.id) unique.set(item.id, item);
+ state.items = [...unique.values()].sort((a,b) =>
+ (Date.parse(b.published_at) || 0) - (Date.parse(a.published_at) || 0) || String(a.id).localeCompare(String(b.id)));
+ const kept = state.items.findIndex(item => item.id === oldId);
+ state.index = Math.max(0, kept);
+ if (kept < 0) state.remaining = intervalMs;
+ }
+ }
+ function step(key, direction = 1) {
+ const state = states.get(key);
+ if (!state?.items.length) return;
+ state.index = (state.index + direction + state.items.length) % state.items.length;
+ state.remaining = intervalMs;
+ }
+ return {
+ setItems, step,
+ restart(key) { const state=states.get(key);if(state) state.remaining=intervalMs; },
+ togglePaused(key) { const state=states.get(key); if(state) state.paused=!state.paused; },
+ resetClocks(now) { states.forEach(state=>{state.clock=now;}); },
+ snapshot(key) {
+ const state=states.get(key);
+ return { item:current(state), index:state.index, count:state.items.length, paused:state.paused };
+ },
+ tick(now, held = new Set()) {
+ const changed=[];
+ for(const [key,state] of states) {
+ const elapsed=state.clock === null ? 0 : Math.max(0,now-state.clock);
+ state.clock=now;
+ if(state.paused || held.has(key) || state.items.length<2) continue;
+ state.remaining-=elapsed;
+ if(state.remaining<=0) {step(key);changed.push(key);}
+ }
+ return changed;
+ },
+ };
+}
diff --git a/frontend/public/earth/js/news-region-model.test.js b/frontend/public/earth/js/news-region-model.test.js
new file mode 100644
index 00000000..4345f2e3
--- /dev/null
+++ b/frontend/public/earth/js/news-region-model.test.js
@@ -0,0 +1,29 @@
+import {expect,test} from "bun:test";
+import {createRegionalNewsRotation} from "./news-region-model.js";
+const item=(id,region,date="2026-09-29")=>({id,region,published_at:date});
+test("four region queues are isolated, deduplicated and never backfilled with global or other regions",()=>{
+ const model=createRegionalNewsRotation(7000);
+ model.setItems([item("a","europe"),item("a","europe"),item("b","americas"),item("c","global")]);
+ expect(model.snapshot("europe").count).toBe(1);
+ expect(model.snapshot("americas").item.id).toBe("b");
+ expect(model.snapshot("asia-pacific").item).toBe(null);
+});
+test("regions rotate independently, pause while read, wrap, and retain the current story on refresh",()=>{
+ const model=createRegionalNewsRotation(7000);
+ const items=[item("a","europe"),item("b","europe"),item("c","americas"),item("d","americas")];
+ model.setItems(items);model.tick(0);model.tick(7000,new Set(["europe"]));
+ expect(model.snapshot("europe").item.id).toBe("a");
+ expect(model.snapshot("americas").item.id).toBe("d");
+ model.tick(14000);expect(model.snapshot("europe").item.id).toBe("b");
+ model.setItems([item("new","europe","2026-09-30"),...items]);
+ expect(model.snapshot("europe").item.id).toBe("b");
+ model.togglePaused("europe");model.tick(21000);expect(model.snapshot("europe").item.id).toBe("b");
+ model.step("europe",-1);expect(model.snapshot("europe").item.id).toBe("a");
+ model.setItems([]);expect(model.snapshot("europe").count).toBe(0);
+});
+test("hidden/resumed pages do not consume reading time",()=>{
+ const model=createRegionalNewsRotation(7000);
+ model.setItems([item("a","europe"),item("b","europe")]);model.tick(0);model.tick(3000);
+ model.resetClocks(300000);model.tick(303000);expect(model.snapshot("europe").item.id).toBe("a");
+ model.tick(304000);expect(model.snapshot("europe").item.id).toBe("b");
+});
diff --git a/frontend/public/earth/js/news.js b/frontend/public/earth/js/news.js
index 0030017e..82f72eda 100644
--- a/frontend/public/earth/js/news.js
+++ b/frontend/public/earth/js/news.js
@@ -28,9 +28,10 @@ import {
recordEarthRealtimeOpen,
} from "./realtime.js";
-// Desktop news has two surfaces:
+// Desktop news has a ticker, a detail HUD and optional regional cards:
// - a persistent top ticker
// - a center HUD that expands from the ticker
+// - four independently rotating region cards sharing the cruise data
// Mobile keeps its existing drawer page.
const EARTH_NEWS_API = "/api/v1/news/earth-feed";
diff --git a/frontend/public/earth/js/object-callout-anchor.js b/frontend/public/earth/js/object-callout-anchor.js
index 2d7992b6..2f63d9e1 100644
--- a/frontend/public/earth/js/object-callout-anchor.js
+++ b/frontend/public/earth/js/object-callout-anchor.js
@@ -1,4 +1,5 @@
import * as THREE from "three";
+import { resolveInteractableMarker } from "./interactable.js";
import { CONFIG } from "./constants.js";
import { projectedSphereRadius, smoothHighlightAnchor } from "./highlight-anchor.js";
@@ -18,12 +19,14 @@ function cableSamples(lines, limit = 96) {
}
export function createObjectCalloutAnchor(candidate, {
- getEarth, getCamera, getCablesById, getSatellitePoints, getSatellitePositions,
+ getEarth, getCamera, getCablesById, getSatellitePoints, getSatellitePositions, getSatelliteData,
getObstacles = () => [],
}) {
const samples = candidate.type === "cable"
? cableSamples(getCablesById(candidate.object.userData.cableId)) : [];
let state = {};
+ let satelliteCatalog = null, satelliteIndex = candidate.index;
+ const satelliteId = candidate.object?.properties?.norad_cat_id ?? candidate.object?.properties?.norad_id;
let lastTime = 0;
const world = new THREE.Vector3();
const center = new THREE.Vector3();
@@ -60,11 +63,24 @@ export function createObjectCalloutAnchor(candidate, {
};
let preferred;
if (candidate.type === "satellite") {
- preferred = project(getSatellitePositions()?.[candidate.index]?.current, getSatellitePoints(), "clicked");
+ if (getSatelliteData && satelliteId != null) {
+ const catalog = getSatelliteData();
+ if (catalog !== satelliteCatalog) {
+ satelliteCatalog = catalog;
+ satelliteIndex = catalog?.findIndex(item =>
+ String(item.properties?.norad_cat_id ?? item.properties?.norad_id) === String(satelliteId)) ?? -1;
+ }
+ }
+ const position = getSatellitePositions()?.[satelliteIndex]?.current;
+ if (!position || position.lengthSq() === 0) return null;
+ preferred = project(position, getSatellitePoints(), "clicked");
} else if (candidate.type === "cable") {
preferred = project(candidate.localAnchor || candidate.object.userData.localCenter, candidate.object, "clicked");
} else {
- preferred = project(candidate.object?.position, candidate.object?.parent || earth, "clicked");
+ const marker = resolveInteractableMarker(candidate.object);
+ preferred = project(marker?.position, marker?.parent || earth, "clicked");
+ const displayed = marker?.userData?.icon_presentation_screen;
+ if (preferred?.front && displayed) preferred = { ...preferred, ...displayed };
}
if (!preferred) return null;
const candidates = samples.map((sample) => project(sample.local, sample.object, sample.key)).filter(Boolean);
diff --git a/frontend/public/earth/js/object-callout-anchor.test.js b/frontend/public/earth/js/object-callout-anchor.test.js
index 306c82fb..9b5cb24d 100644
--- a/frontend/public/earth/js/object-callout-anchor.test.js
+++ b/frontend/public/earth/js/object-callout-anchor.test.js
@@ -1,6 +1,9 @@
+import { bgpEventIdentity } from "./bgp-identity.js";
+import { markerPresentationId } from "./marker-stack.js";
import { expect, test } from "bun:test";
import * as THREE from "three";
import { CONFIG } from "./constants.js";
+import { createInteractableLayer, resolveInteractableMarker } from "./interactable.js";
import { createObjectCalloutAnchor } from "./object-callout-anchor.js";
function context() {
@@ -37,3 +40,88 @@ test("a rear point keeps a finite rim guide instead of dropping its connector",
expect(Number.isFinite(source.x) && Number.isFinite(source.y)).toBe(true);
expect(Math.hypot(source.x - 600, source.y - 400)).toBeGreaterThan(100);
});
+
+
+test("selected stacked markers connect to their displayed icon without changing geography", () => {
+ const { earth, providers } = context();
+ const position = new THREE.Vector3(0, 0, CONFIG.earthRadius);
+ const marker = { position, parent:earth, userData:{icon_presentation_screen:{x:636,y:436}} };
+ const update = createObjectCalloutAnchor({type:"compute_center",object:marker},providers);
+ expect(update()).toMatchObject({x:636,y:436,front:true});
+ expect(position.toArray()).toEqual([0,0,CONFIG.earthRadius]);
+ marker.userData.icon_presentation_screen=null;
+ const restored = createObjectCalloutAnchor({type:"compute_center",object:marker},providers)();
+ expect(restored).toMatchObject({x:600,y:400});
+});
+
+
+test("live anonymous and duplicate-ID markers cannot resolve to the last marker",()=>{
+ const {earth,providers}=context(),originalDocument=globalThis.document,originalWindow=globalThis.window;
+ globalThis.window={innerWidth:1200,innerHeight:800,devicePixelRatio:1};
+ globalThis.document={createElement:()=>({getContext:()=>new Proxy({}, {get:()=>()=>{}})})};
+ let layer;
+ try {
+ layer=createInteractableLayer({id:"missing-id-regression",objectType:"bgp_collector",cluster:false,getPosition:item=>item,icon:{draw(){}}});
+ layer.attach(earth);layer.setVisible(true);
+ for(const duplicate of [false,true]) {
+ layer.setData([{...(duplicate?{id:7}:{}),collector:"rrc22",latitude:0,longitude:-80},
+ {...(duplicate?{id:7}:{}),collector:"rrc26",latitude:0,longitude:-100}]);
+ const [selected,other]=layer.getMarkers();
+ expect(resolveInteractableMarker(selected)).toBe(selected);
+ expect(resolveInteractableMarker(other)).toBe(other);
+ const anchor=createObjectCalloutAnchor({type:"bgp_collector",object:selected},providers)();
+ const expected=selected.position.clone().project(providers.getCamera());
+ expect(anchor.x).toBeCloseTo((expected.x+1)*600,6);
+ layer.setData([{id:7,collector:"rrc26",latitude:0,longitude:-100}]);
+ expect(resolveInteractableMarker(selected)).toBe(selected);
+ }
+ } finally {layer?.clearData();globalThis.document=originalDocument;globalThis.window=originalWindow;}
+});
+
+test("collector identity survives reordered refreshes; other surface cards retain their own object",()=>{
+ const {earth}=context(),originalDocument=globalThis.document,originalWindow=globalThis.window;
+ globalThis.window={innerWidth:1200,innerHeight:800,devicePixelRatio:1};
+ globalThis.document={createElement:()=>({getContext:()=>new Proxy({}, {get:()=>()=>{}})})};
+ const scenarios=[
+ {type:"bgp_collector",getItemId:item=>item.collector,a:{collector:"rrc22"},b:{collector:"rrc26"}},
+ {type:"bgp",a:{id:1},b:{id:2}},
+ {type:"compute_center",a:{id:0},b:{id:2}},
+ {type:"earth_interactable",a:{id:"point-a"},b:{id:"point-b"}},
+ {type:"vessel",getItemId:item=>item.mmsi,a:{mmsi:123},b:{mmsi:456}},
+ ];
+ try {for(const scenario of scenarios) {
+ const layer=createInteractableLayer({id:`identity-${scenario.type}`,objectType:scenario.type,
+ ...(scenario.getItemId?{getItemId:scenario.getItemId}:{}),cluster:false,getPosition:item=>item,icon:{draw(){}}});
+ try {
+ layer.attach(earth);layer.setVisible(true);
+ const a={...scenario.a,latitude:0,longitude:-80},b={...scenario.b,latitude:0,longitude:-100};
+ layer.setData([a,b]);const selected=layer.getMarkers()[0];
+ layer.setData([b,{...a,latitude:5}]);
+ expect(resolveInteractableMarker(selected)).toBe(layer.getMarkers()[1]);
+ expect(resolveInteractableMarker(selected)).not.toBe(layer.getMarkers()[0]);
+ } finally {layer.clearData();}
+ }} finally {globalThis.document=originalDocument;globalThis.window=originalWindow;}
+});
+
+test("satellite connectors follow NORAD across a reordered catalog and disappear if identity is removed",()=>{
+ const {earth,providers}=context();
+ const a={properties:{norad_cat_id:11}},b={properties:{norad_cat_id:22}};
+ let catalog=[a,b],positions=[{current:new THREE.Vector3(10,0,110)},{current:new THREE.Vector3(-20,0,110)}];
+ const anchor=createObjectCalloutAnchor({type:"satellite",object:a,index:0},
+ {...providers,getSatelliteData:()=>catalog,getSatellitePositions:()=>positions,getSatellitePoints:()=>earth});
+ const initial=anchor();
+ catalog=[b,{properties:{norad_cat_id:11}}];positions=[positions[1],positions[0]];
+ expect(anchor().x).toBeCloseTo(initial.x,6);
+ expect(anchor().y).toBeCloseTo(initial.y,6);
+ catalog=[b];positions=[positions[0]];expect(anchor()).toBeNull();
+});
+
+
+test("BGP sources sharing a numeric row ID are different selection and stack identities",()=>{
+ const incident={id:7,source:"bgp_incident",incident_key:"incident-7"};
+ const anomaly={id:7,source:"ris_live_bgp"};
+ expect(bgpEventIdentity(incident)).not.toBe(bgpEventIdentity(anomaly));
+ expect(bgpEventIdentity({...incident,id:8})).toBe(bgpEventIdentity(incident));
+ const marker=data=>({uuid:"fallback",userData:{...data,icon_layer_id:"bgp-events",icon_item_id:bgpEventIdentity(data)}});
+ expect(markerPresentationId(marker(incident))).not.toBe(markerPresentationId(marker(anomaly)));
+});
diff --git a/frontend/public/earth/js/satellite-display.test.js b/frontend/public/earth/js/satellite-display.test.js
index 78da238b..59eefa81 100644
--- a/frontend/public/earth/js/satellite-display.test.js
+++ b/frontend/public/earth/js/satellite-display.test.js
@@ -1,7 +1,7 @@
import { expect, test } from "bun:test";
import * as THREE from "three";
import { satelliteCategory, satellitePixelSize, satelliteLabel } from "./satellite-display.js";
-import { createSatelliteLabels } from "./satellite-labels.js";
+import { createSatelliteLabels, normalizeSatelliteLabelCount, normalizeSatelliteLabelMinZoom } from "./satellite-labels.js";
import { distanceForGlobeZoom } from "./globe-navigation.js";
import { summarizeFrames, summarizeFrameWindows } from "./frame-stats.js";
@@ -44,6 +44,18 @@ test("near labels start at 400%, stay capped, use real text, and honor filters",
const root=container.children[0],visible=root.children.filter(node=>!node.hidden);
expect(visible.length).toBeGreaterThan(0);expect(visible.length).toBeLessThanOrEqual(36);
expect(visible[0].children[1].textContent).toStartWith("NORAD ");
+ labels.setMinZoom(5); labels.update(args); expect(root.hidden).toBe(true);
+ labels.setMinZoom(2.5);
+ camera.position.z=distanceForGlobeZoom(2.49,100,300);camera.updateMatrixWorld();labels.update(args);
+ expect(root.hidden).toBe(true);
+ camera.position.z=distanceForGlobeZoom(2.5,100,300);camera.updateMatrixWorld();labels.update(args);
+ expect(root.hidden).toBe(false);
+ labels.setMinZoom(4);
+ camera.position.z=distanceForGlobeZoom(4,100,300);camera.updateMatrixWorld();labels.update(args);
+ labels.setMaxCount(5); labels.update(args);
+ expect(root.children.filter(node=>!node.hidden).length).toBe(Math.min(5,visible.length));
+ labels.setMaxCount(36); labels.update(args);
+ expect(root.children.filter(node=>!node.hidden).length).toBe(visible.length);
labels.update({...args,isVisible:()=>false});expect(root.children.every(node=>node.hidden)).toBe(true);
camera.position.z=distanceForGlobeZoom(3,100,300);camera.updateMatrixWorld();labels.update(args);expect(root.hidden).toBe(true);
} finally {labels.dispose();globalThis.document=oldDocument;}
@@ -58,3 +70,18 @@ test("reference palette keeps real inclination ownership", () => {
expect(satelliteCategory({ inclination: 10 }).color).toBe("#3399ff");
expect(satelliteCategory({ inclination: 98 }).color).toBe("#cc33ff");
});
+
+test("label count settings preserve defaults and enforce the integer range",()=>{
+ for (const value of [undefined,null,"",NaN,Infinity,"invalid"]) expect(normalizeSatelliteLabelCount(value)).toBe(36);
+ expect(normalizeSatelliteLabelCount(1)).toBe(5);
+ expect(normalizeSatelliteLabelCount(100)).toBe(36);
+ expect(normalizeSatelliteLabelCount("12")).toBe(12);
+ expect(normalizeSatelliteLabelCount(12.7)).toBe(13);
+});
+
+test("close-up threshold defaults to 400% and is bounded by 250% and globe zoom",()=>{
+ for(const value of [undefined,null,"",NaN,Infinity,"invalid"]) expect(normalizeSatelliteLabelMinZoom(value)).toBe(4);
+ expect(normalizeSatelliteLabelMinZoom(1)).toBe(2.5);
+ expect(normalizeSatelliteLabelMinZoom(10)).toBe(5);
+ expect(normalizeSatelliteLabelMinZoom("3.2")).toBe(3.2);
+});
diff --git a/frontend/public/earth/js/satellite-labels.js b/frontend/public/earth/js/satellite-labels.js
index abdc71e3..c6ff5b1e 100644
--- a/frontend/public/earth/js/satellite-labels.js
+++ b/frontend/public/earth/js/satellite-labels.js
@@ -6,9 +6,21 @@ import { isSurfaceAnchorVisible } from "./surface-marker-occlusion.js";
const MAX_LABELS = SATELLITE_CONFIG.labelMaxCount;
const SCAN_INTERVAL_MS = SATELLITE_CONFIG.labelScanIntervalMs;
+export function normalizeSatelliteLabelCount(value) {
+ const count = value == null || value === "" ? NaN : Number(value);
+ return Number.isFinite(count)
+ ? Math.max(SATELLITE_CONFIG.labelMinCount, Math.min(MAX_LABELS, Math.round(count)))
+ : MAX_LABELS;
+}
+export function normalizeSatelliteLabelMinZoom(value) {
+ const zoom = value == null || value === "" ? NaN : Number(value);
+ return Number.isFinite(zoom)
+ ? Math.max(SATELLITE_CONFIG.labelMinZoomLowerBound, Math.min(CONFIG.maxZoom, zoom))
+ : SATELLITE_CONFIG.labelMinZoom;
+}
export function createSatelliteLabels() {
let root = null, featuresRef = null, metadata = [], nextScan = 0;
- let slots = [], active = [], previous = new Set();
+ let slots = [], active = [], previous = new Set(), maxCount = MAX_LABELS, minZoom = SATELLITE_CONFIG.labelMinZoom;
const projection = new THREE.Matrix4(), view = new THREE.Matrix4();
const cameraLocal = new THREE.Vector3(), projected = new THREE.Vector3();
const hide = () => { if (root && !root.hidden) root.hidden = true; };
@@ -27,9 +39,21 @@ export function createSatelliteLabels() {
}
return {
hide,
+ getMinZoom: () => minZoom,
+ setMinZoom(value) {
+ const next = normalizeSatelliteLabelMinZoom(value);
+ if (next !== minZoom) { minZoom = next; nextScan = 0; }
+ return minZoom;
+ },
+ getMaxCount: () => maxCount,
+ setMaxCount(value) {
+ const next = normalizeSatelliteLabelCount(value);
+ if (next !== maxCount) { maxCount = next; nextScan = 0; }
+ return maxCount;
+ },
dispose() { root?.remove(); root = null; active = []; featuresRef = null; metadata = []; previous.clear(); },
update({ camera, object, renderer, features, positions, isVisible, priority = -1 }) {
- if (!object?.visible || globeZoomForDistance(camera.position.length(), CONFIG.earthRadius, CONFIG.defaultCameraZ) < SATELLITE_CONFIG.labelMinZoom - 1e-6) { hide(); nextScan = 0; return; }
+ if (!object?.visible || globeZoomForDistance(camera.position.length(), CONFIG.earthRadius, CONFIG.defaultCameraZ) < minZoom - 1e-6) { hide(); nextScan = 0; return; }
ensureRoot(); if (root.hidden) root.hidden = false;
if (featuresRef !== features) {
featuresRef = features; metadata = features.map(feature => satelliteLabel(feature.properties));
@@ -64,7 +88,7 @@ export function createSatelliteLabels() {
}
candidates.sort((a,b)=>a.score-b.score);
const occupied = [], chosen = [];
- const limit = Math.min(MAX_LABELS, Math.max(8, Math.floor(width * height / 23000)));
+ const limit = Math.min(maxCount, Math.max(8, Math.floor(width * height / 23000)));
for (const candidate of candidates) {
const text = metadata[candidate.index];
const labelWidth = Math.min(130, Math.max(text.name.length, text.detail.length) * 7 + 8);
diff --git a/frontend/public/earth/js/satellite-motion.js b/frontend/public/earth/js/satellite-motion.js
index 0a9b2aac..b4efd1e4 100644
--- a/frontend/public/earth/js/satellite-motion.js
+++ b/frontend/public/earth/js/satellite-motion.js
@@ -8,6 +8,13 @@ export function createSatelliteMotion() {
if (!target.length) return false;
const alpha = Math.max(0, Math.min(1, (now - startedAt) / duration));
if (alpha === lastAlpha) return false;
+ if (alpha === 0 || alpha === 1) {
+ const values = alpha === 0 ? from : target;
+ rendered.set(values);
+ if (output !== rendered) output.set(values);
+ lastAlpha = alpha;
+ return true;
+ }
for (let i = 0; i < target.length; i += 3) {
const a = fromRadii[i / 3];
const b = targetRadii[i / 3];
@@ -39,8 +46,8 @@ export function createSatelliteMotion() {
}
// Radii change at propagation cadence, not at display refresh cadence.
for (let i = 0; i < target.length; i += 3) {
- fromRadii[i / 3] = Math.hypot(from[i], from[i + 1], from[i + 2]);
- targetRadii[i / 3] = Math.hypot(target[i], target[i + 1], target[i + 2]);
+ fromRadii[i / 3] = Math.sqrt(from[i] * from[i] + from[i + 1] * from[i + 1] + from[i + 2] * from[i + 2]);
+ targetRadii[i / 3] = Math.sqrt(target[i] * target[i] + target[i + 1] * target[i + 1] + target[i + 2] * target[i + 2]);
}
startedAt = now; duration = Math.max(1, intervalMs); lastAlpha = -1;
},
diff --git a/frontend/public/earth/js/satellite-trail-geometry.js b/frontend/public/earth/js/satellite-trail-geometry.js
index 31b81831..f7904c94 100644
--- a/frontend/public/earth/js/satellite-trail-geometry.js
+++ b/frontend/public/earth/js/satellite-trail-geometry.js
@@ -1,28 +1,52 @@
-// Short SGP4 tails are almost straight. Collapse redundant ribbon segments
-// only below a conservative screen-error bound for every supported zoom.
-export function canUseTrailChord(state, length, minimumCameraRadius, projectionScale, maxErrorPx = 0.2) {
- const count = state.trailCount;
- if (count < 2) return false;
- const first = state.trail[(state.trailIndex - count + length) % length];
- const last = state.trail[(state.trailIndex - 1 + length) % length];
- if (!first || !last) return false;
- const dx=last.x-first.x, dy=last.y-first.y, dz=last.z-first.z;
- const chordSq=dx*dx+dy*dy+dz*dz;
- if (chordSq < 1e-8) return false;
- let errorSq=0, radiusSq=0;
+// Retain as many samples as the current projection needs, including temporal
+// spacing: interpolated position and fade must stay within the same pixel bound.
+export function selectTrailSamples(state, length, cameraRadius, projectionScale, indices, stack, maxErrorPx = 0.2) {
+ const count=state.trailCount;
+ if(count<2) return 0;
+ const start=(state.trailIndex-count+length)%length;
+ const first=state.trail[start],last=state.trail[(start+count-1)%length];
+ if(!first || !last) return 0;
+ const dx=last.x-first.x,dy=last.y-first.y,dz=last.z-first.z;
+ let radiusSq=0,initialError=0,initialWorst=-1;
+ // The radius bound and the initial whole-span error use the same samples.
+ // Compute both in one pass; retain exactly the previous subdivision result.
for(let i=0;i0 && iinitialError) {initialError=distance;initialWorst=i;}
+ }
}
- const safeDepth=minimumCameraRadius-Math.sqrt(radiusSq);
- if(safeDepth<=1) return false;
- const tolerance=maxErrorPx*safeDepth/projectionScale;
- return errorSq<=tolerance*tolerance;
+ const depth=cameraRadius-Math.sqrt(radiusSq);
+ if(depth<=1) {for(let i=0;ithreshold)) {indices[0]=0;indices[1]=count-1;return 2;}
+ indices.fill(0,0,count);indices[0]=indices[count-1]=indices[initialWorst]=1;
+ let top=0;
+ if(initialWorst>1) {stack[top++]=0;stack[top++]=initialWorst;}
+ if(count-1-initialWorst>1) {stack[top++]=initialWorst;stack[top++]=count-1;}
+ while(top) {
+ const end=stack[--top],begin=stack[--top];
+ const a=state.trail[(start+begin)%length],b=state.trail[(start+end)%length];
+ let worst=-1,error=threshold;
+ for(let i=begin+1;ierror) {error=distance;worst=i;}
+ }
+ if(worst<0) continue;
+ indices[worst]=1;
+ if(worst-begin>1) {stack[top++]=begin;stack[top++]=worst;}
+ if(end-worst>1) {stack[top++]=worst;stack[top++]=end;}
+ }
+ let written=0;
+ for(let i=0;inew THREE.Vector3(radius*Math.cos(i/9*angle),radius*Math.sin(i/9*angle),0)),trailIndex:0,trailCount:10}; }
-test("only subpixel short arcs collapse; curved or near-camera trails retain segments",()=>{
- expect(canUseTrailChord(arc(104,.0025),10,110,2500)).toBe(true);
- expect(canUseTrailChord(arc(104,.03),10,110,2500)).toBe(false);
- expect(canUseTrailChord(arc(124,.0025),10,110,2500)).toBe(false);
- expect(canUseTrailChord(arc(104,0),10,110,2500)).toBe(false);
- expect(canUseTrailChord(arc(104,.0025),10,110,100000)).toBe(false);
+import {selectTrailSamples,markActiveAttribute} from "./satellite-trail-geometry.js";
+function arc(radius,angle) {return {trail:Array.from({length:10},(_,i)=>new THREE.Vector3(radius*Math.cos(i/9*angle),radius*Math.sin(i/9*angle),0)),trailIndex:0,trailCount:10};}
+function select(state,camera,scale) {const out=new Uint16Array(10),stack=new Uint16Array(20);return [...out.subarray(0,selectTrailSamples(state,10,camera,scale,out,stack))];}
+test("distant short arcs collapse while near-camera or curved tails keep their detail",()=>{
+ expect(select(arc(104,.0025),110,2500)).toEqual([0,9]);
+ expect(select(arc(104,.03),110,2500).length).toBeGreaterThan(2);
+ expect(select(arc(124,.0025),110,2500)).toEqual([0,1,2,3,4,5,6,7,8,9]);
+ expect(select(arc(104,.0025),110,100000).length).toBeGreaterThan(2);
+ expect(select(arc(104,.03),300,2500).length).toBeLessThan(select(arc(104,.03),110,2500).length);
+});
+test("irregular worker timing only merges spans within the positional and chronological error bound",()=>{
+ const state=arc(104,.004);
+ state.trail[4].multiplyScalar(1.00001);state.trail[6].y+=.004;
+ const original=JSON.stringify(state),samples=select(state,180,2500);
+ const tolerance=.2*(180-Math.max(...state.trail.map(p=>p.length())))/2500;
+ for(let j=0;j{
+ const state=arc(104,.0025),out=new Uint16Array(10),stack=new Uint16Array(20);
+ expect(selectTrailSamples(state,10,100,2000,out,stack)).toBe(10);
+ state.trailCount=3;state.trailIndex=2;
+ const count=selectTrailSamples(state,10,100,2000,out,stack);
+ expect([...out.subarray(0,count)]).toEqual([0,1,2]);
+ state.trailCount=0;expect(selectTrailSamples(state,10,100,2000,out,stack)).toBe(0);
});
test("upload range covers only active ribbon vertices",()=>{
const attr=new THREE.InstancedBufferAttribute(new Float32Array(300),3);
markActiveAttribute(attr,30);expect(attr.updateRanges).toEqual([{start:0,count:30}]);
markActiveAttribute(attr,60);expect(attr.updateRanges).toEqual([{start:0,count:60}]);
});
+
+
+test("combined scan preserves recursive subdivision across wrapped and irregular histories",()=>{
+ let seed=1749;
+ const random=()=>{seed=(Math.imul(seed,1664525)+1013904223)>>>0;return seed/4294967296;};
+ for(let trial=0;trial<1200;trial++) {
+ const count=2+trial%9,start=trial%10,camera=100+random()*250,scale=800+random()*10000;
+ const points=Array.from({length:count},(_,i)=>new THREE.Vector3(100+i*.001,Math.sin(i*.1)*random()*.1,random()*.0001));
+ const radius=Math.sqrt(Math.max(...points.map(p=>p.lengthSq()))),depth=camera-radius;
+ const expected=new Set([0,count-1]);
+ function split(a,b) {
+ const delta=points[b].clone().sub(points[a]);
+ let error=(.2*depth/scale)**2,worst=-1;
+ for(let i=a+1;ierror){error=d;worst=i;}
+ }
+ if(worst!==-1){expected.add(worst);split(a,worst);split(worst,b);}
+ }
+ if(depth<=1) points.forEach((_,i)=>expected.add(i));else split(0,count-1);
+ const trail=new Array(10);points.forEach((p,i)=>trail[(start+i)%10]=p);
+ const actual=select({trail,trailCount:count,trailIndex:(start+count)%10},camera,scale);
+ expect(actual).toEqual([...expected].sort((a,b)=>a-b));
+ }
+});
diff --git a/frontend/public/earth/js/satellites.js b/frontend/public/earth/js/satellites.js
index 27494aaa..02ccf706 100644
--- a/frontend/public/earth/js/satellites.js
+++ b/frontend/public/earth/js/satellites.js
@@ -1,5 +1,5 @@
import { createSatelliteFootprintGeometry, SATELLITE_FOOTPRINT_VERTEX_SHADER } from "./satellite-footprint-geometry.js";
-import { canUseTrailChord, markActiveAttribute } from "./satellite-trail-geometry.js";
+import { selectTrailSamples, markActiveAttribute } from "./satellite-trail-geometry.js";
import { createSatelliteLabels } from "./satellite-labels.js";
import { SATELLITE_CATEGORIES, satelliteCategory, satellitePixelSize } from "./satellite-display.js";
import { openOrbitSampleTimes, createOrbitFlowGeometry, createOrbitFlowMaterial } from "./satellite-orbit-visual.js";
@@ -40,6 +40,17 @@ let selectedSatellite = null;
let satellitePositions = [];
const satelliteMotion = createSatelliteMotion();
const satelliteLabels = createSatelliteLabels();
+export function getSatelliteLabelMinZoom() { return satelliteLabels.getMinZoom(); }
+export function setSatelliteLabelMinZoom(zoom) { return satelliteLabels.setMinZoom(zoom); }
+export function getSatelliteLabelCount() { return satelliteLabels.getMaxCount(); }
+export function setSatelliteLabelCount(count) { return satelliteLabels.setMaxCount(count); }
+let satelliteLabelsEnabled = true;
+export function getSatelliteLabelsEnabled() { return satelliteLabelsEnabled; }
+export function setSatelliteLabelsEnabled(enabled) {
+ satelliteLabelsEnabled = Boolean(enabled);
+ if (!satelliteLabelsEnabled) satelliteLabels.hide();
+ return satelliteLabelsEnabled;
+}
let hoverRingSprite = null;
let lockedRingSprite = null;
let lockedDotSprite = null;
@@ -50,6 +61,8 @@ let lockedIridiumFootprintMesh = null;
let predictedOrbitLine = null;
let relatedSatelliteSprites = [];
let highlightedSatelliteIndices = null;
+let satellitePointColorsDirty = true;
+let lastPointHighlight = null;
let earthObjRef = null;
let sceneRef = null;
let cameraRef = null;
@@ -57,6 +70,7 @@ let lockedSatelliteIndex = null;
let hoveredSatelliteIndex = null;
let positionUpdateAccumulator = 0;
let satelliteCapacity = 0;
+let trailProjection = null;
let satelliteDisplayStyle = DEFAULT_SATELLITE_DISPLAY_STYLE;
let satelliteIdleBreathingEnabled = false;
let satelliteRealAltitudeEnabled = true;
@@ -93,6 +107,8 @@ const SATELLITE_CONSTELLATION_LABELS = Object.freeze({
});
const TRAIL_LENGTH = SATELLITE_CONFIG.trailLength;
+const trailSampleIndices = new Uint16Array(TRAIL_LENGTH);
+const trailSampleStack = new Uint16Array(TRAIL_LENGTH * 2);
const TRAIL_RIBBON_VERTEX_SHADER = /* glsl */ `
attribute vec3 instanceStart;
@@ -515,6 +531,7 @@ function createSatellitePositionState(index = 0) {
}
function resetSatelliteTrailState() {
+ trailProjection = null;
satellitePositions.forEach((position) => {
position.trail = [];
position.trailIndex = 0;
@@ -768,6 +785,8 @@ export async function loadSatellites(options = {}) {
satellitePropagator.reset();
resetSatelliteTrailState();
ensureSatelliteCapacity(satelliteData.length);
+ satellitePointColorsDirty = true;
+ updateSatellitePointVisibilityAttributes();
satelliteWorkerDisabled = false;
startSatellitePositionWorker();
positionUpdateAccumulator = POSITION_UPDATE_INTERVAL_MS;
@@ -831,21 +850,12 @@ function applySatellitePositionSnapshot(snapshot, shouldUpdateTrails) {
const positions = satellitePoints.geometry.attributes.position.array;
const colors = satellitePoints.geometry.attributes.color.array;
const pointAlphas = satellitePoints.geometry.attributes.alpha.array;
- const instanceStarts = satelliteTrails.geometry.attributes.instanceStart.array;
- const instanceEnds = satelliteTrails.geometry.attributes.instanceEnd.array;
- const instanceColorStarts = satelliteTrails.geometry.attributes.instanceColorStart.array;
- const instanceColorEnds = satelliteTrails.geometry.attributes.instanceColorEnd.array;
const baseTime = new Date(snapshot.baseTime);
const count = Math.min(satelliteData.length, satelliteCapacity);
- let trailSegmentCount = 0;
- const halfFov = (cameraRef?.fov || 75) * Math.PI / 360;
- const tangent = Math.tan(halfFov);
- const projectionScale = window.innerHeight * (window.devicePixelRatio || 1) / (2 * tangent)
- * (1 + Math.hypot((cameraRef?.aspect || 1) * tangent, tangent));
+ const refreshColors = satellitePointColorsDirty || lastPointHighlight !== highlightedSatelliteIndices;
for (let i = 0; i < count; i++) {
const satellite = satelliteData[i];
- const props = satellite.properties;
const adjustedTime = satellitePositions[i].currentTime || new Date();
adjustedTime.setTime(getSatelliteSampleTimeMs(baseTime.getTime(), i, count));
let pos = snapshot.positions
@@ -887,30 +897,77 @@ function applySatellitePositionSnapshot(snapshot, shouldUpdateTrails) {
positions[i * 3 + 1] = pos.y;
positions[i * 3 + 2] = pos.z;
+ if (refreshColors) {
+ const {r,g,b} = getSatelliteRuleColor(satelliteRules[i]);
+ const brightness = highlightedSatelliteIndices !== null && !highlightedSatelliteIndices.has(i)
+ ? DIMMED_SATELLITE_BRIGHTNESS : 1;
+ colors[i*3]=r*brightness;colors[i*3+1]=g*brightness;colors[i*3+2]=b*brightness;
+ }
+
+ }
+
+ satelliteMotion.push(positions.subarray(0, count * 3), performance.now(), POSITION_UPDATE_INTERVAL_MS);
+ for (let i = count; i < satelliteCapacity; i++) {
+ positions[i * 3] = 0;
+ positions[i * 3 + 1] = 0;
+ positions[i * 3 + 2] = 0;
+ pointAlphas[i] = 0;
+
+ }
+
+ satellitePoints.geometry.attributes.position.needsUpdate = true;
+ if (refreshColors) {
+ satellitePoints.geometry.attributes.color.needsUpdate = true;
+ satellitePointColorsDirty = false;
+ lastPointHighlight = highlightedSatelliteIndices;
+ }
+ satellitePoints.geometry.setDrawRange(0, count);
+
+ rebuildSatelliteTrails(getTrailProjection());
+
+ // Keep the hover ring synced with the propagated satellite position even
+ // when the pointer stays still and no new hover event is emitted.
+ if (
+ hoveredSatelliteIndex !== null &&
+ hoveredSatelliteIndex >= 0 &&
+ hoveredSatelliteIndex < count &&
+ hoveredSatelliteIndex !== lockedSatelliteIndex
+ ) {
+ updateHoverRingPosition(satellitePositions[hoveredSatelliteIndex].current);
+ }
+}
+
+function getTrailProjection() {
+ const tangent = Math.tan((cameraRef?.fov || 75) * Math.PI / 360);
+ const scale = window.innerHeight * (window.devicePixelRatio || 1) / (2 * tangent)
+ * (1 + Math.hypot((cameraRef?.aspect || 1) * tangent, tangent));
+ // Round toward more detail, so a bucket remains safe throughout zoom/resize.
+ return {cameraRadius:Math.floor((cameraRef?.position.length() || CONFIG.earthRadius) / 8) * 8,
+ projectionScale:Math.ceil(scale / 128) * 128};
+}
+
+function rebuildSatelliteTrails(view) {
+ const instanceStarts = satelliteTrails.geometry.attributes.instanceStart.array;
+ const instanceEnds = satelliteTrails.geometry.attributes.instanceEnd.array;
+ const instanceColorStarts = satelliteTrails.geometry.attributes.instanceColorStart.array;
+ const instanceColorEnds = satelliteTrails.geometry.attributes.instanceColorEnd.array;
+ const count = Math.min(satelliteData.length, satelliteCapacity);
+ let trailSegmentCount = 0;
+ for (let i = 0; i < count; i++) {
+ const pos = satellitePositions[i].current;
const rule = satelliteRules[i];
const categoryIndex = SATELLITE_CATEGORIES.indexOf(rule);
- const { r, g, b } = getSatelliteRuleColor(rule);
-
- const isNonFocusDimmed =
- highlightedSatelliteIndices !== null && !highlightedSatelliteIndices.has(i);
- const pointBrightness = isNonFocusDimmed ? DIMMED_SATELLITE_BRIGHTNESS : 1;
- const trailBrightness = isNonFocusDimmed
+ const {r,g,b} = getSatelliteRuleColor(rule);
+ const trailBrightness = highlightedSatelliteIndices !== null && !highlightedSatelliteIndices.has(i)
? DIMMED_SATELLITE_TRAIL_BRIGHTNESS : 1;
-
- colors[i * 3] = r * pointBrightness;
- colors[i * 3 + 1] = g * pointBrightness;
- colors[i * 3 + 2] = b * pointBrightness;
- const pointAlpha = shouldHideSatellitePoint(i) || !isSatelliteCategoryVisible(i) ? 0 : 1;
- pointAlphas[i] = pointAlpha;
-
const satPosition = satellitePositions[i];
const tc = satPosition.trailCount;
let hasVisibleTrail = false;
- const compactTrail = canUseTrailChord(satPosition, TRAIL_LENGTH,
- CONFIG.earthRadius + CONFIG.minimumCameraAltitude, projectionScale);
- for (let j = 0; j < (compactTrail ? 1 : TRAIL_LENGTH - 1); j++) {
- const sampleA = compactTrail ? 0 : j;
- const sampleB = compactTrail ? tc - 1 : j + 1;
+ const sampleCount = selectTrailSamples(satPosition, TRAIL_LENGTH, view.cameraRadius,
+ view.projectionScale, trailSampleIndices, trailSampleStack);
+ for (let j = 0; j < sampleCount - 1; j++) {
+ const sampleA = trailSampleIndices[j];
+ const sampleB = trailSampleIndices[j + 1];
if (sampleB < tc) {
const idxA =
(satPosition.trailIndex - tc + sampleA + TRAIL_LENGTH) % TRAIL_LENGTH;
@@ -966,42 +1023,20 @@ function applySatellitePositionSnapshot(snapshot, shouldUpdateTrails) {
}
satPosition.renderTrailTipOffset = (trailSegmentCount - 1) * 3;
}
-
- satelliteMotion.push(positions.subarray(0, count * 3), performance.now(), POSITION_UPDATE_INTERVAL_MS);
- for (let i = count; i < satelliteCapacity; i++) {
- positions[i * 3] = 0;
- positions[i * 3 + 1] = 0;
- positions[i * 3 + 2] = 0;
- pointAlphas[i] = 0;
-
- }
-
- satellitePoints.geometry.attributes.position.needsUpdate = true;
- satellitePoints.geometry.attributes.color.needsUpdate = true;
- satellitePoints.geometry.attributes.alpha.needsUpdate = true;
- satellitePoints.geometry.setDrawRange(0, count);
-
for (const name of TRAIL_INSTANCE_ATTRIBUTE_NAMES) {
markActiveAttribute(satelliteTrails.geometry.attributes[name], trailSegmentCount * 3);
}
markActiveAttribute(satelliteTrails.geometry.attributes.instanceCategory, trailSegmentCount);
satelliteTrails.geometry.instanceCount = trailSegmentCount;
-
- // Keep the hover ring synced with the propagated satellite position even
- // when the pointer stays still and no new hover event is emitted.
- if (
- hoveredSatelliteIndex !== null &&
- hoveredSatelliteIndex >= 0 &&
- hoveredSatelliteIndex < count &&
- hoveredSatelliteIndex !== lockedSatelliteIndex
- ) {
- updateHoverRingPosition(satellitePositions[hoveredSatelliteIndex].current);
- }
+ trailProjection = view;
}
function renderSatelliteMotion() {
if (!showSatellites && lockedSatelliteIndex === null && hoveredSatelliteIndex === null) return;
if (!satellitePoints || !satellitePositions.length) return;
+ const view = getTrailProjection();
+ if (showTrails && (!trailProjection || view.cameraRadius < trailProjection.cameraRadius ||
+ view.projectionScale > trailProjection.projectionScale)) rebuildSatelliteTrails(view);
const positions = satellitePoints.geometry.attributes.position;
if (!satelliteMotion.sample(performance.now(), positions.array)) return;
const count = Math.min(satelliteData.length, satelliteCapacity);
@@ -1022,7 +1057,7 @@ function renderSatelliteMotion() {
}
export function updateSatelliteLabels(renderer) {
- if (!showSatellites || !cameraRef || !renderer) { satelliteLabels.hide(); return; }
+ if (!satelliteLabelsEnabled || !showSatellites || !cameraRef || !renderer) { satelliteLabels.hide(); return; }
satelliteLabels.update({ camera:cameraRef, object:satellitePoints, renderer,
features:satelliteData, positions:satellitePositions, isVisible:isSatelliteCategoryVisible,
priority:lockedSatelliteIndex ?? hoveredSatelliteIndex ?? -1 });
@@ -1076,6 +1111,12 @@ export function selectSatellite(index) {
return getSatelliteAt(index);
}
+export function getSatelliteRenderMetrics() {
+ return {count:satelliteData.length,capacity:satelliteCapacity,
+ trailSegments:satelliteTrails?.geometry.instanceCount || 0,trailProjection,
+ pointsVisible:Boolean(satellitePoints?.visible),trailsVisible:Boolean(satelliteTrails?.visible)};
+}
+
export function getSatellitePoints() {
return satellitePoints;
}
@@ -1099,11 +1140,13 @@ export function setSatelliteSunDirection(direction) {
}
export function setLockedSatelliteIndex(index) {
+ if (lockedSatelliteIndex === index) return;
lockedSatelliteIndex = index;
updateSatellitePointVisibilityAttributes();
}
export function setHoveredSatelliteIndex(index) {
+ if (hoveredSatelliteIndex === index) return;
hoveredSatelliteIndex = index;
updateSatellitePointVisibilityAttributes();
}
@@ -1161,7 +1204,7 @@ function getSatelliteFootprintPolicy(props = {}) {
return SATELLITE_FOOTPRINT_POLICIES.NONE;
}
-function getSatelliteConstellationLabel(props = {}) {
+export function getSatelliteConstellationLabel(props = {}) {
const constellationGroup = inferSatelliteConstellationGroup(props);
if (!constellationGroup) return "未分类";
return (
@@ -1188,45 +1231,6 @@ function getSatellitePresentationMode(props = {}) {
return SATELLITE_PRESENTATION_MODES.SELF_GLOW;
}
-function getSatelliteFootprintCapabilityLabel(props = {}) {
- const footprintPolicy = getSatelliteFootprintPolicy(props);
- switch (footprintPolicy) {
- case SATELLITE_FOOTPRINT_POLICIES.STARLINK_GROUND_FOOTPRINT:
- return "支持 Starlink 地表覆盖";
- case SATELLITE_FOOTPRINT_POLICIES.IRIDIUM_COVERAGE_RING:
- return "支持 Iridium 外圈覆盖";
- default:
- return "默认不显示 footprint";
- }
-}
-
-function getSatellitePresentationModeLabel(mode) {
- switch (mode) {
- case SATELLITE_PRESENTATION_MODES.STARLINK_GROUND_FOOTPRINT:
- return "真实地表覆盖(Starlink)";
- case SATELLITE_PRESENTATION_MODES.IRIDIUM_SPOT_BEAMS:
- return "真实地表覆盖(Iridium 外圈)";
- default:
- return "自身发光";
- }
-}
-
-export function getSatellitePresentationInfo(props = {}) {
- const footprintPolicy = getSatelliteFootprintPolicy(props);
- const presentationMode = getSatellitePresentationMode(props);
-
- return {
- constellationGroup: inferSatelliteConstellationGroup(props),
- constellationLabel: getSatelliteConstellationLabel(props),
- footprintPolicy,
- footprintCapabilityLabel: getSatelliteFootprintCapabilityLabel(props),
- presentationMode,
- presentationModeLabel: getSatellitePresentationModeLabel(
- presentationMode,
- ),
- };
-}
-
function getLockedSatelliteProperties() {
if (lockedSatelliteIndex === null) return null;
return satelliteData[lockedSatelliteIndex]?.properties || null;
@@ -1473,8 +1477,10 @@ function clearLockedSatelliteStyleVisuals() {
function updateLockedDotWorldTransform(position) {
if (!lockedDotSprite || !position || !earthObjRef) return;
- earthObjRef.updateMatrixWorld(true);
- const worldPosition = position.clone().applyMatrix4(earthObjRef.matrixWorld);
+ // These scene-level overlays need only the earth transform, not updates to
+ // every earth descendant (the renderer still updates the full scene).
+ earthObjRef.updateWorldMatrix(true, false);
+ const worldPosition = scratchWorldSatellitePosition.copy(position).applyMatrix4(earthObjRef.matrixWorld);
lockedDotSprite.position.copy(worldPosition);
if (cameraRef) {
lockedDotSprite.quaternion.copy(cameraRef.quaternion);
@@ -1494,8 +1500,10 @@ function updateLockedDotWorldTransform(position) {
function updateLockedHaloWorldTransform(position) {
if (!position || !earthObjRef || !lockedHaloMesh) return;
- earthObjRef.updateMatrixWorld(true);
- const worldPosition = position.clone().applyMatrix4(earthObjRef.matrixWorld);
+ // These scene-level overlays need only the earth transform, not updates to
+ // every earth descendant (the renderer still updates the full scene).
+ earthObjRef.updateWorldMatrix(true, false);
+ const worldPosition = scratchWorldSatellitePosition.copy(position).applyMatrix4(earthObjRef.matrixWorld);
const viewDirection = cameraRef
? scratchToCamera.subVectors(cameraRef.position, worldPosition).normalize()
: null;
@@ -1773,13 +1781,13 @@ function updateIridiumReservedStyle(position) {
});
}
-function createRingSprite(position, isLocked = false, color = "#ffcc00") {
+function createRingSprite(position, isLocked = false, color = "#ffffff") {
if (!earthObjRef) return null;
const ringTexture = createRingTexture(
8,
12,
- isLocked ? color : "#ffffff",
+ color,
isLocked ? LOCKED_RING_HOVER_LINE_WIDTH : HOVER_RING_LINE_WIDTH,
);
const filledTexture = isLocked
@@ -1855,7 +1863,8 @@ export function showHoverRing(position, isLocked = false) {
}
hideHoverRings();
- hoverRingSprite = createRingSprite(position, false);
+ const hoverColor = getSatelliteLegendRule(satelliteData[hoveredSatelliteIndex]?.properties).color;
+ hoverRingSprite = createRingSprite(position, false, hoverColor);
return hoverRingSprite;
}
@@ -2195,6 +2204,7 @@ export function clearSatelliteData() {
stopSatellitePositionWorker();
satelliteData = [];
satelliteRules = [];
+ satellitePointColorsDirty = true;lastPointHighlight = null;
satelliteCategoryCounts.clear();
satellitePropagator.reset();
selectedSatellite = null;
diff --git a/frontend/public/earth/js/spatial-callout-controller.js b/frontend/public/earth/js/spatial-callout-controller.js
index 433bd43d..75f02a94 100644
--- a/frontend/public/earth/js/spatial-callout-controller.js
+++ b/frontend/public/earth/js/spatial-callout-controller.js
@@ -1,37 +1,26 @@
import * as THREE from "three";
-import { CalloutConnector } from "./callout-connector.js";
-import { advanceCallouts } from "./callout-routing.js";
-import {
- getCalloutMotionMode,
- canRelocateUserCard,
- rememberCalloutLayout,
- reviewTangledLayout,
- READING_INTERVAL_MS,
- MANUAL_READING_HOLD_MS,
- isResponsiveCalloutMotion,
- rotationNeedsReflow,
-} from "./callout-stability.js";
-import { CONFIG } from "./constants.js";
-import { projectedSphereRadius, smoothHighlightAnchor } from "./highlight-anchor.js";
-import { bindHUDDrag } from "./hud-drag.js";
-import { CALLOUT_POSITION_VERSION, restoreCalloutPlacement } from "./callout-saved-placement.js";
+import {CalloutConnector} from "./callout-connector.js";
+import {createCalloutSettleGate, layoutObstaclesSignature, updateCalloutFloat} from "./callout-rest.js";
+import {centralReadingExclusion, legalDockRect, planDockLayout, settleCardDrop} from "./callout-dock-layout.js";
+import {createDockMotion, advanceDockMotion} from "./callout-dock-motion.js";
+import {CONFIG} from "./constants.js";
+import {projectedSphereRadius, smoothHighlightAnchor} from "./highlight-anchor.js";
+import {bindHUDDrag} from "./hud-drag.js";
+import {advanceCalloutReveal} from "./callout-reveal.js";
+import {createRegionConnectorPath} from "./callout-region-path.js";
-import { advanceCalloutReveal } from "./callout-reveal.js";
-import { createRegionConnectorPath } from "./callout-region-path.js";
-import { scoreCalloutLayout, improvesCalloutLayout } from "./callout-proximity.js";
-
-const EDGE = 12;
-const RESPONSIVE_LAYOUT_INTERVAL_MS = 72;
const STORAGE_KEY = "planet.compute.card-positions.v1";
-const clamp = (value, min, max) => Math.max(min, Math.min(Math.max(min, max), value));
+const EDGE = 12;
+const clamp = (value,min,max) => Math.max(min,Math.min(Math.max(min,max),value));
export function renderSpatialCalloutConnector(state, { animate = false } = {}) {
const point = state?.sourcePoint || state?.point;
+ const rect = state && { x: state.displayX ?? state.x + (state.floatX || 0), y: state.displayY ?? state.y + (state.floatY || 0), width: state.width, height: state.height };
if (!point || !state.connector) return false;
if (state.connector.isAnimating?.()) return true;
const rearChanged = state.lastConnectorFront !== point.front;
const sameRect = state.lastConnectorRect && ["x", "y", "width", "height"].every(
- key => Math.abs(state[key] - state.lastConnectorRect[key]) < 0.5,
+ key => Math.abs(rect[key] - state.lastConnectorRect[key]) < 0.5,
);
const positionSettled = Math.hypot(state.x - state.targetX, state.y - state.targetY) < 0.5;
if (state.connector.isVisible?.() === true && state.lastConnector &&
@@ -40,12 +29,7 @@ export function renderSpatialCalloutConnector(state, { animate = false } = {}) {
return true;
}
- const path = createRegionConnectorPath(point, {
- x: state.x,
- y: state.y,
- width: state.width,
- height: state.height,
- });
+ const path = createRegionConnectorPath(point, rect);
const rendered = path ? state.connector.render(path, { animate }) : false;
if (!rendered) state.connector.hide();
@@ -58,380 +42,224 @@ export function renderSpatialCalloutConnector(state, { animate = false } = {}) {
}
state.lastConnector = { x: point.x, y: point.y };
state.lastConnectorFront = point.front;
- state.lastConnectorRect = { x: state.x, y: state.y, width: state.width, height: state.height };
+ state.lastConnectorRect = rect;
return rendered;
}
-export function createCalloutController({
- root,
- getSpatialContext,
- getAnchorCandidates,
- project,
- solve,
-}) {
- const cards = new Map();
- let saved = {};
- try { saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || "{}"); } catch { /* Optional layout preference. */ }
- if (!saved || typeof saved !== "object" || Array.isArray(saved)) saved = {};
- let obstacles = [], layoutJob = null, revision = 0, lastLayoutAt = -Infinity;
- let dirty = true, mobile = false, lastObstacleAt = -Infinity, lastViewport = "";
- let previousMotionMode = null, currentGlobe = null;
- let layoutReview = null, lastQualityAt = -Infinity, pendingGroupReflow = false;
- const reflowGate = { lastAttemptAt: -Infinity };
- const invalidate = () => {
- dirty = true;
- if (layoutReview) pendingGroupReflow = true;
- layoutJob = null; layoutReview = null; revision++;
- };
- const requestResponsiveLayout = () => { dirty = true; };
- const persist = () => {
- try { localStorage.setItem(STORAGE_KEY, JSON.stringify(saved)); } catch { /* Storage may be unavailable. */ }
- };
- const resizeObserver = new ResizeObserver(entries => {
- for (const entry of entries) {
- const state = cards.get(entry.target.dataset.region);
- if (!state) continue;
- const width = entry.target.offsetWidth, height = entry.target.offsetHeight;
- if (state.width === width && state.height === height) continue;
- state.width = width; state.height = height;
- if (state.userPlaced && !mobile) savePosition(state);
+export function createCalloutController({root,getSpatialContext,getAnchorCandidates,project}) {
+ const cards=new Map(), byElement=new WeakMap();
+ let saved={};
+ try {saved=JSON.parse(localStorage.getItem(STORAGE_KEY)||"{}");} catch { /* Optional preferences. */ }
+ if(!saved || typeof saved!=="object" || Array.isArray(saved)) saved={};
+ let dirty=true, revision=0, mobile=false, lastViewport="", lastObstacleAt=-Infinity;
+ let obstacles=[], preferredKey=null, urgent=false;
+ const settle=createCalloutSettleGate();
+ const reducedMotion=window.matchMedia("(prefers-reduced-motion: reduce)");
+ const invalidate=()=>{dirty=true;revision++;};
+ const persist=()=>{try {localStorage.setItem(STORAGE_KEY,JSON.stringify(saved));} catch { /* Optional preferences. */ }};
+
+ function savePosition(state) {
+ saved[state.key]={x:state.targetX,y:state.targetY,viewportWidth:innerWidth,viewportHeight:innerHeight,
+ width:state.element.style.width,height:state.element.style.height};
+ persist();
+ }
+ function measure(state) {
+ state.width=state.element.offsetWidth;state.height=state.element.offsetHeight;
+ state.header=state.element.querySelector("header");
+ }
+ function writePosition(state,viewport) {
+ const ratio=window.devicePixelRatio || 1;
+ let x=state.x+(state.floatX||0),y=state.y+(state.floatY||0);
+ if(!state.dragging && !legalDockRect({x,y,width:state.width,height:state.height},
+ [centralReadingExclusion(viewport)],viewport,0)) {x=state.x;y=state.y;}
+ x=Math.round(x*ratio)/ratio;y=Math.round(y*ratio)/ratio;
+ if(x!==state.displayX) state.element.style.left=`${x}px`;
+ if(y!==state.displayY) state.element.style.top=`${y}px`;
+ state.displayX=x;state.displayY=y;
+ }
+ const resizeObserver=new ResizeObserver(entries=>{
+ const scale=parseFloat(getComputedStyle(document.documentElement).getPropertyValue("--hud-scale"))||1;
+ for(const entry of entries) {
+ const state=byElement.get(entry.target);if(!state) continue;
+ for(const axis of ["width","height"]) {
+ const value=entry.target.style[axis];
+ if(/^[0-9.]+px$/.test(value)) entry.target.style[axis]=`calc(${parseFloat(value)/scale}px * var(--hud-scale))`;
+ }
+ const width=entry.target.offsetWidth,height=entry.target.offsetHeight;
+ if(width===state.width && height===state.height) continue;
+ state.width=width;state.height=height;
invalidate();
}
});
- function savePosition(state) {
- saved[state.key] = { x: state.x, y: state.y, viewportWidth: innerWidth, viewportHeight: innerHeight,
- width: state.element.style.width, height: state.element.style.height,
- positionVersion: CALLOUT_POSITION_VERSION };
- persist();
- }
- function writePosition(state) {
- const transform = `translate3d(${state.x.toFixed(1)}px, ${state.y.toFixed(1)}px, 0)`;
- if (transform === state.lastTransform) return;
- state.element.style.transform = transform;
- state.lastTransform = transform;
- }
function attach(item) {
- const stored = saved?.[item.key];
- if (stored?.width) item.element.style.width = stored.width;
- if (stored?.height) item.element.style.height = stored.height;
- const state = { ...item, x: NaN, y: NaN, targetX: NaN, targetY: NaN,
- width: item.element.offsetWidth, height: item.element.offsetHeight,
- lockedUntil: 0, userPlaced: false, revealPhase: "pending",
- connector: new CalloutConnector({ container: root, className: "callout-connector compute-connector" }) };
- const restored = restoreCalloutPlacement(stored, { width: innerWidth, height: innerHeight }, state);
- if (restored.migrated) { saved[item.key] = restored.stored; persist(); }
- if (restored.position) {
- state.x = restored.position.x;
- state.y = restored.position.y;
- state.targetX = state.x; state.targetY = state.y; state.userPlaced = true;
- item.element.dataset.dragged = "true";
- } else {
- delete item.element.dataset.dragged;
+ const stored=saved[item.key];
+ if(stored?.width) item.element.style.width=stored.width;
+ if(stored?.height) item.element.style.height=stored.height;
+ const state={...item,x:NaN,y:NaN,targetX:NaN,targetY:NaN,userPlaced:false,
+ revealPhase:"pending",connector:new CalloutConnector({container:root,className:"callout-connector compute-connector"})};
+ if(Number.isFinite(stored?.x) && Number.isFinite(stored?.y)) {
+ state.preference={x:stored.x*innerWidth/(stored.viewportWidth||innerWidth),
+ y:stored.y*innerHeight/(stored.viewportHeight||innerHeight)};state.userPlaced=true;
+ item.element.dataset.dragged="true";
}
- const hold = () => {
- state.lockedUntil = Infinity;
- if (Number.isFinite(state.x)) {
- state.targetX = state.x; state.targetY = state.y; state.route = null;
- }
- };
- const release = () => {
- state.interacting = state.hovering || state.focused || state.dragging;
- if (!state.interacting) state.lockedUntil = Math.max(performance.now() + 1800,
- state.expandedHoldUntil || 0, state.userHoldUntil || 0);
- };
- const enter = () => { state.hovering = true; state.interacting = true; hold(); };
- const leave = () => { state.hovering = false; release(); };
- const focus = event => {
- state.focused = Boolean(event.target.matches(":focus-visible, input, textarea, select, [contenteditable=true]"));
- if (state.focused) { state.interacting = true; hold(); }
- };
- const blur = event => {
- if (event.relatedTarget && item.element.contains(event.relatedTarget)) return;
- state.focused = false;
- release();
- };
- const listeners = [
- ["pointerenter", enter],
- ["pointerleave", leave],
- ["focusin", focus],
- ["focusout", blur],
+ measure(state);
+ const listeners=[
+ ["pointerenter",()=>{state.hovering=true;}],
+ ["pointerleave",()=>{state.hovering=false;}],
+ ["focusin",event=>{state.focused=Boolean(event.target.matches(":focus-visible, input, textarea, select, [contenteditable=true]"));}],
+ ["focusout",event=>{if(!item.element.contains(event.relatedTarget)) state.focused=false;}],
];
- listeners.forEach(([event, handler]) => item.element.addEventListener(event, handler));
- const stopDrag = bindHUDDrag(item.element, {
- enabled: () => !mobile && Number.isFinite(state.x),
- readPosition: () => ({ left: state.x, top: state.y }),
- onStart: () => {
- state.dragging = true;
- state.interacting = true;
- state.lockedUntil = Infinity;
- state.route = null;
+ listeners.forEach(([event,handler])=>item.element.addEventListener(event,handler));
+ item.element.addEventListener("click",click,true);
+ const stopDrag=bindHUDDrag(item.element,{
+ enabled:()=>!mobile && Number.isFinite(state.x),
+ readPosition:()=>({left:state.displayX??state.x,top:state.displayY??state.y}),
+ onStart:()=>{
+ for(const card of cards.values()) card.element.classList.toggle("is-callout-front",card===state);
+ state.motion=null;state.settlingDrop=false;state.dragging=true;state.floatX=state.floatY=0;
},
- onMove: ({ left, top }) => {
- state.x = state.targetX = clamp(left, EDGE, innerWidth - state.width - EDGE);
- state.y = state.targetY = clamp(top, EDGE, innerHeight - state.height - EDGE);
- state.userPlaced = true; state.relocate = false;
- item.element.dataset.dragged = "true";
- writePosition(state);
+ onMove:({left,top})=>{
+ state.x=state.targetX=clamp(left,EDGE,innerWidth-state.width-EDGE);
+ state.y=state.targetY=clamp(top,EDGE,innerHeight-state.height-EDGE);
+ state.preference={x:state.x,y:state.y};state.userPlaced=true;
+ item.element.dataset.dragged="true";writePosition(state,{width:innerWidth,height:innerHeight});
},
- onEnd: (moved) => {
- state.dragging = false;
- release();
- if (moved) {
- const now = performance.now();
- state.userHoldUntil = now + MANUAL_READING_HOLD_MS;
- state.manualReferencePoint = state.sourcePoint ? { ...state.sourcePoint } : null;
- if (state.sourcePoint && currentGlobe) rememberCalloutLayout(state, state.sourcePoint, currentGlobe, now);
- release();
- savePosition(state); invalidate();
+ onEnd:moved=>{
+ state.dragging=false;
+ if(moved) {
+ const viewport={width:innerWidth,height:innerHeight};
+ const size={width:state.width,height:state.height};
+ const target=settleCardDrop({x:state.x,y:state.y},size,viewport);
+ state.targetX=target.x;state.targetY=target.y;state.preference={x:target.x,y:target.y};
+ const adjusted=Math.hypot(target.x-state.x,target.y-state.y)>0.5;
+ // A central drop exits directly to its nearest legal edge. Hovering
+ // the released card must not pause this correction in the center.
+ state.motion=adjusted && !reducedMotion.matches
+ ? createDockMotion(state,target,size,[],viewport) : null;
+ state.settlingDrop=Boolean(state.motion);
+ if(!state.motion) {state.x=target.x;state.y=target.y;}
+ savePosition(state);state.ignoreClickUntil=performance.now()+200;
+ urgent=true;invalidate();
}
},
});
- state.cleanup = () => {
- stopDrag();
- listeners.forEach(([event, handler]) => item.element.removeEventListener(event, handler));
- };
+ state.cleanup=()=>{stopDrag();item.element.classList.remove("is-callout-front");item.element.removeEventListener("click",click,true);listeners.forEach(([event,handler])=>item.element.removeEventListener(event,handler));};
return state;
}
function set(items) {
- const keys = new Set(items.map(item => item.key));
- for (const [key, state] of cards) if (!keys.has(key)) {
- state.cleanup(); state.connector.hide(); state.connector.connectorEl?.remove();
- resizeObserver.unobserve(state.element); cards.delete(key); invalidate();
+ const keys=new Set(items.map(item=>item.key));
+ for(const [key,state] of cards) if(!keys.has(key)) {
+ state.cleanup();state.connector.hide();state.connector.connectorEl?.remove();
+ resizeObserver.unobserve(state.element);byElement.delete(state.element);cards.delete(key);invalidate();
}
- for (const item of items) {
- const existing = cards.get(item.key);
- if (existing) {
- existing.anchor = item.anchor;
- existing.anchorCandidates = item.anchorCandidates;
- const nextCodes = Array.isArray(item.anchorCodes) ? item.anchorCodes : [];
- const nextCodeKey = nextCodes.join(",");
- if (existing.anchorCodeKey !== nextCodeKey) {
- existing.anchorCodes = nextCodes;
- existing.anchorCodeKey = nextCodeKey;
- existing.highlightAnchorState = {
- ...existing.highlightAnchorState,
- candidateKey: null,
- };
- }
- continue;
+ for(const item of items) {
+ const existing=cards.get(item.key);
+ if(existing) {
+ existing.anchor=item.anchor;existing.anchorCodes=item.anchorCodes;existing.anchorCandidates=item.anchorCandidates;
+ if(existing.header!==item.element.querySelector("header")) {measure(existing);invalidate();}
+ } else {
+ const state=attach(item);cards.set(item.key,state);byElement.set(item.element,state);resizeObserver.observe(item.element);
+ item.element.style.visibility="hidden";item.element.dataset.calloutPhase="pending";invalidate();
}
- const state = attach(item);
- state.anchorCodeKey = Array.isArray(state.anchorCodes) ? state.anchorCodes.join(",") : "";
- cards.set(item.key, state); resizeObserver.observe(item.element);
- item.element.style.visibility = "hidden";
- item.element.dataset.calloutPhase = "pending"; invalidate();
}
}
function measureObstacles(now) {
- if (now - lastObstacleAt < 500) return;
- lastObstacleAt = now;
- const selector = ".hud-panel, #desktop-news-ticker, #info-panel, #legend, #toolbar-hub, .earth-toolbar-cluster.is-expanded .earth-toolbar-orb, .earth-stack-toolbar, .hud-panel-brand";
- const next = [...document.querySelectorAll(selector)].filter(el => !el.matches(".compute-card") &&
- (!root.contains(el) || el.matches(".compute-picker, .compute-evidence"))).filter(el => {
- const style = getComputedStyle(el);
- return !el.hidden && !el.classList.contains("hud-panel-hidden") && style.display !== "none" &&
- style.visibility !== "hidden" && style.opacity !== "0" && el.getClientRects().length;
- }).map(el => {
- const { x, y, width, height } = el.getBoundingClientRect();
- return { x, y, width, height, transient: el.matches(".compute-picker, .compute-evidence") };
- });
- if (JSON.stringify(next) !== JSON.stringify(obstacles)) { obstacles = next; invalidate(); }
+ if(now-lastObstacleAt<500) return;lastObstacleAt=now;
+ const owned=new Set([...cards.values()].map(state=>state.element));
+ const next=[...document.querySelectorAll(".hud-panel, #desktop-news-ticker, #info-panel, #legend, #toolbar-hub, .hud-panel-brand")]
+ .filter(el=>!owned.has(el) && !el.matches(".compute-picker,.compute-evidence") && !el.hidden &&
+ !el.classList.contains("hud-panel-hidden") && getComputedStyle(el).visibility!=="hidden" &&
+ getComputedStyle(el).opacity!=="0" && el.getClientRects().length)
+ .map(el=>{const r=el.getBoundingClientRect();return {x:r.x,y:r.y,width:r.width,height:r.height};});
+ if(layoutObstaclesSignature(next)!==layoutObstaclesSignature(obstacles)) {obstacles=next;invalidate();}
}
- function update(deltaMs, now) {
- if (!cards.size || root.hidden) return;
- mobile = document.documentElement.classList.contains("layout-mode-mobile");
- const viewportKey = `${innerWidth}:${innerHeight}:${mobile}`;
- if (viewportKey !== lastViewport) { lastViewport = viewportKey; invalidate(); }
- if (mobile) {
- for (const state of cards.values()) { state.connector.hide(); state.element.style.visibility = ""; }
- return;
+ function preparePlan(viewport) {
+ const items=[...cards.values()].map(state=>({key:state.key,point:state.point,
+ size:{width:state.width,height:state.height},
+ reading:state.hovering||state.focused,userPlaced:state.userPlaced,
+ previousPosition:Number.isFinite(state.targetX)?{x:state.targetX,y:state.targetY}:state.preference}));
+ const priorityKey=preferredKey || items.find(item=>item.reading)?.key;
+ const plan=planDockLayout(items,obstacles,viewport,priorityKey);
+ const planned=[];
+ for(const state of cards.values()) {
+ const target=plan.targets.get(state.key);
+ const moved=Number.isFinite(state.x) && Math.hypot(target.x-state.x,target.y-state.y)>0.5;
+ const motion=moved && !reducedMotion.matches
+ ? createDockMotion(state,target,{width:state.width,height:state.height},plan.obstacles,viewport) : null;
+ planned.push({state,target,motion});
}
- const context = getSpatialContext?.();
- if (!context?.earth || !context?.camera) return;
- const motionMode = getCalloutMotionMode(context);
- const responsiveMotion = isResponsiveCalloutMotion(motionMode);
- const settlingMotion = previousMotionMode !== null &&
- isResponsiveCalloutMotion(previousMotionMode) && !responsiveMotion;
- previousMotionMode = motionMode;
- context.camera.updateMatrixWorld();
- const center = new THREE.Vector3().setFromMatrixPosition(context.earth.matrixWorld);
- const cameraPosition = new THREE.Vector3().setFromMatrixPosition(context.camera.matrixWorld);
- const cameraDistance = cameraPosition.distanceTo(center);
- const rim = center.clone().add(new THREE.Vector3().setFromMatrixColumn(context.camera.matrixWorld, 0).multiplyScalar(CONFIG.earthRadius)).project(context.camera);
- center.project(context.camera);
- const globe = { x: (center.x + 1) * innerWidth / 2, y: (1 - center.y) * innerHeight / 2,
- radius: Math.abs(rim.x - center.x) * innerWidth / 2 };
- const sourceGlobe = {
- ...globe,
- radius: projectedSphereRadius(globe.radius, cameraDistance, CONFIG.earthRadius),
- };
- currentGlobe = sourceGlobe;
- const items = [];
- const sourceObstacles = [
- ...obstacles,
- ...[...cards.values()].filter(card => Number.isFinite(card.x) &&
- Number.isFinite(card.y) && card.width > 0 && card.height > 0).map(card => ({
- x: card.x,
- y: card.y,
- width: card.width,
- height: card.height,
- })),
- ];
- let motionLayoutRequested = false;
- for (const state of cards.values()) {
- const point = project(state.anchor, context.earth, context.camera, innerWidth, innerHeight);
- if (!point) { state.connector.hide(); continue; }
- state.point = point;
- const needsAlternateSource = state.highlightAnchorState?.candidateKey != null ||
- !point.front || !Number.isFinite(point.visibility) || point.visibility < 0.34;
- const candidateAnchors = needsAlternateSource
- ? state.anchorCandidates || getAnchorCandidates?.(state.anchorCodes) || []
- : [];
- const candidatePoints = candidateAnchors.map(anchor =>
- project(anchor, context.earth, context.camera, innerWidth, innerHeight)).filter(Boolean);
- const anchorResult = smoothHighlightAnchor({
- ...state.highlightAnchorState,
- cardPoint: Number.isFinite(state.x) ? {
- x: state.x + state.width / 2,
- y: state.y + state.height / 2,
- } : null,
- }, {
- preferred: point,
- candidates: candidatePoints,
- globe: sourceGlobe,
- obstacles: sourceObstacles,
- viewport: { width: innerWidth, height: innerHeight },
- deltaMs,
- });
- state.highlightAnchorState = anchorResult.state;
- state.sourcePoint = anchorResult.source || point;
- const expanded = state.element.classList.contains("is-expanded");
- if (expanded && !state.readingExpanded && Number.isFinite(state.x)) {
- state.expandedHoldUntil = now + MANUAL_READING_HOLD_MS;
- state.lockedUntil = Math.max(state.lockedUntil, state.expandedHoldUntil);
- }
- state.readingExpanded = expanded;
- state.interacting = state.hovering || state.focused || state.dragging;
- // A completed card interaction must not keep the layout frozen while the
- // user deliberately turns the globe.
- if (responsiveMotion && !state.interacting && Number.isFinite(state.lockedUntil)) {
- state.lockedUntil = 0;
- }
- const reading = state.revealPhase === "drawing" || (responsiveMotion ? state.interacting :
- state.lockedUntil > now || state.dragging);
- if (reading) state.route = null;
- if (state.wasReading && !reading) invalidate();
- state.wasReading = reading;
- state.element.classList.toggle("is-rear", !state.sourcePoint.front);
- // Sizes are cached by ResizeObserver, not remeasured in the render loop.
- if (!state.width || !state.height) continue;
- if (rotationNeedsReflow(state, state.sourcePoint, sourceGlobe, now, motionMode)) {
- motionLayoutRequested = true;
- }
- const layoutPoint = state.layoutReferencePoint || state.sourcePoint;
- items.push({ key: state.key, point: layoutPoint, front: layoutPoint.front, size: { width: state.width, height: state.height },
- previousPosition: Number.isFinite(state.x) ? { x: state.targetX, y: state.targetY } : null,
- previousSide: state.side, previousAngle: state.angle, userPlaced: state.userPlaced,
- locked: reading, relocate: state.relocate });
+ // Commit the complete batch without changing any card's presentation state.
+ for(const {state,target,motion} of planned) {
+ state.targetX=target.x;state.targetY=target.y;
+ if(state.motion && state.motion.points.at(-1).x===target.x && state.motion.points.at(-1).y===target.y) continue;
+ state.motion=motion;state.floatX=state.floatY=0;
+ if(!motion) {state.x=target.x;state.y=target.y;}
+ if(state.revealPhase==="visible") state.element.style.visibility="";
}
+ preferredKey=null;dirty=false;urgent=false;
+ }
+ function update(deltaMs,now) {
+ if(!cards.size || root.hidden) return;
+ mobile=document.documentElement.classList.contains("layout-mode-mobile");
+ if(mobile) {for(const state of cards.values()) {state.connector.hide();state.element.style.visibility="";}return;}
+ const viewport={width:innerWidth,height:innerHeight};
+ const viewportKey=`${innerWidth}:${innerHeight}`;
+ if(viewportKey!==lastViewport) {lastViewport=viewportKey;for(const state of cards.values()) measure(state);urgent=true;invalidate();}
measureObstacles(now);
- const viewport = { width: innerWidth, height: innerHeight, globe };
- const freshItems = items.map(item => ({ ...item, point: cards.get(item.key).sourcePoint }));
- const previous = new Map(items.filter(item => item.previousPosition).map(item =>
- [item.key, { ...item.previousPosition, ...item.size }]));
- let qualityRequested = false;
- if (!responsiveMotion && previous.size === items.length && now - lastQualityAt > 250) {
- lastQualityAt = now;
- qualityRequested = reviewTangledLayout(reflowGate, scoreCalloutLayout(freshItems, previous, viewport), now);
+ const context=getSpatialContext?.();if(!context?.earth || !context?.camera) return;
+ context.camera.updateMatrixWorld();
+ const center=new THREE.Vector3().setFromMatrixPosition(context.earth.matrixWorld);
+ const distance=context.camera.position.distanceTo(center);
+ const rim=center.clone().add(new THREE.Vector3().setFromMatrixColumn(context.camera.matrixWorld,0).multiplyScalar(CONFIG.earthRadius)).project(context.camera);
+ center.project(context.camera);
+ const globe={x:(center.x+1)*innerWidth/2,y:(1-center.y)*innerHeight/2,
+ radius:projectedSphereRadius(Math.abs(rim.x-center.x)*innerWidth/2,distance,CONFIG.earthRadius)};
+ const busy=context.isDragging || context.activeTouchPoints>0 || context.hasActiveGlobeInertia ||
+ [...cards.values()].some(state=>state.dragging) || Boolean(document.querySelector(".hud-panel.is-dragging,.hud-panel.is-resizing"));
+ const sources=[...obstacles,...[...cards.values()].filter(state=>Number.isFinite(state.x))
+ .map(state=>({x:state.x,y:state.y,width:state.width,height:state.height}))];
+ for(const state of cards.values()) {
+ state.point=project(state.anchor,context.earth,context.camera,innerWidth,innerHeight);
+ if(!state.point) {state.connector.hide();continue;}
+ const alternate=state.highlightAnchorState?.candidateKey!=null || !state.point.front || state.point.visibility<0.34;
+ const candidates=alternate?(state.anchorCandidates||getAnchorCandidates?.(state.anchorCodes)||[]):[];
+ const result=smoothHighlightAnchor({...state.highlightAnchorState,cardPoint:Number.isFinite(state.x)?
+ {x:state.x+state.width/2,y:state.y+state.height/2}:null},{preferred:state.point,
+ candidates:candidates.map(anchor=>project(anchor,context.earth,context.camera,innerWidth,innerHeight)).filter(Boolean),
+ globe,obstacles:sources,viewport,deltaMs});
+ state.highlightAnchorState=result.state;state.sourcePoint=result.source||state.point;
+ state.element.classList.toggle("is-rear",!state.sourcePoint.front);
}
- pendingGroupReflow ||= qualityRequested || (motionLayoutRequested && (responsiveMotion ||
- now - reflowGate.lastAttemptAt >= READING_INTERVAL_MS));
- const groupReflow = pendingGroupReflow;
- if (groupReflow) {
- for (const item of items) {
- const state = cards.get(item.key);
- if (item.locked || !canRelocateUserCard(state, state.sourcePoint, sourceGlobe, now)) continue;
- item.point = state.sourcePoint;
- item.relocate = true;
- item.userPlaced = false;
+ const settled=settle(now,busy,String(revision));
+ if(dirty && !busy && (settled||urgent)) preparePlan(viewport);
+ for(const state of cards.values()) {
+ if(!Number.isFinite(state.x)) continue;
+ const reading=state.hovering||state.focused;
+ if(state.motion && !state.dragging) {
+ // Interaction pauses progress; the committed destination survives.
+ const next=advanceDockMotion(state.motion,deltaMs,busy || (reading && !state.settlingDrop));
+ state.x=next.x;state.y=next.y;
+ if(next.done) {state.motion=null;state.settlingDrop=false;}
}
- requestResponsiveLayout();
- }
- const eagerLayout = responsiveMotion || settlingMotion;
- const layoutInterval = settlingMotion ? 0 : eagerLayout ? RESPONSIVE_LAYOUT_INTERVAL_MS : 400;
- if (!layoutJob && dirty && now - lastLayoutAt >= layoutInterval) {
- layoutReview = groupReflow && !responsiveMotion && previous.size === items.length
- ? { items: freshItems, before: scoreCalloutLayout(freshItems, previous, viewport) } : null;
- if (groupReflow && !responsiveMotion) reflowGate.lastAttemptAt = now;
- pendingGroupReflow = false;
- layoutJob = solve(items, obstacles, viewport);
- dirty = false; lastLayoutAt = now;
- }
- let result = layoutJob?.next();
- // A yielded job can otherwise be invalidated by the next fast-motion
- // sample forever. The bounded card set is cheap enough to finish here.
- if (eagerLayout) while (result && !result.done) result = layoutJob.next();
- if (result?.done) {
- layoutJob = null;
- const next = new Map([...result.value].map(([key, target]) =>
- [key, { ...target, width: cards.get(key)?.width, height: cards.get(key)?.height }]));
- const accept = !layoutReview || improvesCalloutLayout(layoutReview.before,
- scoreCalloutLayout(layoutReview.items, next, viewport));
- if (accept) for (const [key, target] of result.value) {
- const state = cards.get(key);
- const activelyReading = state?.revealPhase === "drawing" || state?.hovering || state?.focused || state?.dragging;
- if (!state || (Number.isFinite(state.x) && (activelyReading || (!responsiveMotion && state.lockedUntil > now)))) continue;
- const moved = Number.isFinite(state.targetX) && Math.hypot(target.x - state.targetX, target.y - state.targetY) > 2;
- if (moved && state.userPlaced && canRelocateUserCard(state, state.sourcePoint, sourceGlobe, now)) {
- state.userPlaced = false;
- delete state.element.dataset.dragged;
- saved[key] = { width: state.element.style.width, height: state.element.style.height,
- positionVersion: CALLOUT_POSITION_VERSION };
- persist();
+ updateCalloutFloat(state,now,deltaMs,reducedMotion.matches||busy||reading||Boolean(state.motion));
+ writePosition(state,viewport);
+ {
+ const rendered=renderSpatialCalloutConnector(state,{animate:state.revealPhase==="pending"&&!reducedMotion.matches});
+ const wasVisible=state.revealPhase==="visible";
+ state.revealPhase=advanceCalloutReveal(state,{now,rendered,animating:state.connector.isAnimating(),reducedMotion:reducedMotion.matches});
+ if(state.revealPhase==="visible" && !wasVisible) {
+ state.element.style.visibility="";
+ if(!reducedMotion.matches) state.element.animate([{opacity:0},{opacity:1}],{duration:180,easing:"ease"});
}
- state.targetX = target.x; state.targetY = target.y; state.side = target.side; state.angle = target.angle;
- state.relocate = false;
- if (layoutReview || responsiveMotion) rememberCalloutLayout(state, state.sourcePoint, sourceGlobe, now);
- }
- layoutReview = null;
- }
- const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
- const placed = [...cards.values()].filter(state => state.point && Number.isFinite(state.targetX));
- for (const state of placed) {
- if (!Number.isFinite(state.x)) { state.x = state.targetX; state.y = state.targetY; }
- if (!state.dragging) {
- state.x = clamp(state.x, EDGE, innerWidth - state.width - EDGE);
- state.y = clamp(state.y, EDGE, innerHeight - state.height - EDGE);
- }
- }
- advanceCallouts(placed, obstacles, { width: innerWidth, height: innerHeight, globe, revision }, now, deltaMs);
- for (const state of placed) {
- writePosition(state);
- const rendered = renderSpatialCalloutConnector(state, {
- animate: state.revealPhase === "pending" && !reducedMotion,
- });
- const wasVisible = state.revealPhase === "visible";
- const phase = advanceCalloutReveal(state, {
- now, rendered, animating: state.connector.isAnimating(), reducedMotion,
- });
- state.element.dataset.calloutPhase = phase;
- if (phase === "visible" && !wasVisible) {
- state.element.style.visibility = "";
- if (!reducedMotion) state.element.animate([{ opacity: 0 }, { opacity: 1 }], {
- duration: 180, easing: "ease",
- });
}
+ if(state.element.dataset.calloutPhase!==state.revealPhase) state.element.dataset.calloutPhase=state.revealPhase;
}
}
- const reset = event => {
- const button = event.target.closest('[data-action="card-auto"]');
- if (!button) return;
- const state = cards.get(button.dataset.card);
- if (!state) return;
- delete saved[state.key]; persist(); state.userPlaced = false; state.relocate = true;
- delete state.element.dataset.dragged;
- state.lockedUntil = 0; state.element.style.width = ""; state.element.style.height = ""; invalidate();
+ const click=event=>{
+ const element=event.target.closest(".compute-card,.news-region-card");
+ const state=byElement.get(element);
+ if(!state || state.ignoreClickUntil>performance.now()) return;
+ if(event.target.closest('[data-action="card-collapse"]')) {preferredKey=state.key;invalidate();}
};
- root.addEventListener("click", reset);
- return { set, update, invalidate, destroy() { set([]); resizeObserver.disconnect(); root.removeEventListener("click", reset); } };
+ return {set,update,invalidate,destroy(){set([]);resizeObserver.disconnect();}};
}
diff --git a/frontend/public/earth/js/spatial-callouts.js b/frontend/public/earth/js/spatial-callouts.js
index e19d1e98..6f1dfef1 100644
--- a/frontend/public/earth/js/spatial-callouts.js
+++ b/frontend/public/earth/js/spatial-callouts.js
@@ -1,355 +1,55 @@
import * as THREE from "three";
+import {createCalloutController} from "./spatial-callout-controller.js";
+import {CONFIG} from "./constants.js";
+import {getCountryAnchorCandidates} from "./country-boundaries.js";
+import {latLonToVector3} from "./utils.js";
-import { createCalloutController } from "./spatial-callout-controller.js";
-import { packCalloutTargets, packDirectionalEdgeCallouts } from "./callout-packing.js";
-import { calloutEdgeDistance, calloutDirectionDelta, calloutSourceDistance, calloutProximityCost, refineCalloutAssignments } from "./callout-proximity.js";
-import { CONFIG } from "./constants.js";
-import { getCountryAnchorCandidates } from "./country-boundaries.js";
-import { latLonToVector3 } from "./utils.js";
-
-const EDGE = 12;
-const GAP = 14;
-
-const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
-const overlaps = (a, b, gap = GAP) => a.x < b.x + b.width + gap && a.x + a.width + gap > b.x &&
- a.y < b.y + b.height + gap && a.y + a.height + gap > b.y;
-const layoutGap = (viewport) => viewport.width <= 1080 || viewport.height <= 760 ? 8 : GAP;
-const overlapArea = (a, b) => Math.max(0,
- Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) *
- Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y));
-const globeDepth = (rect, globe) => {
- if (!globe?.radius) return 0;
- const x = clamp(globe.x, rect.x, rect.x + rect.width);
- const y = clamp(globe.y, rect.y, rect.y + rect.height);
- return Math.max(0, globe.radius + 8 - Math.hypot(x - globe.x, y - globe.y));
-};
+const geographicLocalPositions = new WeakMap();
+const projectedWorld = new THREE.Vector3();
+const projectedCenter = new THREE.Vector3();
+const projectedNormal = new THREE.Vector3();
+const projectedView = new THREE.Vector3();
export function projectGeographicAnchor(anchor, earth, camera, width, height) {
if (!anchor || !Number.isFinite(anchor.latitude) || !Number.isFinite(anchor.longitude) || !earth || !camera) return null;
- const world = latLonToVector3(anchor.latitude, anchor.longitude, CONFIG.earthRadius + 0.25)
- .applyMatrix4(earth.matrixWorld);
- const center = new THREE.Vector3().setFromMatrixPosition(earth.matrixWorld);
- const normal = world.clone().sub(center).normalize();
- const visibility = normal.dot(camera.position.clone().sub(world).normalize());
- const projected = world.clone().project(camera);
- if (!Number.isFinite(projected.x) || !Number.isFinite(projected.y)) return null;
+ let cached = geographicLocalPositions.get(anchor);
+ if (!cached || cached.latitude !== anchor.latitude || cached.longitude !== anchor.longitude) {
+ cached = {latitude:anchor.latitude, longitude:anchor.longitude,
+ local:latLonToVector3(anchor.latitude, anchor.longitude, CONFIG.earthRadius + 0.25)};
+ geographicLocalPositions.set(anchor, cached);
+ }
+ projectedWorld.copy(cached.local).applyMatrix4(earth.matrixWorld);
+ projectedCenter.setFromMatrixPosition(earth.matrixWorld);
+ projectedNormal.copy(projectedWorld).sub(projectedCenter).normalize();
+ projectedView.copy(camera.position).sub(projectedWorld).normalize();
+ const visibility = projectedNormal.dot(projectedView);
+ projectedWorld.project(camera);
+ if (!Number.isFinite(projectedWorld.x) || !Number.isFinite(projectedWorld.y)) return null;
return {
- x: (projected.x + 1) * width / 2,
- y: (1 - projected.y) * height / 2,
- front: visibility > 0.04 && projected.z < 1,
+ x: (projectedWorld.x + 1) * width / 2,
+ y: (1 - projectedWorld.y) * height / 2,
+ front: visibility > 0.04 && projectedWorld.z < 1,
visibility,
key: anchor.key,
};
}
-export function chooseCalloutTargets(items, obstacles, viewport) {
- const job = solveCalloutLayout(items, obstacles, viewport);
- let result = job.next();
- while (!result.done) result = job.next();
- return result.value;
-}
-
-function asTargets(placed, globe) {
- return new Map(placed.map(target => [target.key, {
- x: target.x, y: target.y,
- side: target.x + target.width / 2 < globe.x ? "left" : "right",
- angle: Math.atan2(target.y + target.height / 2 - globe.y,
- target.x + target.width / 2 - globe.x),
- }]));
-}
-
-function* solveCalloutLayout(items, obstacles, viewport) {
- const gap = layoutGap(viewport);
- viewport = { ...viewport, globe: {
- x: viewport.width / 2, y: viewport.height / 2, radius: 0, ...viewport.globe,
- } };
- const edgeLayout = packDirectionalEdgeCallouts(items, obstacles, viewport);
- if (edgeLayout) return asTargets([...edgeLayout].map(([key, rect]) => ({ key, ...rect })), viewport.globe);
- const contentArea = items.reduce((area, item) => area + item.size.width * item.size.height, 0);
- if (items.length > 2 && contentArea > viewport.width * viewport.height * 0.35) {
- const packed = packCalloutTargets(items, obstacles, viewport);
- if (packed) return asTargets([...packed].map(([key, rect]) => ({ key, ...rect })), viewport.globe);
- }
- const byKey = new Map(items.map((item) => [item.key, item]));
- const orders = [
- [...items.filter((item) => item.front), ...items.filter((item) => !item.front)],
- items, [...items].reverse(),
- ];
- let best = null;
- let bestCollision = Infinity;
- let bestRelation = Infinity;
- const trials = [
- ...orders.map(order => ({ order, avoidGlobe: true })),
- ...orders.map(order => ({ order, avoidGlobe: false })),
- ];
- for (const { order, avoidGlobe } of trials) {
- const constraints = avoidGlobe ? viewport :
- { ...viewport, globe: { ...viewport.globe, radius: 0 } };
- const placed = [];
- for (const item of order) {
- const { point, size, previousSide, previousAngle } = item;
- const globe = { x: viewport.width / 2, y: viewport.height / 2, radius: 0,
- ...viewport.globe };
- const rawAngle = Math.atan2(point.y - globe.y, point.x - globe.x);
- const closeToPole = Math.abs(point.x - globe.x) < 100;
- const preferredAngle = Number.isFinite(previousAngle) &&
- (Math.hypot(point.x - globe.x, point.y - globe.y) < 60 ||
- Math.abs(Math.atan2(Math.sin(rawAngle - previousAngle), Math.cos(rawAngle - previousAngle))) < 0.12)
- ? previousAngle : rawAngle;
- const angles = [0, -0.16, 0.16, -0.34, 0.34, -0.55, 0.55, -0.78, 0.78,
- -1.02, 1.02, -1.3, 1.3, -1.6, 1.6, -1.9, 1.9, -2.2, 2.2,
- -2.6, 2.6, -3, 3];
- const candidates = angles.flatMap((shift) => [0, 55, 110].map((extension) => {
- const angle = preferredAngle + shift;
- const radius = globe.radius + Math.max(size.width, size.height) / 2 + 24 + extension;
- const rawX = globe.x + Math.cos(angle) * radius - size.width / 2;
- const rawY = globe.y + Math.sin(angle) * radius - size.height / 2;
- return {
- x: clamp(rawX, EDGE, viewport.width - size.width - EDGE),
- y: clamp(rawY, EDGE, viewport.height - size.height - EDGE),
- width: size.width, height: size.height, angle, shift,
- clipped: Math.abs(rawX - clamp(rawX, EDGE, viewport.width - size.width - EDGE)) +
- Math.abs(rawY - clamp(rawY, EDGE, viewport.height - size.height - EDGE)),
- };
- }));
- // At close zoom, nearby foreground space is preferable to a connector
- // stretched across the whole globe to reach a remote empty corner.
- for (const shift of [0, -0.34, 0.34, -0.7, 0.7]) {
- const angle = preferredAngle + shift;
- const distance = Math.abs(Math.cos(angle)) * size.width / 2 +
- Math.abs(Math.sin(angle)) * size.height / 2 + 40;
- const rawX = point.x + Math.cos(angle) * distance - size.width / 2;
- const rawY = point.y + Math.sin(angle) * distance - size.height / 2;
- const x = clamp(rawX, EDGE, viewport.width - size.width - EDGE);
- const y = clamp(rawY, EDGE, viewport.height - size.height - EDGE);
- candidates.push({ x, y, width: size.width, height: size.height, angle, shift,
- clipped: Math.abs(rawX - x) + Math.abs(rawY - y) });
- }
- for (const shift of [0, -1, 1]) {
- const edgeX = clamp(point.x - size.width / 2 + shift * (size.width + gap), EDGE, viewport.width - size.width - EDGE);
- const edgeY = clamp(point.y - size.height / 2 + shift * (size.height + gap), EDGE, viewport.height - size.height - EDGE);
- for (const rect of [
- { x: EDGE, y: edgeY }, { x: viewport.width - size.width - EDGE, y: edgeY },
- { x: edgeX, y: EDGE }, { x: edgeX, y: viewport.height - size.height - EDGE },
- ]) candidates.push({ ...rect, ...size, clipped: 0 });
- }
- if (closeToPole && previousSide) {
- const x = clamp(globe.x - size.width / 2 + (previousSide === "left" ? -1 : 1),
- EDGE, viewport.width - size.width - EDGE);
- for (const y of [EDGE, viewport.height - size.height - EDGE]) {
- candidates.push({ x, y, ...size, clipped: 0 });
- }
- }
- const score = (box) => {
- const overlapArea = [...obstacles, ...placed].reduce((sum, other) => {
- if (!overlaps(box, other, gap)) return sum;
- return sum + Math.max(0, Math.min(box.x + box.width + gap, other.x + other.width + gap) -
- Math.max(box.x, other.x - gap)) * Math.max(0, Math.min(box.y + box.height + gap,
- other.y + other.height + gap) - Math.max(box.y, other.y - gap));
- }, 0);
- const intrusion = globeDepth(box, globe);
- const side = box.x + box.width / 2 < globe.x ? "left" : "right";
- return overlapArea * 1000 + intrusion * (avoidGlobe ? 30 : 4) + box.clipped * 6 +
- calloutProximityCost(item, box, globe, viewport) +
- (closeToPole && previousSide && side !== previousSide ? 120 : 0);
- };
- let target = candidates[0];
- let targetScore = Infinity;
- for (const candidate of candidates) {
- const candidateScore = score(candidate);
- if (candidateScore >= targetScore) continue;
- target = candidate;
- targetScore = candidateScore;
- }
- target.key = item.key;
- placed.push(target);
- separateCalloutPositions(placed, obstacles, constraints, 0);
- yield;
- }
- const collision = placed.reduce((sum, rect, index) => sum +
- obstacles.reduce((area, obstacle) => area + overlapArea(rect, obstacle), 0) +
- placed.slice(index + 1).reduce((area, next) => area + overlapArea(rect, next), 0), 0);
- const total = placed.reduce((sum, rect) => sum + globeDepth(rect, viewport.globe), 0);
- const relation = placed.reduce((sum, target) =>
- sum + calloutProximityCost(byKey.get(target.key), target, viewport.globe, viewport), 0);
- const globeWeight = viewport.globe.radius < Math.min(viewport.width, viewport.height) * 0.32 ? 1000 : 4;
- const quality = relation + total * globeWeight;
- if (collision > bestCollision || (collision === bestCollision && quality >= bestRelation)) continue;
- bestCollision = collision;
- bestRelation = quality;
- best = placed;
- const local = placed.every(target => {
- const item = byKey.get(target.key);
- return calloutDirectionDelta(item.point, target, viewport.globe) <= Math.PI / 3 &&
- calloutSourceDistance(item.point, target) <= Math.max(320, viewport.globe.radius * 0.8);
- });
- if (collision < 0.1 && (total < 0.1 || globeWeight === 4) && local) break;
- }
- if (bestCollision > 0.1) {
- const packed = packCalloutTargets(items, obstacles, viewport);
- if (packed) best = [...packed].map(([key, rect]) => ({ key, ...rect }));
- }
- const reassigned = refineCalloutAssignments(items,
- new Map((best || []).map(rect => [rect.key, rect])), obstacles, viewport);
- return asTargets([...reassigned].map(([key, rect]) => ({ key, ...rect })), viewport.globe);
-}
-
-export function separateCalloutPositions(states, obstacles, viewport, now, maxPasses = 16) {
- const gap = layoutGap(viewport);
- viewport = { ...viewport, globe: {
- x: viewport.width / 2, y: viewport.height / 2, radius: 0, ...viewport.globe,
- } };
- const movable = (state) => !(state.lockedUntil > now);
- let changed = false;
- const shift = (state, dx, dy) => {
- if (!movable(state)) return;
- const x = clamp(state.x + dx, EDGE, viewport.width - state.width - EDGE);
- const y = clamp(state.y + dy, EDGE, viewport.height - state.height - EDGE);
- changed ||= Math.abs(x - state.x) + Math.abs(y - state.y) > 0.25;
- state.x = x;
- state.y = y;
- };
- // Coupled constraints need relaxation: a correction may temporarily touch a
- // neighbour which the next pass moves. Rejecting every such move deadlocks.
- for (let pass = 0; pass < maxPasses; pass++) {
- changed = false;
- for (const state of states) {
- if (!movable(state)) continue;
- for (const obstacle of obstacles) {
- if (!overlaps(state, obstacle, gap)) continue;
- const options = [
- [obstacle.x - gap - state.width - state.x, 0],
- [obstacle.x + obstacle.width + gap - state.x, 0],
- [0, obstacle.y - gap - state.height - state.y],
- [0, obstacle.y + obstacle.height + gap - state.y],
- ].filter(([dx, dy]) => state.x + dx >= EDGE && state.y + dy >= EDGE &&
- state.x + dx + state.width <= viewport.width - EDGE &&
- state.y + dy + state.height <= viewport.height - EDGE);
- options.sort((a, b) => {
- const cost = ([dx, dy]) => Math.abs(dx) + Math.abs(dy) +
- globeDepth({ ...state, x: state.x + dx, y: state.y + dy }, viewport.globe) * 20;
- return cost(a) - cost(b);
- });
- if (options.length) shift(state, ...options[0]);
- }
- }
- for (let i = 0; i < states.length; i++) {
- for (let j = i + 1; j < states.length; j++) {
- const a = states[i];
- const b = states[j];
- if (!overlaps(a, b, gap)) continue;
- const x = Math.min(a.x + a.width + gap - b.x, b.x + b.width + gap - a.x);
- const y = Math.min(a.y + a.height + gap - b.y, b.y + b.height + gap - a.y);
- if (!movable(a) && !movable(b)) continue;
- // A short vertical push can be undone by the viewport or a tool on
- // every pass. Compare both axes, including moving just one neighbour,
- // so a crowded column can use the available space beside it.
- const options = [];
- const fractions = movable(a) && movable(b) ? [0.5, 1, 0] : [movable(a) ? 1 : 0];
- for (const [dx, dy] of [
- [(a.x + a.width / 2 <= b.x + b.width / 2 ? -1 : 1) * (x + 0.1), 0],
- [0, (a.y + a.height / 2 <= b.y + b.height / 2 ? -1 : 1) * (y + 0.1)],
- ]) {
- for (const fraction of fractions) {
- const next = (state, weight) => ({ ...state,
- x: clamp(state.x + dx * weight, EDGE, viewport.width - state.width - EDGE),
- y: clamp(state.y + dy * weight, EDGE, viewport.height - state.height - EDGE),
- });
- const nextA = next(a, fraction);
- const nextB = next(b, fraction - 1);
- const obstruction = (rect) => obstacles.reduce((sum, obstacle) =>
- sum + overlapArea(rect, obstacle), 0) + globeDepth(rect, viewport.globe) * rect.width;
- const travel = Math.abs(nextA.x - a.x) + Math.abs(nextA.y - a.y) +
- Math.abs(nextB.x - b.x) + Math.abs(nextB.y - b.y);
- options.push({ a: nextA, b: nextB,
- cost: overlapArea(nextA, nextB) * 100 +
- (obstruction(nextA) + obstruction(nextB)) * 100 + travel });
- }
- }
- const best = options.reduce((best, option) => option.cost < best.cost ? option : best);
- shift(a, best.a.x - a.x, best.a.y - a.y);
- shift(b, best.b.x - b.x, best.b.y - b.y);
- }
- }
- if (viewport.globe?.radius) {
- const globe = viewport.globe;
- for (const state of states) {
- const depth = globeDepth(state, globe);
- if (depth <= 0.1 || !movable(state)) continue;
- let dx = clamp(globe.x, state.x, state.x + state.width) - globe.x;
- let dy = clamp(globe.y, state.y, state.y + state.height) - globe.y;
- if (Math.hypot(dx, dy) < 0.01) {
- dx = state.x + state.width / 2 - globe.x;
- dy = state.y + state.height / 2 - globe.y || -1;
- }
- const length = Math.hypot(dx, dy);
- shift(state, dx / length * (depth + 0.1), dy / length * (depth + 0.1));
- }
- }
- if (!changed) break;
- }
- // In a saturated column, local relaxation can cycle between two constraints.
- // Repair only residual collisions using edges of the occupied rectangles;
- // ordinary spring motion does not need this bounded free-space search.
- for (const state of states) {
- if (!movable(state)) continue;
- const occupied = [...obstacles, ...states.filter((other) => other !== state)];
- if (!occupied.some((other) => overlapArea(state, other) > 0.5) &&
- globeDepth(state, viewport.globe) < 0.5) continue;
- const xs = [state.x, EDGE, viewport.width - state.width - EDGE];
- const ys = [state.y, EDGE, viewport.height - state.height - EDGE];
- for (const other of occupied) {
- xs.push(other.x - state.width - gap, other.x + other.width + gap);
- ys.push(other.y - state.height - gap, other.y + other.height + gap);
- }
- let best = null;
- let bestDistance = Infinity;
- for (const x of xs) {
- if (x < EDGE || x + state.width > viewport.width - EDGE) continue;
- for (const y of ys) {
- if (y < EDGE || y + state.height > viewport.height - EDGE) continue;
- const distance = Math.hypot(x - state.x, y - state.y);
- if (distance >= bestDistance) continue;
- const rect = { x, y, width: state.width, height: state.height };
- if (globeDepth(rect, viewport.globe) > 0.1 || occupied.some((other) => overlaps(rect, other, gap))) continue;
- best = rect;
- bestDistance = distance;
- }
- }
- if (best) shift(state, best.x - state.x, best.y - state.y);
- }
-}
-
-export function* solveStableCalloutLayout(items, obstacles, viewport) {
- const fixed = [], moving = [];
- const gap = layoutGap(viewport);
- const globe = viewport.globe || { x: viewport.width / 2, y: viewport.height / 2, radius: 0 };
- for (const item of [...items].sort((a,b) => Number(Boolean(b.locked || b.userPlaced)) - Number(Boolean(a.locked || a.userPlaced)))) {
- const p = item.previousPosition;
- const rect = p ? { key: item.key, ...p, ...item.size } : null;
- const bounded = rect && rect.x >= EDGE && rect.y >= EDGE && rect.x + rect.width <= viewport.width - EDGE && rect.y + rect.height <= viewport.height - EDGE;
- const relevantObstacles = item.userPlaced ? obstacles.filter(other => !other.transient) : obstacles;
- const clear = bounded && ![...relevantObstacles, ...fixed].some(other => overlaps(rect, other, gap));
- const nearby = rect && calloutDirectionDelta(item.point, rect, globe) <= Math.PI / 3 &&
- calloutSourceDistance(item.point, rect) <= Math.max(220, globe.radius * 0.45) &&
- calloutEdgeDistance(rect, viewport) <= 40;
- if (rect && (item.locked || (clear && !item.relocate &&
- (item.userPlaced || !viewport.repairDistantPlacements || nearby)))) fixed.push(rect);
- else moving.push(item);
- }
- const results = asTargets(fixed, viewport.globe || { x: viewport.width / 2, y: viewport.height / 2 });
- if (moving.length) {
- const moved = yield* solveCalloutLayout(moving, [...obstacles, ...fixed], viewport);
- for (const [key, value] of moved) results.set(key, value);
- }
- return results;
-}
-
export function createSpatialCallouts(options) {
- return createCalloutController({
- getAnchorCandidates: getCountryAnchorCandidates,
- ...options,
- project: projectGeographicAnchor,
- solve: solveStableCalloutLayout,
- });
+ return createCalloutController({getAnchorCandidates:getCountryAnchorCandidates,...options,project:projectGeographicAnchor});
+}
+
+export function createCalloutGroups(controller) {
+ const groups = new Map();
+ const sync = () => controller.set([...groups.values()].flat());
+ return {
+ scope(key) {
+ return {
+ set(items) { groups.set(key, items); sync(); },
+ invalidate: () => controller.invalidate(),
+ destroy() { groups.delete(key); sync(); },
+ };
+ },
+ update: (delta, now) => controller.update(delta, now),
+ destroy() { groups.clear(); controller.destroy(); },
+ };
}
diff --git a/frontend/public/earth/js/spatial-callouts.test.js b/frontend/public/earth/js/spatial-callouts.test.js
index 27336f37..8da2c2ef 100644
--- a/frontend/public/earth/js/spatial-callouts.test.js
+++ b/frontend/public/earth/js/spatial-callouts.test.js
@@ -3,7 +3,7 @@ import * as THREE from "three";
import { CalloutConnector, createConnectorPath } from "./callout-connector.js";
import { renderSpatialCalloutConnector } from "./spatial-callout-controller.js";
-import { chooseCalloutTargets, projectGeographicAnchor, separateCalloutPositions } from "./spatial-callouts.js";
+import { projectGeographicAnchor } from "./spatial-callouts.js";
test("geographic anchor preserves its real projection and front/rear depth while rotating", () => {
const earth = new THREE.Object3D();
@@ -106,128 +106,3 @@ for (const animate of [false, true]) {
}
});
}
-
-for (const count of [2, 4, 6]) {
- test(`${count} keyed callouts remain bounded and separate from existing HUD`, () => {
- const viewport = { width: 1366, height: 768, globe: { x: 683, radius: 350 } };
- const obstacles = [{ x: 20, y: 20, width: 240, height: 160 }];
- const items = Array.from({ length: count }, (_, index) => ({
- key: `region-${index}`,
- point: { x: index % 2 ? 820 : 540, y: 240 + Math.floor(index / 2) * 110 },
- size: { width: 210, height: 145 },
- previousSide: index % 2 ? "right" : "left",
- }));
- const positions = chooseCalloutTargets(items, obstacles, viewport);
- expect(positions.size).toBe(count);
- for (const item of items) {
- const position = positions.get(item.key);
- expect(position.x).toBeGreaterThanOrEqual(12);
- expect(position.x + item.size.width).toBeLessThanOrEqual(viewport.width - 12);
- expect(position.y).toBeGreaterThanOrEqual(12);
- expect(position.y + item.size.height).toBeLessThanOrEqual(viewport.height - 12);
- expect(position.x < 260 && position.y < 180).toBe(false);
- }
- const placed = items.map((item) => ({ ...positions.get(item.key), ...item.size }));
- for (let i = 0; i < placed.length; i++) {
- for (let j = i + 1; j < placed.length; j++) {
- const a = placed[i];
- const b = placed[j];
- expect(a.x < b.x + b.width && a.x + a.width > b.x &&
- a.y < b.y + b.height && a.y + a.height > b.y).toBe(false);
- }
- }
- });
-}
-
-test("near-center side hysteresis keeps identity on its previous side", () => {
- const items = [{ key: "JP", point: { x: 690, y: 300 }, size: { width: 200, height: 150 }, previousSide: "left" }];
- const positions = chooseCalloutTargets(items, [], { width: 1366, height: 768 });
- expect(positions.get("JP").side).toBe("left");
-});
-
-test("radial anchors place cards above, below and diagonally around the globe", () => {
- const viewport = { width: 1200, height: 900, globe: { x: 600, y: 450, radius: 200 } };
- const items = [
- { key: "north", point: { x: 600, y: 280 }, size: { width: 180, height: 110 } },
- { key: "south", point: { x: 600, y: 620 }, size: { width: 180, height: 110 } },
- { key: "northeast", point: { x: 750, y: 300 }, size: { width: 180, height: 110 } },
- ];
- const positions = chooseCalloutTargets(items, [], viewport);
- expect(positions.get("north").y + 110).toBeLessThan(viewport.globe.y - 100);
- expect(positions.get("south").y).toBeGreaterThan(viewport.globe.y + 100);
- expect(positions.get("northeast").x).toBeGreaterThan(viewport.globe.x);
- expect(positions.get("northeast").y).toBeLessThan(viewport.globe.y);
- const north = positions.get("north");
- const originalHTMLElement = globalThis.HTMLElement;
- globalThis.HTMLElement = class {};
- try {
- const path = createConnectorPath(items[0].point, {
- x: north.x, y: north.y, width: 180, height: 110,
- }, { routingMode: "adaptive" });
- expect(path.end.y).toBeGreaterThan(north.y + 110);
- } finally {
- globalThis.HTMLElement = originalHTMLElement;
- }
-});
-
-test("six full-size front/rear cards avoid existing desktop tools where space permits", () => {
- const viewport = { width: 1366, height: 768, globe: { x: 683, y: 384, radius: 182 } };
- const obstacles = [
- { x: 523, y: 15, width: 320, height: 200 },
- { x: 14, y: 118, width: 196, height: 274 },
- { x: 1053, y: 14, width: 300, height: 215 },
- { x: 1181, y: 509, width: 171, height: 245 },
- { x: 14, y: 695, width: 198, height: 60 },
- { x: 373, y: 680, width: 620, height: 76 },
- ];
- const points = [[580, 420], [780, 260], [790, 415], [810, 340], [590, 470], [760, 495]];
- const items = points.map(([x, y], index) => ({
- key: String(index), point: { x, y },
- front: [0, 2, 4].includes(index),
- size: { width: 180, height: 165 },
- }));
- const positions = chooseCalloutTargets(items, obstacles, viewport);
- const placed = items.map((item) => ({ ...positions.get(item.key), ...item.size }));
- const intersects = (a, b) => a.x < b.x + b.width && a.x + a.width > b.x &&
- a.y < b.y + b.height && a.y + a.height > b.y;
- for (let i = 0; i < placed.length; i++) {
- for (let j = i + 1; j < placed.length; j++) expect(intersects(placed[i], placed[j])).toBe(false);
- for (const obstacle of obstacles) expect(intersects(placed[i], obstacle)).toBe(false);
- const nearX = Math.max(placed[i].x, Math.min(viewport.globe.x, placed[i].x + placed[i].width));
- const nearY = Math.max(placed[i].y, Math.min(viewport.globe.y, placed[i].y + placed[i].height));
- expect(Math.hypot(nearX - viewport.globe.x, nearY - viewport.globe.y)).toBeGreaterThanOrEqual(viewport.globe.radius);
- }
- expect(positions.get("4").side).toBe("left");
-});
-
-test("transient spring positions separate instead of covering another card or picker", () => {
- const states = [
- { x: 760, y: 130, width: 224, height: 65, vx: 1, vy: 1, lockedUntil: 0 },
- { x: 820, y: 165, width: 224, height: 65, vx: -1, vy: -1, lockedUntil: 0 },
- ];
- const picker = { x: 483, y: 15, width: 400, height: 168 };
- separateCalloutPositions(states, [picker], { width: 1366, height: 768 }, 100);
- const overlaps = (a, b) => a.x < b.x + b.width && a.x + a.width > b.x &&
- a.y < b.y + b.height && a.y + a.height > b.y;
- expect(overlaps(states[0], picker)).toBe(false);
- expect(overlaps(states[1], picker)).toBe(false);
- expect(overlaps(states[0], states[1])).toBe(false);
-});
-
-test("a saturated vertical stack uses horizontal space instead of recurring overlaps", () => {
- const states = [243, 404, 565].map((y) => ({ x: 990, y, width: 180, height: 165 }));
- const obstacles = [
- { x: 1053, y: 14, width: 300, height: 215 },
- { x: 1181, y: 509, width: 171, height: 245 },
- { x: 373, y: 680, width: 620, height: 76 },
- ];
- separateCalloutPositions(states, obstacles,
- { width: 1366, height: 768, globe: { x: 683, y: 384, radius: 182 } }, 0, 4);
- const intersects = (a, b) => a.x < b.x + b.width && a.x + a.width > b.x &&
- a.y < b.y + b.height && a.y + a.height > b.y;
- for (const [index, state] of states.entries()) {
- for (const other of [...obstacles, ...states.slice(index + 1)]) {
- expect(intersects(state, other)).toBe(false);
- }
- }
-});
diff --git a/frontend/public/earth/js/surface-line-lod-worker.js b/frontend/public/earth/js/surface-line-lod-worker.js
new file mode 100644
index 00000000..8d02ec5d
--- /dev/null
+++ b/frontend/public/earth/js/surface-line-lod-worker.js
@@ -0,0 +1,11 @@
+import {simplifySurfaceLines} from "./surface-line-simplification.js";
+const sources=new Map();
+self.onmessage=({data})=>{
+ if(data.type==="register") {sources.set(data.id,{positions:data.positions,faces:data.faces});return;}
+ if(data.type!=="simplify") return;
+ const source=sources.get(data.id);if(!source) return;
+ try {
+ const positions=simplifySurfaceLines(source.positions,source.faces,data.tolerance);
+ self.postMessage({id:data.id,tolerance:data.tolerance,positions},[positions.buffer]);
+ } catch(error) {self.postMessage({id:data.id,error:String(error?.message||error)});}
+};
diff --git a/frontend/public/earth/js/surface-line-lod.js b/frontend/public/earth/js/surface-line-lod.js
new file mode 100644
index 00000000..5e75b5d6
--- /dev/null
+++ b/frontend/public/earth/js/surface-line-lod.js
@@ -0,0 +1,70 @@
+import * as THREE from "three";
+import {surfaceLineTolerance} from "./surface-line-simplification.js";
+const CACHE_LIMIT=3;
+
+export function createSurfaceLineLod() {
+ const records=new Map();let worker=null,failed=false,disposed=false,nextId=0;
+ const cameraPosition=new THREE.Vector3(),earthPosition=new THREE.Vector3();
+ const fail=error=>{
+ if(failed||disposed) return;failed=true;
+ for(const record of records.values()) record.object.geometry=record.full;
+ worker?.terminate();worker=null;
+ console.warn("[surface-lines] using full geometry",error?.message||error);
+ };
+ try {
+ worker=new Worker(new URL("./surface-line-lod-worker.js",import.meta.url),{type:"module"});
+ worker.onerror=fail;
+ worker.onmessage=({data})=>{
+ if(disposed||failed) return;
+ const record=records.get(data.id);if(!record) return;
+ record.pending=null;
+ if(data.error) {fail(data.error);return;}
+ const geometry=new THREE.BufferGeometry();
+ geometry.setAttribute("position",new THREE.BufferAttribute(data.positions,3));
+ geometry.boundingSphere=record.full.boundingSphere?.clone()||null;
+ record.levels.set(data.tolerance,geometry);
+ // A late coarse response is cached, never installed directly. The next
+ // frame checks the CURRENT camera's error budget before selecting it.
+ while(record.levels.size>CACHE_LIMIT) {
+ const entry=[...record.levels].find(([,value])=>value!==record.object.geometry);
+ if(!entry) break;entry[1].dispose();record.levels.delete(entry[0]);
+ }
+ };
+ } catch(error) {fail(error);}
+ return {
+ register(object,faces,radius) {
+ if(failed||!worker||!object.geometry.attributes.position?.count) return;
+ const id=++nextId,full=object.geometry;
+ full.computeBoundingSphere();
+ const positions=new Float32Array(full.attributes.position.array),indices=new Uint32Array(faces);
+ records.set(id,{object,full,radius,levels:new Map(),pending:null});
+ worker.postMessage({type:"register",id,positions,faces:indices},[positions.buffer,indices.buffer]);
+ },
+ update(camera,renderer,earth) {
+ if(failed||disposed||!worker||!camera||!renderer||!earth) return;
+ camera.updateMatrixWorld();
+ const cameraRadius=cameraPosition.setFromMatrixPosition(camera.matrixWorld)
+ .distanceTo(earthPosition.setFromMatrixPosition(earth.matrixWorld));
+ const worldScale=earth.matrixWorld.getMaxScaleOnAxis();
+ const tangent=Math.tan(camera.fov*Math.PI/360);
+ const scale=renderer.domElement.height/(2*tangent)*(1+Math.hypot(camera.aspect*tangent,tangent));
+ for(const [id,record] of records) {
+ const tolerance=surfaceLineTolerance(cameraRadius,record.radius*worldScale,scale*worldScale);
+ let selected=record.full,best=0;
+ for(const [error,geometry] of record.levels) if(error<=tolerance&&error>best) {best=error;selected=geometry;}
+ if(record.object.geometry!==selected) record.object.geometry=selected;
+ if(tolerance>0 && !record.levels.has(tolerance) && record.pending===null && record.object.visible) {
+ record.pending=tolerance;worker.postMessage({type:"simplify",id,tolerance});
+ }
+ }
+ },
+ destroy() {
+ disposed=true;worker?.terminate();worker=null;
+ for(const record of records.values()) {
+ record.object.geometry=record.full;
+ for(const geometry of record.levels.values()) geometry.dispose();
+ }
+ records.clear();
+ },
+ };
+}
diff --git a/frontend/public/earth/js/surface-line-lod.test.js b/frontend/public/earth/js/surface-line-lod.test.js
new file mode 100644
index 00000000..99b8cd1a
--- /dev/null
+++ b/frontend/public/earth/js/surface-line-lod.test.js
@@ -0,0 +1,23 @@
+import {expect,test} from "bun:test";
+import * as THREE from "three";
+import {createSurfaceLineLod} from "./surface-line-lod.js";
+test("late coarse results cannot replace a close view, and teardown rejects stale responses",()=>{
+ const Original=globalThis.Worker;let worker;
+ globalThis.Worker=class {messages=[];terminated=false;constructor(){worker=this;}postMessage(data){this.messages.push(data);}terminate(){this.terminated=true;}};
+ try {
+ const controller=createSurfaceLineLod();
+ const full=new THREE.BufferGeometry();full.setAttribute("position",new THREE.BufferAttribute(new Float32Array([100,0,0,100,1,0]),3));
+ const line=new THREE.LineSegments(full,new THREE.LineBasicMaterial()),earth=new THREE.Object3D();
+ earth.updateMatrixWorld();controller.register(line,new Uint32Array([1,1]),100.48);
+ const camera=new THREE.PerspectiveCamera(75,16/9,.1,5000),renderer={domElement:{height:1080}};
+ camera.position.z=300;controller.update(camera,renderer,earth);
+ const request=worker.messages.at(-1);expect(request.type).toBe("simplify");
+ camera.position.z=110;controller.update(camera,renderer,earth);
+ worker.onmessage({data:{id:request.id,tolerance:request.tolerance,positions:new Float32Array([100,0,0,100,1,0])}});
+ controller.update(camera,renderer,earth);expect(line.geometry).toBe(full);
+ camera.position.z=300;controller.update(camera,renderer,earth);expect(line.geometry).not.toBe(full);
+ controller.destroy();expect(line.geometry).toBe(full);expect(worker.terminated).toBe(true);
+ worker.onmessage({data:{id:request.id,tolerance:request.tolerance,positions:new Float32Array(6)}});
+ expect(line.geometry).toBe(full);expect(full.attributes.position.array.length).toBe(6);
+ } finally {if(Original===undefined)delete globalThis.Worker;else globalThis.Worker=Original;}
+});
diff --git a/frontend/public/earth/js/surface-line-simplification.js b/frontend/public/earth/js/surface-line-simplification.js
new file mode 100644
index 00000000..3baad9e8
--- /dev/null
+++ b/frontend/public/earth/js/surface-line-simplification.js
@@ -0,0 +1,47 @@
+// Simplify only connected runs on the SAME flat Earth surface triangle.
+// Crossing a face boundary, a discontinuity, or a closed ring keeps the source
+// vertices, so reduced geometry cannot cut through the underlying globe.
+export function simplifySurfaceLines(positions, faces, tolerance) {
+ if(faces.length*3!==positions.length || positions.length%6) throw new Error("Invalid surface line buffers");
+ const result=new Float32Array(positions.length), segments=positions.length/6;
+ let written=0, first=0, keep=new Uint8Array(256), stack=new Int32Array(512);
+ const same=(a,b)=>positions[a]===positions[b]&&positions[a+1]===positions[b+1]&&positions[a+2]===positions[b+2];
+ const copy=(a,b)=>{for(let axis=0;axis<3;axis++) result[written++]=positions[a+axis];for(let axis=0;axis<3;axis++) result[written++]=positions[b+axis];};
+ while(firstindex===0?first*6:(first+index-1)*6+3;
+ let top=0;stack[top++]=0;stack[top++]=count-1;
+ while(top) {
+ const end=stack[--top],begin=stack[--top],a=offset(begin),b=offset(end);
+ const dx=positions[b]-positions[a],dy=positions[b+1]-positions[a+1],dz=positions[b+2]-positions[a+2];
+ const length=dx*dx+dy*dy+dz*dz;
+ let worst=-1,error=tolerance*tolerance;
+ for(let i=begin+1;ierror) {error=distance;worst=i;}
+ }
+ if(worst<0) continue;keep[worst]=1;
+ if(worst-begin>1) {stack[top++]=begin;stack[top++]=worst;}
+ if(end-worst>1) {stack[top++]=worst;stack[top++]=end;}
+ }
+ let previous=0;
+ for(let i=1;i0 ? 2**Math.floor(Math.log2(limit)) : 0;
+}
diff --git a/frontend/public/earth/js/surface-line-simplification.test.js b/frontend/public/earth/js/surface-line-simplification.test.js
new file mode 100644
index 00000000..7c77e27c
--- /dev/null
+++ b/frontend/public/earth/js/surface-line-simplification.test.js
@@ -0,0 +1,41 @@
+import {expect,test} from "bun:test";
+import * as THREE from "three";
+import {simplifySurfaceLines,surfaceLineTolerance} from "./surface-line-simplification.js";
+import {appendSurfaceSegments} from "./earth-surface.js";
+function segments(points) {return new Float32Array(points.slice(1).flatMap((point,i)=>[...points[i],...point]));}
+test("collinear same-face detail merges without mutating the source",()=>{
+ const source=segments([[0,0,0],[1,.00001,0],[2,0,0],[3,0,0]]),copy=source.slice();
+ const reduced=simplifySurfaceLines(source,new Uint32Array(6).fill(7),.001);
+ expect([...reduced]).toEqual([0,0,0,3,0,0]);expect([...source]).toEqual([...copy]);
+});
+test("face boundaries and disconnected geometry cannot be bridged",()=>{
+ const source=segments([[0,0,0],[1,0,0],[2,0,0],[3,1,0]]);
+ const faces=new Uint32Array([1,1,1,2,2,2]);
+ expect([...simplifySurfaceLines(source,faces,100)]).toEqual([...source]);
+ const separate=new Float32Array([0,0,0,1,0,0,10,0,0,11,0,0]);
+ expect([...simplifySurfaceLines(separate,new Uint32Array(4).fill(1),100)]).toEqual([...separate]);
+});
+test("small closed islands retain every original edge even with a large tolerance",()=>{
+ const source=segments([[0,0,0],[1,0,0],[1,1,0],[0,0,0]]);
+ expect([...simplifySurfaceLines(source,new Uint32Array(6).fill(1),100)]).toEqual([...source]);
+});
+test("surface tags do not change the existing draped positions or cross triangle planes",()=>{
+ const ring=Array.from({length:100},(_,i)=>[10+i*.0001,20+i*.0001]);
+ const points=[],faces=[],reference=[];
+ appendSurfaceSegments(ring,100.48,points,faces);appendSurfaceSegments(ring,100.48,reference);
+ expect(points.map(p=>p.toArray())).toEqual(reference.map(p=>p.toArray()));
+ expect(faces.length).toBe(points.length);
+ const source=new Float32Array(points.flatMap(p=>p.toArray()));
+ const reduced=simplifySurfaceLines(source,new Uint32Array(faces),.01);
+ expect(reduced.length).toBeLessThan(source.length);
+ for(let i=0;ip.distanceTo(point)<.00001)).toBe(true);
+ }
+});
+test("quantized tolerances never exceed the screen-space budget and tighten on zoom",()=>{
+ const far=surfaceLineTolerance(300,100.48,2000),near=surfaceLineTolerance(110,100.48,2000);
+ expect(far).toBeLessThanOrEqual(.15*(300-100.48)/2000);
+ expect(near).toBeLessThan(far);
+ expect(surfaceLineTolerance(100,100.48,2000)).toBe(0);
+});
diff --git a/frontend/public/earth/js/typewriter.js b/frontend/public/earth/js/typewriter.js
new file mode 100644
index 00000000..4a88b42f
--- /dev/null
+++ b/frontend/public/earth/js/typewriter.js
@@ -0,0 +1,37 @@
+export function createTypewriter({ schedule = setTimeout, cancel = clearTimeout } = {}) {
+ let timer = null, activeTarget = null, generation = 0;
+ function stop() {
+ generation++;
+ if (timer !== null) cancel(timer);
+ timer = null;
+ activeTarget?.classList.remove("is-typing");
+ activeTarget = null;
+ }
+ return {
+ stop,
+ isTyping: () => activeTarget !== null,
+ start(target, value, {stepMs=22,startDelayMs=90,maxDurationMs=Infinity,isPaused=()=>false,onComplete=()=>{}} = {}) {
+ stop();
+ if (!target) return;
+ const token=generation, characters=Array.from(String(value ?? ""));
+ const batch=Math.max(1,Math.ceil(characters.length*stepMs/maxDurationMs));
+ let index=0;
+ activeTarget=target;target.textContent="";target.classList.add("is-typing");
+ const tick=()=>{
+ if(token !== generation) return;
+ if(isPaused()) {timer=schedule(tick,stepMs);return;}
+ index=Math.min(characters.length,index+batch);
+ target.textContent=characters.slice(0,index).join("");
+ if(index{jobs.set(++id,{fn,at:now+delay});return id;},cancel:key=>jobs.delete(key),
+ advance(ms){const end=now+ms;for(;;){const next=[...jobs].sort((a,b)=>a[1].at-b[1].at)[0];if(!next||next[1].at>end)break;now=next[1].at;jobs.delete(next[0]);next[1].fn();}now=end;}};
+}
+const target=()=>({textContent:"",classList:{add(){},remove(){}}});
+test("each news card types independently; stopping one never cancels its peers",()=>{
+ const time=clock(),first=createTypewriter(time),second=createTypewriter(time),a=target(),b=target();
+ first.start(a,"ABC",{startDelayMs:0,stepMs:20});second.start(b,"新闻全文",{startDelayMs:0,stepMs:20});
+ time.advance(20);expect(a.textContent).toBe("AB");expect(b.textContent).toBe("新闻");
+ first.stop();time.advance(100);expect(a.textContent).toBe("AB");expect(b.textContent).toBe("新闻全文");
+});
+test("typing waits until a card is visible and calls completion only after full Unicode text",()=>{
+ const time=clock(),writer=createTypewriter(time),el=target();let paused=true,done=0;
+ writer.start(el,"📰完整摘要",{startDelayMs:0,stepMs:20,isPaused:()=>paused,onComplete:()=>done++});
+ time.advance(200);expect(el.textContent).toBe("");paused=false;time.advance(100);
+ expect(el.textContent).toBe("📰完整摘要");expect(done).toBe(1);
+});
+test("long summaries remain complete within the per-card typing budget",()=>{
+ const time=clock(),writer=createTypewriter(time),el=target(),text="正文".repeat(1000);let done=false;
+ writer.start(el,text,{startDelayMs:0,stepMs:20,maxDurationMs:4000,onComplete:()=>{done=true;}});
+ time.advance(4000);expect(el.textContent).toBe(text);expect(done).toBe(true);
+});
+
+
+test("interrupting cruise exits the typing wait without delaying manual selection", async()=>{
+ const {waitForTypewriter}=await import("./typewriter.js");
+ let current=true,frames=0;
+ const result=await waitForTypewriter({isTyping:()=>true},{isCurrent:()=>current,nextFrame:async()=>{frames++;current=false;}});
+ expect(result).toBe(false);expect(frames).toBe(1);
+});
diff --git a/frontend/public/earth/js/ui.js b/frontend/public/earth/js/ui.js
index 6718c176..30779ec3 100644
--- a/frontend/public/earth/js/ui.js
+++ b/frontend/public/earth/js/ui.js
@@ -22,6 +22,11 @@ let loadingActive = false;
let loadingLockedWidth = 0;
let pendingLoadingMessage = "";
+// Selection describes the result, independently of mouse/touch/motion input.
+export function showSelectionStatus(name) {
+ showStatusMessage(earthMessage("status.selected", { name }), "info");
+}
+
function createStatusEntry(message, type = "info") {
return { message, type };
}
diff --git a/frontend/src/admin/pages/CardImagePreview.tsx b/frontend/src/admin/pages/CardImagePreview.tsx
new file mode 100644
index 00000000..ebf8004d
--- /dev/null
+++ b/frontend/src/admin/pages/CardImagePreview.tsx
@@ -0,0 +1,24 @@
+import { useEffect, useState } from 'react'
+import type { ImageAsset } from './card-images-model'
+
+export function CardImagePreview({ asset, title, english }: {asset: ImageAsset | null; title: string; english: boolean}) {
+ const source = asset?.variants['1280'] || asset?.url
+ const [loaded, setLoaded] = useState('')
+ const [failed, setFailed] = useState('')
+ useEffect(() => { setLoaded(''); setFailed('') }, [source])
+ return
+
{title || (english ? 'Detail card preview' : '详情卡预览')}
+
+
+ {source ?

setLoaded(source)} onError={() => setFailed(source)} style={{objectPosition:`${asset?.focus_x}% ${asset?.focus_y}%`}} /> : null}
+
+
+
{english ? 'Name' : '名称'}{title || '—'}
+
{english ? 'Source' : '来源'}{asset?.credit || '—'}
+
{english ? 'Image' : '配图'}{asset?.title || (english ? 'None' : '无')}
+
{english ? 'Dimensions' : '尺寸'}{asset ? `${asset.width} × ${asset.height}` : '—'}
+
+
+ {source && failed === source ?
{english ? 'Image could not load; the data card remains available.' : '图片加载失败,数据卡片仍正常显示。'}
: null}
+
+}
diff --git a/frontend/src/admin/pages/CardImageSettings.tsx b/frontend/src/admin/pages/CardImageSettings.tsx
new file mode 100644
index 00000000..8c60b386
--- /dev/null
+++ b/frontend/src/admin/pages/CardImageSettings.tsx
@@ -0,0 +1,182 @@
+import { useEffect, useRef, useState, type ReactNode } from 'react'
+import axios from 'axios'
+import { ImagePlus, Link2, Plus, RefreshCw, Save, Trash2 } from 'lucide-react'
+import { useLocale } from '../../i18n/locale'
+import { Button } from '../components/ui/button'
+import { ConfirmDialog } from '../components/ui/dialog'
+import { Input } from '../components/ui/input'
+import { Select } from '../components/ui/select'
+import { AdminSwitch } from '../components/ui/switch'
+import { Panel } from '../patterns/patterns'
+import { CardImagePreview } from './CardImagePreview'
+import { CARD_IMAGES_API, CARD_IMAGES_REVISION_KEY, imageRequestError, useImageTargets,
+ type EntityType, type MatchScope, type ImageAsset, type ImageRule,
+ type ImageConfiguration, type ImageEnvelope, type ImageResolution } from './card-images-model'
+import './card-images.css'
+
+function Field({label,children}:{label:string;children:ReactNode}) { return }
+const newId = () => `custom-${crypto.randomUUID()}`
+
+export function CardImageSettings({active}:{active:boolean}) {
+ const {locale} = useLocale(), english = locale === 'en-US'
+ const t = (zh:string,en:string) => english ? en : zh
+ const [saved,setSaved] = useState(null)
+ const [draft,setDraft] = useState(null)
+ const [view,setView] = useState<'assets'|'rules'>('assets')
+ const [selected,setSelected] = useState('')
+ const [busy,setBusy] = useState(false), [error,setError] = useState(''), [message,setMessage] = useState('')
+ const [reloadVersion,setReloadVersion] = useState(0)
+ const [confirmation,setConfirmation] = useState<{label:string;run:()=>void} | null>(null)
+ const [entityType,setEntityType] = useState('satellite')
+ const [scope,setScope] = useState('object')
+ const [search,setSearch] = useState(''), [target,setTarget] = useState(''), [targetLabel,setTargetLabel] = useState('')
+ const [ruleAsset,setRuleAsset] = useState(''), [ruleEnabled,setRuleEnabled] = useState(true)
+ const [editingRuleId,setEditingRuleId] = useState(null)
+ const [previewSearch,setPreviewSearch] = useState(''), [previewTarget,setPreviewTarget] = useState('')
+ const [resolution,setResolution] = useState(null)
+ const uploadRef = useRef(null), previewRevision = useRef(0)
+ const targets = useImageTargets(active && view === 'rules', entityType, scope, search)
+ const previewTargets = useImageTargets(active && view === 'rules', entityType, 'object', previewSearch)
+ const dirty = Boolean(saved && draft && JSON.stringify(saved.config) !== JSON.stringify(draft))
+ const types = [{value:'satellite',label:t('卫星','Satellites')},{value:'compute_center',label:t('算力设施','Compute facilities')},{value:'cable',label:t('海缆','Subsea cables')},{value:'landing_point',label:t('登陆站','Landing stations')},{value:'vessel',label:t('船舶','Vessels')},{value:'bgp',label:t('BGP 事件','BGP events')},{value:'bgp_collector',label:t('BGP 观测站','BGP collectors')},{value:'earth_interactable',label:t('自定义交互点','Custom points')}]
+ const categoryLabels: Record = {
+ supercomputer:t('超算中心','Supercomputer'), gpu_cluster:t('GPU 集群','GPU cluster'),
+ data_center:t('数据中心','Data center'), cloud_center:t('云计算中心','Cloud computing center'),
+ edge_node:t('边缘计算节点','Edge computing node'),
+ }
+ const scopes = [{value:'object',label:t('指定物件','Specific object')},{value:'model',label:t('型号','Model')},{value:'group',label:t('分组','Group')},{value:'category',label:t('分类','Category')}]
+ const edit = (next:ImageConfiguration) => { setDraft(next);setError('');setMessage('');setResolution(null);previewRevision.current++ }
+ useEffect(() => {
+ if (!document.querySelector('link[data-card-image-styles]')) {
+ const link=document.createElement('link');link.rel='stylesheet';link.href='/earth/css/card-images.css';link.dataset.cardImageStyles='true';document.head.append(link)
+ }
+ }, [])
+ useEffect(() => {
+ if (!active || saved) return
+ const abort=new AbortController();setBusy(true)
+ axios.get(`${CARD_IMAGES_API}/configuration`,{signal:abort.signal})
+ .then(({data})=>{setSaved(data);setDraft(data.config);setSelected(data.config.assets[0]?.id || '');setError('')})
+ .catch(failure=>{if(!abort.signal.aborted)setError(imageRequestError(failure,english))})
+ .finally(()=>{if(!abort.signal.aborted)setBusy(false)})
+ return ()=>abort.abort()
+ },[active,saved,reloadVersion,english])
+ useEffect(()=>{
+ if(!dirty)return
+ const guard=(event:BeforeUnloadEvent)=>{event.preventDefault();event.returnValue=''}
+ window.addEventListener('beforeunload',guard);return ()=>window.removeEventListener('beforeunload',guard)
+ },[dirty])
+ if(!active && !saved)return null
+ const asset=draft?.assets.find(item=>item.id===selected) || null
+ const patchAsset=(patch:Partial)=>{if(draft && asset)edit({...draft,assets:draft.assets.map(item=>item.id===asset.id?{...item,...patch}:item)})}
+ const refresh=()=>{setSaved(null);setReloadVersion(value=>value+1);setConfirmation(null)}
+ async function save() {
+ if(!saved || !draft)return
+ setBusy(true);setError('')
+ try {
+ const {data}=await axios.put(`${CARD_IMAGES_API}/configuration`,{revision:saved.revision,config:draft})
+ setSaved(data);setDraft(data.config);setMessage(t('已保存,详情卡将使用新配置。','Saved. Detail cards will use the new configuration.'))
+ try { localStorage.setItem(CARD_IMAGES_REVISION_KEY,data.revision) } catch { /* Saved server state remains authoritative when browser storage is unavailable. */ }
+ } catch(failure){setError(imageRequestError(failure,english))} finally{setBusy(false)}
+ }
+ async function upload(file:File) {
+ if(!draft)return
+ setBusy(true);setError('')
+ try {
+ const form=new FormData();form.append('file',file)
+ const {data}=await axios.post(`${CARD_IMAGES_API}/upload`,form)
+ if(!draft.assets.some(item=>item.id===data.id))edit({...draft,assets:[...draft.assets,data]})
+ setSelected(data.id);setView('assets')
+ }catch(failure){setError(imageRequestError(failure,english))}finally{setBusy(false);if(uploadRef.current)uploadRef.current.value=''}
+ }
+ function addUrl() {
+ if(!draft)return
+ const id=newId();edit({...draft,assets:[...draft.assets,{id,title:t('新配图','New image'),url:'',variants:{},width:0,height:0,credit:'',source_url:'',license:'',license_url:'',kind:'photo',rights_status:'available',enabled:true,focus_x:50,focus_y:50}]});setSelected(id)
+ }
+ function saveRule() {
+ if(!draft || !target || !ruleAsset)return
+ const value=scope==='object'?target:target.toLowerCase()
+ const existing=draft.rules.find(rule=>rule.entity_type===entityType && rule.scope===scope && rule.value===value)
+ if(existing && existing.id!==editingRuleId) {setError(t('该目标已有规则,请选择现有规则进行修改。','This target already has an assignment. Select that assignment to edit it.'));return}
+ const rule:ImageRule={id:editingRuleId || newId(),entity_type:entityType,scope,value,label:targetLabel || value,
+ asset_id:ruleAsset==='__none__'?null:ruleAsset,suppress:ruleAsset==='__none__',enabled:ruleEnabled}
+ edit({...draft,rules:editingRuleId?draft.rules.map(item=>item.id===editingRuleId?rule:item):[...draft.rules,rule]});setEditingRuleId(rule.id)
+ }
+ function selectRule(rule:ImageRule) {
+ setEditingRuleId(rule.id)
+ setEntityType(rule.entity_type);setScope(rule.scope);setSearch('');setTarget(rule.value);setTargetLabel(rule.label)
+ setRuleAsset(rule.suppress?'__none__':rule.asset_id || '');setRuleEnabled(rule.enabled);setResolution(null)
+ }
+ async function preview() {
+ if(!draft || !previewTarget)return
+ const version=++previewRevision.current;setError('')
+ try {
+ const {data}=await axios.post(`${CARD_IMAGES_API}/preview`,{config:draft,entity_type:entityType,entity_id:previewTarget})
+ if(version===previewRevision.current)setResolution(data)
+ }catch(failure){if(version===previewRevision.current)setError(imageRequestError(failure,english))}
+ }
+ const targetOptions=targets.items.map(item=>({value:item.value,label:item.value==='*'?t('此类型全部物件','All objects of this type'):scope==='object'?`${item.label} · ${item.value}`:scope==='category'?(categoryLabels[item.value] || item.label):item.label}))
+ if(target && !targetOptions.some(item=>item.value===target))targetOptions.unshift({value:target,label:targetLabel || target})
+ const errorText=error || (targets.error?imageRequestError(targets.error,english):'') || (previewTargets.error?imageRequestError(previewTargets.error,english):'')
+ return
+
+
{t('详情卡配图','Detail card images')}
+
+
+
+
+
+
+
+ {errorText?{errorText}
:null}
+ {message?{message}
:null}
+ {!draft?{busy?t('加载中…','Loading…'):t('暂无可用配置','Configuration unavailable')}
:}
+ {if(!open)setConfirmation(null)}} title={t('确认操作','Confirm action')} description={confirmation?.label} onConfirm={()=>confirmation?.run()}/>
+
+}
diff --git a/frontend/src/admin/pages/PlainResourcePages.tsx b/frontend/src/admin/pages/PlainResourcePages.tsx
index d83af513..a14afef6 100644
--- a/frontend/src/admin/pages/PlainResourcePages.tsx
+++ b/frontend/src/admin/pages/PlainResourcePages.tsx
@@ -45,6 +45,7 @@ import { ControlGroup as TactileControlGroup } from '../../components/tactile-ui
import { useToast } from '../components/ui/toast'
import { DetailPanel, EmptyState, PageFrame, Panel, StatCell, StatusText, SummaryStrip } from '../patterns/patterns'
import { ComputeComparisonSettings } from './ComputeComparisonSettings'
+import { CardImageSettings } from './CardImageSettings'
import {
COLLECTION_QUEUE_ACTIVE_STATUSES, isStaleTaskUpdate, patchCollectionTask, upsertCollectionTask,
type CollectionQueueItem, type CollectionQueueStatus,
@@ -1403,7 +1404,7 @@ function snapshotOptionLabel(record: AnyRecord) {
const emptyRows = () => []
-const placeholderSectionKeys = new Set(['basemap', 'layer_resources', 'models_3d'])
+const placeholderSectionKeys = new Set(['basemap', 'models_3d'])
function isPlaceholderSection(key: string) {
return placeholderSectionKeys.has(key)
@@ -3438,6 +3439,8 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
const activeSection = useMemo(() => config.sections.find((section) => section.key === activeSectionKey) ?? config.sections[0], [activeSectionKey, config.sections])
const activeState = useMemo(() => states.find((state) => state.section.key === activeSection?.key), [activeSection?.key, states])
const isComputeConfigSection = config === configs.earthContent && activeSection?.key === 'compute_comparison'
+ const isCardImagesSection = config === configs.earthContent && activeSection?.key === 'layer_resources'
+ const isSpecialContentSection = isComputeConfigSection || isCardImagesSection
const rows = activeState?.rows ?? []
const isDatasourceBuiltinSection = config === configs.datasources && activeSection?.key === 'builtin'
const selectedDatasourceRows = useMemo(
@@ -7094,9 +7097,9 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
className="an-resource-page"
actions={(
<>
- {!isComputeConfigSection ? : null}
+ {!isSpecialContentSection ? : null}
{renderCollectionQueueAction()}
- {!isComputeConfigSection ? moduleActions : null}
+ {!isSpecialContentSection ? moduleActions : null}
{config.actions.map((action) => (