alpha2-render 0.6.1

Render graph and effect registry for alpha2.
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
//! Pictures the CPU renderer keeps: node results and lent source pictures.

use std::sync::{Arc, Weak};

use super::frames::{FramePool, HalfPixel};
use super::half;
use crate::{RenderError, RenderSize};

/// A rectangle of pixels: `x..x + width` by `y..y + height`.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash)]
pub(crate) struct PixelBox {
    pub(crate) x: u32,
    pub(crate) y: u32,
    pub(crate) width: u32,
    pub(crate) height: u32,
}

impl PixelBox {
    pub(crate) const EMPTY: Self = Self {
        x: 0,
        y: 0,
        width: 0,
        height: 0,
    };

    pub(crate) const fn whole(size: RenderSize) -> Self {
        Self {
            x: 0,
            y: 0,
            width: size.width,
            height: size.height,
        }
    }

    pub(crate) const fn is_empty(self) -> bool {
        self.width == 0 || self.height == 0
    }

    pub(crate) const fn right(self) -> u32 {
        self.x + self.width
    }

    pub(crate) const fn bottom(self) -> u32 {
        self.y + self.height
    }

    pub(crate) fn pixels(self) -> usize {
        self.width as usize * self.height as usize
    }

    pub(crate) const fn contains(self, x: u32, y: u32) -> bool {
        x >= self.x && x < self.x + self.width && y >= self.y && y < self.y + self.height
    }

    /// The pixels both hold; empty when they do not meet.
    pub(crate) fn intersect(self, other: Self) -> Self {
        let x = self.x.max(other.x);
        let y = self.y.max(other.y);
        let right = self.right().min(other.right());
        let bottom = self.bottom().min(other.bottom());
        if right <= x || bottom <= y {
            return Self::EMPTY;
        }
        Self {
            x,
            y,
            width: right - x,
            height: bottom - y,
        }
    }

    /// The smallest box holding both; an empty box adds nothing.
    pub(crate) fn union(self, other: Self) -> Self {
        if self.is_empty() {
            return other;
        }
        if other.is_empty() {
            return self;
        }
        let x = self.x.min(other.x);
        let y = self.y.min(other.y);
        Self {
            x,
            y,
            width: self.right().max(other.right()) - x,
            height: self.bottom().max(other.bottom()) - y,
        }
    }

    /// Grown by `margin` pixels on every side, kept inside `size`.
    pub(crate) fn expand(self, margin: u32, size: RenderSize) -> Self {
        if self.is_empty() {
            return self;
        }
        let x = self.x.saturating_sub(margin);
        let y = self.y.saturating_sub(margin);
        let right = self.right().saturating_add(margin).min(size.width);
        let bottom = self.bottom().saturating_add(margin).min(size.height);
        Self {
            x,
            y,
            width: right - x,
            height: bottom - y,
        }
    }
}

/// Storage of a picture's premultiplied sRGB RGBA.
#[derive(Clone, Debug)]
pub(crate) enum Pixels {
    /// Half-float bits, as the `Rgba16Float` intermediate holds them.
    Half(Vec<[u16; 4]>),
    /// 8-bit codes, as an `Rgba8Unorm` texture holds them.
    Unorm8(Vec<[u8; 4]>),
}

/// A CPU picture of premultiplied sRGB RGBA, like every GPU intermediate.
///
/// Only the content rectangle is stored; everything outside is transparent, so a small label on
/// a large canvas stores only the label.
#[derive(Clone, Debug)]
pub struct CpuImage {
    size: RenderSize,
    bounds: PixelBox,
    pixels: Pixels,
    /// Where the pixel buffer goes when the picture drops.
    pool: Weak<FramePool>,
}

impl CpuImage {
    pub(crate) fn new(size: RenderSize, bounds: PixelBox, pixels: Pixels) -> Self {
        let bounds = bounds.intersect(PixelBox::whole(size));
        debug_assert_eq!(
            match &pixels {
                Pixels::Half(pixels) => pixels.len(),
                Pixels::Unorm8(pixels) => pixels.len(),
            },
            bounds.pixels()
        );
        Self {
            size,
            bounds,
            pixels,
            pool: Weak::new(),
        }
    }

    /// A picture of half-float `pixels` from [`FramePool::take`] that gives them back on drop.
    pub(crate) fn pooled(
        size: RenderSize,
        bounds: PixelBox,
        pixels: Vec<HalfPixel>,
        pool: &Arc<FramePool>,
    ) -> Self {
        let mut image = Self::new(size, bounds, Pixels::Half(pixels));
        image.pool = Arc::downgrade(pool);
        image
    }

