57 lines
2.4 KiB
JavaScript
57 lines
2.4 KiB
JavaScript
import * as THREE from "three";
|
|
import {createCalloutController} from "./spatial-callout-controller.js";
|
|
import {CONFIG} from "./constants.js";
|
|
import {getCountryAnchorCandidates} from "./country-boundaries.js";
|
|
import {latLonToVector3} from "./utils.js";
|
|
|
|
const geographicLocalPositions = new WeakMap();
|
|
const projectedWorld = new THREE.Vector3();
|
|
const projectedCenter = new THREE.Vector3();
|
|
const projectedNormal = new THREE.Vector3();
|
|
const projectedView = new THREE.Vector3();
|
|
|
|
export function projectGeographicAnchor(anchor, earth, camera, width, height) {
|
|
if (!anchor || !Number.isFinite(anchor.latitude) || !Number.isFinite(anchor.longitude) || !earth || !camera) return null;
|
|
let cached = geographicLocalPositions.get(anchor);
|
|
if (!cached || cached.latitude !== anchor.latitude || cached.longitude !== anchor.longitude) {
|
|
cached = {latitude:anchor.latitude, longitude:anchor.longitude,
|
|
local:latLonToVector3(anchor.latitude, anchor.longitude, CONFIG.earthRadius + 0.25)};
|
|
geographicLocalPositions.set(anchor, cached);
|
|
}
|
|
projectedWorld.copy(cached.local).applyMatrix4(earth.matrixWorld);
|
|
projectedCenter.setFromMatrixPosition(earth.matrixWorld);
|
|
projectedNormal.copy(projectedWorld).sub(projectedCenter).normalize();
|
|
projectedView.copy(camera.position).sub(projectedWorld).normalize();
|
|
const visibility = projectedNormal.dot(projectedView);
|
|
projectedWorld.project(camera);
|
|
if (!Number.isFinite(projectedWorld.x) || !Number.isFinite(projectedWorld.y)) return null;
|
|
return {
|
|
x: (projectedWorld.x + 1) * width / 2,
|
|
y: (1 - projectedWorld.y) * height / 2,
|
|
front: visibility > 0.04 && projectedWorld.z < 1,
|
|
visibility,
|
|
key: anchor.key,
|
|
};
|
|
}
|
|
|
|
export function createSpatialCallouts(options) {
|
|
return createCalloutController({getAnchorCandidates:getCountryAnchorCandidates,...options,project:projectGeographicAnchor});
|
|
}
|
|
|
|
export function createCalloutGroups(controller) {
|
|
const groups = new Map();
|
|
const sync = () => controller.set([...groups.values()].flat());
|
|
return {
|
|
scope(key) {
|
|
return {
|
|
set(items) { groups.set(key, items); sync(); },
|
|
setSpotlightKeys: (keys) => controller.setSpotlightKeys?.(keys, key),
|
|
invalidate: () => controller.invalidate(),
|
|
destroy() { groups.delete(key); sync(); },
|
|
};
|
|
},
|
|
update: (delta, now) => controller.update(delta, now),
|
|
destroy() { groups.clear(); controller.destroy(); },
|
|
};
|
|
}
|