sdl3-rs

repository·master·Indexed 18 days ago

https://github.com/vhspace/sdl3-rs

Idiomatic Rust bindings for SDL3 (Simple DirectMedia Layer 3), providing a cross-platform abstraction for multimedia tasks including windowing, event handling, audio, GPU access, and keyboard input. The library includes support for SDL_image, SDL_mixer, and SDL_ttf, and provides high-level Rust interfaces for GPU texture configuration, IOStream management, and SDL hints.

Tokens
13.5K
Snippets
55
Records
66
Agent score
62%

What's inside sdl3-rs

  1. Add sdl3 to your project

    master

    To use the SDL3 Rust bindings, add the sdl3 crate to your Cargo.toml dependencies. Note that the current version is in a migration phase, so some features may be missing or undergoing changes.

    [dependencies]
    sdl3 = { version = "0", features = [] }
  2. Run the SDL3 renderer examples

    master

    The sdl3-rs repository includes several example programs demonstrating different aspects of the SDL3 renderer API. You can run these examples using cargo run --example <example_name>.

    Note that some texture-related examples require the unsafe_textures feature to be enabled.

    # Basic renderer examples
    cargo r --example renderer_01_change_the_color
    cargo r --example renderer_02_primitives
    cargo r --example renderer_03_lines
    cargo r --example renderer_04_points
    cargo r --example renderer_05_rectangles
    
    # Texture-related examples (require --features="unsafe_textures")
    cargo r --example renderer_06_textures_lifetime_solution --features="unsafe_textures"
    cargo r --example renderer_07_streaming_textures --features="unsafe_textures"
    cargo r --example renderer_08_rotating_textures --features="unsafe_textures"
    cargo r --example renderer_09_scaling_textures --features="unsafe_textures"
  3. Access gyroscope and accelerometer data via Sensor API

    master

    The Sensor API provides access to motion sensors (gyroscope and accelerometer) on compatible controllers like PlayStation, Switch, and Steam controllers.

    Units

    • Accelerometer: m/s²
    • Gyroscope: radians per second

    Axis Orientation (when holding the controller)

    • X-axis: -x (left) to +x (right)
    • Y-axis: -y (down) to +y (up)
    • Z-axis: -z (forward) to +z (backward)

    Rotations (anti-clockwise around axis)

    • Pitch: -x to +x (pitch towards up)
    • Yaw: -y to +y (yaw from right to left)
    • Roll: -z to +z (roll from right to left)
  4. Thread-safe mixer access with MixerLock

    master

    To ensure thread-safe access to the mixer, use the lock() method. This returns a MixerLock RAII guard. The mixer is automatically unlocked when the guard is dropped.

    {
        let _lock = mixer.lock();
        // Perform thread-sensitive mixer operations here
    }
    // _lock is dropped here, unlocking the mixer
  5. Manage audio playback with Track

    master

    A Track is the primary object used to play sounds on an SDL3 Mixer. Each track manages its own audio source, gain, looping, position, and effects. Multiple tracks can play simultaneously on the same mixer.

    Note: A Track must not outlive its parent Mixer due to lifetime constraints.

    // Conceptual usage pattern
    let track = mixer.get_track();
    track.set_audio(&audio_source)?;
    track.play()?;
  6. Initialize a Mixer device

    master

    To use SDL3_mixer, you must first create a Mixer instance. You can either open a connection to the default audio device or a specific hardware device.

    • Default Device: Use open_device() to let SDL choose the best format and use the default playback device.
    • Specific Device: Use open_device_id(device_id, spec) to target a specific SDL_AudioDeviceID with a custom SDL_AudioSpec.
    • Memory-only Mixer: Use create_memory(spec) to create a mixer that renders to a buffer instead of an audio device. This is useful for software rendering or testing.
    // Open default device
    let mixer = Mixer::open_device(None)?;
    
    // Open specific device with custom spec
    let mixer = Mixer::open_device_id(device_id, Some(&spec))?;
    
    // Create a memory-only mixer for software rendering
    let mixer = Mixer::create_memory(None)?;
  7. Load and play audio

    master

    Once a Mixer is initialized, you can load audio data from various sources and play it.

    Loading Audio

    • From File: Use load_audio(path, predecode). If predecode is true, the audio is fully decompressed into memory; otherwise, it is decoded on the fly.
    • From IOStream: Use load_audio_io(io, predecode) to load from an abstraction of a stream.
    • From Raw PCM: Use load_raw_audio(data, spec) to load raw byte slices with a specific SDL_AudioSpec.
    • From Sine Wave: Use create_sine_wave(hz, amplitude, ms) to generate a test tone.

    Playing Audio

    • Fire and Forget: Use play_audio(&audio) to play a sound once without managing its lifecycle. SDL_mixer handles the temporary track creation and cleanup automatically.
    • Tag-based Playback: Use play_tag(tag, options) to start playing all tracks associated with a specific string tag. You can pass Properties to options for advanced control.
    // Load and play a file
    let audio = mixer.load_audio("music.wav", true)?;
    mixer.play_audio(&audio)?;
    
    // Generate a sine wave for testing
    let tone = mixer.create_sine_wave(440, 0.5, -1)?;
    mixer.play_audio(&tone)?;
  8. Initialize SDL with `init()`

    master

    To use SDL3, you must first initialize the library using sdl3::init(). This returns an Sdl context object. The Sdl object represents the main thread and is used to obtain access to various subsystems (audio, video, etc.).

    Important Threading Rule: Sdl must be initialized on the main thread. If you attempt to initialize it from a different thread, it will return an error unless you enable the test-mode feature (intended for cargo test).

    When the Sdl object is dropped, SDL_Quit() is automatically called, cleaning up the library.

    let sdl_context = sdl3::init().unwrap();
    // Use sdl_context to access subsystems...
  9. Check SDL3 extension library support

    master

    Not all SDL3 extension libraries are currently supported by sdl3-rs. Check the status of the library you need before proceeding with your implementation:

    LibrarySupport Status
    SDL_image✅ Supported
    SDL_mixer✅ Supported
    SDL_ttf✅ Supported
    sdl3-main✅ Supported
    SDL_gfx🟨 Waiting on improvements to the C library
    SDL_sound🟨 Awaiting a stable C release
    SDL_net🟨 Awaiting a stable C release
    Dear ImGUI❌ Not currently supported
    RmlUI❌ Not currently supported
    SDL_shadercross❌ Not currently supported
  10. Sleep the current thread with `delay`

    master

    Suspends the current thread for the specified number of milliseconds.

    Recommendation: It is recommended to use std::thread::sleep() instead of delay() for standard Rust development.

    delay(16); // Sleep for approximately 1 frame at 60fps