import { useEffect, useRef, useState } from "react"; import { ALTITUDE_LEVELS_MM } from "./altitudeLevels"; import { floorHeightAt, isRestingOnFruit } from "./collision"; import { apiPath } from "./env"; import FlyScene from "./FlyScene"; import { playBiteSound, resumeAudioContext } from "./flyBuzz"; import { BITE_ANIM_DURATION_S } from "./FlyInstances"; import MobileControlSheet, { MOBILE_SHEET_HANDLE_HEIGHT } from "./MobileControlSheet"; import SidePanel from "./SidePanel"; import { FLY_GROUND_OFFSET_MM, useFlyLayout } from "./useFlyLayout"; import { useIsMobile } from "./useIsMobile"; import { useKeyboardControls } from "./useKeyboardControls"; import { useLiveFlyState } from "./useLiveFlyState"; import { useVda5050Nats } from "./vda5050/useVda5050Nats"; /** Every backend-connected fly defaults to VDA5050 operatingMode AUTOMATIC * (even idle, order-less ones) -- FlyInstances.tsx only lets the local * joystick move a fly when it's NOT AUTOMATIC, so without this, selecting a * fly while a backend is connected would silently make the joystick do * nothing. Tells the backend a fly is now under local/manual control on * select, and hands it back on deselect (a no-op, harmlessly ignored, when * there's no backend to reach). */ function setManualMode(flyId: string, manual: boolean): void { fetch(apiPath(`fly/${flyId}/manual?manual=${manual}`), { method: "POST" }).catch(() => {}); } // Fire-and-forget, same tolerant shape as setManualMode above -- the // backend's own refill is authoritative once it round-trips over NATS // (useVda5050Nats.ts already writes powerSupply.stateOfCharge into // live.batteryPercent), this just reports the bite happened. function feedFly(flyId: string): void { fetch(apiPath(`fly/${flyId}/feed`), { method: "POST" }).catch(() => {}); } // Matches backend/src/flyyt_backend/fly.py's BATTERY_FEED_REFILL_PERCENT -- // used only for the optimistic local bump below. const FEED_REFILL_PERCENT = 15; export default function App() { const flies = useFlyLayout(); const livePositionsRef = useLiveFlyState(flies); useVda5050Nats(livePositionsRef); const joystickRef = useRef({ x: 0, y: 0 }); const wingSlidersRef = useRef({ left: 0, right: 0 }); const [selectedFlyId, setSelectedFlyId] = useState(null); const [panelCollapsed, setPanelCollapsed] = useState(false); const [sheetExpanded, setSheetExpanded] = useState(false); const [flying, setFlying] = useState(false); const [altitudeLevelIndex, setAltitudeLevelIndex] = useState(0); const isMobile = useIsMobile(); useEffect(() => { if (!selectedFlyId) return; setManualMode(selectedFlyId, true); return () => setManualMode(selectedFlyId, false); }, [selectedFlyId]); // Selecting a fly -- whether via a chip in the mobile sheet or tapping it // directly in the 3D scene -- surfaces its controls (and squeezes the // canvas to make room), same as the desktop panel already keeps its // controls visible/enabled once something's selected. Only squeeze the // canvas when there's something to show; an empty selection never forces // the sheet open on its own. useEffect(() => { if (selectedFlyId) setSheetExpanded(true); }, [selectedFlyId]); // Syncs the flight switch/altitude slider's UI state onto whichever fly is // selected, same shape as setManualMode above (body applies, cleanup // reverts) -- the cleanup is what auto-lands a flying fly the moment you // deselect it or select a different one, rather than leaving it hovering // unattended with no visible control surface. useEffect(() => { if (!selectedFlyId) return; const live = livePositionsRef.current.get(selectedFlyId); if (live) { live.flying = flying; // "Land" means descend to whatever's actually under the fly right // now (floor, or a tabletop if it happens to be over one), not // always the flat floor constant. live.targetAltitudeMm = flying ? ALTITUDE_LEVELS_MM[altitudeLevelIndex] : floorHeightAt(live.x, live.z) + FLY_GROUND_OFFSET_MM; } return () => { const prevLive = livePositionsRef.current.get(selectedFlyId); if (prevLive) { prevLive.flying = false; prevLive.targetAltitudeMm = floorHeightAt(prevLive.x, prevLive.z) + FLY_GROUND_OFFSET_MM; } }; }, [flying, altitudeLevelIndex, selectedFlyId, livePositionsRef]); // Keeps the flight switch honest once battery actually runs out mid-air -- // FlyInstances.tsx already forces the SIMULATED fly to crash (effectiveFlying // false the instant batteryPercent hits 0), but without this the switch // itself would keep showing "flying" even though the fly's already on the // ground. Same light poll idiom as useStatusSnapshot.ts, since battery // lives in the ref, not React state. useEffect(() => { if (!flying || !selectedFlyId) return; const id = setInterval(() => { const live = livePositionsRef.current.get(selectedFlyId); if (live && live.batteryPercent <= 0) setFlying(false); }, 500); return () => clearInterval(id); }, [flying, selectedFlyId, livePositionsRef]); // Freshly selecting a different fly always shows it as grounded in the // switch/slider, matching the auto-land-on-deselect behavior above. useEffect(() => { setFlying(false); setAltitudeLevelIndex(0); }, [selectedFlyId]); const toggleFlying = () => { setFlying((f) => { const next = !f; // Flying always starts its climb at the minimum level, never // wherever altitudeLevelIndex was last left -- otherwise landing and // taking off again on the same selected fly jumps straight back to // its previous altitude instead of restarting from the floor. if (next) setAltitudeLevelIndex(0); return next; }); }; const onAltitudeChange = (index: number) => { setAltitudeLevelIndex(Math.min(ALTITUDE_LEVELS_MM.length - 1, Math.max(0, index))); // Changing altitude implies airborne; landing is only ever via the // switch/Space, not by stepping back down past level 0. setFlying(true); }; const onAltitudeStep = (direction: 1 | -1) => onAltitudeChange(altitudeLevelIndex + direction); const onFeed = () => { if (!selectedFlyId) return; const live = livePositionsRef.current.get(selectedFlyId); if (!live) return; if (!isRestingOnFruit(live.x, live.y, live.z, live.flying)) return; // no-op if not close enough playBiteSound(); live.biteAnimRemainingS = BITE_ANIM_DURATION_S; // triggers FlyInstances.tsx's dip/nod gesture live.batteryPercent = Math.min(100, live.batteryPercent + FEED_REFILL_PERCENT); // optimistic local bump feedFly(selectedFlyId); }; useKeyboardControls({ selectedFlyId, joystickRef, onToggleFlying: toggleFlying, onAltitudeStep, onFeed }); return ( // Buzzing audio needs a user gesture to start (browser autoplay policy); // this covers every click/tap anywhere in the app rather than needing a // dedicated "enable sound" button. dvw/dvh (not vw/vh) so mobile browser // chrome showing/hiding doesn't clip content or leave a jumpy gap.
resumeAudioContext()} >
{isMobile ? (
setSheetExpanded((e) => !e)} flying={flying} onToggleFlying={toggleFlying} altitudeLevelIndex={altitudeLevelIndex} onAltitudeChange={onAltitudeChange} />
) : ( setPanelCollapsed((c) => !c)} joystickRef={joystickRef} wingSlidersRef={wingSlidersRef} livePositionsRef={livePositionsRef} flying={flying} onToggleFlying={toggleFlying} altitudeLevelIndex={altitudeLevelIndex} onAltitudeChange={onAltitudeChange} /> )}
); }