drone-sim
by mraad
README.md
# Drone Sim
A drone flight simulator: **three.js** frontend (single self-contained HTML file) +
**FastAPI / FastMCP** backend so an MCP client (e.g. Claude) can pilot the drone in
real time over WebSocket.
```
Browser (three.js sim) ⇄ ws://…/ws ⇄ FastAPI ⇄ FastMCP tools ⇄ MCP client
```
## Quickstart
```bash
uv sync
uv run uvicorn server.app:app --port 9000
```
Open <http://127.0.0.1:9000> — fly immediately with the keyboard. The frontend has
zero build steps and zero local dependencies (three.js is resolved via an import map
from the jsDelivr CDN).
## Keyboard controls
RC mode-2 style, matching WebBaseDroneSimulation:
| Key | Action |
|---|---|
| `W` / `S` | throttle up / down |
| `A` / `D` | yaw left / right |
| `↑` / `↓` | pitch forward / back |
| `←` / `→` | roll (strafe) left / right |
| `Shift` | speed boost |
| `V` | cycle camera: chase → first-person → overhead |
| `R` | reset to spawn |
HUD (top-left) shows link status, speed, altitude AGL, vertical speed, heading,
position (plus lat/lon when terrain is loaded), camera mode, active MCP command, FPS.
## MCP control
MCP endpoint (streamable HTTP): `http://127.0.0.1:9000/mcp/`
```json
{ "mcpServers": { "drone-sim": { "url": "http://127.0.0.1:9000/mcp/" } } }
```
Or with Claude Code: `claude mcp add --transport http drone-sim http://127.0.0.1:9000/mcp/`
Tools (a browser tab must be open so a drone is connected):
| Tool | Description |
|---|---|
| `move(direction, distance_m, speed_ms)` | fly forward/backward/left/right N meters |
| `change_altitude(delta_m)` | climb (+) or descend (−) |
| `turn(yaw_deg)` | rotate, positive = clockwise |
| `goto(x, z \| lat, lon, altitude_m)` | fly to scene or geographic coordinates |
| `fly_path(waypoints, speed_ms)` | fly straight segments through 3D waypoints |
| `fly_spline(waypoints, speed_ms)` | fly a smooth Catmull-Rom curve through 3D waypoints |
| `get_state()` | latest telemetry (position, heading, speed…) |
| `get_extent()` | loaded world's bounding box: local meters + geographic lat/lon |
| `capture_frame(camera, width, height, fov_deg)` | one JPEG frame at a fixed pixel size, with its metadata |
| `place_object(id, model, x, z \| lat, lon, heading_deg, length_m)` | put a box or a glTF model on the ground |
| `remove_object(id)` | remove one placed object, or all when `id` is omitted |
| `stop()` | cancel maneuver, hover |
| `reset()` | respawn at the scene's spawn point (origin, or the landmark viewpoint) |
Commands return the drone's real outcome: `completed`, `aborted` (human pressed a
key — the pilot always wins), `failed`, or `timeout`. `goto` with lat/lon requires
terrain to be loaded (geo origin known).
`capture_frame`, `place_object` and `remove_object` do not interrupt a maneuver, so
a client can take frames during a flight.
- `capture_frame` renders off the main loop, so the frame size does not depend on
the browser window. Camera `nadir` (default) looks straight down from the drone,
north-up, with vertical field of view `fov_deg` (default 60); the drone is hidden.
`chase` and `fpv` are the pilot views. The result is the image plus metadata:
`pos`, `geo`, `altitude_agl`, `heading_deg` and, for `nadir`, `ground_m_per_px`
(correct on flat ground under the drone).
- `place_object` takes `model`: `"box"` (a car-sized red placeholder), a
`.glb`/`.gltf` file name under `static/models/`, or a same-origin path. To use
models that are not in this repository, set `DRONE_SIM_ASSETS=/path/to/dir`; the
server mounts that directory at `/assets` (for example `model="/assets/car.glb"`).
The model is centred, seated on the terrain and turned `heading_deg` clockwise.
`length_m` scales it so its longer horizontal side has that length. Placing an
existing `id` replaces the object. Draco or Meshopt compressed glTF is not supported.
`fly_path` / `fly_spline` take `waypoints`: a list of ≥2 points, each `{x, z, alt}`
(scene meters) or `{lat, lon, alt}` (geographic, needs terrain). `alt` is absolute
and optional (carries the previous point's altitude when omitted). The drone starts
from its current position; `fly_spline` follows a smooth Catmull-Rom curve while
`fly_path` corners point to point. Both cruise at `speed_ms` and hold a forward pitch.
## Real-world scenery from GeoTIFFs (optional)
Bundled scenes:
```bash
./notre_dame.sh # Notre-Dame de Paris: DEM + aerial + geolocated 3D cathedral
./chbaniyeh.sh # Chbaniyeh, Lebanon: DEM + aerial
```
Both are wrappers around `./scene.sh NAME [drape|dem|flat]`, which serves
`data/NAME_dem.tif` and `data/NAME_ortho.tif`. To add a scene, put a DEM and an
orthophoto with identical bounds in `data/` under a new name. `data/` is
gitignored, so the rasters stay local.
See [`NOTRE_DAME.md`](NOTRE_DAME.md) and [`CHBANIYEH.md`](CHBANIYEH.md) for
coverage, sources, attribution, and alternate launch modes.
The Notre-Dame scene also loads a 3D cathedral (`static/models/notre_dame.stl`,
served at `/models/`). The model is placed from its OpenStreetMap footprint and
loads only when that point is inside the active raster. The drone then spawns in
front of the west façade.
> **Building an orthophoto from Esri World Imagery exports:** the `export`
> endpoint enlarges the bbox to fit the requested image size. Request a `size`
> that matches the bbox aspect, and georeference each tile from the `extent` in
> the response, not from the bbox you asked for. Otherwise mosaicked tiles
> overlap and drift. See `NOTRE_DAME.md` § Regenerate the rasters.
Two ways to replace the procedural city with real geospatial data. Both put the HUD
into geo mode so it shows live lat/lon and `goto(lat=…, lon=…)` works. Set **both**
env vars to drape the imagery onto the 3D relief; with only one you get the DEM
heightfield or a flat basemap; with neither, the procedural city. `?vscale=N` on the
page URL exaggerates gentle relief.
**3D terrain — a single-band elevation DEM:**
```bash
DRONE_SIM_COG=/path/to/dem.tif uv run uvicorn server.app:app --port 9000
```
The backend warps any-CRS raster to EPSG:4326, downsamples (`/api/terrain?size=256`),
and the frontend renders a hypsometrically tinted heightfield at its real coordinates.
**Flat draped imagery — an aerial/satellite orthophoto (RGB/RGBA):**
```bash
DRONE_SIM_BASEMAP=/path/to/ortho.tif uv run uvicorn server.app:app --port 9000
```
The backend warps the RGB to EPSG:4326, encodes an aspect-correct JPEG
(`/api/basemap` + `/api/basemap.jpg`), and the frontend drapes it on a flat ground
plane at its real extent — you fly over the actual imagery, north-up. Use this for
photos that carry no elevation (an RGB ortho is not a DEM); for 3D relief supply a
DEM via `DRONE_SIM_COG` instead.
## WebSocket protocol (`/ws`)
Browser → server:
```json
{"type": "hello", "role": "drone", "version": 1}
{"type": "telemetry", "t": 1.2, "pos": {…}, "vel": {…}, "yaw": 0.0,
"heading_deg": 0, "speed_ms": 0, "vspeed_ms": 0, "altitude_agl": 12,
"geo": null, "active_cmd": null, "camera": "chase"}
{"type": "ack", "id": "…", "status": "accepted|completed|aborted|failed", "detail": ""}
```
Server → browser:
```json
{"type": "command", "id": "…", "action": "move|altitude|turn|goto|fly_path|stop|reset", "params": {…}}
```
`fly_path` params are `{waypoints, speed_ms, smooth}`. The MCP `fly_spline` tool
sends the same action with `smooth: true` (Catmull-Rom curve).
## Tests
```bash
uv run pytest # unit + integration
uv run pytest -m "not integration" # unit only
node --test tests/test_frontend.mjs # autopilot regression checks (Node.js)
```
`tests/fake_drone.py` is a headless drone stand-in used by the integration tests to
validate the full MCP → WebSocket → drone → ack round trip without a browser.
## Layout
```
static/index.html # entire frontend (scene, physics, HUD, cameras, WS client)
static/models/ # landmark meshes, served at /models/ (notre_dame.stl)
server/manager.py # WS registry, telemetry cache, command futures
server/mcp_server.py# FastMCP tool definitions
server/app.py # FastAPI app: static, /models, /ws, /api/terrain, /api/basemap, /mcp mount
scene.sh # launch a bundled scene from data/NAME_{dem,ortho}.tif
notre_dame.sh, chbaniyeh.sh # one-line wrappers around scene.sh
serve.sh # background start/stop/status/restart for the server
tests/ # unit + integration harness
```
## License
The code is under the [MIT License](LICENSE).
Bundled and downloaded assets keep their own licenses:
- `static/models/notre_dame.stl`: "Notre Dame de Paris" by GazdaTony, based on Chigirinsky's model,
[Thingiverse 3570750](https://www.thingiverse.com/thing:3570750),
[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). Credit the authors when you redistribute it.
- three.js loads from the jsDelivr CDN at run time (MIT).
- Scene rasters in `data/` are not in the repository. Each source has its own terms; see
[NOTRE_DAME.md](NOTRE_DAME.md) and [CHBANIYEH.md](CHBANIYEH.md).
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues