Skip to main content

crcbl_frame/ui_pass/
textures.rs

1//! What a [`DrawList::texture`](crcbl_ui::DrawList::texture) rectangle needs
2//! from the UI pass: the caller's pairing of each [`TextureId`] with a graph
3//! image, the split of a half's indices into one draw per bind, and the set-1
4//! bind groups those draws name.
5
6use core::ops::Range;
7use std::sync::{Mutex, PoisonError};
8
9use crcbl_hal::{
10    BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutHandle, BindingResource, Device,
11    ImageViewHandle,
12};
13use crcbl_ui::draw_list::TextureRun;
14use crcbl_ui::image::TextureId;
15
16use crate::graph::ImageId;
17
18/// One texture a frame's draw list names, as the render graph knows it — what
19/// [`UiRenderer::add_passes_with_textures`](super::UiRenderer::add_passes_with_textures)
20/// takes.
21///
22/// `image` is any image in the same graph that a fragment shader can sample
23/// as filterable float: a secondary view's target, the target a primary camera
24/// drew into, an imported texture. The UI pass declares that it reads it, so
25/// the graph puts the barrier between it and the passes that drew it, and the
26/// caller declares nothing. Those passes are added first: the graph runs passes
27/// in the order they were declared.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub struct UiTexture {
30    /// The name the draw list used.
31    pub id: TextureId,
32    /// The image it stands for this frame.
33    pub image: ImageId,
34}
35
36/// One draw of a half: an index range, and the texture its set 1 binds — or
37/// `None` for the transparent placeholder every range but a texture run binds.
38#[derive(Clone, Debug, PartialEq, Eq)]
39pub(super) struct Draw {
40    pub(super) indices: Range<u32>,
41    pub(super) texture: Option<TextureId>,
42}
43
44/// Splits `segment` into the draws that record it: every [`TextureRun`] inside
45/// it is a draw of its own, and each stretch between two runs is one draw.
46///
47/// Runs never straddle the overlay cut (see
48/// [`Triangles::textures`](crcbl_ui::draw_list::Triangles::textures)), so a
49/// run is either inside a half or outside it; one reaching past `segment`
50/// anyway is clamped to it rather than drawn out of range.
51pub(super) fn draws(segment: Range<u32>, runs: &[TextureRun]) -> Vec<Draw> {
52    let mut draws = Vec::new();
53    let mut cursor = segment.start;
54    for run in runs {
55        let start = run.indices.start.max(segment.start);
56        let end = run.indices.end.min(segment.end);
57        if start >= end {
58            continue;
59        }
60        if cursor < start {
61            draws.push(Draw {
62                indices: cursor..start,
63                texture: None,
64            });
65        }
66        draws.push(Draw {
67            indices: start..end,
68            texture: Some(run.texture),
69        });
70        cursor = end;
71    }
72    if cursor < segment.end {
73        draws.push(Draw {
74            indices: cursor..segment.end,
75            texture: None,
76        });
77    }
78    draws
79}
80
81/// The image `id` stands for, the first pairing in `textures` that names it.
82pub(super) fn image_of(textures: &[UiTexture], id: TextureId) -> Option<ImageId> {
83    textures
84        .iter()
85        .find(|texture| texture.id == id)
86        .map(|texture| texture.image)
87}
88
89/// One set-1 group, and whether a frame recorded through its slot used it.
90#[derive(Debug)]
91struct Cached {
92    view: ImageViewHandle,
93    group: BindGroupHandle,
94    used: bool,
95}
96
97/// The set-1 groups naming the textures frames sampled, per frame in flight.
98///
99/// **Kept rather than rebuilt**: a view that samples the same target every
100/// frame writes one descriptor when the target is (re)made, not one a frame.
101/// A group is released on its slot's next turn after a frame that did not use
102/// it, which is the same rotation that keeps the vertex ring safe: by then the
103/// last frame that bound it has finished.
104///
105/// Behind a [`Mutex`] because the pass bodies that fill it borrow the renderer
106/// shared — [`UiRenderer::add_passes`](super::UiRenderer::add_passes) takes
107/// `&self`, as every caller has always called it.
108#[derive(Debug)]
109pub(super) struct TextureGroups {
110    slots: Mutex<Vec<Vec<Cached>>>,
111}
112
113impl TextureGroups {
114    pub(super) fn new(frames: usize) -> Self {
115        Self {
116            slots: Mutex::new((0..frames).map(|_| Vec::new()).collect()),
117        }
118    }
119
120    /// Begins `slot`'s turn: releases every group the slot's last frame did not
121    /// use, and marks the rest unused until this frame uses them.
122    pub(super) fn retire(&mut self, device: &dyn Device, slot: usize) {
123        let slots = self.slots.get_mut().unwrap_or_else(PoisonError::into_inner);
124        slots[slot].retain_mut(|cached| {
125            if !cached.used {
126                device.destroy_bind_group(cached.group);
127            }
128            let kept = cached.used;
129            cached.used = false;
130            kept
131        });
132    }
133
134    /// The group binding `view` for a frame in `slot`, built on first use.
135    ///
136    /// [`None`] when the device refused it, logged: the draw is skipped, as
137    /// `crcbl_render::bind_group_cache`'s groups skip theirs.
138    pub(super) fn group(
139        &self,
140        device: &dyn Device,
141        layout: BindGroupLayoutHandle,
142        slot: usize,
143        view: ImageViewHandle,
144    ) -> Option<BindGroupHandle> {
145        let mut slots = self.slots.lock().unwrap_or_else(PoisonError::into_inner);
146        let groups = &mut slots[slot];
147        if let Some(cached) = groups.iter_mut().find(|cached| cached.view == view) {
148            cached.used = true;
149            return Some(cached.group);
150        }
151        match device.create_bind_group(&BindGroupDesc {
152            label: Some("ui texture"),
153            layout,
154            entries: &[BindGroupEntry {
155                binding: 0,
156                array_index: 0,
157                resource: BindingResource::ImageView(view),
158            }],
159            variable_count: None,
160        }) {
161            Ok(group) => {
162                groups.push(Cached {
163                    view,
164                    group,
165                    used: true,
166                });
167                Some(group)
168            }
169            Err(error) => {
170                crcbl_core::log::error!("graph: ui texture bind group failed: {error}");
171                None
172            }
173        }
174    }
175
176    /// The view each held group names, across every slot.
177    #[cfg(test)]
178    pub(super) fn views(&self) -> Vec<ImageViewHandle> {
179        self.slots
180            .lock()
181            .unwrap_or_else(PoisonError::into_inner)
182            .iter()
183            .flatten()
184            .map(|cached| cached.view)
185            .collect()
186    }
187
188    /// Releases every group. The device must be idle.
189    pub(super) fn destroy(&mut self, device: &dyn Device) {
190        let slots = self.slots.get_mut().unwrap_or_else(PoisonError::into_inner);
191        for cached in slots.iter_mut().flat_map(|slot| slot.drain(..)) {
192            device.destroy_bind_group(cached.group);
193        }
194    }
195}