rcus-render 0.2.0

wgpu renderer for rcus: solid quads, a runtime glyph atlas, and scissored text
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
use wgpu::ShaderSource;

use crate::quad::{BoxVertex, TextVertex};

const BOX_SHADER: &str = r#"
struct VsOut {
    @builtin(position) position: vec4<f32>,
    @location(0) local: vec2<f32>,
    @location(1) half: vec2<f32>,
    @location(2) radius: f32,
    @location(3) border_width: f32,
    @location(4) fill: vec4<f32>,
    @location(5) border: vec4<f32>,
    @location(6) shadow_offset: vec2<f32>,
    @location(7) shadow_blur: f32,
    @location(8) shadow_spread: f32,
    @location(9) shadow_color: vec4<f32>,
};

@vertex
fn vs(
    @location(0) position: vec2<f32>,
    @location(1) local: vec2<f32>,
    @location(2) half: vec2<f32>,
    @location(3) radius: f32,
    @location(4) border_width: f32,
    @location(5) fill: vec4<f32>,
    @location(6) border: vec4<f32>,
    @location(7) shadow_offset: vec2<f32>,
    @location(8) shadow_blur: f32,
    @location(9) shadow_spread: f32,
    @location(10) shadow_color: vec4<f32>,
) -> VsOut {
    var output: VsOut;
    output.position = vec4<f32>(position, 0.0, 1.0);
    output.local = local;
    output.half = half;
    output.radius = radius;
    output.border_width = border_width;
    output.fill = fill;
    output.border = border;
    output.shadow_offset = shadow_offset;
    output.shadow_blur = shadow_blur;
    output.shadow_spread = shadow_spread;
    output.shadow_color = shadow_color;
    return output;
}

// Distance in pixels from `p` to the edge of a box centred on the origin. A
// radius of zero makes this the distance to a plain rectangle, which is why a
// flat box needs no special case anywhere else.
fn sd_box(p: vec2<f32>, half: vec2<f32>, radius: f32) -> f32 {
    let r = min(radius, min(half.x, half.y));
    let q = abs(p) - half + vec2<f32>(r, r);
    return length(max(q, vec2<f32>(0.0, 0.0))) + min(max(q.x, q.y), 0.0) - r;
}

// One layer of translucent colour over what is already there, in straight
// alpha, because the target blends with src-alpha.
fn over(base_rgb: vec3<f32>, base_a: f32, top_rgb: vec3<f32>, top_a: f32) -> vec4<f32> {
    let a = top_a + base_a * (1.0 - top_a);
    if a <= 0.0 {
        return vec4<f32>(0.0, 0.0, 0.0, 0.0);
    }
    let rgb = (top_rgb * top_a + base_rgb * base_a * (1.0 - top_a)) / a;
    return vec4<f32>(rgb, a);
}

@fragment
fn fs(input: VsOut) -> @location(0) vec4<f32> {
    let sd = sd_box(input.local, input.half, input.radius);
    // `sd` is in pixels, so one unit of it is one pixel of softness.
    let fill_mask = 1.0 - smoothstep(-0.5, 0.5, sd);

    var color = over(
        vec3<f32>(0.0, 0.0, 0.0),
        0.0,
        input.fill.rgb,
        fill_mask * input.fill.a,
    );

    if input.shadow_color.a > 0.0 {
        let spread = input.shadow_spread;
        let ssd = sd_box(
            input.local - input.shadow_offset,
            input.half + vec2<f32>(spread, spread),
            input.radius + spread,
        );
        let blur = max(input.shadow_blur, 0.001);
        let mask = 1.0 - smoothstep(-blur, blur, ssd);
        color = over(color.rgb, color.a, input.shadow_color.rgb, mask * input.shadow_color.a);
    }

    if input.border_width > 0.0 && input.border.a > 0.0 {
        // The border is the ring between the edge and one border-width inside
        // it: distance from the edge greater than zero, and no more than the
        // border's width. Masking only on the inner bound would flood the whole
        // interior with the border colour.
        let outside = smoothstep(-0.5, 0.5, sd + input.border_width);
        let inside = 1.0 - smoothstep(-0.5, 0.5, sd);
        let mask = outside * inside;
        color = over(color.rgb, color.a, input.border.rgb, mask * input.border.a);
    }

    return color;
}
"#;

const TEXT_SHADER: &str = r#"
struct Uniforms {
    viewport: vec2<f32>,
};

@group(0) @binding(0) var<uniform> uniforms: Uniforms;
@group(0) @binding(1) var atlas: texture_2d_array<f32>;
@group(0) @binding(2) var atlas_sampler: sampler;

struct VsOut {
    @builtin(position) position: vec4<f32>,
    @location(0) uv: vec2<f32>,
    @location(1) color: vec4<f32>,
    @location(2) @interpolate(flat) layer: f32,
};

