Skip to main content

Crate nadir_platform

Crate nadir_platform 

Source
Expand description

The OS layer of the Nadir engine: a window and its events, gamepads, OpenGL contexts, audio output, the user’s folders, an error dialog and a precise sleep, with one safe API on Linux, Windows and macOS.

§Where it fits

This crate wraps the raw declarations of nadir_sys, and is where the rest of Nadir meets the operating system, through one API that is the same on every system. nadir-gfx draws through its GlContext, nadir-input reads its Events, and nadir_engine opens the window with it and runs the main loop. A game reaches it through nadir_engine, which re-exports Event as nadir::Event and, with its own dev feature, the allocation counter. Depend on this crate directly for a window and its events without the rest of the engine.

§The window

§Events

An Event is something that happened to the window, to the keyboard and mouse, or to a gamepad (below), in the order the system reported it:

  • One Event::ScaleFactorChanged comes before any other event. On Windows and macOS another comes each time the scale factor changes.
  • Event::CloseRequested leaves the window open: the game decides.
  • Event::Key names the physical key, a nadir_core::Key, whatever the keyboard layout, and says whether a press is a repeat.
  • Event::Text is a character typed, after the key press that typed it: one a character, a composed one included, never a control character, and none for a shortcut. On Linux it comes from an X input method, on Windows from WM_CHAR, and on macOS from a key press’s characters.
  • Event::MouseMoved is in physical pixels from the top-left corner of the inside of the window, with y growing downward, on every system. Event::MouseWheel is in lines.
  • Right after Event::Focused(false), every key and button that is down gets a release, so nothing stays held while the window cannot see it go up.

§Gamepads

§Drawing

  • Platform::gpu_surface gives what the GPU draws the window with: for now always GpuSurface::Gl, an OpenGL context current on the thread that opened the window.
  • GlContext looks GL functions up (GlContext::get_proc_address), shows a frame (GlContext::swap_buffers) and sets the swap interval. The functions it returns are called through the types of nadir_sys::gl, which is unsafe; nadir-gfx does that, behind a safe API.
  • create_headless_gl makes a HeadlessGl, an OpenGL 3.3 core context that draws only offscreen, into render targets, with no window and no display server: for tests and golden images.
  • A thread has at most one OpenGL context, the window’s or a headless one, and it stays current there until it is dropped. A second fails with PlatformError::GlContextExists. Each context this crate makes has a GlContextId (GlContext::context_id), which says whether the context still exists, so that a user can keep the id in place of a borrow. The stand-in of Windows and macOS (below) has none.

§Audio

  • open_audio opens the default output device, as an AudioOutputConfig asks (48 kHz stereo, 30 ms of latency by default), and starts an audio thread that feeds it until the AudioStream it returns is dropped. AudioStream::latency is the device’s buffer, or None while there is no device.
  • The thread calls an AudioRender, given to open_audio, a period at a time: AudioRender::render fills it, and AudioRender::underrun hears of each time the device ran dry. It must not block, allocate, free or log, as nadir-audio’s mixer does not; a panic in it ends the stream.
  • A device that stops working, as one unplugged does, or that is not there at the start, is logged, and the thread renders on in time while it tries to open it again once a second, and logs when it has. It logs nothing else.
  • It needs no window: open it before Platform::new, or without one.

§The game’s files, errors and timing

  • user_dirs works out the folders for the game’s settings, saves and logs, as a UserDirs. It creates none of them. It rejects a studio or game name that some system would refuse as a folder name, on every system, so that a name that works on one works on all.
  • show_error_dialog tells the player about an error that stops the game: on stderr, and also in a message box on Windows and an alert on macOS.
  • precise_sleep blocks until an Instant, for a frame limiter. It sleeps, then spins through the last millisecond, and never returns early.

§Examples

Open a window and run until it is closed:

use std::time::{Duration, Instant};

use nadir_core::log::{debug, info};
use nadir_core::{Key, UVec2};
use nadir_platform::{Event, Platform, WindowConfig, precise_sleep};

