emblema 0.7.0

A Flutter-class 2D renderer: Vulkan and GLES backends, WSI and DRM/KMS presentation.
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
//! A texture of the `gpu` module's drawn by the 2D renderer as an image:
//! what `VulkanContext::gpu_texture_image` is for, and `flutter_gpu`'s
//! `Texture.asImage`.
//!
//! The image is the texture, not a copy of it, so what is drawn has to be
//! what the texture holds: written from bytes in each format the renderer
//! has an image of, and drawn by a pass, before and after the pass draws
//! it again. A texture the renderer cannot sample is refused.

#![cfg(feature = "gpu")]

use emblema::vulkan::gpu::{
    ColorAttachment, PassTarget, PixelFormat as GpuFormat, StorageMode, Texture, TextureDescriptor,
    TextureType,
};
use emblema::vulkan::VulkanContext;
use emblema::{
    BackendPreference, Canvas, Color, Context, Extent2D, Image, Paint, PixelFormat, Rect, Sampling,
};

const SIDE: u32 = 16;

/// Red, green, blue and yellow: every channel none or all of itself, so
/// that an sRGB curve leaves each as it is.
const QUADRANTS: [[f32; 4]; 4] = [
    [1.0, 0.0, 0.0, 1.0],
    [0.0, 1.0, 0.0, 1.0],
    [0.0, 0.0, 1.0, 1.0],
    [1.0, 1.0, 0.0, 1.0],
];

fn context() -> Option<Context> {
    match Context::new(BackendPreference::Vulkan) {
        Ok(ctx) => Some(ctx),
        Err(e) => {
            eprintln!("skipping: no Vulkan context ({e})");
            None
        }
    }
}

fn vulkan(ctx: &mut Context) -> &mut VulkanContext {
    #[allow(unreachable_patterns, clippy::infallible_destructuring_match)]
    match ctx {
        Context::Vulkan(vulkan) => vulkan,
        _ => unreachable!("a Vulkan context was asked for"),
    }
}

/// A half-precision float of `value`, which is 0 or 1 here.
fn half(value: f32) -> [u8; 2] {
    if value == 0.0 { 0u16 } else { 0x3c00 }.to_le_bytes()
}

/// One texel of `color` as `format` lays it out.
fn texel(format: GpuFormat, color: [f32; 4]) -> Vec<u8> {
    let byte = |v: f32| (v * 255.0) as u8;
    let [r, g, b, a] = color;
    match format {
        GpuFormat::R8G8B8A8Unorm | GpuFormat::R8G8B8A8UnormSrgb => {
            vec![byte(r), byte(g), byte(b), byte(a)]
        }
        GpuFormat::B8G8R8A8Unorm | GpuFormat::B8G8R8A8UnormSrgb => {
            vec![byte(b), byte(g), byte(r), byte(a)]
        }
        GpuFormat::R16G16B16A16Float => color.iter().flat_map(|v| half(*v)).collect(),
        GpuFormat::R32G32B32A32Float => color.iter().flat_map(|v| v.to_le_bytes()).collect(),
        GpuFormat::R32Float => r.to_le_bytes().to_vec(),
        other => panic!("{other:?} is not a format this test writes"),
    }
}

/// The four quadrants, a color each, row by row from the top.
fn quadrants(format: GpuFormat) -> Vec<u8> {
    let mut bytes = Vec::new();
    for y in 0..SIDE {
        for x in 0..SIDE {
            let quadrant = usize::from(x >= SIDE / 2) + 2 * usize::from(y >= SIDE / 2);
            bytes.extend(texel(format, QUADRANTS[quadrant]));
        }
    }
    bytes
}

fn sampled(format: GpuFormat) -> TextureDescriptor {
    TextureDescriptor::sampled(format, SIDE, SIDE)
}

/// What the 2D renderer draws of `image`, over all of a surface of
/// `side`, read back.
fn drawn(ctx: &mut Context, image: &Image, side: u32) -> Vec<u8> {
    drawn_at(ctx, image, side, Sampling::Nearest)
}

