pane_ui 0.1.0

A RON-driven, hot-reloadable wgpu UI library with spring animations and consistent scaling
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
use std::collections::HashMap;
use std::path::Path;
use wgpu::util::DeviceExt;

// ── Constants ─────────────────────────────────────────────────────────────────

/// Minimum GIF frame delay in seconds.  Some encoders write 0 ms delays; this
/// clamps them to ~60 fps so a broken GIF does not busy-loop.
const MIN_FRAME_DELAY_SECS: f32 = 1.0 / 60.0;

// ── TextureId ─────────────────────────────────────────────────────────────────

/// Opaque handle to a texture (static or animated GIF) stored in [`TextureRegistry`].
///
/// Returned by [`TextureRegistry::load`] and [`TextureRegistry::load_gif`].
/// Pass it back to the registry to retrieve the current bind group, UV rect,
/// dimensions, or hidden state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TextureId(pub usize);

// ── GifMode ───────────────────────────────────────────────────────────────────

/// Controls what happens when an animated GIF reaches its last frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
pub enum GifMode {
    /// Restart from frame 0 and play indefinitely.
    Loop,
    /// Freeze on the last frame.
    Once,
    /// Freeze on the last frame and hide the widget (`is_hidden` returns `true`).
    OnceHide,
}

// ── UvRect ────────────────────────────────────────────────────────────────────

/// Normalised UV coordinates for a sub-region of a texture.
///
/// The registry does not use a texture atlas, so this is always [`UvRect::FULL`].
/// The type exists so callers can be written atlas-agnostically.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct UvRect {
    pub u_min: f32,
    pub v_min: f32,
    pub u_max: f32,
    pub v_max: f32,
}

impl UvRect {
    /// The full `[0, 1] × [0, 1]` UV range — no atlas sub-region.
    pub const FULL: Self = Self {
        u_min: 0.0,
        v_min: 0.0,
        u_max: 1.0,
        v_max: 1.0,
    };
}

// ── StoredTexture ─────────────────────────────────────────────────────────────

/// A single uploaded texture frame.
///
/// The prefixed fields (`_texture`, `_view`) are kept alive only for RAII
/// purposes — wgpu frees GPU memory when these values are dropped.  The bind
/// group is the only field actually used at draw time.
struct StoredTexture {
    /// Keeps the underlying GPU allocation alive.
    _texture: wgpu::Texture,
    /// Keeps the view alive; referenced by `bind_group`.
    _view: wgpu::TextureView,
    bind_group: wgpu::BindGroup,
    width: u32,
    height: u32,
}

// ── TextureKind ───────────────────────────────────────────────────────────────

/// Internal storage for one registry entry — either a static image or a GIF.
enum TextureKind {
    /// A single static frame.
    Static(StoredTexture),
    /// An animated GIF with per-frame timing state.
    Gif {
        frames: Vec<StoredTexture>,
        /// Per-frame display duration in seconds, parallel to `frames`.
        delays: Vec<f32>,
        /// Index of the currently displayed frame.
        current: usize,
        /// Seconds accumulated toward the next frame advance.
        timer: f32,
        mode: GifMode,
        /// `true` once a `Once`/`OnceHide` GIF has reached its last frame.
        done: bool,
    },
}

// ── TextureRegistry ───────────────────────────────────────────────────────────

/// GPU texture store.  Manages upload, animated GIF playback, and bind-group
/// lookup for use in draw calls.
///
/// Every path is deduplicated: a second call to `load("foo.png")` returns the
/// same [`TextureId`] as the first without re-uploading to the GPU.
///
/// All uploaded textures share a single bilinear [`wgpu::Sampler`]; samplers are
/// immutable in wgpu, so sharing is safe and avoids per-texture GPU object overhead.
pub struct TextureRegistry {
    entries: Vec<TextureKind>,
    /// Path → [`TextureId`] cache; prevents duplicate GPU uploads for the same file.
    path_cache: HashMap<String, TextureId>,
    /// Shared bilinear sampler reused by every uploaded texture.
    sampler: wgpu::Sampler,
    /// 1×1 white texture bind group returned when no real texture is bound.
    dummy_bind_group: wgpu::BindGroup,
    /// Texture bind group layout shared with the render pipeline.
    pub(crate) bind_group_layout: wgpu::BindGroupLayout,
}

impl TextureRegistry {
    /// Create a new registry, allocating the shared sampler, bind-group layout,
    /// and a 1×1 white dummy texture on `device`.
    pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Self {
        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("texture_bind_group_layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });

        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("texture_sampler"),
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            address_mode_w: wgpu::AddressMode::ClampToEdge,
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::MipmapFilterMode::Nearest,
            ..Default::default()
        });