    /// A transparent picture of `size`, which stores nothing.
    pub(crate) fn transparent(size: RenderSize) -> Self {
        Self {
            size,
            bounds: PixelBox::EMPTY,
            pixels: Pixels::Half(Vec::new()),
            pool: Weak::new(),
        }
    }

    /// A picture from packed premultiplied sRGB RGBA8, sampled like the texture
    /// [`crate::Renderer::upload_rgba8`] creates.
    ///
    /// # Errors
    /// [`RenderError::InvalidImageData`] when `rgba8` is not four bytes per pixel of `size`.
    pub fn from_premultiplied_rgba8(size: RenderSize, rgba8: &[u8]) -> Result<Self, RenderError> {
        let expected = size.width as usize * size.height as usize * 4;
        if rgba8.len() != expected {
            return Err(RenderError::InvalidImageData);
        }
        let pixels = rgba8.as_chunks::<4>().0.to_vec();
        Ok(Self::new(
            size,
            PixelBox::whole(size),
            Pixels::Unorm8(pixels),
        ))
    }

    /// The picture's dimensions.
    #[must_use]
    pub const fn size(&self) -> RenderSize {
        self.size
    }

    pub(crate) const fn bounds(&self) -> PixelBox {
        self.bounds
    }

    pub(crate) const fn pixels(&self) -> &Pixels {
        &self.pixels
    }

    /// Bytes the picture holds.
    #[must_use]
    pub fn retained_bytes(&self) -> u64 {
        let pixels = self.bounds.pixels() as u64;
        match self.pixels {
            Pixels::Half(_) => pixels * 8,
            Pixels::Unorm8(_) => pixels * 4,
        }
    }

    /// Packed RGBA8 rounded to nearest, as [`crate::Renderer::read_rgba8`] reads a texture.
    #[must_use]
    pub fn read_rgba8(&self) -> Vec<u8> {
        let width = self.size.width as usize;
        let mut bytes = vec![0_u8; width * self.size.height as usize * 4];
        let bounds = self.bounds;
        for row in 0..bounds.height as usize {
            let start = ((bounds.y as usize + row) * width + bounds.x as usize) * 4;
            let out = &mut bytes[start..start + bounds.width as usize * 4];
            match &self.pixels {
                Pixels::Half(pixels) => {
                    let line = &pixels[row * bounds.width as usize..][..bounds.width as usize];
                    for (pixel, out) in line.iter().zip(out.as_chunks_mut::<4>().0) {
                        *out = half::load4(*pixel).map(half::unorm8);
                    }
                }
                Pixels::Unorm8(pixels) => {
                    let line = &pixels[row * bounds.width as usize..][..bounds.width as usize];
                    out.copy_from_slice(line.as_flattened());
                }
            }
        }
        bytes
    }

    /// Every pixel's stored half-float bits, row by row; zero outside the content.
    #[cfg(test)]
    pub(crate) fn stored_bits(&self) -> Vec<[u16; 4]> {
        let mut bits = Vec::with_capacity(self.size.width as usize * self.size.height as usize);
        for y in 0..self.size.height {
            for x in 0..self.size.width {
                bits.push(half::store4(self.texel(x, y)));
            }
        }
        bits
    }

    /// [`Texels::texel`] of this picture.
    #[inline(always)]
    #[allow(clippy::inline_always)]
    pub(crate) fn texel(&self, x: u32, y: u32) -> [f32; 4] {
        self.texels().texel(x, y)
    }

    /// The picture's storage resolved for sampling, to make once and sample many times.
    #[inline(always)]
    #[allow(clippy::inline_always)]
    pub(crate) fn texels(&self) -> Texels<'_> {
        Texels {
            storage: match &self.pixels {
                Pixels::Half(pixels) => Storage::Half(pixels, half::table()),
                Pixels::Unorm8(pixels) => Storage::Unorm8(pixels),
            },
            bounds: self.bounds,
            whole: self.bounds == PixelBox::whole(self.size),
            last: [
                i64::from(self.size.width) - 1,
                i64::from(self.size.height) - 1,
            ],
            #[allow(clippy::cast_precision_loss)]
            size: [self.size.width as f32, self.size.height as f32],
        }
    }

    /// Pixels `x0..x0 + out.len()` of row `y` into `out`; transparent outside the content.
    pub(crate) fn decode_row(&self, y: u32, x0: u32, out: &mut [[f32; 4]]) {
        let bounds = self.bounds;
        if y < bounds.y || y >= bounds.bottom() {
            out.fill([0.0; 4]);
            return;
        }
        let row = (y - bounds.y) as usize * bounds.width as usize;
        let start = x0.max(bounds.x);
        #[allow(clippy::cast_possible_truncation)]
        let end = (x0 + out.len() as u32).min(bounds.right());
        out.fill([0.0; 4]);
        if start >= end {
            return;
        }
        let target = &mut out[(start - x0) as usize..(end - x0) as usize];
        let source = row + (start - bounds.x) as usize..row + (end - bounds.x) as usize;
        match &self.pixels {
            Pixels::Half(pixels) => {
                let table = half::table();
                for (pixel, bits) in target.iter_mut().zip(&pixels[source]) {
                    *pixel = bits.map(|bits| table[usize::from(bits)]);
                }
            }
            Pixels::Unorm8(pixels) => {
                for (pixel, codes) in target.iter_mut().zip(&pixels[source]) {
                    *pixel = codes.map(half::unorm8_value);
                }
            }
        }
    }

    /// [`Texels::texel_clamped`] of this picture.
    #[inline(always)]
    #[allow(clippy::inline_always)]
    pub(crate) fn texel_clamped(&self, x: i64, y: i64) -> [f32; 4] {
        self.texels().texel_clamped(x, y)
    }

    /// [`Texels::sample`] of this picture.
    #[inline(always)]
    #[allow(clippy::inline_always)]
    pub(crate) fn sample(&self, u: f32, v: f32) -> [f32; 4] {
        self.texels().sample(u, v)
    }
}