fn drawn_at(ctx: &mut Context, image: &Image, side: u32, sampling: Sampling) -> Vec<u8> {
    let size = Extent2D::new(side, side);
    let whole = Rect::from_size(side as f32, side as f32);
    let mut canvas = Canvas::new(size);
    canvas.clear(Color::linear(0.0, 0.0, 0.0, 0.0));
    canvas
        .draw_rect(
            whole,
            &Paint::image(0, whole)
                .with_sampling(sampling)
                .with_anti_alias(false),
        )
        .expect("rect");
    let mut surface = ctx
        .create_surface(size, PixelFormat::Rgba8Unorm)
        .expect("surface");
    ctx.draw_with_images(&mut surface, &canvas.finish(), &[image])
        .expect("draw the image");
    let pixels = ctx.read(&mut surface).expect("read");
    ctx.destroy_surface(surface);
    pixels
}

fn at(pixels: &[u8], side: u32, x: u32, y: u32) -> [u8; 4] {
    let i = ((y * side + x) * 4) as usize;
    [pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]]
}

fn bytes_of(color: [f32; 4]) -> [u8; 4] {
    color.map(|v| (v * 255.0) as u8)
}

/// The image of `texture`, drawn; and the texture as it was.
fn image_of(ctx: &mut Context, texture: &Texture) -> Image {
    Image::Vulkan(
        vulkan(ctx)
            .gpu_texture_image(texture)
            .expect("an image of the texture"),
    )
}

/// In each format the renderer has an image of, and the device samples, a
/// texture written from bytes is drawn as what it holds.
#[test]
fn a_texture_written_from_bytes_is_drawn_as_what_it_holds() {
    let Some(mut ctx) = context() else {
        return;
    };
    let mut drew = 0;
    for format in [
        GpuFormat::R8G8B8A8Unorm,
        GpuFormat::R8G8B8A8UnormSrgb,
        GpuFormat::B8G8R8A8Unorm,
        GpuFormat::B8G8R8A8UnormSrgb,
        GpuFormat::R16G16B16A16Float,
        GpuFormat::R32G32B32A32Float,
        GpuFormat::R32Float,
    ] {
        if !vulkan(&mut ctx).gpu_format_support(format).sampled {
            eprintln!("skipping {format:?}: this device does not sample it");
            continue;
        }
        let texture = vulkan(&mut ctx)
            .gpu_create_texture(&sampled(format))
            .expect("a texture");
        vulkan(&mut ctx)
            .gpu_write_texture(&texture, 0, 0, &quadrants(format))
            .expect("written");
        let image = image_of(&mut ctx, &texture);
        let pixels = drawn(&mut ctx, &image, SIDE);
        for (quadrant, (x, y)) in [(4, 4), (12, 4), (4, 12), (12, 12)].into_iter().enumerate() {
            let mut want = bytes_of(QUADRANTS[quadrant]);
            if format == GpuFormat::R32Float {
                // One channel: red is what it holds, and the rest is the
                // nothing and the all that a shader reads of one.
                want = [want[0], 0, 0, 255];
            }
            assert_eq!(at(&pixels, SIDE, x, y), want, "{format:?} at ({x}, {y})");
        }
        ctx.destroy_image(image);
        vulkan(&mut ctx).gpu_destroy_texture(texture);
        drew += 1;
    }
    assert!(drew > 0, "no format was drawn");
}

/// The sRGB formats are sampled through their curve and the others are
/// not: the same middling bytes are drawn as themselves from one, and
/// darker from the other.
#[test]
fn an_srgb_texture_is_drawn_through_its_curve() {
    let Some(mut ctx) = context() else {
        return;
    };
    let mut gray = |format: GpuFormat| {
        let texture = vulkan(&mut ctx)
            .gpu_create_texture(&sampled(format))
            .expect("a texture");
        vulkan(&mut ctx)
            .gpu_write_texture(
                &texture,
                0,
                0,
                &[128, 128, 128, 255].repeat((SIDE * SIDE) as usize),
            )
            .expect("written");
        let image = image_of(&mut ctx, &texture);
        let pixel = at(&drawn(&mut ctx, &image, SIDE), SIDE, 8, 8);
        ctx.destroy_image(image);
        vulkan(&mut ctx).gpu_destroy_texture(texture);
        pixel
    };
    for (plain, curved) in [
        (GpuFormat::R8G8B8A8Unorm, GpuFormat::R8G8B8A8UnormSrgb),
        (GpuFormat::B8G8R8A8Unorm, GpuFormat::B8G8R8A8UnormSrgb),
    ] {
        assert_eq!(gray(plain), [128, 128, 128, 255], "{plain:?}");
        // 128 through the curve is 0.2158 of full, which is 55.
        assert_eq!(gray(curved), [55, 55, 55, 255], "{curved:?}");
    }
}

