emblema 0.7.1

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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! Draw the picture at the top of the README.
//!
//! One frame that puts most of the drawing surface on screen at once: gradients
//! of three kinds, blurred layers, frosted glass over what is behind it, round
//! capped strokes along arcs and curves, dashing, clips, shadows and a blend.
//! There is no text, because rasterizing glyph outlines is the caller's job here
//! and an example that faked it would show the wrong thing.
//!
//! ```sh
//! cargo run -p emblema --example showcase -- showcase.ppm
//! magick showcase.ppm docs/images/showcase.png
//! ```
//!
//! Given a frame count as well, it draws that many frames of one seamless loop
//! instead, numbered after the path -- `showcase-000.ppm` onward -- through one
//! context and one surface, which is how an application's frame loop would use
//! them:
//!
//! ```sh
//! cargo run --release -p emblema --example showcase -- frames/showcase.ppm 60
//! ```
//!
//! Frame zero is the still picture.

use std::error::Error;
use std::f32::consts::{PI, TAU};

use emblema::{
    BackendPreference, BlendMode, Canvas, Color, Context, Dash, Extent2D, GradientStop, Layer,
    LineCap, LineJoin, Paint, Path, PathBuilder, PixelFormat, PointMode, Rect, StrokeStyle, Style,
    Surface, Vec2,
};

const WIDTH: u32 = 1280;
const HEIGHT: u32 = 640;
const SIZE: Extent2D = Extent2D {
    width: WIDTH,
    height: HEIGHT,
};

type Outcome<T = ()> = Result<T, Box<dyn Error>>;

/// More frames than a loop needs, and few enough that a mistyped count does not
/// fill a disk with uncompressed images.
const MAX_FRAMES: u32 = 1000;

fn main() {
    let mut args = std::env::args().skip(1);
    let path = args.next().unwrap_or_else(|| "showcase.ppm".into());
    let frames = match args.next().map(|n| n.parse::<u32>()) {
        None => None,
        Some(Ok(n)) if (1..=MAX_FRAMES).contains(&n) => Some(n),
        Some(_) => {
            eprintln!("showcase: the frame count must be a whole number from 1 to {MAX_FRAMES}");
            std::process::exit(2);
        }
    };
    if let Err(e) = run(&path, frames) {
        eprintln!("showcase: {e}");
        std::process::exit(1);
    }
}

fn run(path: &str, frames: Option<u32>) -> Outcome {
    let mut ctx = Context::new(BackendPreference::Auto)
        .map_err(|e| format!("no usable rendering backend: {e}"))?;
    eprintln!("{:?} on {}", ctx.backend(), ctx.capabilities().device_name);

    let mut surface = ctx.create_surface(SIZE, PixelFormat::Rgba8Unorm)?;
    // Nothing here frees a GPU object on drop, so the surface is destroyed on
    // the way out whether or not drawing into it worked.
    let drawn = render_all(&mut ctx, &mut surface, path, frames);
    ctx.destroy_surface(surface);
    drawn
}

fn render_all(
    ctx: &mut Context,
    surface: &mut Surface,
    path: &str,
    frames: Option<u32>,
) -> Outcome {
    let Some(count) = frames else {
        return render(ctx, surface, 0.0, path);
    };
    let stem = path.strip_suffix(".ppm").unwrap_or(path);
    for frame in 0..count {
        let phase = frame as f32 / count as f32;
        render(ctx, surface, phase, &format!("{stem}-{frame:03}.ppm"))?;
    }
    Ok(())
}

fn render(ctx: &mut Context, surface: &mut Surface, phase: f32, path: &str) -> Outcome {
    let recording = compose(phase)?;
    ctx.draw(surface, &recording)?;
    let pixels = ctx.read(surface)?;
    write_ppm(path, SIZE, &pixels).map_err(|e| format!("writing {path}: {e}"))?;
    eprintln!("wrote {path}");
    Ok(())
}

/// A displacement that loops once over a phase from zero to one.
///
/// Measured from where the wave stands at phase zero rather than from its
/// center, so every value it moves is exactly its still-picture value on frame
/// zero, and the still and the loop are the same picture at rest.
fn wobble(phase: f32, offset: f32, amplitude: f32) -> f32 {
    amplitude * ((TAU * phase + offset).sin() - offset.sin())
}