let mut platform = Platform::new(&WindowConfig {
    title: "My game".to_string(),
    size: UVec2::new(640, 360),
    min_size: UVec2::ZERO,
    resizable: true,
    fullscreen: false,
    vsync: true,
})?;
// Frames to run while Windows drags the window, or macOS resizes it.
platform.set_modal_frame_callback(Box::new(|frame| {
    debug!("a modal frame at {}x{}", frame.size.x, frame.size.y);
}));
let mut events = Vec::new();
let mut fullscreen = false;
let mut next_frame = Instant::now();
'run: loop {
    events.clear();
    platform.pump_events(&mut events);
    for &event in &events {
        match event {
            Event::CloseRequested => break 'run,
            Event::Key { key: Key::F11, pressed: true, repeat: false } => {
                fullscreen = !fullscreen;
                platform.set_fullscreen(fullscreen);
            }
            Event::Resized(size) => info!("now {}x{} physical pixels", size.x, size.y),
            _ => {}
        }
    }
    next_frame += Duration::from_micros(16_667);
    precise_sleep(next_frame);
}

Draw offscreen, and ask the driver for its name through the GL function types of nadir-sys, which a program that does this depends on too:

use core::ffi::{CStr, c_void};
use core::mem;

use nadir_platform::{GlContext, create_headless_gl};
use nadir_sys::gl::{GL_RENDERER, PFNGLGETSTRINGPROC};

let gl = create_headless_gl()?;
let pointer = gl.get_proc_address(c"glGetString");
assert!(!pointer.is_null());
// SAFETY: the pointer is not null, and is `glGetString`, of this type.
let get_string =
    unsafe { mem::transmute::<*const c_void, PFNGLGETSTRINGPROC>(pointer) };
// SAFETY: the context is current on this thread, and takes this name.
let name = unsafe { get_string(GL_RENDERER) };
assert!(!name.is_null());
// SAFETY: the string is not null, ends with a NUL, and lives as long as
// the context.
let renderer = unsafe { CStr::from_ptr(name.cast()) };
nadir_core::log::info!("drawing with {}", renderer.to_string_lossy());

§Errors

Every call that can fail returns a PlatformError, whose message says what went wrong and, where the player can fix it, how: which library or function is missing, or that a Wayland session needs XWayland turned on. The calls that change the window, such as Platform::set_title, return nothing, and log what fails. PlatformError is #[non_exhaustive]: new kinds of error can join it.

§Threads

A Platform stays on the thread that opened it, and so does its OpenGL context. On macOS that must be the main thread: on any other, Platform::new fails with PlatformError::NotMainThread. A HeadlessGl is neither Send nor Sync.

open_audio starts a thread of its own, nadir-audio, which alone calls the AudioRender and the system’s audio functions. The AudioStream it returns is Send and Sync on every system, and can be opened and dropped on any thread.

§Counting allocations (feature dev)

With the dev feature, the global allocator of every binary that links this crate counts heap allocations, for each thread and for the whole process, so that tests can show that a steady frame allocates nothing. thread_alloc_counts and process_alloc_counts read the counts, as an AllocCounts, and AllocCounts::since takes the difference of two readings. No other crate in the binary may declare a global allocator. Turn dev on only from a [features] table or a [dev-dependencies] entry, so that no release build carries it. The counter sees only what goes through Rust’s allocator: C libraries that call malloc, such as Mesa and Xlib, are not counted.

use std::hint::black_box;

use nadir_platform::thread_alloc_counts;

let mut numbers: Vec<u32> = Vec::with_capacity(64);
let start = thread_alloc_counts();
for number in 0..64 {
    numbers.push(black_box(number));
}
// The pushes fit the capacity, so nothing was allocated.
assert_eq!(thread_alloc_counts().since(start).allocations, 0);

The headless-test feature is for the workspace’s own tests, which need an EGL driver with OpenGL 3.3 on Linux.

