Skip to main content

nadir_platform/
lib.rs

1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The OS layer of the Nadir engine: a window and its events, gamepads,
16//! OpenGL contexts, audio output, the user's folders, an error dialog and a
17//! precise sleep, with one safe API on Linux, Windows and macOS.
18//!
19//! # Where it fits
20//!
21//! This crate wraps the raw declarations of [`nadir_sys`], and is where the
22//! rest of Nadir meets the operating system, through one API that is the
23//! same on every system. `nadir-gfx` draws through its [`GlContext`],
24//! `nadir-input` reads its [`Event`]s, and `nadir_engine` opens the window
25//! with it and runs the main loop. A game reaches it through `nadir_engine`, which re-exports
26//! [`Event`] as `nadir::Event` and, with its own `dev` feature, the
27//! allocation counter. Depend on this crate directly for a window and its
28//! events without the rest of the engine.
29//!
30//! # The window
31//!
32//! - [`Platform::new`] opens the window that a [`WindowConfig`] describes:
33//!   its title, its size and smallest size in logical pixels, whether it can
34//!   be resized, whether it starts fullscreen, and vsync.
35//! - [`Platform::pump_events`] appends the [`Event`]s that arrived since the
36//!   last call, and does not wait for any. Call it once a frame.
37//! - [`Platform::window_size`] is the inside of the window in physical
38//!   pixels, and [`Platform::scale_factor`] the physical pixels a logical
39//!   one covers.
40//! - [`Platform::set_fullscreen`], [`Platform::set_title`] and
41//!   [`Platform::set_cursor_visible`] change the window.
42//! - [`Platform::set_modal_frame_callback`] sets what runs while the system
43//!   holds the event loop, and `pump_events` does not return: while Windows
44//!   drags or resizes the window, and while macOS resizes it. The callback
45//!   gets a [`ModalFrame`] with the size and the scale factor, so that the
46//!   game can run frames meanwhile. Linux never calls it.
47//!
48//! # Events
49//!
50//! An [`Event`] is something that happened to the window, to the keyboard
51//! and mouse, or to a gamepad (below), in the order the system reported it:
52//!
53//! - One [`Event::ScaleFactorChanged`] comes before any other event. On
54//!   Windows and macOS another comes each time the scale factor changes.
55//! - [`Event::CloseRequested`] leaves the window open: the game decides.
56//! - [`Event::Key`] names the physical key, a [`nadir_core::Key`], whatever
57//!   the keyboard layout, and says whether a press is a repeat.
58//! - [`Event::Text`] is a character typed, after the key press that typed
59//!   it: one a character, a composed one included, never a control
60//!   character, and none for a shortcut. On Linux it comes from an X input
61//!   method, on Windows from `WM_CHAR`, and on macOS from a key press's
62//!   `characters`.
63//! - [`Event::MouseMoved`] is in physical pixels from the top-left corner of
64//!   the inside of the window, with y growing downward, on every system.
65//!   [`Event::MouseWheel`] is in lines.
66//! - Right after [`Event::Focused`]`(false)`, every key and button that is
67//!   down gets a release, so nothing stays held while the window cannot see
68//!   it go up.
69//!
70//! # Gamepads
71//!
72//! - [`Platform::poll_gamepads`] appends what the gamepads did since the
73//!   last call, without waiting: call it once a frame, beside
74//!   `pump_events`. Its first call reports the pads already plugged in.
75//! - A pad plugged in is [`Event::GamepadConnected`], at rest; what is held
76//!   on it follows as events. A pad unplugged is put back at rest by events,
77//!   then [`Event::GamepadDisconnected`]. So the events alone give each
78//!   pad's state, which [`Platform::gamepad_state`] also gives, as a
79//!   [`GamepadState`].
80//! - A [`GamepadId`] is never given twice: a pad plugged in again is a new
81//!   one.
82//! - [`Event::GamepadButton`] names a [`nadir_core::GamepadButton`] by its
83//!   place on the pad, with the Xbox pad's names: `A` is the bottom face
84//!   button on every pad. [`Event::GamepadAxis`] gives a stick's axis from
85//!   -1 to 1, with +Y down, and a trigger from 0 to 1, raw: dead zones are
86//!   the input layer's.
87//! - Pads are read whether or not the window has the focus.
88//!
89//! # Drawing
90//!
91//! - [`Platform::gpu_surface`] gives what the GPU draws the window with: for
92//!   now always [`GpuSurface::Gl`], an OpenGL context current on the thread
93//!   that opened the window.
94//! - [`GlContext`] looks GL functions up ([`GlContext::get_proc_address`]),
95//!   shows a frame ([`GlContext::swap_buffers`]) and sets the swap interval.
96//!   The functions it returns are called through the types of
97//!   [`nadir_sys::gl`], which is `unsafe`; `nadir-gfx` does that, behind a
98//!   safe API.
99//! - [`create_headless_gl`] makes a [`HeadlessGl`], an OpenGL 3.3 core
100//!   context that draws only offscreen, into render targets, with no window
101//!   and no display server: for tests and golden images.
102//! - A thread has at most one OpenGL context, the window's or a headless
103//!   one, and it stays current there until it is dropped. A second fails
104//!   with [`PlatformError::GlContextExists`]. Each context this crate makes
105//!   has a [`GlContextId`] ([`GlContext::context_id`]), which says whether
106//!   the context still exists, so that a user can keep the id in place of a
107//!   borrow. The stand-in of Windows and macOS (below) has none.
108//!
109//! # Audio
110//!
111//! - [`open_audio`] opens the default output device, as an
112//!   [`AudioOutputConfig`] asks (48 kHz stereo, 30 ms of latency by
113//!   default), and starts an audio thread that feeds it until the
114//!   [`AudioStream`] it returns is dropped. [`AudioStream::latency`] is the
115//!   device's buffer, or `None` while there is no device.
116//! - The thread calls an [`AudioRender`], given to `open_audio`, a period
117//!   at a time: [`AudioRender::render`] fills it, and
118//!   [`AudioRender::underrun`] hears of each time the device ran dry. It
119//!   must not block, allocate, free or log, as `nadir-audio`'s mixer does
120//!   not; a panic in it ends the stream.
121//! - A device that stops working, as one unplugged does, or that is not
122//!   there at the start, is logged, and the thread renders on in time while
123//!   it tries to open it again once a second, and logs when it has. It logs
124//!   nothing else.
125//! - It needs no window: open it before [`Platform::new`], or without one.
126//!
127//! # The game's files, errors and timing
128//!
129//! - [`user_dirs`] works out the folders for the game's settings, saves and
130//!   logs, as a [`UserDirs`]. It creates none of them. It rejects a studio
131//!   or game name that some system would refuse as a folder name, on every
132//!   system, so that a name that works on one works on all.
133//! - [`show_error_dialog`] tells the player about an error that stops the
134//!   game: on stderr, and also in a message box on Windows and an alert on
135//!   macOS.
136//! - [`precise_sleep`] blocks until an [`Instant`](std::time::Instant), for
137//!   a frame limiter. It sleeps, then spins through the last millisecond,
138//!   and never returns early.
139//!
140//! # Examples
141//!
142//! Open a window and run until it is closed:
143//!
144//! ```no_run
145//! use std::time::{Duration, Instant};
146//!
147//! use nadir_core::log::{debug, info};
148//! use nadir_core::{Key, UVec2};
149//! use nadir_platform::{Event, Platform, WindowConfig, precise_sleep};
150//!
151//! let mut platform = Platform::new(&WindowConfig {
152//!     title: "My game".to_string(),
153//!     size: UVec2::new(640, 360),
154//!     min_size: UVec2::ZERO,
155//!     resizable: true,
156//!     fullscreen: false,
157//!     vsync: true,
158//! })?;
159//! // Frames to run while Windows drags the window, or macOS resizes it.
160//! platform.set_modal_frame_callback(Box::new(|frame| {
161//!     debug!("a modal frame at {}x{}", frame.size.x, frame.size.y);
162//! }));
163//! let mut events = Vec::new();
164//! let mut fullscreen = false;
165//! let mut next_frame = Instant::now();
166//! 'run: loop {
167//!     events.clear();
168//!     platform.pump_events(&mut events);
169//!     for &event in &events {
170//!         match event {
171//!             Event::CloseRequested => break 'run,
172//!             Event::Key { key: Key::F11, pressed: true, repeat: false } => {
173//!                 fullscreen = !fullscreen;
174//!                 platform.set_fullscreen(fullscreen);
175//!             }
176//!             Event::Resized(size) => info!("now {}x{} physical pixels", size.x, size.y),
177//!             _ => {}
178//!         }
179//!     }
180//!     next_frame += Duration::from_micros(16_667);
181//!     precise_sleep(next_frame);
182//! }
183//! # Ok::<(), nadir_platform::PlatformError>(())
184//! ```
185//!
186//! Draw offscreen, and ask the driver for its name through the GL function
187//! types of `nadir-sys`, which a program that does this depends on too:
188//!
189//! ```no_run
190//! use core::ffi::{CStr, c_void};
191//! use core::mem;
192//!
193//! use nadir_platform::{GlContext, create_headless_gl};
194//! use nadir_sys::gl::{GL_RENDERER, PFNGLGETSTRINGPROC};
195//!
196//! let gl = create_headless_gl()?;
197//! let pointer = gl.get_proc_address(c"glGetString");
198//! assert!(!pointer.is_null());
199//! // SAFETY: the pointer is not null, and is `glGetString`, of this type.
200//! let get_string =
201//!     unsafe { mem::transmute::<*const c_void, PFNGLGETSTRINGPROC>(pointer) };
202//! // SAFETY: the context is current on this thread, and takes this name.
203//! let name = unsafe { get_string(GL_RENDERER) };
204//! assert!(!name.is_null());
205//! // SAFETY: the string is not null, ends with a NUL, and lives as long as
206//! // the context.
207//! let renderer = unsafe { CStr::from_ptr(name.cast()) };
208//! nadir_core::log::info!("drawing with {}", renderer.to_string_lossy());
209//! # Ok::<(), nadir_platform::PlatformError>(())
210//! ```
211//!
212//! # Errors
213//!
214//! Every call that can fail returns a [`PlatformError`], whose message says
215//! what went wrong and, where the player can fix it, how: which library or
216//! function is missing, or that a Wayland session needs XWayland turned on.
217//! The calls that change the window, such as [`Platform::set_title`],
218//! return nothing, and log what fails. [`PlatformError`] is
219//! `#[non_exhaustive]`: new kinds of error can join it.
220//!
221//! # Threads
222//!
223//! A [`Platform`] stays on the thread that opened it, and so does its OpenGL
224//! context. On macOS that must be the main thread: on any other,
225//! [`Platform::new`] fails with [`PlatformError::NotMainThread`]. A
226//! [`HeadlessGl`] is neither `Send` nor `Sync`.
227//!
228//! [`open_audio`] starts a thread of its own, `nadir-audio`, which alone
229//! calls the [`AudioRender`] and the system's audio functions. The
230//! [`AudioStream`] it returns is `Send` and `Sync` on every system, and can
231//! be opened and dropped on any thread.
232//!
233//! # Counting allocations (feature `dev`)
234//!
235//! With the `dev` feature, the global allocator of every binary that links
236//! this crate counts heap allocations, for each thread and for the whole
237//! process, so that tests can show that a steady frame allocates nothing.
238//! `thread_alloc_counts` and `process_alloc_counts` read the counts, as an
239//! `AllocCounts`, and `AllocCounts::since` takes the difference of two
240//! readings. No other crate in the binary may declare a global allocator.
241//! Turn `dev` on only from a `[features]` table or a `[dev-dependencies]`
242//! entry, so that no release build carries it. The counter sees only what
243//! goes through Rust's allocator: C libraries that call `malloc`, such as
244//! Mesa and Xlib, are not counted.
245//!
246//! ```
247//! # #[cfg(feature = "dev")]
248//! # {
249//! use std::hint::black_box;
250//!
251//! use nadir_platform::thread_alloc_counts;
252//!
253//! let mut numbers: Vec<u32> = Vec::with_capacity(64);
254//! let start = thread_alloc_counts();
255//! for number in 0..64 {
256//!     numbers.push(black_box(number));
257//! }
258//! // The pushes fit the capacity, so nothing was allocated.
259//! assert_eq!(thread_alloc_counts().since(start).allocations, 0);
260//! # }
261//! ```
262//!
263//! The `headless-test` feature is for the workspace's own tests, which need
264//! an EGL driver with OpenGL 3.3 on Linux.
265//!
266//! # Platforms
267//!
268//! - **Linux**, on X11: everything above. A Wayland session runs the window
269//!   through XWayland. Xlib (`libX11.so.6`), EGL (`libEGL.so.1`) and ALSA
270//!   (`libasound.so.2`) are loaded while the program runs, not linked, so
271//!   that a machine without them gets [`PlatformError::LibraryNotFound`] or
272//!   [`PlatformError::MissingSymbols`]. The window's context and
273//!   [`create_headless_gl`] are OpenGL 3.3 core through EGL; the headless
274//!   one needs `EGL_MESA_platform_surfaceless`, which Mesa and NVIDIA have.
275//!   The scale factor is read once, from `Xft.dpi`, when the window opens.
276//!   Typed text comes from the X input method that `XMODIFIERS` names, or
277//!   else Xlib's own, which composes from the locale's Compose file.
278//!   Audio goes to ALSA's `default` device, which PipeWire or PulseAudio
279//!   usually provides. Gamepads are the kernel's event devices in
280//!   `/dev/input`, which the desktop's udev rules open to the user at the
281//!   seat, watched with `inotify` for pads plugged in; the drivers `xpad`,
282//!   `hid-playstation` and `hid-nintendo` give the standard codes, and an
283//!   Xbox pad over Bluetooth its own axes, which are read too.
284//! - **Windows** 10 and later: a Win32 window, aware of each monitor's DPI,
285//!   with borderless fullscreen. It builds and passes its tests in CI, and
286//!   still awaits its checks by hand (roadmap task M1.5). It has no OpenGL
287//!   context yet (M2.6): [`Platform::gpu_surface`] is a stand-in with no
288//!   functions, whose swaps fail with [`PlatformError::Unsupported`], and
289//!   [`create_headless_gl`] returns that error. [`WindowConfig::vsync`] is
290//!   ignored there for now, and [`open_audio`] returns
291//!   [`PlatformError::Unsupported`] until M6.4. It reports no gamepads until
292//!   M8.2.
293//! - **macOS** 12 and later: an AppKit window, whose fullscreen is the
294//!   system's own, in a Space of its own. It builds and passes its tests in
295//!   CI, and still awaits its checks by hand (M1.6). It has no OpenGL context
296//!   yet (M2.7): the same stand-in as on Windows, and `vsync` is ignored.
297//!   Nor has it audio output yet (M6.5), nor gamepads (M8.3).
298//! - On any other system, [`Platform::new`], [`user_dirs`],
299//!   [`create_headless_gl`] and [`open_audio`] return
300//!   [`PlatformError::Unsupported`].
301//!
302//! Not built yet on any system: Metal (M10.1), showing a text being
303//! composed, noticing that the window was minimized, holding the pointer
304//! inside the window, and native Wayland. macOS has no input method for
305//! typed text yet.
306
307// One of the three crates allowed to contain `unsafe` (AGENTS.md, rule 3). The
308// workspace denies `unsafe_code` everywhere else.
309#![allow(unsafe_code)]
310
311// The README's examples are compiled as doc tests too.
312#[cfg(doctest)]
313#[doc = include_str!("../README.md")]
314struct ReadmeDoctests;
315
316#[cfg(feature = "dev")]
317mod alloc_counter;
318mod audio;
319mod dialog;
320mod error;
321mod event;
322mod gamepad;
323mod gpu;
324mod paths;
325mod sleep;
326#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
327mod text;
328
329#[cfg(target_os = "linux")]
330mod linux;
331#[cfg(target_os = "macos")]
332mod macos;
333#[cfg(not(target_os = "linux"))]
334mod no_audio;
335#[cfg(not(target_os = "linux"))]
336mod no_gamepads;
337#[cfg(not(target_os = "linux"))]
338mod no_gl;
339#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
340mod unsupported;
341#[cfg(target_os = "windows")]
342mod windows;
343
344use nadir_core::UVec2;
345
346#[cfg(feature = "dev")]
347pub use alloc_counter::{AllocCounts, process_alloc_counts, thread_alloc_counts};
348pub use audio::{AudioOutputConfig, AudioRender, AudioStream, open_audio};
349pub use dialog::show_error_dialog;
350pub use error::PlatformError;
351pub use event::Event;
352pub use gamepad::{GamepadId, GamepadState};
353pub use gpu::{GlContext, GlContextId, GpuSurface, HeadlessGl, create_headless_gl};
354pub use paths::{UserDirs, user_dirs};
355pub use sleep::precise_sleep;
356
357#[cfg(target_os = "linux")]
358use linux::Backend;
359#[cfg(target_os = "linux")]
360use linux::Gamepads;
361#[cfg(target_os = "macos")]
362use macos::Backend;
363#[cfg(not(target_os = "linux"))]
364use no_gamepads::Gamepads;
365#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
366use unsupported::Backend;
367#[cfg(target_os = "windows")]
368use windows::Backend;
369
370/// What window to open.
371#[derive(Clone, Debug, PartialEq, Eq)]
372pub struct WindowConfig {
373    /// The text in the title bar.
374    pub title: String,
375    /// The size of the inside of the window, in logical pixels. The window
376    /// gets this many physical pixels times the scale factor.
377    pub size: UVec2,
378    /// The smallest size the user can give the window, in logical pixels. A
379    /// zero means no limit in that direction.
380    pub min_size: UVec2,
381    /// Whether the user can resize the window.
382    pub resizable: bool,
383    /// Whether the window starts fullscreen. Fullscreen is borderless: the
384    /// window covers the monitor, and the video mode does not change.
385    pub fullscreen: bool,
386    /// Whether a swap waits for the display's refresh, so that frames do not
387    /// tear: a swap interval of 1, or else 0. If the driver cannot do it, the
388    /// window opens anyway, and a warning is logged. See
389    /// [`GlContext::set_swap_interval`]. Windows and macOS ignore it for now.
390    pub vsync: bool,
391}
392
393/// What a modal frame callback is told: see
394/// [`Platform::set_modal_frame_callback`].
395#[derive(Clone, Copy, Debug, PartialEq)]
396pub struct ModalFrame {
397    /// The size of the inside of the window, in physical pixels.
398    pub size: UVec2,
399    /// The window's scale factor, as [`Platform::scale_factor`] gives it.
400    pub scale_factor: f32,
401}
402
403/// The game's window and its connection to the operating system.
404///
405/// It stays on the thread that created it. On Linux it holds that thread's
406/// OpenGL context, so the thread cannot have another (see [`GlContext`]).
407pub struct Platform {
408    backend: Backend,
409    gamepads: Gamepads,
410}
411
412impl Platform {
413    /// Opens the window.
414    ///
415    /// On Linux, it first sets the C library's character locale
416    /// (`LC_CTYPE`) from the environment, if it is still "C", which a Rust
417    /// program never changes: X's input methods type in it, and in "C" they
418    /// compose Latin-1 characters only. The locale is the whole process's,
419    /// and changing it races with another thread's C code that reads it
420    /// meanwhile, so open the window before starting threads that call such
421    /// code. A program that has set a locale of its own keeps it.
422    ///
423    /// # Errors
424    ///
425    /// Fails if this system has no backend, if there is no display server
426    /// to connect to, or if a system library is missing or too old. On
427    /// macOS it fails on any thread but the main one. On Linux it also fails
428    /// if the graphics driver cannot make an OpenGL 3.3 core context for the
429    /// window, or if this thread already has an OpenGL context.
430    pub fn new(config: &WindowConfig) -> Result<Self, PlatformError> {
431        Ok(Self {
432            backend: Backend::new(config)?,
433            gamepads: Gamepads::new(),
434        })
435    }
436
437    /// Appends the events that arrived since the last call to `out`. Does
438    /// not wait for any.
439    pub fn pump_events(&mut self, out: &mut Vec<Event>) {
440        self.backend.pump_events(out);
441    }
442
443    /// Appends what happened to the gamepads since the last call to `out`:
444    /// pads plugged in and unplugged, and their buttons and axes. Does not
445    /// wait for any. Call it once a frame, beside
446    /// [`Platform::pump_events`].
447    ///
448    /// The first call reports the pads that are already plugged in: each one
449    /// [`Event::GamepadConnected`], at rest, then what is held on it. A pad
450    /// unplugged is put back at rest by events of their own before its
451    /// [`Event::GamepadDisconnected`], so that the events alone always give
452    /// each pad's state. Pads are read whether or not the window has the
453    /// focus.
454    ///
455    /// Linux reads the kernel's event devices, and needs read access to the
456    /// gamepads' nodes in `/dev/input`, which the desktop's udev rules
457    /// normally give the user at the seat. Windows (roadmap task M8.2) and
458    /// macOS (M8.3) report no pads yet.
459    pub fn poll_gamepads(&mut self, out: &mut Vec<Event>) {
460        self.gamepads.poll(out);
461    }
462
463    /// What the pad's buttons and axes are, as the events reported so far
464    /// leave them, while it is plugged in. `None` for a pad that was
465    /// unplugged, or never reported.
466    pub fn gamepad_state(&self, id: GamepadId) -> Option<&GamepadState> {
467        self.gamepads.state(id)
468    }
469
470    /// The size of the inside of the window, in physical pixels.
471    pub fn window_size(&self) -> UVec2 {
472        self.backend.window_size()
473    }
474
475    /// How many physical pixels one logical pixel covers: 1.0 on a standard
476    /// display, 2.0 on one of twice the density.
477    pub fn scale_factor(&self) -> f32 {
478        self.backend.scale_factor()
479    }
480
481    /// Enters or leaves borderless fullscreen.
482    pub fn set_fullscreen(&mut self, on: bool) {
483        self.backend.set_fullscreen(on);
484    }
485
486    /// Changes the text in the title bar.
487    pub fn set_title(&mut self, title: &str) {
488        self.backend.set_title(title);
489    }
490
491    /// Shows or hides the pointer while it is over the window.
492    pub fn set_cursor_visible(&mut self, visible: bool) {
493        self.backend.set_cursor_visible(visible);
494    }
495
496    /// Sets what to call while the operating system runs an event loop of
497    /// its own, and [`Platform::pump_events`] therefore does not return:
498    /// while the user drags or resizes the window on Windows, or resizes it
499    /// on macOS. It is called every 10 to 16 ms on Windows, and on macOS
500    /// once for each step of the resize, so that the game can run frames.
501    /// It replaces any callback set before.
502    ///
503    /// The events of that time come from the next pump, after the loop.
504    /// On Linux there is no such loop, and the callback is never called.
505    pub fn set_modal_frame_callback(&mut self, callback: Box<dyn FnMut(ModalFrame)>) {
506        self.backend.set_modal_frame_callback(callback);
507    }
508
509    /// What the GPU draws the window with. On Linux it is the window's
510    /// OpenGL context, current on this thread. On Windows and macOS, for
511    /// now, it is a context with no functions, whose swaps fail with
512    /// [`PlatformError::Unsupported`].
513    pub fn gpu_surface(&self) -> GpuSurface<'_> {
514        self.backend.gpu_surface()
515    }
516}