fn rgb(hex: u32) -> Color {
    rgba(hex, 1.0)
}

fn rgba(hex: u32, alpha: f32) -> Color {
    let c = |shift: u32| ((hex >> shift) & 0xff) as f32 / 255.0;
    Color::srgb(c(16), c(8), c(0), alpha)
}

fn stops(colors: &[(u32, f32)]) -> Vec<GradientStop> {
    colors
        .iter()
        .map(|&(hex, at)| GradientStop::new(rgb(hex), at))
        .collect()
}

fn stroke(paint: Paint, width: f32) -> Paint {
    paint.with_style(Style::Stroke(
        StrokeStyle::new(width)
            .with_cap(LineCap::Round)
            .with_join(LineJoin::Round),
    ))
}

fn compose(phase: f32) -> Outcome<emblema::Recording> {
    let mut canvas = Canvas::new(SIZE);
    let (w, h) = (WIDTH as f32, HEIGHT as f32);

    canvas.clear(rgb(0x0b1026));

    // Night sky.
    canvas.draw_rect(
        Rect::from_size(w, h),
        &Paint::linear_gradient(
            Vec2::new(0.0, 0.0),
            Vec2::new(w, h),
            stops(&[(0x0b1026, 0.0), (0x1a1446, 0.55), (0x2b0f3a, 1.0)]),
        ),
    )?;

    // Glowing blobs, blurred as one layer. They are what the glass panels
    // frost, so they have to be behind them.
    canvas.save_layer(Layer::opacity(0.85).with_blur(60.0));
    for (i, (center, radius, hex)) in [
        (Vec2::new(250.0, 170.0), 170.0, 0xff3d8b),
        (Vec2::new(620.0, 520.0), 200.0, 0x3d7bff),
        (Vec2::new(1010.0, 140.0), 180.0, 0x19d3c5),
        (Vec2::new(1150.0, 560.0), 120.0, 0xffa53d),
    ]
    .into_iter()
    .enumerate()
    {
        let k = i as f32 * 1.7;
        let drift = Vec2::new(
            center.x + wobble(phase, k, 40.0),
            center.y + wobble(phase, k + 1.3, 30.0),
        );
        canvas.draw_circle(drift, radius, &Paint::fill(rgb(hex)))?;
    }
    canvas.restore();

    // A faint dot grid, the kind of texture an interface background carries.
    // One draw for all of it: each point is a stroke's round cap.
    let grid: Vec<Vec2> = (0..HEIGHT / 32)
        .flat_map(|row| (0..WIDTH / 32).map(move |col| (row, col)))
        .map(|(row, col)| Vec2::new(20.0 + col as f32 * 32.0, 20.0 + row as f32 * 32.0))
        .collect();
    canvas.draw_points(
        PointMode::Points,
        &grid,
        &stroke(Paint::fill(rgba(0xffffff, 0.08)), 2.4),
    )?;

    let ring = Rect::new(60.0, 80.0, 400.0, 560.0);
    let chart = Rect::new(440.0, 80.0, 900.0, 400.0);
    let tiles = Rect::new(440.0, 440.0, 900.0, 560.0);
    let side = Rect::new(940.0, 80.0, 1220.0, 560.0);

    for panel in [ring, chart, tiles, side] {
        glass(&mut canvas, panel)?;
    }

    progress_ring(&mut canvas, ring, phase)?;
    line_chart(&mut canvas, chart, phase)?;
    bars(&mut canvas, tiles, phase)?;
    controls(&mut canvas, side, phase)?;

    Ok(canvas.finish())
}

/// A frosted panel: a shadow under it, a blur of whatever is behind it, a
/// translucent fill and a hairline edge catching the light.
fn glass(canvas: &mut Canvas, panel: Rect) -> Outcome {
    let radius = 28.0;
    canvas.draw_shadow(
        &panel.to_rounded_path(radius),
        rgba(0x000000, 0.6),
        18.0,
        true,
    )?;

    canvas.save();
    canvas.clip_path(&panel.to_rounded_path(radius))?;
    canvas.save_layer_bounds(Layer::opacity(1.0).with_backdrop_blur(24.0), panel);
    canvas.draw_rect(
        panel,
        &Paint::linear_gradient(
            Vec2::new(panel.left, panel.top),
            Vec2::new(panel.right, panel.bottom),
            vec![
                GradientStop::new(rgba(0xffffff, 0.16), 0.0),
                GradientStop::new(rgba(0xffffff, 0.05), 1.0),
            ],
        ),
    )?;
    canvas.restore();
    canvas.restore();

    canvas.draw_rrect(panel, radius, &Paint::stroke(rgba(0xffffff, 0.22), 1.5))?;
    Ok(())
}

