1use wgpu::ShaderSource;
2
3use crate::quad::{TextVertex, Vertex};
4
5const SOLID_SHADER: &str = r#"
6struct VsOut {
7 @builtin(position) position: vec4<f32>,
8 @location(0) color: vec4<f32>,
9};
10
11@vertex
12fn vs(@location(0) position: vec2<f32>, @location(1) color: vec4<f32>) -> VsOut {
13 var output: VsOut;
14 output.position = vec4<f32>(position, 0.0, 1.0);
15 output.color = color;
16 return output;
17}
18
19@fragment
20fn fs(input: VsOut) -> @location(0) vec4<f32> {
21 return input.color;
22}
23"#;
24
25const TEXT_SHADER: &str = r#"
26struct Uniforms {
27 viewport: vec2<f32>,
28};
29
30@group(0) @binding(0) var<uniform> uniforms: Uniforms;
31@group(0) @binding(1) var atlas: texture_2d_array<f32>;
32@group(0) @binding(2) var atlas_sampler: sampler;
33
34struct VsOut {
35 @builtin(position) position: vec4<f32>,
36 @location(0) uv: vec2<f32>,
37 @location(1) color: vec4<f32>,
38 @location(2) @interpolate(flat) layer: f32,
39};
40
41@vertex
42fn vs(
43 @location(0) position: vec2<f32>,
44 @location(1) uv: vec2<f32>,
45 @location(2) color: vec4<f32>,
46 @location(3) layer: f32,
47) -> VsOut {
48 var output: VsOut;
49 let ndc = vec2<f32>(
50 position.x / uniforms.viewport.x * 2.0 - 1.0,
51 1.0 - position.y / uniforms.viewport.y * 2.0,
52 );
53 output.position = vec4<f32>(ndc, 0.0, 1.0);
54 output.uv = uv;
55 output.color = color;
56 output.layer = layer;
57 return output;
58}
59
60@fragment
61fn fs(input: VsOut) -> @location(0) vec4<f32> {
62 let coverage = textureSample(atlas, atlas_sampler, input.uv, i32(input.layer)).r;
63 return vec4<f32>(input.color.rgb, input.color.a * coverage);
64}
65"#;
66
67#[repr(C)]
69#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
70pub struct Viewport {
71 pub width: f32,
72 pub height: f32,
73}
74
75pub struct SolidPipeline {
76 pub pipeline: wgpu::RenderPipeline,
77}
78
79pub struct TextPipeline {
80 pub pipeline: wgpu::RenderPipeline,
81 pub layout: wgpu::PipelineLayout,
82 pub bind_group_layout: wgpu::BindGroupLayout,
83 pub uniform: wgpu::Buffer,
84 pub sampler: wgpu::Sampler,
85 pub bind_group: wgpu::BindGroup,
86 atlas: Option<(wgpu::Texture, wgpu::TextureView, usize)>,
89}
90
91impl SolidPipeline {
92 pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> anyhow::Result<Self> {
93 let targets = color_targets(format);
94 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
95 label: Some("rcus-solid-shader"),
96 source: ShaderSource::Wgsl(SOLID_SHADER.into()),
97 });
98 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
99 label: Some("rcus-solid-layout"),
100 bind_group_layouts: &[],
101 push_constant_ranges: &[],
102 });
103 Ok(Self {
104 pipeline: device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
105 label: Some("rcus-solid-pipeline"),
106 layout: Some(&layout),
107 vertex: vertex_state(&shader, &solid_attributes()),
108 fragment: Some(fragment_state(&shader, &targets)),
109 primitive: primitive_state(),
110 depth_stencil: None,
111 multisample: wgpu::MultisampleState::default(),
112 multiview: None,
113 cache: None,
114 }),
115 })
116 }
117}
118
119impl TextPipeline {
120 pub fn new(
121 device: &wgpu::Device,
122 queue: &wgpu::Queue,
123 format: wgpu::TextureFormat,
124 ) -> anyhow::Result<Self> {
125 let targets = blended_target(format);
126 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
127 label: Some("rcus-text-shader"),
128 source: ShaderSource::Wgsl(TEXT_SHADER.into()),
129 });
130 let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
131 label: Some("rcus-text-bind-group-layout"),
132 entries: &[
133 wgpu::BindGroupLayoutEntry {
134 binding: 0,
135 visibility: wgpu::ShaderStages::VERTEX,
136 ty: wgpu::BindingType::Buffer {
137 ty: wgpu::BufferBindingType::Uniform,
138 has_dynamic_offset: false,
139 min_binding_size: wgpu::BufferSize::new(
140 std::mem::size_of::<Viewport>() as u64
141 ),
142 },
143 count: None,
144 },
145 wgpu::BindGroupLayoutEntry {
146 binding: 1,
147 visibility: wgpu::ShaderStages::FRAGMENT,
148 ty: wgpu::BindingType::Texture {
149 sample_type: wgpu::TextureSampleType::Float { filterable: true },
150 view_dimension: wgpu::TextureViewDimension::D2Array,
151 multisampled: false,
152 },
153 count: None,
154 },
155 wgpu::BindGroupLayoutEntry {
156 binding: 2,
157 visibility: wgpu::ShaderStages::FRAGMENT,
158 ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
159 count: None,
160 },
161 ],
162 });
163 let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
164 label: Some("rcus-text-layout"),
165 bind_group_layouts: &[&bind_group_layout],
166 push_constant_ranges: &[],
167 });
168 let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
169 label: Some("rcus-text-pipeline"),
170 layout: Some(&layout),
171 vertex: vertex_state(&shader, &text_attributes()),
172 fragment: Some(fragment_state(&shader, &targets)),
173 primitive: primitive_state(),
174 depth_stencil: None,
175 multisample: wgpu::MultisampleState::default(),
176 multiview: None,
177 cache: None,
178 });
179 let uniform = device.create_buffer(&wgpu::BufferDescriptor {
180 label: Some("rcus-viewport-uniform"),
181 size: std::mem::size_of::<Viewport>() as u64,
182 usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
183 mapped_at_creation: false,
184 });
185 queue.write_buffer(
186 &uniform,
187 0,
188 bytemuck::bytes_of(&Viewport {
189 width: 1.0,
190 height: 1.0,
191 }),
192 );
193 let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
194 label: Some("rcus-atlas-sampler"),
195 mag_filter: wgpu::FilterMode::Linear,
196 min_filter: wgpu::FilterMode::Linear,
197 mipmap_filter: wgpu::FilterMode::Nearest,
198 address_mode_u: wgpu::AddressMode::ClampToEdge,
199 address_mode_v: wgpu::AddressMode::ClampToEdge,
200 ..Default::default()
201 });
202 let atlas = device.create_texture(&wgpu::TextureDescriptor {
203 label: Some("rcus-atlas-placeholder"),
204 size: wgpu::Extent3d {
205 width: 1,
206 height: 1,
207 depth_or_array_layers: 1,
208 },
209 mip_level_count: 1,
210 sample_count: 1,
211 dimension: wgpu::TextureDimension::D2,
212 format: wgpu::TextureFormat::R8Unorm,
213 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
214 view_formats: &[],
215 });
216 let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
217 label: Some("rcus-text-bind-group"),
218 layout: &bind_group_layout,
219 entries: &[
220 wgpu::BindGroupEntry {
221 binding: 0,
222 resource: uniform.as_entire_binding(),
223 },
224 wgpu::BindGroupEntry {
225 binding: 1,
226 resource: wgpu::BindingResource::TextureView(&atlas.create_view(
227 &wgpu::TextureViewDescriptor {
228 dimension: Some(wgpu::TextureViewDimension::D2Array),
229 ..Default::default()
230 },
231 )),
232 },
233 wgpu::BindGroupEntry {
234 binding: 2,
235 resource: wgpu::BindingResource::Sampler(&sampler),
236 },
237 ],
238 });
239 Ok(Self {
240 pipeline,
241 layout,
242 bind_group_layout,
243 uniform,
244 sampler,
245 bind_group,
246 atlas: None,
247 })
248 }
249
250 pub fn sync_atlas(
253 &mut self,
254 device: &wgpu::Device,
255 queue: &wgpu::Queue,
256 set: &crate::text::AtlasSet,
257 ) {
258 let layers = set.layers();
259 let current = self.atlas.as_ref().map(|(_, _, count)| *count);
260 if current == Some(layers) {
261 if let Some((texture, _, _)) = self.atlas.as_ref() {
262 crate::text::upload_atlas_layers(queue, texture, set);
263 }
264 return;
265 }
266 let texture = crate::text::create_atlas_texture(device, layers);
267 crate::text::upload_atlas_layers(queue, &texture, set);
268 let view = crate::text::atlas_view(&texture);
269 self.set_atlas(device, &view);
270 self.atlas = Some((texture, view, layers));
271 }
272
273 fn set_atlas(&mut self, device: &wgpu::Device, view: &wgpu::TextureView) {
275 self.bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
276 label: Some("rcus-text-bind-group"),
277 layout: &self.bind_group_layout,
278 entries: &[
279 wgpu::BindGroupEntry {
280 binding: 0,
281 resource: self.uniform.as_entire_binding(),
282 },
283 wgpu::BindGroupEntry {
284 binding: 1,
285 resource: wgpu::BindingResource::TextureView(view),
286 },
287 wgpu::BindGroupEntry {
288 binding: 2,
289 resource: wgpu::BindingResource::Sampler(&self.sampler),
290 },
291 ],
292 });
293 }
294
295 pub fn set_viewport(&self, queue: &wgpu::Queue, width: f32, height: f32) {
296 queue.write_buffer(
297 &self.uniform,
298 0,
299 bytemuck::bytes_of(&Viewport { width, height }),
300 );
301 }
302}
303
304fn vertex_state<'a>(
305 module: &'a wgpu::ShaderModule,
306 buffers: &'a [wgpu::VertexBufferLayout<'a>],
307) -> wgpu::VertexState<'a> {
308 wgpu::VertexState {
309 module,
310 entry_point: "vs",
311 compilation_options: Default::default(),
312 buffers,
313 }
314}
315
316fn fragment_state<'a>(
317 module: &'a wgpu::ShaderModule,
318 targets: &'a [Option<wgpu::ColorTargetState>],
319) -> wgpu::FragmentState<'a> {
320 wgpu::FragmentState {
321 module,
322 entry_point: "fs",
323 compilation_options: Default::default(),
324 targets,
325 }
326}
327
328fn color_targets(format: wgpu::TextureFormat) -> [Option<wgpu::ColorTargetState>; 1] {
330 [Some(format.into())]
331}
332
333fn blended_target(format: wgpu::TextureFormat) -> [Option<wgpu::ColorTargetState>; 1] {
340 [Some(wgpu::ColorTargetState {
341 format,
342 blend: Some(wgpu::BlendState {
343 color: wgpu::BlendComponent {
344 src_factor: wgpu::BlendFactor::SrcAlpha,
345 dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
346 operation: wgpu::BlendOperation::Add,
347 },
348 alpha: wgpu::BlendComponent {
349 src_factor: wgpu::BlendFactor::One,
350 dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
351 operation: wgpu::BlendOperation::Add,
352 },
353 }),
354 write_mask: wgpu::ColorWrites::ALL,
355 })]
356}
357
358fn primitive_state() -> wgpu::PrimitiveState {
359 wgpu::PrimitiveState {
360 topology: wgpu::PrimitiveTopology::TriangleList,
361 strip_index_format: None,
362 front_face: wgpu::FrontFace::Ccw,
363 cull_mode: None,
364 unclipped_depth: false,
365 polygon_mode: wgpu::PolygonMode::Fill,
366 conservative: false,
367 }
368}
369
370fn solid_attributes() -> Vec<wgpu::VertexBufferLayout<'static>> {
371 vec![wgpu::VertexBufferLayout {
372 array_stride: std::mem::size_of::<Vertex>() as u64,
373 step_mode: wgpu::VertexStepMode::Vertex,
374 attributes: &[
375 wgpu::VertexAttribute {
376 format: wgpu::VertexFormat::Float32x2,
377 offset: 0,
378 shader_location: 0,
379 },
380 wgpu::VertexAttribute {
381 format: wgpu::VertexFormat::Float32x4,
382 offset: 8,
383 shader_location: 1,
384 },
385 ],
386 }]
387}
388
389fn text_attributes() -> Vec<wgpu::VertexBufferLayout<'static>> {
390 vec![wgpu::VertexBufferLayout {
391 array_stride: std::mem::size_of::<TextVertex>() as u64,
392 step_mode: wgpu::VertexStepMode::Vertex,
393 attributes: &[
394 wgpu::VertexAttribute {
395 format: wgpu::VertexFormat::Float32x2,
396 offset: 0,
397 shader_location: 0,
398 },
399 wgpu::VertexAttribute {
400 format: wgpu::VertexFormat::Float32x2,
401 offset: 8,
402 shader_location: 1,
403 },
404 wgpu::VertexAttribute {
405 format: wgpu::VertexFormat::Float32x4,
406 offset: 16,
407 shader_location: 2,
408 },
409 wgpu::VertexAttribute {
410 format: wgpu::VertexFormat::Float32,
411 offset: 32,
412 shader_location: 3,
413 },
414 ],
415 }]
416}