rouge-render 0.1.0

wgpu renderer, effects and shared GPU surfaces for Rouge
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
551
use crate::{Color, Corners, Point, Rect};
use std::ptr;

const SHADOW_REACH: f32 = 28.0;
const HEADER: usize = 4;
/// From the upper left, so the top and left edges catch the light.
const DIAGONAL_RIM_ANGLE: f32 = -0.643_501_1;
pub(crate) const PASSTHROUGH_WGSL: &str = include_str!("shaders/passthrough.wgsl");

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Inputs(u8);

impl Inputs {
    pub const CONTENT: Inputs = Inputs(1);
    pub const BACKDROP: Inputs = Inputs(2);
    pub const BOTH: Inputs = Inputs(3);

    pub const fn content(self) -> bool {
        self.0 & 1 != 0
    }

    pub const fn backdrop(self) -> bool {
        self.0 & 2 != 0
    }
}

pub trait ShaderEffect: 'static {
    const WGSL: &'static str;
    const INPUTS: Inputs;
    const CLOCK: Option<usize> = None;

    fn uniforms(&self, _uniforms: &mut [f32; EffectInstance::UNIFORMS]) {}

    fn margin(&self) -> f32 {
        0.0
    }

    fn content_blur(&self) -> f32 {
        0.0
    }

    fn backdrop_blur(&self) -> f32 {
        0.0
    }

    fn backdrop_reach(&self) -> Option<f32> {
        None
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EffectInstance {
    wgsl: &'static str,
    inputs: Inputs,
    clock: Option<usize>,
    values: [f32; EffectInstance::VALUES],
}

impl EffectInstance {
    pub const UNIFORMS: usize = 16;
    pub const VALUES: usize = Self::UNIFORMS + HEADER;

    pub fn new<T: ShaderEffect>(effect: &T) -> Self {
        assert!(
            T::CLOCK.is_none_or(|index| index < Self::UNIFORMS),
            "rouge: an effect's clock is one of its {} uniform values",
            Self::UNIFORMS
        );
        let mut uniforms = [0.0; Self::UNIFORMS];
        effect.uniforms(&mut uniforms);
        let mut values = [0.0; Self::VALUES];
        values[0] = effect.margin().max(0.0);
        values[1] = effect.content_blur().max(0.0);
        values[2] = effect.backdrop_blur().max(0.0);
        values[3] = effect.backdrop_reach().map_or(-1.0, |reach| reach.max(0.0));
        values[HEADER..].copy_from_slice(&uniforms);
        EffectInstance {
            wgsl: T::WGSL,
            inputs: T::INPUTS,
            clock: T::CLOCK,
            values,
        }
    }

    pub fn with_values(self, values: [f32; Self::VALUES]) -> Self {
        EffectInstance { values, ..self }
    }

    pub fn at(mut self, seconds: f32) -> Self {
        if let Some(index) = self.clock {
            self.values[HEADER + index] = seconds;
        }
        self
    }

    pub fn wgsl(&self) -> &'static str {
        self.wgsl
    }

    pub fn same_shader(&self, other: &EffectInstance) -> bool {
        self.inputs == other.inputs
            && self.clock == other.clock
            && (ptr::eq(self.wgsl, other.wgsl) || self.wgsl == other.wgsl)
    }

    pub fn inputs(&self) -> Inputs {
        self.inputs
    }

    pub fn clock(&self) -> Option<usize> {
        self.clock
    }

    pub fn values(&self) -> &[f32; Self::VALUES] {
        &self.values
    }

    pub fn margin(&self) -> f32 {
        self.values[0]
    }

    pub fn content_blur(&self) -> f32 {
        self.values[1]
    }

    pub fn backdrop_blur(&self) -> f32 {
        self.values[2]
    }

    pub fn backdrop_reach(&self) -> Option<f32> {
        Some(self.values[3]).filter(|reach| *reach >= 0.0)
    }

    pub fn uniforms(&self) -> [f32; Self::UNIFORMS] {
        let mut uniforms = [0.0; Self::UNIFORMS];
        uniforms.copy_from_slice(&self.values[HEADER..]);
        uniforms
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EffectDraw {
    pub effect: EffectInstance,
    pub bounds: Rect,
    pub corner_radii: Corners,
}

impl EffectDraw {
    pub fn new<T: ShaderEffect>(effect: &T, bounds: Rect) -> Self {
        EffectDraw {
            effect: EffectInstance::new(effect),
            bounds,
            corner_radii: Corners::ZERO,
        }
    }
}

pub(crate) struct Passthrough;

impl ShaderEffect for Passthrough {
    const WGSL: &'static str = PASSTHROUGH_WGSL;
    const INPUTS: Inputs = Inputs::CONTENT;
}

pub(crate) struct SurfaceSample {
    pub opaque: bool,
}

impl ShaderEffect for SurfaceSample {
    const WGSL: &'static str = include_str!("shaders/surface.wgsl");
    const INPUTS: Inputs = Inputs::CONTENT;

    fn uniforms(&self, uniforms: &mut [f32; EffectInstance::UNIFORMS]) {
        uniforms[0] = f32::from(u8::from(self.opaque));
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Blur {
    pub radius: f32,
}

impl Blur {
    pub const fn new(radius: f32) -> Self {
        Blur { radius }
    }
}

impl ShaderEffect for Blur {
    const WGSL: &'static str = PASSTHROUGH_WGSL;
    const INPUTS: Inputs = Inputs::CONTENT;

    fn content_blur(&self) -> f32 {
        self.radius
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BackdropBlur {
    pub radius: f32,
}

impl BackdropBlur {
    pub const fn new(radius: f32) -> Self {
        BackdropBlur { radius }
    }
}

impl ShaderEffect for BackdropBlur {
    const WGSL: &'static str = include_str!("shaders/backdrop_blur.wgsl");
    const INPUTS: Inputs = Inputs::BACKDROP;

    fn margin(&self) -> f32 {
        1.0
    }

    fn backdrop_blur(&self) -> f32 {
        self.radius
    }

    fn backdrop_reach(&self) -> Option<f32> {
        Some(0.0)
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ColorMatrix {
    pub rows: [[f32; 4]; 3],
}

const LUMA: [f32; 3] = [0.2126, 0.7152, 0.0722];

impl ColorMatrix {
    pub const IDENTITY: ColorMatrix = ColorMatrix {
        rows: [
            [1.0, 0.0, 0.0, 0.0],
            [0.0, 1.0, 0.0, 0.0],
            [0.0, 0.0, 1.0, 0.0],
        ],
    };

    pub const fn new(rows: [[f32; 4]; 3]) -> Self {
        ColorMatrix { rows }
    }

    pub fn saturate(amount: f32) -> Self {
        let mut rows = [[0.0; 4]; 3];
        for (row, cells) in rows.iter_mut().enumerate() {
            for (column, luma) in LUMA.into_iter().enumerate() {
                cells[column] = luma * (1.0 - amount) + if row == column { amount } else { 0.0 };
            }
        }
        ColorMatrix { rows }
    }

    pub fn grayscale() -> Self {
        Self::saturate(0.0)
    }

    pub fn brightness(amount: f32) -> Self {
        Self::scale(amount, 0.0)
    }

    pub fn contrast(amount: f32) -> Self {
        Self::scale(amount, 0.5 - 0.5 * amount)
    }

    pub fn invert() -> Self {
        Self::scale(-1.0, 1.0)
    }

    pub fn tint(color: Color) -> Self {
        let mut matrix = Self::IDENTITY;
        for (cells, channel) in matrix.rows.iter_mut().zip([color.r, color.g, color.b]) {
            for cell in cells.iter_mut().take(3) {
                *cell *= 1.0 - color.a;
            }
            cells[3] = channel * color.a;
        }
        matrix
    }

    pub fn then(&self, next: &ColorMatrix) -> ColorMatrix {
        let mut rows = [[0.0; 4]; 3];
        for (out, by) in rows.iter_mut().zip(next.rows) {
            for (column, cell) in out.iter_mut().enumerate() {
                let through: f32 = (0..3).map(|k| by[k] * self.rows[k][column]).sum();
                *cell = through + if column == 3 { by[3] } else { 0.0 };
            }
        }
        ColorMatrix { rows }
    }

    fn scale(factor: f32, offset: f32) -> Self {
        let mut matrix = Self::IDENTITY;
        for (index, cells) in matrix.rows.iter_mut().enumerate() {
            cells[index] = factor;
            cells[3] = offset;
        }
        matrix
    }
}

impl ShaderEffect for ColorMatrix {
    const WGSL: &'static str = include_str!("shaders/color_matrix.wgsl");
    const INPUTS: Inputs = Inputs::CONTENT;

    fn uniforms(&self, uniforms: &mut [f32; EffectInstance::UNIFORMS]) {
        uniforms[..12].copy_from_slice(self.rows.as_flattened());
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
enum MaskKind {
    Linear { from: Point, to: Point },
    Radial { center: Point, radius: f32 },
    Shape,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Mask {
    kind: MaskKind,
    stops: (f32, f32),
    inverted: bool,
}

impl Mask {
    const fn of(kind: MaskKind) -> Self {
        Mask {
            kind,
            stops: (0.0, 1.0),
            inverted: false,
        }
    }

    pub const fn linear_gradient(from: Point, to: Point) -> Self {
        Mask::of(MaskKind::Linear { from, to })
    }

    pub const fn radial_gradient(center: Point, radius: f32) -> Self {
        Mask::of(MaskKind::Radial { center, radius })
    }

    pub const fn shape() -> Self {
        Mask::of(MaskKind::Shape)
    }

    pub const fn stops(mut self, opaque_until: f32, clear_from: f32) -> Self {
        self.stops = (opaque_until, clear_from);
        self
    }

    pub const fn invert(mut self) -> Self {
        self.inverted = true;
        self
    }
}

impl ShaderEffect for Mask {
    const WGSL: &'static str = include_str!("shaders/mask.wgsl");
    const INPUTS: Inputs = Inputs::CONTENT;

    fn uniforms(&self, uniforms: &mut [f32; EffectInstance::UNIFORMS]) {
        let (kind, shape) = match self.kind {
            MaskKind::Linear { from, to } => (0.0, [from.x, from.y, to.x, to.y]),
            MaskKind::Radial { center, radius } => (1.0, [center.x, center.y, radius, 0.0]),
            MaskKind::Shape => (2.0, [0.0; 4]),
        };
        uniforms[..4].copy_from_slice(&[
            kind,
            f32::from(u8::from(self.inverted)),
            self.stops.0,
            self.stops.1,
        ]);
        uniforms[4..8].copy_from_slice(&shape);
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BlendMode {
    Multiply,
    Screen,
    Overlay,
    Darken,
    Lighten,
    ColorDodge,
    ColorBurn,
    HardLight,
    SoftLight,
    Difference,
    Exclusion,
    PlusLighter,
}

impl ShaderEffect for BlendMode {
    const WGSL: &'static str = include_str!("shaders/blend.wgsl");
    const INPUTS: Inputs = Inputs::BOTH;

    fn uniforms(&self, uniforms: &mut [f32; EffectInstance::UNIFORMS]) {
        uniforms[0] = f32::from(*self as u8);
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Glass {
    blur: f32,
    tint: Color,
    refraction: f32,
    dispersion: f32,
    highlight: f32,
    edge_width: f32,
    shadow: f32,
    saturation: f32,
    light: Point,
    light_strength: f32,
    light_reach: f32,
    rim_angle: f32,
    rim_fill: f32,
}

impl Default for Glass {
    fn default() -> Self {
        Self::new()
    }
}

impl Glass {
    pub const fn new() -> Self {
        Glass {
            blur: 10.0,
            tint: Color::new(1.0, 1.0, 1.0, 0.08),
            refraction: 0.7,
            dispersion: 0.12,
            highlight: 0.35,
            edge_width: 14.0,
            shadow: 0.25,
            saturation: 1.0,
            light: Point::new(0.0, 0.0),
            light_strength: 0.0,
            light_reach: 1.0,
            rim_angle: DIAGONAL_RIM_ANGLE,
            rim_fill: 0.6,
        }
    }

    pub const fn frosted(blur: f32) -> Self {
        Glass {
            blur,
            tint: Color::TRANSPARENT,
            refraction: 0.0,
            dispersion: 0.0,
            highlight: 0.0,
            edge_width: 1.0,
            shadow: 0.0,
            ..Glass::new()
        }
    }

    pub const fn blur(mut self, radius: f32) -> Self {
        self.blur = radius;
        self
    }

    pub const fn tint(mut self, tint: Color) -> Self {
        self.tint = tint;
        self
    }

    pub const fn refraction(mut self, amount: f32) -> Self {
        self.refraction = amount;
        self
    }

    pub const fn dispersion(mut self, amount: f32) -> Self {
        self.dispersion = amount;
        self
    }

    pub const fn highlight(mut self, amount: f32) -> Self {
        self.highlight = amount;
        self
    }

    pub const fn edge_width(mut self, width: f32) -> Self {
        self.edge_width = width;
        self
    }

    pub const fn shadow(mut self, amount: f32) -> Self {
        self.shadow = amount;
        self
    }

    pub const fn saturation(mut self, amount: f32) -> Self {
        self.saturation = amount;
        self
    }

    pub const fn light(mut self, at: Point, strength: f32, reach: f32) -> Self {
        self.light = at;
        self.light_strength = strength;
        self.light_reach = reach;
        self
    }

    /// Aims the light that catches the rim: `angle` is where it shines from, in radians clockwise
    /// from straight up, and `fill` is how much of it bounces onto the opposite edge.
    pub const fn rim_light(mut self, angle: f32, fill: f32) -> Self {
        self.rim_angle = angle;
        self.rim_fill = fill;
        self
    }
}

impl ShaderEffect for Glass {
    const WGSL: &'static str = include_str!("shaders/glass.wgsl");
    const INPUTS: Inputs = Inputs::BACKDROP;

    fn uniforms(&self, uniforms: &mut [f32; EffectInstance::UNIFORMS]) {
        uniforms[..4].copy_from_slice(&self.tint.to_array());
        uniforms[4..].copy_from_slice(&[
            self.refraction,
            self.dispersion,
            self.highlight,
            self.edge_width,
            self.shadow,
            self.saturation,
            self.light.x,
            self.light.y,
            self.light_strength,
            self.light_reach,
            self.rim_angle,
            self.rim_fill,
        ]);
    }

    fn margin(&self) -> f32 {
        let outward =
            (-self.refraction).max(0.0) * self.edge_width * 2.0 * (1.0 + self.dispersion.abs());
        let shadow = if self.shadow > 0.0 { SHADOW_REACH } else { 1.0 };
        shadow.max(outward)
    }

    fn backdrop_blur(&self) -> f32 {
        self.blur
    }

    fn backdrop_reach(&self) -> Option<f32> {
        Some(self.refraction.abs() * self.edge_width * 2.0 * (1.0 + self.dispersion.abs()))
    }
}