fn arc_path(center: Vec2, radius: f32, start: f32, sweep: f32) -> Path {
    let mut b = PathBuilder::new();
    b.move_to(Vec2::new(
        center.x + radius * start.cos(),
        center.y + radius * start.sin(),
    ));
    b.arc(center, Vec2::new(radius, radius), start, sweep);
    b.build()
}

/// A progress ring: a track, an arc swept through a sweep gradient, and a
/// glowing knob at its end.
fn progress_ring(canvas: &mut Canvas, panel: Rect, phase: f32) -> Outcome {
    let center = Vec2::new((panel.left + panel.right) / 2.0, panel.top + 190.0);
    let radius = 110.0;
    let start = -PI / 2.0;
    let sweep = TAU * (0.72 + wobble(phase, 0.0, 0.16));

    canvas.draw_circle(
        center,
        radius,
        &stroke(Paint::fill(rgba(0xffffff, 0.10)), 22.0),
    )?;

    // Rotated so the arc starts at twelve o'clock while the gradient's seam
    // stays at its own zero angle, far enough behind the arc that the round
    // cap at its start does not reach across it.
    let lead = 0.2;
    canvas.save();
    canvas.translate(center.x, center.y);
    canvas.rotate(start - lead);
    let origin = Vec2::new(0.0, 0.0);
    let gradient = Paint::sweep_gradient(
        origin,
        0.0,
        lead + sweep,
        stops(&[
            (0x19d3c5, 0.0),
            (0x3d7bff, 0.45),
            (0xb54dff, 0.8),
            (0xff3d8b, 1.0),
        ]),
    );
    canvas.draw_path(
        &arc_path(origin, radius, lead, sweep),
        &stroke(gradient, 22.0),
    )?;

    let tip = Vec2::new(radius * (lead + sweep).cos(), radius * (lead + sweep).sin());
    canvas.save_layer(Layer::opacity(0.9).with_blur(10.0));
    canvas.draw_circle(tip, 18.0, &Paint::fill(rgb(0xff3d8b)))?;
    canvas.restore();
    canvas.draw_circle(tip, 8.0, &Paint::fill(rgb(0xffffff)))?;
    canvas.restore();

    // An inner disc with a radial gradient, where a number would go.
    canvas.draw_circle(
        center,
        70.0,
        &Paint::radial_gradient(
            Vec2::new(center.x - 20.0, center.y - 25.0),
            90.0,
            vec![
                GradientStop::new(rgba(0xffffff, 0.14), 0.0),
                GradientStop::new(rgba(0xffffff, 0.02), 1.0),
            ],
        ),
    )?;

    // Three legend rows: a swatch and a rounded placeholder line each.
    for (i, hex) in [0x19d3c5u32, 0x3d7bff, 0xff3d8b].into_iter().enumerate() {
        let top = panel.top + 350.0 + i as f32 * 36.0;
        canvas.draw_rrect(
            Rect::new(panel.left + 40.0, top, panel.left + 60.0, top + 20.0),
            6.0,
            &Paint::fill(rgb(hex)),
        )?;
        let len = [170.0, 120.0, 200.0][i];
        canvas.draw_rrect(
            Rect::new(
                panel.left + 76.0,
                top + 5.0,
                panel.left + 76.0 + len,
                top + 15.0,
            ),
            5.0,
            &Paint::fill(rgba(0xffffff, 0.25)),
        )?;
    }
    Ok(())
}

