Skip to main content

dream_soft_render/
texture.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3use std::collections::HashMap;
4use std::fmt;
5use std::hash::{BuildHasherDefault, Hasher};
6use std::io;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use crate::Error;
10
11#[cfg(feature = "egui")]
12mod egui_textures;
13
14#[cfg(feature = "egui")]
15pub(crate) use egui_textures::TextureDeltaStats;
16
17/// Total bytes of texture pixels one renderer may hold (8 MiB): egui's font atlas and
18/// textures together with those made by [`SoftwareRenderer::create_texture`](crate::SoftwareRenderer::create_texture).
19pub const MAX_TEXTURE_BYTES: usize = 8 * 1024 * 1024;
20
21/// The longest texture side, in texels. Sampling computes a texel index as `uv * (side - 1)` in
22/// `f32`, with the side converted through `usize_to_f32`'s `u16` clamp, so a longer side would
23/// sample the wrong texels.
24pub(crate) const MAX_TEXTURE_SIDE: usize = 65_536;
25
26/// A texture owned by a [`SoftwareRenderer`](crate::SoftwareRenderer), returned by
27/// [`create_texture`](crate::SoftwareRenderer::create_texture).
28///
29/// Handles are unique across the whole process and never reused. A freed handle stays invalid,
30/// and a handle from one renderer is [`Error::UnknownTexture`] to every other renderer instead
31/// of quietly naming whatever texture that renderer happens to hold under the same number.
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
33pub struct TextureId(pub(crate) u64);
34
35// One counter for every renderer in the process, so handles cannot alias across renderers.
36static NEXT_TEXTURE_ID: AtomicU64 = AtomicU64::new(0);
37
38/// How the store names a texture: one egui uploaded, or one made through
39/// [`SoftwareRenderer::create_texture`](crate::SoftwareRenderer::create_texture).
40#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
41pub(crate) enum TextureKey {
42    #[cfg(feature = "egui")]
43    Egui(egui::TextureId),
44    Native(TextureId),
45}
46
47impl TextureId {
48    /// Issues the next process-wide handle, or `None` once the handle space is exhausted.
49    ///
50    /// Handles run from 0 through `u64::MAX - 1`. The counter parks at `u64::MAX`, which marks
51    /// exhaustion and is never issued. It never wraps, because a wrapped counter would hand out
52    /// a handle that is already in use.
53    pub(crate) fn issue() -> Option<Self> {
54        issue_from(&NEXT_TEXTURE_ID).map(Self)
55    }
56}
57
58impl fmt::Display for TextureId {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        write!(f, "#{}", self.0)
61    }
62}
63
64fn issue_from(counter: &AtomicU64) -> Option<u64> {
65    // `try_update` replaces this method on newer Rust, but requires a newer MSRV.
66    #[allow(deprecated)]
67    counter
68        .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |next| {
69            next.checked_add(1)
70        })
71        .ok()
72}
73
74/// Stands in for "no texture": zero-sized textures sample as opaque white.
75pub(crate) static EMPTY_TEXTURE: TextureImage = TextureImage {
76    width: 0,
77    height: 0,
78    pixels: Vec::new(),
79};
80
81/// Hashes texture keys with one multiply per word. The keys are ids this crate or egui hands
82/// out, never chosen by an adversary, so `SipHash`'s flood resistance buys nothing, and the store
83/// is looked up once per textured draw.
84#[derive(Default)]
85struct TextureKeyHasher(u64);
86
87impl Hasher for TextureKeyHasher {
88    fn finish(&self) -> u64 {
89        self.0
90    }
91
92    fn write(&mut self, bytes: &[u8]) {
93        for &byte in bytes {
94            self.write_u64(u64::from(byte));
95        }
96    }
97
98    fn write_u64(&mut self, value: u64) {
99        self.0 = (self.0.rotate_left(5) ^ value).wrapping_mul(0x517c_c1b7_2722_0a95);
100    }
101
102    fn write_usize(&mut self, value: usize) {
103        self.write_u64(value as u64);
104    }
105}
106
107#[derive(Debug, Default)]
108pub(crate) struct TextureStore {
109    textures: HashMap<TextureKey, TextureImage, BuildHasherDefault<TextureKeyHasher>>,
110    bytes_used: usize,
111}
112
113impl TextureStore {
114    pub(crate) fn insert_native(
115        &mut self,
116        id: TextureId,
117        width: usize,
118        height: usize,
119        pixels: &[u8],
120    ) -> Result<(), Error> {
121        if width == 0 || height == 0 || width > MAX_TEXTURE_SIDE || height > MAX_TEXTURE_SIDE {
122            return Err(Error::TextureSize { width, height });
123        }
124        let expected = rgba8_byte_len(width, height).ok_or(Error::TextureSize { width, height })?;
125        check_pixel_data_length(expected, pixels)?;
126        let requested = self.bytes_used.saturating_add(expected);
127        if requested > MAX_TEXTURE_BYTES {
128            return Err(Error::TextureBudget {
129                requested,
130                budget: MAX_TEXTURE_BYTES,
131            });
132        }
133        self.textures.insert(
134            TextureKey::Native(id),
135            TextureImage {
136                width,
137                height,
138                pixels: pixels.to_vec(),
139            },
140        );
141        self.bytes_used = requested;
142        Ok(())
143    }
144
145    pub(crate) fn update_native(
146        &mut self,
147        id: TextureId,
148        pos: [usize; 2],
149        size: [usize; 2],
150        pixels: &[u8],
151    ) -> Result<(), Error> {
152        let [width, height] = size;
153        let expected = rgba8_byte_len(width, height).ok_or(Error::TextureUpdateOutOfBounds(id))?;
154        check_pixel_data_length(expected, pixels)?;
155        let texture = self
156            .textures
157            .get_mut(&TextureKey::Native(id))
158            .ok_or(Error::UnknownTexture(id))?;
159        texture
160            .validate_update_bounds(pos, width, height)
161            .map_err(|_| Error::TextureUpdateOutOfBounds(id))?;
162        let row_bytes = width * 4;
163        for (row, source) in pixels
164            .chunks_exact(row_bytes.max(1))
165            .enumerate()
166            .take(height)
167        {
168            let destination = ((pos[1] + row) * texture.width + pos[0]) * 4;
169            texture.pixels[destination..destination + row_bytes].copy_from_slice(source);
170        }
171        Ok(())
172    }
173
174    pub(crate) fn free_native(&mut self, id: TextureId) -> Result<(), Error> {
175        if self.textures.contains_key(&TextureKey::Native(id)) {
176            self.free(TextureKey::Native(id));
177            Ok(())
178        } else {
179            Err(Error::UnknownTexture(id))
180        }
181    }
182
183    fn free(&mut self, id: TextureKey) {
184        if let Some(texture) = self.textures.remove(&id) {
185            self.bytes_used = self
186                .bytes_used
187                .checked_sub(texture.pixels.len())
188                .expect("texture byte accounting underflow");
189        }
190    }
191
192    pub(crate) fn get(&self, id: TextureKey) -> Option<&TextureImage> {
193        self.textures.get(&id)
194    }
195
196    #[cfg(feature = "egui")]
197    pub(crate) fn len(&self) -> usize {
198        self.textures.len()
199    }
200
201    #[cfg(feature = "egui")]
202    pub(crate) fn bytes_used(&self) -> usize {
203        self.bytes_used
204    }
205}
206
207#[derive(Debug, Clone, Eq, PartialEq)]
208pub(crate) struct TextureImage {
209    pub(crate) width: usize,
210    pub(crate) height: usize,
211    pub(crate) pixels: Vec<u8>,
212}
213
214impl TextureImage {
215    fn validate_update_bounds(
216        &self,
217        pos: [usize; 2],
218        width: usize,
219        height: usize,
220    ) -> io::Result<()> {
221        let x_end = pos[0]
222            .checked_add(width)
223            .ok_or_else(|| io::Error::other("partial texture x range overflow"))?;
224        let y_end = pos[1]
225            .checked_add(height)
226            .ok_or_else(|| io::Error::other("partial texture y range overflow"))?;
227        if x_end > self.width || y_end > self.height {
228            return Err(io::Error::other(
229                "partial texture update exceeds texture bounds",
230            ));
231        }
232        Ok(())
233    }
234}
235
236fn rgba8_byte_len(width: usize, height: usize) -> Option<usize> {
237    width.checked_mul(height)?.checked_mul(4)
238}
239
240fn check_pixel_data_length(expected: usize, pixels: &[u8]) -> Result<(), Error> {
241    if pixels.len() == expected {
242        Ok(())
243    } else {
244        Err(Error::PixelDataLength {
245            expected,
246            actual: pixels.len(),
247        })
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    #[test]
256    fn texture_id_issuance_stops_instead_of_wrapping() {
257        let counter = AtomicU64::new(u64::MAX - 2);
258        assert_eq!(issue_from(&counter), Some(u64::MAX - 2));
259        assert_eq!(issue_from(&counter), Some(u64::MAX - 1));
260        assert_eq!(issue_from(&counter), None);
261        assert_eq!(issue_from(&counter), None);
262    }
263}