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
Platform::newopens the window that aWindowConfigdescribes: its title, its size and smallest size in logical pixels, whether it can be resized, whether it starts fullscreen, and vsync.Platform::pump_eventsappends theEvents that arrived since the last call, and does not wait for any. Call it once a frame.Platform::window_sizeis the inside of the window in physical pixels, andPlatform::scale_factorthe physical pixels a logical one covers.Platform::set_fullscreen,Platform::set_titleandPlatform::set_cursor_visiblechange the window.Platform::set_modal_frame_callbacksets what runs while the system holds the event loop, andpump_eventsdoes not return: while Windows drags or resizes the window, and while macOS resizes it. The callback gets aModalFramewith the size and the scale factor, so that the game can run frames meanwhile. Linux never calls it.
§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::ScaleFactorChangedcomes before any other event. On Windows and macOS another comes each time the scale factor changes. Event::CloseRequestedleaves the window open: the game decides.Event::Keynames the physical key, anadir_core::Key, whatever the keyboard layout, and says whether a press is a repeat.Event::Textis 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 fromWM_CHAR, and on macOS from a key press’scharacters.Event::MouseMovedis in physical pixels from the top-left corner of the inside of the window, with y growing downward, on every system.Event::MouseWheelis 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
Platform::poll_gamepadsappends what the gamepads did since the last call, without waiting: call it once a frame, besidepump_events. Its first call reports the pads already plugged in.- A pad plugged in is
Event::GamepadConnected, at rest; what is held on it follows as events. A pad unplugged is put back at rest by events, thenEvent::GamepadDisconnected. So the events alone give each pad’s state, whichPlatform::gamepad_statealso gives, as aGamepadState. - A
GamepadIdis never given twice: a pad plugged in again is a new one. Event::GamepadButtonnames anadir_core::GamepadButtonby its place on the pad, with the Xbox pad’s names:Ais the bottom face button on every pad.Event::GamepadAxisgives a stick’s axis from -1 to 1, with +Y down, and a trigger from 0 to 1, raw: dead zones are the input layer’s.- Pads are read whether or not the window has the focus.
§Drawing
Platform::gpu_surfacegives what the GPU draws the window with: for now alwaysGpuSurface::Gl, an OpenGL context current on the thread that opened the window.GlContextlooks 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 ofnadir_sys::gl, which isunsafe;nadir-gfxdoes that, behind a safe API.create_headless_glmakes aHeadlessGl, 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 aGlContextId(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_audioopens the default output device, as anAudioOutputConfigasks (48 kHz stereo, 30 ms of latency by default), and starts an audio thread that feeds it until theAudioStreamit returns is dropped.AudioStream::latencyis the device’s buffer, orNonewhile there is no device.- The thread calls an
AudioRender, given toopen_audio, a period at a time:AudioRender::renderfills it, andAudioRender::underrunhears of each time the device ran dry. It must not block, allocate, free or log, asnadir-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_dirsworks out the folders for the game’s settings, saves and logs, as aUserDirs. 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_dialogtells 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_sleepblocks until anInstant, 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 getsPlatformError::LibraryNotFoundorPlatformError::MissingSymbols. The window’s context andcreate_headless_glare OpenGL 3.3 core through EGL; the headless one needsEGL_MESA_platform_surfaceless, which Mesa and NVIDIA have. The scale factor is read once, fromXft.dpi, when the window opens. Typed text comes from the X input method thatXMODIFIERSnames, or else Xlib’s own, which composes from the locale’s Compose file. Audio goes to ALSA’sdefaultdevice, 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 withinotifyfor pads plugged in; the driversxpad,hid-playstationandhid-nintendogive 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_surfaceis a stand-in with no functions, whose swaps fail withPlatformError::Unsupported, andcreate_headless_glreturns that error.WindowConfig::vsyncis ignored there for now, andopen_audioreturnsPlatformError::Unsupporteduntil 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
vsyncis ignored. Nor has it audio output yet (M6.5), nor gamepads (M8.3). - On any other system,
Platform::new,user_dirs,create_headless_glandopen_audioreturnPlatformError::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§
- Alloc
Counts - Counts of heap use, on one thread or in the whole process.
- Audio
Output Config - What audio output to open, as
open_audiotakes it. - Audio
Stream - Audio output that is playing: an audio thread, and the device it fills.
- Gamepad
Id - Which gamepad an event is of.
- Gamepad
State - What a gamepad’s buttons and axes are now, as the events reported so far
leave them: see
Platform::gamepad_state. - GlContext
Id - Names one of
nadir-platform’s OpenGL contexts. No two contexts of a process get the same id. - Headless
Gl - An OpenGL 3.3 core context that draws only offscreen, into render
targets, for tests and golden images. Make one with
create_headless_gl. - Modal
Frame - 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.
- User
Dirs - The folders where a game keeps what it writes, one set per game and user.
- Window
Config - 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_surfacegives it: for now alwaysGpuSurface::Gl. Metal joins it on macOS later. - Platform
Error - Errors produced by
nadir-platform.
Traits§
- Audio
Render - What makes the sound: the audio thread calls it, as
open_audiodescribes. - 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.
titlenames the game, andmessagesays 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 bystudio, keeps its settings, saves and logs.