mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 23:50:08 +00:00
feat(atlas): a WebGL globe engine
One shader morphs an orthographic globe into a flat map as the zoom grows. Country and region meshes are built in a worker from the TopoJSON, picked on the GPU and coloured from a status texture; borders, coasts and flight arcs are instanced screen-space lines. Regions are fetched ahead of the zoom and kept to a bounded set; labels avoid each other. Includes the day and night line, the moon in its phase and the badge medals.
This commit is contained in:
@@ -0,0 +1,118 @@
|
||||
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
|
||||
import { GlobeEngine, type AtlasMeshManifest, type GlobeHit } from './GlobeEngine';
|
||||
import { placeLabels, type GlobeLabel } from './globeLabels';
|
||||
import { globeTheme } from './globeTheme';
|
||||
|
||||
export interface AtlasGlobeHandle {
|
||||
engine: GlobeEngine | null;
|
||||
}
|
||||
|
||||
export interface AtlasGlobeProps {
|
||||
fetchJson: (path: string) => Promise<unknown>;
|
||||
dark: boolean;
|
||||
/** Country name for a label, by ISO A2 (localised by the caller). */
|
||||
labelFor: (a2: string) => string | null;
|
||||
/** Whether a country's region names are drawn when zoomed in. */
|
||||
labelRegionsOf?: (a2: string) => boolean;
|
||||
/** Paints statuses once the geometry is in (and again whenever this changes). */
|
||||
paint: (engine: GlobeEngine) => void;
|
||||
paintKey: unknown;
|
||||
onHover?: (hit: GlobeHit | null, x: number, y: number) => void;
|
||||
onSelect?: (hit: GlobeHit | null, x: number, y: number) => void;
|
||||
onReady?: (manifest: AtlasMeshManifest) => void;
|
||||
onFrame?: (engine: GlobeEngine) => void;
|
||||
onError?: (err: unknown) => void;
|
||||
insetBottom?: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Atlas globe: a WebGL2 canvas driven by GlobeEngine, with country names
|
||||
* as HTML labels on top so every script, the user's text size and screen
|
||||
* readers work without a glyph atlas.
|
||||
*/
|
||||
const AtlasGlobe = forwardRef<AtlasGlobeHandle, AtlasGlobeProps>(function AtlasGlobe(props, ref) {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const labelsRef = useRef<HTMLDivElement>(null);
|
||||
const engineRef = useRef<GlobeEngine | null>(null);
|
||||
const propsRef = useRef(props);
|
||||
propsRef.current = props;
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
get engine() {
|
||||
return engineRef.current;
|
||||
},
|
||||
}),
|
||||
[]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
let engine: GlobeEngine;
|
||||
try {
|
||||
engine = new GlobeEngine({
|
||||
canvas,
|
||||
fetchJson: (p) => propsRef.current.fetchJson(p),
|
||||
theme: globeTheme(propsRef.current.dark),
|
||||
onHover: (h, x, y) => propsRef.current.onHover?.(h, x, y),
|
||||
onSelect: (h, x, y) => propsRef.current.onSelect?.(h, x, y),
|
||||
onError: (e) => propsRef.current.onError?.(e),
|
||||
onReady: () => {
|
||||
if (engine.manifest) propsRef.current.onReady?.(engine.manifest);
|
||||
propsRef.current.paint(engine);
|
||||
setReady(true);
|
||||
},
|
||||
onFrame: (e) => {
|
||||
if (labelsRef.current)
|
||||
placeLabels(labelsRef.current, labelPool, e, propsRef.current.labelFor, propsRef.current.labelRegionsOf);
|
||||
propsRef.current.onFrame?.(e);
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
propsRef.current.onError?.(err);
|
||||
return;
|
||||
}
|
||||
const labelPool: GlobeLabel[] = [];
|
||||
engine.onRegionLoaded = () => propsRef.current.paint(engine);
|
||||
engineRef.current = engine;
|
||||
return () => {
|
||||
engine.dispose();
|
||||
engineRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
engineRef.current?.setTheme(globeTheme(props.dark));
|
||||
}, [props.dark]);
|
||||
|
||||
useEffect(() => {
|
||||
const e = engineRef.current;
|
||||
if (e && ready) {
|
||||
props.paint(e);
|
||||
e.kick();
|
||||
}
|
||||
// paintKey stands for everything paint() reads.
|
||||
}, [props.paintKey, ready]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
engineRef.current?.setInsetBottom(props.insetBottom ?? 0);
|
||||
}, [props.insetBottom]);
|
||||
|
||||
return (
|
||||
<div className={props.className} style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', touchAction: 'none', cursor: 'grab' }}
|
||||
aria-label="Atlas"
|
||||
role="img"
|
||||
/>
|
||||
<div ref={labelsRef} aria-hidden="true" style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }} />
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
export default AtlasGlobe;
|
||||
@@ -0,0 +1,179 @@
|
||||
import type { BadgeMotif, BadgeTier } from '@trek/shared';
|
||||
import {
|
||||
CalendarClock,
|
||||
Compass,
|
||||
Earth,
|
||||
Flag,
|
||||
Flame,
|
||||
Footprints,
|
||||
Globe,
|
||||
Map as MapIcon,
|
||||
Moon,
|
||||
Orbit,
|
||||
Plane,
|
||||
PlaneTakeoff,
|
||||
Sailboat,
|
||||
Snowflake,
|
||||
Sparkles,
|
||||
Star,
|
||||
TowerControl,
|
||||
TreePalm,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react';
|
||||
import React from 'react';
|
||||
|
||||
/**
|
||||
* A badge as a hexagonal glass medal: a tinted glass body, a ring in the tier's
|
||||
* metal, and a motif drawn for this badge alone. The shine is a CSS layer that
|
||||
* follows the pointer (see .ag-medal in atlasGlobe.css). Map/medal paint, not UI
|
||||
* surfaces, so the colours are literal here.
|
||||
*/
|
||||
|
||||
export const TIERS: Record<BadgeTier, [string, string]> = {
|
||||
bronze: ['#f5b06b', '#a55a1e'], // theme-lint-disable: medal metal
|
||||
silver: ['#eef2f7', '#8a97ab'], // theme-lint-disable: medal metal
|
||||
gold: ['#fde68a', '#c98a0e'], // theme-lint-disable: medal metal
|
||||
aurora: ['#5eead4', '#a78bfa'], // theme-lint-disable: medal metal
|
||||
};
|
||||
|
||||
const HEX = '46,3 89,27 89,77 46,101 3,77 3,27';
|
||||
const INNER = '46,12 80,31 80,73 46,92 12,73 12,31';
|
||||
const INK = '#e0f2fe'; // theme-lint-disable: medal line art
|
||||
const ACCENT = '#7dd3fc'; // theme-lint-disable: medal line art
|
||||
|
||||
/**
|
||||
* One drawn symbol per motif, from the same icon set as the rest of TREK so every
|
||||
* medal reads at a glance and shares one stroke weight. Badges that come in steps
|
||||
* (5, 10, 25 countries) carry their number under the symbol.
|
||||
*/
|
||||
const ICONS: Record<BadgeMotif, LucideIcon> = {
|
||||
first: Footprints,
|
||||
countries: Flag,
|
||||
continents: Earth,
|
||||
seven: Earth,
|
||||
region: MapIcon,
|
||||
earth: Orbit,
|
||||
moon: Moon,
|
||||
flights: Plane,
|
||||
longhaul: PlaneTakeoff,
|
||||
airports: TowerControl,
|
||||
dateline: CalendarClock,
|
||||
equator: Globe,
|
||||
hemispheres: Compass,
|
||||
tropics: TreePalm,
|
||||
polar: Snowflake,
|
||||
streak: Flame,
|
||||
burst: Sparkles,
|
||||
wish: Star,
|
||||
islands: Sailboat,
|
||||
};
|
||||
|
||||
function Motif({ motif, label }: { motif: BadgeMotif; label?: string }): React.ReactElement {
|
||||
const Icon = ICONS[motif];
|
||||
if (motif === 'seven') {
|
||||
// All seven continents: the globe with seven lit points around it.
|
||||
return (
|
||||
<>
|
||||
<Icon x={31} y={37} size={30} color={INK} strokeWidth={1.6} />
|
||||
{Array.from({ length: 7 }, (_, i) => {
|
||||
const a = (i / 7) * Math.PI * 2 - Math.PI / 2;
|
||||
return <circle key={i} cx={46 + Math.cos(a) * 25} cy={52 + Math.sin(a) * 25} r="2.4" fill={ACCENT} />;
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (!label) return <Icon x={28} y={34} size={36} color={INK} strokeWidth={1.5} />;
|
||||
const long = label.length >= 4;
|
||||
return (
|
||||
<>
|
||||
<Icon x={33} y={28} size={26} color={INK} strokeWidth={1.7} />
|
||||
<text
|
||||
x="46"
|
||||
y="75"
|
||||
textAnchor="middle"
|
||||
fontWeight="700"
|
||||
fontSize={long ? 11 : label.length === 3 ? 13 : 15}
|
||||
letterSpacing="0.2"
|
||||
fill={INK}
|
||||
>
|
||||
{label}
|
||||
</text>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export interface BadgeMedalProps {
|
||||
motif: BadgeMotif;
|
||||
tier: BadgeTier;
|
||||
earned: boolean;
|
||||
/** 0..1 progress ring for a badge not yet earned. */
|
||||
progress?: number;
|
||||
/** Short text some motifs carry (a number, a country code). */
|
||||
label?: string;
|
||||
/** Back side: shown instead of the motif. */
|
||||
back?: React.ReactNode;
|
||||
size?: number;
|
||||
id: string;
|
||||
}
|
||||
|
||||
export default function BadgeMedal({
|
||||
motif,
|
||||
tier,
|
||||
earned,
|
||||
progress = 0,
|
||||
label,
|
||||
back,
|
||||
size = 92,
|
||||
id,
|
||||
}: BadgeMedalProps): React.ReactElement {
|
||||
const [c1, c2] = TIERS[tier];
|
||||
const g = `bm-${id}`;
|
||||
return (
|
||||
<svg viewBox="0 0 92 104" width={size} height={(size * 104) / 92} aria-hidden="true">
|
||||
<defs>
|
||||
<linearGradient id={`${g}-r`} x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stopColor={c1} />
|
||||
<stop offset="0.5" stopColor={c2} />
|
||||
<stop offset="1" stopColor={c1} />
|
||||
</linearGradient>
|
||||
<radialGradient id={`${g}-f`} cx="0.35" cy="0.25" r="0.9">
|
||||
<stop offset="0" stopColor="rgb(125 211 252 / 0.32)" />
|
||||
<stop offset="0.55" stopColor="rgb(30 41 70 / 0.82)" />
|
||||
<stop offset="1" stopColor="rgb(10 14 28 / 0.96)" />
|
||||
</radialGradient>
|
||||
<filter id={`${g}-g`} x="-30%" y="-30%" width="160%" height="160%">
|
||||
<feGaussianBlur stdDeviation="2" result="b" />
|
||||
<feMerge>
|
||||
<feMergeNode in="b" />
|
||||
<feMergeNode in="SourceGraphic" />
|
||||
</feMerge>
|
||||
</filter>
|
||||
</defs>
|
||||
<polygon
|
||||
points={HEX}
|
||||
fill={`url(#${g}-f)`}
|
||||
stroke={`url(#${g}-r)`}
|
||||
strokeWidth={earned ? 5 : 2}
|
||||
strokeOpacity={earned ? 1 : 0.35}
|
||||
strokeDasharray={earned ? undefined : '4 3'}
|
||||
/>
|
||||
<polygon points={INNER} fill="none" stroke="rgb(255 255 255 / 0.14)" strokeWidth="1" />
|
||||
{!earned && progress > 0 && (
|
||||
<polygon
|
||||
points={INNER}
|
||||
fill="none"
|
||||
stroke={ACCENT}
|
||||
strokeWidth="2.4"
|
||||
pathLength={100}
|
||||
strokeDasharray={`${Math.round(progress * 100)} 100`}
|
||||
strokeLinecap="round"
|
||||
filter={`url(#${g}-g)`}
|
||||
/>
|
||||
)}
|
||||
<g opacity={earned ? 1 : 0.38} filter={`url(#${g}-g)`}>
|
||||
{back ?? <Motif motif={motif} label={label} />}
|
||||
</g>
|
||||
<path d="M10 28 L46 8 L82 28" fill="none" stroke="rgb(255 255 255 / 0.35)" strokeWidth="1.2" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,803 @@
|
||||
/**
|
||||
* Drives the Atlas globe: camera with inertia and a zoom spring, gestures,
|
||||
* loading the right level of detail and the regions in view, picking, and one
|
||||
* animation loop that only runs while something moves.
|
||||
*
|
||||
* Framework free. AtlasGlobe.tsx mounts it and feeds it data; it reports back
|
||||
* through the callbacks in GlobeEngineOptions.
|
||||
*/
|
||||
import type { Topology } from 'topojson-specification';
|
||||
import { GlobeRenderer, MAX_FEATURES, type ArcLayer, type GlobeTheme } from './GlobeRenderer';
|
||||
import {
|
||||
frameParams,
|
||||
MAX_ZOOM,
|
||||
MIN_ZOOM,
|
||||
morphOf,
|
||||
projectPoint,
|
||||
RAD,
|
||||
sunVector,
|
||||
xSqueeze,
|
||||
type FrameParams,
|
||||
type GlobeCamera,
|
||||
type GlobeViewport,
|
||||
} from './globeMath';
|
||||
import { buildOcean, type BuiltLayer, type LineMesh } from './globeMesh';
|
||||
import type { MeshRequest, MeshResponse } from './globeMesh.worker';
|
||||
|
||||
export interface AtlasMeshManifest {
|
||||
version: number;
|
||||
lods: string[];
|
||||
regionLods: string[];
|
||||
world: Record<string, string>;
|
||||
countries: Array<{
|
||||
a2: string | null;
|
||||
a3: string;
|
||||
name: string;
|
||||
anchor: [number, number] | null;
|
||||
bbox: number[];
|
||||
area: number;
|
||||
}>;
|
||||
regions: Record<string, { bbox: number[]; counted: number; total: number; index: string }>;
|
||||
/** [a2, code, name, nameEn, lon, lat] per region */
|
||||
regionSearch?: string;
|
||||
attribution: string[];
|
||||
}
|
||||
|
||||
export interface RegionIndex {
|
||||
bbox: number[];
|
||||
counted: number;
|
||||
features: Array<{
|
||||
code: string | null;
|
||||
name: string | null;
|
||||
nameEn: string | null;
|
||||
anchor: [number, number] | null;
|
||||
counted: boolean;
|
||||
}>;
|
||||
files: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface GlobeEngineOptions {
|
||||
canvas: HTMLCanvasElement;
|
||||
/** Fetches a JSON file below /api/addons/atlas/mesh/ (auth and API base are the caller's). */
|
||||
fetchJson: (path: string) => Promise<unknown>;
|
||||
theme: GlobeTheme;
|
||||
initial?: Partial<GlobeCamera>;
|
||||
onFrame?: (engine: GlobeEngine) => void;
|
||||
onHover?: (hit: GlobeHit | null, x: number, y: number) => void;
|
||||
onSelect?: (hit: GlobeHit | null, x: number, y: number) => void;
|
||||
onReady?: () => void;
|
||||
onError?: (err: unknown) => void;
|
||||
}
|
||||
|
||||
export type GlobeHit =
|
||||
| { kind: 'country'; index: number; a2: string | null }
|
||||
| { kind: 'region'; a2: string; code: string | null; name: string | null };
|
||||
|
||||
/** Zoom from which regions crossfade in, and from which the finer region files load. */
|
||||
export const REGION_FADE_START = 5;
|
||||
export const REGION_FADE_END = 6;
|
||||
/**
|
||||
* From here on the regions in view are fetched ahead, while the zoom is still
|
||||
* on its way, so they are drawn by the time they fade in instead of a beat later.
|
||||
*/
|
||||
const REGION_PREFETCH_ZOOM = 3;
|
||||
/** How often the view is checked for regions to fetch, in seconds. */
|
||||
const REGION_SCAN_EVERY = 0.2;
|
||||
/** A region file that failed is asked for again after this long, not every frame. */
|
||||
const REGION_RETRY_AFTER = 20;
|
||||
const REGION_FINE_ZOOM = 8;
|
||||
const WORLD_LOD_ZOOM: Array<[string, number]> = [
|
||||
['l2', 4.2],
|
||||
['l1', 2.0],
|
||||
['l0', 0],
|
||||
];
|
||||
const MAX_EDGE: Record<string, number> = { l0: 8, l1: 4, l2: 2, r0: 3, r1: 1.5 };
|
||||
const FIRST_REGION_ID = 512;
|
||||
|
||||
export class GlobeEngine {
|
||||
readonly renderer: GlobeRenderer;
|
||||
readonly cam: GlobeCamera = { lon: 10, lat: 30, zoom: 1 };
|
||||
manifest: AtlasMeshManifest | null = null;
|
||||
readonly regionIndex = new Map<string, RegionIndex>();
|
||||
/** Status-texture id of each country's first region. */
|
||||
readonly regionBase = new Map<string, number>();
|
||||
vp: GlobeViewport = { width: 1, height: 1, baseRadius: 1, globeY: 0, flatY: 0 };
|
||||
frame: FrameParams;
|
||||
theme: GlobeTheme;
|
||||
hover = -1;
|
||||
selected = -1;
|
||||
selectedOutline: LineMesh | null = null;
|
||||
arcs: ArcLayer[] = [];
|
||||
arcStart = 0;
|
||||
revealStart = 0;
|
||||
/** Set while something orbits the globe and needs every frame. */
|
||||
ambient = false;
|
||||
private reducedMotion =
|
||||
typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
private idleTimer = 0;
|
||||
/** Extra px at the bottom the map should keep clear (sheets, docks). */
|
||||
insetBottom = 0;
|
||||
|
||||
private opts: GlobeEngineOptions;
|
||||
private dpr = 1;
|
||||
private targetZoom = 1;
|
||||
private vx = 0;
|
||||
private vy = 0;
|
||||
private dragging = false;
|
||||
private pointers = new Map<number, { x: number; y: number }>();
|
||||
private pinch: { d: number; z: number } | null = null;
|
||||
private down: { x: number; y: number; t: number } | null = null;
|
||||
private fly: { from: GlobeCamera; to: GlobeCamera; t0: number; dur: number } | null = null;
|
||||
private raf = 0;
|
||||
private idleFrames = 0;
|
||||
private alive = true;
|
||||
private worker: Worker;
|
||||
private job = 0;
|
||||
private pending = new Map<number, { resolve: (l: BuiltLayer) => void; reject: (err: Error) => void }>();
|
||||
private worldLoading = new Set<string>();
|
||||
private regionLoading = new Set<string>();
|
||||
private regionFailedAt = new Map<string, number>();
|
||||
private regionScanAt = -1;
|
||||
private inViewRegionKeys: ReadonlySet<string> = new Set();
|
||||
private prefetchQueue: string[] = [];
|
||||
private prefetchTimer = 0;
|
||||
private nextRegionId = FIRST_REGION_ID;
|
||||
private ink: { id: number; lon: number; lat: number; t0: number } | null = null;
|
||||
private t0 = performance.now();
|
||||
private lastHoverAt = 0;
|
||||
private resizeObs: ResizeObserver;
|
||||
private regionKeys: string[] = [];
|
||||
private zoomAnchor: { x: number; y: number; lon: number; lat: number } | null = null;
|
||||
private sun: [number, number, number] = sunVector(new Date());
|
||||
private sunAt = 0;
|
||||
|
||||
constructor(opts: GlobeEngineOptions) {
|
||||
this.opts = opts;
|
||||
this.theme = opts.theme;
|
||||
Object.assign(this.cam, opts.initial ?? {});
|
||||
this.targetZoom = this.cam.zoom;
|
||||
this.renderer = new GlobeRenderer(opts.canvas);
|
||||
this.renderer.setOcean(buildOcean());
|
||||
this.frame = frameParams(this.cam, this.vp);
|
||||
this.worker = new Worker(new URL('./globeMesh.worker.ts', import.meta.url), { type: 'module' });
|
||||
// A build that fails rejects its own job only: the caller decides what that
|
||||
// means (a region stays plain, a missing world level keeps the coarser one).
|
||||
this.worker.onmessage = (e: MessageEvent<MeshResponse>) => {
|
||||
const job = this.pending.get(e.data.job);
|
||||
this.pending.delete(e.data.job);
|
||||
if (!job) return;
|
||||
if (e.data.layer) job.resolve(e.data.layer);
|
||||
else job.reject(new Error(e.data.error ?? 'Atlas mesh build failed'));
|
||||
};
|
||||
this.bindInput(opts.canvas);
|
||||
this.resizeObs = new ResizeObserver(() => this.resize());
|
||||
this.resizeObs.observe(opts.canvas);
|
||||
opts.canvas.addEventListener('webglcontextlost', this.onContextLost);
|
||||
this.resize();
|
||||
void this.boot();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- loading
|
||||
|
||||
private build(topo: Topology, object: string, maxEdge: number, idBase: number): Promise<BuiltLayer> {
|
||||
const job = ++this.job;
|
||||
return new Promise((resolve, reject) => {
|
||||
this.pending.set(job, { resolve, reject });
|
||||
this.worker.postMessage({ job, topo, object, maxEdge, idBase } satisfies MeshRequest);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A fetch tried again with growing pauses (1, 2, 4, 8 s): a server that is
|
||||
* restarting or a connection that drops for a moment must not leave the
|
||||
* globe empty for good.
|
||||
*/
|
||||
private async fetchRetrying(path: string): Promise<unknown> {
|
||||
for (let n = 0; ; n++) {
|
||||
try {
|
||||
return await this.opts.fetchJson(path);
|
||||
} catch (err) {
|
||||
if (n >= 4 || !this.alive) throw err;
|
||||
await new Promise((r) => window.setTimeout(r, 1000 * 2 ** n));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async boot(): Promise<void> {
|
||||
try {
|
||||
this.manifest = (await this.fetchRetrying('manifest')) as AtlasMeshManifest;
|
||||
await this.loadWorld('l0');
|
||||
this.revealStart = this.now();
|
||||
this.opts.onReady?.();
|
||||
this.kick();
|
||||
} catch (err) {
|
||||
this.opts.onError?.(err);
|
||||
}
|
||||
}
|
||||
|
||||
private async loadWorld(lod: string): Promise<void> {
|
||||
if (!this.manifest || this.renderer.hasWorld(lod) || this.worldLoading.has(lod)) return;
|
||||
this.worldLoading.add(lod);
|
||||
try {
|
||||
const topo = (await this.fetchRetrying(`world/${this.manifest.world[lod]}`)) as Topology;
|
||||
const layer = await this.build(topo, 'countries', MAX_EDGE[lod], 0);
|
||||
if (!this.alive) return;
|
||||
this.renderer.setWorld(lod, layer);
|
||||
this.kick();
|
||||
} finally {
|
||||
this.worldLoading.delete(lod);
|
||||
}
|
||||
}
|
||||
|
||||
async loadRegionIndex(a2: string): Promise<RegionIndex | null> {
|
||||
const have = this.regionIndex.get(a2);
|
||||
if (have) return have;
|
||||
const entry = this.manifest?.regions[a2];
|
||||
if (!entry) return null;
|
||||
const idx = (await this.opts.fetchJson(entry.index)) as RegionIndex;
|
||||
if (!this.regionIndex.has(a2)) {
|
||||
this.regionIndex.set(a2, idx);
|
||||
if (this.nextRegionId + idx.features.length < MAX_FEATURES) {
|
||||
this.regionBase.set(a2, this.nextRegionId);
|
||||
this.nextRegionId += idx.features.length;
|
||||
}
|
||||
}
|
||||
return this.regionIndex.get(a2) ?? null;
|
||||
}
|
||||
|
||||
private async loadRegion(a2: string, lod: string): Promise<void> {
|
||||
const key = `${a2}:${lod}`;
|
||||
if (this.renderer.hasRegion(key) || this.regionLoading.has(key)) return;
|
||||
const failedAt = this.regionFailedAt.get(key);
|
||||
if (failedAt !== undefined && this.now() - failedAt < REGION_RETRY_AFTER) return;
|
||||
this.regionLoading.add(key);
|
||||
try {
|
||||
const idx = await this.loadRegionIndex(a2);
|
||||
const base = this.regionBase.get(a2);
|
||||
if (!idx || base === undefined) return;
|
||||
const topo = (await this.opts.fetchJson(idx.files[lod])) as Topology;
|
||||
const layer = await this.build(topo, 'regions', MAX_EDGE[lod], base);
|
||||
if (!this.alive) return;
|
||||
this.renderer.setRegion(key, layer, this.inViewRegionKeys);
|
||||
this.onRegionLoaded?.(a2);
|
||||
this.kick();
|
||||
} catch {
|
||||
// A country's regions are detail on top of a working globe: one that does
|
||||
// not load leaves the country plain and is asked for again later, it does
|
||||
// not turn the whole Atlas into an error.
|
||||
this.regionFailedAt.set(key, this.now());
|
||||
} finally {
|
||||
this.regionLoading.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the coarse regions of these countries in the background, one at a
|
||||
* time while the browser is idle (the owner passes the countries the user is
|
||||
* most likely to zoom into), so their first zoom finds them ready.
|
||||
*/
|
||||
prefetchRegions(codes: string[]): void {
|
||||
const known = new Set(this.prefetchQueue);
|
||||
for (const a2 of codes) if (this.manifest?.regions[a2] && !known.has(a2)) this.prefetchQueue.push(a2);
|
||||
this.schedulePrefetch();
|
||||
}
|
||||
|
||||
private schedulePrefetch(): void {
|
||||
if (this.prefetchTimer || !this.prefetchQueue.length || !this.alive) return;
|
||||
const next = () => {
|
||||
this.prefetchTimer = 0;
|
||||
const a2 = this.prefetchQueue.shift();
|
||||
if (!a2 || !this.alive) return;
|
||||
void this.loadRegion(a2, 'r0').finally(() => this.schedulePrefetch());
|
||||
};
|
||||
const idle = (window as Window & { requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => number })
|
||||
.requestIdleCallback;
|
||||
this.prefetchTimer = idle ? idle(next, { timeout: 1500 }) : window.setTimeout(next, 120);
|
||||
}
|
||||
|
||||
/** Called after a country's regions arrived, so the owner can colour them. */
|
||||
onRegionLoaded: ((a2: string) => void) | null = null;
|
||||
|
||||
private worldKey(): string {
|
||||
for (const [lod, z] of WORLD_LOD_ZOOM) if (this.cam.zoom >= z && this.renderer.hasWorld(lod)) return lod;
|
||||
for (const [lod] of WORLD_LOD_ZOOM.slice().reverse()) if (this.renderer.hasWorld(lod)) return lod;
|
||||
return 'l0';
|
||||
}
|
||||
|
||||
private wantedWorld(): string {
|
||||
for (const [lod, z] of WORLD_LOD_ZOOM) if (this.cam.zoom >= z) return lod;
|
||||
return 'l0';
|
||||
}
|
||||
|
||||
/** Countries with regions whose box overlaps the view, nearest first. */
|
||||
private countriesInView(): string[] {
|
||||
const m = this.manifest;
|
||||
if (!m) return [];
|
||||
const out: Array<[string, number]> = [];
|
||||
const { width, height } = this.vp;
|
||||
for (const c of m.countries) {
|
||||
if (!c.a2 || !m.regions[c.a2]) continue;
|
||||
const [w, s, e, n] = c.bbox;
|
||||
let best = Infinity;
|
||||
let inView = false;
|
||||
for (const [lon, lat] of [
|
||||
[(w + e) / 2, (s + n) / 2],
|
||||
[w, s],
|
||||
[e, n],
|
||||
[w, n],
|
||||
[e, s],
|
||||
c.anchor ?? [(w + e) / 2, (s + n) / 2],
|
||||
]) {
|
||||
const p = projectPoint(lon, lat, this.frame);
|
||||
if (p.visible < 0) continue;
|
||||
if (p.x > -200 && p.x < width + 200 && p.y > -200 && p.y < height + 200) inView = true;
|
||||
best = Math.min(best, Math.hypot(p.x - width / 2, p.y - height / 2));
|
||||
}
|
||||
if (inView) out.push([c.a2, best]);
|
||||
}
|
||||
return out
|
||||
.sort((a, b) => a[1] - b[1])
|
||||
.slice(0, 10)
|
||||
.map((x) => x[0]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- camera
|
||||
|
||||
private now(): number {
|
||||
return (performance.now() - this.t0) / 1000;
|
||||
}
|
||||
|
||||
resize(): void {
|
||||
const c = this.opts.canvas;
|
||||
const r = c.getBoundingClientRect();
|
||||
this.dpr = Math.min(2, window.devicePixelRatio || 1);
|
||||
c.width = Math.max(1, Math.round(r.width * this.dpr));
|
||||
c.height = Math.max(1, Math.round(r.height * this.dpr));
|
||||
const narrow = r.width < 640;
|
||||
const usable = r.height - this.insetBottom;
|
||||
this.vp = {
|
||||
width: r.width,
|
||||
height: r.height,
|
||||
baseRadius: narrow ? r.width * 0.42 : Math.min(r.width, usable) * 0.31,
|
||||
// On a phone the globe sits a little lower, clear of the search and buttons on top.
|
||||
globeY: narrow ? usable * 0.54 : usable * 0.5,
|
||||
flatY: usable * 0.5,
|
||||
};
|
||||
this.kick();
|
||||
}
|
||||
|
||||
setInsetBottom(px: number): void {
|
||||
if (Math.abs(px - this.insetBottom) < 1) return;
|
||||
this.insetBottom = px;
|
||||
this.resize();
|
||||
}
|
||||
|
||||
setTheme(theme: GlobeTheme): void {
|
||||
this.theme = theme;
|
||||
this.kick();
|
||||
}
|
||||
|
||||
flyTo(lon: number, lat: number, zoom = Math.max(this.cam.zoom, 1), dur = 1100): void {
|
||||
let dl = lon - this.cam.lon;
|
||||
dl = ((dl + 540) % 360) - 180;
|
||||
this.fly = {
|
||||
from: { ...this.cam },
|
||||
to: { lon: this.cam.lon + dl, lat: Math.max(-70, Math.min(70, lat)), zoom },
|
||||
t0: performance.now(),
|
||||
dur,
|
||||
};
|
||||
this.vx = this.vy = 0;
|
||||
this.kick();
|
||||
}
|
||||
|
||||
/** Flies so a country's box fills the view. */
|
||||
flyToBox(bbox: number[], minZoom = 1, maxZoom = 7): void {
|
||||
const [w, s, e, n] = bbox;
|
||||
const span = Math.max(e - w, (n - s) * 1.6, 0.5);
|
||||
const zoom = Math.max(minZoom, Math.min(maxZoom, (110 / span) ** 0.85));
|
||||
this.flyTo((w + e) / 2, (s + n) / 2, zoom);
|
||||
}
|
||||
|
||||
zoomBy(f: number): void {
|
||||
this.targetZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, this.targetZoom * f));
|
||||
this.kick();
|
||||
}
|
||||
|
||||
startInk(id: number, lon: number, lat: number): void {
|
||||
this.ink = { id, lon, lat, t0: this.now() };
|
||||
this.kick();
|
||||
}
|
||||
|
||||
setSelected(id: number, outline: LineMesh | null): void {
|
||||
this.selected = id;
|
||||
this.selectedOutline = outline;
|
||||
this.kick();
|
||||
}
|
||||
|
||||
setArcs(arcs: ArcLayer[]): void {
|
||||
this.arcs = arcs;
|
||||
this.arcStart = this.now();
|
||||
this.kick();
|
||||
}
|
||||
|
||||
project(lon: number, lat: number): ReturnType<typeof projectPoint> {
|
||||
return projectPoint(lon, lat, this.frame);
|
||||
}
|
||||
|
||||
get morph(): number {
|
||||
return this.frame.t;
|
||||
}
|
||||
|
||||
get regionAlpha(): number {
|
||||
const z = this.cam.zoom;
|
||||
return Math.max(0, Math.min(1, (z - REGION_FADE_START) / (REGION_FADE_END - REGION_FADE_START)));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- input
|
||||
|
||||
private bindInput(c: HTMLCanvasElement): void {
|
||||
c.addEventListener('pointerdown', this.onDown);
|
||||
c.addEventListener('pointermove', this.onMove);
|
||||
c.addEventListener('pointerup', this.onUp);
|
||||
c.addEventListener('pointercancel', this.onUp);
|
||||
c.addEventListener('pointerleave', this.onLeave);
|
||||
c.addEventListener('wheel', this.onWheel, { passive: false });
|
||||
c.addEventListener('dblclick', this.onDbl);
|
||||
}
|
||||
|
||||
private local(e: PointerEvent | WheelEvent | MouseEvent): { x: number; y: number } {
|
||||
const r = this.opts.canvas.getBoundingClientRect();
|
||||
return { x: e.clientX - r.left, y: e.clientY - r.top };
|
||||
}
|
||||
|
||||
private onDown = (e: PointerEvent): void => {
|
||||
this.opts.canvas.setPointerCapture(e.pointerId);
|
||||
const p = this.local(e);
|
||||
this.pointers.set(e.pointerId, p);
|
||||
this.down = { ...p, t: performance.now() };
|
||||
this.vx = this.vy = 0;
|
||||
this.fly = null;
|
||||
this.zoomAnchor = null;
|
||||
this.dragging = true;
|
||||
this.clearHover();
|
||||
if (this.pointers.size === 2) {
|
||||
const [a, b] = [...this.pointers.values()];
|
||||
this.pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), z: this.targetZoom };
|
||||
}
|
||||
this.kick();
|
||||
};
|
||||
|
||||
private onMove = (e: PointerEvent): void => {
|
||||
const p = this.local(e);
|
||||
const prev = this.pointers.get(e.pointerId);
|
||||
if (prev) {
|
||||
this.pointers.set(e.pointerId, p);
|
||||
if (this.pointers.size === 2 && this.pinch) {
|
||||
const [a, b] = [...this.pointers.values()];
|
||||
const d = Math.hypot(a.x - b.x, a.y - b.y);
|
||||
this.targetZoom = Math.max(MIN_ZOOM * 0.85, Math.min(MAX_ZOOM * 1.1, (this.pinch.z * d) / this.pinch.d));
|
||||
this.cam.zoom = this.targetZoom;
|
||||
this.kick();
|
||||
return;
|
||||
}
|
||||
if (this.pointers.size > 1) return;
|
||||
const k = 1 / (this.frame.scale * RAD);
|
||||
const kx = k / xSqueeze(this.frame);
|
||||
const dx = p.x - prev.x;
|
||||
const dy = p.y - prev.y;
|
||||
this.cam.lon -= dx * kx;
|
||||
this.cam.lat = Math.max(-80, Math.min(80, this.cam.lat + dy * k));
|
||||
this.vx = dx * kx * 0.85 + this.vx * 0.15;
|
||||
this.vy = dy * k * 0.85 + this.vy * 0.15;
|
||||
this.kick();
|
||||
return;
|
||||
}
|
||||
const now = performance.now();
|
||||
if (now - this.lastHoverAt < 45) return;
|
||||
this.lastHoverAt = now;
|
||||
const hit = this.hitAt(p.x, p.y);
|
||||
const id = hit ? this.idOf(hit) : -1;
|
||||
if (id !== this.hover) {
|
||||
this.hover = id;
|
||||
this.kick();
|
||||
}
|
||||
this.opts.onHover?.(hit, p.x, p.y);
|
||||
};
|
||||
|
||||
private onUp = (e: PointerEvent): void => {
|
||||
if (!this.pointers.has(e.pointerId)) return;
|
||||
this.pointers.delete(e.pointerId);
|
||||
if (this.pointers.size < 2) this.pinch = null;
|
||||
if (this.pointers.size > 0) return;
|
||||
this.dragging = false;
|
||||
const p = this.local(e);
|
||||
if (this.down && Math.hypot(p.x - this.down.x, p.y - this.down.y) < 6 && performance.now() - this.down.t < 400) {
|
||||
this.vx = this.vy = 0;
|
||||
this.opts.onSelect?.(this.hitAt(p.x, p.y), p.x, p.y);
|
||||
}
|
||||
this.down = null;
|
||||
this.kick();
|
||||
};
|
||||
|
||||
private onLeave = (): void => {
|
||||
if (this.dragging) return;
|
||||
this.hover = -1;
|
||||
this.opts.onHover?.(null, 0, 0);
|
||||
this.kick();
|
||||
};
|
||||
|
||||
/** Drops the hover while the camera moves; the next pointer move picks again. */
|
||||
private clearHover(): void {
|
||||
if (this.hover === -1) return;
|
||||
this.hover = -1;
|
||||
this.opts.onHover?.(null, 0, 0);
|
||||
}
|
||||
|
||||
private onWheel = (e: WheelEvent): void => {
|
||||
e.preventDefault();
|
||||
this.clearHover();
|
||||
const before = this.targetZoom;
|
||||
const f = Math.exp(-e.deltaY * (e.deltaMode === 1 ? 0.05 : 0.0016));
|
||||
this.targetZoom = Math.max(MIN_ZOOM * 0.9, Math.min(MAX_ZOOM, before * f));
|
||||
// On the flat map the place under the cursor stays under the cursor while the
|
||||
// zoom glides; tick() moves the centre to keep it there, frame by frame.
|
||||
if (this.frame.t > 0.5 && this.targetZoom !== before) {
|
||||
const p = this.local(e);
|
||||
const geo = this.unprojectFlat(p.x, p.y);
|
||||
this.zoomAnchor = { x: p.x, y: p.y, lon: geo[0], lat: geo[1] };
|
||||
}
|
||||
this.fly = null;
|
||||
this.kick();
|
||||
};
|
||||
|
||||
/** Screen point to lon/lat on the flat map (t = 1); close enough while t > 0.5. */
|
||||
private unprojectFlat(x: number, y: number): [number, number] {
|
||||
const f = this.frame;
|
||||
const k = 1 / (f.scale * RAD);
|
||||
return [this.cam.lon + ((x - f.originX) * k) / xSqueeze(f), this.cam.lat - (y - f.originY) * k];
|
||||
}
|
||||
|
||||
/** Moves the centre so the anchored place sits under its screen point again. */
|
||||
private holdAnchor(): void {
|
||||
const a = this.zoomAnchor;
|
||||
if (!a) return;
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const f = frameParams(this.cam, this.vp);
|
||||
const k = 1 / (f.scale * RAD);
|
||||
this.cam.lat = Math.max(-80, Math.min(80, a.lat + (a.y - f.originY) * k));
|
||||
this.cam.lon = a.lon - ((a.x - f.originX) * k) / xSqueeze(f);
|
||||
}
|
||||
}
|
||||
|
||||
private onDbl = (e: MouseEvent): void => {
|
||||
const p = this.local(e);
|
||||
const hit = this.hitAt(p.x, p.y);
|
||||
if (!hit) this.zoomBy(1.8);
|
||||
};
|
||||
|
||||
private onContextLost = (e: Event): void => {
|
||||
e.preventDefault();
|
||||
this.opts.onError?.(new Error('WebGL context lost'));
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- picking
|
||||
|
||||
idOf(hit: GlobeHit): number {
|
||||
if (hit.kind === 'country') return hit.index;
|
||||
const idx = this.regionIndex.get(hit.a2);
|
||||
const base = this.regionBase.get(hit.a2);
|
||||
if (!idx || base === undefined) return -1;
|
||||
const i = idx.features.findIndex((f) => f.code === hit.code);
|
||||
return i < 0 ? -1 : base + i;
|
||||
}
|
||||
|
||||
/**
|
||||
* The country under the middle of the view, the one whose regions get their
|
||||
* names. Read from the pick buffer, so it is the country really there and not
|
||||
* the first whose bounding box holds the point (France's box spans half the
|
||||
* world with its overseas parts). The read-back is not free, so it is only
|
||||
* redone when the camera moved, at most every 150 ms.
|
||||
*/
|
||||
focusCountry(): string | null {
|
||||
const now = this.now();
|
||||
const cam = `${this.cam.lon.toFixed(3)},${this.cam.lat.toFixed(3)},${this.cam.zoom.toFixed(2)}`;
|
||||
if (cam === this.focusCam || now - this.focusAt < 0.15) return this.focus;
|
||||
this.focusAt = now;
|
||||
this.focusCam = cam;
|
||||
const hit = this.hitAt(this.vp.width / 2, this.vp.height / 2);
|
||||
this.focus = hit?.a2 ?? null;
|
||||
return this.focus;
|
||||
}
|
||||
|
||||
private focus: string | null = null;
|
||||
private focusAt = -1;
|
||||
private focusCam = '';
|
||||
|
||||
hitAt(x: number, y: number): GlobeHit | null {
|
||||
const id = this.renderer.pick(x, y, this.regionAlpha > 0.5);
|
||||
if (id < 0) return null;
|
||||
if (id < FIRST_REGION_ID) {
|
||||
const c = this.manifest?.countries[id];
|
||||
return c ? { kind: 'country', index: id, a2: c.a2 } : null;
|
||||
}
|
||||
for (const [a2, base] of this.regionBase) {
|
||||
const idx = this.regionIndex.get(a2);
|
||||
if (idx && id >= base && id < base + idx.features.length) {
|
||||
const f = idx.features[id - base];
|
||||
return { kind: 'region', a2, code: f.code, name: f.nameEn ?? f.name };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- loop
|
||||
|
||||
/** Starts the loop if it sleeps. */
|
||||
kick(): void {
|
||||
this.idleFrames = 0;
|
||||
if (this.idleTimer) {
|
||||
window.clearTimeout(this.idleTimer);
|
||||
this.idleTimer = 0;
|
||||
}
|
||||
if (!this.raf && this.alive) this.raf = requestAnimationFrame(this.tick);
|
||||
}
|
||||
|
||||
private tick = (): void => {
|
||||
this.raf = 0;
|
||||
if (!this.alive) return;
|
||||
let moving = false;
|
||||
const now = performance.now();
|
||||
if (this.fly) {
|
||||
const p = Math.min(1, (now - this.fly.t0) / this.fly.dur);
|
||||
const e = p < 0.5 ? 4 * p * p * p : 1 - Math.pow(-2 * p + 2, 3) / 2;
|
||||
const { from, to } = this.fly;
|
||||
this.cam.lon = from.lon + (to.lon - from.lon) * e;
|
||||
this.cam.lat = from.lat + (to.lat - from.lat) * e;
|
||||
// Pull back a little mid-flight, so long hops read as travel.
|
||||
const hop = Math.min(1, Math.abs(to.lon - from.lon) / 120) * Math.sin(Math.PI * e) * 0.35;
|
||||
this.cam.zoom = Math.max(MIN_ZOOM, from.zoom + (to.zoom - from.zoom) * e - hop * from.zoom);
|
||||
this.targetZoom = this.cam.zoom;
|
||||
if (p >= 1) {
|
||||
this.fly = null;
|
||||
this.targetZoom = to.zoom;
|
||||
}
|
||||
moving = true;
|
||||
}
|
||||
if (!this.dragging && !this.fly && (Math.abs(this.vx) > 1e-3 || Math.abs(this.vy) > 1e-3)) {
|
||||
this.cam.lon -= this.vx;
|
||||
this.cam.lat = Math.max(-80, Math.min(80, this.cam.lat + this.vy));
|
||||
this.vx *= 0.93;
|
||||
this.vy *= 0.93;
|
||||
moving = true;
|
||||
}
|
||||
if (!this.pinch) {
|
||||
if (this.targetZoom < MIN_ZOOM) this.targetZoom += (MIN_ZOOM - this.targetZoom) * 0.18;
|
||||
if (this.targetZoom > MAX_ZOOM) this.targetZoom += (MAX_ZOOM - this.targetZoom) * 0.18;
|
||||
}
|
||||
const dz = (this.targetZoom - this.cam.zoom) * 0.2;
|
||||
if (Math.abs(dz) > 1e-4) {
|
||||
this.cam.zoom += dz;
|
||||
moving = true;
|
||||
if (this.zoomAnchor && morphOf(this.cam.zoom) > 0.5) this.holdAnchor();
|
||||
} else {
|
||||
this.zoomAnchor = null;
|
||||
}
|
||||
this.cam.lon = ((this.cam.lon + 540) % 360) - 180;
|
||||
|
||||
this.frame = frameParams(this.cam, this.vp);
|
||||
const want = this.wantedWorld();
|
||||
// A finer level that cannot load leaves the coarser one on screen.
|
||||
if (!this.renderer.hasWorld(want)) this.loadWorld(want).catch(() => undefined);
|
||||
// Fetch ahead, by where the zoom is heading and not only where it is, and
|
||||
// during the motion too: the coarse regions well before they fade in, the
|
||||
// fine ones a step before they are drawn.
|
||||
const heading = Math.max(this.cam.zoom, this.targetZoom);
|
||||
const scanNow = this.now();
|
||||
if (heading >= REGION_PREFETCH_ZOOM && scanNow - this.regionScanAt >= REGION_SCAN_EVERY) {
|
||||
this.regionScanAt = scanNow;
|
||||
const fine = heading >= REGION_FINE_ZOOM - 1;
|
||||
const inView = this.countriesInView();
|
||||
// What is in view now is what must not be dropped, and the last to go.
|
||||
this.inViewRegionKeys = new Set(inView.flatMap((a2) => [`${a2}:r0`, `${a2}:r1`]));
|
||||
for (const k of this.inViewRegionKeys) this.renderer.touchRegion(k);
|
||||
for (const a2 of inView) {
|
||||
void this.loadRegion(a2, 'r0');
|
||||
if (fine) void this.loadRegion(a2, 'r1');
|
||||
}
|
||||
}
|
||||
this.regionKeys = this.collectRegionKeys();
|
||||
|
||||
const time = this.now();
|
||||
if (time - this.sunAt > 30) {
|
||||
this.sun = sunVector(new Date());
|
||||
this.sunAt = time;
|
||||
}
|
||||
let inkActive = false;
|
||||
let ink: { id: number; lon: number; lat: number; radius: number } | null = null;
|
||||
if (this.ink) {
|
||||
const p = (time - this.ink.t0) / 0.75;
|
||||
inkActive = p < 1;
|
||||
ink = {
|
||||
id: this.ink.id,
|
||||
lon: this.ink.lon,
|
||||
lat: this.ink.lat,
|
||||
radius: (1 - Math.pow(1 - Math.min(1, p), 3)) * Math.PI,
|
||||
};
|
||||
if (!inkActive) this.ink = null;
|
||||
}
|
||||
const arcProgress = Math.min(1.001, (time - this.arcStart) / 1.6);
|
||||
this.renderer.draw({
|
||||
frame: this.frame,
|
||||
dpr: this.dpr,
|
||||
width: this.vp.width,
|
||||
height: this.vp.height,
|
||||
time,
|
||||
revealStart: this.revealStart,
|
||||
hover: this.hover,
|
||||
selected: this.selected,
|
||||
ink,
|
||||
regionAlpha: this.regionAlpha,
|
||||
theme: this.theme,
|
||||
arcs: this.arcs,
|
||||
arcProgress,
|
||||
regionKeys: this.regionKeys,
|
||||
worldKey: this.worldKey(),
|
||||
selectedOutline: this.selectedOutline,
|
||||
sun: this.sun,
|
||||
night: this.theme.dark ? 0.34 : 0.1,
|
||||
});
|
||||
this.opts.onFrame?.(this);
|
||||
|
||||
const revealing = time - this.revealStart < 3.2;
|
||||
const twinkle = this.theme.dark && this.frame.t < 0.9;
|
||||
if (moving || inkActive || revealing || arcProgress < 1 || this.dragging) this.idleFrames = 0;
|
||||
else this.idleFrames++;
|
||||
// Things that orbit (moon, satellites) need every frame while the globe shows;
|
||||
// otherwise keep only the stars alive at a low rate once everything rests.
|
||||
const ambient = this.ambient && this.frame.t < 0.6 && !document.hidden && !this.reducedMotion;
|
||||
if (this.idleFrames < 3 || ambient) this.raf = requestAnimationFrame(this.tick);
|
||||
else if (twinkle) this.idleTimer = window.setTimeout(() => this.kick(), 90);
|
||||
};
|
||||
|
||||
private collectRegionKeys(): string[] {
|
||||
if (this.regionAlpha <= 0) return [];
|
||||
const fine = this.cam.zoom >= REGION_FINE_ZOOM;
|
||||
const out: string[] = [];
|
||||
for (const a2 of this.regionIndex.keys()) {
|
||||
const k1 = `${a2}:r1`;
|
||||
const k0 = `${a2}:r0`;
|
||||
if (fine && this.renderer.hasRegion(k1)) out.push(k1);
|
||||
else if (this.renderer.hasRegion(k0)) out.push(k0);
|
||||
else if (this.renderer.hasRegion(k1)) out.push(k1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
get zoom(): number {
|
||||
return this.cam.zoom;
|
||||
}
|
||||
|
||||
isMorphing(): boolean {
|
||||
const t = morphOf(this.cam.zoom);
|
||||
return t > 0 && t < 1;
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.alive = false;
|
||||
this.prefetchQueue = [];
|
||||
window.clearTimeout(this.idleTimer);
|
||||
cancelAnimationFrame(this.raf);
|
||||
this.resizeObs.disconnect();
|
||||
this.worker.terminate();
|
||||
const c = this.opts.canvas;
|
||||
c.removeEventListener('pointerdown', this.onDown);
|
||||
c.removeEventListener('pointermove', this.onMove);
|
||||
c.removeEventListener('pointerup', this.onUp);
|
||||
c.removeEventListener('pointercancel', this.onUp);
|
||||
c.removeEventListener('pointerleave', this.onLeave);
|
||||
c.removeEventListener('wheel', this.onWheel);
|
||||
c.removeEventListener('dblclick', this.onDbl);
|
||||
c.removeEventListener('webglcontextlost', this.onContextLost);
|
||||
this.renderer.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Star } from 'lucide-react';
|
||||
import { forwardRef, useImperativeHandle, useRef } from 'react';
|
||||
import type { GlobeEngine } from './GlobeEngine';
|
||||
|
||||
export interface GlobePin {
|
||||
key: string;
|
||||
lon: number;
|
||||
lat: number;
|
||||
title: string;
|
||||
/** A wish that was reached (ticked off by hand or by a recording). */
|
||||
reached?: boolean;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
export interface GlobePinsHandle {
|
||||
layout: (engine: GlobeEngine) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Places pinned on the globe, the bucket list's wishes with coordinates. Small
|
||||
* star buttons moved per frame with transform; hidden behind the horizon.
|
||||
*/
|
||||
const GlobePins = forwardRef<GlobePinsHandle, { pins: GlobePin[] }>(function GlobePins({ pins }, ref) {
|
||||
const refs = useRef<Array<HTMLButtonElement | null>>([]);
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
layout(engine: GlobeEngine) {
|
||||
const { width, height } = engine.vp;
|
||||
pins.forEach((p, i) => {
|
||||
const el = refs.current[i];
|
||||
if (!el) return;
|
||||
const s = engine.project(p.lon, p.lat);
|
||||
const show = s.visible > 0.02 && s.x > -20 && s.x < width + 20 && s.y > -20 && s.y < height + 20;
|
||||
el.style.transform = `translate3d(${s.x.toFixed(1)}px, ${s.y.toFixed(1)}px, 0) translate(-50%, -50%)`;
|
||||
el.style.opacity = show ? String(Math.min(1, s.visible * 6)) : '0';
|
||||
el.style.pointerEvents = show ? 'auto' : 'none';
|
||||
});
|
||||
},
|
||||
}),
|
||||
[pins]
|
||||
);
|
||||
return (
|
||||
<>
|
||||
{pins.map((p, i) => (
|
||||
<button
|
||||
key={p.key}
|
||||
ref={(el) => {
|
||||
refs.current[i] = el;
|
||||
}}
|
||||
type="button"
|
||||
onClick={p.onClick}
|
||||
title={p.title}
|
||||
aria-label={p.title}
|
||||
// No press transition: the global one animates transform, and a pin moved
|
||||
// every frame would trail the globe and spring back to its place.
|
||||
data-no-press
|
||||
className="ag-pin absolute start-0 top-0"
|
||||
data-reached={p.reached ? '1' : '0'}
|
||||
>
|
||||
<Star size={11} strokeWidth={2.4} />
|
||||
</button>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
export default GlobePins;
|
||||
@@ -0,0 +1,592 @@
|
||||
/**
|
||||
* WebGL2 renderer of the Atlas globe. Owns the GPU state only: programs,
|
||||
* layer buffers, the status textures and the picking target. What to show
|
||||
* comes in through setStatus()/setLayer() and one draw() per frame.
|
||||
*
|
||||
* Colours live in two small textures indexed by feature id, so marking a
|
||||
* country rewrites four bytes instead of rebuilding geometry.
|
||||
*/
|
||||
import type { FrameParams } from './globeMath';
|
||||
import type { BuiltLayer, FillMesh, LineMesh } from './globeMesh';
|
||||
import { FILL_FS, FILL_VS, LINE_FS, LINE_VS, PICK_FS, RIM_FS, SKY_FS, SKY_VS } from './globeShaders';
|
||||
|
||||
export const STATUS_TEX_W = 256;
|
||||
export const STATUS_TEX_H = 64;
|
||||
export const MAX_FEATURES = STATUS_TEX_W * STATUS_TEX_H;
|
||||
|
||||
export type Rgb = [number, number, number];
|
||||
|
||||
export interface GlobeTheme {
|
||||
land: Rgb;
|
||||
ocean: Rgb;
|
||||
oceanDeep: Rgb;
|
||||
space0: Rgb;
|
||||
space1: Rgb;
|
||||
glow: Rgb;
|
||||
border: [number, number, number, number];
|
||||
coast: [number, number, number, number];
|
||||
regionBorder: [number, number, number, number];
|
||||
selection: [number, number, number, number];
|
||||
arc: [number, number, number, number];
|
||||
dark: boolean;
|
||||
}
|
||||
|
||||
export interface ArcLayer {
|
||||
/** per segment: a.lon, a.lat, b.lon, b.lat, hA, hB, sA, sB */
|
||||
data: Float32Array;
|
||||
count: number;
|
||||
width: number;
|
||||
}
|
||||
|
||||
export interface DrawState {
|
||||
frame: FrameParams;
|
||||
dpr: number;
|
||||
width: number;
|
||||
height: number;
|
||||
time: number;
|
||||
revealStart: number;
|
||||
hover: number;
|
||||
selected: number;
|
||||
ink: { id: number; lon: number; lat: number; radius: number } | null;
|
||||
regionAlpha: number;
|
||||
theme: GlobeTheme;
|
||||
arcs: ArcLayer[];
|
||||
arcProgress: number;
|
||||
/** Region layers to draw, by key. */
|
||||
regionKeys: string[];
|
||||
worldKey: string;
|
||||
selectedOutline: LineMesh | null;
|
||||
/** Unit vector to the sun in earth-fixed coordinates. */
|
||||
sun: [number, number, number];
|
||||
night: number;
|
||||
}
|
||||
|
||||
interface Program {
|
||||
prog: WebGLProgram;
|
||||
u: Record<string, WebGLUniformLocation | null>;
|
||||
a: Record<string, number>;
|
||||
}
|
||||
|
||||
interface GpuFill {
|
||||
vao: WebGLVertexArrayObject;
|
||||
pickVao: WebGLVertexArrayObject;
|
||||
count: number;
|
||||
buffers: WebGLBuffer[];
|
||||
}
|
||||
|
||||
interface GpuLines {
|
||||
vao: WebGLVertexArrayObject;
|
||||
count: number;
|
||||
buffers: WebGLBuffer[];
|
||||
}
|
||||
|
||||
interface GpuLayer {
|
||||
fill: GpuFill;
|
||||
coast: GpuLines;
|
||||
borders: GpuLines;
|
||||
}
|
||||
|
||||
function compile(gl: WebGL2RenderingContext, type: number, src: string): WebGLShader {
|
||||
const s = gl.createShader(type) as WebGLShader;
|
||||
gl.shaderSource(s, src);
|
||||
gl.compileShader(s);
|
||||
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
|
||||
const log = gl.getShaderInfoLog(s);
|
||||
gl.deleteShader(s);
|
||||
throw new Error(`Atlas globe shader failed: ${log ?? 'unknown'}`);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function link(gl: WebGL2RenderingContext, vs: string, fs: string): Program {
|
||||
const prog = gl.createProgram() as WebGLProgram;
|
||||
gl.attachShader(prog, compile(gl, gl.VERTEX_SHADER, vs));
|
||||
gl.attachShader(prog, compile(gl, gl.FRAGMENT_SHADER, fs));
|
||||
gl.linkProgram(prog);
|
||||
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
|
||||
throw new Error(`Atlas globe program failed: ${gl.getProgramInfoLog(prog) ?? 'unknown'}`);
|
||||
}
|
||||
const u: Program['u'] = {};
|
||||
const n = gl.getProgramParameter(prog, gl.ACTIVE_UNIFORMS) as number;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const info = gl.getActiveUniform(prog, i);
|
||||
if (info) u[info.name] = gl.getUniformLocation(prog, info.name);
|
||||
}
|
||||
const a: Program['a'] = {};
|
||||
const m = gl.getProgramParameter(prog, gl.ACTIVE_ATTRIBUTES) as number;
|
||||
for (let i = 0; i < m; i++) {
|
||||
const info = gl.getActiveAttrib(prog, i);
|
||||
if (info) a[info.name] = gl.getAttribLocation(prog, info.name);
|
||||
}
|
||||
return { prog, u, a };
|
||||
}
|
||||
|
||||
/** How many region layers (a country at one detail) stay on the GPU at most. */
|
||||
const MAX_REGION_LAYERS = 64;
|
||||
|
||||
export class GlobeRenderer {
|
||||
readonly gl: WebGL2RenderingContext;
|
||||
private fillP: Program;
|
||||
private pickP: Program;
|
||||
private lineP: Program;
|
||||
private skyP: Program;
|
||||
private rimP: Program;
|
||||
private quad: WebGLVertexArrayObject;
|
||||
private cornerBuf: WebGLBuffer;
|
||||
private statusTex: WebGLTexture;
|
||||
private fxTex: WebGLTexture;
|
||||
private status = new Uint8Array(MAX_FEATURES * 4);
|
||||
private fx = new Uint8Array(MAX_FEATURES * 4);
|
||||
private statusDirty = true;
|
||||
private ocean: GpuFill | null = null;
|
||||
private worlds = new Map<string, GpuLayer>();
|
||||
private regions = new Map<string, GpuLayer>();
|
||||
private arcs = new Map<ArcLayer, GpuLines>();
|
||||
private outline: { src: LineMesh; gpu: GpuLines } | null = null;
|
||||
private pickFbo: WebGLFramebuffer | null = null;
|
||||
private pickTex: WebGLTexture | null = null;
|
||||
private pickSize = [0, 0];
|
||||
private last: DrawState | null = null;
|
||||
|
||||
constructor(canvas: HTMLCanvasElement) {
|
||||
const gl = canvas.getContext('webgl2', {
|
||||
antialias: true,
|
||||
alpha: false,
|
||||
premultipliedAlpha: false,
|
||||
preserveDrawingBuffer: false,
|
||||
});
|
||||
if (!gl) throw new Error('WebGL2 unavailable');
|
||||
this.gl = gl;
|
||||
this.fillP = link(gl, FILL_VS, FILL_FS);
|
||||
this.pickP = link(gl, FILL_VS, PICK_FS);
|
||||
this.lineP = link(gl, LINE_VS, LINE_FS);
|
||||
this.skyP = link(gl, SKY_VS, SKY_FS);
|
||||
this.rimP = link(gl, SKY_VS, RIM_FS);
|
||||
this.quad = this.makeQuad();
|
||||
this.cornerBuf = gl.createBuffer() as WebGLBuffer;
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, this.cornerBuf);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, -1, 1, -1, 0, 1, 0, 1, 1, -1, 1, 1]), gl.STATIC_DRAW);
|
||||
this.statusTex = this.makeTex();
|
||||
this.fxTex = this.makeTex();
|
||||
}
|
||||
|
||||
private makeTex(): WebGLTexture {
|
||||
const gl = this.gl;
|
||||
const t = gl.createTexture() as WebGLTexture;
|
||||
gl.bindTexture(gl.TEXTURE_2D, t);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, STATUS_TEX_W, STATUS_TEX_H, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
||||
return t;
|
||||
}
|
||||
|
||||
private makeQuad(): WebGLVertexArrayObject {
|
||||
const gl = this.gl;
|
||||
const vao = gl.createVertexArray() as WebGLVertexArrayObject;
|
||||
gl.bindVertexArray(vao);
|
||||
const b = gl.createBuffer();
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, b);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);
|
||||
for (const p of [this.skyP, this.rimP]) {
|
||||
const loc = p.a.a_pos;
|
||||
if (loc === undefined) continue;
|
||||
gl.enableVertexAttribArray(loc);
|
||||
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
|
||||
}
|
||||
gl.bindVertexArray(null);
|
||||
return vao;
|
||||
}
|
||||
|
||||
/** rgba: colour + fill strength. fx: hatch, reveal order (0..255), outline, spare. */
|
||||
setStatus(
|
||||
id: number,
|
||||
rgba: [number, number, number, number],
|
||||
fx: [number, number, number, number] = [0, 0, 0, 0]
|
||||
): void {
|
||||
if (id < 0 || id >= MAX_FEATURES) return;
|
||||
this.status.set(rgba, id * 4);
|
||||
this.fx.set(fx, id * 4);
|
||||
this.statusDirty = true;
|
||||
}
|
||||
|
||||
clearStatus(from: number, to: number): void {
|
||||
this.status.fill(0, from * 4, to * 4);
|
||||
this.fx.fill(0, from * 4, to * 4);
|
||||
this.statusDirty = true;
|
||||
}
|
||||
|
||||
private uploadFill(m: FillMesh): GpuFill {
|
||||
const gl = this.gl;
|
||||
const buffers: WebGLBuffer[] = [];
|
||||
const make = (data: Float32Array | Uint32Array, target: number): WebGLBuffer => {
|
||||
const b = gl.createBuffer() as WebGLBuffer;
|
||||
gl.bindBuffer(target, b);
|
||||
gl.bufferData(target, data, gl.STATIC_DRAW);
|
||||
buffers.push(b);
|
||||
return b;
|
||||
};
|
||||
const llB = make(m.ll, gl.ARRAY_BUFFER);
|
||||
const refB = make(m.ref, gl.ARRAY_BUFFER);
|
||||
const fidB = make(m.fid, gl.ARRAY_BUFFER);
|
||||
const idxB = make(m.index, gl.ELEMENT_ARRAY_BUFFER);
|
||||
const vaoFor = (p: Program): WebGLVertexArrayObject => {
|
||||
const vao = gl.createVertexArray() as WebGLVertexArrayObject;
|
||||
gl.bindVertexArray(vao);
|
||||
const bind = (name: string, buf: WebGLBuffer, size: number): void => {
|
||||
const loc = p.a[name];
|
||||
if (loc === undefined || loc < 0) return;
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
|
||||
gl.enableVertexAttribArray(loc);
|
||||
gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 0, 0);
|
||||
};
|
||||
bind('a_ll', llB, 2);
|
||||
bind('a_ref', refB, 2);
|
||||
bind('a_fid', fidB, 1);
|
||||
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, idxB);
|
||||
gl.bindVertexArray(null);
|
||||
return vao;
|
||||
};
|
||||
return { vao: vaoFor(this.fillP), pickVao: vaoFor(this.pickP), count: m.index.length, buffers };
|
||||
}
|
||||
|
||||
private uploadLines(seg: Float32Array, count: number, stride: 4 | 8): GpuLines {
|
||||
const gl = this.gl;
|
||||
const p = this.lineP;
|
||||
const vao = gl.createVertexArray() as WebGLVertexArrayObject;
|
||||
gl.bindVertexArray(vao);
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, this.cornerBuf);
|
||||
gl.enableVertexAttribArray(p.a.a_corner);
|
||||
gl.vertexAttribPointer(p.a.a_corner, 2, gl.FLOAT, false, 0, 0);
|
||||
const b = gl.createBuffer() as WebGLBuffer;
|
||||
gl.bindBuffer(gl.ARRAY_BUFFER, b);
|
||||
gl.bufferData(gl.ARRAY_BUFFER, seg, gl.STATIC_DRAW);
|
||||
const bytes = stride * 4;
|
||||
const attr = (name: string, offset: number): void => {
|
||||
const loc = p.a[name];
|
||||
if (loc === undefined || loc < 0) return;
|
||||
gl.enableVertexAttribArray(loc);
|
||||
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, bytes, offset);
|
||||
gl.vertexAttribDivisor(loc, 1);
|
||||
};
|
||||
attr('a_a', 0);
|
||||
attr('a_b', 8);
|
||||
if (stride === 8) {
|
||||
attr('a_h', 16);
|
||||
attr('a_s', 24);
|
||||
}
|
||||
gl.bindVertexArray(null);
|
||||
return { vao, count, buffers: [b] };
|
||||
}
|
||||
|
||||
private uploadLayer(l: BuiltLayer): GpuLayer {
|
||||
return {
|
||||
fill: this.uploadFill(l.fill),
|
||||
coast: this.uploadLines(l.coast.seg, l.coast.count, 4),
|
||||
borders: this.uploadLines(l.borders.seg, l.borders.count, 4),
|
||||
};
|
||||
}
|
||||
|
||||
private freeLayer(g: GpuLayer | null): void {
|
||||
if (!g) return;
|
||||
const gl = this.gl;
|
||||
for (const part of [g.fill, g.coast, g.borders]) {
|
||||
for (const b of part.buffers) gl.deleteBuffer(b);
|
||||
gl.deleteVertexArray(part.vao);
|
||||
}
|
||||
gl.deleteVertexArray(g.fill.pickVao);
|
||||
}
|
||||
|
||||
setOcean(m: FillMesh): void {
|
||||
this.ocean = this.uploadFill(m);
|
||||
}
|
||||
|
||||
setWorld(key: string, l: BuiltLayer): void {
|
||||
const next = this.uploadLayer(l);
|
||||
this.freeLayer(this.worlds.get(key) ?? null);
|
||||
this.worlds.set(key, next);
|
||||
}
|
||||
|
||||
hasWorld(key: string): boolean {
|
||||
return this.worlds.has(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a country's regions on the GPU. Past MAX_REGION_LAYERS the ones held
|
||||
* longest go (never one of `inUse`, the layers drawn now): a long session
|
||||
* over many countries would otherwise keep every region it ever touched.
|
||||
* Gone ones come back from the browser cache when they are wanted again.
|
||||
*/
|
||||
setRegion(key: string, l: BuiltLayer, inUse: ReadonlySet<string> = new Set()): void {
|
||||
const next = this.uploadLayer(l);
|
||||
this.freeLayer(this.regions.get(key) ?? null);
|
||||
this.regions.delete(key);
|
||||
this.regions.set(key, next);
|
||||
for (const old of [...this.regions.keys()]) {
|
||||
if (this.regions.size <= MAX_REGION_LAYERS) break;
|
||||
if (old === key || inUse.has(old)) continue;
|
||||
this.freeLayer(this.regions.get(old) ?? null);
|
||||
this.regions.delete(old);
|
||||
}
|
||||
}
|
||||
|
||||
/** Marks a region layer as just used, so it is the last to go. */
|
||||
touchRegion(key: string): void {
|
||||
const layer = this.regions.get(key);
|
||||
if (!layer) return;
|
||||
this.regions.delete(key);
|
||||
this.regions.set(key, layer);
|
||||
}
|
||||
|
||||
hasRegion(key: string): boolean {
|
||||
return this.regions.has(key);
|
||||
}
|
||||
|
||||
private arcGpu(a: ArcLayer): GpuLines {
|
||||
let g = this.arcs.get(a);
|
||||
if (!g) {
|
||||
g = this.uploadLines(a.data, a.count, 8);
|
||||
this.arcs.set(a, g);
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
/** Frees the arc buffers of layers no longer drawn. */
|
||||
private pruneArcs(keep: ArcLayer[]): void {
|
||||
for (const [k, v] of this.arcs) {
|
||||
if (keep.includes(k)) continue;
|
||||
for (const b of v.buffers) this.gl.deleteBuffer(b);
|
||||
this.gl.deleteVertexArray(v.vao);
|
||||
this.arcs.delete(k);
|
||||
}
|
||||
}
|
||||
|
||||
private outlineGpu(m: LineMesh): GpuLines {
|
||||
if (this.outline?.src === m) return this.outline.gpu;
|
||||
if (this.outline) {
|
||||
for (const b of this.outline.gpu.buffers) this.gl.deleteBuffer(b);
|
||||
this.gl.deleteVertexArray(this.outline.gpu.vao);
|
||||
}
|
||||
const gpu = this.uploadLines(m.seg, m.count, 4);
|
||||
this.outline = { src: m, gpu };
|
||||
return gpu;
|
||||
}
|
||||
|
||||
private setProjection(p: Program, s: DrawState): void {
|
||||
const gl = this.gl;
|
||||
const f = s.frame;
|
||||
gl.uniform2f(p.u.u_center, f.centerLon, f.centerLat);
|
||||
gl.uniform1f(p.u.u_t, f.t);
|
||||
gl.uniform1f(p.u.u_scale, f.scale * s.dpr);
|
||||
gl.uniform2f(p.u.u_origin, f.originX * s.dpr, f.originY * s.dpr);
|
||||
gl.uniform2f(p.u.u_viewport, s.width * s.dpr, s.height * s.dpr);
|
||||
}
|
||||
|
||||
private get world(): GpuLayer | null {
|
||||
return this.last ? (this.worlds.get(this.last.worldKey) ?? null) : null;
|
||||
}
|
||||
|
||||
draw(s: DrawState): void {
|
||||
const gl = this.gl;
|
||||
this.last = s;
|
||||
const W = Math.round(s.width * s.dpr);
|
||||
const H = Math.round(s.height * s.dpr);
|
||||
gl.viewport(0, 0, W, H);
|
||||
gl.disable(gl.DEPTH_TEST);
|
||||
gl.enable(gl.BLEND);
|
||||
gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
|
||||
const th = s.theme;
|
||||
const f = s.frame;
|
||||
|
||||
// Sky
|
||||
gl.useProgram(this.skyP.prog);
|
||||
gl.uniform2f(this.skyP.u.u_viewport, W, H);
|
||||
gl.uniform2f(this.skyP.u.u_globe, f.originX * s.dpr, f.originY * s.dpr);
|
||||
gl.uniform1f(this.skyP.u.u_radius, f.scale * s.dpr);
|
||||
gl.uniform1f(this.skyP.u.u_t, f.t);
|
||||
gl.uniform1f(this.skyP.u.u_time, s.time);
|
||||
gl.uniform2f(this.skyP.u.u_drift, f.centerLon, f.centerLat);
|
||||
gl.uniform3fv(this.skyP.u.u_space0, th.space0);
|
||||
gl.uniform3fv(this.skyP.u.u_space1, th.space1);
|
||||
gl.uniform3fv(this.skyP.u.u_glow, th.glow);
|
||||
gl.uniform1f(this.skyP.u.u_dark, th.dark ? 1 : 0);
|
||||
gl.bindVertexArray(this.quad);
|
||||
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
||||
|
||||
if (this.statusDirty) {
|
||||
gl.bindTexture(gl.TEXTURE_2D, this.statusTex);
|
||||
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, STATUS_TEX_W, STATUS_TEX_H, gl.RGBA, gl.UNSIGNED_BYTE, this.status);
|
||||
gl.bindTexture(gl.TEXTURE_2D, this.fxTex);
|
||||
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, STATUS_TEX_W, STATUS_TEX_H, gl.RGBA, gl.UNSIGNED_BYTE, this.fx);
|
||||
this.statusDirty = false;
|
||||
}
|
||||
|
||||
// Fills
|
||||
const p = this.fillP;
|
||||
gl.useProgram(p.prog);
|
||||
this.setProjection(p, s);
|
||||
gl.activeTexture(gl.TEXTURE0);
|
||||
gl.bindTexture(gl.TEXTURE_2D, this.statusTex);
|
||||
gl.uniform1i(p.u.u_status, 0);
|
||||
gl.activeTexture(gl.TEXTURE1);
|
||||
gl.bindTexture(gl.TEXTURE_2D, this.fxTex);
|
||||
gl.uniform1i(p.u.u_fx, 1);
|
||||
gl.uniform3fv(p.u.u_land, th.land);
|
||||
gl.uniform3fv(p.u.u_ocean, th.ocean);
|
||||
gl.uniform3fv(p.u.u_oceanDeep, th.oceanDeep);
|
||||
gl.uniform1f(p.u.u_time, s.time);
|
||||
gl.uniform1f(p.u.u_revealStart, s.revealStart);
|
||||
gl.uniform1i(p.u.u_hover, s.hover);
|
||||
gl.uniform1i(p.u.u_selected, s.selected);
|
||||
gl.uniform1i(p.u.u_inkId, s.ink ? s.ink.id : -1);
|
||||
gl.uniform2f(p.u.u_inkLL, s.ink ? (s.ink.lon * Math.PI) / 180 : 0, s.ink ? (s.ink.lat * Math.PI) / 180 : 0);
|
||||
gl.uniform1f(p.u.u_inkR, s.ink ? s.ink.radius : 0);
|
||||
gl.uniform1f(p.u.u_dpr, s.dpr);
|
||||
gl.uniform1f(p.u.u_layerAlpha, 1);
|
||||
gl.uniform3fv(p.u.u_sun, s.sun);
|
||||
gl.uniform1f(p.u.u_night, s.night);
|
||||
gl.uniform1f(p.u.u_shadeMin, th.dark ? 0.42 : 0.82);
|
||||
// Dark mode lights a hovered country up; on near-white land in light mode it tints it blue.
|
||||
if (th.dark) gl.uniform4f(p.u.u_hoverTint, 1, 1, 1, 0.09);
|
||||
else gl.uniform4f(p.u.u_hoverTint, 0.42, 0.56, 0.82, 0.16);
|
||||
if (this.ocean) {
|
||||
gl.uniform1i(p.u.u_mode, 1);
|
||||
gl.bindVertexArray(this.ocean.vao);
|
||||
gl.drawElements(gl.TRIANGLES, this.ocean.count, gl.UNSIGNED_INT, 0);
|
||||
}
|
||||
const regionsOn = s.regionAlpha > 0.001 && s.regionKeys.some((k) => this.regions.has(k));
|
||||
if (this.world) {
|
||||
gl.uniform1i(p.u.u_mode, 0);
|
||||
gl.uniform1f(p.u.u_dimBase, 1);
|
||||
gl.uniform1f(p.u.u_regionFade, s.regionAlpha);
|
||||
gl.bindVertexArray(this.world.fill.vao);
|
||||
gl.drawElements(gl.TRIANGLES, this.world.fill.count, gl.UNSIGNED_INT, 0);
|
||||
}
|
||||
if (regionsOn) {
|
||||
gl.uniform1i(p.u.u_mode, 2);
|
||||
gl.uniform1f(p.u.u_layerAlpha, s.regionAlpha);
|
||||
for (const k of s.regionKeys) {
|
||||
const r = this.regions.get(k);
|
||||
if (!r) continue;
|
||||
gl.bindVertexArray(r.fill.vao);
|
||||
gl.drawElements(gl.TRIANGLES, r.fill.count, gl.UNSIGNED_INT, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Lines
|
||||
const lp = this.lineP;
|
||||
gl.useProgram(lp.prog);
|
||||
this.setProjection(lp, s);
|
||||
gl.uniform1f(lp.u.u_lift, 0);
|
||||
gl.uniform1f(lp.u.u_progress, 2);
|
||||
gl.uniform1f(lp.u.u_glow, 0);
|
||||
const lines = (g: GpuLines, color: number[], width: number): void => {
|
||||
if (!g.count) return;
|
||||
gl.uniform4fv(lp.u.u_color, color);
|
||||
gl.uniform1f(lp.u.u_width, width * s.dpr);
|
||||
gl.bindVertexArray(g.vao);
|
||||
gl.vertexAttrib2f(lp.a.a_h, 0, 0);
|
||||
gl.vertexAttrib2f(lp.a.a_s, 0, 0);
|
||||
gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, g.count);
|
||||
};
|
||||
if (regionsOn) {
|
||||
const c = [...th.regionBorder];
|
||||
c[3] *= s.regionAlpha;
|
||||
for (const k of s.regionKeys) {
|
||||
const r = this.regions.get(k);
|
||||
if (r) lines(r.borders, c, 0.7);
|
||||
}
|
||||
}
|
||||
if (this.world) {
|
||||
lines(this.world.borders, th.border, 0.8);
|
||||
lines(this.world.coast, th.coast, 0.9);
|
||||
}
|
||||
if (s.selectedOutline) {
|
||||
gl.uniform1f(lp.u.u_glow, 0.55);
|
||||
lines(this.outlineGpu(s.selectedOutline), th.selection, 1.8);
|
||||
gl.uniform1f(lp.u.u_glow, 0);
|
||||
}
|
||||
if (this.arcs.size > s.arcs.length) this.pruneArcs(s.arcs);
|
||||
if (s.arcs.length) {
|
||||
gl.uniform1f(lp.u.u_lift, 1);
|
||||
gl.uniform1f(lp.u.u_progress, s.arcProgress);
|
||||
for (const a of s.arcs) {
|
||||
const g = this.arcGpu(a);
|
||||
gl.uniform4fv(lp.u.u_color, th.arc);
|
||||
gl.uniform1f(lp.u.u_width, a.width * s.dpr);
|
||||
gl.uniform1f(lp.u.u_glow, 0.35);
|
||||
gl.bindVertexArray(g.vao);
|
||||
gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, g.count);
|
||||
}
|
||||
gl.uniform1f(lp.u.u_lift, 0);
|
||||
}
|
||||
|
||||
// Rim light over the limb
|
||||
gl.useProgram(this.rimP.prog);
|
||||
gl.uniform2f(this.rimP.u.u_viewport, W, H);
|
||||
gl.uniform2f(this.rimP.u.u_globe, f.originX * s.dpr, f.originY * s.dpr);
|
||||
gl.uniform1f(this.rimP.u.u_radius, f.scale * s.dpr);
|
||||
gl.uniform1f(this.rimP.u.u_t, f.t);
|
||||
gl.uniform3fv(this.rimP.u.u_glow, th.glow);
|
||||
gl.bindVertexArray(this.quad);
|
||||
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
|
||||
gl.bindVertexArray(null);
|
||||
}
|
||||
|
||||
/** Feature id under a CSS-pixel position, or -1. Renders an id pass of the last frame. */
|
||||
pick(x: number, y: number, includeRegions: boolean): number {
|
||||
const s = this.last;
|
||||
if (!s) return -1;
|
||||
const gl = this.gl;
|
||||
const W = Math.round(s.width * s.dpr);
|
||||
const H = Math.round(s.height * s.dpr);
|
||||
if (!this.pickFbo || this.pickSize[0] !== W || this.pickSize[1] !== H) {
|
||||
if (this.pickTex) gl.deleteTexture(this.pickTex);
|
||||
if (this.pickFbo) gl.deleteFramebuffer(this.pickFbo);
|
||||
this.pickTex = gl.createTexture();
|
||||
gl.bindTexture(gl.TEXTURE_2D, this.pickTex);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, W, H, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
|
||||
this.pickFbo = gl.createFramebuffer();
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, this.pickFbo);
|
||||
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.pickTex, 0);
|
||||
this.pickSize = [W, H];
|
||||
}
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, this.pickFbo);
|
||||
gl.viewport(0, 0, W, H);
|
||||
gl.disable(gl.BLEND);
|
||||
gl.clearColor(0, 0, 0, 0);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT);
|
||||
const p = this.pickP;
|
||||
gl.useProgram(p.prog);
|
||||
this.setProjection(p, s);
|
||||
if (this.world) {
|
||||
gl.bindVertexArray(this.world.fill.pickVao);
|
||||
gl.drawElements(gl.TRIANGLES, this.world.fill.count, gl.UNSIGNED_INT, 0);
|
||||
}
|
||||
if (includeRegions) {
|
||||
for (const k of s.regionKeys) {
|
||||
const r = this.regions.get(k);
|
||||
if (!r) continue;
|
||||
gl.bindVertexArray(r.fill.pickVao);
|
||||
gl.drawElements(gl.TRIANGLES, r.fill.count, gl.UNSIGNED_INT, 0);
|
||||
}
|
||||
}
|
||||
const px = new Uint8Array(4);
|
||||
gl.readPixels(Math.round(x * s.dpr), H - Math.round(y * s.dpr) - 1, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px);
|
||||
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
|
||||
gl.bindVertexArray(null);
|
||||
gl.enable(gl.BLEND);
|
||||
const id = px[0] + (px[1] << 8) + (px[2] << 16);
|
||||
return id - 1;
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
const gl = this.gl;
|
||||
for (const w of this.worlds.values()) this.freeLayer(w);
|
||||
this.worlds.clear();
|
||||
for (const r of this.regions.values()) this.freeLayer(r);
|
||||
this.regions.clear();
|
||||
// The context is left alive: React mounts twice in development and the
|
||||
// second engine takes over the same canvas.
|
||||
void gl;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { forwardRef, useImperativeHandle, useMemo, useRef } from 'react';
|
||||
import type { GlobeEngine } from './GlobeEngine';
|
||||
import { moonPhase, smoothstep } from './globeMath';
|
||||
|
||||
export interface GlobeSkyHandle {
|
||||
layout: (engine: GlobeEngine) => void;
|
||||
/** A shooting star across the sky, for the moment something is marked. */
|
||||
shootingStar: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* What hangs in the sky around the globe: the moon in its real phase, and the
|
||||
* shooting star that crosses when a country is marked. The moon is placed per
|
||||
* frame without React rendering.
|
||||
*/
|
||||
const GlobeSky = forwardRef<GlobeSkyHandle, { dark: boolean }>(function GlobeSky({ dark }, ref) {
|
||||
const moonRef = useRef<HTMLDivElement>(null);
|
||||
const starHost = useRef<HTMLDivElement>(null);
|
||||
const phase = useMemo(() => moonPhase(new Date()), []);
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
layout(engine: GlobeEngine) {
|
||||
const f = engine.frame;
|
||||
const { width, height } = engine.vp;
|
||||
const fade = 1 - smoothstep(0.05, 0.6, f.t);
|
||||
if (!moonRef.current) return;
|
||||
if (!dark) {
|
||||
moonRef.current.style.opacity = '0';
|
||||
return;
|
||||
}
|
||||
const d = Math.max(f.scale * 1.75, Math.min(width, height) * 0.42);
|
||||
const x = f.originX + Math.cos(-0.65) * d * 1.25;
|
||||
const y = f.originY + Math.sin(-0.65) * d * 0.62;
|
||||
moonRef.current.style.transform = `translate3d(${x.toFixed(1)}px, ${y.toFixed(1)}px, 0) translate(-50%, -50%)`;
|
||||
moonRef.current.style.opacity = String(fade * 0.95);
|
||||
},
|
||||
shootingStar() {
|
||||
const host = starHost.current;
|
||||
if (!host || !dark || window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
|
||||
const el = document.createElement('div');
|
||||
el.className = 'ag-shooting-star';
|
||||
el.style.left = `${host.clientWidth * (0.55 + Math.random() * 0.35)}px`;
|
||||
el.style.top = `${host.clientHeight * (0.05 + Math.random() * 0.25)}px`;
|
||||
host.appendChild(el);
|
||||
el.animate(
|
||||
[
|
||||
{ transform: 'rotate(-28deg) translateX(0) scaleX(0.2)', opacity: 0 },
|
||||
{ transform: 'rotate(-28deg) translateX(-90px) scaleX(1)', opacity: 1, offset: 0.25 },
|
||||
{ transform: 'rotate(-28deg) translateX(-420px) scaleX(0.6)', opacity: 0 },
|
||||
],
|
||||
{ duration: 1100, easing: 'cubic-bezier(.2,.6,.3,1)' }
|
||||
).onfinish = () => el.remove();
|
||||
},
|
||||
}),
|
||||
[dark]
|
||||
);
|
||||
|
||||
// The lit part of the moon: the disc with an ellipse carving the shadow.
|
||||
const lit = phase.lit;
|
||||
const waxing = phase.phase < 0.5;
|
||||
const k = Math.abs(1 - 2 * lit);
|
||||
const shadowPath = `M 14 1 A 13 13 0 0 ${waxing ? 0 : 1} 14 27 A ${(13 * k).toFixed(2)} 13 0 0 ${lit > 0.5 === waxing ? 1 : 0} 14 1 Z`;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div ref={starHost} aria-hidden="true" className="pointer-events-none absolute inset-0 overflow-hidden" />
|
||||
<div
|
||||
ref={moonRef}
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute start-0 top-0"
|
||||
style={{ filter: 'drop-shadow(0 0 14px rgb(220 230 255 / 0.35))' }}
|
||||
>
|
||||
<svg width="28" height="28" viewBox="0 0 28 28">
|
||||
<defs>
|
||||
<radialGradient id="ag-moon" cx="0.4" cy="0.35" r="0.75">
|
||||
<stop offset="0" stopColor="rgb(244 246 251)" />
|
||||
<stop offset="1" stopColor="rgb(170 179 197)" />
|
||||
</radialGradient>
|
||||
</defs>
|
||||
<circle cx="14" cy="14" r="13" fill="url(#ag-moon)" />
|
||||
<circle cx="10" cy="10" r="2.4" fill="rgb(0 0 0)" opacity="0.07" />
|
||||
<circle cx="17" cy="17" r="3.2" fill="rgb(0 0 0)" opacity="0.06" />
|
||||
<path d={shadowPath} fill="rgb(7 10 20)" opacity="0.88" />
|
||||
</svg>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
export default GlobeSky;
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import React from 'react';
|
||||
|
||||
export interface GlobeStat {
|
||||
key: string;
|
||||
icon: LucideIcon;
|
||||
value: React.ReactNode;
|
||||
label: string;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
const CARD =
|
||||
'ag-liquid-card flex w-[132px] flex-none flex-col justify-between gap-2 rounded-[14px] px-3 py-2.5 text-start transition-colors';
|
||||
|
||||
/**
|
||||
* The Atlas numbers in the bottom corner: the frosted card every floating map
|
||||
* control in TREK uses, holding one small card per number (badge in badge).
|
||||
* A number with an action is a button.
|
||||
*/
|
||||
export default function GlobeStatsBar({
|
||||
stats,
|
||||
className = 'bottom-[22px] start-[22px] max-w-[calc(100%-120px)]',
|
||||
}: {
|
||||
stats: GlobeStat[];
|
||||
className?: string;
|
||||
}): React.ReactElement {
|
||||
return (
|
||||
<div
|
||||
className={`ag-liquid pointer-events-auto absolute flex gap-1.5 overflow-x-auto rounded-[20px] p-1.5 ${className}`}
|
||||
style={{ scrollbarWidth: 'none' }}
|
||||
>
|
||||
{stats.map((s) => {
|
||||
const Icon = s.icon;
|
||||
const body = (
|
||||
<>
|
||||
<span className="flex items-start justify-between gap-2">
|
||||
<span className="text-title font-semibold tabular-nums leading-none text-content">{s.value}</span>
|
||||
<Icon size={16} strokeWidth={1.9} className="mt-0.5 flex-none text-content-muted" />
|
||||
</span>
|
||||
<span className="whitespace-nowrap text-caption text-content-muted">{s.label}</span>
|
||||
</>
|
||||
);
|
||||
return s.onClick ? (
|
||||
<button key={s.key} type="button" onClick={s.onClick} className={CARD}>
|
||||
{body}
|
||||
</button>
|
||||
) : (
|
||||
<div key={s.key} className={CARD}>
|
||||
{body}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
/*
|
||||
* The globe Atlas chrome: glass capsules, labels, the country card.
|
||||
* The globe is its own night sky, so the glass is tuned against it rather than
|
||||
* against the app surfaces. The scene is a night sky in both modes; the controls
|
||||
* on top (search, zoom, stats) follow the app's light or dark mode.
|
||||
*/
|
||||
.atlas-globe {
|
||||
--ag-glass: linear-gradient(180deg, rgb(255 255 255 / 0.11), rgb(255 255 255 / 0.04));
|
||||
--ag-glass-solid: rgb(16 20 34 / 0.9);
|
||||
--ag-edge: rgb(255 255 255 / 0.13);
|
||||
--ag-edge-hi: rgb(255 255 255 / 0.3);
|
||||
--ag-hi: inset 0 1px 0 rgb(255 255 255 / 0.22);
|
||||
--ag-shadow: 0 12px 32px rgb(0 0 0 / 0.38);
|
||||
--ag-ink: rgb(238 242 255);
|
||||
--ag-muted: rgb(150 160 182);
|
||||
--ag-faint: rgb(100 110 132);
|
||||
--ag-accent: rgb(125 211 252);
|
||||
--ag-mint: rgb(94 234 212);
|
||||
--ag-label: rgb(226 232 245 / 0.92);
|
||||
--ag-label-shadow: 0 1px 2px rgb(0 0 0 / 0.85), 0 0 10px rgb(0 0 0 / 0.55);
|
||||
position: relative;
|
||||
color: var(--ag-ink);
|
||||
background: rgb(3 5 12);
|
||||
}
|
||||
|
||||
html:not(.dark) .ag-btn {
|
||||
background: rgb(15 23 42 / 0.04);
|
||||
}
|
||||
|
||||
html:not(.dark) .ag-btn[data-on='1'] {
|
||||
background: rgb(37 99 235 / 0.12);
|
||||
border-color: rgb(37 99 235 / 0.4);
|
||||
}
|
||||
|
||||
html:not(.dark) .ag-bar {
|
||||
background: rgb(15 23 42 / 0.08);
|
||||
}
|
||||
|
||||
.ag-glass {
|
||||
background: var(--ag-glass);
|
||||
border: 1px solid var(--ag-edge);
|
||||
box-shadow: var(--ag-hi), var(--ag-shadow);
|
||||
backdrop-filter: blur(18px) saturate(150%);
|
||||
-webkit-backdrop-filter: blur(18px) saturate(150%);
|
||||
}
|
||||
|
||||
[data-no-transparency] .ag-glass,
|
||||
.atlas-globe[data-moving='1'] .ag-glass-big {
|
||||
backdrop-filter: none;
|
||||
-webkit-backdrop-filter: none;
|
||||
background: var(--ag-glass-solid);
|
||||
}
|
||||
|
||||
.atlas-globe-label {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
white-space: nowrap;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.01em;
|
||||
color: var(--ag-label);
|
||||
text-shadow: var(--ag-label-shadow);
|
||||
will-change: transform, opacity;
|
||||
transition: opacity 0.25s;
|
||||
}
|
||||
|
||||
.atlas-globe-label[data-region='1'] {
|
||||
font-weight: 400;
|
||||
opacity: 0.85;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
.ag-num {
|
||||
font-variant-numeric: tabular-nums;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.ag-muted {
|
||||
color: var(--ag-muted);
|
||||
}
|
||||
|
||||
.ag-faint {
|
||||
color: var(--ag-faint);
|
||||
}
|
||||
|
||||
.ag-btn {
|
||||
border: 1px solid var(--ag-edge);
|
||||
background: rgb(255 255 255 / 0.06);
|
||||
transition:
|
||||
border-color 0.2s,
|
||||
background 0.2s;
|
||||
}
|
||||
|
||||
.ag-btn:hover {
|
||||
border-color: var(--ag-edge-hi);
|
||||
}
|
||||
|
||||
.ag-btn[data-on='1'] {
|
||||
background: rgb(125 211 252 / 0.18);
|
||||
border-color: rgb(125 211 252 / 0.5);
|
||||
}
|
||||
|
||||
.ag-bar {
|
||||
height: 6px;
|
||||
border-radius: 99px;
|
||||
background: rgb(255 255 255 / 0.09);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.ag-bar > i {
|
||||
display: block;
|
||||
height: 100%;
|
||||
border-radius: 99px;
|
||||
background: linear-gradient(90deg, var(--ag-accent), var(--ag-mint));
|
||||
box-shadow: 0 0 12px rgb(125 211 252 / 0.55);
|
||||
transition: width 0.9s cubic-bezier(0.2, 0.9, 0.2, 1);
|
||||
}
|
||||
|
||||
/* A badge in the Passport: a glass medal that tilts towards the pointer and flips. */
|
||||
.ag-medal {
|
||||
perspective: 600px;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.ag-medal[data-earned='1'] {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.ag-medal-body {
|
||||
position: relative;
|
||||
display: block;
|
||||
width: 92px;
|
||||
height: 104px;
|
||||
transform-style: preserve-3d;
|
||||
transform: rotateX(var(--rx, 0deg)) rotateY(calc(var(--ry, 0deg) + var(--flip, 0deg)));
|
||||
transition: transform 0.7s cubic-bezier(0.2, 0.9, 0.25, 1.1);
|
||||
}
|
||||
|
||||
.ag-medal[data-flipped='1'] {
|
||||
--flip: 180deg;
|
||||
}
|
||||
|
||||
.ag-medal-face,
|
||||
.ag-medal-back {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
backface-visibility: hidden;
|
||||
}
|
||||
|
||||
.ag-medal-back {
|
||||
transform: rotateY(180deg);
|
||||
}
|
||||
|
||||
.ag-medal-shine {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
clip-path: polygon(50% 0, 100% 25%, 100% 75%, 50% 100%, 0 75%, 0 25%);
|
||||
background:
|
||||
radial-gradient(60% 45% at var(--mx, 30%) var(--my, 20%), rgb(255 255 255 / 0.5), rgb(255 255 255 / 0) 60%),
|
||||
linear-gradient(
|
||||
115deg,
|
||||
rgb(125 211 252 / 0) 30%,
|
||||
rgb(167 139 250 / 0.22) 45%,
|
||||
rgb(94 234 212 / 0.2) 55%,
|
||||
rgb(125 211 252 / 0) 70%
|
||||
);
|
||||
mix-blend-mode: screen;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.ag-medal[data-earned='0'] .ag-medal-shine {
|
||||
opacity: 0.25;
|
||||
}
|
||||
|
||||
.ag-shooting-star {
|
||||
position: absolute;
|
||||
width: 140px;
|
||||
height: 2px;
|
||||
border-radius: 99px;
|
||||
transform-origin: right center;
|
||||
background: linear-gradient(90deg, rgb(255 255 255 / 0), rgb(255 255 255 / 0.95));
|
||||
box-shadow: 0 0 10px rgb(186 230 253 / 0.8);
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ag-medal-body {
|
||||
transform: rotateY(var(--flip, 0deg));
|
||||
}
|
||||
|
||||
.ag-bar > i,
|
||||
.atlas-globe-label {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* The controls on top of the scene wear TREK's map chrome, like every floating
|
||||
* map control in the app: the sidebar surface, the app's text colours and the
|
||||
* map control shadow. Only the scene itself (sky, globe, labels) is Atlas's own.
|
||||
*/
|
||||
:root .atlas-globe.atlas-globe {
|
||||
--ag-glass: var(--sidebar-bg);
|
||||
--ag-glass-solid: var(--sidebar-bg);
|
||||
--ag-edge: var(--border-primary);
|
||||
--ag-edge-hi: var(--text-faint, var(--border-primary));
|
||||
--ag-hi: 0 0 0 0 transparent;
|
||||
--ag-shadow: 0 2px 10px rgb(0 0 0 / 0.25);
|
||||
--ag-ink: var(--text-primary);
|
||||
--ag-muted: var(--text-muted);
|
||||
--ag-faint: var(--text-faint, var(--text-muted));
|
||||
}
|
||||
|
||||
:root .atlas-globe .ag-glass {
|
||||
backdrop-filter: blur(20px) saturate(180%);
|
||||
-webkit-backdrop-filter: blur(20px) saturate(180%);
|
||||
}
|
||||
|
||||
/*
|
||||
* TREK's liquid glass (the dashboard tiles' tokens, dashboard.css) for every
|
||||
* control over the globe: shells, the stat cards inside them, the search, chips.
|
||||
*/
|
||||
.atlas-globe {
|
||||
/* Over the night sky the dashboard's glass needs more white to still read as white. */
|
||||
--glass-bg: linear-gradient(135deg, oklch(1 0 0 / 0.92) 0%, oklch(0.99 0.006 75 / 0.82) 100%);
|
||||
--glass-border: oklch(1 0 0 / 0.75);
|
||||
--glass-shadow: 0 1px 2px oklch(0.4 0.02 60 / 0.05), 0 12px 32px -14px oklch(0.3 0.02 60 / 0.2);
|
||||
--glass-highlight: inset 0 1px 0 oklch(1 0 0 / 0.8);
|
||||
--glass-blur: blur(22px) saturate(1.7);
|
||||
--glass-card: oklch(1 0 0 / 0.7);
|
||||
}
|
||||
|
||||
.dark .atlas-globe {
|
||||
--glass-bg: linear-gradient(135deg, oklch(0.31 0 0 / 0.58) 0%, oklch(0.25 0 0 / 0.42) 100%);
|
||||
--glass-border: oklch(1 0 0 / 0.1);
|
||||
--glass-shadow: 0 1px 2px oklch(0 0 0 / 0.3), 0 12px 32px -14px oklch(0 0 0 / 0.55);
|
||||
--glass-highlight: inset 0 1px 0 oklch(1 0 0 / 0.09);
|
||||
--glass-card: oklch(1 0 0 / 0.05);
|
||||
}
|
||||
|
||||
[data-no-transparency] .atlas-globe {
|
||||
--glass-bg: var(--bg-card);
|
||||
--glass-border: var(--border-primary);
|
||||
--glass-highlight: 0 0 0 0 transparent;
|
||||
--glass-blur: none;
|
||||
--glass-card: var(--bg-tertiary, var(--bg-card));
|
||||
}
|
||||
|
||||
.atlas-globe .ag-liquid {
|
||||
background: var(--glass-bg);
|
||||
border: 1px solid var(--glass-border);
|
||||
box-shadow: var(--glass-shadow), var(--glass-highlight);
|
||||
backdrop-filter: var(--glass-blur);
|
||||
-webkit-backdrop-filter: var(--glass-blur);
|
||||
}
|
||||
|
||||
.atlas-globe .ag-liquid-card {
|
||||
background: var(--glass-card);
|
||||
border: 1px solid var(--glass-border);
|
||||
box-shadow: var(--glass-highlight);
|
||||
}
|
||||
|
||||
.atlas-globe .ag-liquid-card:is(button):hover {
|
||||
background: color-mix(in oklch, var(--glass-card), var(--text-primary) 6%);
|
||||
}
|
||||
|
||||
/* A wish with coordinates pinned on the globe: a small amber disc with a star. */
|
||||
.ag-pin {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 999px;
|
||||
color: rgb(255 255 255);
|
||||
background: rgb(245 158 11);
|
||||
border: 1.5px solid rgb(255 255 255 / 0.9);
|
||||
box-shadow:
|
||||
0 2px 8px rgb(0 0 0 / 0.45),
|
||||
0 0 14px rgb(251 191 36 / 0.45);
|
||||
will-change: transform, opacity;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.ag-pin[data-reached='1'] {
|
||||
background: rgb(20 184 166);
|
||||
box-shadow:
|
||||
0 2px 8px rgb(0 0 0 / 0.45),
|
||||
0 0 14px rgb(45 212 191 / 0.45);
|
||||
}
|
||||
|
||||
/* The ring of light behind a badge that was just reached. */
|
||||
.ag-unlock-ring {
|
||||
position: absolute;
|
||||
width: 220px;
|
||||
height: 220px;
|
||||
margin-top: -36px;
|
||||
border-radius: 999px;
|
||||
background: radial-gradient(circle, rgb(125 211 252 / 0.35) 0%, rgb(167 139 250 / 0.18) 40%, transparent 70%);
|
||||
animation: ag-unlock-pulse 1.6s ease-out infinite;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@keyframes ag-unlock-pulse {
|
||||
0% {
|
||||
transform: scale(0.7);
|
||||
opacity: 0.9;
|
||||
}
|
||||
100% {
|
||||
transform: scale(1.5);
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* Country and region names over the globe. A small pool of absolutely placed
|
||||
* elements moved with transform only; the largest countries win when two
|
||||
* labels would overlap.
|
||||
*/
|
||||
import type { GlobeEngine } from './GlobeEngine';
|
||||
|
||||
export interface GlobeLabel {
|
||||
el: HTMLDivElement;
|
||||
key: string;
|
||||
}
|
||||
|
||||
interface Candidate {
|
||||
key: string;
|
||||
text: string;
|
||||
x: number;
|
||||
y: number;
|
||||
rank: number;
|
||||
region: boolean;
|
||||
fade: number;
|
||||
}
|
||||
|
||||
const MAX_LABELS = 150;
|
||||
const MAX_REGION_LABELS = 120;
|
||||
/**
|
||||
* Region names start here, well after the region fills have faded in: on a
|
||||
* phone at 14, on a wider screen, which shows far more at once, only at 18.
|
||||
*/
|
||||
const REGION_LABEL_ZOOM_PHONE = 14;
|
||||
const REGION_LABEL_ZOOM_WIDE = 18;
|
||||
/** The width below which the globe counts as on a phone, as GlobeEngine lays it out. */
|
||||
const NARROW_WIDTH = 640;
|
||||
|
||||
function minAreaFor(zoom: number): number {
|
||||
// Square degrees a country needs before its name shows at this zoom.
|
||||
return 700 / Math.pow(zoom, 2.4);
|
||||
}
|
||||
|
||||
export function placeLabels(
|
||||
host: HTMLDivElement,
|
||||
pool: GlobeLabel[],
|
||||
engine: GlobeEngine,
|
||||
labelFor: (a2: string) => string | null,
|
||||
labelRegionsOf?: (a2: string) => boolean
|
||||
): void {
|
||||
const m = engine.manifest;
|
||||
if (!m) return;
|
||||
const zoom = engine.zoom;
|
||||
const { width, height } = engine.vp;
|
||||
const cands: Candidate[] = [];
|
||||
const minArea = minAreaFor(zoom);
|
||||
const regionA = engine.regionAlpha;
|
||||
|
||||
// From the region label zoom on, every country in view with regions names them,
|
||||
// and its own name gives way (Kansas, not "United States" above it). The
|
||||
// regions nearest the middle of the view come first, the country under the
|
||||
// middle ahead of all; the collision check below keeps it from being a wall.
|
||||
const regionsOn = zoom >= (width < NARROW_WIDTH ? REGION_LABEL_ZOOM_PHONE : REGION_LABEL_ZOOM_WIDE);
|
||||
const focus = regionsOn ? centreCountry(engine) : null;
|
||||
const named = new Set<string>();
|
||||
const cx = width / 2;
|
||||
const cy = height / 2;
|
||||
if (regionsOn) {
|
||||
for (const [a2, idx] of engine.regionIndex) {
|
||||
for (const f of idx.features) {
|
||||
if (!f.anchor) continue;
|
||||
const p = engine.project(f.anchor[0], f.anchor[1]);
|
||||
if (p.visible < 0.1 || p.x < 0 || p.x > width || p.y < 0 || p.y > height) continue;
|
||||
named.add(a2);
|
||||
const near = 1 - Math.min(1, Math.hypot(p.x - cx, p.y - cy) / Math.hypot(cx, cy));
|
||||
cands.push({
|
||||
key: `${a2}:${f.code ?? f.name}`,
|
||||
text: f.nameEn ?? f.name ?? '',
|
||||
x: p.x,
|
||||
y: p.y,
|
||||
rank: (a2 === focus ? 2e7 : 1e7) + near * 1e6,
|
||||
region: true,
|
||||
fade: regionA,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const c of m.countries) {
|
||||
if (!c.a2 || !c.anchor) continue;
|
||||
if (named.has(c.a2)) continue;
|
||||
// Countries the user has been to are named earlier than the rest.
|
||||
const mine = labelRegionsOf ? labelRegionsOf(c.a2) : false;
|
||||
if (c.area < minArea * (mine ? 0.3 : 1)) continue;
|
||||
const p = engine.project(c.anchor[0], c.anchor[1]);
|
||||
if (p.visible < 0.12 || p.x < -40 || p.x > width + 40 || p.y < -20 || p.y > height + 20) continue;
|
||||
const text = labelFor(c.a2);
|
||||
if (!text) continue;
|
||||
cands.push({
|
||||
key: c.a2,
|
||||
text,
|
||||
x: p.x,
|
||||
y: p.y,
|
||||
rank: c.area * (mine ? 4 : 1) * (1 - regionA * 0.7),
|
||||
region: false,
|
||||
fade: Math.min(1, p.visible * 4) * (1 - regionA * 0.55),
|
||||
});
|
||||
}
|
||||
cands.sort((a, b) => b.rank - a.rank);
|
||||
let regionCount = 0;
|
||||
|
||||
const placed: Array<[number, number, number, number]> = [];
|
||||
const chosen: Candidate[] = [];
|
||||
for (const c of cands) {
|
||||
if (chosen.length >= MAX_LABELS) break;
|
||||
if (c.region && regionCount >= MAX_REGION_LABELS) continue;
|
||||
const w = c.text.length * (c.region ? 6.2 : 6.6) + 8;
|
||||
const h = 16;
|
||||
const box: [number, number, number, number] = [c.x - w / 2, c.y - h / 2, c.x + w / 2, c.y + h / 2];
|
||||
if (placed.some((b) => box[0] < b[2] && box[2] > b[0] && box[1] < b[3] && box[3] > b[1])) continue;
|
||||
placed.push(box);
|
||||
chosen.push(c);
|
||||
if (c.region) regionCount++;
|
||||
}
|
||||
|
||||
while (pool.length < chosen.length) {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'atlas-globe-label text-caption';
|
||||
host.appendChild(el);
|
||||
pool.push({ el, key: '' });
|
||||
}
|
||||
pool.forEach((l, i) => {
|
||||
const c = chosen[i];
|
||||
if (!c) {
|
||||
if (l.el.style.opacity !== '0') l.el.style.opacity = '0';
|
||||
return;
|
||||
}
|
||||
if (l.key !== c.key) {
|
||||
l.key = c.key;
|
||||
l.el.textContent = c.text;
|
||||
l.el.dataset.region = c.region ? '1' : '';
|
||||
}
|
||||
l.el.style.transform = `translate3d(${c.x.toFixed(1)}px, ${c.y.toFixed(1)}px, 0) translate(-50%, -50%)`;
|
||||
l.el.style.opacity = String(Math.max(0, Math.min(1, c.fade)));
|
||||
});
|
||||
}
|
||||
|
||||
/** The country whose label anchor sits nearest the middle of the view. */
|
||||
function centreCountry(engine: GlobeEngine): string | null {
|
||||
const under = engine.focusCountry();
|
||||
if (under) return engine.regionIndex.has(under) ? under : null;
|
||||
// Open water in the middle (a coast, a lake): the country with regions whose
|
||||
// label point is nearest to the middle of the view.
|
||||
const m = engine.manifest;
|
||||
if (!m) return null;
|
||||
const { width, height } = engine.vp;
|
||||
let best: string | null = null;
|
||||
let bestD = Math.min(width, height) * 0.35;
|
||||
for (const a2 of engine.regionIndex.keys()) {
|
||||
const c = m.countries.find((x) => x.a2 === a2);
|
||||
if (!c?.anchor) continue;
|
||||
const p = engine.project(c.anchor[0], c.anchor[1]);
|
||||
if (p.visible <= 0) continue;
|
||||
const d = Math.hypot(p.x - width / 2, p.y - height / 2);
|
||||
if (d < bestD) {
|
||||
bestD = d;
|
||||
best = a2;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
angularDistance,
|
||||
arcSegments,
|
||||
frameParams,
|
||||
interpolateGreatCircle,
|
||||
moonPhase,
|
||||
MORPH_END,
|
||||
MORPH_START,
|
||||
morphOf,
|
||||
projectPoint,
|
||||
sunVector,
|
||||
wrapPi,
|
||||
xSqueeze,
|
||||
type GlobeViewport,
|
||||
} from './globeMath';
|
||||
|
||||
const VP: GlobeViewport = { width: 1000, height: 800, baseRadius: 300, globeY: 400, flatY: 400 };
|
||||
|
||||
describe('globeMath', () => {
|
||||
it('wraps angles into [-pi, pi)', () => {
|
||||
expect(wrapPi(0)).toBe(0);
|
||||
expect(wrapPi(Math.PI * 3)).toBeCloseTo(-Math.PI);
|
||||
expect(wrapPi(-Math.PI * 1.5)).toBeCloseTo(Math.PI / 2);
|
||||
});
|
||||
|
||||
it('is a globe below the morph and a flat map above it', () => {
|
||||
expect(morphOf(1)).toBe(0);
|
||||
expect(morphOf(MORPH_START)).toBe(0);
|
||||
expect(morphOf(MORPH_END)).toBe(1);
|
||||
const mid = morphOf((MORPH_START + MORPH_END) / 2);
|
||||
expect(mid).toBeGreaterThan(0.4);
|
||||
expect(mid).toBeLessThan(0.6);
|
||||
});
|
||||
|
||||
it('puts the centre of the camera on the screen centre, on the globe and flat', () => {
|
||||
for (const zoom of [1, 6]) {
|
||||
const f = frameParams({ lon: 10, lat: 45, zoom }, VP);
|
||||
const p = projectPoint(10, 45, f);
|
||||
expect(p.x).toBeCloseTo(500, 3);
|
||||
expect(p.y).toBeCloseTo(400, 3);
|
||||
expect(p.visible).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it('hides the far side of the globe', () => {
|
||||
const f = frameParams({ lon: 0, lat: 0, zoom: 1 }, VP);
|
||||
expect(projectPoint(180, 0, f).visible).toBeLessThan(0);
|
||||
expect(projectPoint(60, 0, f).visible).toBeGreaterThan(0);
|
||||
// An orthographic globe: 90 degrees east sits on the limb, one radius away.
|
||||
expect(projectPoint(89.9, 0, f).x).toBeCloseTo(800, 0);
|
||||
});
|
||||
|
||||
it('keeps proportions at the centre latitude once flat', () => {
|
||||
const f = frameParams({ lon: 10, lat: 50, zoom: 8 }, VP);
|
||||
const a = projectPoint(10, 50, f);
|
||||
const east = projectPoint(11, 50, f);
|
||||
const north = projectPoint(10, 51, f);
|
||||
const dx = east.x - a.x;
|
||||
const dy = a.y - north.y;
|
||||
// One degree east is cos(50 deg) of one degree north, as on the ground.
|
||||
expect(dx / dy).toBeCloseTo(Math.cos((50 * Math.PI) / 180), 2);
|
||||
expect(xSqueeze(f)).toBeCloseTo(Math.cos((50 * Math.PI) / 180), 3);
|
||||
});
|
||||
|
||||
it('does not tear a shape across the back of the globe', () => {
|
||||
const f = frameParams({ lon: 0, lat: 0, zoom: 1 }, VP);
|
||||
// Both sides of the antimeridian, unwrapped against one reference, stay apart by
|
||||
// their real distance rather than flipping to opposite screen edges.
|
||||
const a = projectPoint(179, 10, f, 179, 10);
|
||||
const b = projectPoint(-179, 10, f, 179, 10);
|
||||
expect(Math.abs(a.x - b.x)).toBeLessThan(20);
|
||||
});
|
||||
|
||||
it('measures great circles', () => {
|
||||
expect(angularDistance(0, 0, 90, 0)).toBeCloseTo(Math.PI / 2);
|
||||
const [lon, lat] = interpolateGreatCircle(0, 0, 90, 0, 0.5);
|
||||
expect(lon).toBeCloseTo(45);
|
||||
expect(lat).toBeCloseTo(0);
|
||||
});
|
||||
|
||||
it('cuts an arc into lifted, ordered segments', () => {
|
||||
const { data, count } = arcSegments([{ a: [8.57, 50.03], b: [-73.78, 40.64] }], 10);
|
||||
expect(count).toBe(10);
|
||||
// Lift is zero at both airports and highest in the middle.
|
||||
expect(data[4]).toBe(0);
|
||||
expect(data[(count - 1) * 8 + 5]).toBeCloseTo(0, 6);
|
||||
expect(data[5 * 8 + 4]).toBeGreaterThan(data[1 * 8 + 4]);
|
||||
// Progress runs from 0 to 1.
|
||||
expect(data[6]).toBe(0);
|
||||
expect(data[(count - 1) * 8 + 7]).toBe(1);
|
||||
});
|
||||
|
||||
it('points the sun at the right hemisphere through the year', () => {
|
||||
const june = sunVector(new Date(Date.UTC(2026, 5, 21, 12)));
|
||||
const december = sunVector(new Date(Date.UTC(2026, 11, 21, 12)));
|
||||
expect(Math.hypot(...june)).toBeCloseTo(1);
|
||||
expect(june[2]).toBeGreaterThan(0.38);
|
||||
expect(december[2]).toBeLessThan(-0.38);
|
||||
// Around noon UTC the sun stands near the Greenwich meridian.
|
||||
const lon = (Math.atan2(june[1], june[0]) * 180) / Math.PI;
|
||||
expect(Math.abs(lon)).toBeLessThan(10);
|
||||
});
|
||||
|
||||
it('knows the moon phase', () => {
|
||||
const full = moonPhase(new Date(Date.UTC(2026, 0, 3, 10)));
|
||||
expect(full.lit).toBeGreaterThan(0.95);
|
||||
const fresh = moonPhase(new Date(Date.UTC(2026, 0, 18, 19)));
|
||||
expect(fresh.lit).toBeLessThan(0.05);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* The Atlas globe projection, in plain numbers. The vertex shaders in
|
||||
* globeShaders.ts run the same formula on the GPU; this copy places labels,
|
||||
* hit-tests the camera and is what the unit tests pin.
|
||||
*
|
||||
* One parameter `t` morphs an orthographic globe (t = 0) into an
|
||||
* equirectangular map (t = 1) without a cut: the sphere first turns so the
|
||||
* centre latitude sits on the equator by (1 - t), then the hemisphere unrolls
|
||||
* with x = sin(k·λ)/k, which is the globe at k = 1 and the flat map as k → 0.
|
||||
*/
|
||||
|
||||
export const RAD = Math.PI / 180;
|
||||
const TAU = Math.PI * 2;
|
||||
|
||||
/** Zoom where the globe starts to unroll and where it lies flat. */
|
||||
export const MORPH_START = 1.35;
|
||||
export const MORPH_END = 2.6;
|
||||
export const MIN_ZOOM = 0.85;
|
||||
export const MAX_ZOOM = 32;
|
||||
|
||||
export interface GlobeCamera {
|
||||
/** Centre longitude and latitude in degrees. */
|
||||
lon: number;
|
||||
lat: number;
|
||||
/** 1 = the whole globe fits; higher zooms in. */
|
||||
zoom: number;
|
||||
}
|
||||
|
||||
export interface GlobeViewport {
|
||||
/** Size in CSS pixels. */
|
||||
width: number;
|
||||
height: number;
|
||||
/** Globe radius at zoom 1, CSS pixels. */
|
||||
baseRadius: number;
|
||||
/** Screen position of the globe centre at t = 0 and of the map centre at t = 1. */
|
||||
globeY: number;
|
||||
flatY: number;
|
||||
}
|
||||
|
||||
export function smoothstep(a: number, b: number, x: number): number {
|
||||
const t = Math.max(0, Math.min(1, (x - a) / (b - a)));
|
||||
return t * t * (3 - 2 * t);
|
||||
}
|
||||
|
||||
export function morphOf(zoom: number): number {
|
||||
return smoothstep(MORPH_START, MORPH_END, zoom);
|
||||
}
|
||||
|
||||
export function wrapPi(a: number): number {
|
||||
return a - TAU * Math.floor((a + Math.PI) / TAU);
|
||||
}
|
||||
|
||||
export interface FrameParams {
|
||||
t: number;
|
||||
k: number;
|
||||
scale: number;
|
||||
originX: number;
|
||||
originY: number;
|
||||
centerLon: number;
|
||||
centerLat: number;
|
||||
}
|
||||
|
||||
export function frameParams(cam: GlobeCamera, vp: GlobeViewport): FrameParams {
|
||||
const t = morphOf(cam.zoom);
|
||||
return {
|
||||
t,
|
||||
k: 1 - t * 0.9995,
|
||||
scale: vp.baseRadius * cam.zoom,
|
||||
originX: vp.width / 2,
|
||||
originY: vp.globeY + (vp.flatY - vp.globeY) * t,
|
||||
centerLon: cam.lon * RAD,
|
||||
centerLat: cam.lat * RAD,
|
||||
};
|
||||
}
|
||||
|
||||
export interface ScreenPoint {
|
||||
x: number;
|
||||
y: number;
|
||||
/** Positive while the point is on the visible side; larger is further from the edge. */
|
||||
visible: number;
|
||||
/** 1 facing the viewer, 0 at the limb (globe); 1 everywhere once flat. */
|
||||
shade: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Projects a point given in degrees. `refLon/refLat` is the point the
|
||||
* longitude is unwrapped against (the polygon or segment it belongs to), so a
|
||||
* shape that crosses the back of the globe never tears across the screen.
|
||||
*/
|
||||
export function projectPoint(
|
||||
lonDeg: number,
|
||||
latDeg: number,
|
||||
f: FrameParams,
|
||||
refLonDeg = lonDeg,
|
||||
refLatDeg = latDeg
|
||||
): ScreenPoint {
|
||||
const lon = lonDeg * RAD;
|
||||
const lat = latDeg * RAD;
|
||||
const refLon = refLonDeg * RAD;
|
||||
const refLat = refLatDeg * RAD;
|
||||
const phiR = f.centerLat * (1 - f.t);
|
||||
const cphi = Math.cos(phiR);
|
||||
const sphi = Math.sin(phiR);
|
||||
|
||||
const dlr = wrapPi(refLon - f.centerLon);
|
||||
const dl = dlr + wrapPi(lon - f.centerLon - dlr);
|
||||
|
||||
const cl = Math.cos(lat);
|
||||
const px = cl * Math.sin(dl);
|
||||
const py = Math.sin(lat);
|
||||
const pz = cl * Math.cos(dl);
|
||||
const qy = py * cphi - pz * sphi;
|
||||
const qz = py * sphi + pz * cphi;
|
||||
let lam = Math.atan2(px, qz);
|
||||
const phi = Math.asin(Math.max(-1, Math.min(1, qy)));
|
||||
|
||||
const cr = Math.cos(refLat);
|
||||
const rx = cr * Math.sin(dlr);
|
||||
const rz = Math.sin(refLat) * sphi + cr * Math.cos(dlr) * cphi;
|
||||
const lamR = Math.atan2(rx, rz);
|
||||
lam = lamR + wrapPi(lam - lamR);
|
||||
|
||||
const x = (Math.sin(f.k * lam) / f.k) * (Math.cos(phi) * (1 - f.t) + f.t) * xSqueeze(f);
|
||||
const y = Math.sin(phi) * (1 - f.t) + phi * f.t;
|
||||
const c = Math.acos(Math.max(-1, Math.min(1, Math.cos(phi) * Math.cos(lam))));
|
||||
const lim = Math.min(Math.PI, (0.5 * Math.PI) / f.k);
|
||||
return {
|
||||
x: f.originX + x * f.scale,
|
||||
y: f.originY - (y - f.centerLat * f.t) * f.scale,
|
||||
visible: Math.abs(lam) <= Math.PI ? lim - c : -1,
|
||||
shade: Math.max(0, Math.cos(c)) * (1 - f.t) + f.t,
|
||||
};
|
||||
}
|
||||
|
||||
/** How much the flat map squeezes longitude: the cosine of the centre latitude. */
|
||||
export function xSqueeze(f: FrameParams): number {
|
||||
return 1 + (Math.max(0.3, Math.cos(f.centerLat)) - 1) * f.t;
|
||||
}
|
||||
|
||||
/** Great-circle distance in radians between two points given in degrees. */
|
||||
export function angularDistance(lon1: number, lat1: number, lon2: number, lat2: number): number {
|
||||
const a1 = lat1 * RAD;
|
||||
const a2 = lat2 * RAD;
|
||||
const d = (lon2 - lon1) * RAD;
|
||||
const c = Math.sin(a1) * Math.sin(a2) + Math.cos(a1) * Math.cos(a2) * Math.cos(d);
|
||||
return Math.acos(Math.max(-1, Math.min(1, c)));
|
||||
}
|
||||
|
||||
/** Point along the great circle from a to b at fraction s (degrees in, degrees out). */
|
||||
export function interpolateGreatCircle(
|
||||
lon1: number,
|
||||
lat1: number,
|
||||
lon2: number,
|
||||
lat2: number,
|
||||
s: number
|
||||
): [number, number] {
|
||||
const p1 = [
|
||||
Math.cos(lat1 * RAD) * Math.cos(lon1 * RAD),
|
||||
Math.cos(lat1 * RAD) * Math.sin(lon1 * RAD),
|
||||
Math.sin(lat1 * RAD),
|
||||
];
|
||||
const p2 = [
|
||||
Math.cos(lat2 * RAD) * Math.cos(lon2 * RAD),
|
||||
Math.cos(lat2 * RAD) * Math.sin(lon2 * RAD),
|
||||
Math.sin(lat2 * RAD),
|
||||
];
|
||||
const d = angularDistance(lon1, lat1, lon2, lat2);
|
||||
if (d < 1e-9) return [lon1, lat1];
|
||||
const a = Math.sin((1 - s) * d) / Math.sin(d);
|
||||
const b = Math.sin(s * d) / Math.sin(d);
|
||||
const x = a * p1[0] + b * p2[0];
|
||||
const y = a * p1[1] + b * p2[1];
|
||||
const z = a * p1[2] + b * p2[2];
|
||||
return [Math.atan2(y, x) / RAD, Math.atan2(z, Math.hypot(x, y)) / RAD];
|
||||
}
|
||||
|
||||
/**
|
||||
* Unit vector to the sun in earth-fixed coordinates (x towards 0°/0°, z north)
|
||||
* for a moment in time. Low-precision solar position, good to a fraction of a
|
||||
* degree, which is plenty for a day/night line.
|
||||
*/
|
||||
export function sunVector(date: Date): [number, number, number] {
|
||||
const d = date.getTime() / 86400000 - 10957.5; // days since J2000
|
||||
const g = (357.529 + 0.98560028 * d) * RAD;
|
||||
const q = 280.459 + 0.98564736 * d;
|
||||
const L = (q + 1.915 * Math.sin(g) + 0.02 * Math.sin(2 * g)) * RAD;
|
||||
const e = (23.439 - 0.00000036 * d) * RAD;
|
||||
const decl = Math.asin(Math.sin(e) * Math.sin(L));
|
||||
const ra = Math.atan2(Math.cos(e) * Math.sin(L), Math.cos(L));
|
||||
const gmst = ((280.46061837 + 360.98564736629 * d) % 360) * RAD;
|
||||
const lon = ra - gmst;
|
||||
return [Math.cos(decl) * Math.cos(lon), Math.cos(decl) * Math.sin(lon), Math.sin(decl)];
|
||||
}
|
||||
|
||||
/** Moon phase 0..1 (0 new, 0.5 full) and illuminated share, for a moment in time. */
|
||||
export function moonPhase(date: Date): { phase: number; lit: number } {
|
||||
const synodic = 29.530588853;
|
||||
const ref = Date.UTC(2000, 0, 6, 18, 14);
|
||||
const days = (date.getTime() - ref) / 86400000;
|
||||
const phase = (((days % synodic) + synodic) % synodic) / synodic;
|
||||
return { phase, lit: (1 - Math.cos(phase * 2 * Math.PI)) / 2 };
|
||||
}
|
||||
|
||||
/**
|
||||
* A flight arc as instanced segments for the line shader: per segment
|
||||
* a.lon, a.lat, b.lon, b.lat (radians), lift at a and b, and the share of the
|
||||
* arc reached at a and b (so the arc can draw itself in).
|
||||
*/
|
||||
export function arcSegments(
|
||||
routes: Array<{ a: [number, number]; b: [number, number] }>,
|
||||
steps = 48
|
||||
): { data: Float32Array; count: number } {
|
||||
const out = new Float32Array(routes.length * steps * 8);
|
||||
let o = 0;
|
||||
for (const r of routes) {
|
||||
const d = angularDistance(r.a[0], r.a[1], r.b[0], r.b[1]);
|
||||
const peak = 0.015 + d * 0.06;
|
||||
let prev = interpolateGreatCircle(r.a[0], r.a[1], r.b[0], r.b[1], 0);
|
||||
for (let i = 1; i <= steps; i++) {
|
||||
const s0 = (i - 1) / steps;
|
||||
const s1 = i / steps;
|
||||
const next = interpolateGreatCircle(r.a[0], r.a[1], r.b[0], r.b[1], s1);
|
||||
out[o++] = prev[0] * RAD;
|
||||
out[o++] = prev[1] * RAD;
|
||||
out[o++] = next[0] * RAD;
|
||||
out[o++] = next[1] * RAD;
|
||||
out[o++] = peak * Math.sin(Math.PI * s0);
|
||||
out[o++] = peak * Math.sin(Math.PI * s1);
|
||||
out[o++] = s0;
|
||||
out[o++] = s1;
|
||||
prev = next;
|
||||
}
|
||||
}
|
||||
return { data: out, count: o / 8 };
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { Topology } from 'topojson-specification';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildLayer, buildOcean, densify, tessellate } from './globeMesh';
|
||||
|
||||
/** Two squares sharing one edge, as TopoJSON with that edge stored once. */
|
||||
const TWO_SQUARES: Topology = {
|
||||
type: 'Topology',
|
||||
arcs: [
|
||||
[
|
||||
[10, 0],
|
||||
[10, 10],
|
||||
], // shared
|
||||
[
|
||||
[10, 10],
|
||||
[0, 10],
|
||||
[0, 0],
|
||||
[10, 0],
|
||||
],
|
||||
[
|
||||
[10, 0],
|
||||
[20, 0],
|
||||
[20, 10],
|
||||
[10, 10],
|
||||
],
|
||||
],
|
||||
objects: {
|
||||
countries: {
|
||||
type: 'GeometryCollection',
|
||||
geometries: [
|
||||
{ type: 'Polygon', id: 0, arcs: [[0, 1]] },
|
||||
{ type: 'Polygon', id: 1, arcs: [[~0, 2]] },
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
describe('globeMesh', () => {
|
||||
it('splits triangles until every edge is short enough', () => {
|
||||
const coords = [0, 0, 40, 0, 0, 40];
|
||||
const tris = tessellate(coords, [0, 1, 2], 8);
|
||||
for (let i = 0; i < tris.length; i += 3) {
|
||||
const [a, b, c] = [tris[i], tris[i + 1], tris[i + 2]];
|
||||
for (const [p, q] of [
|
||||
[a, b],
|
||||
[b, c],
|
||||
[c, a],
|
||||
]) {
|
||||
expect(Math.hypot(coords[p * 2] - coords[q * 2], coords[p * 2 + 1] - coords[q * 2 + 1])).toBeLessThanOrEqual(
|
||||
8 + 1e-9
|
||||
);
|
||||
}
|
||||
}
|
||||
expect(tris.length / 3).toBeGreaterThan(10);
|
||||
});
|
||||
|
||||
it('densifies lines without moving their ends', () => {
|
||||
const d = densify(
|
||||
[
|
||||
[0, 0],
|
||||
[10, 0],
|
||||
],
|
||||
2
|
||||
);
|
||||
expect(d).toHaveLength(6);
|
||||
expect(d[0]).toEqual([0, 0]);
|
||||
expect(d[5]).toEqual([10, 0]);
|
||||
});
|
||||
|
||||
it('builds fills with the right ids and the shared border once', () => {
|
||||
const layer = buildLayer(TWO_SQUARES, 'countries', 100, (n) => 40 + n);
|
||||
const ids = new Set(Array.from(layer.fill.fid));
|
||||
expect(ids).toEqual(new Set([40, 41]));
|
||||
expect(layer.fill.index.length % 3).toBe(0);
|
||||
// The shared edge is one border segment, the outline is the coast.
|
||||
expect(layer.borders.count).toBe(1);
|
||||
expect(layer.coast.count).toBeGreaterThanOrEqual(6);
|
||||
// Everything leaves in radians.
|
||||
expect(Math.max(...Array.from(layer.fill.ll))).toBeLessThanOrEqual((20 * Math.PI) / 180 + 1e-6);
|
||||
});
|
||||
|
||||
it('covers the whole sphere with the ocean grid', () => {
|
||||
const o = buildOcean(30);
|
||||
expect(o.index.length).toBe((360 / 30) * (180 / 30) * 6);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
/**
|
||||
* Turns a TopoJSON level of detail into GPU-ready arrays: triangles for the
|
||||
* fills, segments for the borders. Pure, so the worker and the tests share it.
|
||||
*
|
||||
* Coordinates leave here in radians. Each fill vertex carries the centre of its
|
||||
* polygon as the reference the shader unwraps longitude against, so a polygon
|
||||
* that crosses the back of the globe stays in one piece.
|
||||
*/
|
||||
import earcut from 'earcut';
|
||||
import type { LineString, MultiLineString, MultiPolygon, Polygon, Position } from 'geojson';
|
||||
import { feature, mesh } from 'topojson-client';
|
||||
import type { GeometryCollection, Topology } from 'topojson-specification';
|
||||
|
||||
const RAD = Math.PI / 180;
|
||||
|
||||
export interface FillMesh {
|
||||
/** lon, lat per vertex (radians) */
|
||||
ll: Float32Array;
|
||||
/** reference lon, lat per vertex (radians) */
|
||||
ref: Float32Array;
|
||||
/** feature id per vertex */
|
||||
fid: Float32Array;
|
||||
index: Uint32Array;
|
||||
}
|
||||
|
||||
export interface LineMesh {
|
||||
/** per segment: a.lon, a.lat, b.lon, b.lat (radians) */
|
||||
seg: Float32Array;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface BuiltLayer {
|
||||
fill: FillMesh;
|
||||
coast: LineMesh;
|
||||
borders: LineMesh;
|
||||
}
|
||||
|
||||
/** Splits triangles until no edge is longer than maxEdge degrees, so they bend with the sphere. */
|
||||
export function tessellate(coords: number[], tris: number[], maxEdge: number): number[] {
|
||||
const out: number[] = [];
|
||||
const mid = new Map<string, number>();
|
||||
const midpoint = (a: number, b: number): number => {
|
||||
const key = a < b ? `${a}:${b}` : `${b}:${a}`;
|
||||
let m = mid.get(key);
|
||||
if (m === undefined) {
|
||||
m = coords.length / 2;
|
||||
coords.push((coords[a * 2] + coords[b * 2]) / 2, (coords[a * 2 + 1] + coords[b * 2 + 1]) / 2);
|
||||
mid.set(key, m);
|
||||
}
|
||||
return m;
|
||||
};
|
||||
const len = (a: number, b: number): number =>
|
||||
Math.hypot(coords[a * 2] - coords[b * 2], coords[a * 2 + 1] - coords[b * 2 + 1]);
|
||||
const stack: Array<[number, number, number]> = [];
|
||||
for (let i = 0; i < tris.length; i += 3) stack.push([tris[i], tris[i + 1], tris[i + 2]]);
|
||||
while (stack.length) {
|
||||
const [a, b, c] = stack.pop() as [number, number, number];
|
||||
const ab = len(a, b);
|
||||
const bc = len(b, c);
|
||||
const ca = len(c, a);
|
||||
const m = Math.max(ab, bc, ca);
|
||||
if (m <= maxEdge) {
|
||||
out.push(a, b, c);
|
||||
} else if (m === ab) {
|
||||
const d = midpoint(a, b);
|
||||
stack.push([a, d, c], [d, b, c]);
|
||||
} else if (m === bc) {
|
||||
const d = midpoint(b, c);
|
||||
stack.push([a, b, d], [a, d, c]);
|
||||
} else {
|
||||
const d = midpoint(c, a);
|
||||
stack.push([a, b, d], [d, b, c]);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Inserts points so no segment is longer than maxEdge degrees. */
|
||||
export function densify(line: Position[], maxEdge: number): Position[] {
|
||||
const out: Position[] = [line[0]];
|
||||
for (let i = 1; i < line.length; i++) {
|
||||
const [x0, y0] = line[i - 1];
|
||||
const [x1, y1] = line[i];
|
||||
const n = Math.max(1, Math.ceil(Math.hypot(x1 - x0, y1 - y0) / maxEdge));
|
||||
for (let k = 1; k <= n; k++) out.push([x0 + ((x1 - x0) * k) / n, y0 + ((y1 - y0) * k) / n]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function polygonsOf(g: Polygon | MultiPolygon | null): Position[][][] {
|
||||
if (!g) return [];
|
||||
return g.type === 'Polygon' ? [g.coordinates] : g.coordinates;
|
||||
}
|
||||
|
||||
function centreOf(ring: Position[]): [number, number] {
|
||||
let w = Infinity;
|
||||
let e = -Infinity;
|
||||
let s = Infinity;
|
||||
let n = -Infinity;
|
||||
for (const [x, y] of ring) {
|
||||
if (x < w) w = x;
|
||||
if (x > e) e = x;
|
||||
if (y < s) s = y;
|
||||
if (y > n) n = y;
|
||||
}
|
||||
return [(w + e) / 2, (s + n) / 2];
|
||||
}
|
||||
|
||||
class Grow {
|
||||
data: Float32Array;
|
||||
length = 0;
|
||||
constructor(n = 4096) {
|
||||
this.data = new Float32Array(n);
|
||||
}
|
||||
push(...v: number[]): void {
|
||||
if (this.length + v.length > this.data.length) {
|
||||
const next = new Float32Array(Math.max(this.data.length * 2, this.length + v.length));
|
||||
next.set(this.data);
|
||||
this.data = next;
|
||||
}
|
||||
for (const x of v) this.data[this.length++] = x;
|
||||
}
|
||||
done(): Float32Array {
|
||||
return this.data.slice(0, this.length);
|
||||
}
|
||||
}
|
||||
|
||||
function linesOf(ml: MultiLineString | LineString, maxEdge: number): LineMesh {
|
||||
const seg = new Grow();
|
||||
const parts = ml.type === 'MultiLineString' ? ml.coordinates : [ml.coordinates];
|
||||
for (const part of parts) {
|
||||
if (part.length < 2) continue;
|
||||
const d = densify(part, maxEdge);
|
||||
for (let i = 1; i < d.length; i++) seg.push(d[i - 1][0] * RAD, d[i - 1][1] * RAD, d[i][0] * RAD, d[i][1] * RAD);
|
||||
}
|
||||
const arr = seg.done();
|
||||
return { seg: arr, count: arr.length / 4 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds one layer. `ids` maps a topology feature's numeric id to the id the
|
||||
* status texture knows it by (countries: their manifest index; regions: a block
|
||||
* reserved for that country).
|
||||
*/
|
||||
export function buildLayer(
|
||||
topo: Topology,
|
||||
objectName: string,
|
||||
maxEdge: number,
|
||||
ids: (topoId: number) => number
|
||||
): BuiltLayer {
|
||||
const obj = topo.objects[objectName] as GeometryCollection;
|
||||
const fc = feature(topo, obj);
|
||||
const ll = new Grow(1 << 16);
|
||||
const ref = new Grow(1 << 16);
|
||||
const fid = new Grow(1 << 15);
|
||||
let index: number[] = [];
|
||||
let vbase = 0;
|
||||
for (const f of fc.features) {
|
||||
const id = ids(Number(f.id));
|
||||
for (const poly of polygonsOf(f.geometry as Polygon | MultiPolygon)) {
|
||||
if (!poly.length || poly[0].length < 4) continue;
|
||||
const flat: number[] = [];
|
||||
const holes: number[] = [];
|
||||
poly.forEach((ring, ri) => {
|
||||
if (ri > 0) holes.push(flat.length / 2);
|
||||
for (let i = 0; i < ring.length - 1; i++) flat.push(ring[i][0], ring[i][1]);
|
||||
});
|
||||
const tris = tessellate(flat, earcut(flat, holes, 2), maxEdge);
|
||||
const [cx, cy] = centreOf(poly[0]);
|
||||
for (let i = 0; i < flat.length; i += 2) {
|
||||
ll.push(flat[i] * RAD, flat[i + 1] * RAD);
|
||||
ref.push(cx * RAD, cy * RAD);
|
||||
fid.push(id);
|
||||
}
|
||||
for (const t of tris) index.push(vbase + t);
|
||||
vbase += flat.length / 2;
|
||||
}
|
||||
if (index.length > 1 << 20) index = index.slice();
|
||||
}
|
||||
const coast = mesh(topo, obj, (a, b) => a === b) as MultiLineString;
|
||||
const borders = mesh(topo, obj, (a, b) => a !== b) as MultiLineString;
|
||||
return {
|
||||
fill: { ll: ll.done(), ref: ref.done(), fid: fid.done(), index: Uint32Array.from(index) },
|
||||
coast: linesOf(coast, maxEdge),
|
||||
borders: linesOf(borders, maxEdge),
|
||||
};
|
||||
}
|
||||
|
||||
/** A latitude/longitude grid over the whole sphere, the ocean the land sits on. */
|
||||
export function buildOcean(step = 6): FillMesh {
|
||||
const ll: number[] = [];
|
||||
const ref: number[] = [];
|
||||
const fid: number[] = [];
|
||||
const index: number[] = [];
|
||||
let v = 0;
|
||||
for (let lon = -180; lon < 180; lon += step) {
|
||||
for (let lat = -90; lat < 90; lat += step) {
|
||||
const cx = (lon + step / 2) * RAD;
|
||||
const cy = (lat + step / 2) * RAD;
|
||||
for (const [x, y] of [
|
||||
[lon, lat],
|
||||
[lon + step, lat],
|
||||
[lon + step, lat + step],
|
||||
[lon, lat + step],
|
||||
]) {
|
||||
ll.push(x * RAD, Math.min(90, y) * RAD);
|
||||
ref.push(cx, cy);
|
||||
fid.push(0);
|
||||
}
|
||||
index.push(v, v + 1, v + 2, v, v + 2, v + 3);
|
||||
v += 4;
|
||||
}
|
||||
}
|
||||
return {
|
||||
ll: Float32Array.from(ll),
|
||||
ref: Float32Array.from(ref),
|
||||
fid: Float32Array.from(fid),
|
||||
index: Uint32Array.from(index),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/// <reference lib="webworker" />
|
||||
/**
|
||||
* Builds globe layers off the main thread. The main thread fetches the
|
||||
* topology (it owns auth and the API base) and hands it over; this worker
|
||||
* triangulates and sends the arrays back as transferables.
|
||||
*/
|
||||
import type { Topology } from 'topojson-specification';
|
||||
import { buildLayer, type BuiltLayer } from './globeMesh';
|
||||
|
||||
export interface MeshRequest {
|
||||
job: number;
|
||||
topo: Topology;
|
||||
object: string;
|
||||
maxEdge: number;
|
||||
/** Status-texture id of topology feature 0; feature n gets idBase + n. */
|
||||
idBase: number;
|
||||
}
|
||||
|
||||
export interface MeshResponse {
|
||||
job: number;
|
||||
layer?: BuiltLayer;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
const scope = self as unknown as DedicatedWorkerGlobalScope;
|
||||
|
||||
scope.onmessage = (e: MessageEvent<MeshRequest>) => {
|
||||
const { job, topo, object, maxEdge, idBase } = e.data;
|
||||
try {
|
||||
const layer = buildLayer(topo, object, maxEdge, (n) => idBase + n);
|
||||
const transfer = [
|
||||
layer.fill.ll.buffer,
|
||||
layer.fill.ref.buffer,
|
||||
layer.fill.fid.buffer,
|
||||
layer.fill.index.buffer,
|
||||
layer.coast.seg.buffer,
|
||||
layer.borders.seg.buffer,
|
||||
];
|
||||
scope.postMessage({ job, layer } satisfies MeshResponse, transfer);
|
||||
} catch (err) {
|
||||
scope.postMessage({ job, error: err instanceof Error ? err.message : String(err) } satisfies MeshResponse);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,308 @@
|
||||
/**
|
||||
* GLSL for the Atlas globe. PROJECT is the GPU twin of projectPoint() in
|
||||
* globeMath.ts; a change to one belongs in the other.
|
||||
*/
|
||||
|
||||
const PROJECT = /* glsl */ `
|
||||
uniform vec2 u_center; // centre lon, lat in radians
|
||||
uniform float u_t; // 0 globe .. 1 flat map
|
||||
uniform float u_scale; // device px per radian
|
||||
uniform vec2 u_origin; // device px of the centre
|
||||
uniform vec2 u_viewport; // device px
|
||||
const float PI = 3.14159265;
|
||||
|
||||
float wrapPi(float a) { return a - 2.0 * PI * floor((a + PI) / (2.0 * PI)); }
|
||||
|
||||
// xy: screen px, z: visibility (> 0 visible), w: shade
|
||||
vec4 project(vec2 ll, vec2 ref) {
|
||||
float k = 1.0 - u_t * 0.9995;
|
||||
float phiR = u_center.y * (1.0 - u_t);
|
||||
float cphi = cos(phiR), sphi = sin(phiR);
|
||||
float dlr = wrapPi(ref.x - u_center.x);
|
||||
float dl = dlr + wrapPi(ll.x - u_center.x - dlr);
|
||||
float cl = cos(ll.y);
|
||||
vec3 p = vec3(cl * sin(dl), sin(ll.y), cl * cos(dl));
|
||||
float qy = p.y * cphi - p.z * sphi;
|
||||
float qz = p.y * sphi + p.z * cphi;
|
||||
float lam = atan(p.x, qz);
|
||||
float phi = asin(clamp(qy, -1.0, 1.0));
|
||||
float cr = cos(ref.y);
|
||||
float lamR = atan(cr * sin(dlr), sin(ref.y) * sphi + cr * cos(dlr) * cphi);
|
||||
lam = lamR + wrapPi(lam - lamR);
|
||||
// Flat, longitude is squeezed by the cosine of the centre latitude, so shapes keep
|
||||
// their proportions where the user looks instead of widening towards the poles.
|
||||
float xs = mix(1.0, max(0.3, cos(u_center.y)), u_t);
|
||||
float x = sin(k * lam) / k * (cos(phi) * (1.0 - u_t) + u_t) * xs;
|
||||
float y = sin(phi) * (1.0 - u_t) + phi * u_t;
|
||||
vec2 s = u_origin + vec2(x, -(y - u_center.y * u_t)) * u_scale;
|
||||
float c = acos(clamp(cos(phi) * cos(lam), -1.0, 1.0));
|
||||
float lim = min(PI, 0.5 * PI / k);
|
||||
float vis = abs(lam) <= PI ? lim - c : -1.0;
|
||||
float shade = max(0.0, cos(c)) * (1.0 - u_t) + u_t;
|
||||
return vec4(s, vis, shade);
|
||||
}
|
||||
|
||||
vec4 toClip(vec2 s) {
|
||||
return vec4(s.x / u_viewport.x * 2.0 - 1.0, 1.0 - s.y / u_viewport.y * 2.0, 0.0, 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
export const FILL_VS = /* glsl */ `#version 300 es
|
||||
precision highp float;
|
||||
${PROJECT}
|
||||
in vec2 a_ll; // radians
|
||||
in vec2 a_ref; // radians
|
||||
in float a_fid;
|
||||
out float v_vis;
|
||||
out float v_shade;
|
||||
out vec2 v_ll;
|
||||
flat out int v_fid;
|
||||
void main() {
|
||||
vec4 p = project(a_ll, a_ref);
|
||||
v_vis = p.z;
|
||||
v_shade = p.w;
|
||||
v_ll = a_ll;
|
||||
v_fid = int(a_fid + 0.5);
|
||||
gl_Position = toClip(p.xy);
|
||||
}
|
||||
`;
|
||||
|
||||
export const FILL_FS = /* glsl */ `#version 300 es
|
||||
precision highp float;
|
||||
precision highp usampler2D;
|
||||
in float v_vis;
|
||||
in float v_shade;
|
||||
in vec2 v_ll;
|
||||
flat in int v_fid;
|
||||
uniform sampler2D u_status; // rgb colour, a strength
|
||||
uniform sampler2D u_fx; // r hatch, g reveal order, b outline flag
|
||||
uniform int u_mode; // 0 land, 1 ocean, 2 region layer
|
||||
uniform vec3 u_land;
|
||||
uniform vec3 u_ocean;
|
||||
uniform vec3 u_oceanDeep;
|
||||
uniform float u_layerAlpha;
|
||||
uniform float u_time;
|
||||
uniform float u_revealStart;
|
||||
uniform int u_hover;
|
||||
uniform int u_selected;
|
||||
uniform int u_inkId;
|
||||
uniform vec2 u_inkLL;
|
||||
uniform float u_inkR;
|
||||
uniform float u_dpr;
|
||||
uniform float u_t;
|
||||
uniform float u_dimBase;
|
||||
uniform float u_regionFade;
|
||||
uniform vec3 u_sun; // unit vector to the sun, earth-fixed
|
||||
uniform float u_night; // how strongly the night side darkens
|
||||
uniform float u_shadeMin; // brightness at the limb (light mode keeps it high)
|
||||
uniform vec4 u_hoverTint; // rgb + strength; selection uses 1.8x the strength
|
||||
out vec4 outColor;
|
||||
|
||||
vec4 fetch(sampler2D tex, int id) { return texelFetch(tex, ivec2(id % 256, id / 256), 0); }
|
||||
|
||||
void main() {
|
||||
if (v_vis < 0.0) discard;
|
||||
float edge = smoothstep(0.0, 0.004, v_vis);
|
||||
float light = mix(u_shadeMin, 1.0, pow(v_shade, 0.65));
|
||||
vec3 nrm = vec3(cos(v_ll.y) * cos(v_ll.x), cos(v_ll.y) * sin(v_ll.x), sin(v_ll.y));
|
||||
float sunDot = dot(nrm, u_sun);
|
||||
float day = smoothstep(-0.12, 0.1, sunDot);
|
||||
float nightMul = mix(1.0 - u_night, 1.0, day);
|
||||
if (u_mode == 1) {
|
||||
vec3 col = mix(u_oceanDeep, u_ocean, pow(v_shade, 0.9));
|
||||
col *= mix(1.0 - u_night * 0.7, 1.0, day);
|
||||
// A faint glint where the sun stands over the sea.
|
||||
col += vec3(0.35, 0.45, 0.6) * pow(max(0.0, sunDot), 40.0) * 0.25 * (1.0 - u_t) * v_shade;
|
||||
outColor = vec4(col, edge);
|
||||
return;
|
||||
}
|
||||
vec4 st = fetch(u_status, v_fid);
|
||||
vec4 fx = fetch(u_fx, v_fid);
|
||||
float reveal = clamp((u_time - u_revealStart - fx.g * 1.6) / 0.45, 0.0, 1.0);
|
||||
float a = st.a * reveal;
|
||||
if (v_fid == u_inkId) {
|
||||
vec3 p1 = vec3(cos(v_ll.y) * cos(v_ll.x), cos(v_ll.y) * sin(v_ll.x), sin(v_ll.y));
|
||||
vec3 p2 = vec3(cos(u_inkLL.y) * cos(u_inkLL.x), cos(u_inkLL.y) * sin(u_inkLL.x), sin(u_inkLL.y));
|
||||
float d = acos(clamp(dot(p1, p2), -1.0, 1.0));
|
||||
a *= 1.0 - smoothstep(u_inkR - 0.01, u_inkR, d);
|
||||
}
|
||||
// A country whose regions are on screen steps back so its regions read.
|
||||
if (u_mode == 0 && fx.b > 0.5) a *= 1.0 - 0.32 * u_regionFade;
|
||||
vec3 base = u_land * (u_mode == 2 ? 1.0 : u_dimBase);
|
||||
vec3 col = mix(base, st.rgb, a);
|
||||
if (fx.r > 0.5) {
|
||||
float h = step(mod(gl_FragCoord.x + gl_FragCoord.y, 7.0 * u_dpr), 1.6 * u_dpr);
|
||||
col = mix(col, st.rgb, h * 0.9 * reveal);
|
||||
a = max(a, h * 0.9 * reveal);
|
||||
}
|
||||
if (v_fid == u_selected) col = mix(col, u_hoverTint.rgb, u_hoverTint.a * 1.8);
|
||||
else if (v_fid == u_hover) col = mix(col, u_hoverTint.rgb, u_hoverTint.a);
|
||||
col *= light;
|
||||
// Night darkens the land; what you marked keeps most of its colour, like lights on.
|
||||
col *= mix(nightMul, 1.0, a * 0.75);
|
||||
float alpha = edge;
|
||||
if (u_mode == 2) alpha *= u_layerAlpha * max(a, (v_fid == u_hover || v_fid == u_selected) ? 0.25 : 0.0);
|
||||
outColor = vec4(col, alpha);
|
||||
}
|
||||
`;
|
||||
|
||||
export const PICK_FS = /* glsl */ `#version 300 es
|
||||
precision highp float;
|
||||
in float v_vis;
|
||||
in float v_shade;
|
||||
in vec2 v_ll;
|
||||
flat in int v_fid;
|
||||
uniform int u_idBase;
|
||||
out vec4 outColor;
|
||||
void main() {
|
||||
if (v_vis < 0.0) discard;
|
||||
int id = v_fid + 1;
|
||||
outColor = vec4(float(id & 255) / 255.0, float((id >> 8) & 255) / 255.0, float((id >> 16) & 255) / 255.0, 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
/** Instanced screen-space lines: borders, coasts, outlines and flight arcs. */
|
||||
export const LINE_VS = /* glsl */ `#version 300 es
|
||||
precision highp float;
|
||||
${PROJECT}
|
||||
in vec2 a_corner; // x: 0 start .. 1 end, y: -1 .. 1 across
|
||||
in vec2 a_a; // radians
|
||||
in vec2 a_b; // radians
|
||||
in vec2 a_h; // lift of a and b (arcs), share of the radius
|
||||
in vec2 a_s; // position along the whole line, 0..1, at a and b
|
||||
uniform float u_width; // device px
|
||||
uniform float u_lift; // 1 lifts arcs above the surface
|
||||
out float v_vis;
|
||||
out float v_across;
|
||||
out float v_s;
|
||||
out float v_shade;
|
||||
vec2 lifted(vec4 p, float h) {
|
||||
vec2 d = p.xy - u_origin;
|
||||
vec2 globe = u_origin + d * (1.0 + h);
|
||||
vec2 flat2 = p.xy - vec2(0.0, h * u_scale * 0.35);
|
||||
return mix(globe, flat2, u_t);
|
||||
}
|
||||
void main() {
|
||||
vec2 mid = (a_a + a_b) * 0.5;
|
||||
if (abs(a_a.x - a_b.x) > PI) mid.x = a_a.x;
|
||||
vec4 pa = project(a_a, mid);
|
||||
vec4 pb = project(a_b, mid);
|
||||
vec2 sa = u_lift > 0.5 ? lifted(pa, a_h.x) : pa.xy;
|
||||
vec2 sb = u_lift > 0.5 ? lifted(pb, a_h.y) : pb.xy;
|
||||
vec2 dir = sb - sa;
|
||||
float len = length(dir);
|
||||
dir = len > 1e-5 ? dir / len : vec2(1.0, 0.0);
|
||||
vec2 n = vec2(-dir.y, dir.x);
|
||||
vec2 s = mix(sa, sb, a_corner.x) + n * a_corner.y * (u_width * 0.5 + 1.0) + dir * (a_corner.x * 2.0 - 1.0) * 0.5;
|
||||
float hv = mix(a_h.x, a_h.y, a_corner.x);
|
||||
v_vis = mix(pa.z, pb.z, a_corner.x) + (u_lift > 0.5 ? hv * 0.6 : 0.0);
|
||||
v_across = a_corner.y * (u_width * 0.5 + 1.0);
|
||||
v_s = mix(a_s.x, a_s.y, a_corner.x);
|
||||
v_shade = mix(pa.w, pb.w, a_corner.x);
|
||||
gl_Position = toClip(s);
|
||||
}
|
||||
`;
|
||||
|
||||
export const LINE_FS = /* glsl */ `#version 300 es
|
||||
precision highp float;
|
||||
in float v_vis;
|
||||
in float v_across;
|
||||
in float v_s;
|
||||
in float v_shade;
|
||||
uniform vec4 u_color;
|
||||
uniform float u_width;
|
||||
uniform float u_progress; // draws the line up to this share (arcs drawing in)
|
||||
uniform float u_glow;
|
||||
out vec4 outColor;
|
||||
void main() {
|
||||
if (v_vis < 0.0 || v_s > u_progress) discard;
|
||||
float d = abs(v_across);
|
||||
float core = 1.0 - smoothstep(u_width * 0.5 - 0.5, u_width * 0.5 + 0.5, d);
|
||||
float a = core;
|
||||
if (u_glow > 0.0) a = max(core, exp(-d * d / (u_width * u_width * 1.2)) * u_glow);
|
||||
float limb = smoothstep(0.0, 0.03, v_vis);
|
||||
outColor = vec4(u_color.rgb, u_color.a * a * limb * mix(0.55, 1.0, v_shade));
|
||||
}
|
||||
`;
|
||||
|
||||
/** Full-screen quad for the backdrop: deep space, stars, atmosphere. */
|
||||
export const SKY_VS = /* glsl */ `#version 300 es
|
||||
precision highp float;
|
||||
in vec2 a_pos;
|
||||
out vec2 v_uv;
|
||||
void main() {
|
||||
v_uv = a_pos * 0.5 + 0.5;
|
||||
gl_Position = vec4(a_pos, 0.0, 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
export const SKY_FS = /* glsl */ `#version 300 es
|
||||
precision highp float;
|
||||
in vec2 v_uv;
|
||||
uniform vec2 u_viewport; // device px
|
||||
uniform vec2 u_globe; // device px of the globe centre
|
||||
uniform float u_radius; // device px
|
||||
uniform float u_t;
|
||||
uniform float u_time;
|
||||
uniform vec2 u_drift; // parallax from the camera, radians
|
||||
uniform vec3 u_space0;
|
||||
uniform vec3 u_space1;
|
||||
uniform vec3 u_glow;
|
||||
uniform float u_dark;
|
||||
out vec4 outColor;
|
||||
|
||||
float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
|
||||
|
||||
float stars(vec2 px, float cell, float density, float size) {
|
||||
vec2 g = floor(px / cell);
|
||||
vec2 f = fract(px / cell);
|
||||
float h = hash(g);
|
||||
if (h > density) return 0.0;
|
||||
vec2 c = vec2(hash(g + 3.1), hash(g + 7.7)) * 0.8 + 0.1;
|
||||
float d = length(f - c) * cell;
|
||||
float tw = 0.65 + 0.35 * sin(u_time * (0.6 + h * 2.0) + h * 40.0);
|
||||
return smoothstep(size, 0.0, d) * tw * (0.4 + 0.6 * hash(g + 1.3));
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec2 px = v_uv * u_viewport;
|
||||
px.y = u_viewport.y - px.y;
|
||||
float r = length(px - u_globe);
|
||||
vec3 col = mix(u_space1, u_space0, smoothstep(0.0, max(u_viewport.x, u_viewport.y) * 0.8, r));
|
||||
float sky = (1.0 - u_t * 0.9) * u_dark;
|
||||
// Milky way: a soft band across the sky, drifting with the camera.
|
||||
vec2 q = px / u_viewport.y + u_drift * vec2(0.08, 0.05);
|
||||
float band = exp(-pow((q.y - 0.35 - 0.45 * q.x + 0.25) * 3.2, 2.0));
|
||||
float dust = hash(floor(px * 0.5)) * 0.5 + 0.5;
|
||||
col += vec3(0.20, 0.24, 0.42) * band * 0.10 * sky * dust;
|
||||
vec2 sp = px + u_drift * vec2(60.0, 40.0) * u_viewport.y / 900.0;
|
||||
float s = stars(sp, 38.0, 0.20, 1.6) + stars(sp * 1.7 + 13.0, 31.0, 0.12, 1.1) * 0.7 + band * stars(sp * 2.3 + 5.0, 17.0, 0.35, 0.9) * 0.8;
|
||||
col += vec3(0.85, 0.9, 1.0) * s * sky;
|
||||
// Atmosphere: a glow hugging the globe, gone once the map lies flat.
|
||||
float atm = (1.0 - smoothstep(0.0, 0.7, u_t));
|
||||
float outside = smoothstep(u_radius * 0.985, u_radius * 1.0, r);
|
||||
float glow = exp(-max(0.0, r - u_radius) / (u_radius * 0.075)) * outside;
|
||||
col += u_glow * glow * 0.55 * atm;
|
||||
outColor = vec4(col, 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
/** A thin bright rim on the limb, drawn over the globe. */
|
||||
export const RIM_FS = /* glsl */ `#version 300 es
|
||||
precision highp float;
|
||||
in vec2 v_uv;
|
||||
uniform vec2 u_viewport;
|
||||
uniform vec2 u_globe;
|
||||
uniform float u_radius;
|
||||
uniform float u_t;
|
||||
uniform vec3 u_glow;
|
||||
out vec4 outColor;
|
||||
void main() {
|
||||
vec2 px = v_uv * u_viewport;
|
||||
px.y = u_viewport.y - px.y;
|
||||
float r = length(px - u_globe);
|
||||
float inner = smoothstep(u_radius * 0.82, u_radius, r) * (1.0 - smoothstep(u_radius, u_radius * 1.004, r));
|
||||
float a = pow(inner, 3.0) * 0.55 * (1.0 - smoothstep(0.0, 0.5, u_t));
|
||||
outColor = vec4(u_glow, a);
|
||||
}
|
||||
`;
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Map paint for the Atlas globe. These are rendering colours for WebGL, not UI
|
||||
* surfaces, so they are numbers here rather than appearance tokens; the accent
|
||||
* is read from the live --accent token so the globe follows the user's scheme.
|
||||
*/
|
||||
import type { GlobeTheme, Rgb } from './GlobeRenderer';
|
||||
|
||||
export function hexToRgb(hex: string): Rgb {
|
||||
const h = hex.replace('#', '').trim();
|
||||
const full =
|
||||
h.length === 3
|
||||
? h
|
||||
.split('')
|
||||
.map((c) => c + c)
|
||||
.join('')
|
||||
: h.slice(0, 6);
|
||||
const n = parseInt(full, 16);
|
||||
if (Number.isNaN(n)) return [0.5, 0.5, 0.5];
|
||||
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
|
||||
}
|
||||
|
||||
export function rgbToBytes(c: Rgb): [number, number, number] {
|
||||
return [Math.round(c[0] * 255), Math.round(c[1] * 255), Math.round(c[2] * 255)];
|
||||
}
|
||||
|
||||
function readCssColor(name: string, fallback: string): string {
|
||||
if (typeof document === 'undefined') return fallback;
|
||||
const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
|
||||
return /^#[0-9a-f]{3,8}$/i.test(v) ? v : fallback;
|
||||
}
|
||||
|
||||
export function globeTheme(dark: boolean): GlobeTheme {
|
||||
const accent = hexToRgb(readCssColor('--accent', dark ? '#e4e4e7' : '#111827'));
|
||||
if (dark) {
|
||||
return {
|
||||
land: [0.15, 0.18, 0.27],
|
||||
ocean: [0.07, 0.11, 0.22],
|
||||
oceanDeep: [0.025, 0.04, 0.09],
|
||||
space0: [0.008, 0.012, 0.03],
|
||||
space1: [0.04, 0.06, 0.13],
|
||||
glow: [0.49, 0.78, 0.99],
|
||||
border: [0.03, 0.04, 0.09, 0.9],
|
||||
coast: [0.55, 0.75, 1.0, 0.16],
|
||||
regionBorder: [0.9, 0.95, 1.0, 0.32],
|
||||
selection: [1, 1, 1, 0.95],
|
||||
arc: [0.88, 0.95, 1.0, 0.95],
|
||||
dark: true,
|
||||
};
|
||||
}
|
||||
// Daylight: a clear sky, a bright sea, warm grey land and white borders.
|
||||
return {
|
||||
land: [0.985, 0.985, 0.98],
|
||||
ocean: [0.72, 0.84, 0.96],
|
||||
oceanDeep: [0.55, 0.7, 0.88],
|
||||
space0: [0.88, 0.93, 0.98],
|
||||
space1: [0.75, 0.85, 0.96],
|
||||
glow: [0.62, 0.8, 1.0],
|
||||
border: [0.72, 0.78, 0.86, 0.9],
|
||||
coast: [0.3, 0.45, 0.65, 0.3],
|
||||
regionBorder: [0.75, 0.8, 0.88, 0.75],
|
||||
selection: [accent[0], accent[1], accent[2], 0.95],
|
||||
arc: [0.16, 0.32, 0.72, 0.9],
|
||||
dark: false,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user