- {/* Separator */}
-
- {/* Config Toggle */}
-
- {/* Filter Toggle */}
-
{/* Separator */}
{/* Live indicator */}
diff --git a/src/components/layout/PanelToggleArrows.tsx b/src/components/layout/PanelToggleArrows.tsx
new file mode 100644
index 00000000..7b18bdb4
--- /dev/null
+++ b/src/components/layout/PanelToggleArrows.tsx
@@ -0,0 +1,45 @@
+"use client";
+
+import { useStore } from "@/core/state/store";
+import { ChevronRight, ChevronLeft } from "lucide-react";
+
+export function PanelToggleArrows() {
+ const leftSidebarOpen = useStore((s) => s.leftSidebarOpen);
+ const configPanelOpen = useStore((s) => s.configPanelOpen);
+
+ const toggleLeftSidebar = useStore((s) => s.toggleLeftSidebar);
+ const toggleConfigPanel = useStore((s) => s.toggleConfigPanel);
+
+ const filterCount = useStore((s) =>
+ Object.values(s.filters).reduce((sum, pf) => sum + Object.keys(pf).length, 0)
+ );
+
+ return (
+ <>
+ {/* Left Toggle */}
+
+
+ {/* Right Toggle */}
+
+ >
+ );
+}
diff --git a/src/core/globe/AnimationLoop.ts b/src/core/globe/AnimationLoop.ts
index 43dd16e2..0977d106 100644
--- a/src/core/globe/AnimationLoop.ts
+++ b/src/core/globe/AnimationLoop.ts
@@ -1,4 +1,12 @@
-import { Cartesian3, Color, Math as CesiumMath, Ellipsoid } from "cesium";
+import {
+ Cartesian3,
+ Color,
+ Math as CesiumMath,
+ Ellipsoid,
+ BoundingSphere,
+ Intersect,
+ CullingVolume
+} from "cesium";
import type { Viewer as CesiumViewer } from "cesium";
import type { GeoEntity, CesiumEntityOptions } from "@/core/plugins/PluginTypes";
import { useStore } from "@/core/state/store";
@@ -17,9 +25,18 @@ interface AnimatableItem {
const R_WGS84_MIN = 6356752.0;
const R2 = R_WGS84_MIN * R_WGS84_MIN;
+// Pre-allocate objects for Zero-Allocation Loop
+const scratchDisplacement = new Cartesian3();
+const scratchNorth = new Cartesian3();
+const scratchEast = new Cartesian3();
+const scratchVelocity = new Cartesian3();
+const scratchSphere = new BoundingSphere(new Cartesian3(), 100); // 100m radius roughly
+const scratchNorthPole = new Cartesian3(0, 0, 1);
+const scratchSurfaceNormal = new Cartesian3();
+
/**
* Creates the per-frame update function for entity position extrapolation,
- * horizon culling, and highlight styling.
+ * horizon culling, frustum culling, and highlight styling.
*/
export function createUpdateLoop(
viewer: CesiumViewer,
@@ -28,6 +45,9 @@ export function createUpdateLoop(
): () => void {
let frameCount = 0;
+ // We instantiate a reusable culling volume object
+ let cullingVolume = new CullingVolume();
+
return () => {
if (!viewer || viewer.isDestroyed()) return;
@@ -42,30 +62,54 @@ export function createUpdateLoop(
const Dh = Math.sqrt(camDistSqr - R2);
const isFullUpdate = frameCount++ % 2 === 0;
+ // Extract camera culling volume for this frame
+ cullingVolume = cam.frustum.computeCullingVolume(cam.positionWC, cam.directionWC, cam.upWC);
+
for (let i = 0; i < animatables.length; i++) {
const item = animatables[i];
const { primitive, labelPrimitive, entity, posRef } = item;
const isSelected = state.selectedEntity?.id === entity.id;
const isHovered = hoveredEntityIdRef.current === entity.id;
- // Position extrapolation
+ // 1. Frustum Culling
+ scratchSphere.center = posRef;
+ // Let's use 1000 for visibility padding, roughly fits billboards
+ scratchSphere.radius = 1000;
+ const intersect = cullingVolume.computeVisibility(scratchSphere);
+ const inFrustum = intersect !== Intersect.OUTSIDE;
+
+ // If it's completely out of the camera's view and not selected, skip all heavy JS processing
+ if (!inFrustum && !isSelected && !isHovered) {
+ primitive.show = false;
+ if (labelPrimitive) labelPrimitive.show = false;
+ continue;
+ }
+
+ // 2. Horizon culling
+ const posDistSqr = Cartesian3.magnitudeSquared(posRef);
+ const Dph = Math.sqrt(Math.max(0, posDistSqr - R2));
+ const distanceToPoint = Cartesian3.distance(camPos, posRef);
+ const isVisible = distanceToPoint <= (Dh + Dph);
+
+ if (!isVisible && !isSelected && !isHovered) {
+ primitive.show = false;
+ if (labelPrimitive) labelPrimitive.show = false;
+ continue;
+ }
+
+ primitive.show = true;
+
+ // 3. Position extrapolation (Zero-Allocation)
if (entity.timestamp && entity.speed !== undefined && entity.heading !== undefined) {
if (isFullUpdate || isSelected || isHovered) {
extrapolatePosition(item, nowMs);
}
}
- // Horizon culling
- const posDistSqr = Cartesian3.magnitudeSquared(posRef);
- const Dph = Math.sqrt(Math.max(0, posDistSqr - R2));
- const distanceToPoint = Cartesian3.distance(camPos, posRef);
- const isVisible = distanceToPoint <= (Dh + Dph);
- primitive.show = isVisible;
-
- // Highlight styling
+ // 4. Highlight styling
applyHighlight(item, isSelected, isHovered);
- // Label visibility
+ // 5. Label visibility
if (labelPrimitive) {
const showLabel = isVisible && (distanceToPoint < 500000 || isSelected || isHovered);
labelPrimitive.show = showLabel;
@@ -75,7 +119,7 @@ export function createUpdateLoop(
};
}
-/** Extrapolate entity position forward/backward in time. */
+/** Extrapolate entity position forward/backward in time using zero-allocation mathematics. */
function extrapolatePosition(item: AnimatableItem, nowMs: number): void {
const { entity, posRef } = item;
if (!entity.timestamp) return;
@@ -83,34 +127,32 @@ function extrapolatePosition(item: AnimatableItem, nowMs: number): void {
const dtSec = (nowMs - entity.timestamp.getTime()) / 1000;
if (Math.abs(dtSec) > 300) return;
+ // Cache base position and velocity vector only once
if (!item.velocityVector) {
const headingRad = CesiumMath.toRadians(entity.heading!);
- const surfaceNormal = Ellipsoid.WGS84.geodeticSurfaceNormal(posRef);
- const northPole = new Cartesian3(0, 0, 1);
+ // Use scratchSurfaceNormal to avoid allocation
+ Ellipsoid.WGS84.geodeticSurfaceNormal(posRef, scratchSurfaceNormal);
- let northDir = new Cartesian3();
- Cartesian3.cross(northPole, surfaceNormal, northDir);
- Cartesian3.cross(surfaceNormal, northDir, northDir);
- Cartesian3.normalize(northDir, northDir);
+ Cartesian3.cross(scratchNorthPole, scratchSurfaceNormal, scratchNorth);
+ Cartesian3.cross(scratchSurfaceNormal, scratchNorth, scratchNorth);
+ Cartesian3.normalize(scratchNorth, scratchNorth);
- let eastDir = new Cartesian3();
- Cartesian3.cross(northDir, surfaceNormal, eastDir);
- Cartesian3.normalize(eastDir, eastDir);
+ Cartesian3.cross(scratchNorth, scratchSurfaceNormal, scratchEast);
+ Cartesian3.normalize(scratchEast, scratchEast);
- const velocityVector = new Cartesian3();
- Cartesian3.multiplyByScalar(northDir, Math.cos(headingRad), velocityVector);
- const tempEast = new Cartesian3();
- Cartesian3.multiplyByScalar(eastDir, Math.sin(headingRad), tempEast);
- Cartesian3.add(velocityVector, tempEast, velocityVector);
- Cartesian3.multiplyByScalar(velocityVector, entity.speed!, velocityVector);
+ Cartesian3.multiplyByScalar(scratchNorth, Math.cos(headingRad), scratchVelocity);
+
+ Cartesian3.multiplyByScalar(scratchEast, Math.sin(headingRad), scratchEast); // reuse scratchEast as tempEast
+ Cartesian3.add(scratchVelocity, scratchEast, scratchVelocity);
+ Cartesian3.multiplyByScalar(scratchVelocity, entity.speed!, scratchVelocity);
item.basePosition = Cartesian3.clone(posRef);
- item.velocityVector = velocityVector;
+ item.velocityVector = Cartesian3.clone(scratchVelocity);
}
- const displacement = new Cartesian3();
- Cartesian3.multiplyByScalar(item.velocityVector!, dtSec, displacement);
- Cartesian3.add(item.basePosition!, displacement, posRef);
+ // Apply zero-allocation displacement calculation
+ Cartesian3.multiplyByScalar(item.velocityVector, dtSec, scratchDisplacement);
+ Cartesian3.add(item.basePosition!, scratchDisplacement, posRef);
item.primitive.position = posRef;
if (item.labelPrimitive) item.labelPrimitive.position = posRef;
diff --git a/src/instrumentation.ts b/src/instrumentation.ts
index a70c96a6..efd6db02 100644
--- a/src/instrumentation.ts
+++ b/src/instrumentation.ts
@@ -1,6 +1,8 @@
export async function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
const { startAviationPolling } = await import("./lib/aviation-polling");
+ const { startAisStream } = await import("./lib/ais-stream");
startAviationPolling();
+ startAisStream();
}
}
diff --git a/src/lib/ais-stream.ts b/src/lib/ais-stream.ts
new file mode 100644
index 00000000..492af6d5
--- /dev/null
+++ b/src/lib/ais-stream.ts
@@ -0,0 +1,148 @@
+import WebSocket from 'ws';
+
+// Map to store the latest position of each vessel
+// MMSI -> Vessel Data
+const vesselCache = new Map
();
+
+let ws: WebSocket | null = null;
+let reconnectTimeout: NodeJS.Timeout | null = null;
+let isConnecting = false;
+
+// Store the socket connection start time to periodically restart it
+// aisstream.io connections can sometimes get stale
+let connectionStartTime = 0;
+const MAX_CONNECTION_AGE_MS = 1000 * 60 * 60; // 1 hour
+
+export function getCachedVessels() {
+ // Return all values from the cache
+ return Array.from(vesselCache.values());
+}
+
+export function startAisStream() {
+ if (ws || isConnecting) {
+ // If connection is too old, restart it
+ if (ws && Date.now() - connectionStartTime > MAX_CONNECTION_AGE_MS) {
+ console.log('[AIS Stream] Connection is stale. Reconnecting...');
+ ws.close(); // This will trigger the onclose handler which reconnects
+ }
+ return;
+ }
+
+ const apiKey = process.env.MARITIME_API_KEY;
+ if (!apiKey) {
+ console.warn('[AIS Stream] MARITIME_API_KEY is not set. AIS streaming is disabled.');
+ return;
+ }
+
+ isConnecting = true;
+ console.log('[AIS Stream] Connecting to aisstream.io...');
+
+ try {
+ ws = new WebSocket('wss://stream.aisstream.io/v0/stream');
+
+ // Set a connection timeout (if it hangs without triggering open/error)
+ const connectionTimeout = setTimeout(() => {
+ if (isConnecting && ws) {
+ console.warn('[AIS Stream] Connection timed out. Terminating...');
+ ws.terminate();
+ }
+ }, 10000);
+
+ ws.on('open', () => {
+ clearTimeout(connectionTimeout);
+ console.log('[AIS Stream] Connected securely to aisstream.io');
+ isConnecting = false;
+ connectionStartTime = Date.now();
+
+ const subscriptionMessage = {
+ ApiKey: apiKey, // The API actually expects "ApiKey" instead of "APIKey" in some docs
+ BoundingBoxes: [[[-90, -180], [90, 180]]],
+ FilterMessageTypes: ["PositionReport"]
+ };
+
+ ws?.send(JSON.stringify(subscriptionMessage));
+ console.log('[AIS Stream] Sent subscription message');
+ });
+
+ ws.on('message', (data) => {
+ try {
+ const rawBuffer = data.toString();
+ // Add verbose logging to see if we are getting data
+ console.log('[AIS Stream] Received raw message fragment:', rawBuffer.substring(0, 100));
+
+ const message = JSON.parse(rawBuffer);
+
+ if (message.MessageType === 'PositionReport') {
+ const report = message.Message.PositionReport;
+ const meta = message.MetaData;
+
+ const mmsi = report.UserID;
+
+ // Basic sanity check on coordinates
+ if (report.Latitude >= 91 || report.Latitude <= -91 ||
+ report.Longitude >= 181 || report.Longitude <= -181) {
+ return;
+ }
+
+ // Convert speed and heading (Sog is in knots, Cog is in degrees)
+ // aisstream sometimes sends 1023 for "not available" speed or 3600 for "not available" course
+ const speed = report.Sog === 1023 ? 0 : report.Sog;
+ const heading = report.Cog === 3600 ? 0 : report.Cog;
+
+ // Derive a rough category from ship type if available, otherwise unknown
+ // Since PositionReport doesn't always have ShipType, we might need a separate lookup
+ // or just default to unknown for now
+
+ vesselCache.set(mmsi, {
+ mmsi: mmsi,
+ name: meta.ShipName?.trim() || `Unknown (${mmsi})`,
+ type: 'other', // Default type unless we get ShipStaticData
+ lat: report.Latitude,
+ lon: report.Longitude,
+ speed: speed,
+ heading: heading,
+ timestamp: meta.time_utc,
+ });
+
+ // To prevent memory leaks, limit cache size
+ // Ensure we don't store more than e.g. 50,000 vessels
+ if (vesselCache.size > 50000) {
+ // Delete the oldest entry (Map iterates in insertion order)
+ const firstKey = vesselCache.keys().next().value;
+ if (firstKey) {
+ vesselCache.delete(firstKey);
+ }
+ }
+ }
+ } catch (e) {
+ // Ignore parsing errors for individual messages
+ }
+ });
+
+ ws.on('close', () => {
+ console.log('[AIS Stream] Connection closed. Reconnecting in 5 seconds...');
+ ws = null;
+ isConnecting = false;
+ scheduleReconnect();
+ });
+
+ ws.on('error', (err) => {
+ console.error('[AIS Stream] WebSocket error:', err.message);
+ // Error usually precedes close, but close handles the reconnect
+ });
+
+ } catch (e) {
+ console.error('[AIS Stream] Failed to establish connection:', e);
+ isConnecting = false;
+ scheduleReconnect();
+ }
+}
+
+function scheduleReconnect() {
+ if (reconnectTimeout) {
+ clearTimeout(reconnectTimeout);
+ }
+ reconnectTimeout = setTimeout(() => {
+ startAisStream();
+ }, 5000);
+}