/// The image is one to draw: the renderer's own write and readback of it
/// are refused, and leave the texture as it was.
#[test]
fn an_image_of_a_texture_is_not_written_or_read_by_the_renderer() {
    let Some(mut ctx) = context() else {
        return;
    };
    let format = GpuFormat::R8G8B8A8Unorm;
    let texture = vulkan(&mut ctx)
        .gpu_create_texture(&sampled(format))
        .expect("a texture");
    vulkan(&mut ctx)
        .gpu_write_texture(&texture, 0, 0, &quadrants(format))
        .expect("written");
    let mut image = image_of(&mut ctx, &texture);
    assert!(ctx.write_image(&mut image, &quadrants(format)).is_err());
    assert!(ctx.read_image(&mut image).is_err());
    let pixels = drawn(&mut ctx, &image, SIDE);
    assert_eq!(at(&pixels, SIDE, 12, 12), bytes_of(QUADRANTS[3]));
    ctx.destroy_image(image);
    vulkan(&mut ctx).gpu_destroy_texture(texture);
}

/// A texture a pass drew is drawn as what the pass left in it, and after
/// the pass draws it again, as that: the image is the texture.
#[test]
fn a_texture_a_pass_drew_is_drawn_as_the_pass_left_it() {
    let Some(mut ctx) = context() else {
        return;
    };
    let target = vulkan(&mut ctx)
        .gpu_create_texture(&{
            let mut d = sampled(GpuFormat::R8G8B8A8Unorm);
            d.render_target = true;
            d
        })
        .expect("a target");
    let cleared = |ctx: &mut Context, color: [f32; 4]| {
        let vulkan = vulkan(ctx);
        let mut encoder = vulkan.gpu_begin().expect("an encoder");
        vulkan
            .gpu_begin_pass(
                &mut encoder,
                &PassTarget {
                    colors: vec![ColorAttachment::cleared(&target, color)],
                    depth_stencil: None,
                },
            )
            .expect("a pass");
        vulkan.gpu_end_pass(&mut encoder).expect("ended");
        // Not waited for: the frame that draws the image comes after it on
        // the same queue.
        let submission = vulkan.gpu_submit_deferred(encoder).expect("submitted");
        drop(submission);
    };
    assert!(
        vulkan(&mut ctx).gpu_texture_image(&target).is_err(),
        "nothing has drawn it"
    );
    // Nor has a pass that is recorded and not submitted: the texture is
    // as it was until the recording runs.
    {
        let vulkan = vulkan(&mut ctx);
        let mut encoder = vulkan.gpu_begin().expect("an encoder");
        vulkan
            .gpu_begin_pass(
                &mut encoder,
                &PassTarget {
                    colors: vec![ColorAttachment::cleared(&target, QUADRANTS[0])],
                    depth_stencil: None,
                },
            )
            .expect("a pass");
        vulkan.gpu_end_pass(&mut encoder).expect("ended");
        assert!(
            vulkan.gpu_texture_image(&target).is_err(),
            "a recording not submitted has drawn nothing"
        );
        vulkan.gpu_discard(encoder);
        assert!(
            vulkan.gpu_texture_image(&target).is_err(),
            "a recording given up has drawn nothing"
        );
    }
    for color in [QUADRANTS[1], QUADRANTS[2]] {
        cleared(&mut ctx, color);
        let image = image_of(&mut ctx, &target);
        let pixels = drawn(&mut ctx, &image, SIDE);
        assert_eq!(at(&pixels, SIDE, 8, 8), bytes_of(color));
        ctx.destroy_image(image);
    }
    // An image made before the pass drew the texture again is the texture
    // still, and is drawn as it now is.
    let image = image_of(&mut ctx, &target);
    cleared(&mut ctx, QUADRANTS[0]);
    let pixels = drawn(&mut ctx, &image, SIDE);
    assert_eq!(at(&pixels, SIDE, 8, 8), bytes_of(QUADRANTS[0]));
    // Destroying the image leaves the texture: it is drawn into and read
    // as before.
    ctx.destroy_image(image);
    cleared(&mut ctx, QUADRANTS[3]);
    let held = vulkan(&mut ctx)
        .gpu_read_texture(&target, 0, 0)
        .expect("read back");
    assert_eq!(&held[..4], bytes_of(QUADRANTS[3]));
    assert!(vulkan(&mut ctx)
        .gpu_settle(std::time::Duration::from_secs(10))
        .expect("settled"));
    vulkan(&mut ctx).gpu_destroy_texture(target);
}