§Platforms

  • Linux, on X11: everything above. A Wayland session runs the window through XWayland. Xlib (libX11.so.6), EGL (libEGL.so.1) and ALSA (libasound.so.2) are loaded while the program runs, not linked, so that a machine without them gets PlatformError::LibraryNotFound or PlatformError::MissingSymbols. The window’s context and create_headless_gl are OpenGL 3.3 core through EGL; the headless one needs EGL_MESA_platform_surfaceless, which Mesa and NVIDIA have. The scale factor is read once, from Xft.dpi, when the window opens. Typed text comes from the X input method that XMODIFIERS names, or else Xlib’s own, which composes from the locale’s Compose file. Audio goes to ALSA’s default device, which PipeWire or PulseAudio usually provides. Gamepads are the kernel’s event devices in /dev/input, which the desktop’s udev rules open to the user at the seat, watched with inotify for pads plugged in; the drivers xpad, hid-playstation and hid-nintendo give the standard codes, and an Xbox pad over Bluetooth its own axes, which are read too.
  • Windows 10 and later: a Win32 window, aware of each monitor’s DPI, with borderless fullscreen. It builds and passes its tests in CI, and still awaits its checks by hand (roadmap task M1.5). It has no OpenGL context yet (M2.6): Platform::gpu_surface is a stand-in with no functions, whose swaps fail with PlatformError::Unsupported, and create_headless_gl returns that error. WindowConfig::vsync is ignored there for now, and open_audio returns PlatformError::Unsupported until M6.4. It reports no gamepads until M8.2.
  • macOS 12 and later: an AppKit window, whose fullscreen is the system’s own, in a Space of its own. It builds and passes its tests in CI, and still awaits its checks by hand (M1.6). It has no OpenGL context yet (M2.7): the same stand-in as on Windows, and vsync is ignored. Nor has it audio output yet (M6.5), nor gamepads (M8.3).
  • On any other system, Platform::new, user_dirs, create_headless_gl and open_audio return PlatformError::Unsupported.

Not built yet on any system: Metal (M10.1), showing a text being composed, noticing that the window was minimized, holding the pointer inside the window, and native Wayland. macOS has no input method for typed text yet.

Structs§

AllocCounts
Counts of heap use, on one thread or in the whole process.
AudioOutputConfig
What audio output to open, as open_audio takes it.
AudioStream
Audio output that is playing: an audio thread, and the device it fills.
GamepadId
Which gamepad an event is of.
GamepadState
What a gamepad’s buttons and axes are now, as the events reported so far leave them: see Platform::gamepad_state.
GlContextId
Names one of nadir-platform’s OpenGL contexts. No two contexts of a process get the same id.
HeadlessGl
An OpenGL 3.3 core context that draws only offscreen, into render targets, for tests and golden images. Make one with create_headless_gl.
ModalFrame
What a modal frame callback is told: see Platform::set_modal_frame_callback.
Platform
The game’s window and its connection to the operating system.
UserDirs
The folders where a game keeps what it writes, one set per game and user.
WindowConfig
What window to open.

Enums§

Event
Something that happened to the window or to an input device.
GpuSurface
What the GPU draws the window with, as Platform::gpu_surface gives it: for now always GpuSurface::Gl. Metal joins it on macOS later.
PlatformError
Errors produced by nadir-platform.

Traits§

AudioRender
What makes the sound: the audio thread calls it, as open_audio describes.
GlContext
An OpenGL context, and the way to its functions.

Functions§

create_headless_gl
Makes an OpenGL 3.3 core context that draws offscreen, with no window and no display server, and makes it current on this thread.
open_audio
Opens the default audio output device, and starts an audio thread that keeps it fed from render.
precise_sleep
Blocks the thread until until, and returns as soon after it as it can. It never returns before.
process_alloc_counts
The heap use of every thread since the process started.
show_error_dialog
Tells the player about an error that stops the game, such as a window that will not open. title names the game, and message says what went wrong.
thread_alloc_counts
The heap use of this thread since it started.
user_dirs
Finds the folders where the game game, made by studio, keeps its settings, saves and logs.