zaxis 0.0.5

An event-driven immediate mode GUI for desktop tools
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
//! Versioned uploads, shared allocations, independent samplers, managed LRU.
use super::{diagnostics::RendererStage, gpu::Gpu, RenderError, Renderer};
use crate::{DrawData, TextureFilter, TextureId};
use std::{
    collections::HashMap,
    sync::{Arc, Weak},
};

pub struct GpuTexture {
    pub(super) texture: wgpu::Texture,
    pub bind_group: wgpu::BindGroup,
    pub(super) size: [u32; 2],
    pub(super) revision: u64,
    pub(super) filter: TextureFilter,
    pub(super) managed: bool,
    pub(super) last_used: u64,
    pub(super) allocation: u64,
    pub(super) pixels: Weak<Vec<u8>>,
}
/// GPU textures shared by a renderer and its siblings.
pub(super) struct TextureStore {
    pub(super) textures: HashMap<TextureId, GpuTexture>,
    /// Producer of the last frame; a change discards textures unless `shared`.
    pub(super) source: Option<u64>,
    /// Sibling renderers present contexts that allocate IDs from one allocator, so a
    /// change of producer must keep the textures.
    pub(super) shared: bool,
    /// Advances once per presented frame; orders least-recently-used eviction.
    pub(super) clock: u64,
    /// Last allocation number handed to a created texture; unique across siblings.
    pub(super) allocations: u64,
}

impl TextureStore {
    pub(super) fn new(white: GpuTexture) -> Self {
        Self {
            textures: HashMap::from([(TextureId::WHITE, white)]),
            source: None,
            shared: false,
            clock: 0,
            allocations: 0,
        }
    }
}

