diff --git a/package-lock.json b/package-lock.json index e71142d6..ba02fa86 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,12 +15,15 @@ "react": "19.2.3", "react-dom": "19.2.3", "resium": "^1.19.4", + "tslib": "^2.8.1", + "ws": "^8.14.2", "zustand": "^5.0.11" }, "devDependencies": { "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", + "@types/ws": "^8.18.1", "copy-webpack-plugin": "^14.0.0", "typescript": "^5" } @@ -866,6 +869,27 @@ "node": ">=20.0.0" } }, + "node_modules/@supabase/realtime-js/node_modules/ws": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/@supabase/storage-js": { "version": "2.98.0", "resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.98.0.tgz", @@ -2480,9 +2504,9 @@ } }, "node_modules/ws": { - "version": "8.19.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", - "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "version": "8.14.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.14.2.tgz", + "integrity": "sha512-wEBG1ftX4jcglPxgFCMJmZ2PLtSbJ2Peg6TmpJFTbe9GZYOQCDPdMYu/Tm0/bGZkw8paZnJY45J4K2PZrLYq8g==", "license": "MIT", "engines": { "node": ">=10.0.0" diff --git a/package.json b/package.json index ec914312..568cf74d 100644 --- a/package.json +++ b/package.json @@ -15,12 +15,15 @@ "react": "19.2.3", "react-dom": "19.2.3", "resium": "^1.19.4", + "tslib": "^2.8.1", + "ws": "^8.14.2", "zustand": "^5.0.11" }, "devDependencies": { "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", + "@types/ws": "^8.18.1", "copy-webpack-plugin": "^14.0.0", "typescript": "^5" } diff --git a/src/app/api/maritime/route.ts b/src/app/api/maritime/route.ts index 4bc7c39d..72dbcb94 100644 --- a/src/app/api/maritime/route.ts +++ b/src/app/api/maritime/route.ts @@ -1,11 +1,37 @@ import { NextResponse } from "next/server"; +import { getCachedVessels } from "@/lib/ais-stream"; /** * Maritime AIS proxy. - * Currently returns demo data — will be connected to a real AIS feed in Phase 2. + * Returns live data from aisstream.io. */ export async function GET() { - // In the future, this will proxy to a real AIS data provider. - // For now, return an empty vessels array so the plugin falls back to demo data. - return NextResponse.json({ vessels: null }); + const vessels = getCachedVessels(); + + // If the cache is completely empty, we return null to trigger the fallback demo data + // in the plugin while the websocket populates. Once it's running, we return the real array. + if (vessels.length === 0) { + return NextResponse.json({ vessels: null }); + } + + // Format the cached data into GeoEntities + const geoEntities = vessels.map((v) => ({ + id: `maritime-${v.mmsi}`, + pluginId: "maritime", + latitude: v.lat, + longitude: v.lon, + heading: v.heading, + speed: v.speed, + timestamp: v.timestamp, + label: v.name, + properties: { + mmsi: v.mmsi, + vesselName: v.name, + vesselType: v.type, // TODO: Enhance with real type categorization if needed + speed_knots: v.speed, + heading: v.heading, + }, + })); + + return NextResponse.json({ vessels: geoEntities }); } diff --git a/src/app/globals.css b/src/app/globals.css index 714f14e2..3cab6115 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -795,9 +795,111 @@ html, body { font-size: 10px; color: var(--text-muted); text-align: center; + text-align: center; font-style: italic; } +/* ─── Panel Toggle Arrows ─────────────────────────────────── */ +.panel-toggle-btn { + position: fixed; + top: 50%; + transform: translateY(-50%); + z-index: 40; /* Below the sidebars (z-index 50) so they can hide behind them */ + display: flex; + align-items: center; + justify-content: center; + width: 32px; /* Thinner tabs */ + height: 80px; /* Taller tabs for easier grabbing */ + background: var(--bg-glass); + backdrop-filter: blur(var(--glass-blur)); + -webkit-backdrop-filter: blur(var(--glass-blur)); + border: var(--glass-border); + color: var(--text-muted); + cursor: pointer; + transition: all var(--duration-normal) var(--ease-smooth); + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4); +} + +.panel-toggle-btn:hover { + background: var(--bg-glass-active); + color: var(--text-primary); + border-color: var(--accent-cyan); +} + +/* LEFT ARROW */ +.panel-toggle-btn--left { + left: 0; + border-radius: 0 var(--radius-lg) var(--radius-lg) 0; + border-left: none; + /* When closed, hide mostly off-screen, poke out 12px */ + transform: translate(-20px, -50%); +} + +.panel-toggle-btn--left:hover { + /* Reveal fully on hover when closed */ + transform: translate(0, -50%); + box-shadow: var(--glow-cyan); +} + +.panel-toggle-btn--left.panel-toggle-btn--open { + /* Attach to the right edge of the left panel (width 280px + left padding 24px) */ + left: calc(280px + var(--space-lg)); + border-radius: 0 var(--radius-sm) var(--radius-sm) 0; + border-left: none; + /* Stay slightly hidden under the panel to look attached, poke out 24px */ + transform: translate(-8px, -50%); +} +.panel-toggle-btn--left.panel-toggle-btn--open:hover { + /* Glow but don't move when already open */ + transform: translate(-4px, -50%); +} + +/* RIGHT ARROW */ +.panel-toggle-btn--right { + right: 0; + border-radius: var(--radius-lg) 0 0 var(--radius-lg); + border-right: none; + /* When closed, hide mostly off-screen, poke out 12px */ + transform: translate(20px, -50%); +} + +.panel-toggle-btn--right:hover { + /* Reveal fully on hover when closed */ + transform: translate(0, -50%); + box-shadow: var(--glow-cyan); +} + +.panel-toggle-btn--right.panel-toggle-btn--open { + /* Attach to the left edge of the right panel (width 320px + right padding 24px) */ + right: calc(320px + var(--space-lg)); + border-radius: var(--radius-sm) 0 0 var(--radius-sm); + border-right: none; + /* Stay slightly hidden under the panel to look attached, poke out 24px */ + transform: translate(8px, -50%); +} + +.panel-toggle-btn--right.panel-toggle-btn--open:hover { + /* Glow but don't move when already open */ + transform: translate(4px, -50%); +} + +.filter-badge--toggle { + position: absolute; + top: -6px; + right: -6px; + background: var(--accent-cyan); + color: var(--bg-primary); + font-size: 10px; + font-weight: 700; + width: 20px; + height: 20px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 50%; + box-shadow: 0 0 10px rgba(34, 211, 238, 0.5); + pointer-events: none; +} /* ─── Filter Components ──────────────────────────────────── */ .filter-section { margin-bottom: var(--space-md); diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsx index 963272e1..2d837632 100644 --- a/src/components/layout/AppShell.tsx +++ b/src/components/layout/AppShell.tsx @@ -15,6 +15,7 @@ import { MaritimePlugin } from "@/plugins/maritime"; import { WildfirePlugin } from "@/plugins/wildfire"; import { useStore } from "@/core/state/store"; import { dataBus } from "@/core/data/DataBus"; +import { PanelToggleArrows } from "@/components/layout/PanelToggleArrows"; import dynamic from "next/dynamic"; // Dynamically import GlobeView with SSR disabled (CesiumJS requires window) @@ -87,6 +88,7 @@ export function AppShell() { {/* Foreground UI Components */} +
diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsx index 4d78b8b0..4966d999 100644 --- a/src/components/layout/Header.tsx +++ b/src/components/layout/Header.tsx @@ -52,13 +52,6 @@ export function Header() { return (
-
WorldWideView
Geospatial Intelligence
@@ -104,28 +97,6 @@ export function Header() {
{/* Always-visible right-side actions */}
- {/* 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); +}