emblema 0.4.7

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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! A rendering context, over whichever backend is available.

use crate::backend::{no_backend, Backend, BackendPreference};
use emblema_core::Recording;
use emblema_hal::{
    Capabilities, Error, Extent2D, HalContext, MemoryBlocks, MemoryUse, PixelFormat, Result,
    RuntimeProgram,
};

/// A device to render with.
///
/// Which backend is behind it is decided at creation and reported by
/// [`Context::backend`]. Callers branch on [`Context::capabilities`] rather than
/// on which backend it turned out to be: a device without fence export is the
/// same problem whether it is Vulkan or GLES.
// The variants differ in size by a couple of kilobytes, and boxing the larger
// one would even them out. That trade is backwards here: a process creates one
// context and keeps it for its lifetime, so the saving is a one-off couple of
// kilobytes, while the cost is an indirection on the way to every backend call
// in the frame loop.
#[allow(clippy::large_enum_variant)]
pub enum Context {
    #[cfg(feature = "vulkan")]
    Vulkan(emblema_hal_vulkan::VulkanContext),
    #[cfg(feature = "gles")]
    Gles(emblema_hal_gles::GlesContext),
}

impl Context {
    /// Create a context, choosing a backend.
    pub fn new(preference: BackendPreference) -> Result<Self> {
        Self::with_memory(preference, MemoryBlocks::default())
    }

    /// Create a context whose backend takes device memory in blocks of
    /// these sizes, where the backend is the one that places it (Vulkan).
    pub fn with_memory(preference: BackendPreference, blocks: MemoryBlocks) -> Result<Self> {
        let mut attempts = Vec::new();

        #[cfg(feature = "vulkan")]
        if matches!(
            preference,
            BackendPreference::Auto | BackendPreference::Vulkan
        ) {
            match emblema_hal_vulkan::VulkanContext::with_memory(
                emblema_hal_vulkan::ContextConfig::default(),
                blocks,
            ) {
                Ok(ctx) => return Ok(Self::Vulkan(ctx)),
                Err(e) => attempts.push((Backend::Vulkan, e)),
            }
        }

        #[cfg(feature = "gles")]
        if matches!(
            preference,
            BackendPreference::Auto | BackendPreference::Gles
        ) {
            match emblema_hal_gles::GlesContext::new(emblema_hal_gles::DisplayTarget::Surfaceless) {
                Ok(ctx) => return Ok(Self::Gles(ctx)),
                Err(e) => attempts.push((Backend::Gles, e)),
            }
        }

        let _ = (preference, blocks);
        Err(no_backend(attempts))
    }

    /// The most device memory of each kind that has been allocated at once
    /// since the context was made, where the backend is the one that places
    /// it: what [`MemoryBlocks`] would have had to hold for no second block
    /// to be made. `None` on a backend whose driver places memory itself.
    pub fn memory_peak(&self) -> Option<MemoryUse> {
        match self {
            #[cfg(feature = "vulkan")]
            Self::Vulkan(ctx) => Some(ctx.memory_peak()),
            #[cfg(feature = "gles")]
            Self::Gles(_) => None,
        }
    }

    pub fn backend(&self) -> Backend {
        match self {
            #[cfg(feature = "vulkan")]
            Self::Vulkan(_) => Backend::Vulkan,
            #[cfg(feature = "gles")]
            Self::Gles(_) => Backend::Gles,
        }
    }

    pub fn capabilities(&self) -> &Capabilities {
        match self {
            #[cfg(feature = "vulkan")]
            Self::Vulkan(ctx) => HalContext::capabilities(ctx),
            #[cfg(feature = "gles")]
            Self::Gles(ctx) => HalContext::capabilities(ctx),
        }
    }