pub fn create_bindings(device: &wgpu::Device) -> (wgpu::BindGroupLayout, wgpu::Sampler) {
    let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: Some("zaxis texture 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("zaxis linear sampler"),
        mag_filter: wgpu::FilterMode::Linear,
        min_filter: wgpu::FilterMode::Linear,
        ..Default::default()
    });
    (layout, sampler)
}
pub fn nearest_sampler(device: &wgpu::Device) -> wgpu::Sampler {
    device.create_sampler(&wgpu::SamplerDescriptor {
        label: Some("zaxis nearest sampler"),
        ..Default::default()
    })
}
impl Gpu {
    pub(super) fn prepare_textures(
        &mut self,
        store: &mut TextureStore,
        data: &DrawData,
    ) -> Result<(), RenderError> {
        if !store.shared && store.source != Some(data.source) {
            store.textures.retain(|id, _| *id == TextureId::WHITE);
        }
        store.source = Some(data.source);
        let active: std::collections::HashSet<_> =
            data.commands.iter().map(|c| c.texture).collect();
        let limit = self.device.limits().max_texture_dimension_2d;
        let mut payloads = std::collections::HashSet::new();
        let mut allocations = std::collections::HashSet::new();
        let mut active_bytes = 0u64;
        for image in &data.textures {
            if image.id == TextureId::WHITE
                || !payloads.insert(image.id)
                || image.size.contains(&0)
                || image.size.iter().any(|s| *s > limit)
                || image.pixels.len() as u64
                    != u64::from(image.size[0]) * u64::from(image.size[1]) * 4
            {
                return Err(RenderError::Texture(format!(
                    "invalid texture {:?}, dimensions {:?}, device limit {limit}",
                    image.id, image.size
                )));
            }
            if active.contains(&image.id)
                && data
                    .texture_options
                    .get(&image.id)
                    .is_some_and(|o| o.managed)
                && allocations.insert((Arc::as_ptr(&image.pixels), image.size, image.revision))
            {
                active_bytes += image.pixels.len() as u64;
            }
        }
        if active
            .iter()
            .any(|id| *id != TextureId::WHITE && !payloads.contains(id))
        {
            return Err(RenderError::InvalidDrawData(
                "complete texture payload required for every referenced ID",
            ));
        }
        if active_bytes > data.texture_budget_bytes {
            return Err(RenderError::Texture(format!(
                "visible image set needs {active_bytes} bytes, GPU budget is {}",
                data.texture_budget_bytes
            )));
        }
        if active
            .iter()
            .filter(|id| data.texture_options.get(id).is_some_and(|o| o.managed))
            .count()
            > data.texture_binding_budget
        {
            return Err(RenderError::Texture(
                "visible image bindings exceed binding budget".into(),
            ));
        }
        self.evict_images(
            store,
            data.texture_budget_bytes.saturating_sub(active_bytes),
            &active,
        );
        for image in &data.textures {
            let options = data
                .texture_options
                .get(&image.id)
                .copied()
                .unwrap_or_default();
            if options.managed && !active.contains(&image.id) {
                continue;
            }
            let lookup = self.diagnostics.start();
            let cached = store
                .textures
                .get(&image.id)
                .is_some_and(|t| t.size == image.size && t.revision == image.revision);
            self.diagnostics.end(RendererStage::TextureLookup, lookup);
            let sampler = if options.filter == TextureFilter::Nearest {
                &self.nearest_sampler
            } else {
                &self.sampler
            };
            if cached {
                let t = store.textures.get_mut(&image.id).unwrap();
                if t.filter != options.filter {
                    t.bind_group = binding(
                        &self.device,
                        &self.texture_layout,
                        sampler,
                        &t.texture,
                        &mut self.diagnostics,
                    );
                    t.filter = options.filter;
                }
                t.managed = options.managed;
                t.last_used = store.clock;
                continue;
            }
            let shared = store
                .textures
                .iter()
                .find(|(id, t)| {
                    **id != image.id
                        && t.size == image.size
                        && t.revision == image.revision
                        && t.pixels
                            .upgrade()
                            .is_some_and(|p| Arc::ptr_eq(&p, &image.pixels))
                })
                .map(|(_, t)| (t.texture.clone(), t.allocation));
            let mut gpu = if let Some((texture, allocation)) = shared {
                GpuTexture {
                    bind_group: binding(
                        &self.device,
                        &self.texture_layout,
                        sampler,
                        &texture,
                        &mut self.diagnostics,
                    ),
                    texture,
                    size: image.size,
                    revision: image.revision,
                    filter: options.filter,
                    managed: options.managed,
                    last_used: store.clock,
                    allocation,
                    pixels: Arc::downgrade(&image.pixels),
                }
            } else {
                let reusable = store
                    .textures
                    .get(&image.id)
                    .filter(|t| t.size == image.size)
                    .is_some_and(|t| {
                        store
                            .textures
                            .values()
                            .filter(|o| o.allocation == t.allocation)
                            .count()
                            == 1
                    });
                let gpu = if reusable {
                    let mut t = store.textures.remove(&image.id).unwrap();
                    let start = self.diagnostics.start();
                    write_texture(&self.queue, &t.texture, image.size, &image.pixels);
                    self.diagnostics.end(RendererStage::WriteTextureCpu, start);
                    if t.filter != options.filter {
                        t.bind_group = binding(
                            &self.device,
                            &self.texture_layout,
                            sampler,
                            &t.texture,
                            &mut self.diagnostics,
                        );
                    }
                    t.revision = image.revision;
                    self.stats.texture_reuploads += 1;
                    t
                } else {
                    self.stats.texture_creations += 1;
                    store.allocations += 1;
                    let mut t = create_texture_profiled(
                        &self.device,
                        &self.queue,
                        &self.texture_layout,
                        sampler,
                        image.size,
                        &image.pixels,
                        image.revision,
                        &mut self.diagnostics,
                    );
                    t.allocation = store.allocations;
                    t
                };
                self.stats.texture_uploads += 1;
                self.stats.texture_upload_bytes += image.pixels.len() as u64;
                gpu
            };
            gpu.pixels = Arc::downgrade(&image.pixels);
            gpu.filter = options.filter;
            gpu.managed = options.managed;
            gpu.last_used = store.clock;
            store.textures.insert(image.id, gpu);
        }
        while store.textures.values().filter(|t| t.managed).count() > data.texture_binding_budget {
            let id = store
                .textures
                .iter()
                .filter(|(id, t)| t.managed && !active.contains(id))
                .min_by_key(|(id, t)| (t.last_used, id.0))
                .map(|(&id, _)| id);
            let Some(id) = id else {
                break;
            };
            store.textures.remove(&id);
            self.stats.texture_evictions += 1;
        }
        self.stats.image_resident_bytes_estimate = image_bytes(store);
        Ok(())
    }
    fn evict_images(
        &mut self,
        store: &mut TextureStore,
        budget: u64,
        active: &std::collections::HashSet<TextureId>,
    ) {
        loop {
            let is_idle = |t: &GpuTexture| {
                t.managed
                    && !store
                        .textures
                        .iter()
                        .any(|(id, o)| active.contains(id) && o.allocation == t.allocation)
            };
            let mut seen = std::collections::HashSet::new();
            let idle_bytes: u64 = store
                .textures
                .values()
                .filter(|t| is_idle(t) && seen.insert(t.allocation))
                .map(|t| u64::from(t.size[0]) * u64::from(t.size[1]) * 4)
                .sum();
            if idle_bytes <= budget {
                break;
            }
            let allocation = store
                .textures
                .iter()
                .filter(|(_, t)| is_idle(t))
                .min_by_key(|(id, t)| (t.last_used, id.0))
                .map(|(_, t)| t.allocation);
            let Some(allocation) = allocation else {
                break;
            };
            store
                .textures
                .retain(|_, t| !t.managed || t.allocation != allocation);
            self.stats.texture_evictions += 1;
        }
    }
}
impl Gpu {
    /// Drop every managed image texture, including those used by sibling renderers.
    pub(super) fn clear_image_textures(&mut self) {
        let mut allocations = std::collections::HashSet::new();
        self.store
            .lock()
            .expect("texture store mutex")
            .textures
            .retain(|_, t| {
                if t.managed {
                    allocations.insert(t.allocation);
                    false
                } else {
                    true
                }
            });
        self.stats.texture_evictions += allocations.len() as u64;
        self.stats.image_resident_bytes_estimate = 0;
    }
}