/// A smooth line over dashed gridlines, with the area under it filled by a
/// gradient that fades out toward the axis.
fn line_chart(canvas: &mut Canvas, panel: Rect, phase: f32) -> Outcome {
    let inner = Rect::new(
        panel.left + 36.0,
        panel.top + 40.0,
        panel.right - 36.0,
        panel.bottom - 36.0,
    );

    for i in 0..4 {
        let y = inner.top + i as f32 * inner.height() / 3.0;
        let mut b = PathBuilder::new();
        b.move_to(Vec2::new(inner.left, y));
        b.line_to(Vec2::new(inner.right, y));
        canvas.draw_path(
            &b.build(),
            &Paint::stroke(rgba(0xffffff, 0.14), 1.0).with_dash(Dash::new(vec![6.0, 6.0], 0.0)),
        )?;
    }

    let values = [0.35f32, 0.55, 0.42, 0.78, 0.60, 0.92, 0.70, 0.84];
    let points: Vec<Vec2> = values
        .iter()
        .enumerate()
        .map(|(i, v)| {
            let v = (v + wobble(phase, i as f32 * 0.9, 0.08)).clamp(0.05, 0.98);
            Vec2::new(
                inner.left + i as f32 * inner.width() / (values.len() - 1) as f32,
                inner.bottom - v * inner.height(),
            )
        })
        .collect();

    let curve = |b: &mut PathBuilder| {
        for pair in points.windows(2) {
            let (a, c) = (pair[0], pair[1]);
            let mid = (c.x - a.x) / 2.0;
            b.cubic_to(Vec2::new(a.x + mid, a.y), Vec2::new(c.x - mid, c.y), c);
        }
    };

    let mut area = PathBuilder::new();
    area.move_to(Vec2::new(inner.left, inner.bottom));
    area.line_to(points[0]);
    curve(&mut area);
    area.line_to(Vec2::new(inner.right, inner.bottom));
    area.close();
    canvas.draw_path(
        &area.build(),
        &Paint::linear_gradient(
            Vec2::new(0.0, inner.top),
            Vec2::new(0.0, inner.bottom),
            vec![
                GradientStop::new(rgba(0x19d3c5, 0.45), 0.0),
                GradientStop::new(rgba(0x3d7bff, 0.0), 1.0),
            ],
        ),
    )?;

    let mut line = PathBuilder::new();
    line.move_to(points[0]);
    curve(&mut line);
    let line = line.build();
    let line_paint = Paint::linear_gradient(
        Vec2::new(inner.left, 0.0),
        Vec2::new(inner.right, 0.0),
        stops(&[(0x19d3c5, 0.0), (0x3d7bff, 0.5), (0xff3d8b, 1.0)]),
    );

    // The same line twice: once wide and blurred for a glow, once crisp.
    canvas.save_layer(Layer::opacity(0.8).with_blur(8.0));
    canvas.draw_path(&line, &stroke(line_paint.clone(), 10.0))?;
    canvas.restore();
    canvas.draw_path(&line, &stroke(line_paint, 4.0))?;

    for p in &points {
        canvas.draw_circle(*p, 6.0, &Paint::fill(rgb(0x0b1026)))?;
        canvas.draw_circle(*p, 6.0, &Paint::stroke(rgb(0xffffff), 2.5))?;
    }
    Ok(())
}

/// A row of rounded bars, each its own gradient.
fn bars(canvas: &mut Canvas, panel: Rect, phase: f32) -> Outcome {
    let heights = [0.45f32, 0.7, 0.55, 0.9, 0.6, 0.8, 0.4, 0.65, 0.75, 0.5];
    let gap = 14.0;
    let left = panel.left + 32.0;
    let span = panel.width() - 64.0;
    let width = (span - gap * (heights.len() - 1) as f32) / heights.len() as f32;
    let bottom = panel.bottom - 24.0;
    let tall = panel.height() - 48.0;
    for (i, v) in heights.iter().enumerate() {
        let x = left + i as f32 * (width + gap);
        let v = (v + wobble(phase, i as f32 * 0.7, 0.15)).clamp(0.15, 1.0);
        let bar = Rect::new(x, bottom - v * tall, x + width, bottom);
        let (from, to) = if i % 2 == 0 {
            (0xb54dff, 0x3d7bff)
        } else {
            (0xff3d8b, 0xffa53d)
        };
        canvas.draw_rrect(
            bar,
            width / 2.0,
            &Paint::linear_gradient(
                Vec2::new(0.0, bar.top),
                Vec2::new(0.0, bar.bottom),
                stops(&[(from, 0.0), (to, 1.0)]),
            ),
        )?;
    }
    Ok(())
}

