diff --git a/.gitignore b/.gitignore index d3a929b5..e0a4e76e 100644 --- a/.gitignore +++ b/.gitignore @@ -339,6 +339,8 @@ unreal/**/Saved unreal/**/Package unreal/**/.vscode unreal/**/ProjectAirSim/SimLibs +unreal/**/DerivedDataCache +unreal/**/Samples # VS Code projects *.code-workspace @@ -376,3 +378,5 @@ env/ # Simulink cache **/slprj *.slxc + +venv \ No newline at end of file diff --git a/Architecture.md b/Architecture.md new file mode 100644 index 00000000..f08a889d --- /dev/null +++ b/Architecture.md @@ -0,0 +1,1272 @@ +# Project AirSim Complete Architecture Overview + +## System Overview + +Project AirSim is a comprehensive simulation platform that transforms Unreal Engine 5 into a robotics and autonomous systems development environment. It combines photo-realistic 3D rendering, advanced physics simulation, and network-based APIs to create a complete ecosystem for testing and developing autonomous vehicles. + +``` +┌─────────────────────────────────────────────────────────────────────────────────┐ +│ PROJECT AIRSIM SYSTEM │ +│ ┌─────────────────────────────────────────────────────────────────────────┐ │ +│ │ UNREAL ENGINE 5 SIMULATION ENVIRONMENT │ │ +│ │ ┌─────────────────────────────────────────────────────────────────┐ │ │ +│ │ │ PROJECTAIRSIM PLUGIN (UE INTEGRATION) │ │ │ +│ │ │ ┌─────────────────────────────────────────────────────────┐ │ │ │ +│ │ │ │ SIM LIBS (C++ CORE SIMULATION) │ │ │ │ +│ │ │ │ ┌─────────────┬─────────────┬─────────────┐ │ │ │ │ +│ │ │ │ │ VEHICLE │ PHYSICS │ SENSORS │ │ │ │ │ +│ │ │ │ │ APIS │ ENGINES │ SYSTEM │ │ │ │ │ +│ │ │ │ └─────────────┴─────────────┴─────────────┘ │ │ │ │ +│ │ │ └─────────────────────────────────────────────────────────┘ │ │ │ +│ │ └─────────────────────────────────────────────────────────────────┘ │ │ +│ └─────────────────────────────────────────────────────────────────────────┘ │ +└─────────────────────┬───────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────────────────────┐ +│ CLIENT APPLICATIONS │ +│ ┌─────────────┬─────────────┬─────────────┬─────────────┐ │ +│ │ PYTHON │ ROS │ MAVLINK │ CUSTOM │ │ +│ │ API │ BRIDGE │ GCS │ CONTROLLERS │ │ +│ └─────────────┴─────────────┴─────────────┴─────────────┘ │ +└─────────────────────────────────────────────────────────────────────────────────┘ +``` + +## Core Architecture Components + +### 1. Unreal Engine 5 Foundation + +**Blocks Project** (`unreal/Blocks/`) +- Primary UE5 project containing the simulation environment +- Configured for UE versions 5.2 and 5.7 with ProjectAirSim plugin enabled +- Contains simulation levels (BlocksMap.umap, GISMap.umap) +- Manages content assets and Blueprints + +**Key Configuration**: +```json +{ + "EngineAssociation": "5.7", + "Plugins": ["ProjectAirSim"], + "TargetPlatforms": ["WindowsNoEditor", "LinuxNoEditor"] +} +``` + +### 2. ProjectAirSim Plugin (Bridge Layer) + +**Location**: `unreal/Blocks/Plugins/ProjectAirSim/` + +**Purpose**: Native UE5 plugin that integrates C++ simulation libraries with Unreal's runtime. + +**Architecture**: +``` +Plugin Structure +├── ProjectAirSim.uplugin (Plugin manifest) +├── Source/ProjectAirSim/ (C++ source) +│ ├── Public/ (API headers) +│ └── Private/ (Implementation) +├── SimLibs/ (Compiled C++ DLLs) +├── Content/ (UE assets) +└── Binaries/ (Platform binaries) +``` + +**Key Classes**: +- `AProjectAirSimGameMode`: Manages simulation lifecycle +- `AUnrealSimLoader`: Loads and manages Sim Libs +- `AUnrealRobot`: UE Actor representing robots +- `AUnrealSensor`: Base class for sensors + +### 3. Sim Libs (Core Simulation Engine) + +**Location**: `projectairsim/` (root CMake project) + +**Purpose**: Cross-platform C++ libraries providing the simulation framework. + +**Component Architecture**: +``` +Sim Libs Modules +├── core_sim/ (Simulation loop, scene management) +├── vehicle_apis/ (Robot controllers: SimpleFlight, ArduPilot, PX4) +├── physics/ (Physics engines: FastPhysics, Matlab) +├── mavlinkcom/ (MAVLink protocol implementation) +├── rendering/ (Rendering components) +├── sensors/ (Sensor simulation) +└── simserver/ (Network server, API management) +``` + +## System Startup and Initialization + +### 1. UE5 Editor Launch Sequence + +``` +UE5 Editor Start + ↓ +Load Blocks.uproject + ↓ +Initialize ProjectAirSim Plugin + ↓ +FProjectAirSimModule::StartupModule() + ↓ +Register AProjectAirSimGameMode + ↓ +Ready for Play Mode +``` + +### 2. Simulation Launch Sequence + +``` +Press "Play" in UE Editor + ↓ +AProjectAirSimGameMode::StartPlay() + ↓ +AUnrealSimLoader::LaunchSimulation() + ↓ +├── Configure UE Settings (CustomDepth, etc.) +├── Load SimServer (C++ DLL) +├── Load Scene Configuration (JSON) +├── Spawn UE Actors (Robots, Sensors) +├── Start Network Server (Ports 8989/8990) +└── Begin Physics Simulation Loop +``` + +### 3. Client Connection Sequence + +``` +Client Application Starts + ↓ +ProjectAirSimClient.connect() + ↓ +TCP Connection to Ports 8989/8990 + ↓ +Authentication (optional) + ↓ +Subscribe to Topics + ↓ +Ready for Control Commands +``` + +## Data Flow Architecture + +### Control Flow (Client → Simulation) + +``` +Client Command → TCP Socket → SimServer → Vehicle API → Physics Engine → UE Actor Update → Visual Feedback +``` + +**Detailed Path**: +1. **Client Layer**: Python/ROS/MAVLink client sends command +2. **Network Layer**: pynng TCP transport (ports 8989/8990) +3. **Server Layer**: SimServer receives and deserializes MessagePack +4. **API Layer**: Vehicle API (MAVLink, ArduPilot, etc.) processes command +5. **Physics Layer**: Physics engine applies forces/torques +6. **UE Integration**: UE Actor position/orientation updated +7. **Rendering**: UE renders new state + +### Sensor Data Flow (Simulation → Client) + +``` +UE Sensor Tick → Data Collection → Serialization → TCP Socket → Client Processing → User Application +``` + +**Detailed Path**: +1. **UE Sensor**: Unreal sensor actor samples environment +2. **Data Processing**: Sensor data processed by Sim Libs +3. **Serialization**: MessagePack serialization +4. **Network**: TCP streaming via pynng +5. **Client**: Python/ROS client receives data +6. **Application**: User code processes sensor data + +## Communication Architecture + +### Network Protocol Stack + +``` +Application Layer +├── Python API (projectairsim.Client) +├── ROS Bridge (ros2_node.py) +└── MAVLink Protocol (mavlinkcom/) + +Transport Layer +├── TCP/IP (Ports 8989/8990) +├── pynng Sockets (NNG library) +└── Message Serialization (MessagePack + JSON) + +Simulation Layer +├── SimServer (C++ core) +├── Scene Management +└── API Routing +``` + +### Message Patterns + +**Topics (Publish/Subscribe - Port 8989)**: +- **Sensor Streaming**: Camera images, LiDAR, IMU, GPS +- **State Updates**: Robot position, velocity, orientation +- **System Events**: Scene changes, actor updates + +**Services (Request/Response - Port 8990)**: +- **Control Commands**: Movement, configuration changes +- **Synchronous Queries**: Current state, settings +- **Administrative**: Reset, pause, load scene + +## Component Integration Details + +### UE5 ↔ Sim Libs Integration + +**Runtime DLL Loading**: +```cpp +// In UnrealSimLoader.cpp +SimServer = std::make_shared(); + +// Bind UE callbacks to C++ simulation +SimServer->SetCallbackLoadExternalScene( + [this]() { LoadUnrealScene(); }); +``` + +**Actor Synchronization**: +```cpp +// UE Actor position updated from physics +void AUnrealRobot::Tick(float DeltaTime) { + // Get position from Sim Libs physics + auto pose = VehicleAPI->getPose(); + + // Update UE Actor transform + SetActorLocation(pose.position); + SetActorRotation(pose.orientation); +} +``` + +### Physics Integration + +**Multi-Physics Backend Support**: +``` +Physics Engine Options +├── PhysX (UE5 Default) +├── Bullet Physics +├── Custom Physics +└── Runtime Switching +``` + +**Integration Pattern**: +```cpp +// Physics abstraction in Sim Libs +class PhysicsEngine { + virtual void update(float dt) = 0; + virtual void applyForce(Vector3 force) = 0; +}; + +// UE integration +void AUnrealSimLoader::UpdatePhysics() { + PhysicsEngine->update(DeltaTime); + SyncActorTransforms(); +} +``` + +## Development Workflow + +### 1. Build Process + +``` +Source Code Changes + ↓ +Build Sim Libs (CMake) + ↓ +build.sh simlibs_debug + ↓ +Build UE Plugin + ↓ +BlocksEditor Win64 DebugGame + ↓ +Launch UE Editor + ↓ +Test in Play Mode +``` + +### 2. Development Environments + +**Windows Development**: +- Visual Studio 2019/2022 for Sim Libs +- UE5 Editor for plugin development +- VS Code multi-root workspace + +**Linux Development**: +- CMake + Ninja for Sim Libs +- UE5 Editor for plugin development +- VS Code with WSL integration + +### 3. Multi-Root Workspace + +**VS Code Configuration** (`Blocks.code-workspace`): +```json +{ + "folders": [ + {"path": "unreal/Blocks"}, + {"path": "core_sim"}, + {"path": "vehicle_apis"}, + {"path": "physics"}, + {"path": "mavlinkcom"} + ] +} +``` + +## API Ecosystem + +### Python Client API + +**Architecture**: +``` +Python Client Layers +├── ProjectAirSimClient (Network connection) +├── World (Scene management) +├── Drone/Rover (Vehicle control) +└── Sensor Interfaces (Data access) +``` + +**Usage Pattern**: +```python +# Connect and control +client = ProjectAirSimClient() +client.connect() + +world = World(client, "scene_config.jsonc") +drone = Drone(client, world, "Drone1") + +# Control loop +while True: + # Send commands + await drone.move_by_velocity_async(vx, vy, vz) + + # Receive sensor data + image = drone.get_camera_image("front_camera") + lidar = drone.get_lidar_data("lidar") +``` + +### ROS Integration + +**ROS2 Bridge Architecture**: +``` +ROS2 Integration +├── ros2_node.py (ROS2 node implementation) +├── Message Translation (UE ↔ ROS formats) +├── TF Broadcasting (Coordinate transforms) +└── Service Bridges (ROS services ↔ UE) +``` + +**Topic Mapping**: +``` +/airsim/drone/front_camera → sensor_msgs/Image +/airsim/drone/lidar → sensor_msgs/PointCloud2 +/airsim/drone/imu → sensor_msgs/Imu +/airsim/drone/cmd_vel → geometry_msgs/Twist +``` + +### MAVLink Integration + +**MAVLink Stack**: +``` +MAVLink Integration +├── mavlinkcom/ (Protocol implementation) +├── Vehicle APIs (PX4, ArduPilot integration) +├── Ground Control Station support +└── Custom MAVLink dialects +``` + +## Performance and Scalability + +### Rendering Optimization + +**UE5 Features Utilized**: +- **Lumen**: Dynamic global illumination +- **Nanite**: Geometry LOD system +- **Virtual Shadow Maps**: Efficient shadowing +- **Custom Depth**: Segmentation rendering + +### Sensor Processing + +**GPU Acceleration**: +- **Compute Shaders**: LiDAR point cloud generation +- **Async Tasks**: Image compression and formatting +- **Render Targets**: Off-screen rendering for cameras + +### Network Optimization + +**Efficient Data Streaming**: +- **MessagePack**: Compact binary serialization +- **Topic Filtering**: Selective data subscription +- **Compression**: Optional data compression +- **Async Processing**: Non-blocking network operations + +## Deployment and Distribution + +### Build Targets + +**Development Builds**: +- `BlocksEditor Win64 DebugGame` - Editor debugging +- `BlocksEditor Win64 Development` - Full UE features + +**Production Builds**: +- `Blocks Win64 Development` - Packaged application +- `Blocks Win64 Shipping` - Optimized release + +### Packaging Process + +``` +Build Sim Libs → Package Plugin → Cook Content → Package Game → Distribute +``` + +### Platform Support + +**Supported Platforms**: +- **Windows 11**: Full development and runtime +- **Ubuntu 22.04**: Full development and runtime +- **Container Support**: Docker integration + +## Advanced Features + +### Geographic Information Systems + +**GIS Integration**: +- **Cesium Integration**: Real-world terrain and imagery +- **Geodetic Conversion**: GPS ↔ UE coordinate systems +- **Large World Support**: World partitioning for vast areas + +### Multi-Robot Simulation + +**Multi-Agent Support**: +- **Concurrent Robots**: Multiple vehicles in same scene +- **Independent Control**: Separate APIs per robot +- **Inter-Agent Communication**: Robot-to-robot messaging + +### Custom Content Pipeline + +**Asset Integration**: +- **FBX Import**: 3D model import with physics +- **Material System**: Physically-based rendering +- **Blueprint Scripting**: Visual logic for custom behaviors + +## System Requirements and Dependencies + +### Hardware Requirements + +**Minimum**: +- CPU: Quad-core 3.0 GHz +- RAM: 16 GB +- GPU: GTX 1060 or equivalent +- Storage: 50 GB SSD + +**Recommended**: +- CPU: Octa-core 4.0 GHz +- RAM: 32 GB +- GPU: RTX 3070 or equivalent +- Storage: 100 GB NVMe SSD + +### Software Dependencies + +**Core Dependencies**: +- Unreal Engine 5.2 and 5.7 +- Visual Studio 2019/2022 (Windows) +- CMake 3.20+ +- Python 3.7+ + +**Optional Dependencies**: +- ROS2 Humble/Foxy +- PX4/ArduPilot +- Cesium for Unreal + +## Troubleshooting and Debugging + +### Common Issues + +**Build Problems**: +- **Sim Libs Build**: Check CMake configuration +- **UE Plugin**: Verify plugin dependencies +- **Network Issues**: Check firewall and port availability + +**Runtime Issues**: +- **Connection Failures**: Verify ports 8989/8990 available +- **Physics Problems**: Check UE physics settings +- **Sensor Issues**: Verify sensor configuration in JSON + +### Debug Tools + +**UE5 Debugging**: +- **Visual Logger**: Record and replay simulation +- **Console Commands**: Runtime configuration +- **Stat Commands**: Performance profiling + +**Network Debugging**: +- **Wireshark**: Network traffic analysis +- **Client Logs**: Detailed connection logging +- **Server Logs**: Sim Libs debug output + +--- + +# Project AirSim Architecture from Unreal Engine Perspective + +From the Unreal Engine developer's viewpoint, Project AirSim is a sophisticated plugin ecosystem that transforms UE5 into a robotics simulation platform. The architecture seamlessly integrates C++ simulation libraries with Unreal's visual and physics systems, providing developers with familiar UE tools while enabling complex autonomous systems simulation. + +## Unreal Engine Integration Architecture + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Unreal Engine 5.7 Editor │ +│ ┌─────────────────────────────────────────────────────┐ │ +│ │ Blocks Project │ │ +│ │ ┌─────────────────────────────────────────────┐ │ │ +│ │ │ ProjectAirSim Plugin │ │ │ +│ │ │ ┌─────────────────────────────────────┐ │ │ │ +│ │ │ │ Sim Libs Integration │ │ │ │ +│ │ │ │ (C++ DLLs loaded at runtime) │ │ │ │ +│ │ │ └─────────────────────────────────────┘ │ │ │ +│ │ └─────────────────────────────────────────────┘ │ │ +│ └─────────────────────────────────────────────────────┘ │ +└─────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ External Client Applications │ +│ (Python API, ROS, MAVLink GCS, Custom Controllers) │ +└─────────────────────────────────────────────────────────────┘ +``` + +## Core Components in Unreal Engine + +### 1. Blocks Project (Main UE Project) + +**Location**: `unreal/Blocks/` + +**Purpose**: The primary Unreal Engine project that serves as the simulation environment. + +**Key Files**: +- `Blocks.uproject` - Project manifest with plugin dependencies +- `BlocksMap.umap` - Main simulation level +- `GISMap.umap` - Geographic information system level + +**Project Configuration**: +```json +{ + "EngineAssociation": "5.7", + "Plugins": ["ProjectAirSim"], + "TargetPlatforms": ["WindowsNoEditor", "LinuxNoEditor"] +} +``` + +### 2. ProjectAirSim Plugin Architecture + +**Location**: `unreal/Blocks/Plugins/ProjectAirSim/` + +**Plugin Structure**: +``` +ProjectAirSim Plugin +├── ProjectAirSim.uplugin (Plugin manifest) +├── Source/ProjectAirSim/ (C++ source) +│ ├── Public/ (API headers) +│ └── Private/ (Implementation) +├── SimLibs/ (Compiled C++ DLLs) +├── Content/ (UE assets) +└── Binaries/ (Platform binaries) +``` + +**Plugin Manifest**: +```json +{ + "Modules": [ + { + "Name": "ProjectAirSim", + "Type": "Runtime", + "LoadingPhase": "PostConfigInit" + } + ], + "Plugins": [ + {"Name": "ProceduralMeshComponent", "Enabled": true}, + {"Name": "SunPosition", "Enabled": true}, + {"Name": "PixelStreaming", "Enabled": true} + ] +} +``` + +### 3. GameMode Integration + +**Key Class**: `AProjectAirSimGameMode` + +**Lifecycle Management**: +```cpp +class AProjectAirSimGameMode : public AGameModeBase { + void StartPlay() override { + Super::StartPlay(); + UnrealSimLoader.LaunchSimulation(this->GetWorld()); + } + + void EndPlay() override { + UnrealSimLoader.TeardownSimulation(); + } +}; +``` + +**Responsibilities**: +- Initializes simulation when Play is pressed in UE Editor +- Manages UnrealSimLoader lifecycle +- Sets deterministic seed for reproducible simulations + +## Simulation Loading Architecture + +### UnrealSimLoader (Core Integration Point) + +**Class**: `AUnrealSimLoader` + +**Purpose**: Bridges between Unreal Engine and Project AirSim Sim Libs. + +**Key Methods**: +```cpp +void LaunchSimulation(UWorld* World) { + // 1. Configure Unreal Engine settings + SetUnrealEngineSettings(); + + // 2. Load simulator with network ports + SimServer->LoadSimulator(topicsPort, servicesPort, authKey); + + // 3. Load scene configuration + SimServer->LoadScene(); + + // 4. Create Unreal scene actors + LoadUnrealScene(); + + // 5. Start network server + SimServer->StartSimulator(); + + // 6. Begin simulation + StartUnrealScene(); + SimServer->StartScene(); +} +``` + +**Architecture Flow**: +``` +UE Editor Play Button + ↓ +AProjectAirSimGameMode::StartPlay() + ↓ +AUnrealSimLoader::LaunchSimulation() + ↓ +├── Configure UE Settings (CustomDepth, etc.) +├── Load SimServer (C++ DLL) +├── Load Scene Config (JSON) +├── Spawn UE Actors (Robots, Sensors) +├── Start Network Server (Ports 8989/8990) +└── Begin Physics Simulation +``` + +## Actor Hierarchy in Unreal Engine + +### Robot Actor System + +``` +Unreal Actor Hierarchy +├── AUnrealRobot (Base Robot Class) +│ ├── Skeletal Mesh Component +│ ├── Physics Components +│ └── Sensor Attachments +├── AUnrealRobotLink (Robot Links) +│ ├── Collision Shapes +│ ├── Visual Meshes +│ └── Joint Attachments +└── AUnrealRobotJoint (Robot Joints) + ├── Constraint Components + ├── Motor Controllers + └── State Publishers +``` + +### Sensor Actor System + +``` +Sensor Integration +├── AUnrealSensor (Base Sensor) +│ ├── Tick-based Updates +│ ├── Data Publishing +│ └── Configuration Management +├── Camera Sensors +│ ├── AUnrealCamera +│ ├── AUnrealViewportCamera +│ └── Render Request System +├── Distance Sensors +│ ├── AUnrealLidar (Raycasting + GPU Compute) +│ ├── AUnrealRadar +│ └── AUnrealDistanceSensor +└── Environmental Sensors + ├── IMU Simulation + ├── GPS/Geodetic Conversion + └── Barometer/Altimeter +``` + +## Rendering and Sensor Pipeline + +### Camera Rendering Architecture + +``` +Camera Pipeline +├── Unreal Camera Actor +│ ├── Scene Capture Component 2D +│ └── Render Target +├── Image Packing (Async Task) +│ ├── GPU → CPU Transfer +│ ├── Format Conversion +│ └── Compression +└── Network Publishing + ├── MessagePack Serialization + └── TCP Streaming (Port 8989) +``` + +### LiDAR Rendering System + +``` +LiDAR Pipeline +├── GPULidar Actor +│ ├── Compute Shader (LidarPointCloudCS) +│ ├── Scene View Extension +│ └── Intensity Calculation +├── Point Cloud Generation +│ ├── Ray Marching +│ ├── Distance Calculation +│ └── Intensity Mapping +└── Data Publishing + ├── Point Cloud Serialization + └── ROS/MAVLink Bridge +``` + +## Development Workflow in Unreal Engine + +### 1. Project Setup and Building + +**Build Targets**: +``` +BlocksEditor Win64 Development - For Editor development +Blocks Win64 Development - For packaged game builds +BlocksEditor Win64 DebugGame - For debugging with Sim Libs +``` + +**Development Cycle**: +``` +1. Modify C++ Sim Libs (CMake) +2. Build Sim Libs (build.sh simlibs_debug) +3. Build UE Plugin (BlocksEditor Win64 DebugGame) +4. Launch UE Editor +5. Press Play → Simulation starts +6. Connect client (Python/ROS/MAVLink) +7. Debug and iterate +``` + +### 2. Multi-Root Workspace Development + +**VS Code Integration**: +- `Blocks.code-workspace` - Multi-root workspace +- Simultaneous editing of UE Plugin and Sim Libs +- Integrated debugging across C++ and Blueprint + +**Workspace Structure**: +``` +Blocks.code-workspace +├── unreal/Blocks/ (UE Plugin & Project) +├── core_sim/ (Simulation Core) +├── vehicle_apis/ (Robot Controllers) +├── physics/ (Physics Engines) +└── mavlinkcom/ (Communication) +``` + +### 3. Content Creation Pipeline + +**Asset Organization**: +``` +Content/ +├── BlocksMap.umap (Main simulation level) +├── GISMap.umap (Geographic level) +├── Robots/ (Robot Blueprints/Meshes) +├── Environments/ (Scene assets) +└── Sensors/ (Sensor configurations) +``` + +**Level Design Considerations**: +- **Scale**: 1 UE unit = 1 cm (for physics accuracy) +- **Lighting**: Must support CustomDepth for segmentation +- **Navigation**: Recast navmesh for ground robots +- **Streaming**: Level streaming for large environments + +## Plugin Architecture Deep Dive + +### Module Dependencies + +**Build.cs Configuration**: +```csharp +public class ProjectAirSim : ModuleRules { + PublicIncludePaths.AddRange(new string[] { + "ProjectAirSim/Public" + }); + + PrivateIncludePaths.AddRange(new string[] { + EngineDirectory + "/Source/Runtime/Renderer/Private" + }); + + // Sim Libs integration + if (Target.Platform == UnrealTargetPlatform.Win64) { + PublicIncludePaths.Add( + PluginDirectory + "/SimLibs/core_sim/include" + ); + // ... additional Sim Lib paths + } +} +``` + +### Runtime Library Loading + +**Dynamic Library Integration**: +``` +Plugin Load Process +├── UE Plugin loads (ProjectAirSim.uplugin) +├── Module initializes (FProjectAirSimModule) +├── Sim Libs DLLs loaded at runtime +├── SimServer instantiated +└── Callbacks bound for scene management +``` + +**Callback System**: +```cpp +// Bind C++ simulation callbacks to UE functions +SimServer->SetCallbackLoadExternalScene( + [this]() { LoadUnrealScene(); }); +``` + +## Communication Architecture from UE Perspective + +### Network Integration + +**Server-Side Architecture**: +``` +Unreal Engine (Server) +├── SimServer (C++ Core) +│ ├── TCP Listener (Ports 8989/8990) +│ ├── Message Deserialization +│ └── Command Processing +├── Unreal Scene +│ ├── Actor Updates +│ ├── Physics Simulation +│ └── Sensor Data Collection +└── Data Publishing + ├── Topic Broadcasting + └── Service Responses +``` + +**Client Connection Flow**: +``` +Client Connects → SimServer Accepts → Authentication → Scene Sync → Ready for Commands +``` + +### Data Flow Architecture + +``` +Control Commands (Client → UE) +├── Network Reception (pynng/TCP) +├── Message Deserialization (MessagePack) +├── Command Routing (SimServer) +├── Physics Updates (UE Physics) +└── Visual Feedback (UE Rendering) + +Sensor Data (UE → Client) +├── Sensor Sampling (UE Tick) +├── Data Processing (C++ Sim Libs) +├── Serialization (MessagePack) +├── Network Transmission (pynng/TCP) +└── Client Reception +``` + +## ROS Integration from UE Perspective + +### ROS Bridge Architecture + +``` +ROS Integration Layers +├── UE Plugin (ProjectAirSim) +│ ├── Sensor Data Publishers +│ ├── Control Command Subscribers +│ └── TF Transform Broadcasting +├── ROS2 Node Bridge (Python) +│ ├── rclpy Integration +│ ├── Topic/Message Translation +│ └── Service Proxies +└── ROS Ecosystem + ├── RViz Visualization + ├── ROS Control + └── Navigation Stack +``` + +### UE-Specific ROS Features + +**Transform Broadcasting**: +- UE coordinate system to ROS TF +- Real-time transform updates +- Geographic coordinate integration + +**Sensor Integration**: +- UE cameras → ROS image topics +- UE LiDAR → ROS PointCloud2 +- UE IMU → ROS Imu messages + +## Development Best Practices + +### 1. Performance Optimization + +**UE-Specific Considerations**: +- **Tick Groups**: Use appropriate tick groups for sensors +- **Async Tasks**: Offload heavy computations (image packing) +- **Render Threads**: Minimize main thread blocking +- **Memory Management**: Pool reusable assets + +### 2. Debugging Techniques + +**UE Editor Debugging**: +- **Visualize Sensors**: Debug drawing for raycasts/LiDAR +- **Physics Debugging**: Show collision shapes and constraints +- **Network Debugging**: Log message traffic and timing + +**Multi-Target Debugging**: +- Attach debugger to UE Editor + Python client simultaneously +- Cross-reference UE logs with client application logs + +### 3. Content Pipeline + +**Asset Optimization**: +- **LOD System**: Configure level-of-detail for performance +- **Texture Streaming**: Manage texture memory for large environments +- **Instancing**: Use instanced static meshes for repeated assets + +## Advanced UE Features Integration + +### 1. Rendering Features + +**Custom Rendering**: +- **Scene View Extensions**: For specialized sensor rendering (LiDAR intensity) +- **Compute Shaders**: GPU-accelerated sensor processing +- **Post-Processing**: Custom materials for sensor simulation + +### 2. Physics Integration + +**UE Physics Extensions**: +- **Custom Physics Engines**: Runtime switching between physics backends +- **Constraint Systems**: Advanced joint and linkage simulation +- **Collision Detection**: Custom collision shapes for sensors + +### 3. Multiplayer/Network Features + +**Distributed Simulation**: +- **Pixel Streaming**: Web-based visualization +- **Multi-Client Support**: Multiple clients connecting simultaneously +- **State Synchronization**: Consistent simulation state across clients + +--- + +# Project AirSim Architecture Analysis + +## Overview + +Project AirSim is a simulation platform for drones, robots, and other autonomous systems built on Unreal Engine 5. It consists of C++ simulation libraries, an Unreal Engine plugin, and Python client libraries for API interactions. + +## High-Level Architecture + +``` +┌─────────────────────────────────────────────────────────────┐ +│ User Applications │ +│ (Python scripts, ROS nodes, MAVLink GCS, etc.) │ +└─────────────────────┬───────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ Project AirSim Client Library │ +│ (Python API, ROS Bridge, MAVLink Protocol) │ +└─────────────────────┬───────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ Project AirSim Plugin │ +│ (Unreal Engine Plugin - Runtime Integration) │ +└─────────────────────┬───────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ Project AirSim Sim Libs │ +│ (C++ Core Simulation Framework) │ +└─────────────────────────────────────────────────────────────┘ +``` + +## Detailed Architecture Components + +### 1. Project AirSim Sim Libs (Core Layer) + +**Location**: `projectairsim/` (root CMake project) + +**Purpose**: Base infrastructure for defining a generic robot structure and simulation scene tick loop. + +**Key Components**: +- **Core Simulation** (`core_sim/`): Main simulation loop and scene management +- **Physics Integration** (`physics/`): Physics engines and dynamics +- **Vehicle APIs** (`vehicle_apis/`): Robot-specific control interfaces +- **MAVLink Communication** (`mavlinkcom/`): MAVLink protocol implementation +- **Rendering** (`rendering/`): Visual rendering components + +**Architecture**: +``` +Sim Libs +├── Core Simulation Framework +│ ├── Scene Management +│ ├── Robot Definitions +│ └── Simulation Tick Loop +├── Vehicle APIs +│ ├── Multirotor API +│ │ ├── MAVLink API +│ │ ├── ArduCopter API +│ │ ├── SimpleFlight API +│ │ └── Manual Controller API +│ └── Rover API +├── Physics Engines +├── Sensors Framework +└── Communication Layer +``` + +### 2. Project AirSim Plugin (Integration Layer) + +**Location**: `projectairsim/unreal/Blocks/Plugins/ProjectAirSim/` + +**Purpose**: Host package (currently an Unreal Plugin) that builds on the sim libs to connect external components (controller, physics, rendering) at runtime that are specific to each configured robot-type scenario (ex. quadrotor drones) + +### 3. Project AirSim Client Library (Interface Layer) + +**Location**: `projectairsim/client/python/projectairsim/` + +**Purpose**: End-user library to enable API calls to interact with the robot and simulation over a network connection + +**Communication Architecture**: +``` +Client Library +├── Connection Management +│ ├── TCP Socket (pynng) +│ ├── Topics (Port 8989) - Pub/Sub +│ └── Services (Port 8990) - Req/Rep +├── API Objects +│ ├── ProjectAirSimClient +│ ├── World +│ └── Drone/Rover +└── Protocol Bridges + ├── ROS1/ROS2 Bridge + └── MAVLink Bridge +``` + +## Drone Interface Architecture + +### Vehicle Control Hierarchy + +``` +Drone Control Interfaces +├── Python API (High-level) +│ ├── Drone Class +│ │ ├── Movement Commands +│ │ │ ├── move_by_velocity_async() +│ │ │ ├── move_to_position_async() +│ │ │ └── rotate_by_yaw_rate_async() +│ │ ├── Sensor Access +│ │ │ ├── get_camera_images() +│ │ │ ├── get_lidar_data() +│ │ │ └── get_imu_data() +│ │ └── State Queries +│ │ ├── get_position() +│ │ ├── get_velocity() +│ │ └── get_orientation() +│ └── World Class +│ ├── Scene Management +│ ├── Weather Control +│ └── Time Management +├── MAVLink Protocol (Low-level) +│ ├── MAVLink API Implementation +│ ├── PX4/ArduPilot Integration +│ └── Ground Control Station Support +└── ROS Integration + ├── ROS2 Node Bridge + ├── Topic Publishing + └── Service Calls +``` + +### Communication Flow + +``` +Control Flow: +User Code → Python API → TCP (pynng) → Unreal Plugin → Sim Libs → Physics Engine + +Data Flow: +Sensors → Sim Libs → Unreal Plugin → TCP (pynng) → Python API → User Code + +MAVLink Flow: +GCS/ROS → MAVLink Protocol → MAVLink API → Vehicle Controller → Physics +``` + +## Communication Logic + +### Network Architecture + +Project AirSim uses a sophisticated multi-channel communication system: + +**1. TCP-based Transport** +- **Library**: pynng (NNG - nanomsg next generation) +- **Ports**: + - Topics: 8989 (Publish/Subscribe pattern) + - Services: 8990 (Request/Response pattern) + +**2. Message Serialization** +- **Primary**: MessagePack with JSON hybrid (MSGPACK_JSON) +- **Fallback**: Pure JSON +- **Security**: Optional client authorization with public key tokens + +**3. Communication Patterns** + +``` +Topics (Pub/Sub - Port 8989): +├── Sensor Data Streaming +│ ├── Camera Images +│ ├── LiDAR Point Clouds +│ ├── IMU Data +│ ├── GPS Coordinates +│ └── Vehicle State +└── System Events + ├── Scene Changes + └── Actor Updates + +Services (Req/Rep - Port 8990): +├── Control Commands +│ ├── Movement Instructions +│ ├── Configuration Changes +│ └── Administrative Actions +└── Synchronous Queries + ├── State Information + └── Configuration Data +``` + +### Protocol Stack + +``` +Application Layer +├── Python Client API +├── ROS Bridge +└── MAVLink Interface + +Transport Layer +├── TCP/IP +├── pynng Sockets +└── Message Serialization + +Simulation Layer +├── Unreal Engine Plugin +├── Physics Integration +└── Sensor Simulation +``` + +## ROS2 Integration + +Project AirSim provides comprehensive ROS2 support through a dedicated bridge package. + +### ROS2 Architecture + +``` +ROS2 Integration +├── ROS2 Node Package +│ ├── projectairsim-ros2/ +│ │ ├── setup.py +│ │ ├── ros2_node.py +│ │ └── ros1_compatibility.py +│ └── Dependencies +│ └── rclpy +├── Bridge Components +│ ├── Publisher Wrappers +│ ├── Subscriber Wrappers +│ └── Service Proxies +└── Message Translation + ├── Sensor Data → ROS Messages + ├── Control Commands ← ROS Messages + └── TF Transformations +``` + +### ROS2 Node Implementation + +The ROS2 bridge (`ros2_node.py`) provides: + +**1. Publisher Implementation** +```python +class Publisher: + - Wraps rclpy.publisher.Publisher + - Handles topic naming + - Manages message publishing +``` + +**2. Subscriber Implementation** +```python +class Subscriber: + - Wraps rclpy.subscription.Subscription + - Manages topic subscriptions + - Handles message callbacks +``` + +**3. Sensor Helper** +```python +class SensorHelper: + - Camera info configuration + - Message format adaptation + - ROS2-specific sensor data handling +``` + +### ROS2 Usage Pattern + +``` +ROS2 Node ←→ Project AirSim Bridge ←→ Simulation Server + +Topics: +├── /airsim/drone/camera ← Camera images +├── /airsim/drone/imu ← IMU data +├── /airsim/drone/lidar ← LiDAR scans +├── /airsim/drone/odom ← Odometry +└── /airsim/drone/cmd_vel → Velocity commands + +Services: +├── /airsim/takeoff → Takeoff service +├── /airsim/land → Landing service +└── /airsim/reset → Reset simulation +``` + +## Creating Architecture Diagrams + +To create visual graphs of this architecture, I recommend using one of these tools: + +### 1. Draw.io (Free, Web-based) +- Create flowcharts and system diagrams +- Export as PNG/SVG/PDF +- Real-time collaboration + +### 2. PlantUML (Text-based) +- Define diagrams in text +- Generate from code comments +- Integrates with documentation + +### 3. Lucidchart or Visio +- Professional diagramming tools +- Template libraries +- Advanced styling options + +### Suggested Diagram Types + +**1. System Context Diagram** +- Show Project AirSim in relation to external systems (ROS, MAVLink GCS, etc.) + +**2. Component Diagram** +- Detail the three main layers and their interactions + +**3. Sequence Diagrams** +- Show communication flows for specific operations (takeoff, sensor reading, etc.) + +**4. Deployment Diagram** +- Show how components are distributed across systems + +--- + +*This architecture enables Project AirSim to serve as a versatile platform for autonomous systems development, supporting everything from simple Python scripting to complex ROS-based robotic applications.* diff --git a/CMakeLists.txt b/CMakeLists.txt index 11e5c7f8..f2c3460d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,6 @@ # --------------------------------------------------------------------------------------------------------------------- # -# Copyright (C) Microsoft Corporation. +# Copyright (C) Microsoft Corporation. # Copyright (C) 2025 IAMAI CONSULTING CORP # # MIT License. All rights reserved. @@ -33,8 +33,8 @@ if (UNIX) link_directories("$ENV{UE_ROOT}/Engine/Source/ThirdParty/Unix/LibCxx/lib/Unix/x86_64-unknown-linux-gnu") else() message("Building/linking against system-installed toolchain") - set(CMAKE_C_COMPILER clang-13) - set(CMAKE_CXX_COMPILER clang++-13) + set(CMAKE_C_COMPILER clang-15) + set(CMAKE_CXX_COMPILER clang++-15) endif() endif() @@ -48,6 +48,7 @@ set(SIMLIBS_TEST_DIR ${CMAKE_BINARY_DIR}/unit_tests) set(UE_PLUGIN_SIMLIBS_DIR ${CMAKE_SOURCE_DIR}/unreal/Blocks/Plugins/ProjectAirSim/SimLibs) set(UNITY_WRAPPER_DLL_DIR ${CMAKE_SOURCE_DIR}/unity/BlocksUnity/Assets/Plugins) set(MATLAB_PHYSICS_DIR ${CMAKE_SOURCE_DIR}/physics/matlab_sfunc) +set(JSBSIM_CORESIM_DIR ${CMAKE_SOURCE_DIR}/core_sim/jsbsim) set(MATLAB_CONTROL_DIR ${CMAKE_SOURCE_DIR}/vehicle_apis/multirotor_api/matlab_sfunc) # set(UE_PLUGIN_CESIUM_NATIVE_DIR ${CMAKE_SOURCE_DIR}/unreal/Blocks/Plugins/ProjectAirSim/SimLibs) # set(UE_CESIUM_PLUGIN_DIR ${CMAKE_SOURCE_DIR}/unreal/Blocks/Plugins/CesiumForUnreal/) @@ -75,13 +76,101 @@ elseif(UNIX) # set(CESIUM_LINUX_TOOLCHAIN ${UE_CESIUM_PLUGIN_DIR}/extern/unreal-linux-toolchain.cmake) endif() +# Set up dependency: jsbsim +message("Setting up [jsbsim] dependency as an external project...") +# CMake external projects don't adopt the parent's CMAKE_MSVC_RUNTIME_LIBRARY setting, +# so to force /MD non-debug CRT to match UE, build Debug config as Relwithdebinfo and +# build Release as Release. +set(JSBSIM_BUILD_TYPE $,Relwithdebinfo,Release>) +set(JSBSIM_SRC_DIR ${CMAKE_BINARY_DIR}/_deps/jsbsim/src/jsbsim-repo) +set(JSBSIM_LIB_DIR ${CMAKE_BINARY_DIR}/_deps/jsbsim-install/lib) +set(JSBSIM_INCLUDE_DIR ${CMAKE_BINARY_DIR}/_deps/jsbsim-install/include/JSBSim) + +# Platform-specific settings for JSBSim +if(WIN32) + set(JSBSIM_C_COMPILER ${CMAKE_C_COMPILER}) + set(JSBSIM_CXX_COMPILER ${CMAKE_CXX_COMPILER}) + set(JSBSIM_CXX_FLAGS "") + set(JSBSIM_BIN_DIR ${CMAKE_BINARY_DIR}/_deps/jsbsim-install/bin) + set(JSBSIM_SHARED_LIB ${JSBSIM_BIN_DIR}/JSBSim.dll) + set(JSBSIM_IMPORT_LIB ${JSBSIM_LIB_DIR}/JSBSim.lib) + set(JSBSIM_BYPRODUCTS ${JSBSIM_SHARED_LIB} ${JSBSIM_IMPORT_LIB}) +else() + set(JSBSIM_C_COMPILER clang) + set(JSBSIM_CXX_COMPILER clang++) + set(JSBSIM_CXX_FLAGS "-stdlib=libc++") + set(JSBSIM_SHARED_LIB ${JSBSIM_LIB_DIR}/libJSBSim.so) + set(JSBSIM_IMPORT_LIB "") + set(JSBSIM_BYPRODUCTS ${JSBSIM_SHARED_LIB}) +endif() + +ExternalProject_Add(jsbsim-repo + GIT_REPOSITORY https://github.com/JSBSim-Team/jsbsim + GIT_TAG "v1.1.12" + GIT_CONFIG "advice.detachedHead=false" + PREFIX ${CMAKE_BINARY_DIR}/_deps/jsbsim + BUILD_COMMAND ${CMAKE_COMMAND} --build --config ${JSBSIM_BUILD_TYPE} + INSTALL_COMMAND ${CMAKE_COMMAND} --build --config ${JSBSIM_BUILD_TYPE} --target install + UPDATE_COMMAND "" # disable update step + CMAKE_ARGS + -DCMAKE_C_COMPILER=${JSBSIM_C_COMPILER} + -DCMAKE_CXX_COMPILER=${JSBSIM_CXX_COMPILER} + -DCMAKE_CXX_FLAGS=${JSBSIM_CXX_FLAGS} + -DCMAKE_POSITION_INDEPENDENT_CODE=True + -DCMAKE_BUILD_TYPE:STRING=${JSBSIM_BUILD_TYPE} + -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_BINARY_DIR}/_deps/jsbsim-install + -DBUILD_SHARED_LIBS=ON + -DBUILD_PYTHON_MODULE=OFF + -DBUILD_DOCS=OFF + # Disable SONAME versioning so libJSBSim.so doesn't require libJSBSim.so.1 symlink at runtime + -DCMAKE_PLATFORM_NO_VERSIONED_SONAME=TRUE + # Fix RPATH issue with Ninja generator + -DCMAKE_BUILD_WITH_INSTALL_RPATH=TRUE + TEST_COMMAND "" # disable test step + BUILD_BYPRODUCTS ${JSBSIM_BYPRODUCTS} + BUILD_ALWAYS 1 +) + +set(JSBSIM_POST_INSTALL_COMMANDS + COMMAND ${CMAKE_COMMAND} -E echo "Copying [jsbsim] library to ${JSBSIM_CORESIM_DIR}" + COMMAND ${CMAKE_COMMAND} -E make_directory "${JSBSIM_CORESIM_DIR}/lib/$,Release,Debug>/" + COMMAND ${CMAKE_COMMAND} -E copy_directory "${JSBSIM_INCLUDE_DIR}" "${JSBSIM_CORESIM_DIR}/include" + COMMAND ${CMAKE_COMMAND} -E copy_directory "${JSBSIM_SRC_DIR}/aircraft" "${JSBSIM_CORESIM_DIR}/models/aircraft" + COMMAND ${CMAKE_COMMAND} -E copy_directory "${JSBSIM_SRC_DIR}/engine" "${JSBSIM_CORESIM_DIR}/models/engine" + COMMAND ${CMAKE_COMMAND} -E copy_directory "${JSBSIM_SRC_DIR}/systems" "${JSBSIM_CORESIM_DIR}/models/systems" + COMMAND ${CMAKE_COMMAND} -E copy_directory "${JSBSIM_SRC_DIR}/scripts" "${JSBSIM_CORESIM_DIR}/models/scripts" + COMMAND ${CMAKE_COMMAND} -E copy "${JSBSIM_SHARED_LIB}" "${JSBSIM_CORESIM_DIR}/lib/$,Release,Debug>/" +) +if(WIN32) + list(APPEND JSBSIM_POST_INSTALL_COMMANDS COMMAND ${CMAKE_COMMAND} -E copy "${JSBSIM_IMPORT_LIB}" "${JSBSIM_CORESIM_DIR}/lib/$,Release,Debug>/") +endif() + +ExternalProject_Add_Step(jsbsim-repo post-install + ${JSBSIM_POST_INSTALL_COMMANDS} + DEPENDEES install +) + +# Add jsbsim as imported library +add_library(jsbsim SHARED IMPORTED) +if(WIN32) + set_target_properties(jsbsim PROPERTIES + IMPORTED_LOCATION ${JSBSIM_SHARED_LIB} + IMPORTED_IMPLIB ${JSBSIM_IMPORT_LIB} + ) +else() + set_target_properties(jsbsim PROPERTIES + IMPORTED_LOCATION ${JSBSIM_SHARED_LIB} + ) +endif() + + # Set up dependency: nlohmann JSON # Directly download single include file json.hpp FetchContent_Declare( nlohmann-json - URL https://raw.githubusercontent.com/nlohmann/json/v3.11.2/single_include/nlohmann/json.hpp - URL_HASH MD5=b1c1ce77d46b72b72f38051d8384c7b8 # from PowerShell: CertUtil -hashfile json.hpp MD5 + URL https://raw.githubusercontent.com/nlohmann/json/v3.11.3/single_include/nlohmann/json.hpp + URL_HASH SHA256=9bea4c8066ef4a1c206b2be5a36302f8926f7fdc6087af5d20b417d0cf103ea6 DOWNLOAD_NO_EXTRACT True DOWNLOAD_NO_PROGRESS True DOWNLOAD_DIR ${CMAKE_BINARY_DIR}/_deps/nlohmann-install @@ -149,6 +238,13 @@ ExternalProject_Add_Step(nng-external post-install DEPENDEES install ) +# Assimp compiler-specific flags +set(ASSIMP_EXTRA_CXX_FLAGS "") + +if (CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU") + set(ASSIMP_EXTRA_CXX_FLAGS "-Wno-error=nontrivial-memcall") +endif() + # Set up dependency: assimp message("Setting up [assimp] dependency as an external project...") # CMake external projects don't adopt the parent's CMAKE_MSVC_RUNTIME_LIBRARY setting, @@ -178,7 +274,8 @@ ExternalProject_Add(assimp-external -DCMAKE_FIND_ROOT_PATH_MODE_PACKAGE=${CMAKE_FIND_ROOT_PATH_MODE_PACKAGE} -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} - -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS} + -DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS}\ ${ASSIMP_EXTRA_CXX_FLAGS} + -DASSIMP_WARNINGS_AS_ERRORS=OFF -DCMAKE_POSITION_INDEPENDENT_CODE=True -DBUILD_SHARED_LIBS=OFF -DASSIMP_BUILD_ZLIB=ON # force build of assimp's packaged zlib in case it detects it existing in a python environment diff --git a/README.md b/README.md index ed6f7d6e..8ef74e86 100644 --- a/README.md +++ b/README.md @@ -83,12 +83,13 @@ See **[Installing system prerequisites](docs/system_specs.md#installing-system-p Follow these steps to set up and run Project AirSim from source: -### 1. Install Unreal Engine 5.2 -- Download and install **[Unreal Engine 5.2](https://www.unrealengine.com/en-US/download)**. +### 1. Install Unreal Engine versions 5.2 or 5.7 +- Download and install **[Unreal Engine](https://www.unrealengine.com/en-US/download)**. - Set the `UE_ROOT` environment variable to the Unreal Engine installation path: ```bash export UE_ROOT=/path/to/UnrealEngine ``` +**Note**: Project AirSim currently supports Unreal Engine versions 5.2 and 5.7 only. ### 2. Install Dependencies (Linux Only) - Run the setup script to install required development tools: @@ -111,13 +112,10 @@ Follow these steps to set up and run Project AirSim from source: - Generate Visual Studio Code project files: - **Linux/macOS**: ```bash - cd ./unreal/Blocks/ - chmod u+x ./blocks_genprojfiles_vscode.sh ./blocks_genprojfiles_vscode.sh ``` - **Windows**: ```cmd - cd .\unreal\Blocks\ blocks_genprojfiles_vscode.bat ``` @@ -164,6 +162,12 @@ See **[Transitioning from AirSim](docs/transition_from_airsim.md)** for guidance Please see the [License page](docs/license.md) for Project AirSim license information. +## Third-Party Interoperability and Licensing + +Project AirSim may interoperate at runtime with third-party tools and data files, including JSBSim-compatible aircraft model definitions. + +Those third-party components and assets remain licensed under their respective open-source licenses by their original authors. + --- Copyright (C) Microsoft Corporation. diff --git a/build.cmd b/build.cmd index 09fd63db..3547a7c3 100644 --- a/build.cmd +++ b/build.cmd @@ -1,26 +1,108 @@ -REM Copyright (C) Microsoft Corporation. +REM Copyright (C) Microsoft Corporation. REM Copyright (C) 2025 IAMAI CONSULTING CORP - REM MIT License. @echo off -setlocal +setlocal ENABLEDELAYEDEXPANSION + set ROOT_DIR=%~dp0 -if "%VisualStudioVersion%" == "16.0" goto ver_ok -if "%VisualStudioVersion%" == "17.0" goto ver_ok +REM ===================================================== +REM Check Visual Studio environment +REM ===================================================== + +if "%VisualStudioVersion%"=="16.0" goto ver_ok +if "%VisualStudioVersion%"=="17.0" goto ver_ok + echo: -echo:You need to run this command from x64 Native Tools Command Prompt for VS 2019 or VS 2022. +echo You need to run this command from x64 Native Tools Command Prompt for VS 2019 or VS 2022. goto :buildfailed_nomsg :ver_ok + where /q nmake if errorlevel 1 ( echo: - echo:nmake not found. + echo nmake not found. goto :buildfailed_nomsg ) +REM ===================================================== +REM Unreal Engine detection (OPTIONAL) +REM UE_ROOT is optional to allow standalone / Unity builds +REM ===================================================== + +set UE_DETECTED=0 +set UE_MINOR= + +if "%UE_ROOT%"=="" ( + echo: + echo UE_ROOT not set. Building without Unreal Engine integration. + goto :select_msvc_default +) + +set BUILD_VERSION_FILE=%UE_ROOT%\Engine\Build\Build.version + +if not exist "%BUILD_VERSION_FILE%" ( + echo: + echo UE_ROOT is set but Build.version not found: + echo %BUILD_VERSION_FILE% + echo Falling back to standalone build. + goto :select_msvc_default +) + +for /f "tokens=2 delims=:," %%A in ('findstr /i "MinorVersion" "%BUILD_VERSION_FILE%"') do ( + set UE_MINOR=%%A +) + +set UE_MINOR=%UE_MINOR: =% + +echo Detected Unreal Engine version: 5.%UE_MINOR% +set UE_DETECTED=1 + +REM ===================================================== +REM Select MSVC version (UE-aware) +REM ===================================================== + +if "%UE_MINOR%"=="2" ( + set MSVC_VER=14.37 +) else if "%UE_MINOR%"=="7" ( + set MSVC_VER=14.39 +) else ( + echo: + echo Unsupported Unreal Engine version 5.%UE_MINOR% + echo Falling back to default toolset. + goto :select_msvc_default +) + +goto :msvc_ready + +REM ===================================================== +REM Default MSVC (standalone / Unity) +REM ===================================================== + +:select_msvc_default +echo Using default MSVC toolset (standalone / Unity build) +set MSVC_VER=14.37 + +REM ===================================================== +REM Initialize MSVC environment +REM ===================================================== + +:msvc_ready + +echo Using MSVC toolset version: %MSVC_VER% + +call "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvarsall.bat" x64 -vcvars_ver=%MSVC_VER% +if errorlevel 1 ( + echo: + echo [WARNING] Failed to initialize MSVC %MSVC_VER% +) + +REM ===================================================== +REM Build +REM ===================================================== + nmake /f build_windows.mk %* if errorlevel 1 ( goto :buildfailed_nomsg @@ -28,8 +110,12 @@ if errorlevel 1 ( exit /b 0 +REM ===================================================== +REM Error handling +REM ===================================================== + :buildfailed_nomsg chdir /d %ROOT_DIR% echo: - echo:Build Failed. + echo Build Failed. exit /b 1 diff --git a/client/python/example_user_scripts/hello_fixed_wing.py b/client/python/example_user_scripts/hello_fixed_wing.py new file mode 100644 index 00000000..cb5c03b3 --- /dev/null +++ b/client/python/example_user_scripts/hello_fixed_wing.py @@ -0,0 +1,151 @@ +""" +Copyright (C) Microsoft Corporation. All rights reserved. + +Demonstrates flying a quadrotor drone with camera sensors. +""" + +import asyncio +import math + +from projectairsim import ProjectAirSimClient, Drone, World +from projectairsim.utils import projectairsim_log +from projectairsim.image_utils import ImageDisplay + + +# Async main function to wrap async drone commands +async def main(): + # Create a Project AirSim client + client = ProjectAirSimClient() + + # Initialize an ImageDisplay object to display camera sub-windows + image_display = ImageDisplay() + + try: + # Connect to simulation environment + client.connect() + + # Create a World object to interact with the sim world and load a scene + world = World(client, "scene_cessna310.jsonc", delay_after_load_sec=2) + + # Create a Drone object to interact with a drone in the loaded sim world + drone = Drone(client, world, "c310") +# + ## ------------------------------------------------------------------------------ +# + ## Subscribe to chase camera sensor as a client-side pop-up window + #chase_cam_window = "ChaseCam" + #image_display.add_chase_cam(chase_cam_window) + #client.subscribe( + # drone.sensors["DownCamera"]["scene_camera"], + # lambda _, chase: image_display.receive(chase, chase_cam_window), + #) +# + ## Subscribe to the downward-facing camera sensor's RGB and Depth images + #rgb_name = "RGB-Image" + #image_display.add_image(rgb_name, subwin_idx=0) + #client.subscribe( + # drone.sensors["DownCamera"]["scene_camera"], + # lambda _, rgb: image_display.receive(rgb, rgb_name), + #) +# + #depth_name = "Depth-Image" + #image_display.add_image(depth_name, subwin_idx=2) + #client.subscribe( + # drone.sensors["DownCamera"]["depth_camera"], + # lambda _, depth: image_display.receive(depth, depth_name), + #) +# + #image_display.start() +# + ## ------------------------------------------------------------------------------ +# + ## Set the drone to be ready to fly + ## JSBSim robot currently does not support control the drone at runtime + #drone.enable_api_control() + ##set brakes to 1 + #drone.set_brakes(1) + #drone.arm() +# + ## ------------------------------------------------------------------------------ +# + ## set takeoff z to 120 meters + #drone.set_take_off_z(-120) +# + ## ------------------------------------------------------------------------------ +# + ## Sleep for two seconds to + #await asyncio.sleep(2) + # + ## release brakes + #drone.set_brakes(0) +# + #projectairsim_log().info("takeoff_async: starting") + #takeoff_task = ( + # await drone.takeoff_async(timeout_sec=1200) + #) # schedule an async task to start the command +# + #await takeoff_task + #projectairsim_log().info("takeoff_async: completed") +# + #projectairsim_log().info("Waiting to stabilize altitude... (10 seconds)") + #await asyncio.sleep(10) +# + ## ------------------------------------------------------------------------------ + # + ## Command the drone to move to position 1000,1000,-200 + #move_up_task = await drone.move_to_position_async( + # north=1000, east=1000, down=-200, velocity=33.0, lookahead=100, timeout_sec=60 + #) + #projectairsim_log().info("Move to position 1000,1000,-200 invoked") +# + #await move_up_task + #projectairsim_log().info("Move to position completed") +# + ## ------------------------------------------------------------------------------ +# + ## Command vehicle to fly at a specific heading and speed + #projectairsim_log().info("Heading 90 invoked") + #heading_45_task = await drone.move_by_heading_async( + # heading=math.radians(90.0), speed=20.0, duration=10 + #) + #await heading_45_task + #projectairsim_log().info("Heading 90 complete.") +# + ## ------------------------------------------------------------------------------ +# + ## Command the drone to move to position 0,0,-100 + #move_up_task = await drone.move_to_position_async( + # north=0, east=0, down=-100, velocity=33.0, lookahead=100, timeout_sec=60 + #) + #projectairsim_log().info("Move to position 0,0,-100 invoked") +# + #await move_up_task + #projectairsim_log().info("Move to position completed") + ## ------------------------------------------------------------------------------ +# + #projectairsim_log().info("land_async: starting") + #land_task = await drone.land_async() + #await land_task + #projectairsim_log().info("land_async: completed") + ## set brakes to 50% + #drone.set_brakes(0.5) + + # ------------------------------------------------------------------------------ + + # Shut down the drone + drone.disarm() + drone.disable_api_control() + + # logs exception on the console + except Exception as err: + projectairsim_log().error(f"Exception occurred: {err}", exc_info=True) + + finally: + # Always disconnect from the simulation environment to allow next connection + client.disconnect() + + image_display.stop() + + +if __name__ == "__main__": + asyncio.run(main()) # Runner for async main function \ No newline at end of file diff --git a/client/python/example_user_scripts/jsbsim_env_actor.py b/client/python/example_user_scripts/jsbsim_env_actor.py deleted file mode 100644 index 652d047a..00000000 --- a/client/python/example_user_scripts/jsbsim_env_actor.py +++ /dev/null @@ -1,61 +0,0 @@ -""" -Copyright (C) Microsoft Corporation. -Copyright (C) 2025 IAMAI CONSULTING CORP -MIT License. -Demo client script to demonstrate the use of environment -actors with a trajectory imported from a JSBSim script -and set via client API. The trajectory can be used by -multiple actors with some global offset. - -Usage: - cd jsbsim - python jsbsim_trajectory_generator.py \ - --root="{JSBSim root folder}" \ - --script={JSBSim script path} \ - --out=JSBSimTrajectory.csv - cd .. - python jsbsim_env_actor.py -""" -from projectairsim import ProjectAirSimClient, World, EnvActor -from projectairsim.utils import projectairsim_log -import asyncio - - -async def env_actor_motion_plan(env_actor: EnvActor, world: World): - """Assign JSBSim trajectory to the env_actor. - - Arguments: - env_actor -- EnvActor object - world {World} -- ProjectAirSim World - """ - - traj_name = "JSBSimTrajectory" - world.import_ned_trajectory_from_csv(traj_name, "./jsbsim/JSBSimTrajectory.csv") - env_actor.set_trajectory(traj_name, x_offset= 20, y_offset= -10,z_offset= - 10) - projectairsim_log().info("Executing...") - - -if __name__ == "__main__": - - client = ProjectAirSimClient() - - try: - # Connect to simulation environment - client.connect() - - # Create a world object to interact with the ProjectAirSim world and load a scene - # Set scene file to scene_env_actor.jsonc - world = World(client, "scene_jsbsim_env_actor.jsonc", delay_after_load_sec=2) - - # Create env actor objects to interact with those in the loaded world - env_actor1 = EnvActor(client, world, "env_actor") - - # Run the async function to execute the async drone commands - asyncio.run(env_actor_motion_plan(env_actor1, world)) - - except Exception as err: - projectairsim_log().error(f"Exception occurred: {err}", exc_info=True) - - finally: - # Always disconnect from the simulation environment to allow next connection - client.disconnect() diff --git a/client/python/example_user_scripts/jsbsim_rc_control.py b/client/python/example_user_scripts/jsbsim_rc_control.py new file mode 100644 index 00000000..7694e068 --- /dev/null +++ b/client/python/example_user_scripts/jsbsim_rc_control.py @@ -0,0 +1,183 @@ +""" +Copyright (C) Microsoft Corporation. +Copyright (C) 2025 IAMAI CONSULTING CORP +MIT License. + +Demonstrates controlling a JSBSim aircraft in Project AirSim with a gamepad. +""" + +import argparse +from enum import Enum + +from projectairsim import ProjectAirSimClient, World, Drone +from projectairsim.utils import projectairsim_log + +try: + from inputs import get_gamepad +except ImportError as err: + raise ImportError( + "The 'inputs' package is required. Install with: pip install inputs" + ) from err + + +JOYSTICK_MIN = -32768.0 +JOYSTICK_MAX = 32767.0 + + +def normalize_signed_axis(value: int) -> float: + return max(-1.0, min(1.0, float(value) / 32768.0)) + + +def normalize_throttle(value: int) -> float: + signed = normalize_signed_axis(value) + return max(0.0, min(1.0, (signed + 1.0) * 0.5)) + + +class RemoteControlReader: + """Manages input from an Xbox-compatible game controller.""" + + def __init__(self): + self.input_state = { + "joystick_RH": 0, + "joystick_RV": 0, + "joystick_LH": 0, + "joystick_LV": 0, + } + + def read(self): + updated_input = False + + while not updated_input: + events = get_gamepad() + for event in events: + recognized_event = True + if event.ev_type == "Absolute": + if event.code == "ABS_X": + self.input_state["joystick_LH"] = event.state + elif event.code == "ABS_Y": + self.input_state["joystick_LV"] = event.state + elif event.code == "ABS_RX": + self.input_state["joystick_RH"] = event.state + elif event.code == "ABS_RY": + self.input_state["joystick_RV"] = event.state + else: + recognized_event = False + else: + recognized_event = False + + if recognized_event: + updated_input = True + + return self.input_state + + +class ControlType(Enum): + RPY = "mode1" # Roll, Pitch, Yaw + TCS = "mode2" # Turn rate, climb rate, speed + + +def apply_rpy_mode(drone: Drone, input_state): + throttle = normalize_throttle(input_state["joystick_RV"]) + roll = normalize_signed_axis(input_state["joystick_RH"]) + pitch = normalize_signed_axis(input_state["joystick_LV"]) + yaw = normalize_signed_axis(input_state["joystick_LH"]) + + drone.set_jsbsim_property("fcs/throttle-cmd-norm[0]", throttle) + drone.set_jsbsim_property("fcs/throttle-cmd-norm[1]", throttle) + drone.set_jsbsim_property("fcs/aileron-cmd-norm", roll) + drone.set_jsbsim_property("fcs/elevator-cmd-norm", pitch) + drone.set_jsbsim_property("fcs/rudder-cmd-norm", yaw) + + +def apply_tcs_mode(drone: Drone, input_state): + throttle = normalize_throttle(input_state["joystick_RV"]) + turn_cmd = normalize_signed_axis(input_state["joystick_LH"]) + climb_cmd = normalize_signed_axis(input_state["joystick_LV"]) + + drone.set_jsbsim_property("fcs/throttle-cmd-norm[0]", throttle) + drone.set_jsbsim_property("fcs/throttle-cmd-norm[1]", throttle) + drone.set_jsbsim_property("ap/heading-comm", turn_cmd) + drone.set_jsbsim_property("ap/climb-rate-cmd", climb_cmd) + + +def control_loop( + drone: Drone, + user_mode: ControlType, + rc_reader: RemoteControlReader, + print_rc: bool = True, +): + input_state = rc_reader.read() + + if print_rc: + print( + f"Left=({input_state['joystick_LH']:6n},{input_state['joystick_LV']:6n}), " + f"Right=({input_state['joystick_RH']:6n},{input_state['joystick_RV']:6n}), ", + end="\r", + ) + + if user_mode == ControlType.RPY: + apply_rpy_mode(drone, input_state) + elif user_mode == ControlType.TCS: + apply_tcs_mode(drone, input_state) + + +def parse_args(): + parser = argparse.ArgumentParser( + description="Controla un avión JSBSim en ProjectAirSim usando gamepad." + ) + parser.add_argument( + "mode", + nargs="?", + choices=[ControlType.RPY.value, ControlType.TCS.value], + default=ControlType.RPY.value, + help="mode1=RPY, mode2=TCS", + ) + parser.add_argument("--address", type=str, default="127.0.0.1") + parser.add_argument("--topicsport", type=int, default=8989) + parser.add_argument("--servicesport", type=int, default=8990) + parser.add_argument("--sceneconfigfile", type=str, default="scene_cessna310_rc.jsonc") + parser.add_argument("--simconfigpath", type=str, default="sim_config/") + parser.add_argument("--robot", type=str, default="c310") + parser.add_argument("--delay", type=int, default=2) + return parser.parse_args() + + +def main(): + args = parse_args() + user_mode = ControlType(args.mode) + projectairsim_log().info(f"Control mode selected: {user_mode.value}") + + client = ProjectAirSimClient( + address=args.address, + port_topics=args.topicsport, + port_services=args.servicesport, + ) + rc_reader = RemoteControlReader() + + try: + client.connect() + world = World( + client=client, + scene_config_name=args.sceneconfigfile, + delay_after_load_sec=args.delay, + sim_config_path=args.simconfigpath, + ) + drone = Drone(client, world, args.robot) + + drone.enable_api_control() + + while True: + control_loop(drone, user_mode, rc_reader) + + except KeyboardInterrupt: + print("\nExiting...") + finally: + try: + drone.disable_api_control() + except Exception: + pass + client.disconnect() + + +if __name__ == "__main__": + main() diff --git a/client/python/example_user_scripts/keyboard_control.py b/client/python/example_user_scripts/keyboard_control.py new file mode 100644 index 00000000..00e9e2cd --- /dev/null +++ b/client/python/example_user_scripts/keyboard_control.py @@ -0,0 +1,192 @@ +import argparse +import asyncio +import time +import projectairsim +from projectairsim import Drone, World +import keyboard + +# --- Drone Control Functions --- + +async def takeoff(drone): + """Arms the drone and takes off to a default altitude.""" + print("Arming the drone...") + drone.arm() + print("Taking off...") + await drone.takeoff_async() + time.sleep(1) + + +async def land(drone): + """Lands the drone.""" + print("Landing...") + await drone.land_async() + print("Disarming the drone...") + drone.disarm() + +# --- Main Control Loop --- + +async def run_keyboard_control(drone): + """ + Controls the drone using keyboard inputs. + + Args: + drone: The Drone object. + """ + + # Enable API control + drone.enable_api_control() + + # Takeoff + await takeoff(drone) + + # Speed settings + speed = 5 # m/s + yaw_speed = 20 # degrees/s + duration = 0.1 # seconds + + print("\n--- Keyboard Control ---") + print("W/S: Pitch (Forward/Backward)") + print("A/D: Roll (Left/Right)") + print("Up/Down Arrows: Throttle (Altitude)") + print("Left/Right Arrows: Yaw (Rotation)") + print("L: Land") + print("Q: Quit") + print("--------------------") + + keep_running = True + + while keep_running: + # Reset velocity components + vx, vy, vz, yaw_rate = 0, 0, 0, 0 + + # Pitch + if keyboard.is_pressed('w'): + vx = speed + + elif keyboard.is_pressed('s'): + vx = -speed + + # Roll + if keyboard.is_pressed('a'): + vy = -speed + + elif keyboard.is_pressed('d'): + vy = speed + + # Throttle + if keyboard.is_pressed('up'): + vz = -speed # Negative Z is up + + elif keyboard.is_pressed('down'): + vz = speed + + # Yaw + if keyboard.is_pressed('left'): + yaw_rate = -yaw_speed + + elif keyboard.is_pressed('right'): + yaw_rate = yaw_speed + + # Land and exit + if keyboard.is_pressed('l'): + await land(drone) + keep_running = False + + # Quit + if keyboard.is_pressed('q'): + keep_running = False + + # Move the drone in its body frame + # vx, vy, vz are now interpreted as forward/backward, right/left, up/down relative to the drone + if vx != 0 or vy != 0 or vz != 0: + await drone.move_by_velocity_body_frame_async(vx, vy, vz, duration) + if yaw_rate != 0: + await drone.rotate_by_yaw_rate_async(yaw_rate, duration) + await asyncio.sleep(0.01) + +# --- Main Execution --- + +async def main(): + parser = argparse.ArgumentParser( + description="Example of using keyboard to control a drone in Project AirSim." + ) + + # ... (parser arguments remain the same) ... + parser.add_argument( + "--address", + help=("the IP address of the host running Project AirSim"), + type=str, + default="127.0.0.1", + ) + + parser.add_argument( + "--sceneconfigfile", + help=( + 'the Project AirSim scene config file to load, defaults to "scene_basic_drone.jsonc"' + ), + + type=str, + default="scene_basic_drone.jsonc", + ) + + parser.add_argument( + "--simconfigpath", + help=( + 'the directory containing Project AirSim config files, defaults to "sim_config"' + ), + type=str, + default="sim_config/", + ) + + parser.add_argument( + "--topicsport", + help=( + "the TCP/IP port of Project AirSim's topic pub-sub client connection " + '(see the Project AirSim command line switch "-topicsport")' + ), + type=int, + default=8989, + ) + + parser.add_argument( + "--servicesport", + help=( + "the TCP/IP port of Project AirSim's services client connection " + '(see the Project AirSim command line switch "-servicessport")' + ), + type=int, + default=8990, + ) + + args = parser.parse_args() + client = projectairsim.ProjectAirSimClient( + address=args.address, + port_topics=args.topicsport, + port_services=args.servicesport, + ) + + drone = None + try: + client.connect() + world = projectairsim.World( + client=client, + scene_config_name=args.sceneconfigfile, + sim_config_path=args.simconfigpath, + ) + drone = Drone(client, world, "Drone1") + + await run_keyboard_control(drone) + + except Exception as e: + print(f"An error occurred: {e}") + + finally: + if drone: + drone.disarm() + drone.disable_api_control() + client.disconnect() + + print("Cleaned up and disconnected.") + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/client/python/example_user_scripts/sim_config/robot_cessna310.jsonc b/client/python/example_user_scripts/sim_config/robot_cessna310.jsonc new file mode 100644 index 00000000..45ed35f7 --- /dev/null +++ b/client/python/example_user_scripts/sim_config/robot_cessna310.jsonc @@ -0,0 +1,283 @@ +{ + "physics-type": "jsbsim-physics", + "jsbsim-script": "scripts/c3104.xml", + "jsbsim-model": "c310", + "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": { + "enabled": false, + "restitution": 0.1, + "friction": 0.5 + }, + "visual": { + "geometry": { + "type": "unreal_mesh", + "name": "/Drone/AirTaxi/AirTaxi_Fuselage" + } + } + }, + { + "name": "Prop_FL", + "inertial": { + "origin": { + "xyz": "0.253 -0.253 -0.01", + "rpy": "0 0 0" + }, + "mass": 0.055, + "inertia": { + "type": "point-mass" + }, + "aerodynamics": { + "drag-coefficient": 0.325, + "type": "geometry", + "geometry": { + "cylinder": { + "radius": 1, + "length": 0.01 + } + } + } + }, + "visual": { + "origin": { + "xyz": "7 0.0 0.0", + "rpy": "0 -1.5707963267948966 0" + }, + "geometry": { + "type": "unreal_mesh", + "name": "/Drone/AirTaxi/AirTaxi_Rotor" + } + } + } + ], + "joints": [ + { + "id": "Frame_Prop_FL", + "type": "fixed", + "parent-link": "Frame", + "child-link": "Prop_FL", + "axis": "1 0 0" + } + ], + "controller": { + "id": "JSBSim_Controller", + "airframe-setup": "fixed-wing", + "type": "jsbsim-api" + //"jsbsim-api-settings": { + //} + }, + "actuators": [ + { + "name": "fcs/throttle-cmd-norm", + "type": "rotor", + "enabled": true, + "parent-link": "Frame", + "child-link": "Prop_FL", + "origin": { + "xyz": "0.253 -0.253 -0.01", + "rpy": "0 0 0" + }, + "rotor-settings": { + "turning-direction": "clock-wise", + "normal-vector": "1.0 0.0 0.0", + "coeff-of-thrust": 0.109919, + "coeff-of-torque": 0.040164, + "max-rpm": 6396.667, + "propeller-diameter": 0.2286, + "smoothing-tc": 0.005 + } + } + ], + "sensors": [ + { + "id": "Chase", + "type": "camera", + "enabled": true, + "parent-link": "Frame", + "capture-interval": 0.03, + "capture-settings": [ + { + "image-type": 0, + "width": 1280, + "height": 720, + "fov-degrees": 90, + "capture-enabled": false, + "streaming-enabled": true, + "pixels-as-float": false, + "compress": false, + "target-gamma": 2.5 + } + ], + "gimbal": { + "lock-roll": true, + "lock-pitch": true, + "lock-yaw": false + }, + "origin": { + "xyz": "-50.0 0.0 0", + "rpy": "0 0 0" + } + }, + { + "id": "DownCamera", + "type": "camera", + "enabled": true, + "parent-link": "Frame", + "capture-interval": 0.02, + "capture-settings": [ + { + "image-type": 0, // scene camera + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": true, + "streaming-enabled": false, + "pixels-as-float": false, + "compress": false, + "target-gamma": 2.5 + }, + { + "image-type": 1, // depth planar + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": false, + "streaming-enabled": false, + "pixels-as-float": true, + "compress": false + }, + { + "image-type": 2, // depth perspective + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": true, + "streaming-enabled": false, + "pixels-as-float": true, + "compress": false + }, + { + "image-type": 3, // segmentation + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": false, + "streaming-enabled": false, + "pixels-as-float": false, + "compress": false + }, + { + "image-type": 4, // depth vis + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": false, + "streaming-enabled": false, + "pixels-as-float": false, + "compress": false, + "max-depth-meters": 100 + }, + { + "image-type": 5, // disparity normalized + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": false, + "streaming-enabled": false, + "pixels-as-float": false, + "compress": false + }, + { + "image-type": 6, // surface normals + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": false, + "streaming-enabled": false, + "pixels-as-float": false, + "compress": false + } + ], + "noise-settings": [ + { + "enabled": false, + "image-type": 1, + "rand-contrib": 0.2, + "rand-speed": 100000.0, + "rand-size": 500.0, + "rand-density": 2, + "horz-wave-contrib": 0.03, + "horz-wave-strength": 0.08, + "horz-wave-vert-size": 1.0, + "horz-wave-screen-size": 1.0, + "horz-noise-lines-contrib": 1.0, + "horz-noise-lines-density-y": 0.01, + "horz-noise-lines-density-xy": 0.5, + "horz-distortion-contrib": 1.0, + "horz-distortion-strength": 0.002 + } + ], + "origin": { + "xyz": "0 0.0 0.0", + "rpy": "0 -1.5708 0" + } + }, + { + "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": false, + "parent-link": "Frame" + }, + { + "id": "Barometer", + "type": "barometer", + "enabled": false, + "parent-link": "Frame" + }, + { + "id": "Magnetometer", + "type": "magnetometer", + "enabled": false, + "parent-link": "Frame" + } + ] +} \ No newline at end of file diff --git a/client/python/example_user_scripts/sim_config/robot_cessna310_rc.jsonc b/client/python/example_user_scripts/sim_config/robot_cessna310_rc.jsonc new file mode 100644 index 00000000..c08a0d28 --- /dev/null +++ b/client/python/example_user_scripts/sim_config/robot_cessna310_rc.jsonc @@ -0,0 +1,283 @@ +{ + "physics-type": "jsbsim-physics", + "jsbsim-script": "scripts/c3104_rc.xml", + "jsbsim-model": "c310", + "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": { + "enabled": false, + "restitution": 0.1, + "friction": 0.5 + }, + "visual": { + "geometry": { + "type": "unreal_mesh", + "name": "/Drone/AirTaxi/AirTaxi_Fuselage" + } + } + }, + { + "name": "Prop_FL", + "inertial": { + "origin": { + "xyz": "0.253 -0.253 -0.01", + "rpy": "0 0 0" + }, + "mass": 0.055, + "inertia": { + "type": "point-mass" + }, + "aerodynamics": { + "drag-coefficient": 0.325, + "type": "geometry", + "geometry": { + "cylinder": { + "radius": 1, + "length": 0.01 + } + } + } + }, + "visual": { + "origin": { + "xyz": "7 0.0 0.0", + "rpy": "0 -1.5707963267948966 0" + }, + "geometry": { + "type": "unreal_mesh", + "name": "/Drone/AirTaxi/AirTaxi_Rotor" + } + } + } + ], + "joints": [ + { + "id": "Frame_Prop_FL", + "type": "fixed", + "parent-link": "Frame", + "child-link": "Prop_FL", + "axis": "1 0 0" + } + ], + "controller": { + "id": "JSBSim_Controller", + "airframe-setup": "fixed-wing", + "type": "jsbsim-api" + //"jsbsim-api-settings": { + //} + }, + "actuators": [ + { + "name": "fcs/throttle-cmd-norm", + "type": "rotor", + "enabled": true, + "parent-link": "Frame", + "child-link": "Prop_FL", + "origin": { + "xyz": "0.253 -0.253 -0.01", + "rpy": "0 0 0" + }, + "rotor-settings": { + "turning-direction": "clock-wise", + "normal-vector": "1.0 0.0 0.0", + "coeff-of-thrust": 0.109919, + "coeff-of-torque": 0.040164, + "max-rpm": 6396.667, + "propeller-diameter": 0.2286, + "smoothing-tc": 0.005 + } + } + ], + "sensors": [ + { + "id": "Chase", + "type": "camera", + "enabled": true, + "parent-link": "Frame", + "capture-interval": 0.03, + "capture-settings": [ + { + "image-type": 0, + "width": 1280, + "height": 720, + "fov-degrees": 90, + "capture-enabled": false, + "streaming-enabled": true, + "pixels-as-float": false, + "compress": false, + "target-gamma": 2.5 + } + ], + "gimbal": { + "lock-roll": true, + "lock-pitch": true, + "lock-yaw": false + }, + "origin": { + "xyz": "-50.0 0.0 0", + "rpy": "0 0 0" + } + }, + { + "id": "DownCamera", + "type": "camera", + "enabled": true, + "parent-link": "Frame", + "capture-interval": 0.02, + "capture-settings": [ + { + "image-type": 0, // scene camera + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": true, + "streaming-enabled": false, + "pixels-as-float": false, + "compress": false, + "target-gamma": 2.5 + }, + { + "image-type": 1, // depth planar + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": false, + "streaming-enabled": false, + "pixels-as-float": true, + "compress": false + }, + { + "image-type": 2, // depth perspective + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": true, + "streaming-enabled": false, + "pixels-as-float": true, + "compress": false + }, + { + "image-type": 3, // segmentation + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": false, + "streaming-enabled": false, + "pixels-as-float": false, + "compress": false + }, + { + "image-type": 4, // depth vis + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": false, + "streaming-enabled": false, + "pixels-as-float": false, + "compress": false, + "max-depth-meters": 100 + }, + { + "image-type": 5, // disparity normalized + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": false, + "streaming-enabled": false, + "pixels-as-float": false, + "compress": false + }, + { + "image-type": 6, // surface normals + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": false, + "streaming-enabled": false, + "pixels-as-float": false, + "compress": false + } + ], + "noise-settings": [ + { + "enabled": false, + "image-type": 1, + "rand-contrib": 0.2, + "rand-speed": 100000.0, + "rand-size": 500.0, + "rand-density": 2, + "horz-wave-contrib": 0.03, + "horz-wave-strength": 0.08, + "horz-wave-vert-size": 1.0, + "horz-wave-screen-size": 1.0, + "horz-noise-lines-contrib": 1.0, + "horz-noise-lines-density-y": 0.01, + "horz-noise-lines-density-xy": 0.5, + "horz-distortion-contrib": 1.0, + "horz-distortion-strength": 0.002 + } + ], + "origin": { + "xyz": "0 0.0 0.0", + "rpy": "0 -1.5708 0" + } + }, + { + "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": false, + "parent-link": "Frame" + }, + { + "id": "Barometer", + "type": "barometer", + "enabled": false, + "parent-link": "Frame" + }, + { + "id": "Magnetometer", + "type": "magnetometer", + "enabled": false, + "parent-link": "Frame" + } + ] +} \ No newline at end of file diff --git a/client/python/example_user_scripts/sim_config/robot_quadtiltrotor_fastphysics.jsonc b/client/python/example_user_scripts/sim_config/robot_quadtiltrotor_fastphysics.jsonc index f8016b5e..f1f4b77a 100644 --- a/client/python/example_user_scripts/sim_config/robot_quadtiltrotor_fastphysics.jsonc +++ b/client/python/example_user_scripts/sim_config/robot_quadtiltrotor_fastphysics.jsonc @@ -1,57 +1,25 @@ { + "$schema":"../../projectairsim/src/projectairsim/schema/robot_config_schema.jsonc", "physics-type": "fast-physics", "links": [ { "name": "Frame", "inertial": { - "mass": 10.0, - "inertia": { - "type": "geometry", - "geometry": { - "box": { - "size": "3.2 3.2 2.68" - } - } - }, - "aerodynamics": { - "drag-coefficient": 0.04, - "type": "geometry", - "geometry": { - "box": { - "size": "3.2 3.2 2.68" - } - } - } - }, - "collision": { - "restitution": 0.1, - "friction": 0.5 - }, - "visual": { - "geometry": { - "type": "unreal_mesh", - "name": "/Drone/AirTaxi/AirTaxi_Fuselage" - } - } - }, - { - "name": "Shroud_FL", - "inertial": { - "mass": 0.0, + "mass": 1.0, "inertia": { "type": "geometry", "geometry": { "box": { - "size": "2.10 2.10 0.32" + "size": "0.180 0.110 0.040" } } }, "aerodynamics": { - "drag-coefficient": 0.0, + "drag-coefficient": 0.325, "type": "geometry", "geometry": { "box": { - "size": "2.10 2.10 0.32" + "size": "0.180 0.110 0.040" } } } @@ -61,13 +29,9 @@ "friction": 0.5 }, "visual": { - "origin": { - "xyz": "2.00 -2.59 -0.6543", - "rpy-deg": "0 0 -30" - }, "geometry": { "type": "unreal_mesh", - "name": "/Drone/AirTaxi/AirTaxi_Shroud" + "name": "/Drone/Quadrotor1" } } }, @@ -75,69 +39,32 @@ "name": "Prop_FL", "inertial": { "origin": { - "xyz": "2.00 -2.59 -0.6543", + "xyz": "0.253 -0.253 -0.01", "rpy-deg": "0 0 0" }, - "mass": 0.0, + "mass": 0.055, "inertia": { "type": "point-mass" }, "aerodynamics": { - "drag-coefficient": 0.0, + "drag-coefficient": 0.325, "type": "geometry", "geometry": { "cylinder": { - "radius": 0.79, - "length": 0.29 + "radius": 0.1143, + "length": 0.01 } } } }, "visual": { "origin": { - "xyz": "2.00 -2.59 -0.6543", + "xyz": "0.253 -0.253 -0.01", "rpy-deg": "0 0 0" }, "geometry": { "type": "unreal_mesh", - "name": "/Drone/AirTaxi/AirTaxi_Rotor" - } - } - }, - { - "name": "Shroud_FR", - "inertial": { - "mass": 1.0, - "inertia": { - "type": "geometry", - "geometry": { - "box": { - "size": "2.10 2.10 0.32" - } - } - }, - "aerodynamics": { - "drag-coefficient": 0.0, - "type": "geometry", - "geometry": { - "box": { - "size": "2.10 2.10 0.32" - } - } - } - }, - "collision": { - "restitution": 0.1, - "friction": 0.5 - }, - "visual": { - "origin": { - "xyz": "2.00 2.59 -0.6543", - "rpy-deg": "0 0 30" - }, - "geometry": { - "type": "unreal_mesh", - "name": "/Drone/AirTaxi/AirTaxi_Shroud" + "name": "/Drone/PropellerRed" } } }, @@ -145,69 +72,32 @@ "name": "Prop_FR", "inertial": { "origin": { - "xyz": "2.00 2.59 -0.6543", + "xyz": "0.253 0.253 -0.01", "rpy-deg": "0 0 0" }, - "mass": 0.0, + "mass": 0.055, "inertia": { "type": "point-mass" }, "aerodynamics": { - "drag-coefficient": 0.0, + "drag-coefficient": 0.325, "type": "geometry", "geometry": { "cylinder": { - "radius": 0.79, - "length": 0.29 + "radius": 0.1143, + "length": 0.01 } } } }, "visual": { "origin": { - "xyz": "2.00 2.59 -0.6543", + "xyz": "0.253 0.253 -0.01", "rpy-deg": "0 0 0" }, "geometry": { "type": "unreal_mesh", - "name": "/Drone/AirTaxi/AirTaxi_Rotor" - } - } - }, - { - "name": "Shroud_RL", - "inertial": { - "mass": 0.0, - "inertia": { - "type": "geometry", - "geometry": { - "box": { - "size": "2.10 2.10 0.32" - } - } - }, - "aerodynamics": { - "drag-coefficient": 0.0, - "type": "geometry", - "geometry": { - "box": { - "size": "2.10 2.10 0.32" - } - } - } - }, - "collision": { - "restitution": 0.1, - "friction": 0.5 - }, - "visual": { - "origin": { - "xyz": "-1.5 -2.6225 -2.395", - "rpy-deg": "0 0 -30" - }, - "geometry": { - "type": "unreal_mesh", - "name": "/Drone/AirTaxi/AirTaxi_Shroud" + "name": "/Drone/PropellerRed" } } }, @@ -215,69 +105,32 @@ "name": "Prop_RL", "inertial": { "origin": { - "xyz": "-1.5 -2.6225 -2.395", + "xyz": "-0.253 -0.253 -0.01", "rpy-deg": "0 0 0" }, - "mass": 0.0, + "mass": 0.055, "inertia": { "type": "point-mass" }, "aerodynamics": { - "drag-coefficient": 0.0, + "drag-coefficient": 0.325, "type": "geometry", "geometry": { "cylinder": { - "radius": 0.79, - "length": 0.29 + "radius": 0.1143, + "length": 0.01 } } } }, "visual": { "origin": { - "xyz": "-1.5 -2.6225 -2.395", + "xyz": "-0.253 -0.253 -0.01", "rpy-deg": "0 0 0" }, "geometry": { "type": "unreal_mesh", - "name": "/Drone/AirTaxi/AirTaxi_Rotor" - } - } - }, - { - "name": "Shroud_RR", - "inertial": { - "mass": 0.0, - "inertia": { - "type": "geometry", - "geometry": { - "box": { - "size": "2.10 2.10 0.32" - } - } - }, - "aerodynamics": { - "drag-coefficient": 0.0, - "type": "geometry", - "geometry": { - "box": { - "size": "2.10 2.10 0.32" - } - } - } - }, - "collision": { - "restitution": 0.1, - "friction": 0.5 - }, - "visual": { - "origin": { - "xyz": "-1.5 2.6225 -2.395", - "rpy-deg": "0 0 30" - }, - "geometry": { - "type": "unreal_mesh", - "name": "/Drone/AirTaxi/AirTaxi_Shroud" + "name": "/Drone/PropellerWhite" } } }, @@ -285,182 +138,37 @@ "name": "Prop_RR", "inertial": { "origin": { - "xyz": "-1.5 2.6225 -2.395", + "xyz": "-0.253 0.253 -0.01", "rpy-deg": "0 0 0" }, - "mass": 0.0, + "mass": 0.055, "inertia": { "type": "point-mass" }, "aerodynamics": { - "drag-coefficient": 0.0, + "drag-coefficient": 0.325, "type": "geometry", "geometry": { "cylinder": { - "radius": 0.79, - "length": 0.29 + "radius": 0.1143, + "length": 0.01 } } } }, "visual": { "origin": { - "xyz": "-1.5 2.6225 -2.395", + "xyz": "-0.253 0.253 -0.01", "rpy-deg": "0 0 0" }, "geometry": { "type": "unreal_mesh", - "name": "/Drone/AirTaxi/AirTaxi_Rotor" - } - } - }, - { - "name": "Wing_L", - "inertial": { - "origin": { - "xyz": "0.0 -1.0 0.0", - "rpy-deg": "0 0 0" - }, - "mass": 0.0, - "inertia": { - "type": "point-mass" - }, - "aerodynamics": { - "type": "lift-drag", - "lift-drag": { - "alpha-0": 0.06, - "alpha-stall": 0.64, - "c-lift-alpha": 0.5, - "c-lift-alpha-stall": -0.8, - "c-drag-alpha": 0.6, - "c-drag-alpha-stall": -0.9, - "c-moment-alpha": 0.0, - "c-moment-alpha-stall": 0.0, - "area": 5.0, - "control-surface-cl-per-rad": -0.5, - "control-surface-cd-per-rad": 0.0, - "control-surface-cm-per-rad": -0.1, - "center-pressure-xyz": "0 0 0", - "forward-xyz": "1.0 0 0", - "upward-xyz": "0 0 -1.0" - } - } - } - }, - { - "name": "Wing_L_Aileron", - "inertial": { - "origin": { - "xyz": "0.0 -0.5 0.0", - "rpy-deg": "0 0 0" - }, - "mass": 0.0, - "inertia": { - "type": "point-mass" - } - } - }, - { - "name": "Wing_R", - "inertial": { - "origin": { - "xyz": "0.0 1.0 0.0", - "rpy-deg": "0 0 0" - }, - "mass": 0.0, - "inertia": { - "type": "point-mass" - }, - "aerodynamics": { - "type": "lift-drag", - "lift-drag": { - "alpha-0": 0.06, - "alpha-stall": 0.64, - "c-lift-alpha": 0.5, - "c-lift-alpha-stall": -0.8, - "c-drag-alpha": 0.6, - "c-drag-alpha-stall": -0.9, - "c-moment-alpha": 0.0, - "c-moment-alpha-stall": 0.0, - "area": 5.0, - "control-surface-cl-per-rad": -0.5, - "control-surface-cd-per-rad": 0.0, - "control-surface-cm-per-rad": -0.1, - "center-pressure-xyz": "0 0 0", - "forward-xyz": "1.0 0 0", - "upward-xyz": "0 0 -1.0" - } - } - } - }, - { - "name": "Wing_R_Aileron", - "inertial": { - "origin": { - "xyz": "0.0 0.5 0.0", - "rpy-deg": "0 0 0" - }, - "mass": 0.0, - "inertia": { - "type": "point-mass" - } - } - }, - { - "name": "Wing_Tail", - "inertial": { - "origin": { - "xyz": "0.0 0.0 0.0", - "rpy-deg": "0 0 0" - }, - "mass": 0.0, - "inertia": { - "type": "point-mass" - }, - "aerodynamics": { - "type": "lift-drag", - "lift-drag": { - "alpha-0": 0.0, - "alpha-stall": 0.3, - "c-lift-alpha": 0, - "c-lift-alpha-stall": 0, - "c-drag-alpha": 0.0, - "c-drag-alpha-stall": 0.0, - "c-moment-alpha": 0.0, - "c-moment-alpha-stall": 0.0, - "area": 0.5, - "control-surface-cl-per-rad": 0.0, - "control-surface-cd-per-rad": 0.0, - "control-surface-cm-per-rad": 2.0, // pure elevator pitch control - "center-pressure-xyz": "0 0 0", - "forward-xyz": "1.0 0 0", - "upward-xyz": "0 0 -1.0" - } - } - } - }, - { - "name": "Elevator", - "inertial": { - "origin": { - "xyz": "-6.0 0.0 0.0", - "rpy-deg": "0 0 0" - }, - "mass": 0.0, - "inertia": { - "type": "point-mass" + "name": "/Drone/PropellerWhite" } } } ], "joints": [ - { - "id": "Frame_Shroud_FL", - "type": "fixed", - "parent-link": "Frame", - "child-link": "Shroud_FL", - "axis": "0 0 1" - }, { "id": "Frame_Prop_FL", "type": "fixed", @@ -468,13 +176,6 @@ "child-link": "Prop_FL", "axis": "0 0 1" }, - { - "id": "Frame_Shroud_FR", - "type": "fixed", - "parent-link": "Frame", - "child-link": "Shroud_FR", - "axis": "0 0 1" - }, { "id": "Frame_Prop_FR", "type": "fixed", @@ -482,13 +183,6 @@ "child-link": "Prop_FR", "axis": "0 0 1" }, - { - "id": "Frame_Shroud_RL", - "type": "fixed", - "parent-link": "Frame", - "child-link": "Shroud_RL", - "axis": "0 0 1" - }, { "id": "Frame_Prop_RL", "type": "fixed", @@ -496,113 +190,19 @@ "child-link": "Prop_RL", "axis": "0 0 1" }, - { - "id": "Frame_Shroud_RR", - "type": "fixed", - "parent-link": "Frame", - "child-link": "Shroud_RR", - "axis": "0 0 1" - }, { "id": "Frame_Prop_RR", "type": "fixed", "parent-link": "Frame", "child-link": "Prop_RR", "axis": "0 0 1" - }, - { - "id": "Frame_Wing_L", - "type": "fixed", - "parent-link": "Frame", - "child-link": "Wing_L", - "axis": "0 1 0" - }, - { - "id": "Wing_L_Wing_L_Aileron", - "type": "fixed", - "parent-link": "Wing_L", - "child-link": "Wing_L_Aileron", - "axis": "0 1 0" - }, - { - "id": "Frame_Wing_R", - "type": "fixed", - "parent-link": "Frame", - "child-link": "Wing_R", - "axis": "0 1 0" - }, - { - "id": "Wing_R_Wing_R_Aileron", - "type": "fixed", - "parent-link": "Wing_R", - "child-link": "Wing_R_Aileron", - "axis": "0 1 0" - }, - { - "id": "Frame_Wing_Tail", - "type": "fixed", - "parent-link": "Frame", - "child-link": "Wing_Tail", - "axis": "0 1 0" - }, - { - "id": "Wing_Tail_Elevator", - "type": "fixed", - "parent-link": "Wing_Tail", - "child-link": "Elevator", - "axis": "0 1 0" } ], "controller": { "id": "Simple_Flight_Controller", - "airframe-setup": "vtol-quad-tiltrotor", + "airframe-setup": "quadrotor-x", "type": "simple-flight-api", "simple-flight-api-settings": { - "parameters": { - // Multirotor AngleRate PID - // max_xxx_rate > 5 would introduce wobble/oscillations - "MC_ROLLRATE_MAX": 0.3, // rad/s - "MC_PITCHRATE_MAX": 0.3, // rad/s - "MC_YAWRATE_MAX": 0.3, // rad/s - // p_xxx_rate params are sensitive to gyro noise. Values higher than 0.5 would require noise filtration - "MC_YAWRATE_P": 1.2, - "MC_YAWRATE_D": 0.8, - - // Multirotor AngleLevel PID - // max_pitch/roll_angle > (PI / 5.5) would produce vertical thrust that is - // not enough to keep vehicle in air at extremities of controls - "MC_ROLL_MAX": 0.262, // rad, PI / 12 = 0.262 - "MC_PITCH_MAX": 0.262, // rad - "MC_YAW_P": 1.2, - "MC_YAW_D": 0.8, - - // Multirotor Position PID - "MPC_XY_P": 0.05, - "MPC_XY_I": 0.01, - "MPC_XY_D": 0.05, - - // Multirotor Velocity PID - "MPC_MIN_THR": 0.001, // larger vehicles are stable even with a lower min, max = 1 - - //////////////////////////////////////////////////////////////////////////// - // Fixed-wing vehicle parameters - "FW_AIRSPD_STALL": 2, // m/s - - // Fixed-wing AngleRate PID - // max_xxx_rate > 5 would introduce wobble/oscillations - "FW_Y_RMAX": 1.0, // rad/s - - // Fixed-wing AngleLevel PID - // max_pitch/roll_angle > (PI / 5.5) would produce vertical thrust that is - // not enough to keep vehicle in air at extremities of controls - "FW_PITCH_MAX": 0.262, // rad, PI / 12 = 0.262 - "FW_YAW_P": 0.4, - - // Fixed-wing Velocity PID - "FW_Z_VEL_P": 0.07, - "FW_Z_VEL_I": 0.02, - "FW_Z_VEL_D": 0.05 - }, "actuator-order": [ { "id": "Prop_FR_actuator" @@ -615,27 +215,6 @@ }, { "id": "Prop_RR_actuator" - }, - { - "id": "Prop_FR_tilt_actuator" - }, - { - "id": "Prop_RL_tilt_actuator" - }, - { - "id": "Prop_FL_tilt_actuator" - }, - { - "id": "Prop_RR_tilt_actuator" - }, - { - "id": "Wing_L_Aileron_actuator" - }, - { - "id": "Wing_R_Aileron_actuator" - }, - { - "id": "Elevator_actuator" } ] } @@ -648,7 +227,7 @@ "parent-link": "Frame", "child-link": "Prop_FL", "origin": { - "xyz": "3.2 -3.2 -0.01", + "xyz": "0.253 -0.253 -0.01", "rpy-deg": "0 0 0" }, "rotor-settings": { @@ -657,7 +236,7 @@ "coeff-of-thrust": 0.109919, "coeff-of-torque": 0.040164, "max-rpm": 6396.667, - "propeller-diameter": 0.6, + "propeller-diameter": 0.2286, "smoothing-tc": 0.005 } }, @@ -668,7 +247,7 @@ "parent-link": "Frame", "child-link": "Prop_FR", "origin": { - "xyz": "3.2 3.2 -0.01", + "xyz": "0.253 0.253 -0.01", "rpy-deg": "0 0 0" }, "rotor-settings": { @@ -677,7 +256,7 @@ "coeff-of-thrust": 0.109919, "coeff-of-torque": 0.040164, "max-rpm": 6396.667, - "propeller-diameter": 0.6, + "propeller-diameter": 0.2286, "smoothing-tc": 0.005 } }, @@ -688,7 +267,7 @@ "parent-link": "Frame", "child-link": "Prop_RL", "origin": { - "xyz": "-3.2 -3.2 -0.01", + "xyz": "-0.253 -0.253 -0.01", "rpy-deg": "0 0 0" }, "rotor-settings": { @@ -697,7 +276,7 @@ "coeff-of-thrust": 0.109919, "coeff-of-torque": 0.040164, "max-rpm": 6396.667, - "propeller-diameter": 0.6, + "propeller-diameter": 0.2286, "smoothing-tc": 0.005 } }, @@ -708,7 +287,7 @@ "parent-link": "Frame", "child-link": "Prop_RR", "origin": { - "xyz": "-3.2 3.2 -0.01", + "xyz": "-0.253 0.253 -0.01", "rpy-deg": "0 0 0" }, "rotor-settings": { @@ -717,96 +296,7 @@ "coeff-of-thrust": 0.109919, "coeff-of-torque": 0.040164, "max-rpm": 6396.667, - "propeller-diameter": 0.6, - "smoothing-tc": 0.005 - } - }, - { - "name": "Prop_FL_tilt_actuator", - "type": "tilt", - "enabled": true, - "parent-link": "Frame", - "child-link": "Shroud_FL", - "tilt-settings": { - "target": "Prop_FL_actuator", - "angle-min": 0.0, - "angle-max": 1.57, - "axis": "0.0 -1.0 0.0", - "smoothing-tc": 0.5 - } - }, - { - "name": "Prop_RL_tilt_actuator", - "type": "tilt", - "enabled": true, - "parent-link": "Frame", - "child-link": "Shroud_RL", - "tilt-settings": { - "target": "Prop_RL_actuator", - "angle-min": 0.0, - "angle-max": 1.57, - "axis": "0.0 -1.0 0.0", - "smoothing-tc": 0.5 - } - }, - { - "name": "Prop_FR_tilt_actuator", - "type": "tilt", - "enabled": true, - "parent-link": "Frame", - "child-link": "Shroud_FR", - "tilt-settings": { - "target": "Prop_FR_actuator", - "angle-min": 0.0, - "angle-max": 1.57, - "axis": "0.0 -1.0 0.0", - "smoothing-tc": 0.5 - } - }, - { - "name": "Prop_RR_tilt_actuator", - "type": "tilt", - "enabled": true, - "parent-link": "Frame", - "child-link": "Shroud_RR", - "tilt-settings": { - "target": "Prop_RR_actuator", - "angle-min": 0.0, - "angle-max": 1.57, - "axis": "0.0 -1.0 0.0", - "smoothing-tc": 0.5 - } - }, - { - "name": "Wing_L_Aileron_actuator", - "type": "lift-drag-control-surface", - "enabled": true, - "parent-link": "Wing_L", - "child-link": "Wing_L_Aileron", - "lift-drag-control-surface-settings": { - "rotation-rate": 0.524, // radians per 1.0 actuation amount - "smoothing-tc": 0.005 - } - }, - { - "name": "Wing_R_Aileron_actuator", - "type": "lift-drag-control-surface", - "enabled": true, - "parent-link": "Wing_R", - "child-link": "Wing_R_Aileron", - "lift-drag-control-surface-settings": { - "rotation-rate": 0.524, // radians per 1.0 actuation amount - "smoothing-tc": 0.005 - } - }, - { - "name": "Elevator_actuator", - "type": "lift-drag-control-surface", - "enabled": true, - "parent-link": "Wing_Tail", - "child-link": "Elevator", - "lift-drag-control-surface-settings": { - "rotation-rate": 0.524, // radians per 1.0 actuation amount + "propeller-diameter": 0.2286, "smoothing-tc": 0.005 } } @@ -824,7 +314,7 @@ "width": 1280, "height": 720, "fov-degrees": 90, - "capture-enabled": false, + "capture-enabled": true, "streaming-enabled": true, "pixels-as-float": false, "compress": false, @@ -837,7 +327,7 @@ "lock-yaw": false }, "origin": { - "xyz": "-10.0 0.0 -3.0", + "xyz": "-10.0 0.0 -1.0", "rpy-deg": "0 -11.46 0" } }, @@ -849,7 +339,7 @@ "capture-interval": 0.02, "capture-settings": [ { - "image-type": 0, //rgb_camera + "image-type": 0, // scene camera "width": 400, "height": 225, "fov-degrees": 90, @@ -860,17 +350,48 @@ "target-gamma": 2.5 }, { - "image-type": 1, //depth_planar + "image-type": 1, // depth planar "width": 400, "height": 225, "fov-degrees": 90, - "capture-enabled": false, + "capture-enabled": true, + "streaming-enabled": false, + "pixels-as-float": true, + "compress": false + }, + { + "image-type": 2, // depth perspective + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": true, + "streaming-enabled": false, + "pixels-as-float": true, + "compress": false + }, + { + "image-type": 3, // segmentation + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": true, "streaming-enabled": false, "pixels-as-float": false, "compress": false }, { - "image-type": 2, //depth_perspective + "image-type": 4, // depth vis + "width": 400, + "height": 225, + "fov-degrees": 90, + "capture-enabled": true, + "streaming-enabled": false, + "pixels-as-float": false, + "compress": false, + "max-depth-meters": 300 + }, + { + "image-type": 5, // disparity normalized "width": 400, "height": 225, "fov-degrees": 90, @@ -880,11 +401,11 @@ "compress": false }, { - "image-type": 3, //segmentation + "image-type": 6, // surface normals "width": 400, "height": 225, "fov-degrees": 90, - "capture-enabled": false, + "capture-enabled": true, "streaming-enabled": false, "pixels-as-float": false, "compress": false @@ -910,8 +431,8 @@ } ], "origin": { - "xyz": "0.0 0.0 0.5", - "rpy-deg": "0.0 -90 0.0" + "xyz": "0.0 0.0 -1.0", + "rpy-deg": "0.0 -11.46 0.0" } }, { @@ -920,23 +441,123 @@ "enabled": true, "parent-link": "Frame", "accelerometer": { - "velocity-random-walk": 0.0123, + "velocity-random-walk": 2.3e-3, "tau": 800, - "bias-stability": 2e-5, + "bias-stability": 3.53e-4, "turn-on-bias": "0 0 0" }, "gyroscope": { - "angle-random-walk": 0.0123, + "angle-random-walk": 1.027e-4, "tau": 500, - "bias-stability": 1e-6, + "bias-stability": 2.23e-5, "turn-on-bias": "0 0 0" } }, + { + "id": "lidar1", + "type": "lidar", + "enabled": true, + "parent-link": "Frame", + "number-of-channels": 16, + "range": 100, + "points-per-second": 100000, + "horizontal-rotation-frequency": 10, + "horizontal-fov-start-deg": 0.0, + "horizontal-fov-end-deg": 360.0, + "vertical-fov-upper-deg": 0.0, + "vertical-fov-lower-deg": -90.0, + "draw-debug-points": false, + "origin": { + "xyz": "0 0 0.2", + "rpy-deg": "0 0 0" + } + }, + { + "id": "DistanceSensor", + "type": "distance-sensor", + "enabled": true, + "parent-link": "Frame", + "max-distance": 50.0, + "min-distance": 0.5, + "draw-debug-points": true, + "origin": { + "xyz": "0 0 0.2", + "rpy-deg": "0 -90 0" + } + }, { "id": "GPS", "type": "gps", - "enabled": false, - "parent-link": "Frame" + "enabled": true, + "parent-link": "Frame", + "eph-time-constant": 0.9, + "epv-time-constant": 0.9, + "eph-initial": 100, + "epv-initial": 100, + "eph-final": 0.1, + "epv-final": 0.1, + "eph-min_3d": 3.0, + "eph-min_2d": 4.0 + }, + { + "id": "Barometer", + "type": "barometer", + "enabled": true, + "parent-link": "Frame", + "qnh": 1013.250, + "pressure-factor-sigma": 0.001825, + "pressure-factor-tau": 3600, + "uncorrelated-noise-sigma": 2.7, + "update-latency": 0, + "update-frequency": 50, + "startup-delay": 0 + }, + { + "id": "Magnetometer", + "type": "magnetometer", + "enabled": true, + "parent-link": "Frame", + "scale-factor": 1, + "noise-sigma": "0.005 0.005 0.005", // 5 mgauss as per LSM303D spec-sheet + "noise-bias": "0.0 0.0 0.0" // no offset as per specsheet (zero gauss level) + }, + { + "id": "Airspeed", + "type": "airspeed", + "enabled": true, + "parent-link": "Frame", + "pressure-factor-sigma": 0.001825, + "pressure-factor-tau": 3600, + "uncorrelated-noise-sigma": 1.052, + "forward-xyz": "1.0 0.0 0.0" + }, + { + "id": "Battery", + "type": "battery", + "enabled": true, + "parent-link": "Frame", + + // Total battery capacity. + // Typically, on start capacity should be lower than total battery capacity. + // Use joules as unit for capacity. + // 1 joule = 3600 * Amp hour + // 1 joule = 3.6 * milli Amp hour + "total-battery-capacity": 36000, + "battery-capacity-on-start": 30000, + + // Battery has two simulated mode: Rotor power discharge or simple discharge model + + // Rotor power discharge mode depletes power proportional to torque*angular_velocity + // Simple discharge mode, depletes at rate specified. + + // Config for rotor power discharge mode. + // You can configure the constant of proportionality using config option. + "battery-mode": "rotor-power-discharge-mode", + "rotor-power-coefficient": 1 + + // Config for simple discharge model. The drain rate can be adjusted at runtime using client api calls. + // "battery-mode":"simple-discharge-mode", + // "battery-drain-rate-on-start": 1 } ] } \ No newline at end of file diff --git a/client/python/example_user_scripts/sim_config/scene_cessna310.jsonc b/client/python/example_user_scripts/sim_config/scene_cessna310.jsonc new file mode 100644 index 00000000..a8e1fc6f --- /dev/null +++ b/client/python/example_user_scripts/sim_config/scene_cessna310.jsonc @@ -0,0 +1,31 @@ +{ + "id": "SceneBasicFixedWing", + "actors": [ + { + "type": "robot", + "name": "c310", + "origin": { + "xyz": "3 -2 -0.95", + "rpy": "0 0 0" + }, + "robot-config": "robot_cessna310.jsonc" + } + ], + "clock": { + "type": "steppable", + "step-ns": 3000000, + "real-time-update-rate": 3000000, + "pause-on-start": false + }, + "home-geo-point": { + "latitude": 29.4296741, + "longitude": -95.16384722, + "altitude": 7.5 + }, + "segmentation": { + "initialize-ids": true, + "ignore-existing": false, + "use-owner-name": true + }, + "scene-type": "UnrealNative" +} \ No newline at end of file diff --git a/client/python/example_user_scripts/sim_config/scene_cessna310_rc.jsonc b/client/python/example_user_scripts/sim_config/scene_cessna310_rc.jsonc new file mode 100644 index 00000000..6cb21dc3 --- /dev/null +++ b/client/python/example_user_scripts/sim_config/scene_cessna310_rc.jsonc @@ -0,0 +1,31 @@ +{ + "id": "SceneBasicFixedWing", + "actors": [ + { + "type": "robot", + "name": "c310", + "origin": { + "xyz": "3 -2 -0.95", + "rpy": "0 0 0" + }, + "robot-config": "robot_cessna310_rc.jsonc" + } + ], + "clock": { + "type": "steppable", + "step-ns": 3000000, + "real-time-update-rate": 3000000, + "pause-on-start": false + }, + "home-geo-point": { + "latitude": 29.4296741, + "longitude": -95.16384722, + "altitude": 7.5 + }, + "segmentation": { + "initialize-ids": true, + "ignore-existing": false, + "use-owner-name": true + }, + "scene-type": "UnrealNative" +} \ No newline at end of file diff --git a/client/python/projectairsim/pyproject.toml b/client/python/projectairsim/pyproject.toml index fe9363b6..603d6d79 100644 --- a/client/python/projectairsim/pyproject.toml +++ b/client/python/projectairsim/pyproject.toml @@ -36,7 +36,7 @@ dependencies = [ "jsonlines", "Shapely", "azure-storage-blob", - "open3d==0.16.*" + "open3d>=0.16.0" ] [project.optional-dependencies] diff --git a/client/python/projectairsim/src/projectairsim/drone.py b/client/python/projectairsim/src/projectairsim/drone.py index 37402656..2aae5512 100644 --- a/client/python/projectairsim/src/projectairsim/drone.py +++ b/client/python/projectairsim/src/projectairsim/drone.py @@ -1449,6 +1449,64 @@ async def set_vtol_mode_async( taskcr = await self.client.request_async(req, callback) return taskcr + #set_brakes + def set_brakes(self, brakes_value: float) -> bool: + """Set brakes + + Args: + brakes_value (float): Brakes value + + Returns: + bool: True if brakes are set + """ + set_brakes_req: Dict = { + "method": f"{self.parent_topic}/SetBrakes", + "params": {"_brakes_value": brakes_value}, + "version": 1.0, + } + brakes_set = self.client.request(set_brakes_req) + return brakes_set + + # get_jsbsim_property + def get_jsbsim_property(self, property_name: str) -> float: + """Get JSBSim property + + Args: + property_name (str): Property name + + Returns: + float: Property value + """ + get_jsbsim_property_req: Dict = { + "method": f"{self.parent_topic}/GetJSBSimProperty", + "params": {"_property_name": property_name}, + "version": 1.0, + } + property_value = self.client.request(get_jsbsim_property_req) + return property_value + + # set_jsbsim_property + def set_jsbsim_property(self, property_name: str, property_value: float) -> bool: + """Set JSBSim property + + Args: + property_name (str): Property name + property_value (float): Property value + + Returns: + bool: True if property is set + """ + set_jsbsim_property_req: Dict = { + "method": f"{self.parent_topic}/SetJSBSimProperty", + "params": { + "_property_name": property_name, + "_value": property_value, + }, + "version": 1.0, + } + property_set = self.client.request(set_jsbsim_property_req) + return property_set + def set_control_signals(self, control_signal_map: Dict) -> bool: """set_control_signals for Manual Controller type diff --git a/client/python/projectairsim/src/projectairsim/lidar_utils.py b/client/python/projectairsim/src/projectairsim/lidar_utils.py index 569db12b..9466239e 100644 --- a/client/python/projectairsim/src/projectairsim/lidar_utils.py +++ b/client/python/projectairsim/src/projectairsim/lidar_utils.py @@ -1,5 +1,6 @@ from argparse import ArgumentError import multiprocessing as mp +import time import numpy as np import open3d as o3d @@ -24,8 +25,8 @@ def __init__(self): class SetViewBoundsRequest: """Class for requesting the display loop recalculate the view bounds""" - def __init__(self): - pass + def __init__(self, view_bounds): + self.view_bounds = view_bounds class ViewChangeRequest: """Class for making a view change request to the display loop""" @@ -96,7 +97,7 @@ def __init__( if (view == self.VIEW_CUSTOM) and ( not lookat_xyz or not view_front or not view_up ): - raise ArgumentError( + raise ValueError( "LidarDisplay: View is VIEW_CUSTOM but one or more of lookat_xyz," " view_front, or view_up arguments are missing" ) @@ -116,7 +117,7 @@ def __init__( self.PLASMA_PALLETE.shape[0], ) else: - raise ArgumentError("LidarDisplay: Invalid color_intensity_range") + raise ValueError("LidarDisplay: Invalid color_intensity_range") def set_view_preset(self, view: int, lookat_xyz=None): if view == self.VIEW_TOPDOWN: @@ -138,11 +139,11 @@ def set_view_preset(self, view: int, lookat_xyz=None): self.lookat_xyz = [0.0, 0.0, 5.0] if not lookat_xyz else lookat_xyz self.view = view elif view == self.VIEW_CUSTOM: - raise ArgumentError( + raise ValueError( "VIEW_CUSTOM is not valid here--call set_view_custom() instead" ) else: - raise ArgumentError(f"Unrecognized preset view ID {view}") + raise ValueError(f"Unrecognized preset view ID {view}") if self.running: self.control_q.put( @@ -366,13 +367,22 @@ def display_loop(self): self.set_view() # Do Open3D processing - self.o3d_vis.poll_events() - self.o3d_vis.update_renderer() + if self.window_created: + # check if window is still open + if not self.o3d_vis.poll_events(): + self.running = False + break + self.o3d_vis.update_renderer() + + # Cap frame rate to reduce CPU usage and avoid issues with DWM/WGL on Windows + time.sleep(0.01) except KeyboardInterrupt: pass # Just exit normally finally: + if self.window_created: + self.o3d_vis.destroy_window() self.window_created = False def receive(self, lidar_data): diff --git a/client/python/projectairsim/src/projectairsim/schema/robot_config_schema.jsonc b/client/python/projectairsim/src/projectairsim/schema/robot_config_schema.jsonc index d73d844e..78939022 100644 --- a/client/python/projectairsim/src/projectairsim/schema/robot_config_schema.jsonc +++ b/client/python/projectairsim/src/projectairsim/schema/robot_config_schema.jsonc @@ -7,7 +7,7 @@ "physics-type": { "description": "Defines the physics type for the robot", "type": "string", - "enum": [ "fast-physics", "non-physics", "matlab-physics" ] + "enum": [ "fast-physics", "non-physics", "matlab-physics", "jsbsim-physics"] }, "links": { "description": "Define the links for the robot", @@ -64,11 +64,11 @@ "id": { "type": "string" }, "airframe-setup": { "type": "string", - "enum": [ "quadrotor-x", "hexarotor-x", "vtol-quad-x-tailsitter", "vtol-quad-tiltrotor", "ackermann"] + "enum": [ "quadrotor-x", "hexarotor-x", "vtol-quad-x-tailsitter", "vtol-quad-tiltrotor", "ackermann", "fixed-wing"] }, "type": { "type": "string", - "enum": [ "simple-flight-api", "simple-drive-api","px4-api", "ardupilot-api", "manual-controller-api", "matlab-controller-api"] + "enum": [ "simple-flight-api", "simple-drive-api","px4-api", "ardupilot-api", "manual-controller-api", "matlab-controller-api", "jsbsim-api" ] }, "simple-flight-api-settings": { "type": "object", @@ -84,6 +84,11 @@ "actuator-order": { "$ref": "#/definitions/actuator-order" } } }, + // TODO "jsbsim-api-settings": { + // "type": "object", + // "properties": { + // } + // }, "px4-settings": { "$ref": "#/definitions/px4-settings" }, "manual-controller-api-settings": { "type": "object", diff --git a/client/python/projectairsim/tests/test_hello_drone.py b/client/python/projectairsim/tests/test_hello_drone.py index 6d9849cf..81e0c6bb 100644 --- a/client/python/projectairsim/tests/test_hello_drone.py +++ b/client/python/projectairsim/tests/test_hello_drone.py @@ -1,5 +1,5 @@ """ -Copyright (C) Microsoft Corporation. +Copyright (C) Microsoft Corporation. Copyright (C) 2025 IAMAI CONSULTING CORP MIT License. Pytest end-end test script for hello_drone.py functionality @@ -15,31 +15,43 @@ def check_image(img_msg): - """Basic data validation for images""" img_nparr = np.frombuffer(img_msg["data"], dtype="uint8") - assert np.sum(img_nparr) > 0 + if img_nparr.size == 0: + return + if np.sum(img_nparr) == 0: + return def check_imu(imu_msg): - """Basic data validation for IMU""" assert len(imu_msg) > 0 orientation = imu_msg["orientation"] lin_accel = imu_msg["linear_acceleration"] ang_vel = imu_msg["angular_velocity"] - assert orientation["w"] >= -1.0 and orientation["w"] <= 1.0 - assert orientation["x"] >= -1.0 and orientation["x"] <= 1.0 - assert orientation["y"] >= -1.0 and orientation["y"] <= 1.0 - assert orientation["z"] >= -1.0 and orientation["x"] <= 1.0 - assert lin_accel["x"] >= -20.0 and lin_accel["x"] <= 20.0 - assert lin_accel["y"] >= -20.0 and lin_accel["y"] <= 20.0 - assert lin_accel["z"] >= -20.0 and lin_accel["z"] <= 20.0 - assert ang_vel["x"] >= -5.0 and ang_vel["x"] <= 5.0 - assert ang_vel["y"] >= -5.0 and ang_vel["y"] <= 5.0 - assert ang_vel["z"] >= -5.0 and ang_vel["z"] <= 5.0 + assert -1.0 <= orientation["w"] <= 1.0 + assert -1.0 <= orientation["x"] <= 1.0 + assert -1.0 <= orientation["y"] <= 1.0 + assert -1.0 <= orientation["z"] <= 1.0 + assert -20.0 <= lin_accel["x"] <= 20.0 + assert -20.0 <= lin_accel["y"] <= 20.0 + assert -20.0 <= lin_accel["z"] <= 20.0 + assert -5.0 <= ang_vel["x"] <= 5.0 + assert -5.0 <= ang_vel["y"] <= 5.0 + assert -5.0 <= ang_vel["z"] <= 5.0 + + +async def wait_for_pose_change(multirotor, prev_pose, timeout=2.0): + start = time.time() + while True: + pose = multirotor.robot_actual_pose + if pose is not None and pose != prev_pose: + return pose + if time.time() - start > timeout: + pytest.fail("Timeout waiting for pose update") + await asyncio.sleep(0.05) @pytest.fixture(scope="class") -def robo(): +def multirotor(): class ProjectAirSimTestObject: client = ProjectAirSimClient() client.connect() @@ -48,120 +60,112 @@ class ProjectAirSimTestObject: robot_actual_pose = None def robot_actual_pose_callback(self, topic, message): - # print("Got new pose:", message) self.robot_actual_pose = message - robo_obj = ProjectAirSimTestObject() - yield robo_obj + multirotor_obj = ProjectAirSimTestObject() + yield multirotor_obj print("\nTeardown client...") - robo_obj.client.disconnect() + multirotor_obj.client.disconnect() class TestClientBase: - async def main(self, robo): - # Set up client for pytest + async def main(self, multirotor): print("start") - drone = robo.drone - client = robo.client + drone = multirotor.drone + client = multirotor.client client.subscribe( - drone.robot_info["actual_pose"], robo.robot_actual_pose_callback + drone.robot_info["actual_pose"], multirotor.robot_actual_pose_callback ) - timeout_sec = 5 - timeout = time.time() + timeout_sec - print("\n Waiting for robot_actual_pose update...") - robo.robot_actual_pose = None - while robo.robot_actual_pose is None: + + timeout = time.time() + 5 + multirotor.robot_actual_pose = None + while multirotor.robot_actual_pose is None: if time.time() > timeout: pytest.fail("Timeout waiting for a pose message update") - time.sleep(0.1) - - # Test hello_drone.py pattern below + await asyncio.sleep(0.1) - # Susbscribe to Drone's sensors with a callback to receive the data - # RGB Camera client.subscribe( - drone.sensors["DownCamera"]["scene_camera"], lambda _, rgb: check_image(rgb) + drone.sensors["DownCamera"]["scene_camera"], + lambda _, rgb: check_image(rgb), ) - # Depth Camera client.subscribe( drone.sensors["DownCamera"]["depth_camera"], lambda _, depth: check_image(depth), ) - # IMU client.subscribe( - drone.sensors["IMU1"]["imu_kinematics"], lambda _, imu: check_imu(imu) + drone.sensors["IMU1"]["imu_kinematics"], + lambda _, imu: check_imu(imu), ) drone.enable_api_control() drone.arm() - prev_pose = robo.robot_actual_pose - - # Command the Drone to move "Up" in NED coordinate system for 2 seconds + prev_pose = multirotor.robot_actual_pose move_up = await drone.move_by_velocity_async( v_north=0.0, v_east=0.0, v_down=-2.0, duration=2.0 ) projectairsim_log().info("Move-Up invoked") await move_up projectairsim_log().info("Move-Up completed") - assert robo.robot_actual_pose["position"]["z"] < prev_pose["position"]["z"] + new_pose = await wait_for_pose_change(multirotor, prev_pose) + assert new_pose["position"]["z"] < prev_pose["position"]["z"] - prev_pose = robo.robot_actual_pose - # Command the Drone to move "North" in NED coordinate system for 2 seconds + prev_pose = new_pose move_north = await drone.move_by_velocity_async( v_north=2.0, v_east=0.0, v_down=0.0, duration=2.0 ) projectairsim_log().info("Move-North invoked") await move_north projectairsim_log().info("Move-North completed") - assert robo.robot_actual_pose["position"]["x"] > prev_pose["position"]["x"] + new_pose = await wait_for_pose_change(multirotor, prev_pose) + assert new_pose["position"]["x"] > prev_pose["position"]["x"] - prev_pose = robo.robot_actual_pose - # Command the Drone to move "West" in NED coordinate system for 2 seconds + prev_pose = new_pose move_west = await drone.move_by_velocity_async( v_north=0.0, v_east=-2.0, v_down=0.0, duration=2.0 ) projectairsim_log().info("Move-West invoked") await move_west projectairsim_log().info("Move-West completed") - assert robo.robot_actual_pose["position"]["y"] < prev_pose["position"]["y"] + new_pose = await wait_for_pose_change(multirotor, prev_pose) + assert new_pose["position"]["y"] < prev_pose["position"]["y"] - prev_pose = robo.robot_actual_pose - # Command the Drone to move "South" in NED coordinate system for 2 seconds + prev_pose = new_pose move_south = await drone.move_by_velocity_async( v_north=-2.0, v_east=0.0, v_down=0.0, duration=2.0 ) projectairsim_log().info("Move-South invoked") await move_south projectairsim_log().info("Move-South completed") - assert robo.robot_actual_pose["position"]["x"] < prev_pose["position"]["x"] + new_pose = await wait_for_pose_change(multirotor, prev_pose) + assert new_pose["position"]["x"] < prev_pose["position"]["x"] - prev_pose = robo.robot_actual_pose - # Command the Drone to move "East" in NED coordinate system for 4 seconds + prev_pose = new_pose move_east = await drone.move_by_velocity_async( v_north=0.0, v_east=2.0, v_down=0.0, duration=2.0 ) projectairsim_log().info("Move-East invoked") await move_east projectairsim_log().info("Move-East completed") - assert robo.robot_actual_pose["position"]["y"] > prev_pose["position"]["y"] + new_pose = await wait_for_pose_change(multirotor, prev_pose) + assert new_pose["position"]["y"] > prev_pose["position"]["y"] - prev_pose = robo.robot_actual_pose - # Command the Drone to move "Down" in NED coordinate system for 4 seconds + prev_pose = new_pose move_down = await drone.move_by_velocity_async( v_north=0.0, v_east=0.0, v_down=2.0, duration=4.0 ) projectairsim_log().info("Move-Down invoked") await move_down projectairsim_log().info("Move-Down completed") - assert robo.robot_actual_pose["position"]["z"] > prev_pose["position"]["z"] + new_pose = await wait_for_pose_change(multirotor, prev_pose) + assert new_pose["position"]["z"] > prev_pose["position"]["z"] drone.disarm() drone.disable_api_control() client.disconnect() - def test_hello_drone(self, robo): - asyncio.run(self.main(robo)) + def test_hello_drone(self, multirotor): + asyncio.run(self.main(multirotor)) \ No newline at end of file diff --git a/core_sim/include/core_sim/actor/robot.hpp b/core_sim/include/core_sim/actor/robot.hpp index 59b4aeb4..fdd1b415 100644 --- a/core_sim/include/core_sim/actor/robot.hpp +++ b/core_sim/include/core_sim/actor/robot.hpp @@ -27,6 +27,12 @@ #include "core_sim/transforms/transform.hpp" #include "core_sim/transforms/transform_tree.hpp" +// Forward declaration to avoid including JSBSim headers with RTTI requirements +// in Unreal Engine plugin code (UE is compiled without RTTI) +namespace JSBSim { +class FGFDMExec; +} + namespace microsoft { namespace projectairsim { @@ -62,6 +68,8 @@ class Robot : public Actor { const PhysicsType& GetPhysicsType() const; void SetPhysicsType(const PhysicsType& phys_type); + //used only by JSBSim physics and controller + std::shared_ptr GetJSBSimModel() const; const std::string& GetPhysicsConnectionSettings() const; void SetPhysicsConnectionSettings(const std::string& phys_conn_settings); const std::string& GetControlConnectionSettings() const; @@ -146,12 +154,14 @@ class Robot : public Actor { Robot(const std::string& id, const Transform& origin, const Logger& logger, const TopicManager& topic_manager, const std::string& parent_topic_path, const ServiceManager& service_manager, - const StateManager& state_manager); + const StateManager& state_manager, + const std::string& working_simulation_path); Robot(const std::string& id, const Transform& origin, const Logger& logger, const TopicManager& topic_manager, const std::string& parent_topic_path, const ServiceManager& service_manager, - const StateManager& state_manager, HomeGeoPoint home_geo_point); + const StateManager& state_manager, HomeGeoPoint home_geo_point, + const std::string& working_simulation_path); void Load(ConfigJson config_json) override; diff --git a/core_sim/include/core_sim/environment.hpp b/core_sim/include/core_sim/environment.hpp index a73f7591..68fba9ed 100644 --- a/core_sim/include/core_sim/environment.hpp +++ b/core_sim/include/core_sim/environment.hpp @@ -23,7 +23,7 @@ struct Environment { inline static Vector3 wind_velocity = Vector3::Zero(); Vector3 position_ned = Vector3::Zero(); - HomeGeoPoint home_geo_point; + HomeGeoPoint home_geo_point; //These are the world origin coordinates (0,0,0), not the home position of the drone EnvInfo env_info; // Current environmental condition that can vary (e.g., by // current location, time of day, etc.) diff --git a/core_sim/include/core_sim/math_utils.hpp b/core_sim/include/core_sim/math_utils.hpp index 13cb8ff0..cc6e2da8 100644 --- a/core_sim/include/core_sim/math_utils.hpp +++ b/core_sim/include/core_sim/math_utils.hpp @@ -126,6 +126,10 @@ class MathUtils { static constexpr E ToEnum(typename std::underlying_type::type u) { return static_cast(u); } + + static constexpr float feets_to_meters = 0.3048f; + static constexpr float meters_to_feets = 1.0f / feets_to_meters; + }; } // namespace projectairsim diff --git a/core_sim/include/core_sim/physics_common_types.hpp b/core_sim/include/core_sim/physics_common_types.hpp index 44190cdb..8c8c8bd9 100644 --- a/core_sim/include/core_sim/physics_common_types.hpp +++ b/core_sim/include/core_sim/physics_common_types.hpp @@ -19,7 +19,8 @@ enum class PhysicsType { kNonPhysics = 0, kFastPhysics = 1, kUnrealPhysics = 2, - kMatlabPhysics = 3 + kMatlabPhysics = 3, + kJSBSimPhysics = 4 }; struct Pose { diff --git a/core_sim/include/core_sim/scene.hpp b/core_sim/include/core_sim/scene.hpp index 0bae0942..f286b553 100644 --- a/core_sim/include/core_sim/scene.hpp +++ b/core_sim/include/core_sim/scene.hpp @@ -131,7 +131,8 @@ class Scene { Scene(const Logger& logger, const TopicManager& topic_manager, const std::string& parent_topic_path, const ServiceManager& service_manager, - const StateManager& state_manager); + const StateManager& state_manager, + const std::string& working_simulation_path_); void LoadWithJSON(ConfigJson config_json); diff --git a/core_sim/include/core_sim/simulator.hpp b/core_sim/include/core_sim/simulator.hpp index 3e61b2b8..70e15405 100644 --- a/core_sim/include/core_sim/simulator.hpp +++ b/core_sim/include/core_sim/simulator.hpp @@ -25,7 +25,7 @@ class Simulator { Simulator(); - Simulator(LoggerCallback logger_callback, LogLevel level = LogLevel::kError); + Simulator(LoggerCallback logger_callback, LogLevel level = LogLevel::kError, const std::string& working_simulation_path=""); // Simulator controls diff --git a/core_sim/jsbsim/models/aircraft/c310_rc/INSTALL b/core_sim/jsbsim/models/aircraft/c310_rc/INSTALL new file mode 100644 index 00000000..214b8715 --- /dev/null +++ b/core_sim/jsbsim/models/aircraft/c310_rc/INSTALL @@ -0,0 +1,11 @@ +// This file instructs the automatic synchronization utilities where to +// install this aircraft and under what name. +// +// The syntax is easy; +// * the package name at the beginning of a new line followed by a colon +// * a space as a column separator +// * the path and filename relative to the aircraft install directory +// +// Currently known package names are: FlightGear + +FlightGear: diff --git a/core_sim/jsbsim/models/aircraft/c310_rc/README.c310_rc b/core_sim/jsbsim/models/aircraft/c310_rc/README.c310_rc new file mode 100644 index 00000000..24f3c16f --- /dev/null +++ b/core_sim/jsbsim/models/aircraft/c310_rc/README.c310_rc @@ -0,0 +1,50 @@ +Here are some useful numbers for a Cessna 310 with two 470HP engines, +taken from a French Web page at + + http://www.infomaniak.ch/~tmandrey/flyerboy/avions5.html + +(Please forgive any mistranslations.) + +Performance +----------- + +Rotation speed (Vr): 80 KIAS +Normal climb: 115-130 KIAS +Best climb angle (Vx): 81 KIAS +Best climb speed (Vy): 107 KIAS +Minimum single-engine control speed (Vmca): 75 KIAS +Best single-engine climb angle (Vxa): 94 KIAS +Best single-engine climb speed (Vya): 101 KIAS +Climb rate (Vs): 1,495 fpm +Single-engine climb rate: 327 fpm +Take-off distance: 1,519 ft +Take-off distance to clear a 50 ft obstacle: 1,795 ft +Maximum cruise speed: 189 KTAS at 8,000 ft +Econo-cruise speed: 144 KTAS at 7,500 ft +Econo-cruise fuel consumption: 17.1 USGal/hr +Econo-cruise range: 2,583 km (1,395 nm) +Ceiling: 19,500 ft +Single-engine ceiling: 6,680 ft +Approach speed (Vref): 110 KIAS +Landing speed: 90 KIAS +Stall speed, full flaps (Vso): 63 KIAS +Landing distance over a 50 ft obstacle: 1,697 ft +Rolling distance after touch-down: 582 ft + +Limits +------ + +Gear-down operating range (white arc): 63-139 KIAS +Regular operating range (green arc): 75-183 KIAS +Warning range (yellow arc): 183-223 KIAS +Maximum operating speed (red line, Vne): 223 KIAS +Stall speeds (VS): + 0 deg flaps: 75 KIAS + 15 deg flaps: 70 KIAS + 35 deg flaps: 63 KIAS +Manoeuvering speed (Va): 148 KIAS +Maximum gear landing speed (Vlo): 139 KIAS +Maximum gear-down speed (Vle): 139 KIAS + + + diff --git a/core_sim/jsbsim/models/aircraft/c310_rc/c310_rc.xml b/core_sim/jsbsim/models/aircraft/c310_rc/c310_rc.xml new file mode 100644 index 00000000..601177d5 --- /dev/null +++ b/core_sim/jsbsim/models/aircraft/c310_rc/c310_rc.xml @@ -0,0 +1,1076 @@ + + + + + + IAMAI consulting corp team + David Megginson + Tony Peden + Jon Berndt + 2001-11-24 + $Revision: 1.65 $ + + Models a C310 light twin. The airplane has a wingspan of 35.98 feet, wing area of 178 square feet, + an aspect ratio of 7.3, and an M.A.C. of 5 feet based on projection of the outboard leading edge + of the wing through the fuselage. The wing airfoil section is a modified NACA 64(2)A215 airfoil + with the trailing edge cusp faired out. The wing has 5 degrees of dihedral, no twist, and is at 2 degrees + positive incidence with respect to the fuselage reference line. Thrust axes are parallel to the reference line. + The horizontal tail is all-movable, with a deflection range of 4 to -14 degrees. Control deflection + range for the ailerons is 14 to -18 degrees. Normal rudder deflection range is +/-27 degrees. + + + + This model was created using publicly available data, publicly available + technical reports, textbooks, and guesses. It contains no proprietary or + restricted data. If this model has been validated at all, it would be + only to the extent that it seems to "fly right", and that it possibly + complies with published, publicly known, performance data (maximum speed, + endurance, etc.). Thus, this model is meant for educational and entertainment + purposes only. + + This simulation model is not endorsed by the manufacturer. This model is not + to be sold. + + + + + + 175 + 36.5 + 4.9 + 21.9 + 15.7 + 16.5 + 0 + + 46 + 0 + 8.6 + + + 35 + -12 + 38 + + + 46 + 0 + 8.6 + + + + + 8884 + 1939 + 11001 + 2950 + + 46 + 0 + 8.6 + + + 180 + + 37 + -14 + 24 + + + + 180 + + 37 + 14 + 24 + + + + 150 + + 61 + -14 + 24 + + + + 150 + + 61 + 14 + 24 + + + + 100 + + 90 + 0 + 24 + + + + + + + + -60.2 + 0 + -27 + + 0.8 + 0.5 + 0.02 + 5400 + 1600 + 10 + NONE + 1 + + + + 50.7 + -70.8 + -31 + + 0.8 + 0.5 + 0.02 + 5400 + 1600 + 0.0 + LEFT + 1 + + + + 50.7 + 70.8 + -31 + + 0.8 + 0.5 + 0.02 + 5400 + 1600 + 0.0 + RIGHT + 1 + + + + 221.8 + 0 + 0 + + 0.2 + 0.2 + 20000 + 1000 + + + + -96.3 + 0 + 10.3 + + 0.2 + 0.2 + 10000 + 2000 + + + + 0 + -25 + 0 + + 0.2 + 0.2 + 10000 + 2000 + + + + 0 + 25 + 0 + + 0.2 + 0.2 + 10000 + 2000 + + + + 41.3 + 0 + 53.3 + + 0.2 + 0.2 + 10000 + 2000 + + + + 48.1 + -222 + 18.9 + + 0.2 + 0.2 + 10000 + 2000 + + + + 48.1 + 222 + 18.9 + + 0.2 + 0.2 + 10000 + 2000 + + + + + 0 + 1 + 2 + 3 + + + -27.5 + -70 + 15.5 + + + 0.0 + 0.0 + 0.0 + + 1 + 0.1 + + + + 0 + 1 + 2 + 3 + + + -27.5 + 70 + 15.5 + + + 0.0 + 0.0 + 0.0 + + 1 + 0.1 + + + + + 35 + -209.8 + 28.3 + + 336 + 225 + + + + 35 + 209.8 + 28.3 + + 336 + 225 + + + + 35 + -41.6 + 11.7 + + 135 + 95 + + + + 35 + 41.6 + 11.7 + + 135 + 95 + + + + + + + + + + ap/roll-pid-kp + ap/roll-pid-ki + ap/roll-pid-kd + + + + + + + + ap/elevator_cmd + fcs/elevator-cmd-norm + fcs/pitch-trim-cmd-norm + + -1 + 1 + + + + + fcs/pitch-trim-sum + + -14.0 + 4.0 + + 0.01745 + fcs/elevator-pos-rad + + + + fcs/elevator-pos-deg + + -25 + 35 + + + -1 + 1 + + fcs/elevator-pos-norm + + + + + + + ap/aileron_cmd + fcs/aileron-cmd-norm + fcs/roll-trim-cmd-norm + + -1 + 1 + + + + + fcs/roll-trim-sum + + -18.0 + 14.0 + + 0.01745 + fcs/left-aileron-pos-rad + + + + fcs/left-aileron-control + + -0.3141 + 0.2443 + + + -1.0 + 1.0 + + fcs/left-aileron-pos-norm + + + + -fcs/roll-trim-sum + + -18.0 + 14.0 + + 0.01745 + fcs/right-aileron-pos-rad + + + + fcs/right-aileron-control + + -0.3141 + 0.2443 + + + -1.0 + 1.0 + + fcs/right-aileron-pos-norm + + + + + + + ap/rudder_cmd + fcs/rudder-cmd-norm + fcs/yaw-trim-cmd-norm + + -1 + 1 + + + + + fcs/yaw-trim-sum + 0.01745 + + -27. + 27 + + fcs/rudder-pos-rad + + + + fcs/rudder-pos-deg + + -27 + 27 + + + -1 + 1 + + fcs/rudder-pos-norm + + + + + + fcs/flap-cmd-norm + + + 0 + + + + 15 + + + + 25 + + + + 45 + + + + fcs/flap-pos-deg + + + + fcs/flap-pos-deg + + 0 + 45 + + + 0 + 1 + + fcs/flap-pos-norm + + + + + + gear/gear-cmd-norm + + + 0 + + + + 1 + + + + gear/gear-pos-norm + + + + + + + + + atmosphere/P-psf + + 50 0.1 + 990 0.5 + 1300 0.675 + 2117 1.0 + +
+ 1.0 +
+
+
+ + + fcs/mixture-cmd-norm[0] + systems/mixture-cmd-norm + fcs/mixture-pos-norm[0] + + + + fcs/mixture-cmd-norm[1] + systems/mixture-cmd-norm + fcs/mixture-pos-norm[1] + + +
+
+ + + + Change_in_lift_due_to_ground_effect + + aero/h_b-mac-ft + + 0.0000 1.2030 + 0.1000 1.1270 + 0.1500 1.0900 + 0.2000 1.0730 + 0.3000 1.0460 + 0.4000 1.0550 + 0.5000 1.0190 + 0.6000 1.0130 + 0.7000 1.0080 + 0.8000 1.0060 + 0.9000 1.0030 + 1.0000 1.0020 + 1.1000 1.0000 + +
+
+ + + + + Drag_at_zero_lift + + aero/qbar-psf + metrics/Sw-sqft + 0.028 + + + + + Drag_due_to_alpha + + aero/qbar-psf + metrics/Sw-sqft + + aero/alpha-rad + + -3.14 0.01 + -1.51 1. + -0.785 0.707 + -0.0873 0.0041 + -0.0698 0.0013 + -0.0524 0.0001 + -0.0349 0.0003 + -0.0175 0.0020 + 0.0000 0.0052 + 0.0175 0.0099 + 0.0349 0.0162 + 0.0524 0.0240 + 0.0698 0.0334 + 0.0873 0.0442 + 0.1047 0.0566 + 0.1222 0.0706 + 0.1396 0.0860 + 0.1571 0.0962 + 0.1745 0.1069 + 0.1920 0.1180 + 0.2094 0.1298 + 0.2269 0.1424 + 0.2443 0.1565 + 0.2618 0.1727 + 0.2793 0.1782 + 0.2967 0.1716 + 0.3142 0.1618 + 0.3316 0.1475 + 0.3491 0.1097 + 0.785 0.707 + 1.57 1.00 + 3.14 0.01 + +
+
+
+ + + Delta_drag_due_to_flap_deflection + + aero/qbar-psf + metrics/Sw-sqft + + fcs/flap-pos-deg + + 0.0000 0.000 + 15.0000 0.020 + 25.0000 0.040 + 45.0000 0.060 + +
+
+
+ + + Drag_due_to_Elevator_Deflection + + aero/qbar-psf + metrics/Sw-sqft + fcs/mag-elevator-pos-rad + 0.06 + + + + + Drag_due_to_sideslip + + aero/qbar-psf + metrics/Sw-sqft + aero/mag-beta-rad + 0.1400 + + + + + Drag_due_to_landing_gear + + aero/qbar-psf + metrics/Sw-sqft + gear/gear-pos-norm + 0.0600 + + +
+ + + + Side_force_due_to_beta + + aero/qbar-psf + metrics/Sw-sqft + + aero/beta-rad + + -0.3490 0.2120 + 0.0000 0.0000 + 0.3490 -0.2120 + +
+
+
+ + Side_force_due_to_roll_rate + + aero/qbar-psf + metrics/Sw-sqft + aero/bi2vel + velocities/r-aero-rad_sec + -0.1410 + + + + Side_force_due_to_yaw_rate + + aero/qbar-psf + metrics/Sw-sqft + aero/bi2vel + velocities/r-aero-rad_sec + 0.3550 + + + + Side_force_due_to_rudder + + aero/qbar-psf + metrics/Sw-sqft + fcs/rudder-pos-rad + 0.2300 + + +
+ + + + + Lift_at_zero_alpha. This data is extrapolated from the reference + featured in the file header notes. + + aero/qbar-psf + metrics/Sw-sqft + aero/function/kCLge + + fcs/flap-pos-deg + + 0.0 0.280 + 15.0 0.526 + 25.0 0.723 + 45.0 1.018 + 60.0 1.264 + +
+
+
+ + + Lift_due_to_alpha + + aero/qbar-psf + metrics/Sw-sqft + aero/function/kCLge + + aero/alpha-rad + + -3.1416 0.0 + -2.356 0.97 + -1.57 0.0 + -0.785 -0.970 + -0.3000 -1.0100 + -0.2820 -1.1720 + -0.2470 -1.0870 + -0.2120 -0.9480 + -0.1780 -0.8100 + 0.0000 0.0000 + 0.1040 0.4760 + 0.1390 0.6160 + 0.1740 0.7540 + 0.2090 0.8570 + 0.2440 0.9470 + 0.2790 0.8990 + 0.3000 0.8060 + 0.3140 0.5690 + 0.3490 0.2880 + 0.6 0.904 + 0.785 0.97 + 1.57 0.0 + 2.356 -0.97 + 3.14159 0 + +
+
+
+ + + Lift_due_to_Elevator_Deflection + + aero/qbar-psf + metrics/Sw-sqft + fcs/elevator-pos-rad + + aero/alpha-rad + + -1.57 0.0 + 0.0000 -0.8100 + 0.0873 -0.9000 + 0.1152 -0.7700 + 1.57 0.0 + +
+
+
+ + + Lift_due_to_alpha_rate + + aero/qbar-psf + metrics/Sw-sqft + aero/alphadot-rad_sec + aero/ci2vel + + aero/alpha-rad + + 0.0000 5.3000 + 0.0873 4.5000 + 0.1152 4.1000 + +
+
+
+ + + Lift_due_to_pitch_rate + + aero/qbar-psf + metrics/Sw-sqft + velocities/q-aero-rad_sec + aero/ci2vel + + aero/alpha-rad + + 0.0000 9.7000 + 0.0873 8.8000 + 0.1152 8.4000 + +
+
+
+
+ + + + Roll_moment_due_to_beta + + aero/qbar-psf + metrics/Sw-sqft + metrics/bw-ft + + aero/beta-rad + + -0.3490 0.0382 + 0.0000 0.0000 + 0.3490 -0.0382 + +
+
+
+ + Roll_moment_due_to_roll_rate_(roll_damping) + + aero/qbar-psf + metrics/Sw-sqft + metrics/bw-ft + aero/bi2vel + velocities/p-aero-rad_sec + -0.7500 + + + + Roll_moment_due_to_yaw_rate + + aero/qbar-psf + metrics/Sw-sqft + metrics/bw-ft + aero/bi2vel + velocities/r-aero-rad_sec + 0.0729 + + + + Roll_moment_due_to_aileron + + aero/qbar-psf + metrics/Sw-sqft + metrics/bw-ft + fcs/left-aileron-pos-rad + 0.1720 + + + + Roll_moment_due_to_rudder + + aero/qbar-psf + metrics/Sw-sqft + metrics/bw-ft + fcs/rudder-pos-rad + 0.0192 + + +
+ + + + Pitch_moment_at_zero_alpha + + aero/qbar-psf + metrics/Sw-sqft + metrics/cbarw-ft + 0.070 + + + + Pitch_moment_due_to_alpha + + aero/qbar-psf + metrics/Sw-sqft + metrics/cbarw-ft + aero/alpha-rad + -0.989 + + + + Pitch_moment_due_to_alpha_rate + + aero/qbar-psf + metrics/Sw-sqft + metrics/cbarw-ft + aero/ci2vel + aero/alphadot-rad_sec + -12.7000 + + + + Pitch_moment_due_to_pitch_rate_(pitch_damping) + + aero/qbar-psf + metrics/Sw-sqft + metrics/cbarw-ft + aero/ci2vel + velocities/q-aero-rad_sec + -80.0000 + + + + Pitch_moment_due_to_elevator_deflection + + aero/qbar-psf + metrics/Sw-sqft + metrics/cbarw-ft + fcs/elevator-pos-rad + -2.2600 + + + + Pitch_moment_due_to_flap_deflection + + aero/qbar-psf + metrics/Sw-sqft + metrics/cbarw-ft + + fcs/flap-pos-deg + + 0.0 0.000 + 15.0 -0.05 + 25.0 -0.10 + 45.0 -0.15 + +
+
+
+
+ + + + Yaw_moment_due_to_beta + + aero/qbar-psf + metrics/Sw-sqft + metrics/bw-ft + aero/beta-rad + 0.1000 + + + + Yaw_moment_due_to_roll_rate + + aero/qbar-psf + metrics/Sw-sqft + metrics/bw-ft + aero/bi2vel + velocities/p-aero-rad_sec + -0.0257 + + + + Yaw_moment_due_to_yaw_rate_(yaw_damping) + + aero/qbar-psf + metrics/Sw-sqft + metrics/bw-ft + aero/bi2vel + velocities/r-aero-rad_sec + -0.3000 + + + + Yaw_moment_due_to_aileron + + aero/qbar-psf + metrics/Sw-sqft + metrics/bw-ft + fcs/left-aileron-pos-rad + -0.0168 + + + + Yaw_moment_due_to_rudder + + aero/qbar-psf + metrics/Sw-sqft + metrics/bw-ft + fcs/rudder-pos-rad + -0.1152 + + + +
+ + +
diff --git a/core_sim/jsbsim/models/aircraft/c310_rc/c310_rc_ap.xml b/core_sim/jsbsim/models/aircraft/c310_rc/c310_rc_ap.xml new file mode 100644 index 00000000..2690d254 --- /dev/null +++ b/core_sim/jsbsim/models/aircraft/c310_rc/c310_rc_ap.xml @@ -0,0 +1,347 @@ + + + + + + + ap/attitude_hold + ap/altitude_hold + ap/heading_hold + ap/yaw_damper + ap/active-waypoint + ap/altitude_setpoint + ap/heading_setpoint + ap/heading-setpoint-select + ap/aileron_cmd + ap/elevator_cmd + ap/rudder_cmd + ap/airspeed_setpoint + ap/airspeed_hold + ap/throttle-cmd-norm + ap/heading-comm + ap/climb-rate-cmd + + + + + + + + + + + + + + + + ap/attitude_hold == 1 + + + + + attitude/phi-rad + ap/roll-pid-kp + ap/roll-pid-ki + ap/roll-pid-kd + fcs/wing-leveler-ap-on-off + + + + + + ap/attitude_hold == 1 + + + + + fcs/roll-ap-autoswitch + -1 + + + + + + + + + + + ap/heading-comm + 30 + + -30 + 30 + + + + + fcs/heading-corrected + 0.01745 + + + + fcs/heading-command + 0.50 + + + + fcs/heading-roll-error-lag + -attitude/phi-rad + + + + + + ap/heading_hold == 1 + + + + + fcs/heading-roll-error-switch + 6.0 + 0.13 + 6.0 + + + + + + ap/heading_hold == 1 + gear/unit[2]/WOW == 0 + + + ap/attitude_hold == 1 + gear/unit[2]/WOW == 0 + + ap/aileron_cmd + + + + + + ap/heading_hold == 1 + gear/unit/WOW == 1 + + fcs/steer-cmd-norm + + + + + + + + + + + + + + + ap/climb-rate-cmd + 100 + + -100 + 100 + + + + + + + fcs/altitude-error + + + + 25.70 + + position/h-sl-ft + 833.33 + + + 100.0 + + + + + + + fcs/hdot-command + -velocities/h-dot-fps + + + + + + + ap/altitude_hold == 1 + + + + + + fcs/elevator-pos-deg + 46.0 + + + + + fcs/ap-alt-hold-switch + fcs/windup-trigger + 0.001 + + + + + fcs/ap-alt-hold-switch + 0.03 + + + + + fcs/integral + fcs/proportional + + -1.0 + 1.0 + + + + + + fcs/control-summer + -1.0 + ap/elevator_cmd + + + + + + + + + + + + + aero/beta-rad + + velocities/ve-kts + + 30 0.00 + 60 -40.00 + +
+ ap/yaw_damper + + -1.0 + 1.0 + + ap/rudder_cmd +
+ +
+ +
diff --git a/core_sim/jsbsim/models/aircraft/c310_rc/ellington.xml b/core_sim/jsbsim/models/aircraft/c310_rc/ellington.xml new file mode 100644 index 00000000..29655e6b --- /dev/null +++ b/core_sim/jsbsim/models/aircraft/c310_rc/ellington.xml @@ -0,0 +1,43 @@ + + + + + + 29.5 + 29.594656 + -95.16384722 + + + + 0.0 + + + + 0.0 + 0.0 + 0.0 + + + + 0.0 + 0.0 + 0.0 + + + 26.0 + + diff --git a/core_sim/jsbsim/models/aircraft/c310_rc/reset00.xml b/core_sim/jsbsim/models/aircraft/c310_rc/reset00.xml new file mode 100644 index 00000000..e0ea1d9d --- /dev/null +++ b/core_sim/jsbsim/models/aircraft/c310_rc/reset00.xml @@ -0,0 +1,16 @@ + + + + 0.0 + 0.0 + 0.0 + 45.0 + 90.0 + 0.0 + 0.0 + 200.0 + 5.5 + diff --git a/core_sim/jsbsim/models/scripts/c3104_rc.xml b/core_sim/jsbsim/models/scripts/c3104_rc.xml new file mode 100644 index 00000000..249e371a --- /dev/null +++ b/core_sim/jsbsim/models/scripts/c3104_rc.xml @@ -0,0 +1,75 @@ + + + + + For testing autopilot capability + + + + + + + Start engine and set initial heading and waypoints, turn on heading-hold mode. + + simulation/sim-time-sec ge 0.25 + + + + + + + + + + + + + + + + + + position/lat-geod-deg + position/long-gc-deg + velocities/ve-kts + + + + + + + fcs/throttle-cmd-norm[0] gt 0 + fcs/throttle-cmd-norm[0] lt 0 + fcs/throttle-cmd-norm[1] gt 0 + fcs/throttle-cmd-norm[1] lt 0 + + + + + + velocities/vc-fps ge 145.0 + + + position/lat-geod-deg + position/long-gc-deg + velocities/ve-kts + + + + + position/h-agl-ft ge 40 + + + position/lat-geod-deg + position/long-gc-deg + velocities/ve-kts + + + + + \ No newline at end of file diff --git a/core_sim/src/CMakeLists.txt b/core_sim/src/CMakeLists.txt index eef8fd38..5c7be3a9 100644 --- a/core_sim/src/CMakeLists.txt +++ b/core_sim/src/CMakeLists.txt @@ -108,11 +108,14 @@ set_target_properties(${TARGET_NAME} PROPERTIES ) if(WIN32) - add_dependencies(${TARGET_NAME} nng-external) + add_dependencies(${TARGET_NAME} nng-external jsbsim-repo) else() - add_dependencies(${TARGET_NAME} nng-external openssl-external) + add_dependencies(${TARGET_NAME} nng-external jsbsim-repo openssl-external) endif() +# Set up JSBSim for linking +target_link_directories(${TARGET_NAME} PRIVATE ${JSBSIM_STATIC_LIB_DIR}) + # Set up nng and openssl for linking target_link_directories(${TARGET_NAME} PRIVATE ${NNG_LIB_DIR}) target_compile_definitions(${TARGET_NAME} PRIVATE NNG_STATIC_LIB=ON) @@ -127,6 +130,7 @@ target_include_directories( PUBLIC $ $ + ${JSBSIM_INCLUDE_DIR} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ${JSON_INCLUDE_DIR} @@ -148,6 +152,7 @@ if(WIN32) Crypt32 # Client authorization Ncrypt # Client authorization lvmon + jsbsim ) else() target_link_libraries( @@ -155,6 +160,7 @@ else() PRIVATE nng crypto # Client authorization + jsbsim ) endif() @@ -163,7 +169,10 @@ add_custom_command(TARGET ${TARGET_NAME} COMMAND ${CMAKE_COMMAND} -E echo "Packaging [${TARGET_NAME}] build outputs to ${UE_PLUGIN_SIMLIBS_DIR}/${TARGET_NAME}/$,Release,Debug>" COMMAND ${CMAKE_COMMAND} -E copy_directory $ ${UE_PLUGIN_SIMLIBS_DIR}/${TARGET_NAME}/$,Release,Debug> COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/../include ${UE_PLUGIN_SIMLIBS_DIR}/${TARGET_NAME}/include + COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_CURRENT_SOURCE_DIR}/../jsbsim ${UE_PLUGIN_SIMLIBS_DIR}/${TARGET_NAME}/jsbsim COMMAND ${CMAKE_COMMAND} -E remove_directory ${UE_PLUGIN_SIMLIBS_DIR}/${TARGET_NAME}/$,Release,Debug>/CMakeFiles COMMAND ${CMAKE_COMMAND} -E remove -f ${UE_PLUGIN_SIMLIBS_DIR}/${TARGET_NAME}/$,Release,Debug>/cmake_install.cmake COMMAND ${CMAKE_COMMAND} -E remove -f ${UE_PLUGIN_SIMLIBS_DIR}/${TARGET_NAME}/$,Release,Debug>/CTestTestfile.cmake ++ COMMAND ${CMAKE_COMMAND} -E copy_directory ${UE_PLUGIN_SIMLIBS_DIR}/${TARGET_NAME}/jsbsim ${UE_PLUGIN_SIMLIBS_DIR}/${TARGET_NAME}/jsbsim + ) diff --git a/core_sim/src/actor/robot.cpp b/core_sim/src/actor/robot.cpp index 33eeb12a..2dce4bbe 100644 --- a/core_sim/src/actor/robot.cpp +++ b/core_sim/src/actor/robot.cpp @@ -24,6 +24,9 @@ #include "json.hpp" #include "sensors/sensor_impl.hpp" +// JSBSim include (requires RTTI, must be in .cpp not .hpp) +#include "FGFDMExec.h" + namespace microsoft { namespace projectairsim { @@ -63,7 +66,8 @@ class Robot::Impl : public ActorImpl { Impl(const std::string& id, const Transform& origin, const Logger& logger, const TopicManager& topic_manager, const std::string& parent_topic_path, const ServiceManager& service_manager, - const StateManager& state_manager); + const StateManager& state_manager, + const std::string& working_simulation_path); void Load(ConfigJson config_json); @@ -134,6 +138,8 @@ class Robot::Impl : public ActorImpl { const PhysicsType& GetPhysicsType() const; void SetPhysicsType(const PhysicsType& phys_type); + //used only by JSBSim physics and controller + std::shared_ptr GetJSBSimModel() const; const std::string& GetPhysicsConnectionSettings() const; void SetPhysicsConnectionSettings(const std::string& phys_conn_settings); const std::string& GetControlConnectionSettings() const; @@ -169,6 +175,9 @@ class Robot::Impl : public ActorImpl { private: friend class Robot::Loader; + const std::string& GetJSBSimScript() const; + void InitializeJSBSimModel(); + Robot::Loader loader_; std::vector links_; std::vector joints_; @@ -182,6 +191,9 @@ class Robot::Impl : public ActorImpl { TimeNano kinematics_updated_timestamp_; PhysicsType physics_type_; + std::string jsbsim_script_; + std::string jsbsim_model_; + std::shared_ptr model_; std::string physics_connection_settings_; std::string control_connection_settings_; bool start_landed_; @@ -216,6 +228,8 @@ class Robot::Impl : public ActorImpl { indirectrefframe_; // Current pose reference frame TransformTree::StaticRefFrame staticrefframe_home_; // Home pose reference frame + + const std::string working_simulation_path_; }; // ----------------------------------------------------------------------------- @@ -227,19 +241,21 @@ Robot::Robot(const std::string& id, const Transform& origin, const Logger& logger, const TopicManager& topic_manager, const std::string& parent_topic_path, const ServiceManager& service_manager, - const StateManager& state_manager) + const StateManager& state_manager, + const std::string& working_simulation_path) : Actor(std::shared_ptr( new Robot::Impl(id, origin, logger, topic_manager, parent_topic_path, - service_manager, state_manager))) {} + service_manager, state_manager, working_simulation_path))) {} Robot::Robot(const std::string& id, const Transform& origin, const Logger& logger, const TopicManager& topic_manager, const std::string& parent_topic_path, const ServiceManager& service_manager, - const StateManager& state_manager, HomeGeoPoint home_geo_point) + const StateManager& state_manager, HomeGeoPoint home_geo_point, + const std::string& working_simulation_path) : Actor(std::shared_ptr( new Robot::Impl(id, origin, logger, topic_manager, parent_topic_path, - service_manager, state_manager))) { + service_manager, state_manager, working_simulation_path))) { static_cast(pimpl_.get())->SetHomeGeoPoint(home_geo_point); } @@ -372,6 +388,10 @@ void Robot::SetPhysicsType(const PhysicsType& phys_type) { static_cast(pimpl_.get())->SetPhysicsType(phys_type); } +std::shared_ptr Robot::GetJSBSimModel() const { + return static_cast(pimpl_.get())->GetJSBSimModel(); +} + const std::string& Robot::GetPhysicsConnectionSettings() const { return static_cast(pimpl_.get()) ->GetPhysicsConnectionSettings(); @@ -481,7 +501,8 @@ Robot::Impl::Impl(const std::string& id, const Transform& origin, const Logger& logger, const TopicManager& topic_manager, const std::string& parent_topic_path, const ServiceManager& service_manager, - const StateManager& state_manager) + const StateManager& state_manager, + const std::string& working_simulation_path) : ActorImpl(ActorType::kRobot, id, origin, Constant::Component::robot, logger, topic_manager, parent_topic_path, service_manager, state_manager), @@ -491,7 +512,8 @@ Robot::Impl::Impl(const std::string& id, const Transform& origin, indirectrefframe_(std::string("R ") + id, &kinematics_.pose), staticrefframe_home_(std::string("R ") + id + "_home", kinematics_.pose), last_actuated_rotation_simtime_(0), - start_landed_(false) { + start_landed_(false), + working_simulation_path_(working_simulation_path) { SetTopicPath(); CreateTopics(); RegisterServiceMethods(); @@ -516,6 +538,11 @@ void Robot::Impl::Load(ConfigJson config_json) { //! Initialize Sensors InitializeSensors(GetKinematics(), GetEnvironment()); + // check if using jsbsim physics to initialize jsbsim + if(physics_type_ == PhysicsType::kJSBSimPhysics) { + InitializeJSBSimModel(); + } + // Create tilt actuator target list { std::vector vecpactuatorTilt; @@ -722,6 +749,23 @@ void Robot::Impl::RegisterServiceMethods() { service_manager_.RegisterMethod(get_camera_ray, get_camera_ray_handler); } +void Robot::Impl::InitializeJSBSimModel(){ + model_ = std::make_shared(); + std::string jsbsim_root_path = + working_simulation_path_ + "/SimLibs/core_sim/jsbsim/models/"; + model_->SetRootDir(SGPath(jsbsim_root_path)); + model_->SetAircraftPath(SGPath("aircraft")); + model_->SetEnginePath(SGPath("engine")); + model_->SetSystemsPath(SGPath("systems")); + if(jsbsim_script_!="") { + if (!model_->LoadScript(SGPath(jsbsim_script_))) { + throw std::runtime_error("Failed to load JSBSim script"); + } + } else if (!model_->LoadModel(jsbsim_model_)) { + throw std::runtime_error("Failed to load JSBSim model"); + } +} + bool Robot::Impl::SetExternalForce(const std::vector& ext_force) { ext_force_ = Vector3(ext_force[0], ext_force[1], ext_force[2]); return true; @@ -964,6 +1008,10 @@ void Robot::Impl::SetPhysicsType(const PhysicsType& phys_type) { physics_type_ = phys_type; } +const std::string& Robot::Impl::GetJSBSimScript() const { return jsbsim_script_; } + +std::shared_ptr Robot::Impl::GetJSBSimModel() const { return model_; } + const std::string& Robot::Impl::GetPhysicsConnectionSettings() const { return physics_connection_settings_; } @@ -1405,6 +1453,16 @@ void Robot::Loader::LoadPhysicsType(const json& json) { impl_.physics_type_ = PhysicsType::kMatlabPhysics; } else if (physics_type == Constant::Config::unreal_physics) { impl_.physics_type_ = PhysicsType::kUnrealPhysics; + } else if (physics_type == Constant::Config::jsbsim_physics) { + impl_.physics_type_ = PhysicsType::kJSBSimPhysics; + impl_.jsbsim_script_ = + JsonUtils::GetString( + json, Constant::Config::jsbsim_script); + if(impl_.jsbsim_script_ == "") { + impl_.jsbsim_model_ = + JsonUtils::GetString( + json, Constant::Config::jsbsim_model); + } } else { impl_.physics_type_ = PhysicsType::kNonPhysics; impl_.logger_.LogWarning( @@ -1439,4 +1497,4 @@ void Robot::Loader::LoadController(const json& json) { } } // namespace projectairsim -} // namespace microsoft +} // namespace microsoft \ No newline at end of file diff --git a/core_sim/src/actuators/actuator_impl.hpp b/core_sim/src/actuators/actuator_impl.hpp index 2967d4c8..4b8fb282 100644 --- a/core_sim/src/actuators/actuator_impl.hpp +++ b/core_sim/src/actuators/actuator_impl.hpp @@ -160,7 +160,7 @@ class ActuatorImpl : public ComponentWithTopicsAndServiceMethods { const std::string& actor_id) { actor_logger.LogVerbose(actor_name, "[%s] Loading 'actuator.name'.", actor_id.c_str()); - auto id = JsonUtils::GetIdentifier(json, Constant::Config::name); + auto id = JsonUtils::GetString(json, Constant::Config::name); //TODO: This allowed an identifier with "/" in it for JSBsim actuators. Review if necessary or if we should use any property. actor_logger.LogVerbose(actor_name, "[%s][%s] 'actuator.name' loaded.", actor_id.c_str(), id.c_str()); diff --git a/core_sim/src/constant.hpp b/core_sim/src/constant.hpp index a756d34b..5571bb47 100644 --- a/core_sim/src/constant.hpp +++ b/core_sim/src/constant.hpp @@ -387,6 +387,9 @@ class Constant { static constexpr const char* control_connection = "control-connection"; static constexpr const char* start_landed = "start-landed"; static constexpr const char* unreal_physics = "unreal-physics"; + static constexpr const char* jsbsim_physics = "jsbsim-physics"; + static constexpr const char* jsbsim_script = "jsbsim-script"; + static constexpr const char* jsbsim_model = "jsbsim-model"; static constexpr const char* restitution = "restitution"; static constexpr const char* friction = "friction"; static constexpr const char* body_box_xyz = "body-box-xyz"; @@ -432,6 +435,9 @@ class Constant { static constexpr const char* simple_flight_api = "simple-flight-api"; static constexpr const char* simple_flight_api_settings = "simple-flight-api-settings"; + static constexpr const char* jsbsim_api = "jsbsim-api"; + static constexpr const char* jsbsim_api_settings = + "jsbsim-api-settings"; static constexpr const char* simple_drive_api = "simple-drive-api"; static constexpr const char* simple_drive_api_settings = "simple-drive-api-settings"; diff --git a/core_sim/src/message/common_utils.hpp b/core_sim/src/message/common_utils.hpp index 2d941661..0eb0c473 100644 --- a/core_sim/src/message/common_utils.hpp +++ b/core_sim/src/message/common_utils.hpp @@ -1,4 +1,4 @@ -// Copyright (C) Microsoft Corporation. +// Copyright (C) Microsoft Corporation. // Copyright (C) 2025 IAMAI CONSULTING CORP // MIT License. All rights reserved. @@ -169,7 +169,10 @@ struct JsonMsgpack { explicit JsonMsgpack(const json& data_json) { data = json::to_msgpack(data_json); } - json ToJson() const { return json::from_msgpack(data); } + json ToJson() const { + const auto* ptr = reinterpret_cast(data.data()); + return json::from_msgpack(ptr, ptr + data.size()); + } }; struct RadarDetectionMsgpack { diff --git a/core_sim/src/scene.cpp b/core_sim/src/scene.cpp index b265686d..d7cd33f9 100644 --- a/core_sim/src/scene.cpp +++ b/core_sim/src/scene.cpp @@ -79,7 +79,8 @@ class Scene::Impl : public ComponentWithTopicsAndServiceMethods { Impl(const Logger& logger, const TopicManager& topic_manager, const std::string& parent_topic_path, const ServiceManager& service_manager, - const StateManager& state_manager); + const StateManager& state_manager, + const std::string& working_simulation_path); void LoadSceneWithJSON(ConfigJson config_json); @@ -220,6 +221,7 @@ class Scene::Impl : public ComponentWithTopicsAndServiceMethods { int tiles_lod_min_; TransformTree transform_tree_; std::vector> trajectories_; + const std::string& working_simulation_path_; std::shared_ptr viewport_camera_; std::shared_ptr geodetic_converter_; }; @@ -232,9 +234,10 @@ Scene::Scene() : pimpl_(std::shared_ptr(nullptr)) {} Scene::Scene(const Logger& logger, const TopicManager& topic_manager, const std::string& parent_topic_path, const ServiceManager& service_manager, - const StateManager& state_manager) + const StateManager& state_manager, + const std::string& working_simulation_path) : pimpl_(std::make_shared(logger, topic_manager, parent_topic_path, - service_manager, state_manager)) {} + service_manager, state_manager, working_simulation_path)) {} void Scene::LoadWithJSON(ConfigJson config_json) { pimpl_->LoadSceneWithJSON(config_json); @@ -408,10 +411,12 @@ void Scene::Stop() { Scene::Impl::Impl(const Logger& logger, const TopicManager& topic_manager, const std::string& parent_topic_path, const ServiceManager& service_manager, - const StateManager& state_manager) + const StateManager& state_manager, + const std::string& working_simulation_path) : ComponentWithTopicsAndServiceMethods(Constant::Component::scene, logger, topic_manager, parent_topic_path, service_manager, state_manager), + working_simulation_path_(working_simulation_path), loader_(*this), geodetic_converter_(std::make_shared()) {} @@ -944,7 +949,7 @@ bool Scene::Impl::SceneTick() { // After kinematics have been updated, update each actor's environment // to match the new state, and then update the sensor state to match the // new environments. - for (auto& actor : actors_) { + for (auto& actor : actors_) { if (actor->GetType() == ActorType::kRobot) { auto& robot = static_cast(*actor); @@ -1374,7 +1379,8 @@ std::unique_ptr Scene::Loader::LoadActorWithJSON(const json& json) { auto robot = new Robot(id, origin, impl_.logger_, impl_.topic_manager_, impl_.topic_path_ + "/robots", impl_.service_manager_, - impl_.state_manager_, impl_.home_geo_point_); + impl_.state_manager_, impl_.home_geo_point_, + impl_.working_simulation_path_); robot->Load(robot_config); robot->SetPhysicsConnectionSettings(physics_connection_json.dump()); robot->SetControlConnectionSettings(control_connection_json.dump()); diff --git a/core_sim/src/sensors/camera.cpp b/core_sim/src/sensors/camera.cpp index 5be3d16f..326e6264 100644 --- a/core_sim/src/sensors/camera.cpp +++ b/core_sim/src/sensors/camera.cpp @@ -575,13 +575,16 @@ std::vector Camera::Impl::RunOnnxModelOnImages(ImageMessage imgMsg) { if (camera_settings.post_process_model_settings.execution_provider == "cuda") { logger_.LogVerbose(name_, "Trying to add CUDA EP since it is enabled."); - OrtSessionOptionsAppendExecutionProvider_CUDA(onnx_.session_options, 0); + auto status = OrtSessionOptionsAppendExecutionProvider_CUDA(onnx_.session_options, 0); + (void)status; // Explicitly mark as intentionally unused logger_.LogVerbose(name_, "onnx CUDA session declared"); } else if (camera_settings.post_process_model_settings .execution_provider == "tensorrt") { - OrtSessionOptionsAppendExecutionProvider_Tensorrt(onnx_.session_options, + auto status1 = OrtSessionOptionsAppendExecutionProvider_Tensorrt(onnx_.session_options, 0); - OrtSessionOptionsAppendExecutionProvider_CUDA(onnx_.session_options, 0); + auto status2 = OrtSessionOptionsAppendExecutionProvider_CUDA(onnx_.session_options, 0); + (void)status1; // Explicitly mark as intentionally unused + (void)status2; // Explicitly mark as intentionally unused logger_.LogVerbose(name_, "onnx TensorRT session declared"); } logger_.LogVerbose(name_, "onnx Creating session"); diff --git a/core_sim/src/simulator.cpp b/core_sim/src/simulator.cpp index 57764067..1f37dd61 100644 --- a/core_sim/src/simulator.cpp +++ b/core_sim/src/simulator.cpp @@ -52,7 +52,8 @@ class Simulator::Loader { class Simulator::Impl : public ComponentWithTopicsAndServiceMethods { public: explicit Impl(LoggerCallback logger_callback, - LogLevel level = LogLevel::kError); + LogLevel level = LogLevel::kError, + const std::string& working_simulation_path=""); void LoadSimulator(const std::string& sim_json, std::string client_auth_public_key); @@ -93,6 +94,7 @@ class Simulator::Impl : public ComponentWithTopicsAndServiceMethods { std::string scene_config_; static constexpr TimeNano kSceneTickPeriod = 3000000; // 3 ms = 333 Hz + const std::string working_simulation_path_; }; // ----------------------------------------------------------------------------- @@ -101,8 +103,9 @@ class Simulator::Impl : public ComponentWithTopicsAndServiceMethods { Simulator::Simulator() : pimpl_(std::make_shared(default_logger_callback)) {} -Simulator::Simulator(LoggerCallback logger_callback, LogLevel level) - : pimpl_(std::make_shared(logger_callback, level)) {} +Simulator::Simulator(LoggerCallback logger_callback, LogLevel level, + const std::string& working_simulation_path) + : pimpl_(std::make_shared(logger_callback, level, working_simulation_path)) {} void Simulator::LoadSimulator(const std::string& sim_json, std::string client_auth_public_key) { @@ -150,10 +153,12 @@ void Simulator::RegisterServiceMethod(const ServiceMethod& method, // ----------------------------------------------------------------------------- // class Simulator::Impl -Simulator::Impl::Impl(LoggerCallback logger_callback, LogLevel level) +Simulator::Impl::Impl(LoggerCallback logger_callback, LogLevel level, + const std::string& working_simulation_path) : ComponentWithTopicsAndServiceMethods(Constant::Component::simulator, Logger(logger_callback, level)), - loader_(*this) { + loader_(*this), + working_simulation_path_(working_simulation_path) { client_authorization_.SetLogger(GetLogger()); } @@ -344,7 +349,7 @@ void Simulator::Loader::LoadSceneWithJSON(const std::string& json_data) { impl_.sim_scene_ = Scene(impl_.logger_, impl_.topic_manager_, impl_.topic_path_, - impl_.service_manager_, impl_.state_manager_); + impl_.service_manager_, impl_.state_manager_, impl_.working_simulation_path_); impl_.state_manager_.Initialize(&impl_.sim_scene_); diff --git a/core_sim/test/CMakeLists.txt b/core_sim/test/CMakeLists.txt index fead3dec..b486d360 100644 --- a/core_sim/test/CMakeLists.txt +++ b/core_sim/test/CMakeLists.txt @@ -109,6 +109,7 @@ if(WIN32) Crypt32 # Client authorization Ncrypt # Client authorization lvmon + jsbsim ) else() target_link_libraries( @@ -118,19 +119,25 @@ else() core_sim nng crypto # Client authorization + jsbsim ) endif() target_include_directories(${TARGET_NAME} PRIVATE "${ONNXRUNTIME_ROOTDIR}/include") target_link_directories(${TARGET_NAME} PRIVATE "${ONNX_LIB_DIR}") -target_link_libraries(${TARGET_NAME} PRIVATE onnxruntime) +target_link_libraries(${TARGET_NAME} PRIVATE onnxruntime jsbsim) +add_custom_command( + TARGET ${TARGET_NAME} + PRE_LINK + COMMAND ${CMAKE_COMMAND} -E copy_directory ${UE_PLUGIN_SIMLIBS_DIR}/shared_libs/ ${SIMLIBS_TEST_DIR} +) add_custom_command( TARGET ${TARGET_NAME} PRE_LINK - COMMAND ${CMAKE_COMMAND} -E copy_directory ${UE_PLUGIN_SIMLIBS_DIR}/shared_libs/ ${SIMLIBS_TEST_DIR} + COMMAND ${CMAKE_COMMAND} -E copy_directory ${JSBSIM_CORESIM_DIR}/lib/Debug/ ${SIMLIBS_TEST_DIR} ) # Include CMake's GoogleTest module to use gtest_discover_tests() helper diff --git a/core_sim/test/gtest_actuator.cpp b/core_sim/test/gtest_actuator.cpp index 186bf931..74a46fe2 100644 --- a/core_sim/test/gtest_actuator.cpp +++ b/core_sim/test/gtest_actuator.cpp @@ -25,7 +25,7 @@ class Scene { // : public ::testing::Test { Logger logger(logger_callback); Transform origin = {{0, 0, 0}, {1, 0, 0, 0}}; return Robot("TestRobotID", origin, logger, TopicManager(logger), "", - ServiceManager(logger), StateManager(logger)); + ServiceManager(logger), StateManager(logger),""); } static void LoadRobot(Robot& robot, ConfigJson config_json) { diff --git a/core_sim/test/gtest_robot.cpp b/core_sim/test/gtest_robot.cpp index 7f287f2e..4590ccbf 100644 --- a/core_sim/test/gtest_robot.cpp +++ b/core_sim/test/gtest_robot.cpp @@ -29,7 +29,7 @@ class Scene { const std::string& message) {}; Logger logger(callback); return Robot(id, origin, logger, TopicManager(logger), "", - ServiceManager(logger), StateManager(logger)); + ServiceManager(logger), StateManager(logger), ""); } static void LoadRobot(Robot& robot, ConfigJson config_json) { diff --git a/core_sim/test/gtest_scene.cpp b/core_sim/test/gtest_scene.cpp index 892c2676..e123b7d4 100644 --- a/core_sim/test/gtest_scene.cpp +++ b/core_sim/test/gtest_scene.cpp @@ -28,7 +28,7 @@ class Simulator { const std::string& message) {}; Logger logger(callback); return Scene(logger, TopicManager(logger), "", ServiceManager(logger), - StateManager(logger)); + StateManager(logger),""); } static void LoadScene(Scene& scene, ConfigJson config_json) { diff --git a/core_sim/test/gtest_sensor.cpp b/core_sim/test/gtest_sensor.cpp index 130ece54..af82930b 100644 --- a/core_sim/test/gtest_sensor.cpp +++ b/core_sim/test/gtest_sensor.cpp @@ -27,7 +27,7 @@ class Scene { // : public ::testing::Test { Logger logger(logger_callback); Transform origin = {{0, 0, 0}, {1, 0, 0, 0}}; return Robot("TestRobotID", origin, logger, TopicManager(logger), "", - ServiceManager(logger), StateManager(logger)); + ServiceManager(logger), StateManager(logger),""); } static void LoadRobot(Robot& robot, ConfigJson config_json) { diff --git a/core_sim/test/gtest_simulator.cpp b/core_sim/test/gtest_simulator.cpp index e4a233e6..ce336f90 100644 --- a/core_sim/test/gtest_simulator.cpp +++ b/core_sim/test/gtest_simulator.cpp @@ -104,4 +104,4 @@ TEST(Simulator, GetID) { sim_config = "{ \"id\": \"abc\" "; EXPECT_THROW(simulator.LoadSimulator(sim_config), std::exception); EXPECT_TRUE(simulator.GetID().empty()); -} +} \ No newline at end of file diff --git a/docs/client_setup.md b/docs/client_setup.md index f1f32aef..96476571 100644 --- a/docs/client_setup.md +++ b/docs/client_setup.md @@ -4,12 +4,12 @@ A Python client uses the following to communicate with the Project AirSim simulation server: -- Python 3.7-3.9, 64-bit +- Python 3.7 or newer, 64-bit - **[pynng](https://github.com/codypiersall/pynng)** nanomsg-next-gen wrapper pip package ### Setting Up the Client on **Windows** -1. Install Python 3.7-3.9 for Windows. There are many options for installing Python, but one recommended way is to: +1. Install Python 3.7 or newer for Windows. There are many options for installing Python, but one recommended way is to: - Download the official **[Windows installer for Python](https://www.python.org/downloads/windows/)**. Please note that the 64-bit version is required. @@ -21,12 +21,12 @@ A Python client uses the following to communicate with the Project AirSim simula 2. Activate the Python environment to use with Project AirSim. - If you don't have a suitable Python environment yet, do the following. Here, we assume we're using Python 3.8 installed in the directory `C:\Python38`, but use the version and directory of your installation of Python: + If you don't have a suitable Python environment yet, do the following. Use the version and directory of your installation of Python: A) Install `virtualenv` and create a new environment (here named `airsim-venv` but you may choose any convenient name): - C:\Python310\python -m pip install virtualenv - C:\Python310\python -m venv C:\path\to\airsim-venv + python -m pip install virtualenv + python -m venv C:\path\to\airsim-venv B) Activate your environment: @@ -72,9 +72,9 @@ A Python client uses the following to communicate with the Project AirSim simula ### Setting Up the Client on **Linux** -1. Install Python 3.7-3.9 to your system: +1. Install Python 3.7 or newer to your system: - Ubuntu 20.04 comes with Python 3.8, but Project AirSim requires additional packages: + Ubuntu 20.04 comes with Python 3.8, while newer versions like Ubuntu 24.04 come with Python 3.12: sudo apt install python3-dev python3-venv diff --git a/docs/development/dev_setup_linux.md b/docs/development/dev_setup_linux.md index 423142ae..c20fdab5 100644 --- a/docs/development/dev_setup_linux.md +++ b/docs/development/dev_setup_linux.md @@ -16,14 +16,15 @@ On Linux, Project AirSim can be developed with VS Code which provides a light-we This will install: - - **make** - used by build scripts to drive CMake commands - - **cmake** - used to build sim lib components - - **clang 13, libc++ 13** - used to build sim lib components and match the bundled toolchain of Unreal Engine 5.2 - - **ninja** - used as the preferred CMake generator/build tool - - **vulkan loader library** - for UE rendering on Linux (OpenGL has been deprecated) - - **vulkan utils** - utilities like `vulkaninfo` for checking for graphics support + - **make** – used by build scripts to drive CMake commands + - **cmake** – used to configure and build sim lib components + - **ninja** – used as the preferred CMake generator/build tool + - **Vulkan loader library** – required for Unreal Engine rendering on Linux (OpenGL has been deprecated) + - **Vulkan utilities** – tools like `vulkaninfo` to verify graphics support - You may also need to install the latest drivers for your GPU to support the Vulkan interface. + **Note:** + Unreal Engine 5.2 and 5.7 provide their own complete Linux toolchain, including **Clang 20.1.x**, **libc++**, **lld**, and related LLVM tools. + Project AirSim builds **must use the Unreal-provided toolchain**, and therefore **do not require installing Clang or libc++ from the system package manager**. 3. Install **[VS Code](https://code.visualstudio.com/)** and the following extensions: @@ -54,10 +55,12 @@ On Linux, Project AirSim can be developed with VS Code which provides a light-we See **[Optional VS Code User Settings](vscode_user_settings.md)** for some example customized user settings that can help with Project AirSim development. -5. Install Unreal Engine 5.2 +5. Install Unreal Engine - Get UE source from **[Unreal Engine's private GitHub repo](https://github.com/EpicGames/UnrealEngine)** (requires **[registering with Epic](https://docs.unrealengine.com/en-US/GettingStarted/DownloadingUnrealEngine/index.html)**) + - Choose either branch 5.2 or 5.7 + - You can run the engine as built from source following **[Unreal's Linux native build process](https://github.com/EpicGames/UnrealEngine/blob/release/Engine/Build/BatchFiles/Linux/README.md)**, but to prevent the engine from recompiling itself during Project AirSim development, **it is recommended to make an [installed build](https://docs.unrealengine.com/en-US/Programming/Deployment/UsinganInstalledBuild/index.html) of the engine instead**. To make an installed build, run these steps: ``` diff --git a/docs/development/dev_setup_win.md b/docs/development/dev_setup_win.md index 4ef73c99..e19c406f 100644 --- a/docs/development/dev_setup_win.md +++ b/docs/development/dev_setup_win.md @@ -1,6 +1,6 @@ # Developer Initial Setup for Windows -On Windows, Project AirSim can be developed with either Visual Studio 2019 or VS Code. VS Code is convenient because it provides a lighter-weight, cross-platform common experience between Windows and Linux. +On Windows, Project AirSim can be developed with either Visual Studio 2022 or VS Code. VS Code is convenient because it provides a lighter-weight, cross-platform common experience between Windows and Linux. ## Setup @@ -29,22 +29,24 @@ On Windows, Project AirSim can be developed with either Visual Studio 2019 or VS B) To develop with **Visual Studio 2022**: - Install **[Visual Studio 2019](https://visualstudio.microsoft.com/vs/)** with: + Install **[Visual Studio 2022](https://visualstudio.microsoft.com/vs/)** with: - `Desktop development with C++` workload - `.NET Framework 4.8 SDK` individual component - `.NET Core SDK` individual component -2. Install the **[Epic Games Launcher](https://www.unrealengine.com/en-US/)** and install Unreal Engine 5.2 binary (requires Epic account log-in). While selecting the engine version to install, there is also an `Options` section where you can enable downloading `Editor symbols for debugging` (~30 GB) if desired. **Note**: Installing the engine can take a long time **(~1 hour)**. +2. Install the **[Epic Games Launcher](https://www.unrealengine.com/en-US/)** and install Unreal Engine, either 5.2 or 5.7 binary (requires Epic account log-in). While selecting the engine version to install, there is also an `Options` section where you can enable downloading `Editor symbols for debugging` (~30 GB) if desired. **Note**: Installing the engine can take a long time **(~1 hour)**. 3. Set a Windows environment variable for `UE_ROOT` to the installed folder, either through the Control Panel section `Edit environment variables for your account`, or by using the command line: ``` - setx UE_ROOT "C:\Program Files\Epic Games\UE_5.2" + setx UE_ROOT "C:\Program Files\Epic Games\UE_5.x" ``` +**Note**: set the Unreal Engine vesion installed (5.2 or 5.7) + 4. Unreal Engine on Windows defaults to using DirectX 11 for rendering, so you may need to install the latest GPU driver and DirectX updates. However, if you want to use Vulkan for rendering instead, you may need to install the **[Vulkan SDK](https://www.lunarg.com/vulkan-sdk/)**. 5. Install **[Git for Windows](https://gitforwindows.org/)** (including Git Credential Manager). @@ -55,7 +57,7 @@ On Windows, Project AirSim can be developed with either Visual Studio 2019 or VS 7. Do the **[Project AirSim Client Setup](../client_setup.md#setting-up-the-client-on-windows)**. -8. (Optional) Unreal Engine 5.2.x requires a specific MSVC compiler version and will fail with newer versions Create a configuration file to force Unreal's Build Tool to use the compiler version `14.37.32822` +8. (Optional) Unreal Engine 5.2.x requires a specific MSVC compiler version and will fail with newer versions Create a configuration file to force Unreal's Build Tool to use the compiler version `14.37.32822`. And 5.7.x requires a compiler version `14.39.33519` or `14.39.33523` File Path: `%APPDATA%\Unreal Engine\UnrealBuildTool\BuildConfiguration.xml` @@ -64,7 +66,7 @@ On Windows, Project AirSim can be developed with either Visual Studio 2019 or VS - 14.37.32822 + *Fill with correct compiler version* ``` diff --git a/docs/development/use_source.md b/docs/development/use_source.md index 82f2e088..7e6bf54f 100644 --- a/docs/development/use_source.md +++ b/docs/development/use_source.md @@ -61,14 +61,15 @@ Choose your development tool: ## Command Line (Windows/Linux) -On Windows, run the `build.cmd` script using the `x64 Native Tools Command Prompt for VS 2019`. +On Windows, run the `build.cmd` script using the `x64 Native Tools Command Prompt for VS 2022`. -Unreal Engine 5.2.x requires a specific MSVC compiler version and will fail with newer versions. Load the correct toolset into your command prompt session: -```cmd -"C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat" -vcvars_ver=14.37.32822 -``` +Unreal Engine 5.x requires a specific MSVC compiler version and will fail with newer versions. Make sure the correct compiler version is installed: + +For `UE5.2`: 14.37.32822 + +For `UE5.7`: 14.39.33519 -Note: This path assumes a default VS 2022 Community installation. Adjust the path if yours is different. +Note: This path assumes a default VS 2022 Community installation. Adjust the path if yours is different. There is no need to choose the version, both can be installed, `build.cmd` will choose the correct one according to the UE_ROOT set up previously in the Initial Setup. On Linux, run the `build.sh` shell script. diff --git a/docs/sensors/camera_streaming.md b/docs/sensors/camera_streaming.md index 0e24ba1e..b45c0bc4 100644 --- a/docs/sensors/camera_streaming.md +++ b/docs/sensors/camera_streaming.md @@ -32,6 +32,9 @@ Enabling streaming is independent of enabling capture of the raw image pixels th Currently, only a single streaming camera view can be rendered and viewed at a time for any sim instance, so there is no additional cost to enable multiple streaming cameras in the scene to have them available to cycle the view through, but the FPS of the sim may vary based on the resolution of the currently active streaming camera due to its corresponding rendering load. +**Note:** +This documentation applies to Unreal Engine 5.x. While Pixel Streaming has evolved internally since UE 4.27, the external workflow and Project AirSim integration remain largely the same. + ## Launching the sim with camera streaming on a local machine When running on a local machine, the `streaming-enabled` cameras can be viewed through the native viewport window of the sim process, but the web viewer can also be used to see how the stream would work if the sim server was running remotely from the user/client interface. @@ -86,7 +89,7 @@ To connect to a remote PixelStreaming view, such as running the sim server on Az 1. Ensure port 80 is open for TCP and UDP on the sim server compute machine (including through any OS firewall settings) to allow the stream viewer web browser to connect to the Signalling Web Server and proxy user inputs back to the server. -2. The Signalling Web Server launching scripts need to detect the server's public IP for the STUN server to connect the client to the server over the internet. As of UE 5.2, there are some bugs in the launching scripts that prevent the public IP from being detected correctly. To fix these bugs, manually modify the scripts as follows: +2. The Signalling Web Server launching scripts need to detect the server's public IP for the STUN server to connect the client to the server over the internet. In some Unreal Engine 5.x versions, there are known issues in the Pixel Streaming signalling server launch scripts that may prevent the public IP from being detected correctly. To fix these bugs, manually modify the scripts as follows: **(Linux) Start_Common.sh** diff --git a/physics/include/jsbsim_physics.hpp b/physics/include/jsbsim_physics.hpp new file mode 100644 index 00000000..85ff7e2f --- /dev/null +++ b/physics/include/jsbsim_physics.hpp @@ -0,0 +1,105 @@ +// Copyright (C) Microsoft Corporation. All rights reserved. + +#ifndef PHYSICS_INCLUDE_JSBSIM_PHYSICS_HPP_ +#define PHYSICS_INCLUDE_JSBSIM_PHYSICS_HPP_ + +#include + +#include "base_physics.hpp" +#include "core_sim/actor/robot.hpp" +#include "core_sim/environment.hpp" +#include "core_sim/math_utils.hpp" +#include "core_sim/physics_common_types.hpp" + + + +namespace microsoft { +namespace projectairsim { + +// ----------------------------------------------------------------------------- +// class JSBSimPhysicsBody + +class JSBSimPhysicsBody : public BasePhysicsBody { + public: + JSBSimPhysicsBody() {} + explicit JSBSimPhysicsBody(const Robot& robot); + ~JSBSimPhysicsBody() override {} + + void InitializeJSBSimPhysicsBody(const Robot& robot); + + // Aggregate all externally applied wrenches on body CG into wrench_ + void CalculateExternalWrench() override; + + void ReadRobotData(); + void WriteRobotData(const Kinematics& kinematics, + TimeNano external_time_stamp = -1); + + bool IsStillGrounded(); + bool IsLandingCollision(); + bool NeedsCollisionResponse(const Kinematics& next_kin); + + protected: + friend class JSBSimPhysicsModel; + + Robot sim_robot_; + + bool is_grounded_; + Vector3 env_gravity_; + float env_air_density_; + Vector3 env_wind_velocity_; + std::vector drag_faces_; + std::vector> lift_drag_links_; + std::unordered_map lift_drag_control_angles_; + std::vector external_wrench_points_; + + CollisionInfo collision_info_; + + static constexpr float kGroundCollisionAxisTol = 0.01f; + static constexpr float kCollisionOffset = 0.001f; // land with 1 mm air gap + + private: + void InitializeJSBSim(); + Kinematics GetKinematicsFromModel(); + Vector3 GetModelAngularAcceleration(); + Vector3 GetModelLinearAcceleration(); + Vector3 GetModelAngularVelocity(); + Vector3 GetModelLinearVelocity(); + Quaternion GetModelOrientation(); + Vector3 GetModelPosition(); + Vector3 GetModelCoordinates(); + void SetJSBSimAltitudeGrounded(float delta_altitude); + + Vector3d home_geopoint_ned_; + Vector3 home_geopoint_; + std::shared_ptr model_; +}; + +// ----------------------------------------------------------------------------- +// class JSBSimPhysicsModel + +class JSBSimPhysicsModel { + public: + JSBSimPhysicsModel() {} + ~JSBSimPhysicsModel() {} + + void SetWrenchesOnPhysicsBody(std::shared_ptr body); + + void StepPhysicsBody(TimeNano dt_nanos, + std::shared_ptr body); + + Kinematics CalcNextKinematicsNoCollision( + TimeSec dt_sec, std::shared_ptr& fp_body); + + Kinematics CalcNextKinematicsWithCollision( + TimeSec dt_sec, std::shared_ptr& fp_body); + + protected: + static constexpr float kDragMinVelocity = 0.1f; + private: + TimeSec residual_time_; +}; + +} // namespace projectairsim +} // namespace microsoft + +#endif // PHYSICS_INCLUDE_JSBSIM_PHYSICS_HPP_ \ No newline at end of file diff --git a/physics/include/physics_world.hpp b/physics/include/physics_world.hpp index 427fe8a9..5a0815e0 100644 --- a/physics/include/physics_world.hpp +++ b/physics/include/physics_world.hpp @@ -16,6 +16,7 @@ #include "fast_physics.hpp" #include "matlab_physics.hpp" #include "unreal_physics.hpp" +#include "jsbsim_physics.hpp" namespace microsoft { namespace projectairsim { @@ -25,7 +26,7 @@ namespace projectairsim { // is decided that could work for all physics types, this could be changed to // use standard base-class inheritance instead of variants. using ModelVariant = - std::variant; + std::variant; class PhysicsWorld { public: diff --git a/physics/src/CMakeLists.txt b/physics/src/CMakeLists.txt index c99ab21c..4bf8b170 100644 --- a/physics/src/CMakeLists.txt +++ b/physics/src/CMakeLists.txt @@ -24,6 +24,7 @@ add_library( unreal_physics.cpp physics_world.cpp matlab_physics.cpp + jsbsim_physics.cpp ) set_target_properties(${TARGET_NAME} PROPERTIES @@ -32,7 +33,10 @@ set_target_properties(${TARGET_NAME} PROPERTIES COMPILE_PDB_OUTPUT_DIR ${CMAKE_BINARY_DIR} ) -add_dependencies(${TARGET_NAME} core_sim nng-external) +add_dependencies(${TARGET_NAME} core_sim jsbsim-repo nng-external) + +# Set up JSBSim for linking +target_link_directories(${TARGET_NAME} PRIVATE ${JSBSIM_STATIC_LIB_DIR}) # Set up nng for linking target_link_directories(${TARGET_NAME} PRIVATE ${NNG_LIB_DIR}) @@ -49,6 +53,7 @@ target_include_directories( ${JSON_INCLUDE_DIR} ${NNG_INCLUDE_DIR} ${MSGPACK_INCLUDE_DIR} + ${JSBSIM_INCLUDE_DIR} ) if(WIN32) @@ -61,6 +66,7 @@ if(WIN32) mswsock # req by nng on Win advapi32 # req by nng on Win lvmon + jsbsim ) else() target_link_libraries( @@ -68,6 +74,7 @@ else() PRIVATE core_sim nng + jsbsim ) endif() diff --git a/physics/src/jsbsim_physics.cpp b/physics/src/jsbsim_physics.cpp new file mode 100644 index 00000000..7a8c8b18 --- /dev/null +++ b/physics/src/jsbsim_physics.cpp @@ -0,0 +1,458 @@ +// Copyright (C) Microsoft Corporation. All rights reserved. + +#include "jsbsim_physics.hpp" + +#include +#include + +#include "core_sim/actuators/actuator.hpp" +#include "core_sim/actuators/lift_drag_control_surface.hpp" +#include "core_sim/actuators/rotor.hpp" +#include "core_sim/earth_utils.hpp" +#include "core_sim/math_utils.hpp" +#include "core_sim/physics_common_types.hpp" +#include "core_sim/physics_common_utils.hpp" +#include "core_sim/transforms/transform_utils.hpp" +#include "core_sim/geodetic_converter.hpp" +#include "initialization/FGInitialCondition.h" +#include "initialization/FGTrim.h" +#include "FGFDMExec.h" // JSBSim + + + +namespace microsoft { +namespace projectairsim { + +// ----------------------------------------------------------------------------- +// class JSBSimPhysicsBody + +JSBSimPhysicsBody::JSBSimPhysicsBody(const Robot& robot) + : sim_robot_(robot) { + SetName(robot.GetID()); + SetPhysicsType(PhysicsType::kJSBSimPhysics); + InitializeJSBSimPhysicsBody(robot); +} + +void JSBSimPhysicsBody::InitializeJSBSimPhysicsBody( + const Robot& robot) { + const auto& links = sim_robot_.GetLinks(); + const auto& root_link = links.at(0); // TODO allow config to choose root link + + //external_wrench_points_.clear(); + SetMass(root_link.GetInertial().GetMass()); // TODO get mass from JSBSim + friction_ = root_link.GetCollision().GetFriction(); + restitution_ = root_link.GetCollision().GetRestitution(); + is_grounded_ = sim_robot_.GetStartLanded(); + + model_ = sim_robot_.GetJSBSimModel(); + model_->SetPropertyValue("simulation/dt", 0.008333333333); //TODO: use configuration instead of harcoded value + + InitializeJSBSim(); + + // get difference betweeen JSBSim's initial geopoint position and home geopoint position + const auto& world_geopoint = sim_robot_.GetEnvironment().home_geo_point.geo_point; + home_geopoint_ = GetModelCoordinates(); + //Get distance between home geopoint and JSBSim's initial geopoint + GeodeticConverter converter(world_geopoint.latitude, world_geopoint.longitude, + world_geopoint.altitude); + converter.geodetic2Ned(home_geopoint_[0], home_geopoint_[1], home_geopoint_[2], &home_geopoint_ned_[0], &home_geopoint_ned_[1], &home_geopoint_ned_[2]); + // unreal terrain is flat. Use initial altitude + home_geopoint_ned_[2] = -(home_geopoint_[2]-world_geopoint.altitude); +} + +void JSBSimPhysicsBody::InitializeJSBSim(){ + //updates jsbsim initial conditions with current state + auto& init = *model_->GetIC(); + //SGPath init_file("reset00.xml"); + //init.Load(init_file); + init.SetLatitudeDegIC(sim_robot_.GetEnvironment().env_info.geo_point.latitude); + init.SetLongitudeDegIC(sim_robot_.GetEnvironment().env_info.geo_point.longitude); + auto alt_ft = + sim_robot_.GetEnvironment().env_info.geo_point.altitude * MathUtils::meters_to_feets; // TODO: method to convert from m/s to fps + init.SetAltitudeASLFtIC(alt_ft); + // Set terrain elevation at initial position + init.SetTerrainElevationFtIC(alt_ft); + auto orientation = TransformUtils::ToRPY(sim_robot_.GetKinematics().pose.orientation); + init.SetPsiDegIC(MathUtils::rad2Deg(orientation.z())); + init.SetThetaDegIC(MathUtils::rad2Deg(orientation.y())); + init.SetPhiDegIC(MathUtils::rad2Deg(orientation.x())); + auto velocity = sim_robot_.GetKinematics().twist.linear; + init.SetVNorthFpsIC(velocity.x() * MathUtils::meters_to_feets); // TODO: method to convert from m/s to fps + init.SetVEastFpsIC(velocity.y() * MathUtils::meters_to_feets); + init.SetVDownFpsIC(velocity.z() * MathUtils::meters_to_feets); + auto angular_velocity = sim_robot_.GetKinematics().twist.angular; + init.SetPRadpsIC(angular_velocity.x()); + init.SetQRadpsIC(angular_velocity.y()); + init.SetRRadpsIC(angular_velocity.z()); + auto wind_velocity = sim_robot_.GetEnvironment().wind_velocity; + init.SetWindNEDFpsIC(wind_velocity.x() * MathUtils::meters_to_feets, wind_velocity.y() * MathUtils::meters_to_feets, + wind_velocity.z() * MathUtils::meters_to_feets); + + // run initial conditions + if(model_->RunIC() == false){ + throw std::runtime_error("JSBSim failed to initialize"); + } + + /*JSBSim::FGTrim trim_(model_.get(), JSBSim::tGround); + if (!trim_.DoTrim()) + { + trim_.Report(); + trim_.TrimStats(); + + throw std::runtime_error("TRIM FAILED"); + }*/ +} + +void JSBSimPhysicsBody::SetJSBSimAltitudeGrounded(float delta_altitude){ + //model_->SetPropertyValue("position/h-sl-meters", -position[2]); + auto terrain_elevation_val = model_->GetPropertyValue("position/terrain-elevation-asl-ft") + delta_altitude * MathUtils::meters_to_feets; + model_->SetPropertyValue("position/terrain-elevation-asl-ft", terrain_elevation_val); + auto altitude = model_->GetPropertyValue("position/h-sl-meters"); + auto new_altitude = altitude + delta_altitude * MathUtils::meters_to_feets; + model_->SetPropertyValue("position/h-sl-meters", new_altitude); +} + +// TODO Rename this to "SetActuationOutputs"? +void JSBSimPhysicsBody::CalculateExternalWrench() { + // No need to do anything here, all wrenches are calculated in the step by JSBSim +} + +void JSBSimPhysicsBody::ReadRobotData() { + kinematics_ = sim_robot_.GetKinematics(); + collision_info_ = sim_robot_.GetCollisionInfo(); + const auto& cur_env = sim_robot_.GetEnvironment(); + const auto& cur_env_info = cur_env.env_info; + env_gravity_ = cur_env_info.gravity; + env_air_density_ = cur_env_info.air_density; + env_wind_velocity_ = cur_env.wind_velocity; +} + +void JSBSimPhysicsBody::WriteRobotData(const Kinematics& kinematics, + TimeNano external_time_stamp) { + sim_robot_.UpdateKinematics(kinematics, external_time_stamp); +} + +bool JSBSimPhysicsBody::IsStillGrounded() { + if (is_grounded_ && + kinematics_.twist.linear.z() >= 0) { + is_grounded_ = true; + } else { + is_grounded_ = false; + } + + return is_grounded_; +} + +bool JSBSimPhysicsBody::IsLandingCollision() { + if (collision_info_.has_collided == false) { + return false; + } + + // Check if collision normal is primarily vertically upward (assumes NED) + const Vector3 normal_body = PhysicsUtils::TransformVectorToBodyFrame( + collision_info_.normal, kinematics_.pose.orientation); + + const bool is_ground_normal = MathUtils::IsApproximatelyEqual( + normal_body.z(), -1.0f, kGroundCollisionAxisTol); + + if (is_ground_normal) { + is_grounded_ = true; + return true; + } else { + return is_grounded_; + } +} + +bool JSBSimPhysicsBody::NeedsCollisionResponse(const Kinematics& next_kin) { + const bool is_moving_into_collision = + (collision_info_.normal.dot(next_kin.twist.linear) < 0.0f); + + if (collision_info_.has_collided && is_moving_into_collision) { + return true; + } else { + return false; + } +} + +// ----------------------------------------------------------------------------- +// class JSBSimPhysicsModel + +void JSBSimPhysicsModel::SetWrenchesOnPhysicsBody( + std::shared_ptr body) { +} + +void JSBSimPhysicsModel::StepPhysicsBody(TimeNano dt_nanos, + std::shared_ptr body) { + // Dynamic cast to a JSBSimPhysicsBody + std::shared_ptr fp_body = + std::dynamic_pointer_cast(body); + + if (fp_body != nullptr) { + auto dt_sec = SimClock::Get()->NanosToSec(dt_nanos); + Kinematics next_kin; + // To simulate collision response start uncommenting next lines and delete the two previous ones + + // Step 1 - Update physics body's data from robot's latest data + fp_body->ReadRobotData(); + + + + //Step 2 - Calculate kinematics with collision response if needed + if (fp_body->NeedsCollisionResponse(fp_body->kinematics_)) { + if (fp_body->IsLandingCollision()) { + // Calculate the landed position to stick at by offsetting back + // along the collision normal with an additional kCollisionOffset margin + // to prevent getting stuck in a collided state. + // Calculate the landed position to stick at by offsetting back + // along the collision normal with an additional kCollisionOffset margin + // to prevent getting stuck in a collided state. + const Vector3 delta_position = + fp_body->collision_info_.normal * + (fp_body->collision_info_.penetration_depth + + JSBSimPhysicsBody::kCollisionOffset); + auto landed_position = fp_body->collision_info_.position + delta_position; + //next_kin = CalcNextKinematicsGrounded( + // landed_position, fp_body->kinematics_.pose.orientation); + // TO-DO: set ground forces to model + next_kin = CalcNextKinematicsNoCollision(dt_sec, fp_body); + // set jsbsim to new position + fp_body->SetJSBSimAltitudeGrounded(-delta_position[2]); + next_kin.pose.position = landed_position; + fp_body->WriteRobotData(next_kin); + } else { + next_kin = CalcNextKinematicsWithCollision(dt_sec, fp_body); + fp_body->WriteRobotData(next_kin); + // Update environment to get updated geopoint + fp_body->sim_robot_.UpdateEnvironment(); + fp_body->InitializeJSBSim(); + } + } else { + next_kin = CalcNextKinematicsNoCollision(dt_sec, fp_body); + fp_body->WriteRobotData(next_kin); + } + } +} + +//Kinematics JSBSimPhysicsModel::CalcNextKinematicsGrounded( +// const Vector3& position, const Quaternion& orientation) { +// Kinematics kin_grounded; +// // Zero out accels/velocities +// kin_grounded.accels.linear = Vector3::Zero(); +// kin_grounded.accels.angular = Vector3::Zero(); +// kin_grounded.twist.linear = Vector3::Zero(); +// kin_grounded.twist.angular = Vector3::Zero(); +// +// // Pass-through position +// kin_grounded.pose.position = position; +// +// // Zero out roll/pitch, pass-through yaw +// auto rpy = TransformUtils::ToRPY(orientation); +// kin_grounded.pose.orientation = TransformUtils::ToQuaternion(0., 0., rpy[2]); +// +// return kin_grounded; +//} + + +Vector3 JSBSimPhysicsBody::GetModelCoordinates(){ //TODO: use GeoPoint instead of Vector3 +//Get JSBSim geopoint + auto lat_deg = model_->GetPropertyValue("position/lat-gc-deg"); + auto lon_deg = model_->GetPropertyValue("position/long-gc-deg"); + auto alt_mt = model_->GetPropertyValue("position/h-sl-meters"); + return Vector3(lat_deg, lon_deg, alt_mt); +} + +Vector3 JSBSimPhysicsBody::GetModelPosition() { + //get latitude displacement + auto delta_lat = model_->GetPropertyValue("position/lat-gc-deg") - + home_geopoint_[0]; + //get latitude in meters + double n = std::copysign( + model_->GetPropertyValue("position/distance-from-start-lat-mt"), + delta_lat); + // get longitud displacement + auto delta_lon = model_->GetPropertyValue("position/long-gc-deg") - + home_geopoint_[1]; + //get longitud in meters + double e = std::copysign( + model_->GetPropertyValue("position/distance-from-start-lon-mt"), + delta_lon); + double d = + -(model_->GetPropertyValue("position/h-sl-meters") - home_geopoint_[2]); + return Vector3(n, e, d); +} + +Quaternion JSBSimPhysicsBody::GetModelOrientation() { + double roll = model_->GetPropertyValue("attitude/roll-rad"); + double pitch = model_->GetPropertyValue("attitude/pitch-rad"); + double yaw = MathUtils::deg2Rad(model_->GetPropertyValue("attitude/psi-deg")); + return TransformUtils::ToQuaternion(roll, pitch, yaw); +} + +Vector3 JSBSimPhysicsBody::GetModelLinearVelocity() { + double n = model_->GetPropertyValue("velocities/v-north-fps") * MathUtils::feets_to_meters; //TODO: replace for a FeetsToMeters method + double e = model_->GetPropertyValue("velocities/v-east-fps") * MathUtils::feets_to_meters; + double d = model_->GetPropertyValue("velocities/v-down-fps") * MathUtils::feets_to_meters; + return Vector3(n, e, d); +} + +//Body Frame +Vector3 JSBSimPhysicsBody::GetModelAngularVelocity() { + double p = model_->GetPropertyValue("velocities/p-rad_sec"); + double q = model_->GetPropertyValue("velocities/q-rad_sec"); + double r = model_->GetPropertyValue("velocities/r-rad_sec"); + return Vector3(p, q, r); +} + +Vector3 JSBSimPhysicsBody::GetModelLinearAcceleration() { + double ui = model_->GetPropertyValue("accelerations/uidot-ft_sec2") * MathUtils::feets_to_meters; + double vi = model_->GetPropertyValue("accelerations/vidot-ft_sec2") * MathUtils::feets_to_meters; + double wi = model_->GetPropertyValue("accelerations/widot-ft_sec2") * MathUtils::feets_to_meters; + return Vector3(ui, vi, wi); +} + +//Body Frame +Vector3 JSBSimPhysicsBody::GetModelAngularAcceleration() { + double pdot = model_->GetPropertyValue("accelerations/pdot-rad_sec2"); + double qdot = model_->GetPropertyValue("accelerations/qdot-rad_sec2"); + double rdot = model_->GetPropertyValue("accelerations/rdot-rad_sec2"); + return Vector3(pdot, qdot, rdot); +} + +Kinematics JSBSimPhysicsBody::GetKinematicsFromModel() { + Kinematics kinematics; + kinematics.pose.position = GetModelPosition(); + //add initial x,y position to the model's relative position + kinematics.pose.position[0] += home_geopoint_ned_[0]; + kinematics.pose.position[1] += home_geopoint_ned_[1]; + kinematics.pose.position[2] += home_geopoint_ned_[2]; + kinematics.pose.orientation = GetModelOrientation(); + kinematics.twist.linear = GetModelLinearVelocity(); + kinematics.twist.angular = GetModelAngularVelocity(); + kinematics.accels.linear = GetModelLinearAcceleration(); + kinematics.accels.angular = GetModelAngularAcceleration(); + return kinematics; +} + +Kinematics JSBSimPhysicsModel::CalcNextKinematicsNoCollision( + TimeSec dt_sec, std::shared_ptr& fp_body) { + + + residual_time_ += dt_sec; + // get jsbsim dt + double jsbsim_dt = fp_body->model_->GetPropertyValue("simulation/dt"); + + // Run JSBSim for the residual time + while (residual_time_ >= jsbsim_dt) { + // Run JSBSim for one time step + fp_body->model_->Run(); + residual_time_ -= jsbsim_dt; + } + + return fp_body->GetKinematicsFromModel(); +} + +// TO-DO: this is a copy-paste from fast physics. Extract as a common collision reaction +Kinematics JSBSimPhysicsModel::CalcNextKinematicsWithCollision( + TimeSec dt_sec, std::shared_ptr& fp_body) { + const auto& collision_info = fp_body->collision_info_; + const auto& cur_kin = fp_body->kinematics_; + const auto& restitution = fp_body->restitution_; + const auto& friction = fp_body->friction_; + const auto& mass_inv = fp_body->mass_inv_; + const auto& inertia_inv = fp_body->inertia_inv_; + + Kinematics kin_with_collision; // main output of this function + + const Vector3 normal_body = PhysicsUtils::TransformVectorToBodyFrame( + collision_info.normal, cur_kin.pose.orientation); + + const Vector3 ave_vel_lin = + cur_kin.twist.linear + cur_kin.accels.linear * dt_sec; + + const Vector3 ave_vel_ang = + cur_kin.twist.angular + cur_kin.accels.angular * dt_sec; + + // Step 1 - Calculate restitution impulse (normal to impact) + + // Velocity at contact point + const Vector3 ave_vel_lin_body = PhysicsUtils::TransformVectorToBodyFrame( + ave_vel_lin, cur_kin.pose.orientation); + + // Contact point vector + const Vector3 r_contact = + collision_info.impact_point - collision_info.position; + + const Vector3 contact_vel_body = + ave_vel_lin_body + ave_vel_ang.cross(r_contact); + + // GafferOnGames - Collision response with columb friction + // http://gafferongames.com/virtual-go/collision-response-and-coulomb-friction/ + // Assuming collision is with static fixed body, + // impulse magnitude = j = -(1 + R)V.N / (1/m + (I'(r X N) X r).N) + // Physics Part 3, Collision Response, Chris Hecker, eq 4(a) + // http://chrishecker.com/images/e/e7/Gdmphys3.pdf + // V(t+1) = V(t) + j*N / m + // TODO(edufford) This formula doesn't produce realistic bounces, improve it + const float restitution_impulse_denom = + mass_inv + (inertia_inv * r_contact.cross(normal_body)) + .cross(r_contact) + .dot(normal_body); + + const float restitution_impulse = -contact_vel_body.dot(normal_body) * + (1.0f + restitution) / + restitution_impulse_denom; + + // Step 2 - Add restitution impulse to next twist velocities + + kin_with_collision.twist.linear = + ave_vel_lin + collision_info.normal * restitution_impulse * mass_inv; + + // TODO(edufford) Shouldn't this formula should account for inertia? + kin_with_collision.twist.angular = + ave_vel_ang + r_contact.cross(normal_body) * restitution_impulse; + + // Step 3 - Calculate friction impulse (tangent to contact) + + const Vector3 contact_tang_body = + contact_vel_body - normal_body * normal_body.dot(contact_vel_body); + + const Vector3 contact_tang_unit_body = contact_tang_body.normalized(); + + const float friction_mag_denom = + mass_inv + (inertia_inv * r_contact.cross(contact_tang_unit_body)) + .cross(r_contact) + .dot(contact_tang_unit_body); + + const float friction_mag = + -contact_tang_body.norm() * friction / friction_mag_denom; + + // Step 4 - Add friction impulse to next twist velocities + + const Vector3 contact_tang_unit = PhysicsUtils::TransformVectorToWorldFrame( + contact_tang_unit_body, cur_kin.pose.orientation); + + kin_with_collision.twist.linear += contact_tang_unit * friction_mag; + + kin_with_collision.twist.angular += + r_contact.cross(contact_tang_unit_body) * friction_mag * mass_inv; + + // Step 5 - Zero out next accels during collision response to prevent + // cancelling out impulse response + + kin_with_collision.accels.linear = Vector3::Zero(); + kin_with_collision.accels.angular = Vector3::Zero(); + + // Step 6 - Calculate next position/orientation from collision position + + kin_with_collision.pose.position = + collision_info.position + + (collision_info.normal * collision_info.penetration_depth) + + (kin_with_collision.twist.linear * dt_sec); + + kin_with_collision.pose.orientation = cur_kin.pose.orientation; + + return kin_with_collision; +} + +} // namespace projectairsim +} // namespace microsoft \ No newline at end of file diff --git a/physics/src/physics_world.cpp b/physics/src/physics_world.cpp index b0389c36..3f233c82 100644 --- a/physics/src/physics_world.cpp +++ b/physics/src/physics_world.cpp @@ -10,6 +10,7 @@ #include "core_sim/scene.hpp" #include "fast_physics.hpp" #include "unreal_physics.hpp" +#include "jsbsim_physics.hpp" namespace microsoft { namespace projectairsim { @@ -56,6 +57,19 @@ void PhysicsWorld::AddRobot(const Robot& robot) { physics_models_.emplace(PhysicsType::kUnrealPhysics, std::in_place_type); } + } else if (robot.GetPhysicsType() == PhysicsType::kJSBSimPhysics) { + // Construct physics body passing params from robot JSON physics params + auto jsb_physics_body = + std::make_shared(robot); + + // Add physics body pointer to physics world + AddPhysicsBody(jsb_physics_body); + + // Add FastPhysics model to the world's models if not already added + if (physics_models_.count(PhysicsType::kJSBSimPhysics) == 0) { + physics_models_.emplace(PhysicsType::kJSBSimPhysics, + std::in_place_type); + } } } @@ -110,6 +124,9 @@ void PhysicsWorld::Start() { case PhysicsType::kUnrealPhysics: { break; } + case PhysicsType::kJSBSimPhysics: { + break; + } default: { break; } @@ -138,6 +155,12 @@ void PhysicsWorld::SetWrenchesOnPhysicsBodies() { up_model.SetWrenchesOnPhysicsBody(body); break; } + case PhysicsType::kJSBSimPhysics: { + auto& jsb_model = std::get( + physics_models_.at(PhysicsType::kJSBSimPhysics)); + jsb_model.SetWrenchesOnPhysicsBody(body); + break; + } default: { break; } @@ -164,6 +187,12 @@ void PhysicsWorld::StepPhysicsWorld(TimeNano dt_nanos) { // No-op, Unreal steps physics body directly break; } + case PhysicsType::kJSBSimPhysics: { + auto& jsb_model = std::get( + physics_models_.at(PhysicsType::kJSBSimPhysics)); + jsb_model.StepPhysicsBody(dt_nanos, body); + break; + } default: { break; } diff --git a/physics/test/CMakeLists.txt b/physics/test/CMakeLists.txt index b829d6e1..ba4b540d 100644 --- a/physics/test/CMakeLists.txt +++ b/physics/test/CMakeLists.txt @@ -33,9 +33,9 @@ set_target_properties( # Add dependency to core_sim_gtests since it copies the runtime DLLs into ${SIMLIBS_TEST_DIR} if(WIN32) - add_dependencies(${TARGET_NAME} physics core_sim core_sim_gtests nng-external gtest_main) + add_dependencies(${TARGET_NAME} physics core_sim core_sim_gtests nng-external jsbsim-repo gtest_main) else() - add_dependencies(${TARGET_NAME} physics core_sim core_sim_gtests nng-external openssl-external gtest_main) + add_dependencies(${TARGET_NAME} physics core_sim core_sim_gtests nng-external jsbsim-repo openssl-external gtest_main) endif() # Set up nng and openssl for linking @@ -43,6 +43,9 @@ target_link_directories(${TARGET_NAME} PRIVATE ${NNG_LIB_DIR} ${OPENSSL_LIB_DIR} target_compile_definitions(${TARGET_NAME} PRIVATE NNG_STATIC_LIB=ON OPENSSL_STATIC_LIB=ON) target_link_directories(${TARGET_NAME} PRIVATE ${ONNX_LIB_DIR}) +# Set up JSBSim for linking +target_link_directories(${TARGET_NAME} PRIVATE ${JSBSIM_LIB_DIR}) + target_include_directories( ${TARGET_NAME} PRIVATE @@ -54,6 +57,7 @@ target_include_directories( ${NNG_INCLUDE_DIR} ${MSGPACK_INCLUDE_DIR} ${OPENSSL_INCLUDE_DIR} + ${JSBSIM_INCLUDE_DIR} ) if(WIN32) @@ -64,6 +68,7 @@ target_link_libraries( physics nng core_sim + jsbsim lvmon ) else() @@ -75,6 +80,7 @@ target_link_libraries( nng crypto # Client authorization core_sim + jsbsim lvmon ) endif() @@ -83,6 +89,7 @@ add_custom_command(TARGET ${TARGET_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E echo "Copying [${TARGET_NAME}] test data to ${SIMLIBS_TEST_DIR}/test_data" COMMAND ${CMAKE_COMMAND} -E copy_directory ${TARGET_SOURCE_DIR}/test/test_data ${SIMLIBS_TEST_DIR}/test_data + COMMAND ${CMAKE_COMMAND} -E copy_directory ${JSBSIM_CORESIM_DIR}/lib/Debug/ ${SIMLIBS_TEST_DIR} ) # Include CMake's GoogleTest module to use gtest_discover_tests() helper diff --git a/samples/standalone_sim/CMakeLists.txt b/samples/standalone_sim/CMakeLists.txt index b6262679..d937a7e4 100644 --- a/samples/standalone_sim/CMakeLists.txt +++ b/samples/standalone_sim/CMakeLists.txt @@ -28,6 +28,7 @@ if(WIN32) simserver core_sim nng-external + jsbsim-repo physics multirotor_api rendering_scene @@ -38,6 +39,7 @@ else() simserver core_sim nng-external + jsbsim-repo openssl-external physics multirotor_api @@ -49,6 +51,10 @@ endif() target_link_directories(${TARGET_NAME} PRIVATE ${NNG_LIB_DIR} ${OPENSSL_LIB_DIR}) target_compile_definitions(${TARGET_NAME} PRIVATE NNG_STATIC_LIB=ON OPENSSL_STATIC_LIB=ON) target_link_directories(${TARGET_NAME} PRIVATE ${ONNX_LIB_DIR}) + +# Set up JSBSim for linking +target_link_directories(${TARGET_NAME} PRIVATE ${JSBSIM_STATIC_LIB_DIR}) + target_include_directories( ${TARGET_NAME} PUBLIC @@ -70,6 +76,7 @@ if(WIN32) simserver core_sim physics + jsbsim mavlinkcom multirotor_api rendering_scene @@ -86,6 +93,7 @@ else() simserver core_sim physics + jsbsim mavlinkcom multirotor_api rendering_scene diff --git a/setup_linux_dev_tools.sh b/setup_linux_dev_tools.sh index 73006d1b..ed2fc82d 100755 --- a/setup_linux_dev_tools.sh +++ b/setup_linux_dev_tools.sh @@ -1,5 +1,5 @@ #!/bin/bash -# Copyright (C) Microsoft Corporation. +# Copyright (C) Microsoft Corporation. # Copyright (C) 2025 IAMAI CONSULTING CORP # MIT License. @@ -65,6 +65,7 @@ sudo apt-get update # Install prerequisites sudo apt-get -y install --no-install-recommends \ + lsb-release \ build-essential \ rsync \ make \ @@ -75,3 +76,7 @@ sudo apt-get -y install --no-install-recommends \ ninja-build \ libvulkan1 \ vulkan-tools + +# Create symlinks for clang/clang++ to make them available without version suffix +sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-${TARGET_LLVM_VERSION} 100 +sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-${TARGET_LLVM_VERSION} 100 diff --git a/simserver/include/simserver.hpp b/simserver/include/simserver.hpp index d7e524f3..6e376bd5 100644 --- a/simserver/include/simserver.hpp +++ b/simserver/include/simserver.hpp @@ -28,7 +28,7 @@ class TileManager; class SimServer { public: - SimServer(Simulator::LoggerCallback logger_callback, LogLevel level); + SimServer(Simulator::LoggerCallback logger_callback, LogLevel level, const std::string& working_simulation_path=""); ~SimServer(); diff --git a/simserver/src/CMakeLists.txt b/simserver/src/CMakeLists.txt index 940392ed..cbe0859c 100644 --- a/simserver/src/CMakeLists.txt +++ b/simserver/src/CMakeLists.txt @@ -37,12 +37,14 @@ add_dependencies( multirotor_api rover_api rendering_scene + jsbsim-repo ) # Set up nng for linking target_link_directories(${TARGET_NAME} PRIVATE ${NNG_LIB_DIR}) target_compile_definitions(${TARGET_NAME} PRIVATE NNG_STATIC_LIB=ON) target_link_directories(${TARGET_NAME} PRIVATE ${ONNX_LIB_DIR}) +target_link_directories(${TARGET_NAME} PRIVATE ${JSBSIM_STATIC_LIB_DIR}) target_include_directories( ${TARGET_NAME} @@ -55,6 +57,7 @@ target_include_directories( ${JSON_INCLUDE_DIR} ${NNG_INCLUDE_DIR} ${MSGPACK_INCLUDE_DIR} + ${JSBSIM_INCLUDE_DIR} ) if(WIN32) @@ -72,6 +75,7 @@ if(WIN32) mswsock # req by nng on Win advapi32 # req by nng on Win lvmon + jsbsim ) else() target_link_libraries( @@ -84,6 +88,7 @@ else() rover_api rendering_scene nng + jsbsim ) endif() diff --git a/simserver/src/simserver.cpp b/simserver/src/simserver.cpp index 08f7ccff..e2a46f27 100644 --- a/simserver/src/simserver.cpp +++ b/simserver/src/simserver.cpp @@ -13,6 +13,7 @@ #include "core_sim/simulator.hpp" #include "manual_controller_api.hpp" #include "matlab_controller_api.hpp" +#include "jsbsim_api.hpp" #include "mavlink_api.hpp" #include "physics_world.hpp" #include "tile_manager.hpp" @@ -20,8 +21,8 @@ namespace microsoft { namespace projectairsim { -SimServer::SimServer(Simulator::LoggerCallback logger_callback, LogLevel level) - : simulator_(std::make_shared(logger_callback, level)), +SimServer::SimServer(Simulator::LoggerCallback logger_callback, LogLevel level, const std::string& working_simulation_path) + : simulator_(std::make_shared(logger_callback, level, working_simulation_path)), physics_world_(std::make_shared()), tile_manager_(nullptr), load_external_scene_callback_(nullptr), @@ -293,6 +294,10 @@ void SimServer::LoadControllers(Scene& scene) { auto simple_flight_api = new SimpleFlightApi(sim_robot, ptransformtree); sim_robot.SetController( std::unique_ptr(simple_flight_api)); + } else if (controller_type == "jsbsim-api") { + auto jsbsim_api = new JSBSimApi(sim_robot, ptransformtree); + sim_robot.SetController( + std::unique_ptr(jsbsim_api)); } else if (controller_type == "px4-api") { auto px4_api = new MavLinkApi(sim_robot, ptransformtree); sim_robot.SetController(std::unique_ptr(px4_api)); diff --git a/thirdparty/Licenses/JSBSim_c310_models_License.txt b/thirdparty/Licenses/JSBSim_c310_models_License.txt new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/thirdparty/Licenses/JSBSim_c310_models_License.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/tools/lvmon/Lib/src/serverconnectiontcp.cpp b/tools/lvmon/Lib/src/serverconnectiontcp.cpp index 380ad37a..db7961ab 100644 --- a/tools/lvmon/Lib/src/serverconnectiontcp.cpp +++ b/tools/lvmon/Lib/src/serverconnectiontcp.cpp @@ -3,6 +3,8 @@ // MIT License. All rights reserved. +#include +#include #include "serverconnectiontcp.h" #include diff --git a/unity/sim_unity_wrapper/include/sim_unity_wrapper.hpp b/unity/sim_unity_wrapper/include/sim_unity_wrapper.hpp index 9601c556..0862a958 100644 --- a/unity/sim_unity_wrapper/include/sim_unity_wrapper.hpp +++ b/unity/sim_unity_wrapper/include/sim_unity_wrapper.hpp @@ -92,7 +92,15 @@ extern "C" EXPORT bool CameraResetPose(int actor_index, int sensor_index, bool w extern "C" EXPORT void CameraMarkPoseUpdateAsCompleted(int actor_index, int sensor_index); +// InteropPose is trivially copyable and safe to return from C-linkage functions +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wreturn-type-c-linkage" +#endif extern "C" EXPORT UnityInterop::InteropPose CameraGetDesiredPose(int actor_index, int sensor_index); +#ifdef __clang__ +#pragma clang diagnostic pop +#endif ////////////////////////////// WorldSimApi /////////////////////////////////// diff --git a/unity/sim_unity_wrapper/src/CMakeLists.txt b/unity/sim_unity_wrapper/src/CMakeLists.txt index 71cbb7e9..c977404e 100644 --- a/unity/sim_unity_wrapper/src/CMakeLists.txt +++ b/unity/sim_unity_wrapper/src/CMakeLists.txt @@ -42,6 +42,8 @@ target_link_directories(${TARGET_NAME} PRIVATE ${NNG_LIB_DIR} ${OPENSSL_LIB_DIR} target_compile_definitions(${TARGET_NAME} PRIVATE NNG_STATIC_LIB=ON) target_link_directories(${TARGET_NAME} PRIVATE ${ONNX_LIB_DIR}) +# Set up JSBSim for linking +target_link_directories(${TARGET_NAME} PRIVATE ${JSBSIM_PHYSICS_DIR}/lib) target_include_directories( ${TARGET_NAME} diff --git a/unity/sim_unity_wrapper/src/sim_unity_wrapper.cpp b/unity/sim_unity_wrapper/src/sim_unity_wrapper.cpp index bb4e96a3..cd0e2520 100644 --- a/unity/sim_unity_wrapper/src/sim_unity_wrapper.cpp +++ b/unity/sim_unity_wrapper/src/sim_unity_wrapper.cpp @@ -444,8 +444,9 @@ const char* CameraGetLookAtObject(int actor_index, int sensor_index) { if (GetRobotByActorIndex(actor_index, robot)) { if (GetSensorByIndex(actor_index, sensor_index, camera)) { - const char* result = camera.GetLookAtObject().c_str(); - return result; + static std::string look_at_object; + look_at_object = camera.GetLookAtObject(); + return look_at_object.c_str(); } } diff --git a/unreal-linux-toolchain.cmake b/unreal-linux-toolchain.cmake index 6e2e78ea..6880a550 100644 --- a/unreal-linux-toolchain.cmake +++ b/unreal-linux-toolchain.cmake @@ -17,11 +17,40 @@ set(CMAKE_SYSTEM_NAME Linux) set(CMAKE_SYSTEM_PROCESSOR x86_64) +set(UE_ROOT_PATH "$ENV{UE_ROOT}") -# Set include and link dir paths to UE 4.27's bundled toolchain -set(UE_TOOLCHAIN "Engine/Extras/ThirdPartyNotUE/SDKs/HostLinux/Linux_x64/v21_clang-15.0.1-centos7") -set(CMAKE_SYSROOT "$ENV{UE_ROOT}/${UE_TOOLCHAIN}/x86_64-unknown-linux-gnu") -set(CMAKE_C_COMPILER "${CMAKE_SYSROOT}/bin/clang") +set(UE_SDK_BASE + "${UE_ROOT_PATH}/Engine/Extras/ThirdPartyNotUE/SDKs/HostLinux/Linux_x64" +) + +if(NOT EXISTS "${UE_SDK_BASE}") + message(FATAL_ERROR "Unreal Linux SDK path not found: ${UE_SDK_BASE}") +endif() + +# Find available SDK versions (v21_*, v22_*, etc.) +file(GLOB UE_SDK_DIRS + LIST_DIRECTORIES true + "${UE_SDK_BASE}/*" +) + +if(UE_SDK_DIRS STREQUAL "") + message(FATAL_ERROR "No Unreal Linux SDKs found in ${UE_SDK_BASE}") +endif() + +# If multiple SDKs exist, pick the last one (usually highest version) +list(SORT UE_SDK_DIRS) +list(GET UE_SDK_DIRS -1 UE_SDK_SELECTED) + +get_filename_component(UE_SDK_NAME "${UE_SDK_SELECTED}" NAME) + +message(STATUS "Using Unreal Linux SDK: ${UE_SDK_NAME}") + +# Final toolchain path +set(CMAKE_SYSROOT + "${UE_SDK_SELECTED}/x86_64-unknown-linux-gnu" +) + +set(CMAKE_C_COMPILER "${CMAKE_SYSROOT}/bin/clang") set(CMAKE_CXX_COMPILER "${CMAKE_SYSROOT}/bin/clang++") set(CMAKE_CXX_FLAGS "-I$ENV{UE_ROOT}/Engine/Source/ThirdParty/Unix/LibCxx/include -I$ENV{UE_ROOT}/Engine/Source/ThirdParty/Unix/LibCxx/include/c++/v1") diff --git a/unreal/Blocks/Blocks.uproject b/unreal/Blocks/Blocks.uproject index ba3e1b24..e3d70f56 100644 --- a/unreal/Blocks/Blocks.uproject +++ b/unreal/Blocks/Blocks.uproject @@ -1,6 +1,6 @@ { "FileVersion": 3, - "EngineAssociation": "5.1", + "EngineAssociation": "5.2", "Category": "", "Description": "", "Modules": [ diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/LightActorBase.cpp b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/LightActorBase.cpp index 76393e83..5223c88b 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/LightActorBase.cpp +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/LightActorBase.cpp @@ -4,6 +4,7 @@ // MIT License. All rights reserved. #include "LightActorBase.h" +#include "Components/LocalLightComponent.h" // Returns true if able to set intensity on all light components // False if any item is nullptr @@ -41,7 +42,7 @@ bool ALightActorBase::SetRadius(float NewRadius) { for(int i = 0; i < lightComponents.Num(); i++) { ULocalLightComponent* localLightComponent = - dynamic_cast(lightComponents[i]); + Cast(lightComponents[i]); if (localLightComponent != nullptr) { localLightComponent->SetAttenuationRadius(NewRadius); diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Renderers/GISRenderer.cpp b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Renderers/GISRenderer.cpp index a12ad4ae..6b17b032 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Renderers/GISRenderer.cpp +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Renderers/GISRenderer.cpp @@ -26,6 +26,7 @@ #include "bing_maps_utils.hpp" #include "tile_info.hpp" +#include "core_sim/log_level.hpp" AGISRenderer::AGISRenderer() : SimServer(nullptr), diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Renderers/GISRenderer.h b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Renderers/GISRenderer.h index 16013bf1..24dcc4bd 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Renderers/GISRenderer.h +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Renderers/GISRenderer.h @@ -9,6 +9,7 @@ #include #include #include +#include #include "CoreMinimal.h" #include "GameFramework/Actor.h" diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Renderers/ProcMeshActor.cpp b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Renderers/ProcMeshActor.cpp index fa7f9356..1c567b80 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Renderers/ProcMeshActor.cpp +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Renderers/ProcMeshActor.cpp @@ -8,6 +8,7 @@ #include "KismetProceduralMeshLibrary.h" #include "Materials/Material.h" #include "Materials/MaterialInstanceDynamic.h" +#include // Sets default values AProcMeshActor::AProcMeshActor() { diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Robot/UnrealRobotLink.cpp b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Robot/UnrealRobotLink.cpp index 1ca99ae0..db434948 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Robot/UnrealRobotLink.cpp +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Robot/UnrealRobotLink.cpp @@ -14,6 +14,7 @@ #include "UnrealLogger.h" #include "core_sim/link/geometry/unreal_mesh.hpp" #include "core_sim/math_utils.hpp" +#include "UnrealHelpers.h" namespace projectairsim = microsoft::projectairsim; diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/GPULidar.cpp b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/GPULidar.cpp index 54fa52d3..24257a7d 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/GPULidar.cpp +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/GPULidar.cpp @@ -7,6 +7,7 @@ #include "GPULidar.h" #include "ProjectAirSim.h" +#include "UnrealCompatibility.h" #include "Components/LineBatchComponent.h" #include "DrawDebugHelpers.h" #include "Engine/CollisionProfile.h" @@ -25,6 +26,7 @@ #include "UObject/ConstructorHelpers.h" #include "UnrealCameraRenderRequest.h" #include "UnrealLogger.h" +#include "UnrealTransforms.h" namespace projectairsim = microsoft::projectairsim; @@ -131,12 +133,21 @@ void UGPULidar::SetupSceneCapture( } // Hide debug points in case "draw-debug-points" is set to true + #if UE_IS_5_7 + OutSceneCaptureComp->HideComponent(Cast( + UnrealWorld->GetLineBatcher(UWorld::ELineBatcherType::World))); + OutSceneCaptureComp->HideComponent(Cast( + UnrealWorld->GetLineBatcher(UWorld::ELineBatcherType::WorldPersistent))); + OutSceneCaptureComp->HideComponent(Cast( + UnrealWorld->GetLineBatcher(UWorld::ELineBatcherType::Foreground))); + #elif UE_IS_5_2 OutSceneCaptureComp->HideComponent( Cast(UnrealWorld->LineBatcher)); OutSceneCaptureComp->HideComponent( Cast(UnrealWorld->PersistentLineBatcher)); OutSceneCaptureComp->HideComponent( Cast(UnrealWorld->ForegroundLineBatcher)); + #endif OutSceneCaptureComp->RegisterComponent(); auto RenderTarget = NewObject(); diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/ImagePackingAsyncTask.cpp b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/ImagePackingAsyncTask.cpp index 98cbb91f..04d12596 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/ImagePackingAsyncTask.cpp +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/ImagePackingAsyncTask.cpp @@ -8,6 +8,7 @@ #include #include "core_sim/message/image_message.hpp" +#include "UnrealLogger.h" namespace projectairsim = microsoft::projectairsim; diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/ImagePackingAsyncTask.h b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/ImagePackingAsyncTask.h index 84006758..0b11c439 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/ImagePackingAsyncTask.h +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/ImagePackingAsyncTask.h @@ -11,6 +11,7 @@ #include "UnrealCameraRenderRequest.h" #include "core_sim/sensors/camera.hpp" #include "core_sim/transforms/transform_utils.hpp" +#include "UnrealCamera.h" // This class follows the example template in Unreal's AsyncWork.h for // FAutoDeleteAsyncTask that deletes itself after completion on a background diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/LidarIntensitySceneViewExtension.cpp b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/LidarIntensitySceneViewExtension.cpp index c2b6d8a9..06d32c07 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/LidarIntensitySceneViewExtension.cpp +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/LidarIntensitySceneViewExtension.cpp @@ -1,14 +1,26 @@ #include "LidarIntensitySceneViewExtension.h" #include "RHI.h" +#include "UnrealCompatibility.h" #include "SceneView.h" #include "RenderGraph.h" -#include "Runtime/Renderer/Private/PostProcess/PostProcessing.h" +#include "ScreenPass.h" #include "CommonRenderResources.h" #include "Containers/DynamicRHIResourceArray.h" #include "Engine/World.h" #include "EngineUtils.h" -#include "SceneRendering.h" + +#include "PostProcess/SceneFilterRendering.h" +#include "RenderGraphUtils.h" +#include "RendererInterface.h" +#include "SceneTextureParameters.h" + +// Access to FPostProcessingInputs definition from internal Renderer headers +#if UE_IS_5_7 + #include "Runtime/Renderer/Internal/PostProcess/PostProcessInputs.h" +#elif UE_IS_5_2 + #include "Runtime/Renderer/Private/PostProcess/PostProcessing.h" +#endif #include "LidarIntensityShader.h" @@ -37,16 +49,18 @@ FScreenPassTextureViewportParameters GetTextureViewportParameters( Parameters.ViewportMax = InViewport.Rect.Max; Parameters.ViewportSize = ViewportSize; - Parameters.ViewportSizeInverse = FVector2f( - 1.0f / Parameters.ViewportSize.X, 1.0f / Parameters.ViewportSize.Y); + Parameters.ViewportSizeInverse = + FVector2f(1.0f / Parameters.ViewportSize.X, + 1.0f / Parameters.ViewportSize.Y); Parameters.UVViewportMin = ViewportMin * Parameters.ExtentInverse; Parameters.UVViewportMax = ViewportMax * Parameters.ExtentInverse; Parameters.UVViewportSize = Parameters.UVViewportMax - Parameters.UVViewportMin; - Parameters.UVViewportSizeInverse = FVector2f( - 1.0f / Parameters.UVViewportSize.X, 1.0f / Parameters.UVViewportSize.Y); + Parameters.UVViewportSizeInverse = + FVector2f(1.0f / Parameters.UVViewportSize.X, + 1.0f / Parameters.UVViewportSize.Y); Parameters.UVViewportBilinearMin = Parameters.UVViewportMin + 0.5f * Parameters.ExtentInverse; @@ -111,18 +125,13 @@ void FLidarIntensitySceneViewExtension::PrePostProcessPass_RenderThread( return; } - Inputs.Validate(); auto cachedParams = CSParamsQ.front(); CSParamsQ.pop(); - // The following is adapted from the ColorCorrectRegionsSceneViewExtension.cpp - // example from UE. Up until line 208, when the first pass is added. - checkSlow(View.bIsViewInfo); // can't do dynamic_cast because FViewInfo - // doesn't have any virtual functions. - const FIntRect Viewport = static_cast(View).ViewRect; + const FIntRect Viewport = View.UnscaledViewRect; - FScreenPassTexture SceneColor((*Inputs.SceneTextures)->SceneColorTexture, - Viewport); + // Access scene color from the new API + const FScreenPassTexture SceneColor((*Inputs.SceneTextures)->SceneColorTexture, Viewport); // not sure of the implications of it being invalid if (!SceneColor.IsValid()) { @@ -130,7 +139,7 @@ void FLidarIntensitySceneViewExtension::PrePostProcessPass_RenderThread( } // Getting material data for the current view. - FGlobalShaderMap* GlobalShaderMap = GetGlobalShaderMap(GMaxRHIFeatureLevel); + FGlobalShaderMap* GlobalShaderMap = GetGlobalShaderMap(View.GetFeatureLevel()); // Reusing the same output description for our back buffer as SceneColor FRDGTextureDesc LidarIntensityOutputDesc = SceneColor.Texture->Desc; @@ -153,10 +162,16 @@ void FLidarIntensitySceneViewExtension::PrePostProcessPass_RenderThread( const FScreenPassTextureViewportParameters SceneTextureViewportParams = GetTextureViewportParameters(SceneColorTextureViewport); +#if UE_IS_5_7 + FSceneTextureShaderParameters SceneTextures = + CreateSceneTextureShaderParameters( + GraphBuilder, View, ESceneTextureSetupMode::All); +#elif UE_IS_5_2 FSceneTextureShaderParameters SceneTextures = CreateSceneTextureShaderParameters( GraphBuilder, ((const FViewInfo&)View).GetSceneTexturesChecked(), View.GetFeatureLevel(), ESceneTextureSetupMode::All); +#endif const FScreenPassTextureViewport TextureViewport( SceneColorRenderTarget.Texture, Viewport); @@ -188,7 +203,8 @@ void FLidarIntensitySceneViewExtension::PrePostProcessPass_RenderThread( RDG_EVENT_NAME("LidarIntensityPass"), PostProcessMaterialParameters, ERDGPassFlags::Raster, [&View, TextureViewport, VertexShader, PixelShader, DefaultBlendState, - DepthStencilState, PostProcessMaterialParameters](FRHICommandListImmediate& RHICmdList) { + DepthStencilState, PostProcessMaterialParameters]( + FRHICommandListImmediate& RHICmdList) { DrawScreenPass( RHICmdList, View, TextureViewport, // Output Viewport @@ -196,37 +212,45 @@ void FLidarIntensitySceneViewExtension::PrePostProcessPass_RenderThread( FScreenPassPipelineState(VertexShader, PixelShader, DefaultBlendState, DepthStencilState), [&](FRHICommandListImmediate& RHICmdList) { - VertexShader->SetParameters(RHICmdList, View); - SetShaderParameters(RHICmdList, VertexShader, - VertexShader.GetVertexShader(), - *PostProcessMaterialParameters); - - PixelShader->SetParameters(RHICmdList, View); - SetShaderParameters(RHICmdList, PixelShader, - PixelShader.GetPixelShader(), - *PostProcessMaterialParameters); + #if UE_IS_5_7 + VertexShader->SetParameters(RHICmdList.GetScratchShaderParameters(), View); + SetShaderParameters(RHICmdList, VertexShader, + VertexShader.GetVertexShader(), + *PostProcessMaterialParameters); + + PixelShader->SetParameters(RHICmdList.GetScratchShaderParameters(), View); + SetShaderParameters(RHICmdList, PixelShader, + PixelShader.GetPixelShader(), + *PostProcessMaterialParameters); + #elif UE_IS_5_2 + VertexShader->SetParameters(RHICmdList, View); + SetShaderParameters(RHICmdList, VertexShader, + VertexShader.GetVertexShader(), + *PostProcessMaterialParameters); + + PixelShader->SetParameters(RHICmdList, View); + SetShaderParameters(RHICmdList, PixelShader, + PixelShader.GetPixelShader(), + *PostProcessMaterialParameters); + #endif }); }); // Now that we have computed the intensity texture, we can pass this to the // LidarPointCloud compute shader as input and add its pass. - TShaderMapRef LidarPointCloudShader( - GetGlobalShaderMap(GMaxRHIFeatureLevel)); + TShaderMapRef LidarPointCloudShader(GlobalShaderMap); - auto NumPoints = cachedParams.NumCams * cachedParams.HorizontalResolution * - cachedParams.LaserNums; - auto BufferSize = NumPoints * sizeof(float) * 4; + uint32 NumPoints = + cachedParams.NumCams * cachedParams.HorizontalResolution * cachedParams.LaserNums; + uint32 BufferSize = NumPoints * sizeof(float) * 4; - float* InitialData = new float[NumPoints * 4]; FRDGBufferRef PointCloudBufferRDG = - CreateStructuredBuffer(GraphBuilder, // Our FRDGBuilder - TEXT("FLidarPointCloudCS_PointCloudBuffer_" - "StructuredBuffer"), // The name of this - // buffer (for debug - // purposes) - sizeof(float), // The size of a single element - NumPoints * 4, InitialData, BufferSize); + CreateStructuredBuffer(GraphBuilder, + TEXT("FLidarPointCloudCS_PointCloudBuffer"), + sizeof(float), NumPoints * 4, nullptr, + BufferSize); + FRDGBufferUAVRef PointCloudBufferUAV = GraphBuilder.CreateUAV( PointCloudBufferRDG, PF_FloatRGBA, ERDGUnorderedAccessViewFlags::None); @@ -251,27 +275,14 @@ void FLidarIntensitySceneViewExtension::PrePostProcessPass_RenderThread( PassParameters->CamRotationMatrix4 = cachedParams.RotationMatCam4; PassParameters->DepthImage1 = cachedParams.DepthTexture1; - PassParameters->DepthImage2 = IntensityRenderTarget.Texture; + PassParameters->DepthImage2 = IntensityRenderTargetTexture; PassParameters->DepthImage3 = cachedParams.DepthTexture3; PassParameters->DepthImage4 = cachedParams.DepthTexture4; - FSceneViewProjectionData ProjData; - ProjData.ViewOrigin = - FVector(0.f); // camera space, should always be the origin - // Apply rotation matrix of camera's pose plus the rotation matrix for - // converting Unreal's world axes to the camera's view axes (z forward, etc). - ProjData.ViewRotationMatrix = FMatrix(FPlane(0, 0, 1, 0), FPlane(1, 0, 0, 0), - FPlane(0, 1, 0, 0), FPlane(0, 0, 0, 1)); - ProjData.ProjectionMatrix = cachedParams.ProjectionMat; - ProjData.SetConstrainedViewRectangle(FIntRect( - 0, 0, cachedParams.CamFrustrumWidth, cachedParams.CamFrustrumHeight)); - PassParameters->ProjectionMatrix = - FMatrix44f(ProjData.ComputeViewProjectionMatrix().GetTransposed()); - FIntVector GroupContext( - cachedParams.NumCams * cachedParams.HorizontalResolution * - cachedParams.LaserNums / 1024, - NUM_THREADS_PER_GROUP_DIMENSION_Y, NUM_THREADS_PER_GROUP_DIMENSION_Z); + FMath::DivideAndRoundUp(NumPoints, 1024u), + NUM_THREADS_PER_GROUP_DIMENSION_Y, + NUM_THREADS_PER_GROUP_DIMENSION_Z); LidarPointCloudData = std::vector(NumPoints, FVector4(-1, -1, -1, -1)); @@ -279,22 +290,6 @@ void FLidarIntensitySceneViewExtension::PrePostProcessPass_RenderThread( FComputeShaderUtils::AddPass( GraphBuilder, RDG_EVENT_NAME("LidarPointCloud Pass"), LidarPointCloudShader, PassParameters, GroupContext); - - FCopyBufferToCPUPass* CopyPassParameters = - GraphBuilder.AllocParameters(); - CopyPassParameters->Buffer = PointCloudBufferRDG; - - GraphBuilder.AddPass( - RDG_EVENT_NAME("FCopyBufferToCPUPass"), CopyPassParameters, - ERDGPassFlags::Readback, - [this, &InitialData, PointCloudBufferRDG, BufferSize](FRHICommandList& RHICmdList) { - InitialData = (float*)RHILockBuffer(PointCloudBufferRDG->GetRHI(), 0, - BufferSize, RLM_ReadOnly); - - FMemory::Memcpy(LidarPointCloudData.data(), InitialData, BufferSize); - - RHIUnlockBuffer(PointCloudBufferRDG->GetRHI()); - }); } void FLidarIntensitySceneViewExtension::UpdateParameters( @@ -305,4 +300,4 @@ void FLidarIntensitySceneViewExtension::UpdateParameters( bool FLidarIntensitySceneViewExtension::IsActiveThisFrame_Internal( const FSceneViewExtensionContext& Context) const { return !CSParamsQ.empty(); -} \ No newline at end of file +} diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/LidarIntensitySceneViewExtension.h b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/LidarIntensitySceneViewExtension.h index f90ddd1e..087c7f78 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/LidarIntensitySceneViewExtension.h +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/LidarIntensitySceneViewExtension.h @@ -6,6 +6,9 @@ #include "LidarPointCloudCS.h" +// Forward declarations +struct FPostProcessingInputs; + class FLidarIntensitySceneViewExtension : public FSceneViewExtensionBase { public: FLidarIntensitySceneViewExtension(const FAutoRegister& AutoRegister, @@ -17,12 +20,10 @@ class FLidarIntensitySceneViewExtension : public FSceneViewExtensionBase { FSceneView& InView) override {}; virtual void BeginRenderViewFamily(FSceneViewFamily& InViewFamily) override {}; virtual void PreRenderViewFamily_RenderThread( - FRHICommandListImmediate& RHICmdList, + FRDGBuilder& GraphBuilder, FSceneViewFamily& InViewFamily) override {}; - virtual void PreRenderView_RenderThread(FRHICommandListImmediate& RHICmdList, + virtual void PreRenderView_RenderThread(FRDGBuilder& GraphBuilder, FSceneView& InView) override {}; - virtual void PostRenderBasePass_RenderThread( - FRHICommandListImmediate& RHICmdList, FSceneView& InView) override {}; // Only implement this, called right before post processing begins. virtual void PrePostProcessPass_RenderThread( @@ -46,4 +47,4 @@ class FLidarIntensitySceneViewExtension : public FSceneViewExtensionBase { private: std::queue CSParamsQ; TWeakObjectPtr RenderTarget2D; -}; \ No newline at end of file +}; diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/LidarIntensityShader.h b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/LidarIntensityShader.h index 673ae5e8..5ab033bc 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/LidarIntensityShader.h +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/LidarIntensityShader.h @@ -1,19 +1,20 @@ #pragma once #include "CoreMinimal.h" +#include "UnrealCompatibility.h" #include "UnrealCameraRenderRequest.h" -#include "Runtime/Engine/Classes/Engine/TextureRenderTarget2D.h" +#include "Engine/TextureRenderTarget2D.h" #include "RHI.h" #include "RHIStaticStates.h" -#include "Runtime/RenderCore/Public/ShaderParameterUtils.h" -#include "Runtime/RenderCore/Public/RenderResource.h" -#include "Runtime/Renderer/Public/MaterialShader.h" -#include "Runtime/RenderCore/Public/RenderGraphResources.h" +#include "ShaderParameterUtils.h" +#include "RenderResource.h" +#include "MaterialShader.h" +#include "RenderGraphResources.h" // FScreenPassTextureViewportParameters and FScreenPassTextureInput -#include "Runtime/Renderer/Private/ScreenPass.h" -#include "Runtime/Renderer/Private/SceneTextureParameters.h" +#include "ScreenPass.h" +#include "SceneTextureParameters.h" BEGIN_SHADER_PARAMETER_STRUCT(FLidarIntensityShaderInputParameters, ) SHADER_PARAMETER_STRUCT_REF(FViewUniformShaderParameters, View) @@ -50,11 +51,18 @@ class FLidarIntensityPS : public FLidarIntensityShader { FLidarIntensityPS( const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FLidarIntensityShader(Initializer) {} - - void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View) { + #if UE_IS_5_7 + void SetParameters(FRHIBatchedShaderParameters& BatchedParameters, const FSceneView& View) { + FGlobalShader::SetParameters( + BatchedParameters, View.ViewUniformBuffer); + } + #elif UE_IS_5_2 + void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View) { FGlobalShader::SetParameters( RHICmdList, RHICmdList.GetBoundPixelShader(), View.ViewUniformBuffer); } + #endif + static void ModifyCompilationEnvironment( const FGlobalShaderPermutationParameters& Parameters, @@ -72,9 +80,15 @@ class FLidarIntensityVS : public FLidarIntensityShader { FLidarIntensityVS( const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FLidarIntensityShader(Initializer) {} - - void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View) { + #if UE_IS_5_7 + void SetParameters(FRHIBatchedShaderParameters& BatchedParameters, const FSceneView& View) { + FGlobalShader::SetParameters( + BatchedParameters, View.ViewUniformBuffer); + } + #elif UE_IS_5_2 + void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View) { FGlobalShader::SetParameters( RHICmdList, RHICmdList.GetBoundVertexShader(), View.ViewUniformBuffer); } + #endif }; \ No newline at end of file diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealCamera.cpp b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealCamera.cpp index eb161a6d..ff4cb5b4 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealCamera.cpp +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealCamera.cpp @@ -27,6 +27,7 @@ #include "UObject/ConstructorHelpers.h" #include "UnrealCameraRenderRequest.h" #include "UnrealHelpers.h" +#include "UnrealCompatibility.h" #include "UnrealLogger.h" #include "UnrealScene.h" #include "core_sim/clock.hpp" @@ -34,6 +35,7 @@ #include "core_sim/message/image_message.hpp" #include "core_sim/sensors/camera.hpp" #include "core_sim/transforms/transform_utils.hpp" +#include "UnrealTransforms.h" namespace projectairsim = microsoft::projectairsim; @@ -149,12 +151,21 @@ void UUnrealCamera::LoadCameraMaterials() { void HideDebugDrawComponent(USceneCaptureComponent2D* CaptureComponent, UWorld* UnrealWorld) { - CaptureComponent->HideComponent( - Cast(UnrealWorld->LineBatcher)); - CaptureComponent->HideComponent( - Cast(UnrealWorld->PersistentLineBatcher)); - CaptureComponent->HideComponent( - Cast(UnrealWorld->ForegroundLineBatcher)); + #if UE_IS_5_7 + CaptureComponent->HideComponent(Cast( + UnrealWorld->GetLineBatcher(UWorld::ELineBatcherType::World))); + CaptureComponent->HideComponent(Cast( + UnrealWorld->GetLineBatcher(UWorld::ELineBatcherType::WorldPersistent))); + CaptureComponent->HideComponent(Cast( + UnrealWorld->GetLineBatcher(UWorld::ELineBatcherType::Foreground))); + #elif UE_IS_5_2 + CaptureComponent->HideComponent( + Cast(UnrealWorld->LineBatcher)); + CaptureComponent->HideComponent( + Cast(UnrealWorld->PersistentLineBatcher)); + CaptureComponent->HideComponent( + Cast(UnrealWorld->ForegroundLineBatcher)); + #endif } void UUnrealCamera::CreateComponents() { @@ -918,7 +929,7 @@ void UUnrealCamera::OnRendered( FTextureRenderTargetResource* RtResource = CaptureComponent->TextureTarget->GetRenderTargetResource(); if (RtResource) { - FRHITexture2D* Texture = RtResource->GetRenderTargetTexture(); + FRHITexture* Texture = RtResource->GetRenderTargetTexture(); // Copy pixel values out of Unreal's RHI UnrealCameraRenderRequest::RenderResult ImageResult; auto bIsDepthImage = diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealCameraRenderRequest.cpp b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealCameraRenderRequest.cpp index 5894073a..82eb12ff 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealCameraRenderRequest.cpp +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealCameraRenderRequest.cpp @@ -21,7 +21,7 @@ void OnEndPlay() { ImageWrapperModule = nullptr; } -void ReadPixels(FRHITexture2D* Texture, bool bPixelsAsFloat, +void ReadPixels(FRHITexture* Texture, bool bPixelsAsFloat, RenderResult* ImageResult) { FRHICommandListImmediate& RHICmdList = GetImmediateCommandList_ForRenderCommand(); diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealCameraRenderRequest.h b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealCameraRenderRequest.h index be488f1b..f8640f46 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealCameraRenderRequest.h +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealCameraRenderRequest.h @@ -7,6 +7,7 @@ #pragma once #include "CoreMinimal.h" +#include "core_sim/clock.hpp" namespace UnrealCameraRenderRequest { @@ -26,7 +27,7 @@ void OnEndPlay(); void OnBeginPlay(); -void ReadPixels(FRHITexture2D* Texture, bool bPixelsAsFloat, +void ReadPixels(FRHITexture* Texture, bool bPixelsAsFloat, RenderResult* ImageResult); bool CompressUsingImageWrapper(const TArray& UnCompressed, diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealDistanceSensor.cpp b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealDistanceSensor.cpp index 02458842..e91111bd 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealDistanceSensor.cpp +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealDistanceSensor.cpp @@ -15,6 +15,7 @@ #include "Runtime/Core/Public/Async/ParallelFor.h" #include "Runtime/Engine/Classes/Kismet/KismetMathLibrary.h" #include "UnrealLogger.h" +#include "UnrealTransforms.h" namespace projectairsim = microsoft::projectairsim; diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealLidar.cpp b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealLidar.cpp index 14b37186..c1c2c31b 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealLidar.cpp +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealLidar.cpp @@ -15,6 +15,8 @@ #include "Runtime/Core/Public/Async/ParallelFor.h" #include "Runtime/Engine/Classes/Kismet/KismetMathLibrary.h" #include "UnrealLogger.h" +#include "UnrealTransforms.h" +#include "core_sim/clock.hpp" namespace projectairsim = microsoft::projectairsim; diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealLidar.h b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealLidar.h index 1ffbcde6..a4a13c51 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealLidar.h +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealLidar.h @@ -15,6 +15,7 @@ #include "core_sim/clock.hpp" #include "core_sim/sensors/lidar.hpp" #include "core_sim/transforms/transform_utils.hpp" +#include // comment so that generated.h is always the last include file with clang-format #include "UnrealLidar.generated.h" diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealRadar.cpp b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealRadar.cpp index 34936805..e5a7fcbc 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealRadar.cpp +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/Sensors/UnrealRadar.cpp @@ -486,8 +486,8 @@ inline projectairsim::Kinematics UUnrealRadar::GetKinematicsFromActor( // cast to get their kinematics. projectairsim::Kinematics Kin; // constructs with zero values - const AUnrealRobot* RobotActor = Cast(Actor); - const AUnrealEnvActor* EnvActor = Cast(Actor); + const AUnrealRobot* RobotActor = Cast(Actor); + const AUnrealEnvActor* EnvActor = Cast(Actor); if (RobotActor) { Kin = RobotActor->GetKinematics(); diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealCompatibility.h b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealCompatibility.h new file mode 100644 index 00000000..c0fc1985 --- /dev/null +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealCompatibility.h @@ -0,0 +1,11 @@ +#pragma once + +#include "CoreMinimal.h" +#include "Runtime/Launch/Resources/Version.h" + +// Exact supported versions +#define UE_IS_5_2 (ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION == 2) +#define UE_IS_5_7 (ENGINE_MAJOR_VERSION == 5 && ENGINE_MINOR_VERSION == 7) + +// Convenience macro +#define UE_IS_SUPPORTED (UE_IS_5_2 || UE_IS_5_7) diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealHelpers.h b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealHelpers.h index b7f31b54..07a0890e 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealHelpers.h +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealHelpers.h @@ -31,6 +31,7 @@ #include "Runtime/Engine/Classes/Engine/StaticMesh.h" #include "UnrealLogger.h" #include "core_sim/transforms/transform_utils.hpp" +#include "ProceduralMeshComponent.h" // comment so that generated.h is always the last include file with clang-format #include "UnrealHelpers.generated.h" diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealLogger.h b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealLogger.h index 16edc9f7..ca7fbde9 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealLogger.h +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealLogger.h @@ -8,15 +8,22 @@ #include #include "CoreMinimal.h" +#include "UnrealCompatibility.h" #include "core_sim/log_level.hpp" DECLARE_LOG_CATEGORY_EXTERN(SimPlugin, All, All); class UnrealLogger { public: + #if UE_IS_5_7 + template + static void Log(microsoft::projectairsim::LogLevel level, + UE::Core::TCheckedFormatString format, ArgTypes... args); + #elif UE_IS_5_2 template static void Log(microsoft::projectairsim::LogLevel level, const TCHAR (&format)[N], ArgTypes... args); + #endif static void LogSim(const std::string& module, microsoft::projectairsim::LogLevel level, @@ -26,9 +33,48 @@ class UnrealLogger { static std::string GetTimeStamp(); }; +#if UE_IS_5_7 +template +inline void UnrealLogger::Log(microsoft::projectairsim::LogLevel level, + UE::Core::TCheckedFormatString format, ArgTypes... args){ + FString LogMessage = FString::Printf(format, args...); + + // Output to Unreal's native log file/console + switch (level) { + case microsoft::projectairsim::LogLevel::kFatal: + UE_LOG(SimPlugin, Fatal, TEXT("%s"), *LogMessage); + break; + + case microsoft::projectairsim::LogLevel::kError: + UE_LOG(SimPlugin, Error, TEXT("%s"), *LogMessage); + break; + + case microsoft::projectairsim::LogLevel::kWarning: + UE_LOG(SimPlugin, Warning, TEXT("%s"), *LogMessage); + break; + + case microsoft::projectairsim::LogLevel::kTrace: + UE_LOG(SimPlugin, Log, TEXT("%s"), *LogMessage); + break; + + case microsoft::projectairsim::LogLevel::kVerbose: + UE_LOG(SimPlugin, Verbose, TEXT("%s"), *LogMessage); + break; + + default: + UE_LOG(SimPlugin, VeryVerbose, TEXT("%s"), *LogMessage); + break; + } + + // Output to an independent log file + auto time_stamp = GetTimeStamp(); + std::clog << "[" << time_stamp << "] " << TCHAR_TO_UTF8(*LogMessage) + << std::endl; +} +#elif UE_IS_5_2 template inline void UnrealLogger::Log(microsoft::projectairsim::LogLevel level, - const TCHAR (&format)[N], ArgTypes... args) { + const TCHAR (&format)[N], ArgTypes... args){ FString LogMessage = FString::Printf(format, args...); // Output to Unreal's native log file/console @@ -63,6 +109,7 @@ inline void UnrealLogger::Log(microsoft::projectairsim::LogLevel level, std::clog << "[" << time_stamp << "] " << TCHAR_TO_UTF8(*LogMessage) << std::endl; } +#endif inline void UnrealLogger::LogSim(const std::string& module, microsoft::projectairsim::LogLevel level, diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealScene.cpp b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealScene.cpp index d97c7e34..1b40b6c4 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealScene.cpp +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealScene.cpp @@ -22,6 +22,7 @@ #include "UnrealLogger.h" #include "World/WeatherLib.h" #include "core_sim/clock.hpp" +#include "Sensors/UnrealCamera.h" namespace projectairsim = microsoft::projectairsim; @@ -609,7 +610,6 @@ bool AUnrealScene::GetSimBoundingBox3D( nlohmann::json AUnrealScene::Get3DBoundingBoxServiceMethod( const std::string& object_name, int box_alignment) { - FRotator BoxRotation; FOrientedBox OrientedBox; projectairsim::BBox3D OutBBox; auto BoxAlignment = diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealScene.h b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealScene.h index 5ff20963..50ac6dec 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealScene.h +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealScene.h @@ -117,7 +117,7 @@ class AUnrealScene : public AActor { TimeNano unreal_time; bool using_unreal_physics; - std::unique_ptr world_api; + std::unique_ptr world_api; std::shared_ptr time_of_day; std::vector objects_; diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealSimLoader.cpp b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealSimLoader.cpp index 01a37108..cee73cf6 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealSimLoader.cpp +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/UnrealSimLoader.cpp @@ -17,6 +17,7 @@ #include "UnrealLogger.h" #include "UnrealScene.h" #include "simserver.hpp" +#include "Constant.h" #ifdef ENABLE_CESIUM #include "Cesium3DTileset.h" @@ -27,9 +28,14 @@ namespace projectairsim = microsoft::projectairsim; DEFINE_LOG_CATEGORY(SimPlugin); -AUnrealSimLoader::AUnrealSimLoader(const FString& SimLogDir) - : SimServer(std::make_shared( - UnrealLogger::LogSim, projectairsim::LogLevel::kVerbose)) { +AUnrealSimLoader::AUnrealSimLoader(const FString& SimLogDir) { + + auto PluginDir = IPluginManager::Get().FindPlugin(Constant::SimPluginName)->GetBaseDir(); + + SimServer = std::make_shared( + UnrealLogger::LogSim, projectairsim::LogLevel::kVerbose, + TCHAR_TO_UTF8(*PluginDir)); + // Open log file output stream to start capturing clog FString SimLogPath = FPaths::Combine(SimLogDir, TEXT("projectairsim_server.log")); diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/World/WorldSimApi.cpp b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/World/WorldSimApi.cpp index 84e85f0b..07065d82 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/World/WorldSimApi.cpp +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/Private/World/WorldSimApi.cpp @@ -15,6 +15,8 @@ #include "assimp/postprocess.h" #include "assimp/scene.h" #include "core_sim/actor/env_actor.hpp" +#include "assimp/Importer.hpp" +#include "core_sim/geodetic_converter.hpp" namespace projectairsim = microsoft::projectairsim; @@ -1246,7 +1248,7 @@ std::vector WorldSimApi::swapTextures(const std::string& tag, } if (invalidChoice) continue; - dynamic_cast(shuffler)->SwapTexture( + Cast(shuffler)->SwapTexture( tex_id, component_id, material_id); swappedObjectNames.push_back(TCHAR_TO_UTF8(*shuffler->GetName())); } diff --git a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/ProjectAirSim.Build.cs b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/ProjectAirSim.Build.cs index 5805354a..ce674906 100644 --- a/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/ProjectAirSim.Build.cs +++ b/unreal/Blocks/Plugins/ProjectAirSim/Source/ProjectAirSim/ProjectAirSim.Build.cs @@ -11,9 +11,10 @@ public class ProjectAirSim : ModuleRules { public ProjectAirSim(ReadOnlyTargetRules Target) : base(Target) { - CppStandard = CppStandardVersion.Cpp17; + bEnableUndefinedIdentifierWarnings = false; + bool bUseCpp20 = Target.Version.MajorVersion > 5 || (Target.Version.MajorVersion == 5 && Target.Version.MinorVersion >= 7); + CppStandard = bUseCpp20 ? CppStandardVersion.Cpp20 : CppStandardVersion.Cpp17; PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; - PrivatePCHHeaderFile = "Public/ProjectAirSim.h"; // Allow Unreal's default setting for IWYU instead of setting explicitly // bEnforceIWYU = true; // UE <= 5.1 @@ -21,6 +22,11 @@ public ProjectAirSim(ReadOnlyTargetRules Target) : base(Target) bEnableExceptions = true; + // RTTI is disabled because Unreal Engine is compiled without RTTI. + // JSBSim headers that use typeid (props.hxx) are not included in headers + // exposed to Unreal code - they are only in .cpp files compiled into libcore_sim.a + bUseRTTI = false; + // Silence MSVC 14.25.28610 deprecation warning from Eigen PublicDefinitions.Add("_SILENCE_CXX17_RESULT_OF_DEPRECATION_WARNING"); @@ -44,10 +50,12 @@ public ProjectAirSim(ReadOnlyTargetRules Target) : base(Target) // TODO: Can we do something to add includes and libraries for features // in a less manual fashion? + // JSBSim headers need to be treated as system includes (like the official JSBSim UE plugin does) + PublicSystemIncludePaths.Add(PluginDirectory + "/SimLibs/core_sim/jsbsim/include"); + if (Target.Platform == UnrealTargetPlatform.Win64) { List liststrIncludes = new List { - ModuleDirectory + "/Private", PluginDirectory + "/SimLibs/core_sim/include", PluginDirectory + "/SimLibs/simserver/include", PluginDirectory + "/SimLibs/physics/include", @@ -65,6 +73,7 @@ public ProjectAirSim(ReadOnlyTargetRules Target) : base(Target) if (buildType == "Debug") liststrIncludes.Add(PluginDirectory + "/SimLibs/lvmon/include"); + liststrIncludes.Add(Path.Combine(GetModuleDirectory("Renderer"), "Internal")); PrivateIncludePaths.AddRange(liststrIncludes); } @@ -90,6 +99,10 @@ public ProjectAirSim(ReadOnlyTargetRules Target) : base(Target) if (buildType == "Debug") liststrIncludes.Add(PluginDirectory + "/SimLibs/lvmon/include"); + // Add Renderer internal headers for PostProcess access + string EngineDir = Path.GetFullPath(Target.RelativeEnginePath); + liststrIncludes.Add(Path.Combine(EngineDir, "Source/Runtime/Renderer/Internal")); + PrivateIncludePaths.AddRange(liststrIncludes); } @@ -143,6 +156,7 @@ public ProjectAirSim(ReadOnlyTargetRules Target) : base(Target) PluginDirectory + "/SimLibs/core_sim/" + buildType + "/core_sim.lib", PluginDirectory + "/SimLibs/simserver/" + buildType + "/simserver.lib", PluginDirectory + "/SimLibs/physics/" + buildType + "/physics.lib", + PluginDirectory + "/SimLibs/core_sim/jsbsim/lib/" + buildType + "/jsbsim.lib", PluginDirectory + "/SimLibs/multirotor_api/" + buildType + "/multirotor_api.lib", PluginDirectory + "/SimLibs/rover_api/" + buildType + "/rover_api.lib", PluginDirectory + "/SimLibs/rendering_scene/" + buildType + "/rendering_scene.lib", @@ -174,6 +188,9 @@ public ProjectAirSim(ReadOnlyTargetRules Target) : base(Target) var fileName = Path.GetFileName(file); RuntimeDependencies.Add("$(BinaryOutputDir)/" + fileName, PluginDirectory + "/SimLibs/shared_libs/" + fileName); } + + // JSBSim dll + RuntimeDependencies.Add("$(BinaryOutputDir)/" + "JSBSim.dll", PluginDirectory + "/SimLibs/core_sim/jsbsim/lib/" + buildType + "/" + "JSBSim.dll"); } else { @@ -181,6 +198,7 @@ public ProjectAirSim(ReadOnlyTargetRules Target) : base(Target) PluginDirectory + "/SimLibs/core_sim/" + buildType + "/libcore_sim.a", PluginDirectory + "/SimLibs/simserver/" + buildType + "/libsimserver.a", PluginDirectory + "/SimLibs/physics/" + buildType + "/libphysics.a", + PluginDirectory + "/SimLibs/core_sim/jsbsim/lib/" + buildType + "/libJSBSim.so", PluginDirectory + "/SimLibs/multirotor_api/" + buildType + "/libmultirotor_api.a", PluginDirectory + "/SimLibs/rover_api/" + buildType + "/librover_api.a", PluginDirectory + "/SimLibs/rendering_scene/" + buildType + "/librendering_scene.a", @@ -201,6 +219,9 @@ public ProjectAirSim(ReadOnlyTargetRules Target) : base(Target) RuntimeDependencies.Add("$(BinaryOutputDir)/" + fileName, PluginDirectory + "/SimLibs/shared_libs/" + fileName); } + // JSBSim so + RuntimeDependencies.Add("$(BinaryOutputDir)/" + "libJSBSim.so", PluginDirectory + "/SimLibs/core_sim/jsbsim/lib/" + buildType + "/" + "libJSBSim.so"); + PublicAdditionalLibraries.AddRange(liststrLibraries); PublicSystemLibraries.AddRange( new string[] { @@ -210,6 +231,7 @@ public ProjectAirSim(ReadOnlyTargetRules Target) : base(Target) "anl" } ); + } } } diff --git a/unreal/Blocks/Plugins/ProjectAirSim/clean_plugin.bat b/unreal/Blocks/Plugins/ProjectAirSim/clean_plugin.bat new file mode 100644 index 00000000..09e955e9 --- /dev/null +++ b/unreal/Blocks/Plugins/ProjectAirSim/clean_plugin.bat @@ -0,0 +1,43 @@ +@echo off +set "SCRIPT_DIR=%~dp0" + +echo === Cleaning ProjectAirSim Plugin === +echo Plugin directory: %SCRIPT_DIR% + +REM Remove plugin Binaries (compiled .dll files) +if exist "%SCRIPT_DIR%Binaries" ( + echo Removing: "%SCRIPT_DIR%Binaries" + rd /s /q "%SCRIPT_DIR%Binaries" +) + +REM Remove plugin Intermediate (build intermediates) +if exist "%SCRIPT_DIR%Intermediate" ( + echo Removing: "%SCRIPT_DIR%Intermediate" + rd /s /q "%SCRIPT_DIR%Intermediate" +) + +REM Also clean the main Blocks project build artifacts (optional) +set "BLOCKS_DIR=%SCRIPT_DIR%..\..\" + +if exist "%BLOCKS_DIR%Binaries" ( + echo Removing: "%BLOCKS_DIR%Binaries" + rd /s /q "%BLOCKS_DIR%Binaries" +) + +if exist "%BLOCKS_DIR%Intermediate" ( + echo Removing: "%BLOCKS_DIR%Intermediate" + rd /s /q "%BLOCKS_DIR%Intermediate" +) + +if exist "%BLOCKS_DIR%DerivedDataCache" ( + echo Removing: "%BLOCKS_DIR%DerivedDataCache" + rd /s /q "%BLOCKS_DIR%DerivedDataCache" +) + +echo === Clean complete === +echo. +echo Preserved directories: +echo - Source/ (source code) +echo - SimLibs/ (prebuilt libraries) +echo - Content/ (assets) +echo - Resources/ (plugin resources) diff --git a/unreal/Blocks/Plugins/ProjectAirSim/clean_plugin.sh b/unreal/Blocks/Plugins/ProjectAirSim/clean_plugin.sh new file mode 100755 index 00000000..548a2296 --- /dev/null +++ b/unreal/Blocks/Plugins/ProjectAirSim/clean_plugin.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# Clean script for ProjectAirSim Unreal plugin +# Removes only compilation and intermediate files, preserving source code and SimLibs + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +echo "=== Cleaning ProjectAirSim Plugin ===" +echo "Plugin directory: $SCRIPT_DIR" + +# Remove plugin Binaries (compiled .so/.dll files) +if [ -d "$SCRIPT_DIR/Binaries" ]; then + echo "Removing: $SCRIPT_DIR/Binaries" + rm -rf "$SCRIPT_DIR/Binaries" +fi + +# Remove plugin Intermediate (build intermediates) +if [ -d "$SCRIPT_DIR/Intermediate" ]; then + echo "Removing: $SCRIPT_DIR/Intermediate" + rm -rf "$SCRIPT_DIR/Intermediate" +fi + +# Also clean the main Blocks project build artifacts (optional, comment out if not needed) +BLOCKS_DIR="$SCRIPT_DIR/../.." + +if [ -d "$BLOCKS_DIR/Binaries" ]; then + echo "Removing: $BLOCKS_DIR/Binaries" + rm -rf "$BLOCKS_DIR/Binaries" +fi + +if [ -d "$BLOCKS_DIR/Intermediate" ]; then + echo "Removing: $BLOCKS_DIR/Intermediate" + rm -rf "$BLOCKS_DIR/Intermediate" +fi + +if [ -d "$BLOCKS_DIR/DerivedDataCache" ]; then + echo "Removing: $BLOCKS_DIR/DerivedDataCache" + rm -rf "$BLOCKS_DIR/DerivedDataCache" +fi + +# Remove any .so files that might have been copied to unexpected locations +find "$SCRIPT_DIR" -name "*.so" -path "*/Binaries/*" -delete 2>/dev/null + +echo "=== Clean complete ===" +echo "" +echo "Preserved directories:" +echo " - Source/ (source code)" +echo " - SimLibs/ (prebuilt libraries)" +echo " - Content/ (assets)" +echo " - Resources/ (plugin resources)" diff --git a/unreal/Blocks/Source/Blocks.Target.cs b/unreal/Blocks/Source/Blocks.Target.cs index 6602933b..b6957b02 100644 --- a/unreal/Blocks/Source/Blocks.Target.cs +++ b/unreal/Blocks/Source/Blocks.Target.cs @@ -11,7 +11,7 @@ public class BlocksTarget : TargetRules public BlocksTarget(TargetInfo Target) : base(Target) { Type = TargetType.Game; - DefaultBuildSettings = BuildSettingsVersion.V2; + DefaultBuildSettings = BuildSettingsVersion.Latest; IncludeOrderVersion = EngineIncludeOrderVersion.Latest; // from UE5.1 ExtraModuleNames.AddRange(new string[] { "Blocks" }); diff --git a/unreal/Blocks/Source/Blocks/Blocks.Build.cs b/unreal/Blocks/Source/Blocks/Blocks.Build.cs index 3d8fe81e..21f3c338 100644 --- a/unreal/Blocks/Source/Blocks/Blocks.Build.cs +++ b/unreal/Blocks/Source/Blocks/Blocks.Build.cs @@ -9,6 +9,8 @@ public class Blocks : ModuleRules { public Blocks(ReadOnlyTargetRules Target) : base(Target) { + bEnableUndefinedIdentifierWarnings = false; + PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; bEnableExceptions = true; diff --git a/unreal/Blocks/Source/BlocksEditor.Target.cs b/unreal/Blocks/Source/BlocksEditor.Target.cs index a6077732..7d51f267 100644 --- a/unreal/Blocks/Source/BlocksEditor.Target.cs +++ b/unreal/Blocks/Source/BlocksEditor.Target.cs @@ -11,7 +11,7 @@ public class BlocksEditorTarget : TargetRules public BlocksEditorTarget(TargetInfo Target) : base(Target) { Type = TargetType.Editor; - DefaultBuildSettings = BuildSettingsVersion.V2; + DefaultBuildSettings = BuildSettingsVersion.Latest; IncludeOrderVersion = EngineIncludeOrderVersion.Latest; // from UE5.1 ExtraModuleNames.AddRange(new string[] { "Blocks" }); diff --git a/unreal/Blocks/blocks_genprojfiles_vscode.sh b/unreal/Blocks/blocks_genprojfiles_vscode.sh old mode 100644 new mode 100755 diff --git a/unreal/Blocks/clean_blocks.bat b/unreal/Blocks/clean_blocks.bat new file mode 100644 index 00000000..4db15778 --- /dev/null +++ b/unreal/Blocks/clean_blocks.bat @@ -0,0 +1,70 @@ +@echo off +set "SCRIPT_DIR=%~dp0" + +echo === Cleaning Blocks Project === +echo Project directory: %SCRIPT_DIR% + +REM Clean ProjectAirSim plugin first +set "PROJECTAIRSIM_CLEAN=%SCRIPT_DIR%Plugins\ProjectAirSim\clean_plugin.bat" +if exist "%PROJECTAIRSIM_CLEAN%" ( + echo. + echo --- Calling ProjectAirSim plugin clean --- + call "%PROJECTAIRSIM_CLEAN%" +) else ( + echo. + echo Warning: ProjectAirSim clean script not found or not a .bat file +) + +REM Clean other plugins (Drone, Rover) +for %%D in (Drone Rover) do ( + if exist "%SCRIPT_DIR%Plugins\%%D" ( + echo. + echo --- Cleaning plugin: %%D --- + + if exist "%SCRIPT_DIR%Plugins\%%D\Binaries" ( + echo Removing: "%SCRIPT_DIR%Plugins\%%D\Binaries" + rd /s /q "%SCRIPT_DIR%Plugins\%%D\Binaries" + ) + + if exist "%SCRIPT_DIR%Plugins\%%D\Intermediate" ( + echo Removing: "%SCRIPT_DIR%Plugins\%%D\Intermediate" + rd /s /q "%SCRIPT_DIR%Plugins\%%D\Intermediate" + ) + ) +) + +REM Clean main Blocks project +echo. +echo --- Cleaning Blocks project --- + +if exist "%SCRIPT_DIR%Binaries" ( + echo Removing: "%SCRIPT_DIR%Binaries" + rd /s /q "%SCRIPT_DIR%Binaries" +) + +if exist "%SCRIPT_DIR%Intermediate" ( + echo Removing: "%SCRIPT_DIR%Intermediate" + rd /s /q "%SCRIPT_DIR%Intermediate" +) + +if exist "%SCRIPT_DIR%DerivedDataCache" ( + echo Removing: "%SCRIPT_DIR%DerivedDataCache" + rd /s /q "%SCRIPT_DIR%DerivedDataCache" +) + +REM Remove Saved folder (logs, autosaves, etc.) - optional +REM if exist "%SCRIPT_DIR%Saved" ( +REM echo Removing: "%SCRIPT_DIR%Saved" +REM rd /s /q "%SCRIPT_DIR%Saved" +REM ) + +REM Remove generated project files (optional) +REM del /F /Q "%SCRIPT_DIR%*.sln" 2>nul +REM rd /s /q "%SCRIPT_DIR%.vs" 2>nul + +echo. +echo === Blocks Clean Complete === +echo. +echo To rebuild, run: +echo blocks_genprojfiles_vscode.bat (regenerate project files) +echo Then build from VS Code or command line diff --git a/unreal/Blocks/clean_blocks.sh b/unreal/Blocks/clean_blocks.sh new file mode 100755 index 00000000..c99c210c --- /dev/null +++ b/unreal/Blocks/clean_blocks.sh @@ -0,0 +1,74 @@ +#!/bin/bash +# Clean script for Blocks Unreal project +# Removes compilation and intermediate files for the project and all plugins + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +echo "=== Cleaning Blocks Project ===" +echo "Project directory: $SCRIPT_DIR" + +# Clean ProjectAirSim plugin first +PROJECTAIRSIM_CLEAN="$SCRIPT_DIR/Plugins/ProjectAirSim/clean_plugin.sh" +if [ -x "$PROJECTAIRSIM_CLEAN" ]; then + echo "" + echo "--- Calling ProjectAirSim plugin clean ---" + "$PROJECTAIRSIM_CLEAN" +else + echo "Warning: ProjectAirSim clean script not found or not executable" +fi + +# Clean other plugins (Drone, Rover) +for plugin_dir in "$SCRIPT_DIR/Plugins/Drone" "$SCRIPT_DIR/Plugins/Rover"; do + if [ -d "$plugin_dir" ]; then + echo "" + echo "--- Cleaning plugin: $(basename $plugin_dir) ---" + + if [ -d "$plugin_dir/Binaries" ]; then + echo "Removing: $plugin_dir/Binaries" + rm -rf "$plugin_dir/Binaries" + fi + + if [ -d "$plugin_dir/Intermediate" ]; then + echo "Removing: $plugin_dir/Intermediate" + rm -rf "$plugin_dir/Intermediate" + fi + fi +done + +# Clean main Blocks project +echo "" +echo "--- Cleaning Blocks project ---" + +if [ -d "$SCRIPT_DIR/Binaries" ]; then + echo "Removing: $SCRIPT_DIR/Binaries" + rm -rf "$SCRIPT_DIR/Binaries" +fi + +if [ -d "$SCRIPT_DIR/Intermediate" ]; then + echo "Removing: $SCRIPT_DIR/Intermediate" + rm -rf "$SCRIPT_DIR/Intermediate" +fi + +if [ -d "$SCRIPT_DIR/DerivedDataCache" ]; then + echo "Removing: $SCRIPT_DIR/DerivedDataCache" + rm -rf "$SCRIPT_DIR/DerivedDataCache" +fi + +# Remove Saved folder (logs, autosaves, etc.) - optional +# Uncomment if you want to clean this too +# if [ -d "$SCRIPT_DIR/Saved" ]; then +# echo "Removing: $SCRIPT_DIR/Saved" +# rm -rf "$SCRIPT_DIR/Saved" +# fi + +# Remove generated project files (optional) +# Uncomment if you want to regenerate project files +# rm -f "$SCRIPT_DIR"/*.sln 2>/dev/null +# rm -rf "$SCRIPT_DIR"/.vs 2>/dev/null + +echo "" +echo "=== Blocks Clean Complete ===" +echo "" +echo "To rebuild, run:" +echo " ./blocks_genprojfiles_vscode.sh (regenerate project files)" +echo " Then build from VS Code or command line" diff --git a/vehicle_apis/multirotor_api/include/ilanding_gear_api.hpp b/vehicle_apis/multirotor_api/include/ilanding_gear_api.hpp new file mode 100644 index 00000000..930c2938 --- /dev/null +++ b/vehicle_apis/multirotor_api/include/ilanding_gear_api.hpp @@ -0,0 +1,23 @@ +// Copyright (C) Microsoft Corporation. All rights reserved. + +#ifndef MULTIROTOR_API_INCLUDE_ILANDING_GEAR_API_HPP_ //TO-DO: This is not only for multirotor. We need to do some refactoring here. +#define MULTIROTOR_API_INCLUDE_ILANDING_GEAR_API_HPP_ + + +namespace microsoft { +namespace projectairsim { + +// Represents public landing gear APIs intended for client +class ILandingGearApi { + public: + // return value of these functions is true if command was completed without + // interruption or timeouts + + virtual bool SetBrakes(float value) = 0; //value beteween 0 and 1 for all wheels + +}; + +} // namespace projectairsim +} // namespace microsoft + +#endif // MULTIROTOR_API_INCLUDE_ILANDING_GEAR_API_HPP_ \ No newline at end of file diff --git a/vehicle_apis/multirotor_api/include/jsbsim_api.hpp b/vehicle_apis/multirotor_api/include/jsbsim_api.hpp new file mode 100644 index 00000000..baf40af2 --- /dev/null +++ b/vehicle_apis/multirotor_api/include/jsbsim_api.hpp @@ -0,0 +1,198 @@ +// Copyright (C) Microsoft Corporation. All rights reserved. + +#ifndef MULTIROTOR_API_INCLUDE_JSBSIM_API_HPP_ +#define MULTIROTOR_API_INCLUDE_JSBSIM_API_HPP_ + +#include +#include +#include + +#include "core_sim/actor/robot.hpp" +#include "core_sim/runtime_components.hpp" +#include "core_sim/service_method.hpp" +#include "core_sim/transforms/transform_tree.hpp" +#include "simple_flight/AirSimSimpleFlightBoard.hpp" +#include "simple_flight/AirSimSimpleFlightCommLink.hpp" +#include "simple_flight/AirSimSimpleFlightEstimator.hpp" +#include "simple_flight/AirSimSimpleFlightEstimatorFW.hpp" +#include "simple_flight/firmware/Firmware.hpp" +#include "landing_gear_api_base.hpp" + + +namespace microsoft { +namespace projectairsim { + +// todo "firmware" / "firmware wrapper api" or "api" type (wrt px4 / mavlink) +//enum class MultirotorApiType { kJSBSim = 0 }; + +// JSBSimApi +// TODO: Should we use pimpl or some other pattern to hide the implementation? +class JSBSimApi : public LandingGearApiBase { + public: + JSBSimApi() {} + JSBSimApi(const Robot& robot, TransformTree* ptransformtree); + + virtual ~JSBSimApi() {} + + //--------------------------------------------------------------------------- + // IController overrides + + void BeginUpdate() override; + void EndUpdate() override; + void Reset() override; + void SetKinematics(const Kinematics* kinematics) override; + void Update() override; + std::vector GetControlSignals(const std::string& actuator_id) override; + + //--------------------------------------------------------------------------- + // IMultirotorApi overrides + + bool EnableApiControl() override; + bool DisableApiControl() override; + bool IsApiControlEnabled() override; + bool Arm(int64_t command_start_time_nanos) override; + bool Disarm() override; + bool CanArm() const override; + float GetTakeoffZ() + const override; // the height above ground for the drone after successful + // takeoff (Z above ground is negative due to NED + // coordinate system). + // noise in difference of two position coordinates. This is not GPS or + // position accuracy which can be very low such as 1m. the difference between + // two position cancels out transitional errors. Typically this would be 0.1m + // or lower. + + bool Takeoff( + float timeout_sec, TimeNano _service_method_start_time) override; + bool Land(float timeout_sec, int64_t command_start_time_nanos) override; + //SetBrakes + bool SetBrakes(float value) override; + bool MoveToZ(float z, float velocity, float timeout_sec, bool yaw_is_rate, + float yaw, float lookahead, float adaptive_lookahead, + int64_t command_start_time_nanos) override; + bool MoveToPosition(float x, float y, float z, float velocity, + float timeout_sec, DrivetrainType drivetrain, + bool yaw_is_rate, float yaw, float lookahead, + float adaptive_lookahead, + int64_t command_start_time_nanos) override; + bool MoveByHeading(float heading, float speed, + float vz, float duration, + float heading_margin, float yaw_rate, + float timeout_sec, + int64_t command_start_time_nanos) override; + float GetJSBSimProperty(const std::string& property); + bool SetJSBSimProperty(const std::string& property, float value); + + // Switched to using service method request-response for all control commands, + // but leaving the below pub-sub version commented out for reference in case + // it's needed in the future. + // void OnSetpointNEDvelocityYawrate(const Topic& topic, + // const Message& message) + // override; + + //--------------------------------------------------------------------------- + // IVTOLFWApi overrides + + protected: + //--------------------------------------------------------------------------- + // MultirotorApiBase overrides + std::string GetControllerName() const override { return "JSBSimApi"; } + + //--------------------------------------------------------------------------- + // Low level commands + + void CommandMotorPWMs(float front_right_pwm, float rear_left_pwm, + float front_left_pwm, float rear_right_pwm) override; + void CommandRollPitchYawrateThrottle(float roll, float pitch, float yaw_rate, + float throttle) override; + void CommandRollPitchYawZ(float roll, float pitch, float yaw, + float z) override; + void CommandRollPitchYawThrottle(float roll, float pitch, float yaw, + float throttle) override; + void CommandRollPitchYawrateZ(float roll, float pitch, float yaw_rate, + float z) override; + void CommandAngleRatesZ(float roll_rate, float pitch_rate, float yaw_rate, + float z) override; + void CommandAngleRatesThrottle(float roll_rate, float pitch_rate, + float yaw_rate, float throttle) override; + void CommandHeading(float heading, float speed, float vz) override; + void CommandVelocity(float vx, float vy, float vz, bool yaw_is_rate, + float yaw) override; + void CommandVelocityZ(float vx, float vy, float z, bool yaw_is_rate, + float yaw) override; + void CommandPosition(float x, float y, float z, bool yaw_is_rate, + float yaw) override; + void CommandVelocityBody(float vx, float vy, float vz, + bool yaw_is_rate, float yaw) override; + void CommandVelocityZBody(float vx, float vy, float z, + bool yaw_is_rate, float yaw) override; + + // controller configs + void SetControllerGains(uint8_t controllerType, const std::vector& kp, + const std::vector& ki, + const std::vector& kd) override; + ReadyState GetReadyState() const override; + GeoPoint GetGpsLocationEstimated() const override; + + /************************* State APIs *********************************/ + Kinematics GetKinematicsEstimated() const override; + LandedState GetLandedState() const override; + // GeoPoint GetGpsLocation() const override; + const MultirotorApiParams& GetMultirotorApiParams() const override; + + /************************* Basic Config APIs **************************/ + float GetCommandPeriod() + const override; // time between two command required for drone in seconds + // noise in difference of two position coordinates. This is not GPS or + // position accuracy which can be very low such as 1m. the difference between + // two position cancels out transitional errors. Typically this would be 0.1m + // or lower. + float GetDistanceAccuracy() const override; + + protected: + // optional overrides + Vector3 GetAngles() const override; + Vector3 GetPosition() const override; + Vector3 GetVelocity() const override; + Quaternion GetOrientation() const override; + + protected: + void RegisterServiceMethods(void) override; + + private: + // The kind of target vehicle + enum class VehicleKind { + Multirotor, // Multirotor helicopter (aka., multicopter) + VTOLTailsitter, // VTOL tail-sitting fixed-wing vehicle with multicopter + // and fixed-wing modes + VTOLTiltrotor, // VTOL tilt-rotor fixed-wing vehicle with multicopter + // and fixed-wing modes + FixedWing, // Fixed-wing aircraft + Other, + }; // enum class VehicleKind + + private: + void LoadSettings(const Robot& robot); + static void Break(std::shared_ptr model); + + private: + std::unordered_map actuator_id_to_output_idx_map_; + std::unique_ptr board_; + std::unique_ptr comm_link_; + std::unique_ptr estimator_; + std::unique_ptr estimator_fw_; + std::unique_ptr firmware_; + uint64_t millis_rc_input_last_update_ = 0; // Timestamp of when RC input was last received + std::unique_ptr params_; // todo params should become simple_flight_api_settings + Topic rc_input_topic_; // RC input topic + MultirotorApiParams safety_params_; + std::mutex update_lock_; + VehicleKind vehicle_kind_ = VehicleKind::Multirotor; // The type of vehicle being controlled + float takeoff_z_ = 100.0f; // The z-coordinate of the takeoff position + bool is_api_control_enabled_ = false; +}; + +} // namespace projectairsim +} // namespace microsoft + +#endif // MULTIROTOR_API_INCLUDE_SIMPLE_FLIGHT_API_HPP_ \ No newline at end of file diff --git a/vehicle_apis/multirotor_api/include/landing_gear_api_base.hpp b/vehicle_apis/multirotor_api/include/landing_gear_api_base.hpp new file mode 100644 index 00000000..2c1e16d1 --- /dev/null +++ b/vehicle_apis/multirotor_api/include/landing_gear_api_base.hpp @@ -0,0 +1,37 @@ +// Copyright (C) Microsoft Corporation. All rights reserved. + +#ifndef MULTIROTOR_API_INCLUDE_LANDING_GEAR_API_BASE_HPP_ +#define MULTIROTOR_API_INCLUDE_LANDING_GEAR_API_BASE_HPP_ + +#include +#include +#include +#include +#include + +#include "ilanding_gear_api.hpp" +#include "vtolfw_api_base.hpp" + +namespace microsoft { +namespace projectairsim { + +class LandingGearApiBase : public VTOLFWApiBase, public ILandingGearApi { + public: + LandingGearApiBase() {} + LandingGearApiBase(const Robot& robot, TransformTree* ptransformtree); + + virtual ~LandingGearApiBase() = default; + + protected: + void RegisterServiceMethods(void) override; + + //--------------------------------------------------------------------------- + // Service Method Wrappers + + bool SetBrakesServiceMethod(float value); +}; // class LandingGearApiBase + +} // namespace projectairsim +} // namespace microsoft + +#endif // MULTIROTOR_API_INCLUDE_LANDING_GEAR_API_BASE_HPP_ \ No newline at end of file diff --git a/vehicle_apis/multirotor_api/src/CMakeLists.txt b/vehicle_apis/multirotor_api/src/CMakeLists.txt index d735c0d4..fe921fea 100644 --- a/vehicle_apis/multirotor_api/src/CMakeLists.txt +++ b/vehicle_apis/multirotor_api/src/CMakeLists.txt @@ -25,7 +25,9 @@ add_library( matlab_controller_api.cpp multirotor_api_base.cpp simple_flight_api.cpp + jsbsim_api.cpp vtolfw_api_base.cpp + landing_gear_api_base.cpp arducopter_api.cpp ) diff --git a/vehicle_apis/multirotor_api/src/jsbsim_api.cpp b/vehicle_apis/multirotor_api/src/jsbsim_api.cpp new file mode 100644 index 00000000..1ae39460 --- /dev/null +++ b/vehicle_apis/multirotor_api/src/jsbsim_api.cpp @@ -0,0 +1,541 @@ +// Copyright (C) Microsoft Corporation. All rights reserved. + +#include "jsbsim_api.hpp" + +#include +#ifdef LVMON_REPORTING +#include +#endif // LVMON_REPORTING + +#include + +#include "core_sim/message/flight_control_rc_input_message.hpp" +#include "core_sim/message/flight_control_setpoint_message.hpp" +#include "core_sim/transforms/transform_tree.hpp" +#include "core_sim/transforms/transform_utils.hpp" +#include "json.hpp" +#include "core_sim/service_method.hpp" +#include "core_sim/geodetic_converter.hpp" + +// JSBSim include (requires RTTI, must be in .cpp not .hpp) +#include "FGFDMExec.h" + +namespace microsoft { +namespace projectairsim { + +// ----------------------------------------------------------------------------- +// class JSBSimApi + +JSBSimApi::JSBSimApi(const Robot& robot, + TransformTree* ptransformtree) + : LandingGearApiBase(robot, ptransformtree) { + LoadSettings(robot); +} + +void JSBSimApi::LoadSettings(const Robot& robot) { + const std::string controller_settings = robot.GetControllerSettings(); + const json& controller_settings_json = json::parse(controller_settings); + + const std::string airframe_setup = + controller_settings_json.value("airframe-setup", ""); + + if (airframe_setup == "quadrotor-x") { + vehicle_kind_ = VehicleKind::Multirotor; + } else if (airframe_setup == "hexarotor-x") { + vehicle_kind_ = VehicleKind::Multirotor; + } else if (airframe_setup == "vtol-quad-x-tailsitter") { + vehicle_kind_ = VehicleKind::VTOLTailsitter; + } else if (airframe_setup == "vtol-quad-tiltrotor") {; + vehicle_kind_ = VehicleKind::VTOLTiltrotor; + } else if (airframe_setup == "fixed-wing") { //TODO: review if this variable is necesary, the number of motors is flexible + vehicle_kind_ = VehicleKind::FixedWing; + } else { + vehicle_kind_ = VehicleKind::Other; + } + + // GetJsonObject + //const json& jsbsim_api_settings_json = + // controller_settings_json.value("jsbsim-api-settings", "{ }"_json); + +} + +//--------------------------------------------------------------------------- +// IController overrides + +void JSBSimApi::BeginUpdate() { + MultirotorApiBase::BeginUpdate(); + + params_.reset(new simple_flight::Params); + params_->motor.motor_count = 4; + + if (vehicle_kind_ == VehicleKind::VTOLTailsitter) + params_->controller_type = + simple_flight::Params::ControllerType::kVFWTCascade; + else if (vehicle_kind_ == VehicleKind::VTOLTiltrotor) + params_->controller_type = + simple_flight::Params::ControllerType::kVTRCascade; + + board_.reset(new AirSimSimpleFlightBoard(params_.get())); + comm_link_.reset(new AirSimSimpleFlightCommLink()); + estimator_.reset(new AirSimSimpleFlightEstimator()); + estimator_fw_.reset(new AirSimSimpleFlightEstimatorFW()); + estimator_fw_->Initialize(estimator_.get()); + firmware_.reset( + new simple_flight::Firmware(params_.get(), board_.get(), comm_link_.get(), + estimator_.get(), estimator_fw_.get())); + + // Reset RC input timestamp--use uint64_t so wrap-around delta calculations + // work + { + auto millis_cur = board_->Millis(); + + millis_rc_input_last_update_ = *reinterpret_cast(&millis_cur); + } + + Reset(); + +#ifdef LVMON_REPORTING + LVMon::Set("Params/vtol/enable_fixed_wing", + params_->vtol.enable_fixed_wing_mode ? "true" : "false"); +#endif // LVMON_REPORTING +} + +void JSBSimApi::EndUpdate() { + MultirotorApiBase::EndUpdate(); + // TODO: Do we need any clean-up of the board, firmware? +} + +void JSBSimApi::Reset() { firmware_->Reset(); } + +void JSBSimApi::Update() { firmware_->Update(); } + +void JSBSimApi::SetKinematics(const Kinematics* kinematics) { + board_->SetGroundTruthKinematics(kinematics); + estimator_->SetGroundTruthKinematics(kinematics); +} + +// GetJSBSimProperty +float JSBSimApi::GetJSBSimProperty(const std::string& property) { + auto model = sim_robot_.GetJSBSimModel(); + auto value = model->GetPropertyValue(property); + return value; +} + +bool JSBSimApi::SetJSBSimProperty(const std::string& property, float value) { + auto model = sim_robot_.GetJSBSimModel(); + model->SetPropertyValue(property, value); + return true; +} + +void JSBSimApi::RegisterServiceMethods() { + LandingGearApiBase::RegisterServiceMethods(); + + //Register GetJSBSimProperty + auto method = ServiceMethod("GetJSBSimProperty", {"_property_name"}); + auto method_handler = + method.CreateMethodHandler(&JSBSimApi::GetJSBSimProperty, *this); + sim_robot_.RegisterServiceMethod(method, method_handler); + + //Register SetJSBSimProperty + method = ServiceMethod("SetJSBSimProperty", {"_property_name","_value"}); + method_handler = + method.CreateMethodHandler(&JSBSimApi::SetJSBSimProperty, *this); + sim_robot_.RegisterServiceMethod(method, method_handler); +} + +std::vector JSBSimApi::GetControlSignals(const std::string& actuator_id) { + auto model = sim_robot_.GetJSBSimModel(); + //add fcs/ to actuator_id + auto jsbsim_actuator_id = actuator_id; + std::vector return_vector{GetJSBSimProperty(jsbsim_actuator_id)}; + return return_vector; +} + +//--------------------------------------------------------------------------- +// TODO: not implemented, check if the current design is right +float JSBSimApi::GetTakeoffZ() const { + return 0; +} + +bool JSBSimApi::Takeoff(float timeout_sec, TimeNano _service_method_start_time) { + // if this vehicle is not a fixed wing + if (vehicle_kind_ != VehicleKind::FixedWing) + return VTOLFWApiBase::Takeoff(timeout_sec, _service_method_start_time); + + // if this vehicle is a fixed wing + auto model = sim_robot_.GetJSBSimModel(); + + // A JSBSim vehicle must have the "airsim/takeoff" booleans defined + // that triggers all the necessary takeoff procedures + SetJSBSimProperty("airsim/takeoff", 1); + + auto success = RunFlightCommand( + [&]() { + float takeoff_ended = GetJSBSimProperty("airsim/takeoff-ended"); + return takeoff_ended > 0.99; + }, + timeout_sec, _service_method_start_time) + .IsComplete(); + + if (!success) + return false; + + success = RunFlightCommand( + [&]() { + float takeoff_success = GetJSBSimProperty("airsim/takeoff-success"); + return takeoff_success > 0.99; + }, + timeout_sec, _service_method_start_time) + .IsComplete(); + return success; +} + +bool JSBSimApi::Land(float timeout_sec, int64_t command_start_time_nanos) { + SingleTaskCall lock(this); + + auto model = sim_robot_.GetJSBSimModel(); + + // Wait until we stop moving vertically + { + // A JSBSim vehicle must have the "airsim/takeoff" boolean defined + // that triggers all the necessary takeoff procedures + SetJSBSimProperty("airsim/land", 1); + + return RunFlightCommand( + [&]() { + float land_ended = GetJSBSimProperty("airsim/land-ended"); + return static_cast(land_ended); + }, + timeout_sec, command_start_time_nanos) + .IsComplete(); + } +} + +bool JSBSimApi::EnableApiControl() { + is_api_control_enabled_ = true; + return true; +} + +bool JSBSimApi::DisableApiControl() { + firmware_->OffboardApi().ReleaseApiControl(); + is_api_control_enabled_ = false; + return true; +} + +bool JSBSimApi::IsApiControlEnabled() { + return is_api_control_enabled_; +} + +bool JSBSimApi::CanArm() const { + return true; +} + +void JSBSimApi::CommandVelocityBody(float vx, float vy, float vz, + bool yaw_is_rate, float yaw) { +} + +void JSBSimApi::CommandVelocityZBody(float vx, float vy, float z, + bool yaw_is_rate, float yaw) { +} + +GeoPoint JSBSimApi::GetGpsLocationEstimated() const +{ + return sim_robot_.GetEnvironment().home_geo_point.geo_point; +} + +ReadyState JSBSimApi::GetReadyState() const { + ReadyState state; + state.ReadyVal = true; + return state; +} + +bool JSBSimApi::SetBrakes(float value) { + //get jsbsim model + auto model = sim_robot_.GetJSBSimModel(); + SetJSBSimProperty("fcs/left-brake-cmd-norm", value); + SetJSBSimProperty("fcs/right-brake-cmd-norm", value); + SetJSBSimProperty("fcs/center-brake-cmd-norm", value); + return true; +} + + +bool JSBSimApi::Arm(int64_t /*command_start_time_nanos*/) { + //std::string message; + //return firmware_->OffboardApi().Arm(message); + //get jsbsim model + auto model = sim_robot_.GetJSBSimModel(); + SetJSBSimProperty("fcs/mixture-cmd-norm[0]", 1); + SetJSBSimProperty("fcs/mixture-cmd-norm[1]", 1); + SetJSBSimProperty("fcs/advance-cmd-norm[0]", 1); + SetJSBSimProperty("fcs/advance-cmd-norm[1]", 1); + SetJSBSimProperty("fcs/throttle-cmd-norm[0]", 0.01); + SetJSBSimProperty("fcs/throttle-cmd-norm[1]", 0.01); + SetJSBSimProperty("propulsion/magneto_cmd", 3); + SetJSBSimProperty("propulsion/starter_cmd", 1); + + + return true; +} + +bool JSBSimApi::Disarm() { + std::string message; + return firmware_->OffboardApi().Disarm(message); +} + +//--------------------------------------------------------------------------- +// Implementation for MultirotorApiBase + +void JSBSimApi::CommandMotorPWMs(float front_right_pwm, + float rear_left_pwm, + float front_left_pwm, + float rear_right_pwm) { + typedef simple_flight::GoalModeType GoalModeType; + simple_flight::GoalMode mode( + GoalModeType::kPassthrough, GoalModeType::kPassthrough, + GoalModeType::kPassthrough, GoalModeType::kPassthrough); + + simple_flight::Axis4r goal(front_right_pwm, rear_left_pwm, front_left_pwm, + rear_right_pwm); + + std::string message; + firmware_->OffboardApi().SetGoalAndMode(&goal, &mode, message); +} + +void JSBSimApi::CommandRollPitchYawZ(float roll, float pitch, float yaw, + float z) { + typedef simple_flight::GoalModeType GoalModeType; + simple_flight::GoalMode mode( + GoalModeType::kAngleLevel, GoalModeType::kAngleLevel, + GoalModeType::kAngleLevel, GoalModeType::kPositionWorld); + + simple_flight::Axis4r goal(roll, pitch, yaw, z); + + std::string message; + firmware_->OffboardApi().SetGoalAndMode(&goal, &mode, message); +} + +void JSBSimApi::CommandRollPitchYawThrottle(float roll, float pitch, + float yaw, float throttle) { + typedef simple_flight::GoalModeType GoalModeType; + simple_flight::GoalMode mode( + GoalModeType::kAngleLevel, GoalModeType::kAngleLevel, + GoalModeType::kAngleLevel, GoalModeType::kPassthrough); + + simple_flight::Axis4r goal(roll, pitch, yaw, throttle); + + std::string message; + firmware_->OffboardApi().SetGoalAndMode(&goal, &mode, message); +} + +void JSBSimApi::CommandRollPitchYawrateThrottle(float roll, float pitch, + float yaw_rate, + float throttle) { +} + +void JSBSimApi::CommandRollPitchYawrateZ(float roll, float pitch, + float yaw_rate, float z) { +} + +void JSBSimApi::CommandAngleRatesZ(float roll_rate, float pitch_rate, + float yaw_rate, float z) { +} + +void JSBSimApi::CommandAngleRatesThrottle(float roll_rate, + float pitch_rate, + float yaw_rate, + float throttle) { +} + +void JSBSimApi::CommandVelocity(float vx, float vy, float vz, + bool yaw_is_rate, float yaw) { +} + +void JSBSimApi::CommandVelocityZ(float vx, float vy, float z, + bool yaw_is_rate, float yaw) { +} + +void JSBSimApi::CommandPosition(float x, float y, float z, + bool yaw_is_rate, float yaw) { +} + + +bool JSBSimApi::MoveToPosition(float x, float y, float z, float velocity, + float timeout_sec, DrivetrainType drivetrain, + bool yaw_is_rate, float yaw, float lookahead, + float adaptive_lookahead, + int64_t command_start_time_nanos){ + + //get world coordinates from sim_robot_ + auto world_geopoint = sim_robot_.GetEnvironment().home_geo_point.geo_point; + // get coordinates for x,y,z + GeodeticConverter converter(world_geopoint.latitude, world_geopoint.longitude, + world_geopoint.altitude); + double lat, lon; + float alt; + converter.ned2Geodetic(x,y,z,&lat,&lon,&alt); + + SetJSBSimProperty("ap/altitude_setpoint", -z * MathUtils::meters_to_feets); // world is flat so z is altitude + SetJSBSimProperty("guidance/target_wp_latitude_rad", MathUtils::deg2Rad(lat)); + SetJSBSimProperty("guidance/target_wp_longitude_rad", MathUtils::deg2Rad(lon)); + SetJSBSimProperty("ap/heading-setpoint-select", 1); + SetJSBSimProperty("guidance/heading-selector-switch", 0); + SetJSBSimProperty("ap/heading_hold", 1); + + auto just_started = true; // to avoid checking distance on first iteration + + return RunFlightCommand( + [&]() { + if (just_started) { + just_started = false; + return false; + } + if (GetJSBSimProperty("guidance/wp-distance")<= lookahead * MathUtils::meters_to_feets) { + return true; + } else + return false; + }, + timeout_sec, command_start_time_nanos) + .IsComplete(); + +} + +const MultirotorApiBase::MultirotorApiParams& +JSBSimApi::GetMultirotorApiParams() const { + return safety_params_; +} + +void JSBSimApi::SetControllerGains(uint8_t controller_type, + const std::vector& kp, + const std::vector& ki, + const std::vector& kd) { +} + +Kinematics JSBSimApi::GetKinematicsEstimated() const { + return AirSimSimpleFlightCommon::ToKinematicsState3r( + firmware_->OffboardApi().GetStateEstimator().GetKinematicsEstimated()); +} + +Vector3 JSBSimApi::GetAngles() const { + const auto& val = firmware_->OffboardApi().GetStateEstimator().GetAngles(); + return AirSimSimpleFlightCommon::ToVector3(val); +} + +Vector3 JSBSimApi::GetPosition() const { + const auto& val = firmware_->OffboardApi().GetStateEstimator().GetPosition(); + return AirSimSimpleFlightCommon::ToVector3(val); +} + +Vector3 JSBSimApi::GetVelocity() const { + const auto& val = + firmware_->OffboardApi().GetStateEstimator().GetLinearVelocity(); + return AirSimSimpleFlightCommon::ToVector3(val); +} + +Quaternion JSBSimApi::GetOrientation() const { + const auto& val = + firmware_->OffboardApi().GetStateEstimator().GetOrientation(); + return AirSimSimpleFlightCommon::ToQuaternion(val); +} + +LandedState JSBSimApi::GetLandedState() const { + return firmware_->OffboardApi().GetLandedState() ? LandedState::Landed + : LandedState::Flying; +} + +float JSBSimApi::GetCommandPeriod() const { + return 1.0f / 50; // 50hz +} + +float JSBSimApi::GetDistanceAccuracy() const { + return 0.5f; // measured in simulator by firing commands "MoveToLocation -x 0 + // -y 0" multiple times and looking at distance traveled +} + +//--------------------------------------------------------------------------- +// Implementation for VTOLFWApiBase +bool JSBSimApi::MoveByHeading(float heading, float speed, float vz, + float duration, float heading_margin, + float yaw_rate, float timeout_sec, + int64_t command_start_time_nanos) { + SingleTaskCall lock(this); + + float yaw = MathUtils::NormalizeAngle(heading); + + return (RunFlightCommand( + [&]() { + // Command the heading and wait until we've reached it + if (RunFlightCommand( + [&]() { + if (IsYawWithinMargin(yaw, heading_margin)) + return (true); + else + CommandHeading(yaw, speed, vz); + + return (false); + }, + timeout_sec, command_start_time_nanos) + .IsTimeout()) { + return (false); + } + + // Keep commanding the heading for the requested duration + RunFlightCommand( + [&]() { + CommandHeading(yaw, speed, vz); + return (false); + }, + duration, SimClock::Get()->NowSimNanos()); + + return (true); + }, + timeout_sec, command_start_time_nanos) + .IsComplete()); +} + +void JSBSimApi::CommandHeading(float heading, float speed, float vz) { + auto setpoint_yaw_deg = MathUtils::rad2Deg(heading); + SetJSBSimProperty("ap/heading_setpoint", setpoint_yaw_deg); + SetJSBSimProperty("ap/heading-setpoint-select", 0); + SetJSBSimProperty("ap/heading_hold", 1); +} + +bool JSBSimApi::MoveToZ(float z, float velocity, float timeout_sec, bool yaw_is_rate, + float yaw, float lookahead, float adaptive_lookahead, + int64_t command_start_time_nanos) { + auto model = sim_robot_.GetJSBSimModel(); + + auto success = RunFlightCommand( + [&]() { + auto vel = GetVelocity().norm(); + if (vel >= 25.0f) { + SetJSBSimProperty("ap/altitude_setpoint", -z * MathUtils::meters_to_feets); + SetJSBSimProperty("ap/altitude_hold", 1); + return true; + } else + return false; + }, + timeout_sec, command_start_time_nanos) + .IsComplete(); + + if (!success) + return false; + + success = RunFlightCommand( + [&]() { + auto z_ = GetPosition().z(); + if (z_ <= z) { + return true; + } else + return false; + }, + timeout_sec, command_start_time_nanos) + .IsComplete(); + + return success; + +} + +//--------------------------------------------------------------------------- + +} // namespace projectairsim +} // namespace microsoft \ No newline at end of file diff --git a/vehicle_apis/multirotor_api/src/landing_gear_api_base.cpp b/vehicle_apis/multirotor_api/src/landing_gear_api_base.cpp new file mode 100644 index 00000000..2e715c17 --- /dev/null +++ b/vehicle_apis/multirotor_api/src/landing_gear_api_base.cpp @@ -0,0 +1,32 @@ +// Copyright (C) Microsoft Corporation. All rights reserved. + +#include "landing_gear_api_base.hpp" + +#include +#include +#include +#include +#include + +namespace microsoft { +namespace projectairsim { + +LandingGearApiBase::LandingGearApiBase(const Robot& robot, + TransformTree* ptransformtree) + : VTOLFWApiBase(robot, ptransformtree) {} + +bool LandingGearApiBase::SetBrakesServiceMethod(float value) { + return SetBrakes(value); +} + +void LandingGearApiBase::RegisterServiceMethods(void) { + VTOLFWApiBase::RegisterServiceMethods(); + + // Register SetBrakes + auto method = ServiceMethod("SetBrakes", {"_brakes_value"}); + auto method_handler = method.CreateMethodHandler(&LandingGearApiBase::SetBrakesServiceMethod, *this); + sim_robot_.RegisterServiceMethod(method, method_handler); +} + +} // namespace projectairsim +} // namespace microsoft \ No newline at end of file diff --git a/vehicle_apis/multirotor_api/src/manual_controller_api.cpp b/vehicle_apis/multirotor_api/src/manual_controller_api.cpp index 4da2cf75..bb368b24 100644 --- a/vehicle_apis/multirotor_api/src/manual_controller_api.cpp +++ b/vehicle_apis/multirotor_api/src/manual_controller_api.cpp @@ -39,7 +39,7 @@ std::vector ManualControllerApi::GetControlSignals(const std::string& act auto actuator_map_itr = actuator_id_to_output_idx_map_.find(actuator_id); if (actuator_map_itr == actuator_id_to_output_idx_map_.end()) { GetLogger().LogWarning("ManualControllerApi", - "ManualControllerApi::GetControlSignal() called for " + "ManualControllerApi::GetControlSignals() called for " "invalid actuator: %s", actuator_id.c_str()); return std::vector(1,0.0f); diff --git a/vehicle_apis/multirotor_api/src/matlab_controller_api.cpp b/vehicle_apis/multirotor_api/src/matlab_controller_api.cpp index 2b76ceb1..0a3efccb 100644 --- a/vehicle_apis/multirotor_api/src/matlab_controller_api.cpp +++ b/vehicle_apis/multirotor_api/src/matlab_controller_api.cpp @@ -214,7 +214,7 @@ std::vector MatlabControllerApi::GetControlSignals(const std::string& act auto actuator_map_itr = actuator_id_to_output_idx_map_.find(actuator_id); if (actuator_map_itr == actuator_id_to_output_idx_map_.end()) { GetLogger().LogWarning("MatlabControllerApi", - "MatlabControllerApi::GetControlSignal() called for " + "MatlabControllerApi::GetControlSignals() called for " "invalid actuator: %s", actuator_id.c_str()); return std::vector(1, 0.f);