@vertex
fn vs(
    @location(0) position: vec2<f32>,
    @location(1) uv: vec2<f32>,
    @location(2) color: vec4<f32>,
    @location(3) layer: f32,
) -> VsOut {
    var output: VsOut;
    let ndc = vec2<f32>(
        position.x / uniforms.viewport.x * 2.0 - 1.0,
        1.0 - position.y / uniforms.viewport.y * 2.0,
    );
    output.position = vec4<f32>(ndc, 0.0, 1.0);
    output.uv = uv;
    output.color = color;
    output.layer = layer;
    return output;
}

@fragment
fn fs(input: VsOut) -> @location(0) vec4<f32> {
    let coverage = textureSample(atlas, atlas_sampler, input.uv, i32(input.layer)).r;
    return vec4<f32>(input.color.rgb, input.color.a * coverage);
}
"#;

/// Viewport size, uploaded once per frame and read by the text shader.
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Viewport {
    pub width: f32,
    pub height: f32,
}

pub struct SolidPipeline {
    pub pipeline: wgpu::RenderPipeline,
}

pub struct TextPipeline {
    pub pipeline: wgpu::RenderPipeline,
    pub layout: wgpu::PipelineLayout,
    pub bind_group_layout: wgpu::BindGroupLayout,
    pub uniform: wgpu::Buffer,
    pub sampler: wgpu::Sampler,
    pub bind_group: wgpu::BindGroup,
    /// The atlas array and the layer count it was built for. A new glyph only
    /// re-uploads coverage; a new size adds a layer and rebuilds the view.
    atlas: Option<(wgpu::Texture, wgpu::TextureView, usize)>,
}

impl SolidPipeline {
    pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> anyhow::Result<Self> {
        // The box pass blends: an antialiased corner and a translucent overlay
        // both need the destination, so `replace` would chop them.
        let targets = blended_target(format);
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("rcus-box-shader"),
            source: ShaderSource::Wgsl(BOX_SHADER.into()),
        });
        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("rcus-solid-layout"),
            bind_group_layouts: &[],
            push_constant_ranges: &[],
        });
        Ok(Self {
            pipeline: device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("rcus-box-pipeline"),
                layout: Some(&layout),
                vertex: vertex_state(&shader, &box_attributes()),
                fragment: Some(fragment_state(&shader, &targets)),
                primitive: primitive_state(),
                depth_stencil: None,
                multisample: wgpu::MultisampleState::default(),
                multiview: None,
                cache: None,
            }),
        })
    }
}

impl TextPipeline {
    pub fn new(
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        format: wgpu::TextureFormat,
    ) -> anyhow::Result<Self> {
        let targets = blended_target(format);
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("rcus-text-shader"),
            source: ShaderSource::Wgsl(TEXT_SHADER.into()),
        });
        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("rcus-text-bind-group-layout"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::VERTEX,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: wgpu::BufferSize::new(
                            std::mem::size_of::<Viewport>() as u64
                        ),
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2Array,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
            ],
        });
        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("rcus-text-layout"),
            bind_group_layouts: &[&bind_group_layout],
            push_constant_ranges: &[],
        });
        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("rcus-text-pipeline"),
            layout: Some(&layout),
            vertex: vertex_state(&shader, &text_attributes()),
            fragment: Some(fragment_state(&shader, &targets)),
            primitive: primitive_state(),
            depth_stencil: None,
            multisample: wgpu::MultisampleState::default(),
            multiview: None,
            cache: None,
        });
        let uniform = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("rcus-viewport-uniform"),
            size: std::mem::size_of::<Viewport>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });
        queue.write_buffer(
            &uniform,
            0,
            bytemuck::bytes_of(&Viewport {
                width: 1.0,
                height: 1.0,
            }),
        );
        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("rcus-atlas-sampler"),
            mag_filter: wgpu::FilterMode::Linear,
            min_filter: wgpu::FilterMode::Linear,
            mipmap_filter: wgpu::FilterMode::Nearest,
            address_mode_u: wgpu::AddressMode::ClampToEdge,
            address_mode_v: wgpu::AddressMode::ClampToEdge,
            ..Default::default()
        });
        let atlas = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("rcus-atlas-placeholder"),
            size: wgpu::Extent3d {
                width: 1,
                height: 1,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::R8Unorm,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
            view_formats: &[],
        });
        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rcus-text-bind-group"),
            layout: &bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: uniform.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(&atlas.create_view(
                        &wgpu::TextureViewDescriptor {
                            dimension: Some(wgpu::TextureViewDimension::D2Array),
                            ..Default::default()
                        },
                    )),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::Sampler(&sampler),
                },
            ],
        });
        Ok(Self {
            pipeline,
            layout,
            bind_group_layout,
            uniform,
            sampler,
            bind_group,
            atlas: None,
        })
    }

    /// Brings the glyph atlas in line with the shaped layers, rebuilding the
    /// array only when the layer count changed.
    pub fn sync_atlas(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        set: &crate::text::AtlasSet,
    ) {
        let layers = set.layers();
        let current = self.atlas.as_ref().map(|(_, _, count)| *count);
        if current == Some(layers) {
            if let Some((texture, _, _)) = self.atlas.as_ref() {
                crate::text::upload_atlas_layers(queue, texture, set);
            }
            return;
        }
        let texture = crate::text::create_atlas_texture(device, layers);
        crate::text::upload_atlas_layers(queue, &texture, set);
        let view = crate::text::atlas_view(&texture);
        self.set_atlas(device, &view);
        self.atlas = Some((texture, view, layers));
    }

    /// Points the pipeline at the current atlas array.
    fn set_atlas(&mut self, device: &wgpu::Device, view: &wgpu::TextureView) {
        self.bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("rcus-text-bind-group"),
            layout: &self.bind_group_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: self.uniform.as_entire_binding(),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::TextureView(view),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::Sampler(&self.sampler),
                },
            ],
        });
    }

    pub fn set_viewport(&self, queue: &wgpu::Queue, width: f32, height: f32) {
        queue.write_buffer(
            &self.uniform,
            0,
            bytemuck::bytes_of(&Viewport { width, height }),
        );
    }
}