/// A donut chart, toggles and a slider: the shapes a settings panel is made of.
fn controls(canvas: &mut Canvas, panel: Rect, phase: f32) -> Outcome {
    let center = Vec2::new((panel.left + panel.right) / 2.0, panel.top + 120.0);
    let radius = 72.0;
    let segments = [
        (0.38f32, 0xff3d8b),
        (0.27, 0xffa53d),
        (0.21, 0x19d3c5),
        (0.14, 0x3d7bff),
    ];
    // One full turn per loop, which is what keeps the loop seamless.
    let mut at = -PI / 2.0 + TAU * phase;
    for (share, hex) in segments {
        let sweep = share * TAU - 0.12;
        canvas.draw_path(
            &arc_path(center, radius, at + 0.06, sweep),
            &Paint::stroke(rgb(hex), 26.0),
        )?;
        at += share * TAU;
    }

    // Toggles: two on, one off.
    for (i, on) in [true, false, true].into_iter().enumerate() {
        let top = panel.top + 250.0 + i as f32 * 56.0;
        let track = Rect::new(panel.right - 104.0, top, panel.right - 40.0, top + 32.0);
        let paint = if on {
            Paint::linear_gradient(
                Vec2::new(track.left, 0.0),
                Vec2::new(track.right, 0.0),
                stops(&[(0xb54dff, 0.0), (0xff3d8b, 1.0)]),
            )
        } else {
            Paint::fill(rgba(0xffffff, 0.15))
        };
        canvas.draw_rrect(track, 16.0, &paint)?;
        let knob_x = if on {
            track.right - 16.0
        } else {
            track.left + 16.0
        };
        canvas.draw_circle(
            Vec2::new(knob_x, top + 16.0),
            12.0,
            &Paint::fill(rgb(0xffffff)),
        )?;
        let len = [110.0, 80.0, 130.0][i];
        canvas.draw_rrect(
            Rect::new(
                panel.left + 40.0,
                top + 11.0,
                panel.left + 40.0 + len,
                top + 21.0,
            ),
            5.0,
            &Paint::fill(rgba(0xffffff, 0.25)),
        )?;
    }

    // A slider, with its knob lifted on a shadow.
    let y = panel.bottom - 56.0;
    let track = Rect::new(panel.left + 40.0, y - 4.0, panel.right - 40.0, y + 4.0);
    canvas.draw_rrect(track, 4.0, &Paint::fill(rgba(0xffffff, 0.15)))?;
    let knob = track.left + track.width() * (0.62 + wobble(phase, 0.0, 0.2));
    canvas.draw_rrect(
        Rect::new(track.left, track.top, knob, track.bottom),
        4.0,
        &Paint::linear_gradient(
            Vec2::new(track.left, 0.0),
            Vec2::new(knob, 0.0),
            stops(&[(0x19d3c5, 0.0), (0x3d7bff, 1.0)]),
        ),
    )?;
    let knob_rect = Rect::new(knob - 14.0, y - 14.0, knob + 14.0, y + 14.0);
    canvas.draw_shadow(
        &knob_rect.to_rounded_path(14.0),
        rgba(0x000000, 0.8),
        6.0,
        false,
    )?;
    canvas.draw_circle(Vec2::new(knob, y), 14.0, &Paint::fill(rgb(0xffffff)))?;

    // A sparkle where the blobs are brightest, added rather than painted over.
    canvas.draw_circle(
        Vec2::new(panel.right - 46.0, panel.top + 40.0),
        22.0,
        &Paint::radial_gradient(
            Vec2::new(panel.right - 46.0, panel.top + 40.0),
            22.0,
            vec![
                GradientStop::new(rgba(0xffffff, 0.9), 0.0),
                GradientStop::new(rgba(0xffffff, 0.0), 1.0),
            ],
        )
        .with_blend(BlendMode::Plus),
    )?;
    Ok(())
}

/// Write tightly packed RGBA as a binary PPM, dropping alpha.
fn write_ppm(path: &str, extent: Extent2D, pixels: &[u8]) -> std::io::Result<()> {
    use std::io::Write as _;

    let mut out = std::io::BufWriter::new(std::fs::File::create(path)?);
    write!(out, "P6\n{} {}\n255\n", extent.width, extent.height)?;
    let mut rgb = Vec::with_capacity(pixels.len() / 4 * 3);
    for texel in pixels.chunks_exact(4) {
        rgb.extend_from_slice(&texel[..3]);
    }
    out.write_all(&rgb)?;
    out.flush()
}