Skip to main content

ssplayer_wgpu/
host.rs

1//! A self-contained native host: owns a wgpu stack built from a raw window
2//! handle and drives **any number of** [`SSPlayer`]s with it.
3//!
4//! `Instance` / `Surface` / `Device` / `Queue` live here and the players borrow
5//! device and queue every frame. All of the wgpu work for the C face is in this
6//! module and the swapchain it shares with the web face (`surface.rs`), so
7//! `ffi.rs` stays pure ABI translation.
8//!
9//! It is plain Rust, so a Rust host that has a window handle rather than a winit
10//! `Window` can use it directly instead of assembling wgpu itself.
11//!
12//! **Players live here, behind [`PlayerId`]**, because the C face cannot hold a
13//! `&mut SSPlayer` across calls. `roster.rs` does that bookkeeping.
14
15use crate::player::SSPlayer;
16use crate::renderer::{Retention, SSRenderer, texture_extent_error};
17use crate::roster::{Roster, Slot};
18use crate::scene::{MaskBackend, SSScene, SceneConfig};
19use crate::surface::Swapchain;
20use std::sync::Arc;
21use std::sync::atomic::{AtomicBool, Ordering};
22
23/// Names one player owned by a [`NativeHost`].
24pub use crate::roster::SlotId as PlayerId;
25
26pub use crate::surface::STENCIL_FORMAT;
27
28/// How to build a [`NativeHost`].
29pub struct NativeHostConfig {
30    /// Backends the instance may use. `Backends::PRIMARY` lets wgpu choose.
31    pub backends: wgpu::Backends,
32    /// Drawable width in pixels.
33    pub width: u32,
34    /// Drawable height in pixels.
35    pub height: u32,
36    /// Clear colour, straight RGBA in 0..1.
37    pub clear_color: [f32; 4],
38    /// Allocate a depth/stencil buffer so mask parts rasterise.
39    pub enable_mask: bool,
40    /// Flip the projection to Y-down (screen coordinates).
41    pub y_down: bool,
42}
43
44/// A window-owning wgpu host and the players drawing into it.
45pub struct NativeHost {
46    players: Roster<SSPlayer>,
47    /// Device-scoped renderer. Owned here because the host owns the
48    /// device; **every player above shares this one** — one atlas upload and one
49    /// set of pipelines no matter how many characters are on screen.
50    renderer: SSRenderer,
51    /// One scene per window, drawing every player in `order`.
52    scene: SSScene,
53    /// The window's swapchain, with a stencil buffer unless built with
54    /// `enable_mask = false`.
55    swapchain: Swapchain,
56    device: wgpu::Device,
57    queue: wgpu::Queue,
58    clear_color: wgpu::Color,
59    y_down: bool,
60    /// Set by wgpu when the device is taken away.
61    device_lost: Arc<AtomicBool>,
62    /// Kept last: the instance must outlive the surface it created. It survives a
63    /// device loss, which is what lets `restore_device` ask it for a new adapter.
64    instance: wgpu::Instance,
65}
66
67/// Ask `instance` for an adapter able to present to `surface`.
68///
69/// macOS: `compatible_surface` deadlocks against AppKit on the main thread, so ask
70/// without it there and rely on the capability query that follows.
71fn request_adapter(instance: &wgpu::Instance, surface: &wgpu::Surface<'static>) -> Result<wgpu::Adapter, String> {
72    let compatible_surface = if cfg!(target_vendor = "apple") { None } else { Some(surface) };
73    pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::default(), compatible_surface, force_fallback_adapter: false, apply_limit_buckets: false }))
74        .map_err(|e| format!("no GPU adapter for the requested backend: {e}"))
75}
76
77/// Build a device+queue, and the flag wgpu raises if it is ever lost.
78///
79/// GPU timing has to be asked for here or never; an adapter
80/// without it still draws, only `stats()` goes quiet.
81fn request_device(adapter: &wgpu::Adapter) -> Result<(wgpu::Device, wgpu::Queue, Arc<AtomicBool>), String> {
82    let device_desc = wgpu::DeviceDescriptor { required_features: adapter.features() & wgpu::Features::TIMESTAMP_QUERY, ..Default::default() };
83    let (device, queue) = pollster::block_on(adapter.request_device(&device_desc)).map_err(|e| format!("request_device: {e}"))?;
84    let lost = Arc::new(AtomicBool::new(false));
85    let flag = Arc::clone(&lost);
86    device.set_device_lost_callback(move |_reason, _message| flag.store(true, Ordering::Relaxed));
87    Ok((device, queue, lost))
88}
89
90impl NativeHost {
91    /// Build the wgpu stack for `target` and a player matched to its surface.
92    ///
93    /// # Safety
94    /// `target` must describe a live window, view or layer that outlives the
95    /// returned host. On macOS this must be called from the main thread.
96    pub unsafe fn new(target: wgpu::SurfaceTargetUnsafe, config: &NativeHostConfig) -> Result<Self, String> {
97        let mut instance_desc = wgpu::InstanceDescriptor::new_without_display_handle();
98        instance_desc.backends = config.backends;
99        let instance = wgpu::Instance::new(instance_desc);
100
101        // SAFETY: forwarded from this function's contract.
102        let surface = unsafe { instance.create_surface_unsafe(target) }.map_err(|e| format!("create_surface: {e}"))?;
103
104        let adapter = request_adapter(&instance, &surface)?;
105        let (device, queue, device_lost) = request_device(&adapter)?;
106
107        let swapchain = Swapchain::new(&device, &adapter, surface, (config.width, config.height), None, config.enable_mask).ok_or("the adapter cannot present to this surface")?;
108        let renderer = SSRenderer::new(&device);
109        let mut scene = SSScene::new(&device, &SceneConfig { color_format: swapchain.format(), stencil_format: config.enable_mask.then_some(STENCIL_FORMAT), mask: if config.enable_mask { MaskBackend::Stencil } else { MaskBackend::None } });
110        let (width, height) = swapchain.size();
111        scene.set_viewport(&queue, width as f32, height as f32, config.y_down);
112
113        let c = config.clear_color;
114        Ok(Self { players: Roster::default(), renderer, scene, swapchain, device, queue, clear_color: wgpu::Color { r: c[0] as f64, g: c[1] as f64, b: c[2] as f64, a: c[3] as f64 }, y_down: config.y_down, device_lost, instance })
115    }
116
117    /// Add a player to this window and return its id.
118    ///
119    /// Players are cheap — no GPU resource of their own — so a window
120    /// holding a dozen characters costs one device, one renderer and one scene.
121    pub fn create_player(&mut self) -> PlayerId {
122        self.players.insert(SSPlayer::new())
123    }
124
125    /// Remove a player. Returns whether `id` named a live one; a stale id is a
126    /// no-op rather than a mistake made silently.
127    pub fn destroy_player(&mut self, id: PlayerId) -> bool {
128        // Its texture overrides live in the renderer, which outlives it.
129        if let Some(player) = self.players.get_mut(id) {
130            for key in player.override_keys() {
131                self.renderer.forget_texture(key);
132            }
133        }
134        self.players.remove(id)
135    }
136
137    /// The player `id` names, or `None` if it has been destroyed.
138    pub fn player_mut(&mut self, id: PlayerId) -> Option<&mut SSPlayer> {
139        self.players.get_mut(id)
140    }
141
142    /// How many players this window currently holds.
143    pub fn player_count(&self) -> usize {
144        self.players.len()
145    }
146
147    /// What the last frame cost.
148    pub fn stats(&self) -> crate::SceneStats {
149        self.scene.stats()
150    }
151
152    /// Why this window's device cannot hold a `width` x `height` texture, or
153    /// `None` when it can: empty, or past its `max_texture_dimension_2d`.
154    ///
155    /// What the C face asks before it hands a host's pixels over, so a texture
156    /// too large for the device comes back as an error code instead of one
157    /// [`NativeHost::upload_texture`] can only report on stderr.
158    pub fn texture_extent_error(&self, width: u32, height: u32) -> Option<String> {
159        texture_extent_error(&self.device, (width, height))
160    }
161
162    /// Register a texture for a reference-mode pack, lending the renderer this
163    /// host's device+queue. Shared by every player in the window.
164    ///
165    /// One the device cannot hold is not uploaded; see
166    /// [`SSRenderer::upload_texture`].
167    pub fn upload_texture(&mut self, hash: u32, rgba: &[u8], width: u32, height: u32) {
168        self.renderer.upload_texture(&self.device, &self.queue, hash, rgba, (width, height), Retention::Retain);
169    }
170
171    /// Register a texture from **encoded** image bytes (PNG), for hosts that have
172    /// no image decoder of their own — the C face's reference-mode path.
173    ///
174    /// The library already carries a PNG decoder for embedded packs,
175    /// so lending it out costs nothing and saves every C viewer from bringing
176    /// ImageIO / WIC / libpng along just to show a reference-mode `.ssab`. The
177    /// host still does the reading: nothing here opens a file.
178    pub fn upload_texture_encoded(&mut self, hash: u32, encoded: &[u8]) -> Result<(), String> {
179        let image = image::load_from_memory(encoded).map_err(|e| format!("decode image: {e}"))?;
180        let rgba = image.to_rgba8();
181        let (width, height) = rgba.dimensions();
182        if let Some(why) = self.texture_extent_error(width, height) {
183            return Err(why);
184        }
185        self.renderer.upload_texture(&self.device, &self.queue, hash, &rgba, (width, height), Retention::Retain);
186        Ok(())
187    }
188
189    /// Advance every player and build this frame's GPU buffers. Players are drawn
190    /// in ascending `order`, whatever order the slots happen to be in.
191    pub fn update(&mut self, delta_secs: f32) {
192        if self.is_device_lost() {
193            return;
194        }
195        self.scene.update_with(&mut self.renderer, &self.device, &self.queue, delta_secs, self.players.slots_mut(), Slot::value_mut);
196    }
197
198    /// Acquire the swapchain image, draw the prepared frame, and present.
199    ///
200    /// A lost/outdated/timed-out surface is absorbed by reconfiguring, and an
201    /// occluded one by waiting, skipping one frame either way; that is reported
202    /// as success.
203    pub fn render(&mut self) -> Result<(), String> {
204        if self.is_device_lost() {
205            return Ok(());
206        }
207        self.swapchain.render(&self.device, &self.queue, &mut self.renderer, &mut self.scene, self.clear_color, "ss-native frame").map_err(String::from)
208    }
209
210    /// Fade each player as one layer rather than part by part; see
211    /// [`SSScene::set_group_alpha`]. Kept across a device restore.
212    pub fn set_group_alpha(&mut self, on: bool) {
213        self.scene.set_group_alpha(on);
214    }
215
216    /// Whether players fade as one layer each.
217    pub fn group_alpha(&self) -> bool {
218        self.scene.group_alpha()
219    }
220
221    /// Resize the swapchain, the depth/stencil buffer and the projection to a new
222    /// drawable size in pixels. Zero in either dimension is ignored, and a size
223    /// past the device's `max_texture_dimension_2d` draws at that limit.
224    ///
225    /// While the device is lost only the size is recorded, and `restore_device`
226    /// applies it.
227    pub fn resize(&mut self, width: u32, height: u32) {
228        // A minimized window reports zero. Its last size stays configured until
229        // it comes back, rather than a 1 x 1 swapchain that matches no window;
230        // the web face, whose configure sizes the canvas, clamps instead.
231        if width == 0 || height == 0 {
232            return;
233        }
234        let lost = self.is_device_lost();
235        self.swapchain.resize(&self.device, width, height, lost);
236        if !lost {
237            let (width, height) = self.swapchain.size();
238            self.scene.set_viewport(&self.queue, width as f32, height as f32, self.y_down);
239        }
240    }
241
242    /// Whether the driver has taken the device away. While this is true
243    /// `update` / `render` / `resize` keep off the GPU.
244    pub fn is_device_lost(&self) -> bool {
245        self.device_lost.load(Ordering::Relaxed)
246    }
247
248    /// Rebuild the wgpu stack after a device loss and restore everything drawing
249    /// through it, resuming playback where it was interrupted.
250    ///
251    /// Errors if the GPU is gone for good, or if the replacement adapter cannot
252    /// present this window's format — the scene's pipelines are baked against it, so that case is a rebuild from [`NativeHost::new`].
253    pub fn restore_device(&mut self) -> Result<(), String> {
254        let adapter = request_adapter(&self.instance, self.swapchain.surface())?;
255        if !self.swapchain.presents_on(&adapter) {
256            return Err("the restored adapter cannot present this window's original surface format; rebuild the host".into());
257        }
258        let (device, queue, device_lost) = request_device(&adapter)?;
259
260        self.swapchain.restore(&device, &adapter);
261        // Widest scope first: a player re-registers its atlases into the renderer.
262        self.renderer.restore_device(&device, &queue);
263        self.scene.restore_device(&device, &queue);
264        for player in self.players.iter_mut() {
265            player.restore_textures(&mut self.renderer, &device, &queue);
266        }
267        // After the scene's own restore, which re-applies the viewport it last saw.
268        let (width, height) = self.swapchain.size();
269        self.scene.set_viewport(&queue, width as f32, height as f32, self.y_down);
270
271        self.device = device;
272        self.queue = queue;
273        self.device_lost = device_lost;
274        Ok(())
275    }
276}