diff --git a/.agents/skills/bump-version-and-release/SKILL.md b/.agents/skills/bump-version-and-release/SKILL.md index dd5c303aa..8409f65cb 100644 --- a/.agents/skills/bump-version-and-release/SKILL.md +++ b/.agents/skills/bump-version-and-release/SKILL.md @@ -15,7 +15,7 @@ Bump the `VERSION=` line in `/.env` whenever a pull request **materially changes Bump VERSION when the PR touches: -- Any `Dockerfile` under `robot/`, `simulation/isaac-sim/`, `simulation/ms-airsim/`, `gcs/`, `common/`, or `tests/docker/` +- Any `Dockerfile` under `robot/`, `simulation/isaac-sim/`, `simulation/ms-airsim/`, `simulation/project-airsim/`, `gcs/`, `common/`, or `tests/docker/` - `docker-compose.yaml` or any included sub-compose file (when the change affects what is built or installed into images) - Code that is **baked into** an image (i.e., copied during build, not bind-mounted at runtime). The workspace is bind-mounted (`DOCKER_IMAGE_BUILD_MODE` is a tag discriminator only — a real `prebuilt` workspace-baked stage is future work), so source-only changes under `robot/ros_ws/src/**` do not strictly require a rebuild — but bumping is still safer if you are unsure. - Apt packages, pip requirements, ROS package manifests installed during the build diff --git a/.agents/skills/configure-multi-robot/SKILL.md b/.agents/skills/configure-multi-robot/SKILL.md index 04b1ff940..37466074a 100644 --- a/.agents/skills/configure-multi-robot/SKILL.md +++ b/.agents/skills/configure-multi-robot/SKILL.md @@ -26,7 +26,7 @@ If you only ever touch one robot, you can usually skip this skill — but the mo ## Prerequisites -- Familiarity with the AirStack docker-compose layout (`.env`, `robot/docker/`, `simulation/{isaac-sim,ms-airsim}/`) +- Familiarity with the AirStack docker-compose layout (`.env`, `robot/docker/`, `simulation/{isaac-sim,ms-airsim,project-airsim}/`) - Basic understanding of ROS 2 namespaces and TF frame names - You have already read [`docs/robot/docker/robot_identity.md`](../../../docs/robot/docker/robot_identity.md), or are willing to as you go — that file is the canonical reference for the resolution mechanism @@ -269,7 +269,7 @@ self.target_frame = f"{robot_name}/base_link" ## Sim-Side Robot Spawning -Both simulators read `NUM_ROBOTS` from the environment and spawn matching vehicles named `robot_1`, `robot_2`, … so the names line up with what the resolver assigns to robot containers. +Every PX4 simulator (Isaac Sim, Microsoft AirSim, Project AirSim) reads `NUM_ROBOTS` from the environment and spawn matching vehicles named `robot_1`, `robot_2`, … so the names line up with what the resolver assigns to robot containers. ### Microsoft AirSim (legacy) @@ -288,6 +288,10 @@ Both simulators read `NUM_ROBOTS` from the environment and spawn matching vehicl The `ms-airsim` container's `entrypoint.sh` (in `simulation/ms-airsim/docker/`) loops `for i in $(seq 1 "$NUM_ROBOTS")` to start one PX4 SITL instance per vehicle. AirSim binds them via the per-robot TCP ports. +### Project AirSim + +[`simulation/project-airsim/config/generate_scene.py`](../../../simulation/project-airsim/config/generate_scene.py) writes one scene with a vehicle per robot: from the fleet file when `FLEET_CONFIG_FILE` is set (each robot's `spawn:` and optional `physics:`), else `robot_1..robot_NUM_ROBOTS` spaced `PROJECT_AIRSIM_SPAWN_SPACING` m (default 3) apart along x. The `project-airsim` container's `entrypoint.sh` then starts one PX4 SITL instance (`-i $i`) per generated robot. See [Fleets → Simulation](../../../docs/development/fleets.md#simulation) for physics resolution. + ### Isaac Sim (Pegasus) With a fleet, [`fleet_spawn.py`](../../../simulation/isaac-sim/launch_scripts/fleet_spawn.py) is selected automatically: spawn positions come from each robot's `spawn:`, the scene from `sim.scene`, and sensor toggles from the vehicle manifests (any `lidar*` sensor enables the RTX lidar subgraph — the per-vehicle `ENABLE_LIDAR` equivalent). The legacy path: @@ -389,7 +393,7 @@ Two developers on the same LAN running `airstack up` will see each other's robot ### 6. Forgetting to pass `NUM_ROBOTS` to the simulator container -Both Isaac Sim and AirSim read `NUM_ROBOTS` themselves at startup. `airstack up` and the test harness propagate it for you, but if you start the simulator alone (e.g. `docker compose up isaac-sim`), the simulator will spawn 1 drone regardless of how many robot containers you started. Always set `NUM_ROBOTS` at the top-level invocation, not after the simulator is already running. +Isaac Sim, Microsoft AirSim, and Project AirSim read `NUM_ROBOTS` themselves at startup. `airstack up` and the test harness propagate it for you, but if you start the simulator alone (e.g. `docker compose up isaac-sim`), the simulator will spawn 1 drone regardless of how many robot containers you started. Always set `NUM_ROBOTS` at the top-level invocation, not after the simulator is already running. ### 7. Hardcoded TF frame `base_link` from outside the namespace @@ -487,6 +491,7 @@ docker exec -e ROS_DOMAIN_ID=1 airstack-robot-desktop-1 bash -c \ - [`robot/ros_ws/src/autonomy_bringup/launch/robot.launch.xml`](../../../robot/ros_ws/src/autonomy_bringup/launch/robot.launch.xml) — top-level `push_ros_namespace` - [`robot/ros_ws/src/autonomy_bringup/config/dds_router.yaml`](../../../robot/ros_ws/src/autonomy_bringup/config/dds_router.yaml) — cross-domain allowlist pattern - [`simulation/ms-airsim/config/generate_settings.py`](../../../simulation/ms-airsim/config/generate_settings.py) and [`settings.json.j2`](../../../simulation/ms-airsim/config/settings.json.j2) +- [`simulation/project-airsim/config/generate_scene.py`](../../../simulation/project-airsim/config/generate_scene.py) - [`simulation/isaac-sim/launch_scripts/example_multi_px4_pegasus_launch_script.py`](../../../simulation/isaac-sim/launch_scripts/example_multi_px4_pegasus_launch_script.py) - [`tests/conftest.py`](../../../tests/conftest.py) — `airstack_env` fixture and `--num-robots` parametrization diff --git a/.agents/skills/create-module/SKILL.md b/.agents/skills/create-module/SKILL.md index 72e121d50..7477a9c98 100644 --- a/.agents/skills/create-module/SKILL.md +++ b/.agents/skills/create-module/SKILL.md @@ -60,7 +60,7 @@ Summary: `license`, `type` (`isaac_extension` | `ros_package` | `data` | `platform`), `airstack_compat` (semver range vs trunk `.env` `VERSION`, e.g. `">=0.19.0 <0.21.0"` — never a branch name), `targets` - (non-empty: `robot` | `gcs` | `isaac-sim` | `ms-airsim`). + (non-empty: `robot` | `gcs` | `isaac-sim` | `ms-airsim` | `project-airsim`). - **Optional:** `deps` `{apt, pip}`, `dockerfile` (path ending `Dockerfile.module`), `overlay_image`, `compose`, `assets` (`[{url (https), sha256, dest}]` — no Git LFS), `docs`, `foxglove`, `hooks` diff --git a/.agents/skills/run-system-tests/SKILL.md b/.agents/skills/run-system-tests/SKILL.md index 262b4019f..9636c7a1a 100644 --- a/.agents/skills/run-system-tests/SKILL.md +++ b/.agents/skills/run-system-tests/SKILL.md @@ -52,8 +52,8 @@ For details on the co-located layout and adding new unit tests, see the | File | Mark | What it tests | Hardware required | |------|------|---------------|-------------------| -| `tests/system/test_build_docker.py` | `build_docker` | `airstack images build` for `robot-desktop`, `gcs`, `isaac-sim`, `ms-airsim`; records image size to `metrics.json` | Docker daemon | -| `tests/system/test_build_packages.py` | `build_packages` | `colcon build` (`bws`) inside the robot, GCS, and ms-airsim ROS workspaces — brought up with `AUTOLAUNCH=false` | Docker daemon | +| `tests/system/test_build_docker.py` | `build_docker` | `airstack images build` for `robot-desktop`, `gcs`, `isaac-sim`, `ms-airsim`, `project-airsim`; records image size to `metrics.json` | Docker daemon | +| `tests/system/test_build_packages.py` | `build_packages` | `colcon build` (`bws`) inside the robot, GCS, ms-airsim, and project-airsim ROS workspaces — brought up with `AUTOLAUNCH=false` | Docker daemon | | `tests/system/test_liveliness.py` | `liveliness` | Stack bring-up: containers Running, `/clock` readiness, tmux panes, sentinel ROS 2 nodes, compute, infra-only `test_stable` | Docker daemon, NVIDIA GPU + `nvidia-container-toolkit`, sim license / Omniverse creds | | `tests/system/test_sensors.py` | `sensors` | Topic Hz (Isaac: batched on sim + robot; LiDAR `echo-once` + cloud sanity), RTF, `test_sensor_streams_stable` | Docker daemon, NVIDIA GPU + `nvidia-container-toolkit`, sim license / Omniverse creds | | `tests/system/test_takeoff_hover_land.py` | `takeoff_hover_land` | 4-phase flight chain per `(sim, num_robots, iteration, velocity)`: `test_px4_ready` → `test_takeoff` → `test_hover` → `test_landing`. Records altitude error, overshoot, hover stability, landing accuracy, odometry drift | Docker daemon, NVIDIA GPU, sim license | @@ -99,8 +99,8 @@ rates if too many `ros2 topic hz` processes run concurrently. - **Sim-side (Isaac):** three `parallel_sample_hz` passes — `/clock`, then both `image_rect` topics, then both `depth_ground_truth` topics. - **Robot-side (Isaac):** two passes — both stereo images, then both depths. - **ms-airsim** keeps a single four-topic parallel batch on the robot container. -- **Filtered LiDAR** (`PointCloud2`): uses `ros2 topic echo --once` per robot + **ms-airsim** and **project-airsim** keep a single four-topic parallel batch on the robot container. +- **Filtered LiDAR** (`PointCloud2`, sims with `has_lidar` in `SIM_CONFIG`: `isaacsim`, `projectairsim`): uses `ros2 topic echo --once` per robot (see `parallel_echo_once_robot_topics` in `tests/harness/sim.py`), not `topic hz`. - **Multi-drone Pegasus script:** pytest sets `ENABLE_LIDAR=true` in `conftest.py` `SIM_CONFIG["isaacsim"]["extra_env"]` so LiDAR matches the @@ -178,7 +178,7 @@ The `airstack_env` fixture is parametrized over `(sim, num_robots, iteration)` t | Flag | Default | Affects | Becomes | |------|---------|---------|---------| -| `--sim` | `isaacsim` | `airstack_env` | One env-tuple per sim (`msairsim` opt-in) | +| `--sim` | `isaacsim` | `airstack_env` | One env-tuple per sim (`msairsim`, `projectairsim` opt-in) | | `--num-robots` | `1,3` | `airstack_env` | Cross-product with sim | | `--stack` | `None` (= `full_default`) | `airstack_env` | Stack folder under `stacks/` to launch (sets `AIRSTACK_STACK_DIR` for `airstack up`); the `wiring` test drift-checks against `stacks//wiring.md` | | `--fleet` | `None` (legacy `--num-robots` behavior) | `airstack_env` | Fleet preset under `config/fleets/` (e.g. `sim_three_mixed`); sets `FLEET_CONFIG_FILE` and derives `NUM_ROBOTS` from the fleet's robot count, **overriding `--num-robots`** | @@ -385,9 +385,9 @@ If multiple tests need the same setup, add a fixture in `conftest.py` (not in yo - **Forgetting `build_packages`**. If you run `-m liveliness` locally on a fresh checkout, the workspace inside the container is empty and sentinel nodes won't appear. Either run `-m "build_packages or liveliness"` or rely on the CI auto-prepend. - **Mixing marks unintentionally**. `-m "liveliness or takeoff_hover_land"` brings the stack up once per selected mark's test classes (per parametrization). `-m "liveliness or sensors"` runs **both** classes for each tuple — **two** full ``airstack up`` / ``down`` cycles per `(sim, robots, iter)` because ``airstack_env`` is class-scoped. Combine deliberately, not by reflex. - **Running on insufficient hardware**. `liveliness`, `sensors`, and `takeoff_hover_land` require an NVIDIA GPU plus nvidia-container-toolkit; without them the sim container won't get GPU access and topic Hz checks will time out. If you only have a CPU, scope to `-m "build_docker or build_packages"`. -- **Expecting interactive sim feedback**. `airstack_env` runs headless by default (`MS_AIRSIM_HEADLESS=true`, `ISAAC_SIM_HEADLESS=true`, `QT_QPA_PLATFORM=offscreen`). Don't add stdin prompts, GUI dialogs, or `input()` calls to test code — they will hang in CI. For local visual debugging only, pass `--gui`. +- **Expecting interactive sim feedback**. `airstack_env` runs headless by default (`MS_AIRSIM_HEADLESS=true`, `PROJECT_AIRSIM_HEADLESS=true`, `ISAAC_SIM_HEADLESS=true`, `QT_QPA_PLATFORM=offscreen`). Don't add stdin prompts, GUI dialogs, or `input()` calls to test code — they will hang in CI. For local visual debugging only, pass `--gui`. - **Not capturing metrics in a new test**. If a test fails silently (no metric recorded) the regression report has nothing to compare. Always record at least one scalar via `MetricsRecorder` so the test shows up in `metrics.json`. -- **Letting parametrize cardinality explode**. Default `--num-robots 1,3` (and `--sim msairsim` if you opt in) multiplies stack bring-ups for each selected mark (`liveliness`, `sensors`, `takeoff_hover_land`, …) — expensive. Override locally to a single tuple while iterating. `--sim` defaults to `isaacsim` only. +- **Letting parametrize cardinality explode**. Default `--num-robots 1,3` (and each extra `--sim` target you opt in, e.g. `msairsim`, `projectairsim`) multiplies stack bring-ups for each selected mark (`liveliness`, `sensors`, `takeoff_hover_land`, …) — expensive. Override locally to a single tuple while iterating. `--sim` defaults to `isaacsim` only. - **Hardcoded container names**. Always use `find_container`, `get_robot_containers`, or `wait_for_container` — replica suffixes (`-1`, `-2`, `-3`) and compose project prefixes change. - **Asserting on stdout instead of using `read_log_tail`**. The conftest captures each subprocess's combined stdout/stderr in memory; assertions should reference it via `read_log_tail()` (`f"airstack up failed:\n{read_log_tail()}"`) so failures attach the relevant context to the JUnit XML. - **Trying to SSH into a CI runner mid-job**. Workers are ephemeral OSMO pods destroyed after job completion. Re-running creates a fresh pod. For genuine runner debugging, see `.github/orchestrator/README.md` (also exposed at `tests/ci-cd-orchestrator.md`) — but in most cases, reproduce locally with `airstack test`. diff --git a/.agents/skills/use-airstack-cli/SKILL.md b/.agents/skills/use-airstack-cli/SKILL.md index 1147a112f..64cfd0e02 100644 --- a/.agents/skills/use-airstack-cli/SKILL.md +++ b/.agents/skills/use-airstack-cli/SKILL.md @@ -13,7 +13,7 @@ metadata: Use this skill any time you need to: -- Start, stop, or inspect AirStack services (robot, isaac-sim, ms-airsim, gcs, docs) +- Start, stop, or inspect AirStack services (robot, isaac-sim, ms-airsim, project-airsim, gcs, docs) - Launch a specific **stack** (`--stack`) or **fleet** (`--fleet`) - Manage **modules** (`airstack module add|list|sync|remove|create|lock|doctor`) - Build or source the ROS 2 workspace inside a container @@ -68,11 +68,12 @@ plus optional compose service names and passthrough flags (`--build`, `--recreat | Flag | What it does | |------|--------------| -| `--sim isaac\|airsim` | Selects the simulator: swaps the compose profile (`isaac-sim` / `ms-airsim`) and the matching `URDF_FILE` | +| `--sim isaac\|airsim\|projectairsim\|simple` | Selects the simulator: swaps the compose profile (`isaac-sim` / `ms-airsim` / `project-airsim` / `simple`) and the matching `URDF_FILE`. `airsim` = Microsoft AirSim (legacy, UE4); `projectairsim` (aliases `pas`, `project-airsim`) = Project AirSim (UE5, stereo + depth + LiDAR) | | `--robots N` | Exports `NUM_ROBOTS=N`; on Isaac also keeps `ISAAC_SIM_SCRIPT_NAME` consistent (auto-selects the multi-drone script for N>1) | | `--stack NAME[:ENTRY]` | Launches `stacks/NAME/launch/ENTRY.launch.xml` (default entry: `stack`). Stacks are the **only** launch dispatch; no `--stack` = `full_default`. `NAME:onboard` / `NAME:offboard` select split-stack entries | | `--fleet NAME` | Launches `config/fleets/NAME.yaml`: validates it, exports `FLEET_CONFIG_FILE`, derives `NUM_ROBOTS`, selects the Isaac fleet spawner (`fleet_spawn.py`), and for heterogeneous fleets includes the generated per-robot services. Mutually exclusive with `--robots` | -| `--headless` | Sets `ISAAC_SIM_HEADLESS=true`, `MS_AIRSIM_HEADLESS=true`, `QT_QPA_PLATFORM=offscreen` | +| `--headless` | Sets `ISAAC_SIM_HEADLESS=true`, `MS_AIRSIM_HEADLESS=true`, `PROJECT_AIRSIM_HEADLESS=true`, `QT_QPA_PLATFORM=offscreen` | +| `--physics fast-physics\|jsbsim` | Project AirSim only: exports `PROJECT_AIRSIM_PHYSICS` (vehicle dynamics for every robot; default `fast-physics`, `jsbsim` experimental) | | `--play` / `--no-play` | Whether the sim auto-presses Play on start (`PLAY_SIM_ON_START`) | | `--no-autolaunch` | Containers start **idle** (no tmuxinator launch sequence) — the development mode | | `--wait` | Block until the stack is flight-ready (runs `airstack ready` after up) | @@ -82,6 +83,7 @@ plus optional compose service names and passthrough flags (`--build`, `--recreat airstack up # default profile from .env airstack up --sim isaac --robots 2 # Isaac, two robots, consistent sim script airstack up --sim airsim --headless --play --wait +airstack up --sim projectairsim --scene neighborhood # Project AirSim (UE5), LiDAR + stereo airstack up --stack lite_default --sim isaac # launch a specific stack airstack up --stack lite_offload_global:offboard # split-stack ground half airstack up --fleet sim_three_mixed --sim isaac # fleet launch (RFC #380) @@ -141,9 +143,10 @@ rebuild on next up) — it does **not** touch containers, volumes, or networks. ### Container naming convention Compose generates names of the form `--`. With the default -`PROJECT_NAME="airstack"`: `airstack-robot-desktop-1`, `airstack-isaac-sim-1`, -`airstack-ms-airsim-1`, `airstack-gcs-1`, `airstack-docs-1`. With `--robots 2` you -also get `airstack-robot-desktop-2`. Always confirm with `airstack status` or +`PROJECT_NAME="airstack"`: `airstack-robot-desktop-1`, `airstack-gcs-1`, +`airstack-docs-1`. With `--robots 2` you also get `airstack-robot-desktop-2`. +Simulator services set a fixed `container_name` instead: `isaac-sim`, +`ms-airsim`, `project-airsim`. Always confirm with `airstack status` or `docker ps --format '{{.Names}}'` rather than guessing. ## Modules, Stacks, Fleets, Doctor (RFC #379/#380) @@ -200,7 +203,7 @@ and which ground hosts run split-stack offboard halves. Guide: airstack fleet list # table: robots, vehicles, stacks, shape (homogeneous/heterogeneous/+split) airstack fleet generate # write .airstack/generated/docker-compose.fleet.yaml (heterogeneous only; # homogeneous fleets need no generation — deploy.replicas handles them) -airstack up --fleet [--sim isaac|airsim] +airstack up --fleet [--sim isaac|airsim|projectairsim] ``` ### Sync from `airstack.yaml` @@ -374,7 +377,7 @@ For full details on **pytest system tests** (fixtures, all 11 marks, `--stack` / `--fleet` options, metrics, `/pytest` CI), see the [`run-system-tests`](../run-system-tests/SKILL.md) skill and [`tests/README.md`](../../../tests/README.md). For **authoring and running -scenarios inside Isaac Sim or AirSim** (missions, RViz checks, scene tweaks), see +scenarios inside Isaac Sim, Project AirSim, or AirSim** (missions, RViz checks, scene tweaks), see the [`test-in-simulation`](../test-in-simulation/SKILL.md) skill. ### Lint and format @@ -471,7 +474,7 @@ airstack commands # list every registered command airstack install # Install Docker + nvidia-container-toolkit (one time) airstack setup # Shell function, submodules, config, module sync (one time) airstack up # Start default profile from .env (stack: full_default) -airstack up --sim isaac|airsim # Pick the simulator (profile + URDF + Isaac script derived) +airstack up --sim isaac|airsim|projectairsim|simple # Pick the simulator (profile + URDF + Isaac script derived) airstack up --sim isaac --robots 2 # Multi-robot (keeps NUM_ROBOTS and the sim script consistent) airstack up --stack lite_default --sim isaac # Launch a specific stack airstack up --stack lite_offload_global:offboard # Split-stack entry point diff --git a/.airstack/modules/module.sh b/.airstack/modules/module.sh index a04bf6267..895f54607 100755 --- a/.airstack/modules/module.sh +++ b/.airstack/modules/module.sh @@ -581,7 +581,7 @@ maintainer: ${maintainer} license: TODO type: ros_package # isaac_extension | ros_package | data | platform airstack_compat: "${compat}" -targets: [robot] # host containers touched: robot | gcs | isaac-sim | ms-airsim +targets: [robot] # host containers touched: robot | gcs | isaac-sim | ms-airsim | project-airsim deps: {apt: [], pip: []} # dep tier 1; rosdep keys live in package.xml dockerfile: null # tier 2: Dockerfile.module using ARG BASE_IMAGE diff --git a/.airstack/modules/ready.sh b/.airstack/modules/ready.sh index cd9a3e76b..44c0f6c76 100644 --- a/.airstack/modules/ready.sh +++ b/.airstack/modules/ready.sh @@ -153,7 +153,7 @@ function _ready_run_gates { results[sim_clock]=ok else results[sim_clock]=failed - log_error "Sim never published /clock. Inspect the sim: airstack connect isaac-sim (or ms-airsim), or airstack logs " + log_error "Sim never published /clock. Inspect the sim: airstack connect isaac-sim (or ms-airsim / project-airsim), or airstack logs " log_error "If PLAY_SIM_ON_START=false, press Play in the Isaac Sim window." READY_OVERALL=1 fi diff --git a/.env b/.env index 05ac8adb4..e6d082aba 100644 --- a/.env +++ b/.env @@ -12,7 +12,7 @@ PROJECT_NAME="airstack" # If you've run ./airstack.sh setup, then this will auto-generate from the git commit hash every time a change is made # to a Dockerfile or docker-compose.yaml file. Otherwise this can also be set explicitly to make a release version. # auto-generated from git commit hash -VERSION="0.21.0-dev.18" +VERSION="0.21.0-dev.19" # Image-tag discriminator ONLY (appears in the image tag suffix, e.g. ..._robot-x86-64_dev). # No Dockerfile consumes it: "prebuilt" does NOT bake the built ros_ws into the image today — # a real prebuilt (workspace-baked) stage is future work. Keep "dev" (mounted code, built live). @@ -55,6 +55,21 @@ PLAY_SIM_ON_START="true" # Sim starts PLAYING by default (launch with `airstack # MS_AIRSIM_BINARY_PATH="/ms-airsim-env/Blocks/LinuxNoEditor/Blocks.sh" # ================================================= +# ================= PROJECT-AIRSIM ================ +# Packaged UE5 environment, set by `airstack up --sim projectairsim --scene +# ` (see simulation/scenes.yaml). A fetch_env.sh key; auto-fetched +# from the Project AirSim GitHub release on first launch. Empty = blocks. +# PROJECT_AIRSIM_ENV="blocks" +# Vehicle dynamics for every robot: fast-physics (default) | jsbsim +# (`airstack up --physics ...`; per-robot: fleet robots..physics). +# PROJECT_AIRSIM_PHYSICS="fast-physics" +# PROJECT_AIRSIM_ENV_DIR=./simulation/project-airsim/assets/envs +# PROJECT_AIRSIM_BINARY_PATH="/project-airsim-env/Blocks/Blocks.sh" +# Release whose environments are fetched; must match the client the image +# compiles (PROJECT_AIRSIM_REF build arg in simulation/project-airsim/docker/Dockerfile). +# PROJECT_AIRSIM_RELEASE="v1.1.0" +# ================================================= + # ================= ROBOT ===================== ROBOT_NAME_MAP_CONFIG_FILE="default_robot_name_map.yaml" # Determines how to set ROBOT_NAME and ROS_DOMAIN_ID. See robot/docker/robot_name_map/ diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml index 403864781..aec24c834 100644 --- a/.github/workflows/docker-build.yml +++ b/.github/workflows/docker-build.yml @@ -10,7 +10,7 @@ on: compose_profiles: description: 'Docker Compose profiles to build (comma-separated)' required: false - default: 'desktop,isaac-sim,ms-airsim' + default: 'desktop,isaac-sim,ms-airsim,project-airsim' type: string force_rebuild: description: 'Force a full rebuild of every service (skip retag)' @@ -19,7 +19,7 @@ on: type: boolean env: - DEFAULT_PROFILES: 'desktop,isaac-sim,ms-airsim' + DEFAULT_PROFILES: 'desktop,isaac-sim,ms-airsim,project-airsim' jobs: check-docker-tag-change: diff --git a/.github/workflows/module-system-tests.yml b/.github/workflows/module-system-tests.yml index 781298ab6..ff084290f 100644 --- a/.github/workflows/module-system-tests.yml +++ b/.github/workflows/module-system-tests.yml @@ -51,7 +51,7 @@ on: type: string default: "build_packages or liveliness" sim: - description: "Sim targets, comma-separated: isaacsim,msairsim." + description: "Sim targets, comma-separated: isaacsim,msairsim,projectairsim." type: string default: "isaacsim" num_robots: @@ -116,7 +116,7 @@ on: type: string default: "build_packages or liveliness" sim: - description: "Sim targets, comma-separated: isaacsim,msairsim." + description: "Sim targets, comma-separated: isaacsim,msairsim,projectairsim." type: string default: "isaacsim" num_robots: @@ -403,7 +403,7 @@ jobs: # The ephemeral runner starts with no local images. `airstack_env` in # tests/conftest.py fails fast if compose images are missing, so prep - # them here. Profile-gated services (ms-airsim, isaac-sim) are skipped + # them here. Profile-gated services (ms-airsim, project-airsim, isaac-sim) are skipped # by compose unless their profile is active, so we mirror the fixture's # profile selection from the sim input. Pull versioned tags, then retag # floating cache_* tags onto the VERSION name (unreleased trunk refs @@ -419,6 +419,7 @@ jobs: run: | profiles=desktop [[ ",$SIM_INPUT," == *,msairsim,* ]] && profiles="$profiles,ms-airsim" + [[ ",$SIM_INPUT," == *,projectairsim,* ]] && profiles="$profiles,project-airsim" [[ ",$SIM_INPUT," == *,isaacsim,* ]] && profiles="$profiles,isaac-sim" export COMPOSE_PROFILES="$profiles" echo "Pulling images for COMPOSE_PROFILES=$COMPOSE_PROFILES (no_image_build=$NO_IMAGE_BUILD)" diff --git a/.github/workflows/scripts/docker_image_plan.py b/.github/workflows/scripts/docker_image_plan.py index 5f35b88d0..a42d47f24 100755 --- a/.github/workflows/scripts/docker_image_plan.py +++ b/.github/workflows/scripts/docker_image_plan.py @@ -53,6 +53,13 @@ "simulation/ms-airsim/docker/docker-compose.yaml", "simulation/ms-airsim/docker/entrypoint.sh", ], + # The Project AirSim client pin (PROJECT_AIRSIM_REF/SHA build-arg + # defaults) lives in the Dockerfile, so a version bump changes the hash. + "project-airsim": [ + "simulation/project-airsim/docker/Dockerfile", + "simulation/project-airsim/docker/docker-compose.yaml", + "simulation/project-airsim/docker/entrypoint.sh", + ], } # Extra roots when DOCKER_IMAGE_BUILD_MODE=prebuilt (workspace baked into image). @@ -428,7 +435,7 @@ def main(argv: list[str] | None = None) -> int: parser.add_argument( "--profiles", default="", - help="Compose profiles (default: COMPOSE_PROFILES or desktop,isaac-sim,ms-airsim)", + help="Compose profiles (default: COMPOSE_PROFILES or desktop,isaac-sim,ms-airsim,project-airsim)", ) parser.add_argument( "--force-rebuild", @@ -479,7 +486,7 @@ def main(argv: list[str] | None = None) -> int: args.profiles or os.environ.get("COMPOSE_PROFILES") or env.get("COMPOSE_PROFILES") - or "desktop,isaac-sim,ms-airsim" + or "desktop,isaac-sim,ms-airsim,project-airsim" ) plan = build_plan( diff --git a/.github/workflows/system-tests.yml b/.github/workflows/system-tests.yml index bf7d99cbf..940418ff4 100644 --- a/.github/workflows/system-tests.yml +++ b/.github/workflows/system-tests.yml @@ -15,7 +15,7 @@ on: default: "liveliness or takeoff_hover_land" required: false sim: - description: "Sim targets, comma-separated: isaacsim,msairsim. Default isaacsim; pass msairsim to opt in." + description: "Sim targets, comma-separated: isaacsim,msairsim,projectairsim. Default isaacsim; pass msairsim or projectairsim to opt in." default: isaacsim required: false num_robots: @@ -373,7 +373,7 @@ jobs: # The ephemeral runner starts with no local images. `airstack_env` in # tests/conftest.py fails fast if compose images are missing, so prep - # them here. Profile-gated services (ms-airsim, isaac-sim) are skipped + # them here. Profile-gated services (ms-airsim, project-airsim, isaac-sim) are skipped # by compose unless their profile is active, so we mirror the fixture's # profile selection from the parsed --sim. Pull versioned tags, then # retag floating cache_* tags onto the VERSION name (PR tags never @@ -388,6 +388,7 @@ jobs: run: | profiles=desktop [[ ",$SIM_INPUT," == *,msairsim,* ]] && profiles="$profiles,ms-airsim" + [[ ",$SIM_INPUT," == *,projectairsim,* ]] && profiles="$profiles,project-airsim" [[ ",$SIM_INPUT," == *,isaacsim,* ]] && profiles="$profiles,isaac-sim" export COMPOSE_PROFILES="$profiles" echo "Pulling images for COMPOSE_PROFILES=$COMPOSE_PROFILES (no_image_build=$NO_IMAGE_BUILD)" diff --git a/.gitignore b/.gitignore index 0d67d9654..0e39981da 100644 --- a/.gitignore +++ b/.gitignore @@ -86,6 +86,9 @@ gcs/saves/* # Downloaded UE4 scene binaries (fetched via assets/scenes/fetch_scene.sh) simulation/ms-airsim/assets/scenes/* !simulation/ms-airsim/assets/scenes/fetch_scene.sh +# Project AirSim packaged UE5 environments (fetched on first launch, 0.9-3.3 GB each) +simulation/project-airsim/assets/envs/* +!simulation/project-airsim/assets/envs/fetch_env.sh # Test results tests/results/ diff --git a/AGENTS.md b/AGENTS.md index e7dae30fe..64b4729bb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ This file provides guidance to AI coding agents (OpenHands, Claude Code, etc.) w **Project:** AirStack - Comprehensive autonomous aerial robotics stack developed by AirLab CMU -**Stack:** ROS 2 Jazzy | Docker-based development | Isaac Sim with Pegasus extension | Microsoft AirSim (legacy, UE4) | Field robotics +**Stack:** ROS 2 Jazzy | Docker-based development | Isaac Sim with Pegasus extension | Project AirSim (UE5) | Microsoft AirSim (legacy, UE4) | Field robotics **Primary Goal:** Enable agents to understand the architecture, implement new algorithms/modules, and integrate them correctly into the layered autonomy stack. @@ -14,7 +14,7 @@ This file provides guidance to AI coding agents (OpenHands, Claude Code, etc.) w AirStack provides a complete end-to-end system for autonomous drone operations including: - Modular autonomy stack (interface, sensors, perception, local planning, global planning, behavior) -- High-fidelity simulation environments (Isaac Sim with Pegasus extension, Microsoft AirSim legacy/UE4) +- High-fidelity simulation environments (Isaac Sim with Pegasus extension, Project AirSim/UE5, Microsoft AirSim legacy/UE4) - Ground Control Station for mission planning and monitoring - Multi-robot coordination capabilities - Hardware deployment tools @@ -44,6 +44,7 @@ AirStack/ │ └── behavior/ # High-level mission execution ├── simulation/isaac-sim/ # Isaac Sim (Pegasus extension) ├── simulation/ms-airsim/ # AirSim (UE4 + PX4 SITL) +├── simulation/project-airsim/ # Project AirSim (UE5 + PX4 SITL + C++ ROS 2 bridge) ├── gcs/ # Ground Control Station ├── common/ # Shared packages & utilities ├── docs/ # MkDocs documentation @@ -176,7 +177,7 @@ airstack install # Install Docker and dependencies # Container management airstack up [service] # Start services (robot, isaac-sim, gcs) -airstack up --sim isaac|airsim --robots N # Intent flags: derive profiles/URDF/sim script (add --headless, --play/--no-play, --no-autolaunch, --wait, --dry-run, --config-only) +airstack up --sim isaac|airsim|projectairsim|simple --robots N # Intent flags: derive profiles/URDF/sim script (add --headless, --play/--no-play, --no-autolaunch, --wait, --dry-run, --config-only) airstack up --stack [:] --sim isaac # Stack launch (RFC #379): stacks//launch/.launch.xml — the ONLY dispatch (no --stack = full_default; legacy AUTONOMY_ROLE was removed); see docs/development/stacks.md airstack up --fleet --sim isaac # Fleet launch (RFC #380): config/fleets/.yaml drives identity/placement/spawns; see docs/development/fleets.md airstack fleet list|generate # Fleet files: table / per-robot compose for heterogeneous fleets @@ -251,7 +252,7 @@ docker exec airstack-robot-desktop-1 bash -c "ros2 topic echo --onc 2. **Unit tests (`pytest`, `unit` mark):** Fast, hermetic checks. Test **source** lives co-located with each ROS 2 package in `/test/` (standard colcon convention). [`tests/colcon_unit_test_packages.yaml`](tests/colcon_unit_test_packages.yaml) lists which packages have unit tests, and `tests/conftest.py` collects them from there under `--import-mode=importlib`. To add a package's unit tests, list it in that YAML. Python unit tests run automatically in `unit-tests.yml` on `ubuntu-latest`; C++ gtests run through the `system-tests.yml` `build_packages` path. Example: `airstack test -m unit -v`. See `add-unit-tests` skill. -3. **System Level (`tests/system/`):** Full simulation tests (Isaac Sim or Microsoft AirSim legacy) +3. **System Level (`tests/system/`):** Full simulation tests (Isaac Sim, Project AirSim, or Microsoft AirSim legacy) - End-to-end autonomy stack testing - Real sensor simulation - Multi-robot scenarios @@ -263,10 +264,10 @@ Pytest-based system tests live under [`tests/system/`](tests/system/). They brin | File | Mark | What it tests | Hardware | |------|------|---------------|----------| -| [`tests/system/test_build_docker.py`](tests/system/test_build_docker.py) | `build_docker` | Docker image builds (robot-desktop, gcs, isaac-sim, ms-airsim) | Docker | +| [`tests/system/test_build_docker.py`](tests/system/test_build_docker.py) | `build_docker` | Docker image builds (robot-desktop, gcs, isaac-sim, ms-airsim, project-airsim) | Docker | | [`tests/system/test_build_packages.py`](tests/system/test_build_packages.py) | `build_packages` | `colcon build` inside each container | Docker | | [`tests/system/test_liveliness.py`](tests/system/test_liveliness.py) | `liveliness` | Stack bring-up: containers, ``/clock`` readiness, tmux, sentinel ROS 2 nodes, compute, infra-only stability poll | Docker, GPU, sim license | -| [`tests/system/test_sensors.py`](tests/system/test_sensors.py) | `sensors` | Topic Hz (Isaac: batched sim + robot ``ros2 topic hz``; filtered LiDAR ``echo-once`` + validation script), RTF, sensor stability time-series | Docker, GPU, sim license | +| [`tests/system/test_sensors.py`](tests/system/test_sensors.py) | `sensors` | Topic Hz (Isaac: batched sim + robot ``ros2 topic hz``; filtered LiDAR ``echo-once`` + validation script on Isaac and Project AirSim), RTF, sensor stability time-series | Docker, GPU, sim license | | [`tests/system/test_takeoff_hover_land.py`](tests/system/test_takeoff_hover_land.py) | `takeoff_hover_land` | 4-phase flight chain (PX4 ready → takeoff → hover → land) per (sim, num_robots, iter, velocity) | Docker, GPU, sim license | | [`tests/system/test_fixed_trajectory.py`](tests/system/test_fixed_trajectory.py) | `autonomy` | 4-phase flight chain (PX4 ready → takeoff → execute Circle/Figure8/Racetrack/Line trajectory → land) per (sim, num_robots, iter, trajectory_type); records cross-track error and path RMSE | Docker, GPU, sim license | | [`tests/system/test_waypoint_flight.py`](tests/system/test_waypoint_flight.py) | `waypoint_flight` | 4-phase flight chain (PX4 ready → takeoff → NavigateTask waypoint route → land) per (sim, num_robots, iter); pass/fail judged on the odometry track by the standalone [`tests/waypoint_checker.py`](tests/waypoint_checker.py) (in-order corridor arrival within `--waypoint-tolerance`, final goal within `--goal-tolerance`, per-waypoint `--waypoint-timeout`) | Docker, GPU, sim license | @@ -403,6 +404,7 @@ Each major component has its own Docker container: - **robot**: ROS 2 autonomy stack (Jazzy) - **isaac-sim**: NVIDIA Isaac Sim with Pegasus extension (profile: `desktop` or `robot`) - **airsim**: AirSim UE4 binary + PX4 SITL + ROS 2 bridge (profile: `ms-airsim`) +- **project-airsim**: Project AirSim UE5 packaged env + PX4 SITL + C++ ROS 2 bridge (profile: `project-airsim`) - **gcs**: Ground Control Station - **docs**: Documentation building (MkDocs) @@ -466,7 +468,7 @@ Common mistakes when adding modules: 6. **Testing Oversights** - ❌ Only testing module in isolation - ✅ Test in full autonomy stack context - - ✅ Verify in Isaac Sim or Microsoft AirSim (legacy) simulation + - ✅ Verify in Isaac Sim, Project AirSim, or Microsoft AirSim (legacy) simulation ## Key Differences from CLAUDE.md @@ -497,6 +499,7 @@ This guide supersedes `CLAUDE.md` (which now symlinks here). Key updates: - [Getting Started](docs/getting_started/index.md) - [Autonomy Stack Overview](docs/robot/autonomy/index.md) - [Isaac Sim Setup](docs/simulation/isaac_sim/index.md) +- [Project AirSim Setup](docs/simulation/project-airsim/index.md) - [Microsoft AirSim (legacy) Setup](docs/simulation/ms-airsim/index.md) - [Testing Guide](docs/development/intermediate/testing/index.md) diff --git a/airstack.sh b/airstack.sh index 8b9da5019..706dd91ed 100755 --- a/airstack.sh +++ b/airstack.sh @@ -164,9 +164,11 @@ function print_command_help { echo "Usage: airstack up [service_name] [options]" echo "" echo "Launch-intent options (consumed by airstack; they derive + export env vars):" - echo " --sim isaac|airsim|simple" + echo " --sim isaac|airsim|projectairsim|simple" echo " Select the simulator: swaps the compose profile and" - echo " the matching URDF_FILE. 'simple' launches the" + echo " the matching URDF_FILE. 'airsim' is Microsoft AirSim" + echo " (legacy, UE4); 'projectairsim' (alias 'pas') is Project" + echo " AirSim (UE5, stereo + depth + GPU LiDAR). 'simple' launches the" echo " lightweight kinematic simple-sim (no PX4/MAVROS):" echo " the simple-robot service replaces robot-desktop" echo " (SIM_TYPE=simple), the 'desktop' profile is dropped" @@ -191,8 +193,16 @@ function print_command_help { echo " exports it (Isaac: ISAAC_SIM_SCENE [+ ISAAC_SIM_STAGE_SCALE] —" echo " a Pegasus catalog key or Nucleus USD URL; MS AirSim:" echo " MS_AIRSIM_SCENE — a pre-built UE4 scene, auto-fetched if" - echo " missing). Unknown scene = error + table of available scenes." - echo " --headless Run the sim without a GUI (ISAAC_SIM_HEADLESS/MS_AIRSIM_HEADLESS)." + echo " missing; Project AirSim: PROJECT_AIRSIM_ENV — a packaged UE5" + echo " environment, auto-fetched if missing). Unknown scene = error" + echo " + table of available scenes." + echo " --physics fast-physics|jsbsim" + echo " Project AirSim only: vehicle dynamics model for every robot" + echo " (PROJECT_AIRSIM_PHYSICS; default fast-physics). Per-robot" + echo " choice: fleet robots..physics. See" + echo " docs/simulation/project-airsim/index.md." + echo " --headless Run the sim without a GUI (ISAAC_SIM_HEADLESS/MS_AIRSIM_HEADLESS/" + echo " PROJECT_AIRSIM_HEADLESS)." echo " --play / --no-play Start the sim playing, or paused (PLAY_SIM_ON_START)." echo " --no-autolaunch Start containers idle (AUTOLAUNCH=false; launch manually)." echo " --wait After starting, block until flight-ready (airstack ready)." @@ -223,7 +233,7 @@ function print_command_help { echo " (deploy.replicas handles them) — the command says so" echo " and writes nothing." echo "" - echo "Run a fleet: airstack up --fleet [--sim isaac|airsim]" + echo "Run a fleet: airstack up --fleet [--sim isaac|airsim|projectairsim]" ;; osmo) echo "Usage: airstack osmo [options]" @@ -395,7 +405,7 @@ function print_command_help { echo "" echo "AirStack-specific options (defaults from tests/conftest.py):" echo " --sim=TARGETS Comma-separated sim targets: isaacsim, msairsim," - echo " simplesim (default: isaacsim)" + echo " projectairsim, simplesim (default: isaacsim)" echo " --num-robots=COUNTS Comma-separated robot counts (default: 1,3)" echo " --stack=NAME Stack folder under stacks/ to launch (default:" echo " the full_default dispatch)" @@ -1139,6 +1149,7 @@ function parse_launch_intent { AIRSTACK_INTENT_STACK="" AIRSTACK_INTENT_FLEET="" AIRSTACK_INTENT_SCENE="" + AIRSTACK_INTENT_PHYSICS="" AIRSTACK_FLEET_COMPOSE_FILE="" AIRSTACK_DRY_RUN="" AIRSTACK_CONFIG_ONLY="" @@ -1162,6 +1173,8 @@ function parse_launch_intent { --fleet=*) AIRSTACK_INTENT_FLEET="${a#--fleet=}";; --scene) i=$((i+1)); AIRSTACK_INTENT_SCENE="${args[$i]:-}";; --scene=*) AIRSTACK_INTENT_SCENE="${a#--scene=}";; + --physics) i=$((i+1)); AIRSTACK_INTENT_PHYSICS="${args[$i]:-}";; + --physics=*) AIRSTACK_INTENT_PHYSICS="${a#--physics=}";; --wait) AIRSTACK_UP_WAIT="1";; # NOTE: shadows compose's own `up --dry-run`; ours validates the # derived launch config and exits without starting services. @@ -1177,8 +1190,12 @@ function parse_launch_intent { return 1 fi case "$AIRSTACK_INTENT_SIM" in - ""|isaac|isaacsim|airsim|msairsim|ms-airsim|simple|simplesim|simple-sim) ;; - *) log_error "Unknown --sim '$AIRSTACK_INTENT_SIM' (expected: isaac | airsim | simple)"; return 1;; + ""|isaac|isaacsim|airsim|msairsim|ms-airsim|projectairsim|pas|project-airsim|simple|simplesim|simple-sim) ;; + *) log_error "Unknown --sim '$AIRSTACK_INTENT_SIM' (expected: isaac | airsim | projectairsim | simple)"; return 1;; + esac + case "$AIRSTACK_INTENT_PHYSICS" in + ""|fast-physics|jsbsim) ;; + *) log_error "Unknown --physics '$AIRSTACK_INTENT_PHYSICS' (expected: fast-physics | jsbsim)"; return 1;; esac if [[ -n "$AIRSTACK_INTENT_FLEET" && -n "$AIRSTACK_INTENT_ROBOTS" ]]; then log_error "--fleet and --robots are mutually exclusive: the fleet file defines the robot count (RFC #380 §2)." @@ -1358,6 +1375,9 @@ function apply_launch_intent { airsim|msairsim|ms-airsim) sim_profile="ms-airsim" urdf="robot_descriptions/iris/urdf/iris_stereo.ms-airsim.urdf";; + projectairsim|pas|project-airsim) + sim_profile="project-airsim" + urdf="robot_descriptions/iris/urdf/iris_stereo_lidar.project-airsim.urdf";; simple|simplesim|simple-sim) # simple-sim (lightweight kinematic sim, no PX4/MAVROS): the # simple-robot service (SIM_TYPE=simple) IS the robot container, @@ -1374,7 +1394,7 @@ function apply_launch_intent { IFS=',' read -ra _parr <<< "$profiles" for p in "${_parr[@]}"; do case "$p" in - isaac-sim|ms-airsim|simple|"") ;; + isaac-sim|ms-airsim|project-airsim|simple|"") ;; desktop) [[ "$sim_profile" == "simple" ]] || kept+=("$p");; *) kept+=("$p");; esac @@ -1404,6 +1424,7 @@ function apply_launch_intent { if [[ "$AIRSTACK_INTENT_HEADLESS" == "true" ]]; then export ISAAC_SIM_HEADLESS="true" export MS_AIRSIM_HEADLESS="true" + export PROJECT_AIRSIM_HEADLESS="true" export QT_QPA_PLATFORM="offscreen" fi @@ -1412,6 +1433,13 @@ function apply_launch_intent { # with it means N robot containers and 1 drone in sim (silent today). local profiles_final profiles_final=$(resolve_launch_var COMPOSE_PROFILES "$@") + if [[ -n "$AIRSTACK_INTENT_PHYSICS" ]]; then + if [[ ",$profiles_final," != *",project-airsim,"* ]]; then + log_error "--physics selects Project AirSim's vehicle dynamics; it needs the project-airsim profile (resolved profiles: ${profiles_final:-}). Use 'airstack up --sim projectairsim --physics $AIRSTACK_INTENT_PHYSICS'." + return 1 + fi + export PROJECT_AIRSIM_PHYSICS="$AIRSTACK_INTENT_PHYSICS" + fi if [[ -n "$AIRSTACK_INTENT_ROBOTS" && ",$profiles_final," == *",isaac-sim,"* ]]; then local script want="" script=$(resolve_launch_var ISAAC_SIM_SCRIPT_NAME "$@") @@ -1438,8 +1466,9 @@ function apply_launch_intent { local scene_sim="" [[ ",$profiles_final," == *",isaac-sim,"* ]] && scene_sim="isaac" [[ ",$profiles_final," == *",ms-airsim,"* ]] && scene_sim="msairsim" + [[ ",$profiles_final," == *",project-airsim,"* ]] && scene_sim="projectairsim" if [[ -z "$scene_sim" ]]; then - log_error "--scene requires an Isaac or MS AirSim profile (resolved profiles: ${profiles_final:-}); simple-sim has no scene catalog. Use 'airstack up --sim isaac|airsim --scene $AIRSTACK_INTENT_SCENE'." + log_error "--scene requires an Isaac, MS AirSim or Project AirSim profile (resolved profiles: ${profiles_final:-}); simple-sim has no scene catalog. Use 'airstack up --sim isaac|airsim|projectairsim --scene $AIRSTACK_INTENT_SCENE'." python3 "$PROJECT_ROOT/simulation/resolve_scene.py" --table >&2 || true return 1 fi @@ -1456,6 +1485,9 @@ function apply_launch_intent { if [[ "$scene_sim" == "msairsim" ]]; then ensure_msairsim_scene "$(resolve_launch_var MS_AIRSIM_SCENE "$@")" "$@" || return 1 fi + if [[ "$scene_sim" == "projectairsim" ]]; then + ensure_projectairsim_env "$(resolve_launch_var PROJECT_AIRSIM_ENV "$@")" "$@" || return 1 + fi fi return 0 } @@ -1504,6 +1536,44 @@ function ensure_msairsim_scene { return 0 } +# Project AirSim environments are packaged UE5 builds (0.9-3.3 GB) fetched +# into the bind-mounted envs dir on first use — same flow as the MS AirSim +# scenes above: ask before a multi-GB download when interactive, otherwise +# let the container auto-fetch it (visible in the `pas` tmux window). +function ensure_projectairsim_env { + local env_key="$1"; shift + local fetch_sh="$PROJECT_ROOT/simulation/project-airsim/assets/envs/fetch_env.sh" + local bin + bin=$(resolve_launch_var PROJECT_AIRSIM_BINARY_PATH "$@") + if [[ -n "$bin" ]]; then + log_warn "--scene is overridden by PROJECT_AIRSIM_BINARY_PATH=$bin (the explicit binary path wins in the container). Unset PROJECT_AIRSIM_BINARY_PATH to use --scene." + return 0 + fi + local env_dir name + env_dir=$(resolve_launch_var PROJECT_AIRSIM_ENV_DIR "$@") + [[ -z "$env_dir" ]] && env_dir="$PROJECT_ROOT/simulation/project-airsim/assets/envs" + [[ "$env_dir" != /* ]] && env_dir="$PROJECT_ROOT/${env_dir#./}" + name=$(bash "$fetch_sh" --name "$env_key") || { + log_error "fetch_env.sh does not know environment key '$env_key' (simulation/scenes.yaml out of sync?)" + return 1 + } + [[ -f "$(ENVS_DIR="$env_dir" bash "$fetch_sh" --launcher "$env_key")" ]] && return 0 + log_warn "Project AirSim environment '$name' is not present locally under $env_dir." + if [[ -t 0 && -t 1 && "${AIRSTACK_ASSUME_YES:-}" != "1" ]]; then + local ans + read -r -p "Download it now from github.com/iamaisim/ProjectAirSim releases (0.9-3.3 GB)? [Y/n] " ans + case "$ans" in + n|N|no|NO) + log_error "Aborted. Point PROJECT_AIRSIM_BINARY_PATH at an existing environment launcher, or rerun and accept the download." + return 1;; + esac + ENVS_DIR="$env_dir" bash "$fetch_sh" "$env_key" || return 1 + else + log_info "Non-interactive run: the project-airsim container will auto-fetch '$name' on first launch (progress in the pas tmux window)." + fi + return 0 +} + # Print the resolved launch configuration and dump it (gitignored) so every # run leaves a record of what it actually launched. function print_launch_config { @@ -1518,9 +1588,15 @@ function print_launch_config { [[ -n "$_fleet_cfg" ]] && keys+=(FLEET_CONFIG_FILE) # Scene keys likewise only appear when a scene is selected (--scene or env). local _sk - for _sk in ISAAC_SIM_SCENE ISAAC_SIM_STAGE_SCALE MS_AIRSIM_SCENE; do + for _sk in ISAAC_SIM_SCENE ISAAC_SIM_STAGE_SCALE MS_AIRSIM_SCENE PROJECT_AIRSIM_ENV; do [[ -n "$(resolve_launch_var "$_sk" "$@")" ]] && keys+=("$_sk") done + # Project AirSim keys only when that simulator is selected (the other + # simulators' effective config stays byte-identical). + if [[ ",$(resolve_launch_var COMPOSE_PROFILES "$@")," == *",project-airsim,"* ]]; then + keys+=(PROJECT_AIRSIM_HEADLESS) + [[ -n "$(resolve_launch_var PROJECT_AIRSIM_PHYSICS "$@")" ]] && keys+=(PROJECT_AIRSIM_PHYSICS) + fi local k v lines=() for k in "${keys[@]}"; do v=$(resolve_launch_var "$k" "$@") @@ -1540,6 +1616,12 @@ function print_launch_config { _airsim_scene=$(resolve_launch_var MS_AIRSIM_SCENE "$@") [[ -n "$_airsim_scene" ]] && log_info " ms-airsim: scene=$_airsim_scene" fi + if [[ ",$profiles," == *",project-airsim,"* ]]; then + local _pas_env _pas_phys + _pas_env=$(resolve_launch_var PROJECT_AIRSIM_ENV "$@") + _pas_phys=$(resolve_launch_var PROJECT_AIRSIM_PHYSICS "$@") + log_info " project-airsim: env=${_pas_env:-blocks} physics=${_pas_phys:-fast-physics} headless=$(resolve_launch_var PROJECT_AIRSIM_HEADLESS "$@")" + fi log_info " urdf=$(resolve_launch_var URDF_FILE "$@")" local _stack_dir _stack_dir=$(resolve_launch_var AIRSTACK_STACK_DIR "$@") @@ -1613,11 +1695,11 @@ function preflight_up { # 1. Exactly one simulator profile local n=0 s - for s in isaac-sim ms-airsim simple; do [[ ",$profiles," == *",$s,"* ]] && n=$((n+1)); done + for s in isaac-sim ms-airsim project-airsim simple; do [[ ",$profiles," == *",$s,"* ]] && n=$((n+1)); done if (( n > 1 )); then - _pf_error "Only one simulator profile can be active at a time (isaac-sim, ms-airsim, simple). Resolved: $profiles" + _pf_error "Only one simulator profile can be active at a time (isaac-sim, ms-airsim, project-airsim, simple). Resolved: $profiles" elif (( n == 0 )); then - log_warn "No simulator profile active — robot containers will wait for a sim that never starts. Use 'airstack up --sim isaac|airsim|simple' (or add a sim profile)." + log_warn "No simulator profile active — robot containers will wait for a sim that never starts. Use 'airstack up --sim isaac|airsim|projectairsim|simple' (or add a sim profile)." fi # 2. URDF must match the simulator @@ -1626,6 +1708,7 @@ function preflight_up { if [[ -n "$urdf" ]]; then [[ ",$profiles," == *",ms-airsim,"* && "$urdf" != *.ms-airsim.* ]] && log_warn "URDF_FILE ($urdf) does not match ms-airsim profile. Expected *.ms-airsim.* URDF (or use --sim airsim)." [[ ",$profiles," == *",isaac-sim,"* && "$urdf" != *.pegasus.* && "$urdf" != *.isaacsim.* ]] && log_warn "URDF_FILE ($urdf) does not match isaac-sim profile. Expected *.pegasus.* or *.isaacsim.* URDF (or use --sim isaac)." + [[ ",$profiles," == *",project-airsim,"* && "$urdf" != *.project-airsim.* ]] && log_warn "URDF_FILE ($urdf) does not match project-airsim profile. Expected *.project-airsim.* URDF (or use --sim projectairsim)." fi if [[ ",$profiles," == *",isaac-sim,"* ]]; then @@ -2105,6 +2188,9 @@ function cmd_clean { "$PROJECT_ROOT/simulation/ms-airsim/ros_ws/build" "$PROJECT_ROOT/simulation/ms-airsim/ros_ws/install" "$PROJECT_ROOT/simulation/ms-airsim/ros_ws/log" + "$PROJECT_ROOT/simulation/project-airsim/ros_ws/build" + "$PROJECT_ROOT/simulation/project-airsim/ros_ws/install" + "$PROJECT_ROOT/simulation/project-airsim/ros_ws/log" "$PROJECT_ROOT/simulation/simple-sim/ros_ws/build" "$PROJECT_ROOT/simulation/simple-sim/ros_ws/install" "$PROJECT_ROOT/simulation/simple-sim/ros_ws/log" @@ -2454,7 +2540,7 @@ function register_builtin_commands { COMMAND_HELP["install"]="Install dependencies (Docker Engine, NVIDIA Container Toolkit)" COMMAND_HELP["setup"]="Configure AirStack settings and add to shell profile" COMMAND_HELP["images"]="Manage Docker Compose service images: list (default)|build|push|pull|delete|rm (see 'airstack help images')" - COMMAND_HELP["up"]="Start services [--sim isaac|airsim|simple] [--robots N] [--stack NAME] [--fleet NAME] [--headless] [--play|--no-play] [--no-autolaunch] [--wait] [--dry-run] [--config-only]" + COMMAND_HELP["up"]="Start services [--sim isaac|airsim|projectairsim|simple] [--physics fast-physics|jsbsim] [--robots N] [--stack NAME] [--fleet NAME] [--headless] [--play|--no-play] [--no-autolaunch] [--wait] [--dry-run] [--config-only]" COMMAND_HELP["down"]="down services" COMMAND_HELP["clean"]="Remove all ROS 2 build artifacts (build/, install/, log/)" COMMAND_HELP["connect"]="Connect to a running container (supports partial name matching)" diff --git a/common/module_schema/README.md b/common/module_schema/README.md index b9d60a14c..80f000b6e 100644 --- a/common/module_schema/README.md +++ b/common/module_schema/README.md @@ -41,7 +41,7 @@ Exit code 0 when valid, 1 otherwise. Contract tests: | `license` | non-empty string | checked at registration | | `type` | `isaac_extension` \| `ros_package` \| `data` \| `platform` | `platform` is future (RFC #380 §6) | | `airstack_compat` | semver range | vs trunk `.env` `VERSION`, e.g. `">=0.19.0 <0.21.0"`, `">=0.19.0-alpha.18 <0.20.0"`. Branch names (`main`) and partial versions (`0.19`) are invalid. | -| `targets` | non-empty array of `robot` \| `gcs` \| `isaac-sim` \| `ms-airsim` | host containers touched | +| `targets` | non-empty array of `robot` \| `gcs` \| `isaac-sim` \| `ms-airsim` \| `project-airsim` | host containers touched | ### Optional (with defaults) diff --git a/common/module_schema/module.schema.json b/common/module_schema/module.schema.json index 9641bc34e..aac0e8dbd 100644 --- a/common/module_schema/module.schema.json +++ b/common/module_schema/module.schema.json @@ -49,7 +49,7 @@ "minItems": 1, "items": { "type": "string", - "enum": ["robot", "gcs", "isaac-sim", "ms-airsim"] + "enum": ["robot", "gcs", "isaac-sim", "ms-airsim", "project-airsim"] }, "description": "Host containers this module touches." }, diff --git a/common/ros_packages/robot_descriptions/iris/urdf/iris_stereo_lidar.project-airsim.urdf b/common/ros_packages/robot_descriptions/iris/urdf/iris_stereo_lidar.project-airsim.urdf new file mode 100644 index 000000000..58eaea046 --- /dev/null +++ b/common/ros_packages/robot_descriptions/iris/urdf/iris_stereo_lidar.project-airsim.urdf @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/vehicles/quad_default/vehicle.yaml b/config/vehicles/quad_default/vehicle.yaml index dd309deb3..629aff865 100644 --- a/config/vehicles/quad_default/vehicle.yaml +++ b/config/vehicles/quad_default/vehicle.yaml @@ -24,6 +24,17 @@ airframe: base_urdf: robot_descriptions/iris/urdf/iris_with_sensors.pegasus.robot.urdf # ms-airsim runs a reduced stereo-only URDF today; `airstack up --sim airsim` # keeps exporting it (env wins over the fleet resolver's URDF_FILE). + # Project AirSim likewise: `--sim projectairsim` exports + # iris_stereo_lidar.project-airsim.urdf (stereo + body-aligned ouster frame). + +# Project AirSim representation of this airframe (read by +# simulation/project-airsim/config/generate_scene.py). `physics` is the +# vehicle-level default; a fleet's sim.physics / robots..physics and +# PROJECT_AIRSIM_PHYSICS (airstack up --physics) override it, in that order +# of increasing precedence. jsbsim uses the Auterion quadrotor_x model that +# ships inside the packaged environments. +project_airsim: + physics: fast-physics # One entry per sensor: the real driver and the sim representation declared # together (one source of truth for both worlds). `id` is the sensors/* topic diff --git a/docker-compose.yaml b/docker-compose.yaml index 9511e6960..8e598f393 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -7,6 +7,7 @@ include: - simulation/isaac-sim/docker/docker-compose.yaml - simulation/simple-sim/docker/docker-compose.yaml - simulation/ms-airsim/docker/docker-compose.yaml + - simulation/project-airsim/docker/docker-compose.yaml - robot/docker/docker-compose.yaml - gcs/docker/docker-compose.yaml - docs/docker/docker-compose.yaml diff --git a/docs/assets/media/project_airsim_demo.mp4 b/docs/assets/media/project_airsim_demo.mp4 new file mode 100644 index 000000000..4be5365e2 Binary files /dev/null and b/docs/assets/media/project_airsim_demo.mp4 differ diff --git a/docs/assets/media/project_airsim_demo_poster.jpg b/docs/assets/media/project_airsim_demo_poster.jpg new file mode 100644 index 000000000..4fe2c399a Binary files /dev/null and b/docs/assets/media/project_airsim_demo_poster.jpg differ diff --git a/docs/assets/media/project_airsim_lumen_ab.jpg b/docs/assets/media/project_airsim_lumen_ab.jpg new file mode 100644 index 000000000..32124ae5e Binary files /dev/null and b/docs/assets/media/project_airsim_lumen_ab.jpg differ diff --git a/docs/development/beginner/airstack-cli/index.md b/docs/development/beginner/airstack-cli/index.md index 6c6aaa42a..f3f6181cd 100644 --- a/docs/development/beginner/airstack-cli/index.md +++ b/docs/development/beginner/airstack-cli/index.md @@ -116,9 +116,9 @@ One command group — run `airstack help osmo` for the full reference. | Flag | Description | |------|-------------| -| `--sim isaac\|airsim\|simple` | Pick the simulator: swaps in the matching compose profile (`isaac-sim` / `ms-airsim`) and selects the matching URDF; `simple` launches the lightweight kinematic simple-sim (no PX4/MAVROS) with the `simple-robot` service in place of `robot-desktop` | +| `--sim isaac\|airsim\|projectairsim\|simple` | Pick the simulator: swaps in the matching compose profile (`isaac-sim` / `ms-airsim` / `project-airsim`) and selects the matching URDF. `airsim` is Microsoft AirSim (legacy, UE4); `projectairsim` (aliases `pas`, `project-airsim`) is [Project AirSim](../../../simulation/project-airsim/index.md) (UE5, stereo + depth + LiDAR); `simple` launches the lightweight kinematic simple-sim (no PX4/MAVROS) with the `simple-robot` service in place of `robot-desktop` | | `--robots N` | Number of robots (positive integer): exports `NUM_ROBOTS=N` and, on Isaac Sim, auto-selects the single-/multi-drone launch script to match. Mutually exclusive with `--fleet` (the fleet file defines the robot count) | -| `--headless` | Run the simulator without a GUI (sets `ISAAC_SIM_HEADLESS`, `MS_AIRSIM_HEADLESS`, offscreen Qt) | +| `--headless` | Run the simulator without a GUI (sets `ISAAC_SIM_HEADLESS`, `MS_AIRSIM_HEADLESS`, `PROJECT_AIRSIM_HEADLESS`, offscreen Qt) | | `--play` / `--no-play` | Start (or don't start) simulation playback automatically (`PLAY_SIM_ON_START`) | | `--no-autolaunch` | Start containers without auto-launching the autonomy stack (`AUTOLAUNCH=false`) — the usual mode for development | | `--wait` | After starting containers, block until the stack is flight-ready (runs `airstack ready`) | @@ -126,6 +126,7 @@ One command group — run `airstack help osmo` for the full reference. | `--stack NAME[:ENTRY]` | Launch a stack folder: `stacks/NAME/launch/ENTRY.launch.xml` (default entry `stack`). Stacks are the only launch dispatch; no `--stack` launches the trunk reference stack `full_default`. See [Stacks](../../stacks.md) | | `--fleet NAME` | Launch a fleet (`config/fleets/NAME.yaml`): exports `FLEET_CONFIG_FILE`, derives `NUM_ROBOTS`, selects the Isaac fleet spawner, and (for heterogeneous fleets) includes the generated per-robot services. See [Fleets](../../fleets.md) | | `--scene NAME` | Select the simulation scene by shortname from the shared scene catalog (`simulation/scenes.yaml`): maps `NAME` to the active simulator's scene reference and exports it. See [Scenes](../../../simulation/scenes.md) | +| `--physics fast-physics\|jsbsim` | Project AirSim only: vehicle dynamics model for every robot (exports `PROJECT_AIRSIM_PHYSICS`; default `fast-physics`; `jsbsim` is experimental). Requires the `project-airsim` profile. Per-robot choice goes in the fleet file (`robots..physics`) | Also supported: `--build` (build images before starting) and `--env-file FILE` (layer an extra env file on top of the root `.env`). diff --git a/docs/development/fleets.md b/docs/development/fleets.md index 5123ee3e7..53accee87 100644 --- a/docs/development/fleets.md +++ b/docs/development/fleets.md @@ -68,7 +68,8 @@ network: {domain_policy: auto, gossip_domain: 99, gcs_domain: 0} ``` Per-robot keys: `vehicle`, `stack`, `unit`, `spawn` (sim-only, `[x, y, z]` m), -`hosts` (split placement), `overrides` (leaf values only — accepted by the +`hosts` (split placement), `physics` (Project AirSim only, see +[Simulation](#simulation)), `overrides` (leaf values only — accepted by the schema, launch-time application is future work). `defaults:` keeps homogeneous fleets terse. A robot needing different *topology* points at a different stack folder — that division keeps fleet files skimmable. @@ -84,6 +85,7 @@ then as `/` against external stack repos declared in airstack fleet list # what exists, robots, shape airstack up --fleet sim_one_default --sim isaac # homogeneous: replicas airstack up --fleet sim_three_mixed --sim isaac # heterogeneous: generated services +airstack up --fleet sim_one_default --sim projectairsim # same fleet on Project AirSim airstack ready ``` @@ -177,6 +179,21 @@ ground: - **ms-airsim** — `generate_settings.py` already consumes `NUM_ROBOTS`, which the fleet derives; nothing more is needed (spawn spacing stays the simulator's `AIRSIM_SPAWN_SPACING` grid for now). +- **Project AirSim** — `simulation/project-airsim/config/generate_scene.py` + reads the fleet file: one vehicle per robot, at its `spawn` (relative to + the environment's spawn origin). Each robot's dynamics model + (`fast-physics`, or the experimental `jsbsim`) resolves, first hit wins: + `PROJECT_AIRSIM_PHYSICS` (`airstack up --physics`) › `robots..physics` + › `sim.physics` › the vehicle's `project_airsim.physics` › `fast-physics`. + Other simulators ignore both keys. + + ```yaml + robots: + robot_1: {spawn: [0, 0, 0.07]} + robot_2: {spawn: [3, 0, 0.07], physics: jsbsim} # per robot + sim: {scene: default, physics: fast-physics} # fleet-wide default + ``` + - **Test harness** — `airstack test ... --fleet ` passes `FLEET_CONFIG_FILE` + the derived `NUM_ROBOTS` through `airstack_env` (Isaac runs pin `fleet_spawn.py`). Without `--fleet`, `--num-robots` diff --git a/docs/development/intermediate/testing/ci_cd.md b/docs/development/intermediate/testing/ci_cd.md index e759a9310..816d0df5b 100644 --- a/docs/development/intermediate/testing/ci_cd.md +++ b/docs/development/intermediate/testing/ci_cd.md @@ -144,7 +144,7 @@ flowchart TB dockerd["inner dockerd
+ nvidia-container-toolkit"] runner["actions-runner run.sh --jitconfig"] subgraph compose ["docker compose stack started by airstack up"] - sim["isaac-sim or ms-airsim"] + sim["isaac-sim, ms-airsim, or project-airsim"] robot["robot-desktop x NUM_ROBOTS"] gcs["gcs"] end diff --git a/docs/development/intermediate/testing/end_to_end_testing.md b/docs/development/intermediate/testing/end_to_end_testing.md index 5b6f233e9..f3d8bb79e 100644 --- a/docs/development/intermediate/testing/end_to_end_testing.md +++ b/docs/development/intermediate/testing/end_to_end_testing.md @@ -64,7 +64,7 @@ Each run sweeps: | Parameter | CLI flag | Default | | --------- | -------- | ------- | -| Simulator | `--sim` | `isaacsim` (`msairsim` opt-in) | +| Simulator | `--sim` | `isaacsim` (`msairsim`, `projectairsim` opt-in) | | Robot count | `--num-robots` | `1,3` | | Repeat count | `--stress-iterations` | `1` | | Trajectory type | `--trajectory-types` | `Circle,Figure8,Racetrack,Line` | @@ -320,7 +320,7 @@ airstack test -m autonomy \ | Option | Default | Description | | ------ | ------- | ----------- | -| `--sim` | `isaacsim` | Comma-separated sim targets (`msairsim` opt-in) | +| `--sim` | `isaacsim` | Comma-separated sim targets (`msairsim`, `projectairsim` opt-in) | | `--num-robots` | `1,3` | Comma-separated robot counts | | `--stress-iterations` | `1` | Repeat count per `(sim, num_robots)` | | `--trajectory-types` | `Circle,Figure8,Racetrack,Line` | Trajectory sweep | @@ -431,7 +431,7 @@ Action server: `/{robot_name}/tasks/fixed_trajectory` — see also [Tasks and Ta | PX4 ready timeout | Sim not running, GPU issue | Check `nvidia-smi`, Isaac `omni_pass.env` | | `trajectory_success = 0` | Tracker stall or timeout | Check trajectory_controller logs; rebuild the workspace (`-m build_packages`) | | Cross-track error >> 5 m | Wrong tracker params or frame bug | Compare launch params; check world-frame transform | -| Tests run for hours | Default `--num-robots 1,3` (and `--sim msairsim` if opted in) | Pin `--sim isaacsim --num-robots 1 --stress-iterations 1` | +| Tests run for hours | Default `--num-robots 1,3` (and each extra `--sim` target opted in) | Pin `--sim isaacsim --num-robots 1 --stress-iterations 1` | --- diff --git a/docs/development/intermediate/testing/using_ci.md b/docs/development/intermediate/testing/using_ci.md index 20a99cffd..a8ef8becf 100644 --- a/docs/development/intermediate/testing/using_ci.md +++ b/docs/development/intermediate/testing/using_ci.md @@ -76,10 +76,10 @@ list and per-mark reference live in |---|---|---|---| | `unit` | `/test/` (co-located) | Hermetic Python/numpy logic co-located with each ROS 2 package | Off-by-one and boundary errors in filters, converters, validators; regressions in pure algorithm code | | `build_docker` | `system/test_build_docker.py` | Every image builds; records image sizes | Broken Dockerfiles, deleted apt packages, upstream base-image drift, accidental image bloat | -| `build_packages` | `system/test_build_packages.py` | `colcon build` inside robot, GCS, and ms-airsim workspaces | Missing `package.xml` dependencies, uninstalled launch/config files, C++ breakage on a clean tree | +| `build_packages` | `system/test_build_packages.py` | `colcon build` inside robot, GCS, ms-airsim, and project-airsim workspaces | Missing `package.xml` dependencies, uninstalled launch/config files, C++ breakage on a clean tree | | `liveliness` | `system/test_liveliness.py` | Containers reach Running, `/clock` publishes, tmux panes alive, sentinel ROS 2 nodes present, compute snapshot, stability poll | Launch files that crash on start, nodes that die after 30 s, `ROBOT_NAME`/domain-ID misconfiguration, runaway CPU or memory | | `wiring` | `system/test_wiring_snapshot.py` | Observed wiring snapshot of the running ROS graph, drift-checked against the stack's committed `stacks//wiring.md` | Topic remaps that silently disconnect, nodes publishing into the void, launch-file edits that change the graph without updating `wiring.md` | -| `sensors` | `system/test_sensors.py` | Stereo and depth publish rates on both sim and robot side, filtered LiDAR liveness plus geometry sanity, sim real-time factor, time-series stability | Broken sim-to-ROS bridges, sensor Hz that silently halves, RTF collapse from a heavy new node, LiDAR filter range regressions | +| `sensors` | `system/test_sensors.py` | Stereo and depth publish rates on both sim and robot side, filtered LiDAR liveness plus geometry sanity (LiDAR sims: `isaacsim`, `projectairsim`), sim real-time factor, time-series stability | Broken sim-to-ROS bridges, sensor Hz that silently halves, RTF collapse from a heavy new node, LiDAR filter range regressions | | `takeoff_hover_land` | `system/test_takeoff_hover_land.py` | Four-phase chain per (sim, robots, iteration, velocity): PX4 ready → takeoff to 10 m → hover → land | Controller tuning regressions, altitude overshoot, hover drift, state-estimation bias against ground truth, PX4/MAVROS handshake breakage | | `autonomy` | `system/test_fixed_trajectory.py` | Same chain with a Circle / Figure8 / Racetrack / Line pattern in the middle; records cross-track error and path RMSE | Path-tracker regressions, trajectory-library math errors, velocity/acceleration limit violations that show up as corner-cutting | | `waypoint_flight` | `system/test_waypoint_flight.py` | Same chain with an ordered `NavigateTask` waypoint route in the middle; the odometry track is judged by the standalone `waypoint_checker.py` (in-order corridor arrival, final-goal tolerance, per-waypoint timeout) | Waypoint sequencing regressions, behavior-tree/navigation task breakage, routes that skip or stall at a waypoint | @@ -114,7 +114,8 @@ stack cycles per tuple**: ```text -m liveliness → 1 bring-up per (sim, robots, iter) -m "liveliness or sensors" → 2 bring-ups per (sim, robots, iter) ---sim msairsim → opt in; both sims doubles all of the above +--sim msairsim → opt in; each extra sim target (msairsim, + projectairsim) multiplies all of the above --num-robots 1,3 → doubles it again ``` diff --git a/docs/development/module_ci.md b/docs/development/module_ci.md index 58ba70eb2..37101cb35 100644 --- a/docs/development/module_ci.md +++ b/docs/development/module_ci.md @@ -75,7 +75,7 @@ The secrets are optional — without them the run still works, just slower. |---|---|---| | `airstack_ref` | *(required)* | Tag/branch/SHA of `castacks/AirStack` to test against. Must include the module CLI (`airstack module add`/`sync`). | | `marks` | `build_packages or liveliness` | pytest marks expression (see [tests/README.md](../../tests/README.md)). `build_packages` auto-prepended when absent. | -| `sim` | `isaacsim` | Sim targets, comma-separated: `isaacsim,msairsim`. | +| `sim` | `isaacsim` | Sim targets, comma-separated: `isaacsim,msairsim,projectairsim`. | | `num_robots` | `1` | Robot counts, comma-separated (e.g. `1,3`). | | `stress_iterations` | `1` | Iterations per (sim, num_robots) config. | | `stable_duration` | `120` | Seconds for the `test_stable` polling window. | @@ -129,7 +129,8 @@ the claim is inspectable; the CI caller is where they actually run. image, or `marks: build_packages` through this workflow — pure `build_packages` runs never bake sim images). Minutes, no GPU. - **PR / nightly:** `liveliness` (plus `sensors` where relevant) via this - workflow; `sim: msairsim` is the cheap bring-up. + workflow; `sim: msairsim` is the cheap bring-up (`sim: projectairsim` when + the module consumes LiDAR). - **Release / compatibility claim:** the module's full conformance mark set on GPU — this run is what stamps the badge. - **Trunk-side nightly canary** (planned) runs registered modules against diff --git a/docs/development/modules.md b/docs/development/modules.md index 69543d4bd..fef83b5e0 100644 --- a/docs/development/modules.md +++ b/docs/development/modules.md @@ -195,7 +195,7 @@ standalone repo by hand today. `robot-offboard`, `simple-robot`, …) re-parse the base file and do not see override-file additions. Override the set with `AIRSTACK_MODULE_ROBOT_SERVICES=svc1,svc2` if you need others. -- **`gcs` / `ms-airsim` targets** get no placement yet. +- **`gcs` / `ms-airsim` / `project-airsim` targets** get no placement yet. - **`airstack_compat`** ranges are validated syntactically but not yet checked against the checkout's `.env` `VERSION` at sync time. - **vcs2l** is installed with `pip3 install --user`; make sure `~/.local/bin` @@ -220,7 +220,7 @@ plans. Permutations are never published. The chain is deterministic — modules sorted by name within each tier, tiers in order 1 → 2 → 3-as-build, grouped per target host (`robot` / `gcs` / -`isaac-sim` / `ms-airsim`): +`isaac-sim` / `ms-airsim` / `project-airsim`): ```text /airstack:v0.19.0_robot-x86-64_dev ← trunk base, pulled, never rebuilt diff --git a/docs/real_world/supported_platforms.md b/docs/real_world/supported_platforms.md index e734cc831..04d51fde6 100644 --- a/docs/real_world/supported_platforms.md +++ b/docs/real_world/supported_platforms.md @@ -6,7 +6,7 @@ AirStack targets one compute platform per Docker Compose profile: each service i | Platform | Compose profile → service(s) | Base image (from compose `build.args`) | Status | | -------- | ---------------------------- | -------------------------------------- | ------ | -| x86-64 desktop/laptop (development + simulation) | `desktop` → `robot-desktop` (+ `gcs`) | `nvidia/cuda:13.0.2-base-ubuntu24.04` | **CI-tested (sim)**: `system-tests.yml` runs build, liveliness, sensor, and flight marks against this profile on ephemeral x86 GPU runners; `test_build_docker.py` builds the `robot-desktop`, `gcs`, `isaac-sim`, and `ms-airsim` images | +| x86-64 desktop/laptop (development + simulation) | `desktop` → `robot-desktop` (+ `gcs`) | `nvidia/cuda:13.0.2-base-ubuntu24.04` | **CI-tested (sim)**: `system-tests.yml` runs build, liveliness, sensor, and flight marks against this profile on ephemeral x86 GPU runners; `test_build_docker.py` builds the `robot-desktop`, `gcs`, `isaac-sim`, `ms-airsim`, and `project-airsim` images | | x86-64 desktop, split-topology debugging | `desktop_split` → `robot-desktop-onboard` + `robot-offboard` (+ `gcs`) | Same image as `robot-desktop` | Profile exists; shares the CI-tested desktop image, but the split topology itself is not CI-exercised | | x86-64 ground station (field, offboard half) | `offboard` → `robot-offboard` + `gcs-real` | Same image as `robot-desktop`; GCS from `osrf/ros:jazzy-desktop-full` | Profile exists for field use paired with `l4t_lite`/`voxl` vehicles; not CI-exercised | | NVIDIA Jetson Orin AGX/NX (full stack onboard) | `l4t` → `robot-l4t` (+ `robot-l4t-stack-base`, `zed-l4t`) | `dustynv/ros:jazzy-ros-base-r36.4.0-cu128-24.04` via the intermediate `Dockerfile.l4t-stack-base` image | **Supported, field-used**: the [installation guide](installation/index.md) documents tested install and run on Jetson Orin AGX/NX with Ubuntu 22.04 (L4T / JetPack); not covered by CI | diff --git a/docs/release_notes/index.md b/docs/release_notes/index.md index a859071a4..d1cc851e7 100644 --- a/docs/release_notes/index.md +++ b/docs/release_notes/index.md @@ -19,6 +19,41 @@ its own notes. --> ## 0.21.0 (Unreleased) +- **Project AirSim simulator backend (`airstack up --sim projectairsim`).** + [Project AirSim](https://github.com/iamaisim/ProjectAirSim), the + IAMAI-maintained UE5 successor to Microsoft AirSim, joins Isaac Sim, + Microsoft AirSim (legacy) and Simple Sim + ([guide](../simulation/project-airsim/index.md)). One `project-airsim` + container runs a packaged UE5 environment (Blocks by default, others via + `--scene`, fetched and SHA-256-verified on first launch), PX4 SITL v1.16.1 + in lockstep, and the C++ `pas_ros_bridge`. The bridge is a single process + serving every robot on its own DDS domain, because Project AirSim's topic + socket admits one client; it publishes the same stereo/depth/ground-truth + topics as the other simulators plus a 10 Hz LiDAR sweep + (`sensors/ouster/point_cloud_raw`). Unlike Microsoft AirSim (legacy), the + default MIGHTY stack therefore runs on it, and cameras render headless. New + flag `--physics fast-physics|jsbsim`, per robot via fleet + `robots..physics` / `sim.physics` (JSBSim is experimental: PX4's EKF + does not yet complete tilt alignment). Validated with liveliness, sensors, + takeoff/hover/land (0.5–2 m/s), fixed trajectories, MIGHTY waypoint flight, + and two robots. `PROJECT_AIRSIM_LUMEN` toggles Lumen GI and reflections + per camera in environments packaged with the plugin from Project AirSim + `main`; the guide covers packaging a custom environment (including UE 5.8). + Integration findings now encoded as defaults: + - The packaged Blocks world origin is inside a block, so spawns are + anchored at a surveyed point. + - Project AirSim's dipole magnetometer only agrees with PX4's World + Magnetic Model near its reference location, which is now the default + home. + - Its own PX4 control link is parked on an unused port so it cannot take + MAVROS's. + - The C++ client is compiled from a pinned, SHA-verified sparse clone; no + Project AirSim source enters the repository. +- **Fix: PX4 SITL image builds.** PX4's `Tools/setup/ubuntu.sh` pulls the + newest pandas, which needs numpy ≥ 2 and cannot replace the Debian numpy + 1.26 that ROS Jazzy is built against. The ms-airsim and project-airsim + images pin `numpy<2` for that step. + - **Fix: MAVROS 2.15–2.16 moved every MAVROS topic to `interface/mavros/mavros/...`.** Plugin sub-nodes took the UAS node's fully qualified name (mavros#2310, fixed upstream in 2.17.0), so diff --git a/docs/robot/autonomy_modes.md b/docs/robot/autonomy_modes.md index 6b836ac70..4dd5b4e98 100644 --- a/docs/robot/autonomy_modes.md +++ b/docs/robot/autonomy_modes.md @@ -49,6 +49,7 @@ The hardware-profile defaults are redefinable per deployment (env / |---|---| | `isaac-sim` | NVIDIA Isaac Sim (Pegasus) | | `ms-airsim` | Microsoft AirSim (legacy) (UE4) | +| `project-airsim` | Project AirSim (UE5) | | `simple` | Simple Sim | Only one simulator profile can be active at a time. `airstack up` will error if multiple are set. @@ -62,7 +63,7 @@ Combine with a simulator profile. ``` Dev desktop -├── simulator (isaac-sim / ms-airsim / simple) +├── simulator (isaac-sim / ms-airsim / project-airsim / simple) ├── robot-desktop × N [stack: full_default] └── gcs ``` @@ -74,6 +75,9 @@ airstack up --sim isaac # Microsoft AirSim (legacy): airstack up --sim airsim +# Project AirSim: +airstack up --sim projectairsim + # Multiple simulated robots: airstack up --sim isaac --robots 3 ``` @@ -92,7 +96,7 @@ Use this to debug the split configuration and domain bridge without needing phys ``` Dev desktop -├── simulator (isaac-sim / ms-airsim / simple) +├── simulator (isaac-sim / ms-airsim / project-airsim / simple) ├── robot-desktop-onboard × N [stack: lite_default, ROS_DOMAIN_ID = 1..N] ├── robot-offboard × N [stack: lite_offload_global:offboard, ROS_DOMAIN_ID = 0] └── gcs [domain 0] diff --git a/docs/robot/configuration/environment_variables.md b/docs/robot/configuration/environment_variables.md index 3fe239ed2..f2782d123 100644 --- a/docs/robot/configuration/environment_variables.md +++ b/docs/robot/configuration/environment_variables.md @@ -18,8 +18,8 @@ These variables assemble every image tag as `${PROJECT_DOCKER_REGISTRY}/${PROJEC | Variable | Purpose | Default | Consumed by | | -------- | ------- | ------- | ----------- | -| `AUTOLAUNCH` | If `false`, containers spawn idle with no launch command (tmux session still created) | `"true"` | Container `command:` of every robot service, `isaac-sim`, `ms-airsim`, and `gcs` (each gates its tmux autolaunch on it) | -| `NUM_ROBOTS` | Number of robot containers to launch (compose replicas) | `"1"` | `deploy.replicas` of `robot-desktop`/`robot-offboard`; forwarded into `isaac-sim`, `ms-airsim`, and `gcs` containers (drone spawn count / peer list). Overridden by `airstack up --robots N`; derived from the fleet file with `--fleet` | +| `AUTOLAUNCH` | If `false`, containers spawn idle with no launch command (tmux session still created) | `"true"` | Container `command:` of every robot service, `isaac-sim`, `ms-airsim`, `project-airsim`, and `gcs` (each gates its tmux autolaunch on it) | +| `NUM_ROBOTS` | Number of robot containers to launch (compose replicas) | `"1"` | `deploy.replicas` of `robot-desktop`/`robot-offboard`; forwarded into `isaac-sim`, `ms-airsim`, `project-airsim`, and `gcs` containers (drone spawn count / peer list). Overridden by `airstack up --robots N`; derived from the fleet file with `--fleet` | | `RECORD_BAGS` | Start the bag recorder node with the stack (see [Rosbags](../logging/rosbags.md)) | `"false"` | `robot_base` and `gcs` `environment:` → `bag_recorder_pid` via the logging bringup | ## Isaac Sim @@ -62,11 +62,13 @@ All four are forwarded into (or read by the `command:` of) the `isaac-sim` servi | `AUTOLAUNCH` | `--no-autolaunch` | Overrides the `.env` value above (sets `false`) | As in Launch Behavior | | `ISAAC_SIM_HEADLESS` | `--headless` | Run Isaac Sim without a window | `isaac-sim` `environment:` (default `false`; forced `true` by the `isaac-sim-livestream` service) | | `MS_AIRSIM_HEADLESS` | `--headless` | Run the UE4 binary off-screen | `ms-airsim` `environment:` | +| `PROJECT_AIRSIM_HEADLESS` | `--headless` | Run the UE5 environment off-screen (cameras and LiDAR still render) | `project-airsim` `environment:` | +| `PROJECT_AIRSIM_PHYSICS` | `--physics fast-physics\|jsbsim` | Vehicle dynamics model for every robot; overrides the fleet and vehicle defaults | `project-airsim` `environment:` → `config/generate_scene.py` | | `QT_QPA_PLATFORM` | `--headless` (sets `offscreen`) | Keeps Qt tools (RViz etc.) from requiring a display | `robot_base` `environment:` | -| `COMPOSE_PROFILES` | `--sim isaac\|airsim\|simple` (swaps the simulator profile; `simple` also drops `desktop`), `--fleet` (heterogeneous: swaps `desktop` for `fleet`) | Overrides the `.env` value above | Docker Compose profile selection | -| `URDF_FILE` | `--sim isaac\|airsim` | Swaps to the simulator-matched sensor URDF | As in Robot Identity & Description | +| `COMPOSE_PROFILES` | `--sim isaac\|airsim\|projectairsim\|simple` (swaps the simulator profile; `simple` also drops `desktop`), `--fleet` (heterogeneous: swaps `desktop` for `fleet`) | Overrides the `.env` value above | Docker Compose profile selection | +| `URDF_FILE` | `--sim isaac\|airsim\|projectairsim` | Swaps to the simulator-matched sensor URDF | As in Robot Identity & Description | | `ISAAC_SIM_SCRIPT_NAME` | `--robots` (one ↔ multi example script) and `--fleet` (→ `fleet_spawn.py`); an explicit env value always wins | Overrides the `.env` value above | As in Isaac Sim | -| `ISAAC_SIM_SCENE`, `ISAAC_SIM_STAGE_SCALE`, `MS_AIRSIM_SCENE` | `--scene ` via `simulation/resolve_scene.py` (`simulation/scenes.yaml` catalog) | Scene selection for the active simulator — see [Scenes](../../simulation/scenes.md) | `isaac-sim` / `ms-airsim` `environment:` → the launch scripts / `entrypoint.sh` | +| `ISAAC_SIM_SCENE`, `ISAAC_SIM_STAGE_SCALE`, `MS_AIRSIM_SCENE`, `PROJECT_AIRSIM_ENV` | `--scene ` via `simulation/resolve_scene.py` (`simulation/scenes.yaml` catalog) | Scene selection for the active simulator — see [Scenes](../../simulation/scenes.md) | `isaac-sim` / `ms-airsim` / `project-airsim` `environment:` → the launch scripts / `entrypoint.sh` | ## Notable Optional Variables @@ -76,6 +78,9 @@ These appear commented-out in `.env` (or are read by compose with a built-in def | -------- | ------- | ------------- | | `ISAAC_SIM_SCENE`, `ISAAC_SIM_STAGE_SCALE` | Direct scene override / stage scale for cm-authored stages (normally set via `--scene`) | [Scenes](../../simulation/scenes.md) | | `MS_AIRSIM_SCENE`, `MS_AIRSIM_ENV_DIR`, `MS_AIRSIM_BINARY_PATH`, `MS_AIRSIM_HEADLESS`, `MS_AIRSIM_PX4_START_DELAY` | UE4 scene fetching/selection, binary override, off-screen rendering, PX4 start delay | [MS AirSim Docker](../../simulation/ms-airsim/docker.md) | +| `PROJECT_AIRSIM_ENV`, `PROJECT_AIRSIM_ENV_DIR`, `PROJECT_AIRSIM_BINARY_PATH`, `PROJECT_AIRSIM_RELEASE` | UE5 environment selection, host download directory, launcher override, Project AirSim release to fetch from (default `v1.1.0`) | [Project AirSim](../../simulation/project-airsim/index.md) | +| `PROJECT_AIRSIM_HEADLESS`, `PROJECT_AIRSIM_PHYSICS`, `PROJECT_AIRSIM_LUMEN`, `PROJECT_AIRSIM_PX4_START_DELAY` | Off-screen rendering, dynamics model (`fast-physics`/`jsbsim`), Lumen global illumination, PX4 start delay | [Project AirSim](../../simulation/project-airsim/index.md) | +| `PROJECT_AIRSIM_CAM_*`, `PROJECT_AIRSIM_LIDAR_*`, `PROJECT_AIRSIM_CHASE_CAM`, `PROJECT_AIRSIM_SPAWN_ORIGIN` | Stereo camera and LiDAR parameters, third-person chase camera, spawn origin | [Project AirSim](../../simulation/project-airsim/index.md) | | `BAG_STORAGE_PATH` | Host directory mounted at `/bags` on the `l4t` profile (default `/media/airlab/Storage/airstack_collection`) | [Rosbags](../logging/rosbags.md) | | `LOG_CONFIG` | Bag recorder topic-selection file in `logging_bringup/config/` (default `log.yaml`) | [Rosbags](../logging/rosbags.md) | | `ISAAC_SIM_FOLLOW_CAM`, `ISAAC_SIM_FOLLOW_CAM_OFFSET`, `ISAAC_SIM_FOLLOW_CAM_LIGHT`, `ISAAC_SIM_FOLLOW_CAM_TOPIC`, `ISAAC_SIM_FOLLOW_CAM_RES` | Viewport follow-camera: drone domain id to chase, world-frame offset, headlight for unlit interiors; optionally publish the camera as a raw `sensor_msgs/Image` topic (`WxH`, default 1280x720) for headless video capture | [Isaac Sim](../../simulation/isaac_sim/index.md) (read by `pegasus_app.py`) | diff --git a/docs/simulation/index.md b/docs/simulation/index.md index 9edcb15cb..001e9ec77 100644 --- a/docs/simulation/index.md +++ b/docs/simulation/index.md @@ -2,7 +2,7 @@ AirStack provides simulation environments for developing and testing autonomous systems before deploying to hardware. Simulation enables rapid iteration, safe testing of edge cases, and multi-robot scenarios. -Three simulators are supported because no single one covers every development need: **Isaac Sim** (primary) for high-fidelity rendering, physics, and full sensor suites; **Microsoft AirSim (legacy)** for native PX4-in-the-loop testing with pre-built Unreal Engine scenes and no Omniverse dependency; and **Simple Sim** for fast, lightweight iteration on planning and perception code without PX4 or a heavyweight GPU workload. Pick the lightest simulator that exercises what you're working on. +Four simulators are supported because no single one covers every development need: **Isaac Sim** (primary) for high-fidelity rendering, physics, and full sensor suites; **Project AirSim** for PX4-in-the-loop testing in packaged Unreal Engine 5 environments with stereo, depth, and LiDAR and no Omniverse dependency; **Microsoft AirSim (legacy)** for PX4-in-the-loop testing with pre-built Unreal Engine 4 scenes (stereo and depth only); and **Simple Sim** for fast, lightweight iteration on planning and perception code without PX4 or a heavyweight GPU workload. Pick the lightest simulator that exercises what you're working on. ## Directory Structure @@ -24,6 +24,13 @@ simulation/ │ │ └── Dockerfile # Image definition │ ├── config/ # Microsoft AirSim (legacy) settings.json │ └── ros_ws/ # Depth bridge ROS package +├── project-airsim/ +│ ├── docker/ # Project AirSim containerization +│ │ ├── docker-compose.yaml # Launch configuration +│ │ └── Dockerfile # Image definition +│ ├── config/ # Scene/robot config generator +│ ├── assets/envs/ # Packaged UE5 environments (fetched on first use) +│ └── ros_ws/ # C++ ROS 2 bridge (pas_ros_bridge) └── simple-sim/ ├── docker/ # Simple simulator container │ └── docker-compose.yaml # Launch configuration @@ -37,6 +44,7 @@ Simulation components are launched via Docker Compose. Each simulator has its ow - **Isaac Sim:** `simulation/isaac-sim/docker/docker-compose.yaml` - **Microsoft AirSim (legacy):** `simulation/ms-airsim/docker/docker-compose.yaml` +- **Project AirSim:** `simulation/project-airsim/docker/docker-compose.yaml` - **Simple Sim:** `simulation/simple-sim/docker/docker-compose.yaml` **Key launch points:** @@ -90,6 +98,22 @@ An open-source drone simulator built on Unreal Engine with native PX4 SITL integ **Location:** `simulation/ms-airsim/` +### Project AirSim (Unreal Engine 5) + +[Project AirSim](https://github.com/iamaisim/ProjectAirSim) is the maintained successor to Microsoft AirSim (IAMAI Simulations; UE5; MIT). AirStack runs a packaged UE5 environment, PX4 SITL in lockstep, and a C++ ROS 2 bridge in one container, publishing the same sensor topics as the other simulators plus a 3D LiDAR. + +**Use cases:** + +- PX4-in-the-loop testing in UE5 environments +- LiDAR + stereo autonomy, including the default MIGHTY stack (`full_default`) +- Headless camera rendering for CI + +**Launch:** `airstack up --sim projectairsim` + +**Location:** `simulation/project-airsim/` + +**Getting Started:** [Project AirSim](project-airsim/index.md) + ### Simple Sim (Lightweight) A lightweight kinematic simulator (single ROS 2 node, no PX4/MAVROS — it mocks the MAVROS interface directly) for fast iteration when full Isaac Sim fidelity isn't needed. Single robot only. See [Simple Sim](simple_sim/index.md). diff --git a/docs/simulation/ms-airsim/index.md b/docs/simulation/ms-airsim/index.md index c4d27faa9..9e26a1b93 100644 --- a/docs/simulation/ms-airsim/index.md +++ b/docs/simulation/ms-airsim/index.md @@ -25,7 +25,7 @@ Microsoft AirSim (legacy) provides an alternative simulation backend for AirStac ## Project status -Microsoft archived AirSim, which is why AirStack labels it "legacy": it remains a stable, supported simulation backend here, but the upstream project receives no new features. For a maintained successor, see [Project AirSim](https://github.com/iamaisim/ProjectAirSim) (UE5, new API). +Microsoft archived AirSim, which is why AirStack labels it "legacy": it remains a stable, supported simulation backend here, but the upstream project receives no new features. Its maintained successor, [Project AirSim](https://github.com/iamaisim/ProjectAirSim) (UE5, new API), is also integrated into AirStack — see [Project AirSim](../project-airsim/index.md) (`airstack up --sim projectairsim`), which adds a 3D LiDAR and runs the default MIGHTY stack. ## Quick Start diff --git a/docs/simulation/project-airsim/index.md b/docs/simulation/project-airsim/index.md new file mode 100644 index 000000000..e445a4d44 --- /dev/null +++ b/docs/simulation/project-airsim/index.md @@ -0,0 +1,290 @@ +# Project AirSim + +[Project AirSim](https://github.com/iamaisim/ProjectAirSim) is the maintained successor to Microsoft AirSim, developed by IAMAI Simulations on Unreal Engine 5. AirStack runs it with PX4 SITL in lockstep and a C++ ROS 2 bridge. The bridge publishes the same sensor topics as the other simulators, plus a 3D LiDAR. That LiDAR means the default MIGHTY stack (`full_default`) runs on Project AirSim; Microsoft AirSim (legacy) has no LiDAR and runs only the stereo-based DROAN stacks. + + +*The default MIGHTY stack (`full_default`) flying a 100 m street route on Project AirSim's LiDAR in the Neighborhood environment, followed by the optional chase camera, with the onboard left stereo camera inset (`airstack up --sim projectairsim --scene neighborhood`, 3× speed).* + +## Overview + +What Project AirSim provides in AirStack: + +- **PX4 SITL in lockstep.** PX4 v1.16.1 connects over HIL TCP on a steppable 3 ms clock. MAVROS in the robot container talks to PX4 exactly as it does on hardware. +- **Stereo + depth + 3D LiDAR.** Front stereo RGB, ground-truth depth, and a GPU-rendered Ouster-style LiDAR on the same topics Isaac Sim uses. +- **Headless rendering.** Cameras render in `--headless` mode, so camera-dependent CI tests run without a display. +- **Packaged UE5 environments.** Blocks, Neighborhood, LandscapeMountains and CityEnviron, downloaded on first use. No Omniverse account is required. +- **Selectable vehicle dynamics.** Built-in fast-physics (the default) or JSBSim. + +**Trade-offs vs Isaac Sim:** + +- Lighter: no Nucleus, about 8 GB image, environments of 0.9–3.3 GB, and the stack is flight-ready in under a minute (see [Compute cost](#compute-cost)). +- Fewer environments and assets; scenes come as packaged binaries, not editable USD. +- The LiDAR is sparser than Isaac's OS1-128 model (about 10k points per sweep). + +## Quick Start + +### 1. Launch + +```bash +airstack up --sim projectairsim # aliases: --sim pas, --sim project-airsim +airstack up --sim projectairsim --headless # no GUI; cameras still render +``` + +(Equivalently: `airstack up --env-file overrides/project-airsim.env`.) + +The first launch downloads the Blocks environment (about 870 MB) into `simulation/project-airsim/assets/envs/`; progress shows in the container's `pas` tmux window. Wait until the stack is flight-ready: + +```bash +airstack ready +``` + +### 2. Pick an environment + +```bash +airstack up --sim projectairsim --scene neighborhood +``` + +| `--scene` | Environment | Download | Spawn | +|---|---|---|---| +| `default`, `blocks` | Blocks | 0.9 GB | surveyed | +| `neighborhood` | Neighborhood | 2.0 GB | surveyed | +| `landscape-mountains` | LandscapeMountains | 0.9 GB | world origin — set `PROJECT_AIRSIM_SPAWN_ORIGIN` | +| `city-environ` | CityEnviron | 3.3 GB | world origin — set `PROJECT_AIRSIM_SPAWN_ORIGIN` | + +Environments come from the Project AirSim GitHub release named by `PROJECT_AIRSIM_RELEASE` (default `v1.1.0`). Each download is checked against the SHA-256 GitHub publishes for it. See [Spawn origins](#spawn-origins) for why some environments need a spawn point. + +### 3. Pick the physics model + +```bash +airstack up --sim projectairsim --physics jsbsim +``` + +See [Choosing a physics model](#choosing-a-physics-model). + +### 4. Connect + +```bash +airstack connect project-airsim +``` + +The tmux session `project-airsim` has these windows: + +| Window | Process | +|---|---| +| `pas` | The packaged UE5 environment | +| `loader` | One-shot scene loader (idle afterwards) | +| `robot__px4` | PX4 SITL shell for robot *i* (`pxh>`; try `commander status`) | +| `bridge` | The ROS 2 bridge: rates per stream every 10 s | + +## Architecture + +```mermaid +flowchart LR + subgraph PAS["project-airsim container (172.31.0.200)"] + UE["Packaged UE5 environment
topics :8989 · services :8990"] + LOAD["pas_scene_loader
(loads the generated scene, exits)"] + BR["pas_ros_bridge (C++)
one process, one DDS domain per robot"] + PX["PX4 SITL × N
HIL TCP 4560+i (lockstep)"] + LOAD -- services --> UE + BR -- topics --> UE + PX -- TCP --> UE + end + subgraph R["robot container robot_i (ROS_DOMAIN_ID = i)"] + MAV["MAVROS"] + STACK["autonomy stack"] + end + MAV <-- "MAVLink UDP 14580+i ↔ 14540+i" --> PX + BR -- "/clock, sensors, ground truth" --> STACK +``` + +Startup order (`simulation/project-airsim/docker/entrypoint.sh`). The order matters because PX4 must start after the scene exists: + +1. `config/generate_scene.py` writes one scene file (every robot's config inlined) and `airstack_meta.json`, the bridge's topic map. +2. `colcon build` of `ros_ws` (the bridge, linked against the pinned C++ client in `/opt/projectairsim`). +3. The UE5 environment starts; the entrypoint waits for its services port. +4. `pas_scene_loader` loads the scene and exits. +5. After `PROJECT_AIRSIM_PX4_START_DELAY` seconds, one PX4 SITL instance per robot starts (`-i `). +6. `pas_ros_bridge` starts. + +**One bridge process for all robots.** Project AirSim's topic socket accepts exactly one client. The bridge holds it and fans data out to one ROS 2 context per robot, each on that robot's `ROS_DOMAIN_ID`. Any other tool that connects to the topics port (8989) while AirStack runs disconnects the bridge. Tools that only need services (such as `createVoxelGrid` or ground-truth kinematics) can use the services port (8990) freely. + +**PX4 ports for robot *i*:** + +| Link | Port | Notes | +|---|---|---| +| HIL lockstep | TCP 4560+i | Project AirSim listens; PX4 connects | +| MAVROS (offboard) | UDP 14580+i ↔ 14540+i | Same as Isaac Sim and hardware | +| Project AirSim control link | UDP 24540+i | Deliberately unused. Project AirSim's default (14540) would take MAVROS's port. | + +Because Project AirSim's own control link is parked on an unused port, its parameter push never reaches PX4. PX4 parameters are therefore set PX4-side, through `PX4_PARAM_*` environment variables in the entrypoint. + +## Choosing a physics model + +| | `fast-physics` (default) | `jsbsim` | +|---|---|---| +| Model | Project AirSim's rigid-body quad: point-mass rotors, box drag | Auterion's `quadrotor_x` JSBSim flight-dynamics model | +| Status | Validated: liveliness, sensors, takeoff/hover/land, fixed trajectories, MIGHTY waypoint flight, two robots | **Experimental:** the scene loads and sensors stream, but PX4's EKF does not complete tilt alignment at rest (IMU contact jitter) | +| Use for | All AirStack testing | Investigating flight-dynamics fidelity | + +Selection, first match wins: + +1. `airstack up --physics jsbsim` (or `PROJECT_AIRSIM_PHYSICS`), for every robot +2. fleet file `robots..physics`, for one robot +3. fleet file `sim.physics`, for the whole fleet +4. vehicle manifest `project_airsim.physics` (`config/vehicles//vehicle.yaml`) +5. `fast-physics` + +A mixed fleet, for example: + +```yaml +robots: + robot_1: {spawn: [0, 0, 0]} + robot_2: {spawn: [0, 3, 0], physics: jsbsim} +sim: + physics: fast-physics +``` + +Both variants carry identical sensors and PX4 settings; only the dynamics differ. The choice per robot is printed in the container log (`generate_scene: robot_1: physics=...`). + +## Spawn origins + +Project AirSim places `0 0 0` at the Unreal world origin, not at a player start. In the packaged Blocks environment that origin lies inside a block and below the ground surface. A drone spawned there is pushed out of the geometry every few seconds, which looks like it teleports to the ground mid-flight. Each environment therefore has a **spawn origin** (NED metres, world frame), and fleet `spawn:` offsets apply relative to it: + +| Environment | Spawn origin (NED) | How it was chosen | +|---|---|---| +| `blocks` | (−38, 0, −1.24) | Nearest point with a clear 40 m × 40 m area ahead and to the left; 5 cm above the measured ground | +| `neighborhood` | (0, 0, −1.24) | The world origin is open street (an east–west road); 5 cm above the measured ground | +| others | (0, 0, 0) | Not surveyed; the container log warns | + +Override it with `PROJECT_AIRSIM_SPAWN_ORIGIN=x,y,z` (NED). To survey an environment: + +1. Query occupancy with the `createVoxelGrid` service. Its grid axes come back in (y, up, x) order. +2. Pick a point above ground whose surroundings are clear. +3. Refine the height by landing a drone there: its landed height is the ground top. + +Indoors, check the spawn with a camera frame before flying. In a packaged supermarket, the voxel survey missed a shelf deck over the world origin (takeoff stalled at 0.6 m) and wall freezers at a "clear" point. A frame from the chase camera (`PROJECT_AIRSIM_CHASE_CAM=true`) shows either at once. + +Ground truth (`/robot_i/odom_ground_truth`) is reported relative to each robot's own spawn, matching MAVROS's local origin. + +**Home geo point.** The default home (`PROJECT_AIRSIM_HOME_LAT/LON/ALT`) is Project AirSim's reference location (47.641468, −122.140165, 122 m). Project AirSim's magnetometer uses a dipole approximation whose inclination roughly matches the World Magnetic Model only near that location. PX4's EKF2 checks against the World Magnetic Model, so at a distant home it refuses to arm with *heading estimate not stable*. + +## Sensors and Topics + +Published by `pas_ros_bridge` on robot *i*'s domain: + +| Topic | Type | Rate (default) | +|---|---|---| +| `/robot_i/sensors/front_stereo/{left,right}/image_rect` | `sensor_msgs/Image` (`bgr8`) | ~19 Hz | +| `/robot_i/sensors/front_stereo/{left,right}/camera_info` | `sensor_msgs/CameraInfo` | per image; right P[0,3] = −fx·baseline | +| `/robot_i/sensors/front_stereo/{left,right}/depth_ground_truth` | `sensor_msgs/Image` (`32FC1` m, NaN = no return) | ~19 Hz | +| `/robot_i/sensors/ouster/point_cloud_raw` | `sensor_msgs/PointCloud2` (x, y, z, intensity) | 10 Hz sweeps | +| `/robot_i/odom_ground_truth` | `nav_msgs/Odometry` (ENU, spawn-relative) | 50 Hz | +| `/robot_i/pas_bridge/diagnostics` | `diagnostic_msgs/DiagnosticArray` | every 10 s | +| `/clock` | `rosgraph_msgs/Clock` | ~83 Hz | +| `/robot_i/sensors/chase/image` (+ `camera_info`) | `sensor_msgs/Image` | 30 Hz, only with `PROJECT_AIRSIM_CHASE_CAM=true` | + +All sensor streams use RELIABLE, keep-last-2 QoS, which matches both reliable and best-effort subscribers. Streams with no subscriber are not decoded. + +**Frames.** Images use `camera_left` / `camera_right` (optical frames) and the cloud uses `ouster`, all defined by `iris_stereo_lidar.project-airsim.urdf`. Project AirSim works in NED (world) and FRD (body); the bridge converts to ENU / FLU. + +**LiDAR.** Project AirSim's GPU LiDAR renders a complete 360° ring every frame (about 40 Hz) at a coarse azimuth step. The bridge merges the rings of each sweep period into one cloud and drops exact repeats, producing one dense sweep at `PROJECT_AIRSIM_LIDAR_RATE`, as a spinning sensor does. The defaults approximate the OS1-128 that Isaac Sim models: 128 channels, ±22.5°, 100 m range, 10 Hz. + +**Depth** arrives from the simulator as half-precision metres, so resolution coarsens with range (about 1 cm at 10 m and 6 cm at 100 m). + +## Lumen and recording + +Camera images use the lighting the packaged environment was built with. Blocks has no dynamic global illumination, so its shadowed faces render near-black. Neighborhood's lighting fills its shadows. The released environments are Shipping builds, which ignore console-variable overrides (command line, `-ini:` and user config files alike), so their lighting model cannot be changed from outside the package. + +`PROJECT_AIRSIM_LUMEN=true` or `false` forces Lumen GI and reflections on or off per RGB capture, through Project AirSim's `lumen-gi-enabled` / `lumen-reflections-enabled` capture settings. Unset keeps the environment's own method. The settings arrived after `v1.1.0` (Project AirSim PR #181), so the released environments ignore them. To use Lumen, package your own environment with the plugin built from Project AirSim `main` (see [Custom environments](#custom-environments)). + +![Lumen off (left) and on (right) in a packaged supermarket scene: onboard RGB (top) and chase camera (bottom)](../../assets/media/project_airsim_lumen_ab.jpg) + +In that supermarket scene, Lumen lifts the onboard camera's darkest-30 % pixels from a mean of 2 to 16 (0–255). It costs about 6 % of the onboard camera rate (16.0 → 15.1 Hz), 11 % of the 720p chase camera rate, and 0.4–0.9 GB of VRAM on an RTX 5090. + +`PROJECT_AIRSIM_CHASE_CAM=true` adds a third-person camera (1280×720 at 30 Hz, gimbal-levelled, 6 m behind and 2 m above the drone), published on `/robot_i/sensors/chase/image` for demos and recordings. + +## Custom environments + +Any Unreal project can become a Project AirSim environment by adding the plugin and packaging it (upstream guide: [Using the plugin in a custom environment](https://github.com/iamaisim/ProjectAirSim/blob/main/docs/use_plugin.md)). This is also the route to Lumen, until a release ships the Lumen capture settings. + +1. **Build the plugin** from Project AirSim `main` with the Unreal Engine version your project uses (`build.sh` in the Project AirSim repository). The built `unreal/Blocks/Plugins/{ProjectAirSim,Drone,Rover}` folders are the plugin. +2. **Add it to your project:** copy those three folders into `/Plugins/` and enable them in the `.uproject`. In `Config/DefaultEngine.ini` set `GlobalDefaultGameMode=/Script/ProjectAirSim.ProjectAirSimGameMode` and `GameDefaultMap` to your map. A Blueprint-only project needs an (empty) C++ `Source` module to compile the plugin. +3. **Cook the plugin content:** in `Config/DefaultGame.ini`, under `[/Script/UnrealEd.ProjectPackagingSettings]`, add `+DirectoriesToAlwaysCook=(Path="/ProjectAirSim")` (and `/Drone`, `/Rover`), plus `+MapsToCook=` for your map. +4. **Package a Development build for Linux:** + ```bash + $UE_ROOT/Engine/Build/BatchFiles/RunUAT.sh BuildCookRun -project=.uproject \ + -nop4 -build -cook -compressed -pak -stage -archive -archivedirectory= \ + -map=/Game// -clientconfig=Development -utf8output + ``` + Use Development rather than Shipping, because Shipping ignores every console-variable override. +5. **Run it:** put the package under `simulation/project-airsim/assets/envs//`, then launch with `PROJECT_AIRSIM_BINARY_PATH=/project-airsim-env//.sh` and a spawn origin for the map (`PROJECT_AIRSIM_SPAWN_ORIGIN=x,y,z`, see [Spawn origins](#spawn-origins)). + +!!! note "Unreal Engine 5.8" + Plugin sources up to Project AirSim `1281f03` don't compile against UE 5.8, because `FJsonObject` keys are now `UE::FSharedString`. In `PASSceneConnector.cpp`, copy each key into an `FString` (`const FString Key(*Pair.Key);`) before concatenating it. + +The client the `project-airsim` image compiles is pinned to `v1.1.0`. Its wire protocol is unchanged on `main`, so it drives environments built from `main`. + +## Compute cost + +Measured on one workstation (RTF = real-time factor). The workload is one robot running the `full_default` stack, headless, hovering at 10 m. Sim-container figures are averaged over 60 s of hover. + +| | Project AirSim (Blocks) | Microsoft AirSim legacy (Blocks) | Isaac Sim (default scene) | +|---|---|---|---| +| `airstack up` → flight-ready | **22 s** | 21 s | 105 s | +| Simulator CPU | 5.4 cores | 3.3 cores | 6.5 cores | +| Simulator RAM | 1.0 GB | 0.5 GB | 12.7 GB | +| GPU utilisation | 79 % | 63 % | 19 % | +| GPU memory | 2.0 GB | 0.7 GB | 4.1 GB | +| Real-time factor | 1.00 | 1.00 | 1.17 | +| Simulator image | 8.4 GB | 8.6 GB | 23.1 GB | +| Environment download | 0.9 GB (once) | 0.2 GB (once) | streamed from Nucleus | +| Sensors simulated | stereo + depth + GPU LiDAR | stereo + depth | stereo + depth + RTX LiDAR | + +Test conditions: single RTX 5090, 30 hardware threads, one robot; workspaces already built and environments already downloaded. CPU and RAM are measured on the simulator container (`docker stats`); GPU figures are above the idle desktop baseline. The robot container runs the same stack in all three (about 3.5 cores; less on Microsoft AirSim, which has no LiDAR for MIGHTY's mapping to consume). Unreal renders uncapped in headless mode, which is why Project AirSim's GPU utilisation is high on an otherwise idle scene. + +## Configuration + +All variables are optional; set them in `.env`, an `--env-file`, or the shell. + +| Variable | Default | Description | +|---|---|---| +| `PROJECT_AIRSIM_ENV` | `blocks` | Packaged environment (`fetch_env.sh` key). Set by `--scene`. | +| `PROJECT_AIRSIM_RELEASE` | `v1.1.0` | Release to download environments from. Must match the client the image compiles (`PROJECT_AIRSIM_REF` build argument). | +| `PROJECT_AIRSIM_ENV_DIR` | `simulation/project-airsim/assets/envs` | Host directory holding downloaded environments | +| `PROJECT_AIRSIM_BINARY_PATH` | — | Explicit environment launcher in the container; bypasses `PROJECT_AIRSIM_ENV` | +| `PROJECT_AIRSIM_HEADLESS` | `false` | `-RenderOffScreen`; cameras still render. Set by `--headless`. | +| `PROJECT_AIRSIM_RENDER` | `vulkan` | `null` disables rendering entirely (no cameras or LiDAR): GPU-free physics and PX4 only | +| `PROJECT_AIRSIM_PHYSICS` | — (`fast-physics`) | `fast-physics` or `jsbsim`, for every robot. Set by `--physics`. | +| `PROJECT_AIRSIM_LUMEN` | — | `true` / `false` / unset; see [Lumen and recording](#lumen-and-recording) | +| `PROJECT_AIRSIM_CHASE_CAM` | `false` | Third-person chase camera | +| `PROJECT_AIRSIM_SPAWN_ORIGIN` | per environment | `x,y,z` NED spawn origin; see [Spawn origins](#spawn-origins) | +| `PROJECT_AIRSIM_SPAWN_SPACING` | `3` | Metres between robots (along ENU x) when no fleet is used | +| `PROJECT_AIRSIM_PX4_START_DELAY` | `3` | Seconds between scene load and PX4 start (too short gives a bad EKF origin) | +| `PROJECT_AIRSIM_CAM_WIDTH` / `_HEIGHT` / `_FOV` / `_RATE` / `_PITCH` | 480 / 300 / 90° / 20 Hz / 0° | Stereo cameras; baseline 0.12 m | +| `PROJECT_AIRSIM_LIDAR` | `true` | `false` removes the LiDAR | +| `PROJECT_AIRSIM_LIDAR_CHANNELS` / `_COLUMNS` / `_RATE` / `_RANGE` | 128 / 512 / 10 Hz / 100 m | LiDAR model | +| `PROJECT_AIRSIM_HOME_LAT` / `_LON` / `_ALT` | 47.641468 / −122.140165 / 122 | Geo origin; see [Spawn origins](#spawn-origins) | +| `PROJECT_AIRSIM_START_LANDED` | `true` | Hold robots at their spawn until takeoff | + +**Version pinning.** The image compiles Project AirSim's C++ client from a shallow, sparse clone of the tag `PROJECT_AIRSIM_REF`, and checks that the tag resolves to the commit `PROJECT_AIRSIM_SHA` (build arguments in `simulation/project-airsim/docker/Dockerfile`). No Project AirSim source is kept in the AirStack repository or the final image. When upgrading, bump the tag, the commit and `PROJECT_AIRSIM_RELEASE` together: the server has no version handshake, and the bridge logs the server build on connect. + +## Troubleshooting + +**The drone teleports to the ground, or `collision_info` reports constant contacts.** The spawn is inside geometry. Survey the environment and set `PROJECT_AIRSIM_SPAWN_ORIGIN` (see [Spawn origins](#spawn-origins)). + +**PX4: *heading estimate not stable*.** The home geo point is far from Project AirSim's reference location; see [Spawn origins](#spawn-origins). + +**The bridge window shows *topic never appeared* or no data.** The scene did not load (check the `loader` window), or another client took the topics port. Restart the bridge in its window; the scene does not need reloading. + +**The bridge exits with *sim clock went backwards*.** The scene was reloaded, which resets the clock to zero. PX4 must restart too, so restart the container. + +**No environment launches.** Check the `pas` window. The download is verified against GitHub's SHA-256, so a mismatch aborts. `PROJECT_AIRSIM_BINARY_PATH` must point at the environment's `.sh` inside the container. + +## See Also + +- [Simulation Overview](../index.md): choosing between simulators +- [Simulation Scenes](../scenes.md): the cross-simulator scene catalog +- [`pas_ros_bridge`](https://github.com/castacks/AirStack/blob/develop/simulation/project-airsim/ros_ws/src/pas_ros_bridge/README.md): bridge internals +- Upstream: [Project AirSim documentation](https://iamaisim.github.io/ProjectAirSim/) diff --git a/docs/simulation/scenes.md b/docs/simulation/scenes.md index 4cca0f56b..1f2d900de 100644 --- a/docs/simulation/scenes.md +++ b/docs/simulation/scenes.md @@ -2,7 +2,8 @@ Every simulator names its environments differently — Isaac Sim loads Pegasus catalog entries or USD stages from an Omniverse Nucleus server, while -Microsoft AirSim (legacy) runs pre-built Unreal Engine binaries. So that +Microsoft AirSim (legacy) and Project AirSim run pre-built Unreal Engine +binaries. So that developers don't have to know each simulator's addressing scheme, AirStack keeps one simulator-agnostic **scene catalog** and a single launch flag: `airstack up --scene ` maps the shortname to whatever the selected @@ -19,6 +20,9 @@ airstack up --sim isaac --scene warehouse # Microsoft AirSim (legacy): the Blocks UE4 scene airstack up --sim airsim --scene blocks + +# Project AirSim: the packaged UE5 neighborhood environment +airstack up --sim projectairsim --scene neighborhood ``` Passing an unknown scene — or one the selected simulator doesn't have — @@ -26,10 +30,10 @@ prints a table of every available scene per simulator: ```bash airstack up --sim isaac --scene blocks -# ERROR: scene 'blocks' is not available for Isaac (only: MS AirSim). Available scenes: -# SCENE ISAAC MS AIRSIM -# abandoned-factory nucleus:AbandonedFactory.stage.usd - -# blocks - blocks +# ERROR: scene 'blocks' is not available for Isaac (only: MS AirSim, Project AirSim). Available scenes: +# SCENE ISAAC MS AIRSIM PROJECT AIRSIM +# abandoned-factory nucleus:AbandonedFactory.stage.usd - - +# blocks - blocks blocks # ... ``` @@ -43,7 +47,7 @@ python3 simulation/resolve_scene.py --table The catalog lives in [`simulation/scenes.yaml`](https://github.com/castacks/AirStack/blob/main/simulation/scenes.yaml). Each shortname declares the scene reference per simulator, so the same name can -exist for both simulators without ambiguity — resolution always follows the +exist for several simulators without ambiguity — resolution always follows the simulator selected by `--sim` (or the active compose profile): ```yaml @@ -56,6 +60,7 @@ scenes: isaac: Warehouse # bare string = Pegasus catalog key (or a USD URL) blocks: msairsim: blocks # fetch_scene.sh key (pre-built UE4 binary) + projectairsim: blocks # fetch_env.sh key (packaged UE5 environment) ``` `airstack up --scene` resolves the shortname host-side @@ -67,8 +72,10 @@ flowchart LR A["airstack up --sim isaac --scene construction-site"] --> B["resolve_scene.py
reads simulation/scenes.yaml"] B -->|Isaac| C["ISAAC_SIM_SCENE
ISAAC_SIM_STAGE_SCALE"] B -->|MS AirSim| D["MS_AIRSIM_SCENE"] + B -->|Project AirSim| G["PROJECT_AIRSIM_ENV"] C --> E["Pegasus launch script
loads catalog key or USD URL"] D --> F["ms-airsim entrypoint
fetches + runs the UE4 binary"] + G --> H["project-airsim entrypoint
fetches + runs the UE5 environment"] ``` The exported variables are ordinary launch config — they appear in the @@ -85,6 +92,7 @@ ISAAC_SIM_SCENE="omniverse://my-server/My/Stage.usd" airstack up --sim isaac | `ISAAC_SIM_SCENE` | Isaac | A Pegasus `SIMULATION_ENVIRONMENTS` key (e.g. `Warehouse`) or a USD reference (`omniverse://`/`https://` URL or `*.usd` path). Empty = the launch script's default (`Default Environment`). | | `ISAAC_SIM_STAGE_SCALE` | Isaac | Scale applied to the loaded `/World/stage` prim. `0.01` converts centimeter-authored stages to meters; default `1.0`. | | `MS_AIRSIM_SCENE` | MS AirSim | A `fetch_scene.sh` catalog key (e.g. `blocks`, `airsimnh`). Empty = `blocks`. Ignored when `MS_AIRSIM_BINARY_PATH` is set. | +| `PROJECT_AIRSIM_ENV` | Project AirSim | A `fetch_env.sh` catalog key (`blocks`, `neighborhood`, `landscapemountains`, `cityenviron`). Empty = `blocks`. Ignored when `PROJECT_AIRSIM_BINARY_PATH` is set. | Fleets can pin a scene in their fleet file (`sim.scene`); a `--scene` flag on the command line overrides it, with a log line noting the override. @@ -171,6 +179,33 @@ You can also pre-fetch manually: An explicit `MS_AIRSIM_BINARY_PATH` (pointing at any extracted UE4 binary) always wins over `--scene`. +### Project AirSim — packaged UE5 environments + +These map to `fetch_env.sh` keys; the packaged Linux environments come from the +[Project AirSim release](https://github.com/iamaisim/ProjectAirSim/releases) +named by `PROJECT_AIRSIM_RELEASE` (default `v1.1.0`): + +| Shortname | UE5 environment | +|-----------|-----------------| +| `blocks` (also `default`) | Blocks | +| `neighborhood` | Neighborhood | +| `landscape-mountains` | LandscapeMountains | +| `city-environ` | CityEnviron | + +Environments (0.9–3.3 GB each) download on first use into +`simulation/project-airsim/assets/envs/`, with the same flow as MS AirSim +scenes: an interactive `airstack up` asks before downloading, and a +non-interactive run lets the container auto-fetch inside the `pas` tmux window. +Every downloaded part is verified against the SHA-256 digest GitHub publishes +for the release asset. To pre-fetch manually: + +```bash +./simulation/project-airsim/assets/envs/fetch_env.sh neighborhood +``` + +An explicit `PROJECT_AIRSIM_BINARY_PATH` (pointing at any packaged +environment's launcher) always wins over `--scene`. + ## Using a Stage Directly in a Launch Script The example Pegasus launch scripts resolve their scene from the environment, @@ -207,7 +242,10 @@ PegasusApp( For MS AirSim, the catalog can only reference scenes `fetch_scene.sh` knows how to download (the v1.8.1 release binaries); add the key to both files. +Project AirSim works the same way with `fetch_env.sh` (the packaged +environments of the Project AirSim release). **Learn more:** [Pegasus scene setup](isaac_sim/pegasus_scene_setup.md) · [Spawning drones](isaac_sim/spawning_drones.md) · -[Microsoft AirSim setup](ms-airsim/index.md) +[Microsoft AirSim setup](ms-airsim/index.md) · +[Project AirSim setup](project-airsim/index.md) diff --git a/mkdocs.yml b/mkdocs.yml index f3d42d677..946cc4173 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -25,6 +25,8 @@ exclude_docs: | # same-dir plugin copies them into every site build (~15 GB per build). simulation/ms-airsim/assets/scenes/** simulation/ms-airsim/environments/** + # Downloaded Project AirSim UE5 environments (fetched by assets/envs/fetch_env.sh) + simulation/project-airsim/assets/envs/** # Fetched module checkouts (RFC #379 §9): the docs deploy workflows clone the # registry index + each registered module repo into the gitignored modules/ # dir. Their content is linked from docs/modules/ (generated by @@ -106,6 +108,7 @@ nav: - Isaac Sim: docs/simulation/isaac_sim/index.md - Pegasus Extension: docs/simulation/isaac_sim/pegasus_scene_setup.md - Microsoft AirSim (legacy): docs/simulation/ms-airsim/index.md + - Project AirSim: docs/simulation/project-airsim/index.md - Simple Sim: docs/simulation/simple_sim/index.md - Ground Control Station: docs/gcs/index.md - CI/CD Architecture: docs/development/intermediate/testing/ci_cd.md @@ -180,6 +183,7 @@ nav: - Robot: docs/robot/docker/index.md - Isaac Sim: docs/simulation/isaac_sim/docker.md - Microsoft AirSim (legacy): docs/simulation/ms-airsim/docker.md + - Project AirSim bridge: simulation/project-airsim/ros_ws/src/pas_ros_bridge/README.md - Simple Sim: docs/simulation/simple_sim/docker.md - GCS: docs/gcs/docker/index.md - Deployment Topologies: docs/robot/autonomy_modes.md diff --git a/overrides/project-airsim.env b/overrides/project-airsim.env new file mode 100644 index 000000000..6ebec3e2c --- /dev/null +++ b/overrides/project-airsim.env @@ -0,0 +1,9 @@ +# overrides specific to running Project AirSim +# run as airstack up --env-file overrides/project-airsim.env; OR docker compose --env-file .env --env-file overrides/project-airsim.env up +# +# Equivalent intent flag (derives both values below): airstack up --sim projectairsim +# This file selects a SIMULATOR, not a topology — stack/fleet selection is +# orthogonal: add --stack (docs/development/stacks.md) or +# --fleet (docs/development/fleets.md) on the same command line. +COMPOSE_PROFILES="desktop,project-airsim" +URDF_FILE="robot_descriptions/iris/urdf/iris_stereo_lidar.project-airsim.urdf" diff --git a/simulation/ms-airsim/docker/Dockerfile b/simulation/ms-airsim/docker/Dockerfile index dcb2c4537..b6f098b5b 100644 --- a/simulation/ms-airsim/docker/Dockerfile +++ b/simulation/ms-airsim/docker/Dockerfile @@ -12,7 +12,12 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ # PX4 SITL ARG PX4_VERSION="v1.16.1" RUN git clone --branch ${PX4_VERSION} --recursive https://github.com/PX4/PX4-Autopilot.git -RUN cd PX4-Autopilot && Tools/setup/ubuntu.sh --no-nuttx --no-sim-tools +# numpy<2: PX4's requirements pull the newest pandas, and pandas >= 3 needs +# numpy >= 2, which pip cannot install over the Debian numpy 1.26 that the +# ROS Jazzy Python packages are built against ("Cannot uninstall numpy"). +RUN echo "numpy<2" > /tmp/pip-constraints.txt \ + && cd PX4-Autopilot && PIP_CONSTRAINT=/tmp/pip-constraints.txt \ + Tools/setup/ubuntu.sh --no-nuttx --no-sim-tools RUN cd PX4-Autopilot && make px4_sitl_default # Microsoft AirSim (legacy) Python client with msgpack fix diff --git a/simulation/project-airsim/assets/envs/fetch_env.sh b/simulation/project-airsim/assets/envs/fetch_env.sh new file mode 100755 index 000000000..a25a46ba0 --- /dev/null +++ b/simulation/project-airsim/assets/envs/fetch_env.sh @@ -0,0 +1,182 @@ +#!/usr/bin/env bash +# Fetch and extract a Project AirSim pre-built (packaged UE5) environment into +# simulation/project-airsim/assets/envs//. Idempotent — skips when the +# environment's launcher (/.sh) already exists. +# +# Usage: fetch_env.sh [env] +# fetch_env.sh --name # print the env's directory name and exit +# fetch_env.sh --launcher # print the env's launcher path and exit +# fetch_env.sh --list # print the catalog keys and exit +# env (default: blocks) — one of: blocks, landscapemountains, neighborhood, +# cityenviron +# +# Environments come from the Project AirSim GitHub release named by +# PROJECT_AIRSIM_RELEASE (default v1.1.0). Large environments are published +# as byte-split parts (.001, .002, ...) that are concatenated before +# extraction. Every downloaded part is verified against the SHA-256 digest +# GitHub publishes for the release asset; a mismatch aborts. +# +# Environments are fetched at first launch rather than baked into the image: +# they carry Epic/third-party asset terms, and they are 0.9–3.3 GB each. + +set -euo pipefail + +RELEASE="${PROJECT_AIRSIM_RELEASE:-v1.1.0}" +VERSION="${RELEASE#v}" +REPO="iamaisim/ProjectAirSim" +ENVS_DIR="${ENVS_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)}" + +catalog() { + # key → directory name / asset base name / number of split parts (0 = single zip) + case "$1" in + blocks) echo "Blocks 0" ;; + landscapemountains) echo "LandscapeMountains 0" ;; + neighborhood) echo "Neighborhood 2" ;; + cityenviron) echo "CityEnviron 2" ;; + *) return 1 ;; + esac +} + +# SHA-256 digests GitHub publishes for the v1.1.0 Linux assets +# (gh api repos/iamaisim/ProjectAirSim/releases/tags/v1.1.0 → .assets[].digest). +# Other releases are verified against the live API digest instead. +known_digest() { + case "$1" in + Blocks-Linux-1.1.0.zip) echo b2632f3749791ce407ba1520136d28547e8a4116fbe49b082a65076f37fd627a ;; + LandscapeMountains-Linux-1.1.0.zip) echo 39072741e86bce4ffcfa84f5e8a3e530f2d8af606e42a1360fa15e08c2137cee ;; + Neighborhood-Linux-1.1.0.zip.001) echo a9281509cf8ac92d7aa00ed07f939f62eec95d31f7714681d05667a7e9a9556b ;; + Neighborhood-Linux-1.1.0.zip.002) echo 1e15609e4ddf5fcdd4683c453123e357ed26a3f973505851c67c8bdd467cf439 ;; + CityEnviron-Linux-1.1.0.zip.001) echo fb4d1db03e38a13dab0403c606509724da630de63073948ebbe921aba1bc611a ;; + CityEnviron-Linux-1.1.0.zip.002) echo 813e870b51fb50a835ec1c7d0a817ab98a86b765cfc43fa46cf3f9f0494101e8 ;; + *) echo "" ;; + esac +} + +api_digest() { + # Fallback for releases without a pinned table: ask the GitHub API. + curl -fsSL "https://api.github.com/repos/$REPO/releases/tags/$RELEASE" \ + | python3 -c 'import json,sys; a={x["name"]:(x.get("digest") or "") for x in json.load(sys.stdin)["assets"]}; print(a.get(sys.argv[1],"").removeprefix("sha256:"))' "$1" +} + +if [ "${1:-}" = "--list" ]; then + echo "blocks landscapemountains neighborhood cityenviron" + exit 0 +fi +NAME_ONLY="" +LAUNCHER_ONLY="" +if [ "${1:-}" = "--name" ]; then + NAME_ONLY=1 + shift +elif [ "${1:-}" = "--launcher" ]; then + LAUNCHER_ONLY=1 + shift +fi +ENV_KEY="${1:-blocks}" +read -r NAME PARTS < <(catalog "$ENV_KEY") || { + echo "unknown Project AirSim environment: $ENV_KEY (choose: $("$0" --list))" >&2 + exit 2 +} +if [ -n "$NAME_ONLY" ]; then + echo "$NAME" + exit 0 +fi + +DEST="$ENVS_DIR/$NAME" + +# Packaged environments do not share one layout (Blocks: Blocks.sh at the +# zip root; Neighborhood: a Neighborhood-Linux-/ wrapper holding +# AirSimNH.sh). The launcher's file name is recorded in /.launcher at +# extraction; .sh is the fallback for environments extracted earlier. +launcher_path() { + if [ -f "$DEST/.launcher" ]; then + echo "$DEST/$(cat "$DEST/.launcher")" + else + echo "$DEST/$NAME.sh" + fi +} +if [ -n "$LAUNCHER_ONLY" ]; then + launcher_path + exit 0 +fi + +# The packaged env runs as the container's non-root `pas` user, whose uid +# need not own these (bind-mounted, host-owned) files: make them readable and +# the launcher + engine binaries executable instead of chown-ing host files. +# Zip extraction does not always preserve exec bits, so this runs on every +# call, not only after a download. +fix_permissions() { + chmod -R a+rX "$DEST" + chmod a+x "$(launcher_path)" + find "$DEST" -path '*/Binaries/Linux/*' -type f -exec chmod a+x {} + 2>/dev/null || true +} + +if [ -f "$(launcher_path)" ]; then + fix_permissions + echo "$NAME already present in $DEST" + exit 0 +fi + +ZIP="$NAME-Linux-$VERSION.zip" +if [ "$PARTS" -eq 0 ]; then + ASSETS=("$ZIP") +else + ASSETS=() + for k in $(seq 1 "$PARTS"); do ASSETS+=("$(printf '%s.%03d' "$ZIP" "$k")"); done +fi + +mkdir -p "$ENVS_DIR" +TMP="$(mktemp -d "$ENVS_DIR/.fetch-$NAME.XXXXXX")" +trap 'rm -rf "$TMP"' EXIT + +for asset in "${ASSETS[@]}"; do + echo "Downloading $asset ($RELEASE)..." + curl -fL --retry 3 "https://github.com/$REPO/releases/download/$RELEASE/$asset" -o "$TMP/$asset" + want="$(known_digest "$asset")" + [ -z "$want" ] && want="$(api_digest "$asset" || true)" + if [ -z "$want" ]; then + echo "WARNING: no published SHA-256 for $asset — skipping verification" >&2 + else + got="$(sha256sum "$TMP/$asset" | cut -d' ' -f1)" + if [ "$got" != "$want" ]; then + echo "ERROR: SHA-256 mismatch for $asset (got $got, want $want)" >&2 + exit 1 + fi + echo "Verified $asset" + fi +done + +if [ "$PARTS" -ne 0 ]; then + echo "Joining ${#ASSETS[@]} parts..." + cat "${ASSETS[@]/#/$TMP/}" > "$TMP/$ZIP" + rm -f "${ASSETS[@]/#/$TMP/}" +fi + +echo "Extracting to $DEST..." +mkdir -p "$TMP/extract" +unzip -q "$TMP/$ZIP" -d "$TMP/extract" +SRC="$TMP/extract" +# Lift a single wrapper directory (e.g. Neighborhood-Linux-1.1.0/). +if ! compgen -G "$SRC/*.sh" > /dev/null; then + shopt -s nullglob dotglob + entries=("$SRC"/*) + shopt -u nullglob dotglob + if [ "${#entries[@]}" -eq 1 ] && [ -d "${entries[0]}" ]; then + SRC="${entries[0]}" + fi +fi +# The launcher: .sh if present, else the only top-level *.sh. +if [ -f "$SRC/$NAME.sh" ]; then + LAUNCHER="$NAME.sh" +else + mapfile -t scripts < <(cd "$SRC" && ls -1 *.sh 2>/dev/null) + if [ "${#scripts[@]}" -ne 1 ]; then + echo "ERROR: $ZIP: cannot identify the environment launcher (top-level .sh files: ${scripts[*]:-none})" >&2 + exit 1 + fi + LAUNCHER="${scripts[0]}" +fi +rm -rf "$DEST" +mv "$SRC" "$DEST" +echo "$LAUNCHER" > "$DEST/.launcher" +fix_permissions +echo "Ready: $DEST/$LAUNCHER" diff --git a/simulation/project-airsim/config/generate_scene.py b/simulation/project-airsim/config/generate_scene.py new file mode 100755 index 000000000..ccd90bfab --- /dev/null +++ b/simulation/project-airsim/config/generate_scene.py @@ -0,0 +1,622 @@ +#!/usr/bin/env python3 +"""Generate the Project AirSim scene for AirStack. + +Writes one fully merged scene file (robot configs inlined, so the loader needs +no sim_config directory) plus ``airstack_meta.json``, the per-robot facts the +entrypoint and the C++ bridge read (ports, physics, sensor geometry). + +Robots come from the fleet file when ``FLEET_CONFIG_FILE`` is set (resolved +with tools/fleet/resolve_fleet.py from the mounted AirStack checkout), else +``robot_1..robot_NUM_ROBOTS``. + +Conventions: + * Project AirSim is NED world / FRD body; AirStack fleet spawns are ENU, so + a spawn (x, y, z) ENU becomes origin (y, x, -z) NED. + * Robot i (1-based) gets PX4 HIL TCP 4560+i (PX4 SITL instance -i i + connects there) and a DECOY control link on UDP 24540+i: Project AirSim + binds its own "GCS" link to PX4 on control-port, whose upstream default + 14540 collides with MAVROS. The decoy keeps 14540+i/14580+i for MAVROS. + * Physics per robot resolves, first hit wins: PROJECT_AIRSIM_PHYSICS env > + fleet robots..physics > fleet sim.physics > vehicle + project_airsim.physics > fast-physics. +""" + +from __future__ import annotations + +import argparse +import json +import math +import os +import sys +from pathlib import Path + +PHYSICS_CHOICES = ("fast-physics", "jsbsim") +DEFAULT_PHYSICS = "fast-physics" +SCENE_ID = "SceneAirStack" +HIL_TCP_BASE = 4560 +DECOY_CONTROL_LOCAL_BASE = 24540 +DECOY_CONTROL_REMOTE_BASE = 24580 + +# Iris-like quad X (Project AirSim sample geometry; rotor order matches PX4 +# quad-x outputs FR, RL, FL, RR). +_ARM = 0.253 +_ROTORS = ( + # name, x, y, turning direction, jsbsim esc index + ("FL", _ARM, -_ARM, "clock-wise", 2), + ("FR", _ARM, _ARM, "counter-clock-wise", 0), + ("RL", -_ARM, -_ARM, "counter-clock-wise", 1), + ("RR", -_ARM, _ARM, "clock-wise", 3), +) +_PX4_ACTUATOR_ORDER = ("FR", "RL", "FL", "RR") + + +# Where robot spawns are anchored in each packaged environment (NED metres, +# world frame). Project AirSim places "0 0 0" at the Unreal world origin, NOT +# at a PlayerStart, and that origin is not a safe spawn: in Blocks it lies +# INSIDE a 20 m x 11 m block, under a ground slab whose top is 1.19 m above +# the origin — a robot spawned there is resolved out of the geometry every few +# seconds (it "teleports" to the ground mid-flight). Surveyed with the +# createVoxelGrid service (1 m voxels) and refined by landing a drone (the +# landed height is the ground top); see the docs page for the procedure. +# `start-landed` holds a robot at its spawn height until takeoff, so a spawn +# above the ground floats there and lands lower than it started. Entries +# without a survey fall back to the origin and are flagged unverified. +ENV_SPAWN_ORIGIN_NED = { + # Nearest spawn (1 m voxel survey) whose 40 m x 40 m box ahead (+x, + # north) and to the left (-y, west) is clear with 5 m margins — the + # default waypoint_flight route (30 m forward, 30 m left at +10 m) and + # the fixed trajectories then fly open space, and robots spaced along + # +y stay clear of the origin block (x >= -2). z = 5 cm above the 1.19 m + # ground top. + "blocks": (-38.0, 0.0, -1.24), + # The world origin is open street (survey 2026-11-30): an east-west road + # through the origin (x -2..+8 m), hedges and houses from x ~ +10 m. + # Ground top 1.19 m up, as in Blocks. + "neighborhood": (0.0, 0.0, -1.24), +} + + +class ConfigError(ValueError): + """Invalid generator input (bad physics name, bad numbers, bad fleet).""" + + +# ── parameter parsing ──────────────────────────────────────────────────────── + +def _env_str(env, key, default): + """String setting; empty counts as unset (compose passes ${VAR:-} as '').""" + return env.get(key, "").strip() or default + + +def _env_tristate(env, key): + """'' (unset) → None; true/false (and 1/0/yes/no/on/off) → bool.""" + raw = env.get(key, "").strip().lower() + if raw == "": + return None + if raw in ("1", "true", "yes", "on"): + return True + if raw in ("0", "false", "no", "off"): + return False + raise ConfigError(f"{key}={raw!r} must be true, false, or unset") + + +def _env_float(env, key, default): + raw = env.get(key, "") + if raw == "": + return float(default) + try: + return float(raw) + except ValueError as exc: + raise ConfigError(f"{key}={raw!r} is not a number") from exc + + +def _env_int(env, key, default): + value = _env_float(env, key, default) + if value != int(value): + raise ConfigError(f"{key}={env.get(key)!r} must be an integer") + return int(value) + + +def params_from_env(env): + """Collect every tunable from the environment (defaults = docs defaults).""" + channels = _env_int(env, "PROJECT_AIRSIM_LIDAR_CHANNELS", 128) + columns = _env_int(env, "PROJECT_AIRSIM_LIDAR_COLUMNS", 512) + lidar_hz = _env_float(env, "PROJECT_AIRSIM_LIDAR_RATE", 10) + env_key = (env.get("PROJECT_AIRSIM_ENV", "") or "blocks").strip().lower() + origin_raw = env.get("PROJECT_AIRSIM_SPAWN_ORIGIN", "").strip() + if origin_raw: + try: + spawn_origin = tuple(float(v) for v in origin_raw.split(",")) + except ValueError as exc: + raise ConfigError(f"PROJECT_AIRSIM_SPAWN_ORIGIN={origin_raw!r} is not 'x,y,z'") from exc + if len(spawn_origin) != 3: + raise ConfigError(f"PROJECT_AIRSIM_SPAWN_ORIGIN={origin_raw!r} is not 'x,y,z'") + origin_source = "PROJECT_AIRSIM_SPAWN_ORIGIN" + elif env_key in ENV_SPAWN_ORIGIN_NED: + spawn_origin, origin_source = ENV_SPAWN_ORIGIN_NED[env_key], f"surveyed ({env_key})" + else: + spawn_origin, origin_source = (0.0, 0.0, 0.0), "unverified (world origin)" + p = { + "env": env_key, + "spawn_origin_ned": [float(v) for v in spawn_origin], + "spawn_origin_source": origin_source, + "num_robots": _env_int(env, "NUM_ROBOTS", 1), + # start-landed pins a robot at its spawn until takeoff (no drop-in). + "start_landed": _env_str(env, "PROJECT_AIRSIM_START_LANDED", "true").lower() + not in ("0", "false", "no", "off"), + "physics_override": env.get("PROJECT_AIRSIM_PHYSICS", "").strip(), + "spawn_spacing": _env_float(env, "PROJECT_AIRSIM_SPAWN_SPACING", 3), + "cam_width": _env_int(env, "PROJECT_AIRSIM_CAM_WIDTH", 480), + "cam_height": _env_int(env, "PROJECT_AIRSIM_CAM_HEIGHT", 300), + "cam_fov": _env_float(env, "PROJECT_AIRSIM_CAM_FOV", 90), + "cam_rate": _env_float(env, "PROJECT_AIRSIM_CAM_RATE", 20), + "cam_x": _env_float(env, "PROJECT_AIRSIM_CAM_X", 0.4), + "cam_y": _env_float(env, "PROJECT_AIRSIM_CAM_Y", 0.06), + "cam_z": _env_float(env, "PROJECT_AIRSIM_CAM_Z", 0.0), + "cam_pitch": _env_float(env, "PROJECT_AIRSIM_CAM_PITCH", 0.0), + "lidar_enabled": _env_str(env, "PROJECT_AIRSIM_LIDAR", "true").lower() not in ("0", "false", "no", "off"), + "lidar_channels": channels, + "lidar_rate": lidar_hz, + "lidar_points_per_second": _env_int( + env, "PROJECT_AIRSIM_LIDAR_POINTS_PER_SECOND", channels * columns * lidar_hz), + "lidar_range": _env_float(env, "PROJECT_AIRSIM_LIDAR_RANGE", 100), + "lidar_vfov_upper": _env_float(env, "PROJECT_AIRSIM_LIDAR_VFOV_UPPER", 22.5), + "lidar_vfov_lower": _env_float(env, "PROJECT_AIRSIM_LIDAR_VFOV_LOWER", -22.5), + "lidar_z": _env_float(env, "PROJECT_AIRSIM_LIDAR_Z", 0.075), + "lidar_type": _env_str(env, "PROJECT_AIRSIM_LIDAR_TYPE", "gpu_cylindrical"), + # Home geo point: Project AirSim's reference location (its sample + # scenes' home). PAS's magnetometer uses a dipole approximation + # (inherited from legacy AirSim, core_sim earth_utils.hpp) whose + # inclination only roughly matches the World Magnetic Model PX4's + # EKF2 checks against near this point (~55 vs 69 deg here, accepted; + # at PX4's Zurich default it is ~24 vs 63 deg and EKF2 refuses to arm + # with "heading estimate not stable"). Move it only with that in mind. + "home_lat": _env_float(env, "PROJECT_AIRSIM_HOME_LAT", 47.641468), + "home_lon": _env_float(env, "PROJECT_AIRSIM_HOME_LON", -122.140165), + "home_alt": _env_float(env, "PROJECT_AIRSIM_HOME_ALT", 122.0), + "step_ns": _env_int(env, "PROJECT_AIRSIM_STEP_NS", 3_000_000), + "jsbsim_model": _env_str(env, "PROJECT_AIRSIM_JSBSIM_MODEL", "quadrotor_x"), + # Lumen GI + reflections on RGB captures: None = the packaged + # project's own GI method; True/False force it per capture. Only + # environments built with Project AirSim PR #181 (after v1.1.0) + # honour the keys; older captures always use the project's method, + # and Shipping builds ignore command-line / user-ini overrides. + "lumen": _env_tristate(env, "PROJECT_AIRSIM_LUMEN"), + # Optional third-person chase camera for demos / recording. + "chase_cam": _env_tristate(env, "PROJECT_AIRSIM_CHASE_CAM") or False, + "chase_width": _env_int(env, "PROJECT_AIRSIM_CHASE_WIDTH", 1280), + "chase_height": _env_int(env, "PROJECT_AIRSIM_CHASE_HEIGHT", 720), + "chase_fov": _env_float(env, "PROJECT_AIRSIM_CHASE_FOV", 90), + "chase_rate": _env_float(env, "PROJECT_AIRSIM_CHASE_RATE", 30), + } + if p["num_robots"] < 1: + raise ConfigError("NUM_ROBOTS must be >= 1") + if not 5 <= p["cam_fov"] <= 170: + raise ConfigError("PROJECT_AIRSIM_CAM_FOV must be in [5, 170] degrees") + if p["cam_rate"] <= 0 or p["lidar_rate"] <= 0: + raise ConfigError("camera / lidar rates must be > 0") + return p + + +def validate_physics(value, source): + if value not in PHYSICS_CHOICES: + raise ConfigError( + f"unknown physics {value!r} from {source} " + f"(choose one of: {', '.join(PHYSICS_CHOICES)})") + return value + + +def resolve_physics(env_value="", robot_value=None, fleet_value=None, vehicle_value=None): + """Return (physics, source) — first non-empty wins, per the docs order.""" + for value, source in ( + (env_value, "PROJECT_AIRSIM_PHYSICS"), + (robot_value, "fleet robots..physics"), + (fleet_value, "fleet sim.physics"), + (vehicle_value, "vehicle project_airsim.physics"), + ): + if value: + return validate_physics(str(value).strip(), source), source + return DEFAULT_PHYSICS, "default" + + +# ── robot list ─────────────────────────────────────────────────────────────── + +def robots_from_count(params): + robots = [] + for i in range(1, params["num_robots"] + 1): + physics, source = resolve_physics(params["physics_override"]) + robots.append({ + "name": f"robot_{i}", + "index": i, + # legacy convention (ms-airsim): spaced along ENU x + "spawn_enu": [(i - 1) * params["spawn_spacing"], 0.0, 0.0], + "physics": physics, + "physics_source": source, + }) + return robots + + +def robots_from_fleet(params, fleet_file, airstack_root): + sys.path.insert(0, str(Path(airstack_root) / "tools" / "fleet")) + import resolve_fleet # noqa: E402 (mounted AirStack checkout) + + fleet_path = Path(fleet_file) + if not fleet_path.is_absolute(): + fleet_path = Path(airstack_root) / fleet_path + fleet = resolve_fleet.load_fleet(str(fleet_path)) + resolved = resolve_fleet.resolve_fleet(fleet, str(airstack_root)) + fleet_physics = (resolved.get("sim") or {}).get("physics") + robots = [] + for r in resolved["robots"]: + vehicle = resolve_fleet.load_vehicle(str(airstack_root), r["vehicle"]) + vehicle_physics = (vehicle.get("project_airsim") or {}).get("physics") + physics, source = resolve_physics( + params["physics_override"], r.get("physics"), fleet_physics, vehicle_physics) + robots.append({ + "name": r["robot_name"], + "index": r["index"], + "spawn_enu": list(r["spawn"]), + "physics": physics, + "physics_source": source, + }) + return robots + + +# ── config builders ────────────────────────────────────────────────────────── + +def _xyz(x, y, z): + return f"{x:g} {y:g} {z:g}" + + +def _origin(x, y, z, roll=0.0, pitch=0.0, yaw=0.0): + return {"xyz": _xyz(x, y, z), "rpy-deg": _xyz(roll, pitch, yaw)} + + +def enu_to_ned(x, y, z): + return y, x, -z + + +def _links(): + links = [{ + "name": "Frame", + "inertial": { + "mass": 1.0, + "inertia": {"type": "geometry", "geometry": {"box": {"size": "0.180 0.110 0.040"}}}, + "aerodynamics": {"drag-coefficient": 0.325, "type": "geometry", + "geometry": {"box": {"size": "0.180 0.110 0.040"}}}, + }, + "collision": {"restitution": 0.1, "friction": 0.5}, + "visual": {"geometry": {"type": "unreal_mesh", "name": "/Drone/Quadrotor1"}}, + }] + for name, x, y, _, _ in _ROTORS: + origin = _origin(x, y, -0.01) + links.append({ + "name": f"Prop_{name}", + "inertial": { + "origin": origin, "mass": 0.055, "inertia": {"type": "point-mass"}, + "aerodynamics": {"drag-coefficient": 0.325, "type": "geometry", + "geometry": {"cylinder": {"radius": 0.1143, "length": 0.01}}}, + }, + "visual": {"origin": origin, "geometry": { + "type": "unreal_mesh", + "name": "/Drone/PropellerRed" if name.startswith("F") else "/Drone/PropellerWhite"}}, + }) + return links + + +def _joints(): + return [{"id": f"Frame_Prop_{n}", "type": "fixed", "parent-link": "Frame", + "child-link": f"Prop_{n}", "axis": "0 0 1"} for n, *_ in _ROTORS] + + +def _actuators(physics): + out = [] + for name, x, y, direction, esc in _ROTORS: + rotor = { + "turning-direction": direction, "normal-vector": "0.0 0.0 -1.0", + "coeff-of-thrust": 0.109919, "coeff-of-torque": 0.040164, + "max-rpm": 6396.667, "propeller-diameter": 0.2286, "smoothing-tc": 0.005, + } + if physics == "jsbsim": + rotor["jsbsim-cmd"] = f"fcs/esc-cmd-norm[{esc}]" + rotor["jsbsim-state"] = f"fcs/esc-out[{esc}]" + out.append({ + "name": f"Prop_{name}_actuator", "type": "rotor", "enabled": True, + "parent-link": "Frame", "child-link": f"Prop_{name}", + "origin": _origin(x, y, -0.01), "rotor-settings": rotor, + }) + return out + + +def _controller(index, params): + return { + "id": "PX4_Controller", + "type": "px4-api", + "px4-settings": { + "lock-step": True, + "use-serial": False, + "use-tcp": True, + "tcp-port": HIL_TCP_BASE + index, + "local-host-ip": "127.0.0.1", + "control-ip-address": "127.0.0.1", + "control-port-local": DECOY_CONTROL_LOCAL_BASE + index, + "control-port-remote": DECOY_CONTROL_REMOTE_BASE + index, + "qgc-host-ip": "", + # Best-effort only: pushed over the decoy control link, which PX4 + # never talks to. The entrypoint sets the real PX4 params. + "parameters": {"NAV_RCL_ACT": 0, "NAV_DLL_ACT": 0, "COM_OBL_RC_ACT": 5, + "LPE_LAT": params["home_lat"], "LPE_LON": params["home_lon"]}, + "actuator-order": [{"id": f"Prop_{n}_actuator"} for n in _PX4_ACTUATOR_ORDER], + }, + } + + +def stereo_geometry(params): + """Body-FRD camera origins. AirStack URDF puts camera_left at FLU +y.""" + return { + "front_left": (params["cam_x"], -params["cam_y"], -params["cam_z"]), + "front_right": (params["cam_x"], params["cam_y"], -params["cam_z"]), + } + + +def _lumen_keys(params): + if params["lumen"] is None: + return {} + return {"lumen-gi-enabled": params["lumen"], "lumen-reflections-enabled": params["lumen"]} + + +def _camera(sensor_id, xyz_frd, params): + capture = {"width": params["cam_width"], "height": params["cam_height"], + "fov-degrees": params["cam_fov"], "capture-enabled": True, + "streaming-enabled": False, "pixels-as-float": False, "compress": False} + return { + "id": sensor_id, "type": "camera", "enabled": True, "parent-link": "Frame", + "capture-interval": round(1.0 / params["cam_rate"], 6), + "capture-settings": [ + dict(capture, **{"image-type": 0, "target-gamma": 2.5}, **_lumen_keys(params)), # RGB + dict(capture, **{"image-type": 1}), # depth planar + ], + # Degrees, positive = nose up — same sign as the legacy settings.json + # "Pitch" knob (Project AirSim's down-camera sample uses -90). + "origin": _origin(*xyz_frd, 0.0, params["cam_pitch"], 0.0), + } + + +def _lidar(params): + return { + "id": "ouster", "type": "lidar", "lidar-type": params["lidar_type"], "enabled": True, + "parent-link": "Frame", + "number-of-channels": params["lidar_channels"], + "range": params["lidar_range"], + "points-per-second": params["lidar_points_per_second"], + "horizontal-rotation-frequency": params["lidar_rate"], + "report-frequency": params["lidar_rate"], + "horizontal-fov-start-deg": 0.0, "horizontal-fov-end-deg": 360.0, + "vertical-fov-upper-deg": params["lidar_vfov_upper"], + "vertical-fov-lower-deg": params["lidar_vfov_lower"], + "disable-self-hits": True, "draw-debug-points": False, + # URDF: base_link -> ouster at +z (FLU) with no rotation → FRD -z. + "origin": _origin(0.0, 0.0, -params["lidar_z"]), + "report-point-cloud": True, + "report-azimuth-elevation-range": False, + "report-no-return-points": False, + } + + +def _chase_camera(params): + """Third-person camera behind and above the drone (demo/recording only). + Gimbal-locked in roll and pitch so the horizon stays level; follows yaw.""" + capture = {"image-type": 0, "width": params["chase_width"], + "height": params["chase_height"], "fov-degrees": params["chase_fov"], + "capture-enabled": True, "streaming-enabled": False, + "pixels-as-float": False, "compress": False, "target-gamma": 2.5, + "motion-blur-amount": 0.0} + capture.update(_lumen_keys(params)) + return { + "id": "chase", "type": "camera", "enabled": True, "parent-link": "Frame", + "capture-interval": round(1.0 / params["chase_rate"], 6), + "capture-settings": [capture], + "gimbal": {"lock-roll": True, "lock-pitch": True, "lock-yaw": False}, + "origin": _origin(-6.0, 0.0, -2.0, 0.0, -15.0, 0.0), + } + + +def _nav_sensors(): + return [ + {"id": "IMU1", "type": "imu", "enabled": True, "parent-link": "Frame", + "accelerometer": {"velocity-random-walk": 2.353e-3, "tau": 800, + "bias-stability": 3.53e-4, "turn-on-bias": "0 0 0"}, + "gyroscope": {"angle-random-walk": 8.72644e-5, "tau": 500, + "bias-stability": 2.23014e-5, "turn-on-bias": "0 0 0"}}, + {"id": "GPS", "type": "gps", "enabled": True, "parent-link": "Frame"}, + {"id": "Barometer", "type": "barometer", "enabled": True, "parent-link": "Frame"}, + {"id": "Magnetometer", "type": "magnetometer", "enabled": True, "parent-link": "Frame"}, + ] + + +def build_robot_config(robot, params): + physics = validate_physics(robot["physics"], f"robot {robot['name']}") + cams = stereo_geometry(params) + sensors = [_camera(cid, xyz, params) for cid, xyz in cams.items()] + if params["lidar_enabled"]: + sensors.append(_lidar(params)) + if params["chase_cam"]: + sensors.append(_chase_camera(params)) + sensors += _nav_sensors() + cfg = {} + if physics == "jsbsim": + cfg.update({ + "physics-type": "jsbsim-physics", + "jsbsim-model": params["jsbsim_model"], + # Resolved inside the packaged env's plugin dir + # (Plugins/ProjectAirSim/SimLibs/jsbsim/models — verified in + # Blocks-Linux-1.1.0). + "jsbsim-root-path": "/SimLibs/jsbsim/models/", + "jsbsim-aircraft-path": "aircraft", + "jsbsim-engine-path": "engine", + "jsbsim-systems-path": "systems", + "jsbsim-dt": params["step_ns"] / 1e9, + }) + else: + cfg["physics-type"] = "fast-physics" + cfg.update({ + "links": _links(), + "joints": _joints(), + "controller": _controller(robot["index"], params), + "actuators": _actuators(physics), + "sensors": sensors, + }) + return cfg + + +def spawn_ned(robot, params): + """World-frame NED spawn: env spawn origin + the robot's ENU offset.""" + dx, dy, dz = enu_to_ned(*robot["spawn_enu"]) + ox, oy, oz = params["spawn_origin_ned"] + return [ox + dx, oy + dy, oz + dz] + + +def build_scene(robots, params): + actors = [] + for r in robots: + x, y, z = spawn_ned(r, params) + actors.append({ + "type": "robot", + "name": r["name"], + "origin": _origin(x, y, z), + "start-landed": params["start_landed"], + "robot-config": build_robot_config(r, params), + }) + return { + "id": SCENE_ID, + "actors": actors, + "clock": {"type": "steppable", "step-ns": params["step_ns"], + "real-time-update-rate": params["step_ns"], "pause-on-start": False}, + "home-geo-point": {"latitude": params["home_lat"], "longitude": params["home_lon"], + "altitude": params["home_alt"]}, + "segmentation": {"initialize-ids": True, "ignore-existing": False, "use-owner-name": True}, + "scene-type": "UnrealNative", + } + + +def intrinsics(params): + """Pinhole intrinsics matching Project AirSim's camera model.""" + w, h = params["cam_width"], params["cam_height"] + fx = w / (2.0 * math.tan(math.radians(params["cam_fov"]) / 2.0)) + return {"width": w, "height": h, "fx": fx, "fy": fx, "cx": w / 2.0, "cy": h / 2.0} + + +def robot_streams(name, params): + """The bridge's topic map for one robot: Project AirSim topic → ROS topic. + + This is the ONLY place AirStack's sim-side topic contract is spelled out + for Project AirSim (the same names ms_airsim_ros_bridge and Isaac + publish), so the C++ bridge carries no topic strings of its own. + """ + sensors = f"/Sim/{SCENE_ID}/robots/{name}/sensors" + streams = [] + for side, sensor_id in (("left", "front_left"), ("right", "front_right")): + ros = f"/{name}/sensors/front_stereo/{side}" + streams.append({ + "kind": "image", "pas_topic": f"{sensors}/{sensor_id}/scene_camera", + "ros_topic": f"{ros}/image_rect", "info_topic": f"{ros}/camera_info", + "frame_id": f"camera_{side}", "right": side == "right", + }) + streams.append({ + "kind": "depth", "pas_topic": f"{sensors}/{sensor_id}/depth_planar_camera", + "ros_topic": f"{ros}/depth_ground_truth", "frame_id": f"camera_{side}", + }) + if params["lidar_enabled"]: + streams.append({ + "kind": "lidar", "pas_topic": f"{sensors}/ouster/lidar", + "ros_topic": f"/{name}/sensors/ouster/point_cloud_raw", "frame_id": "ouster", + }) + if params["chase_cam"]: + streams.append({ + "kind": "image", "pas_topic": f"{sensors}/chase/scene_camera", + "ros_topic": f"/{name}/sensors/chase/image", + "info_topic": f"/{name}/sensors/chase/camera_info", + "frame_id": "chase_camera", "right": False, + # Own intrinsics (the stereo pair's are the default). + "width": params["chase_width"], "height": params["chase_height"], + "fov": params["chase_fov"], + }) + return streams + + +def build_meta(robots, params): + cams = stereo_geometry(params) + baseline = abs(cams["front_right"][1] - cams["front_left"][1]) + return { + "scene_id": SCENE_ID, + "env": params["env"], + "spawn_origin_ned": params["spawn_origin_ned"], + "spawn_origin_source": params["spawn_origin_source"], + "clock_topic": f"/Sim/{SCENE_ID}/clock", + "camera": dict(intrinsics(params), baseline=baseline, rate=params["cam_rate"]), + "lidar": {"enabled": params["lidar_enabled"], "rate": params["lidar_rate"]}, + "robots": [{ + "name": r["name"], + "index": r["index"], + "domain_id": r["index"], + "physics": r["physics"], + "physics_source": r["physics_source"], + # Ground truth is published relative to this point (the robot's + # own start), matching MAVROS's local origin and legacy AirSim. + "spawn_ned": spawn_ned(r, params), + "hil_tcp_port": HIL_TCP_BASE + r["index"], + "decoy_control_port": DECOY_CONTROL_LOCAL_BASE + r["index"], + "mavros_offboard_ports": [14540 + r["index"], 14580 + r["index"]], + "kinematics_method": f"/Sim/{SCENE_ID}/robots/{r['name']}/GetGroundTruthKinematics", + "odom_topic": f"/{r['name']}/odom_ground_truth", + "odom_frame_id": f"{r['name']}/map", + "odom_child_frame_id": f"{r['name']}/base_link", + "streams": robot_streams(r["name"], params), + } for r in robots], + } + + +def generate(env, out_dir, airstack_root=None): + params = params_from_env(env) + fleet_file = env.get("FLEET_CONFIG_FILE", "").strip() + if fleet_file: + if not airstack_root: + raise ConfigError("FLEET_CONFIG_FILE is set but no AirStack checkout is mounted") + robots = robots_from_fleet(params, fleet_file, airstack_root) + else: + robots = robots_from_count(params) + scene = build_scene(robots, params) + meta = build_meta(robots, params) + out = Path(out_dir) + out.mkdir(parents=True, exist_ok=True) + (out / "scene_airstack.jsonc").write_text(json.dumps(scene, indent=2) + "\n") + (out / "airstack_meta.json").write_text(json.dumps(meta, indent=2) + "\n") + return scene, meta + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + ap.add_argument("--out", default=os.environ.get( + "PROJECT_AIRSIM_GENERATED_DIR", "/root/project-airsim/generated")) + ap.add_argument("--airstack-root", default=os.environ.get("AIRSTACK_ROOT", "/root/AirStack")) + args = ap.parse_args(argv) + try: + _, meta = generate(os.environ, args.out, args.airstack_root) + except ConfigError as exc: + print(f"generate_scene: ERROR: {exc}", file=sys.stderr) + return 2 + if meta["spawn_origin_source"].startswith("unverified"): + print(f"generate_scene: WARNING: no surveyed spawn origin for env " + f"'{meta['env']}' — spawning at the Unreal world origin, which may be " + f"inside geometry. Set PROJECT_AIRSIM_SPAWN_ORIGIN=x,y,z (NED).", file=sys.stderr) + print(f"generate_scene: env={meta['env']} spawn origin NED {meta['spawn_origin_ned']} " + f"({meta['spawn_origin_source']})") + for r in meta["robots"]: + print(f"generate_scene: {r['name']}: physics={r['physics']} ({r['physics_source']}), " + f"HIL tcp {r['hil_tcp_port']}, decoy control udp {r['decoy_control_port']}, " + f"MAVROS udp {r['mavros_offboard_ports'][0]}<->{r['mavros_offboard_ports'][1]}") + print(f"generate_scene: wrote {args.out}/scene_airstack.jsonc and airstack_meta.json") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/simulation/project-airsim/docker/Dockerfile b/simulation/project-airsim/docker/Dockerfile new file mode 100644 index 000000000..0257716d9 --- /dev/null +++ b/simulation/project-airsim/docker/Dockerfile @@ -0,0 +1,71 @@ +FROM osrf/ros:jazzy-desktop-full + +WORKDIR /root + +# ── Layers shared verbatim with simulation/ms-airsim/docker/Dockerfile ────── +# Keep these first and byte-identical so both sim images reuse the same +# (slow) PX4 SITL build layers from the build cache. +RUN apt-get update && apt-get install -y --no-install-recommends \ + python3-pip tmux vim wget curl unzip \ + ros-jazzy-mavros ros-jazzy-tf2-ros ros-jazzy-tf2-geometry-msgs \ + libvulkan1 \ + && rm -rf /var/lib/apt/lists/* + +# PX4 SITL +ARG PX4_VERSION="v1.16.1" +RUN git clone --branch ${PX4_VERSION} --recursive https://github.com/PX4/PX4-Autopilot.git +# numpy<2: PX4's requirements pull the newest pandas, and pandas >= 3 needs +# numpy >= 2, which pip cannot install over the Debian numpy 1.26 that the +# ROS Jazzy Python packages are built against ("Cannot uninstall numpy"). +RUN echo "numpy<2" > /tmp/pip-constraints.txt \ + && cd PX4-Autopilot && PIP_CONSTRAINT=/tmp/pip-constraints.txt \ + Tools/setup/ubuntu.sh --no-nuttx --no-sim-tools +RUN cd PX4-Autopilot && make px4_sitl_default +# ── end shared layers ──────────────────────────────────────────────────────── + +RUN apt-get update && apt-get install -y --no-install-recommends \ + cmake ninja-build g++ libeigen3-dev \ + python3-jinja2 python3-yaml \ + vulkan-tools netcat-openbsd iproute2 sudo \ + && rm -rf /var/lib/apt/lists/* + +# Project AirSim C++ client library, compiled from a PINNED shallow+sparse +# clone (no Project AirSim source is vendored in the AirStack repo, and none +# survives in this image: the source and build trees are deleted in the same +# layer). REF is the release tag; SHA must equal the tag's commit, so a +# moved/re-pointed tag fails the build instead of silently changing the +# client. Bump both together with PROJECT_AIRSIM_RELEASE (the env zips the +# entrypoint downloads) — the client and the packaged sim must match. +ARG PROJECT_AIRSIM_REF="v1.1.0" +ARG PROJECT_AIRSIM_SHA="be18449c8305641a6bf0d6061f8fd7f405371354" +RUN git clone --depth 1 --filter=blob:none --sparse --branch "${PROJECT_AIRSIM_REF}" \ + https://github.com/iamaisim/ProjectAirSim.git /tmp/pas \ + && cd /tmp/pas \ + && test "$(git rev-parse HEAD)" = "${PROJECT_AIRSIM_SHA}" \ + && git sparse-checkout set --no-cone \ + /client/cpp/ /core_sim/include/ /core_sim/src/ \ + /client/python/example_user_scripts/sim_config/ /docs/license.md \ + && cmake -S client/cpp -B /tmp/pas-build -G Ninja \ + -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF \ + -DCMAKE_POSITION_INDEPENDENT_CODE=ON \ + -DCMAKE_INSTALL_PREFIX=/opt/projectairsim \ + && cmake --build /tmp/pas-build --parallel \ + && cmake --install /tmp/pas-build \ + && echo "${PROJECT_AIRSIM_REF} ${PROJECT_AIRSIM_SHA}" > /opt/projectairsim/SOURCE_PIN \ + && rm -rf /tmp/pas /tmp/pas-build +ENV PROJECT_AIRSIM_CLIENT_ROOT=/opt/projectairsim + +# Non-root user for the Unreal binary (UE refuses to run as root). +RUN useradd -m -s /bin/bash -G sudo pas && \ + echo 'pas ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers && \ + echo "source /opt/ros/jazzy/setup.bash" >> /home/pas/.bashrc + +RUN echo "source /opt/ros/jazzy/setup.bash" >> /root/.bashrc + +# tmux plugin manager (tpm) +RUN git clone --depth 1 https://github.com/tmux-plugins/tpm /root/.tmux/plugins/tpm + +COPY entrypoint.sh /root/entrypoint.sh +RUN chmod +x /root/entrypoint.sh + +WORKDIR /root diff --git a/simulation/project-airsim/docker/docker-compose.yaml b/simulation/project-airsim/docker/docker-compose.yaml new file mode 100644 index 000000000..85a1b05c0 --- /dev/null +++ b/simulation/project-airsim/docker/docker-compose.yaml @@ -0,0 +1,107 @@ + +services: + project-airsim: + profiles: + - project-airsim + image: &project_airsim_image ${PROJECT_DOCKER_REGISTRY}/${PROJECT_NAME}:v${VERSION}_project-airsim + build: + context: ./ + dockerfile: Dockerfile + tags: + - *project_airsim_image + - &project_airsim_cache ${PROJECT_DOCKER_REGISTRY}/${PROJECT_NAME}:${CACHE_TAG:-cache}_project-airsim + cache_from: + - *project_airsim_image + - *project_airsim_cache + container_name: project-airsim + entrypoint: "" + command: /root/entrypoint.sh + stdin_open: true + tty: true + ipc: host + privileged: true + networks: + airstack_network: + # INVARIANT: every sim service (isaac-sim, ms-airsim, project-airsim, + # simple-sim) binds this same fixed address — robot containers reach + # the sim (PX4 SITL for MAVROS) at SIM_IP (default 172.31.0.200), so + # only one sim can run at a time. + ipv4_address: 172.31.0.200 + environment: + - DISPLAY + - QT_X11_NO_MITSHM=1 + - NVIDIA_DRIVER_CAPABILITIES=all + - XDG_RUNTIME_DIR=/tmp + - NUM_ROBOTS=${NUM_ROBOTS:-1} + - AUTOLAUNCH=${AUTOLAUNCH:-true} + # Fleet input (airstack up --fleet): generate_scene.py resolves robots, + # spawns and per-robot physics from the mounted checkout at /root/AirStack. + - FLEET_CONFIG_FILE=${FLEET_CONFIG_FILE:-} + # Environment selection (`airstack up --scene ` → + # simulation/scenes.yaml): a fetch_env.sh key; auto-fetched into the + # mounted envs dir on first launch. Empty = blocks. Ignored when + # PROJECT_AIRSIM_BINARY_PATH is set. + - PROJECT_AIRSIM_ENV=${PROJECT_AIRSIM_ENV:-} + - PROJECT_AIRSIM_BINARY_PATH=${PROJECT_AIRSIM_BINARY_PATH:-} + - PROJECT_AIRSIM_RELEASE=${PROJECT_AIRSIM_RELEASE:-v1.1.0} + - PROJECT_AIRSIM_HEADLESS=${PROJECT_AIRSIM_HEADLESS:-false} + # vulkan | null (null = -nullrhi: no rendering/cameras/LiDAR, GPU-free) + - PROJECT_AIRSIM_RENDER=${PROJECT_AIRSIM_RENDER:-vulkan} + # fast-physics (default) | jsbsim — overrides fleet/vehicle choices + - PROJECT_AIRSIM_PHYSICS=${PROJECT_AIRSIM_PHYSICS:-} + - PROJECT_AIRSIM_PX4_START_DELAY=${PROJECT_AIRSIM_PX4_START_DELAY:-3} + # Sensor knobs (config/generate_scene.py defaults when unset) + - PROJECT_AIRSIM_CAM_WIDTH=${PROJECT_AIRSIM_CAM_WIDTH:-} + - PROJECT_AIRSIM_CAM_HEIGHT=${PROJECT_AIRSIM_CAM_HEIGHT:-} + - PROJECT_AIRSIM_CAM_FOV=${PROJECT_AIRSIM_CAM_FOV:-} + - PROJECT_AIRSIM_CAM_RATE=${PROJECT_AIRSIM_CAM_RATE:-} + - PROJECT_AIRSIM_CAM_PITCH=${PROJECT_AIRSIM_CAM_PITCH:-} + - PROJECT_AIRSIM_LIDAR=${PROJECT_AIRSIM_LIDAR:-} + - PROJECT_AIRSIM_LIDAR_CHANNELS=${PROJECT_AIRSIM_LIDAR_CHANNELS:-} + - PROJECT_AIRSIM_LIDAR_COLUMNS=${PROJECT_AIRSIM_LIDAR_COLUMNS:-} + - PROJECT_AIRSIM_LIDAR_RATE=${PROJECT_AIRSIM_LIDAR_RATE:-} + - PROJECT_AIRSIM_LIDAR_RANGE=${PROJECT_AIRSIM_LIDAR_RANGE:-} + - PROJECT_AIRSIM_SPAWN_SPACING=${PROJECT_AIRSIM_SPAWN_SPACING:-} + - PROJECT_AIRSIM_SPAWN_ORIGIN=${PROJECT_AIRSIM_SPAWN_ORIGIN:-} + # true | false | unset (= the environment's project default) + - PROJECT_AIRSIM_LUMEN=${PROJECT_AIRSIM_LUMEN:-} + # Third-person chase camera → /robot_N/sensors/chase/image (demos) + - PROJECT_AIRSIM_CHASE_CAM=${PROJECT_AIRSIM_CHASE_CAM:-} + - PROJECT_AIRSIM_START_LANDED=${PROJECT_AIRSIM_START_LANDED:-} + # Remaining generate_scene.py / entrypoint knobs (empty = their defaults) + - PROJECT_AIRSIM_CAM_X=${PROJECT_AIRSIM_CAM_X:-} + - PROJECT_AIRSIM_CAM_Y=${PROJECT_AIRSIM_CAM_Y:-} + - PROJECT_AIRSIM_CAM_Z=${PROJECT_AIRSIM_CAM_Z:-} + - PROJECT_AIRSIM_CHASE_WIDTH=${PROJECT_AIRSIM_CHASE_WIDTH:-} + - PROJECT_AIRSIM_CHASE_HEIGHT=${PROJECT_AIRSIM_CHASE_HEIGHT:-} + - PROJECT_AIRSIM_CHASE_FOV=${PROJECT_AIRSIM_CHASE_FOV:-} + - PROJECT_AIRSIM_CHASE_RATE=${PROJECT_AIRSIM_CHASE_RATE:-} + - PROJECT_AIRSIM_HOME_LAT=${PROJECT_AIRSIM_HOME_LAT:-} + - PROJECT_AIRSIM_HOME_LON=${PROJECT_AIRSIM_HOME_LON:-} + - PROJECT_AIRSIM_HOME_ALT=${PROJECT_AIRSIM_HOME_ALT:-} + - PROJECT_AIRSIM_JSBSIM_MODEL=${PROJECT_AIRSIM_JSBSIM_MODEL:-} + - PROJECT_AIRSIM_LIDAR_TYPE=${PROJECT_AIRSIM_LIDAR_TYPE:-} + - PROJECT_AIRSIM_LIDAR_POINTS_PER_SECOND=${PROJECT_AIRSIM_LIDAR_POINTS_PER_SECOND:-} + - PROJECT_AIRSIM_LIDAR_VFOV_UPPER=${PROJECT_AIRSIM_LIDAR_VFOV_UPPER:-} + - PROJECT_AIRSIM_LIDAR_VFOV_LOWER=${PROJECT_AIRSIM_LIDAR_VFOV_LOWER:-} + - PROJECT_AIRSIM_LIDAR_Z=${PROJECT_AIRSIM_LIDAR_Z:-} + - PROJECT_AIRSIM_LIDAR_FRAME=${PROJECT_AIRSIM_LIDAR_FRAME:-} + - PROJECT_AIRSIM_STEP_NS=${PROJECT_AIRSIM_STEP_NS:-} + - PROJECT_AIRSIM_STARTUP_TIMEOUT=${PROJECT_AIRSIM_STARTUP_TIMEOUT:-} + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: 1 + capabilities: [gpu] + volumes: + - /tmp/.X11-unix:/tmp/.X11-unix + - ../config:/root/project-airsim/config:ro + - ../ros_ws:/root/ros_ws:rw + - ${PROJECT_AIRSIM_ENV_DIR:-../assets/envs}:/project-airsim-env:rw + # AirStack checkout (read-only): fleet + vehicle files and the fleet + # resolver for generate_scene.py. + - ../../..:/root/AirStack:ro + - /usr/share/vulkan/icd.d/nvidia_icd.json:/usr/share/vulkan/icd.d/nvidia_icd.json:ro + - ../../../common/.tmux.conf:/root/.tmux.conf:rw diff --git a/simulation/project-airsim/docker/entrypoint.sh b/simulation/project-airsim/docker/entrypoint.sh new file mode 100755 index 000000000..4ea92976b --- /dev/null +++ b/simulation/project-airsim/docker/entrypoint.sh @@ -0,0 +1,148 @@ +#!/bin/bash +# Project AirSim container entrypoint. +# +# Order matters (and is why this is one script, not independent services): +# 1. generate the scene (+ airstack_meta.json) from env / fleet +# 2. build the ROS workspace (pas_ros_bridge: C++ bridge + scene loader) +# 3. launch the packaged UE5 environment (tmux window `pas`) +# 4. wait for its services port, then load the scene (window `loader`) +# 5. let sensors settle, then start one PX4 SITL per robot (robot__px4) — +# PX4 must start AFTER the scene exists, and restart whenever it reloads +# 6. start the ONE ROS 2 bridge process for all robots (window `bridge`) — +# Project AirSim's topic socket admits a single client, so per-robot +# bridge processes are impossible. +set -euo pipefail + +NUM_ROBOTS="${NUM_ROBOTS:-1}" +AUTOLAUNCH="${AUTOLAUNCH:-true}" +PROJECT_AIRSIM_HEADLESS="${PROJECT_AIRSIM_HEADLESS:-false}" +# vulkan (default) | null — `null` runs UE with -nullrhi: no rendering at all +# (no cameras, no GPU LiDAR) but physics, PX4 lockstep and the clock work, so +# flight-only checks can run without a GPU. +PROJECT_AIRSIM_RENDER="${PROJECT_AIRSIM_RENDER:-vulkan}" +PROJECT_AIRSIM_PX4_START_DELAY="${PROJECT_AIRSIM_PX4_START_DELAY:-3}" +PROJECT_AIRSIM_TOPICS_PORT="${PROJECT_AIRSIM_TOPICS_PORT:-8989}" +PROJECT_AIRSIM_SERVICES_PORT="${PROJECT_AIRSIM_SERVICES_PORT:-8990}" +PROJECT_AIRSIM_STARTUP_TIMEOUT="${PROJECT_AIRSIM_STARTUP_TIMEOUT:-1800}" +ENV_MOUNT=/project-airsim-env +CONFIG_DIR=/root/project-airsim/config +GEN_DIR=/root/project-airsim/generated +PX4_ROOT=/root/PX4-Autopilot +SESSION=project-airsim + +log() { echo "[project-airsim] $*"; } + +# 1. Scene generation (fails fast on bad physics names / numbers / fleets). +# Clear load markers first: a restarted container keeps its filesystem. +rm -f "$GEN_DIR/.scene_loaded" "$GEN_DIR/.scene_failed" +python3 "$CONFIG_DIR/generate_scene.py" --out "$GEN_DIR" --airstack-root /root/AirStack +NUM_ROBOTS="$(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["robots"]))' "$GEN_DIR/airstack_meta.json")" + +# The tmux session is created right before Unreal launches (or idle, without +# autolaunch): an empty `pas` pane during the bridge build reads as a crashed +# pane to the liveliness check. +new_session() { + tmux new -d -s "$SESSION" -n pas + # Room for the centered window list (pas, loader, robot__px4, bridge). + tmux set-option -t "$SESSION" status-right '' +} + +# Environment resolution. An explicit PROJECT_AIRSIM_BINARY_PATH wins (and must +# exist). Otherwise PROJECT_AIRSIM_ENV (a fetch_env.sh key, set by `airstack +# up --scene `; default blocks) picks the packaged environment and +# the `pas` window auto-fetches it so the download is visible. +FETCH_PREFIX="" +if [ -z "${PROJECT_AIRSIM_BINARY_PATH:-}" ]; then + PROJECT_AIRSIM_ENV="${PROJECT_AIRSIM_ENV:-blocks}" + ENV_NAME="$(bash "$ENV_MOUNT/fetch_env.sh" --name "$PROJECT_AIRSIM_ENV")" || { + echo "ERROR: unknown PROJECT_AIRSIM_ENV='$PROJECT_AIRSIM_ENV' ($(bash "$ENV_MOUNT/fetch_env.sh" --list))." >&2 + exit 1 + } + # The launcher name is only known after the fetch (it differs per + # environment), so the `pas` window resolves it after fetching. + PROJECT_AIRSIM_BINARY_PATH='$(ENVS_DIR='"$ENV_MOUNT"' bash '"$ENV_MOUNT"'/fetch_env.sh --launcher '"$PROJECT_AIRSIM_ENV"')' + FETCH_PREFIX="ENVS_DIR=$ENV_MOUNT bash $ENV_MOUNT/fetch_env.sh $PROJECT_AIRSIM_ENV && " +elif [ ! -f "$PROJECT_AIRSIM_BINARY_PATH" ]; then + echo "ERROR: PROJECT_AIRSIM_BINARY_PATH=$PROJECT_AIRSIM_BINARY_PATH does not exist." >&2 + echo "Extract the environment into the mounted volume, or unset PROJECT_AIRSIM_BINARY_PATH to auto-fetch one (PROJECT_AIRSIM_ENV, default blocks)." >&2 + exit 1 +fi + +if [ "$AUTOLAUNCH" != "true" ]; then + log "AUTOLAUNCH=$AUTOLAUNCH — environment resolved to $PROJECT_AIRSIM_BINARY_PATH; nothing started." + new_session + exec sleep infinity +fi + +# 2. Build the bridge workspace (links the image's /opt/projectairsim client). +log "building ros_ws (pas_ros_bridge)..." +# (ROS setup scripts read unset variables: relax nounset while sourcing.) +(set +u; cd /root/ros_ws && source /opt/ros/jazzy/setup.bash && \ + colcon build --symlink-install --cmake-args -DCMAKE_BUILD_TYPE=Release) + +# 3. Unreal. +UE_FLAGS="-nosound -unattended -nopause -NoSplash -log" +UE_FLAGS+=" -topicsport=$PROJECT_AIRSIM_TOPICS_PORT -servicesport=$PROJECT_AIRSIM_SERVICES_PORT" +case "$PROJECT_AIRSIM_RENDER" in + vulkan) UE_FLAGS+=" -vulkan" + if [ "$PROJECT_AIRSIM_HEADLESS" = "true" ]; then UE_FLAGS+=" -RenderOffScreen"; fi ;; + null) UE_FLAGS+=" -nullrhi" ;; + *) echo "ERROR: PROJECT_AIRSIM_RENDER must be vulkan or null (got '$PROJECT_AIRSIM_RENDER')" >&2; exit 1 ;; +esac +# Unreal runs as `pas` with HOME=/home/pas so it has a writable user dir +# (~/.config/Epic//Saved) for its saved config and crash reports. +log "launching $PROJECT_AIRSIM_BINARY_PATH $UE_FLAGS" +new_session +tmux send-keys -t "$SESSION:pas" \ + "${FETCH_PREFIX}sudo -E -u pas HOME=/home/pas $PROJECT_AIRSIM_BINARY_PATH $UE_FLAGS" ENTER + +# 4. Wait for the services port (includes any first-launch env download). +log "waiting for Project AirSim services port $PROJECT_AIRSIM_SERVICES_PORT (timeout ${PROJECT_AIRSIM_STARTUP_TIMEOUT}s)..." +deadline=$((SECONDS + PROJECT_AIRSIM_STARTUP_TIMEOUT)) +until nc -z 127.0.0.1 "$PROJECT_AIRSIM_SERVICES_PORT" 2>/dev/null; do + if [ "$SECONDS" -ge "$deadline" ]; then + echo "ERROR: Project AirSim did not open port $PROJECT_AIRSIM_SERVICES_PORT within ${PROJECT_AIRSIM_STARTUP_TIMEOUT}s — see the 'pas' tmux window." >&2 + exec sleep infinity + fi + sleep 1 +done +log "services port open after ${SECONDS}s; loading scene" + +tmux new-window -t "$SESSION" -n loader +tmux send-keys -t "$SESSION:loader" \ + "source /root/ros_ws/install/setup.bash && ros2 run pas_ros_bridge pas_scene_loader --scene $GEN_DIR/scene_airstack.jsonc --port-topics $PROJECT_AIRSIM_TOPICS_PORT --port-services $PROJECT_AIRSIM_SERVICES_PORT && touch $GEN_DIR/.scene_loaded || touch $GEN_DIR/.scene_failed" ENTER +until [ -e "$GEN_DIR/.scene_loaded" ] || [ -e "$GEN_DIR/.scene_failed" ]; do sleep 1; done +if [ -e "$GEN_DIR/.scene_failed" ]; then + echo "ERROR: scene load failed — see the 'loader' tmux window." >&2 + exec sleep infinity +fi +# The loader is one-shot: tag its now-idle pane 'shell' so health checks +# (tests/system/test_liveliness.py) don't read it as a crashed process. +tmux select-pane -t "$SESSION:loader" -T shell + +# 5. PX4 SITL per robot. Too short a settle → PX4 snapshots a bad local +# origin (altitude offset) — same lesson as the legacy AirSim container. +log "waiting ${PROJECT_AIRSIM_PX4_START_DELAY}s for sensors to settle before PX4" +sleep "$PROJECT_AIRSIM_PX4_START_DELAY" +for i in $(seq 1 "$NUM_ROBOTS"); do + inst="/root/px4_instance_$i" + # Fresh instance dir every launch: PX4 SITL persists parameters there, + # and a restarted container must not inherit hand-set params. + rm -rf "$inst" && mkdir -p "$inst" + window="robot_${i}_px4" + tmux new-window -t "$SESSION" -n "$window" + # PX4_PARAM_* env overrides (honoured by PX4 >= 1.14 rcS): Project + # AirSim's own parameter push travels its (decoy) control link and never + # reaches PX4, so set them PX4-side. CBRK_SUPPLY_CHK: PAS's HIL stream + # carries no power-supply status ("system power unavailable"). + tmux send-keys -t "$SESSION:$window" \ + "cd $inst && PX4_SIM_MODEL=none_iris PX4_PARAM_NAV_RCL_ACT=0 PX4_PARAM_NAV_DLL_ACT=0 PX4_PARAM_COM_OBL_RC_ACT=5 PX4_PARAM_MAV_1_BROADCAST=1 PX4_PARAM_CBRK_SUPPLY_CHK=894281 $PX4_ROOT/build/px4_sitl_default/bin/px4 $PX4_ROOT/ROMFS/px4fmu_common -s $PX4_ROOT/ROMFS/px4fmu_common/init.d-posix/rcS -i $i" ENTER +done + +# 6. The single bridge process (all robots, one DDS domain per robot). +tmux new-window -t "$SESSION" -n bridge +tmux send-keys -t "$SESSION:bridge" \ + "source /root/ros_ws/install/setup.bash && ros2 run pas_ros_bridge pas_ros_bridge --meta $GEN_DIR/airstack_meta.json --port-topics $PROJECT_AIRSIM_TOPICS_PORT --port-services $PROJECT_AIRSIM_SERVICES_PORT --lidar-frame ${PROJECT_AIRSIM_LIDAR_FRAME:-sensor}" ENTER + +log "up: $NUM_ROBOTS robot(s); attach with: docker exec -it project-airsim tmux attach -t $SESSION" +exec sleep infinity diff --git a/simulation/project-airsim/ros_ws/src/pas_ros_bridge/CMakeLists.txt b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/CMakeLists.txt new file mode 100644 index 000000000..ff7ecbb8a --- /dev/null +++ b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/CMakeLists.txt @@ -0,0 +1,63 @@ +cmake_minimum_required(VERSION 3.16) +project(pas_ros_bridge LANGUAGES CXX) + +if(NOT CMAKE_CXX_STANDARD) + set(CMAKE_CXX_STANDARD 17) +endif() +set(CMAKE_CXX_STANDARD_REQUIRED ON) +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Release) +endif() +add_compile_options(-Wall -Wextra -Wpedantic) + +find_package(ament_cmake REQUIRED) +find_package(rclcpp REQUIRED) +find_package(sensor_msgs REQUIRED) +find_package(nav_msgs REQUIRED) +find_package(rosgraph_msgs REQUIRED) +find_package(diagnostic_msgs REQUIRED) + +# Project AirSim C++ client (static lib + headers, incl. its msgpack and +# nlohmann-json copies), installed by the project-airsim image. +set(_pas_root "$ENV{PROJECT_AIRSIM_CLIENT_ROOT}") +if(NOT _pas_root) + set(_pas_root "/opt/projectairsim") +endif() +find_package(ProjectAirSimCppClient REQUIRED CONFIG + HINTS "${_pas_root}/lib/cmake/ProjectAirSimCppClient") + +# Pure conversion/decoding code: no rclcpp node, no network — unit-tested. +add_library(pas_bridge_core STATIC + src/conversions.cpp + src/decode.cpp +) +target_include_directories(pas_bridge_core PUBLIC + $) +# Only the client's header-only deps (msgpack, nlohmann-json) are needed here; +# take its include dir + compile definitions without linking the client lib. +target_include_directories(pas_bridge_core SYSTEM PUBLIC "${ProjectAirSimCppClient_INCLUDE_DIR}") +target_compile_definitions(pas_bridge_core PUBLIC MSGPACK_NO_BOOST) +target_link_libraries(pas_bridge_core PUBLIC + ${sensor_msgs_TARGETS} ${nav_msgs_TARGETS}) + +add_executable(pas_ros_bridge src/bridge_main.cpp) +target_link_libraries(pas_ros_bridge + pas_bridge_core ProjectAirSim::Client + rclcpp::rclcpp ${sensor_msgs_TARGETS} ${nav_msgs_TARGETS} + ${rosgraph_msgs_TARGETS} ${diagnostic_msgs_TARGETS}) + +add_executable(pas_scene_loader src/scene_loader_main.cpp) +target_link_libraries(pas_scene_loader ProjectAirSim::Client) + +install(TARGETS pas_ros_bridge pas_scene_loader + RUNTIME DESTINATION lib/${PROJECT_NAME}) + +if(BUILD_TESTING) + find_package(ament_cmake_gtest REQUIRED) + ament_add_gtest(test_conversions test/test_conversions.cpp) + target_link_libraries(test_conversions pas_bridge_core) + ament_add_gtest(test_decode test/test_decode.cpp) + target_link_libraries(test_decode pas_bridge_core) +endif() + +ament_package() diff --git a/simulation/project-airsim/ros_ws/src/pas_ros_bridge/README.md b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/README.md new file mode 100644 index 000000000..6df840e0a --- /dev/null +++ b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/README.md @@ -0,0 +1,92 @@ +# pas_ros_bridge + +C++ ROS 2 bridge between [Project AirSim](https://github.com/iamaisim/ProjectAirSim) and AirStack, plus the scene loader. It runs inside the `project-airsim` simulator container. For the user-facing guide, see [Project AirSim](../../../../../docs/simulation/project-airsim/index.md). + +## Overview + +| Executable | Role | +|---|---| +| `pas_scene_loader` | Loads the generated scene into the running Project AirSim server, logs the server build, and exits (0 = loaded). | +| `pas_ros_bridge` | Long-running bridge for **every** robot in the scene: stereo RGB, depth, camera_info, LiDAR sweeps, ground-truth odometry and `/clock`, each on its robot's `ROS_DOMAIN_ID`. | + +They are separate so the bridge can restart without reloading the scene. A reload rewinds Project AirSim's steppable clock and forces a PX4 restart. + +## Architecture + +```mermaid +flowchart LR + PAS["Project AirSim
topics :8989 (one client)
services :8990"] + subgraph B["pas_ros_bridge (one process)"] + C["pasc::Client
(the single topic client)"] + D["decode.cpp
msgpack → ROS messages"] + K["kinematics poll
(service, 50 Hz/robot)"] + X1["rclcpp::Context
domain 1"] + XN["rclcpp::Context
domain N"] + end + PAS -- topic callbacks --> C --> D + PAS -- GetGroundTruthKinematics --> K + D --> X1 & XN + K --> X1 & XN +``` + +**Why one process.** Project AirSim's topic socket is an NNG PAIR0 socket that admits exactly one client, so per-robot bridge processes are impossible. The bridge creates one `rclcpp::Context` per robot, initialised with that robot's domain id, so robot *i* sees only its own sensors and its own copy of `/clock`. + +**Topic map.** The bridge holds no topic names. `simulation/project-airsim/config/generate_scene.py` writes `airstack_meta.json` with each robot's `streams`, and the bridge publishes exactly those. Each stream gives a Project AirSim topic, a ROS topic, a frame id and a kind (`image` / `depth` / `lidar`). `tests/meta/test_project_airsim_scene_contract.py` checks the map against the topics the system tests probe. + +**Hot path.** Payloads are unpacked with msgpack referencing the received buffer, so image bytes are copied once, straight into the ROS message, which is published as a `unique_ptr`. Depth is converted from little-endian binary16 to `32FC1` in one pass, with no-return mapped to NaN. LiDAR points are written straight into the `PointCloud2` buffer, converting FRD to FLU. Streams with no ROS subscriber are not decoded. + +**LiDAR sweeps.** The GPU LiDAR emits a full 360° ring every render frame and republishes unchanged rings. `SweepAccumulator` buckets rings into fixed `1/rate` time slots, drops exact repeats, and emits one merged sweep per slot. The output rate is exactly the configured LiDAR rate, at the cost of one ring of latency. + +**Frames.** Project AirSim works in NED (world) and FRD (body). Ground truth is converted to ENU / FLU with the same math as the legacy Microsoft AirSim bridge, pinned by `test/test_conversions.cpp`, and is reported relative to each robot's spawn point. + +## Interfaces + +Published on robot *i*'s domain (names come from `airstack_meta.json`): + +| Topic | Type | QoS | +|---|---|---| +| `/robot_i/sensors/front_stereo/{left,right}/image_rect` | `sensor_msgs/Image` (`bgr8`) | reliable, keep-last 2 | +| `/robot_i/sensors/front_stereo/{left,right}/camera_info` | `sensor_msgs/CameraInfo` | reliable, keep-last 2 | +| `/robot_i/sensors/front_stereo/{left,right}/depth_ground_truth` | `sensor_msgs/Image` (`32FC1`) | reliable, keep-last 2 | +| `/robot_i/sensors/ouster/point_cloud_raw` | `sensor_msgs/PointCloud2` | reliable, keep-last 2 | +| `/robot_i/sensors/chase/image` (optional) | `sensor_msgs/Image` | reliable, keep-last 2 | +| `/robot_i/odom_ground_truth` | `nav_msgs/Odometry` | reliable, keep-last 10 | +| `/robot_i/pas_bridge/diagnostics` | `diagnostic_msgs/DiagnosticArray` | keep-last 1 | +| `/clock` | `rosgraph_msgs/Clock` | reliable, keep-last 10 | + +Reliable publishers match both reliable and best-effort subscribers. + +## Configuration + +`pas_ros_bridge` takes plain command-line flags; the entrypoint passes them: + +| Flag | Default | Description | +|---|---|---| +| `--meta FILE` | (required) | `airstack_meta.json` from `generate_scene.py` | +| `--host` | `127.0.0.1` | Project AirSim server | +| `--port-topics` / `--port-services` | `8989` / `8990` | Server ports | +| `--clock-rate` | `100` | Maximum `/clock` rate (Hz); the sim steps every 3 ms | +| `--gt-rate` | `50` | Ground-truth poll rate per robot (Hz) | +| `--lidar-frame` | `sensor` | Frame of the incoming point cloud: `sensor` (the GPU LiDAR's) or `world` (transform with the message's sensor pose) | +| `--stats-period` | `10` | Seconds between rate logs and diagnostics | +| `--connect-timeout` | `120` | Seconds to wait for the server and its topics | + +`pas_scene_loader --scene FILE [--host] [--port-topics] [--port-services] [--retries]`. + +If the clock goes backwards (the scene was reloaded), the bridge exits with code 3 instead of publishing a rewound `/clock`. + +## Dependencies + +- `rclcpp`, `sensor_msgs`, `nav_msgs`, `rosgraph_msgs`, `diagnostic_msgs` +- The Project AirSim C++ client (`find_package(ProjectAirSimCppClient)`, imported target `ProjectAirSim::Client`). The `project-airsim` image compiles it from a pinned sparse clone into `/opt/projectairsim`, and its headers also provide msgpack and nlohmann-json. Set `PROJECT_AIRSIM_CLIENT_ROOT` to build against a different install. + +## Build and test + +Inside the `project-airsim` container: + +```bash +cd /root/ros_ws && colcon build --packages-select pas_ros_bridge +colcon test --packages-select pas_ros_bridge && colcon test-result --verbose +``` + +`test/test_conversions.cpp` covers frame conversion pinned to the legacy fixtures, fp16 depth, and camera_info including the stereo baseline. `test/test_decode.cpp` covers the msgpack decoders on synthetic payloads in the server's layouts, ground truth, and sweep accumulation. System-level checks run with `airstack test -m "liveliness or sensors" --sim projectairsim`. diff --git a/simulation/project-airsim/ros_ws/src/pas_ros_bridge/include/pas_ros_bridge/conversions.hpp b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/include/pas_ros_bridge/conversions.hpp new file mode 100644 index 000000000..ef92007bf --- /dev/null +++ b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/include/pas_ros_bridge/conversions.hpp @@ -0,0 +1,72 @@ +// Copyright (c) 2026 Carnegie Mellon University +// SPDX-License-Identifier: BSD-3-Clause-Clear +// +// Pure conversions between Project AirSim's conventions and ROS's. +// +// Project AirSim: world NED, body FRD, depth as IEEE-754 binary16 metres +// (little-endian, +inf = no return), pinhole cameras with fx = fy = +// w / (2 tan(fov/2)) and the principal point at the image centre. +// ROS / AirStack: world ENU, body FLU, depth 32FC1 metres with NaN = no +// return, REP-103/104 camera_info. +// +// The NED→ENU math is the same as the legacy ms_airsim_ros_bridge +// (_ned_vec_to_enu / _ned_quat_to_enu); test/test_conversions.cpp pins +// numerically identical outputs on shared fixtures. +#pragma once + +#include +#include +#include + +#include + +namespace pas_ros_bridge { + +struct Vec3 { + double x{0.0}, y{0.0}, z{0.0}; +}; + +struct Quat { + double w{1.0}, x{0.0}, y{0.0}, z{0.0}; +}; + +// World-frame vector (position / velocity) NED → ENU. +Vec3 NedToEnu(const Vec3& v); + +// Body-FRD-in-world-NED orientation → body-FLU-in-world-ENU. +// q_enu = q_NED_TO_ENU * q_ned * q_FLU_TO_FRD. +Quat NedFrdToEnuFlu(const Quat& q); + +// Body-frame vector FRD → FLU (also sensor-frame points). +Vec3 FrdToFlu(const Vec3& v); + +// Rotate v by unit quaternion q (q v q*). +Vec3 Rotate(const Quat& q, const Vec3& v); +Quat Conjugate(const Quat& q); + +// IEEE-754 binary16 → float (handles subnormals, inf, NaN). +float HalfToFloat(std::uint16_t h); + +// Convert `n_pixels` little-endian binary16 depth values (2 bytes each) to +// float32 metres. +inf / NaN (no return) become quiet NaN, the AirStack +// invalid-depth convention (matches the Isaac and legacy bridges). +void Depth16ToFloat32(const std::uint8_t* src, std::size_t n_pixels, float* dst); + +struct Intrinsics { + std::uint32_t width{0}; + std::uint32_t height{0}; + double fx{0.0}, fy{0.0}, cx{0.0}, cy{0.0}; +}; + +// Intrinsics from image size and horizontal FOV (degrees), Project AirSim's +// camera model (core_sim/src/sensors/camera.cpp). +Intrinsics IntrinsicsFromFov(std::uint32_t width, std::uint32_t height, double fov_deg); + +// camera_info for a rectified, undistorted pinhole camera. For the RIGHT +// camera of a stereo pair, P[0,3] = -fx * baseline (REP-104), so +// stereo_image_proc recovers depth; the left camera gets P[0,3] = 0. +// (Upstream Project AirSim publishes P = identity, unstamped, once.) +sensor_msgs::msg::CameraInfo MakeCameraInfo(const Intrinsics& k, double baseline_m, + bool is_right, const std::string& frame_id); + +} // namespace pas_ros_bridge diff --git a/simulation/project-airsim/ros_ws/src/pas_ros_bridge/include/pas_ros_bridge/decode.hpp b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/include/pas_ros_bridge/decode.hpp new file mode 100644 index 000000000..72e6d61bf --- /dev/null +++ b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/include/pas_ros_bridge/decode.hpp @@ -0,0 +1,98 @@ +// Copyright (c) 2026 Carnegie Mellon University +// SPDX-License-Identifier: BSD-3-Clause-Clear +// +// Decoders for Project AirSim topic payloads (msgpack maps, layouts from +// core_sim/src/message/*_message.cpp at the pinned client SHA) into ROS +// messages. No network, no node — unit-tested on synthetic payloads. +#pragma once + +#include +#include +#include + +#include +#include +#include +#include + +#include "json.hpp" // nlohmann-json, shipped with the Project AirSim client + +#include "pas_ros_bridge/conversions.hpp" + +namespace pas_ros_bridge { + +builtin_interfaces::msg::Time NanosToRosTime(std::int64_t nanos); + +// ImageMessage: {time_stamp, height, width, encoding, big_endian, step, +// data(bin), pos_*, rot_*, annotations}. Encodings: "BGR" (8UC3), "16FC1" +// (binary16 depth metres), "PNG" (compressed — rejected: the generator never +// enables compression, and decoding PNG would cost more than the transport +// it saves). +// +// Fills `out` (header stamp + data + encoding + step) and returns true, or +// returns false with `error` set. Depth becomes 32FC1 metres (NaN = no +// return). The payload's `step` field is not trusted (the server sends 1). +bool DecodeImage(const std::string& payload, const std::string& frame_id, + sensor_msgs::msg::Image* out, std::string* error); + +enum class LidarFrame { + kSensor, // point_cloud already in the sensor frame (FRD) + kWorld, // point_cloud in world NED; transform by the message's sensor pose +}; + +bool ParseLidarFrame(const std::string& name, LidarFrame* out); + +// LidarMessage: {time_stamp, point_cloud[x,y,z,...] (float), azimuth_.., +// segmentation_cloud, intensity_cloud, laser_index_cloud, pose{position, +// orientation}}. Produces an x,y,z(,intensity) float32 PointCloud2 in the +// sensor's FLU frame `frame_id`. +bool DecodeLidar(const std::string& payload, LidarFrame frame, const std::string& frame_id, + sensor_msgs::msg::PointCloud2* out, std::string* error); + +// Project AirSim's GPU LiDAR publishes a complete 360-degree ring every +// render frame (~40+ Hz, coarse azimuth step that varies with frame time), +// and republishes an unchanged ring between renders. A spinning LiDAR (what +// AirStack's planners and mappers are tuned on — Isaac's OS1 at 10 Hz) +// delivers one dense sweep per rotation. SweepAccumulator merges rings over +// one sweep period into a single cloud and drops exact repeats; the motion +// smear is bounded like a real spinning sensor's (period x speed). +class SweepAccumulator { + public: + explicit SweepAccumulator(double sweep_period_s); + // Rings are bucketed into fixed time slots floor(stamp / period); when a + // ring from a NEW slot arrives, the previous slot's merged sweep is emitted + // (returns true, fills `out`, stamp = that slot's newest ring) and the new + // ring starts the next sweep. One sweep per slot = exactly the configured + // rate whenever rings arrive faster than it, at the cost of one ring of + // latency. + bool Add(const sensor_msgs::msg::PointCloud2& ring, sensor_msgs::msg::PointCloud2* out); + std::uint64_t duplicates() const { return duplicates_; } + + private: + std::int64_t period_ns_; + std::int64_t slot_{-1}; + sensor_msgs::msg::PointCloud2 acc_; + std::vector last_ring_head_; + std::uint32_t last_ring_width_{0}; + std::uint64_t duplicates_{0}; +}; + +// ClockMessage: {time_stamp}. +bool DecodeClock(const std::string& payload, std::int64_t* nanos, std::string* error); + +// GetGroundTruthKinematics service result (KinematicsMessage as JSON): +// {time_stamp, pose:{position,orientation}, twist:{linear, angular}, +// accels:{...}} (the topic form nests these under "kinematics"; both work). +// NED/FRD in, ENU/FLU out — the same convention as the legacy +// ms_airsim_ros_bridge's //odom_ground_truth (pose and twist vectors +// rotated world NED → ENU) so test_takeoff_hover_land compares +// it against MAVROS odometry unchanged. Position is reported relative to +// `origin_ned` (the robot's spawn point, world NED) — Project AirSim +// kinematics are world-frame, while MAVROS's local origin and the legacy +// bridge's ground truth start at the robot's own spawn. +bool KinematicsJsonToOdometry(const nlohmann::json& result, const Vec3& origin_ned, + const std::string& frame_id, + const std::string& child_frame_id, nav_msgs::msg::Odometry* out, + std::string* error); + +} // namespace pas_ros_bridge diff --git a/simulation/project-airsim/ros_ws/src/pas_ros_bridge/package.xml b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/package.xml new file mode 100644 index 000000000..c1059fe1b --- /dev/null +++ b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/package.xml @@ -0,0 +1,33 @@ + + + + pas_ros_bridge + 0.1.0 + + Project AirSim to ROS 2 bridge for AirStack (C++). One process serves every + robot of the loaded scene — Project AirSim's topic socket admits a single + client — and publishes each robot's stereo images, depth, camera_info, + LiDAR, ground-truth odometry and /clock on that robot's ROS_DOMAIN_ID, in + the same topic layout as the Isaac Sim and legacy AirSim bridges. Also + provides pas_scene_loader, which loads the generated scene and exits. + + AirLab CMU + BSD-3-Clause-Clear + + ament_cmake + + rclcpp + sensor_msgs + nav_msgs + rosgraph_msgs + diagnostic_msgs + + + ament_cmake_gtest + + + ament_cmake + + diff --git a/simulation/project-airsim/ros_ws/src/pas_ros_bridge/src/bridge_main.cpp b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/src/bridge_main.cpp new file mode 100644 index 000000000..e1f7c7efc --- /dev/null +++ b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/src/bridge_main.cpp @@ -0,0 +1,521 @@ +// Copyright (c) 2026 Carnegie Mellon University +// SPDX-License-Identifier: BSD-3-Clause-Clear +// +// pas_ros_bridge — Project AirSim → ROS 2 for every robot of the loaded scene. +// +// Why one process for all robots: Project AirSim's topic socket is an NNG +// PAIR0 socket — exactly one client may subscribe. So this process holds the +// single topic connection and fans data out to one rclcpp::Context per robot, +// each initialised on that robot's ROS_DOMAIN_ID (AirStack's isolation rule: +// robot N lives on domain N and sees only its own sensors and its own copy of +// /clock). +// +// The topic map (Project AirSim topic → ROS topic, frame ids, kinds) comes +// from airstack_meta.json, written by simulation/project-airsim/config/ +// generate_scene.py; this file holds no topic names. +// +// Usage: +// pas_ros_bridge --meta /root/project-airsim/generated/airstack_meta.json +// [--host 127.0.0.1] [--port-topics 8989] [--port-services 8990] +// [--clock-rate 100] [--gt-rate 50] [--lidar-frame sensor|world] +// [--stats-period 10] +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "json.hpp" +#include "pas_ros_bridge/conversions.hpp" +#include "pas_ros_bridge/decode.hpp" + +namespace pasc = microsoft::projectairsim::client; +namespace mp = microsoft::projectairsim; +using json = nlohmann::json; +using namespace std::chrono_literals; +using namespace pas_ros_bridge; + +namespace { + +std::atomic g_stop{false}; +std::atomic g_exit_code{0}; + +void OnSignal(int) { g_stop = true; } + +struct Args { + std::string meta; + std::string host = "127.0.0.1"; + unsigned port_topics = 8989; + unsigned port_services = 8990; + double clock_rate = 100.0; + double gt_rate = 50.0; + std::string lidar_frame = "sensor"; + double stats_period = 10.0; + double connect_timeout = 120.0; +}; + +[[noreturn]] void Usage(const std::string& error) { + std::cerr << "pas_ros_bridge: " << error + << "\nusage: pas_ros_bridge --meta FILE [--host H] [--port-topics P]" + " [--port-services P] [--clock-rate HZ] [--gt-rate HZ]" + " [--lidar-frame sensor|world] [--stats-period S] [--connect-timeout S]\n"; + std::exit(2); +} + +Args ParseArgs(int argc, char** argv) { + Args a; + for (int i = 1; i < argc; ++i) { + const std::string k = argv[i]; + if (k == "--ros-args") break; // leave ROS arguments to rclcpp + auto next = [&]() -> std::string { + if (i + 1 >= argc) Usage("missing value for " + k); + return argv[++i]; + }; + try { + if (k == "--meta") a.meta = next(); + else if (k == "--host") a.host = next(); + else if (k == "--port-topics") a.port_topics = static_cast(std::stoul(next())); + else if (k == "--port-services") a.port_services = static_cast(std::stoul(next())); + else if (k == "--clock-rate") a.clock_rate = std::stod(next()); + else if (k == "--gt-rate") a.gt_rate = std::stod(next()); + else if (k == "--lidar-frame") a.lidar_frame = next(); + else if (k == "--stats-period") a.stats_period = std::stod(next()); + else if (k == "--connect-timeout") a.connect_timeout = std::stod(next()); + else Usage("unknown argument " + k); + } catch (const std::invalid_argument&) { + Usage("bad number for " + k); + } + } + if (a.meta.empty()) Usage("--meta is required"); + if (a.clock_rate <= 0 || a.gt_rate <= 0) Usage("rates must be > 0"); + return a; +} + +// Reliable + keep-last: a RELIABLE publisher matches both reliable and +// best-effort subscribers (the reverse is not true), and the legacy AirSim +// bridge published every sensor stream reliably, so existing consumers keep +// matching. Depth 2 bounds latency for large images. +rclcpp::QoS SensorQoS() { return rclcpp::QoS(rclcpp::KeepLast(2)).reliable(); } + +enum class Kind { kImage, kDepth, kLidar }; + +struct Counters { + std::atomic received{0}; + std::atomic published{0}; + std::atomic idle{0}; // dropped: no ROS subscriber + std::atomic errors{0}; +}; + +struct Stream { + Kind kind{Kind::kImage}; + std::string pas_topic, ros_topic, frame_id; + bool right{false}; + rclcpp::Publisher::SharedPtr image_pub; + rclcpp::Publisher::SharedPtr info_pub; + rclcpp::Publisher::SharedPtr cloud_pub; + sensor_msgs::msg::CameraInfo info_template; + std::unique_ptr sweep; // lidar only + Counters counters; + std::uint64_t last_published{0}; // stats thread only + rclcpp::Logger logger = rclcpp::get_logger("pas_ros_bridge"); +}; + +struct Robot { + std::string name; + std::size_t domain_id{0}; + rclcpp::Context::SharedPtr context; + rclcpp::Node::SharedPtr node; + rclcpp::Publisher::SharedPtr clock_pub; + rclcpp::Publisher::SharedPtr odom_pub; + rclcpp::Publisher::SharedPtr diag_pub; + std::string kinematics_method, odom_frame, odom_child_frame; + Vec3 spawn_ned; // ground truth is reported relative to this point + std::vector> streams; + Counters odom; +}; + +class Bridge { + public: + Bridge(const Args& args, const json& meta, int argc, char** argv) + : args_(args) { + if (!ParseLidarFrame(args.lidar_frame, &lidar_frame_)) { + Usage("--lidar-frame must be sensor or world"); + } + clock_topic_ = meta.at("clock_topic").get(); + clock_period_ns_ = static_cast(1e9 / args.clock_rate); + const auto& cam = meta.at("camera"); + Intrinsics k; + k.width = cam.at("width").get(); + k.height = cam.at("height").get(); + k.fx = cam.at("fx").get(); + k.fy = cam.at("fy").get(); + k.cx = cam.at("cx").get(); + k.cy = cam.at("cy").get(); + const double baseline = cam.at("baseline").get(); + const double lidar_rate = meta.at("lidar").value("rate", 10.0); + + bool first = true; + for (const auto& r : meta.at("robots")) { + auto robot = std::make_unique(); + robot->name = r.at("name").get(); + robot->domain_id = r.at("domain_id").get(); + robot->kinematics_method = r.at("kinematics_method").get(); + robot->odom_frame = r.at("odom_frame_id").get(); + robot->odom_child_frame = r.at("odom_child_frame_id").get(); + const auto& spawn = r.at("spawn_ned"); + robot->spawn_ned = {spawn.at(0).get(), spawn.at(1).get(), + spawn.at(2).get()}; + + rclcpp::InitOptions init; + init.set_domain_id(robot->domain_id); + init.auto_initialize_logging(first); // rcl logging is process-global + first = false; + robot->context = std::make_shared(); + robot->context->init(argc, argv, init); + rclcpp::NodeOptions opts; + opts.context(robot->context); + opts.start_parameter_services(false); + robot->node = std::make_shared("pas_ros_bridge", opts); + + robot->clock_pub = robot->node->create_publisher( + "/clock", rclcpp::QoS(rclcpp::KeepLast(10)).reliable()); + robot->odom_pub = robot->node->create_publisher( + r.at("odom_topic").get(), rclcpp::QoS(rclcpp::KeepLast(10)).reliable()); + robot->diag_pub = robot->node->create_publisher( + "/" + robot->name + "/pas_bridge/diagnostics", rclcpp::QoS(rclcpp::KeepLast(1))); + + for (const auto& s : r.at("streams")) { + auto st = std::make_unique(); + const auto kind = s.at("kind").get(); + st->pas_topic = s.at("pas_topic").get(); + st->ros_topic = s.at("ros_topic").get(); + st->frame_id = s.at("frame_id").get(); + st->logger = robot->node->get_logger(); + if (kind == "image") { + st->kind = Kind::kImage; + st->right = s.value("right", false); + st->image_pub = robot->node->create_publisher( + st->ros_topic, SensorQoS()); + st->info_pub = robot->node->create_publisher( + s.at("info_topic").get(), SensorQoS()); + Intrinsics ki = k; + if (s.contains("width") && s.contains("height") && s.contains("fov")) { + ki = IntrinsicsFromFov(s.at("width").get(), + s.at("height").get(), + s.at("fov").get()); // e.g. the chase camera + } + st->info_template = MakeCameraInfo(ki, baseline, st->right, st->frame_id); + } else if (kind == "depth") { + st->kind = Kind::kDepth; + st->image_pub = robot->node->create_publisher( + st->ros_topic, SensorQoS()); + } else if (kind == "lidar") { + st->kind = Kind::kLidar; + st->cloud_pub = robot->node->create_publisher( + st->ros_topic, SensorQoS()); + st->sweep = std::make_unique(1.0 / lidar_rate); + } else { + throw std::runtime_error("unknown stream kind '" + kind + "' in meta"); + } + by_topic_[st->pas_topic] = st.get(); + robot->streams.push_back(std::move(st)); + } + RCLCPP_INFO(robot->node->get_logger(), "%s: domain %zu, %zu stream(s)", + robot->name.c_str(), robot->domain_id, robot->streams.size()); + robots_.push_back(std::move(robot)); + } + } + + rclcpp::Logger log() const { return robots_.front()->node->get_logger(); } + + bool Connect() { + client_ = std::make_shared(); + const auto deadline = std::chrono::steady_clock::now() + + std::chrono::duration(args_.connect_timeout); + while (!g_stop) { + const auto status = client_->Connect(args_.host, args_.port_topics, args_.port_services); + if (status == pasc::Status::OK) break; + if (std::chrono::steady_clock::now() > deadline) { + RCLCPP_FATAL(log(), "could not connect to Project AirSim at %s:%u/%u", + args_.host.c_str(), args_.port_topics, args_.port_services); + return false; + } + std::this_thread::sleep_for(1s); + } + std::string server_hash; + if (client_->GetBuildCommitHash(&server_hash) == pasc::Status::OK) { + RCLCPP_INFO(log(), "connected; server build %s, client %s", server_hash.c_str(), + pasc::Client::GetVersion()); + } + return !g_stop; + } + + // Subscribe every mapped topic once it exists (the scene is loaded before + // the bridge starts, but topics can trail the load by a few ticks). + bool Subscribe() { + std::set pending; + pending.insert(clock_topic_); + for (const auto& [topic, _] : by_topic_) pending.insert(topic); + const auto deadline = std::chrono::steady_clock::now() + + std::chrono::duration(args_.connect_timeout); + auto callback = [this](const std::string& topic, const std::string& payload) { + OnMessage(topic, payload); + }; + while (!pending.empty() && !g_stop) { + const auto available = client_->GetTopicInfo(); + const std::set have(available.begin(), available.end()); + for (auto it = pending.begin(); it != pending.end();) { + if (have.count(*it) && client_->Subscribe(it->c_str(), callback) == pasc::Status::OK) { + RCLCPP_INFO(log(), "subscribed %s", it->c_str()); + it = pending.erase(it); + } else { + ++it; + } + } + if (pending.empty()) break; + if (std::chrono::steady_clock::now() > deadline) { + for (const auto& t : pending) RCLCPP_ERROR(log(), "topic never appeared: %s", t.c_str()); + return false; + } + std::this_thread::sleep_for(500ms); + } + return !g_stop; + } + + void Run() { + std::vector threads; + for (auto& r : robots_) threads.emplace_back([this, rp = r.get()] { OdomLoop(*rp); }); + threads.emplace_back([this] { StatsLoop(); }); + while (!g_stop) std::this_thread::sleep_for(100ms); + for (auto& t : threads) t.join(); + client_->UnsubscribeAll(); + client_->Disconnect(); + for (auto& r : robots_) r->context->shutdown("pas_ros_bridge exiting"); + } + + private: + void OnMessage(const std::string& topic, const std::string& payload) { + if (topic == clock_topic_) { + OnClock(payload); + return; + } + const auto it = by_topic_.find(topic); + if (it == by_topic_.end()) return; + Stream& s = *it->second; + s.counters.received++; + std::string error; + switch (s.kind) { + case Kind::kImage: { + if (s.image_pub->get_subscription_count() == 0 && + s.info_pub->get_subscription_count() == 0) { + s.counters.idle++; + return; + } + auto img = std::make_unique(); + if (!DecodeImage(payload, s.frame_id, img.get(), &error)) break; + auto info = std::make_unique(s.info_template); + info->header = img->header; + s.image_pub->publish(std::move(img)); + s.info_pub->publish(std::move(info)); + s.counters.published++; + return; + } + case Kind::kDepth: { + if (s.image_pub->get_subscription_count() == 0) { + s.counters.idle++; + return; + } + auto img = std::make_unique(); + if (!DecodeImage(payload, s.frame_id, img.get(), &error)) break; + s.image_pub->publish(std::move(img)); + s.counters.published++; + return; + } + case Kind::kLidar: { + if (s.cloud_pub->get_subscription_count() == 0) { + s.counters.idle++; + return; + } + sensor_msgs::msg::PointCloud2 ring; + if (!DecodeLidar(payload, lidar_frame_, s.frame_id, &ring, &error)) break; + auto sweep = std::make_unique(); + if (s.sweep->Add(ring, sweep.get())) { + s.cloud_pub->publish(std::move(sweep)); + s.counters.published++; + } + return; + } + } + s.counters.errors++; + RCLCPP_WARN_THROTTLE(s.logger, *robots_.front()->node->get_clock(), 5000, "%s: %s", + topic.c_str(), error.c_str()); + } + + void OnClock(const std::string& payload) { + std::int64_t nanos = 0; + std::string error; + if (!DecodeClock(payload, &nanos, &error)) { + RCLCPP_WARN_THROTTLE(log(), *robots_.front()->node->get_clock(), 5000, "%s", error.c_str()); + return; + } + // A steppable clock restarts at 0 when the scene reloads. ROS time + // jumping backwards breaks every use_sim_time node, and PX4 must restart + // too — fail loudly instead of publishing a rewound clock. + if (nanos + clock_period_ns_ < last_clock_ns_) { + RCLCPP_FATAL(log(), "sim clock went backwards (%ld -> %ld ns): scene reloaded? " + "Restart the project-airsim container.", static_cast(last_clock_ns_.load()), + static_cast(nanos)); + g_exit_code = 3; + g_stop = true; + return; + } + if (nanos > last_clock_ns_) last_clock_ns_ = nanos; + if (nanos - last_clock_pub_ns_ < clock_period_ns_ && last_clock_pub_ns_ != 0) return; + last_clock_pub_ns_ = nanos; + rosgraph_msgs::msg::Clock msg; + msg.clock = NanosToRosTime(nanos); + for (auto& r : robots_) r->clock_pub->publish(msg); + } + + void OdomLoop(Robot& r) { + const auto period = std::chrono::duration(1.0 / args_.gt_rate); + auto next = std::chrono::steady_clock::now(); + while (!g_stop) { + next += std::chrono::duration_cast(period); + pasc::Message response; + pasc::Status status; + { + std::lock_guard lock(request_mutex_); + status = client_->Request(r.kinematics_method, json::object(), &response); + } + if (status == pasc::Status::OK) { + mp::ResponseMessage reply; + reply.Deserialize(response); + nav_msgs::msg::Odometry odom; + std::string error; + r.odom.received++; + if (reply.GetErrorCode() == 0 && + KinematicsJsonToOdometry(reply.GetResult(), r.spawn_ned, r.odom_frame, + r.odom_child_frame, &odom, &error)) { + r.odom_pub->publish(odom); + r.odom.published++; + } else { + r.odom.errors++; + RCLCPP_WARN_THROTTLE(r.node->get_logger(), *r.node->get_clock(), 5000, + "ground truth for %s: %s", r.name.c_str(), + error.empty() ? reply.GetResult().dump().c_str() : error.c_str()); + } + } else { + r.odom.errors++; + } + std::this_thread::sleep_until(next); + } + } + + void StatsLoop() { + const auto period = std::chrono::duration(args_.stats_period); + auto next = std::chrono::steady_clock::now(); + std::uint64_t last_odom_total = 0; + while (!g_stop) { + next += std::chrono::duration_cast(period); + while (!g_stop && std::chrono::steady_clock::now() < next) std::this_thread::sleep_for(100ms); + if (g_stop) break; + std::uint64_t odom_total = 0; + for (auto& r : robots_) { + diagnostic_msgs::msg::DiagnosticArray diag; + diag.header.stamp = NanosToRosTime(last_clock_ns_); + for (auto& s : r->streams) { + const auto pub = s->counters.published.load(); + const double hz = static_cast(pub - s->last_published) / args_.stats_period; + s->last_published = pub; + diagnostic_msgs::msg::DiagnosticStatus st; + st.name = s->ros_topic; + st.hardware_id = s->pas_topic; + st.level = s->counters.errors > 0 ? diagnostic_msgs::msg::DiagnosticStatus::WARN + : diagnostic_msgs::msg::DiagnosticStatus::OK; + auto kv = [](const char* k, const std::string& v) { + diagnostic_msgs::msg::KeyValue p; + p.key = k; + p.value = v; + return p; + }; + st.values = {kv("publish_hz", std::to_string(hz)), + kv("received", std::to_string(s->counters.received.load())), + kv("published", std::to_string(pub)), + kv("idle_no_subscriber", std::to_string(s->counters.idle.load())), + kv("errors", std::to_string(s->counters.errors.load()))}; + diag.status.push_back(st); + if (pub > 0 || s->counters.errors > 0) { + RCLCPP_INFO(r->node->get_logger(), "%-50s %6.1f Hz (rx %lu, err %lu)", + s->ros_topic.c_str(), hz, + static_cast(s->counters.received.load()), + static_cast(s->counters.errors.load())); + } + } + odom_total += r->odom.published; + r->diag_pub->publish(diag); + } + RCLCPP_INFO(log(), "sim time %.2f s, ground truth %.1f Hz total", + static_cast(last_clock_ns_) / 1e9, + static_cast(odom_total - last_odom_total) / args_.stats_period); + last_odom_total = odom_total; + } + } + + Args args_; + LidarFrame lidar_frame_{LidarFrame::kSensor}; + std::string clock_topic_; + std::int64_t clock_period_ns_{0}; + std::atomic last_clock_ns_{0}; // written by the client thread + std::int64_t last_clock_pub_ns_{0}; + std::vector> robots_; + std::unordered_map by_topic_; + std::shared_ptr client_; + std::mutex request_mutex_; +}; + +} // namespace + +int main(int argc, char** argv) { + const Args args = ParseArgs(argc, argv); + std::signal(SIGINT, OnSignal); + std::signal(SIGTERM, OnSignal); + + json meta; + try { + std::ifstream in(args.meta); + if (!in) Usage("cannot read " + args.meta); + meta = json::parse(in); + } catch (const json::exception& ex) { + Usage(std::string("bad meta file: ") + ex.what()); + } + + try { + Bridge bridge(args, meta, argc, argv); + if (!bridge.Connect() || !bridge.Subscribe()) return g_stop ? 0 : 1; + RCLCPP_INFO(bridge.log(), "bridging; lidar frame mode: %s", args.lidar_frame.c_str()); + bridge.Run(); + } catch (const std::exception& ex) { + std::cerr << "pas_ros_bridge: fatal: " << ex.what() << std::endl; + return 1; + } + return g_exit_code; +} diff --git a/simulation/project-airsim/ros_ws/src/pas_ros_bridge/src/conversions.cpp b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/src/conversions.cpp new file mode 100644 index 000000000..86fddfc11 --- /dev/null +++ b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/src/conversions.cpp @@ -0,0 +1,110 @@ +// Copyright (c) 2026 Carnegie Mellon University +// SPDX-License-Identifier: BSD-3-Clause-Clear +#include "pas_ros_bridge/conversions.hpp" + +#include +#include +#include + +namespace pas_ros_bridge { + +namespace { +constexpr double kSqrt2Inv = 0.70710678118654752440; +} // namespace + +Vec3 NedToEnu(const Vec3& v) { return {v.y, v.x, -v.z}; } + +Quat NedFrdToEnuFlu(const Quat& q) { + // Expanded product of 180° about (1,1,0)/√2 (NED→ENU), q, and 180° about +X + // (FLU→FRD); identical to ms_airsim_ros_bridge._ned_quat_to_enu. + return { + -kSqrt2Inv * (q.w + q.z), + -kSqrt2Inv * (q.x + q.y), + kSqrt2Inv * (q.y - q.x), + kSqrt2Inv * (q.z - q.w), + }; +} + +Vec3 FrdToFlu(const Vec3& v) { return {v.x, -v.y, -v.z}; } + +Quat Conjugate(const Quat& q) { return {q.w, -q.x, -q.y, -q.z}; } + +Vec3 Rotate(const Quat& q, const Vec3& v) { + // v' = v + 2w (u × v) + 2 u × (u × v), u = (x, y, z) + const double ux = q.x, uy = q.y, uz = q.z; + const double tx = 2.0 * (uy * v.z - uz * v.y); + const double ty = 2.0 * (uz * v.x - ux * v.z); + const double tz = 2.0 * (ux * v.y - uy * v.x); + return { + v.x + q.w * tx + (uy * tz - uz * ty), + v.y + q.w * ty + (uz * tx - ux * tz), + v.z + q.w * tz + (ux * ty - uy * tx), + }; +} + +float HalfToFloat(std::uint16_t h) { + const std::uint32_t sign = static_cast(h & 0x8000u) << 16; + std::uint32_t exponent = (h >> 10) & 0x1Fu; + std::uint32_t mantissa = h & 0x3FFu; + std::uint32_t bits; + if (exponent == 0) { + if (mantissa == 0) { + bits = sign; // ±0 + } else { + // Subnormal: normalise. + exponent = 1; + while ((mantissa & 0x400u) == 0) { + mantissa <<= 1; + --exponent; + } + mantissa &= 0x3FFu; + bits = sign | ((exponent + (127 - 15)) << 23) | (mantissa << 13); + } + } else if (exponent == 0x1F) { + bits = sign | 0x7F800000u | (mantissa << 13); // inf / NaN + } else { + bits = sign | ((exponent + (127 - 15)) << 23) | (mantissa << 13); + } + float out; + std::memcpy(&out, &bits, sizeof(out)); + return out; +} + +void Depth16ToFloat32(const std::uint8_t* src, std::size_t n_pixels, float* dst) { + const float nan = std::numeric_limits::quiet_NaN(); + for (std::size_t i = 0; i < n_pixels; ++i) { + const std::uint16_t h = + static_cast(src[2 * i]) | + static_cast(static_cast(src[2 * i + 1]) << 8); + // Exponent all-ones = inf or NaN = no return. + dst[i] = ((h & 0x7C00u) == 0x7C00u) ? nan : HalfToFloat(h); + } +} + +Intrinsics IntrinsicsFromFov(std::uint32_t width, std::uint32_t height, double fov_deg) { + Intrinsics k; + k.width = width; + k.height = height; + k.fx = static_cast(width) / (2.0 * std::tan(fov_deg * M_PI / 360.0)); + k.fy = k.fx; + k.cx = static_cast(width) / 2.0; + k.cy = static_cast(height) / 2.0; + return k; +} + +sensor_msgs::msg::CameraInfo MakeCameraInfo(const Intrinsics& k, double baseline_m, + bool is_right, const std::string& frame_id) { + sensor_msgs::msg::CameraInfo info; + info.header.frame_id = frame_id; + info.width = k.width; + info.height = k.height; + info.distortion_model = "plumb_bob"; + info.d.assign(5, 0.0); + info.k = {k.fx, 0.0, k.cx, 0.0, k.fy, k.cy, 0.0, 0.0, 1.0}; + info.r = {1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0}; + const double tx = is_right ? -k.fx * baseline_m : 0.0; + info.p = {k.fx, 0.0, k.cx, tx, 0.0, k.fy, k.cy, 0.0, 0.0, 0.0, 1.0, 0.0}; + return info; +} + +} // namespace pas_ros_bridge diff --git a/simulation/project-airsim/ros_ws/src/pas_ros_bridge/src/decode.cpp b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/src/decode.cpp new file mode 100644 index 000000000..57c329ff7 --- /dev/null +++ b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/src/decode.cpp @@ -0,0 +1,354 @@ +// Copyright (c) 2026 Carnegie Mellon University +// SPDX-License-Identifier: BSD-3-Clause-Clear +#include "pas_ros_bridge/decode.hpp" + +#include +#include +#include + +#include "msgpack.hpp" + +namespace pas_ros_bridge { + +namespace { + +// Reference STR/BIN in the caller's payload instead of copying them into the +// msgpack zone: the payload outlives every decode call (it is the topic +// callback's argument), and images are the bulk of the traffic. +bool ReferenceAll(msgpack::type::object_type, std::size_t, void*) { return true; } + +msgpack::object_handle Unpack(const std::string& payload) { + return msgpack::unpack(payload.data(), payload.size(), ReferenceAll); +} + +std::string_view KeyOf(const msgpack::object_kv& kv) { + if (kv.key.type == msgpack::type::STR) return {kv.key.via.str.ptr, kv.key.via.str.size}; + return {}; +} + +const msgpack::object* Find(const msgpack::object& map, std::string_view key) { + if (map.type != msgpack::type::MAP) return nullptr; + for (std::uint32_t i = 0; i < map.via.map.size; ++i) { + if (KeyOf(map.via.map.ptr[i]) == key) return &map.via.map.ptr[i].val; + } + return nullptr; +} + +bool AsInt64(const msgpack::object* o, std::int64_t* out) { + if (!o) return false; + if (o->type == msgpack::type::POSITIVE_INTEGER) { + *out = static_cast(o->via.u64); + return true; + } + if (o->type == msgpack::type::NEGATIVE_INTEGER) { + *out = o->via.i64; + return true; + } + return false; +} + +double AsDouble(const msgpack::object& o) { + switch (o.type) { + case msgpack::type::FLOAT32: + case msgpack::type::FLOAT64: return o.via.f64; + case msgpack::type::POSITIVE_INTEGER: return static_cast(o.via.u64); + case msgpack::type::NEGATIVE_INTEGER: return static_cast(o.via.i64); + default: throw std::runtime_error("expected a number"); + } +} + +std::string_view AsBytes(const msgpack::object* o) { + if (!o) return {}; + if (o->type == msgpack::type::BIN) return {o->via.bin.ptr, o->via.bin.size}; + if (o->type == msgpack::type::STR) return {o->via.str.ptr, o->via.str.size}; + return {}; +} + +bool AsVec3(const msgpack::object* o, Vec3* out) { + if (!o || o->type != msgpack::type::MAP) return false; + const auto* x = Find(*o, "x"); + const auto* y = Find(*o, "y"); + const auto* z = Find(*o, "z"); + if (!x || !y || !z) return false; + *out = {AsDouble(*x), AsDouble(*y), AsDouble(*z)}; + return true; +} + +bool AsQuat(const msgpack::object* o, Quat* out) { + if (!o || o->type != msgpack::type::MAP) return false; + const auto* w = Find(*o, "w"); + const auto* x = Find(*o, "x"); + const auto* y = Find(*o, "y"); + const auto* z = Find(*o, "z"); + if (!w || !x || !y || !z) return false; + *out = {AsDouble(*w), AsDouble(*x), AsDouble(*y), AsDouble(*z)}; + return true; +} + +void SetFields(sensor_msgs::msg::PointCloud2* cloud, bool with_intensity) { + const char* names[] = {"x", "y", "z", "intensity"}; + const int n = with_intensity ? 4 : 3; + cloud->fields.clear(); + for (int i = 0; i < n; ++i) { + sensor_msgs::msg::PointField f; + f.name = names[i]; + f.offset = static_cast(4 * i); + f.datatype = sensor_msgs::msg::PointField::FLOAT32; + f.count = 1; + cloud->fields.push_back(f); + } + cloud->point_step = static_cast(4 * n); +} + +double JsonNumber(const nlohmann::json& j, const char* key) { + if (!j.contains(key) || !j[key].is_number()) { + throw std::runtime_error(std::string("missing number '") + key + "'"); + } + return j[key].get(); +} + +Vec3 JsonVec3(const nlohmann::json& j) { + return {JsonNumber(j, "x"), JsonNumber(j, "y"), JsonNumber(j, "z")}; +} + +} // namespace + +builtin_interfaces::msg::Time NanosToRosTime(std::int64_t nanos) { + builtin_interfaces::msg::Time t; + if (nanos < 0) nanos = 0; + t.sec = static_cast(nanos / 1000000000LL); + t.nanosec = static_cast(nanos % 1000000000LL); + return t; +} + +bool DecodeImage(const std::string& payload, const std::string& frame_id, + sensor_msgs::msg::Image* out, std::string* error) { + try { + const auto handle = Unpack(payload); + const msgpack::object& msg = handle.get(); + std::int64_t stamp = 0, width = 0, height = 0; + if (!AsInt64(Find(msg, "time_stamp"), &stamp) || !AsInt64(Find(msg, "width"), &width) || + !AsInt64(Find(msg, "height"), &height) || width <= 0 || height <= 0) { + *error = "image payload lacks time_stamp/width/height"; + return false; + } + const auto encoding = AsBytes(Find(msg, "encoding")); + const auto data = AsBytes(Find(msg, "data")); + const auto w = static_cast(width); + const auto h = static_cast(height); + const std::size_t pixels = static_cast(w) * h; + + out->header.stamp = NanosToRosTime(stamp); + out->header.frame_id = frame_id; + out->width = w; + out->height = h; + out->is_bigendian = 0; + if (encoding == "BGR") { + if (data.size() != pixels * 3) { + *error = "BGR image size mismatch"; + return false; + } + out->encoding = "bgr8"; + out->step = w * 3; + out->data.assign(reinterpret_cast(data.data()), + reinterpret_cast(data.data()) + data.size()); + return true; + } + if (encoding == "16FC1") { + if (data.size() != pixels * 2) { + *error = "16FC1 depth size mismatch"; + return false; + } + out->encoding = "32FC1"; + out->step = w * 4; + out->data.resize(pixels * 4); + Depth16ToFloat32(reinterpret_cast(data.data()), pixels, + reinterpret_cast(out->data.data())); + return true; + } + *error = "unsupported image encoding '" + std::string(encoding) + + "' (PNG compression must stay disabled in the scene config)"; + return false; + } catch (const std::exception& ex) { + *error = std::string("image decode failed: ") + ex.what(); + return false; + } +} + +bool ParseLidarFrame(const std::string& name, LidarFrame* out) { + if (name == "sensor") { + *out = LidarFrame::kSensor; + return true; + } + if (name == "world") { + *out = LidarFrame::kWorld; + return true; + } + return false; +} + +bool DecodeLidar(const std::string& payload, LidarFrame frame, const std::string& frame_id, + sensor_msgs::msg::PointCloud2* out, std::string* error) { + try { + const auto handle = Unpack(payload); + const msgpack::object& msg = handle.get(); + std::int64_t stamp = 0; + if (!AsInt64(Find(msg, "time_stamp"), &stamp)) { + *error = "lidar payload lacks time_stamp"; + return false; + } + const auto* points = Find(msg, "point_cloud"); + if (!points || points->type != msgpack::type::ARRAY || points->via.array.size % 3 != 0) { + *error = "lidar point_cloud missing or not a multiple of 3"; + return false; + } + const std::uint32_t n = points->via.array.size / 3; + const auto* intensity = Find(msg, "intensity_cloud"); + const bool with_intensity = intensity && intensity->type == msgpack::type::ARRAY && + intensity->via.array.size == n; + + Quat inv_orientation; + Vec3 sensor_position; + if (frame == LidarFrame::kWorld) { + const auto* pose = Find(msg, "pose"); + Quat q; + if (!pose || !AsVec3(Find(*pose, "position"), &sensor_position) || + !AsQuat(Find(*pose, "orientation"), &q)) { + *error = "lidar frame mode 'world' needs the message pose"; + return false; + } + inv_orientation = Conjugate(q); + } + + out->header.stamp = NanosToRosTime(stamp); + out->header.frame_id = frame_id; + out->height = 1; + out->width = n; + out->is_bigendian = false; + out->is_dense = true; + SetFields(out, with_intensity); + out->row_step = out->point_step * n; + out->data.resize(static_cast(out->row_step)); + + const msgpack::object* p = points->via.array.ptr; + auto* dst = reinterpret_cast(out->data.data()); + const std::uint32_t stride = with_intensity ? 4 : 3; + for (std::uint32_t i = 0; i < n; ++i) { + Vec3 v{AsDouble(p[3 * i]), AsDouble(p[3 * i + 1]), AsDouble(p[3 * i + 2])}; + if (frame == LidarFrame::kWorld) { + v = Rotate(inv_orientation, + {v.x - sensor_position.x, v.y - sensor_position.y, v.z - sensor_position.z}); + } + const Vec3 flu = FrdToFlu(v); + float* d = dst + static_cast(i) * stride; + d[0] = static_cast(flu.x); + d[1] = static_cast(flu.y); + d[2] = static_cast(flu.z); + if (with_intensity) d[3] = static_cast(AsDouble(intensity->via.array.ptr[i])); + } + return true; + } catch (const std::exception& ex) { + *error = std::string("lidar decode failed: ") + ex.what(); + return false; + } +} + +SweepAccumulator::SweepAccumulator(double sweep_period_s) + : period_ns_(static_cast(sweep_period_s * 1e9)) {} + +bool SweepAccumulator::Add(const sensor_msgs::msg::PointCloud2& ring, + sensor_msgs::msg::PointCloud2* out) { + // Exact repeat of the previous ring (same size, same leading bytes): the + // server re-sent an unchanged render — skip it. + const std::size_t head = std::min(ring.data.size(), 64); + if (ring.width == last_ring_width_ && head > 0 && last_ring_head_.size() == head && + std::memcmp(last_ring_head_.data(), ring.data.data(), head) == 0) { + ++duplicates_; + return false; + } + last_ring_width_ = ring.width; + last_ring_head_.assign(ring.data.begin(), ring.data.begin() + static_cast(head)); + + const std::int64_t stamp = + static_cast(ring.header.stamp.sec) * 1000000000LL + ring.header.stamp.nanosec; + const std::int64_t slot = period_ns_ > 0 ? stamp / period_ns_ : stamp; + bool emitted = false; + if (slot_ >= 0 && (slot != slot_ || acc_.point_step != ring.point_step)) { + *out = std::move(acc_); // previous slot complete + emitted = true; + slot_ = -1; + } + if (slot_ < 0) { + acc_ = ring; // first ring of a sweep + slot_ = slot; + } else { + acc_.data.insert(acc_.data.end(), ring.data.begin(), ring.data.end()); + acc_.width += ring.width; + acc_.row_step = acc_.point_step * acc_.width; + acc_.header.stamp = ring.header.stamp; + } + return emitted; +} + +bool DecodeClock(const std::string& payload, std::int64_t* nanos, std::string* error) { + try { + const auto handle = Unpack(payload); + if (!AsInt64(Find(handle.get(), "time_stamp"), nanos) || *nanos < 0) { + *error = "clock payload lacks a valid time_stamp"; + return false; + } + return true; + } catch (const std::exception& ex) { + *error = std::string("clock decode failed: ") + ex.what(); + return false; + } +} + +bool KinematicsJsonToOdometry(const nlohmann::json& result, const Vec3& origin_ned, + const std::string& frame_id, + const std::string& child_frame_id, nav_msgs::msg::Odometry* out, + std::string* error) { + try { + // The service result is flat ({time_stamp, pose, twist, accels} — see + // core_sim json_utils.hpp); the msgpack topic form nests the same fields + // under "kinematics". Accept both. + const auto& kin = result.contains("kinematics") ? result.at("kinematics") : result; + const auto& pose = kin.at("pose"); + const Vec3 world = JsonVec3(pose.at("position")); + const Vec3 p = NedToEnu({world.x - origin_ned.x, world.y - origin_ned.y, + world.z - origin_ned.z}); + const auto& o = pose.at("orientation"); + const Quat q = NedFrdToEnuFlu( + {JsonNumber(o, "w"), JsonNumber(o, "x"), JsonNumber(o, "y"), JsonNumber(o, "z")}); + const auto& twist = kin.at("twist"); + const Vec3 lin = NedToEnu(JsonVec3(twist.at("linear"))); + const Vec3 ang = NedToEnu(JsonVec3(twist.at("angular"))); + + std::int64_t stamp = 0; + if (result.contains("time_stamp") && result["time_stamp"].is_number_integer()) { + stamp = result["time_stamp"].get(); + } + out->header.stamp = NanosToRosTime(stamp); + out->header.frame_id = frame_id; + out->child_frame_id = child_frame_id; + out->pose.pose.position.x = p.x; + out->pose.pose.position.y = p.y; + out->pose.pose.position.z = p.z; + out->pose.pose.orientation.w = q.w; + out->pose.pose.orientation.x = q.x; + out->pose.pose.orientation.y = q.y; + out->pose.pose.orientation.z = q.z; + out->twist.twist.linear.x = lin.x; + out->twist.twist.linear.y = lin.y; + out->twist.twist.linear.z = lin.z; + out->twist.twist.angular.x = ang.x; + out->twist.twist.angular.y = ang.y; + out->twist.twist.angular.z = ang.z; + return true; + } catch (const std::exception& ex) { + *error = std::string("kinematics parse failed: ") + ex.what(); + return false; + } +} + +} // namespace pas_ros_bridge diff --git a/simulation/project-airsim/ros_ws/src/pas_ros_bridge/src/scene_loader_main.cpp b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/src/scene_loader_main.cpp new file mode 100644 index 000000000..7f3f6153c --- /dev/null +++ b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/src/scene_loader_main.cpp @@ -0,0 +1,101 @@ +// Copyright (c) 2026 Carnegie Mellon University +// SPDX-License-Identifier: BSD-3-Clause-Clear +// +// pas_scene_loader — load the generated AirStack scene into a running Project +// AirSim server, report the server's build, and exit (0 = loaded). +// +// Kept separate from pas_ros_bridge on purpose: the bridge can then restart +// without reloading the scene, and a reload (which rewinds the steppable +// clock to 0 and forces a PX4 restart) only ever happens through this tool. +// +// Usage: pas_scene_loader --scene FILE [--host H] [--port-topics P] +// [--port-services P] [--retries N] +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace pasc = microsoft::projectairsim::client; + +int main(int argc, char** argv) { + std::string scene, host = "127.0.0.1"; + unsigned port_topics = 8989, port_services = 8990; + int retries = 30; + for (int i = 1; i < argc; ++i) { + const std::string k = argv[i]; + auto next = [&]() -> std::string { + if (i + 1 >= argc) { + std::cerr << "pas_scene_loader: missing value for " << k << "\n"; + std::exit(2); + } + return argv[++i]; + }; + if (k == "--scene") scene = next(); + else if (k == "--host") host = next(); + else if (k == "--port-topics") port_topics = static_cast(std::stoul(next())); + else if (k == "--port-services") port_services = static_cast(std::stoul(next())); + else if (k == "--retries") retries = std::stoi(next()); + else { + std::cerr << "pas_scene_loader: unknown argument " << k << "\n"; + return 2; + } + } + if (scene.empty() || !std::filesystem::exists(scene)) { + std::cerr << "pas_scene_loader: --scene FILE is required and must exist (got '" << scene + << "')\n"; + return 2; + } + + auto client = std::make_shared(); + pasc::Status status = pasc::Status::Failed; + for (int attempt = 0; attempt <= retries; ++attempt) { + status = client->Connect(host, port_topics, port_services); + if (status == pasc::Status::OK) break; + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + if (status != pasc::Status::OK) { + std::cerr << "pas_scene_loader: cannot connect to " << host << ":" << port_topics << "/" + << port_services << "\n"; + return 1; + } + std::string server_hash = "unknown"; + client->GetBuildCommitHash(&server_hash); + std::cout << "pas_scene_loader: server build " << server_hash << ", client " + << pasc::Client::GetVersion() << std::endl; + + // The generated scene has every robot-config inlined, so it is sent as-is + // with RequestLoadScene; unlike World::Initialize this surfaces the + // server's reason when it rejects the scene. + std::ifstream in(scene); + std::stringstream buf; + buf << in.rdbuf(); + pasc::Message response; + status = client->RequestLoadScene(buf.str(), &response); + std::string reason; + if (status == pasc::Status::OK || status == pasc::Status::RejectedByServer) { + microsoft::projectairsim::ResponseMessage reply; + reply.Deserialize(response); + if (reply.GetErrorCode() != 0) { + reason = reply.GetResult().dump(); + status = pasc::Status::RejectedByServer; + } + } + if (status != pasc::Status::OK) { + std::cerr << "pas_scene_loader: loading " << scene << " failed (status " + << static_cast(status) << ")" << (reason.empty() ? "" : ": " + reason) + << "\n"; + client->Disconnect(); + return 1; + } + std::cout << "pas_scene_loader: loaded " << scene << std::endl; + // Disconnect: the topic socket admits one client, and the bridge needs it. + client->Disconnect(); + return 0; +} diff --git a/simulation/project-airsim/ros_ws/src/pas_ros_bridge/test/test_conversions.cpp b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/test/test_conversions.cpp new file mode 100644 index 000000000..726372b8b --- /dev/null +++ b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/test/test_conversions.cpp @@ -0,0 +1,129 @@ +// Copyright (c) 2026 Carnegie Mellon University +// SPDX-License-Identifier: BSD-3-Clause-Clear +#include + +#include +#include +#include +#include + +#include "pas_ros_bridge/conversions.hpp" + +using namespace pas_ros_bridge; + +namespace { + +// Expected values were produced by the legacy ms_airsim_ros_bridge +// _ned_vec_to_enu / _ned_quat_to_enu functions (extracted with ast from +// simulation/ms-airsim/ros_ws/src/ms_airsim_ros_bridge/ms_airsim_ros_bridge/ +// bridge_node.py on 2026-11-30): both bridges must publish identical +// odom_ground_truth for the same kinematics. +constexpr double kTol = 1e-12; + +void ExpectQuat(const Quat& q, double x, double y, double z, double w) { + EXPECT_NEAR(q.x, x, kTol); + EXPECT_NEAR(q.y, y, kTol); + EXPECT_NEAR(q.z, z, kTol); + EXPECT_NEAR(q.w, w, kTol); +} + +std::uint16_t FloatToHalfBits(float f) { + // Reference encoder for ±0 and normal-range values only (tests below). + std::uint32_t b; + std::memcpy(&b, &f, 4); + const std::uint32_t sign = (b >> 16) & 0x8000u; + if ((b & 0x7FFFFFFFu) == 0) return static_cast(sign); + const int exp = static_cast((b >> 23) & 0xFF) - 127 + 15; + const std::uint32_t mant = (b >> 13) & 0x3FFu; + return static_cast(sign | (static_cast(exp) << 10) | mant); +} + +} // namespace + +TEST(Frames, NedVectorMatchesLegacy) { + const Vec3 v = NedToEnu({1.5, -2.25, -3.0}); + EXPECT_DOUBLE_EQ(v.x, -2.25); + EXPECT_DOUBLE_EQ(v.y, 1.5); + EXPECT_DOUBLE_EQ(v.z, 3.0); +} + +TEST(Frames, IdentityQuatMatchesLegacy) { + // Nose north, level (NED identity) → facing +y in ENU (yaw +90°). + ExpectQuat(NedFrdToEnuFlu({1, 0, 0, 0}), -0.0, 0.0, -0.70710678118654746, -0.70710678118654746); +} + +TEST(Frames, GeneralQuatMatchesLegacy) { + // roll 5°, pitch 10°, yaw 30° (NED/FRD) + const Quat q{0.96231828515262297, 0.019436667336159463, 0.095352424550506409, + 0.25391661851111352}; + ExpectQuat(NedFrdToEnuFlu(q), -0.081168145279307144, 0.053680546725176283, + -0.50091562228606334, -0.86000794789639534); +} + +TEST(Frames, FrdToFluFlipsYZ) { + const Vec3 v = FrdToFlu({1, 2, 3}); + EXPECT_EQ(v.x, 1); + EXPECT_EQ(v.y, -2); + EXPECT_EQ(v.z, -3); +} + +TEST(Frames, RotateAndConjugateRoundTrip) { + const double h = std::sqrt(0.5); + const Quat yaw90{h, 0, 0, h}; // +90° about z + const Vec3 r = Rotate(yaw90, {1, 0, 0}); + EXPECT_NEAR(r.x, 0, kTol); + EXPECT_NEAR(r.y, 1, kTol); + const Vec3 back = Rotate(Conjugate(yaw90), r); + EXPECT_NEAR(back.x, 1, kTol); + EXPECT_NEAR(back.y, 0, kTol); +} + +TEST(Depth, HalfDecodesExactly) { + for (float f : {0.0f, 0.5f, 1.0f, 2.75f, 10.0f, 123.5f, 65504.0f}) { + EXPECT_EQ(HalfToFloat(FloatToHalfBits(f)), f) << f; + } + EXPECT_EQ(HalfToFloat(0x0001), std::ldexp(1.0f, -24)); // smallest subnormal + EXPECT_EQ(HalfToFloat(0x03FF), std::ldexp(1023.0f, -24)); + EXPECT_TRUE(std::isinf(HalfToFloat(0x7C00))); + EXPECT_TRUE(std::signbit(HalfToFloat(0x8000))); +} + +TEST(Depth, NoReturnBecomesNaN) { + // Little-endian binary16: 4.0 m, +inf (sky), NaN, 0.25 m. + const std::uint16_t vals[] = {FloatToHalfBits(4.0f), 0x7C00, 0x7E00, FloatToHalfBits(0.25f)}; + std::vector bytes; + for (auto v : vals) { + bytes.push_back(static_cast(v & 0xFF)); + bytes.push_back(static_cast(v >> 8)); + } + float out[4]; + Depth16ToFloat32(bytes.data(), 4, out); + EXPECT_EQ(out[0], 4.0f); + EXPECT_TRUE(std::isnan(out[1])); + EXPECT_TRUE(std::isnan(out[2])); + EXPECT_EQ(out[3], 0.25f); +} + +TEST(CameraInfo, IntrinsicsMatchProjectAirSimModel) { + const Intrinsics k = IntrinsicsFromFov(480, 300, 90.0); + EXPECT_NEAR(k.fx, 240.0, 1e-9); // w / (2 tan 45°) + EXPECT_EQ(k.fy, k.fx); + EXPECT_EQ(k.cx, 240.0); + EXPECT_EQ(k.cy, 150.0); +} + +TEST(CameraInfo, StereoProjectionCarriesBaseline) { + const Intrinsics k = IntrinsicsFromFov(480, 300, 90.0); + const auto left = MakeCameraInfo(k, 0.12, false, "camera_left"); + const auto right = MakeCameraInfo(k, 0.12, true, "camera_right"); + EXPECT_EQ(left.header.frame_id, "camera_left"); + EXPECT_EQ(left.distortion_model, "plumb_bob"); + EXPECT_EQ(left.k[0], k.fx); + EXPECT_EQ(left.k[2], k.cx); + // P = [K | 0] for the left camera — never identity (upstream's bug). + EXPECT_EQ(left.p[0], k.fx); + EXPECT_EQ(left.p[3], 0.0); + // REP-104: right camera P[0,3] = -fx * baseline. + EXPECT_NEAR(right.p[3], -k.fx * 0.12, 1e-12); + EXPECT_NEAR(-right.p[3] / right.p[0], 0.12, 1e-12); // what stereo_image_proc reads +} diff --git a/simulation/project-airsim/ros_ws/src/pas_ros_bridge/test/test_decode.cpp b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/test/test_decode.cpp new file mode 100644 index 000000000..b673bbbd1 --- /dev/null +++ b/simulation/project-airsim/ros_ws/src/pas_ros_bridge/test/test_decode.cpp @@ -0,0 +1,236 @@ +// Copyright (c) 2026 Carnegie Mellon University +// SPDX-License-Identifier: BSD-3-Clause-Clear +// +// Decoders against synthetic payloads packed with the same msgpack layouts +// the server uses (core_sim/src/message/*_message.cpp, MSGPACK_DEFINE_MAP). +#include + +#include +#include +#include +#include + +#include "msgpack.hpp" +#include "pas_ros_bridge/decode.hpp" + +using namespace pas_ros_bridge; + +namespace { + +struct Packer { + msgpack::sbuffer buf; + msgpack::packer pk{buf}; + std::string str() const { return {buf.data(), buf.size()}; } +}; + +std::string PackImage(std::int64_t stamp, std::uint32_t w, std::uint32_t h, const std::string& enc, + const std::vector& data) { + Packer p; + p.pk.pack_map(7); + p.pk.pack(std::string("time_stamp")); p.pk.pack(stamp); + p.pk.pack(std::string("height")); p.pk.pack(h); + p.pk.pack(std::string("width")); p.pk.pack(w); + p.pk.pack(std::string("encoding")); p.pk.pack(enc); + p.pk.pack(std::string("big_endian")); p.pk.pack(false); + p.pk.pack(std::string("step")); p.pk.pack(1u); // the server really sends 1 + p.pk.pack(std::string("data")); + p.pk.pack_bin(static_cast(data.size())); + p.pk.pack_bin_body(reinterpret_cast(data.data()), + static_cast(data.size())); + return p.str(); +} + +void PackVec3(msgpack::packer& pk, float x, float y, float z) { + pk.pack_map(3); + pk.pack(std::string("x")); pk.pack(x); + pk.pack(std::string("y")); pk.pack(y); + pk.pack(std::string("z")); pk.pack(z); +} + +std::string PackLidar(std::int64_t stamp, const std::vector& xyz, + const std::vector& intensity, float px, float py, float pz, + float qw, float qx, float qy, float qz) { + Packer p; + p.pk.pack_map(4); + p.pk.pack(std::string("time_stamp")); p.pk.pack(stamp); + p.pk.pack(std::string("point_cloud")); p.pk.pack(xyz); + p.pk.pack(std::string("intensity_cloud")); p.pk.pack(intensity); + p.pk.pack(std::string("pose")); + p.pk.pack_map(2); + p.pk.pack(std::string("position")); PackVec3(p.pk, px, py, pz); + p.pk.pack(std::string("orientation")); + p.pk.pack_map(4); + p.pk.pack(std::string("w")); p.pk.pack(qw); + p.pk.pack(std::string("x")); p.pk.pack(qx); + p.pk.pack(std::string("y")); p.pk.pack(qy); + p.pk.pack(std::string("z")); p.pk.pack(qz); + return p.str(); +} + +const float* Points(const sensor_msgs::msg::PointCloud2& c) { + return reinterpret_cast(c.data.data()); +} + +} // namespace + +TEST(Image, BgrPassesThroughWithComputedStep) { + std::vector px(4 * 2 * 3); + for (std::size_t i = 0; i < px.size(); ++i) px[i] = static_cast(i); + sensor_msgs::msg::Image img; + std::string err; + ASSERT_TRUE(DecodeImage(PackImage(1'500'000'000LL, 4, 2, "BGR", px), "camera_left", &img, &err)) + << err; + EXPECT_EQ(img.encoding, "bgr8"); + EXPECT_EQ(img.step, 12u); + EXPECT_EQ(img.data, px); + EXPECT_EQ(img.header.frame_id, "camera_left"); + EXPECT_EQ(img.header.stamp.sec, 1); + EXPECT_EQ(img.header.stamp.nanosec, 500'000'000u); +} + +TEST(Image, DepthBecomes32FC1WithNaN) { + // 2x1: 2.0 m (0x4000), +inf (0x7C00) + const std::vector px{0x00, 0x40, 0x00, 0x7C}; + sensor_msgs::msg::Image img; + std::string err; + ASSERT_TRUE(DecodeImage(PackImage(0, 2, 1, "16FC1", px), "camera_left", &img, &err)) << err; + EXPECT_EQ(img.encoding, "32FC1"); + EXPECT_EQ(img.step, 8u); + float d[2]; + std::memcpy(d, img.data.data(), 8); + EXPECT_EQ(d[0], 2.0f); + EXPECT_TRUE(std::isnan(d[1])); +} + +TEST(Image, RejectsPngAndSizeMismatch) { + sensor_msgs::msg::Image img; + std::string err; + EXPECT_FALSE(DecodeImage(PackImage(0, 1, 1, "PNG", {1, 2, 3}), "c", &img, &err)); + EXPECT_NE(err.find("PNG"), std::string::npos); + EXPECT_FALSE(DecodeImage(PackImage(0, 2, 2, "BGR", {1, 2, 3}), "c", &img, &err)); + EXPECT_FALSE(DecodeImage("not msgpack at all", "c", &img, &err)); +} + +TEST(Lidar, SensorFrameFlipsToFlu) { + sensor_msgs::msg::PointCloud2 cloud; + std::string err; + ASSERT_TRUE(DecodeLidar(PackLidar(42, {1, 2, 3, 4, -5, 6}, {0.5f, 0.25f}, 0, 0, 0, 1, 0, 0, 0), + LidarFrame::kSensor, "ouster", &cloud, &err)) + << err; + ASSERT_EQ(cloud.width, 2u); + ASSERT_EQ(cloud.fields.size(), 4u); // x y z intensity + EXPECT_EQ(cloud.point_step, 16u); + EXPECT_EQ(cloud.row_step, 32u); + EXPECT_EQ(cloud.header.frame_id, "ouster"); + const float* p = Points(cloud); + EXPECT_EQ(p[0], 1); + EXPECT_EQ(p[1], -2); + EXPECT_EQ(p[2], -3); + EXPECT_EQ(p[3], 0.5f); + EXPECT_EQ(p[4], 4); + EXPECT_EQ(p[5], 5); + EXPECT_EQ(p[6], -6); +} + +TEST(Lidar, WorldFrameUsesSensorPose) { + // Sensor at NED (10, 0, -2), yawed +90° (facing east). A world point 3 m + // east of the sensor is 3 m straight ahead in the sensor frame. + const float h = std::sqrt(0.5f); + sensor_msgs::msg::PointCloud2 cloud; + std::string err; + ASSERT_TRUE(DecodeLidar(PackLidar(0, {10, 3, -2}, {}, 10, 0, -2, h, 0, 0, h), + LidarFrame::kWorld, "ouster", &cloud, &err)) + << err; + ASSERT_EQ(cloud.fields.size(), 3u); // intensity count mismatch → dropped + const float* p = Points(cloud); + EXPECT_NEAR(p[0], 3, 1e-5); + EXPECT_NEAR(p[1], 0, 1e-5); + EXPECT_NEAR(p[2], 0, 1e-5); +} + +TEST(Lidar, RejectsRaggedCloud) { + sensor_msgs::msg::PointCloud2 cloud; + std::string err; + EXPECT_FALSE(DecodeLidar(PackLidar(0, {1, 2}, {}, 0, 0, 0, 1, 0, 0, 0), LidarFrame::kSensor, + "ouster", &cloud, &err)); +} + +TEST(Clock, ReadsTimeStamp) { + Packer p; + p.pk.pack_map(1); + p.pk.pack(std::string("time_stamp")); + p.pk.pack(std::int64_t{3'000'000}); + std::int64_t ns = 0; + std::string err; + ASSERT_TRUE(DecodeClock(p.str(), &ns, &err)) << err; + EXPECT_EQ(ns, 3'000'000); +} + +TEST(Kinematics, FlatServiceResultToOdometry) { + const nlohmann::json result = { + {"time_stamp", 2'000'000'000LL}, + {"pose", {{"position", {{"x", 1.0}, {"y", 2.0}, {"z", -3.0}}}, + {"orientation", {{"w", 1.0}, {"x", 0.0}, {"y", 0.0}, {"z", 0.0}}}}}, + {"twist", {{"linear", {{"x", 0.5}, {"y", 0.0}, {"z", -1.0}}}, + {"angular", {{"x", 0.0}, {"y", 0.0}, {"z", 0.1}}}}}, + {"accels", {{"linear", {{"x", 0}, {"y", 0}, {"z", 0}}}, + {"angular", {{"x", 0}, {"y", 0}, {"z", 0}}}}}}; + nav_msgs::msg::Odometry odom; + std::string err; + ASSERT_TRUE(KinematicsJsonToOdometry(result, Vec3{}, "robot_1/map", "robot_1/base_link", &odom, + &err)) + << err; + EXPECT_EQ(odom.header.frame_id, "robot_1/map"); + EXPECT_EQ(odom.child_frame_id, "robot_1/base_link"); + EXPECT_EQ(odom.header.stamp.sec, 2); + EXPECT_DOUBLE_EQ(odom.pose.pose.position.x, 2.0); // east + EXPECT_DOUBLE_EQ(odom.pose.pose.position.y, 1.0); // north + EXPECT_DOUBLE_EQ(odom.pose.pose.position.z, 3.0); // up + EXPECT_DOUBLE_EQ(odom.twist.twist.linear.y, 0.5); + EXPECT_DOUBLE_EQ(odom.twist.twist.linear.z, 1.0); + // Nested (topic-form) results parse identically. + nav_msgs::msg::Odometry nested; + ASSERT_TRUE(KinematicsJsonToOdometry( + {{"time_stamp", 2'000'000'000LL}, + {"kinematics", {{"pose", result["pose"]}, {"twist", result["twist"]}}}}, + Vec3{}, "robot_1/map", "robot_1/base_link", &nested, &err)) + << err; + EXPECT_EQ(nested.pose.pose.position.x, odom.pose.pose.position.x); + EXPECT_FALSE(KinematicsJsonToOdometry({{"pose", 1}}, Vec3{}, "m", "b", &odom, &err)); + // Relative to the robot's spawn: world NED (1, 2, -3) seen from a spawn at + // NED (-7, -7, -2.2) is (8, 9, -0.8) NED → ENU (9, 8, 0.8). + ASSERT_TRUE(KinematicsJsonToOdometry(result, Vec3{-7, -7, -2.2}, "m", "b", &odom, &err)) << err; + EXPECT_NEAR(odom.pose.pose.position.x, 9.0, 1e-12); + EXPECT_NEAR(odom.pose.pose.position.y, 8.0, 1e-12); + EXPECT_NEAR(odom.pose.pose.position.z, 0.8, 1e-12); +} + +namespace { +sensor_msgs::msg::PointCloud2 Ring(std::int64_t stamp_ns, std::vector xyz) { + sensor_msgs::msg::PointCloud2 c; + std::string err; + DecodeLidar(PackLidar(stamp_ns, xyz, {}, 0, 0, 0, 1, 0, 0, 0), LidarFrame::kSensor, "ouster", + &c, &err); + return c; +} +} // namespace + +TEST(Sweep, AccumulatesOnePeriodAndDropsRepeats) { + SweepAccumulator acc(0.1); // 10 Hz + sensor_msgs::msg::PointCloud2 out; + EXPECT_FALSE(acc.Add(Ring(0, {1, 0, 0}), &out)); + EXPECT_FALSE(acc.Add(Ring(25'000'000, {1, 0, 0}), &out)); // exact repeat + EXPECT_EQ(acc.duplicates(), 1u); + EXPECT_FALSE(acc.Add(Ring(50'000'000, {2, 0, 0, 3, 0, 0}), &out)); + EXPECT_FALSE(acc.Add(Ring(90'000'000, {4, 0, 0}), &out)); // still slot 0 [0, 100 ms) + // First ring of slot 1 emits slot 0's sweep and starts the next one. + ASSERT_TRUE(acc.Add(Ring(130'000'000, {5, 0, 0}), &out)); + EXPECT_EQ(out.width, 4u); // 1 + 2 + 1, repeat excluded + EXPECT_EQ(out.row_step, out.point_step * 4); + EXPECT_EQ(out.data.size(), out.row_step); + EXPECT_EQ(out.header.stamp.nanosec, 90'000'000u); + EXPECT_EQ(Points(out)[0], 1.0f); + EXPECT_EQ(Points(out)[9], 4.0f); + ASSERT_TRUE(acc.Add(Ring(200'000'000, {6, 0, 0}), &out)); + EXPECT_EQ(out.width, 1u); // slot 1 held only the 130 ms ring +} diff --git a/simulation/resolve_scene.py b/simulation/resolve_scene.py index deab74037..3b8ac6551 100644 --- a/simulation/resolve_scene.py +++ b/simulation/resolve_scene.py @@ -6,7 +6,7 @@ availability table on stderr and exits 1. Usage: - resolve_scene.py --sim isaac|msairsim --scene NAME # emit export lines + resolve_scene.py --sim isaac|msairsim|projectairsim --scene NAME # emit export lines resolve_scene.py --table # print the table """ @@ -21,8 +21,14 @@ SIM_ALIASES = { "isaac": "isaac", "isaacsim": "isaac", "isaac-sim": "isaac", "airsim": "msairsim", "msairsim": "msairsim", "ms-airsim": "msairsim", + "projectairsim": "projectairsim", "pas": "projectairsim", + "project-airsim": "projectairsim", } -SIM_LABELS = {"isaac": "Isaac", "msairsim": "MS AirSim"} +SIMS = ("isaac", "msairsim", "projectairsim") +SIM_LABELS = {"isaac": "Isaac", "msairsim": "MS AirSim", "projectairsim": "Project AirSim"} +# The env var each simulator's container reads its scene from (isaac adds +# ISAAC_SIM_STAGE_SCALE, see main()). +SIM_EXPORTS = {"msairsim": "MS_AIRSIM_SCENE", "projectairsim": "PROJECT_AIRSIM_ENV"} def load_catalog(path=CATALOG): @@ -57,13 +63,11 @@ def short_ref(sim, spec): def print_table(scenes, out=sys.stderr): - rows = [("SCENE", SIM_LABELS["isaac"].upper(), SIM_LABELS["msairsim"].upper())] + rows = [("SCENE",) + tuple(SIM_LABELS[s].upper() for s in SIMS)] for name in sorted(scenes): entry = scenes[name] or {} - rows.append((name, - short_ref("isaac", entry.get("isaac")), - short_ref("msairsim", entry.get("msairsim")))) - widths = [max(len(r[i]) for r in rows) for i in range(3)] + rows.append((name,) + tuple(short_ref(s, entry.get(s)) for s in SIMS)) + widths = [max(len(r[i]) for r in rows) for i in range(len(rows[0]))] for i, r in enumerate(rows): print(" ".join(c.ljust(w) for c, w in zip(r, widths)).rstrip(), file=out) if i == 0: @@ -101,7 +105,7 @@ def main(): print(f"ERROR: unknown scene '{args.scene}'. Available scenes:", file=sys.stderr) else: - others = [SIM_LABELS[s] for s in ("isaac", "msairsim") + others = [SIM_LABELS[s] for s in SIMS if s != sim and entry.get(s) is not None] print(f"ERROR: scene '{args.scene}' is not available for " f"{SIM_LABELS[sim]} (only: {', '.join(others) or 'none'}). " @@ -114,7 +118,7 @@ def main(): print(f"ISAAC_SIM_SCENE={ref}") print(f"ISAAC_SIM_STAGE_SCALE={scale}") else: - print(f"MS_AIRSIM_SCENE={spec}") + print(f"{SIM_EXPORTS[sim]}={spec}") return 0 diff --git a/simulation/scenes.yaml b/simulation/scenes.yaml index a1f549990..43b4ebe70 100644 --- a/simulation/scenes.yaml +++ b/simulation/scenes.yaml @@ -13,16 +13,20 @@ # # 0.01 converts cm-authored stages to meters # msairsim: # fetch_scene.sh catalog key (pre-built UE4 # # binary downloaded on first use) +# projectairsim: # fetch_env.sh catalog key (packaged UE5 +# # environment downloaded on first use) # # `airstack up --sim isaac --scene ` exports ISAAC_SIM_SCENE (+ # ISAAC_SIM_STAGE_SCALE); `--sim airsim --scene ` exports -# MS_AIRSIM_SCENE. Launch scripts / entrypoints do the final resolution. +# MS_AIRSIM_SCENE; `--sim projectairsim --scene ` exports +# PROJECT_AIRSIM_ENV. Launch scripts / entrypoints do the final resolution. scenes: # ── Pegasus SIMULATION_ENVIRONMENTS catalog (NVIDIA Isaac assets) ───────── default: isaac: Default Environment msairsim: blocks + projectairsim: blocks black-gridroom: isaac: Black Gridroom curved-gridroom: @@ -85,15 +89,24 @@ scenes: # Only the UE4 binaries that actually ship in the AirSim v1.8.1 release. blocks: msairsim: blocks + projectairsim: blocks neighborhood: msairsim: airsimnh + projectairsim: neighborhood abandoned-park: msairsim: abandonedpark landscape-mountains: msairsim: landscapemountains + projectairsim: landscapemountains zhangjiajie: msairsim: zhangjiajie africa-savannah: msairsim: africasavannah msbuild2018: msairsim: msbuild2018 + + # ── Project AirSim packaged UE5 environments (fetch_env.sh) ─────────────── + # The v1.1.0 release's Linux environments; blocks / neighborhood / + # landscape-mountains above are shared with the MS AirSim entries. + city-environ: + projectairsim: cityenviron diff --git a/tests/README.md b/tests/README.md index 6401b1602..480f1f7c5 100644 --- a/tests/README.md +++ b/tests/README.md @@ -19,11 +19,11 @@ Pytest hooks and the shared fixtures live in `tests/conftest.py`; reusable helpe | Module | Mark | What it tests | Hardware required | |--------|------|---------------|-------------------| -| [`system/test_build_docker.py`](system/test_build_docker.py) | `build_docker` | Docker image builds (robot-desktop, gcs, isaac-sim, ms-airsim); records image sizes | Docker daemon | -| [`system/test_build_packages.py`](system/test_build_packages.py) | `build_packages` | `colcon build` inside each container (robot, GCS, ms-airsim ROS workspace) | Docker daemon | +| [`system/test_build_docker.py`](system/test_build_docker.py) | `build_docker` | Docker image builds (robot-desktop, gcs, isaac-sim, ms-airsim, project-airsim); records image sizes | Docker daemon | +| [`system/test_build_packages.py`](system/test_build_packages.py) | `build_packages` | `colcon build` inside each container (robot, GCS, ms-airsim and project-airsim ROS workspaces) | Docker daemon | | [`system/test_wiring_snapshot.py`](system/test_wiring_snapshot.py) | `wiring` | Observed wiring snapshot of the running ROS graph (via [`wiring_snapshot.py`](wiring_snapshot.py)), drift-checked against the stack's committed `stacks//wiring.md`; writes the observed snapshot to `/wiring/` | Docker daemon, GPU, sim license | | [`system/test_liveliness.py`](system/test_liveliness.py) | `liveliness` | Stack bring-up: container Running state, ``/clock`` readiness, tmux panes, sentinel ROS 2 nodes, compute snapshot, infra-only ``test_stable`` (tmux + nodes + compute) | Docker daemon, GPU, sim license | -| [`system/test_sensors.py`](system/test_sensors.py) | `sensors` | After liveliness in collection order: sim + robot stereo/depth Hz (**Isaac:** batched ``ros2 topic hz`` to avoid bridge overload; **ms-airsim:** single batch), filtered LiDAR via ``echo --once`` + cloud sanity (isaacsim), sim RTF, ``test_sensor_streams_stable`` | Docker daemon, GPU, sim license | +| [`system/test_sensors.py`](system/test_sensors.py) | `sensors` | After liveliness in collection order: sim + robot stereo/depth Hz (**Isaac:** batched ``ros2 topic hz`` to avoid bridge overload; **ms-airsim, project-airsim:** single batch), filtered LiDAR via ``echo --once`` + cloud sanity (LiDAR sims: isaacsim, projectairsim), sim RTF, ``test_sensor_streams_stable`` | Docker daemon, GPU, sim license | | [`system/test_takeoff_hover_land.py`](system/test_takeoff_hover_land.py) | `takeoff_hover_land` | End-to-end flight: PX4 readiness gate, takeoff to 10 m, hover stability, land — one chain per (sim, num_robots, iteration, velocity) | Docker daemon, GPU, sim license | | [`system/test_fixed_trajectory.py`](system/test_fixed_trajectory.py) | `autonomy` | Fixed-pattern trajectory evaluation: takeoff, execute a trajectory (Circle, Figure8, Racetrack, Line), record path deviation metrics, land — one chain per (sim, num_robots, iteration, trajectory_type) | Docker daemon, GPU, sim license | | [`system/test_waypoint_flight.py`](system/test_waypoint_flight.py) | `waypoint_flight` | Ordered-waypoint navigation: takeoff, send a waypoint route to `NavigateTask`, judge the odometry track with the standalone [`waypoint_checker.py`](waypoint_checker.py), land — one chain per (sim, num_robots, iteration) | Docker daemon, GPU, sim license | @@ -127,8 +127,8 @@ and are driven by [`system/test_sensors.py`](system/test_sensors.py): | Path | What we measure | How | |------|-----------------|-----| | Sim → `/clock`, stereo images, stereo depth | Publish rate | ``ros2 topic hz`` on the sim container: ``/clock`` alone, then **chunks of two** ``image_rect`` topics, then **chunks of two** depth topics (``ISAACSIM_HZ_CHUNK_SIZE`` in ``sensor_probes.py``). | -| Robot → same topic names (bridge) | Publish rate | Same **two-at-a-time** chunking on the robot container for Isaac. ms-airsim: one batch of four topics. | -| Robot → filtered ``.../ouster/point_cloud`` | Stream alive | ``ros2 topic echo --once`` per robot (not Hz — large ``PointCloud2``). | +| Robot → same topic names (bridge) | Publish rate | Same **two-at-a-time** chunking on the robot container for Isaac. ms-airsim / project-airsim: one batch of four topics. | +| Robot → filtered ``.../ouster/point_cloud`` (isaacsim, projectairsim) | Stream alive | ``ros2 topic echo --once`` per robot (not Hz — large ``PointCloud2``). | | LiDAR geometry | Near-range vs ``near_range_m`` | ``robot/ros_ws/src/sensors/lidar_point_cloud_filter/scripts/validate_lidar_filter_clouds.py`` (raw vs filtered). | Sim **RTF** (real-time factor from ``/clock``) is also in the `sensors` suite. @@ -252,7 +252,7 @@ pytest tests/ -m sensors \ | Option | Default | Description | |--------|---------|-------------| -| `--sim` | `isaacsim` | Comma-separated sim targets (`msairsim` opt-in) | +| `--sim` | `isaacsim` | Comma-separated sim targets (`msairsim`, `projectairsim` opt-in) | | `--num-robots` | `1,3` | Comma-separated robot counts | | `--stack` | _(none)_ | Stack folder under `stacks/` to launch (sets `AIRSTACK_STACK_DIR`); default dispatch is `stacks/full_default`. The `wiring` mark drift-checks against `stacks//wiring.md` | | `--fleet` | _(none)_ | Fleet preset under `config/fleets/` (sets `FLEET_CONFIG_FILE`); derives `NUM_ROBOTS` from the fleet's robot count, overriding `--num-robots` | diff --git a/tests/conftest.py b/tests/conftest.py index 9d34388a3..f903901e1 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -24,8 +24,8 @@ def pytest_addoption(parser): parser.addoption("--sim", default="isaacsim", help="Comma-separated sim targets: isaacsim, msairsim, " - "simplesim. Default isaacsim; pass --sim msairsim " - "to opt in. simplesim only drives the simple_sim " + "projectairsim, simplesim. Default isaacsim; pass " + "--sim msairsim or --sim projectairsim to opt in. simplesim only drives the simple_sim " "smoke test (-m simple_sim).") parser.addoption("--num-robots", default="1,3", help="Comma-separated robot counts, e.g. 1,3") @@ -269,6 +269,7 @@ def airstack_env(request): # robot-desktop, so the desktop profile must stay off (see SIM_CONFIG). "COMPOSE_PROFILES": cfg.get("compose_profiles", f"desktop,{cfg['profile']}"), "MS_AIRSIM_HEADLESS": "true" if headless else "false", + "PROJECT_AIRSIM_HEADLESS": "true" if headless else "false", "ISAAC_SIM_HEADLESS": "true" if headless else "false", } if headless: diff --git a/tests/harness/diagnostics.py b/tests/harness/diagnostics.py index 554120669..a646a5548 100644 --- a/tests/harness/diagnostics.py +++ b/tests/harness/diagnostics.py @@ -22,6 +22,11 @@ "MS_AIRSIM_HEADLESS", "MS_AIRSIM_ENV_DIR", "MS_AIRSIM_BINARY_PATH", + "PROJECT_AIRSIM_HEADLESS", + "PROJECT_AIRSIM_PHYSICS", + "PROJECT_AIRSIM_ENV", + "PROJECT_AIRSIM_ENV_DIR", + "PROJECT_AIRSIM_BINARY_PATH", "PX4_PARAM_SET", ) diff --git a/tests/harness/sim.py b/tests/harness/sim.py index e0cc76972..cc2428ca4 100644 --- a/tests/harness/sim.py +++ b/tests/harness/sim.py @@ -24,11 +24,29 @@ "MS_AIRSIM_BINARY_PATH": "", }, }, + # Project AirSim (UE5): one container runs the packaged env, PX4 SITL and + # the C++ pas_ros_bridge, which publishes the same stereo/depth topics as + # ms-airsim PLUS the raw Ouster-style LiDAR (has_lidar → the filtered + # LiDAR liveliness/sanity probes run, as on Isaac). + "projectairsim": { + "profile": "project-airsim", + "sim_container": "project-airsim", + "sim_setup_bash": "/root/ros_ws/install/setup.bash", + "robot_setup_bash": "/root/AirStack/robot/ros_ws/install/setup.bash", + "has_lidar": True, + "extra_env": { + "URDF_FILE": "robot_descriptions/iris/urdf/iris_stereo_lidar.project-airsim.urdf", + # Clear user-set paths in .env so the entrypoint auto-fetches Blocks. + "PROJECT_AIRSIM_ENV_DIR": "", + "PROJECT_AIRSIM_BINARY_PATH": "", + }, + }, "isaacsim": { "profile": "isaac-sim", "sim_container": "isaac-sim", "sim_setup_bash": "/opt/ros/jazzy/setup.bash", "robot_setup_bash": "/root/AirStack/robot/ros_ws/install/setup.bash", + "has_lidar": True, "extra_env": { "ISAAC_SIM_USE_STANDALONE": "true", "ISAAC_SIM_SCRIPT_NAME": "example_multi_px4_pegasus_launch_script.py", diff --git a/tests/meta/test_docker_layer_plan_contract.py b/tests/meta/test_docker_layer_plan_contract.py index 2415ae881..27c0591b5 100644 --- a/tests/meta/test_docker_layer_plan_contract.py +++ b/tests/meta/test_docker_layer_plan_contract.py @@ -138,7 +138,7 @@ def test_identity_rule_dep_free_module(planner, overlay, tmp_path, capsys): assert planner.main(["--project-root", str(root)]) == 0 plan = read_plan(root) - assert set(plan) == {"robot", "gcs", "isaac-sim", "ms-airsim"} + assert set(plan) == {"robot", "gcs", "isaac-sim", "ms-airsim", "project-airsim"} for host, entry in plan.items(): assert entry["steps"] == [], f"{host} has steps for a dep-free module" assert entry["final_tag"] == entry["base_image"] @@ -222,7 +222,7 @@ def test_heavy_module_tier1_then_tier2(planner, tmp_path): assert robot["final_tag"] == f"{ROBOT_BASE}-m{lock['plan_hash'][:8]}" # hosts the module does not target stay identity - for host in ("gcs", "isaac-sim", "ms-airsim"): + for host in ("gcs", "isaac-sim", "ms-airsim", "project-airsim"): assert plan[host]["steps"] == [] assert plan[host]["final_tag"] == plan[host]["base_image"] diff --git a/tests/meta/test_launch_intent_contract.py b/tests/meta/test_launch_intent_contract.py index 8f15ad20c..600569898 100644 --- a/tests/meta/test_launch_intent_contract.py +++ b/tests/meta/test_launch_intent_contract.py @@ -340,3 +340,58 @@ def test_override_l4t_px4_realrobot_env_still_derives_expected_config(): # pins the full stack explicitly and must not draw the removal error assert cfg["AIRSTACK_STACK_DIR"] == "/root/AirStack/stacks/full_default" assert "AUTONOMY_ROLE was removed" not in out + + +# ── Project AirSim (--sim projectairsim, --physics) ─────────────────────────── + +@pytest.mark.parametrize("alias", ["projectairsim", "pas", "project-airsim"]) +def test_sim_projectairsim_derives_profile_and_urdf(alias): + _, out, cfg = run_up_dry("--sim", alias) + profiles = cfg["COMPOSE_PROFILES"].split(",") + assert "project-airsim" in profiles and "desktop" in profiles + assert "ms-airsim" not in profiles and "isaac-sim" not in profiles + assert cfg["URDF_FILE"].endswith("iris_stereo_lidar.project-airsim.urdf") + # Its keys appear only when it is the selected simulator. + assert "PROJECT_AIRSIM_HEADLESS" in cfg + assert "project-airsim: env=blocks physics=fast-physics" in out + + +def test_projectairsim_keys_absent_for_other_sims(): + """The other simulators' effective config stays byte-identical.""" + for sim in ("airsim", "isaac"): + _, _, cfg = run_up_dry("--sim", sim) + assert not any(k.startswith("PROJECT_AIRSIM_") for k in cfg), sim + + +def test_physics_flag_exports_and_requires_projectairsim(): + _, _, cfg = run_up_dry("--sim", "projectairsim", "--physics", "jsbsim") + assert cfg["PROJECT_AIRSIM_PHYSICS"] == "jsbsim" + code, out, _ = run_up_dry("--sim", "isaac", "--physics", "jsbsim", check=False) + assert code != 0 and "--physics selects Project AirSim" in out + code, out, _ = run_up_dry("--sim", "projectairsim", "--physics", "bullet", check=False) + assert code != 0 and "Unknown --physics 'bullet'" in out + + +def test_headless_covers_projectairsim(): + _, _, cfg = run_up_dry("--sim", "projectairsim", "--headless") + assert cfg["PROJECT_AIRSIM_HEADLESS"] == "true" + + +def test_projectairsim_scene_maps_to_env_key(): + _, _, cfg = run_up_dry("--sim", "projectairsim", "--scene", "neighborhood", + env={"AIRSTACK_ASSUME_YES": "1"}) + assert cfg["PROJECT_AIRSIM_ENV"] == "neighborhood" + code, out, _ = run_up_dry("--sim", "projectairsim", "--scene", "hospital", check=False) + assert code != 0 and "not available for Project AirSim" in out + + +def test_projectairsim_env_file_override(): + _, _, cfg = run_up_dry("--env-file", "overrides/project-airsim.env") + assert "project-airsim" in cfg["COMPOSE_PROFILES"].split(",") + assert cfg["URDF_FILE"].endswith("iris_stereo_lidar.project-airsim.urdf") + + +def test_two_sim_profiles_rejected_including_projectairsim(): + code, out, _ = run_up_dry(env={"COMPOSE_PROFILES": "desktop,ms-airsim,project-airsim"}, + check=False) + assert code != 0 and "Only one simulator profile" in out diff --git a/tests/meta/test_project_airsim_scene_contract.py b/tests/meta/test_project_airsim_scene_contract.py new file mode 100644 index 000000000..d04365642 --- /dev/null +++ b/tests/meta/test_project_airsim_scene_contract.py @@ -0,0 +1,333 @@ +# Copyright (c) 2026 Carnegie Mellon University +# SPDX-License-Identifier: BSD-3-Clause-Clear +"""Contract tests for the Project AirSim scene generator. + +``simulation/project-airsim/config/generate_scene.py`` turns env knobs (and an +optional fleet file) into the one scene the sim loads plus +``airstack_meta.json`` for the entrypoint and the C++ bridge. Pins: + +- **Port plan** — robot i gets PX4 HIL TCP 4560+i and a DECOY Project AirSim + control link on UDP 24540+i; nothing in the sim binds MAVROS's 14540+i / + 14580+i (Project AirSim's upstream control-port default 14540 would steal + robot_1's MAVROS link). +- **Physics selection** — fast-physics by default; jsbsim selectable; the + resolution order is env > fleet robot > fleet sim > vehicle > default; + unknown names are named errors; the two variants differ ONLY in dynamics + (same sensors, same PX4 settings). +- **Geometry = URDF** — sensor origins in the scene (NED/FRD) equal the + ``iris_stereo_lidar.project-airsim.urdf`` joints (FLU) the robot's + robot_state_publisher broadcasts. +- **Meta** — intrinsics/baseline the bridge publishes in camera_info match the + scene's camera settings. +""" +import importlib.util +import json +import math +import xml.etree.ElementTree as ET + +import pytest +import yaml + +from harness.discovery import repo_path + +pytestmark = pytest.mark.unit + +REPO = repo_path() +GEN_PATH = REPO / "simulation" / "project-airsim" / "config" / "generate_scene.py" +URDF = (REPO / "common" / "ros_packages" / "robot_descriptions" / "iris" / "urdf" + / "iris_stereo_lidar.project-airsim.urdf") + + +@pytest.fixture(scope="module") +def gen(): + spec = importlib.util.spec_from_file_location("pas_generate_scene", GEN_PATH) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +def _generate(gen, tmp_path, **env): + scene, meta = gen.generate({k: str(v) for k, v in env.items()}, tmp_path, str(REPO)) + # Files on disk are valid JSON and equal the returned objects. + assert json.loads((tmp_path / "scene_airstack.jsonc").read_text()) == scene + assert json.loads((tmp_path / "airstack_meta.json").read_text()) == meta + return scene, meta + + +def _px4(actor): + return actor["robot-config"]["controller"]["px4-settings"] + + +def _sensors(actor): + return {s["id"]: s for s in actor["robot-config"]["sensors"]} + + +def _xyz(s): + return tuple(float(v) for v in s.split()) + + +def _list(s): + return [float(v) for v in s.split()] + + +# ── port plan ──────────────────────────────────────────────────────────────── + +def test_single_robot_defaults(gen, tmp_path): + scene, meta = _generate(gen, tmp_path) + assert scene["clock"]["type"] == "steppable" + (actor,) = scene["actors"] + assert actor["name"] == "robot_1" and actor["start-landed"] is True + # robot-config is inlined so the loader needs no sim_config directory + assert isinstance(actor["robot-config"], dict) + px4 = _px4(actor) + assert px4["lock-step"] and px4["use-tcp"] + assert px4["tcp-port"] == 4561 + assert px4["control-ip-address"] == "127.0.0.1" + assert px4["control-port-local"] == 24541 + assert meta["robots"][0]["mavros_offboard_ports"] == [14541, 14581] + assert actor["robot-config"]["physics-type"] == "fast-physics" + + +def test_multi_robot_ports_unique_and_never_mavros(gen, tmp_path): + scene, meta = _generate(gen, tmp_path, NUM_ROBOTS=3) + names = [a["name"] for a in scene["actors"]] + assert names == ["robot_1", "robot_2", "robot_3"] + used = [] + for i, actor in enumerate(scene["actors"], start=1): + px4 = _px4(actor) + assert px4["tcp-port"] == 4560 + i + used += [px4["tcp-port"], px4["control-port-local"], px4["control-port-remote"]] + assert len(used) == len(set(used)) + mavros = {p for r in meta["robots"] for p in r["mavros_offboard_ports"]} + assert not mavros & set(used), "a sim-side port collides with MAVROS" + assert [r["domain_id"] for r in meta["robots"]] == [1, 2, 3] + + +def test_spawns_follow_legacy_spacing_in_ned(gen, tmp_path): + scene, meta = _generate(gen, tmp_path, NUM_ROBOTS=2, PROJECT_AIRSIM_SPAWN_SPACING=5, + PROJECT_AIRSIM_SPAWN_ORIGIN="0,0,0") + # ENU x spacing → NED y (matches the legacy ms-airsim settings.json "Y"). + assert _xyz(scene["actors"][1]["origin"]["xyz"]) == (0.0, 5.0, -0.0) + assert meta["robots"][1]["spawn_ned"] == [0.0, 5.0, -0.0] + + +def test_blocks_spawns_clear_of_the_origin_block(gen, tmp_path): + """The Unreal world origin is inside geometry in Blocks (surveyed + 2026-11-30): the default env anchors spawns at the surveyed clear point, + and ground truth is reported relative to each robot's own spawn.""" + scene, meta = _generate(gen, tmp_path, NUM_ROBOTS=3) + assert meta["env"] == "blocks" and meta["spawn_origin_source"].startswith("surveyed") + xs = {_xyz(a["origin"]["xyz"])[0] for a in scene["actors"]} + # One line at x = -38: the route box ahead ends 1 m short of the origin + # block (x >= -2). + assert xs == {-38.0} + assert [r["spawn_ned"] for r in meta["robots"]] == [ + _list(a["origin"]["xyz"]) for a in scene["actors"]] + _, meta = _generate(gen, tmp_path, PROJECT_AIRSIM_ENV="neighborhood") + assert meta["spawn_origin_source"] == "surveyed (neighborhood)" + _, meta = _generate(gen, tmp_path, PROJECT_AIRSIM_ENV="cityenviron") + assert meta["spawn_origin_source"].startswith("unverified") + _, meta = _generate(gen, tmp_path, PROJECT_AIRSIM_SPAWN_ORIGIN="1,2,-3") + assert meta["spawn_origin_ned"] == [1.0, 2.0, -3.0] + with pytest.raises(gen.ConfigError, match="x,y,z"): + _generate(gen, tmp_path, PROJECT_AIRSIM_SPAWN_ORIGIN="1,2") + + +# ── physics selection ──────────────────────────────────────────────────────── + +def test_physics_resolution_order(gen): + r = gen.resolve_physics + assert r() == ("fast-physics", "default") + assert r("", None, None, "jsbsim")[0] == "jsbsim" + assert r("", None, "jsbsim", "fast-physics")[0] == "jsbsim" + assert r("", "fast-physics", "jsbsim", "jsbsim")[0] == "fast-physics" + assert r("jsbsim", "fast-physics", "fast-physics", "fast-physics") == ( + "jsbsim", "PROJECT_AIRSIM_PHYSICS") + + +def test_unknown_physics_is_a_named_error(gen, tmp_path): + with pytest.raises(gen.ConfigError, match="fast-physics, jsbsim"): + _generate(gen, tmp_path, PROJECT_AIRSIM_PHYSICS="bullet") + assert gen.main(["--out", str(tmp_path / "x")]) == 0 # sanity: defaults OK + + +def test_jsbsim_differs_only_in_dynamics(gen, tmp_path): + fast, _ = _generate(gen, tmp_path / "fast") + jsb, meta = _generate(gen, tmp_path / "jsb", PROJECT_AIRSIM_PHYSICS="jsbsim") + f, j = fast["actors"][0]["robot-config"], jsb["actors"][0]["robot-config"] + assert j["physics-type"] == "jsbsim-physics" and j["jsbsim-model"] == "quadrotor_x" + assert j["jsbsim-root-path"] == "/SimLibs/jsbsim/models/" + assert meta["robots"][0]["physics"] == "jsbsim" + for act in j["actuators"]: + assert act["rotor-settings"]["jsbsim-cmd"].startswith("fcs/esc-cmd-norm[") + assert f["sensors"] == j["sensors"] + assert f["controller"] == j["controller"] + assert f["links"] == j["links"] + # Every ESC index 0..3 is driven exactly once. + escs = sorted(a["rotor-settings"]["jsbsim-cmd"] for a in j["actuators"]) + assert escs == [f"fcs/esc-cmd-norm[{k}]" for k in range(4)] + + +def test_fleet_physics_per_robot(gen, tmp_path): + fleet = { + "defaults": {"vehicle": "quad_default", "stack": "stacks/full_default"}, + "robots": {"robot_1": {"spawn": [0, 0, 0]}, + "robot_2": {"spawn": [4, 2, 0], "physics": "jsbsim"}}, + "sim": {"scene": "default", "physics": "fast-physics"}, + } + path = tmp_path / "fleet.yaml" + path.write_text(yaml.safe_dump(fleet)) + scene, meta = _generate(gen, tmp_path / "out", FLEET_CONFIG_FILE=path, + PROJECT_AIRSIM_SPAWN_ORIGIN="0,0,0") + phys = {r["name"]: (r["physics"], r["physics_source"]) for r in meta["robots"]} + assert phys == {"robot_1": ("fast-physics", "fleet sim.physics"), + "robot_2": ("jsbsim", "fleet robots..physics")} + assert _xyz(scene["actors"][1]["origin"]["xyz"]) == (2.0, 4.0, -0.0) + # Env override beats the fleet for every robot. + _, meta = _generate(gen, tmp_path / "out2", FLEET_CONFIG_FILE=path, + PROJECT_AIRSIM_PHYSICS="jsbsim") + assert {r["physics"] for r in meta["robots"]} == {"jsbsim"} + + +def test_bad_numbers_are_named_errors(gen, tmp_path): + with pytest.raises(gen.ConfigError, match="PROJECT_AIRSIM_CAM_WIDTH"): + _generate(gen, tmp_path, PROJECT_AIRSIM_CAM_WIDTH="wide") + with pytest.raises(gen.ConfigError, match="NUM_ROBOTS"): + _generate(gen, tmp_path, NUM_ROBOTS=0) + + +# ── geometry ───────────────────────────────────────────────────────────────── + +def _urdf_joints(): + root = ET.parse(URDF).getroot() + return {j.find("child").get("link"): _xyz(j.find("origin").get("xyz")) + for j in root.findall("joint")} + + +def test_sensor_geometry_matches_urdf(gen, tmp_path): + scene, _ = _generate(gen, tmp_path) + sensors = _sensors(scene["actors"][0]) + joints = _urdf_joints() + + def flu(frd): # body FRD → FLU + x, y, z = frd + return (x, -y, -z) + + for sensor_id, link in (("front_left", "camera_left"), ("front_right", "camera_right"), + ("ouster", "ouster")): + got = flu(_xyz(sensors[sensor_id]["origin"]["xyz"])) + assert got == pytest.approx(joints[link], abs=1e-9), sensor_id + assert _xyz(sensors["ouster"]["origin"]["rpy-deg"]) == (0.0, 0.0, 0.0) + + +def test_cameras_capture_rgb_and_depth(gen, tmp_path): + scene, _ = _generate(gen, tmp_path, PROJECT_AIRSIM_CAM_RATE=25) + for cam in ("front_left", "front_right"): + s = _sensors(scene["actors"][0])[cam] + types = [c["image-type"] for c in s["capture-settings"]] + assert types == [0, 1] # scene + depth planar + assert all(c["capture-enabled"] and not c["compress"] for c in s["capture-settings"]) + assert s["capture-interval"] == pytest.approx(0.04) + + +def test_lidar_defaults_match_isaac_os1_and_can_be_disabled(gen, tmp_path): + scene, meta = _generate(gen, tmp_path) + lidar = _sensors(scene["actors"][0])["ouster"] + assert lidar["lidar-type"] == "gpu_cylindrical" + assert lidar["number-of-channels"] == 128 # Isaac OS1_REV6_128ch10hz512res + assert lidar["points-per-second"] == 128 * 512 * 10 + assert lidar["horizontal-rotation-frequency"] == 10 + scene, meta = _generate(gen, tmp_path, PROJECT_AIRSIM_LIDAR="false") + assert "ouster" not in _sensors(scene["actors"][0]) + assert meta["lidar"]["enabled"] is False + + +def test_empty_compose_passthrough_means_default(gen, tmp_path): + """docker compose passes an unset ``${VAR:-}`` as ''. An empty string knob + must mean "default", not a literal '' (an empty lidar-type silently picks + Project AirSim's CPU raycast LiDAR, which stalls dense scenes).""" + scene, meta = _generate(gen, tmp_path, PROJECT_AIRSIM_LIDAR_TYPE="", + PROJECT_AIRSIM_LIDAR="", PROJECT_AIRSIM_START_LANDED="", + PROJECT_AIRSIM_JSBSIM_MODEL="") + assert _sensors(scene["actors"][0])["ouster"]["lidar-type"] == "gpu_cylindrical" + assert meta["lidar"]["enabled"] is True + + +def test_meta_intrinsics_and_baseline(gen, tmp_path): + _, meta = _generate(gen, tmp_path, PROJECT_AIRSIM_CAM_WIDTH=640, + PROJECT_AIRSIM_CAM_HEIGHT=480, PROJECT_AIRSIM_CAM_FOV=90) + cam = meta["camera"] + assert cam["fx"] == pytest.approx(640 / (2 * math.tan(math.radians(45)))) + assert (cam["cx"], cam["cy"]) == (320.0, 240.0) + assert cam["baseline"] == pytest.approx(0.12) + + +# ── bridge topic map ───────────────────────────────────────────────────────── + +def test_stream_map_is_airstacks_sensor_contract(gen, tmp_path): + """The bridge publishes exactly the topics the harness probes + (tests/sensor_probes.py) and the stacks consume — nothing else.""" + from sensor_probes import ROBOT_LIDAR_TOPIC_TEMPLATES, STEREO_DEPTH_TOPIC_TEMPLATES + + scene, meta = _generate(gen, tmp_path, NUM_ROBOTS=2) + sensors_by_robot = {a["name"]: _sensors(a) for a in scene["actors"]} + for n, robot in enumerate(meta["robots"], start=1): + ros = {s["ros_topic"] for s in robot["streams"]} + expected = {t.replace("{N}", str(n)) for t in STEREO_DEPTH_TOPIC_TEMPLATES} + # The bridge publishes the RAW cloud; lidar_point_cloud_filter makes + # the filtered .../point_cloud the harness probes. + expected |= {t.replace("{N}", str(n)) + "_raw" for t in ROBOT_LIDAR_TOPIC_TEMPLATES} + assert ros == expected + assert robot["odom_topic"] == f"/robot_{n}/odom_ground_truth" + # Every PAS topic names a sensor that really exists on that robot. + for s in robot["streams"]: + parts = s["pas_topic"].split("/") + assert parts[:5] == ["", "Sim", meta["scene_id"], "robots", robot["name"]] + assert parts[6] in sensors_by_robot[robot["name"]] + assert meta["clock_topic"] == f"/Sim/{meta['scene_id']}/clock" + # Exactly one right camera per robot, used for the P[0,3] baseline term. + assert [s["right"] for s in meta["robots"][0]["streams"] if s["kind"] == "image"] == [False, True] + + +def test_every_robot_urdf_survives_launch_ros_yaml_parse(): + """launch_ros YAML-parses robot_description: a URDF whose text reads as a + YAML mapping (e.g. a comment containing 'word: word') aborts the whole + robot launch with "Unable to parse the value of parameter + robot_description as yaml". Every URDF must load as a plain string.""" + urdf_dir = URDF.parent + for path in sorted(urdf_dir.glob("*.urdf")): + assert isinstance(yaml.safe_load(path.read_text()), str), path.name + + +def test_lumen_and_chase_camera_knobs(gen, tmp_path): + scene, meta = _generate(gen, tmp_path) + s = _sensors(scene["actors"][0]) + assert "chase" not in s + assert "lumen-gi-enabled" not in s["front_left"]["capture-settings"][0] # project default + scene, meta = _generate(gen, tmp_path, PROJECT_AIRSIM_LUMEN="true", + PROJECT_AIRSIM_CHASE_CAM="true") + s = _sensors(scene["actors"][0]) + rgb, depth = s["front_left"]["capture-settings"] + assert rgb["lumen-gi-enabled"] is True and rgb["lumen-reflections-enabled"] is True + assert "lumen-gi-enabled" not in depth # depth comes from a replacement material + assert s["chase"]["gimbal"] == {"lock-roll": True, "lock-pitch": True, "lock-yaw": False} + chase = [x for x in meta["robots"][0]["streams"] if x["ros_topic"].endswith("/chase/image")] + assert chase and (chase[0]["width"], chase[0]["height"]) == (1280, 720) + with pytest.raises(gen.ConfigError, match="PROJECT_AIRSIM_LUMEN"): + _generate(gen, tmp_path, PROJECT_AIRSIM_LUMEN="maybe") + + +def test_every_knob_reaches_the_container(): + """Each PROJECT_AIRSIM_* variable the generator or entrypoint reads must be + passed through the compose service, or setting it in .env silently does + nothing (internal plumbing excepted).""" + import re + base = REPO / "simulation" / "project-airsim" + read = set() + for f in (base / "config" / "generate_scene.py", base / "docker" / "entrypoint.sh"): + read |= set(re.findall(r"PROJECT_AIRSIM_[A-Z0-9_]+[A-Z0-9]", f.read_text())) + compose = (base / "docker" / "docker-compose.yaml").read_text() + internal = {"PROJECT_AIRSIM_GENERATED_DIR", "PROJECT_AIRSIM_TOPICS_PORT", + "PROJECT_AIRSIM_SERVICES_PORT"} + missing = sorted(v for v in read - internal if f"- {v}=" not in compose) + assert not missing, f"read but not passed through compose: {missing}" diff --git a/tests/sensor_probes.py b/tests/sensor_probes.py index 140e10c0a..aab4bf137 100644 --- a/tests/sensor_probes.py +++ b/tests/sensor_probes.py @@ -269,9 +269,9 @@ def robot_lidar_echo_probes(env): def check_robot_filtered_lidar(env, *, duration=10, window=5): - """Filtered LiDAR is publishing (Isaac only): ``echo --once`` per robot container.""" - if env.get("sim") != "isaacsim": - return True, "robot lidar skipped (not isaacsim)", {} + """Filtered LiDAR is publishing (sims with ``has_lidar``): ``echo --once`` per robot.""" + if not env["cfg"].get("has_lidar"): + return True, f"robot lidar skipped ({env.get('sim')} has no lidar)", {} cfg = env["cfg"] robots = get_robot_containers(env["robot_pattern"]) if not robots: @@ -285,8 +285,9 @@ def check_robot_filtered_lidar(env, *, duration=10, window=5): probes = robot_lidar_echo_probes(env) per_topic_timeout = max(40, int(duration * 4)) logger.info( - "Filtered LiDAR: echo-once for %d topic(s) (isaacsim, timeout=%ss per topic)", + "Filtered LiDAR: echo-once for %d topic(s) (%s, timeout=%ss per topic)", len(probes), + env.get("sim"), per_topic_timeout, ) rates = parallel_echo_once_robot_topics( @@ -303,9 +304,9 @@ def check_robot_filtered_lidar(env, *, duration=10, window=5): def check_lidar_filtered_cloud_sanity(env): - """One-shot filtered/raw cloud checks inside each robot container (isaacsim).""" - if env.get("sim") != "isaacsim": - return True, "lidar cloud sanity skipped (not isaacsim)", {} + """One-shot filtered/raw cloud checks inside each robot container (``has_lidar`` sims).""" + if not env["cfg"].get("has_lidar"): + return True, f"lidar cloud sanity skipped ({env.get('sim')} has no lidar)", {} cfg = env["cfg"] robots = get_robot_containers(env["robot_pattern"]) if len(robots) < env["num_robots"]: diff --git a/tests/system/test_build_docker.py b/tests/system/test_build_docker.py index 58f1eb547..2c869f5e5 100644 --- a/tests/system/test_build_docker.py +++ b/tests/system/test_build_docker.py @@ -26,4 +26,7 @@ def test_build_isaac_sim(self): def test_build_ms_airsim(self): self._build_and_record("ms-airsim", env={"COMPOSE_PROFILES": "ms-airsim"}) + def test_build_project_airsim(self): + self._build_and_record("project-airsim", env={"COMPOSE_PROFILES": "project-airsim"}) + # TODO: Test other profiles that build their own docker containers diff --git a/tests/system/test_build_packages.py b/tests/system/test_build_packages.py index aa84b0464..27ce724a2 100644 --- a/tests/system/test_build_packages.py +++ b/tests/system/test_build_packages.py @@ -129,3 +129,33 @@ def test_colcon_build_ms_airsim(self): assert build.returncode == 0, f"colcon build failed:\n{read_log_tail()}" finally: airstack_cmd("down") + + def test_colcon_build_project_airsim(self): + """Build + gtest the C++ pas_ros_bridge against the image's pinned + Project AirSim client (/opt/projectairsim).""" + _warn_if_prebuilt("simulation/project-airsim/ros_ws") + try: + result = airstack_cmd( + "up", "project-airsim", + env_overrides={"AUTOLAUNCH": "false", "DISPLAY": "", + "COMPOSE_PROFILES": "project-airsim", + "URDF_FILE": "robot_descriptions/iris/urdf/" + "iris_stereo_lidar.project-airsim.urdf"}, + timeout=120, + ) + assert result.returncode == 0, f"airstack up failed:\n{read_log_tail()}" + + container = wait_for_container("project-airsim", timeout=60) + assert container, "project-airsim container not found" + + build = docker_exec( + container, + "source /opt/ros/jazzy/setup.bash && cd /root/ros_ws && " + "colcon build --symlink-install --cmake-args -DCMAKE_BUILD_TYPE=Release && " + "colcon test --packages-select pas_ros_bridge && " + "colcon test-result --verbose", + timeout=900, + ) + assert build.returncode == 0, f"colcon build/test failed:\n{build.stdout[-3000:]}" + finally: + airstack_cmd("down") diff --git a/tests/system/test_liveliness.py b/tests/system/test_liveliness.py index aec1a39e0..4e8c3dc6e 100644 --- a/tests/system/test_liveliness.py +++ b/tests/system/test_liveliness.py @@ -107,6 +107,26 @@ def _check_sim_startup_process(env): ok, message = _check_tmux_panes(env) if not ok: return ok, message + if env["sim"] == "projectairsim": + # Still starting = healthy: a first launch builds the bridge and + # downloads the environment (GBs) before Unreal exists. Otherwise the + # GPU must be visible and the Unreal process (any build configuration + # runs from /Binaries/Linux/) alive; port readiness is left to + # the /clock wait. + result = docker_exec( + env["sim_container"], + "pgrep -f 'fetch_env.sh|colcon build' >/dev/null && exit 0; " + "nvidia-smi -L >/dev/null && " + "pgrep -f '/Binaries/Linux/' >/dev/null", + timeout=10, + ) + if result.returncode != 0: + return False, ( + "Project AirSim infrastructure prerequisite failed: no environment " + "download or bridge build in progress, and the GPU is unavailable " + "or the UE5 process exited" + ) + return True, "Project AirSim starting up or UE5 process healthy" if env["sim"] != "msairsim": return True, message result = docker_exec( diff --git a/tests/system/test_sensors.py b/tests/system/test_sensors.py index 35e212e5d..7f0d60f15 100644 --- a/tests/system/test_sensors.py +++ b/tests/system/test_sensors.py @@ -104,7 +104,7 @@ def test_robot_stereo_bridge_rates(self, airstack_env): @pytest.mark.dependency(name="sensors_robot_lidar", depends=["sensors_robot_stereo"]) def test_robot_filtered_lidar_stream(self, airstack_env): - """Filtered LiDAR ``echo --once`` per robot (isaacsim only; skipped elsewhere).""" + """Filtered LiDAR ``echo --once`` per robot (LiDAR sims: isaacsim, projectairsim).""" ok, msg, _ = check_robot_filtered_lidar(airstack_env) assert ok, msg @@ -127,7 +127,7 @@ def test_sim_clock_realtime_factor(self, airstack_env): depends=["sensors_robot_lidar", "sensors_nodes"], ) def test_lidar_filtered_cloud_sanity(self, airstack_env): - """Point cloud geometry vs ``near_range_m`` (isaacsim only).""" + """Point cloud geometry vs ``near_range_m`` (LiDAR sims: isaacsim, projectairsim).""" ok, msg, _ = check_lidar_filtered_cloud_sanity(airstack_env) assert ok, msg diff --git a/tools/compose_module_layers.py b/tools/compose_module_layers.py index 451bc3871..44b9c70df 100644 --- a/tools/compose_module_layers.py +++ b/tools/compose_module_layers.py @@ -18,7 +18,7 @@ The chain is deterministic: modules sorted by name within each tier, tiers in order 1 → 2 → 3-as-build, grouped per target host (``robot`` | ``gcs`` | -``isaac-sim`` | ``ms-airsim``). +``isaac-sim`` | ``ms-airsim`` | ``project-airsim``). **Zero-module identity rule (hard requirement):** when no module contributes a docker-relevant declaration, every host's plan is exactly @@ -81,7 +81,7 @@ # gcs/docker/gcs-base-docker-compose.yaml, simulation/*/docker/docker-compose.yaml). # The robot suffix carries DOCKER_IMAGE_BUILD_MODE, the others do not — that is # the existing trunk scheme, mirrored here on purpose. -HOSTS = ("robot", "gcs", "isaac-sim", "ms-airsim") +HOSTS = ("robot", "gcs", "isaac-sim", "ms-airsim", "project-airsim") # Compose services that get an `image:` override under --build, per host. # robot-l4t is deliberately absent: its image chains from robot-l4t-stack-base @@ -92,6 +92,7 @@ "gcs": ("gcs",), "isaac-sim": ("isaac-sim",), "ms-airsim": ("ms-airsim",), + "project-airsim": ("project-airsim",), } COMPOSED_HEADER = """\ diff --git a/tools/fleet/resolve_fleet.py b/tools/fleet/resolve_fleet.py index e4db0b64c..738416081 100755 --- a/tools/fleet/resolve_fleet.py +++ b/tools/fleet/resolve_fleet.py @@ -60,7 +60,7 @@ # Robot-level keys the schema accepts. Unknown keys are named errors so typos # (``vehicel:``) fail loudly instead of silently applying defaults. -ROBOT_KEYS = {"vehicle", "unit", "stack", "spawn", "hosts", "overrides"} +ROBOT_KEYS = {"vehicle", "unit", "stack", "spawn", "hosts", "overrides", "physics"} GROUND_KEYS = {"stack"} FLEET_KEYS = {"defaults", "robots", "ground", "sim", "network"} NETWORK_KEYS = {"domain_policy", "gossip_domain", "gcs_domain"} @@ -265,6 +265,10 @@ def resolve_robot(fleet, root, key): "calibration_dir": calibration_rel, "overrides": overrides, "lidar": vehicle_has_lidar(vehicle_manifest), + # Sim physics model (Project AirSim: fast-physics | jsbsim). None = + # inherit fleet sim.physics / the vehicle default; validated by the + # simulator's scene generator, which owns the list of choices. + "physics": entry.get("physics"), }