        // 1×1 white pixel — used as the "no texture" sentinel in draw calls.
        let white_texture = device.create_texture_with_data(
            queue,
            &wgpu::TextureDescriptor {
                label: Some("dummy_white"),
                size: wgpu::Extent3d {
                    width: 1,
                    height: 1,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::Rgba8UnormSrgb,
                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                view_formats: &[],
            },
            wgpu::util::TextureDataOrder::LayerMajor,
            &[255u8, 255, 255, 255],
        );
        let white_view = white_texture.create_view(&wgpu::TextureViewDescriptor::default());
        let dummy_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("dummy_bind_group"),
            layout: &bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&white_view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&sampler),
                },
            ],
        });

        Self {
            entries: Vec::new(),
            path_cache: HashMap::new(),
            sampler,
            dummy_bind_group,
            bind_group_layout,
        }
    }

    /// Return the 1×1 white bind group used when a widget has no texture assigned.
    pub const fn dummy(&self) -> &wgpu::BindGroup {
        &self.dummy_bind_group
    }

    /// Load a static image from `path` and upload it to the GPU.
    ///
    /// If `path` was loaded before, returns the existing [`TextureId`] without
    /// re-uploading.  Supports any format recognised by the `image` crate.
    pub fn load(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        path: &str,
    ) -> Result<TextureId, String> {
        if let Some(&id) = self.path_cache.get(path) {
            return Ok(id);
        }
        let img = image::open(Path::new(path))
            .map_err(|e| format!("Failed to load image '{path}': {e}"))?
            .into_rgba8();
        let (width, height) = img.dimensions();
        let stored = self.upload(device, queue, path, width, height, &img.into_raw());
        let id = TextureId(self.entries.len());
        self.entries.push(TextureKind::Static(stored));
        self.path_cache.insert(path.to_string(), id);
        Ok(id)
    }

    /// Load an animated GIF from `path`, upload all frames to the GPU, and
    /// configure playback according to `mode`.
    ///
    /// If `path` was loaded before with the same call, returns the existing
    /// [`TextureId`].  All GIF frames must have identical dimensions; this is
    /// asserted at load time.
    pub fn load_gif(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        path: &str,
        mode: GifMode,
    ) -> Result<TextureId, String> {
        use image::AnimationDecoder;

        if let Some(&id) = self.path_cache.get(path) {
            return Ok(id);
        }

        let file =
            std::fs::File::open(path).map_err(|e| format!("Failed to open gif '{path}': {e}"))?;
        let decoder = image::codecs::gif::GifDecoder::new(std::io::BufReader::new(file))
            .map_err(|e| format!("Failed to decode gif '{path}': {e}"))?;
        let frames: Vec<image::Frame> = decoder
            .into_frames()
            .collect_frames()
            .map_err(|e| format!("Failed to collect gif frames '{path}': {e}"))?;

        if frames.is_empty() {
            return Err(format!("Gif '{path}' has no frames"));
        }

        // Assert all frames are the same size (the GIF spec allows variable-size
        // frames, but variable-size frames are not supported here).
        let (w0, h0) = frames[0].buffer().dimensions();
        for (i, frame) in frames.iter().enumerate().skip(1) {
            let (w, h) = frame.buffer().dimensions();
            assert!(
                w == w0 && h == h0,
                "[pane_ui] GIF '{path}' frame {i} is {w}×{h}, expected {w0}×{h0}"
            );
        }

        let mut stored_frames = Vec::with_capacity(frames.len());
        let mut delays = Vec::with_capacity(frames.len());

        for (i, frame) in frames.iter().enumerate() {
            let img = frame.buffer();
            let (width, height) = img.dimensions();
            let stored = self.upload(
                device,
                queue,
                &format!("{path}_frame{i}"),
                width,
                height,
                img.as_raw(),
            );
            stored_frames.push(stored);
            let (num, den) = frame.delay().numer_denom_ms();
            delays.push((num as f32 / den as f32 / 1000.0).max(MIN_FRAME_DELAY_SECS));
        }

        let id = TextureId(self.entries.len());
        self.entries.push(TextureKind::Gif {
            frames: stored_frames,
            delays,
            current: 0,
            timer: 0.0,
            mode,
            done: false,
        });
        self.path_cache.insert(path.to_string(), id);
        Ok(id)
    }

    /// Advance all animated GIFs by `dt` seconds, updating the current frame
    /// index.  Call once per frame before any draw calls.
    pub fn update(&mut self, dt: f32) {
        for entry in &mut self.entries {
            let TextureKind::Gif {
                frames,
                delays,
                current,
                timer,
                mode,
                done,
            } = entry
            else {
                continue;
            };
            if *done {
                continue;
            }

            *timer += dt;
            // Drain accumulated time in a loop so fast-forwarding (e.g. after a
            // hitch) lands on the correct frame rather than skipping at most one.
            loop {
                let delay = delays[*current];
                if *timer < delay {
                    break;
                }
                *timer -= delay;
                let next = *current + 1;
                if next >= frames.len() {
                    match mode {
                        GifMode::Loop => {
                            *current = 0;
                        }
                        GifMode::Once | GifMode::OnceHide => {
                            *current = frames.len() - 1;
                            *done = true;
                            break;
                        }
                    }
                } else {
                    *current = next;
                }
            }
        }
    }

    /// Reset a GIF to frame 0 and restart playback.  No-op for static textures.
    pub fn reset_gif(&mut self, id: TextureId) {
        if let TextureKind::Gif {
            current,
            timer,
            done,
            ..
        } = &mut self.entries[id.0]
        {
            *current = 0;
            *timer = 0.0;
            *done = false;
        }
    }

    /// Return the bind group for the current frame of `id`.
    pub fn current_bind_group(&self, id: TextureId) -> &wgpu::BindGroup {
        match &self.entries[id.0] {
            TextureKind::Static(t) => &t.bind_group,
            TextureKind::Gif {
                frames, current, ..
            } => &frames[*current].bind_group,
        }
    }

    /// Return the UV rect for `id`.
    ///
    /// Always [`UvRect::FULL`] — each texture (and each GIF frame) is its own
    /// GPU texture, so no atlas sub-region is needed.
    pub const fn current_uv_rect(_id: TextureId) -> UvRect {
        UvRect::FULL
    }

    /// Returns `true` if `id` is a [`GifMode::OnceHide`] GIF that has finished
    /// playing.  The widget should not be drawn in this state.
    pub fn is_hidden(&self, id: TextureId) -> bool {
        match &self.entries[id.0] {
            TextureKind::Gif { mode, done, .. } => *done && *mode == GifMode::OnceHide,
            TextureKind::Static(_) => false,
        }
    }

    /// Return the pixel dimensions `(width, height)` of `id`.
    ///
    /// For GIFs, returns the dimensions of frame 0 (all frames are guaranteed
    /// equal at load time).
    pub fn dimensions(&self, id: TextureId) -> (u32, u32) {
        match &self.entries[id.0] {
            TextureKind::Static(t) => (t.width, t.height),
            TextureKind::Gif { frames, .. } => (frames[0].width, frames[0].height),
        }
    }

    /// Upload raw RGBA bytes to the GPU and return a [`StoredTexture`].
    ///
    /// Uses the registry's shared sampler, so no per-texture sampler is created.
    fn upload(
        &self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        label: &str,
        width: u32,
        height: u32,
        rgba: &[u8],
    ) -> StoredTexture {
        let texture = device.create_texture_with_data(
            queue,
            &wgpu::TextureDescriptor {
                label: Some(label),
                size: wgpu::Extent3d {
                    width,
                    height,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::Rgba8UnormSrgb,
                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                view_formats: &[],
            },
            wgpu::util::TextureDataOrder::LayerMajor,
            rgba,
        );
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("texture_bind_group"),
            layout: &self.bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(&view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&self.sampler),
                },
            ],
        });
        StoredTexture {
            _texture: texture,
            _view: view,
            bind_group,
            width,
            height,
        }
    }
}