    /// Create a surface to draw into.
    pub fn create_surface(&mut self, extent: Extent2D, format: PixelFormat) -> Result<Surface> {
        match self {
            #[cfg(feature = "vulkan")]
            Self::Vulkan(ctx) => Ok(Surface::Vulkan(HalContext::create_texture(
                ctx,
                &emblema_hal::TextureDescriptor::offscreen(extent, format),
            )?)),
            #[cfg(feature = "gles")]
            Self::Gles(ctx) => Ok(Surface::Gles(HalContext::create_texture(
                ctx,
                &emblema_hal::TextureDescriptor::offscreen(extent, format),
            )?)),
        }
    }

    /// Draw a recording into a surface.
    pub fn draw(&mut self, surface: &mut Surface, recording: &Recording) -> Result<()> {
        self.draw_with_images(surface, recording, &[])
    }

    /// Draw a recording whose paints sample images.
    ///
    /// `images` is the table a [`Shader::Image`] slot indexes, in slot order.
    /// A recording carries slots rather than images because it is produced
    /// without touching a device; supplying the table here is what resolves
    /// them.
    ///
    /// The surface is borrowed mutably and the images immutably, so a recording
    /// cannot sample the surface it draws into. That restriction is real, and
    /// having the compiler state it beats discovering it as a picture that
    /// differs by driver.
    ///
    /// [`Shader::Image`]: emblema_core::Shader::Image
    pub fn draw_with_images(
        &mut self,
        surface: &mut Surface,
        recording: &Recording,
        images: &[&Image],
    ) -> Result<()> {
        match (self, surface) {
            #[cfg(feature = "vulkan")]
            (Self::Vulkan(ctx), Surface::Vulkan(texture)) => {
                let images = vulkan_textures(images)?;
                emblema_core::execute::<emblema_hal_vulkan::VulkanHal>(
                    ctx, texture, recording, &images,
                )
            }
            #[cfg(feature = "gles")]
            (Self::Gles(ctx), Surface::Gles(texture)) => {
                let images = gles_textures(images)?;
                emblema_core::execute::<emblema_hal_gles::GlesHal>(ctx, texture, recording, &images)
            }
            // A surface belongs to the context that made it; pairing one with
            // another context would use a handle the device never allocated.
            #[allow(unreachable_patterns)]
            _ => Err(Error::Unsupported(
                "this surface was created by a different context",
            )),
        }
    }

    /// Build what the first frame into a surface of `format` would build,
    /// ahead of it, for a frame that antialiases at `samples` (a canvas's
    /// count, four unless it was given another).
    ///
    /// Where the backend compiles its shader on a pipeline's first use, that
    /// use is otherwise a frame: on a Raspberry Pi 5 with Mesa's shader cache
    /// empty, 1.8 seconds a sample count, in whichever frame is first. Call it
    /// once the context is made, from the thread that will draw, while the
    /// rest of startup runs. That moves the compile and does not shorten it:
    /// where startup is quicker than the compile, run a step that prepares
    /// and exits once, when an image is built or on first boot, and the
    /// driver's own cache serves every process after. Drawing without it is
    /// correct, only slower the first time.
    pub fn prepare_pipelines(&mut self, format: PixelFormat, samples: u32) -> Result<()> {
        match self {
            #[cfg(feature = "vulkan")]
            Self::Vulkan(ctx) => HalContext::prepare_pipelines(ctx, format, samples),
            #[cfg(feature = "gles")]
            Self::Gles(ctx) => HalContext::prepare_pipelines(ctx, format, samples),
        }
    }