/// A texture with a level nothing wrote is drawn from its first, smaller
/// than it is, and not from what the level beneath happens to hold. Once
/// that level is written, it is what a smaller drawing reads.
#[test]
fn a_texture_is_drawn_from_the_levels_that_were_written() {
    let Some(mut ctx) = context() else {
        return;
    };
    let format = GpuFormat::R8G8B8A8Unorm;
    let texture = vulkan(&mut ctx)
        .gpu_create_texture(&{
            let mut d = sampled(format);
            d.mip_levels = 2;
            d
        })
        .expect("a texture of two levels");
    let solid = |color: [f32; 4], side: u32| texel(format, color).repeat((side * side) as usize);
    vulkan(&mut ctx)
        .gpu_write_texture(&texture, 0, 0, &solid(QUADRANTS[0], SIDE))
        .expect("the first level");
    let image = image_of(&mut ctx, &texture);
    let pixels = drawn_at(&mut ctx, &image, SIDE / 4, Sampling::Mipmap);
    assert_eq!(at(&pixels, SIDE / 4, 2, 2), bytes_of(QUADRANTS[0]));
    ctx.destroy_image(image);
    vulkan(&mut ctx)
        .gpu_write_texture(&texture, 1, 0, &solid(QUADRANTS[2], SIDE / 2))
        .expect("the second level");
    let image = image_of(&mut ctx, &texture);
    let pixels = drawn_at(&mut ctx, &image, SIDE / 4, Sampling::Mipmap);
    assert_eq!(at(&pixels, SIDE / 4, 2, 2), bytes_of(QUADRANTS[2]));
    ctx.destroy_image(image);
    vulkan(&mut ctx).gpu_destroy_texture(texture);
}

/// What the renderer cannot sample as an image is refused: a texture
/// nothing has written, one a shader does not read, one of four samples,
/// a cube, and a format the renderer has no image of.
#[test]
fn a_texture_the_renderer_cannot_sample_is_refused() {
    let Some(mut ctx) = context() else {
        return;
    };
    let vulkan = vulkan(&mut ctx);
    let rgba = GpuFormat::R8G8B8A8Unorm;
    let mut refused = |what: &str, desc: TextureDescriptor, written: bool| {
        let Ok(texture) = vulkan.gpu_create_texture(&desc) else {
            eprintln!("skipping {what}: this device makes no such texture");
            return;
        };
        if written {
            let bytes = desc
                .format
                .level_size(desc.width, desc.height)
                .expect("a format that is written") as usize;
            vulkan
                .gpu_write_texture(&texture, 0, 0, &vec![0; bytes])
                .expect("written");
        }
        assert!(
            vulkan.gpu_texture_image(&texture).is_err(),
            "{what} was given an image"
        );
        vulkan.gpu_destroy_texture(texture);
    };
    refused("a texture nothing has written", sampled(rgba), false);
    refused(
        "a texture no shader reads",
        {
            let mut d = sampled(rgba);
            d.render_target = true;
            d.shader_read = false;
            d
        },
        false,
    );
    refused(
        "a texture of four samples",
        {
            let mut d = sampled(rgba);
            d.storage = StorageMode::DevicePrivate;
            d.sample_count = 4;
            d.ty = TextureType::Texture2DMultisample;
            d.render_target = true;
            d
        },
        false,
    );
    refused(
        "a cube",
        {
            let mut d = sampled(rgba);
            d.ty = TextureType::Cube;
            d
        },
        true,
    );
    refused("two channels", sampled(GpuFormat::R8G8Unorm), true);
    refused(
        "one channel of eight bits",
        sampled(GpuFormat::R8Unorm),
        true,
    );
}