// ── TextureInfo trait ─────────────────────────────────────────────────────────

/// Trait for querying texture state without depending on a live GPU registry.
///
/// Implemented by both [`TextureRegistry`] (real GPU textures) and
/// [`DummyTextureRegistry`] (no-op, for headless / server mode).
pub trait TextureInfo {
    /// Returns `true` if the texture should not be rendered (a finished `OnceHide` GIF).
    fn is_hidden(&self, id: TextureId) -> bool;
    /// Returns the UV sub-rect for the current frame of `id`.
    fn current_uv_rect(&self, id: TextureId) -> UvRect;
}

impl TextureInfo for TextureRegistry {
    fn is_hidden(&self, id: TextureId) -> bool {
        self.is_hidden(id)
    }
    fn current_uv_rect(&self, id: TextureId) -> UvRect {
        Self::current_uv_rect(id)
    }
}

// ── DummyTextureRegistry ──────────────────────────────────────────────────────

/// A no-op [`TextureInfo`] implementation for headless / server mode.
///
/// Returns safe defaults for every query without touching the GPU.
#[derive(Default)]
pub struct DummyTextureRegistry;

impl DummyTextureRegistry {
    /// Create a `DummyTextureRegistry`.
    pub const fn new() -> Self {
        Self
    }
}

/// A `'static` reference to a [`DummyTextureRegistry`] for use as a fallback
/// when no real [`TextureRegistry`] is available (headless mode).
pub static DUMMY_TEX: DummyTextureRegistry = DummyTextureRegistry::new();

impl TextureInfo for DummyTextureRegistry {
    fn is_hidden(&self, _id: TextureId) -> bool {
        false
    }
    fn current_uv_rect(&self, _id: TextureId) -> UvRect {
        UvRect::FULL
    }
}