impl Renderer {
    /// Drop every managed image texture, including those used by sibling renderers.
    pub fn clear_image_textures(&mut self) {
        self.gpu.clear_image_textures();
    }
    pub fn max_texture_dimension_2d(&self) -> u32 {
        self.gpu.device.limits().max_texture_dimension_2d
    }
}
fn image_bytes(store: &TextureStore) -> u64 {
    let mut seen = std::collections::HashSet::new();
    store
        .textures
        .values()
        .filter(|t| t.managed && seen.insert(t.allocation))
        .map(|t| u64::from(t.size[0]) * u64::from(t.size[1]) * 4)
        .sum()
}
pub(super) fn binding(
    device: &wgpu::Device,
    layout: &wgpu::BindGroupLayout,
    sampler: &wgpu::Sampler,
    texture: &wgpu::Texture,
    diagnostics: &mut super::diagnostics::Diagnostics,
) -> wgpu::BindGroup {
    let start = diagnostics.start();
    let view = texture.create_view(&Default::default());
    diagnostics.end(RendererStage::CreateViewCpu, start);
    let start = diagnostics.start();
    let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
        label: Some("zaxis texture binding"),
        layout,
        entries: &[
            wgpu::BindGroupEntry {
                binding: 0,
                resource: wgpu::BindingResource::TextureView(&view),
            },
            wgpu::BindGroupEntry {
                binding: 1,
                resource: wgpu::BindingResource::Sampler(sampler),
            },
        ],
    });
    diagnostics.end(RendererStage::CreateBindGroupCpu, start);
    group
}
pub fn create_texture(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    layout: &wgpu::BindGroupLayout,
    sampler: &wgpu::Sampler,
    size: [u32; 2],
    pixels: &[u8],
    revision: u64,
) -> GpuTexture {
    create_texture_profiled(
        device,
        queue,
        layout,
        sampler,
        size,
        pixels,
        revision,
        &mut Default::default(),
    )
}
mod upload;
use upload::create_texture_profiled;
pub(super) use upload::write_texture;