    /// Build one more variant of the built-in shader ahead of the first draw
    /// that needs it, as [`Context::prepare_pipelines`] builds the core one:
    /// [`MaterialVariant::Shape`](crate::MaterialVariant::Shape) for
    /// rounded rectangles and shadows,
    /// [`MaterialVariant::Image`](crate::MaterialVariant::Image) for
    /// images and composited layers. On a device without advanced blending
    /// (`Capabilities::advanced_blend`), a canvas made
    /// `with_advanced_blends_in_shader` draws an advanced mode with the
    /// variant that has `reads_destination`, whatever the mode.
    ///
    /// Each is a compile of its own, most of a second on some drivers, so it
    /// belongs with a step that prepares once and exits, not with every
    /// start. A runtime program's variant is refused: it is built by the draw
    /// that names it.
    pub fn prepare_variant(
        &mut self,
        format: PixelFormat,
        samples: u32,
        shader: crate::ShaderVariant,
    ) -> Result<()> {
        match self {
            #[cfg(feature = "vulkan")]
            Self::Vulkan(ctx) => ctx.prepare_variant(format, samples, shader),
            #[cfg(feature = "gles")]
            Self::Gles(ctx) => ctx.prepare_variant(format, samples, shader),
        }
    }

    /// Register a fragment program a caller's own build produced.
    ///
    /// Returns the index to name it by, which is what goes into the `program`
    /// of [`Shader::RuntimeEffect`]. Indices are per context: a recording that
    /// names one is bound to the context that registered it, in exactly the
    /// way one naming a texture slot is bound to the textures supplied
    /// beside it.
    ///
    /// Nothing here compiles a shader. The payload for the backend in use has
    /// to be present -- SPIR-V for Vulkan, GLSL ES for GLES -- and one built
    /// for the other backend alone is refused rather than silently ignored.
    /// See the architecture document for why a single source translated on
    /// load was declined.
    ///
    /// [`Shader::RuntimeEffect`]: emblema_core::Shader::RuntimeEffect
    pub fn register_program(&mut self, program: &RuntimeProgram) -> Result<u32> {
        match self {
            #[cfg(feature = "vulkan")]
            Self::Vulkan(ctx) => ctx.register_program(program),
            #[cfg(feature = "gles")]
            Self::Gles(ctx) => ctx.register_program(program),
        }
    }

    /// Allocate an image this context can sample.
    ///
    /// The format decides how the bytes written into it are read, and the
    /// choice is not cosmetic -- though it now points the other way. Color
    /// inside the renderer is sRGB-encoded, and an sRGB format decodes on
    /// sample. A picture's bytes are sRGB-encoded,
    /// because that is what every image file holds, and the pipeline wants them
    /// encoded -- so a picture wants a *plain* format, and
    /// [`PixelFormat::Rgba8UnormSrgb`] would decode it into light that nothing
    /// downstream is expecting and wash it pale. Plain is also right for data
    /// that is not color at all: coverage, a mask, a lookup table, anything
    /// whose numbers mean themselves.
    ///
    /// This advice was the reverse of itself while the renderer worked in
    /// light, and neither choice is detectable afterwards, which is why it is
    /// stated here. Both produce an image; only one produces the right
    /// picture.
    pub fn create_image(&mut self, extent: Extent2D, format: PixelFormat) -> Result<Image> {
        let descriptor = emblema_hal::TextureDescriptor::offscreen(extent, format);
        match self {
            #[cfg(feature = "vulkan")]
            Self::Vulkan(ctx) => HalContext::create_texture(ctx, &descriptor).map(Image::Vulkan),
            #[cfg(feature = "gles")]
            Self::Gles(ctx) => HalContext::create_texture(ctx, &descriptor).map(Image::Gles),
        }
    }

    /// An image with a full mip chain, for drawing smaller than its own size.
    ///
    /// The levels are filled when the image is written, not here, and the
    /// caller supplies only the image itself: a chain built by any rule other
    /// than the backend's own would sample differently on the two backends,
    /// which is the one thing this renderer's tests exist to rule out.
    ///
    /// A third again in memory, which is why it is a separate call rather than
    /// what every image gets. Only [`Sampling::Mipmap`] reads past the first
    /// level, so an image created this way and drawn at any other quality costs
    /// the memory and nothing else.
    ///
    /// [`Sampling::Mipmap`]: crate::Sampling::Mipmap
    pub fn create_mipmapped_image(
        &mut self,
        extent: Extent2D,
        format: PixelFormat,
    ) -> Result<Image> {
        let descriptor = emblema_hal::TextureDescriptor::mipmapped(extent, format);
        match self {
            #[cfg(feature = "vulkan")]
            Self::Vulkan(ctx) => HalContext::create_texture(ctx, &descriptor).map(Image::Vulkan),
            #[cfg(feature = "gles")]
            Self::Gles(ctx) => HalContext::create_texture(ctx, &descriptor).map(Image::Gles),
        }
    }

