Files
planet/frontend/public/earth/js/compute-centers.js
T
linkong e1cc27f13d
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
release: bump version to 0.84.0
2026-12-04 07:07:19 +08:00

1125 lines
39 KiB
JavaScript

import { COMPUTE_SITE_TYPES, COMPUTE_SITE_TYPE_KEYS, countComputeSiteTypes, normalizeComputeSiteType } from "./compute-site-types.js";
import { isLegendItemEnabled } from "./legend-filters.js";
import * as THREE from "three";
import { computeStableComputeCenterPositions } from "./compute-center-positioning.js";
import { COMPUTE_CENTER_CONFIG, CONFIG, PATHS } from "./constants.js";
import {
createInteractableLayer,
SURFACE_AVOIDANCE_PROFILES,
} from "./interactable.js";
import { latLonToVector3 } from "./utils.js";
import { createSurfaceRibbonGeometry, createSurfaceRibbonMaterial } from "./surface-ribbon.js";
import { fetchAdminWriteJson } from "./admin-write-auth.js";
const COMPUTE_CENTER_RENDER_ORDER = 4.5;
const COMPUTE_CENTER_POINT_SIZE = 36;
const COMPUTE_CENTER_ICON_FIT_SIZE = 100;
const COMPUTE_CENTER_ATLAS_CELL_SIZE = 128;
const COMPUTE_CENTER_ICON_SOURCES = {
supercomputer: new URL("../assets/icons/compute-supercomputer.svg", import.meta.url).href,
gpu_cluster: new URL("../assets/icons/compute-gpu-cluster.svg", import.meta.url).href,
data_center: new URL("../assets/icons/compute-hdd-network.svg", import.meta.url).href,
cloud_center: new URL("../assets/icons/compute-cloud.svg", import.meta.url).href,
edge_node: new URL("../assets/icons/compute-edge.svg", import.meta.url).href,
national_hub: new URL("../assets/icons/compute-national-hub.svg", import.meta.url).href,
};
let showComputeCenters = true;
let typeCounts = countComputeSiteTypes([]);
let unresolvedComputeCenters = [];
let previewRingTexture = null;
let previewRingGroup = null;
let previewRingA = null;
let previewRingB = null;
let previewRingPulseOffset = 0;
const COLLECT_LOCATION_API_BASE = "/api/v1/visualization/compute-centers";
const LOCATION_CAPABILITY_API = "/api/v1/visualization/compute-centers/location-capability";
let computeCenterLocationCapabilityPromise = null;
let computeTopicQuery = null;
let loadGeneration = 0;
let loadController = null;
export function setComputeTopicQuery(query) {
computeTopicQuery = query;
loadGeneration += 1;
loadController?.abort();
}
function getPreviewRingTexture() {
if (previewRingTexture) return previewRingTexture;
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
const context = canvas.getContext("2d");
if (!context) {
previewRingTexture = new THREE.Texture(canvas);
return previewRingTexture;
}
context.clearRect(0, 0, 128, 128);
context.strokeStyle = "rgba(255,255,255,0.96)";
context.lineWidth = 5;
context.beginPath();
context.arc(64, 64, 43, 0, Math.PI * 2);
context.stroke();
previewRingTexture = new THREE.CanvasTexture(canvas);
return previewRingTexture;
}
function ensurePreviewRingGroup(earth) {
if (!earth) return null;
if (!previewRingGroup) {
previewRingGroup = new THREE.Group();
previewRingGroup.name = "compute-center-location-preview";
}
if (previewRingGroup.parent !== earth) {
previewRingGroup.parent?.remove?.(previewRingGroup);
earth.add(previewRingGroup);
}
return previewRingGroup;
}
function createPreviewRingSprite({ color = 0x2dd4bf } = {}) {
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: getPreviewRingTexture(),
color,
transparent: true,
opacity: 0,
depthWrite: false,
depthTest: true,
blending: THREE.AdditiveBlending,
}),
);
sprite.renderOrder = COMPUTE_CENTER_RENDER_ORDER + 0.18;
return sprite;
}
function disposePreviewRingSprite(sprite) {
if (!sprite) return;
sprite.parent?.remove?.(sprite);
sprite.material?.dispose?.();
}
function attachPreviewRings(group, position, color) {
disposePreviewRingSprite(previewRingA);
disposePreviewRingSprite(previewRingB);
previewRingA = createPreviewRingSprite({ color });
previewRingB = createPreviewRingSprite({ color });
previewRingA.position.copy(position);
previewRingB.position.copy(position);
group.add(previewRingA);
group.add(previewRingB);
previewRingPulseOffset = Math.random() * Math.PI * 2;
}
function buildComputeCenterMarkerData(feature) {
const props = feature?.properties || {};
const coordinates = feature?.geometry?.coordinates || [];
const longitude = Number(coordinates[0]);
const latitude = Number(coordinates[1]);
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) {
return null;
}
return {
...props,
latitude,
longitude,
displayLatitude: latitude,
displayLongitude: longitude,
site_type: normalizeComputeSiteType(props.site_type),
};
}
function spreadComputeCenterPositions(markers) {
return computeStableComputeCenterPositions(
markers,
COMPUTE_CENTER_CONFIG.overlapSpread,
);
}
function drawComputeCenterEstimatedBadge(context, isEstimated = false) {
if (isEstimated) {
context.save();
context.fillStyle = "rgba(15,23,42,0.92)";
context.beginPath();
context.arc(94, 36, 12, 0, Math.PI * 2);
context.fill();
context.fillStyle = "rgba(255,255,255,0.98)";
context.font = "bold 18px sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText("?", 94, 36);
context.restore();
}
}
function shouldShowComputeCenterEstimatedBadge(data) {
if (!data) return false;
if (data.needs_confirmation === true) return true;
if (data.location_source === "nominatim_online_geocode") return true;
return false;
}
const computeCenterIconLayer = createInteractableLayer({
id: "computeCenters",
isItemVisible: item => isLegendItemEnabled("computeCenters", normalizeComputeSiteType(item.site_type)),
objectType: "compute_center",
renderOrder: COMPUTE_CENTER_RENDER_ORDER,
altitudeOffset: COMPUTE_CENTER_CONFIG.altitudeOffset,
pointSize: COMPUTE_CENTER_POINT_SIZE,
atlasCellSize: COMPUTE_CENTER_ATLAS_CELL_SIZE,
colors: {
byKind: COMPUTE_CENTER_CONFIG.colors,
normal: COMPUTE_CENTER_CONFIG.colors.data_center,
},
opacity: {
normal: COMPUTE_CENTER_CONFIG.marker.baseOpacity,
dimmed: COMPUTE_CENTER_CONFIG.marker.dimmedOpacity,
hover: 0.98,
locked: 1,
},
stateScale: {
hover: COMPUTE_CENTER_CONFIG.marker.hoverScale,
locked: COMPUTE_CENTER_CONFIG.marker.lockedScale,
dimmed: COMPUTE_CENTER_CONFIG.marker.dimmedScale,
},
pulse: {
enabled: true,
speed: COMPUTE_CENTER_CONFIG.marker.pulseSpeed,
amplitude: COMPUTE_CENTER_CONFIG.marker.pulseAmplitude,
},
icon: {
colorable: false,
badge: ({ marker, item }) => ({ color: COMPUTE_CENTER_CONFIG.colors[marker?.userData?.site_type || item?.site_type] || COMPUTE_CENTER_CONFIG.colors.data_center }),
coordinates: "canvas",
fitSize: COMPUTE_CENTER_ICON_FIT_SIZE,
glowBlur: 16,
getSource({ marker, item }) {
const siteType =
marker?.userData?.site_type || item?.site_type || "gpu_cluster";
return (
COMPUTE_CENTER_ICON_SOURCES[siteType] ||
COMPUTE_CENTER_ICON_SOURCES.data_center
);
},
afterDraw(context, { marker, item }) {
const data = marker?.userData || item;
drawComputeCenterEstimatedBadge(
context,
shouldShowComputeCenterEstimatedBadge(data),
);
},
},
getPosition: (item) => ({
latitude: item.displayLatitude,
longitude: item.displayLongitude,
}),
getKind: (item) => item.site_type || "gpu_cluster",
getBucketKey: (marker) =>
[
marker.userData?.site_type || "gpu_cluster",
shouldShowComputeCenterEstimatedBadge(marker.userData) ? "estimated" : "verified",
].join(":"),
getUserData: (item) => ({
...item,
pulseOffset: Math.random() * Math.PI * 2,
}),
avoidance: SURFACE_AVOIDANCE_PROFILES.city,
cluster: { enabled: true },
});
export function formatComputeCenterTypeLabel(siteType) {
return COMPUTE_SITE_TYPES[normalizeComputeSiteType(siteType)].label;
}
export function formatComputeCenterCapacity(markerData) {
const value = markerData?.capacity_value;
const unit = markerData?.capacity_unit;
if (value === null || value === undefined || value === "") return "-";
if (unit === "FLOP/s" && Number.isFinite(Number(value))) {
const scale = Number(value) >= 1e18 ? [1e18, "EFLOP/s"] : Number(value) >= 1e15 ? [1e15, "PFLOP/s"] : [1e12, "TFLOP/s"];
return `${(Number(value) / scale[0]).toLocaleString("en-US", { maximumFractionDigits: 2 })} ${scale[1]} · ${markerData.metadata?.precision || "—"}`;
}
return `${value}${unit ? ` ${unit}` : ""}`;
}
export function formatComputeCenterUpdatedAt(value) {
if (!value) return "-";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return String(value);
return date.toLocaleString("zh-CN", { hour12: false });
}
export function formatComputeCenterLocationPrecision(markerData) {
if (markerData?.isSpread === true) return "城市级近似位置(分散显示)";
const precision = markerData?.location_precision;
if (precision === "precise") return "精确坐标";
if (precision === "site") return "站点级位置";
if (precision === "city") return "城市级位置";
return "位置未确认";
}
export function formatComputeCenterNeedsConfirmation(markerData) {
if (markerData?.needs_confirmation === true) return "待人工核验";
if (markerData?.is_estimated === true) return "估算位置";
return "已确认";
}
export function getComputeCenterLegendItems() {
return COMPUTE_SITE_TYPE_KEYS.map(key => ({
key, label: COMPUTE_SITE_TYPES[key].label, count: typeCounts[key],
color: COMPUTE_CENTER_CONFIG.colors[key],
}));
}
export function getComputeCenterMarkers() {
return computeCenterIconLayer.getMarkers();
}
export function getComputeCenterCount() {
return computeCenterIconLayer.getCount();
}
export function getComputeCenterStatusSummary() {
if (getComputeCenterCount() === 0) return "暂无算力中心数据";
return COMPUTE_SITE_TYPE_KEYS.filter(key => typeCounts[key] > 0)
.map(key => `${typeCounts[key]} ${COMPUTE_SITE_TYPES[key].label}`).join(" / ");
}
export function setComputeCenterMarkerState(marker, state = "normal") {
computeCenterIconLayer.setMarkerState(marker, state);
}
export function clearComputeCenterSelection() {
getComputeCenterMarkers().forEach((marker) => setComputeCenterMarkerState(marker, "normal"));
}
export function clearComputeCenterData(earth) {
typeCounts = countComputeSiteTypes([]);
unresolvedComputeCenters = [];
clearComputeCenterLocationPreview();
computeCenterIconLayer.clearData(earth);
}
export function clearComputeCenterLocationPreview() {
disposePreviewRingSprite(previewRingA);
disposePreviewRingSprite(previewRingB);
previewRingA = null;
previewRingB = null;
}
export function showComputeCenterLocationPreview(earth, { latitude, longitude, color = 0x2dd4bf } = {}) {
const lat = Number(latitude);
const lon = Number(longitude);
if (!earth || !Number.isFinite(lat) || !Number.isFinite(lon)) return false;
const group = ensurePreviewRingGroup(earth);
if (!group) return false;
const position = latLonToVector3(
lat,
lon,
CONFIG.earthRadius + COMPUTE_CENTER_CONFIG.altitudeOffset + 0.2,
);
attachPreviewRings(group, position, color);
updateComputeCenterLocationPreview();
return true;
}
function updateComputeCenterLocationPreview() {
if (!previewRingA && !previewRingB) return;
const now = performance.now();
const baseScale = 8.5;
const pulseSpeed = 0.00105;
const applyRing = (ring, phaseOffset, maxScale) => {
if (!ring) return;
const phase = (now * pulseSpeed + previewRingPulseOffset + phaseOffset) % 1;
const progress = Math.max(0, Math.min(1, phase));
const fadeIn = Math.max(0, Math.min(1, (progress - 0.04) / 0.16));
const fadeOut = 1 - progress;
const visibility = fadeIn * fadeOut;
ring.scale.setScalar(baseScale * (1.0 + progress * (maxScale - 1.0)));
ring.material.opacity = 0.5 * visibility;
ring.visible = true;
};
applyRing(previewRingA, 0, 1.85);
applyRing(previewRingB, 0.45, 2.35);
}
function recomputeComputeCenterCounts(markerData) {
typeCounts = countComputeSiteTypes(markerData);
}
function buildOptimisticComputeCenterMarkerData({ sourceId, candidate, context, saveResult }) {
const location = saveResult?.location || {};
const existingData = context?.data || {};
const latitude = Number(location.latitude ?? candidate?.latitude);
const longitude = Number(location.longitude ?? candidate?.longitude);
if (!sourceId || !Number.isFinite(latitude) || !Number.isFinite(longitude)) {
return null;
}
const siteType = normalizeComputeSiteType(
context?.site_type || context?.siteType || existingData.site_type || location.site_type,
);
return {
id: context?.recordId || context?.id || existingData.id || saveResult?.record_id || sourceId,
source_id: sourceId,
name:
context?.name ||
existingData.name ||
location.name ||
candidate?.matched_location_name ||
candidate?.display_name ||
"算力中心",
source: saveResult?.source || context?.source || existingData.source || location.source || "",
site_type: siteType,
country: location.country || candidate?.country || context?.country || existingData.country || "",
city: location.city || candidate?.city || context?.city || existingData.city || "",
region: location.region || candidate?.region || "",
latitude,
longitude,
displayLatitude: latitude,
displayLongitude: longitude,
operator: context?.operator || existingData.operator || location.operator || "",
vendor: context?.vendor || existingData.vendor || "",
capacity_value: context?.capacity_value ?? existingData.capacity_value,
capacity_unit: context?.capacity_unit ?? existingData.capacity_unit,
rank: context?.rank ?? existingData.rank,
gpu_count: context?.gpu_count ?? existingData.gpu_count,
gpu_type: context?.gpu_type ?? existingData.gpu_type,
cores: context?.cores ?? existingData.cores,
power: context?.power ?? existingData.power,
updated_at: new Date().toISOString(),
status: "observed",
location_precision: location.precision || candidate?.precision || "city",
location_confidence: location.confidence ?? candidate?.confidence ?? null,
location_source: location.location_source || candidate?.source || "manual_selection",
location_source_note: location.location_source_note || candidate?.source_note || "",
location_verified_at: location.verified_at || new Date().toISOString(),
matched_location_name:
location.matched_location_name ||
candidate?.matched_location_name ||
candidate?.display_name ||
"",
needs_confirmation: location.needs_confirmation === true,
is_estimated: false,
estimated_reason: location.estimated_reason || "",
data_type: "compute_center",
metadata: context?.metadata || existingData.metadata || {},
optimistic_spawn: true,
};
}
export async function spawnSavedComputeCenterLocation(earth, { sourceId, candidate, context, saveResult } = {}) {
clearComputeCenterLocationPreview();
const spawned = buildOptimisticComputeCenterMarkerData({
sourceId,
candidate,
context,
saveResult,
});
if (!spawned) return null;
const currentItems = getComputeCenterMarkers()
.map((marker) => ({ ...(marker.userData || {}) }))
.filter((item) => item.source_id !== sourceId);
currentItems.push(spawned);
const nextItems = spreadComputeCenterPositions(currentItems);
await computeCenterIconLayer.preloadAssets(nextItems);
computeCenterIconLayer.setData(nextItems);
computeCenterIconLayer.attach(earth);
computeCenterIconLayer.setVisible(showComputeCenters);
recomputeComputeCenterCounts(nextItems);
unresolvedComputeCenters = unresolvedComputeCenters.filter((item) => {
const itemSourceId = item?.source_id || item?.id;
return itemSourceId !== sourceId;
});
return {
marker: getComputeCenterMarkers().find((marker) => marker.userData?.source_id === sourceId) || null,
totalCount: getComputeCenterCount(),
supercomputerCount: typeCounts.supercomputer,
gpuClusterCount: typeCounts.gpu_cluster,
typeCounts: { ...typeCounts },
unresolvedCount: unresolvedComputeCenters.length,
unresolved: unresolvedComputeCenters.slice(),
summary: getComputeCenterStatusSummary(),
optimistic: true,
};
}
export function getUnresolvedComputeCenters() {
return unresolvedComputeCenters.slice();
}
// Generic helper used by every entity type that wires the shared
// /collect-location backend pipeline. The endpoint shape (sources, payload
// keys) is domain-specific; the request/response envelope is unified
// (success / candidates / attempted_queries / failure_reason / context).
export async function collectLocationCandidates(endpoint, payload = {}) {
const response = await fetchAdminWriteJson(endpoint, payload);
if (!response.ok) {
const text = await response.text().catch(() => "");
let detail = "";
try {
const parsed = JSON.parse(text);
detail = parsed?.detail?.reason || parsed?.detail?.message || parsed?.detail || "";
} catch {
detail = text;
}
throw new Error(
`Collect location failed: HTTP ${response.status} ${detail}`.trim(),
);
}
return response.json();
}
export async function getComputeCenterLocationCapability({ force = false } = {}) {
if (!computeCenterLocationCapabilityPromise || force) {
computeCenterLocationCapabilityPromise = fetch(LOCATION_CAPABILITY_API, { cache: "no-store" })
.then(async (response) => {
if (!response.ok) {
const text = await response.text().catch(() => "");
return {
enabled: false,
provider: null,
reason: `Web Search 状态检查失败:HTTP ${response.status} ${text}`.trim(),
};
}
const payload = await response.json();
return {
enabled: payload?.enabled === true,
provider: payload?.provider || "",
reason: payload?.reason || "",
};
})
.catch((error) => ({
enabled: false,
provider: null,
reason: `Web Search 状态检查失败:${error?.message || error}`,
}));
}
return computeCenterLocationCapabilityPromise;
}
export async function collectComputeCenterLocation(sourceId, context = {}) {
if (!sourceId) {
throw new Error("sourceId is required");
}
const url = `${COLLECT_LOCATION_API_BASE}/${encodeURIComponent(sourceId)}/collect-location`;
return collectLocationCandidates(url, {
name: context?.name ?? null,
operator: context?.operator ?? null,
site: context?.site ?? null,
organization: context?.organization ?? null,
city: context?.city ?? null,
country: context?.country ?? null,
source: context?.source ?? null,
id: context?.record_id ?? null,
});
}
export async function saveComputeCenterLocation(sourceId, candidate = {}, context = {}) {
if (!sourceId) {
throw new Error("sourceId is required");
}
const latitude = Number(candidate?.latitude);
const longitude = Number(candidate?.longitude);
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) {
throw new Error("candidate latitude/longitude are required");
}
const url = `${COLLECT_LOCATION_API_BASE}/${encodeURIComponent(sourceId)}/location`;
const response = await fetchAdminWriteJson(url, {
source: context?.source ?? null,
name: context?.name ?? candidate?.matched_location_name ?? candidate?.display_name ?? null,
operator: context?.operator ?? null,
site: context?.site ?? null,
city: candidate?.city ?? context?.city ?? null,
country: candidate?.country ?? context?.country ?? null,
latitude,
longitude,
precision: candidate?.precision ?? "city",
confidence: candidate?.confidence ?? null,
location_source: candidate?.source ?? "manual_selection",
source_url: candidate?.source_url ?? null,
source_note: candidate?.source_note ?? null,
raw_payload: candidate || {},
needs_confirmation: false,
verification_status: "verified",
workflow_run_id: context?.workflow_run_id ?? candidate?.workflow_run_id ?? null,
});
if (!response.ok) {
const text = await response.text().catch(() => "");
throw new Error(
`Save compute center location failed: HTTP ${response.status} ${text}`.trim(),
);
}
return response.json();
}
export function toggleComputeCenters(show) {
showComputeCenters = Boolean(show);
computeCenterIconLayer.setVisible(showComputeCenters);
if (!showComputeCenters) {
nationalComputeHubLayer.setVisible(false);
if (nationalHubSynergyGroup) nationalHubSynergyGroup.visible = false;
} else if (nationalHubOverlayActive) {
nationalComputeHubLayer.setVisible(true);
if (nationalHubSynergyGroup) nationalHubSynergyGroup.visible = true;
}
}
export function getShowComputeCenters() {
return showComputeCenters;
}
export async function loadComputeCenters(_scene, earth) {
const generation = ++loadGeneration;
loadController?.abort();
loadController = new AbortController();
const query = new URLSearchParams(computeTopicQuery || {});
if (!query.get("year")) query.delete("year");
const url = computeTopicQuery ? `/api/v1/data-products/compute/facilities?${query}` : PATHS.computeCentersApi;
const separator = url.includes("?") ? "&" : "?";
let response;
try {
response = await fetch(
`${url}${separator}_=${Date.now()}`,
{ cache: "no-store", signal: loadController.signal },
);
} catch (error) {
if (error?.name === "AbortError") {
return { count: 0, stale: true, aborted: true };
}
throw error;
}
if (!response.ok) {
throw new Error(`Compute centers HTTP ${response.status}`);
}
const payload = await response.json();
const features = Array.isArray(payload?.features) ? payload.features : [];
const unresolved = Array.isArray(payload?.unresolved) ? payload.unresolved : [];
const markerData = spreadComputeCenterPositions(
features
.map((feature) => buildComputeCenterMarkerData(feature))
.filter(Boolean),
)
.slice(0, COMPUTE_CENTER_CONFIG.maxRenderedMarkers);
await computeCenterIconLayer.preloadAssets(markerData);
if (generation !== loadGeneration) return {
stale: true, totalCount: getComputeCenterCount(), supercomputerCount: typeCounts.supercomputer, gpuClusterCount: typeCounts.gpu_cluster, typeCounts: { ...typeCounts },
unresolvedCount: unresolvedComputeCenters.length, summary: getComputeCenterStatusSummary(),
};
clearComputeCenterData(earth);
unresolvedComputeCenters = unresolved;
recomputeComputeCenterCounts(markerData);
computeCenterIconLayer.setData(markerData);
computeCenterIconLayer.attach(earth);
computeCenterIconLayer.setVisible(showComputeCenters);
if (computeTopicQuery) window.dispatchEvent(new CustomEvent("earth:compute-topic-data", { detail: payload }));
return {
topicPayload: computeTopicQuery ? payload : null,
totalCount: getComputeCenterCount(),
supercomputerCount: typeCounts.supercomputer,
gpuClusterCount: typeCounts.gpu_cluster,
typeCounts: { ...typeCounts },
unresolvedCount: unresolvedComputeCenters.length,
unresolved: unresolvedComputeCenters.slice(),
summary: getComputeCenterStatusSummary(),
};
}
const NATIONAL_HUB_COLORS = {
eastern_demand: "#a855f7",
western_green: "#14b8a6",
};
const nationalComputeHubLayer = createInteractableLayer({
id: "nationalComputeHubs",
isItemVisible: () => true,
objectType: "compute_center",
renderOrder: COMPUTE_CENTER_RENDER_ORDER + 0.08,
altitudeOffset: COMPUTE_CENTER_CONFIG.altitudeOffset,
pointSize: 42,
atlasCellSize: COMPUTE_CENTER_ATLAS_CELL_SIZE,
colors: {
byKind: NATIONAL_HUB_COLORS,
normal: NATIONAL_HUB_COLORS.western_green,
},
opacity: {
normal: 0.96,
dimmed: 0.5,
hover: 1,
locked: 1,
},
stateScale: {
hover: 1.2,
locked: 1.28,
dimmed: 0.88,
},
pulse: {
enabled: true,
speed: 0.0042,
amplitude: 0.06,
},
icon: {
colorable: false,
badge: ({ marker, item }) => ({
color: NATIONAL_HUB_COLORS[marker?.userData?.hub_role || item?.hub_role] || NATIONAL_HUB_COLORS.western_green,
}),
coordinates: "canvas",
fitSize: 102,
glowBlur: 18,
getSource: () => COMPUTE_CENTER_ICON_SOURCES.national_hub,
},
getPosition: (item) => ({
latitude: item.displayLatitude,
longitude: item.displayLongitude,
}),
getKind: (item) => item.hub_role || "western_green",
getBucketKey: (marker) => `national_hub:${marker.userData?.hub_role || "western_green"}`,
getUserData: (item) => ({
...item,
pulseOffset: Math.random() * Math.PI * 2,
}),
avoidance: SURFACE_AVOIDANCE_PROFILES.city,
cluster: { enabled: false },
});
let nationalHubOverlayActive = false;
let nationalHubSynergyGroup = null;
let nationalHubSynergyMaterial = null;
let nationalHubPulseEntries = [];
let stageLogicalArcGroup = null;
let stageLogicalArcEntries = [];
const _hubWorldVec = new THREE.Vector3();
const _earthCenterVec = new THREE.Vector3();
const _hubNormalVec = new THREE.Vector3();
const _hubViewVec = new THREE.Vector3();
function disposeThreeGroupChildren(group) {
if (!group) return;
for (const child of [...group.children]) {
group.remove(child);
child.geometry?.dispose?.();
if (Array.isArray(child.material)) {
child.material.forEach((m) => m?.dispose?.());
} else {
child.material?.dispose?.();
}
}
}
function buildElevatedArcSegments(
fromLat,
fromLon,
toLat,
toLon,
{
baseOffset = COMPUTE_CENTER_CONFIG.altitudeOffset + 0.08,
peakLift = 4.2,
segments = 36,
startColor = new THREE.Color(0xa855f7),
endColor = new THREE.Color(0x14b8a6),
dashed = false,
} = {},
) {
const vStart = latLonToVector3(fromLat, fromLon, 1).normalize();
const vEnd = latLonToVector3(toLat, toLon, 1).normalize();
const positions = [];
const colors = [];
const tempVec = new THREE.Vector3();
const prevVec = new THREE.Vector3();
const tempColor = new THREE.Color();
const prevColor = new THREE.Color();
for (let i = 0; i <= segments; i += 1) {
const t = i / segments;
tempVec.copy(vStart).lerp(vEnd, t);
if (tempVec.lengthSq() < 1e-6) {
tempVec.set(0, 1, 0);
} else {
tempVec.normalize();
}
const radius = CONFIG.earthRadius + baseOffset + Math.sin(Math.PI * t) * peakLift;
tempVec.multiplyScalar(radius);
tempColor.copy(startColor).lerp(endColor, t);
if (i > 0 && (!dashed || i % 2 === 1)) {
positions.push(prevVec.x, prevVec.y, prevVec.z, tempVec.x, tempVec.y, tempVec.z);
colors.push(prevColor.r, prevColor.g, prevColor.b, tempColor.r, tempColor.g, tempColor.b);
}
prevVec.copy(tempVec);
prevColor.copy(tempColor);
}
return { positions, colors };
}
export function isNationalComputeHubsActive() {
return nationalHubOverlayActive;
}
export function clearNationalComputeHubsOverlay(earth) {
nationalHubOverlayActive = false;
nationalHubPulseEntries = [];
nationalHubSynergyMaterial = null;
if (nationalHubSynergyGroup) {
disposeThreeGroupChildren(nationalHubSynergyGroup);
nationalHubSynergyGroup.parent?.remove?.(nationalHubSynergyGroup);
nationalHubSynergyGroup = null;
}
nationalComputeHubLayer.clearData(earth);
window.dispatchEvent(new CustomEvent("earth:national-hubs-state", { detail: { active: false } }));
}
export async function setNationalComputeHubsOverlay(
earth,
hubs = [],
{ active = true, showSynergyArcs = true } = {},
) {
if (!earth || !active || !Array.isArray(hubs) || !hubs.length) {
clearNationalComputeHubsOverlay(earth);
return { active: false, count: 0 };
}
const markerItems = hubs
.filter((hub) => Number.isFinite(Number(hub?.latitude)) && Number.isFinite(Number(hub?.longitude)))
.map((hub) => {
const lat = Number(hub.latitude);
const lon = Number(hub.longitude);
const isWestern = hub.role === "western_green";
return {
id: hub.id,
source_id: hub.id,
name: hub.name,
name_en: hub.name_en || hub.name,
source: hub.source_id || "ndrc-east-west-2022",
site_type: isWestern ? "data_center" : "gpu_cluster",
hub_role: isWestern ? "western_green" : "eastern_demand",
is_national_hub: true,
country: "CN",
city: hub.name,
region: isWestern ? "西部绿色算力训练枢纽" : "东部热数据推理需求枢纽",
latitude: lat,
longitude: lon,
displayLatitude: lat,
displayLongitude: lon,
operator: "全国一体化算力网络国家枢纽节点",
power: `目标 PUE ≤ ${hub.target_pue}`,
status: "observed",
location_precision: "precise",
needs_confirmation: false,
is_estimated: false,
verification_status: "verified",
location_source_note: `国家枢纽协同关系示意 · ${hub.green_power_note || ""}`.trim(),
paired_hub_ids: Array.isArray(hub.paired_hub_ids) ? hub.paired_hub_ids : [],
data_type: "compute_center",
};
});
await nationalComputeHubLayer.preloadAssets(markerItems);
clearNationalComputeHubsOverlay(earth);
nationalHubOverlayActive = true;
nationalComputeHubLayer.setData(markerItems);
nationalComputeHubLayer.attach(earth);
nationalComputeHubLayer.setVisible(showComputeCenters);
nationalHubSynergyGroup = new THREE.Group();
nationalHubSynergyGroup.name = "national-compute-hubs-synergy";
earth.add(nationalHubSynergyGroup);
const byId = new Map(markerItems.map((item) => [item.id, item]));
if (showSynergyArcs) {
const allPos = [];
const allCol = [];
const seenPairs = new Set();
for (const item of markerItems) {
if (item.hub_role !== "eastern_demand") continue;
for (const peerId of item.paired_hub_ids) {
const peer = byId.get(peerId);
if (!peer) continue;
const pairKey = [item.id, peer.id].sort().join("|");
if (seenPairs.has(pairKey)) continue;
seenPairs.add(pairKey);
const seg = buildElevatedArcSegments(
item.latitude,
item.longitude,
peer.latitude,
peer.longitude,
{
baseOffset: COMPUTE_CENTER_CONFIG.altitudeOffset + 0.06,
peakLift: 4.4,
segments: 40,
startColor: new THREE.Color(0xa855f7),
endColor: new THREE.Color(0x14b8a6),
},
);
allPos.push(...seg.positions);
allCol.push(...seg.colors);
}
}
if (allPos.length) {
const geom = new THREE.BufferGeometry();
geom.setAttribute("position", new THREE.Float32BufferAttribute(allPos, 3));
geom.setAttribute("color", new THREE.Float32BufferAttribute(allCol, 3));
nationalHubSynergyMaterial = new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.72,
depthTest: true,
depthWrite: false,
blending: THREE.AdditiveBlending,
});
const lines = new THREE.LineSegments(geom, nationalHubSynergyMaterial);
lines.renderOrder = COMPUTE_CENTER_RENDER_ORDER + 0.14;
lines.userData = {
relation_kind: "hub_synergy_preview",
label: "国家枢纽协同关系(非实时物理链路)",
};
nationalHubSynergyGroup.add(lines);
}
}
nationalHubPulseEntries = [];
markerItems
.filter((item) => item.hub_role === "western_green")
.forEach((item, index) => {
const localPos = latLonToVector3(
item.latitude,
item.longitude,
CONFIG.earthRadius + COMPUTE_CENTER_CONFIG.altitudeOffset + 0.12,
);
const ringA = createPreviewRingSprite({ color: 0x14b8a6 });
const ringB = createPreviewRingSprite({ color: 0x5eead4 });
ringA.position.copy(localPos);
ringB.position.copy(localPos);
ringA.renderOrder = COMPUTE_CENTER_RENDER_ORDER + 0.16;
ringB.renderOrder = COMPUTE_CENTER_RENDER_ORDER + 0.16;
nationalHubSynergyGroup.add(ringA);
nationalHubSynergyGroup.add(ringB);
nationalHubPulseEntries.push({
localPos,
ringA,
ringB,
phaseOffset: index * 0.24,
});
});
nationalHubSynergyGroup.visible = showComputeCenters;
window.dispatchEvent(
new CustomEvent("earth:national-hubs-state", {
detail: { active: true, count: markerItems.length },
}),
);
return { active: true, count: markerItems.length };
}
function buildElevatedArcPolyline(
fromLat,
fromLon,
toLat,
toLon,
{
baseOffset = COMPUTE_CENTER_CONFIG.altitudeOffset + 0.08,
peakLift = 4.2,
segments = 44,
} = {},
) {
const vStart = latLonToVector3(fromLat, fromLon, 1).normalize();
const vEnd = latLonToVector3(toLat, toLon, 1).normalize();
const pts = [];
const tempVec = new THREE.Vector3();
for (let i = 0; i <= segments; i += 1) {
const t = i / segments;
tempVec.copy(vStart).lerp(vEnd, t);
if (tempVec.lengthSq() < 1e-6) {
tempVec.set(0, 1, 0);
} else {
tempVec.normalize();
}
const radius = CONFIG.earthRadius + baseOffset + Math.sin(Math.PI * t) * peakLift;
pts.push(tempVec.clone().multiplyScalar(radius));
}
return pts;
}
export function clearStageLogicalArcsOverlay() {
stageLogicalArcEntries = [];
if (!stageLogicalArcGroup) return;
disposeThreeGroupChildren(stageLogicalArcGroup);
stageLogicalArcGroup.parent?.remove?.(stageLogicalArcGroup);
stageLogicalArcGroup = null;
}
export function setStageLogicalArcsOverlay(earth, arcs = []) {
clearStageLogicalArcsOverlay();
if (!earth || !Array.isArray(arcs) || !arcs.length) return;
stageLogicalArcGroup = new THREE.Group();
stageLogicalArcGroup.name = "stage-logical-as-routes";
earth.add(stageLogicalArcGroup);
const beforePolylines = [];
const afterPolylines = [];
for (const arc of arcs) {
const fLat = Number(arc?.from_lat);
const fLon = Number(arc?.from_lon);
const tLat = Number(arc?.to_lat);
const tLon = Number(arc?.to_lon);
if (![fLat, fLon, tLat, tLon].every(Number.isFinite)) continue;
const isBefore = arc.phase === "before";
const poly = buildElevatedArcPolyline(fLat, fLon, tLat, tLon, {
baseOffset: COMPUTE_CENTER_CONFIG.altitudeOffset + 0.35,
peakLift: isBefore ? 6.4 : 8.6,
segments: 44,
});
if (isBefore) beforePolylines.push(poly);
else afterPolylines.push(poly);
}
const startedAtMs = typeof performance !== "undefined" ? performance.now() : Date.now();
if (beforePolylines.length) {
const geom = createSurfaceRibbonGeometry(beforePolylines);
const mat = createSurfaceRibbonMaterial({
color: 0x64748b,
glowColor: 0x94a3b8,
halfWidthPx: 2.6,
opacity: 0.68,
pulseSpeed: 0.25,
pulseFreq: 1.5,
pulseIntensity: 0.18,
reveal: 1.0,
additive: false,
});
const mesh = new THREE.Mesh(geom, mat);
mesh.renderOrder = COMPUTE_CENTER_RENDER_ORDER + 0.22;
mesh.raycast = () => {};
stageLogicalArcGroup.add(mesh);
stageLogicalArcEntries.push({ material: mat, startedAtMs, revealDurationMs: 0 });
}
if (afterPolylines.length) {
const geom = createSurfaceRibbonGeometry(afterPolylines);
const mat = createSurfaceRibbonMaterial({
color: 0xf59e0b,
glowColor: 0xfb7185,
halfWidthPx: 4.8,
opacity: 0.94,
pulseSpeed: 0.72,
pulseFreq: 2.4,
pulseIntensity: 0.75,
reveal: 0.0,
additive: true,
});
const mesh = new THREE.Mesh(geom, mat);
mesh.renderOrder = COMPUTE_CENTER_RENDER_ORDER + 0.24;
mesh.raycast = () => {};
stageLogicalArcGroup.add(mesh);
stageLogicalArcEntries.push({ material: mat, startedAtMs, revealDurationMs: 650 });
}
}
export function updateStageLogicalArcsAnimation() {
if (!stageLogicalArcEntries.length) return;
const nowMs = typeof performance !== "undefined" ? performance.now() : Date.now();
const nowSec = nowMs * 0.001;
for (const entry of stageLogicalArcEntries) {
const uniforms = entry.material?.uniforms;
if (!uniforms) continue;
uniforms.uTime.value = nowSec;
if (entry.revealDurationMs > 0) {
const linear = Math.max(0, Math.min(1, (nowMs - entry.startedAtMs) / entry.revealDurationMs));
uniforms.uReveal.value = 1 - Math.pow(1 - linear, 2.2);
}
}
}
export function focusComputeEntityById(earth, entityId) {
if (!entityId) return null;
const targetId = String(entityId);
const allMarkers = [
...(nationalHubOverlayActive ? nationalComputeHubLayer.getMarkers() : []),
...computeCenterIconLayer.getMarkers(),
];
const hit = allMarkers.find((m) => {
const u = m?.userData || {};
return (
String(u.id || "") === targetId ||
String(u.source_id || "") === targetId ||
String(u.name || "") === targetId
);
});
if (!hit?.userData) return null;
const { latitude, longitude, name, hub_role: hubRole } = hit.userData;
const color = hubRole === "western_green" ? 0x14b8a6 : 0xa855f7;
showComputeCenterLocationPreview(earth, { latitude, longitude, color });
return { latitude, longitude, name };
}
function updateNationalHubPulses(camera) {
if (!nationalHubOverlayActive || !nationalHubSynergyGroup?.visible) return;
const now = performance.now();
if (nationalHubSynergyMaterial) {
nationalHubSynergyMaterial.opacity = 0.54 + 0.24 * (0.5 + 0.5 * Math.sin(now * 0.0026));
}
const earthObj = nationalHubSynergyGroup.parent;
if (earthObj && camera) {
_earthCenterVec.setFromMatrixPosition(earthObj.matrixWorld);
}
for (const entry of nationalHubPulseEntries) {
let frontFactor = 1;
if (earthObj && camera) {
_hubWorldVec.copy(entry.localPos).applyMatrix4(earthObj.matrixWorld);
_hubNormalVec.copy(_hubWorldVec).sub(_earthCenterVec).normalize();
_hubViewVec.copy(camera.position).sub(_hubWorldVec).normalize();
const dot = _hubNormalVec.dot(_hubViewVec);
frontFactor = dot > 0.06 ? Math.min(1, (dot - 0.06) / 0.16) : 0;
}
const applyPulse = (ring, offset, maxScale) => {
if (!ring) return;
if (frontFactor <= 0.001) {
ring.visible = false;
return;
}
const progress = (now * 0.00085 + entry.phaseOffset + offset) % 1;
const fadeIn = Math.max(0, Math.min(1, (progress - 0.04) / 0.18));
const fadeOut = 1 - progress;
ring.scale.setScalar(6.8 * (1 + progress * (maxScale - 1)));
ring.material.opacity = 0.46 * fadeIn * fadeOut * frontFactor;
ring.visible = true;
};
applyPulse(entry.ringA, 0, 1.75);
applyPulse(entry.ringB, 0.48, 2.2);
}
}
export function getComputeCenterPointerIntersections(options) {
const baseHits = computeCenterIconLayer.getPointerIntersections(options);
if (!nationalHubOverlayActive || !showComputeCenters) return baseHits;
const hubHits = nationalComputeHubLayer.getPointerIntersections(options);
return [...hubHits, ...baseHits];
}
export function updateComputeCenterVisualState(lockedObjectType, lockedObject, camera) {
updateComputeCenterLocationPreview();
updateNationalHubPulses(camera);
updateStageLogicalArcsAnimation();
if (nationalHubOverlayActive) {
nationalComputeHubLayer.updateVisualState(lockedObjectType, lockedObject, camera);
}
computeCenterIconLayer.updateVisualState(lockedObjectType, lockedObject, camera);
}
export function applyComputeCenterLegendFilter() { computeCenterIconLayer.refreshFilter(); }