Skip to main content

rcus_render/
pipeline.rs

1use wgpu::ShaderSource;
2
3use crate::quad::{BoxVertex, TextVertex};
4
5const BOX_SHADER: &str = r#"
6struct VsOut {
7    @builtin(position) position: vec4<f32>,
8    @location(0) local: vec2<f32>,
9    @location(1) half: vec2<f32>,
10    @location(2) radius: f32,
11    @location(3) border_width: f32,
12    @location(4) fill: vec4<f32>,
13    @location(5) border: vec4<f32>,
14    @location(6) shadow_offset: vec2<f32>,
15    @location(7) shadow_blur: f32,
16    @location(8) shadow_spread: f32,
17    @location(9) shadow_color: vec4<f32>,
18};
19
20@vertex
21fn vs(
22    @location(0) position: vec2<f32>,
23    @location(1) local: vec2<f32>,
24    @location(2) half: vec2<f32>,
25    @location(3) radius: f32,
26    @location(4) border_width: f32,
27    @location(5) fill: vec4<f32>,
28    @location(6) border: vec4<f32>,
29    @location(7) shadow_offset: vec2<f32>,
30    @location(8) shadow_blur: f32,
31    @location(9) shadow_spread: f32,
32    @location(10) shadow_color: vec4<f32>,
33) -> VsOut {
34    var output: VsOut;
35    output.position = vec4<f32>(position, 0.0, 1.0);
36    output.local = local;
37    output.half = half;
38    output.radius = radius;
39    output.border_width = border_width;
40    output.fill = fill;
41    output.border = border;
42    output.shadow_offset = shadow_offset;
43    output.shadow_blur = shadow_blur;
44    output.shadow_spread = shadow_spread;
45    output.shadow_color = shadow_color;
46    return output;
47}
48
49// Distance in pixels from `p` to the edge of a box centred on the origin. A
50// radius of zero makes this the distance to a plain rectangle, which is why a
51// flat box needs no special case anywhere else.
52fn sd_box(p: vec2<f32>, half: vec2<f32>, radius: f32) -> f32 {
53    let r = min(radius, min(half.x, half.y));
54    let q = abs(p) - half + vec2<f32>(r, r);
55    return length(max(q, vec2<f32>(0.0, 0.0))) + min(max(q.x, q.y), 0.0) - r;
56}
57
58// One layer of translucent colour over what is already there, in straight
59// alpha, because the target blends with src-alpha.
60fn over(base_rgb: vec3<f32>, base_a: f32, top_rgb: vec3<f32>, top_a: f32) -> vec4<f32> {
61    let a = top_a + base_a * (1.0 - top_a);
62    if a <= 0.0 {
63        return vec4<f32>(0.0, 0.0, 0.0, 0.0);
64    }
65    let rgb = (top_rgb * top_a + base_rgb * base_a * (1.0 - top_a)) / a;
66    return vec4<f32>(rgb, a);
67}
68
69@fragment
70fn fs(input: VsOut) -> @location(0) vec4<f32> {
71    let sd = sd_box(input.local, input.half, input.radius);
72    // `sd` is in pixels, so one unit of it is one pixel of softness.
73    let fill_mask = 1.0 - smoothstep(-0.5, 0.5, sd);
74
75    var color = over(
76        vec3<f32>(0.0, 0.0, 0.0),
77        0.0,
78        input.fill.rgb,
79        fill_mask * input.fill.a,
80    );
81
82    if input.shadow_color.a > 0.0 {
83        let spread = input.shadow_spread;
84        let ssd = sd_box(
85            input.local - input.shadow_offset,
86            input.half + vec2<f32>(spread, spread),
87            input.radius + spread,
88        );
89        let blur = max(input.shadow_blur, 0.001);
90        let mask = 1.0 - smoothstep(-blur, blur, ssd);
91        color = over(color.rgb, color.a, input.shadow_color.rgb, mask * input.shadow_color.a);
92    }
93
94    if input.border_width > 0.0 && input.border.a > 0.0 {
95        // The border is the ring between the edge and one border-width inside
96        // it: distance from the edge greater than zero, and no more than the
97        // border's width. Masking only on the inner bound would flood the whole
98        // interior with the border colour.
99        let outside = smoothstep(-0.5, 0.5, sd + input.border_width);
100        let inside = 1.0 - smoothstep(-0.5, 0.5, sd);
101        let mask = outside * inside;
102        color = over(color.rgb, color.a, input.border.rgb, mask * input.border.a);
103    }
104
105    return color;
106}
107"#;
108
109const TEXT_SHADER: &str = r#"
110struct Uniforms {
111    viewport: vec2<f32>,
112};
113
114@group(0) @binding(0) var<uniform> uniforms: Uniforms;
115@group(0) @binding(1) var atlas: texture_2d_array<f32>;
116@group(0) @binding(2) var atlas_sampler: sampler;
117
118struct VsOut {
119    @builtin(position) position: vec4<f32>,
120    @location(0) uv: vec2<f32>,
121    @location(1) color: vec4<f32>,
122    @location(2) @interpolate(flat) layer: f32,
123};
124
125@vertex
126fn vs(
127    @location(0) position: vec2<f32>,
128    @location(1) uv: vec2<f32>,
129    @location(2) color: vec4<f32>,
130    @location(3) layer: f32,
131) -> VsOut {
132    var output: VsOut;
133    let ndc = vec2<f32>(
134        position.x / uniforms.viewport.x * 2.0 - 1.0,
135        1.0 - position.y / uniforms.viewport.y * 2.0,
136    );
137    output.position = vec4<f32>(ndc, 0.0, 1.0);
138    output.uv = uv;
139    output.color = color;
140    output.layer = layer;
141    return output;
142}
143
144@fragment
145fn fs(input: VsOut) -> @location(0) vec4<f32> {
146    let coverage = textureSample(atlas, atlas_sampler, input.uv, i32(input.layer)).r;
147    return vec4<f32>(input.color.rgb, input.color.a * coverage);
148}
149"#;
150
151/// Viewport size, uploaded once per frame and read by the text shader.
152#[repr(C)]
153#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
154pub struct Viewport {
155    pub width: f32,
156    pub height: f32,
157}
158
159pub struct SolidPipeline {
160    pub pipeline: wgpu::RenderPipeline,
161}
162
163pub struct TextPipeline {
164    pub pipeline: wgpu::RenderPipeline,
165    pub layout: wgpu::PipelineLayout,
166    pub bind_group_layout: wgpu::BindGroupLayout,
167    pub uniform: wgpu::Buffer,
168    pub sampler: wgpu::Sampler,
169    pub bind_group: wgpu::BindGroup,
170    /// The atlas array and the layer count it was built for. A new glyph only
171    /// re-uploads coverage; a new size adds a layer and rebuilds the view.
172    atlas: Option<(wgpu::Texture, wgpu::TextureView, usize)>,
173}
174
175impl SolidPipeline {
176    pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> anyhow::Result<Self> {
177        // The box pass blends: an antialiased corner and a translucent overlay
178        // both need the destination, so `replace` would chop them.
179        let targets = blended_target(format);
180        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
181            label: Some("rcus-box-shader"),
182            source: ShaderSource::Wgsl(BOX_SHADER.into()),
183        });
184        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
185            label: Some("rcus-solid-layout"),
186            bind_group_layouts: &[],
187            push_constant_ranges: &[],
188        });
189        Ok(Self {
190            pipeline: device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
191                label: Some("rcus-box-pipeline"),
192                layout: Some(&layout),
193                vertex: vertex_state(&shader, &box_attributes()),
194                fragment: Some(fragment_state(&shader, &targets)),
195                primitive: primitive_state(),
196                depth_stencil: None,
197                multisample: wgpu::MultisampleState::default(),
198                multiview: None,
199                cache: None,
200            }),
201        })
202    }
203}
204
205impl TextPipeline {
206    pub fn new(
207        device: &wgpu::Device,
208        queue: &wgpu::Queue,
209        format: wgpu::TextureFormat,
210    ) -> anyhow::Result<Self> {
211        let targets = blended_target(format);
212        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
213            label: Some("rcus-text-shader"),
214            source: ShaderSource::Wgsl(TEXT_SHADER.into()),
215        });
216        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
217            label: Some("rcus-text-bind-group-layout"),
218            entries: &[
219                wgpu::BindGroupLayoutEntry {
220                    binding: 0,
221                    visibility: wgpu::ShaderStages::VERTEX,
222                    ty: wgpu::BindingType::Buffer {
223                        ty: wgpu::BufferBindingType::Uniform,
224                        has_dynamic_offset: false,
225                        min_binding_size: wgpu::BufferSize::new(
226                            std::mem::size_of::<Viewport>() as u64
227                        ),
228                    },
229                    count: None,
230                },
231                wgpu::BindGroupLayoutEntry {
232                    binding: 1,
233                    visibility: wgpu::ShaderStages::FRAGMENT,
234                    ty: wgpu::BindingType::Texture {
235                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
236                        view_dimension: wgpu::TextureViewDimension::D2Array,
237                        multisampled: false,
238                    },
239                    count: None,
240                },
241                wgpu::BindGroupLayoutEntry {
242                    binding: 2,
243                    visibility: wgpu::ShaderStages::FRAGMENT,
244                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
245                    count: None,
246                },
247            ],
248        });
249        let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
250            label: Some("rcus-text-layout"),
251            bind_group_layouts: &[&bind_group_layout],
252            push_constant_ranges: &[],
253        });
254        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
255            label: Some("rcus-text-pipeline"),
256            layout: Some(&layout),
257            vertex: vertex_state(&shader, &text_attributes()),
258            fragment: Some(fragment_state(&shader, &targets)),
259            primitive: primitive_state(),
260            depth_stencil: None,
261            multisample: wgpu::MultisampleState::default(),
262            multiview: None,
263            cache: None,
264        });
265        let uniform = device.create_buffer(&wgpu::BufferDescriptor {
266            label: Some("rcus-viewport-uniform"),
267            size: std::mem::size_of::<Viewport>() as u64,
268            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
269            mapped_at_creation: false,
270        });
271        queue.write_buffer(
272            &uniform,
273            0,
274            bytemuck::bytes_of(&Viewport {
275                width: 1.0,
276                height: 1.0,
277            }),
278        );
279        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
280            label: Some("rcus-atlas-sampler"),
281            mag_filter: wgpu::FilterMode::Linear,
282            min_filter: wgpu::FilterMode::Linear,
283            mipmap_filter: wgpu::FilterMode::Nearest,
284            address_mode_u: wgpu::AddressMode::ClampToEdge,
285            address_mode_v: wgpu::AddressMode::ClampToEdge,
286            ..Default::default()
287        });
288        let atlas = device.create_texture(&wgpu::TextureDescriptor {
289            label: Some("rcus-atlas-placeholder"),
290            size: wgpu::Extent3d {
291                width: 1,
292                height: 1,
293                depth_or_array_layers: 1,
294            },
295            mip_level_count: 1,
296            sample_count: 1,
297            dimension: wgpu::TextureDimension::D2,
298            format: wgpu::TextureFormat::R8Unorm,
299            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
300            view_formats: &[],
301        });
302        let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
303            label: Some("rcus-text-bind-group"),
304            layout: &bind_group_layout,
305            entries: &[
306                wgpu::BindGroupEntry {
307                    binding: 0,
308                    resource: uniform.as_entire_binding(),
309                },
310                wgpu::BindGroupEntry {
311                    binding: 1,
312                    resource: wgpu::BindingResource::TextureView(&atlas.create_view(
313                        &wgpu::TextureViewDescriptor {
314                            dimension: Some(wgpu::TextureViewDimension::D2Array),
315                            ..Default::default()
316                        },
317                    )),
318                },
319                wgpu::BindGroupEntry {
320                    binding: 2,
321                    resource: wgpu::BindingResource::Sampler(&sampler),
322                },
323            ],
324        });
325        Ok(Self {
326            pipeline,
327            layout,
328            bind_group_layout,
329            uniform,
330            sampler,
331            bind_group,
332            atlas: None,
333        })
334    }
335
336    /// Brings the glyph atlas in line with the shaped layers, rebuilding the
337    /// array only when the layer count changed.
338    pub fn sync_atlas(
339        &mut self,
340        device: &wgpu::Device,
341        queue: &wgpu::Queue,
342        set: &crate::text::AtlasSet,
343    ) {
344        let layers = set.layers();
345        let current = self.atlas.as_ref().map(|(_, _, count)| *count);
346        if current == Some(layers) {
347            if let Some((texture, _, _)) = self.atlas.as_ref() {
348                crate::text::upload_atlas_layers(queue, texture, set);
349            }
350            return;
351        }
352        let texture = crate::text::create_atlas_texture(device, layers);
353        crate::text::upload_atlas_layers(queue, &texture, set);
354        let view = crate::text::atlas_view(&texture);
355        self.set_atlas(device, &view);
356        self.atlas = Some((texture, view, layers));
357    }
358
359    /// Points the pipeline at the current atlas array.
360    fn set_atlas(&mut self, device: &wgpu::Device, view: &wgpu::TextureView) {
361        self.bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
362            label: Some("rcus-text-bind-group"),
363            layout: &self.bind_group_layout,
364            entries: &[
365                wgpu::BindGroupEntry {
366                    binding: 0,
367                    resource: self.uniform.as_entire_binding(),
368                },
369                wgpu::BindGroupEntry {
370                    binding: 1,
371                    resource: wgpu::BindingResource::TextureView(view),
372                },
373                wgpu::BindGroupEntry {
374                    binding: 2,
375                    resource: wgpu::BindingResource::Sampler(&self.sampler),
376                },
377            ],
378        });
379    }
380
381    pub fn set_viewport(&self, queue: &wgpu::Queue, width: f32, height: f32) {
382        queue.write_buffer(
383            &self.uniform,
384            0,
385            bytemuck::bytes_of(&Viewport { width, height }),
386        );
387    }
388}
389
390fn vertex_state<'a>(
391    module: &'a wgpu::ShaderModule,
392    buffers: &'a [wgpu::VertexBufferLayout<'a>],
393) -> wgpu::VertexState<'a> {
394    wgpu::VertexState {
395        module,
396        entry_point: "vs",
397        compilation_options: Default::default(),
398        buffers,
399    }
400}
401
402fn fragment_state<'a>(
403    module: &'a wgpu::ShaderModule,
404    targets: &'a [Option<wgpu::ColorTargetState>],
405) -> wgpu::FragmentState<'a> {
406    wgpu::FragmentState {
407        module,
408        entry_point: "fs",
409        compilation_options: Default::default(),
410        targets,
411    }
412}
413
414/// One color target for a surface format, owned by the pipeline that uses it.
415/// The target both passes draw into.
416///
417/// A glyph is coverage-weighted colour over what the boxes already drew, and a
418/// rounded box edge is antialiased, so neither can replace the destination:
419/// without a blend state every glyph is a filled rectangle in the text colour,
420/// and every rounded corner is chopped.
421fn blended_target(format: wgpu::TextureFormat) -> [Option<wgpu::ColorTargetState>; 1] {
422    [Some(wgpu::ColorTargetState {
423        format,
424        blend: Some(wgpu::BlendState {
425            color: wgpu::BlendComponent {
426                src_factor: wgpu::BlendFactor::SrcAlpha,
427                dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
428                operation: wgpu::BlendOperation::Add,
429            },
430            alpha: wgpu::BlendComponent {
431                src_factor: wgpu::BlendFactor::One,
432                dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
433                operation: wgpu::BlendOperation::Add,
434            },
435        }),
436        write_mask: wgpu::ColorWrites::ALL,
437    })]
438}
439
440fn primitive_state() -> wgpu::PrimitiveState {
441    wgpu::PrimitiveState {
442        topology: wgpu::PrimitiveTopology::TriangleList,
443        strip_index_format: None,
444        front_face: wgpu::FrontFace::Ccw,
445        cull_mode: None,
446        unclipped_depth: false,
447        polygon_mode: wgpu::PolygonMode::Fill,
448        conservative: false,
449    }
450}
451
452/// One attribute per shader input, in the order the struct declares them.
453///
454/// The array is a constant rather than a built Vec because wgpu borrows it for
455/// the pipeline's lifetime.
456const BOX_ATTRIBUTES: [wgpu::VertexAttribute; 11] = [
457    wgpu::VertexAttribute {
458        format: wgpu::VertexFormat::Float32x2,
459        offset: 0,
460        shader_location: 0,
461    },
462    wgpu::VertexAttribute {
463        format: wgpu::VertexFormat::Float32x2,
464        offset: 8,
465        shader_location: 1,
466    },
467    wgpu::VertexAttribute {
468        format: wgpu::VertexFormat::Float32x2,
469        offset: 16,
470        shader_location: 2,
471    },
472    wgpu::VertexAttribute {
473        format: wgpu::VertexFormat::Float32,
474        offset: 24,
475        shader_location: 3,
476    },
477    wgpu::VertexAttribute {
478        format: wgpu::VertexFormat::Float32,
479        offset: 28,
480        shader_location: 4,
481    },
482    wgpu::VertexAttribute {
483        format: wgpu::VertexFormat::Float32x4,
484        offset: 32,
485        shader_location: 5,
486    },
487    wgpu::VertexAttribute {
488        format: wgpu::VertexFormat::Float32x4,
489        offset: 48,
490        shader_location: 6,
491    },
492    wgpu::VertexAttribute {
493        format: wgpu::VertexFormat::Float32x2,
494        offset: 64,
495        shader_location: 7,
496    },
497    wgpu::VertexAttribute {
498        format: wgpu::VertexFormat::Float32,
499        offset: 72,
500        shader_location: 8,
501    },
502    wgpu::VertexAttribute {
503        format: wgpu::VertexFormat::Float32,
504        offset: 76,
505        shader_location: 9,
506    },
507    wgpu::VertexAttribute {
508        format: wgpu::VertexFormat::Float32x4,
509        offset: 80,
510        shader_location: 10,
511    },
512];
513
514fn box_attributes() -> Vec<wgpu::VertexBufferLayout<'static>> {
515    vec![wgpu::VertexBufferLayout {
516        array_stride: std::mem::size_of::<BoxVertex>() as u64,
517        step_mode: wgpu::VertexStepMode::Vertex,
518        attributes: &BOX_ATTRIBUTES,
519    }]
520}
521
522fn text_attributes() -> Vec<wgpu::VertexBufferLayout<'static>> {
523    vec![wgpu::VertexBufferLayout {
524        array_stride: std::mem::size_of::<TextVertex>() as u64,
525        step_mode: wgpu::VertexStepMode::Vertex,
526        attributes: &[
527            wgpu::VertexAttribute {
528                format: wgpu::VertexFormat::Float32x2,
529                offset: 0,
530                shader_location: 0,
531            },
532            wgpu::VertexAttribute {
533                format: wgpu::VertexFormat::Float32x2,
534                offset: 8,
535                shader_location: 1,
536            },
537            wgpu::VertexAttribute {
538                format: wgpu::VertexFormat::Float32x4,
539                offset: 16,
540                shader_location: 2,
541            },
542            wgpu::VertexAttribute {
543                format: wgpu::VertexFormat::Float32,
544                offset: 32,
545                shader_location: 3,
546            },
547        ],
548    }]
549}