    /// An image over a dma-buf another producer made -- a camera, a decoder,
    /// another renderer -- sampled as an image written from host memory is.
    ///
    /// `extent` and `format` are the renderer's view of the buffer, as
    /// [`ExternalImageDesc`] speaks DRM fourccs. The descriptors are the
    /// context's from here, on success or failure. The producer finishes
    /// each frame before handing it over, and writes into the buffer while
    /// it is being drawn only at its own risk: the image reads whatever the
    /// buffer holds when the frame that samples it runs. Never written to
    /// with [`Self::write_image`]; released with [`Self::destroy_image`].
    ///
    /// [`Error::Unsupported`] where the device cannot import a dma-buf, or
    /// cannot sample this format at this layout -- and always on the GLES
    /// backend, for now.
    ///
    /// [`ExternalImageDesc`]: emblema_hal::ExternalImageDesc
    #[cfg(unix)]
    pub fn import_image(
        &mut self,
        image: emblema_hal::ExternalImageDesc,
        extent: Extent2D,
        format: PixelFormat,
    ) -> Result<Image> {
        match self {
            #[cfg(feature = "vulkan")]
            Self::Vulkan(ctx) => {
                HalContext::import_sampled_texture(ctx, image, extent, format).map(Image::Vulkan)
            }
            #[cfg(feature = "gles")]
            Self::Gles(ctx) => {
                HalContext::import_sampled_texture(ctx, image, extent, format).map(Image::Gles)
            }
        }
    }

    /// Fill an image from host memory, tightly packed and top row first.
    ///
    /// Decoding is out of scope for this crate; bring `image` or another
    /// decoder and hand the pixels here.
    pub fn write_image(&mut self, image: &mut Image, pixels: &[u8]) -> Result<()> {
        match (self, image) {
            #[cfg(feature = "vulkan")]
            (Self::Vulkan(ctx), Image::Vulkan(texture)) => {
                HalContext::write_texture(ctx, texture, pixels)
            }
            #[cfg(feature = "gles")]
            (Self::Gles(ctx), Image::Gles(texture)) => {
                HalContext::write_texture(ctx, texture, pixels)
            }
            #[allow(unreachable_patterns)]
            _ => Err(Error::Unsupported(
                "this image was created by a different context",
            )),
        }
    }

    /// Release an image.
    ///
    /// Explicit for the same reason a surface is: the memory belongs to the
    /// context, which an image cannot reach from its own `Drop`.
    pub fn destroy_image(&mut self, image: Image) {
        match (self, image) {
            #[cfg(feature = "vulkan")]
            (Self::Vulkan(ctx), Image::Vulkan(texture)) => {
                HalContext::destroy_texture(ctx, texture)
            }
            #[cfg(feature = "gles")]
            (Self::Gles(ctx), Image::Gles(texture)) => HalContext::destroy_texture(ctx, texture),
            #[allow(unreachable_patterns)]
            _ => {}
        }
    }