/// A picture's stored pixels, borrowed.
#[derive(Clone, Copy)]
enum Storage<'a> {
    Half(&'a [[u16; 4]], &'static [f32; 65_536]),
    Unorm8(&'a [[u8; 4]]),
}

/// A [`CpuImage`] resolved for sampling: its storage, half-float table and bounds, read once.
#[derive(Clone, Copy)]
pub(crate) struct Texels<'a> {
    storage: Storage<'a>,
    bounds: PixelBox,
    /// The content covers the whole picture, so no texel needs the bounds test.
    whole: bool,
    last: [i64; 2],
    size: [f32; 2],
}

// The per-sample helpers must inline into the kernels' loops, which are generic over closures.
#[allow(clippy::inline_always)]
impl Texels<'_> {
    /// Pixel at `(x, y)` inside the picture; transparent outside the content.
    #[inline(always)]
    pub(crate) fn texel(&self, x: u32, y: u32) -> [f32; 4] {
        let bounds = self.bounds;
        if !self.whole && !bounds.contains(x, y) {
            return [0.0; 4];
        }
        debug_assert!(bounds.contains(x, y), "({x}, {y}) is inside the picture");
        let index = (y - bounds.y) as usize * bounds.width as usize + (x - bounds.x) as usize;
        match self.storage {
            Storage::Half(pixels, table) => pixels[index].map(|bits| table[usize::from(bits)]),
            Storage::Unorm8(pixels) => pixels[index].map(half::unorm8_value),
        }
    }

    /// Pixel at `(x, y)` with clamp-to-edge addressing.
    #[inline(always)]
    pub(crate) fn texel_clamped(&self, x: i64, y: i64) -> [f32; 4] {
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        self.texel(
            x.clamp(0, self.last[0]) as u32,
            y.clamp(0, self.last[1]) as u32,
        )
    }

    /// Bilinear sample at normalized `(u, v)`, clamped to the edge, as `textureSampleLevel` at 0.
    #[inline(always)]
    pub(crate) fn sample(&self, u: f32, v: f32) -> [f32; 4] {
        // Every position outside [-1, size] reads the edge texel, so clamping changes no sample
        // and keeps the integer neighbours below in range.
        let x = (u * self.size[0] - 0.5).clamp(-1.0, self.size[0]);
        let y = (v * self.size[1] - 0.5).clamp(-1.0, self.size[1]);
        let x0 = x.floor();
        let y0 = y.floor();
        let fx = x - x0;
        let fy = y - y0;
        #[allow(clippy::cast_possible_truncation)]
        let (ix, iy) = (x0 as i64, y0 as i64);
        let t00 = self.texel_clamped(ix, iy);
        let t10 = self.texel_clamped(ix + 1, iy);
        let t01 = self.texel_clamped(ix, iy + 1);
        let t11 = self.texel_clamped(ix + 1, iy + 1);
        let mut out = [0.0; 4];
        for channel in 0..4 {
            let top = t00[channel] + (t10[channel] - t00[channel]) * fx;
            let bottom = t01[channel] + (t11[channel] - t01[channel]) * fx;
            out[channel] = top + (bottom - top) * fy;
        }
        out
    }
}

impl Drop for CpuImage {
    fn drop(&mut self) {
        if let Pixels::Half(pixels) = &mut self.pixels
            && let Some(pool) = self.pool.upgrade()
        {
            pool.give_back(std::mem::take(pixels));
        }
    }
}