Skip to main content

mln_webgpu/shaders/
shader_program.rs

1// Ports include/mln/shaders/webgpu/shader_program.hpp and
2// src/mln/shaders/webgpu/shader_program.cpp
3//
4// wgpu vs. Dawn: shader module creation runs inside a validation error scope
5// so that a WGSL compile error yields "no module" (the C++ null check); the
6// C++ backend gets null only on catastrophic failure and Dawn reports the
7// compile error asynchronously. On Emscripten the scope is skipped (see
8// `validated`).
9//
10// TODO(port): the `ShaderProgram(name, backend, vertexModule, fragmentModule)`
11// constructor for precompiled modules (unused on the M1 path).
12
13use std::any::Any;
14use std::borrow::Cow;
15use std::cell::{Cell, RefCell};
16use std::collections::{BTreeMap, HashMap};
17use std::rc::Rc;
18
19use mln_gfx::color_mode::{BlendFunction, ColorMode};
20use mln_gfx::depth_mode::DepthMode;
21use mln_gfx::gfx_types::DrawModeType;
22use mln_gfx::shader::Shader;
23use mln_gfx::shaders::shader_defines::MAX_TEXTURE_COUNT_PER_SHADER;
24use mln_gfx::shaders::shader_program_base::ShaderProgramBase;
25use mln_gfx::stencil_mode::{StencilMode, Test};
26use mln_gfx::types::{
27    ColorBlendEquationType, ColorBlendFactorType, DepthFunctionType, DepthMaskType, StencilFunctionType, StencilOpType,
28};
29use mln_gfx::vertex_attribute::VertexAttributeArray;
30use mln_util::identity::SimpleIdentity;
31
32use crate::context::Context;
33use crate::shaders::shader_source::{AttributeInfo, TextureInfo, prelude};
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub enum BindingType {
37    UniformBuffer,
38    ReadOnlyStorageBuffer,
39    StorageBuffer,
40    Sampler,
41    Texture,
42    /// For RGBA32Float textures that require textureLoad instead of textureSample
43    UnfilterableTexture,
44}
45
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
47pub struct BindingInfo {
48    pub group: u32,
49    pub binding: u32,
50    pub type_: BindingType,
51    pub visibility: wgpu::ShaderStages,
52}
53
54/// Runs `create` inside a validation error scope and returns the error the
55/// scope caught, which stands in for the C++ null result. On Emscripten the
56/// scope is skipped: popping it waits in `wgpuInstanceWaitAny`, which yields
57/// to the browser in the middle of a frame and expires the canvas texture.
58/// Errors there reach the device's uncaptured-error callback instead.
59fn validated<T>(device: &wgpu::Device, create: impl FnOnce() -> T) -> Result<T, wgpu::Error> {
60    #[cfg(target_os = "emscripten")]
61    {
62        let _ = device;
63        Ok(create())
64    }
65    #[cfg(not(target_os = "emscripten"))]
66    {
67        let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
68        let value = create();
69        match pollster::block_on(scope.pop()) {
70            None => Ok(value),
71            Some(error) => Err(error),
72        }
73    }
74}
75
76fn is_space(b: u8) -> bool {
77    matches!(b, b' ' | b'\t' | b'\n' | b'\x0b' | b'\x0c' | b'\r')
78}
79
80fn trim_string(value: &str) -> String {
81    value.trim_matches(|c: char| c.is_ascii() && is_space(c as u8)).to_owned()
82}
83
84fn webgpu_blend_operation(equation: ColorBlendEquationType) -> wgpu::BlendOperation {
85    match equation {
86        ColorBlendEquationType::Add => wgpu::BlendOperation::Add,
87        ColorBlendEquationType::Subtract => wgpu::BlendOperation::Subtract,
88        ColorBlendEquationType::ReverseSubtract => wgpu::BlendOperation::ReverseSubtract,
89    }
90}
91
92fn webgpu_blend_factor(factor: ColorBlendFactorType) -> wgpu::BlendFactor {
93    use ColorBlendFactorType as F;
94    match factor {
95        F::Zero => wgpu::BlendFactor::Zero,
96        F::One => wgpu::BlendFactor::One,
97        F::SrcColor => wgpu::BlendFactor::Src,
98        F::OneMinusSrcColor => wgpu::BlendFactor::OneMinusSrc,
99        F::SrcAlpha => wgpu::BlendFactor::SrcAlpha,
100        F::OneMinusSrcAlpha => wgpu::BlendFactor::OneMinusSrcAlpha,
101        F::DstAlpha => wgpu::BlendFactor::DstAlpha,
102        F::OneMinusDstAlpha => wgpu::BlendFactor::OneMinusDstAlpha,
103        F::DstColor => wgpu::BlendFactor::Dst,
104        F::OneMinusDstColor => wgpu::BlendFactor::OneMinusDst,
105        F::SrcAlphaSaturate => wgpu::BlendFactor::SrcAlphaSaturated,
106        F::ConstantColor => wgpu::BlendFactor::Constant,
107        F::OneMinusConstantColor => wgpu::BlendFactor::OneMinusConstant,
108        F::ConstantAlpha => wgpu::BlendFactor::Constant,
109        F::OneMinusConstantAlpha => wgpu::BlendFactor::OneMinusConstant,
110    }
111}
112
113fn to_primitive_topology(draw_mode_type: DrawModeType) -> wgpu::PrimitiveTopology {
114    match draw_mode_type {
115        DrawModeType::Points => wgpu::PrimitiveTopology::PointList,
116        DrawModeType::Lines | DrawModeType::LineLoop => wgpu::PrimitiveTopology::LineList,
117        DrawModeType::LineStrip => wgpu::PrimitiveTopology::LineStrip,
118        DrawModeType::TriangleStrip => wgpu::PrimitiveTopology::TriangleStrip,
119        // WebGPU does not support triangle fan directly; approximate with triangle list
120        DrawModeType::TriangleFan => wgpu::PrimitiveTopology::TriangleList,
121        DrawModeType::Triangles => wgpu::PrimitiveTopology::TriangleList,
122    }
123}
124
125fn depth_compare_function(func: DepthFunctionType) -> wgpu::CompareFunction {
126    use DepthFunctionType as D;
127    match func {
128        D::Never => wgpu::CompareFunction::Never,
129        D::Less => wgpu::CompareFunction::Less,
130        D::Equal => wgpu::CompareFunction::Equal,
131        D::LessEqual => wgpu::CompareFunction::LessEqual,
132        D::Greater => wgpu::CompareFunction::Greater,
133        D::NotEqual => wgpu::CompareFunction::NotEqual,
134        D::GreaterEqual => wgpu::CompareFunction::GreaterEqual,
135        D::Always => wgpu::CompareFunction::Always,
136    }
137}
138
139fn stencil_compare_function(func: StencilFunctionType) -> wgpu::CompareFunction {
140    use StencilFunctionType as S;
141    match func {
142        S::Never => wgpu::CompareFunction::Never,
143        S::Less => wgpu::CompareFunction::Less,
144        S::Equal => wgpu::CompareFunction::Equal,
145        S::LessEqual => wgpu::CompareFunction::LessEqual,
146        S::Greater => wgpu::CompareFunction::Greater,
147        S::NotEqual => wgpu::CompareFunction::NotEqual,
148        S::GreaterEqual => wgpu::CompareFunction::GreaterEqual,
149        S::Always => wgpu::CompareFunction::Always,
150    }
151}
152
153fn to_stencil_op(op: StencilOpType) -> wgpu::StencilOperation {
154    use StencilOpType as O;
155    match op {
156        O::Zero => wgpu::StencilOperation::Zero,
157        O::Keep => wgpu::StencilOperation::Keep,
158        O::Replace => wgpu::StencilOperation::Replace,
159        O::Increment => wgpu::StencilOperation::IncrementClamp,
160        O::Decrement => wgpu::StencilOperation::DecrementClamp,
161        O::Invert => wgpu::StencilOperation::Invert,
162        O::IncrementWrap => wgpu::StencilOperation::IncrementWrap,
163        O::DecrementWrap => wgpu::StencilOperation::DecrementWrap,
164    }
165}
166
167/// A vertex buffer layout (`WGPUVertexBufferLayout`) with owned attributes.
168#[derive(Clone, Debug)]
169pub struct VertexLayout {
170    pub array_stride: u64,
171    pub step_mode: wgpu::VertexStepMode,
172    pub attributes: Vec<wgpu::VertexAttribute>,
173}
174
175pub struct ShaderProgram {
176    shader_program_id: SimpleIdentity,
177    shader_name: String,
178    context: Rc<Context>,
179    vertex_shader_module: Option<wgpu::ShaderModule>,
180    fragment_shader_module: Option<wgpu::ShaderModule>,
181    bind_group_layouts: Vec<wgpu::BindGroupLayout>,
182    bind_group_order: Vec<u32>,
183    pipeline_layout: Option<wgpu::PipelineLayout>,
184    render_pipeline_cache: RefCell<HashMap<u64, wgpu::RenderPipeline>>,
185    vertex_attributes: VertexAttributeArray,
186    instance_attributes: VertexAttributeArray,
187    texture_bindings: [Option<usize>; MAX_TEXTURE_COUNT_PER_SHADER],
188    binding_infos: Vec<BindingInfo>,
189    bindings_per_group: Vec<Vec<BindingInfo>>,
190    has_vertex_entry_point: bool,
191    has_fragment_entry_point: bool,
192    logged_missing_entry_point: Cell<bool>,
193}
194
195impl ShaderProgram {
196    /// Static name member (`is_shader_v`)
197    pub const NAME: &'static str = "WebGPUShader";
198
199    /// `ShaderProgram(context, vertexSource, fragmentSource, attrs, texts, name)`
200    pub fn new(
201        context: &Context,
202        vertex_source: &str,
203        fragment_source: &str,
204        attrs: &[AttributeInfo],
205        texts: &[TextureInfo],
206        name: &str,
207    ) -> Self {
208        let mut program = Self::from_sources(context, vertex_source, fragment_source);
209        if name != "ShaderProgram" {
210            program.shader_name = name.to_owned();
211        }
212        for attr in attrs {
213            program.init_attribute(attr);
214        }
215        for tex in texts {
216            program.init_texture(tex);
217        }
218        program
219    }
220
221    /// `ShaderProgram(Context&, vertexSource, fragmentSource)` (minimal
222    /// constructor; name "ContextShader").
223    pub fn from_sources(context: &Context, vertex_source: &str, fragment_source: &str) -> Self {
224        let mut program = ShaderProgram {
225            shader_program_id: SimpleIdentity::new(),
226            shader_name: "ContextShader".to_owned(),
227            context: context.rc(),
228            vertex_shader_module: None,
229            fragment_shader_module: None,
230            bind_group_layouts: Vec::new(),
231            bind_group_order: Vec::new(),
232            pipeline_layout: None,
233            render_pipeline_cache: RefCell::new(HashMap::new()),
234            vertex_attributes: VertexAttributeArray::new(),
235            instance_attributes: VertexAttributeArray::new(),
236            texture_bindings: [None; MAX_TEXTURE_COUNT_PER_SHADER],
237            binding_infos: Vec::new(),
238            bindings_per_group: Vec::new(),
239            has_vertex_entry_point: true,
240            has_fragment_entry_point: true,
241            logged_missing_entry_point: Cell::new(false),
242        };
243        let Some(device) = context.get_backend().get_device() else {
244            return program;
245        };
246
247        program.has_vertex_entry_point = !trim_string(vertex_source).is_empty();
248        program.has_fragment_entry_point = !trim_string(fragment_source).is_empty();
249
250        let create_module = |label: &str, source: &str| -> Option<wgpu::ShaderModule> {
251            let module = validated(&device, || {
252                device.create_shader_module(wgpu::ShaderModuleDescriptor {
253                    label: Some(label),
254                    source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(source)),
255                })
256            });
257            module.map_err(|error| eprintln!("{error}")).ok()
258        };
259
260        // Get the prelude from common.hpp
261        let mut vertex_with_prelude = String::new();
262        if program.has_vertex_entry_point {
263            vertex_with_prelude = format!("{}\n{}", prelude(), vertex_source);
264            program.vertex_shader_module = create_module("Vertex Shader Module", &vertex_with_prelude);
265            if program.vertex_shader_module.is_none() {
266                eprintln!("Failed to create vertex shader module for {}", program.shader_name);
267                eprintln!("Vertex shader source length: {}", vertex_with_prelude.len());
268            }
269        }
270
271        let mut fragment_with_prelude = String::new();
272        if program.has_fragment_entry_point {
273            fragment_with_prelude = format!("{}\n{}", prelude(), fragment_source);
274            program.fragment_shader_module = create_module("Fragment Shader Module", &fragment_with_prelude);
275            if program.fragment_shader_module.is_none() {
276                eprintln!("Failed to create fragment shader module for {}", program.shader_name);
277                eprintln!("Fragment shader source length: {}", fragment_with_prelude.len());
278            }
279        }
280
281        program.create_pipeline_layout(&vertex_with_prelude, &fragment_with_prelude);
282        program
283    }
284
285    /// `getRenderPipeline(renderable, vertexLayouts, ..., reuseHash)`. The
286    /// renderable is unused in C++ and not passed.
287    #[allow(clippy::too_many_arguments)]
288    pub fn get_render_pipeline(
289        &self,
290        vertex_layouts: &[VertexLayout],
291        color_mode: &ColorMode,
292        depth_mode: &DepthMode,
293        stencil_mode: &StencilMode,
294        draw_mode_type: DrawModeType,
295        reuse_hash: Option<u64>,
296    ) -> Option<wgpu::RenderPipeline> {
297        // Check cache first
298        if let Some(hash) = reuse_hash
299            && let Some(pipeline) = self.render_pipeline_cache.borrow().get(&hash)
300        {
301            return Some(pipeline.clone());
302        }
303        // Create new pipeline
304        let pipeline = self.create_pipeline(vertex_layouts, color_mode, depth_mode, stencil_mode, draw_mode_type);
305        // Cache the pipeline if we have a reuse hash
306        if let (Some(hash), Some(p)) = (reuse_hash, &pipeline) {
307            self.render_pipeline_cache.borrow_mut().insert(hash, p.clone());
308        }
309        pipeline
310    }
311
312    pub fn get_binding_infos(&self) -> &[BindingInfo] {
313        &self.binding_infos
314    }
315
316    pub fn get_binding_infos_for_group(&self, group: u32) -> &[BindingInfo] {
317        for (i, &g) in self.bind_group_order.iter().enumerate() {
318            if g == group {
319                return &self.bindings_per_group[i];
320            }
321        }
322        &[]
323    }
324
325    pub fn get_bind_group_layout(&self, group: u32) -> Option<&wgpu::BindGroupLayout> {
326        self.bind_group_order.iter().position(|&g| g == group).map(|i| &self.bind_group_layouts[i])
327    }
328
329    pub fn get_bind_group_layouts(&self) -> &[wgpu::BindGroupLayout] {
330        &self.bind_group_layouts
331    }
332
333    pub fn get_bind_group_order(&self) -> &[u32] {
334        &self.bind_group_order
335    }
336
337    pub fn get_shader_name(&self) -> &str {
338        &self.shader_name
339    }
340
341    /// Whether both WGSL modules compiled.
342    pub fn has_shader_modules(&self) -> bool {
343        self.vertex_shader_module.is_some() && self.fragment_shader_module.is_some()
344    }
345
346    pub fn init_attribute(&mut self, info: &AttributeInfo) {
347        let index = info.index as i32;
348        // Indexes must be unique, if there's a conflict check the `attributes`
349        // array in the shader
350        #[cfg(debug_assertions)]
351        {
352            self.vertex_attributes.visit_attributes(|a| debug_assert!(a.get_index() != index));
353            self.instance_attributes.visit_attributes(|a| debug_assert!(a.get_index() != index));
354        }
355        self.vertex_attributes.set(info.id, index, info.data_type, 1);
356    }
357
358    pub fn init_instance_attribute(&mut self, info: &AttributeInfo) {
359        // Index is the block index of the instance attribute
360        let index = info.index as i32;
361        #[cfg(debug_assertions)]
362        self.vertex_attributes.visit_attributes(|a| debug_assert!(a.get_index() != index));
363        self.instance_attributes.set(info.id, index, info.data_type, 1);
364    }
365
366    pub fn init_texture(&mut self, info: &TextureInfo) {
367        debug_assert!(info.id < self.texture_bindings.len());
368        if info.id >= self.texture_bindings.len() {
369            return;
370        }
371        self.texture_bindings[info.id] = Some(info.index);
372    }
373
374    fn create_pipeline_layout(&mut self, vertex_source: &str, fragment_source: &str) {
375        let Some(device) = self.context.get_backend().get_device() else {
376            return;
377        };
378        if !vertex_source.is_empty() || !fragment_source.is_empty() {
379            self.binding_infos.clear();
380            if !vertex_source.is_empty() {
381                self.analyze_shader_bindings(vertex_source, wgpu::ShaderStages::VERTEX);
382            }
383            if !fragment_source.is_empty() {
384                self.analyze_shader_bindings(fragment_source, wgpu::ShaderStages::FRAGMENT);
385            }
386        }
387
388        self.rebuild_bind_group_layouts(&device);
389
390        let layouts: Vec<Option<&wgpu::BindGroupLayout>> = self.bind_group_layouts.iter().map(Some).collect();
391        self.pipeline_layout = Some(device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
392            label: Some("Pipeline Layout"),
393            bind_group_layouts: &layouts,
394            immediate_size: 0,
395        }));
396    }
397
398    /// Scans `@group(N) @binding(M) var<...> name: type` declarations, as the
399    /// C++ text scanner does.
400    fn analyze_shader_bindings(&mut self, source: &str, stage: wgpu::ShaderStages) {
401        let b = source.as_bytes();
402        let find = |pat: &str, from: usize| source.get(from..).and_then(|s| s.find(pat)).map(|p| p + from);
403        let find_char = |c: char, from: usize| source.get(from..).and_then(|s| s.find(c)).map(|p| p + from);
404        let mut search_pos = 0usize;
405        while let Some(group_token) = find("@group", search_pos) {
406            let Some(group_paren) = find_char('(', group_token) else { break };
407            let mut group_start = group_paren + 1;
408            while group_start < b.len() && is_space(b[group_start]) {
409                group_start += 1;
410            }
411            let mut group_end = group_start;
412            while group_end < b.len() && b[group_end].is_ascii_digit() {
413                group_end += 1;
414            }
415            if group_end == group_start {
416                search_pos = group_end;
417                continue;
418            }
419            let group: u32 = source[group_start..group_end].parse().unwrap_or(0);
420
421            let Some(binding_token) = find("@binding", group_end) else { break };
422            let Some(binding_paren) = find_char('(', binding_token) else { break };
423            let mut binding_start = binding_paren + 1;
424            while binding_start < b.len() && is_space(b[binding_start]) {
425                binding_start += 1;
426            }
427            let mut binding_end = binding_start;
428            while binding_end < b.len() && b[binding_end].is_ascii_digit() {
429                binding_end += 1;
430            }
431            if binding_end == binding_start {
432                search_pos = binding_end;
433                continue;
434            }
435            let binding: u32 = source[binding_start..binding_end].parse().unwrap_or(0);
436
437            let Some(var_pos) = find("var", binding_end) else { break };
438            if var_pos > binding_end && b[var_pos - 1].is_ascii_alphabetic() {
439                search_pos = var_pos + 3;
440                continue;
441            }
442            let mut after_var = var_pos + 3;
443            while after_var < b.len() && is_space(b[after_var]) {
444                after_var += 1;
445            }
446
447            let mut type_ = BindingType::UniformBuffer;
448            if after_var < b.len() && b[after_var] == b'<' {
449                let Some(qualifier_end) = find_char('>', after_var) else { break };
450                let qualifier = trim_string(&source[after_var + 1..qualifier_end]);
451                if qualifier.contains("storage") {
452                    type_ = if qualifier.contains("read_write") {
453                        BindingType::StorageBuffer
454                    } else {
455                        BindingType::ReadOnlyStorageBuffer
456                    };
457                } else {
458                    type_ = BindingType::UniformBuffer;
459                }
460                after_var = qualifier_end + 1;
461            }
462
463            let Some(colon_pos) = find_char(':', after_var) else { break };
464            // Extract the variable name
465            let var_name = trim_string(&source[after_var..colon_pos]);
466            let type_start = colon_pos + 1;
467            let mut type_end = type_start;
468            while type_end < b.len() {
469                let c = b[type_end];
470                if c == b';' || c == b'\n' || c == b'\r' {
471                    break;
472                }
473                type_end += 1;
474            }
475            let type_name = trim_string(&source[type_start..type_end]);
476
477            if type_ == BindingType::UniformBuffer {
478                if type_name.contains("sampler") {
479                    type_ = BindingType::Sampler;
480                } else if type_name.contains("texture") {
481                    // textureLoad only (no textureSample) means unfilterable
482                    let uses_texture_load = source.contains(&format!("textureLoad({var_name}"));
483                    let uses_texture_sample = source.contains(&format!("textureSample({var_name}"));
484                    type_ = if uses_texture_load && !uses_texture_sample {
485                        BindingType::UnfilterableTexture
486                    } else {
487                        BindingType::Texture
488                    };
489                }
490            }
491
492            if let Some(existing) =
493                self.binding_infos.iter_mut().find(|info| info.group == group && info.binding == binding)
494            {
495                existing.visibility |= stage;
496                if existing.type_ == BindingType::UniformBuffer && type_ != BindingType::UniformBuffer {
497                    existing.type_ = type_;
498                }
499            } else {
500                self.binding_infos.push(BindingInfo { group, binding, type_, visibility: stage });
501            }
502
503            search_pos = type_end;
504        }
505    }
506
507    fn rebuild_bind_group_layouts(&mut self, device: &wgpu::Device) {
508        self.bind_group_layouts.clear();
509        self.bind_group_order.clear();
510        self.bindings_per_group.clear();
511
512        if self.binding_infos.is_empty() {
513            self.binding_infos.push(BindingInfo {
514                group: 0,
515                binding: 0,
516                type_: BindingType::UniformBuffer,
517                visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
518            });
519        }
520
521        let mut grouped: BTreeMap<u32, Vec<BindingInfo>> = BTreeMap::new();
522        for info in &self.binding_infos {
523            grouped.entry(info.group).or_default().push(*info);
524        }
525
526        for (group, mut infos) in grouped {
527            infos.sort_by_key(|info| info.binding);
528            let layout_entries: Vec<wgpu::BindGroupLayoutEntry> = infos
529                .iter()
530                .map(|info| wgpu::BindGroupLayoutEntry {
531                    binding: info.binding,
532                    visibility: info.visibility,
533                    ty: match info.type_ {
534                        BindingType::UniformBuffer => wgpu::BindingType::Buffer {
535                            ty: wgpu::BufferBindingType::Uniform,
536                            has_dynamic_offset: false,
537                            min_binding_size: None,
538                        },
539                        BindingType::ReadOnlyStorageBuffer => wgpu::BindingType::Buffer {
540                            ty: wgpu::BufferBindingType::Storage { read_only: true },
541                            has_dynamic_offset: false,
542                            min_binding_size: None,
543                        },
544                        BindingType::StorageBuffer => wgpu::BindingType::Buffer {
545                            ty: wgpu::BufferBindingType::Storage { read_only: false },
546                            has_dynamic_offset: false,
547                            min_binding_size: None,
548                        },
549                        BindingType::Sampler => wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
550                        BindingType::Texture => wgpu::BindingType::Texture {
551                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
552                            view_dimension: wgpu::TextureViewDimension::D2,
553                            multisampled: false,
554                        },
555                        BindingType::UnfilterableTexture => wgpu::BindingType::Texture {
556                            sample_type: wgpu::TextureSampleType::Float { filterable: false },
557                            view_dimension: wgpu::TextureViewDimension::D2,
558                            multisampled: false,
559                        },
560                    },
561                    count: None,
562                })
563                .collect();
564            let label = format!("Shader Bind Group {group}");
565            let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
566                label: Some(&label),
567                entries: &layout_entries,
568            });
569            self.bind_group_order.push(group);
570            self.bindings_per_group.push(infos);
571            self.bind_group_layouts.push(layout);
572        }
573    }
574
575    fn create_pipeline(
576        &self,
577        vertex_layouts: &[VertexLayout],
578        color_mode: &ColorMode,
579        depth_mode: &DepthMode,
580        stencil_mode: &StencilMode,
581        draw_mode_type: DrawModeType,
582    ) -> Option<wgpu::RenderPipeline> {
583        let device = self.context.get_backend().get_device();
584        if !self.has_vertex_entry_point || !self.has_fragment_entry_point {
585            if !self.logged_missing_entry_point.get() {
586                eprintln!(
587                    "WebGPU: shader '{}' is missing WGSL entry points; skipping pipeline creation",
588                    self.shader_name
589                );
590                self.logged_missing_entry_point.set(true);
591            }
592            return None;
593        }
594        let (Some(device), Some(vertex_module), Some(fragment_module), Some(pipeline_layout)) = (
595            device,
596            self.vertex_shader_module.as_ref(),
597            self.fragment_shader_module.as_ref(),
598            self.pipeline_layout.as_ref(),
599        ) else {
600            eprintln!(
601                "createPipeline missing requirement: vertexModule={}, fragmentModule={}, pipelineLayout={}",
602                self.vertex_shader_module.is_some(),
603                self.fragment_shader_module.is_some(),
604                self.pipeline_layout.is_some()
605            );
606            return None;
607        };
608
609        let buffers: Vec<Option<wgpu::VertexBufferLayout<'_>>> = vertex_layouts
610            .iter()
611            .map(|l| {
612                Some(wgpu::VertexBufferLayout {
613                    array_stride: l.array_stride,
614                    step_mode: l.step_mode,
615                    attributes: &l.attributes,
616                })
617            })
618            .collect();
619
620        // Set up fragment state with color mode blending. Quirk ported: the
621        // blend state is always set; `Replace` keeps the SrcAlpha /
622        // OneMinusSrcAlpha defaults.
623        let mut alpha_blend = wgpu::BlendComponent {
624            operation: webgpu_blend_operation(ColorBlendEquationType::Add),
625            src_factor: webgpu_blend_factor(ColorBlendFactorType::SrcAlpha),
626            dst_factor: webgpu_blend_factor(ColorBlendFactorType::OneMinusSrcAlpha),
627        };
628        let mut color_blend = alpha_blend;
629        // Apply color mode blending if not replace
630        if color_mode.blend_function != BlendFunction::Replace {
631            let f = &color_mode.blend_function;
632            color_blend = wgpu::BlendComponent {
633                operation: webgpu_blend_operation(f.equation()),
634                src_factor: webgpu_blend_factor(f.src_factor()),
635                dst_factor: webgpu_blend_factor(f.dst_factor()),
636            };
637            alpha_blend = color_blend;
638        }
639
640        let color_format = self.context.get_backend().get_color_format().unwrap_or(wgpu::TextureFormat::Bgra8Unorm);
641        let mut write_mask = wgpu::ColorWrites::empty();
642        if color_mode.mask.r {
643            write_mask |= wgpu::ColorWrites::RED;
644        }
645        if color_mode.mask.g {
646            write_mask |= wgpu::ColorWrites::GREEN;
647        }
648        if color_mode.mask.b {
649            write_mask |= wgpu::ColorWrites::BLUE;
650        }
651        if color_mode.mask.a {
652            write_mask |= wgpu::ColorWrites::ALPHA;
653        }
654        let targets = [Some(wgpu::ColorTargetState {
655            format: color_format,
656            blend: Some(wgpu::BlendState { color: color_blend, alpha: alpha_blend }),
657            write_mask,
658        })];
659
660        // Set up primitive state
661        let primitive = wgpu::PrimitiveState {
662            topology: to_primitive_topology(draw_mode_type),
663            strip_index_format: if matches!(draw_mode_type, DrawModeType::LineStrip | DrawModeType::TriangleStrip) {
664                Some(wgpu::IndexFormat::Uint16)
665            } else {
666                None
667            },
668            front_face: wgpu::FrontFace::Ccw,
669            cull_mode: None,
670            ..Default::default()
671        };
672
673        // Set up depth stencil state
674        let depth_stencil = self.context.get_backend().get_depth_stencil_format().map(|depth_format| {
675            let keep_face = wgpu::StencilFaceState {
676                compare: wgpu::CompareFunction::Always,
677                fail_op: wgpu::StencilOperation::Keep,
678                depth_fail_op: wgpu::StencilOperation::Keep,
679                pass_op: wgpu::StencilOperation::Keep,
680            };
681            let mut stencil = wgpu::StencilState { front: keep_face, back: keep_face, read_mask: 0, write_mask: 0 };
682
683            let stencil_enabled = !(stencil_mode.test == Test::Always
684                && stencil_mode.mask == 0
685                && stencil_mode.fail == StencilOpType::Keep
686                && stencil_mode.depth_fail == StencilOpType::Keep
687                && stencil_mode.pass == StencilOpType::Keep);
688            if stencil_enabled {
689                let function = stencil_mode.test.func();
690                let read_mask = stencil_mode.test.masked().unwrap_or(0xFF);
691                let face = wgpu::StencilFaceState {
692                    compare: stencil_compare_function(function),
693                    fail_op: to_stencil_op(stencil_mode.fail),
694                    depth_fail_op: to_stencil_op(stencil_mode.depth_fail),
695                    pass_op: to_stencil_op(stencil_mode.pass),
696                };
697                stencil = wgpu::StencilState { front: face, back: face, read_mask, write_mask: stencil_mode.mask };
698            }
699
700            if self.shader_name == "ClippingMaskProgram" {
701                stencil.front.pass_op = wgpu::StencilOperation::Replace;
702                if stencil.write_mask == 0 {
703                    stencil.write_mask = 0xFF;
704                }
705                if stencil.read_mask == 0 {
706                    stencil.read_mask = 0xFF;
707                }
708                stencil.front.compare = wgpu::CompareFunction::Always;
709                stencil.back = stencil.front;
710            }
711
712            wgpu::DepthStencilState {
713                format: depth_format,
714                depth_write_enabled: Some(depth_mode.mask == DepthMaskType::ReadWrite),
715                depth_compare: Some(depth_compare_function(depth_mode.func)),
716                stencil,
717                bias: wgpu::DepthBiasState::default(),
718            }
719        });
720
721        // Create render pipeline (inside an error scope: a failure is the C++
722        // null pipeline)
723        let pipeline = validated(&device, || {
724            device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
725                label: Some(&self.shader_name),
726                layout: Some(pipeline_layout),
727                vertex: wgpu::VertexState {
728                    module: vertex_module,
729                    entry_point: Some("main"),
730                    compilation_options: Default::default(),
731                    buffers: &buffers,
732                },
733                primitive,
734                depth_stencil,
735                multisample: wgpu::MultisampleState { count: 1, mask: 0xFFFF_FFFF, alpha_to_coverage_enabled: false },
736                fragment: Some(wgpu::FragmentState {
737                    module: fragment_module,
738                    entry_point: Some("main"),
739                    compilation_options: Default::default(),
740                    targets: &targets,
741                }),
742                multiview_mask: None,
743                cache: None,
744            })
745        });
746        pipeline.map_err(|error| eprintln!("{} pipeline creation failed: {error}", self.shader_name)).ok()
747    }
748}
749
750impl Shader for ShaderProgram {
751    fn type_name(&self) -> &'static str {
752        Self::NAME
753    }
754    fn as_any(&self) -> &dyn Any {
755        self
756    }
757}
758
759impl ShaderProgramBase for ShaderProgram {
760    fn get_id(&self) -> SimpleIdentity {
761        self.shader_program_id
762    }
763    fn get_sampler_location(&self, id: usize) -> Option<usize> {
764        self.texture_bindings.get(id).copied().flatten()
765    }
766    fn get_vertex_attributes(&self) -> &VertexAttributeArray {
767        &self.vertex_attributes
768    }
769    fn get_instance_attributes(&self) -> &VertexAttributeArray {
770        &self.instance_attributes
771    }
772}
773
774/// Downcast a shader handle to the WebGPU program (C++ `static_cast`).
775pub fn as_webgpu_shader(shader: &Rc<dyn ShaderProgramBase>) -> Option<&ShaderProgram> {
776    shader.as_any().downcast_ref::<ShaderProgram>()
777}