Compare commits

..

4 Commits

Author SHA1 Message Date
rayd1o
4b8feeb87e release: bump version to 0.75.3
Some checks failed
ci / backend (push) Has been cancelled
ci / frontend (push) Has been cancelled
release / images (push) Has been cancelled
ci / delivery (push) Has been cancelled
2026-09-27 09:30:06 +08:00
rayd1o
a2025dbfe0 release: bump version to 0.75.2
Some checks failed
ci / backend (push) Has been cancelled
ci / frontend (push) Has been cancelled
release / images (push) Has been cancelled
ci / delivery (push) Has been cancelled
2026-09-25 02:03:53 +08:00
rayd1o
003b316d42 release: bump version to 0.75.1
Some checks failed
ci / backend (push) Has been cancelled
ci / frontend (push) Has been cancelled
ci / delivery (push) Has been cancelled
release / images (push) Has been cancelled
2026-09-25 00:16:30 +08:00
rayd1o
0c40764c58 feat: configure compute comparisons and restore adaptive globe dragging
Some checks failed
ci / backend (push) Has been cancelled
ci / frontend (push) Has been cancelled
ci / delivery (push) Has been cancelled
2026-09-24 22:59:55 +08:00
87 changed files with 3231 additions and 882 deletions

View File

@@ -113,6 +113,9 @@ behavior and document the compatibility note in `docs/harness-audit.md` or
## Operating Mode
- Default to acting directly when the user gives a clear task.
- For authorized multi-agent work, follow the Coding Agent Model Strategy in
`rules.md` workflow: Sol for implementation, Luna for bounded supporting work,
and Astra for complex reasoning; the main agent owns final verification.
- Ask before acting only when the missing decision is risky, cannot be
discovered from repository context, and no conservative assumption is safe.
- Read relevant files before editing.

View File

@@ -17,6 +17,7 @@ are the source of detail for specific subsystems.
| `deploy/helm/planet/` | Helm chart for staging/deployment smoke paths | CI runs helm lint/template when delivery checks are available. |
| `.gitea/workflows/` | CI, release image build, staging deploy workflows | This repository uses Gitea workflow files, not `.github/workflows/`. |
| `planet.sh` | Main local lifecycle script | Owns init/start/restart/stop/health/log/createuser/destroy. |
| `planet.cmd` and `scripts/windows/` | Portable Windows entry, bound desktop launcher generation, and WSL restart bridge | Delegates service lifecycle to `planet.sh`; Windows and isolated WSL regression tests live under `scripts/harness/`. |
## Runtime Entry Points

View File

@@ -1 +1 @@
0.75.0
0.75.3

View File

@@ -1,25 +1,38 @@
"""Read-only compute topic: independent macro observations and facility samples."""
"""Compute observations, administrator configuration and independent facility samples."""
from datetime import UTC, datetime
from typing import Literal
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import and_, case, func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.visualization import convert_compute_centers_to_geojson
from app.core.earth_geography_policy import display_country
from app.core.enums import UserRole
from app.core.security import get_current_user
from app.db.session import get_db
from app.models.collected_data import CollectedData
from app.models.data_snapshot import DataSnapshot
from app.services.compute_center_locations import refresh_compute_center_location_cache
from app.models.user import User
from app.schemas.compute_configuration import (
ComputeConfiguration,
ComputeConfigurationReset,
ComputeConfigurationWrite,
)
from app.services.compute_catalog import (
PARTICIPANTS,
participant_members,
source_country_names,
source_country_participants,
)
from app.services.compute_center_locations import refresh_compute_center_location_cache
from app.services.compute_configuration import (
DEFAULT_CONFIGURATION,
configuration_response,
publish_configuration,
read_configuration,
)
from app.services.compute_history import compute_history
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from sqlalchemy import and_, case, func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
router = APIRouter()
SOURCES = ("top500", "epoch_ai_gpu")
@@ -38,10 +51,60 @@ def selected_countries(countries: str) -> list[str]:
@router.get("/series")
async def get_series(
response: Response,
countries: str = "CN,US",
mode: Literal["global_share", "bilateral_share", "absolute"] = "global_share",
db: AsyncSession = Depends(get_db),
):
return compute_history(selected_countries(countries), mode)
codes = selected_countries(countries)
envelope = await read_configuration(db)
response.headers["Cache-Control"] = "no-store"
result = compute_history(codes, mode, ComputeConfiguration.model_validate(envelope["config"]))
result.update(
version=envelope["revision"],
provenance="bundled_reports" if envelope["is_default"] else "admin_curated_reports",
)
return result
async def configuration_admin(user: User = Depends(get_current_user)) -> User:
if user.role not in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
raise HTTPException(403, "Administrator access required")
return user
@router.get("/configuration")
async def get_configuration(
response: Response,
_actor: User = Depends(configuration_admin),
db: AsyncSession = Depends(get_db),
):
response.headers["Cache-Control"] = "no-store"
return configuration_response(await read_configuration(db))
@router.put("/configuration")
async def update_configuration(
payload: ComputeConfigurationWrite,
actor: User = Depends(configuration_admin),
db: AsyncSession = Depends(get_db),
):
envelope = await publish_configuration(
db, revision=payload.revision, config=payload.config, actor=actor,
)
return configuration_response(envelope)
@router.post("/configuration/reset")
async def reset_configuration(
payload: ComputeConfigurationReset,
actor: User = Depends(configuration_admin),
db: AsyncSession = Depends(get_db),
):
envelope = await publish_configuration(
db, revision=payload.revision, config=DEFAULT_CONFIGURATION, actor=actor, reset=True,
)
return configuration_response(envelope)
async def sample_query(db: AsyncSession, countries: list[str], year: int | None):

View File

@@ -0,0 +1,94 @@
"""Validated, source-backed observations for the compute comparison cards."""
from datetime import date
from typing import Annotated, Literal, Self
from app.services.compute_catalog import COUNTRY_PARTICIPANTS
from pydantic import BaseModel, ConfigDict, Field, HttpUrl, field_validator, model_validator
Year = Annotated[int, Field(strict=True, ge=2000, le=2100)]
Value = Annotated[float, Field(strict=True, allow_inf_nan=False, ge=0, le=1e12)]
Identifier = Annotated[str, Field(min_length=1, max_length=80, pattern=r"^[a-zA-Z0-9_-]+$")]
Text = Annotated[str, Field(min_length=1, max_length=500)]
class ConfigurationModel(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
class ComputeSource(ConfigurationModel):
id: Identifier
title: Text
url: HttpUrl
publisher: Text
report_year: Year
published_at: date | None = None
locator: Text
@field_validator("url")
@classmethod
def public_reference(cls, value: HttpUrl) -> HttpUrl:
if value.username or value.password or len(str(value)) > 2000:
raise ValueError("Use a report URL without credentials (maximum 2000 characters)")
return value
class ComputeObservation(ConfigurationModel):
year: Year
metric: Literal["global_share", "absolute"]
source_id: Identifier
values: dict[str, Value] = Field(min_length=1, max_length=250)
@model_validator(mode="after")
def comparable_values(self) -> Self:
if any(code not in COUNTRY_PARTICIPANTS for code in self.values):
raise ValueError(
"Use countries from the canonical compute catalog, not regional totals"
)
if self.metric == "global_share" and sum(self.values.values()) > 100.000001:
raise ValueError("Global shares for one year must total at most 100 percent")
return self
class InnovationObservation(ConfigurationModel):
year: Year
value: Annotated[float, Field(strict=True, allow_inf_nan=False, ge=-100, le=100)]
source_id: Identifier
class ComputeConfiguration(ConfigurationModel):
reviewed_at: date
sources: list[ComputeSource] = Field(max_length=200)
observations: list[ComputeObservation] = Field(max_length=202)
innovation: list[InnovationObservation] = Field(max_length=101)
@model_validator(mode="after")
def consistent_evidence(self) -> Self:
ids = [source.id for source in self.sources]
if len(ids) != len(set(ids)):
raise ValueError("Report source IDs must be unique")
keys = [(row.metric, row.year) for row in self.observations]
if len(keys) != len(set(keys)):
raise ValueError("Each metric/year may have only one observation")
years = [row.year for row in self.innovation]
if len(years) != len(set(years)):
raise ValueError("Innovation observation years must be unique")
sources = {source.id: source for source in self.sources}
for row in [*self.observations, *self.innovation]:
source = sources.get(row.source_id)
if source is None:
raise ValueError(f"Missing report source: {row.source_id}")
if row.year > source.report_year:
raise ValueError("Observation year must not be after its report year")
if self.reviewed_at > date.today():
raise ValueError("Review date must not be in the future")
return self
class ComputeConfigurationWrite(ConfigurationModel):
revision: str = Field(min_length=1, max_length=80)
config: ComputeConfiguration
class ComputeConfigurationReset(ConfigurationModel):
revision: str = Field(min_length=1, max_length=80)

View File

@@ -18,7 +18,6 @@ from app.services.business_logs import emit_business_log, exception_context
from app.services.collectors.base import BaseCollector
from app.services.collectors.downloads import DownloadHTTPStatusError, ResumableFileDownloader
logger = get_logger(__name__, service="collector")
ACTIVE_GROUP = "active"
FALLBACK_GROUPS = (
@@ -39,6 +38,7 @@ FALLBACK_GROUPS = (
)
FETCH_RETRY_ATTEMPTS = 3
FETCH_RETRY_BASE_DELAY_SECONDS = 0.8
CELESTRAK_CACHE_TTL_SECONDS = 2 * 60 * 60
CELESTRAK_NOT_UPDATED_MARKER = "GP data has not updated since your last successful"
@@ -51,6 +51,8 @@ class CelesTrakTLECollector(BaseCollector):
_downloader = ResumableFileDownloader(
cache_namespace="celestrak",
default_accept="application/json",
preflight_head=False,
cache_ttl_seconds=CELESTRAK_CACHE_TTL_SECONDS,
)
@property
@@ -195,7 +197,9 @@ class CelesTrakTLECollector(BaseCollector):
if not is_final_attempt:
await asyncio.sleep(FETCH_RETRY_BASE_DELAY_SECONDS * attempt)
raise RuntimeError(f"CelesTrak active satellite download failed after retries: {last_error}")
raise RuntimeError(
f"CelesTrak active satellite download failed after retries: {last_error}"
)
async def _fetch_fallback_groups(
self,
@@ -226,25 +230,25 @@ class CelesTrakTLECollector(BaseCollector):
try:
for group in FALLBACK_GROUPS:
group_url = self._group_url(group)
cached_path = self._downloader.get_cached_file(
group_url,
".json",
validate_existing=self._validate_json_file,
)
if cached_path is not None:
body_path = cached_path
else:
try:
body_path = await self._downloader.download_file(
client,
group_url,
extension=".json",
accept="application/json",
validate_existing=self._validate_json_file,
)
except DownloadHTTPStatusError as exc:
if not self._is_not_updated_response(exc):
raise RuntimeError(f"CelesTrak fallback group '{group}' download failed: {exc}") from exc
try:
body_path = await self._downloader.download_file(
client,
group_url,
extension=".json",
accept="application/json",
validate_existing=self._validate_json_file,
)
except DownloadHTTPStatusError as exc:
if not self._is_not_updated_response(exc):
raise RuntimeError(
f"CelesTrak fallback group '{group}' download failed: {exc}"
) from exc
body_path = self._downloader.get_cached_file(
group_url,
".json",
validate_existing=self._validate_json_file,
)
if body_path is None:
raise RuntimeError(
f"CelesTrak fallback group '{group}' has not updated and no local cached copy is available"
) from exc
@@ -348,13 +352,13 @@ class CelesTrakTLECollector(BaseCollector):
commit=True,
)
@staticmethod
def _validate_json_file(path: Path) -> bool:
@classmethod
def _validate_json_file(cls, path: Path) -> bool:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
cls._load_active_payload(path)
except RuntimeError:
return False
return isinstance(data, list)
return True
async def _log_parse_failure(self, exc: Exception) -> None:
await emit_business_log(
@@ -375,7 +379,8 @@ class CelesTrakTLECollector(BaseCollector):
),
)
def _load_active_payload(self, path: Path) -> List[Dict[str, Any]]:
@staticmethod
def _load_active_payload(path: Path) -> List[Dict[str, Any]]:
try:
raw = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError, UnicodeDecodeError) as exc:
@@ -391,7 +396,9 @@ class CelesTrakTLECollector(BaseCollector):
else:
invalid_count += 1
if invalid_count:
raise RuntimeError(f"CelesTrak active payload contains {invalid_count} invalid record(s)")
raise RuntimeError(
f"CelesTrak active payload contains {invalid_count} invalid record(s)"
)
if not records:
raise RuntimeError("CelesTrak active payload contains no satellite records")
return records

View File

@@ -12,7 +12,6 @@ from typing import Any, Awaitable, Callable
import httpx
ProgressCallback = Callable[[int, int | None], Awaitable[None]]
ValidateCallback = Callable[[Path], bool]
@@ -52,10 +51,14 @@ class ResumableFileDownloader:
user_agent: str = "Planet-Intelligence-System/1.0 (Python/collector)",
default_accept: str = "*/*",
cache_root: Path | None = None,
preflight_head: bool = True,
cache_ttl_seconds: float = 0,
) -> None:
self._cache_dir = (cache_root or default_download_cache_root()) / cache_namespace
self._user_agent = user_agent
self._default_accept = default_accept
self._preflight_head = preflight_head
self._cache_ttl_seconds = cache_ttl_seconds
@staticmethod
def _cache_key(url: str) -> str:
@@ -93,8 +96,9 @@ class ResumableFileDownloader:
if not meta_path.exists():
return {}
try:
return json.loads(meta_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
data = json.loads(meta_path.read_text(encoding="utf-8"))
return data if isinstance(data, dict) else {}
except json.JSONDecodeError, OSError:
return {}
@staticmethod
@@ -111,20 +115,25 @@ class ResumableFileDownloader:
return last_modified == str(meta.get("last_modified") or "").strip()
return True
@staticmethod
def _response_info(response: httpx.Response) -> dict[str, Any]:
# httpx yields decoded bytes; encoded Content-Length cannot validate them.
raw_length = response.headers.get("content-length")
encoded = response.headers.get("content-encoding", "identity") != "identity"
return {
"etag": response.headers.get("etag"),
"last_modified": response.headers.get("last-modified"),
"content_length": int(raw_length) if raw_length and not encoded else None,
"accept_ranges": (response.headers.get("accept-ranges") or "").lower(),
}
async def fetch_remote_info(self, client: httpx.AsyncClient, url: str) -> dict[str, Any]:
try:
response = await client.head(url)
if response.status_code >= 400:
return {}
content_length_raw = response.headers.get("content-length")
content_length = int(content_length_raw) if content_length_raw else None
return {
"etag": response.headers.get("etag"),
"last_modified": response.headers.get("last-modified"),
"content_length": content_length,
"accept_ranges": (response.headers.get("accept-ranges") or "").lower(),
}
except (httpx.HTTPError, ValueError):
return self._response_info(response)
except httpx.HTTPError, ValueError:
return {}
async def download_file(
@@ -139,14 +148,24 @@ class ResumableFileDownloader:
) -> Path:
self._cache_dir.mkdir(parents=True, exist_ok=True)
final_path, part_path, meta_path = self._cache_paths(url, extension)
cached_path = self.get_cached_file(url, extension, validate_existing=validate_existing)
if cached_path and 0 <= time.time() - cached_path.stat().st_mtime < self._cache_ttl_seconds:
size = cached_path.stat().st_size
if progress_callback:
await progress_callback(size, size)
return cached_path
meta = self._load_meta(meta_path)
remote = await self.fetch_remote_info(client, url)
remote = await self.fetch_remote_info(client, url) if self._preflight_head else {}
expected_size = remote.get("content_length")
if final_path.exists():
local_size = final_path.stat().st_size
size_match = expected_size is None or local_size == expected_size
if self._validators_match(meta, remote) and size_match:
if (
(remote.get("etag") or remote.get("last_modified"))
and self._validators_match(meta, remote)
and size_match
):
if validate_existing and not validate_existing(final_path):
final_path.unlink(missing_ok=True)
else:
@@ -181,9 +200,13 @@ class ResumableFileDownloader:
headers["If-Range"] = str(remote.get("last_modified"))
async with client.stream("GET", url, headers=headers) as response:
if response.status_code == 304 and final_path.exists():
if progress_callback and expected_size and expected_size > 0:
await progress_callback(expected_size, expected_size)
if response.status_code == 304:
if cached_path is None:
raise RuntimeError(f"Server returned 304 without a valid local cache for {url}")
final_path.touch()
size = final_path.stat().st_size
if progress_callback:
await progress_callback(size, size)
return final_path
if response.status_code >= 400:
body = (await response.aread()).decode("utf-8", errors="replace")
@@ -194,12 +217,16 @@ class ResumableFileDownloader:
else:
mode = "wb"
resume_from = 0
remote = self._response_info(response)
expected_size = remote.get("content_length")
downloaded = resume_from
last_emit_bytes = 0
last_emit_time = time.monotonic()
min_emit_bytes = (
max(expected_size // 150, 512 * 1024) if expected_size and expected_size > 0 else 1024 * 1024
max(expected_size // 150, 512 * 1024)
if expected_size and expected_size > 0
else 1024 * 1024
)
with part_path.open(mode) as f:
@@ -230,6 +257,10 @@ class ResumableFileDownloader:
f"Resumable download incomplete for {url}: expected={expected_size}, got={final_size}"
)
# Never replace the last good payload with an HTML error or invalid JSON.
if validate_existing and not validate_existing(part_path):
part_path.unlink(missing_ok=True)
raise RuntimeError(f"Downloaded file validation failed for {url}")
part_path.replace(final_path)
self._save_meta(
meta_path,
@@ -242,9 +273,6 @@ class ResumableFileDownloader:
},
)
if validate_existing and not validate_existing(final_path):
raise RuntimeError(f"Downloaded file validation failed for {url}")
if progress_callback and expected_size and expected_size > 0:
await progress_callback(expected_size, expected_size)

View File

@@ -0,0 +1,99 @@
"""Database overrides with bundled defaults and atomic, revision-checked publishing."""
import hashlib
from pathlib import Path
from uuid import uuid4
from app.core.request_context import get_request_id
from app.models.system_log import AuditLog
from app.models.system_setting import SystemSetting
from app.models.user import User
from app.schemas.compute_configuration import ComputeConfiguration
from app.services.compute_catalog import COUNTRY_CATALOG
from fastapi import HTTPException
from sqlalchemy import select
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
CATEGORY = "compute_comparison"
DEFAULT_PATH = Path(__file__).with_name("compute_history_defaults.json")
DEFAULT_CONFIGURATION = ComputeConfiguration.model_validate_json(DEFAULT_PATH.read_text())
DEFAULT_REVISION = hashlib.sha256(DEFAULT_PATH.read_bytes()).hexdigest()
def default_envelope() -> dict:
return {
"config": DEFAULT_CONFIGURATION.model_dump(mode="json"),
"revision": DEFAULT_REVISION,
"is_default": True,
}
async def read_configuration(db: AsyncSession) -> dict:
record = (
await db.execute(select(SystemSetting).where(SystemSetting.category == CATEGORY))
).scalar_one_or_none()
return dict(record.payload) if record else default_envelope()
def configuration_response(envelope: dict) -> dict:
return {
**envelope,
"countries": [
{key: country[key] for key in ("code", "name", "name_en")}
for country in COUNTRY_CATALOG
],
}
async def publish_configuration(
db: AsyncSession,
*,
revision: str,
config: ComputeConfiguration,
actor: User,
reset: bool = False,
) -> dict:
# The unique category plus row lock also serializes concurrent first writes.
await db.execute(
insert(SystemSetting)
.values(category=CATEGORY, payload=default_envelope())
.on_conflict_do_nothing(index_elements=[SystemSetting.category])
)
record = (
await db.execute(
select(SystemSetting).where(SystemSetting.category == CATEGORY).with_for_update()
)
).scalar_one()
if record.payload["revision"] != revision:
await db.rollback()
raise HTTPException(409, "Configuration changed. Reload before saving your edits.")
envelope = (
default_envelope()
if reset
else {
"config": config.model_dump(mode="json"),
"revision": uuid4().hex,
"is_default": reset,
}
)
before = record.payload
if reset:
await db.delete(record)
else:
record.payload = envelope
# Audit and configuration commit together: a published edit must be attributable.
db.add(
AuditLog(
actor_id=actor.id,
actor_name=actor.username,
action="compute_comparison.reset" if reset else "compute_comparison.update",
target_type="system_setting",
target_id=CATEGORY,
result="success",
request_id=get_request_id(),
details={"before": before, "after": envelope},
)
)
await db.commit()
return envelope

View File

@@ -1,74 +1,16 @@
"""Versioned, source-backed annual observations for compute comparisons."""
from copy import deepcopy
from datetime import date
from app.schemas.compute_configuration import ComputeConfiguration
from app.services.compute_catalog import (
CATALOG,
DEFAULT_PARTICIPANTS,
PARTICIPANTS,
participant_members,
)
HISTORY_VERSION = "compute-history-2026-09-22"
HISTORY_YEARS = tuple(range(2020, 2027))
REPORTS = {
"caict-2021": {
"title": "中国算力发展指数白皮书(2021)",
"url": "https://www.caict.ac.cn/kxyj/qwfb/bps/202109/P020210918521091309950.pdf",
"publisher": "中国信息通信研究院",
"report_year": 2021,
"published_at": None,
"locator": "正文 11 页图 4(2020 年全球份额)",
},
"caict-2022": {
"title": "中国算力发展指数白皮书(2022)",
"url": "https://www.caict.ac.cn/kxyj/qwfb/bps/202211/P020221105727522653499.pdf",
"publisher": "中国信息通信研究院",
"report_year": 2022,
"published_at": None,
"locator": "正文 13 页图 5(2021 年全球份额)",
},
"caict-2023": {
"title": "中国算力发展指数白皮书(2023)",
"url": "https://www.caict.ac.cn/kxyj/qwfb/bps/202309/P020240326630458153765.pdf",
"publisher": "中国信息通信研究院",
"report_year": 2023,
"published_at": None,
"locator": "正文 13 页图 5(2022 年全球份额);16 页(中国总规模)",
},
"caict-2024": {
"title": "先进计算暨算力发展指数蓝皮书(2024年)",
"url": "https://www.caict.ac.cn/kxyj/qwfb/bps/202501/P020250117503621662777.pdf",
"publisher": "中国信息通信研究院",
"report_year": 2024,
"published_at": None,
"locator": "正文 10 页图 3(2023 年全球份额);12 页(中国总规模)",
},
"innovation-2026": {
"title": "全球人工智能创新指数报告 2026:科技日报报道",
"url": "https://finance.sina.com.cn/tech/roll/2026-07-17/doc-iniickaz8224252.shtml",
"publisher": "科技日报(新浪转载)",
"published_at": "2026-07-17",
"publication_year": 2026,
"locator": "2023–2025 年美国减中国的指数分差",
},
}
GLOBAL_SHARES = {
year: {"US": us, "CN": cn, "JP": jp}
for year, (us, cn, jp) in {
2020: (36, 31, 6), 2021: (34, 33, 5),
2022: (34, 33, 4), 2023: (41, 31, 4),
}.items()
}
ABSOLUTE_COMPUTE = {2022: {"CN": 302}, 2023: {"CN": 435}}
GAPS = {2023: 22.02, 2024: 19.96, 2025: 17.95}
def _observations(mode: str, year: int) -> dict[str, float | int]:
return (GLOBAL_SHARES if mode in {"global_share", "bilateral_share"} else ABSOLUTE_COMPUTE).get(
year, {}
)
from app.services.compute_configuration import DEFAULT_CONFIGURATION
def _participant_value(
@@ -85,7 +27,11 @@ def _participant_value(
if missing:
return None, coverage
if mode == "bilateral_share":
if not set(members).issubset({"CN", "US"}) or not {"CN", "US"}.issubset(observations):
if (
not set(members).issubset({"CN", "US"})
or not {"CN", "US"}.issubset(observations)
or observations["US"] + observations["CN"] <= 0
):
coverage.update(
{
"status": "incompatible",
@@ -96,7 +42,8 @@ def _participant_value(
return (
round(
sum(observations[member] for member in members)
/ (observations["US"] + observations["CN"]) * 100,
/ (observations["US"] + observations["CN"])
* 100,
2,
),
coverage,
@@ -104,16 +51,32 @@ def _participant_value(
return sum(observations[member] for member in members), coverage
def compute_history(countries: list[str], mode: str = "global_share") -> dict:
def compute_history(
countries: list[str],
mode: str = "global_share",
config: ComputeConfiguration | None = None,
) -> dict:
"""Aggregate only fully covered, same-year compatible observations."""
config = config if config is not None else DEFAULT_CONFIGURATION
metric = "global_share" if mode == "bilateral_share" else mode
annual = {row.year: row for row in config.observations if row.metric == metric}
gaps = {row.year: row for row in config.innovation}
observed_years = [row.year for row in config.observations] + list(gaps)
years = tuple(
range(
min(observed_years, default=date.today().year),
max([date.today().year, *observed_years]) + 1,
)
)
members_by_participant = participant_members(countries)
rows = []
for year in HISTORY_YEARS:
observations = _observations(mode, year)
for year in years:
record = annual.get(year)
observations = record.values if record else {}
values, coverage = {}, {}
for code, members in members_by_participant.items():
values[code], coverage[code] = _participant_value(members, observations, mode)
evidence_id = f"caict-{year + 1}" if observations else None
evidence_id = record.source_id if record else None
rows.append(
{"year": year, "values": values, "coverage": coverage, "evidence_id": evidence_id}
)
@@ -121,11 +84,11 @@ def compute_history(countries: list[str], mode: str = "global_share") -> dict:
selected_members = {member for members in members_by_participant.values() for member in members}
has_innovation_scope = {"CN", "US"}.issubset(selected_members)
return {
"version": HISTORY_VERSION,
"provenance": "reviewed_official_reports",
"reviewed_at": "2026-09-22",
"version": f"compute-history-{config.reviewed_at}",
"provenance": "curated_reports",
"reviewed_at": config.reviewed_at.isoformat(),
"time_basis": "retrospective",
"years": HISTORY_YEARS,
"years": years,
"mode": mode,
"unit": "EFlop/s (FP32)" if mode == "absolute" else "%",
"denominator": {"global_share": "global", "bilateral_share": "US+CN", "absolute": None}[
@@ -138,18 +101,22 @@ def compute_history(countries: list[str], mode: str = "global_share") -> dict:
"innovation": [
{
"year": year,
"value": GAPS.get(year) if has_innovation_scope else None,
"evidence_id": "innovation-2026" if year in GAPS and has_innovation_scope else None,
"value": gaps[year].value if year in gaps and has_innovation_scope else None,
"evidence_id": gaps[year].source_id
if year in gaps and has_innovation_scope
else None,
}
for year in HISTORY_YEARS
for year in years
],
"evidence": deepcopy(REPORTS),
"evidence": {
source.id: source.model_dump(mode="json", exclude={"id"}) for source in config.sources
},
"innovation_scope": ["US", "CN"],
"limitations": [
"公开设施样本不代表全国总算力;FP64、FP16 与 FP32 不可直接相加。",
"区域值只在全部成员有同年、同指标、可比较观测时汇总;缺失成员时返回 null。",
"全球份额不从中美或其他局部成员反推剩余地区。",
"年度资料来自信通院官方报告,观测年与报告年份分列;跨年方法可比性仍需核验。",
"年度资料按已配置报告引用展示,观测年与报告年份分列;跨年方法可比性仍需核验。",
"创新分差为美国减中国;只有分差,不反推单国得分,不证明算力与创新的因果关系。",
],
}

View File

@@ -0,0 +1,125 @@
{
"reviewed_at": "2026-09-22",
"sources": [
{
"id": "caict-2021",
"title": "中国算力发展指数白皮书(2021)",
"url": "https://www.caict.ac.cn/kxyj/qwfb/bps/202109/P020210918521091309950.pdf",
"publisher": "中国信息通信研究院",
"report_year": 2021,
"published_at": null,
"locator": "正文 11 页图 4(2020 年全球份额)"
},
{
"id": "caict-2022",
"title": "中国算力发展指数白皮书(2022)",
"url": "https://www.caict.ac.cn/kxyj/qwfb/bps/202211/P020221105727522653499.pdf",
"publisher": "中国信息通信研究院",
"report_year": 2022,
"published_at": null,
"locator": "正文 13 页图 5(2021 年全球份额)"
},
{
"id": "caict-2023",
"title": "中国算力发展指数白皮书(2023)",
"url": "https://www.caict.ac.cn/kxyj/qwfb/bps/202309/P020240326630458153765.pdf",
"publisher": "中国信息通信研究院",
"report_year": 2023,
"published_at": null,
"locator": "正文 13 页图 5(2022 年全球份额);16 页(中国总规模)"
},
{
"id": "caict-2024",
"title": "先进计算暨算力发展指数蓝皮书(2024年)",
"url": "https://www.caict.ac.cn/kxyj/qwfb/bps/202501/P020250117503621662777.pdf",
"publisher": "中国信息通信研究院",
"report_year": 2024,
"published_at": null,
"locator": "正文 10 页图 3(2023 年全球份额);12 页(中国总规模)"
},
{
"id": "innovation-2026",
"title": "全球人工智能创新指数报告 2026:科技日报报道",
"url": "https://finance.sina.com.cn/tech/roll/2026-07-17/doc-iniickaz8224252.shtml",
"publisher": "科技日报(新浪转载)",
"report_year": 2026,
"published_at": "2026-07-17",
"locator": "2023–2025 年美国减中国的指数分差"
}
],
"observations": [
{
"year": 2020,
"metric": "global_share",
"source_id": "caict-2021",
"values": {
"US": 36,
"CN": 31,
"JP": 6
}
},
{
"year": 2021,
"metric": "global_share",
"source_id": "caict-2022",
"values": {
"US": 34,
"CN": 33,
"JP": 5
}
},
{
"year": 2022,
"metric": "global_share",
"source_id": "caict-2023",
"values": {
"US": 34,
"CN": 33,
"JP": 4
}
},
{
"year": 2023,
"metric": "global_share",
"source_id": "caict-2024",
"values": {
"US": 41,
"CN": 31,
"JP": 4
}
},
{
"year": 2022,
"metric": "absolute",
"source_id": "caict-2023",
"values": {
"CN": 302
}
},
{
"year": 2023,
"metric": "absolute",
"source_id": "caict-2024",
"values": {
"CN": 435
}
}
],
"innovation": [
{
"year": 2023,
"value": 22.02,
"source_id": "innovation-2026"
},
{
"year": 2024,
"value": 19.96,
"source_id": "innovation-2026"
},
{
"year": 2025,
"value": 17.95,
"source_id": "innovation-2026"
}
]
}

View File

@@ -0,0 +1,218 @@
"""Request-level regressions for quota-limited satellite downloads."""
import gzip
import json
import os
import time
from unittest.mock import AsyncMock
import httpx
import pytest
from app.services.collectors.celestrak import CelesTrakTLECollector, CELESTRAK_CACHE_TTL_SECONDS
from app.services.collectors.downloads import ResumableFileDownloader
URL = "https://celestrak.example/gp.php?GROUP=active&FORMAT=json"
def setup_collector(monkeypatch, tmp_path, handler):
collector = CelesTrakTLECollector()
collector._resolved_url = "https://celestrak.example/gp.php"
monkeypatch.setattr(collector._downloader, "_cache_dir", tmp_path)
monkeypatch.setattr(collector, "update_phase_progress", AsyncMock())
monkeypatch.setattr("app.services.collectors.celestrak.emit_business_log", AsyncMock())
monkeypatch.setattr("app.services.collectors.celestrak.asyncio.sleep", AsyncMock())
original_client = httpx.AsyncClient
monkeypatch.setattr(
"app.services.collectors.celestrak.httpx.AsyncClient",
lambda **kwargs: original_client(transport=httpx.MockTransport(handler), **kwargs),
)
return collector
def expire(path):
old = time.time() - CELESTRAK_CACHE_TTL_SECONDS - 1
os.utime(path, (old, old))
@pytest.mark.asyncio
async def test_celestrak_uses_one_get_and_revalidates_after_cache_expiry(monkeypatch, tmp_path):
requests = []
def handler(request):
requests.append(request)
assert request.method == "GET", "HEAD consumes this upstream's download allowance"
return httpx.Response(
200, json=[{"NORAD_CAT_ID": len(requests)}], headers={"etag": f'"v{len(requests)}"'}
)
collector = setup_collector(monkeypatch, tmp_path, handler)
assert (await collector.fetch())[0]["NORAD_CAT_ID"] == 1
assert (await collector.fetch())[0]["NORAD_CAT_ID"] == 1
assert len(requests) == 1
path = collector._downloader.cached_file_path(URL, ".json")
expire(path)
assert (await collector.fetch())[0]["NORAD_CAT_ID"] == 2
assert requests[1].headers["if-none-match"] == '"v1"'
@pytest.mark.asyncio
async def test_not_updated_reuses_valid_cache_without_retry_storm(monkeypatch, tmp_path):
requests = []
def handler(request):
requests.append(request.method)
return httpx.Response(
403, text="GP data has not updated since your last successful download"
)
collector = setup_collector(monkeypatch, tmp_path, handler)
path = collector._downloader.cached_file_path(URL, ".json")
path.write_text('[{"NORAD_CAT_ID":42}]')
expire(path)
assert (await collector.fetch())[0]["NORAD_CAT_ID"] == 42
assert requests == ["GET"]
@pytest.mark.asyncio
async def test_bad_download_does_not_replace_last_good_cache(monkeypatch, tmp_path):
collector = setup_collector(monkeypatch, tmp_path, lambda request: httpx.Response(200, json=[]))
path = collector._downloader.cached_file_path(URL, ".json")
path.write_text('[{"NORAD_CAT_ID":42}]')
expire(path)
with pytest.raises(RuntimeError, match="validation failed"):
await collector.fetch()
assert json.loads(path.read_text()) == [{"NORAD_CAT_ID": 42}]
@pytest.mark.asyncio
async def test_corrupt_cache_is_not_reused_or_conditionally_requested(monkeypatch, tmp_path):
requests = []
def handler(request):
requests.append(request)
return httpx.Response(200, json=[{"NORAD_CAT_ID": 7}])
collector = setup_collector(monkeypatch, tmp_path, handler)
path, _, meta = collector._downloader._cache_paths(URL, ".json")
path.write_text("[]")
meta.write_text('{"etag":"old"}')
assert (await collector.fetch())[0]["NORAD_CAT_ID"] == 7
assert "if-none-match" not in requests[0].headers
@pytest.mark.asyncio
async def test_conditional_304_keeps_payload_and_refreshes_cache_window(tmp_path):
downloader = ResumableFileDownloader(
cache_namespace="test", cache_root=tmp_path, preflight_head=False, cache_ttl_seconds=7200
)
path, _, meta = downloader._cache_paths(URL, ".json")
path.parent.mkdir(parents=True)
path.write_text('[{"NORAD_CAT_ID":42}]')
meta.write_text('{"etag":"v1"}')
expire(path)
requests = []
def handler(request):
requests.append(request)
return httpx.Response(304)
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
for _ in range(2):
await downloader.download_file(
client,
URL,
extension=".json",
validate_existing=CelesTrakTLECollector._validate_json_file,
)
assert len(requests) == 1
assert requests[0].headers["if-none-match"] == "v1"
assert json.loads(path.read_text())[0]["NORAD_CAT_ID"] == 42
@pytest.mark.asyncio
async def test_compressed_get_length_uses_decoded_payload(tmp_path):
raw = json.dumps([{"NORAD_CAT_ID": 42}]).encode()
body = gzip.compress(raw)
downloader = ResumableFileDownloader(
cache_namespace="test", cache_root=tmp_path, preflight_head=False
)
async with httpx.AsyncClient(
transport=httpx.MockTransport(
lambda request: httpx.Response(
200,
content=body,
headers={"content-encoding": "gzip", "content-length": str(len(body))},
)
)
) as client:
path = await downloader.download_file(
client,
URL,
extension=".json",
validate_existing=CelesTrakTLECollector._validate_json_file,
)
assert path.read_bytes() == raw
@pytest.mark.asyncio
async def test_other_collectors_keep_head_and_range_resume(tmp_path):
downloader = ResumableFileDownloader(cache_namespace="test", cache_root=tmp_path)
final, part, meta = downloader._cache_paths(URL, ".bin")
part.parent.mkdir(parents=True)
part.write_bytes(b"abc")
meta.write_text('{"etag":"v1"}')
requests = []
def handler(request):
requests.append(request)
if request.method == "HEAD":
return httpx.Response(
200, headers={"etag": "v1", "accept-ranges": "bytes", "content-length": "6"}
)
assert request.headers["range"] == "bytes=3-"
return httpx.Response(206, content=b"def", headers={"content-range": "bytes 3-5/6"})
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
await downloader.download_file(client, URL, extension=".bin")
assert [r.method for r in requests] == ["HEAD", "GET"]
assert final.read_bytes() == b"abcdef"
@pytest.mark.asyncio
async def test_fallback_group_refreshes_expired_cache(monkeypatch, tmp_path):
requests = []
def handler(request):
requests.append(request)
if request.url.params["GROUP"] == "active":
return httpx.Response(
403, text="GP data has not updated since your last successful download"
)
return httpx.Response(200, json=[{"NORAD_CAT_ID": 99}])
collector = setup_collector(monkeypatch, tmp_path, handler)
monkeypatch.setattr("app.services.collectors.celestrak.FALLBACK_GROUPS", ("starlink",))
path = collector._downloader.cached_file_path(collector._group_url("starlink"), ".json")
path.write_text('[{"NORAD_CAT_ID":42}]')
expire(path)
assert (await collector.fetch())[0]["NORAD_CAT_ID"] == 99
assert [r.method for r in requests] == ["GET", "GET"]
@pytest.mark.asyncio
async def test_generic_cache_without_validators_must_refresh(tmp_path):
downloader = ResumableFileDownloader(cache_namespace="test", cache_root=tmp_path)
path = downloader.cached_file_path(URL, ".json")
path.parent.mkdir(parents=True)
path.write_text("[]")
requests = []
def handler(request):
requests.append(request.method)
return httpx.Response(200, content=b"[1]" if request.method == "GET" else b"")
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
await downloader.download_file(client, URL, extension=".json")
assert requests == ["HEAD", "GET"]
assert path.read_text() == "[1]"

View File

@@ -0,0 +1,222 @@
from copy import deepcopy
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from app.api.v1.compute_intelligence import configuration_admin, get_series, router
from app.core.security import get_current_user
from app.db.session import get_db
from app.models.system_log import AuditLog
from app.schemas.compute_configuration import ComputeConfiguration
from app.services.compute_configuration import (
DEFAULT_CONFIGURATION,
default_envelope,
publish_configuration,
read_configuration,
)
from app.services.compute_history import compute_history
from fastapi import FastAPI, HTTPException, Response
from httpx import ASGITransport, AsyncClient
from pydantic import ValidationError
def default_config():
return DEFAULT_CONFIGURATION.model_dump(mode="json")
@pytest.mark.parametrize(
"mutation",
[
lambda value: value["observations"][0]["values"].update(CN=101),
lambda value: value["observations"][0]["values"].update(CN=-1),
lambda value: value["observations"][0]["values"].update(CN=float("nan")),
lambda value: value["observations"][0]["values"].update(CN=True),
lambda value: value["observations"][0]["values"].update(EUROPE=10),
lambda value: value["observations"][0].update(source_id="unknown"),
lambda value: value["observations"][0].update(year=2026),
lambda value: value["observations"].append(value["observations"][0]),
lambda value: value["sources"].append(value["sources"][0]),
lambda value: value["innovation"].append(value["innovation"][0]),
lambda value: value["sources"][0].update(url="javascript:alert(1)"),
lambda value: value["sources"][0].update(url="https://user:pass@example.com/report"),
],
)
def test_rejects_invalid_or_ambiguous_evidence(mutation):
payload = default_config()
mutation(payload)
with pytest.raises(ValidationError):
ComputeConfiguration.model_validate(payload)
def test_arbitrary_report_updates_values_sources_and_years_without_code_changes():
payload = default_config()
payload["sources"].append(
{
"id": "new-report",
"title": "New report",
"url": "https://example.com/report",
"publisher": "Research group",
"report_year": 2026,
"locator": "Figure 2",
}
)
payload["observations"].append(
{
"year": 2025,
"metric": "global_share",
"source_id": "new-report",
"values": {"CN": 25, "US": 50, "JP": 0},
}
)
config = ComputeConfiguration.model_validate(payload)
result = compute_history(["CN", "US", "JP", "EUROPE"], config=config)
row = next(row for row in result["compute"] if row["year"] == 2025)
assert row["values"] == {"CN": 25, "US": 50, "JP": 0, "EUROPE": None}
assert result["evidence"][row["evidence_id"]]["title"] == "New report"
assert DEFAULT_CONFIGURATION.model_dump(mode="json") == default_config()
def test_zero_bilateral_denominator_is_missing_and_empty_override_stays_empty():
payload = default_config()
payload["observations"][0]["values"] = {"CN": 0, "US": 0}
result = compute_history(
["CN", "US"], "bilateral_share", ComputeConfiguration.model_validate(payload)
)
assert result["compute"][0]["values"] == {"CN": None, "US": None}
payload.update(sources=[], observations=[], innovation=[])
result = compute_history(["CN"], config=ComputeConfiguration.model_validate(payload))
assert all(row["values"]["CN"] is None for row in result["compute"])
assert result["evidence"] == {}
def fake_db(record=None):
db = AsyncMock()
db.add = MagicMock()
result = MagicMock()
result.scalar_one_or_none.return_value = record
result.scalar_one.return_value = record
db.execute.return_value = result
return db
@pytest.mark.asyncio
async def test_fresh_install_uses_defaults_without_writing_database():
db = fake_db()
assert await read_configuration(db) == default_envelope()
db.add.assert_not_called()
db.commit.assert_not_awaited()
@pytest.mark.asyncio
async def test_series_reads_persisted_override_and_disables_http_cache():
envelope = default_envelope()
envelope["is_default"] = False
envelope["revision"] = "custom"
envelope["config"]["observations"][3]["values"]["CN"] = 30
response = Response()
data = await get_series(
response, "CN,US", "global_share", fake_db(SimpleNamespace(payload=envelope))
)
assert data["compute"][3]["values"]["CN"] == 30
assert data["version"] == "custom"
assert data["provenance"] == "admin_curated_reports"
assert response.headers["Cache-Control"] == "no-store"
@pytest.mark.asyncio
async def test_publish_and_audit_are_one_transaction_and_conflicts_do_not_overwrite():
record = SimpleNamespace(payload=default_envelope())
db = fake_db(record)
actor = SimpleNamespace(id=1, username="admin")
old = deepcopy(record.payload)
result = await publish_configuration(
db,
revision=old["revision"],
config=DEFAULT_CONFIGURATION,
actor=actor,
)
assert result["revision"] != old["revision"]
audit = db.add.call_args.args[0]
assert isinstance(audit, AuditLog)
assert audit.details == {"before": old, "after": result}
assert audit.actor_id == actor.id
db.commit.assert_awaited_once()
with pytest.raises(HTTPException) as failure:
await publish_configuration(
db, revision=old["revision"], config=DEFAULT_CONFIGURATION, actor=actor
)
assert failure.value.status_code == 409
assert record.payload == result
db.rollback.assert_awaited_once()
db.commit.assert_awaited_once()
@pytest.mark.asyncio
async def test_reset_changes_revision_and_restores_bundled_data():
record = SimpleNamespace(
payload={**default_envelope(), "revision": "custom", "is_default": False}
)
result = await publish_configuration(
fake_db(record),
revision="custom",
config=DEFAULT_CONFIGURATION,
actor=SimpleNamespace(id=1, username="admin"),
reset=True,
)
assert result["is_default"] is True
assert result["config"] == default_config()
assert result["revision"] != "custom"
@pytest.mark.asyncio
@pytest.mark.parametrize("role", ["user", "viewer", "operator"])
async def test_non_admin_cannot_configure(role):
with pytest.raises(HTTPException) as failure:
await configuration_admin(SimpleNamespace(role=role))
assert failure.value.status_code == 403
@pytest.mark.asyncio
async def test_http_configuration_auth_validation_and_public_series():
app = FastAPI()
app.include_router(router)
record = SimpleNamespace(payload=default_envelope())
db = fake_db(record)
app.dependency_overrides[get_db] = lambda: db
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
assert (await client.get("/configuration")).status_code == 401
assert (await client.get("/series")).status_code == 200
app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(
id=1,
username="admin",
role="admin",
)
loaded = (await client.get("/configuration")).json()
invalid = deepcopy(loaded["config"])
invalid["observations"][0]["values"]["CN"] = 200
response = await client.put(
"/configuration",
json={
"revision": loaded["revision"],
"config": invalid,
},
)
assert response.status_code == 422
db.commit.assert_not_awaited()
response = await client.put(
"/configuration",
json={
"revision": loaded["revision"],
"config": loaded["config"],
},
)
assert response.status_code == 200
assert response.json()["revision"] != loaded["revision"]
assert (
await client.post(
"/configuration/reset",
json={
"revision": loaded["revision"],
},
)
).status_code == 409

View File

@@ -262,6 +262,7 @@ def test_absolute_report_year_mapping_and_bilateral_denominator_ignore_other_cou
bilateral = compute_history(["CN", "US", "JP"], "bilateral_share")
values = next(row["values"] for row in bilateral["compute"] if row["year"] == 2023)
assert values == {"CN": 43.06, "US": 56.94, "JP": None}
for report in absolute["evidence"].values():
if report.get("report_year"):
for row in absolute["compute"]:
if row["evidence_id"]:
report = absolute["evidence"][row["evidence_id"]]
assert report["url"].startswith("https://www.caict.ac.cn/")

View File

@@ -8,6 +8,52 @@ This project follows the repository versioning rule:
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
- `bugfix` -> `+0.0.1`
## [0.75.3] — 2026-09-27
Released: 2026-09-27
### Highlights
- 升级地球材质、地图标记与卫星展示,修复拖拽、采集缓存和任务队列,清理废弃渲染路径。
### Improved / Fixed
- 高清地表采用海陆分离 Shader、可读夜侧与单层柔和大气;保留四张底图及真实昼夜,移除旧厚光壳和无用高光配置。
- 卫星在真实轨道采样之间平滑移动,类别色在昼夜保持一致,蓝色覆盖与拾取位置同步;预测轨道开放并加入方向流光,消除强制闭合尖角。
- 地表设施统一渐变徽标,BGP 保留不规则扁平例外;修复低缩放圆点开关,电视面板与播放器恢复方角。
- 鼠标与单指拖出球体仍持续旋转,保留惯性并在极大倍率下限制灵敏度;修复欧拉角换支导致的反向和普通横拖侧歪。
- CelesTrak 改为直接 GET、限时有效缓存和校验后原子替换;采集队列按 task ID 保留独立历史,防止失败任务被新任务或迟到消息重新激活。
---
## [0.75.2] — 2026-09-25
Released: 2026-09-25
### Highlights
- 修复 Windows 启动器固定使用旧版 PowerShell 的问题,优先在 Windows Terminal 新窗口中运行 PowerShell 7。
### Fixed
- 仓库与桌面 CMD 引导优先使用 `pwsh.exe`,缺少新版 PowerShell 或 Terminal 时保留可用环境回退。
- 已以管理员运行的入口同样进入首选终端,子窗口校验权限后直接衔接 WSL,避免重复提权和递归开窗。
- 补齐终端选择、含空格路径、提权分支回归和中英文说明,保持 WSL 重启参数及默认端口不变。
---
## [0.75.1] — 2026-09-25
Released: 2026-09-25
### Highlights
- Windows 启动器从当前项目位置识别 WSL 发行版与目录,首次生成本机桌面 CMD,后续沿用标准重启流程。
- 算力对比数据可由后台维护;小球恢复惯性拖动,大幅放大后保留球面跟手,修复移出球面后的反向旋转。
### Added / Fixed / Improved
- 桌面入口兼容两种 WSL UNC 路径和 Windows 本地磁盘映射,保留原有文件,支持只安装检查;默认端口仍为 3000 / 8000 / 8010。
- 算力报告来源、年度观测与创新分差使用数据库配置,提供数值校验、版本冲突保护、事务审计、恢复默认和地球自动刷新。
- 根据相机视锥在按下时固定拖动模式;小球使用旧版位移平滑与惯性,大球不再用球外最近点生成反向旋转。
- 更新开发 agent 的 Sol / Luna / Astra 分工规则,补齐中英文运维说明、启动故障编号与隔离回归测试。
---
## [0.75.0] — 2026-09-23
Released: 2026-09-23

View File

@@ -79,6 +79,16 @@ git diff --unified=0 HEAD -- <path>
## Harness Commands
Windows desktop launcher tests run separately on Windows with
`powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\harness\test_windows_launcher.ps1`.
They use temporary desktop folders and mocked restart commands; no UAC prompt
or real service restart is triggered. The WSL bridge regression suite,
`scripts/harness/test_windows_restart.py`, is included in quick-check and uses
disposable command substitutes. For a real entry-point check without restarting,
run the repository `planet.cmd --install-only`, then the generated desktop
launcher with the same flag. Installation and mocked checks do not prove a live
elevated restart; report that separately when it has not been exercised.
| Tier | Command | What It Does |
| --- | --- | --- |
| Doctor | `scripts/harness/doctor.sh` | Checks required files, required tools, optional delivery tools, and forbidden frontend lockfiles. |

View File

@@ -1,5 +1,7 @@
# Earth Predicted Orbit Plan
> 2026-09-27 状态更新:选中轨道现为 96% 周期的开放弧线,已移除强制闭合,使用同一 Line Shader 绘制沿预测方向前进的流光;传播器、轨道平面与高度策略保留。以下早期设计以当前实现和技术文档为准。
> Source note: this plan absorbs useful ideas from a sisyphus-created draft formerly stored at `.sisyphus/plans/predicted-orbit.md`.
## Goal

View File

@@ -467,6 +467,15 @@ Epoch uses its official public CSV, retaining theoretical FP16 performance, orig
Neither collector returns sample data on failure. Empty fetches or transformed results, schema errors, and losses exceeding 40% of the previous snapshot fail while retaining prior data. Incomplete writes are rolled back. TOP500 location migration copies only a unique exact name and canonical-country match to the new system ID, retaining the historical key; rank is never a migration key.
`compute_history.py` stores controlled imports from the reviewed research plan, including annual observations, sources, and a version. Reference periods and publication dates are distinct; unknown publication days remain unspecified. `/api/v1/data-products/compute/series` offers global share, fixed US + China bilateral share, and available FP32 absolute observations. Innovation gaps are independent and never expanded into inferred national scores.
`compute_history_defaults.json` ships the original report data. `compute_configuration.py` reads a complete override from the `compute_comparison` category in `system_settings`; absent records use bundled defaults without migrations or manual initialization. `compute_history.py` performs same-year aggregation. Reference periods and publication dates remain distinct, and unknown publication days remain unspecified. `/api/v1/data-products/compute/series` reads configuration on each request with `Cache-Control: no-store`, offering global share, fixed US + China bilateral share and FP32 absolute observations. Innovation gaps remain independent. An empty override stays empty instead of silently restoring observations.
Under the same prefix, `GET/PUT /configuration` and `POST /configuration/reset` require admin/super_admin. Writes accept `{revision, config}` and reset accepts `revision`. Pydantic validates canonical countries, finite values, share totals, duplicate metric/year pairs and report references; each metric/year has one report basis. PostgreSQL category uniqueness and row locking serialize first writes and updates; stale revisions return 409. Configuration and before/after audit records commit in one transaction. Reset removes the override so subsequent reads use the current bundled defaults. `version` is a configuration revision, while `reviewed_at` is the supplied review date. Admin-curated data is not automatically labeled official. Source URLs are references, not scrape instructions.
`/api/v1/data-products/compute/facilities` reads successful snapshots with `compute_contract=v1`, applying country filters and per-source counts in SQL. Epoch excludes planned, decommissioned, superseded, and suspected duplicate records; TOP500 means list observations. Cross-source deduplication remains pending. Historical cutoffs use collection time, never pretending a recently fetched old source was available earlier. Geographic results are bounded and report truncation; total record counts are independent of this limit. Official site helpers are keyed by exact `source` + `source_id`; their access-map centers are site-level references only and retain their official URL in `source_note`.
### CelesTrak download windows and caching
Both active and fallback-group downloads skip HEAD preflight and send GET directly: a preflight may consume the upstream download allowance before the body request. Valid complete cache entries are reused for two hours, then refreshed with conditional GET when validators exist, or ordinary GET otherwise. A 304 reuses validated cache; only the explicit “GP data has not updated” 403 permits a valid-cache fallback. Other 403 errors remain failures. Fallback groups also respect cache age rather than reusing old files indefinitely.
A nonempty GP record list is validated in `.part` before atomically replacing the cache; failed downloads preserve the previous valid payload. Length comes from the GET response, and compressed wire length is not compared with decoded bytes. Other collectors retain HEAD metadata and Range resume support. Restoring a raw cache does not populate the database: trigger a new collection task afterward.

View File

@@ -1,13 +1,22 @@
# Earth Frontend Context
## HD surface and atmosphere materials
The visible HD surface uses a single-draw ShaderMaterial in `earth-surface-material.js`, retaining the R+0.48 mesh, depth policy and surface pick target. The existing controller still switches all four 8K maps, updates the sampler and disposes the previous texture only after success. Normals, view direction and astronomical sunlight share world coordinates. Land is matte; water has grazing-angle cool reflection without a white specular lobe. The existing geographic land/ocean texture owns the optical mask independently of border visibility, with a conservative chroma fallback until loaded and reflection suppression over ice. Original JPEGs are neither repainted nor downsampled.
Color textures are tagged sRGB with mipmaps. The r128 surface shader decodes sRGB; r160 uses hardware texture decoding. Both combine light in linear space and encode once. A local filmic curve affects only the surface instead of enabling global ACES exposure on the sky and data layers. The terminator spans normal dot products [-0.075, 0.16]; night shading has its own geographic texture ghosting and cool ambient branch. A 0.55 power of the locally tone-mapped texture retains shadow variation, followed by separate muted land and deep-indigo ocean tints and low ambient floors. Day/night mixing remains linear with one final sRGB output. Day exposure and reflections are unchanged; no synthetic city lights are added. One R×1.025 BackSide/Additive shell replaces the three rim shells, with depthWrite=false and depthTest=true; inner scattering is part of the surface pass. Independently switchable clouds use matte day/night shading at renderOrder 1.1. The sky uses the existing `starmap_deep_8k.jpg` without a tint overlay.
## Configurable compute observations
Compute cards read annual observations from `/api/v1/data-products/compute/series`; the admin Compute comparison section is the maintenance entry point. `compute-topic.js` fetches with no-store, listens for same-origin `planet-compute-configuration` notifications, and checks every 60 seconds while visible and enabled, plus when the page becomes visible. Observation refresh does not reload facility layers. `destroy()` releases the timer, channel and visibility listener. Country membership, full regional coverage and missing-value semantics remain backend-owned.
## Surface texture provenance
On 2026-09-21, `assets/8k_earth_daymap.jpg` was replaced with an 8192×4096 Web derivative of the paired Natural Earth I raster. Its loading path and rendering code remain unchanged. The source is a 16200×8100 EPSG:4326 image; the previous JPEG is preserved byte-for-byte under `resources/earth/archive/2026-09-21/`. Source/license records, the catalogue versus embedded-version discrepancy, SHA256 hashes, JPEG parameters, and recalculated world-file metadata live in `resources/earth/natural-earth-1/`. Large originals remain in Git-ignored `downloads/earth/`, outside the frontend release bundle.
The base-map selector defaults to Original basemap, listed first and saves the source chosen in the display menu. Natural Earth I remains available alongside “Original basemap”, a byte-identical copy of the September 21, 2026 archive; NASA 21K is source archive material only, while runtime delivery stays at one 8K texture. A new source replaces the old GPU texture only after successful loading and releases the old one then; failures retain the old texture and stale responses cannot overwrite the current source. This is a source switch, not an additional rendering layer. The physical texture is JPEG sRGB, does not bake political borders, and detailed boundary alignment is not yet validated. The starfield is restored byte-for-byte to commit `83a10a6c`: `celestial.js` matches that commit, `skyTint` and `skyBrightness` are removed, and `brightStarOpacity` is back to `0.88`; star density and color are no longer calibrated. The HD overlay uses a white `MeshBasicMaterial` with opacity `1` and `toneMapped:false`, with `texture-colors.js` centralizing sRGB read/write. The 0.128 path uses `encoding` plus `LinearTosRGB`; the 0.160.1 path uses `colorSpace` plus the normal colorspace fragment. There is no Phong white-light or colored twilight overlay, blue night tint, `cameraBoost`, or shoulder curve; daylight neutral scaling keeps brightness at or below the source maximum, and dark mode only applies neutral scaling. The original texture asset is unchanged. Natural Earth is intrinsically pale; this does not claim missing detail was restored. Earth still supports the Three 0.128 import-map runtime and frontend package Three 0.160.1 runtime, and WebGL1 derivatives remain enabled for `fwidth`.
Day/night shading uses a narrow smooth transition centered on the solar horizon (normal dot product ±0.12). The day side is capped at the source brightness; night-side linear illumination is 0.24, rising smoothly to at most 0.60 in source shadows to retain dark ocean and forest detail. Shading uses a neutral scalar without added exposure, colored veils, rendering passes, or textures.
Basemaps and TV channels share `hud-select-menu.js` for the HUD popover, list, selection mark, keyboard navigation, and positioning; `tv-source-menu.js` only adapts channel copy. Basemaps disable search, pagination, and counts. The trigger owner identifies popover clicks as internal to the mobile drawer.
This document describes the current real structure of the Earth display frontend. The focus is on helping future changes to the HUD, layers, media panel, real terrain, and BGP visualization avoid repeating past structural and state-sync pitfalls.
@@ -284,7 +293,7 @@ The surface hover tooltip preference is persisted by `controls.js` as `shared.su
The real satellite altitude preference is persisted by `controls.js`, while the rendering state lives in `satellites.js`. When enabled, the real radius from SGP4 is compressed logarithmically into the current Earth visual radius range. When disabled, satellite dots, trails, and predicted orbits all return to the legacy same-sphere display. Toggling this setting must refresh satellite positions and clear trail buffers so a trail never mixes both height models. `maxRealAltitudeOffset = 25` is a visual cap tuned for the current camera and `earthRadius = 100`: GEO / MEO remain clearly higher than LEO, but the highest orbits stay within about 25% beyond the globe radius so selection targets, red trails, and the globe do not feel disconnected.
SGP4 propagation returns an inertial-frame position, so it must not be drawn directly as Earth-fixed longitude / latitude. `satellites.js` uses `gstime` to convert ECI/TEME positions to ECF, then maps that result into the same Three.js axes as `latLonToVector3()`. Satellite dots and short trails use Earth-fixed coordinates for each sample time, representing the object's current position relative to the globe surface. The locked predicted orbit uses the `gstime` from the lock moment for the whole future orbit, projecting the inertial orbit plane onto the current globe pose; that keeps the line closed and keeps the visual orbit inclination aligned with the details card. Fallback predicted orbits must also use a real RAAN + inclination orbital-plane formula, not treat inclination as a constant latitude.
SGP4 propagation returns an inertial-frame position, so it must not be drawn directly as Earth-fixed longitude / latitude. `satellites.js` uses `gstime` to convert ECI/TEME positions to ECF, then maps that result into the same Three.js axes as `latLonToVector3()`. Satellite dots and short trails use Earth-fixed coordinates for each sample time, representing the object's current position relative to the globe surface. The locked predicted orbit uses the `gstime` from the lock moment for an open 96%-period prediction arc, projecting the inertial orbit plane onto the current globe pose. No first vertex or closing chord is appended; arc-length highlights travel toward increasing prediction time, and visual inclination stays aligned with the details card. Fallback predicted orbits must also use a real RAAN + inclination orbital-plane formula, not treat inclination as a constant latitude.
Boundary precision is stored separately by `country-boundaries.js` under `planet.earth.boundaries.highPrecisionEnabled`. When high precision is off, Earth keeps using the bundled low-precision `countries-admin0.min.geojson` fallback even if high-precision manifest/PMTiles files exist locally. When high precision is on but the artifact is missing, the Earth toolbar settings call `/api/v1/earth/boundaries/build` and poll progress. After success, `reloadCountryBoundaries()` hot-swaps the boundary layer without refreshing the page. Boundary hover is independent from interactable hover: a country polygon remains highlighted whenever the surface coordinate is inside it, while the tooltip can still prioritize a satellite, vessel, BGP marker, or other interactable.
@@ -365,7 +374,7 @@ If future cable, satellite, or news cruise is added, do not copy a new set of `m
[controls.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/controls.js) owns the Earth zoom state, and every zoom entry point must ultimately call `setZoomLevel()` to write the camera distance. Do not write `camera.position.z` from other modules, or the zoom percentage, drag sensitivity, and Interactable clustering thresholds will diverge again.
`globe-navigation.js` maps zoom to `sqrt(R² + (D₀² - R²) / zoom²)` with minimum surface clearance and the matching inverse. The 100% camera pose remains unchanged; 500% stays outside the globe. Mouse and single-touch dragging use ray/sphere intersections and quaternion rotation to keep the grabbed surface under the pointer, without an empirical sensitivity multiplier or frame-by-frame catch-up. Auto-rotation is suspended during dragging and pinching. Release inertia follows the measured axis; paused releases and cancellation do not fling. Returning from a pinch to one finger rebases the grab point. Click suppression uses displacement from pointer-down, including slow drags.
`globe-navigation.js` retains the safe zoom-distance mapping. Mouse and single-touch drags uniformly use legacy screen deltas, 0.18 smoothing and release inertia, including movement outside the globe silhouette; ray/sphere intersection no longer gates dragging. Normal zoom retains legacy sensitivity. Once the globe exceeds the viewport, a smooth surface-distance/viewport cap limits excessive rotation at extreme zoom. Horizontal motion uses geographic yaw, vertical input changes tilt, and quaternion math prevents multi-revolution reversal. Pinch transitions and pointer capture remain intact.
Interactable clustering is selected per layer through `cluster.strategy`. `stable-spherical` uses discrete zoom bands and local 3D bucket clustering, so BGP, compute centers, and Earth interactables do not regroup while the globe rotates inside the same band. `dynamic-screen` keeps projection-based clustering, and `none` disables it. Vessels explicitly disable clustering and avoidance so incremental updates do not rebuild cluster topology. Stable cluster dots stay rigidly aligned to their 3D centroid projection and do not participate in 2D avoidance. See [Earth Interactable Clustering](/home/ray/dev/linkong/planet/docs/technical/en/earth-interactable-clustering.md) for strategy configuration and tuning.
@@ -447,3 +456,7 @@ The root attributes `data-earth-first-frame-ms` and `data-earth-surface-ready-ms
Positioned cards stay hidden while the shared connector draws for 420 ms, then fade in using the HUD 180 ms opacity timing. Targets remain fixed during drawing; subsequent motion does not replay entrance. Reduced-motion preferences skip this animation.
Object clicks, search focus and gesture confirmation share `PresentationController`. Cable selection updates selection/legend state without independently opening the card. InfoCard reveal callbacks are versioned so staging or hiding invalidates older callbacks. Connector completion gates card reveal; cancelled cruises no longer hide a newer selection. Object details reuse the regional-card edge candidates and collision scoring, with dimensions measured while staged. Selecting a mobile search result collapses the search drawer so the focused object, connector and compact card remain visible.
### Satellite particles and smooth rendering
Real GP/TLE propagation remains in the Worker at 250ms sampling intervals. `satellite-motion.js` interpolates radius-preserving rendered positions each frame without changing orbits, sample-time offsets or altitude policy. Rendering, picking current positions, trail tips, hover/locked rings and footprints share these positions. Data/count/altitude resets clear interpolation to prevent unrelated transitions. Batched Points shade analytic discs for the reference small-sphere appearance, with restrained size scaling instead of individual sphere meshes. Starlink and Iridium footprints share `SATELLITE_CONFIG.footprintColor` (`#3399ff`). The old yellow-day/blue-night shader mix is removed; sunlight only adjusts opacity. Satellite particles and predicted orbits share their category color, with a thin dark particle outline for bright terrain. Coverage geometry and capability policy remain unchanged.

View File

@@ -1,5 +1,17 @@
# Earth Layer Style Property Index
`EARTH_MATERIAL_CONFIG.surface.night` centralizes night texture contrast (detailGamma=0.55) and separate land/ocean tint and ambient values. It only contributes to the night branch, keeps day exposure unchanged, and reuses the geographic mask without another texture or draw call.
## Modern object presentation
- Surface: `EARTH_MATERIAL_CONFIG.surface` owns exposure=0.9, landSaturation=0.9, oceanAbsorption=0.36, oceanDeepColor=[0.004,0.012,0.032], night retention and Fresnel parameters. `atmosphere` owns the single shell's radius, color and strength. Base and terrain specular highlights are disabled.
- Cables blend a cool normal tint with their category color, consistently with the legend. Selected pulses follow cumulative route length with 6 repetitions and speed 4.5 in the existing batch draw. Drawing no longer writes depth; original Line pick objects, cable IDs and state logic remain intact.
- Landing points use the 128×128 monochrome `marker-landing-point.svg` micro-core instead of a glossy procedural ball; Sprite picking and billboard size logic remain intact.
- Compute markers use canonical SVG inner glyphs over shared gradient plates, pale rims, top highlights and shadows. GPU/AI uses purple stacked layers, supercomputers purple chips, and infrastructure teal server racks. Estimated badges, optional compact dots and picking remain intact.
- Satellite inclination categories remain distinct using muted cool colors. Propagation, trail caches, selection, footprint geometry and display modes are unchanged. BGP severity, vessel heading and related-object emphasis remain intact; shared HUD surfaces and short tooltip reveals use the same dark visual family.
This document records the material, color, opacity, line width, radius offset, and `renderOrder` style properties of all Earth frontend layers. For layer ordering relationships, see [Earth Render Layer Order](/home/ray/dev/linkong/planet/docs/technical/en/earth-render-layer-order.md).
## Naming Conventions
@@ -20,15 +32,11 @@ This document records the material, color, opacity, line width, radius offset, a
| Earth base radius | `CONFIG.earthRadius` | `100` | `earth.js:createEarth()` |
| Earth base color | `EARTH_MATERIAL_CONFIG.color` | `0x010609` | `MeshPhongMaterial.color` |
| Earth base emissive | `EARTH_MATERIAL_CONFIG.emissive` | `0x010609` | `MeshPhongMaterial.emissive` |
| Earth base specular | `EARTH_MATERIAL_CONFIG.specular` | `0x1a2d45` | `MeshPhongMaterial.specular` |
| Earth base shininess | `EARTH_MATERIAL_CONFIG.shininess` | `12` | `MeshPhongMaterial.shininess` |
| Earth base specular | `EARTH_MATERIAL_CONFIG.specular` | `0x000000` | `MeshPhongMaterial.specular` |
| Earth base shininess | `EARTH_MATERIAL_CONFIG.shininess` | `0` | `MeshPhongMaterial.shininess` |
| Earth base opacity | `EARTH_MATERIAL_CONFIG.opacity` | `1` | `MeshPhongMaterial.opacity` |
| HD texture radius offset | `EARTH_MATERIAL_CONFIG.textureOverlayAltitudeOffset` | `0.48` | Standalone HD texture sphere radius; must keep enough depth separation from the land/ocean base and Earth base sphere to avoid far-zoom z-fighting |
| HD texture opacity | `EARTH_MATERIAL_CONFIG.textureOverlayOpacity` | `0.88` | HD texture `MeshPhongMaterial.opacity` |
| HD texture renderOrder | `EARTH_MATERIAL_CONFIG.textureOverlayRenderOrder` | `0.96` | `_earthTextureOverlay.renderOrder` |
| HD texture specular | `EARTH_MATERIAL_CONFIG.textureOverlaySpecular` | `0x05080d` | Reduces specular highlight in direct-light areas to avoid blown-out texture |
| HD texture shininess | `EARTH_MATERIAL_CONFIG.textureOverlayShininess` | `4` | Reduces specular concentration |
| HD texture color multiplier | inline | `0xffffff` | `_earthTextureOverlayMaterial.color` |
## Earth Occluder and Day/Night
@@ -36,7 +44,7 @@ This document records the material, color, opacity, line width, radius offset, a
| --- | --- | --- | --- |
| Occluder radius factor | `EARTH_MATERIAL_CONFIG.occluderRadiusFactor` | `0.999` | Depth occluder sphere radius |
| Occluder segments | `EARTH_MATERIAL_CONFIG.occluderSegments` | `48` | Occluder geometry segments |
| Occluder renderOrder | inline | `-1` | `occluder.renderOrder` |
| Occluder renderOrder | inline | `0.5` | `occluder.renderOrder` |
| Day/night sun direction | `EARTH_MATERIAL_CONFIG.dayNight.sunDirection` | `{ x: 1, y: 0.2, z: 0.4 }` | Custom day/night shader |
| Night-side minimum brightness | `EARTH_MATERIAL_CONFIG.dayNight.nightFloor` | `0.24` | Shader uniform |
| Day-side boost | `EARTH_MATERIAL_CONFIG.dayNight.dayBoost` | `1.12` | Shader uniform |
@@ -50,27 +58,12 @@ This document records the material, color, opacity, line width, radius offset, a
| Name | Variable | Current Value | Location / Notes |
| --- | --- | --- | --- |
| Inner atmosphere radius factor | `EARTH_MATERIAL_CONFIG.atmosInnerRadiusFactor` | `1.01` | `atmosInnerGeo` |
| Inner atmosphere segments | `EARTH_MATERIAL_CONFIG.atmosInnerSegments` | `64` | `atmosInnerGeo` |
| Inner atmosphere color | `EARTH_MATERIAL_CONFIG.atmosInnerColor` | `[0.25, 0.62, 1.0]` | Shader RGB |
| Inner atmosphere rim power | `EARTH_MATERIAL_CONFIG.atmosInnerRimPower` | `3.2` | Shader rim falloff |
| Inner atmosphere intensity | `EARTH_MATERIAL_CONFIG.atmosInnerIntensity` | `0.18` | Shader alpha multiplier |
| Outer atmosphere radius factor | `EARTH_MATERIAL_CONFIG.atmosOuterRadiusFactor` | `1.016` | `atmosOuterGeo` |
| Outer atmosphere segments | `EARTH_MATERIAL_CONFIG.atmosOuterSegments` | `48` | `atmosOuterGeo` |
| Outer atmosphere color | `EARTH_MATERIAL_CONFIG.atmosOuterColor` | `[0.18, 0.45, 0.9]` | Shader RGB |
| Outer atmosphere rim power | `EARTH_MATERIAL_CONFIG.atmosOuterRimPower` | `5.0` | Shader rim falloff |
| Outer atmosphere intensity | `EARTH_MATERIAL_CONFIG.atmosOuterIntensity` | `0.02` | Shader alpha multiplier |
| Atmosphere blending | inline | `THREE.AdditiveBlending` | `ShaderMaterial.blending` |
| Atmosphere renderOrder | inline | `1` | `atmosInner/Outer.renderOrder` |
| No-HD-texture rim glow color | `EARTH_MATERIAL_CONFIG.rimGlowColor` | `[0.35, 0.65, 1.0]` | Fresnel shell RGB when HD texture is hidden or unavailable |
| No-HD-texture rim glow power | `EARTH_MATERIAL_CONFIG.rimGlowPower` | `3.8` | Shader rim falloff; higher = narrower edge |
| No-HD-texture rim glow intensity | `EARTH_MATERIAL_CONFIG.rimGlowIntensity` | `0.28` | Shader alpha multiplier |
| No-HD-texture rim glow segments | `EARTH_MATERIAL_CONFIG.rimGlowSegments` | `64` | `earth-rim-glow` geometry segments |
| Cloud layer radius offset | `CLOUD_LAYER_CONFIG.radiusOffset` | `3` | Cloud sphere radius |
| Cloud layer segments | `CLOUD_LAYER_CONFIG.widthSegments / heightSegments` | `64 / 64` | Cloud sphere geometry |
| Cloud layer opacity | `CLOUD_LAYER_CONFIG.opacity` | `0.15` | `MeshPhongMaterial.opacity` |
| Cloud layer opacity | `CLOUD_LAYER_CONFIG.opacity` | `0.15` | `MeshBasicMaterial.opacity` |
| Cloud texture | `CLOUD_LAYER_CONFIG.textureUrl` | `"./assets/earth_clouds_1024.png"` | Cloud texture map |
| Cloud blending | inline | `THREE.AdditiveBlending` | `MeshPhongMaterial.blending` |
| Cloud blending | inline | `THREE.AdditiveBlending` | `MeshBasicMaterial.blending` |
## Land/Ocean Base and Country Borders
@@ -123,8 +116,8 @@ The land/ocean base is an Earth base-map asset and preloads at startup; the "Bor
| Terrain opacity | `TERRAIN_CONFIG.opacity` | `0.68` | `MeshPhongMaterial.opacity` |
| Terrain color | `TERRAIN_CONFIG.color` | `0x8aa884` | `MeshPhongMaterial.color` |
| Terrain emissive | `TERRAIN_CONFIG.emissive` | `0x030704` | Reduces self-emission to preserve terrain shading |
| Terrain specular | `TERRAIN_CONFIG.specular` | `0x344438` | Gives terrain local sheen without boosting HD texture brightness |
| Terrain shininess | `TERRAIN_CONFIG.shininess` | `16` | Tightens terrain highlight |
| Terrain specular | `TERRAIN_CONFIG.specular` | `0x000000` | Matte terrain; no white specular lobe |
| Terrain shininess | `TERRAIN_CONFIG.shininess` | `0` | Specular disabled |
| Terrain renderOrder | inline | `1.2` | `terrain.renderOrder` |
| Terrain polygonOffset | inline | `factor -1`, `units -1` | Reduces z-fighting near sphere surface |
@@ -174,8 +167,8 @@ The land/ocean base is an Earth base-map asset and preloads at startup; the "Bor
| Satellite altitude compression scale | `SATELLITE_CONFIG.altitudeCompressionKm` | `1200` | TLE/SGP4 altitude compression; larger values soften high-orbit separation |
| Satellite real-altitude cap | `SATELLITE_CONFIG.maxDisplayAltitudeKm` | `40000` | Altitude clamp for the compressed display mapping, covering GEO-range altitude |
| Satellite real-altitude display offset range | `minRealAltitudeOffset / maxRealAltitudeOffset` | `4 / 25` | Compressed offset added to `CONFIG.earthRadius`; `25` is about one quarter of the current globe radius `100`, keeping high-orbit separation visible without pushing GEO/MEO trails too far away |
| Satellite dot base pixel size | `SATELLITE_CONFIG.dotBaseSize` | `2.8` | Point shader size |
| Satellite backdrop dot scale | `SATELLITE_CONFIG.dotBackdropScale` | `1.28` | Backdrop dot size |
| Satellite dot base pixel size | `SATELLITE_CONFIG.dotBaseSize` | `2.2` | Point shader size |
| Satellite backdrop dot scale | `SATELLITE_CONFIG.dotBackdropScale` | `1.4` | Backdrop dot size |
| Satellite dot opacity range | `dotOpacityMin / dotOpacityMax` | `0.42 / 1.0` | Breathing animation |
| Satellite dot breathing speed | `SATELLITE_CONFIG.dotBreathingSpeed` | `0.12` | Dot opacity animation |
| Satellite backdrop renderOrder | inline | `5` | `satelliteBackdropPoints.renderOrder` |
@@ -216,8 +209,8 @@ AIS vessel markers use batched `THREE.Points`, not one `THREE.Sprite` per vessel
| Hover scale | `COMPUTE_CENTER_CONFIG.marker.hoverScale` | `1.16` | Hover overlay size multiplier |
| Locked scale | `COMPUTE_CENTER_CONFIG.marker.lockedScale` | `1.22` | Locked overlay size multiplier, with pulse |
| Dimmed scale / opacity | `dimmedScale / dimmedOpacity` | `0.82 / 0.34` | Dim state |
| Supercomputer color | `COMPUTE_CENTER_CONFIG.colors.supercomputer` | `"#38bdf8"` | Marker texture |
| GPU cluster color | `COMPUTE_CENTER_CONFIG.colors.gpu_cluster` | `"#2dd4bf"` | Marker texture |
| Supercomputer color | `COMPUTE_CENTER_CONFIG.colors.supercomputer` | `"#a855f7"` | Marker texture |
| GPU cluster color | `COMPUTE_CENTER_CONFIG.colors.gpu_cluster` | `"#a855f7"` | Marker texture |
| Linked color | `COMPUTE_CENTER_CONFIG.colors.linked` | `"#f8fafc"` | Linked state |
| Compute center renderOrder | local `COMPUTE_CENTER_RENDER_ORDER` | `4.5` | Surface facility below satellites |
@@ -263,3 +256,30 @@ AIS vessel markers use batched `THREE.Points`, not one `THREE.Sprite` per vessel
| Star radius range | `minRadius + radiusJitter` | `800 + 200` | Random distribution |
| Star color | `STARFIELD_CONFIG.color` | `0xffffff` | `PointsMaterial.color` |
| Star size | `STARFIELD_CONFIG.size` | `0.5` | `PointsMaterial.size` |
## Badge taxonomy and palette
| Type | Primary color | Inner glyph |
| --- | --- | --- |
| Datacenter/infrastructure | Teal `#14b8a6` → `#0d9488`, rim `#5eead4` | Server rack |
| GPU/AI | Purple `#a855f7` → `#7e22ce`, rim `#d8b4fe` | Stacked compute layers |
| Supercomputer | Same purple family | Chip |
| Cable landing point | Amber `#f59e0b`, pale-gold `#fef3c7` rim | Glowing circular core |
| BGP collector | Blue and existing activity heat colors | Flat broadcast tower, no badge plate |
| BGP event | Low/medium/high/critical: blue/amber/orange/red | Irregular flat event symbols, no badge plate |
| Vessel | Cargo blue, tanker orange, passenger teal, fishing amber, military indigo, other silver | Heading arrow; anchored state retained |
| Custom marker | Place green, note yellow, alert red, default blue | Pin, note sheet, warning triangle |
BGP retains irregular flat symbols as the exception; other finite surface objects share cached badge textures without a new DOM node or draw object per marker. Vessels retain heading buckets and vertex colors rather than multiplying buckets by vessel type. Satellites use distinct category colors with a thin dark outline; orbit and footprint calculations stay intact. Optional low-zoom dots remain available, default off; both rendering and pick sizing honor the switch.
### Stable satellite palette
Category colors follow [satellitemap.space](https://satellitemap.space/) while retaining this project's real inclination classes: 0–30° blue `#3399ff`, 30–60° orange `#ff801a`, 60–90° green `#00e680`, 90–120° purple `#cc33ff`, 120–180° rose `#ff3366`, unknown gray `#94a3b8`. A satellite keeps its hue across day/night; predicted orbits no longer use an unrelated yellow-purple gradient.
All coverage uses `#3399ff`, opacity 0.34, with a day-side opacity multiplier of 1.65 rather than switching to yellow. Particle dark-outline scale is 1.4 and opacity 0.46, reusing the existing backdrop point batch without additional draw batches.
### Selected orbit and panel outlines
Prediction draws an open 96%-period arc with faded endpoints and no appended closing vertex. Highlights travel forward along cumulative arc length in the same Line draw. TV and shared HUD shells use square corners, including the player clip, without changing panel size or dragging. Temporary frame-statistics instrumentation and its QA-only DOM attributes are removed from release code.

View File

@@ -1,6 +1,6 @@
# Earth Render Layer Order
The compute topic reuses the compute-center Interactable icons, depth behavior, and layer order. Country/year changes replace that layer's data and clear prior selection. Its HUD is screen UI excluded from Earth picking in `main.js`. Regional cards are tethered in screen space; rear anchors do not draw connectors through the globe. Facility details reuse the existing card and mobile details drawer. The existing outer atmosphere shell remains, while the starfield is restored to commit `83a10a6c` (`brightStarOpacity:0.88`; no tint/brightness calibration). The HD overlay is a white `MeshBasicMaterial` with opacity 1 and `toneMapped:false`; `texture-colors.js` selects the r128 `encoding`/`LinearTosRGB` path or r160 `colorSpace`/colorspace fragment. No Phong white light, colored twilight, blue night tint, camera boost, or shoulder curve is added. No new post-processing, GPU draw pass, or high-resolution texture was added; the compute topic adds 45 local SVG flag assets.
The compute topic reuses the compute-center Interactable icons, depth behavior, and layer order. Country/year changes replace that layer's data and clear prior selection. Its HUD is screen UI excluded from Earth picking in `main.js`. Regional cards are tethered in screen space; rear anchors do not draw connectors through the globe. Facility details reuse the existing card and mobile details drawer. The visible HD surface uses a single-draw ShaderMaterial in `earth-surface-material.js`, retaining the R+0.48 mesh, depth policy and surface pick target. The existing controller still switches all four 8K maps, updates the sampler and disposes the previous texture only after success. Normals, view direction and astronomical sunlight share world coordinates. Land is matte; water has grazing-angle cool reflection without a white specular lobe. The existing geographic land/ocean texture owns the optical mask independently of border visibility, with a conservative chroma fallback until loaded and reflection suppression over ice. Original JPEGs are neither repainted nor downsampled. Color textures are tagged sRGB with mipmaps. The r128 surface shader decodes sRGB; r160 uses hardware texture decoding. Both combine light in linear space and encode once. A local filmic curve affects only the surface instead of enabling global ACES exposure on the sky and data layers. The terminator spans normal dot products [-0.12, 0.28]; night attenuation retains 0.12–0.32 linear illumination after tone mapping to avoid crushing source shadows twice. One R×1.025 BackSide/Additive shell replaces the three rim shells, with depthWrite=false and depthTest=true; inner scattering is part of the surface pass. Independently switchable clouds use matte day/night shading at renderOrder 1.1. The sky uses the existing `starmap_deep_8k.jpg` without a tint overlay.
This document records the current Earth renderer's layer order and the intent of each layer. When adjusting `renderOrder`, radius offsets, depth strategy, or pointer interaction, update this document accordingly.
@@ -16,12 +16,12 @@ Note: the layer control panel order and the registration / startup load order ar
| Order | Layer | Source | Render / Radius Strategy | Depth / Interaction Strategy | Notes |
| --- | --- | --- | --- | --- | --- |
| -1000 | Celestial background mesh | `celestial.js` | Background sphere | Not part of surface picking | Behind all Earth content. |
| -1 | Earth occluder sphere | `earth.js` | Invisible inner sphere | Writes depth buffer | Occludes objects behind the Earth. |
| 0.5 | Earth occluder sphere | `earth.js` | Invisible inner sphere | Writes depth buffer | Occludes objects behind the Earth. |
| 0 | Earth base sphere | `earth.js` | `CONFIG.earthRadius` | Surface picking fallback target | Dark base; still visible when all optional map layers are off. |
| 0.2 | Country dark tint | `country-boundaries.js` | `tintAltitudeOffset` | Raycast disabled | Used when HD texture is off. |
| 0.86 | Land/ocean base fill | `country-boundaries.js` | `landAltitudeOffset = 0.32`; ocean `#010609`, land `#080f1b` | Raycast disabled | Base map remains usable even when country borders are off; radius is separated from the base sphere to avoid far-zoom z-fighting. |
| 0.96 | HD Earth texture | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | Surface picking target when visible | HD texture always overlays the land/ocean base fill; radius must stay above the land/ocean base and far enough from the base sphere. |
| 1 | Atmospheric glow and clouds | `earth.js` | Atmosphere / cloud spheres | Not in normal object selection path | Cloud layer controlled by the "Cloud Layer" toggle. |
| 1 / 1.1 | Atmosphere / clouds | `earth.js` | One atmosphere shell at R×1.025; clouds at R+3 | Atmosphere uses BackSide, depthWrite=false, depthTest=true; cloud toggle retained | Inner scattering shares the surface pass; no fullscreen post-processing. |
| 1 | Submarine cables / landing points | `cables.js`, `cable-batches.js` | All cable segments share one `LineSegments`; all landing points use instanced billboards; render order remains `1`; cable altitude offset stays `0.2`, while landing-point anchors use the HD surface offset `0.48` | Original `Line` / `Sprite` objects retain per-item picking and selection state but no longer draw individually; landing-point sphere occlusion remains, with `depthTest: false` on the batch | Style textures and instance attributes preserve color, pulse, size, visibility, and click behavior. |
| 1.2 | Real terrain | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` plus terrain displacement | Raycast disabled | Terrain overlays HD texture; temporarily hidden when HD texture is off, restores to prior state when re-enabled. |
| 2.05 | Grid lines | `earth.js` | `CONFIG.earthRadius + 0.14` | Raycast disabled | Low-opacity lines over HD texture. |
@@ -35,7 +35,7 @@ Note: the layer control panel order and the registration / startup load order ar
| 4.5 | Compute centers | `compute-centers.js`, `interactable.js` | `COMPUTE_CENTER_RENDER_ORDER` | Screen-space Interactable picking, with surface-icon collision handling | Surface facilities, below satellites. |
| 5 | Satellite background dot | `satellites.js` | Fixed renderOrder; by default TLE/SGP4 altitude is compressed to `CONFIG.earthRadius + 4..25`; with real altitude disabled or propagation failed, uses `fallbackAltitudeOffset = 8` | Screen-space satellite picking | Below satellite dots. |
| 6 | Satellite dots | `satellites.js` | Same compressed / fallback height as satellite backdrop dots | Screen-space satellite picking | Satellite dots above footprints and compute centers. |
| 12+ | Satellite locked ring, halo, predicted orbit | `satellites.js` | `SATELLITE_CONFIG.overlayRenderOrder` and offsets; predicted orbit follows the same real-altitude toggle and fixes the lock-time globe pose to draw a closed inertial orbit; returns to same-sphere mode when real altitude is disabled | Satellite overlay path | Used for selected/locked satellite emphasis. |
| 12+ | Satellite locked ring, halo, predicted orbit | `satellites.js` | `SATELLITE_CONFIG.overlayRenderOrder` and offsets; predicted orbit follows the same real-altitude toggle and fixes the lock-time globe pose to draw an open 96%-period inertial arc with forward-flow highlights; returns to same-sphere mode when real altitude is disabled | Satellite overlay path | Used for selected/locked satellite emphasis. |
| 98-100 | Sun / moon halo and sprite | `celestial.js` | Fixed renderOrder | Celestial picking disabled | Foreground celestial sprites. |
## Full-set rendering and updates

View File

@@ -1,5 +1,9 @@
# Admin Frontend Context
## Compute comparison configuration
The Earth content `compute_comparison` section mounts `ComputeComparisonSettings.tsx`. Structured forms maintain report sources, annual country observations and innovation gaps using the shared Panel, Input, Select, Button and confirmation dialog; operators do not edit JSON. Drafts survive section switches, full-page unload warns about unsaved work, and discarding a draft or restoring defaults requires confirmation. Management data loads on activation. Publishing sends the backend revision to prevent overwriting concurrent edits, and failures preserve the draft. The content area scrolls internally while the heading and publish controls stay in the first viewport. `compute-comparison-model.ts` owns types and same-origin update notifications; `compute-comparison.css` only owns this section's layout.
This document describes the current real structure of the console frontend. The goal is to help future page development, table refactoring, layout governance, and state consolidation quickly find the right entry points.
Related references:
@@ -71,6 +75,8 @@ This keeps Earth, AI, collection management, and other multi-section pages from
## Datasource Collection Queue
`datasource-task-queue.ts` reconciles attempts by task ID. Retrying a source adds a new attempt and preserves failed/completed/cancelled history; source matching is allowed only for active placeholders without an ID. Late events cannot reactivate terminal attempts, and older task polls cannot overwrite the latest datasource task. Task status uses `ListChecks`; refresh retains `RefreshCw`.
The Admin datasource page routes single-source trigger, table-selected trigger, and trigger-all into a browser-download-list style collection queue:
- Queue state is managed by [PlainResourcePages.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/PlainResourcePages.tsx). It is a current-session visibility layer and does not fake task history in `localStorage`.

View File

@@ -412,12 +412,26 @@ Docs supports: category navigation, Markdown rendering, tables and code blocks,
## Compute intelligence
Administrators maintain card data in **Earth content → Compute comparison**. Add a report title, URL, publisher, report year and page/figure locator under Sources, then add country values by observation year, metric and source under Observations. Save and publish applies the complete configuration. Global shares use the world denominator; absolute values use FP32 EFlop/s. Bilateral shares are derived from same-year US and China observations, and regions require every member. Do not mix FP16/FP64 capacity, regional estimates or facility counts. Omit missing countries; enter zero only when the source explicitly reports zero.
Innovation gap observations remain independent US-minus-China values. Referenced reports cannot be removed until their observations are removed or reassigned. Duplicate metric/year rows, missing sources and global shares totaling over 100% are rejected. Concurrent edits return a conflict while preserving the local draft. Restore defaults requires confirmation and restores the bundled report data. Publishing and restoring are audited. Same-origin Earth pages receive a refresh notification; other visible pages check once per minute and hidden pages check when visible again. Reports must still be reviewed manually; configuring a URL does not scrape a report.
Open the analysis icon beside Compute Centers, then enable Show region cards. Connectors draw to their target positions before the cards fade in; subsequent globe motion does not replay entrance. Closing the configuration window or pressing Escape leaves the cards enabled; the analysis icon reopens configuration, while the switch disables the cards. Anchors rotate with Earth while cards remain readable. Dragging or expanding grants reading time; after a substantial change in geographic direction, cards can move together when that materially reduces crossing or detours. Active interaction prevents movement, while manual positions remain preferences rather than permanent pins. Rear regions retain their state without a connector drawn through the globe. Existing layer, news, and media windows remain available.
The picker groups the canonical comparison catalog as China, US, Europe, APAC excluding China, and Other; the groups are display buckets, not statistical denominators. It offers period and metric selection. Bilateral share still uses US + China as its fixed denominator; unavailable measures stay missing for other participants. Regional anchors are label positions, never facility locations. Source buttons open report evidence and facility buttons reuse the existing detail card. Mobile uses a compact regional overview in the drawer. Each row is an accordion: tapping the same header collapses it, tapping another collapses the old row, and at most one long card is open. The expanded card keeps trends, region members, facilities, media, and sources; there is no region subpage. Settings remain a separate on-demand page.
The default national metric is global compute-device scale, covering basic, intelligent, and supercomputer capacity with observations from 2020–2023. The reviewed absolute observations are 302 for 2022 (`caict2023` evidence) and 435 for 2023 (`caict2024` evidence). Japan's global-share observations are 6%/5%/4%/4% for 2020/2021/2022/2023. Product groups APAC and OTHER do not mean the report's Japan or “other” categories, and EUROPE remains missing until its membership matches the report. Bilateral share always uses US + China as its denominator. A missing primary value may show the latest reported year (currently 2023); explicitly selecting 2026 still shows missing and does not backfill. Unconfirmed comparability does not produce year-over-year change. National report metrics remain separate from public facility samples; coverage counts remain auxiliary evidence, never computed capacity or a global coverage rate. TOP500 and Epoch may overlap, so source-record counts are not a global census. API review metadata is `reviewed_at=2026-09-22` with the matching version date. An independent Epoch share mode is not implemented.
The default national metric is global compute-device scale, covering basic, intelligent, and supercomputer capacity with observations from 2020–2023. The reviewed absolute observations are 302 for 2022 (`caict2023` evidence) and 435 for 2023 (`caict2024` evidence). Japan's global-share observations are 6%/5%/4%/4% for 2020/2021/2022/2023. Product groups APAC and OTHER do not mean the report's Japan or “other” categories, and EUROPE remains missing until its membership matches the report. Bilateral share always uses US + China as its denominator. A missing primary value may show the latest reported year (currently 2023); explicitly selecting 2026 still shows missing and does not backfill. Unconfirmed comparability does not produce year-over-year change. National report metrics remain separate from public facility samples; coverage counts remain auxiliary evidence, never computed capacity or a global coverage rate. TOP500 and Epoch may overlap, so source-record counts are not a global census. The bundled reports were reviewed on 2026-09-22; published overrides use their maintained review date and observations. An independent Epoch share mode is not implemented.
This prototype shows up to six content cards. The main card centers on the selected compute metric: a large share percentage or absolute value with its unit, observation year, historical context, and source entry. Missing comparable data is shown as “No comparable data yet”; a trend is omitted when there are no observations rather than rendered as an empty chart. Facility records and coverage metadata remain complete but move to the expanded auxiliary area; sample counts are evidence context, never a compute value or global coverage rate. Region previews may show member counts, and long lists open only when needed. Desktop compact cards are about 268px wide with content-driven height; expanded cards support user resizing up to 480px. Mobile keeps the same single metric meaning in the one-card accordion rather than promoting facility counts. Local card position and size are saved, with a reset-to-auto action. The content layout leaves room for later image and video integration, but those media data are not connected yet. When outside space is insufficient, cards can travel through the globe's foreground instead of teleporting or shrinking to labels.
When the map cards switch is off, the overview summary still loads. Turning it on shares the map loading event; a newer request cancels the previous one. Drawer event handling follows `composedPath()` so replacing inner HTML cannot accidentally collapse the active row. The shared HUD collapsible panel animation is reused and respects reduced-motion preferences. Facility names remain in a scroll region capped at 240px; rows are left-aligned, wrap long names, and retain at least 42px of touch height.
## Surface and object appearance
The real surface retains all four map choices. Day/night shading follows the sun, with uniform illumination when disabled. Selected cables show traveling pulses and landing points use amber micro-markers. Facilities show chip symbols up close while the compact-dot preference remains available. Satellites retain self-glow/ground-coverage modes, trails and their existing orbital motion. BGP severity, vessel heading, related highlights, detail cards and mobile drawers retain their established interactions.
### Satellite orbits and collection attempts
Selecting a satellite shows an open predicted arc with highlights moving in the travel direction. Satellites, trails and footprints remain synchronized. Coverage stays blue across day/night; particle and orbit category colors match the legend. Dragging continues outside the globe silhouette, with reduced sensitivity at extreme zoom. The TV panel has square corners like other cards.
Retriggering a datasource creates a new task while older failures remain in the failed group. Task Status uses a checklist icon, distinct from Refresh. CelesTrak can reuse valid recent download cache; each new collection attempt still gets its own task and updates collected data.

View File

@@ -1,6 +1,20 @@
# `planet.sh` Startup Performance Optimization
## Background
## Windows desktop launcher
The launcher prefers a new Windows Terminal window and explicitly runs PowerShell 7 (`pwsh.exe`), independently of the default Terminal profile. Without PowerShell 7 it falls back to Windows PowerShell; without Terminal it starts the available PowerShell directly. The CMD bootstrap also prefers PowerShell 7. Ordinary entries request elevation; entries already running as administrator still dispatch to the preferred terminal without another elevation request. The child validates its privileges and enters WSL directly, preventing recursive windows. The existing post-restart WSL shell is retained.
On first use, open the actual project folder in Windows Explorer and double-click the repository's `planet.cmd`. It derives the WSL distribution and Linux project directory from its own location, creates `Planet.cmd` on the current user's actual Windows desktop, then follows the normal restart flow. Both `\\wsl$\distribution\...` and `\\wsl.localhost\distribution\...` work. Local Windows-drive checkouts use the default WSL distribution and `wslpath`. Windows resolves the desktop location, including redirected desktops such as OneDrive; WSL, zsh and project dependencies must already be installed.
Subsequent desktop launches use the bound target, request the existing administrator elevation and call `planet.sh restart --allow-lan`. No test ports are embedded: defaults remain frontend 3000, backend 8000 and AI Provider 8010, subject to explicit `DEFAULT_*_PORT` environment overrides. Successful restarts open Earth using the actual `ports.env` values and retain the WSL shell; failures display their error without opening a success page. `scripts/windows/planet-launcher.ps1` owns path resolution, desktop installation and elevation; `scripts/windows/restart.zsh` only bridges to the existing lifecycle script.
Use `planet.cmd --install-only` on Windows to generate or validate a launcher without restarting services. Re-running the repository entry updates the same target's launcher. Other projects and unmanaged files are preserved by choosing a target-specific filename. After moving a checkout, regenerate from its new location; old launchers never guess another directory. Desktop launchers require the scripts in the checkout and are not standalone installation packages.
Do not copy the raw repository `planet.cmd` to the desktop by itself: first installation needs the adjacent `scripts/windows/` directory. On another computer, generate a new launcher from that computer's checkout instead of reusing an old desktop copy. Server paths such as `/home/linkong/planet` and personal workstation paths both work without machine-specific Git edits. Run under the Windows account that owns the WSL distribution; elevating under a different account may expose a different set of registered distributions. Installation itself does not require administrator privileges; elevation is requested for the actual restart.
Run Windows regression checks with `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\harness\test_windows_launcher.ps1`. They cover target resolution, special characters, generated launchers and name collisions. `scripts/harness/test_windows_restart.py` uses disposable command substitutes to check restart arguments, browser opening after success and shell retention after failure. The latter runs in quick-check without starting real services.
## Startup background
Use `zsh ./planet.sh start --non-motion-agent` for daily startup; use `init` when preparing a new environment. When investigating latency, distinguish initial dependency downloads, container readiness, and application initialization using the stage timestamps.

View File

@@ -311,6 +311,8 @@ For each newly confirmed cause, update both language tables with a stable code,
<!-- planet-error-catalog:start -->
| Error code | Matching fragments (semicolon-separated) | Cause / established failure | Remedy |
| --- | --- | --- | --- |
| P_CELESTRAK_NOT_UPDATED | GP data has not updated since your last successful | CelesTrak rejected a repeated download within an update window. HEAD 200 followed by GET 403 can mean preflight consumed the allowance, not an unreachable egress route. | Use the collector without HEAD preflight and preserve validated raw cache. Without valid cache, wait for the next GP update or configure Space-Track instead of retrying repeatedly. |
| P_WINDOWS_LAUNCHER_TARGET_MISSING | P_WINDOWS_LAUNCHER_TARGET_MISSING | The bound WSL project is unavailable or lacks launcher scripts, commonly after moving a checkout, losing access to a distribution or copying another machine's desktop launcher. | Run the repository planet.cmd from the current checkout to regenerate this machine's desktop launcher and verify the WSL distribution; do not hardcode another machine's path. |
| P_PROXY_EXTERNAL | PLANET_PROXY_EXTERNAL | Docker proxy settings belong to another configuration source or have been edited manually. | Inspect daemon.json, systemd proxy settings and the Planet ownership record before changing ownership; existing settings are preserved. |
| P_AUTH_BOOTSTRAP_MISSING | DEFAULT_LOGIN_USER_MISSING | The active backend database is confirmed to lack default accounts, often in an isolated preview that skipped initialization. | Verify database ownership and run the existing account initializer without resetting existing passwords or clearing data. |
| P_AUTH_PROFILE_INVALID | AUTH_IDENTITY_RESPONSE_INVALID | Login succeeds but the identity response lacks required fields or incorrectly rejects a stored local email address. | Load the complete persisted identity, separate response serialization from registration validation, and run default-account identity regressions. |

View File

@@ -74,4 +74,10 @@ Open `/forgot-password`, enter your email, receive a code, then enter the code p
## Try compute intelligence
To maintain card values, an administrator opens **Earth content → Compute comparison**, adds report sources, enters comparable annual country observations, then chooses **Save and publish**. Omit missing countries; facility counts never replace compute shares. Bundled defaults can be restored and Earth cards automatically check published configuration.
Open the analysis icon beside Compute Centers and enable Show region cards. Closing configuration keeps the cards active; the switch controls their visibility. Resize or collapse desktop cards and inspect observed history, sources, and facility details. On mobile, use the Compute drawer tab. National indicators and facility samples are separate. “—” means missing evidence, not zero capacity.
### Inspect satellites and retry collection
Enable satellites in Earth and select a particle to inspect its open predicted orbit, travel-direction highlights and supported footprint. Dragging continues beyond the globe silhouette. A failed datasource can be triggered again: the new task is separate, and older failures remain in the current queue’s failed group.

View File

@@ -498,6 +498,15 @@ Epoch 改用官方公开 CSV,保留 FP16 理论性能、原始日期、状态
两个采集器不再生成示例回退。空原文、转换后空结果、结构错误或相对上次快照减少超过 40% 会失败并保留旧快照;写入失败回滚不完整记录。TOP500 身份切换仅在旧位置名称、规范国家完全一致且唯一时复制位置到新系统 ID,旧位置保留用于历史查询,绝不按名次迁移。
`compute_history.py` 保存从已核对研究计划受控导入的年度数值、来源和版本,参考期与发表时间分开;未知具体发表日保持未提供。`/api/v1/data-products/compute/series` 支持全球份额、固定中美分母的双边份额及已知 FP32 绝对量。创新分差独立返回,不反推单国指数。
`compute_history_defaults.json` 提供原有报告数据,`compute_configuration.py` 从 `system_settings` 的 `compute_comparison` 分类读取完整数据库覆盖;没有记录时使用默认值,不需要迁移或人工初始化。`compute_history.py` 只处理同年聚合,参考期与发表时间分开;未知具体发表日保持未提供。`/api/v1/data-products/compute/series` 支持全球份额、固定中美分母的双边份额及 FP32 绝对量,逐次读取配置并返回 `Cache-Control: no-store`。创新分差独立返回,不反推单国指数。空配置保留缺失,不回填默认观测。
同前缀的 `GET/PUT /configuration` 和 `POST /configuration/reset` 仅允许 admin/super_admin。写入体为 `{revision, config}`,重置只需要 `revision`。Pydantic 校验国家目录、有限数值、比例总和、重复指标年份和报告引用;每个指标年份只允许一个报告口径。PostgreSQL 唯一分类与行锁串行化首次写入和更新,旧版本返回 409。审计记录和配置在同一事务提交;重置移除覆盖,下次读取随版本默认值。`version` 为配置修订标识,`reviewed_at` 为录入的核验日期,不能将管理员配置一概称为官方报告。来源链接只作引用,不触发抓取。
`/api/v1/data-products/compute/facilities` 仅读取 `compute_contract=v1` 的成功快照,数据库执行国家过滤和按来源计数。Epoch 默认排除规划、退役、已被替代和疑似重复记录;TOP500 表示榜单观测,跨源仍未合并。历史选择按采集时间截止,不将最近抓到的旧资料冒充过去已知的快照。地理结果有返回上限与截断标记,记录统计不受该上限影响。官方 site helper 按精确 `source` + `source_id` 匹配;access map 中心只表示 site 级参考点,并在 `source_note` 保留官方 URL。
### CelesTrak 下载窗口与缓存
CelesTrak active 和 fallback group 均禁用 HEAD 预检,直接 GET,避免预检被上游记为下载后使正文请求收到 403。完整有效缓存两小时内复用;到期后进行条件 GET(有 ETag/Last-Modified 时)或普通 GET。304 复用已校验缓存;仅明确的“GP data has not updated”403 可以回退到有效缓存,其他 403 不伪装成功。fallback group 同样检查缓存时效,不永久使用旧文件。
下载在 `.part` 上校验非空 GP 记录列表后原子替换缓存,失败保留上一份有效文件。内容长度以 GET 响应为准;压缩响应不拿压缩长度校验解压后的字节数。其他采集器继续支持 HEAD 元数据和 Range 断点续传。原始缓存不等于已入库数据,恢复缓存后仍须触发新采集任务。

View File

@@ -1,13 +1,18 @@
# 智能星球前端结构
## 高清地表与大气材质
高清地表由 `earth-surface-material.js` 的单次绘制 `ShaderMaterial` 负责,保持原有 R+0.48 网格、深度策略和地表拾取对象。四张 8K 底图仍由原控制器切换,成功后更新采样 uniform 并释放旧纹理,失败保留原图。法线、视线和真实太阳方向统一到世界坐标;土地哑光,海洋只有掠射角冷色反射,没有白色镜面高光。海洋区分优先复用现有海陆地理纹理,未加载时使用保守色差估计,冰雪抑制反射;关闭国界线不移除光学遮罩。原始 JPEG 不重绘、不降采样。
颜色纹理标记 sRGB 并启用 mipmaps。r128 在地表 Shader 中解码 sRGB,r160 由纹理硬件格式解码;二者在线性空间合成光照后只编码一次。局部 filmic 曲线只作用于地表,不打开全局 ACES 曝光,避免改变星空和业务图层。晨昏范围为法线点积 [-0.075, 0.16],夜侧单独计算地理纹理透光与冷色环境漫射:对局部色调映射后的纹理用 0.55 次幂保留暗部层次,再分别应用陆地冷灰绿、海洋深靛蓝的纹理系数和极弱环境底色;最后在线性空间按晨昏系数混合昼夜并统一输出 sRGB。日面曝光和反射不变,不添加虚构城市灯光。大气收敛为 R×1.025 的一个 BackSide/Additive 壳,depthWrite=false、depthTest=true,内沿散射并入地表;云图独立开关,使用哑光昼夜材质并在 1.1 顺序绘制。星图使用已有 `starmap_deep_8k.jpg`,不加染色遮罩。
## 地表贴图资源记录
2026-09-21,`assets/8k_earth_daymap.jpg` 替换为 Natural Earth I 配套栅格的 8192×4096 Web 派生图,加载路径和渲染代码未变。源图为 EPSG:4326、16200×8100;旧 JPG 在仓库 `resources/earth/archive/2026-09-21/` 逐字节保留。来源、许可、源包/目录版本差异、SHA256、JPEG 参数及按导出尺寸重算的定位文件见 `resources/earth/natural-earth-1/`。原始大文件位于 Git 忽略的 `downloads/earth/`,不进入前端发布包。
底图选择器默认使用“原始底图”,并将该选项放在首位,显示菜单可切换并在本地保存选择。已有 Natural Earth I 保留可用,并增加“原始底图”选项,使用 2026-09-21 归档原图的逐字节副本;NASA 21K 只作为源归档,运行时统一使用一张 8K 贴图。新贴图成功加载后才替换并释放旧 GPU 纹理,失败时保留旧纹理,过期响应不会覆盖当前结果;这是源切换,不新增渲染层。物理贴图为 JPEG sRGB,未烘焙政治边界,也未完成逐段边界对齐验收。星空逐字节恢复到上次提交前的 commit `83a10a6c`:`celestial.js` 与该提交一致,删除 `skyTint`、`skyBrightness`,`brightStarOpacity` 恢复为 `.88`,不再校准星空密度和颜色。高清 overlay 使用白色 `MeshBasicMaterial`、opacity 1、`toneMapped:false`,由 `texture-colors.js` 统一 sRGB 读写;r128 使用 `encoding`/`LinearTosRGB`,r160 使用 `colorSpace`/colorspace fragment。不叠加 Phong 白光、彩色暮光、蓝色夜染、`cameraBoost` 或 shoulder 曲线;daylight 中性亮度不超过原图最大值,dark 仅做 neutral 缩放,原图资源不变。Natural Earth 原图本身偏浅,不声称恢复不存在的细节。为 WebGL1 的 `fwidth` 开启 derivatives。
昼夜明暗使用以太阳地平线为中心的窄平滑过渡(法线点积 ±0.12)。日面保持原图亮度上限;夜面线性光照系数为 0.24,原图暗部最高保留 0.60,按源亮度连续过渡,以保持暗色海洋和森林细节。只使用中性标量,不增加曝光、彩色罩层、额外渲染通道或纹理。
地表底图与新闻频道复用 `hud-select-menu.js` 的 HUD 浮层、列表、选中标记、键盘导航和定位;`tv-source-menu.js` 仅保留频道文案适配。底图关闭搜索、分页和计数,菜单通过触发按钮归属参与移动抽屉的内部点击判断。
本文件描述当前智能星球前端的真实结构,重点是帮助后续继续改 HUD、图层、媒体面板、真实地形、BGP 可视化时,不再重复踩结构和状态同步上的坑。
@@ -19,6 +24,8 @@
## 当前目标
算力卡片的年度观测由 `/api/v1/data-products/compute/series` 返回,后台“算力对比”配置为唯一维护入口。`compute-topic.js` 以 no-store 请求读取数据,接收同源 `planet-compute-configuration` 发布通知,并在可见且专题启用时每 60 秒及页面恢复可见时检查更新;刷新观测不重拉设施图层。`destroy()` 释放计时器、通知通道和可见性监听。国家目录、区域完整覆盖条件与缺失语义仍由后端统一处理。
Earth 前端不是普通管理页,它是独立的大屏展示前端。当前产品目标是:
- 维持地球视图的空间感和可读性
@@ -437,6 +444,8 @@ asset 图标大小由 `Interactable` 的 `icon.fitSize` 控制。SVG / 图片文
[controls.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/controls.js) 统一维护智能星球缩放状态,所有入口最终都必须调用 `setZoomLevel()` 写相机距离。不要在其他模块直接写 `camera.position.z`,否则缩放百分比、拖拽灵敏度和 Interactable 聚合阈值会再次分叉。
鼠标与单指统一使用原有屏幕位移驱动、0.18 平滑和松手惯性。按下后拖出球体轮廓仍连续旋转,不再调用射线/球面命中作为拖动前提。常规缩放保留原灵敏度;球体超出视口后平滑加入按相机距地表距离和视口尺寸计算的旋转上限,修正极大倍率的放大效应。左右绕地理轴、上下改倾角,四元数保持多圈不反向;双指缩放切换与 pointer capture 保留。
滚轮输入分两类处理:传统鼠标滚轮保留 10% 档位和短动画,并用 `wheelZoomTarget` 作为连续滚动的逻辑基准;触控板 / 高精度滚轮按 pixel delta 连续缩放,直接调用 `setZoomLevel()`,不走 10% 档位动画。触控板路径还会过滤反向后的短窗口旧方向小 residual delta,避免惯性尾巴把用户刚反向的缩放又拉回旧方向。
该提示每 90ms 最多更新一次,显示 760ms 后淡出。它是视角反馈,不是数据加载进度,也不应该写进图层 loading 状态。
@@ -445,7 +454,7 @@ asset 图标大小由 `Interactable` 的 `icon.fitSize` 控制。SVG / 图片文
`globe-navigation.js` 统一投影缩放与表面拖动。相机距离采用 `sqrt(R² + (D₀² - R²) / zoom²)`,并保留最小地表净空;100% 视角不变,500% 仍在球外,反向换算也使用同一公式。滚轮、按钮、捏合、搜索与巡航继续共用 `setZoomLevel()`。
鼠标和单指通过相机射线取得球面抓点,以四元数将同一地表点旋转到当前接触位置;按住期间不使用经验倍率或追赶平滑,自转也不叠加。松手后沿实际旋转轴衰减惯性,停住再松手或取消手势不触发甩动。双指进入缩放时清除拖动惯性,回到单指时重建抓点。拖动阈值按起点至当前位置的累计位移判断,避免慢拖被当作点击。
鼠标和单指在按下时按实际相机视锥选择并固定拖动模式:球体完整放入视口时,使用旧版屏幕位移、缩放灵敏度、0.18 追赶平滑和松手衰减惯性,指针移出球面仍保持原方向;球体放大到被视口裁切且按下命中球面时,才用射线抓点与四元数逐像素跟手。大球拖动移出球面后暂停更新并清除甩动速度,不再用可能反向的最近点代替真实交点;从球外开始则使用屏幕位移拖动。一趟拖动中不切换模式,自转不叠加。双指进入缩放时清除惯性,回到单指时重新判断模式并建立抓点。拖动阈值仍按起点累计位移判断,取消手势不产生惯性。
### `data-status-target`
@@ -493,7 +502,7 @@ Earth 设置面板当前由 [controls.js](/home/ray/dev/linkong/planet/frontend/
卫星真实高度开关由 `controls.js` 持久化,实际渲染状态在 `satellites.js`。开启时,SGP4 得到的真实半径会按对数压缩到当前 Earth 视觉半径范围;关闭时,卫星点、轨迹和预测轨道都回到旧版同层球面。切换时必须刷新卫星位置并清理轨迹缓存,避免同一条轨迹混入两个高度模型。`maxRealAltitudeOffset = 25` 是当前相机和 `earthRadius = 100` 下的视觉上限:它让 GEO / MEO 比 LEO 明显更高,但把最高轨道控制在地球半径外约 25%,避免选择点、红色轨迹和主体地球之间出现过大的空场。
SGP4 传播输出是惯性系位置,不能直接当成 Earth 的经纬度固定坐标使用。`satellites.js` 会用当前时间的 `gstime` 把 ECI/TEME 位置转换到 ECF,再映射到 `latLonToVector3()` 使用的 Three.js 坐标轴。卫星点和短尾迹使用随采样时间变化的地固坐标,表示相对当前地球表面的实际位置;锁定后的预测轨道线使用锁定时刻固定的 `gstime`,把未来一圈惯性轨道投到当前地球姿态上显示,因此会闭合,并且轨道面倾角应与详情卡一致。fallback 预测轨道也必须使用真正的 RAAN + inclination 轨道平面公式,不能把 inclination 当成恒定纬度。
SGP4 传播输出是惯性系位置,不能直接当成 Earth 的经纬度固定坐标使用。`satellites.js` 会用当前时间的 `gstime` 把 ECI/TEME 位置转换到 ECF,再映射到 `latLonToVector3()` 使用的 Three.js 坐标轴。卫星点和短尾迹使用随采样时间变化的地固坐标,表示相对当前地球表面的实际位置;锁定后的预测轨道线使用锁定时刻固定的 `gstime`,把未来 96% 周期的惯性轨道投到当前地球姿态上显示为开放弧线;不追加首点或用直线强制封口,轨道面倾角与详情卡一致。流光按累计弧长和未来采样方向移动。fallback 预测轨道也必须使用真正的 RAAN + inclination 轨道平面公式,不能把 inclination 当成恒定纬度。
国界精度偏好独立存储在 `country-boundaries.js` 的 `planet.earth.boundaries.highPrecisionEnabled`。未开启高精时,即使本机已经有高精 manifest/PMTiles,也继续加载低精 `countries-admin0.min.geojson` fallback;开启高精但高精产物缺失时,智能星球工具栏设置会调用 `/api/v1/earth/boundaries/build` 启动后台构建并轮询进度。构建成功后调用 `reloadCountryBoundaries()` 热切换,不再刷新整个页面。国界 hover 与 tooltip 解耦:只要地表坐标落在国界 polygon 内就保持高亮;如果鼠标同时命中卫星、船只、BGP 等 interactable,tooltip 显示 interactable 信息,但国界高亮不应闪烁。
@@ -579,3 +588,7 @@ Earth 由 `earth-runtime-plugin.mjs` 将本地模块合并为带内容哈希的
空间卡片定位后保持隐藏,先复用 `CalloutConnector` 的 420 ms 绘线动画,再按共享 HUD 的 180 ms 淡入时长显示卡片。绘线期间固定目标位置,后续跟随运动不重播入场;系统减少动态效果时直接呈现。
物件点击、搜索定位及手势确认统一通过 `PresentationController`。海缆选择处理器只更新选择与图例,不再绕过控制器提前显示卡片;共享 InfoCard 的显示回调带版本标记,新的隐藏/预布局请求会使旧回调失效。所有连线卡片以绘线完成事件作为显示门槛,取消的旧巡航不能关闭新的选择卡片。物件详情复用算力卡的边缘候选与避让评分,按隐藏状态下测得的真实尺寸定位置;手机搜索结果被选中时收起搜索抽屉,让地图定位、引导线与精简卡片可见。
### 卫星粒子与平滑显示
卫星仍由真实 GP/TLE 传播器和 Worker 每 250ms 计算采样。`satellite-motion.js` 在相邻样本之间逐帧做半径保持插值,不改轨道、采样时刻偏移或真实高度策略。绘制缓冲、拾取使用的 current 位置、尾迹末端、悬停/锁定环和覆盖投影共享平滑位置;数据替换、数量变化或高度重置会清空插值,避免跨对象拖影。粒子用批量 Points 中的解析圆盘明暗表现参考页的小球感,缩放温和变化,避免为每颗卫星增加球网格。Starlink 与 Iridium 覆盖统一使用 `SATELLITE_CONFIG.footprintColor`(`#3399ff`);移除日侧黄/夜侧蓝的 Shader 混色,日照只调节透明度。卫星和预测轨道沿用同一轨道类别色,粒子使用薄深色衬边保证明亮地图上的可读性。范围计算和能力策略不变。

View File

@@ -1,5 +1,17 @@
# 智能星球图层样式属性索引
`EARTH_MATERIAL_CONFIG.surface.night` 集中夜侧纹理对比(detailGamma=0.55)及海陆各自的 tint/ambient 参数。它只参与夜侧混合,不调整日面曝光;沿用现有地理遮罩,无新增贴图或 Draw Call。
## 现代物件视觉
- 地表:`EARTH_MATERIAL_CONFIG.surface` 集中 exposure=0.9、landSaturation=0.9、oceanAbsorption=0.36、oceanDeepColor=[0.004,0.012,0.032]、夜面保留与 Fresnel 参数;`atmosphere` 集中单壳半径、颜色和强度。低清基座及地形关闭镜面高光。
- 海缆:常态冷色与原分类色混合,图例与线路保持一致;选中后参考流光沿真实线路累计长度移动,6 个周期、速度 4.5。复用同一批量 draw,绘制材质不写深度;原 Line 对象、cableId、选中逻辑不变。
- 登陆点:`marker-landing-point.svg` 为 128×128 琥珀微核单色源,取代带高光的程序球;Sprite 拾取和 billboard 批量绘制保持原尺寸逻辑。
- 算力:三个规范 SVG 只负责内置符号;`marker-badges.js` 与 `interactable.js` 共同绘制渐变方块底板、浅色边圈、上沿高光与投影。GPU/AI 使用电紫堆叠层,超算使用电紫芯片,数据中心/基础设施使用青绿机柜。估算标志和原拾取/联动保留。
- 卫星:保留真实倾角分类,用蓝、橙、绿、紫、玫红、灰区分,图例、粒子与预测轨道使用同一类别色。粒子不受日夜染色,薄深衬边提高浅色地表对比;覆盖投影统一蓝色,日照只改变透明度。轨道传播、拾取与覆盖范围保持原逻辑。
本文记录当前 Earth 前端各图层的材质、颜色、透明度、线宽、半径偏移和
`renderOrder` 等样式属性。层级关系请配合
[智能星球渲染图层顺序](/home/ray/dev/linkong/planet/docs/technical/zh/earth-render-layer-order.md)
@@ -23,15 +35,11 @@
| 智能星球基座半径 | `CONFIG.earthRadius` | `100` | `earth.js:createEarth()` |
| 智能星球基座颜色 | `EARTH_MATERIAL_CONFIG.color` | `0x010609` | `MeshPhongMaterial.color` |
| 智能星球基座 emissive | `EARTH_MATERIAL_CONFIG.emissive` | `0x010609` | `MeshPhongMaterial.emissive` |
| 智能星球基座 specular | `EARTH_MATERIAL_CONFIG.specular` | `0x1a2d45` | `MeshPhongMaterial.specular` |
| 智能星球基座 shininess | `EARTH_MATERIAL_CONFIG.shininess` | `12` | `MeshPhongMaterial.shininess` |
| 智能星球基座 specular | `EARTH_MATERIAL_CONFIG.specular` | `0x000000` | `MeshPhongMaterial.specular` |
| 智能星球基座 shininess | `EARTH_MATERIAL_CONFIG.shininess` | `0` | `MeshPhongMaterial.shininess` |
| 智能星球基座 opacity | `EARTH_MATERIAL_CONFIG.opacity` | `1` | `MeshPhongMaterial.opacity` |
| 高清材质半径偏移 | `EARTH_MATERIAL_CONFIG.textureOverlayAltitudeOffset` | `0.48` | 独立高清材质球半径;必须与海陆基座和地球基座保持足够深度间距,避免远距 z-fighting |
| 高清材质透明度 | `EARTH_MATERIAL_CONFIG.textureOverlayOpacity` | `0.88` | 高清材质 `MeshPhongMaterial.opacity` |
| 高清材质 renderOrder | `EARTH_MATERIAL_CONFIG.textureOverlayRenderOrder` | `0.96` | `_earthTextureOverlay.renderOrder` |
| 高清材质 specular | `EARTH_MATERIAL_CONFIG.textureOverlaySpecular` | `0x05080d` | 降低直射区域镜面高光,避免贴图死白 |
| 高清材质 shininess | `EARTH_MATERIAL_CONFIG.textureOverlayShininess` | `4` | 降低高光集中度 |
| 高清材质颜色乘色 | inline | `0xffffff` | `_earthTextureOverlayMaterial.color` |
## Earth 遮挡与昼夜
@@ -39,7 +47,7 @@
| --- | --- | --- | --- |
| 遮挡球半径系数 | `EARTH_MATERIAL_CONFIG.occluderRadiusFactor` | `0.999` | 深度遮挡球半径 |
| 遮挡球分段 | `EARTH_MATERIAL_CONFIG.occluderSegments` | `48` | 遮挡球几何分段 |
| 遮挡球 renderOrder | inline | `-1` | `occluder.renderOrder` |
| 遮挡球 renderOrder | inline | `0.5` | `occluder.renderOrder` |
| 昼夜太阳方向 | `EARTH_MATERIAL_CONFIG.dayNight.sunDirection` | `{ x: 1, y: 0.2, z: 0.4 }` | 自定义 day/night shader |
| 夜侧最低亮度 | `EARTH_MATERIAL_CONFIG.dayNight.nightFloor` | `0.24` | shader uniform |
| 日侧增强 | `EARTH_MATERIAL_CONFIG.dayNight.dayBoost` | `1.12` | shader uniform |
@@ -53,30 +61,13 @@
| 正式名称 | 变量名 | 当前值 | 使用位置 / 说明 |
| --- | --- | --- | --- |
| 内层大气半径系数 | `EARTH_MATERIAL_CONFIG.atmosInnerRadiusFactor` | `1.01` | `atmosInnerGeo` |
| 内层大气分段 | `EARTH_MATERIAL_CONFIG.atmosInnerSegments` | `64` | `atmosInnerGeo` |
| 内层大气颜色 | `EARTH_MATERIAL_CONFIG.atmosInnerColor` | `[0.25, 0.62, 1.0]` | shader RGB |
| 内层大气 rim power | `EARTH_MATERIAL_CONFIG.atmosInnerRimPower` | `3.2` | shader rim |
| 内层大气强度 | `EARTH_MATERIAL_CONFIG.atmosInnerIntensity` | `0.18` | shader alpha multiplier |
| 外层大气半径系数 | `EARTH_MATERIAL_CONFIG.atmosOuterRadiusFactor` | `1.0025` | `atmosOuterGeo` |
| 外层大气分段 | `EARTH_MATERIAL_CONFIG.atmosOuterSegments` | `48` | `atmosOuterGeo` |
| 外层大气颜色 | `EARTH_MATERIAL_CONFIG.atmosOuterColor` | `[0.18, 0.45, 0.9]` | shader RGB |
| 外层大气 rim power | `EARTH_MATERIAL_CONFIG.atmosOuterRimPower` | `9.0` | shader rim |
| 外层大气强度 | `EARTH_MATERIAL_CONFIG.atmosOuterIntensity` | `0.0025` | shader alpha multiplier |
| 大气辉光 blending | inline | `THREE.AdditiveBlending` | `ShaderMaterial.blending` |
| 大气辉光 renderOrder | inline | `1` | `atmosInner/Outer.renderOrder` |
| 无高清材质边缘光颜色 | `EARTH_MATERIAL_CONFIG.rimGlowColor` | `[0.42, 0.72, 1.0]` | 高清材质隐藏或不可用时的 Fresnel shell RGB |
| 无高清材质边缘光半径系数 | `EARTH_MATERIAL_CONFIG.rimGlowRadiusFactor` | `1.0035` | `earth-rim-glow` 外扩球壳半径 |
| 无高清材质边缘光 rim power | `EARTH_MATERIAL_CONFIG.rimGlowPower` | `3.4` | shader rim 衰减;值越大边缘越窄 |
| 无高清材质边缘光强度 | `EARTH_MATERIAL_CONFIG.rimGlowIntensity` | `0.24` | shader alpha multiplier |
| 无高清材质边缘光分段 | `EARTH_MATERIAL_CONFIG.rimGlowSegments` | `96` | `earth-rim-glow` 几何分段 |
| 无高清材质边缘光 renderOrder | `EARTH_MATERIAL_CONFIG.rimGlowRenderOrder` | `1.08` | `_earthRimGlow.renderOrder` |
| 无高清材质边缘光 depthTest | inline | `false` | 避免被海陆基座或地表填充遮住 |
| 云图半径偏移 | `CLOUD_LAYER_CONFIG.radiusOffset` | `3` | 云层球半径 |
| 云图分段 | `CLOUD_LAYER_CONFIG.widthSegments / heightSegments` | `64 / 64` | 云层球几何分段 |
| 云图透明度 | `CLOUD_LAYER_CONFIG.opacity` | `0.15` | `MeshPhongMaterial.opacity` |
| 云图透明度 | `CLOUD_LAYER_CONFIG.opacity` | `0.15` | `MeshBasicMaterial.opacity` |
| 云图贴图 | `CLOUD_LAYER_CONFIG.textureUrl` | `"./assets/earth_clouds_1024.png"` | 云层贴图 |
| 云图 blending | inline | `THREE.AdditiveBlending` | `MeshPhongMaterial.blending` |
| 云图 blending | inline | `THREE.AdditiveBlending` | `MeshBasicMaterial.blending` |
## 海陆基座与国界
@@ -129,8 +120,8 @@
| 地形透明度 | `TERRAIN_CONFIG.opacity` | `0.68` | `MeshPhongMaterial.opacity` |
| 地形颜色 | `TERRAIN_CONFIG.color` | `0x8aa884` | `MeshPhongMaterial.color` |
| 地形 emissive | `TERRAIN_CONFIG.emissive` | `0x030704` | 降低自发光,恢复地形明暗层次 |
| 地形 specular | `TERRAIN_CONFIG.specular` | `0x344438` | 给地形局部光泽,不抬高高清贴图直射亮度 |
| 地形 shininess | `TERRAIN_CONFIG.shininess` | `16` | 收紧地形高光,增强起伏辨识 |
| 地形 specular | `TERRAIN_CONFIG.specular` | `0x000000` | 给地形局部光泽,不抬高高清贴图直射亮度 |
| 地形 shininess | `TERRAIN_CONFIG.shininess` | `0` | 关闭镜面高光 |
| 地形 renderOrder | inline | `1.2` | `terrain.renderOrder` |
| 地形 polygonOffset | inline | `factor -1`, `units -1` | 降低贴近球面时的闪烁 |
@@ -180,8 +171,8 @@
| 卫星真实高度压缩尺度 | `SATELLITE_CONFIG.altitudeCompressionKm` | `1200` | TLE/SGP4 高度压缩映射,数值越大高轨差异越温和 |
| 卫星真实高度上限 | `SATELLITE_CONFIG.maxDisplayAltitudeKm` | `40000` | 压缩映射的高度截断,覆盖 GEO 附近高度 |
| 卫星真实高度显示偏移范围 | `minRealAltitudeOffset / maxRealAltitudeOffset` | `4 / 25` | 压缩后映射到 `CONFIG.earthRadius + offset`;`25` 约为当前地球半径 `100` 的四分之一,用于保留高轨分层同时避免 GEO/MEO 轨迹离主体过远 |
| 卫星点基础像素大小 | `SATELLITE_CONFIG.dotBaseSize` | `2.8` | 点 shader size |
| 卫星背景点缩放 | `SATELLITE_CONFIG.dotBackdropScale` | `1.28` | 背景点大小 |
| 卫星点基础像素大小 | `SATELLITE_CONFIG.dotBaseSize` | `2.2` | 点 shader size |
| 卫星背景点缩放 | `SATELLITE_CONFIG.dotBackdropScale` | `1.4` | 背景点大小 |
| 卫星点透明度范围 | `dotOpacityMin / dotOpacityMax` | `0.42 / 1.0` | 呼吸动画 |
| 卫星点呼吸速度 | `SATELLITE_CONFIG.dotBreathingSpeed` | `0.12` | 点 opacity 动画 |
| 卫星背景点颜色 | inline | `0x0b1626` | backdrop point baseColor |
@@ -235,8 +226,8 @@ AIS 船只普通态使用批量 `THREE.Points`,不是逐船 `THREE.Sprite`。
| hover 缩放 | `COMPUTE_CENTER_CONFIG.marker.hoverScale` | `1.16` | hover overlay 尺寸倍率 |
| locked 缩放 | `COMPUTE_CENTER_CONFIG.marker.lockedScale` | `1.22` | locked overlay 尺寸倍率,并叠加 pulse |
| dimmed 缩放 / 透明度 | `dimmedScale / dimmedOpacity` | `0.82 / 0.34` | dim 状态 |
| 超算颜色 | `COMPUTE_CENTER_CONFIG.colors.supercomputer` | `"#38bdf8"` | marker texture |
| GPU 集群颜色 | `COMPUTE_CENTER_CONFIG.colors.gpu_cluster` | `"#2dd4bf"` | marker texture |
| 超算颜色 | `COMPUTE_CENTER_CONFIG.colors.supercomputer` | `"#a855f7"` | marker texture |
| GPU 集群颜色 | `COMPUTE_CENTER_CONFIG.colors.gpu_cluster` | `"#a855f7"` | marker texture |
| 关联颜色 | `COMPUTE_CENTER_CONFIG.colors.linked` | `"#f8fafc"` | 关联态 |
| 算力中心 renderOrder | local `COMPUTE_CENTER_RENDER_ORDER` | `4.5` | 地表设施低于卫星点 |
@@ -286,3 +277,30 @@ AIS 船只普通态使用批量 `THREE.Points`,不是逐船 `THREE.Sprite`。
| 星空半径范围 | `minRadius + radiusJitter` | `800 + 200` | 随机分布 |
| 星空点颜色 | `STARFIELD_CONFIG.color` | `0xffffff` | `PointsMaterial.color` |
| 星空点大小 | `STARFIELD_CONFIG.size` | `0.5` | `PointsMaterial.size` |
## 方块徽标分类与配色
| 类型 | 主色 | 内置图标 |
| --- | --- | --- |
| 数据中心/基础设施 | 青绿 `#14b8a6` → `#0d9488`,边框 `#5eead4` | 服务器机柜 |
| GPU/AI | 电紫 `#a855f7` → `#7e22ce`,边框 `#d8b4fe` | 堆叠算力层 |
| 超级计算机 | 同一电紫 | 芯片 |
| 海缆登陆点 | 琥珀 `#f59e0b`,浅金 `#fef3c7` 边圈 | 发光圆核 |
| BGP 观测站 | 蓝色及原活动热度色 | 扁平广播塔,不使用方块底板 |
| BGP 事件 | 低/中/高/严重:蓝/琥珀/橙/红 | 不规则扁平符号(三角、感叹号、波动、爆发、泄漏),不使用方块 |
| 船舶 | 货轮蓝、油轮橙、客船青绿、渔船琥珀、军舰靛紫、其他银灰 | 方块内航向箭头,停泊状态独立保留 |
| 自定义标记 | 地点绿、备注黄、告警红、默认蓝 | 地点针、备注页、告警三角 |
BGP 保持不规则扁平符号作为唯一例外;其他有限地表物件使用缓存的徽标纹理,不为每个图标新增 DOM 或独立绘制对象。船舶继续按航向分桶,以顶点色区分船型,不将船型与航向相乘扩张批次数。卫星使用参考的鲜明类别色与薄深色衬边;轨道和覆盖计算不变。“低缩放圆点”开关仍可开启,新默认关闭;渲染与拾取尺寸共同尊重开关,不再关闭后仍强制用圆点。
### 卫星统一色板
参考 [satellitemap.space](https://satellitemap.space/) 的类别色;本地 3d.html 中的模拟壳层与数量不作为项目分类依据。当前项目仍按真实轨道倾角分类:0–30° 蓝 `#3399ff`、30–60° 橙 `#ff801a`、60–90° 绿 `#00e680`、90–120° 紫 `#cc33ff`、120–180° 玫红 `#ff3366`,未知灰 `#94a3b8`。同一颗卫星跨昼夜保持同一颜色,预测轨道不再使用无关的黄紫渐变。
覆盖统一 `#3399ff`,opacity=0.34,日侧透明度增益=1.65;不再以黄色区分日面。粒子深色衬边尺寸系数=1.4、透明度=0.46,复用原有背景点批次,没有新增绘制批次。
### 选中轨道与面板轮廓
预测轨道绘制 96% 周期的开放弧线,不追加首点,端部渐隐;按累计弧长沿未来采样方向推进亮色流光,复用同一 Line 绘制。电视与通用 HUD 外壳恢复方角,播放器裁剪区域同样为方角;不改变窗口尺寸与拖拽。发布代码移除临时逐帧性能统计,不保留只用于验收的 DOM 诊断接口。

View File

@@ -12,17 +12,17 @@
## 地表图层栈
算力专题沿用原算力中心 Interactable 图标、深度与层次顺序;国家/年份切换会替换该层数据并清除旧选中状态。专题 HUD 属于屏幕 UI,在 `main.js` 的指针排除列表中,不参与地球 picking;区域数据卡在屏幕空间由地理锚点牵引,背面不画穿球连线,设施详情复用原详情卡和移动端详情抽屉。外层大气壳保持原有实现;星空逐字节恢复到 commit `83a10a6c`,`brightStarOpacity` 为 `.88`,删除 `skyTint`/`skyBrightness`,不再校准密度和颜色。高清 overlay 使用白色 `MeshBasicMaterial`、opacity 1、`toneMapped:false`;`texture-colors.js` 统一选择 r128 的 `encoding`/`LinearTosRGB` 或 r160 的 `colorSpace`/colorspace fragment。不叠加 Phong 白光、彩色暮光、蓝色夜染、camera boost 或 shoulder 曲线。没有新增后处理、GPU draw pass 或高分辨率纹理;算力专题新增 45 个本地 SVG 旗帜资源。
算力专题沿用原算力中心 Interactable 图标、深度与层次顺序;国家/年份切换会替换该层数据并清除旧选中状态。专题 HUD 属于屏幕 UI,在 `main.js` 的指针排除列表中,不参与地球 picking;区域数据卡在屏幕空间由地理锚点牵引,背面不画穿球连线,设施详情复用原详情卡和移动端详情抽屉。高清地表由 `earth-surface-material.js` 的单次绘制 `ShaderMaterial` 负责,保持原有 R+0.48 网格、深度策略和地表拾取对象。四张 8K 底图仍由原控制器切换,成功后更新采样 uniform 并释放旧纹理,失败保留原图。法线、视线和真实太阳方向统一到世界坐标;土地哑光,海洋只有掠射角冷色反射,没有白色镜面高光。海洋区分优先复用现有海陆地理纹理,未加载时使用保守色差估计,冰雪抑制反射;关闭国界线不移除光学遮罩。原始 JPEG 不重绘、不降采样。 颜色纹理标记 sRGB 并启用 mipmaps。r128 在地表 Shader 中解码 sRGB,r160 由纹理硬件格式解码;二者在线性空间合成光照后只编码一次。局部 filmic 曲线只作用于地表,不打开全局 ACES 曝光,避免改变星空和业务图层。晨昏范围为法线点积 [-0.12, 0.28],夜面在线性色调映射后保留 0.12–0.32 光照,避免暗部被曲线再次压黑。大气收敛为 R×1.025 的一个 BackSide/Additive 壳,depthWrite=false、depthTest=true,内沿散射并入地表;云图独立开关,使用哑光昼夜材质并在 1.1 顺序绘制。星图使用已有 `starmap_deep_8k.jpg`,不加染色遮罩。
| 顺序 | 图层 | 来源 | 渲染 / 半径策略 | 深度 / 交互策略 | 备注 |
| --- | --- | --- | --- | --- | --- |
| -1000 | 天体背景 mesh | `celestial.js` | 背景球 | 不参与地表拾取 | 位于所有智能星球内容之后。 |
| -1 | 智能星球遮挡球 | `earth.js` | 地球内侧不可见球 | 写入深度 | 遮挡地球背面的对象。 |
| 0.5 | 智能星球遮挡球 | `earth.js` | 地球内侧不可见球 | 写入深度 | 遮挡地球背面的对象。 |
| 0 | 智能星球基座球 | `earth.js` | `CONFIG.earthRadius` | 地表拾取兜底目标 | 深色基座,所有可选地图层关闭时仍可见。 |
| 0.2 | 国界暗色 tint | `country-boundaries.js` | `tintAltitudeOffset` | 禁用 raycast | 高清材质关闭时使用。 |
| 0.86 | 海陆基座填充 | `country-boundaries.js` | `landAltitudeOffset = 0.32`; 海洋 `#010609`,陆地 `#080f1b` | 禁用 raycast | 即使国界线关闭,基座地图仍保持可用;半径与基座球拉开以避免远距 z-fighting。 |
| 0.96 | 高清 Earth 材质 | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | 可见时作为地表拾取目标 | 高清材质始终压过海陆基座填充;半径必须高于海陆基座并与基座球保持足够间距。 |
| 1 | 大气辉光和云图 | `earth.js` | 大气 / 云层球 | 不走普通对象选择路径 | 云图由“大气云图”图层开关控制。 |
| 1 / 1.1 | 大气辉光 / 云图 | `earth.js` | 单层大气 R×1.025;云图 R+3 | 大气 BackSide、depthWrite=false、depthTest=true;保留云图开关 | 内沿光照并入高清地表,不新增全屏后处理。 |
| 1 | 海缆 / 登陆点 | `cables.js`, `cable-batches.js` | 海缆全量线段合并为一个 `LineSegments`;登陆点全量使用实例化 billboard;`renderOrder = 1`、海缆半径偏移仍为 `0.2`;登陆点锚点改为高清地表的 `0.48` | 原始 `Line` / `Sprite` 仅作为逐项拾取和选择状态对象,材质不再单独绘制;登陆点仍按球体遮挡判断背面可见性,批量材质 `depthTest: false` | 样式通过线缆样式纹理和登陆点实例属性同步;保留颜色、脉冲、尺寸、显隐与点击语义。 |
| 1.2 | 真实地形 | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` 加地形位移 | 禁用 raycast | 地形压过高清材质;高清材质关闭时临时隐藏,重新开启后恢复原状态。 |
| 2.05 | 经纬线 | `earth.js` | `CONFIG.earthRadius + 0.14` | 禁用 raycast | 低透明度显示在高清材质上。 |
@@ -36,7 +36,7 @@
| 4.5 | 算力中心 | `compute-centers.js`, `interactable.js` | 使用 `COMPUTE_CENTER_RENDER_ORDER` 并由 `Interactable` 绘制 | 通过 `Interactable` 屏幕空间 picking,参与同坐标避让 | 地表设施层,保持在卫星下方。登陆点已下沉到海缆层。 |
| 5 | 卫星背景点 | `satellites.js` | 固定 renderOrder;默认按 TLE/SGP4 真实高度压缩到 `CONFIG.earthRadius + 4..25`,关闭真实高度或传播失败时回退到 `fallbackAltitudeOffset = 8` | 屏幕空间卫星拾取 | 位于卫星点下方。 |
| 6 | 卫星点 | `satellites.js` | 与卫星背景点使用同一压缩高度 / fallback 高度 | 屏幕空间卫星拾取 | 卫星点压过 footprint 和算力中心。 |
| 12+ | 卫星锁定 ring、halo、预测轨道 | `satellites.js` | `SATELLITE_CONFIG.overlayRenderOrder` 及偏移;预测轨道使用同一真实高度开关,并固定锁定时刻的地球姿态来绘制闭合惯性轨道;关闭真实高度时回到同层球面 | 卫星覆盖层路径 | 用于选中 / 锁定卫星强调。 |
| 12+ | 卫星锁定 ring、halo、预测轨道 | `satellites.js` | `SATELLITE_CONFIG.overlayRenderOrder` 及偏移;预测轨道使用同一真实高度开关,并固定锁定时刻的地球姿态来绘制 96% 周期开放惯性轨道与方向流光;关闭真实高度时回到同层球面 | 卫星覆盖层路径 | 用于选中 / 锁定卫星强调。 |
| 98-100 | 太阳 / 月亮 halo 和 sprite | `celestial.js` | 固定 renderOrder | 天体拾取禁用 | 前景天体 sprite。 |
## 全量绘制与更新约束

View File

@@ -1,5 +1,9 @@
# 控制台前端结构
## 算力对比配置
“智能星球内容”的 `compute_comparison` 分区挂载独立 `ComputeComparisonSettings.tsx`,通过结构化表单维护来源、年度国家观测及创新分差,复用现有 Panel、Input、Select、Button 和确认弹窗,不让运营人员编辑 JSON。草稿在同页切换分区时保留,整页离开提示未保存内容;手动重新加载和恢复默认需确认。组件仅激活时读取管理接口,保存使用后端 revision 防止覆盖其他编辑者,失败保留草稿。表单内容区负责内部滚动,标题和发布操作留在首屏。`compute-comparison-model.ts` 集中类型与同源更新通知,`compute-comparison.css` 只负责该分区布局。
本文件描述当前控制台前端的真实结构,目标是帮助后续页面开发、表格改造、布局治理和状态收口时快速找到正确入口。
相关规则建议一起参考:
@@ -71,6 +75,8 @@
## 数据源采集队列
队列由 `datasource-task-queue.ts` 按独立 task ID 合并状态。同一数据源再次采集会新增一条任务,旧失败/完成/取消记录保留;仅尚未取得 task ID 的活动占位项允许按数据源绑定。迟到推送不能把终态改回进行中,旧任务轮询也不能覆盖数据源当前的新任务。任务状态按钮使用 `ListChecks`,刷新按钮仍使用 `RefreshCw`。
Admin 的数据源页把单源触发、表格勾选触发和触发全部统一接入浏览器下载列表式采集队列:
- 队列状态由 [PlainResourcePages.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/PlainResourcePages.tsx) 管理,只保存当前会话中的可见任务,不用 `localStorage` 伪造历史。

View File

@@ -411,12 +411,26 @@ AIS 船只图例按船型显示颜色:货轮、油轮、客船、渔船、军
## 算力与资源态势
管理员可在控制台“智能星球内容 → 算力对比”维护卡片数据。先在“报告来源”录入报告标题、链接、发布机构、报告年份与页码,再在“年度观测”按年份选择指标、来源和国家数值,最后“保存并发布”。占比以全球为分母,绝对量统一为 FP32 EFlop/s;中美双边份额由同年全球份额计算,区域仅在成员数据完整时汇总。不要混入 FP16/FP64、地区估计值或设施记录数;空缺国家应不录入,明确的零值才填 0。
“创新指数分差”独立维护美国减中国的观测,不反推单国指数。来源被观测引用时不能直接移除;重复指标年份、无效来源、占比总和超过 100% 等内容会拒绝发布。多人同时编辑时,后保存者收到冲突提示,草稿保留以便核对。“恢复默认”需要确认,会恢复随版本提供的报告数据;保存和恢复均有操作审计。同源页面收到发布通知后更新,其他正在展示的地球页每分钟检查一次,后台标签页恢复可见时也会检查。数值仍需人工核验报告,配置链接不会自动抓取报告。
点击算力中心图层行的“算力态势分析”打开配置窗,再开启“显示区域卡片”,地球周围会先绘制到目标位置的连接线,随后数据卡平滑出现;再次转动时不会重播入场。关闭配置窗或按 Escape 仅收起配置,卡片继续显示;再次点击分析按钮可重开配置,关闭显示开关才会停用卡片。区域锚点随地球旋转,卡片保持朝向读者;背面区域有状态提示,不绘制穿过地球的连线。其他图层、新闻和媒体窗口保持可用。
选择器按规范目录分为中国、美国、欧洲、不含中国的亚太和其他五组;这些分组只用于展示,不参与统计分母,可改变参考期与指标口径。双边份额的分母仍固定为美国加中国,其他参与方没有该口径时显示缺失。区域中心只用于卡片定位,不代表设施位置。点击来源查看报告,点击设施按钮使用原有详情卡。手机通过底部抽屉的“算力”页查看紧凑地区概览:同一列表中的短卡采用手风琴,重复点击卡头收起,点击另一张先收起旧卡,最多同时展开一张长卡。展开详情保留趋势、区域成员、设施、媒体和来源,不设地区二级页面;设置仍是单独按需页。
默认主指标为全球计算设备总规模,拆分基础计算、智能计算和超级计算,观察期为 2020—2023。已核对的绝对量为 2022 年 302(证据 `caict2023`)和 2023 年 435(证据 `caict2024`)。日本全球份额为 2020/2021/2022/2023 = 6%/5%/4%/4%。产品分组 APAC、OTHER 不能直接等同报告里的日本或“其他”;EUROPE 成员集合尚未与报告对齐,仍显示缺失。双边份额分母固定为美国加中国,不受日本加入影响。主指标缺失时可显示最近有报告的年份(当前到 2023),明确选择 2026 仍显示缺失,不回填最近值。不可比性未确认时不展示同比变化。国家报告指标与公开设施样本独立,覆盖 count 只保留在辅助证据区,不能当作算力值或全球覆盖率。TOP500 与 Epoch 可能重复收录,来源记录数不代表全球设施总数。API 审计字段为 `reviewed_at=2026-09-22`,版本与该日期一致。独立 Epoch 份额模式尚未实现。
默认主指标为全球计算设备总规模,拆分基础计算、智能计算和超级计算,观察期为 2020—2023。已核对的绝对量为 2022 年 302(证据 `caict2023`)和 2023 年 435(证据 `caict2024`)。日本全球份额为 2020/2021/2022/2023 = 6%/5%/4%/4%。产品分组 APAC、OTHER 不能直接等同报告里的日本或“其他”;EUROPE 成员集合尚未与报告对齐,仍显示缺失。双边份额分母固定为美国加中国,不受日本加入影响。主指标缺失时可显示最近有报告的年份(当前到 2023),明确选择 2026 仍显示缺失,不回填最近值。不可比性未确认时不展示同比变化。国家报告指标与公开设施样本独立,覆盖 count 只保留在辅助证据区,不能当作算力值或全球覆盖率。TOP500 与 Epoch 可能重复收录,来源记录数不代表全球设施总数。默认报告核验日期为 2026-09-22;后台发布后以维护的核验日期和实际观测为准。独立 Epoch 份额模式尚未实现。
当前原型最多同时显示六张内容卡。主卡围绕当前选择的算力指标:大号百分比或带单位的绝对量、观测年份、历史上下文和来源入口。缺少可比数据时明确显示“暂无可比数据”;没有观测值时不绘制空趋势图。设施记录和覆盖信息仍完整保留,但移到展开后的辅助区;样本数只是证据上下文,不能当作算力值或全球覆盖率。区域预览可以显示成员数,长列表仅在需要时展开。桌面卡片约宽 268 像素,高度随内容自适应;展开卡片支持用户调整至最高 480 像素。手机手风琴单卡也保持同一占比/绝对量语义,不把设施条数提升为主数字。位置和尺寸保存于本地,并可恢复自动布局。拖动或展开后先留出阅读时间;地区随地球明显转到另一侧或上下方后,卡片才会在能减少连线交叉、绕行的情况下成组平滑换位。鼠标正在卡片上操作时不移动,手动位置不会被立即抢回,也不会永久阻止必要调整。图片、视频等内容可以沿用内容区布局,当前尚未接入这些媒体数据。空间不足时卡片可以经过球体前景移动,不再靠瞬移避让或缩成小标签。
地图卡片开关关闭时仍会加载概览摘要,打开后共享地图加载事件;新请求会取消旧请求。抽屉事件使用 `composedPath()`,即使通过 innerHTML 换节点也不会误收起当前卡片。复用共享 HUD 折叠面板动画,并尊重 reduced-motion。设施名单使用最高 240px 的内部滚动区域,名称左对齐并正常换行,每行至少保留 42px 触控高度。
## 地表与物件视觉
真实地表保留原有四种底图选择;日夜模式按太阳方向控制明暗,关闭后均匀照亮。海缆选中时沿线显示流动脉冲,登陆点使用琥珀微标;设施在近距离显示芯片图标,低缩放圆点设置继续有效。卫星仍可切换自身发光/真实地表覆盖,显示轨迹并沿既有轨道运动。BGP 告警、船舶方向、关联高亮、详情卡与移动端抽屉继续使用原有操作。
### 卫星轨道与采集任务
选中卫星后,预测轨道以开放弧线显示,线上流光表示运行方向;卫星、轨迹与覆盖投影继续同步移动。覆盖区昼夜保持蓝色,粒子和轨道按图例保持固定类别色。拖动从地球移到轮廓外仍可继续旋转,大倍率下灵敏度会减小。电视窗口使用与其他卡片一致的方角。
再次触发同一数据源会创建新任务,旧失败项留在失败分组。“任务状态”使用清单图标,与刷新操作区分。CelesTrak 在短时间内可复用有效下载缓存;重新采集仍会生成独立任务并更新采集数据。

View File

@@ -1,6 +1,20 @@
# planet.sh 启动性能优化
## 背景
## Windows 桌面启动器
启动窗口优先使用 Windows Terminal,并显式运行 PowerShell 7(`pwsh.exe`),不依赖 Terminal 默认配置文件。未安装 PowerShell 7 时回退到 Windows PowerShell;未安装 Terminal 时直接启动可用的 PowerShell。CMD 初始引导同样优先 PowerShell 7。普通入口请求提权,已经以管理员运行的入口也会进入新 Terminal 窗口,但不会再次请求提权;子窗口校验权限后直接执行 WSL,避免递归打开窗口。重启完成后仍保留原有 WSL shell。
首次在 Windows 文件资源管理器中打开实际项目目录,双击仓库根目录的 `planet.cmd`。它从自身位置识别 WSL 发行版和 Linux 项目目录,在 Windows 当前用户的实际桌面生成 `Planet.cmd`,随后进入正常重启流程。支持 `\\wsl$\发行版\...` 与 `\\wsl.localhost\发行版\...`;仓库位于 Windows 本地磁盘时,使用默认 WSL 发行版及 `wslpath` 映射。系统桌面位置由 Windows 获取,兼容不同用户名和 OneDrive 等桌面重定向;WSL、zsh 及项目依赖仍须先准备好。
后续双击桌面副本,使用已绑定的发行版与目录,申请原有管理员权限,并调用 `planet.sh restart --allow-lan`。不写入测试端口;默认前端 3000、后端 8000、AI Provider 8010,显式 `DEFAULT_*_PORT` 环境配置仍有效。成功后按实际 `ports.env` 端口打开 Earth,终端保留 WSL shell;失败只显示错误,不打开成功页面。源文件负责生成入口,`scripts/windows/planet-launcher.ps1` 负责 Windows 路径、桌面安装与提权,`scripts/windows/restart.zsh` 只衔接现有重启流程。
只生成或检查副本而不重启服务,可在 Windows 中运行 `planet.cmd --install-only`。从仓库再次运行会刷新同一目标的副本;已有其他项目或非托管 `Planet.cmd` 时另存带目标标识的文件,不覆盖。目录移动后从新位置重新运行仓库入口,旧副本不会猜测新目录。桌面副本依赖项目中的脚本,不是可脱离仓库运行的安装包。
不要把仓库原始 `planet.cmd` 单独复制到桌面,它需要相邻的 `scripts/windows/` 才能完成首次生成。换电脑时应从新电脑的项目目录重新生成,不能直接沿用旧电脑的桌面副本。服务器的 `/home/linkong/planet` 与个人电脑的其他路径均可使用,不必修改提交到 Git 的路径。应在拥有目标 WSL 发行版的 Windows 账号下运行;若提权时改用其他账号,其 WSL 发行版注册可能不同。首次生成不要求管理员权限,真正重启时才申请提权。
Windows 回归命令为 `powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts\harness\test_windows_launcher.ps1`,覆盖路径识别、特殊字符、生成副本及名称冲突。`scripts/harness/test_windows_restart.py` 用临时替身验证重启参数、成功打开页面和失败保留 shell,已接入 quick-check,不启动实际服务。
## 启动背景
日常启动使用 `zsh ./planet.sh start --non-motion-agent`;新环境首次准备才需要 `init`。排查耗时时,应区分首次依赖下载、容器就绪和应用初始化,结合阶段日志时间判断。

View File

@@ -311,6 +311,8 @@ OTP 一次性验证码走 Redis,key 格式 `otp:{purpose}:{email}`,TTL 600
<!-- planet-error-catalog:start -->
| 错误编号 | 匹配片段(分号分隔) | 原因/已确认的故障现象 | 处理建议 |
| --- | --- | --- | --- |
| P_CELESTRAK_NOT_UPDATED | GP data has not updated since your last successful | CelesTrak 拒绝同一更新窗口的重复下载;若日志是 HEAD 200 后 GET 403,预检可能已消耗下载额度,这不表示出口不通。 | 使用不发 HEAD 的采集器版本,保留并校验原始下载缓存;无有效缓存时等待下一次 GP 更新或配置 Space-Track,避免连续重试。 |
| P_WINDOWS_LAUNCHER_TARGET_MISSING | P_WINDOWS_LAUNCHER_TARGET_MISSING | 桌面启动器绑定的 WSL 项目目录不可访问或缺少启动脚本,常见于项目移动、发行版不可用或复制旧机器的副本。 | 从当前项目目录运行仓库 planet.cmd 重新生成本机桌面副本,检查 WSL 发行版;不修改成其他电脑的固定路径。 |
| P_PROXY_EXTERNAL | PLANET_PROXY_EXTERNAL | 当前 Docker 代理由其他配置管理,或已被人工修改,不能安全自动覆盖。 | 检查 daemon.json、systemd 代理及 Planet 管理记录,确认归属后再调整;脚本保留现有配置。 |
| P_AUTH_BOOTSTRAP_MISSING | DEFAULT_LOGIN_USER_MISSING | 已确认当前后端数据库缺少默认账户,常见于跳过初始化的隔离预览。 | 核对数据库归属后运行现有默认账户初始化,不重置已有账户或清空数据库。 |
| P_AUTH_PROFILE_INVALID | AUTH_IDENTITY_RESPONSE_INVALID | 已确认登录成功但身份响应字段缺失,或响应错误拒绝既有本地邮箱。 | 从真实用户记录加载完整身份,区分响应序列化与注册输入校验;运行默认账户身份回归。 |

View File

@@ -74,4 +74,10 @@
## 试用算力专题
维护卡片数值:管理员打开“智能星球内容 → 算力对比”,先维护报告来源,再填写年度国家观测并“保存并发布”。只录入同年同口径数据,缺失国家不填,设施数量不会替代算力份额。可恢复内置默认值,地球卡片自动检查已发布配置。
在算力中心旁打开“算力态势分析”,开启“显示区域卡片”,选择地区并旋转地球。关闭配置窗会保留卡片,显示开关才控制启停。桌面卡片可调整大小、收起并查看真实历史图;点击来源或设施进入详情。手机使用底部“算力”页。国家指标与设施样本分开,“—”表示缺数据,不代表算力为零。
### 查看卫星与重试采集
在 Earth 启用卫星并选中一个粒子,可查看开放预测轨道、方向流光及受支持的覆盖投影。拖动移出球体仍会继续旋转。数据源采集失败后可重新触发;新任务独立显示,旧失败记录保留在当前任务队列的失败分组。

View File

@@ -16,12 +16,15 @@
## Current Version
- `main` 当前主线历史推导到:`0.16.5`
- `dev` 当前开发分支历史推导到:`0.75.0`
- `dev` 当前开发分支历史推导到:`0.75.3`
## Timeline
| Version | Type | Branch | Commit | Summary |
| --- | --- | --- | --- | --- |
| `0.75.3` | improvement | `dev` | `v0.75.3` | 地球海陆材质与可读夜侧、连续拖拽、现代徽标、卫星平滑开放轨道及流光,修复 CelesTrak 缓存与任务历史并清理废弃实现 |
| `0.75.2` | bugfix | `dev` | `v0.75.2` | Windows 启动器优先 Terminal 与 PowerShell 7,修复管理员入口分流,补齐兼容回退与提权测试 |
| `0.75.1` | improvement | `dev` | `v0.75.1` | Windows 启动器自动生成本机桌面入口,后台维护算力比较数据,恢复小球惯性与大球跟手分流并更新 agent 策略 |
| `0.75.0` | feature | `dev` | `v0.75.0` | 四图切换默认原始底图,新增算力区域态势卡片,统一空间连线与重排,优化启动和缩放拖动并补齐地理规则交付 |
| `0.74.7` | improvement | `dev` | `v0.74.7` | Docker 镜像网络故障临时回退,精简副行进度与失败显示,修复数据库端口冲突及启动重试并补齐实际验证 |
| `0.74.6` | improvement | `dev` | `v0.74.6` | 自动检测 Docker 构建代理与直连,统一运维错误诊断,支持跳过 AI Provider 构建并修复 Compose 回退与失败退出状态 |

View File

@@ -1,6 +1,6 @@
{
"name": "planet-frontend",
"version": "0.75.0",
"version": "0.75.3",
"private": true,
"packageManager": "bun@1",
"dependencies": {

View File

@@ -1,6 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#2dd4bf" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M3.904 1.777C4.978 1.289 6.427 1 8 1s3.022.289 4.096.777C13.125 2.245 14 2.993 14 4s-.875 1.755-1.904 2.223C11.022 6.711 9.573 7 8 7s-3.022-.289-4.096-.777C2.875 5.755 2 5.007 2 4s.875-1.755 1.904-2.223Z"/>
<path d="M2 6.161V7c0 1.007.875 1.755 1.904 2.223C4.978 9.71 6.427 10 8 10s3.022-.289 4.096-.777C13.125 8.755 14 8.007 14 7v-.839c-.457.432-1.004.751-1.49.972C11.278 7.693 9.682 8 8 8s-3.278-.307-4.51-.867c-.486-.22-1.033-.54-1.49-.972Z"/>
<path d="M2 9.161V10c0 1.007.875 1.755 1.904 2.223C4.978 12.711 6.427 13 8 13s3.022-.289 4.096-.777C13.125 11.755 14 11.007 14 10v-.839c-.457.432-1.004.751-1.49.972-1.232.56-2.828.867-4.51.867s-3.278-.307-4.51-.867c-.486-.22-1.033-.54-1.49-.972Z"/>
<path d="M2 12.161V13c0 1.007.875 1.755 1.904 2.223C4.978 15.711 6.427 16 8 16s3.022-.289 4.096-.777C13.125 14.755 14 14.007 14 13v-.839c-.457.432-1.004.751-1.49.972-1.232.56-2.828.867-4.51.867s-3.278-.307-4.51-.867c-.486-.22-1.033-.54-1.49-.972Z"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128" color="white"><g fill="currentColor"><path d="M64 17L110 40L64 63L18 40Z"/><path d="M18 57L64 80L110 57V72L64 95L18 72Z"/><path d="M18 88L64 111L110 88V101L64 124L18 101Z"/></g></svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 271 B

View File

@@ -1,3 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#f8fafc" viewBox="0 0 16 16">
<path d="M2 2a2 2 0 0 0-2 2v1a2 2 0 0 0 2 2h5.5v3A1.5 1.5 0 0 0 6 11.5H.5a.5.5 0 0 0 0 1H6A1.5 1.5 0 0 0 7.5 14h1a1.5 1.5 0 0 0 1.5-1.5h5.5a.5.5 0 0 0 0-1H10A1.5 1.5 0 0 0 8.5 10V7H14a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H2zm.5 3a.5.5 0 1 1 0-1 .5.5 0 0 1 0 1zm2 0a.5.5 0 1 1 0-1 .5.5 0 0 1 0 1z"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128" color="white"><g fill="none" stroke="currentColor" stroke-width="7" stroke-linejoin="round"><rect x="27" y="14" width="74" height="100" rx="9"/><path d="M27 47H101M27 80H101M61 31H87M61 64H87M61 97H87"/></g><g fill="currentColor"><circle cx="43" cy="31" r="4"/><circle cx="43" cy="64" r="4"/><circle cx="43" cy="97" r="4"/></g></svg>

Before

Width:  |  Height:  |  Size: 399 B

After

Width:  |  Height:  |  Size: 421 B

View File

@@ -1,3 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#38bdf8" class="bi bi-buildings-fill" viewBox="0 0 16 16">
<path d="M15 .5a.5.5 0 0 0-.724-.447l-8 4A.5.5 0 0 0 6 4.5v3.14L.342 9.526A.5.5 0 0 0 0 10v5.5a.5.5 0 0 0 .5.5h9a.5.5 0 0 0 .5-.5V14h1v1.5a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5V.5ZM2 11h1v1H2v-1Zm2 0h1v1H4v-1Zm-1 2v1H2v-1h1Zm1 0h1v1H4v-1Zm9-10v1h-1V3h1ZM8 5h1v1H8V5Zm1 2v1H8V7h1ZM8 9h1v1H8V9Zm2 0h1v1h-1V9Zm-1 2v1H8v-1h1Zm1 0h1v1h-1v-1Zm3-2v1h-1V9h1Zm-1 2h1v1h-1v-1Zm-2-4h1v1h-1V7Zm3 0v1h-1V7h1Zm-2-2v1h-1V5h1Zm1 0h1v1h-1V5Z"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128" color="white"><g fill="none" stroke="currentColor" stroke-width="8" stroke-linejoin="round"><rect x="27" y="27" width="74" height="74" rx="9"/><rect x="46" y="46" width="36" height="36" rx="3"/><path d="M45 9V27M64 9V27M83 9V27M45 101V119M64 101V119M83 101V119M9 45H27M9 64H27M9 83H27M101 45H119M101 64H119M101 83H119"/></g></svg>

Before

Width:  |  Height:  |  Size: 562 B

After

Width:  |  Height:  |  Size: 418 B

View File

@@ -1,10 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="100 50 600 680">
<!-- Location pin with circular cutout. Coordinates in 1000-unit space (canvas scale: size/1000). -->
<!-- States: color via fill attribute — default white for 3D canvas, orange (#ffaa00) for normal, white for hover/locked -->
<path
fill-rule="evenodd"
fill="currentColor"
d="M400 704 C386 704 375 697 367 684 L173 378 C117 290 144 173 229 111 C278 75 337 57 400 57 C463 57 522 75 571 111 C656 173 683 290 627 378 L433 684 C425 697 414 704 400 704 Z
M400 320 m-86 0 a86 86 0 1 0 172 0 a86 86 0 1 0 -172 0"
/>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128" color="white">
<defs><radialGradient id="halo"><stop offset="0.55" stop-color="currentColor" stop-opacity="0.28"/><stop offset="1" stop-color="currentColor" stop-opacity="0"/></radialGradient></defs>
<circle cx="64" cy="64" r="60" fill="url(#halo)"/>
<circle cx="64" cy="64" r="34" fill="currentColor"/>
<circle cx="64" cy="64" r="34" fill="none" stroke="currentColor" stroke-width="7"/>
</svg>

Before

Width:  |  Height:  |  Size: 611 B

After

Width:  |  Height:  |  Size: 490 B

View File

@@ -25,10 +25,10 @@
--hud-title-size: calc(1.02rem * var(--hud-scale));
--hud-panel-header-title-size: calc(0.82rem * var(--hud-scale));
--hud-kicker-size: calc(0.68rem * var(--hud-scale));
--hud-surface-top: rgba(17, 31, 53, 0.84);
--hud-surface-bottom: rgba(7, 17, 31, 0.76);
--hud-surface-top: rgba(10, 23, 37, 0.92);
--hud-surface-bottom: rgba(5, 13, 24, 0.88);
--hud-surface-overlay: rgba(157, 204, 255, 0.07);
--hud-border: rgba(201, 225, 247, 0.14);
--hud-border: rgba(124, 190, 218, 0.18);
--hud-border-hover: rgba(226, 238, 250, 0.24);
--hud-border-active: rgba(235, 244, 255, 0.32);
--hud-shadow: 0 18px 46px rgba(1, 7, 16, 0.34);
@@ -38,7 +38,7 @@
--hud-title: #dbe8f5;
--hud-text: #eef4fb;
--hud-text-muted: #8ea3ba;
--hud-text-soft: #6f849b;
--hud-text-soft: #a0b5c7;
--hud-accent: #91baff;
--hud-accent-strong: #d7e8ff;
--glass-fill-top: rgba(255, 255, 255, 0.08);

View File

@@ -9,10 +9,11 @@
position: absolute;
overflow: hidden;
isolation: isolate;
border-radius: 0;
background:
radial-gradient(circle at var(--panel-glow-x) var(--panel-glow-y), rgba(255, 255, 255, calc(0.08 + var(--panel-glow-opacity))), transparent 30%),
radial-gradient(circle at var(--panel-glow-x) var(--panel-glow-y), rgba(91, 190, 230, calc(0.025 + var(--panel-glow-opacity) * 0.25)), transparent 45%),
radial-gradient(circle at 86% 115%, rgba(145, 186, 255, 0.08), transparent 36%),
linear-gradient(180deg, rgba(255, 255, 255, 0.05), transparent 26%),
linear-gradient(180deg, rgba(145, 211, 240, 0.025), transparent 26%),
linear-gradient(180deg, var(--hud-surface-top), var(--hud-surface-bottom));
border: 1px solid var(--hud-border);
box-shadow:
@@ -21,8 +22,8 @@
var(--hud-shadow),
0 0 0 1px rgba(255, 255, 255, 0.02),
0 0 20px rgba(123, 176, 236, calc(0.04 + var(--panel-glow-opacity) * 0.32));
backdrop-filter: blur(18px) saturate(125%);
-webkit-backdrop-filter: blur(18px) saturate(125%);
backdrop-filter: blur(12px) saturate(115%);
-webkit-backdrop-filter: blur(12px) saturate(115%);
transition:
background 0.22s ease,
border-color 0.22s ease,
@@ -36,7 +37,7 @@
border-radius: inherit;
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.12), rgba(255, 255, 255, 0.02) 58%, transparent 100%);
opacity: 0.52;
opacity: 0.16;
pointer-events: none;
transform:
perspective(240px)
@@ -83,7 +84,7 @@
}
.hud-panel:hover:not(.is-dragging)::before {
opacity: 0.6;
opacity: 0.23;
}
.hud-panel:hover:not(.is-dragging)::after {
@@ -2566,8 +2567,8 @@ label.is-disabled.earth-mobile-settings-card {
.earth-tooltip {
position: absolute;
background:
linear-gradient(180deg, rgba(21, 37, 61, 0.96), rgba(8, 18, 31, 0.95));
border: 1px solid rgba(214, 230, 247, 0.14);
linear-gradient(180deg, rgba(10, 27, 43, 0.97), rgba(5, 15, 28, 0.96));
border: 1px solid rgba(90, 196, 228, 0.32);
border-radius: 10px;
padding: 8px 12px;
font-size: 0.78rem;
@@ -2577,6 +2578,16 @@ label.is-disabled.earth-mobile-settings-card {
box-shadow: var(--hud-shadow-soft);
display: none;
user-select: none;
animation: earth-tooltip-reveal 0.2s cubic-bezier(0.16, 1, 0.3, 1) both;
}
@keyframes earth-tooltip-reveal {
from { opacity: 0; transform: translateX(-6px); }
to { opacity: 1; transform: translateX(0); }
}
@media (prefers-reduced-motion: reduce) {
.earth-tooltip { animation: none; }
}
.earth-search-modal {

View File

@@ -217,7 +217,7 @@
position: relative;
flex: 1 1 auto;
min-height: calc(220px * var(--hud-scale));
border-radius: calc(16px * var(--hud-scale));
border-radius: 0;
overflow: hidden;
border: 1px solid rgba(201, 225, 247, 0.1);
background:

View File

@@ -1,4 +1,5 @@
import * as THREE from "three";
import { CABLE_CONFIG } from "./constants.js";
const CABLE_STYLE_TEXTURE_MAX_WIDTH = 1024;
@@ -24,6 +25,7 @@ export function createCableLineBatch(lines) {
count + Math.max(0, line.geometry.attributes.position.count - 1) * 2, 0);
const positions = new Float32Array(vertexCount * 3);
const styleIndices = new Float32Array(vertexCount);
const progress = new Float32Array(vertexCount);
const width = Math.min(lines.length, CABLE_STYLE_TEXTURE_MAX_WIDTH);
const height = Math.ceil(lines.length / width);
const styles = new Float32Array(width * height * 4);
@@ -32,12 +34,19 @@ export function createCableLineBatch(lines) {
let cursor = 0;
lines.forEach((line, index) => {
const source = line.geometry.attributes.position;
const distances = new Float32Array(source.count);
for (let i = 1; i < source.count; i++) {
distances[i] = distances[i - 1] + Math.hypot(source.getX(i) - source.getX(i - 1),
source.getY(i) - source.getY(i - 1), source.getZ(i) - source.getZ(i - 1));
}
const totalDistance = distances[source.count - 1] || 1;
for (let segment = 0; segment < source.count - 1; segment += 1) {
for (const endpoint of [segment, segment + 1]) {
positions[cursor * 3] = source.getX(endpoint);
positions[cursor * 3 + 1] = source.getY(endpoint);
positions[cursor * 3 + 2] = source.getZ(endpoint);
styleIndices[cursor] = index;
progress[cursor] = distances[endpoint] / totalDistance;
cursor += 1;
}
}
@@ -48,30 +57,44 @@ export function createCableLineBatch(lines) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
geometry.setAttribute("styleIndex", new THREE.BufferAttribute(styleIndices, 1));
geometry.setAttribute("progress", new THREE.BufferAttribute(progress, 1));
const material = new THREE.ShaderMaterial({
uniforms: {
styles: { value: styleTexture },
styleSize: { value: new THREE.Vector2(width, height) },
uTime: { value: 0 },
},
transparent: true,
depthTest: true,
depthWrite: true,
depthWrite: false,
vertexShader: `
uniform sampler2D styles;
uniform vec2 styleSize;
attribute float styleIndex;
attribute float progress;
varying vec4 vStyle;
varying float vProgress;
void main() {
vec2 uv = (vec2(mod(styleIndex, styleSize.x), floor(styleIndex / styleSize.x)) + 0.5) / styleSize;
vStyle = texture2D(styles, uv);
vProgress = progress;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
varying vec4 vStyle;
varying float vProgress;
uniform float uTime;
void main() {
if (vStyle.a <= 0.0) discard;
gl_FragColor = vStyle;
float alpha = abs(vStyle.a);
if (alpha <= 0.0) discard;
vec3 color = vStyle.rgb;
if (vStyle.a < 0.0) {
float pulse = smoothstep(0.6, 1.0, fract(vProgress * ${CABLE_CONFIG.visual.pulseRepeats.toFixed(1)} - uTime * ${CABLE_CONFIG.visual.pulseSpeed.toFixed(1)}));
color = mix(vec3(0.3, 0.8, 1.0), vec3(0.7, 1.0, 1.0), pulse);
alpha = max(alpha, 0.8 + pulse * 0.2);
}
gl_FragColor = vec4(color, alpha);
}
`,
});
@@ -80,11 +103,12 @@ export function createCableLineBatch(lines) {
object.name = "cable-line-batch";
object.renderOrder = lines[0].renderOrder;
object.onBeforeRender = () => {
material.uniforms.uTime.value = performance.now() * 0.001;
let changed = false;
lines.forEach((line, index) => {
const { color, opacity } = line.material;
const offset = index * 4;
const alpha = line.visible ? opacity : 0;
const alpha = line.visible ? opacity * (line.material.userData.cableSelected ? -1 : 1) : 0;
if (styles[offset] !== Math.fround(color.r) || styles[offset + 1] !== Math.fround(color.g)
|| styles[offset + 2] !== Math.fround(color.b) || styles[offset + 3] !== Math.fround(alpha)) {
styles[offset] = color.r;
@@ -145,6 +169,10 @@ export function createLandingPointBatch(markers, texture) {
varying vec4 vStyle;
void main() {
vec4 color = texture2D(map, vUv) * vStyle;
float radius = distance(vUv, vec2(0.5));
float border = smoothstep(0.242, 0.254, radius) * (1.0 - smoothstep(0.283, 0.296, radius));
float brightness = max(vStyle.r, max(vStyle.g, vStyle.b));
color.rgb = mix(color.rgb, vec3(1.0, 0.953, 0.78) * brightness, border);
if (color.a < 0.01) discard;
gl_FragColor = color;
}

View File

@@ -3,6 +3,7 @@
import * as THREE from "three";
import { createCableLineBatch, createLandingPointBatch } from "./cable-batches.js";
import { earthSurfacePoint } from "./earth-surface.js";
import { configureColorTexture } from "./texture-colors.js";
import {
CONFIG,
@@ -36,7 +37,6 @@ const LANDING_POINT_SPRITE_ASPECT = 1;
const LANDING_POINT_SIZE_REFERENCE_FOV = 75;
const LANDING_POINT_SIZE_SCALE_MIN = 0.16;
const LANDING_POINT_SIZE_SCALE_MAX = 3;
const LANDING_POINT_ATLAS_CELL_SIZE = 128;
let landingPointTexture = null;
function getLandingPointPulse() {
@@ -56,57 +56,14 @@ function getLandingPointDimColor() {
return `#${color.getHexString()}`;
}
function createLandingPointBallTexture() {
const canvas = document.createElement("canvas");
canvas.width = LANDING_POINT_ATLAS_CELL_SIZE;
canvas.height = LANDING_POINT_ATLAS_CELL_SIZE;
const context = canvas.getContext("2d");
const center = LANDING_POINT_ATLAS_CELL_SIZE / 2;
const radius = 46;
context.clearRect(0, 0, canvas.width, canvas.height);
const shadow = context.createRadialGradient(
center - 16,
center - 18,
8,
center,
center,
radius,
);
shadow.addColorStop(0, "rgba(255, 255, 255, 1)");
shadow.addColorStop(0.48, "rgba(238, 238, 238, 0.98)");
shadow.addColorStop(0.82, "rgba(178, 178, 178, 0.94)");
shadow.addColorStop(1, "rgba(92, 92, 92, 0.88)");
context.beginPath();
context.arc(center, center, radius, 0, Math.PI * 2);
context.fillStyle = shadow;
context.fill();
context.beginPath();
context.ellipse(center - 14, center - 18, 14, 9, -0.45, 0, Math.PI * 2);
context.fillStyle = "rgba(255, 255, 255, 0.38)";
context.fill();
context.beginPath();
context.arc(center, center, radius - 1, 0, Math.PI * 2);
context.strokeStyle = "rgba(255, 255, 255, 0.24)";
context.lineWidth = 2;
context.stroke();
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.generateMipmaps = false;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.needsUpdate = true;
return texture;
}
async function getLandingPointTexture() {
if (landingPointTexture) return landingPointTexture;
landingPointTexture = createLandingPointBallTexture();
const source = new URL("../assets/icons/marker-landing-point.svg", import.meta.url).href;
landingPointTexture = await new THREE.TextureLoader().loadAsync(source);
configureColorTexture(landingPointTexture);
landingPointTexture.generateMipmaps = false;
landingPointTexture.minFilter = THREE.LinearFilter;
landingPointTexture.magFilter = THREE.LinearFilter;
return landingPointTexture;
}
@@ -192,6 +149,8 @@ function getCableColor(properties) {
function createCableLine(points, color, properties) {
if (points.length < 2) return null;
color = new THREE.Color(CABLE_CONFIG.visual.normalTint)
.lerp(new THREE.Color(color), CABLE_CONFIG.visual.sourceColorWeight).getHex();
const lineGeometry = new THREE.BufferGeometry().setFromPoints(points);
lineGeometry.computeBoundingSphere();

View File

@@ -205,6 +205,7 @@ function createSkySphere() {
opacity: CELESTIAL_CONFIG.skyOpacity,
depthWrite: false,
depthTest: false,
toneMapped: false,
fog: false,
});

View File

@@ -10,7 +10,7 @@ import { latLonToVector3 } from "./utils.js";
const COMPUTE_CENTER_RENDER_ORDER = 4.5;
const COMPUTE_CENTER_POINT_SIZE = 36;
const COMPUTE_CENTER_ICON_FIT_SIZE = 60;
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,
@@ -191,6 +191,8 @@ const computeCenterIconLayer = createInteractableLayer({
amplitude: COMPUTE_CENTER_CONFIG.marker.pulseAmplitude,
},
icon: {
colorable: false,
badge: ({ marker, item }) => ({ color: COMPUTE_CENTER_CONFIG.colors[marker?.userData?.site_type || item?.site_type] || "#14b8a6" }),
coordinates: "canvas",
fitSize: COMPUTE_CENTER_ICON_FIT_SIZE,
glowBlur: 16,

View File

@@ -16,6 +16,7 @@ import { createSpatialCallouts } from "./spatial-callouts.js";
const API = "/api/v1/data-products/compute";
const MAX_VISIBLE_REGIONS = 6;
const CONFIGURATION_REFRESH_MS = 60_000;
const LOCAL_FLAG_CODES = new Set([
"af", "ao", "au", "br", "ca", "ch", "cn", "co", "cr", "de", "do", "eg",
"es", "fi", "fr", "gb", "hu", "id", "ie", "in", "it", "jp", "ke", "kr",
@@ -740,7 +741,7 @@ export function initComputeTopic({
if (refreshMap && cardsEnabled) refreshFacilities();
try {
const params = new URLSearchParams({ countries: countries.join(","), mode });
const response = await fetch(`${API}/series?${params}`, { signal: request.signal });
const response = await fetch(`${API}/series?${params}`, { signal: request.signal, cache: "no-store" });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const payload = await response.json();
if (token !== serial || (!configVisible && !cardsEnabled)) return;
@@ -1004,6 +1005,14 @@ export function initComputeTopic({
};
window.addEventListener("resize", resize);
window.addEventListener("earth:locale-change", locale);
const refreshConfiguration = () => {
if (!document.hidden && (configVisible || cardsEnabled)) load({ refreshMap: false });
};
const configurationChannel = typeof BroadcastChannel === "undefined" ? null
: new BroadcastChannel("planet-compute-configuration");
if (configurationChannel) configurationChannel.onmessage = refreshConfiguration;
const configurationTimer = setInterval(refreshConfiguration, CONFIGURATION_REFRESH_MS);
document.addEventListener("visibilitychange", refreshConfiguration);
renderPicker();
renderMobile();
return {
@@ -1026,6 +1035,9 @@ export function initComputeTopic({
cardsEnabled = false;
serial++;
request?.abort();
clearInterval(configurationTimer);
configurationChannel?.close();
document.removeEventListener("visibilitychange", refreshConfiguration);
document.body.classList.remove("compute-topic-open");
for (const controller of cardPanels.values()) controller.destroy();
cardPanels.clear();

View File

@@ -9,6 +9,10 @@ export const CONFIG = {
earthRadius: 100,
rotationSpeed: 0.0005,
minimumCameraAltitude: 10,
dragRotationFactorBase: 0.005,
dragRotationZoomExponent: 1.8,
dragRotationScaleMin: 0.12,
dragRotationScaleMax: 1.65,
};
export const ROTATION_MODE = {
@@ -116,7 +120,7 @@ export const CELESTIAL_CONFIG = {
updateIntervalMs: 10_000,
skyRadius: 2600,
skyOpacity: 1,
starMapUrl: "./assets/celestial/starmap_equatorial_4k.jpg",
starMapUrl: "./assets/celestial/starmap_deep_8k.jpg",
brightStarsUrl: "./assets/celestial/bright-stars.json",
orientationEulerRad: {
x: 0.46,
@@ -204,8 +208,8 @@ export const TERRAIN_CONFIG = {
opacity: 0.68,
color: 0x8aa884,
emissive: 0x030704,
specular: 0x344438,
shininess: 16,
specular: 0x000000,
shininess: 0,
urlTemplate:
"/api/v1/visualization/terrain/terrarium/{z}/{x}/{y}.png",
batchUrl: "/api/v1/visualization/terrain/terrarium/batch",
@@ -287,12 +291,12 @@ export const VESSEL_CONFIG = {
dimmedOpacity: 0.26,
},
colors: {
cargo: "#4A90D9",
tanker: "#E85D04",
passenger: "#06D6A0",
fishing: "#FFD166",
military: "#73797E",
other: "#9B9B9B",
cargo: "#38bdf8",
tanker: "#f97316",
passenger: "#14b8a6",
fishing: "#f59e0b",
military: "#818cf8",
other: "#94a3b8",
},
sizeStabilization: {
min: 0.1,
@@ -325,8 +329,9 @@ export const COMPUTE_CENTER_CONFIG = {
pulseAmplitude: 0.03,
},
colors: {
supercomputer: "#38bdf8",
gpu_cluster: "#2dd4bf",
supercomputer: "#a855f7",
gpu_cluster: "#a855f7",
infrastructure: "#14b8a6",
linked: "#f8fafc",
},
sizeStabilization: {
@@ -345,6 +350,13 @@ export const CABLE_COLORS = {
};
export const CABLE_CONFIG = {
visual: {
normalTint: 0x328ebc,
sourceColorWeight: 0.38,
normalOpacity: 0.7,
pulseRepeats: 6,
pulseSpeed: 4.5,
},
lockedOpacityMin: 0.2,
lockedOpacityMax: 1.0,
otherOpacity: 0.5,
@@ -361,7 +373,7 @@ export const CABLE_CONFIG = {
},
landingPoint: {
altitudeOffset: EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET,
color: 0xffaa00,
color: 0xf59e0b,
opacity: 1.0,
renderOrder: 1,
},
@@ -399,9 +411,13 @@ export const SATELLITE_CONFIG = {
maxRealAltitudeOffset: 25,
frontFacingDotThreshold: 0.015,
overlayRenderOrder: 12,
dotBaseSize: 2.8,
dotBackdropScale: 1.28,
dotZoomScalePower: 1,
dotBaseSize: 2.2,
dotBackdropScale: 1.4,
dotOutlineOpacity: 0.46,
footprintColor: 0x3399ff,
footprintOpacity: 0.34,
footprintDayVisibilityBoost: 1.65,
dotZoomScalePower: 0.55,
ringSize: 0.07,
apiPath: '/api/v1/visualization/geo/satellites',
breathingSpeed: 0.036,
@@ -410,7 +426,7 @@ export const SATELLITE_CONFIG = {
breathingOpacityMax: 0.9,
dotBreathingSpeed: 0.12,
dotBreathingScaleAmplitude: 0.28,
dotOpacityMin: 0.42,
dotOpacityMin: 0.72,
dotOpacityMax: 1.0
};
@@ -444,10 +460,10 @@ export const BGP_CONFIG = {
lockedMax: 1.0
},
severityColors: {
critical: 0xff4d4f,
high: 0xff9f43,
medium: 0xffd166,
low: 0x4dabf7
critical: 0xf43f5e,
high: 0xf97316,
medium: 0xf59e0b,
low: 0x38bdf8
},
severityScales: {
critical: 1.18,
@@ -540,42 +556,42 @@ export const EARTH_MATERIAL_CONFIG = {
// Base sphere sits below the country fill and high-res texture overlays.
// Keep it dark so a delayed overlay never flashes or reads as a white layer.
color: 0x010609,
specular: 0x1a2d45,
shininess: 12,
specular: 0x000000,
shininess: 0,
emissive: 0x010609,
opacity: 1,
textureOverlayAltitudeOffset: EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET,
textureWidthSegments: 128,
textureHeightSegments: 128,
textureOverlayOpacity: 1,
textureOverlayRenderOrder: 0.96,
// Depth-mask occluder keeps far-side objects hidden behind the earth
occluderRadiusFactor: 0.999,
occluderSegments: 48,
// Fresnel atmosphere glow — inner rim
atmosInnerRadiusFactor: 1.01,
atmosInnerSegments: 64,
atmosInnerColor: [0.38, 0.60, 0.84],
atmosInnerRimPower: 3.2,
atmosInnerIntensity: 0.10,
// Fresnel atmosphere glow — outer corona
atmosOuterRadiusFactor: 1.025,
atmosOuterSegments: 48,
atmosOuterColor: [0.32, 0.52, 0.74],
atmosOuterRimPower: 6.0,
atmosOuterIntensity: 0.08,
atmosOuterEdgeFeather: 0.14,
// Subtle Fresnel edge cue shown when the high-res texture is hidden or unavailable.
rimGlowColor: [0.42, 0.72, 1.0],
rimGlowRadiusFactor: 1.0035,
rimGlowPower: 3.4,
rimGlowIntensity: 0.24,
rimGlowSegments: 96,
rimGlowRenderOrder: 1.08,
surface: {
exposure: 0.9,
landSaturation: 0.9,
oceanAbsorption: 0.36,
oceanDeepColor: [0.004, 0.012, 0.032],
// Independent night-side texture contrast and cool ambient, in linear RGB.
night: {
detailGamma: 0.55,
landTint: [0.07, 0.075, 0.08],
landAmbient: [0.003, 0.005, 0.008],
oceanTint: [0.008, 0.016, 0.024],
oceanAmbient: [0.0015, 0.004, 0.012],
},
terminator: [-0.075, 0.16],
oceanReflection: [0.025, 0.12, 0.32],
atmosphereColor: [0.08, 0.28, 0.65],
innerRimStrength: 0.28,
},
atmosphere: {
radiusFactor: 1.025,
color: [0.18, 0.48, 0.88],
strength: 0.65,
},
dayNight: {
enabled: true,

View File

@@ -1574,7 +1574,7 @@ function cloneEarthSettings(settings) {
satelliteRealAltitudeEnabled:
settings.shared.satelliteRealAltitudeEnabled !== false,
interactableCompactDotsEnabled:
settings.shared.interactableCompactDotsEnabled !== false,
settings.shared.interactableCompactDotsEnabled === true,
surfaceHoverInfoMode: normalizeSurfaceHoverInfoMode(
settings.shared.surfaceHoverInfoMode,
),
@@ -4303,15 +4303,6 @@ function resetAllShortcutBindings() {
showStatusMessage(earthMessage("status.shortcutsReset"), "info");
}
function moveCruiseRegionInOrder(region, targetRegion) {
if (!region || !targetRegion || region === targetRegion) return;
const currentOrder = getCruiseRegionOrder().filter((item) => item !== region);
const targetIndex = currentOrder.indexOf(targetRegion);
if (targetIndex < 0) return;
currentOrder.splice(targetIndex, 0, region);
setCruiseRegionOrder(currentOrder);
}
function getCruiseRegionOrderRows(list) {
if (!(list instanceof HTMLElement)) return [];
return Array.from(list.querySelectorAll("[data-cruise-region-order-item]")).filter(

View File

@@ -5,6 +5,7 @@ import Pbf from "pbf";
import { CONFIG, COUNTRY_BOUNDARY_CONFIG } from "./constants.js";
import { screenToEarthCoords, vector3ToLatLon } from "./utils.js";
import { appendSurfaceSegments } from "./earth-surface.js";
import { setEarthLandMask } from "./earth.js";
// ─── Module state ──────────────────────────────────────────────────────────────
let _earthObj = null;
@@ -401,16 +402,6 @@ function setActiveTileKeys(nextKeys) {
});
}
function tileUrlForKey(key) {
const [kind, z, x, y] = key.split("/");
const prefix = COUNTRY_BOUNDARY_CONFIG.tileBasePath.replace(/\/?$/, "/");
const versionSuffix = _tileAssetVersion ? `?v=${encodeURIComponent(_tileAssetVersion)}` : "";
if (kind === "claim") {
return `${prefix}china-claims/${z}/${x}/${y}.geojson${versionSuffix}`;
}
return `${prefix}${z}/${x}/${y}.geojson${versionSuffix}`;
}
function versionedBoundaryAssetUrl(path) {
const url = new URL(path, COUNTRY_BOUNDARY_CONFIG.tileBasePath);
if (_tileAssetVersion) url.searchParams.set("v", _tileAssetVersion);
@@ -487,16 +478,6 @@ async function loadPmtilesMvtFeatures(key) {
return features;
}
async function loadDebugGeojsonFeatures(key) {
const resp = await fetch(tileUrlForKey(key));
if (!resp.ok) {
if (resp.status === 404) return [];
throw new Error(`boundary tile ${key} HTTP ${resp.status}`);
}
const payload = await resp.json();
return (payload.features || []).filter(f => f.geometry);
}
async function loadBoundaryTile(key) {
if (_tileCache.has(key)) {
touchTileKey(key);
@@ -1028,6 +1009,7 @@ export async function loadCountryBoundaries() {
const coastlineFeatures = baseFeatures.filter(isStandaloneCoastlineFeature);
_landTexture = buildLandTexture(_features);
setEarthLandMask(_landTexture, OCEAN_HEX, COUNTRY_BOUNDARY_CONFIG.landColor);
_landMesh = makeLandMesh(_landTexture);
_earthObj.add(_landMesh);
@@ -1245,6 +1227,7 @@ export function clearCountryBoundaryData() {
disposeObj(_claimGroup);
disposeObj(_landMesh);
disposeObj(_tintMesh);
setEarthLandMask(null);
_landTexture?.dispose?.();
_tileCache.forEach(entry => disposeTileObject(entry.object));
_tileCache.clear();

View File

@@ -37,22 +37,30 @@ function normalizeInteractableItem(item) {
};
}
function drawInteractableIcon(context, { glow = false, color = "#7dd3fc" }) {
if (glow) {
context.shadowColor = color;
context.shadowBlur = 16;
}
function drawInteractableIcon(context, { marker, color = "#7dd3fc" }) {
const kind = marker?.userData?.kind || "default";
context.strokeStyle = color;
context.fillStyle = color;
context.strokeStyle = "rgba(8, 15, 27, 0.92)";
context.lineWidth = 7;
context.lineCap = "round";
context.lineJoin = "round";
context.beginPath();
context.arc(0, 0, 27, 0, Math.PI * 2);
context.fill();
if (kind === "note") {
context.roundRect(-27, -34, 54, 68, 6);
context.moveTo(-14, -16); context.lineTo(14, -16);
context.moveTo(-14, 0); context.lineTo(14, 0);
context.moveTo(-14, 16); context.lineTo(6, 16);
} else if (kind === "alert") {
context.moveTo(0, -34); context.lineTo(34, 28); context.lineTo(-34, 28); context.closePath();
context.moveTo(0, -13); context.lineTo(0, 6);
context.moveTo(0, 17); context.lineTo(0, 18);
} else {
context.moveTo(0, 36);
context.bezierCurveTo(-49, -6, -29, -35, 0, -35);
context.bezierCurveTo(29, -35, 49, -6, 0, 36);
context.moveTo(11, -10); context.arc(0, -10, 11, 0, Math.PI * 2);
}
context.stroke();
context.fillStyle = "rgba(255,255,255,0.95)";
context.beginPath();
context.arc(0, 0, 9, 0, Math.PI * 2);
context.fill();
}
const earthInteractableLayer = createInteractableLayer({
@@ -81,6 +89,7 @@ const earthInteractableLayer = createInteractableLayer({
},
avoidance: SURFACE_AVOIDANCE_PROFILES.city,
icon: {
badge: true,
draw: drawInteractableIcon,
},
getPosition: (item) => ({
@@ -88,6 +97,7 @@ const earthInteractableLayer = createInteractableLayer({
longitude: item.longitude,
}),
getKind: (item) => item.kind || "default",
getBucketKey: (marker) => marker.userData.kind || "default",
getUserData: (item) => ({
...item,
type: "earth_interactable",

View File

@@ -1,7 +1,7 @@
import { expect, test } from "bun:test";
import * as THREE from "three";
import { applyEarthDayNightShader } from "./earth.js";
import { CELESTIAL_CONFIG, EARTH_MATERIAL_CONFIG } from "./constants.js";
import { CELESTIAL_CONFIG } from "./constants.js";
import { configureColorTexture, preserveTextureOutput } from "./texture-colors.js";
function basicShader(legacy = false) {
@@ -27,10 +27,9 @@ for (const legacy of [false, true]) {
});
}
test("color maps are sRGB and the surface does not blend the dark base into the image", () => {
test("color maps are sRGB without a legacy sky tint", () => {
const texture = new THREE.Texture();
configureColorTexture(texture);
expect(texture.colorSpace).toBe(THREE.SRGBColorSpace);
expect(EARTH_MATERIAL_CONFIG.textureOverlayOpacity).toBe(1);
expect(CELESTIAL_CONFIG.skyTint).toBeUndefined();
});

View File

@@ -0,0 +1,168 @@
import * as THREE from "three";
// ShaderMaterial does not apply output conversion automatically. r128 samples
// encoded color textures; modern Three uploads them using the sRGB GPU format.
const LEGACY_TEXTURE_ENCODING = !THREE.SRGBColorSpace;
const COLOR_PIPELINE = `
vec3 surfaceLinear(vec3 color) {
return mix(color / 12.92, pow((color + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), color));
}
vec3 surfaceSRGB(vec3 color) {
color = max(color, vec3(0.0));
return mix(color * 12.92, 1.055 * pow(color, vec3(1.0 / 2.4)) - 0.055, step(vec3(0.0031308), color));
}
vec3 surfaceToneMap(vec3 color) {
// Bounded filmic shoulder, local to Earth so sky and data colors stay stable.
return clamp((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14), 0.0, 1.0);
}
`;
export const SURFACE_VERTEX_SHADER = `
varying vec2 vUv;
varying vec3 vWorldNormal;
varying vec3 vWorldPosition;
void main() {
vUv = uv;
vec4 worldPosition = modelMatrix * vec4(position, 1.0);
vWorldPosition = worldPosition.xyz;
// normalMatrix handles parent transforms; move its view-space result back
// to world space without assuming the camera is at the origin.
vWorldNormal = normalize(vec3(normalize(normalMatrix * normal) * mat3(viewMatrix)));
gl_Position = projectionMatrix * viewMatrix * worldPosition;
}
`;
export const SURFACE_FRAGMENT_SHADER = `
uniform sampler2D uDayMap;
uniform sampler2D uLandMask;
uniform float uLandMaskAvailable;
uniform vec3 uMaskOcean;
uniform vec3 uMaskLand;
uniform vec3 uSunDirectionWorld;
uniform float uDayNightEnabled;
uniform float uExposure;
uniform float uOceanAbsorption;
uniform vec3 uOceanDeepColor;
uniform float uLandSaturation;
uniform float uNightDetailGamma;
uniform vec3 uNightLandTint;
uniform vec3 uNightLandAmbient;
uniform vec3 uNightOceanTint;
uniform vec3 uNightOceanAmbient;
uniform vec2 uTerminator;
uniform vec3 uOceanReflection;
uniform vec3 uAtmosphereColor;
uniform float uInnerRimStrength;
varying vec2 vUv;
varying vec3 vWorldNormal;
varying vec3 vWorldPosition;
${COLOR_PIPELINE}
void main() {
vec3 source = texture2D(uDayMap, vUv).rgb;
#ifdef LEGACY_TEXTURE_ENCODING
source = surfaceLinear(source);
#endif
vec3 normal = normalize(vWorldNormal);
vec3 viewDirection = normalize(cameraPosition - vWorldPosition);
float sunFacing = dot(normal, normalize(uSunDirectionWorld));
float daylight = mix(1.0, smoothstep(uTerminator.x, uTerminator.y, sunFacing), uDayNightEnabled);
float luminance = dot(source, vec3(0.2126, 0.7152, 0.0722));
// Until geography is ready use a conservative blue-chroma estimate. Once
// available the shared geographic mask is independent of the chosen map.
float ocean = smoothstep(0.015, 0.12, source.b - max(source.r, source.g));
if (uLandMaskAvailable > 0.5) {
vec3 mask = texture2D(uLandMask, vUv).rgb;
vec3 range = uMaskLand - uMaskOcean;
ocean = 1.0 - clamp(dot(mask - uMaskOcean, range) / max(dot(range, range), 0.00001), 0.0, 1.0);
}
// Ice retains its source appearance, even over ocean polygons.
ocean *= 1.0 - smoothstep(0.45, 0.8, min(source.r, min(source.g, source.b)));
vec3 land = mix(vec3(luminance), source, uLandSaturation);
vec3 base = mix(land, source * uOceanAbsorption + uOceanDeepColor, ocean);
float diffuse = mix(1.0, 0.78 + 0.22 * max(sunFacing, 0.0), uDayNightEnabled);
vec3 color = base * diffuse;
float fresnel = pow(1.0 - clamp(dot(normal, viewDirection), 0.0, 1.0), 3.4);
// No white specular lobe: only grazing-angle sky reflection on water.
color += uOceanReflection * fresnel * ocean * daylight;
float rimLight = mix(1.0, smoothstep(-0.18, 0.45, sunFacing), uDayNightEnabled);
color += uAtmosphereColor * pow(fresnel, 1.6) * uInnerRimStrength * rimLight;
// A separate night branch preserves geographic contrast without raising
// day exposure or adding a uniform gray veil. All values remain linear.
vec3 nightDetail = pow(surfaceToneMap(mix(land, source * uOceanAbsorption, ocean) * uExposure), vec3(uNightDetailGamma));
vec3 nightLand = nightDetail * uNightLandTint + uNightLandAmbient;
vec3 nightOcean = nightDetail * uNightOceanTint + uNightOceanAmbient;
vec3 nightColor = mix(nightLand, nightOcean, ocean);
color = mix(nightColor, surfaceToneMap(color * uExposure), daylight);
gl_FragColor = vec4(surfaceSRGB(color), 1.0);
}
`;
export function createEarthSurfaceMaterial(config, sunDirection, enabled) {
return new THREE.ShaderMaterial({
uniforms: {
uDayMap: { value: null },
uLandMask: { value: null },
uLandMaskAvailable: { value: 0 },
uMaskOcean: { value: new THREE.Vector3() },
uMaskLand: { value: new THREE.Vector3(1, 1, 1) },
uSunDirectionWorld: { value: sunDirection.clone() },
uDayNightEnabled: { value: enabled ? 1 : 0 },
uExposure: { value: config.exposure },
uOceanAbsorption: { value: config.oceanAbsorption },
uOceanDeepColor: { value: new THREE.Vector3(...config.oceanDeepColor) },
uLandSaturation: { value: config.landSaturation },
uNightDetailGamma: { value: config.night.detailGamma },
uNightLandTint: { value: new THREE.Vector3(...config.night.landTint) },
uNightLandAmbient: { value: new THREE.Vector3(...config.night.landAmbient) },
uNightOceanTint: { value: new THREE.Vector3(...config.night.oceanTint) },
uNightOceanAmbient: { value: new THREE.Vector3(...config.night.oceanAmbient) },
uTerminator: { value: new THREE.Vector2(...config.terminator) },
uOceanReflection: { value: new THREE.Vector3(...config.oceanReflection) },
uAtmosphereColor: { value: new THREE.Vector3(...config.atmosphereColor) },
uInnerRimStrength: { value: config.innerRimStrength },
},
defines: LEGACY_TEXTURE_ENCODING ? { LEGACY_TEXTURE_ENCODING: 1 } : {},
vertexShader: SURFACE_VERTEX_SHADER,
fragmentShader: SURFACE_FRAGMENT_SHADER,
side: THREE.FrontSide,
transparent: true,
depthTest: true,
depthWrite: false,
toneMapped: false,
});
}
export function createEarthAtmosphereMaterial(config, sunDirection, enabled) {
return new THREE.ShaderMaterial({
uniforms: {
uSunDirectionWorld: { value: sunDirection.clone() },
uDayNightEnabled: { value: enabled ? 1 : 0 },
uColor: { value: new THREE.Vector3(...config.color) },
uStrength: { value: config.strength },
},
vertexShader: SURFACE_VERTEX_SHADER,
fragmentShader: `
uniform vec3 uSunDirectionWorld;
uniform float uDayNightEnabled;
uniform vec3 uColor;
uniform float uStrength;
varying vec3 vWorldNormal;
varying vec3 vWorldPosition;
void main() {
vec3 normal = normalize(vWorldNormal);
vec3 viewDirection = normalize(cameraPosition - vWorldPosition);
float facing = clamp(abs(dot(normal, viewDirection)), 0.0, 1.0);
float rim = pow(1.0 - facing, 3.0) * smoothstep(0.0, 0.22, facing);
float daylight = smoothstep(-0.22, 0.45, dot(normal, normalize(uSunDirectionWorld)));
float illumination = mix(1.0, mix(0.12, 1.0, daylight), uDayNightEnabled);
gl_FragColor = vec4(uColor, rim * illumination * uStrength);
}
`,
side: THREE.BackSide,
transparent: true,
blending: THREE.AdditiveBlending,
depthWrite: false,
depthTest: true,
toneMapped: false,
});
}

View File

@@ -0,0 +1,77 @@
import { expect, test } from "bun:test";
import * as THREE from "three";
import {
createEarth, getEarthSurfacePickTarget, setDayNightEnabled,
setEarthLandMask, setEarthSunDirection, setEarthTextureVisible,
} from "./earth.js";
import { CONFIG, EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET } from "./constants.js";
import { createCableLineBatch } from "./cable-batches.js";
test("the real texture shell retains its geometry and pick target, with one atmosphere draw", () => {
const earth = createEarth(new THREE.Scene());
const surface = earth.getObjectByName("earth-high-res-texture-overlay");
const atmosphere = earth.getObjectByName("earth-atmosphere-scattering");
expect(surface.geometry.parameters.radius).toBe(CONFIG.earthRadius + EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET);
expect(surface.material.isShaderMaterial).toBe(true);
expect(surface.material.depthWrite).toBe(false);
expect(surface.raycast).toBe(THREE.Mesh.prototype.raycast);
expect(earth.children.filter(child => child.material?.isShaderMaterial).length).toBe(2);
expect(atmosphere.material.side).toBe(THREE.BackSide);
expect(atmosphere.material.depthWrite).toBe(false);
expect(atmosphere.material.depthTest).toBe(true);
expect(getEarthSurfacePickTarget()).toBe(earth);
setEarthTextureVisible(false);
expect(getEarthSurfacePickTarget()).toBe(earth);
setEarthTextureVisible(true);
});
test("world-space sunlight, day/night and geographic masking update the visible shader owners", () => {
const earth = createEarth(new THREE.Scene());
const surface = earth.getObjectByName("earth-high-res-texture-overlay");
const atmosphere = earth.getObjectByName("earth-atmosphere-scattering");
const direction = new THREE.Vector3(-2, 1, 3);
setEarthSunDirection(direction);
for (const mesh of [surface, atmosphere]) {
expect(mesh.material.uniforms.uSunDirectionWorld.value.distanceTo(direction.clone().normalize())).toBeLessThan(1e-8);
}
setDayNightEnabled(false);
expect(surface.material.uniforms.uDayNightEnabled.value).toBe(0);
expect(atmosphere.material.uniforms.uDayNightEnabled.value).toBe(0);
setDayNightEnabled(true);
const mask = new THREE.Texture();
setEarthLandMask(mask, 0x010609, 0x080f1b);
expect(surface.material.uniforms.uLandMask.value).toBe(mask);
expect(surface.material.uniforms.uMaskLand.value.z).toBeCloseTo(27 / 255);
setEarthLandMask(null);
expect(surface.material.uniforms.uLandMask.value).toBeNull();
expect(surface.material.uniforms.uLandMaskAvailable.value).toBe(0);
});
test("cable pulses use arc length while keeping original pick objects and independent states", () => {
const lines = [0, 1].map(index => {
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, index, 0), new THREE.Vector3(1, index, 0), new THREE.Vector3(4, index, 0),
]);
const line = new THREE.Line(geometry, new THREE.LineBasicMaterial({ color: 0x328ebc, opacity: 0.7 }));
line.userData.cableId = `route-${index}`;
return line;
});
const originalPositions = lines[0].geometry.attributes.position.array.slice();
const originalRaycast = lines[0].raycast;
const batch = createCableLineBatch(lines);
const progress = batch.object.geometry.attributes.progress;
expect([...progress.array.slice(0, 4)]).toEqual([0, 0.25, 0.25, 1]);
lines[0].material.userData.cableSelected = true;
batch.object.onBeforeRender();
const styles = batch.object.material.uniforms.styles.value.image.data;
expect(styles[3]).toBeLessThan(0);
expect(styles[7]).toBeGreaterThan(0);
lines[0].visible = false;
batch.object.onBeforeRender();
expect(styles[3]).toBe(0);
expect(lines[0].raycast).toBe(originalRaycast);
expect(lines[0].userData.cableId).toBe("route-0");
expect(lines[0].geometry.attributes.position.array).toEqual(originalPositions);
batch.dispose();
expect(lines[0].geometry.attributes.position.count).toBe(3);
});

View File

@@ -14,6 +14,7 @@ import { latLonToVector3 } from './utils.js';
import { configureColorTexture, preserveTextureOutput, shaderOutputMarker } from './texture-colors.js';
import { createEarthMapController } from './earth-map-sources.js';
import { earthTextureImages } from './earth-texture-image.js';
import { createEarthAtmosphereMaterial, createEarthSurfaceMaterial } from './earth-surface-material.js';
export let earth = null;
export let clouds = null;
@@ -28,7 +29,6 @@ let _earthTextureOverlayMaterial = null;
let _earthShaders = [];
let _dayNightEnabled = true;
let _textureVisible = true;
let _earthRimGlow = null;
let _cloudTexture = null;
let _cloudTextureLoadPromise = null;
const _earthSunDirection = new THREE.Vector3(
@@ -50,6 +50,7 @@ const earthMap = createEarthMapController({
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.ClampToEdgeWrapping;
texture.anisotropy = 16;
texture.generateMipmaps = true;
texture.minFilter = THREE.LinearMipmapLinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.needsUpdate = true;
@@ -57,11 +58,9 @@ const earthMap = createEarthMapController({
},
applyTexture: (texture) => {
if (_earthTextureOverlayMaterial) {
_earthTextureOverlayMaterial.map = texture;
_earthTextureOverlayMaterial.needsUpdate = true;
_earthTextureOverlayMaterial.uniforms.uDayMap.value = texture;
}
if (_earthTextureOverlay) _earthTextureOverlay.visible = _textureVisible && Boolean(texture);
if (_earthRimGlow) _earthRimGlow.visible = !(_textureVisible && texture);
},
onChange: (detail) => {
if (typeof window !== "undefined") {
@@ -146,16 +145,8 @@ export function createEarth(scene) {
C.textureWidthSegments,
C.textureHeightSegments,
);
_earthTextureOverlayMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
toneMapped: false,
transparent: true,
opacity: C.textureOverlayOpacity,
side: THREE.FrontSide,
depthWrite: false,
depthTest: true,
});
applyEarthDayNightShader(_earthTextureOverlayMaterial);
_earthTextureOverlayMaterial = createEarthSurfaceMaterial(C.surface, _earthSunDirection, _dayNightEnabled);
_earthShaders.push(_earthTextureOverlayMaterial);
_earthTextureOverlay = new THREE.Mesh(
textureOverlayGeometry,
_earthTextureOverlayMaterial,
@@ -182,115 +173,14 @@ export function createEarth(scene) {
occluder.renderOrder = 0.5;
earth.add(occluder);
// Keep the original atmosphere shells on the legacy camera-facing shader so
// they stay as a soft edge cue instead of becoming a visible transparent hull
// at close zoom levels.
const ATMOS_VERTEX_SHADER = `
varying vec3 vNormal;
void main() {
vNormal = normalize(normalMatrix * normal);
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
const RIM_VERTEX_SHADER = `
varying vec3 vNormal;
varying vec3 vViewDirection;
void main() {
vNormal = normalize(normalMatrix * normal);
vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
vViewDirection = normalize(-mvPosition.xyz);
gl_Position = projectionMatrix * mvPosition;
}
`;
// Fresnel atmosphere — inner rim
const [ir, ig, ib] = C.atmosInnerColor;
const atmosInnerGeo = new THREE.SphereGeometry(
CONFIG.earthRadius * C.atmosInnerRadiusFactor,
C.atmosInnerSegments,
C.atmosInnerSegments,
const atmosphere = new THREE.Mesh(
new THREE.SphereGeometry(CONFIG.earthRadius * C.atmosphere.radiusFactor, 64, 48),
createEarthAtmosphereMaterial(C.atmosphere, _earthSunDirection, _dayNightEnabled),
);
const atmosInnerMat = new THREE.ShaderMaterial({
vertexShader: ATMOS_VERTEX_SHADER,
fragmentShader: `
varying vec3 vNormal;
void main() {
float rim = 1.0 - abs(dot(vNormal, vec3(0.0, 0.0, 1.0)));
float intensity = pow(rim, ${C.atmosInnerRimPower.toFixed(1)});
gl_FragColor = vec4(${ir.toFixed(2)}, ${ig.toFixed(2)}, ${ib.toFixed(2)}, intensity * ${C.atmosInnerIntensity.toFixed(2)});
}
`,
blending: THREE.AdditiveBlending,
side: THREE.BackSide,
transparent: true,
depthWrite: false,
});
const atmosInner = new THREE.Mesh(atmosInnerGeo, atmosInnerMat);
atmosInner.renderOrder = 1;
earth.add(atmosInner);
// Fresnel atmosphere — outer corona
const [outerR, outerG, outerB] = C.atmosOuterColor;
const atmosOuterGeo = new THREE.SphereGeometry(
CONFIG.earthRadius * C.atmosOuterRadiusFactor,
C.atmosOuterSegments,
C.atmosOuterSegments,
);
const atmosOuterMat = new THREE.ShaderMaterial({
vertexShader: ATMOS_VERTEX_SHADER,
fragmentShader: `
varying vec3 vNormal;
void main() {
float rim = 1.0 - abs(dot(vNormal, vec3(0.0, 0.0, 1.0)));
// Fade at the outer silhouette instead of drawing a hard luminous ring.
float facing = abs(dot(normalize(vNormal), vec3(0.0, 0.0, 1.0)));
float edgeFade = smoothstep(0.0, ${C.atmosOuterEdgeFeather.toFixed(2)}, facing);
float intensity = pow(rim, ${C.atmosOuterRimPower.toFixed(1)}) * edgeFade;
gl_FragColor = vec4(${outerR.toFixed(2)}, ${outerG.toFixed(2)}, ${outerB.toFixed(2)}, intensity * ${C.atmosOuterIntensity.toFixed(2)});
}
`,
blending: THREE.AdditiveBlending,
side: THREE.BackSide,
transparent: true,
depthWrite: false,
});
const atmosOuter = new THREE.Mesh(atmosOuterGeo, atmosOuterMat);
atmosOuter.renderOrder = 1;
earth.add(atmosOuter);
// Fresnel rim cue: an outer shell keeps the edge tied to the globe while bypassing
// the darker fill layers that can otherwise hide a same-radius glow. Unlike the
// legacy atmosphere shells, this one uses the real view direction so its highlight
// stays attached to the visible globe edge while zooming.
const [rr, rg, rb] = C.rimGlowColor;
const rimGlowGeo = new THREE.SphereGeometry(
CONFIG.earthRadius * C.rimGlowRadiusFactor,
C.rimGlowSegments,
C.rimGlowSegments,
);
const rimGlowMat = new THREE.ShaderMaterial({
vertexShader: RIM_VERTEX_SHADER,
fragmentShader: `
varying vec3 vNormal;
varying vec3 vViewDirection;
void main() {
float viewFacing = max(dot(normalize(vNormal), normalize(vViewDirection)), 0.0);
float rim = 1.0 - viewFacing;
float alpha = pow(rim, ${C.rimGlowPower.toFixed(1)}) * ${C.rimGlowIntensity.toFixed(2)};
gl_FragColor = vec4(${rr.toFixed(2)}, ${rg.toFixed(2)}, ${rb.toFixed(2)}, alpha);
}
`,
blending: THREE.AdditiveBlending,
side: THREE.FrontSide,
transparent: true,
depthTest: false,
depthWrite: false,
});
_earthRimGlow = new THREE.Mesh(rimGlowGeo, rimGlowMat);
_earthRimGlow.name = "earth-rim-glow";
_earthRimGlow.renderOrder = C.rimGlowRenderOrder;
earth.add(_earthRimGlow);
atmosphere.name = "earth-atmosphere-scattering";
atmosphere.renderOrder = 1;
_earthShaders.push(atmosphere.material);
earth.add(atmosphere);
// Texture is loaded separately via loadEarthTexture() for staged loading
return earth;
@@ -302,7 +192,7 @@ export function createClouds(scene, earthObj) {
CLOUD_LAYER_CONFIG.widthSegments,
CLOUD_LAYER_CONFIG.heightSegments,
);
const material = new THREE.MeshPhongMaterial({
const material = new THREE.MeshBasicMaterial({
transparent: true,
opacity: CLOUD_LAYER_CONFIG.opacity,
depthTest: true,
@@ -310,9 +200,11 @@ export function createClouds(scene, earthObj) {
blending: THREE.AdditiveBlending,
side: THREE.DoubleSide
});
applyEarthDayNightShader(material);
clouds = new THREE.Mesh(geometry, material);
clouds.name = "earth-atmosphere-clouds";
clouds.renderOrder = 1.1;
clouds.visible = false;
earthObj.add(clouds);
@@ -343,6 +235,7 @@ export function loadCloudTexture() {
textureLoader.load(
CLOUD_LAYER_CONFIG.textureUrl,
(texture) => {
configureColorTexture(texture);
_cloudTexture = texture;
clouds.material.map = texture;
clouds.material.needsUpdate = true;
@@ -513,6 +406,16 @@ export function clearEarthTexture() {
earthMap.clear();
}
export function setEarthLandMask(texture, oceanHex = 0, landHex = 0xffffff) {
const uniforms = _earthTextureOverlayMaterial?.uniforms;
if (!uniforms) return;
uniforms.uLandMask.value = texture;
uniforms.uLandMaskAvailable.value = texture ? 1 : 0;
for (const [uniform, color] of [[uniforms.uMaskOcean, oceanHex], [uniforms.uMaskLand, landHex]]) {
uniform.value.set(((color >> 16) & 255) / 255, ((color >> 8) & 255) / 255, (color & 255) / 255);
}
}
export function setEarthSunDirection(direction) {
if (!direction) return;
_earthSunDirection.copy(direction).normalize();
@@ -556,11 +459,7 @@ export function setEarthTextureVisible(visible) {
_earthTextureOverlay.visible = textureShowing;
}
if (_earthTextureOverlayMaterial) {
_earthTextureOverlayMaterial.map = earthMap.getTexture();
_earthTextureOverlayMaterial.needsUpdate = true;
}
if (_earthRimGlow) {
_earthRimGlow.visible = !textureShowing;
_earthTextureOverlayMaterial.uniforms.uDayMap.value = earthMap.getTexture();
}
}

View File

@@ -1,15 +1,5 @@
import * as THREE from "three";
const DRAG_INERTIA = Object.freeze({
frameMs: 16,
minimumSampleMs: 8,
maximumFrameMs: 40,
releasePauseMs: 80,
minimumSpeed: 0.000005,
maximumSpeed: 0.003,
damping: 0.92,
});
// Magnify the apparent sphere radius, not the camera's distance to its center.
// At zoom=1 the existing camera pose is unchanged; larger zoom never enters it.
export function distanceForGlobeZoom(zoom, radius, defaultDistance, minimumAltitude = 10) {
@@ -23,71 +13,55 @@ export function globeZoomForDistance(distance, radius, defaultDistance) {
Math.max(0.0001, distance ** 2 - radius ** 2));
}
export function createSurfaceDrag(radius) {
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const center = new THREE.Vector3();
const hit = new THREE.Vector3();
const sphere = new THREE.Sphere(center, radius);
const anchor = new THREE.Vector3();
const current = new THREE.Vector3();
// Keep the legacy pixel sensitivity until the globe fills the viewport. At
// extreme zoom cap it by the surface distance, with no pointer/sphere gating.
export function globeDragRotationFactor(zoom, camera, viewport, config) {
const legacy = config.dragRotationFactorBase * THREE.MathUtils.clamp(
Math.pow(Math.max(zoom, 0.01), -config.dragRotationZoomExponent),
config.dragRotationScaleMin, config.dragRotationScaleMax,
);
const distance = camera.position.length();
const radius = config.earthRadius;
const tangent = Math.tan(THREE.MathUtils.degToRad(camera.fov) / 2);
const diameter = radius / Math.sqrt(Math.max(1, distance * distance - radius * radius)) * viewport.height / tangent;
const coverage = diameter / Math.max(1, Math.min(viewport.width, viewport.height));
const blend = THREE.MathUtils.smoothstep(coverage, 1, 1.5);
const surface = 2 * Math.max(config.minimumCameraAltitude, distance - radius) * tangent / (Math.max(1, viewport.height) * radius);
return legacy + (Math.min(legacy, surface) - legacy) * blend;
}
// All pointer drags are pixel-driven, including outside the silhouette. Rotate
// around the geographic axis horizontally and camera right vertically. Keep
// quaternion math so Euler rebasing cannot reverse drag or add unwanted bank.
export function createScreenSpaceDrag() {
const pending = new THREE.Vector2();
const cameraRotation = new THREE.Quaternion();
const parentInverse = new THREE.Quaternion();
const initial = new THREE.Quaternion();
const change = new THREE.Quaternion();
const previous = new THREE.Quaternion();
const axis = new THREE.Vector3();
let active = false, speed = 0, lastMoveAt = 0;
function pointerNormal(earth, camera, point, viewport, output) {
camera.updateMatrixWorld();
earth.getWorldPosition(center);
raycaster.setFromCamera(pointer.set(
(point.x - viewport.left) / viewport.width * 2 - 1,
1 - (point.y - viewport.top) / viewport.height * 2,
), camera);
if (!raycaster.ray.intersectSphere(sphere, hit)) {
// Outside the silhouette there is no grabbed surface; continue smoothly
// around its rim instead of producing a jump or an invalid intersection.
raycaster.ray.closestPointToPoint(center, hit);
}
output.copy(hit).sub(center).normalize().applyQuaternion(parentInverse);
}
const screenUp = new THREE.Vector3();
const north = new THREE.Vector3();
const localNorth = new THREE.Vector3(0, 1, 0);
const change = new THREE.Quaternion();
return {
begin(earth, camera, point, viewport, now) {
speed = 0; active = true; lastMoveAt = now;
move(yaw, pitch) { pending.x += yaw; pending.y += pitch; },
stop() { pending.set(0, 0); },
advance(earth, camera, smoothing) {
const length = pending.length();
if (!length) return;
// Bound a delayed frame without throwing away accumulated pointer motion.
const fraction = Math.min(smoothing, (Math.PI / 4) / length);
camera.getWorldQuaternion(cameraRotation);
parentInverse.identity();
if (earth.parent) earth.parent.getWorldQuaternion(parentInverse).invert();
pointerNormal(earth, camera, point, viewport, anchor);
initial.copy(earth.quaternion);
},
move(earth, camera, point, viewport, now) {
if (!active) return;
pointerNormal(earth, camera, point, viewport, current);
previous.copy(earth.quaternion);
change.setFromUnitVectors(anchor, current);
earth.quaternion.copy(initial).premultiply(change);
change.copy(earth.quaternion).multiply(previous.invert()).normalize();
if (change.w < 0) change.set(-change.x, -change.y, -change.z, -change.w);
axis.set(change.x, change.y, change.z);
const angle = 2 * Math.atan2(axis.length(), Math.max(0, change.w));
axis.normalize();
speed = Math.min(DRAG_INERTIA.maximumSpeed, angle / Math.max(DRAG_INERTIA.minimumSampleMs, now - lastMoveAt));
lastMoveAt = now;
},
end(now, cancelled = false) {
active = false;
if (cancelled || now - lastMoveAt > DRAG_INERTIA.releasePauseMs) speed = 0;
},
stop() { active = false; speed = 0; },
hasInertia() { return !active && speed > DRAG_INERTIA.minimumSpeed; },
advance(earth, deltaMs) {
if (active || speed <= DRAG_INERTIA.minimumSpeed) return false;
const elapsed = Math.min(deltaMs, DRAG_INERTIA.maximumFrameMs);
change.setFromAxisAngle(axis, speed * elapsed);
screenUp.set(0, 1, 0).applyQuaternion(cameraRotation).applyQuaternion(parentInverse);
north.copy(localNorth).applyQuaternion(earth.quaternion);
const direction = north.dot(screenUp) < 0 ? -1 : 1;
change.setFromAxisAngle(localNorth, pending.x * fraction * direction);
earth.quaternion.multiply(change);
axis.set(1, 0, 0).applyQuaternion(cameraRotation).applyQuaternion(parentInverse);
change.setFromAxisAngle(axis, pending.y * fraction);
earth.quaternion.premultiply(change).normalize();
speed *= Math.pow(DRAG_INERTIA.damping, elapsed / DRAG_INERTIA.frameMs);
return true;
pending.multiplyScalar(1 - fraction);
},
};
}

View File

@@ -1,7 +1,7 @@
import { expect, test } from "bun:test";
import * as THREE from "three";
import { CONFIG, EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET } from "./constants.js";
import { createSurfaceDrag, distanceForGlobeZoom, globeZoomForDistance } from "./globe-navigation.js";
import { createScreenSpaceDrag, globeDragRotationFactor, distanceForGlobeZoom, globeZoomForDistance } from "./globe-navigation.js";
const radius = CONFIG.earthRadius + EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET;
const distance = zoom => distanceForGlobeZoom(zoom, CONFIG.earthRadius,
@@ -33,49 +33,96 @@ function scene(zoom, width, height) {
const p = local.clone().applyMatrix4(earth.matrixWorld).project(camera);
return { x: viewport.left + (p.x + 1) * width / 2, y: viewport.top + (1 - p.y) * height / 2 };
};
const grabbed = new THREE.Vector3(0, 0, radius).applyQuaternion(earth.quaternion.clone().invert());
return { camera, earth, viewport, project, grabbed };
return { camera, earth, viewport, project };
}
for (const zoom of [0.5, 1, 2, 3, 5]) for (const [width, height] of [[1440, 900], [390, 844]]) {
test(`${zoom * 100}% at ${width}px: the grabbed surface follows the pointer pixel for pixel`, () => {
const f = scene(zoom, width, height);
const drag = createSurfaceDrag(radius);
const start = f.project(f.grabbed);
drag.begin(f.earth, f.camera, start, f.viewport, 0);
for (let step = 1; step <= 20; step++) {
const target = { x: start.x + step, y: start.y + step * 0.6 };
drag.move(f.earth, f.camera, target, f.viewport, step * 16);
const actual = f.project(f.grabbed);
expect(actual.x).toBeCloseTo(target.x, 6);
expect(actual.y).toBeCloseTo(target.y, 6);
expect(drag.advance(f.earth, 16)).toBe(false);
for (const [width, height] of [[1440, 900], [390, 844]]) {
test(`screen drag keeps pointer direction after multiple revolutions and quaternion rebasing at ${width}px`, () => {
const f = scene(0.5, width, height);
const drag = createScreenSpaceDrag();
for (const turns of [-12, -3, 0, 5, 20]) for (const pitch of [0.3, 2.6, -2.7]) {
for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
f.earth.rotation.set(pitch, turns * Math.PI * 2 + 1.8, 0.7);
// Camera focusing writes quaternions; this
// canonicalizes XYZ angles, reproducing the legacy reversed Y axis.
f.earth.quaternion.copy(f.earth.quaternion.clone());
const point = new THREE.Vector3(0, 0, radius).applyQuaternion(f.earth.quaternion.clone().invert());
const before = f.project(point);
drag.stop();
drag.move(dx * 0.02, dy * 0.02);
drag.advance(f.earth, f.camera, 0.25);
const after = f.project(point);
if (dx) expect((after.x - before.x) * dx).toBeGreaterThan(0);
if (dy) expect((after.y - before.y) * dy).toBeGreaterThan(0);
expect(f.earth.quaternion.length()).toBeCloseTo(1, 10);
}
}
});
}
test("a paused release or cancellation cannot fling the globe", () => {
const f = scene(5, 1440, 900);
const drag = createSurfaceDrag(radius), start = f.project(f.grabbed);
drag.begin(f.earth, f.camera, start, f.viewport, 0);
drag.move(f.earth, f.camera, { x: start.x + 50, y: start.y }, f.viewport, 16);
drag.end(200);
expect(drag.hasInertia()).toBe(false);
drag.begin(f.earth, f.camera, start, f.viewport, 220);
drag.move(f.earth, f.camera, { x: start.x + 30, y: start.y }, f.viewport, 236);
drag.end(237, true);
expect(drag.hasInertia()).toBe(false);
test("screen drag follows a rotated camera with a transformed parent and retains damped motion", () => {
const f = scene(0.5, 1440, 900), drag = createScreenSpaceDrag();
const parent = new THREE.Object3D();
parent.rotation.set(0.8, 1.2, -0.7); parent.add(f.earth);
f.camera.position.set(250, 100, 400); f.camera.lookAt(0, 0, 0); f.camera.updateMatrixWorld();
parent.updateMatrixWorld(true);
const point = f.camera.position.clone().normalize().multiplyScalar(radius);
f.earth.worldToLocal(point);
let previous = f.project(point);
drag.move(0.05, 0.02);
for (let i = 0; i < 12; i++) {
drag.advance(f.earth, f.camera, 0.25);
const current = f.project(point);
expect(current.x).toBeGreaterThan(previous.x);
expect(current.y).toBeGreaterThan(previous.y);
previous = current;
}
drag.stop();
const rotation = f.earth.quaternion.clone();
drag.advance(f.earth, f.camera, 0.25);
expect(f.earth.quaternion.angleTo(rotation)).toBeCloseTo(0, 7);
});
test("pinch zoom can rebase the remaining finger without a jump", () => {
const f = scene(1, 390, 844), drag = createSurfaceDrag(radius);
const start = f.project(f.grabbed);
drag.begin(f.earth, f.camera, start, f.viewport, 0);
drag.stop();
f.camera.position.z = distance(5);
f.camera.updateMatrixWorld();
const before = f.earth.quaternion.clone();
drag.begin(f.earth, f.camera, start, f.viewport, 100);
drag.move(f.earth, f.camera, start, f.viewport, 116);
expect(f.earth.quaternion.angleTo(before)).toBeCloseTo(0, 7);
test("repeated horizontal small-globe drags and inertia preserve the existing geographic axis", () => {
const f = scene(1, 1440, 900), drag = createScreenSpaceDrag();
for (const pitch of [0.4, 2.6, -2.7]) {
f.earth.rotation.set(pitch, 18 * Math.PI + 1.8, 0.35);
const north = new THREE.Vector3(0, 1, 0).applyQuaternion(f.earth.quaternion);
for (let step = 0; step < 600; step++) {
drag.move(step % 80 < 40 ? 0.035 : -0.035, 0);
drag.advance(f.earth, f.camera, 0.18);
expect(new THREE.Vector3(0, 1, 0).applyQuaternion(f.earth.quaternion).distanceTo(north)).toBeLessThan(1e-10);
}
drag.stop();
}
});
test("vertical small-globe input deliberately changes tilt", () => {
const f = scene(1, 1440, 900), drag = createScreenSpaceDrag();
const north = new THREE.Vector3(0, 1, 0).applyQuaternion(f.earth.quaternion);
drag.move(0, 0.3); drag.advance(f.earth, f.camera, 1);
expect(new THREE.Vector3(0, 1, 0).applyQuaternion(f.earth.quaternion).distanceTo(north)).toBeGreaterThan(0.1);
});
for (const [width, height] of [[1440, 900], [390, 844]]) for (const zoom of [0.5, 1, 3, 5]) {
test(`${zoom * 100}% at ${width}px: dragging outside the globe keeps rotating in the pointer direction`, () => {
const f = scene(zoom, width, height), drag = createScreenSpaceDrag();
const factor = globeDragRotationFactor(zoom, f.camera, f.viewport, CONFIG);
let previous = f.earth.quaternion.clone();
for (let x = width / 2; x < width * 1.2; x += 10) {
drag.move(10 * factor, 0); drag.advance(f.earth, f.camera, 0.18);
const north = new THREE.Vector3(0, 1, 0).applyQuaternion(previous);
const delta = f.earth.quaternion.clone().multiply(previous.clone().invert());
expect(new THREE.Vector3(delta.x, delta.y, delta.z).dot(north)).toBeGreaterThan(0);
previous.copy(f.earth.quaternion);
}
});
}
test("normal zoom keeps legacy sensitivity while extreme zoom limits magnification", () => {
const normal = scene(1, 1440, 900), large = scene(5, 1440, 900);
expect(globeDragRotationFactor(1, normal.camera, normal.viewport, CONFIG)).toBe(CONFIG.dragRotationFactorBase);
expect(globeDragRotationFactor(5, large.camera, large.viewport, CONFIG)).toBeLessThan(CONFIG.dragRotationFactorBase * CONFIG.dragRotationScaleMin);
});

View File

@@ -1,3 +1,4 @@
import { drawMarkerBadge } from "./marker-badges.js";
import * as THREE from "three";
import { CONFIG } from "./constants.js";
@@ -16,7 +17,6 @@ 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_MAX_SCREEN_DIAMETER_PX = 96;
const CLUSTER_SEED_DISTANCE_FACTOR = 1.8;
const CLUSTER_TRANSITION_MS = 220;
const CLUSTER_BAND_HYSTERESIS = 0.08;
@@ -50,7 +50,7 @@ const SPHERICAL_CLUSTER_BANDS = Object.freeze([
Object.freeze({ key: "near", maxZoom: 3.5, distance: 4 }),
Object.freeze({ key: "detail", maxZoom: Number.POSITIVE_INFINITY, distance: 0 }),
]);
let compactDotsEnabled = true;
let compactDotsEnabled = false;
let screenAvoidanceRevision = 0;
// Named overlap profiles. Layers that should be recognized as sharing a place
@@ -530,32 +530,11 @@ function findScreenClusterGroups(entries) {
return groups;
}
function getScreenDistance(entryA, entryB) {
return Math.hypot(entryA.x - entryB.x, entryA.y - entryB.y);
}
function getAngularDistance(entryA, entryB) {
const dot = entryA.direction.dot(entryB.direction);
return Math.acos(Math.min(1, Math.max(-1, dot)));
}
function getScreenBounds(entries) {
return entries.reduce(
(bounds, entry) => ({
left: Math.min(bounds.left, entry.x - entry.radiusPx),
right: Math.max(bounds.right, entry.x + entry.radiusPx),
top: Math.min(bounds.top, entry.y - entry.radiusPx),
bottom: Math.max(bounds.bottom, entry.y + entry.radiusPx),
}),
{
left: Number.POSITIVE_INFINITY,
right: Number.NEGATIVE_INFINITY,
top: Number.POSITIVE_INFINITY,
bottom: Number.NEGATIVE_INFINITY,
},
);
}
function splitLargeScreenClusterGroup(groupEntries) {
const maxMarkersPerDot = groupEntries.reduce(
(maxCount, entry) => Math.min(maxCount, entry.maxMarkersPerDot || CLUSTER_MAX_MARKERS_PER_DOT),
@@ -965,7 +944,7 @@ export function createInteractableLayer(options = {}) {
const drawX = (atlasCellSize - drawWidth) / 2;
const drawY = (atlasCellSize - drawHeight) / 2;
if (icon.colorable !== false && drawOptions.color) {
if ((icon.colorable !== false || icon.badge) && drawOptions.color) {
const tintCanvas = createCanvas(atlasCellSize, atlasCellSize);
const tintContext = tintCanvas.getContext("2d");
tintContext.clearRect(0, 0, atlasCellSize, atlasCellSize);
@@ -993,7 +972,15 @@ export function createInteractableLayer(options = {}) {
atlasCellSize,
...drawOptions,
};
if (icon.coordinates !== "canvas") {
const badgeOptions = typeof icon.badge === "function" ? icon.badge(resolvedDrawOptions) : icon.badge;
if (badgeOptions) {
const palette = drawMarkerBadge(context, { ...resolvedDrawOptions, ...badgeOptions });
resolvedDrawOptions.color = palette.ink;
resolvedDrawOptions.glow = false;
context.translate(canvas.width / 2, canvas.height / 2);
context.scale(0.6, 0.6);
if (icon.coordinates === "canvas") context.translate(-canvas.width / 2, -canvas.height / 2);
} else if (icon.coordinates !== "canvas") {
context.translate(canvas.width / 2, canvas.height / 2);
}
if (icon.draw) {
@@ -1001,7 +988,10 @@ export function createInteractableLayer(options = {}) {
} else {
drawAssetIcon(context, getIconSource(resolvedDrawOptions), resolvedDrawOptions);
}
icon.afterDraw?.(context, resolvedDrawOptions);
context.restore();
context.save();
if (icon.coordinates !== "canvas") context.translate(canvas.width / 2, canvas.height / 2);
icon.afterDraw?.(context, { atlasCellSize, ...drawOptions });
context.restore();
const texture = new THREE.CanvasTexture(canvas);
@@ -1136,7 +1126,7 @@ export function createInteractableLayer(options = {}) {
}
function shouldUseCompactDots(camera) {
return getCameraZoom(camera) <= COMPACT_DOT_ZOOM_THRESHOLD;
return compactDotsEnabled && getCameraZoom(camera) <= COMPACT_DOT_ZOOM_THRESHOLD;
}
function getMarkerStableId(marker, fallbackIndex = 0) {

View File

@@ -1,11 +1,12 @@
import * as THREE from "three";
import { SATELLITE_CONFIG } from "./constants.js";
const EARTH_RADIUS_KM = 6378.137;
const SURFACE_SCALE = 1.003;
const SURFACE_OFFSET = 0.72;
const CLUSTER_DIAMETER_KM_APPROX = 4500;
const CLUSTER_RADIUS_KM_BASE = CLUSTER_DIAMETER_KM_APPROX / 2;
const IRIDIUM_OVERLAY_COLOR = 0x5faeff;
const IRIDIUM_OVERLAY_COLOR = SATELLITE_CONFIG.footprintColor;
const IRIDIUM_REFERENCE_ALTITUDE_KM = 780;
const FILL_RINGS = 12;
const FILL_SEGMENTS = 48;

View File

@@ -1,4 +1,4 @@
import { createSurfaceDrag } from "./globe-navigation.js";
import { createScreenSpaceDrag, globeDragRotationFactor } from "./globe-navigation.js";
import * as THREE from "three";
import {
@@ -345,7 +345,8 @@ let isDragging = false;
let previousMousePosition = { x: 0, y: 0 };
let targetRotation = { x: 0, y: 0 };
let inertialVelocity = { x: 0, y: 0 };
const surfaceDrag = createSurfaceDrag(CONFIG.earthRadius + EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET);
const screenSpaceDrag = createScreenSpaceDrag();
let screenSpaceInertia = false;
let hoveredCable = null;
let hoveredBGP = null;
let hoveredComputeCenter = null;
@@ -367,7 +368,6 @@ let lastBGPClickCollector = null;
let lastBGPClickType = null;
let lastBGPClickPos = { x: 0, y: 0 };
let lastVesselHoverPickTime = 0;
let earthTexture = null;
let animationFrameId = null;
let initialized = false;
let destroyed = false;
@@ -577,12 +577,15 @@ function setGlobeDraggingUiState(active) {
function hasActiveGlobeInertia() {
return (
surfaceDrag.hasInertia() ||
Math.abs(inertialVelocity.x) > INERTIA_MIN_VELOCITY ||
Math.abs(inertialVelocity.y) > INERTIA_MIN_VELOCITY
);
}
function getDragRotationFactor() {
return globeDragRotationFactor(getZoomLevel(), camera, renderer.domElement.getBoundingClientRect(), CONFIG);
}
function getTargetSwitchZoomOptions(requestedZoom) {
const currentZoom = getZoomLevel();
const defaultZoom = getDefaultEarthZoomLevel();
@@ -3837,6 +3840,7 @@ function applyCableVisualState() {
allCables.forEach((cable) => {
const cableId = cable.userData.cableId;
const state = getCableState(cableId);
cable.material.userData.cableSelected = state === CABLE_STATE.LOCKED;
const hasFocus =
(lockedObjectType === "cable" && lockedObject) ||
@@ -3872,7 +3876,7 @@ function applyCableVisualState() {
((origColor & 255) / 255) * brightness,
);
} else {
cable.material.opacity = 1;
cable.material.opacity = CABLE_CONFIG.visual.normalOpacity;
cable.material.color.setHex(cable.userData.originalColor);
}
}
@@ -4517,7 +4521,8 @@ function setupMotionControl() {
export function applyMotionRotate(axisOrDirection, directionOrIntensity = 1, maybeIntensity = 1) {
const earth = getEarth();
if (!earth) return false;
surfaceDrag.stop();
screenSpaceDrag.stop();
screenSpaceInertia = false;
const axisCall = axisOrDirection === "horizontal" || axisOrDirection === "vertical";
const axis = axisCall ? axisOrDirection : "horizontal";
const direction = axisCall ? directionOrIntensity : axisOrDirection;
@@ -5753,9 +5758,11 @@ function onMouseMove(event) {
isLongDrag = true;
}
surfaceDrag.move(earth, camera, { x: event.clientX, y: event.clientY },
renderer.domElement.getBoundingClientRect(), event.timeStamp || performance.now());
targetRotation = { x: earth.rotation.x, y: earth.rotation.y };
const factor = getDragRotationFactor();
const deltaX = (event.clientX - previousMousePosition.x) * factor;
const deltaY = (event.clientY - previousMousePosition.y) * factor;
screenSpaceDrag.move(deltaX, deltaY);
inertialVelocity = { x: deltaY, y: deltaX };
previousMousePosition = { x: event.clientX, y: event.clientY };
if (!document.body.classList.contains("layout-mode-mobile")) {
clearCountryBoundaryHover();
@@ -6047,10 +6054,10 @@ function onMouseDown(event) {
previousMousePosition = { x: event.clientX, y: event.clientY };
dragStartPointer = { ...previousMousePosition };
inertialVelocity = { x: 0, y: 0 };
screenSpaceDrag.stop();
screenSpaceInertia = true;
if (earth) {
targetRotation = { x: earth.rotation.x, y: earth.rotation.y };
surfaceDrag.begin(earth, camera, { x: event.clientX, y: event.clientY },
renderer.domElement.getBoundingClientRect(), event.timeStamp || performance.now());
}
clearDocumentSelection();
setGlobeDraggingUiState(true);
@@ -6059,7 +6066,8 @@ function onMouseDown(event) {
}
function onMouseUp(event = {}, cancelInertia = false) {
surfaceDrag.end(event.timeStamp || performance.now(), cancelInertia || event.type === "pointercancel");
const cancelled = cancelInertia || event.type === "pointercancel";
if (cancelled) inertialVelocity = { x: 0, y: 0 };
isDragging = false;
setGlobeDraggingUiState(false);
clearDocumentSelection();
@@ -6089,7 +6097,7 @@ function onPointerDown(event) {
};
activeDragPointerId = null;
onMouseUp();
surfaceDrag.stop();
screenSpaceDrag.stop();
inertialVelocity = { x: 0, y: 0 };
return;
}
@@ -6424,7 +6432,7 @@ function animate() {
const hasInertia = hasActiveGlobeInertia();
if (getAutoRotate() && getRotationMode() === ROTATION_MODE.ROTATE && earth && !isDragging && activeTouchPoints.size === 0 && !hasInertia) {
earth.rotation.y += getAutoRotationSpeed() * (deltaTime / 16);
earth.rotateY(getAutoRotationSpeed() * (deltaTime / 16));
// Keep the drag target aligned with autorotation only when the user is not
// actively dragging and there is no residual inertial motion to preserve.
@@ -6435,26 +6443,32 @@ function animate() {
}
if (earth) {
if (isDragging || surfaceDrag.advance(earth, deltaTime)) {
// Pointer movement has already placed the grabbed surface point exactly.
targetRotation.x = earth.rotation.x;
targetRotation.y = earth.rotation.y;
if (isDragging) {
screenSpaceDrag.advance(earth, camera, DRAG_SMOOTHING_FACTOR);
targetRotation = { x: earth.rotation.x, y: earth.rotation.y };
} else if (
Math.abs(inertialVelocity.x) > INERTIA_MIN_VELOCITY ||
Math.abs(inertialVelocity.y) > INERTIA_MIN_VELOCITY
) {
// Continue rotating after release and gradually decay the motion.
targetRotation.x += inertialVelocity.x * (deltaTime / 16);
targetRotation.y += inertialVelocity.y * (deltaTime / 16);
earth.rotation.x +=
(targetRotation.x - earth.rotation.x) * DRAG_SMOOTHING_FACTOR;
earth.rotation.y +=
(targetRotation.y - earth.rotation.y) * DRAG_SMOOTHING_FACTOR;
if (screenSpaceInertia) {
screenSpaceDrag.move(inertialVelocity.y * (deltaTime / 16), inertialVelocity.x * (deltaTime / 16));
screenSpaceDrag.advance(earth, camera, DRAG_SMOOTHING_FACTOR);
targetRotation = { x: earth.rotation.x, y: earth.rotation.y };
} else {
// Keep the gesture-control rotation path independent of pointer drag.
targetRotation.x += inertialVelocity.x * (deltaTime / 16);
targetRotation.y += inertialVelocity.y * (deltaTime / 16);
earth.rotation.x += (targetRotation.x - earth.rotation.x) * DRAG_SMOOTHING_FACTOR;
earth.rotation.y += (targetRotation.y - earth.rotation.y) * DRAG_SMOOTHING_FACTOR;
}
inertialVelocity.x *= Math.pow(INERTIA_DAMPING, deltaTime / 16);
inertialVelocity.y *= Math.pow(INERTIA_DAMPING, deltaTime / 16);
} else {
inertialVelocity.x = 0;
inertialVelocity.y = 0;
screenSpaceDrag.stop();
screenSpaceInertia = false;
targetRotation.x = earth.rotation.x;
targetRotation.y = earth.rotation.y;
}
@@ -6556,7 +6570,8 @@ function animate() {
export function destroy() {
if (destroyed) return;
destroyed = true;
surfaceDrag.stop();
screenSpaceDrag.stop();
screenSpaceInertia = false;
stopVesselRealtime();
currentLoadToken += 1;
isDataLoading = false;

View File

@@ -0,0 +1,53 @@
// Reference-aligned badge surfaces shared by all finite ground-object layers.
// Painted into the existing texture atlas: no DOM nodes or per-marker meshes.
const REFERENCE_BADGES = {
'#14b8a6': { top: '#14b8a6', bottom: '#0d9488', border: '#5eead4', ink: '#042f2e' },
'#a855f7': { top: '#a855f7', bottom: '#7e22ce', border: '#d8b4fe', ink: '#3b0764' },
'#f59e0b': { top: '#f59e0b', bottom: '#d97706', border: '#fef3c7', ink: '#451a03' },
};
function blend(color, target, amount) {
const value = Number.parseInt(color.slice(1), 16);
const end = Number.parseInt(target.slice(1), 16);
return '#' + [16, 8, 0].map(shift => Math.round(((value >> shift) & 255) * (1 - amount) + ((end >> shift) & 255) * amount).toString(16).padStart(2, '0')).join('');
}
export function markerBadgePalette(color = '#38bdf8') {
const normalized = /^#[0-9a-f]{6}$/i.test(color) ? color.toLowerCase() : '#38bdf8';
return REFERENCE_BADGES[normalized] || {
top: normalized,
bottom: blend(normalized, '#020617', 0.25),
border: blend(normalized, '#ffffff', 0.64),
ink: blend(normalized, '#020617', 0.87),
};
}
export function drawMarkerBadge(context, { color, atlasCellSize = 128, glow = false }) {
const palette = markerBadgePalette(color);
const scale = atlasCellSize / 128;
context.save();
context.scale(scale, scale);
const gradient = context.createLinearGradient(22, 18, 108, 110);
gradient.addColorStop(0, palette.top);
gradient.addColorStop(1, palette.bottom);
context.shadowColor = glow ? palette.top : 'rgba(0,0,0,0.65)';
context.shadowBlur = glow ? 17 : 11;
context.shadowOffsetY = glow ? 0 : 6;
context.beginPath();
context.roundRect(20, 18, 88, 88, 19);
context.fillStyle = gradient;
context.fill();
context.shadowBlur = 0;
context.shadowOffsetY = 0;
context.lineWidth = 2.8;
context.strokeStyle = palette.border;
context.stroke();
context.beginPath();
context.moveTo(38, 23);
context.lineTo(89, 23);
context.strokeStyle = 'rgba(255,255,255,0.23)';
context.lineWidth = 2;
context.stroke();
context.restore();
return palette;
}

View File

@@ -0,0 +1,57 @@
import { expect, test } from 'bun:test';
import * as THREE from 'three';
import { markerBadgePalette } from './marker-badges.js';
import { createInteractableLayer, getInteractableCompactDotsEnabled, setInteractableCompactDotsEnabled } 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' });
expect(markerBadgePalette('#a855f7')).toEqual({ top: '#a855f7', bottom: '#7e22ce', border: '#d8b4fe', ink: '#3b0764' });
expect(markerBadgePalette('#f59e0b').border).toBe('#fef3c7');
});
test('compact dots are optional; complete badges keep marker identity, anchors and batched rendering', () => {
const previousDocument = globalThis.document, previousWindow = globalThis.window;
const previousCompact = getInteractableCompactDotsEnabled();
const canvases = [];
globalThis.window = { innerWidth: 1280, innerHeight: 720, devicePixelRatio: 1 };
globalThis.document = { createElement() {
const trace = [];
const canvas = { width: 128, height: 128, trace, getContext() { return new Proxy({}, {
get(_target, key) { if (key === 'createLinearGradient' || key === 'createRadialGradient') return () => ({ addColorStop() {} });
if (key === 'measureText') return () => ({ width: 10 });
return (...args) => { trace.push([key, ...args]); };
},
}); } };
canvases.push(canvas); return canvas;
} };
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 }),
});
const earth = new THREE.Object3D(), camera = new THREE.PerspectiveCamera(75, 1280 / 720, 0.1, 5000);
camera.position.z = 350; camera.updateMatrixWorld();
layer.attach(earth); layer.setVisible(true);
layer.setData([{ id: 'same-object', latitude: 15, longitude: 25 }]);
const marker = layer.getMarkers()[0], anchor = marker.position.clone();
layer.updateVisualState(null, null, camera);
const points = layer.group.children.find(group => group.children.some(child => child.isPoints)).children.find(child => child.isPoints);
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(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;
}
});

View File

@@ -0,0 +1,43 @@
// Smooth rendering between propagated orbit samples; never propagate synthetic
// orbits or lerp satellite identities. Radial normalization avoids chord sinking.
export function createSatelliteMotion() {
let from = new Float32Array(), target = new Float32Array(), rendered = new Float32Array();
let startedAt = 0, duration = 1, lastAlpha = -1;
function sample(now, output) {
if (!target.length) return false;
const alpha = Math.max(0, Math.min(1, (now - startedAt) / duration));
if (alpha === lastAlpha) return false;
for (let i = 0; i < target.length; i += 3) {
const a = Math.hypot(from[i], from[i + 1], from[i + 2]);
const b = Math.hypot(target[i], target[i + 1], target[i + 2]);
const x = from[i] + (target[i] - from[i]) * alpha;
const y = from[i + 1] + (target[i + 1] - from[i + 1]) * alpha;
const z = from[i + 2] + (target[i + 2] - from[i + 2]) * alpha;
const length = Math.hypot(x, y, z);
const scale = length > 1e-8 ? (a + (b - a) * alpha) / length : 0;
rendered[i] = output[i] = x * scale;
rendered[i + 1] = output[i + 1] = y * scale;
rendered[i + 2] = output[i + 2] = z * scale;
}
lastAlpha = alpha;
return true;
}
return {
push(values, now, intervalMs) {
if (target.length !== values.length || !target.length) {
from = new Float32Array(values); target = new Float32Array(values); rendered = new Float32Array(values);
} else {
sample(now, rendered);
from.set(rendered); target.set(values);
for (let i = 0; i < target.length; i += 3) {
const dot = from[i] * target[i] + from[i + 1] * target[i + 1] + from[i + 2] * target[i + 2];
// A large discontinuity means data/altitude was replaced, not motion.
if (dot <= 0) from.set(target.subarray(i, i + 3), i);
}
}
startedAt = now; duration = Math.max(1, intervalMs); lastAlpha = -1;
},
sample,
reset() { from = new Float32Array(); target = new Float32Array(); rendered = new Float32Array(); lastAlpha = -1; },
};
}

View File

@@ -0,0 +1,35 @@
import { expect, test } from 'bun:test';
import { createSatelliteMotion } from './satellite-motion.js';
test('orbit samples move smoothly at render cadence without sinking inside their radius', () => {
const motion=createSatelliteMotion(), out=new Float32Array(3);
motion.push(new Float32Array([100,0,0]),0,250); motion.sample(0,out);
motion.push(new Float32Array([0,100,0]),0,250);
let previous=0;
for(let time=0;time<=250;time+=10){
motion.sample(time,out);
expect(Math.hypot(...out)).toBeCloseTo(100,4);
expect(out[1]).toBeGreaterThanOrEqual(previous); previous=out[1];
}
expect(out[1]).toBeCloseTo(100,5);
expect(motion.sample(300,out)).toBe(false);
});
test('a new worker sample rebases from the displayed position without a jump',()=>{
const motion=createSatelliteMotion(),out=new Float32Array(3);
motion.push(new Float32Array([100,0,0]),0,250); motion.sample(0,out);
motion.push(new Float32Array([90,44,0]),0,250); motion.sample(100,out);
const before=out.slice();
motion.push(new Float32Array([80,60,0]),100,250); motion.sample(100,out);
expect([...out]).toEqual([...before]);
motion.sample(116,out); expect(out[1]).toBeGreaterThan(before[1]);
});
test('reset, count changes and discontinuous replacement do not blend unrelated satellites',()=>{
const motion=createSatelliteMotion(),out=new Float32Array(6);
motion.push(new Float32Array([100,0,0]),0,250); motion.sample(0,out);
motion.reset(); motion.push(new Float32Array([0,100,0,0,0,120]),100,250); motion.sample(100,out);
expect([...out]).toEqual([0,100,0,0,0,120]);
motion.push(new Float32Array([0,-100,0,0,0,120]),200,250); motion.sample(200,out);
expect([...out]).toEqual([0,-100,0,0,0,120]);
});

View File

@@ -0,0 +1,57 @@
import * as THREE from 'three';
export const ORBIT_VISUAL = Object.freeze({
visibleFraction: 0.96,
sampleSeconds: 10,
flowRepeats: 16,
flowSpeed: 0.45,
endFade: 0.015,
});
export function openOrbitSampleTimes(periodSeconds) {
const duration = periodSeconds * ORBIT_VISUAL.visibleFraction;
const segments = Math.max(2, Math.ceil(duration / ORBIT_VISUAL.sampleSeconds));
return Array.from({ length: segments + 1 }, (_, index) => duration * index / segments);
}
export function createOrbitFlowGeometry(points) {
const positions = new Float32Array(points.length * 3);
const distance = new Float32Array(points.length);
points.forEach((point, index) => {
point.toArray(positions, index * 3);
if (index) distance[index] = distance[index - 1] + point.distanceTo(points[index - 1]);
});
const length = distance[distance.length - 1] || 1;
for (let i = 0; i < distance.length; i++) distance[i] /= length;
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setAttribute('orbitProgress', new THREE.BufferAttribute(distance, 1));
return geometry;
}
export function createOrbitFlowMaterial(color) {
return new THREE.ShaderMaterial({
uniforms: { uColor: { value: new THREE.Color(color) }, uTime: { value: 0 } },
transparent: true, depthTest: true, depthWrite: false, toneMapped: false,
vertexShader: `
attribute float orbitProgress;
varying float vProgress;
void main() {
vProgress = orbitProgress;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform vec3 uColor;
uniform float uTime;
varying float vProgress;
void main() {
// Increasing progress is increasing prediction time / travel direction.
float phase = fract(vProgress * ${ORBIT_VISUAL.flowRepeats.toFixed(1)} - uTime * ${ORBIT_VISUAL.flowSpeed.toFixed(2)});
float pulse = smoothstep(0.45, 0.95, phase) * (1.0 - smoothstep(0.95, 1.0, phase));
float ends = smoothstep(0.0, ${ORBIT_VISUAL.endFade}, vProgress) * (1.0 - smoothstep(${1 - ORBIT_VISUAL.endFade}, 1.0, vProgress));
gl_FragColor = vec4(mix(uColor, vec3(1.0), pulse * 0.65), (0.56 + 0.44 * pulse) * ends);
}
`,
});
}

View File

@@ -0,0 +1,28 @@
import { expect, test } from "bun:test";
import * as THREE from "three";
import { openOrbitSampleTimes, createOrbitFlowGeometry } from "./satellite-orbit-visual.js";
test("prediction samples form an open chronological arc with no overshoot or closing chord", () => {
for (const period of [5573.7, 86400]) {
const times = openOrbitSampleTimes(period);
expect(times[0]).toBe(0);
expect(times.at(-1)).toBeLessThan(period);
const points = times.map(time => new THREE.Vector3(Math.cos(time / period * 2 * Math.PI), Math.sin(time / period * 2 * Math.PI), 0));
const geometry = createOrbitFlowGeometry(points);
const positions = geometry.attributes.position;
expect(positions.count).toBe(points.length);
expect(new THREE.Vector3().fromBufferAttribute(positions, 0).distanceTo(new THREE.Vector3().fromBufferAttribute(positions, positions.count - 1))).toBeGreaterThan(0.1);
for (let i = 1; i < times.length; i++) expect(times[i]).toBeGreaterThan(times[i - 1]);
geometry.dispose();
}
});
test("flow progress follows distance and chronological direction across unequal orbit segments", () => {
const points = [new THREE.Vector3(0,0,0),new THREE.Vector3(1,0,0),new THREE.Vector3(1,3,0)];
const geometry = createOrbitFlowGeometry(points);
expect([...geometry.attributes.orbitProgress.array]).toEqual([0,0.25,1]);
geometry.dispose();
const degenerate = createOrbitFlowGeometry([points[0],points[0]]);
expect([...degenerate.attributes.orbitProgress.array]).toEqual([0,0]);
degenerate.dispose();
});

View File

@@ -1,3 +1,5 @@
import { ORBIT_VISUAL, openOrbitSampleTimes, createOrbitFlowGeometry, createOrbitFlowMaterial } from "./satellite-orbit-visual.js";
import { createSatelliteMotion } from "./satellite-motion.js";
// satellites.js - Satellite visualization module with real SGP4 positions and animations
import * as THREE from "three";
@@ -33,6 +35,7 @@ let showSatellites = false;
let showTrails = true;
let selectedSatellite = null;
let satellitePositions = [];
const satelliteMotion = createSatelliteMotion();
let hoverRingSprite = null;
let lockedRingSprite = null;
let lockedDotSprite = null;
@@ -220,7 +223,7 @@ function createSatellitePointMaterial({
}) {
return new THREE.ShaderMaterial({
uniforms: {
pointTexture: { value: texture },
...(texture ? { pointTexture: { value: texture } } : {}),
size: { value: size * getPointPixelRatio() },
opacity: { value: opacity },
baseColor: { value: new THREE.Color(baseColor) },
@@ -259,16 +262,30 @@ function createSatellitePointMaterial({
}
`,
fragmentShader: `
uniform sampler2D pointTexture;
${useVertexColor ? "" : "uniform sampler2D pointTexture;"}
uniform float opacity;
varying float vAlpha;
varying vec3 vColor;
void main() {
${useVertexColor ? `
vec2 disc = (gl_PointCoord - 0.5) * 2.0;
float distanceSquared = dot(disc, disc);
float edge = 1.0 - smoothstep(0.72, 1.0, distanceSquared);
float depth = sqrt(max(0.0, 1.0 - distanceSquared));
float light = 0.82 + 0.18 * max(dot(normalize(vec3(-disc.x, disc.y, depth)), normalize(vec3(-0.3, 0.4, 1.0))), 0.0);
float brightness = max(vColor.r, max(vColor.g, vColor.b));
// Stable category hue on both hemispheres; only a small core highlight.
vec3 particleColor = mix(vColor, vec3(brightness), pow(depth, 12.0) * 0.12);
float alphaValue = edge * opacity * vAlpha;
if (alphaValue < 0.02) discard;
gl_FragColor = vec4(particleColor * light, alphaValue);
` : `
vec4 texel = texture2D(pointTexture, gl_PointCoord);
float alphaValue = texel.a * opacity * vAlpha;
if (alphaValue < ${alphaTest.toFixed(3)}) discard;
gl_FragColor = vec4(vColor * texel.rgb, alphaValue);
`}
}
`,
});
@@ -278,7 +295,7 @@ const SATELLITE_LEGEND_RULES = [
{
key: "equatorial",
label: "赤道轨道(0-30°)",
color: "#ff3333",
color: "#3399ff",
match: (props) => {
const inclination = Number(props?.inclination ?? 0);
return inclination >= 0 && inclination < 30;
@@ -287,7 +304,7 @@ const SATELLITE_LEGEND_RULES = [
{
key: "low",
label: "低倾角轨道(30-60°)",
color: "#ff9933",
color: "#ff801a",
match: (props) => {
const inclination = Number(props?.inclination ?? 0);
return inclination >= 30 && inclination < 60;
@@ -296,7 +313,7 @@ const SATELLITE_LEGEND_RULES = [
{
key: "medium",
label: "中倾角轨道(60-90°)",
color: "#ffff33",
color: "#00e680",
match: (props) => {
const inclination = Number(props?.inclination ?? 0);
return inclination >= 60 && inclination < 90;
@@ -305,7 +322,7 @@ const SATELLITE_LEGEND_RULES = [
{
key: "high",
label: "高倾角轨道(90-120°)",
color: "#33ff33",
color: "#cc33ff",
match: (props) => {
const inclination = Number(props?.inclination ?? 0);
return inclination >= 90 && inclination < 120;
@@ -314,7 +331,7 @@ const SATELLITE_LEGEND_RULES = [
{
key: "retrograde",
label: "逆行轨道(120-180°)",
color: "#3333ff",
color: "#ff3366",
match: (props) => {
const inclination = Number(props?.inclination ?? 0);
return inclination >= 120 && inclination <= 180;
@@ -323,7 +340,7 @@ const SATELLITE_LEGEND_RULES = [
{
key: "other",
label: "其他",
color: "#d7e2f4",
color: "#94a3b8",
match: () => true,
},
];
@@ -399,9 +416,9 @@ export function updateSatelliteIdleBreathingVisual(isIdle = true) {
}
if (satelliteBackdropPoints.material.uniforms?.opacity) {
satelliteBackdropPoints.material.uniforms.opacity.value = 0.42;
satelliteBackdropPoints.material.uniforms.opacity.value = SATELLITE_CONFIG.dotOutlineOpacity;
} else {
satelliteBackdropPoints.material.opacity = 0.42;
satelliteBackdropPoints.material.opacity = SATELLITE_CONFIG.dotOutlineOpacity;
}
for (const points of [satellitePoints, satelliteBackdropPoints]) {
@@ -506,36 +523,6 @@ function disposeObjectTree(object, parent = earthObjRef) {
disposeObject3D(object, parent);
}
function createDotTexture() {
const canvas = document.createElement("canvas");
canvas.width = DOT_TEXTURE_SIZE;
canvas.height = DOT_TEXTURE_SIZE;
const ctx = canvas.getContext("2d");
const center = DOT_TEXTURE_SIZE / 2;
const radius = center - 2;
const gradient = ctx.createRadialGradient(
center,
center,
0,
center,
center,
radius,
);
gradient.addColorStop(0, "rgba(255, 255, 255, 1)");
gradient.addColorStop(0.5, "rgba(255, 255, 255, 0.8)");
gradient.addColorStop(1, "rgba(255, 255, 255, 0)");
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(center, center, radius, 0, Math.PI * 2);
ctx.fill();
const texture = new THREE.CanvasTexture(canvas);
texture.needsUpdate = true;
return texture;
}
function createBackdropDotTexture() {
const canvas = document.createElement("canvas");
canvas.width = DOT_TEXTURE_SIZE;
@@ -607,7 +594,6 @@ function createFilledCircleTexture(color = "#ffcc00") {
export function createSatellites(scene, earthObj) {
initSatelliteScene(scene, earthObj);
const dotTexture = createDotTexture();
const backdropTexture = createBackdropDotTexture();
const pointsGeometry = new THREE.BufferGeometry();
@@ -618,13 +604,12 @@ export function createSatellites(scene, earthObj) {
texture: backdropTexture,
useVertexColor: false,
baseColor: 0x0b1626,
opacity: 0.42,
opacity: SATELLITE_CONFIG.dotOutlineOpacity,
alphaTest: 0.04,
});
const pointsMaterial = createSatellitePointMaterial({
size: getSatelliteDotBaseSize(),
texture: dotTexture,
useVertexColor: true,
opacity: 0.9,
alphaTest: 0.1,
@@ -759,6 +744,7 @@ function clearSatelliteTrailGeometry() {
}
function clearSatelliteTrails() {
satelliteMotion.reset();
resetSatelliteTrailState();
clearSatelliteTrailGeometry();
if (satelliteData.length) startSatellitePositionWorker();
@@ -1020,6 +1006,7 @@ export async function loadSatellites(options = {}) {
const data = await response.json();
satelliteData = data.features || [];
satelliteMotion.reset();
satellitePropagator.reset();
resetSatelliteTrailState();
ensureSatelliteCapacity(satelliteData.length);
@@ -1055,6 +1042,7 @@ export function updateSatellitePositions(deltaTime = 0, force = false, options =
positionUpdateAccumulator += deltaTime;
}
renderSatelliteMotion();
if (!force && positionUpdateAccumulator < POSITION_UPDATE_INTERVAL_MS) {
return;
}
@@ -1078,6 +1066,7 @@ export function updateSatellitePositions(deltaTime = 0, force = false, options =
return;
}
applySatellitePositionSnapshot({ baseTime: Date.now() + elapsedMs }, shouldUpdateTrails);
renderSatelliteMotion();
}
function applySatellitePositionSnapshot(snapshot, shouldUpdateTrails) {
@@ -1213,8 +1202,10 @@ function applySatellitePositionSnapshot(snapshot, shouldUpdateTrails) {
instanceColorEnds[base + 2] = b * fallbackAlphaEnd;
trailSegmentCount++;
}
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;
@@ -1269,6 +1260,29 @@ function applySatellitePositionSnapshot(snapshot, shouldUpdateTrails) {
}
}
function renderSatelliteMotion() {
if (!showSatellites && lockedSatelliteIndex === null && hoveredSatelliteIndex === null) return;
if (!satellitePoints || !satelliteBackdropPoints || !satellitePositions.length) return;
const positions = satellitePoints.geometry.attributes.position;
if (!satelliteMotion.sample(performance.now(), positions.array)) return;
const count = Math.min(satelliteData.length, satelliteCapacity);
const backdrop = satelliteBackdropPoints.geometry.attributes.position;
backdrop.array.set(positions.array.subarray(0, count * 3));
const trailEnds = satelliteTrails.geometry.attributes.instanceEnd;
const now = Date.now();
for (let i = 0; i < count; i++) {
const state = satellitePositions[i];
state.current.fromArray(positions.array, i * 3);
state.currentTime?.setTime(getSatelliteSampleTimeMs(now, i, count));
if (showTrails && state.renderTrailTipOffset >= 0) {
state.current.toArray(trailEnds.array, state.renderTrailTipOffset);
}
}
positions.needsUpdate = true;
backdrop.needsUpdate = true;
if (showTrails) trailEnds.needsUpdate = true;
}
export function toggleSatellites(visible) {
showSatellites = visible;
if (satelliteBackdropPoints) {
@@ -1559,8 +1573,8 @@ function createGroundFootprintMaterial() {
depthTest: true,
depthWrite: false,
uniforms: {
uColor: { value: new THREE.Color(0xffffff) },
uOpacity: { value: 0.46 },
uColor: { value: new THREE.Color(SATELLITE_CONFIG.footprintColor) },
uOpacity: { value: SATELLITE_CONFIG.footprintOpacity },
uMajorKm: { value: 1000 },
uMinorKm: { value: 700 },
uGapCenterNorthKm: { value: 0 },
@@ -1576,7 +1590,7 @@ function createGroundFootprintMaterial() {
uGapSoftnessKm: { value: 6 },
uGlowMode: { value: 0 },
uSunDirectionWorld: { value: satelliteSunDirection.clone() },
uDayVisibilityBoost: { value: 1.48 },
uDayVisibilityBoost: { value: SATELLITE_CONFIG.footprintDayVisibilityBoost },
},
vertexShader: `
varying vec3 vWorldPosition;
@@ -1654,12 +1668,10 @@ function createGroundFootprintMaterial() {
float daylight = clamp(sunFacing * 0.5 + 0.5, 0.0, 1.0);
alpha *= mix(1.0, uDayVisibilityBoost, daylight);
vec3 nightColor = vec3(0.24, 0.56, 1.0);
vec3 dayColor = vec3(1.0, 0.72, 0.08);
vec3 finalColor = mix(nightColor, dayColor, daylight);
// A footprint keeps one blue hue. Daylight only raises contrast through
// opacity; it must never recolor the same coverage patch yellow.
if (alpha <= 0.001) discard;
gl_FragColor = vec4(finalColor, alpha);
gl_FragColor = vec4(uColor, alpha);
}
`,
});
@@ -2345,7 +2357,7 @@ function applyDimMaterialState(isDimmed) {
}
}
if (satelliteBackdropPoints) {
const opacity = isDimmed ? DIMMED_SATELLITE_BACKDROP_OPACITY : 0.42;
const opacity = isDimmed ? DIMMED_SATELLITE_BACKDROP_OPACITY : SATELLITE_CONFIG.dotOutlineOpacity;
if (satelliteBackdropPoints.material.uniforms?.opacity) {
satelliteBackdropPoints.material.uniforms.opacity.value = opacity;
} else {
@@ -2446,15 +2458,14 @@ function calculateOrbitalPeriod(meanMotion) {
function calculatePredictedOrbit(
satellite,
periodSeconds,
sampleInterval = 10,
) {
const points = [];
const samples = Math.ceil(periodSeconds / sampleInterval);
const sampleTimes = openOrbitSampleTimes(periodSeconds);
const startTime = getSelectedSatellitePositionState(satellite)?.currentTime || new Date();
const fixedSiderealTime = gstime(startTime);
for (let i = 0; i <= samples; i++) {
const time = new Date(startTime.getTime() + i * sampleInterval * 1000);
for (const offsetSeconds of sampleTimes) {
const time = new Date(startTime.getTime() + offsetSeconds * 1000);
const pos = computeSatelliteInertialOrbitPosition(
satellite,
time,
@@ -2463,21 +2474,13 @@ function calculatePredictedOrbit(
if (pos) points.push(pos);
}
if (points.length < samples * 0.5) {
return calculateFallbackPredictedOrbit(satellite, samples);
if (points.length < sampleTimes.length * 0.5) {
return calculateFallbackPredictedOrbit(satellite, sampleTimes.length - 1);
}
closeOrbitLoop(points);
return points;
}
function closeOrbitLoop(points) {
if (points.length > 2) {
points.push(points[0].clone());
}
}
function calculateFallbackPredictedOrbit(satellite, samples) {
const points = [];
const radius =
@@ -2492,7 +2495,7 @@ function calculateFallbackPredictedOrbit(satellite, samples) {
const sinInclination = Math.sin(inclinationRad);
for (let i = 0; i <= samples; i++) {
const argument = (i / samples) * Math.PI * 2;
const argument = (i / samples) * Math.PI * 2 * ORBIT_VISUAL.visibleFraction;
const cosArgument = Math.cos(argument);
const sinArgument = Math.sin(argument);
@@ -2509,7 +2512,6 @@ function calculateFallbackPredictedOrbit(satellite, samples) {
points.push(new THREE.Vector3(ecfX, ecfZ, -ecfY));
}
closeOrbitLoop(points);
return points;
}
@@ -2537,34 +2539,13 @@ export function showPredictedOrbit(satellite) {
const points = calculatePredictedOrbit(satellite, periodSeconds);
if (points.length < 2) return;
const positions = new Float32Array(points.length * 3);
const colors = new Float32Array(points.length * 3);
for (let i = 0; i < points.length; i++) {
positions[i * 3] = points[i].x;
positions[i * 3 + 1] = points[i].y;
positions[i * 3 + 2] = points[i].z;
const t = i / (points.length - 1);
colors[i * 3] = 1 - t * 0.4;
colors[i * 3 + 1] = 1 - t * 0.6;
colors[i * 3 + 2] = t;
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));
const material = new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.8,
blending: THREE.AdditiveBlending,
depthTest: true,
depthWrite: false,
});
const geometry = createOrbitFlowGeometry(points);
const material = createOrbitFlowMaterial(getSatelliteLegendRule(satellite.properties).color);
predictedOrbitLine = new THREE.Line(geometry, material);
const startedAt = performance.now();
predictedOrbitLine.onBeforeRender = () => {
material.uniforms.uTime.value = (performance.now() - startedAt) / 1000;
};
predictedOrbitLine.renderOrder = SATELLITE_CONFIG.overlayRenderOrder;
earthObjRef.add(predictedOrbitLine);
}
@@ -2577,6 +2558,7 @@ export function hidePredictedOrbit() {
}
export function clearSatelliteData() {
satelliteMotion.reset();
stopSatellitePositionWorker();
satelliteData = [];
satellitePropagator.reset();

View File

@@ -198,6 +198,7 @@ const vesselIconLayer = createInteractableLayer({
},
avoidance: false,
icon: {
badge: true,
draw(context, { marker, rotationBin = 0, glow = false, color = "#ffffff" }) {
const anchored = Boolean(marker?.userData?.anchored);
if (!anchored) {

View File

@@ -0,0 +1,240 @@
import axios from 'axios'
import { Plus, RefreshCw, RotateCcw, Save, Trash2 } from 'lucide-react'
import { useEffect, useRef, useState, type FormEvent, type ReactNode } from 'react'
import Scrollbar from '../../components/Scrollbar/Scrollbar'
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 { Panel } from '../patterns/patterns'
import {
notifyComputeConfigurationChanged, reportIsUsed,
type ComputeConfiguration, type ComputeConfigurationResponse, type ComputeObservation,
} from './compute-comparison-model'
import './compute-comparison.css'
const ENDPOINT = `${import.meta.env.VITE_API_URL || '/api/v1'}/data-products/compute/configuration`
type View = 'observations' | 'sources' | 'innovation'
function Field({ title, children }: { title: string; children: ReactNode }) {
return <label className="an-compute-field"><span>{title}</span>{children}</label>
}
function validationMessage(message: string, english: boolean) {
const normalized = message.replace(/^Value error, /, '')
if (english) return normalized
const translations: Record<string, string> = {
'Global shares for one year must total at most 100 percent': '同年各国全球算力占比之和不能超过 100%。',
'Each metric/year may have only one observation': '同一指标、同一年只能保留一条年度观测。',
'Report source IDs must be unique': '报告来源不能重复。',
'Innovation observation years must be unique': '创新指数分差的年份不能重复。',
'Observation year must not be after its report year': '观测年份不能晚于所选报告的年份。',
'Review date must not be in the future': '核验日期不能晚于今天。',
'Use countries from the canonical compute catalog, not regional totals': '请使用国家观测,不能直接录入区域合计。',
'Use a report URL without credentials (maximum 2000 characters)': '报告链接不能包含账号密码,长度不能超过 2000 字符。',
}
if (normalized.startsWith('Missing report source:')) return '请为观测选择有效的报告来源。'
return translations[normalized] || '字段内容无效,请检查必填项、数值范围和报告链接。'
}
function requestError(error: unknown, english: boolean) {
if (!axios.isAxiosError(error)) return english ? 'Request failed.' : '请求失败。'
if (error.response?.status === 409) return english
? 'Someone updated this configuration. Your draft is preserved. Reload and reconcile before saving.'
: '配置已被其他人更新。当前草稿已保留,请核对后重新加载再保存。'
const detail: unknown = error.response?.data?.detail
if (Array.isArray(detail)) return detail.map((item: { loc?: Array<string | number>; msg?: string }) => {
const section = item.loc?.find(value => ['sources', 'observations', 'innovation'].includes(String(value)))
const index = item.loc?.find(value => typeof value === 'number')
const labels: Record<string, string> = { sources: '报告来源', observations: '年度观测', innovation: '创新指数分差' }
const location = section ? english ? String(section) : labels[String(section)] : ''
const row = typeof index === 'number' ? english ? ` #${index + 1}` : ` 第 ${index + 1} 条` : ''
return `${location}${row}${location ? ':' : ''}${validationMessage(item.msg || '', english)}`
}).join(';')
if (error.response?.status === 403) return english ? 'Administrator access required.' : '仅管理员可以维护算力对比数据。'
return typeof detail === 'string' ? detail : error.message
}
export function ComputeComparisonSettings({ active }: { active: boolean }) {
const { locale } = useLocale()
const english = locale === 'en-US'
const t = (zh: string, en: string) => english ? en : zh
const [saved, setSaved] = useState<ComputeConfigurationResponse | null>(null)
const [draft, setDraft] = useState<ComputeConfiguration | null>(null)
const [view, setView] = useState<View>('observations')
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const [message, setMessage] = useState('')
const [confirmation, setConfirmation] = useState<'reset' | 'reload' | null>(null)
const [loadRevision, setLoadRevision] = useState(0)
const viewportRef = useRef<HTMLDivElement>(null)
const dirty = Boolean(draft && saved && JSON.stringify(draft) !== JSON.stringify(saved.config))
useEffect(() => {
viewportRef.current?.scrollTo({ top: 0 })
}, [view])
useEffect(() => {
if (!active || saved) return
const controller = new AbortController()
setBusy(true)
axios.get<ComputeConfigurationResponse>(ENDPOINT, { signal: controller.signal })
.then(({ data }) => { setSaved(data); setDraft(data.config); setError('') })
.catch(failure => { if (!controller.signal.aborted) setError(requestError(failure, english)) })
.finally(() => { if (!controller.signal.aborted) setBusy(false) })
return () => controller.abort()
}, [active, saved, loadRevision, english])
useEffect(() => {
if (!dirty) return
const preventLoss = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = '' }
window.addEventListener('beforeunload', preventLoss)
return () => window.removeEventListener('beforeunload', preventLoss)
}, [dirty])
const edit = (next: ComputeConfiguration) => { setDraft(next); setMessage(''); setError('') }
const reload = () => { setSaved(null); setLoadRevision(value => value + 1); setMessage('') }
const metricLabel = (metric: string) => metric === 'global_share'
? t('全球算力占比 (%)', 'Global compute share (%)')
: t('计算设备总规模 · FP32 (EFlop/s)', 'Total compute · FP32 (EFlop/s)')
async function publish(reset = false) {
if (!saved || !draft) return
setBusy(true); setError(''); setMessage('')
try {
const { data } = reset
? await axios.post<ComputeConfigurationResponse>(`${ENDPOINT}/reset`, { revision: saved.revision })
: await axios.put<ComputeConfigurationResponse>(ENDPOINT, { revision: saved.revision, config: draft })
setSaved(data); setDraft(data.config); setConfirmation(null)
setMessage(t('已发布,地球卡片将自动更新。', 'Published. Earth cards will refresh automatically.'))
notifyComputeConfigurationChanged()
} catch (failure) { setError(requestError(failure, english)); setConfirmation(null) }
finally { setBusy(false) }
}
function save(event: FormEvent) { event.preventDefault(); void publish() }
if (!active && !saved) return null
const sources = draft?.sources.map(source => ({ value: source.id, label: source.title || source.id })) || []
const sourceSelect = (value: string, onChange: (value: string) => void) => (
<Field title={t('报告来源', 'Report source')}><Select value={value} onValueChange={onChange}
options={sources} placeholder={t('选择报告', 'Select a report')} /></Field>
)
const removeButton = (label: string, onClick: () => void, disabled = false) => (
<Button type="button" size="icon" variant="subtle" title={label} aria-label={label}
disabled={disabled || busy} onClick={onClick}><Trash2 size={15} /></Button>
)
const updateObservation = (index: number, row: ComputeObservation) => {
if (draft) edit({ ...draft, observations: draft.observations.map((item, i) => i === index ? row : item) })
}
return (
<Panel className="an-compute-settings" hidden={!active}>
<form className="an-compute-form" onSubmit={save} onInvalidCapture={event => {
const details = (event.target as HTMLElement).closest('details')
if (details) details.open = true
}}>
<div className="an-panel-heading an-compute-heading">
<div><h2>{t('算力对比数据', 'Compute comparison data')}</h2>
<p>{t('同年、同口径的国家观测;未录入的数值保持缺失。', 'Comparable country observations by year. Omitted values stay unavailable.')}</p></div>
<div className="an-compute-actions">
<Button type="button" size="icon" variant="subtle" title={t('重新加载', 'Reload')} aria-label={t('重新加载', 'Reload')} disabled={busy} onClick={() => dirty ? setConfirmation('reload') : reload()}>
<RefreshCw size={15} /></Button>
<Button type="button" size="icon" variant="subtle" title={t('恢复默认', 'Restore defaults')} aria-label={t('恢复默认', 'Restore defaults')} disabled={busy || !saved} onClick={() => setConfirmation('reset')}>
<RotateCcw size={15} /></Button>
<Button type="submit" disabled={busy || !dirty} loading={busy}>
<Save size={15} />{t('保存并发布', 'Save and publish')}</Button>
</div>
</div>
<div className="an-compute-status" role="status">
{message || (error && !saved ? t('配置读取失败', 'Configuration unavailable') : dirty ? t('有未发布修改', 'Unpublished changes') : saved?.is_default ? t('当前使用内置报告数据', 'Using bundled report data') : saved ? t('当前使用后台配置', 'Using published configuration') : t('正在读取配置…', 'Loading configuration…'))}
</div>
{error ? <p className="an-compute-error" role="alert">{error}</p> : null}
{draft && saved ? <>
<div className="an-compute-toolbar">
<div className="an-compute-actions" role="group" aria-label={t('数据分类', 'Data categories')}>
{([['observations', t('年度观测', 'Observations')], ['sources', t('报告来源', 'Sources')], ['innovation', t('创新指数分差', 'Innovation gap')]] as const).map(([key, label]) => (
<Button key={key} type="button" variant={view === key ? 'primary' : 'subtle'} aria-pressed={view === key} onClick={() => setView(key)}>{label}</Button>
))}
</div>
</div>
<Scrollbar className="an-compute-scroll" viewportRef={viewportRef}>
<fieldset className="an-compute-content" disabled={busy}>
<Field title={t('核验日期', 'Review date')}><Input type="date" required disabled={busy} value={draft.reviewed_at}
onChange={event => edit({ ...draft, reviewed_at: event.target.value })} /></Field>
{view === 'observations' ? <>
<p>{t('占比以全球为分母;绝对量统一为 FP32 EFlop/s。区域只在全部成员都有同年数据时汇总。', 'Shares use the global denominator. Absolute values use FP32 EFlop/s. Regions require every member in the same year.')}</p>
{draft.observations.map((row, index) => <details className="an-compute-row" key={index} open={index === 0 ? true : undefined}>
<summary>{row.year} · {metricLabel(row.metric)} · {Object.keys(row.values).length} {t('个国家', 'countries')}</summary>
<div className="an-compute-fields">
<Field title={t('观测年份', 'Observation year')}><Input type="number" required min={2000} max={2100} value={Number.isFinite(row.year) ? row.year : ''}
onChange={event => updateObservation(index, { ...row, year: event.target.valueAsNumber })} /></Field>
<Field title={t('指标', 'Metric')}><Select value={row.metric} options={(['global_share', 'absolute'] as const).map(metric => ({ value: metric, label: metricLabel(metric) }))}
onValueChange={value => updateObservation(index, { ...row, metric: value as ComputeObservation['metric'] })} /></Field>
{sourceSelect(row.source_id, value => updateObservation(index, { ...row, source_id: value }))}
</div>
<div className="an-compute-values">
{Object.entries(row.values).map(([code, value]) => <div className="an-compute-value" key={code}>
<Field title={saved.countries.find(country => country.code === code)?.[english ? 'name_en' : 'name'] || code}>
<Input type="number" required min={0} max={row.metric === 'global_share' ? 100 : 1e12} step="any" value={Number.isFinite(value) ? value : ''}
onChange={event => updateObservation(index, { ...row, values: { ...row.values, [code]: event.target.valueAsNumber } })} />
</Field>
{removeButton(t(`移除 ${code} 观测`, `Remove ${code} observation`), () => {
const values = { ...row.values }; delete values[code]; updateObservation(index, { ...row, values })
})}
</div>)}
</div>
<div className="an-compute-row-actions">
<Select value="" placeholder={t('添加国家观测', 'Add country observation')}
options={saved.countries.filter(country => !(country.code in row.values)).map(country => ({ value: country.code, label: english ? country.name_en : country.name }))}
onValueChange={code => updateObservation(index, { ...row, values: { ...row.values, [code]: Number.NaN } })} />
{removeButton(t('移除年度观测', 'Remove annual observation'), () => edit({ ...draft, observations: draft.observations.filter((_, i) => i !== index) }))}
</div>
</details>)}
<Button type="button" variant="subtle" onClick={() => edit({ ...draft, observations: [...draft.observations, { year: new Date().getFullYear(), metric: 'global_share', source_id: sources[0]?.value || '', values: {} }] })}>
<Plus size={15} />{t('添加年度观测', 'Add annual observation')}</Button>
</> : view === 'sources' ? <>
{draft.sources.map((source, index) => <details className="an-compute-row" key={index} open={index === 0 ? true : undefined}>
<summary>{source.title || t('新报告', 'New report')} · {source.report_year}</summary>
<div className="an-compute-fields">
{(['title', 'publisher', 'url', 'locator'] as const).map((key, fieldIndex) => <Field key={key} title={[
t('报告标题', 'Report title'), t('发布机构', 'Publisher'), t('报告链接', 'Report URL'), t('页码 / 图表位置', 'Page / figure locator'),
][fieldIndex]}><Input required type={key === 'url' ? 'url' : 'text'} maxLength={key === 'url' ? 2000 : 500}
value={source[key]}
onChange={event => edit({ ...draft, sources: draft.sources.map((item, i) => i === index ? { ...item, [key]: event.target.value } : item) })} /></Field>)}
<Field title={t('报告年份', 'Report year')}><Input type="number" required min={2000} max={2100} value={Number.isFinite(source.report_year) ? source.report_year : ''}
onChange={event => edit({ ...draft, sources: draft.sources.map((item, i) => i === index ? { ...item, report_year: event.target.valueAsNumber } : item) })} /></Field>
<Field title={t('发布日期(可选)', 'Publication date (optional)')}><Input type="date" value={source.published_at || ''}
onChange={event => edit({ ...draft, sources: draft.sources.map((item, i) => i === index ? { ...item, published_at: event.target.value || null } : item) })} /></Field>
</div>
{removeButton(reportIsUsed(draft, source.id) ? t('该来源仍被观测引用', 'Source is referenced by observations') : t('移除报告', 'Remove report'),
() => edit({ ...draft, sources: draft.sources.filter((_, i) => i !== index) }), reportIsUsed(draft, source.id))}
</details>)}
<Button type="button" variant="subtle" onClick={() => edit({ ...draft, sources: [...draft.sources, { id: `report-${crypto.randomUUID()}`, title: '', publisher: '', url: '', locator: '', report_year: new Date().getFullYear(), published_at: null }] })}>
<Plus size={15} />{t('添加报告来源', 'Add report source')}</Button>
</> : <>
<p>{t('美国减中国的创新指数分差,与算力占比独立,不反推单国得分。', 'US minus China innovation index gap. Independent of compute shares; individual scores are not inferred.')}</p>
{draft.innovation.map((row, index) => <div className="an-compute-row" key={index}>
<div className="an-compute-fields">
<Field title={t('观测年份', 'Observation year')}><Input type="number" required min={2000} max={2100} value={Number.isFinite(row.year) ? row.year : ''}
onChange={event => edit({ ...draft, innovation: draft.innovation.map((item, i) => i === index ? { ...item, year: event.target.valueAsNumber } : item) })} /></Field>
<Field title={t('指数分差', 'Index gap')}><Input type="number" required min={-100} max={100} step="any" value={Number.isFinite(row.value) ? row.value : ''}
onChange={event => edit({ ...draft, innovation: draft.innovation.map((item, i) => i === index ? { ...item, value: event.target.valueAsNumber } : item) })} /></Field>
{sourceSelect(row.source_id, value => edit({ ...draft, innovation: draft.innovation.map((item, i) => i === index ? { ...item, source_id: value } : item) }))}
</div>
{removeButton(t('移除创新观测', 'Remove innovation observation'), () => edit({ ...draft, innovation: draft.innovation.filter((_, i) => i !== index) }))}
</div>)}
<Button type="button" variant="subtle" onClick={() => edit({ ...draft, innovation: [...draft.innovation, { year: new Date().getFullYear(), value: Number.NaN, source_id: sources[0]?.value || '' }] })}>
<Plus size={15} />{t('添加创新观测', 'Add innovation observation')}</Button>
</>}
</fieldset>
</Scrollbar>
</> : null}
</form>
<ConfirmDialog open={confirmation !== null} onOpenChange={open => !open && setConfirmation(null)} loading={busy}
title={confirmation === 'reset' ? t('恢复内置报告数据?', 'Restore bundled report data?') : t('放弃草稿并重新加载?', 'Discard draft and reload?')}
description={t('当前未发布修改将被替换。恢复默认会记录在操作审计中。', 'Unpublished edits will be replaced. Restoring defaults is audited.')}
onConfirm={() => { if (confirmation === 'reset') void publish(true); else { setConfirmation(null); reload() } }} />
</Panel>
)
}

View File

@@ -44,6 +44,11 @@ import { AdminSwitch } from '../components/ui/switch'
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 {
COLLECTION_QUEUE_ACTIVE_STATUSES, isStaleTaskUpdate, patchCollectionTask, upsertCollectionTask,
type CollectionQueueItem, type CollectionQueueStatus,
} from './datasource-task-queue'
type AnyRecord = Record<string, unknown>
type Tone = 'success' | 'warning' | 'danger' | 'info' | 'neutral' | 'running' | 'ai'
@@ -102,28 +107,6 @@ type DatasourceFilters = {
dataStatus: string
}
type CollectionQueueStatus = 'queued' | 'running' | 'cancelling' | 'success' | 'failed' | 'skipped' | 'cancelled'
type CollectionQueueItem = {
key: string
sourceId: string
source?: string
name: string
taskId?: number | string | null
taskType?: string
status: CollectionQueueStatus
phase?: string
phaseMessage?: string
progress?: number | null
recordsProcessed?: number | null
totalRecords?: number | null
reason?: string
error?: string
createdAt: number
updatedAt: number
completedAt?: number
}
type DatasourceMetricBaseline = {
taskId: string
sourceId: string
@@ -145,7 +128,6 @@ const DEFAULT_DATASOURCE_FILTERS: DatasourceFilters = {
const DATASOURCE_FILTER_STORAGE_KEY = 'planet.admin.datasource.filters'
const DATASOURCE_FILTER_QUERY_KEYS = ['product', 'module', 'is_active', 'run_status', 'data_status']
const DATASOURCE_TERMINAL_STATUSES = new Set(['success', 'completed', 'failed', 'cancelled', 'canceled', 'stopped'])
const COLLECTION_QUEUE_ACTIVE_STATUSES = new Set<CollectionQueueStatus>(['queued', 'running', 'cancelling'])
const TASK_ACTIVE_STATUSES = new Set(['queued', 'pending', 'running', 'cancelling'])
const TASK_INACTIVE_STATUSES = new Set(['success', 'completed', 'failed', 'error', 'cancelled', 'canceled', 'stopped', 'idle'])
@@ -425,10 +407,6 @@ function queueItemKey(item: AnyRecord) {
return source ? `source-name:${taskType}:${source}` : `queue:${taskType}:${Date.now()}`
}
function isSameQueueTaskType(left?: string, right?: string) {
return text(left, 'collect') === text(right, 'collect')
}
function isActiveQueueStatus(status: CollectionQueueStatus) {
return COLLECTION_QUEUE_ACTIVE_STATUSES.has(status)
}
@@ -3218,49 +3196,22 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
}, [])
const upsertCollectionQueueItem = useCallback((item: CollectionQueueItem) => {
setCollectionQueue((current) => {
const index = current.findIndex((existing) => (
existing.key === item.key
|| (item.taskId && existing.taskId === item.taskId)
|| (isActiveQueueStatus(existing.status) && isSameQueueTaskType(existing.taskType, item.taskType) && item.sourceId && existing.sourceId === item.sourceId)
|| (isActiveQueueStatus(existing.status) && isSameQueueTaskType(existing.taskType, item.taskType) && item.source && existing.source === item.source)
))
if (index < 0) return [item, ...current]
const next = [...current]
next[index] = { ...next[index], ...item, key: next[index].key, createdAt: next[index].createdAt || item.createdAt }
return next
})
setCollectionQueue(current => upsertCollectionTask(current, item))
}, [])
const patchCollectionQueueFromTask = useCallback((payload: AnyRecord) => {
const sourceId = text(payload.datasource_id || payload.source_id || payload.id, '')
const source = text(payload.collector_name || payload.source, '')
const taskId = payload.task_id as number | string | null | undefined
const status = queueStatusFromTask(payload.status || payload.phase, payload.is_running)
const payloadTaskType = text(payload.task_type, '')
setCollectionQueue((current) => current.map((item) => {
const taskTypeMatched = !payloadTaskType || isSameQueueTaskType(item.taskType, payloadTaskType)
const matched = Boolean(taskId && item.taskId === taskId)
|| (taskTypeMatched && Boolean(sourceId && item.sourceId === sourceId))
|| (taskTypeMatched && Boolean(source && item.source === source))
if (!matched) return item
const terminal = ['success', 'failed', 'cancelled', 'skipped'].includes(status)
return {
...item,
taskId: taskId ?? item.taskId,
taskType: text(payload.task_type, item.taskType || ''),
sourceId: sourceId || item.sourceId,
source: source || item.source,
status,
phase: text(payload.phase, item.phase || ''),
phaseMessage: text(payload.phase_message, item.phaseMessage || ''),
progress: typeof payload.progress === 'number' ? payload.progress : item.progress,
recordsProcessed: typeof payload.records_processed === 'number' ? payload.records_processed : item.recordsProcessed,
totalRecords: typeof payload.total_records === 'number' ? payload.total_records : item.totalRecords,
error: text(payload.error_message, item.error || ''),
updatedAt: Date.now(),
completedAt: terminal ? Date.now() : item.completedAt,
}
setCollectionQueue(current => patchCollectionTask(current, {
sourceId: text(payload.datasource_id || payload.source_id || payload.id, '') || undefined,
source: text(payload.collector_name || payload.source, '') || undefined,
taskId: payload.task_id as number | string | null | undefined,
taskType: text(payload.task_type, '') || undefined,
status: queueStatusFromTask(payload.status || payload.phase, payload.is_running),
phase: payload.phase == null ? undefined : text(payload.phase, ''),
phaseMessage: payload.phase_message == null ? undefined : text(payload.phase_message, ''),
progress: typeof payload.progress === 'number' ? payload.progress : undefined,
recordsProcessed: typeof payload.records_processed === 'number' ? payload.records_processed : undefined,
totalRecords: typeof payload.total_records === 'number' ? payload.total_records : undefined,
error: payload.error_message == null ? undefined : text(payload.error_message, ''),
}))
}, [])
@@ -3390,14 +3341,14 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
return {
...state,
rows: state.rows.map((row) => {
if (!isSameDatasourceRow(row, sourceId, source)) return row
if (!isSameDatasourceRow(row, sourceId, source) || isStaleTaskUpdate(row.task_id, payload.task_id, activeDatasourceTaskStatus(row), taskStatus)) return row
const merged = applyLiveMetric(row, { ...row, ...rowPatch, id: row.id, source: row.source })
return normalizeDatasourceTableRecord(merged)
}),
}
}))
setSelected((current) => {
if (!current || !isSameDatasourceRow(current, sourceId, source)) return current
if (!current || !isSameDatasourceRow(current, sourceId, source) || isStaleTaskUpdate(current.task_id, payload.task_id, activeDatasourceTaskStatus(current), taskStatus)) return current
const merged = applyLiveMetric(current, { ...current, ...rowPatch, id: current.id, source: current.source })
return normalizeDatasourceTableRecord(merged)
})
@@ -3413,7 +3364,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
completedDatasourceTasksRef.current.add(pendingKey)
const pendingEntry = pendingDatasourceTasksRef.current[pendingKey]
? [pendingKey, pendingDatasourceTasksRef.current[pendingKey]] as const
: Object.entries(pendingDatasourceTasksRef.current).find(([, item]) => isSameDatasourceRow({ id: item.sourceId, source: item.source }, sourceId, source))
: !payload.task_id ? Object.entries(pendingDatasourceTasksRef.current).find(([, item]) => !item.taskId && isSameDatasourceRow({ id: item.sourceId, source: item.source }, sourceId, source)) : undefined
const pending = pendingEntry?.[1]
const lookupId = sourceId || pending?.sourceId || source
if (!lookupId) return
@@ -3486,6 +3437,7 @@ 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 rows = activeState?.rows ?? []
const isDatasourceBuiltinSection = config === configs.datasources && activeSection?.key === 'builtin'
const selectedDatasourceRows = useMemo(
@@ -7142,9 +7094,9 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
className="an-resource-page"
actions={(
<>
<Button size="icon" variant="subtle" onClick={() => void load()} loading={loading} title={localizeAdminText('刷新', locale)} aria-label={localizeAdminText('刷新', locale)}><RefreshCw size={15} /></Button>
{!isComputeConfigSection ? <Button size="icon" variant="subtle" onClick={() => void load()} loading={loading} title={localizeAdminText('刷新', locale)} aria-label={localizeAdminText('刷新', locale)}><RefreshCw size={15} /></Button> : null}
{renderCollectionQueueAction()}
{moduleActions}
{!isComputeConfigSection ? moduleActions : null}
{config.actions.map((action) => (
<Button key={action.label} asChild size="icon" variant="subtle" title={localizeAdminText(action.label, locale)} aria-label={localizeAdminText(action.label, locale)}>
<Link to={action.to}>{action.icon}</Link>
@@ -7154,17 +7106,18 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
)}
>
<div className="an-page-grid">
<SummaryStrip>
{!isComputeConfigSection ? <SummaryStrip>
<StatCell label={localizeAdminText('接口在线', locale)} value={`${summary.online}/${states.length || 1}`} hint={localizeAdminText('已加载分区', locale)} />
<StatCell label={localizeAdminText('记录数', locale)} value={summary.rows} hint={localizeAdminText('已加载分区汇总', locale)} />
<StatCell label={localizeAdminText('异常接口', locale)} value={summary.failing} hint={localizeAdminText('失败时页面仍可操作', locale)} />
</SummaryStrip>
</SummaryStrip> : null}
<SectionTabs sections={config.sections} states={states} activeKey={activeSection?.key || ''} onChange={handleSectionChange} />
{renderDatasourceFilters()}
</div>
{isPlaygroundSection ? (
{config === configs.earthContent ? <ComputeComparisonSettings active={isComputeConfigSection} /> : null}
{isComputeConfigSection ? null : isPlaygroundSection ? (
<PlaygroundLite />
) : isHierarchySection ? (
config === configs.ai ? renderAIHierarchy() : renderConfigHierarchy()
@@ -7501,12 +7454,13 @@ const configs = {
},
earthContent: {
title: '智能星球内容',
description: '管理智能星球品牌、边界、电视内容和内容资产。',
description: '管理智能星球品牌、算力对比、边界、电视内容和内容资产。',
listTitle: '智能星球内容配置',
listDescription: '只展示智能星球品牌、边界构建和电视内容配置。',
listDescription: '选择内容分区,维护展示配置与报告数据。',
viewMode: 'management',
sections: [
{ key: 'brand', label: '品牌标识', url: '/earth/brand', map: (payload) => singleRow(payload, 'brand', { __title: '品牌配置', __module: '品牌' }).map((row) => ({ ...row, __title: '品牌配置', __module: '品牌', __status: '已读取' })) },
{ key: 'compute_comparison', label: '算力对比', map: emptyRows },
{ key: 'about', label: '关于', url: '/earth/about', map: (payload) => singleRow(payload, 'about', { __title: '关于配置', __module: '关于' }).map((row) => ({ ...row, __title: '关于配置', __module: '关于', __status: '已读取' })) },
{
key: 'earth_assets',

View File

@@ -0,0 +1,47 @@
export interface ComputeSource {
id: string
title: string
url: string
publisher: string
report_year: number
published_at: string | null
locator: string
}
export interface ComputeObservation {
year: number
metric: 'global_share' | 'absolute'
source_id: string
values: Record<string, number>
}
export interface InnovationObservation {
year: number
value: number
source_id: string
}
export interface ComputeConfiguration {
reviewed_at: string
sources: ComputeSource[]
observations: ComputeObservation[]
innovation: InnovationObservation[]
}
export interface ComputeConfigurationResponse {
config: ComputeConfiguration
revision: string
is_default: boolean
countries: Array<{ code: string; name: string; name_en: string }>
}
export function reportIsUsed(config: ComputeConfiguration, id: string) {
return [...config.observations, ...config.innovation].some(row => row.source_id === id)
}
export function notifyComputeConfigurationChanged() {
if (typeof BroadcastChannel === 'undefined') return
const channel = new BroadcastChannel('planet-compute-configuration')
channel.postMessage({ type: 'updated' })
channel.close()
}

View File

@@ -0,0 +1,28 @@
.an-compute-settings {
flex: 1;
min-height: 0;
min-width: 0;
overflow: hidden;
}
.an-compute-settings[hidden] { display: none; }
.an-compute-form { display: flex; flex-direction: column; height: 100%; min-height: 0; }
.an-compute-heading { flex-wrap: wrap; gap: 12px; }
.an-compute-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.an-compute-toolbar { display: flex; flex-wrap: wrap; gap: 12px; justify-content: space-between; padding: 12px 16px; }
.an-compute-status, .an-compute-error { padding: 8px 16px; margin: 0; overflow-wrap: anywhere; }
.an-compute-error { color: var(--an-danger, #b42318); max-height: 100px; overflow: auto; }
.an-compute-scroll { flex: 1; min-height: 0; min-width: 0; }
.an-compute-content { min-width: 0; margin: 0; padding: 0 16px 16px; border: 0; }
.an-compute-row { border-bottom: 1px solid var(--an-border); padding: 12px 0; }
.an-compute-row summary { cursor: pointer; padding: 8px 0; overflow-wrap: anywhere; }
.an-compute-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin: 12px 0; }
.an-compute-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; font-size: 13px; }
.an-compute-field .an-input, .an-compute-field .an-select { width: 100%; min-width: 0; }
.an-compute-values { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }
.an-compute-value { display: flex; align-items: end; gap: 4px; min-width: 0; }
.an-compute-value .an-compute-field { flex: 1; }
.an-compute-row-actions { display: flex; align-items: center; gap: 12px; margin: 12px 0; }
.an-compute-row-actions .an-select { flex: 1; min-width: 0; }
@media (max-width: 680px) {
.an-compute-fields, .an-compute-values { grid-template-columns: minmax(0, 1fr); }
}

View File

@@ -0,0 +1,69 @@
export type CollectionQueueStatus = 'queued' | 'running' | 'cancelling' | 'success' | 'failed' | 'skipped' | 'cancelled'
export type CollectionQueueItem = {
key: string
sourceId: string
source?: string
name: string
taskId?: number | string | null
taskType?: string
status: CollectionQueueStatus
phase?: string
phaseMessage?: string
progress?: number | null
recordsProcessed?: number | null
totalRecords?: number | null
reason?: string
error?: string
createdAt: number
updatedAt: number
completedAt?: number
}
type QueueUpdate = Partial<CollectionQueueItem> & Pick<CollectionQueueItem, 'status'>
export const COLLECTION_QUEUE_ACTIVE_STATUSES = new Set<CollectionQueueStatus>(['queued', 'running', 'cancelling'])
const taskId = (value: unknown) => value == null ? '' : String(value)
function sameAttempt(existing: CollectionQueueItem, update: Partial<CollectionQueueItem>) {
const existingId = taskId(existing.taskId)
const incomingId = taskId(update.taskId)
if (existing.taskType && update.taskType && existing.taskType !== update.taskType) return false
if (existingId) return Boolean(incomingId) && existingId === incomingId
// Only an active, ID-less placeholder may bind to its server task.
if (!COLLECTION_QUEUE_ACTIVE_STATUSES.has(existing.status)) return false
if (existing.sourceId && update.sourceId) return existing.sourceId === update.sourceId
return Boolean(existing.source && update.source && existing.source === update.source)
}
function mergeAttempt(existing: CollectionQueueItem, update: QueueUpdate, now: number): CollectionQueueItem {
// Delayed polling/WS events cannot resurrect or reclassify a finished attempt.
if (!COLLECTION_QUEUE_ACTIVE_STATUSES.has(existing.status) && update.status !== existing.status) return existing
const merged = { ...existing }
for (const [key, value] of Object.entries(update)) {
if (value !== undefined && key !== 'createdAt' && key !== 'key') Object.assign(merged, { [key]: value })
}
merged.key = taskId(merged.taskId) ? `task:${merged.taskType || 'collect'}:${taskId(merged.taskId)}` : existing.key
merged.updatedAt = now
merged.completedAt = COLLECTION_QUEUE_ACTIVE_STATUSES.has(merged.status) ? undefined : existing.completedAt ?? now
return merged
}
export function upsertCollectionTask(current: CollectionQueueItem[], item: CollectionQueueItem) {
const index = current.findIndex(existing => sameAttempt(existing, item))
if (index < 0) return [item, ...current]
return current.map((existing, i) => i === index ? mergeAttempt(existing, item, item.updatedAt) : existing)
}
export function patchCollectionTask(current: CollectionQueueItem[], update: QueueUpdate, now = Date.now()) {
return current.map(existing => sameAttempt(existing, update) ? mergeAttempt(existing, update, now) : existing)
}
// The datasource row is the latest attempt, while the queue holds all attempts.
export function isStaleTaskUpdate(currentId: unknown, incomingId: unknown, currentStatus?: string, incomingStatus?: string) {
const current = taskId(currentId), incoming = taskId(incomingId)
if (!current) return false
if (!incoming) return true
const terminal = ['success', 'completed', 'failed', 'error', 'cancelled', 'canceled', 'skipped', 'stopped']
if (current === incoming && currentStatus && incomingStatus && terminal.includes(currentStatus) && !terminal.includes(incomingStatus)) return true
return /^\d+$/.test(current) && /^\d+$/.test(incoming) && Number(incoming) < Number(current)
}

View File

@@ -8,6 +8,7 @@ import {
EyeOff,
FileText,
ImageUp,
ListChecks,
Pause,
Pickaxe,
Play,
@@ -56,7 +57,7 @@ export const tactileIconPresets = {
send: Send,
settings: SlidersHorizontal,
start: Play,
status: RefreshCw,
status: ListChecks,
stop: Square,
test: Unplug,
plug: Plug,

View File

@@ -1,4 +1,7 @@
export const legacyUiTextEnUS: Record<string, string> = {
'算力对比': 'Compute comparison',
'管理智能星球品牌、算力对比、边界、电视内容和内容资产。': 'Manage Intelligent Planet branding, compute comparison, boundaries, TV and content assets.',
'选择内容分区,维护展示配置与报告数据。': 'Choose a section to maintain display configuration and report data.',
'OpenAI Chat Completions': 'OpenAI Chat Completions',
'OpenAI Responses': 'OpenAI Responses',
'AI Provider连通性正常': 'AI Provider connectivity OK',

View File

@@ -0,0 +1,60 @@
import { expect, test } from 'bun:test'
import { patchCollectionTask, upsertCollectionTask, isStaleTaskUpdate, type CollectionQueueItem } from '../src/admin/pages/datasource-task-queue'
const item = (id: number | string | null, status: CollectionQueueItem['status'] = 'failed', type = 'collect'): CollectionQueueItem => ({
key: id == null ? `source:${type}:20` : `task:${type}:${id}`, taskId: id, sourceId: '20', source: 'celestrak_tle', name: 'CelesTrak', taskType: type,
status, error: status === 'failed' ? `failure-${id}` : undefined, createdAt: 10, updatedAt: 20, completedAt: status === 'failed' ? 20 : undefined,
})
test('a retry creates a new queue attempt and leaves every failed attempt untouched', () => {
const history = [item(97), item(96), item(95)]
let queue = upsertCollectionTask(history, item(98, 'queued'))
queue = patchCollectionTask(queue, { taskId: '98', sourceId: '20', source: 'celestrak_tle', status: 'running', progress: 40 }, 100)
expect(queue).toHaveLength(4)
expect(queue[0].taskId).toBe('98')
expect(queue[0].status).toBe('running')
expect(queue.slice(1)).toEqual(history)
queue = patchCollectionTask(queue, { taskId: 98, sourceId: '20', status: 'failed', error: 'new failure' }, 120)
expect(queue.slice(1)).toEqual(history)
expect(queue[0].completedAt).toBe(120)
})
test('late websocket and upsert events cannot resurrect or reclassify a completed attempt', () => {
const failed = item(97)
expect(patchCollectionTask([failed], { taskId: 97, sourceId: '20', status: 'running' }, 200)).toEqual([failed])
expect(upsertCollectionTask([failed], item('97', 'queued'))).toEqual([failed])
expect(patchCollectionTask([failed], { taskId: 97, status: 'success' }, 200)).toEqual([failed])
expect(patchCollectionTask([failed], { taskId: 97, status: 'failed', error: 'more detail' }, 200)[0].completedAt).toBe(20)
})
test('same-source concurrent attempts and different task types are independent', () => {
const queue = upsertCollectionTask([item(98, 'running')], item(99, 'queued'))
expect(queue).toHaveLength(2)
expect(patchCollectionTask(queue, { taskId: 98, sourceId: '20', status: 'failed' })[0].status).toBe('queued')
expect(patchCollectionTask([item(98, 'running')], { taskId: 98, taskType: 'clear_data', status: 'success' })[0].status).toBe('running')
})
test('only an active ID-less placeholder binds by source; ID-less updates cannot touch real tasks', () => {
const placeholder = item(null, 'queued')
const bound = patchCollectionTask([placeholder, item(97)], { taskId: 98, sourceId: '20', status: 'running' }, 50)
expect(bound[0].key).toBe('task:collect:98')
expect(bound[0].createdAt).toBe(10)
expect(bound[1]).toEqual(item(97))
expect(patchCollectionTask(bound, { sourceId: '20', status: 'failed' }, 60)).toEqual(bound)
const differentSource = { ...placeholder, sourceId: '21' }
expect(patchCollectionTask([differentSource], { taskId: 99, sourceId: '20', source: 'celestrak_tle', status: 'running' })).toEqual([differentSource])
})
test('old poll responses cannot replace the datasource row for a newer task', () => {
expect(isStaleTaskUpdate(98, '97')).toBe(true)
expect(isStaleTaskUpdate(98, null)).toBe(true)
expect(isStaleTaskUpdate(98, '98')).toBe(false)
expect(isStaleTaskUpdate(98, 99)).toBe(false)
expect(isStaleTaskUpdate(null, 99)).toBe(false)
})
test('late running updates for the same completed task do not reactivate the datasource row', () => {
expect(isStaleTaskUpdate(98, '98', 'failed', 'running')).toBe(true)
expect(isStaleTaskUpdate(98, '98', 'success', 'queued')).toBe(true)
expect(isStaleTaskUpdate(98, '99', 'failed', 'queued')).toBe(false)
})

View File

@@ -1,18 +1,12 @@
@echo off
setlocal EnableExtensions
net session >nul 2>&1
if not "%errorlevel%"=="0" (
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "$script = '%~f0'; $arg = '-NoExit -NoProfile -ExecutionPolicy Bypass -Command ""& { & ''' + $script + ''' --elevated }""'; if (Get-Command wt.exe -ErrorAction SilentlyContinue) { Start-Process wt.exe -Verb RunAs -ArgumentList @('powershell.exe', $arg) } else { Start-Process powershell.exe -Verb RunAs -ArgumentList $arg }"
exit /b
)
if /i "%~1"=="--elevated" shift
echo Starting Planet in WSL as Administrator...
echo This window will stay inside WSL after startup. Close it manually when you are done.
echo.
wsl.exe -d Ubuntu --cd /home/linkong/planet -- zsh -lic "./planet.sh restart --allow-lan; planet_exit=\$?; echo; if [ \$planet_exit -eq 0 ]; then echo 'Planet restart finished successfully.'; powershell.exe -NoProfile -Command 'Start-Process "http://localhost:3000/earth"'; else echo \"Planet restart failed with exit code \$planet_exit.\"; fi; echo; echo 'Staying in WSL. Close this terminal manually when you are done.'; exec zsh -l"
exit /b %errorlevel%
setlocal EnableExtensions DisableDelayedExpansion
set "PLANET_LAUNCHER_SOURCE=%~f0"
set "PLANET_LAUNCHER_INSTALL_ONLY="
if /i "%~1"=="--install-only" set "PLANET_LAUNCHER_INSTALL_ONLY=1"
set "PLANET_POWERSHELL=powershell.exe"
where.exe pwsh.exe >nul 2>&1
if not errorlevel 1 set "PLANET_POWERSHELL=pwsh.exe"
%PLANET_POWERSHELL% -NoLogo -NoProfile -ExecutionPolicy Bypass -Command "& (Join-Path (Split-Path -LiteralPath $env:PLANET_LAUNCHER_SOURCE) 'scripts\windows\planet-launcher.ps1') -InstallOnly:($env:PLANET_LAUNCHER_INSTALL_ONLY -eq '1')"
set "planet_launcher_exit=%errorlevel%"
if not "%planet_launcher_exit%"=="0" pause
exit /b %planet_launcher_exit%

View File

@@ -1,6 +1,6 @@
[project]
name = "planet"
version = "0.75.0"
version = "0.75.3"
description = "智能星球计划 - 态势感知系统"
requires-python = ">=3.14"
dependencies = [

View File

@@ -169,6 +169,41 @@ Always.
- Keep confirmed operational failure causes in the error catalog in `docs/technical/{zh,en}/ops-runbook.md`. `planet.sh` diagnostics must read causes and remedies from this catalog. Add a stable error code, matching evidence, and a regression case when fixing a previously unclassified cause; unknown failures must remain explicitly unclassified until verified.
- If a harness rule is no longer true for the current toolchain, update or delete it in the same cleanup pass.
### Coding Agent Model Strategy
This policy applies to repository development agents, not the product's
`aiprovider` model settings. Preserve the user's selected main-agent model;
these preferences do not switch a running task or change global Codex settings.
When delegation is explicitly authorized by the user or an applicable skill,
select workers by task scope and verification difficulty:
| Work | Preferred model | Initial reasoning effort |
| --- | --- | --- |
| Bounded implementation, ordinary bug fixes, focused tests, code review | `gpt-6-sol` | `medium`; `high` for interacting modules |
| Narrow file discovery, evidence extraction, mechanical docs updates, small deterministic edits | `gpt-6-luna` | `low` or `medium` |
| Architecture, ambiguous requirements, difficult rendering/performance bugs, security-sensitive reasoning, repeated failed fixes | `gpt-6-astra` | `high`; increase only when evidence justifies it |
- These are project routing preferences, not measured Planet benchmarks.
Model roles follow [OpenAI model guidance](https://developers.openai.com/api/docs/models),
checked on 2026-09-23. Use the actual host/tool model and effort catalog;
API-supported settings do not automatically imply Codex tool support.
- Keep small or tightly coupled tasks with the main agent. Delegate only bounded,
independent work that can progress alongside useful main-agent work; avoid
parallel edits to the same files and do not create agents merely to fill slots.
- Give each worker its objective, owned paths, constraints, relevant evidence,
and acceptance checks. Prefer a concise handoff over copying the entire history.
- Start directly with the model appropriate to the risk. Escalate Luna to Sol,
or Sol to Astra, when scope exceeds the assigned task or a failed verification
remains unresolved after one focused correction. Pass the reproduction,
attempted fixes, and remaining uncertainty; do not repeat blind retries.
- The main agent owns integration and final verification. Luna findings are
evidence inputs, not sole sign-off for security, migrations, releases, or
complex Earth rendering. All tiers retain the same test and visual gates.
- If the preferred model is unavailable, use the current capable model and
disclose the fallback. Do not silently downgrade or assume older model names
are aliases. Record actual validation outcomes rather than promising savings.
### Git
- Do not revert user changes unless explicitly requested.
@@ -505,7 +540,7 @@ Current icons:
| File | Used in | Description |
|------|---------|-------------|
| `marker-landing-point.svg` | `cables.js` | Cable landing point pin |
| `marker-landing-point.svg` | `cables.js` | Flat landing-point micro-core |
| `bgp-collector.svg` | `bgp.js` | BGP collector marker |
| `bgp-glow-dot.svg` | `bgp.js` | Base radial glow dot |
| `bgp-event-ring.svg` | `bgp.js` | Event ring overlay |

View File

@@ -913,6 +913,16 @@ function apiPayloadFor(requestUrl, method) {
if (path === '/ai/playground/thread') return jsonResponse({ messages: [], session: { state: {} } })
if (path === '/earth/brand') return jsonResponse({ brand: { title: '智能星球', subtitle: 'Smoke', logo_alt: 'Planet' } })
if (path === '/data-products/compute/configuration') return jsonResponse({
config: JSON.parse(readRepoText('backend/app/services/compute_history_defaults.json')),
revision: 'compute-configuration-smoke',
is_default: true,
countries: [
{ code: 'CN', name: '中国', name_en: 'China' },
{ code: 'US', name: '美国', name_en: 'United States' },
{ code: 'JP', name: '日本', name_en: 'Japan' },
],
})
if (path === '/earth/about') return jsonResponse({ about: { title: '智能星球', version: 'smoke', description: 'Harness smoke.' } })
if (path === '/earth/boundaries/status') return jsonResponse({ status: 'ready', provider: 'low', updated_at: now })
if (path === '/earth/boundaries/build/status') return jsonResponse({ status: 'idle', progress: 0 })

View File

@@ -17,11 +17,13 @@ main() {
harness_run zsh -n scripts/lib/docker-proxy.zsh
harness_run zsh -n scripts/lib/docker-mirror.zsh
harness_run zsh -n scripts/lib/error-diagnostics.zsh
harness_run zsh -n scripts/windows/restart.zsh
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_bootstrap.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_command.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_proxy.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_docker_mirror.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_database_startup.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_windows_restart.py
harness_run "$uv_bin" run --frozen --project "$ROOT_DIR" python scripts/harness/test_error_diagnostics.py
harness_run bash -n scripts/bootstrap-dev.sh
harness_run bash -n scripts/harness/lib.sh

View File

@@ -0,0 +1,127 @@
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot '..\windows\planet-launcher.ps1')
function Assert-Equal($Expected, $Actual, $Label) {
if ($Expected -cne $Actual) { throw "$Label expected [$Expected], got [$Actual]" }
}
foreach ($prefix in @('\\wsl$\', '\\wsl.localhost\')) {
$target = Get-PlanetTarget ($prefix + 'Ubuntu-24.04\home\alice\planet app')
Assert-Equal 'Ubuntu-24.04' $target.Distro 'UNC distribution'
Assert-Equal '/home/alice/planet app' $target.LinuxProjectRoot 'UNC Linux path'
}
$specialRoot = '/home/alice/planet ' + [char]0x5730 + [char]0x7403 + " ' & % ! `$ (demo)"
$target = Get-PlanetTarget ('\\wsl$\Debian' + $specialRoot.Replace('/', '\'))
Assert-Equal $specialRoot $target.LinuxProjectRoot 'Special characters'
function Invoke-WslText {
param([string[]]$Arguments)
if ($Arguments[1] -eq 'printenv') { return 'Ubuntu' }
Assert-Equal 'C:\Projects\Planet Space' $Arguments[-1] 'Windows path remains one argument'
return '/mnt/c/Projects/Planet Space'
}
$driveTarget = Get-PlanetTarget 'C:\Projects\Planet Space'
Assert-Equal 'Ubuntu' $driveTarget.Distro 'Default distribution'
Assert-Equal '/mnt/c/Projects/Planet Space' $driveTarget.LinuxProjectRoot 'Mounted drive'
foreach ($elevated in @($false, $true)) {
$bootstrap = Get-PlanetBootstrap $target -RunElevated:$elevated
$tokens = $null; $errors = $null
[void][Management.Automation.Language.Parser]::ParseInput($bootstrap, [ref]$tokens, [ref]$errors)
if ($errors.Count) { throw ($errors | Out-String) }
$encoded = ConvertTo-PlanetEncodedCommand $bootstrap
Assert-Equal $bootstrap ([Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($encoded))) 'Encoded command roundtrip'
if ($bootstrap.Contains($specialRoot)) { throw 'Project path must remain encoded data' }
$match = [regex]::Match($bootstrap, "FromBase64String\('([A-Za-z0-9+/=]+)'\)")
$decoded = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($match.Groups[1].Value)) | ConvertFrom-Json
Assert-Equal $specialRoot $decoded.LinuxProjectRoot 'Bound target roundtrip'
}
function Test-PlanetAdministrator { return $true }
function wsl.exe {
$script:CapturedWslArguments = $args
$global:LASTEXITCODE = 17
Write-Output 'live-wsl-output'
}
$liveOutput = Start-PlanetRestart $target -AlreadyElevated
Assert-Equal 'live-wsl-output' $liveOutput 'WSL output is streamed, not returned as an exit-code array'
Assert-Equal 17 $script:PlanetLauncherExitCode 'WSL exit status preserved'
Assert-Equal $specialRoot $script:CapturedWslArguments[3] 'Working directory is one native argument'
Assert-Equal ($specialRoot + '/scripts/windows/restart.zsh') $script:CapturedWslArguments[8] 'Bridge path is one native argument'
$testDirectory = Join-Path ([IO.Path]::GetTempPath()) ('planet-launcher-tests-' + [guid]::NewGuid().ToString('N'))
[void][IO.Directory]::CreateDirectory($testDirectory)
try {
$launcher = Install-PlanetDesktopLauncher $target -Desktop $testDirectory
Assert-Equal 'Planet.cmd' ([IO.Path]::GetFileName($launcher)) 'First install'
$content = [IO.File]::ReadAllText($launcher)
if ($content -notmatch 'DisableDelayedExpansion' -or $content -notmatch '--install-only') {
throw 'Generated launcher lacks safe CMD mode or install-only option'
}
Assert-Equal $launcher (Install-PlanetDesktopLauncher $target -Desktop $testDirectory) 'Repeat install'
$other = Install-PlanetDesktopLauncher $driveTarget -Desktop $testDirectory
if ($other -eq $launcher) { throw 'Different projects must not overwrite each other' }
Assert-Equal $content ([IO.File]::ReadAllText($launcher)) 'Original target preserved'
[IO.File]::WriteAllText($launcher, 'unrelated user file')
$alternate = Install-PlanetDesktopLauncher $target -Desktop $testDirectory
if ($alternate -eq $launcher) { throw 'Unrelated file overwritten' }
Assert-Equal 'unrelated user file' ([IO.File]::ReadAllText($launcher)) 'User file preserved'
$missing = @{ Distro = 'Ubuntu'; LinuxProjectRoot = '/missing/planet-launcher-test-' + [guid]::NewGuid() }
try { Assert-PlanetTarget $missing; throw 'Missing project accepted' }
catch { if ($_.Exception.Message -notmatch 'P_WINDOWS_LAUNCHER_TARGET_MISSING') { throw } }
Write-Host 'PASS: UNC aliases, drive mapping, special paths, encoding, repeat installation, collisions, missing project'
} finally {
$resolved = [IO.Path]::GetFullPath($testDirectory)
$tempRoot = [IO.Path]::GetFullPath([IO.Path]::GetTempPath())
if (-not $resolved.StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase) -or
[IO.Path]::GetFileName($resolved) -notlike 'planet-launcher-tests-*') { throw 'Unsafe cleanup path' }
Remove-Item -LiteralPath $resolved -Recurse -Force
}
function Get-Command {
param([string]$Name, [string]$CommandType, [string]$ErrorAction)
if ($script:AvailableLaunchCommands.ContainsKey($Name)) {
return [pscustomobject]@{ Source = $script:AvailableLaunchCommands[$Name] }
}
}
$pwshPath = 'C:\Program Files\PowerShell\7\pwsh.exe'
$terminalPath = 'C:\Users\Test\AppData\Local\Microsoft\WindowsApps\wt.exe'
$legacyPath = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
foreach ($hasTerminal in @($true, $false)) {
foreach ($hasPwsh in @($true, $false)) {
$script:AvailableLaunchCommands = @{ 'powershell.exe' = $legacyPath }
if ($hasTerminal) { $script:AvailableLaunchCommands['wt.exe'] = $terminalPath }
if ($hasPwsh) { $script:AvailableLaunchCommands['pwsh.exe'] = $pwshPath }
$launch = Get-PlanetTerminalLaunch 'TESTPAYLOAD'
$expectedShell = if ($hasPwsh) { $pwshPath } else { $legacyPath }
$expectedExecutable = if ($hasTerminal) { $terminalPath } else { $expectedShell }
Assert-Equal $expectedExecutable $launch.FilePath 'Terminal/shell priority'
if ($hasTerminal -and -not $launch.ArgumentList.Contains('"' + $expectedShell + '"')) {
throw 'Terminal shell path must be quoted, including Program Files paths'
}
if ($launch.ArgumentList -notmatch '-EncodedCommand TESTPAYLOAD$') {
throw 'Encoded bootstrap was not preserved'
}
}
}
function Test-PlanetAdministrator { return $script:IsTestAdministrator }
function Start-Process {
param($FilePath, $ArgumentList, $WindowStyle, $Verb)
$script:CapturedLaunch = @{ FilePath = $FilePath; ArgumentList = $ArgumentList; Verb = $Verb }
$script:LaunchCount++
}
$script:AvailableLaunchCommands = @{ 'pwsh.exe' = $pwshPath; 'wt.exe' = $terminalPath }
$script:LaunchCount = 0
foreach ($isAdmin in @($false, $true)) {
$script:IsTestAdministrator = $isAdmin
Start-PlanetRestart $target
Assert-Equal $terminalPath $script:CapturedLaunch.FilePath 'Admin and ordinary entry both use Terminal'
if ($isAdmin -and $script:CapturedLaunch.Verb) { throw 'Already elevated entry must not request UAC again' }
if (-not $isAdmin) { Assert-Equal 'RunAs' $script:CapturedLaunch.Verb 'Ordinary entry requires elevation' }
}
$script:IsTestAdministrator = $false
try { Start-PlanetRestart $target -AlreadyElevated; throw 'Unelevated child accepted' }
catch { if ($_.Exception.Message -ne 'Administrator elevation was not granted.') { throw } }
Assert-Equal 2 $script:LaunchCount 'Child must not recursively launch more windows'
Write-Host 'PASS: Terminal/PowerShell priority, quoted paths, elevation and no recursive dispatch'

View File

@@ -0,0 +1,72 @@
"""Exercise the WSL bridge using disposable commands, never real services."""
import os
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
class WindowsRestartTests(unittest.TestCase):
def run_bridge(self, exit_code, port_state):
with tempfile.TemporaryDirectory(prefix="planet-windows-restart-") as temporary:
root = Path(temporary) / "project space ' 地球"
bridge = root / "scripts/windows/restart.zsh"
bridge.parent.mkdir(parents=True)
shutil.copyfile(ROOT / "scripts/windows/restart.zsh", bridge)
commands = root / "bin"
commands.mkdir()
log = root / "calls.log"
state = root / "state"
state.mkdir()
(state / "ports.env").write_text(port_state)
scripts = {
root
/ "planet.sh": '#!/bin/sh\nprintf "restart:%s:%s\\n" "$PWD" "$*" >> "$TEST_LOG"\nexit '
+ str(exit_code),
commands
/ "powershell.exe": '#!/bin/sh\nprintf "browser:%s\\n" "$PLANET_LAUNCH_URL" >> "$TEST_LOG"',
commands / "zsh": '#!/bin/sh\nprintf "shell:%s\\n" "$*" >> "$TEST_LOG"',
}
for path, body in scripts.items():
path.write_text(body + "\n")
path.chmod(0o755)
result = subprocess.run(
["/usr/bin/zsh", str(bridge)],
cwd="/tmp",
capture_output=True,
text=True,
env={
**os.environ,
"PATH": str(commands) + ":/usr/bin:/bin",
"TEST_LOG": str(log),
"PLANET_STATE_DIR": str(state),
},
timeout=15,
)
self.assertEqual(result.returncode, 0, result.stderr)
calls = log.read_text()
self.assertIn(f"restart:{root}:restart --allow-lan", calls)
self.assertIn("shell:-l", calls)
return calls, result.stdout
def test_success_uses_actual_frontend_port_and_scheme(self):
calls, output = self.run_bridge(0, "FRONTEND_PORT=4177\nFRONTEND_SCHEME=https\n")
self.assertIn("browser:https://localhost:4177/earth", calls)
self.assertIn("successfully", output)
def test_failure_keeps_shell_without_opening_browser(self):
calls, output = self.run_bridge(7, "FRONTEND_PORT=4177\n")
self.assertNotIn("browser:", calls)
self.assertIn("failed with exit code 7", output)
def test_port_state_is_not_executed_as_shell_code(self):
calls, _ = self.run_bridge(0, "FRONTEND_PORT=$(exit 91)\nFRONTEND_SCHEME=javascript\n")
self.assertIn("browser:http://localhost:3000/earth", calls)
if __name__ == "__main__":
unittest.main()

View File

@@ -0,0 +1,196 @@
param(
[string]$Distro,
[string]$LinuxProjectRoot,
[switch]$FromDesktop,
[switch]$InstallOnly,
[switch]$Elevated
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
$script:PlanetTargetFingerprintLength = 12
function Invoke-WslText {
param([string[]]$Arguments)
$output = & wsl.exe @Arguments
if ($LASTEXITCODE -ne 0) {
throw "WSL command failed (exit $LASTEXITCODE). Check the distribution and project directory."
}
return ($output -join "`n").Trim()
}
function Get-PlanetTarget {
param([string]$WindowsRoot)
if ($WindowsRoot -match '^\\\\(?:wsl\$|wsl\.localhost)\\([^\\]+)(\\.*)?$') {
$root = if ($Matches[2]) { $Matches[2].Replace('\', '/') } else { '/' }
return @{ Distro = $Matches[1]; LinuxProjectRoot = $root.TrimEnd('/') }
}
if ($WindowsRoot -notmatch '^[a-zA-Z]:\\') {
throw 'Run planet.cmd from a WSL project folder or a local Windows drive.'
}
$distribution = Invoke-WslText -Arguments @('--exec', 'printenv', 'WSL_DISTRO_NAME')
$root = Invoke-WslText -Arguments @('-d', $distribution, '--exec', 'wslpath', '-a', '-u', $WindowsRoot)
return @{ Distro = $distribution; LinuxProjectRoot = $root.TrimEnd('/') }
}
function Get-PlanetWindowsRoot {
param([hashtable]$Target)
if ([string]::IsNullOrWhiteSpace($Target.Distro) -or
$Target.Distro -match '[\\/\r\n]' -or
$Target.LinuxProjectRoot -notmatch '^/' -or
$Target.LinuxProjectRoot -match '[\r\n]') {
throw 'Invalid WSL distribution or absolute project path.'
}
return '\\wsl$\' + $Target.Distro + $Target.LinuxProjectRoot.Replace('/', '\')
}
function Assert-PlanetTarget {
param([hashtable]$Target)
$windowsRoot = Get-PlanetWindowsRoot $Target
foreach ($relative in @('planet.sh', 'scripts\windows\planet-launcher.ps1', 'scripts\windows\restart.zsh')) {
if (-not (Test-Path -LiteralPath (Join-Path $windowsRoot $relative) -PathType Leaf)) {
throw "P_WINDOWS_LAUNCHER_TARGET_MISSING: $windowsRoot\$relative. Run planet.cmd from the current project folder to regenerate the desktop launcher."
}
}
}
function Get-PlanetBootstrap {
param([hashtable]$Target, [switch]$RunElevated)
# Only base64 crosses CMD/PowerShell command-line parsing; paths are data.
$json = $Target | ConvertTo-Json -Compress
$payload = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($json))
$elevatedFlag = if ($RunElevated) { '$true' } else { '$false' }
return @"
`$ErrorActionPreference = 'Stop'
`$ProgressPreference = 'SilentlyContinue'
try {
`$target = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('$payload')) | ConvertFrom-Json
`$root = '\\wsl$\' + `$target.Distro + `$target.LinuxProjectRoot.Replace('/', '\')
`$helper = Join-Path `$root 'scripts\windows\planet-launcher.ps1'
if (-not (Test-Path -LiteralPath `$helper -PathType Leaf)) {
throw 'P_WINDOWS_LAUNCHER_TARGET_MISSING: Project moved or unavailable. Run planet.cmd from the current project folder again.'
}
& `$helper -Distro `$target.Distro -LinuxProjectRoot `$target.LinuxProjectRoot -FromDesktop -Elevated:$elevatedFlag -InstallOnly:(`$env:PLANET_LAUNCHER_INSTALL_ONLY -eq '1')
exit `$LASTEXITCODE
} catch {
Write-Host `$_.Exception.Message -ForegroundColor Red
exit 1
}
"@
}
function ConvertTo-PlanetEncodedCommand {
param([string]$Command)
return [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($Command))
}
function Install-PlanetDesktopLauncher {
param([hashtable]$Target, [string]$Desktop = [Environment]::GetFolderPath('DesktopDirectory'))
if (-not $Desktop -or -not (Test-Path -LiteralPath $Desktop -PathType Container)) {
throw 'Windows Desktop folder is unavailable.'
}
$identity = $Target.Distro + "`n" + $Target.LinuxProjectRoot
$sha256 = [Security.Cryptography.SHA256]::Create()
try {
$identityBytes = [Text.Encoding]::UTF8.GetBytes($identity)
$fingerprint = [BitConverter]::ToString($sha256.ComputeHash($identityBytes)).Replace('-', '')
$hash = $fingerprint.Substring(0, $script:PlanetTargetFingerprintLength)
} finally {
$sha256.Dispose()
}
$marker = "rem Planet managed launcher v1 target=$hash"
$destination = Join-Path $Desktop 'Planet.cmd'
if ((Test-Path -LiteralPath $destination) -and
-not ([IO.File]::ReadAllText($destination).Contains($marker))) {
$destination = Join-Path $Desktop "Planet-$hash.cmd"
}
if ((Test-Path -LiteralPath $destination) -and
-not ([IO.File]::ReadAllText($destination).Contains($marker))) {
throw "Refusing to overwrite an unrelated file: $destination"
}
$encoded = ConvertTo-PlanetEncodedCommand (Get-PlanetBootstrap $Target)
$lines = @(
'@echo off', 'setlocal EnableExtensions DisableDelayedExpansion', $marker,
'set "PLANET_LAUNCHER_INSTALL_ONLY="',
'if /i "%~1"=="--install-only" set "PLANET_LAUNCHER_INSTALL_ONLY=1"',
'set "PLANET_POWERSHELL=powershell.exe"',
'where.exe pwsh.exe >nul 2>&1',
'if not errorlevel 1 set "PLANET_POWERSHELL=pwsh.exe"',
"%PLANET_POWERSHELL% -NoLogo -NoProfile -ExecutionPolicy Bypass -EncodedCommand $encoded",
'set "planet_launcher_exit=%errorlevel%"',
'if not "%planet_launcher_exit%"=="0" pause',
'exit /b %planet_launcher_exit%'
)
[IO.File]::WriteAllText($destination, ($lines -join "`r`n") + "`r`n", [Text.Encoding]::ASCII)
return $destination
}
function Test-PlanetAdministrator {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Get-PlanetTerminalLaunch {
param([string]$EncodedCommand)
$shell = Get-Command pwsh.exe -CommandType Application -ErrorAction SilentlyContinue |
Select-Object -First 1
if (-not $shell) {
$shell = Get-Command powershell.exe -CommandType Application -ErrorAction Stop |
Select-Object -First 1
}
$shellArguments = "-NoLogo -NoProfile -NoExit -ExecutionPolicy Bypass -EncodedCommand $EncodedCommand"
$launch = @{ FilePath = $shell.Source; ArgumentList = $shellArguments; WindowStyle = 'Normal' }
$terminal = Get-Command wt.exe -CommandType Application -ErrorAction SilentlyContinue |
Select-Object -First 1
if ($terminal) {
$launch.FilePath = $terminal.Source
# Start-Process joins arguments: quote the executable path explicitly.
$launch.ArgumentList = '-w new new-tab --title Planet "' + $shell.Source + '" ' + $shellArguments
}
return $launch
}
function Start-PlanetRestart {
param([hashtable]$Target, [switch]$AlreadyElevated)
$script:PlanetLauncherExitCode = 0
$isAdministrator = Test-PlanetAdministrator
if (-not $AlreadyElevated) {
$encoded = ConvertTo-PlanetEncodedCommand (Get-PlanetBootstrap $Target -RunElevated)
$launch = Get-PlanetTerminalLaunch $encoded
if (-not $isAdministrator) { $launch.Verb = 'RunAs' }
# An interactive terminal is intentional: startup logs and the WSL shell stay visible.
Start-Process @launch | Out-Null
return
}
if (-not $isAdministrator) { throw 'Administrator elevation was not granted.' }
Write-Host "Restarting Planet in $($Target.Distro):$($Target.LinuxProjectRoot)"
& wsl.exe -d $Target.Distro --cd $Target.LinuxProjectRoot --exec zsh -l -i ($Target.LinuxProjectRoot + '/scripts/windows/restart.zsh')
$script:PlanetLauncherExitCode = $LASTEXITCODE
}
if ($MyInvocation.InvocationName -ne '.') {
try {
[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)
$OutputEncoding = [Console]::OutputEncoding
if ($FromDesktop) {
$target = @{ Distro = $Distro; LinuxProjectRoot = $LinuxProjectRoot }
} else {
$root = (Get-Item -LiteralPath (Join-Path $PSScriptRoot '..\..')).FullName
$target = Get-PlanetTarget $root
}
Assert-PlanetTarget $target
if (-not $FromDesktop) {
$desktopLauncher = Install-PlanetDesktopLauncher $target
Write-Host "Desktop launcher ready: $desktopLauncher"
}
if ($InstallOnly) { exit 0 }
# Do not capture the WSL output: the interactive terminal must stream live.
Start-PlanetRestart $target -AlreadyElevated:$Elevated
exit $script:PlanetLauncherExitCode
} catch {
Write-Host $_.Exception.Message -ForegroundColor Red
exit 1
}
}

View File

@@ -0,0 +1,30 @@
#!/usr/bin/env zsh
# Locate the repository from this file, independent of Windows/WSL working directories.
project_root="${0:A:h:h:h}"
cd -- "$project_root" || exit 1
./planet.sh restart --allow-lan
planet_exit=$?
print
if (( planet_exit == 0 )); then
print 'Planet restart finished successfully.'
frontend_port=3000
frontend_scheme=http
port_state="${PLANET_STATE_DIR:-${XDG_STATE_HOME:-$HOME/.local/state}/planet}/ports.env"
if [[ -f "$port_state" ]]; then
while IFS='=' read -r key value; do
case "$key" in
FRONTEND_PORT) [[ "$value" == <1-65535> ]] && frontend_port="$value" ;;
FRONTEND_SCHEME) [[ "$value" == http || "$value" == https ]] && frontend_scheme="$value" ;;
esac
done < "$port_state"
fi
WSLENV="${WSLENV:+$WSLENV:}PLANET_LAUNCH_URL" \
PLANET_LAUNCH_URL="${frontend_scheme}://localhost:${frontend_port}/earth" \
powershell.exe -NoProfile -Command 'Start-Process $env:PLANET_LAUNCH_URL'
else
print "Planet restart failed with exit code $planet_exit."
fi
print
print 'Staying in WSL. Close this terminal manually when you are done.'
exec zsh -l

2
uv.lock generated
View File

@@ -757,7 +757,7 @@ wheels = [
[[package]]
name = "planet"
version = "0.75.0"
version = "0.75.3"
source = { virtual = "." }
dependencies = [
{ name = "aiofiles" },