    /// Read a surface back, tightly packed, in whatever its format holds.
    ///
    /// Four bytes per pixel for the eight-bit formats, which is every surface a
    /// caller is likely to ask for; eight for `Rgba16Float`, as four
    /// half-floats. Nothing is converted on the way out -- the bytes are what
    /// the target holds, and a caller who chose a format wider than eight bits
    /// did so in order to read what it kept.
    pub fn read(&mut self, surface: &mut Surface) -> Result<Vec<u8>> {
        match (self, surface) {
            #[cfg(feature = "vulkan")]
            (Self::Vulkan(ctx), Surface::Vulkan(texture)) => HalContext::read_texture(ctx, texture),
            #[cfg(feature = "gles")]
            (Self::Gles(ctx), Surface::Gles(texture)) => HalContext::read_texture(ctx, texture),
            #[allow(unreachable_patterns)]
            _ => Err(Error::Unsupported(
                "this surface was created by a different context",
            )),
        }
    }

    /// Release a surface.
    ///
    /// Explicit because the memory belongs to the context, which a surface
    /// cannot reach from its own `Drop`.
    pub fn destroy_surface(&mut self, surface: Surface) {
        match (self, surface) {
            #[cfg(feature = "vulkan")]
            (Self::Vulkan(ctx), Surface::Vulkan(texture)) => {
                HalContext::destroy_texture(ctx, texture)
            }
            #[cfg(feature = "gles")]
            (Self::Gles(ctx), Surface::Gles(texture)) => HalContext::destroy_texture(ctx, texture),
            #[allow(unreachable_patterns)]
            _ => {}
        }
    }
}

/// Something to draw into.
/// A texture a paint can sample.
///
/// Distinct from a [`Surface`] in the type system even though both are textures
/// underneath, because the two are used in opposite directions and mixing them
/// up is exactly the mistake worth making impossible: a surface is drawn into,
/// an image is read from.
pub enum Image {
    #[cfg(feature = "vulkan")]
    Vulkan(emblema_hal_vulkan::VulkanTexture),
    #[cfg(feature = "gles")]
    Gles(emblema_hal_gles::GlesTexture),
}

impl Image {
    pub fn extent(&self) -> Extent2D {
        match self {
            #[cfg(feature = "vulkan")]
            Self::Vulkan(texture) => texture.extent(),
            #[cfg(feature = "gles")]
            Self::Gles(texture) => texture.extent(),
        }
    }
}

/// Unwrap a table of images to one backend's textures.
///
/// An image from another backend is an error rather than a skip: the slots are
/// positional, so dropping one would silently shift every slot after it.
#[cfg(feature = "vulkan")]
fn vulkan_textures<'a>(images: &[&'a Image]) -> Result<Vec<&'a emblema_hal_vulkan::VulkanTexture>> {
    images
        .iter()
        .map(|image| match image {
            Image::Vulkan(texture) => Ok(texture),
            #[allow(unreachable_patterns)]
            _ => Err(Error::Unsupported(
                "this image was created by a different context",
            )),
        })
        .collect()
}

#[cfg(feature = "gles")]
fn gles_textures<'a>(images: &[&'a Image]) -> Result<Vec<&'a emblema_hal_gles::GlesTexture>> {
    images
        .iter()
        .map(|image| match image {
            Image::Gles(texture) => Ok(texture),
            #[allow(unreachable_patterns)]
            _ => Err(Error::Unsupported(
                "this image was created by a different context",
            )),
        })
        .collect()
}

pub enum Surface {
    #[cfg(feature = "vulkan")]
    Vulkan(emblema_hal_vulkan::VulkanTexture),
    #[cfg(feature = "gles")]
    Gles(emblema_hal_gles::GlesTexture),
}

impl Surface {
    pub fn extent(&self) -> Extent2D {
        match self {
            #[cfg(feature = "vulkan")]
            Self::Vulkan(texture) => texture.extent(),
            #[cfg(feature = "gles")]
            Self::Gles(texture) => texture.extent(),
        }
    }

    pub fn format(&self) -> PixelFormat {
        match self {
            #[cfg(feature = "vulkan")]
            Self::Vulkan(texture) => texture.format(),
            #[cfg(feature = "gles")]
            Self::Gles(texture) => texture.format(),
        }
    }
}