### Install lotus-sc CLI tool for LOTUS script development Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/quickstart.mdx Installs `lotus-sc`, a command-line interface tool that assists in developing and managing scripts for the LOTUS simulator. ```bash cargo install lotus-sc ``` -------------------------------- ### Install Rust wasm32 target for LOTUS script development Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/quickstart.mdx Installs the `wasm32-unknown-unknown` target for Rust, which is required to compile scripts for the WebAssembly environment used by LOTUS. ```bash rustup target add wasm32-unknown-unknown ``` -------------------------------- ### Start Development Server Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/README.md Command to start the local development server for the documentation project. This command includes features like hot-reloading for efficient development. ```bash bun dev ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/README.md Command to install all necessary project dependencies using the Bun package manager. This should be run after Bun has been successfully installed. ```bash bun install ``` -------------------------------- ### Deploy LOTUS script using lotus-sc CLI Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/quickstart.mdx Deploys the compiled LOTUS script using the `lotus-sc` CLI tool, based on the configuration provided in `script.toml`. ```bash lotus-sc deploy ``` -------------------------------- ### External API Documentation for lotus-script Crate Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/quickstart.mdx Provides a direct link to the comprehensive API documentation for the `lotus-script` Rust crate, hosted on docs.rs, detailing all available modules, structs, traits, and functions. ```APIDOC API Documentation Link: URL: https://docs.rs/lotus-script/latest/ Content: Full API reference for the `lotus-script` Rust crate. ``` -------------------------------- ### Install Bun on Linux Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/README.md Instructions to install the Bun JavaScript runtime on Linux systems using a curl command. A new shell session is required for PATH changes to take effect. ```bash curl -fsSL https://bun.sh/install | bash ``` -------------------------------- ### Build release version of LOTUS script Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/quickstart.mdx Compiles the LOTUS script with optimizations for a release build, resulting in a smaller and faster WASM binary. ```bash lotus-sc build --profile release ``` -------------------------------- ### Create a new Rust library project for LOTUS script Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/quickstart.mdx Initializes a new Rust library project, which serves as the foundation for a LOTUS script. The project name should be replaced with the desired script name. ```bash cargo new --lib ``` -------------------------------- ### Configure script.toml for LOTUS script deployment Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/quickstart.mdx Creates a `script.toml` file to specify deployment parameters, including `user-id` and `sub-id`, which link the script to a specific object in LOTUS. ```toml [deploy] user-id = 1234 sub-id = 5678 ``` -------------------------------- ### Install Bun on Windows Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/README.md Instructions to install the Bun JavaScript runtime on Windows systems using a PowerShell command. A new shell session is required for PATH changes to take effect. ```powershell powershell -c "irm bun.sh/install.ps1 | iex" ``` -------------------------------- ### Minimal Rust script structure for LOTUS Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/quickstart.mdx Provides a basic Rust script template for LOTUS, including necessary imports, a default struct, and implementations for the `Script` trait's `init` and `tick` methods. ```rust use lotus_script::prelude::*; #[derive(Default)] pub struct MyScript {} script!(MyScript); impl Script for MyScript { fn init(&mut self) {} fn tick(&mut self) {} } ``` -------------------------------- ### Add lotus-script dependency to Rust project Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/quickstart.mdx Adds the `lotus-script` crate as a dependency to the Rust project, providing necessary APIs and macros for LOTUS script development. ```bash cargo add lotus-script ``` -------------------------------- ### Configure Cargo.toml for cdylib crate type Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/quickstart.mdx Adds the `cdylib` crate type to `Cargo.toml`, enabling the Rust library to be compiled as a C-compatible dynamic library, suitable for WASM environments. ```toml [lib] crate-type = ["cdylib"] ``` -------------------------------- ### Install lotus-sc CLI Tool Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/reference/lotus-sc.md Installs the lotus-sc command-line tool using Cargo, Rust's package manager. The `--locked` flag ensures that the exact versions of dependencies specified in `Cargo.lock` are used, providing consistent builds. ```bash cargo install --locked lotus-sc ``` -------------------------------- ### Get Mouse Delta (Rust) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/input.md Illustrates how to obtain the `delta` (change) in mouse position. The `delta` provides `x` and `y` components, useful for camera movement or other continuous input processing. ```Rust let delta = mouse_delta(); log::info!("Horizontal: {} Vertical: {}", delta.x, delta.y); ``` -------------------------------- ### Get Variable Value (Rust) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/variables.md Retrieves the value of a variable. If the variable is not yet set, it will be initialized with its default value (e.g., 0 for numerical types). Examples show both explicit type declarations and type inference. ```rust // explicitly type the get_var function let my_int = i32::get_var("myVariableName"); // explicitly type the binding let my_int: i32 = get_var("myVariableName"); // in case the variable type can be inferred let my_int = get_var("myVariableName"); ``` -------------------------------- ### Drawing Basic 3D Debugging Gizmos in Rust Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/gizmos.md This snippet demonstrates how to draw various basic 3D debugging gizmos using the Gizmo API in Rust. It includes examples for drawing a wire cube, a wire sphere, and an arrow, all relative to the object's center for visualization. ```rust // red wire cube in the center of the object extending 0.5 units in all directions Gizmo::wire_cube(Vec3::ZERO, (0.5, 0.5, 0.5), Color::RED).draw(); // wire sphere with a radius of 0.5 Gizmo::wire_sphere(Vec3::ZERO, 0.5, Color:RED).draw(); Gizmo::arrow(start, end, color).draw(); ``` -------------------------------- ### Simulator to Script Parameter Passing (Serialized) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/wasm/api.mdx This sequence diagram illustrates how the simulator passes serialized parameters to a script. The simulator first serializes the parameter, then calls the script's `allocate` function to get a pointer. The simulator then passes the parameter as a u64 (pointer and length). The script is responsible for deallocating the data after use. ```mermaid sequenceDiagram title simulator -> script participant simulator participant script Note over simulator: serializes parameter simulator->>script: allocate(size) script->>simulator: returns pointer u32 simulator->>script: passes param as u64 (pointer u32, length u32) Note over script: SHOULD deallocate after use script->>simulator: function returns ``` -------------------------------- ### Accessing and Controlling a Specific Bogie (Rust) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/vehicle.md Explains how to retrieve a `Bogie` object using its index. Once accessed, the example shows how to set the rail brake force for that bogie, providing higher-level control over braking systems. ```rust let bogie_index = 0; if let Ok(bogie) = Bogie::get(bogie_index) { // Set rail brake force in Newtons bogie.set_rail_brake_force_newton(2000.0); } ``` -------------------------------- ### Sending Messages to Targets in Rust Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/messages.md Demonstrates how to send instances of a custom message type using the `send_message` function in Rust. Examples include sending to all broadcast targets and sending to a specific list of targets like `Parent` and `MySelf`. ```rust // Send to a "single" target send_message(&MyMessage { a_field: 42 }, MessageTarget::broadcast_all()); // Send to multiple targets send_message(&MyMessage { a_field: 42 }, &[MessageTarget::Parent, MessageTarget::MySelf]); ``` -------------------------------- ### Get Elapsed Time Between Ticks (Rust) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/time.md Demonstrates how to retrieve the time elapsed between the last and current tick using `delta()` for standard precision and `delta_f64()` for 64-bit precision. `delta()` is generally sufficient for most use cases. ```Rust let elapsed = delta(); let elapsed_64 = delta_f64(); ``` -------------------------------- ### Implement Adaptive Traction Control in Rust Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/vehicle.md This Rust code snippet demonstrates how to implement an adaptive traction control system for a vehicle in Lotus Simulator. It dynamically adjusts the traction force applied to each axle based on the vehicle's current speed and the quality of the rail. Traction is higher at lower speeds for starting and reduced on poor quality rails to prevent slippage. ```Rust impl Script for MyScript { fn tick(&mut self) { let speed = vehicle::velocity_vs_ground(); // Iterate through all axles on the first bogie for axle_index in 0..4 { if let Ok(axle) = Axle::get(0, axle_index) { let rail_quality = axle.rail_quality(); // Adjust traction based on speed and rail quality let base_traction = if speed < 10.0 { 2000.0 // High traction for starting } else if speed < 50.0 { 1500.0 // Medium traction for acceleration } else { 1000.0 // Lower traction at high speed }; // Reduce traction on poor rails let adjusted_traction = match rail_quality { RailQuality::Perfect => base_traction, RailQuality::Good => base_traction * 0.9, RailQuality::Poor => base_traction * 0.7, RailQuality::Damaged => base_traction * 0.4, }; axle.set_traction_force_newton(adjusted_traction); } } } } ``` -------------------------------- ### Generate Random Numbers in Rust Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/rng.md This Rust code demonstrates how to generate floating-point random numbers between 0.0 and 1.0 using `gen_f64()`, and unsigned 64-bit integers within specified ranges using `gen_u64()`. It shows examples for exclusive and inclusive upper bounds when defining the range. ```rust // between 0.0 and 1.0 let random = gen_f64(); // between 10 and 100 (exclusive) let random = gen_u64(10..100); // between 10 and 100 (inclusive) let random = gen_u64(10..=100); ``` -------------------------------- ### Handling Errors for Axle and Bogie Access (Rust) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/vehicle.md Provides an example of robust error handling when attempting to access `Axle` or `Bogie` objects. It demonstrates how to use a `match` statement with the `Result` type to catch specific `VehicleError` variants like `InvalidBogie` or `InvalidAxle`, ensuring graceful failure for invalid indices. ```rust match Axle::get(bogie_index, axle_index) { Ok(axle) => { // Successfully got the axle axle.set_traction_force_newton(1000.0); }, Err(VehicleError::InvalidBogie) => { log::error!("Invalid bogie index: {}", bogie_index); }, Err(VehicleError::InvalidAxle) => { log::error!("Invalid axle index: {} for bogie {}", axle_index, bogie_index); }, Err(e) => { log::error!("Vehicle error: {:?}", e); } } ``` -------------------------------- ### Select Build Profile with lotus-sc Command Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/recommendations.md These `bash` commands demonstrate how to select a specific build profile (development or release) when compiling with `lotus-sc`. Using the `--profile` option allows developers to switch between optimized release builds and faster development builds, influencing WASM size and compilation speed. ```bash lotus-sc --profile dev # or lotus-sc --profile release ``` -------------------------------- ### Simulator Key Bindings Reference Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/reference/input-actions.md A detailed list mapping specific simulator actions to their default keyboard shortcuts, organized for quick reference of control inputs. ```APIDOC Action | Key Binding --------------------------- | ------------------------- view.reset | Shift + 9 view.driver | F1 view.hardware | Shift + F1 view.passenger | F2 view.outside | F3 view.map | F4 view.previous | Left Arrow view.next | Right Arrow view.previousVeh | Shift + Ctrl + Up Arrow view.nextVeh | Shift + Ctrl + Down Arrow view.forward | Up Arrow view.backward | Down Arrow view.levelPlus | Ctrl + Up Arrow view.levelMinus | Ctrl + Down Arrow switch.toggle.front | G switch.toggle.back | Shift + G Throttle | Q Brake | Y MaxBrake | X or Num 0 Neutral | A Sanding | Num 1 ReverserPlus | W ReverserMinus | S RailBrake | Num 3 HoldToRun | Tab RunButton | Space BrakePlus | Num 2 BrakeMinus | Num 8 SetBrakeDrive | Num 5 SetBrakeRelease | Num + SetBrakeClosed | Num Enter HighVoltageMainSwitchToggle | M Bus.SteeringLeft | Num 4 Bus.SteeringNeutral | Num 5 Bus.SteeringRight | Num 6 Bus.Throttle | Num 8 Bus.Brake | Num 2 Bus.GearBoxMode_D | D Bus.GearBoxMode_N | 1 Bus.GearBoxMode_R | R Gear_0 | 0 Gear_1 | 1 Gear_2 | 2 Gear_3 | 3 Gear_4 | 4 Gear_5 | 5 Gear_6 | 6 GearUp | Ü GearDown | - Clutch | Tab EngineStartStop | M ElectricsToggle | Shift + E ParkBrakeToggle | N ParkBrake2Toggle | Shift + N IndicatorWarn | Ctrl + Num . IndicatorToLeft | Num 7 IndicatorToRight | Num 9 IndicatorOff | Num , FrontLightPlus | L FrontLightMinus | Shift + L Bell1 | B Bell2 | Shift + B Horn1 | H Horn2 | Shift + H DoorReleaseToggle | Num - DoorReleaseLeft | J DoorReleaseRight | K DoorAllOpen | Ö DoorAllClose | Shift + Ö Door1Toggle | Num / DoorSideToggle | Num * DoorSideBoth | Shift + Num * Door1Wing2Toggle | Num * DoorStepPlattformHigh | Shift + Delete DoorStepPlattformLow | Shift + End DoorStepStreet | Shift + Page Down DisplaySel1 | F5 DisplaySel2 | F6 DisplaySel3 | F7 DisplaySel4 | F8 ``` -------------------------------- ### Deploy Script with lotus-sc Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/reference/lotus-sc.md Deploys the script by automatically building it and placing it into the correct directory for LOTUS-Simulator to load. This command assumes that a `script.toml` configuration file is already set up in your project. ```bash lotus-sc deploy ``` -------------------------------- ### TOML Configuration for Script Deployment Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/reference/script.toml.md This TOML configuration defines the parameters for deploying a script. It specifies the `package` from a Cargo workspace to be deployed, along with the `user-id` and `sub-id` of the target where the script should be attached. The `package` field is optional, while `user-id` and `sub-id` are required. ```toml [deploy] # Optional: The package in the cargo workspace that should be deployed. package = "my-package" # Required: The user id of the target to attach the script to. user-id = 1234 # Required: The sub id of the target to attach the script to. sub-id = 5678 ``` -------------------------------- ### Configure Cargo.toml for Development WASM Builds Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/recommendations.md This TOML configuration for `[profile.dev]` is optimized for faster compilation times during development. Setting `opt-level` to 1 provides a balance between build speed and basic optimization, making it suitable for iterative development without sacrificing all debugging capabilities. ```toml [profile.dev] opt-level = 1 ``` -------------------------------- ### Configure Cargo.toml for Release WASM Optimization Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/recommendations.md This TOML configuration for `[profile.release]` optimizes WASM file size and performance for release builds. It sets `opt-level` to 3 for aggressive optimization, enables Link Time Optimization (LTO), disables debugging information, and strips symbols, resulting in smaller and faster WASM modules. ```toml [profile.release] opt-level = 3 lto = true debug = false panic = "abort" strip = true codegen-units = 1 ``` -------------------------------- ### Deploy Release Build with lotus-sc Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/reference/lotus-sc.md Creates and deploys an optimized release build of your script. Release builds are significantly smaller, faster, and more efficient than default debug builds, making them ideal for publishing and distribution. It's recommended to test release builds before publishing. ```bash lotus-sc deploy --profile release ``` -------------------------------- ### Log Messages in Rust Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/logging.md Demonstrates how to use `log::info!` and `log::warning!` macros for logging messages in Rust, including string formatting. Logs can be viewed in the `Script debug` window. ```rust let answer = 42; log::info!("The ultimate answer is {answer}"); let hello = "world"; log::warning!("{hello} is {} characters long", hello.len()); ``` -------------------------------- ### Create a New Texture (Rust) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/textures.md Illustrates how to create a new texture with specified width and height. Textures can be drawn on, drawn onto other textures, and applied to objects in the game world. ```rust // width: 800, height: 600 let texture = Texture::create((800, 600)) ``` -------------------------------- ### Retrieve Current Action State (Rust) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/input.md Demonstrates how to retrieve the current state of a named input action, such as 'Throttle', and check if its `kind` is `JustPressed`. This allows for event-driven logic based on player input. ```Rust let state = action::state("Throttle"); if state.kind.is_just_pressed() { log::info!("Throttle has just been pressed"); } ``` -------------------------------- ### Preload Asset in Rust Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/asset-preloading.md Demonstrates how to preload a specific asset using its `ContentId` in Rust. Preloading improves access latency by loading the asset into memory before it's actively used, ensuring faster retrieval when needed. ```rust preload(ContentId { user_id: 1000, sub_id: 1000 }); ``` -------------------------------- ### Load Bitmap Font and Retrieve Metadata (Rust) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/textures.md Demonstrates how to load a LOTUS bitmap font using `BitmapFont::try_load` to access its metadata, such as properties or text length. The `try_load` method enqueues the font for loading and returns `Some` once it's available. ```rust if let Some(font) = BitmapFont::try_load(ContentId { user_id: 1000, sub_id: 1000 }) { let props = font.properties(); let hello_len = font.text_len("hello", 1); } ``` -------------------------------- ### Register Custom Input Actions (Rust) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/input.md Shows how to register custom input actions by implementing the `actions` method of the `Script` trait. It uses `ActionsBuilder` to define new actions with their string identifiers and default `KeyCode` bindings, enabling user-defined input mappings. ```Rust impl Script for MyScript { fn actions() -> Vec { ActionsBuilder::new() .push("my-custom-action", KeyCode::KeyM) .push("my-other-action", KeyCode::KeyA) .build() } } ``` -------------------------------- ### Script to Simulator Parameter Passing (Serialized) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/wasm/api.mdx This sequence diagram illustrates how a script passes serialized parameters to the simulator. The script serializes the parameter and passes it as a u64 (pointer and length). The simulator then processes the data, and the script may deallocate the pointer after the function returns. ```mermaid sequenceDiagram title script -> simulator participant simulator participant script Note over script: serializes parameter script->>simulator: passes param as u64 (pointer u32, length u32) simulator->>script: function returns Note over script: script MAY deallocate the pointer ``` -------------------------------- ### Adjusting Traction Based on Rail Quality (Rust) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/vehicle.md Shows how to use the `rail_quality()` method of an `Axle` to dynamically adjust traction force. Different `RailQuality` states (Perfect, Good, Poor, Damaged) lead to varying traction force applications, optimizing performance based on track conditions. ```rust if let Ok(axle) = Axle::get(0, 0) { match axle.rail_quality() { RailQuality::Perfect => { // Optimal conditions - maximum performance axle.set_traction_force_newton(2000.0); }, RailQuality::Good => { // Slightly reduced performance axle.set_traction_force_newton(1800.0); }, RailQuality::Poor => { // Significantly reduced performance axle.set_traction_force_newton(1200.0); }, RailQuality::Damaged => { // Minimal performance to prevent damage axle.set_traction_force_newton(500.0); } } } ``` -------------------------------- ### Receiving and Handling Specific Messages in Rust Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/messages.md Explains how to receive and process incoming messages in Rust by implementing the `Script::on_message` method. It shows how to use the `Message::handle` method with a closure to safely cast and handle messages of a specific type, ignoring others. ```rust impl Script for MyScript { fn on_message(&mut self, msg: Message) { msg.handle(|my_message: MyMessage| { log::info!("Received my_message with a_field={}", my_message.a_field); Ok(()) }).unwrap(); } } ``` -------------------------------- ### Controlling Axle Traction Force (Rust) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/vehicle.md Demonstrates how to apply forward traction (acceleration), regenerative braking (negative traction), or release traction (coasting) using the `set_traction_force_newton()` method on an `Axle` object. This allows for precise control over the vehicle's driving and braking forces. ```rust if let Ok(axle) = Axle::get(0, 0) { // Apply forward traction (acceleration) axle.set_traction_force_newton(1500.0); // Apply regenerative braking (negative traction) axle.set_traction_force_newton(-800.0); // No traction force (coasting) axle.set_traction_force_newton(0.0); } ``` -------------------------------- ### Draw Text onto a Texture (Rust) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/textures.md Shows how to draw text onto a texture using the `Texture::draw_text` method. This approach does not require manual font loading; the font is identified by its `ContentId`. ```rust let texture = Texture::create((800, 600)); let font_id = ContentId { user_id: 1000, sub_id: 1000 }; let top_left = (0, 0); let letter_spacing = 5; let full_color = None; texture.draw_text( font_id, "hello", top_left, letter_spacing, full_color, AlphaMode::Opaque ); ``` -------------------------------- ### Mermaid Diagram: Script Lifecycle Flow Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/reference/script-lifecycle.mdx This Mermaid flowchart illustrates the complete lifecycle of a script within the system, from object loading or script changes triggering a reload, through initialization, and into the continuous tick and late_tick cycles, which interact with the engine's main loop. It visually represents the sequence of function calls and events. ```mermaid graph TD ObjectLoaded[Object loaded]@{ shape: event } --> LoadScript ScriptChanged[Script changed]@{ shape: event } --> |Hot reload| LoadScript LoadScript[Load script] --> ScriptInit ScriptInit[call script init] --> ScriptTick ScriptTick[call script tick] --> ScriptLateTick ScriptLateTick[call script late_tick] --> Engine Engine[Engine rest of tick] --> ScriptTick ``` -------------------------------- ### Accessing Global Vehicle State Functions (Rust) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/vehicle.md Demonstrates how to retrieve global vehicle state information such as acceleration, velocity, and pantograph details using the `vehicle` module. These functions provide real-time data about the vehicle's movement and electrical system. ```rust use lotus_script::prelude::*; // Get the vehicle's acceleration relative to the ground let acceleration = vehicle::acceleration_vs_ground(); log::info!("Vehicle acceleration: {:?}", acceleration); // Get the vehicle's velocity relative to the ground let velocity = vehicle::velocity_vs_ground(); log::info!("Vehicle velocity: {:?}", velocity); // Get pantograph height (for electric vehicles) let pantograph_height = vehicle::pantograph_height(); log::info!("Pantograph height: {}", pantograph_height); // Get pantograph voltage (for electric vehicles) let pantograph_voltage = vehicle::pantograph_voltage(); log::info!("Pantograph voltage: {}", pantograph_voltage); ``` -------------------------------- ### Adjust WASM Stack Size in Cargo Config Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/recommendations.md This TOML configuration, placed in `.cargo/config.toml`, modifies the default WASM stack size. By setting `rustflags` for the `wasm32-unknown-unknown` target, it reduces the stack from 1MiB to 64KiB (65536 bytes), which is more appropriate for typical LOTUS-Simulator scripts and reduces memory footprint. ```toml [target.wasm32-unknown-unknown] rustflags = [ "-C", "link-args=-z stack-size=65536", ] ``` -------------------------------- ### Accessing and Interacting with a Specific Axle (Rust) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/vehicle.md Illustrates how to obtain an `Axle` object by its bogie and axle indices. Once accessed, the snippet shows how to retrieve rail quality information and set the traction force for that specific axle. ```rust let bogie_index = 0; let axle_index = 0; if let Ok(axle) = Axle::get(bogie_index, axle_index) { // Do something with the axle, like getting the rail quality of the rails under the axle let rail_quality = axle.rail_quality(); log::info!("Rail quality under axle: {:?}", rail_quality); // Set the traction force in Newtons axle.set_traction_force_newton(1000.0); } ``` -------------------------------- ### Controlling Bogie Rail Brake Force (Rust) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/vehicle.md Illustrates how to apply, moderate, or release rail braking force using the `set_rail_brake_force_newton()` method on a `Bogie` object. This demonstrates how to utilize mechanical braking systems for additional stopping power. ```rust if let Ok(bogie) = Bogie::get(0) { // Apply maximum rail braking bogie.set_rail_brake_force_newton(3000.0); // Apply moderate rail braking bogie.set_rail_brake_force_newton(1500.0); // Release rail brakes bogie.set_rail_brake_force_newton(0.0); } ``` -------------------------------- ### Defining Custom Message Types in Rust Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/messages.md Illustrates how to define a custom message type in Rust by creating a `struct` that can be serialized and deserialized, and then registering it with the `message_type!` macro, optionally specifying a custom bus. ```rust #[derive(Serialize, Deserialize)] pub struct MyMessage { a_field: u32, } message_type!(MyMessage, "my-namespace", "my-message"); // or if you want to also define a bus this message uses message_type!(MyMessage, "my-namespace", "my-message", "my-bus"); ``` -------------------------------- ### Set Variable Value (Rust) Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/variables.md Assigns a new value to an existing variable or initializes a new variable with the specified value if it doesn't exist. ```rust set_var("myVariableName", 42); ``` -------------------------------- ### Implement Emergency Braking System in Rust Source: https://github.com/oriolus-software/docs.lotus-simulator.dev/blob/master/src/content/docs/rust/vehicle.md This Rust code snippet illustrates an emergency braking system for a vehicle in Lotus Simulator. When the vehicle's speed exceeds a predefined safe limit (e.g., 80 km/h), the system automatically applies both rail brakes and regenerative braking across all bogies and axles. A warning message is also logged to indicate activation. ```Rust impl Script for MyScript { fn tick(&mut self) { let speed = vehicle::velocity_vs_ground(); // Emergency braking if speed exceeds safe limit if speed > 80.0 { // Apply rail brakes on all bogies for bogie_index in 0..2 { if let Ok(bogie) = Bogie::get(bogie_index) { bogie.set_rail_brake_force_newton(5000.0); } } // Apply regenerative braking on all axles for bogie_index in 0..2 { for axle_index in 0..4 { if let Ok(axle) = Axle::get(bogie_index, axle_index) { axle.set_traction_force_newton(-2000.0); } } } log::warning!("Emergency braking activated! Speed: {:.1} km/h", speed * 3.6); } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.