fn vertex_state<'a>(
    module: &'a wgpu::ShaderModule,
    buffers: &'a [wgpu::VertexBufferLayout<'a>],
) -> wgpu::VertexState<'a> {
    wgpu::VertexState {
        module,
        entry_point: "vs",
        compilation_options: Default::default(),
        buffers,
    }
}

fn fragment_state<'a>(
    module: &'a wgpu::ShaderModule,
    targets: &'a [Option<wgpu::ColorTargetState>],
) -> wgpu::FragmentState<'a> {
    wgpu::FragmentState {
        module,
        entry_point: "fs",
        compilation_options: Default::default(),
        targets,
    }
}

/// One color target for a surface format, owned by the pipeline that uses it.
/// The target both passes draw into.
///
/// A glyph is coverage-weighted colour over what the boxes already drew, and a
/// rounded box edge is antialiased, so neither can replace the destination:
/// without a blend state every glyph is a filled rectangle in the text colour,
/// and every rounded corner is chopped.
fn blended_target(format: wgpu::TextureFormat) -> [Option<wgpu::ColorTargetState>; 1] {
    [Some(wgpu::ColorTargetState {
        format,
        blend: Some(wgpu::BlendState {
            color: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::SrcAlpha,
                dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                operation: wgpu::BlendOperation::Add,
            },
            alpha: wgpu::BlendComponent {
                src_factor: wgpu::BlendFactor::One,
                dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
                operation: wgpu::BlendOperation::Add,
            },
        }),
        write_mask: wgpu::ColorWrites::ALL,
    })]
}

fn primitive_state() -> wgpu::PrimitiveState {
    wgpu::PrimitiveState {
        topology: wgpu::PrimitiveTopology::TriangleList,
        strip_index_format: None,
        front_face: wgpu::FrontFace::Ccw,
        cull_mode: None,
        unclipped_depth: false,
        polygon_mode: wgpu::PolygonMode::Fill,
        conservative: false,
    }
}

/// One attribute per shader input, in the order the struct declares them.
///
/// The array is a constant rather than a built Vec because wgpu borrows it for
/// the pipeline's lifetime.
const BOX_ATTRIBUTES: [wgpu::VertexAttribute; 11] = [
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32x2,
        offset: 0,
        shader_location: 0,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32x2,
        offset: 8,
        shader_location: 1,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32x2,
        offset: 16,
        shader_location: 2,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32,
        offset: 24,
        shader_location: 3,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32,
        offset: 28,
        shader_location: 4,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32x4,
        offset: 32,
        shader_location: 5,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32x4,
        offset: 48,
        shader_location: 6,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32x2,
        offset: 64,
        shader_location: 7,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32,
        offset: 72,
        shader_location: 8,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32,
        offset: 76,
        shader_location: 9,
    },
    wgpu::VertexAttribute {
        format: wgpu::VertexFormat::Float32x4,
        offset: 80,
        shader_location: 10,
    },
];

fn box_attributes() -> Vec<wgpu::VertexBufferLayout<'static>> {
    vec![wgpu::VertexBufferLayout {
        array_stride: std::mem::size_of::<BoxVertex>() as u64,
        step_mode: wgpu::VertexStepMode::Vertex,
        attributes: &BOX_ATTRIBUTES,
    }]
}

fn text_attributes() -> Vec<wgpu::VertexBufferLayout<'static>> {
    vec![wgpu::VertexBufferLayout {
        array_stride: std::mem::size_of::<TextVertex>() as u64,
        step_mode: wgpu::VertexStepMode::Vertex,
        attributes: &[
            wgpu::VertexAttribute {
                format: wgpu::VertexFormat::Float32x2,
                offset: 0,
                shader_location: 0,
            },
            wgpu::VertexAttribute {
                format: wgpu::VertexFormat::Float32x2,
                offset: 8,
                shader_location: 1,
            },
            wgpu::VertexAttribute {
                format: wgpu::VertexFormat::Float32x4,
                offset: 16,
                shader_location: 2,
            },
            wgpu::VertexAttribute {
                format: wgpu::VertexFormat::Float32,
                offset: 32,
                shader_location: 3,
            },
        ],
    }]
}