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