Skip to main content

mln_webgpu/
drawable.rs

1// Ports include/mln/webgpu/drawable.hpp, src/mln/webgpu/drawable_impl.hpp and
2// src/mln/webgpu/drawable.cpp
3//
4// Logging: the C++ `Log::Warning`/`Log::Error` calls print to stderr here.
5// TODO(port): route them through mln::Log once a logging port exists.
6
7use crate::context::Context;
8use crate::render_pass::RenderPass;
9use crate::shaders::shader_program::{BindingType, ShaderProgram, VertexLayout, as_webgpu_shader};
10use crate::texture2d::Texture2D;
11use crate::uniform_buffer::UniformBuffer;
12use crate::upload_pass::UploadPass;
13use crate::vertex_buffer_resource::{IndexBufferResource, VertexBufferResource};
14use bytemuck::{Pod, Zeroable};
15use mln_gfx::attribute::AttributeBindingArray;
16use mln_gfx::color_mode::{BlendFunction, ColorMode};
17use mln_gfx::context::Context as _;
18use mln_gfx::cull_face_mode::CullFaceMode;
19use mln_gfx::depth_mode::DepthMode;
20use mln_gfx::draw_mode::DrawMode;
21use mln_gfx::drawable::{self, DrawSegment, DrawableBase, UniqueDrawSegment};
22use mln_gfx::gfx_types::{AttributeDataType, DrawModeType};
23use mln_gfx::index_vector::{IndexBufferBase, IndexVectorBasePtr};
24use mln_gfx::paint_parameters::PaintParameters;
25use mln_gfx::shaders::segment::SegmentBase;
26use mln_gfx::shaders::shader_defines::ID_GLOBAL_UBO_INDEX;
27use mln_gfx::shaders::shader_program_base::{ShaderProgramBasePtr, same_shader};
28use mln_gfx::stencil_mode::StencilMode;
29use mln_gfx::texture2d::Texture2D as _;
30use mln_gfx::types::{BufferUsageType, DepthMaskType};
31use mln_gfx::uniform_buffer::{UniformBufferArray, UniformBufferPtr};
32use mln_gfx::upload_pass::UploadPass as _;
33use mln_gfx::util_hash::hash;
34use mln_gfx::vertex_attribute::{VertexAttribute, VertexAttributeArray, VertexAttributeArrayPtr};
35use mln_gfx::vertex_buffer::{IndexBuffer as GfxIndexBuffer, UniqueVertexBufferResource};
36use std::any::Any;
37use std::cell::{Cell, RefCell};
38use std::rc::Rc;
39use std::time::Instant;
40
41#[derive(Clone, Copy, Pod, Zeroable)]
42#[repr(C, align(16))]
43struct GlobalUBOIndexData {
44    value: u32,
45    pad: [u32; 3],
46}
47
48fn hash_stencil_mode(mode: &StencilMode) -> u64 {
49    let mut h = hash(&[
50        mode.ref_ as i64 as u64,
51        u64::from(mode.mask),
52        mode.fail as u64,
53        mode.depth_fail as u64,
54        mode.pass as u64,
55    ]);
56    h = hash(&[h, mode.test.func() as u64]);
57    if let Some(mask) = mode.test.masked() {
58        h = hash(&[h, u64::from(mask)]);
59    }
60    h
61}
62
63fn hash_pipeline_state(
64    vertex_layouts: &[VertexLayout],
65    color_mode: &ColorMode,
66    depth_mode: &DepthMode,
67    stencil_mode: &StencilMode,
68    draw_mode_type: DrawModeType,
69) -> u64 {
70    let mut h = 0u64;
71    // Hash vertex layouts
72    for layout in vertex_layouts {
73        h = hash(&[h, layout.array_stride as u32 as u64]);
74        h = hash(&[h, layout.step_mode as u64]);
75        h = hash(&[h, layout.attributes.len() as u64]);
76        for attr in layout.attributes.iter().take(16) {
77            h = hash(&[h, attr.format as u64, u64::from(attr.shader_location), attr.offset as u32 as u64]);
78        }
79    }
80    // Hash color mode
81    h = hash(&[
82        h,
83        u64::from(color_mode.mask.r),
84        u64::from(color_mode.mask.g),
85        u64::from(color_mode.mask.b),
86        u64::from(color_mode.mask.a),
87    ]);
88    match &color_mode.blend_function {
89        BlendFunction::Replace => h = hash(&[h, 0]),
90        f => {
91            h = hash(&[h, f.equation() as u64, f.src_factor() as u64, f.dst_factor() as u64]);
92        }
93    }
94    // Hash depth mode
95    h = hash(&[h, depth_mode.func as u64, depth_mode.mask as u64]);
96    // Hash stencil mode
97    h = hash(&[h, hash_stencil_mode(stencil_mode)]);
98    // Hash draw mode
99    hash(&[h, draw_mode_type as u64])
100}
101
102fn wgpu_vertex_format_of(type_: AttributeDataType) -> wgpu::VertexFormat {
103    use AttributeDataType as A;
104    use wgpu::VertexFormat as F;
105    match type_ {
106        A::Byte => F::Sint8,
107        A::Byte2 => F::Sint8x2,
108        A::Byte4 => F::Sint8x4,
109        A::UByte => F::Uint8,
110        A::UByte2 => F::Uint8x2,
111        A::UByte4 => F::Uint8x4,
112        A::UByte4Normalized => F::Unorm8x4,
113        A::Short => F::Sint16,
114        A::Short2 => F::Sint16x2,
115        A::Short4 => F::Sint16x4,
116        A::UShort => F::Uint16,
117        A::UShort2 => F::Uint16x2,
118        A::UShort4 => F::Uint16x4,
119        A::Int => F::Sint32,
120        A::Int2 => F::Sint32x2,
121        A::Int3 => F::Sint32x3,
122        A::Int4 => F::Sint32x4,
123        A::UInt => F::Uint32,
124        A::UInt2 => F::Uint32x2,
125        A::UInt3 => F::Uint32x3,
126        A::UInt4 => F::Uint32x4,
127        A::Float => F::Float32,
128        A::Float2 => F::Float32x2,
129        A::Float3 => F::Float32x3,
130        A::Float4 => F::Float32x4,
131        _ => {
132            debug_assert!(false, "Unsupported vertex attribute format");
133            F::Float32x2 // Default fallback
134        }
135    }
136}
137
138/// `struct IndexBuffer : gfx::IndexBufferBase`: adapts `gfx::IndexBuffer`.
139struct IndexBuffer {
140    buffer: GfxIndexBuffer,
141}
142
143impl IndexBufferBase for IndexBuffer {
144    fn as_any(&self) -> &dyn Any {
145        self
146    }
147}
148
149struct BindGroupRecord {
150    slot: u32,
151    #[allow(dead_code)]
152    group: u32,
153    handle: wgpu::BindGroup,
154}
155
156/// `webgpu::Drawable::Impl`
157struct DrawableImpl {
158    segments: Vec<UniqueDrawSegment>,
159    vertex_desc_hash: u64,
160    indexes: Option<IndexVectorBasePtr>,
161    vertex_count: usize,
162    vertex_type: AttributeDataType,
163    attribute_bindings: AttributeBindingArray,
164    instance_bindings: AttributeBindingArray,
165    /// Store dummy vertex buffers to keep them alive
166    dummy_vertex_buffers: Vec<UniqueVertexBufferResource>,
167    uniform_buffers: UniformBufferArray,
168    ubo_index_uniform: Option<UniformBufferPtr>,
169    depth_mode: DepthMode,
170    stencil_mode: StencilMode,
171    #[allow(dead_code)]
172    cull_face_mode: CullFaceMode,
173    vertex_attr_id: usize,
174    stencil_mode_hash: u64,
175    stencil_mode_hash_valid: bool,
176    /// We don't own the pipeline - it's owned by the shader program's cache.
177    pipeline_state: Option<wgpu::RenderPipeline>,
178    previous_stencil_mode: StencilMode,
179    bind_groups: Vec<BindGroupRecord>,
180}
181
182pub struct Drawable {
183    base: DrawableBase,
184    impl_: DrawableImpl,
185}
186
187thread_local! {
188    static DRAW_CALL_COUNT: Cell<u64> = const { Cell::new(0) };
189}
190
191/// Owned resources of a bind group entry (the wgpu entries borrow them).
192enum EntryResource {
193    Buffer(wgpu::Buffer, u64),
194    Sampler(wgpu::Sampler),
195    TextureView(wgpu::TextureView),
196}
197
198impl Drawable {
199    pub fn new(name: String) -> Self {
200        Drawable {
201            base: DrawableBase::new(name),
202            impl_: DrawableImpl {
203                segments: Vec::new(),
204                vertex_desc_hash: 0,
205                indexes: None,
206                vertex_count: 0,
207                vertex_type: AttributeDataType::Invalid,
208                attribute_bindings: Vec::new(),
209                instance_bindings: Vec::new(),
210                dummy_vertex_buffers: Vec::new(),
211                uniform_buffers: UniformBufferArray::new(),
212                ubo_index_uniform: None,
213                depth_mode: DepthMode::disabled(),
214                stencil_mode: StencilMode::default(),
215                cull_face_mode: CullFaceMode::disabled(),
216                vertex_attr_id: 0,
217                stencil_mode_hash: 0,
218                stencil_mode_hash_valid: false,
219                pipeline_state: None,
220                previous_stencil_mode: StencilMode::default(),
221                bind_groups: Vec::new(),
222            },
223        }
224    }
225
226    pub fn set_depth_mode_for_3d(&mut self, value: &DepthMode) {
227        if self.impl_.depth_mode.func != value.func || self.impl_.depth_mode.mask != value.mask {
228            self.impl_.pipeline_state = None;
229        }
230        self.impl_.depth_mode = *value;
231    }
232
233    pub fn set_stencil_mode_for_3d(&mut self, value: &StencilMode) {
234        let new_hash = hash_stencil_mode(value);
235        let m = &self.impl_.stencil_mode;
236        if !self.impl_.stencil_mode_hash_valid
237            || self.impl_.stencil_mode_hash != new_hash
238            || m.ref_ != value.ref_
239            || m.mask != value.mask
240            || m.fail != value.fail
241            || m.depth_fail != value.depth_fail
242            || m.pass != value.pass
243        {
244            self.impl_.pipeline_state = None;
245            self.impl_.stencil_mode_hash_valid = false;
246        }
247        self.impl_.stencil_mode = *value;
248        self.impl_.stencil_mode_hash = new_hash;
249    }
250
251    pub fn set_vertex_attr_id(&mut self, id: usize) {
252        self.impl_.vertex_attr_id = id;
253    }
254
255    pub fn upload(&mut self, upload_pass: &UploadPass) {
256        if self.base.is_custom {
257            return;
258        }
259        let Some(shader) = self.base.shader.clone() else {
260            eprintln!("Missing shader for drawable {}/{}", self.base.unique_id, self.base.name);
261            debug_assert!(false);
262            return;
263        };
264
265        let usage = BufferUsageType::StaticDraw;
266
267        // We need either raw index data or a buffer already created from them.
268        // We can have a buffer and no indexes, but only if it's not marked dirty.
269        let Some(indexes) = self.impl_.indexes.clone() else {
270            debug_assert!(false, "Missing index data");
271            return;
272        };
273        {
274            let mut indexes = indexes.borrow_mut();
275            if indexes.empty() && (indexes.get_buffer().is_none() || indexes.get_dirty()) {
276                debug_assert!(false, "Missing index data");
277                return;
278            }
279            if indexes.get_buffer().is_none() || indexes.get_dirty() {
280                // Create or update a buffer for the index data. We don't
281                // update any existing buffer because it may still be in use
282                // by the previous frame.
283                let resource = upload_pass.create_index_buffer_resource(
284                    bytemuck::cast_slice(indexes.data()),
285                    usage,
286                    /*persistent=*/ false,
287                );
288                let gfx_index_buffer = GfxIndexBuffer::new(indexes.elements(), resource);
289                indexes.set_buffer(Some(Box::new(IndexBuffer { buffer: gfx_index_buffer })));
290                indexes.set_dirty(false);
291            }
292        }
293
294        // Upload vertex attributes (like Metal does)
295        let build_attribs = match (&self.base.vertex_attributes, self.base.attribute_update_time) {
296            (Some(attrs), Some(t)) => attrs.borrow().is_modified_after(t),
297            _ => true,
298        };
299        if build_attribs {
300            let attrs = self.base.vertex_attributes.get_or_insert_with(VertexAttributeArray::new_ptr).clone();
301            // Apply drawable values to shader defaults (matching Metal's approach)
302            let mut vertex_buffers = Vec::new();
303            let attribute_bindings = upload_pass.build_attribute_bindings(
304                self.impl_.vertex_count,
305                self.impl_.vertex_type,
306                /*vertexAttributeIndex=*/ usize::MAX,
307                /*vertexData=*/ &[],
308                shader.get_vertex_attributes(),
309                &mut attrs.borrow_mut(),
310                usage,
311                self.base.attribute_update_time,
312                &mut vertex_buffers,
313            );
314            if self.impl_.attribute_bindings != attribute_bindings {
315                self.impl_.attribute_bindings = attribute_bindings;
316                self.impl_.vertex_desc_hash = 0; // Reset hash when bindings change
317                self.impl_.pipeline_state = None; // Reset pipeline state when attribute bindings change
318                // Store the dummy vertex buffers to keep them alive
319                self.impl_.dummy_vertex_buffers = vertex_buffers;
320            }
321        }
322
323        // Build instance buffer (like Metal does)
324        let build_instance_buffer = match (&self.base.instance_attributes, self.base.attribute_update_time) {
325            (Some(attrs), Some(t)) => attrs.borrow().is_modified_after(t),
326            (Some(_), None) => true,
327            (None, _) => false,
328        };
329        if build_instance_buffer {
330            let attrs = self.base.instance_attributes.clone().unwrap();
331            let mut instance_buffers = Vec::new();
332            let instance_bindings = upload_pass.build_attribute_bindings(
333                self.impl_.vertex_count,
334                self.impl_.vertex_type,
335                usize::MAX,
336                &[],
337                shader.get_instance_attributes(),
338                &mut attrs.borrow_mut(),
339                usage,
340                self.base.attribute_update_time,
341                &mut instance_buffers,
342            );
343            if self.impl_.instance_bindings != instance_bindings {
344                self.impl_.instance_bindings = instance_bindings;
345                self.impl_.pipeline_state = None; // Reset pipeline state when instance bindings change
346                // Store the dummy instance buffers to keep them alive
347                self.impl_.dummy_vertex_buffers.extend(instance_buffers);
348            }
349        }
350
351        // Upload uniform buffers to ensure they're ready for the GPU: only a
352        // check that each has a GPU buffer.
353        for i in 0..self.impl_.uniform_buffers.allocated_size() {
354            if let Some(ub) = self.impl_.uniform_buffers.get(i)
355                && let Some(webgpu_ub) = ub.as_any().downcast_ref::<UniformBuffer>()
356                && webgpu_ub.get_buffer().is_none()
357            {
358                eprintln!("Uniform buffer {i} has no GPU buffer!");
359            }
360        }
361
362        // Upload textures if needed
363        let textures_need_upload = self.base.textures.iter().flatten().any(|t| t.borrow().needs_upload());
364        if textures_need_upload {
365            for texture in self.base.textures.iter().flatten() {
366                let mut t = texture.borrow_mut();
367                if t.needs_upload() {
368                    t.upload();
369                }
370            }
371        }
372
373        self.base.attribute_update_time = Some(Instant::now());
374    }
375
376    /// Build the bind groups for this draw from the shader's metadata.
377    /// Returns false when the draw must be skipped (C++ `return`).
378    fn build_bind_groups(&mut self, context: &Context, render_pass: &RenderPass, shader: &ShaderProgram) -> bool {
379        self.impl_.bind_groups.clear();
380        let Some(device) = context.get_backend().get_device() else {
381            return true;
382        };
383        let draw_call_count = DRAW_CALL_COUNT.with(Cell::get);
384        let global_buffers = render_pass.get_global_uniform_buffers();
385        let textures = &self.base.textures;
386        let find_texture_for_binding = |binding: u32, sampler_binding: bool| -> Option<Rc<RefCell<dyn mln_gfx::texture2d::Texture2D>>> {
387            for (tex_index, texture) in textures.iter().enumerate() {
388                let Some(texture) = texture else { continue };
389                if let Some(location) = shader.get_sampler_location_of(tex_index) {
390                    let location = location as u32;
391                    if (sampler_binding && location == binding)
392                        || (!sampler_binding && (location == binding || location + 1 == binding))
393                    {
394                        return Some(texture.clone());
395                    }
396                }
397            }
398            None
399        };
400
401        let group_order = shader.get_bind_group_order().to_vec();
402        for (slot, &group) in group_order.iter().enumerate() {
403            let Some(layout) = shader.get_bind_group_layout(group) else {
404                eprintln!(
405                    "WebGPU: missing bind group layout for group {group} in shader '{}'",
406                    shader.get_shader_name()
407                );
408                return false;
409            };
410            let binding_infos = shader.get_binding_infos_for_group(group);
411
412            let mut resources: Vec<(u32, EntryResource)> = Vec::with_capacity(binding_infos.len());
413            let mut valid_bindings = true;
414            for binding_info in binding_infos {
415                match binding_info.type_ {
416                    BindingType::UniformBuffer | BindingType::ReadOnlyStorageBuffer | BindingType::StorageBuffer => {
417                        let mut buffer = self.impl_.uniform_buffers.get(binding_info.binding as usize).cloned();
418                        if binding_info.binding as usize == ID_GLOBAL_UBO_INDEX {
419                            let index_data = GlobalUBOIndexData { value: self.base.ubo_index, pad: [0; 3] };
420                            context.emplace_or_update_uniform_buffer(
421                                &mut self.impl_.ubo_index_uniform,
422                                bytemuck::bytes_of(&index_data),
423                                false,
424                            );
425                            if let Some(ubo) = self.impl_.ubo_index_uniform.clone() {
426                                self.impl_.uniform_buffers.set(binding_info.binding as usize, Some(ubo.clone()));
427                                buffer = Some(ubo);
428                            }
429                        }
430                        if buffer.is_none()
431                            && let Some(globals) = &global_buffers
432                        {
433                            buffer = globals.get(binding_info.binding as usize).cloned();
434                        }
435                        let Some(buffer) = buffer else {
436                            if draw_call_count <= 200 {
437                                eprintln!(
438                                    "No buffer found for binding {} type={} group={group}",
439                                    binding_info.binding, binding_info.type_ as i32
440                                );
441                            }
442                            valid_bindings = false;
443                            break;
444                        };
445                        let gpu_buffer = buffer
446                            .as_any()
447                            .downcast_ref::<UniformBuffer>()
448                            .and_then(|b| b.get_buffer().cloned());
449                        let Some(gpu_buffer) = gpu_buffer else {
450                            if draw_call_count <= 200 {
451                                eprintln!(
452                                    "Uniform buffer missing GPU handle for binding {} group={group}",
453                                    binding_info.binding
454                                );
455                            }
456                            valid_bindings = false;
457                            break;
458                        };
459                        resources.push((binding_info.binding, EntryResource::Buffer(gpu_buffer, buffer.get_size() as u64)));
460                    }
461                    BindingType::Sampler => {
462                        let Some(texture) = find_texture_for_binding(binding_info.binding, true) else {
463                            valid_bindings = false;
464                            break;
465                        };
466                        let mut texture = texture.borrow_mut();
467                        let Some(texture) = texture.as_any_mut().downcast_mut::<Texture2D>() else {
468                            valid_bindings = false;
469                            break;
470                        };
471                        if texture.get_sampler().is_none() {
472                            let state = *texture.get_sampler_state();
473                            texture.set_sampler_configuration(state);
474                        }
475                        let Some(sampler) = texture.get_sampler().cloned() else {
476                            valid_bindings = false;
477                            break;
478                        };
479                        resources.push((binding_info.binding, EntryResource::Sampler(sampler)));
480                    }
481                    BindingType::Texture | BindingType::UnfilterableTexture => {
482                        let Some(texture) = find_texture_for_binding(binding_info.binding, false) else {
483                            valid_bindings = false;
484                            break;
485                        };
486                        let mut texture = texture.borrow_mut();
487                        let Some(texture) = texture.as_any_mut().downcast_mut::<Texture2D>() else {
488                            valid_bindings = false;
489                            break;
490                        };
491                        if texture.get_texture().is_none() || texture.get_texture_view().is_none() {
492                            texture.create();
493                        }
494                        let Some(view) = texture.get_texture_view().cloned() else {
495                            valid_bindings = false;
496                            break;
497                        };
498                        resources.push((binding_info.binding, EntryResource::TextureView(view)));
499                    }
500                }
501            }
502
503            if !valid_bindings || resources.is_empty() {
504                eprintln!(
505                    "WebGPU: invalid bindings for drawable '{}' (group={group}, slot={slot})",
506                    self.base.name
507                );
508                return false;
509            }
510
511            let entries: Vec<wgpu::BindGroupEntry<'_>> = resources
512                .iter()
513                .map(|(binding, resource)| wgpu::BindGroupEntry {
514                    binding: *binding,
515                    resource: match resource {
516                        EntryResource::Buffer(buffer, size) => wgpu::BindingResource::Buffer(wgpu::BufferBinding {
517                            buffer,
518                            offset: 0,
519                            size: wgpu::BufferSize::new(*size),
520                        }),
521                        EntryResource::Sampler(sampler) => wgpu::BindingResource::Sampler(sampler),
522                        EntryResource::TextureView(view) => wgpu::BindingResource::TextureView(view),
523                    },
524                })
525                .collect();
526            let label = format!("{} bind-group {group}", self.base.name);
527            let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
528                label: Some(&label),
529                layout,
530                entries: &entries,
531            });
532            self.impl_.bind_groups.push(BindGroupRecord { slot: slot as u32, group, handle: bind_group });
533        }
534        true
535    }
536}
537
538impl ShaderProgram {
539    fn get_sampler_location_of(&self, id: usize) -> Option<usize> {
540        mln_gfx::shaders::shader_program_base::ShaderProgramBase::get_sampler_location(self, id)
541    }
542}
543
544/// `UniqueBinding` in `Drawable::draw`
545struct UniqueBinding {
546    vertex_resource: Rc<dyn mln_gfx::vertex_buffer::VertexBufferResource>,
547    buffer: Option<wgpu::Buffer>,
548    buffer_size: u64,
549    stride: u32,
550    base_offset: u64,
551    step_mode: wgpu::VertexStepMode,
552    attributes: Vec<wgpu::VertexAttribute>,
553    attribute_byte_offsets: Vec<u64>,
554}
555
556fn accumulate_bindings(source: &AttributeBindingArray, step_mode: wgpu::VertexStepMode, out: &mut Vec<UniqueBinding>) {
557    for (attribute_index, binding) in source.iter().enumerate() {
558        let Some(binding) = binding else { continue };
559        let Some(resource) = &binding.vertex_buffer_resource else { continue };
560        let Some(vertex_buffer_res) = resource.as_any().downcast_ref::<VertexBufferResource>() else {
561            continue;
562        };
563        let (buffer, buffer_size) = {
564            let b = vertex_buffer_res.get_buffer();
565            (b.get_buffer().cloned(), b.get_size_in_bytes() as u64)
566        };
567        if buffer.is_none() {
568            continue;
569        }
570        let binding_byte_offset = u64::from(binding.vertex_offset) * u64::from(binding.vertex_stride);
571        let pos = out.iter().position(|e| {
572            std::ptr::addr_eq(Rc::as_ptr(&e.vertex_resource), Rc::as_ptr(resource))
573                && e.stride == binding.vertex_stride
574                && e.step_mode == step_mode
575        });
576        let entry = match pos {
577            None => {
578                out.push(UniqueBinding {
579                    vertex_resource: resource.clone(),
580                    buffer,
581                    buffer_size,
582                    stride: binding.vertex_stride,
583                    base_offset: binding_byte_offset,
584                    step_mode,
585                    attributes: Vec::with_capacity(4),
586                    attribute_byte_offsets: Vec::with_capacity(4),
587                });
588                out.last_mut().unwrap()
589            }
590            Some(i) => {
591                let e = &mut out[i];
592                e.base_offset = e.base_offset.min(binding_byte_offset);
593                e
594            }
595        };
596        entry.attributes.push(wgpu::VertexAttribute {
597            format: wgpu_vertex_format_of(binding.attribute.data_type),
598            offset: u64::from(binding.attribute.offset),
599            shader_location: attribute_index as u32,
600        });
601        entry.attribute_byte_offsets.push(binding_byte_offset);
602    }
603}
604
605impl drawable::Drawable for Drawable {
606    fn base(&self) -> &DrawableBase {
607        &self.base
608    }
609    fn base_mut(&mut self) -> &mut DrawableBase {
610        &mut self.base
611    }
612    fn as_any(&self) -> &dyn Any {
613        self
614    }
615    fn as_any_mut(&mut self) -> &mut dyn Any {
616        self
617    }
618
619    fn draw(&mut self, parameters: &mut dyn PaintParameters) {
620        let draw_call_count = DRAW_CALL_COUNT.with(|c| {
621            c.set(c.get() + 1);
622            c.get()
623        });
624        if self.base.is_custom {
625            return;
626        }
627
628        // Get WebGPU context and render pass (following Metal's pattern)
629        let parameters: &dyn PaintParameters = parameters;
630        let Some(context) = parameters.context().as_any().downcast_ref::<Context>() else {
631            return;
632        };
633        let Some(render_pass) = parameters.render_pass().and_then(|p| p.as_any().downcast_ref::<RenderPass>()) else {
634            eprintln!("No render pass encoder available");
635            debug_assert!(false);
636            return;
637        };
638        if !render_pass.has_encoder() {
639            eprintln!("No render pass encoder available");
640            debug_assert!(false);
641            return;
642        }
643
644        let Some(shader_ptr) = self.base.shader.clone() else {
645            eprintln!("Missing shader for drawable {}/{}", self.base.unique_id, self.base.name);
646            debug_assert!(false);
647            return;
648        };
649        if !self.base.enabled {
650            return;
651        }
652
653        let backend = context.get_backend();
654        if backend.get_device().is_none() || backend.get_queue().is_none() {
655            return;
656        }
657
658        // Bind uniform buffers (a no-op in WebGPU, see UniformBufferArray).
659
660        // Check index buffer is valid (like Metal does)
661        if let Some(indexes) = &self.impl_.indexes {
662            let indexes = indexes.borrow();
663            if indexes.get_buffer().is_none() || indexes.get_dirty() {
664                debug_assert!(false, "Index buffer not uploaded");
665                return;
666            }
667        }
668
669        // Build bind groups based on shader metadata
670        let Some(shader) = as_webgpu_shader(&shader_ptr) else {
671            return;
672        };
673        if !self.build_bind_groups(context, render_pass, shader) {
674            return;
675        }
676
677        let drawable_tile_id = self.base.tile_id;
678        let mut depth_mode = DepthMode::disabled();
679        let mut stencil_mode = StencilMode::disabled();
680        if self.base.is_3d {
681            depth_mode = self.impl_.depth_mode;
682            stencil_mode = self.impl_.stencil_mode;
683        } else {
684            if self.base.enable_depth {
685                depth_mode = parameters.depth_mode_for_sublayer(self.base.sub_layer_index as u8, self.base.depth_type);
686            }
687            if self.base.enable_stencil
688                && let Some(tile_id) = drawable_tile_id
689            {
690                stencil_mode = parameters.stencil_mode_for_clipping(&tile_id.to_unwrapped());
691            }
692        }
693
694        let new_stencil_hash = hash_stencil_mode(&stencil_mode);
695        if !self.impl_.stencil_mode_hash_valid
696            || self.impl_.stencil_mode_hash != new_stencil_hash
697            || self.impl_.depth_mode.func != depth_mode.func
698            || self.impl_.depth_mode.mask != depth_mode.mask
699        {
700            self.impl_.pipeline_state = None;
701            self.impl_.stencil_mode_hash_valid = true;
702        }
703        self.impl_.depth_mode = depth_mode;
704        self.impl_.stencil_mode = stencil_mode;
705        self.impl_.stencil_mode_hash = new_stencil_hash;
706        self.impl_.previous_stencil_mode = stencil_mode;
707
708        let mut unique_bindings: Vec<UniqueBinding> =
709            Vec::with_capacity(self.impl_.attribute_bindings.len() + self.impl_.instance_bindings.len());
710        accumulate_bindings(&self.impl_.attribute_bindings, wgpu::VertexStepMode::Vertex, &mut unique_bindings);
711        accumulate_bindings(&self.impl_.instance_bindings, wgpu::VertexStepMode::Instance, &mut unique_bindings);
712
713        const MAX_VERTEX_BUFFER_SLOTS: usize = 8;
714        if unique_bindings.len() > MAX_VERTEX_BUFFER_SLOTS {
715            eprintln!(
716                "WebGPU: reducing vertex buffer bindings from {} to {MAX_VERTEX_BUFFER_SLOTS}",
717                unique_bindings.len()
718            );
719            unique_bindings.truncate(MAX_VERTEX_BUFFER_SLOTS);
720        }
721
722        for entry in &mut unique_bindings {
723            for j in 0..entry.attributes.len() {
724                if entry.attribute_byte_offsets[j] < entry.base_offset {
725                    continue;
726                }
727                let delta = entry.attribute_byte_offsets[j] - entry.base_offset;
728                entry.attributes[j].offset += u64::from(delta as u32);
729            }
730        }
731
732        if self.impl_.pipeline_state.is_none() {
733            // Create vertex layout from attribute bindings
734            let vertex_layouts: Vec<VertexLayout> = unique_bindings
735                .iter()
736                .map(|b| VertexLayout {
737                    array_stride: u64::from(b.stride),
738                    step_mode: b.step_mode,
739                    attributes: b.attributes.clone(),
740                })
741                .collect();
742            // Use the actual color mode from the drawable (like Metal does)
743            let color_mode = self.base.color_mode;
744            let draw_mode_type =
745                self.impl_.segments.first().map_or(DrawModeType::Triangles, |s| s.get_mode().type_);
746            // Compute pipeline state hash for caching
747            let pipeline_hash =
748                hash_pipeline_state(&vertex_layouts, &color_mode, &depth_mode, &stencil_mode, draw_mode_type);
749            self.impl_.pipeline_state = shader.get_render_pipeline(
750                &vertex_layouts,
751                &color_mode,
752                &depth_mode,
753                &stencil_mode,
754                draw_mode_type,
755                Some(pipeline_hash),
756            );
757            if self.impl_.pipeline_state.is_none() {
758                eprintln!(
759                    "WebGPU: skipping pipeline creation for drawable '{}' (shader='{}')",
760                    self.base.name,
761                    mln_gfx::shader::Shader::type_name(shader)
762                );
763            }
764        }
765
766        let mut encoder_guard = render_pass.get_encoder();
767        let Some(encoder) = encoder_guard.as_mut() else {
768            eprintln!("renderPassEncoder is null!");
769            return;
770        };
771        let Some(pipeline) = &self.impl_.pipeline_state else {
772            eprintln!("WebGPU: no pipeline available for drawable '{}'; draw skipped", self.base.name);
773            return;
774        };
775        encoder.set_pipeline(pipeline);
776        if self.base.enable_stencil {
777            encoder.set_stencil_reference(stencil_mode.ref_ as u32);
778        }
779
780        // Clamp scissor to the current render pass size (not the default
781        // renderable, which may be different during offscreen passes).
782        {
783            let rt_size = render_pass.get_renderable_size();
784            let scissor = parameters.scissor_rect();
785            let sx = scissor.x as u32;
786            let sy = scissor.y as u32;
787            let sw = if sx < rt_size.width { scissor.width.min(rt_size.width - sx) } else { 0 };
788            let sh = if sy < rt_size.height { scissor.height.min(rt_size.height - sy) } else { 0 };
789            if sw > 0 && sh > 0 {
790                encoder.set_scissor_rect(sx, sy, sw, sh);
791            }
792        }
793
794        let mut buffer_slot = 0u32;
795        for binding in &unique_bindings {
796            let Some(buffer) = &binding.buffer else { continue };
797            let buffer_size = binding.buffer_size;
798            if binding.base_offset >= buffer_size {
799                eprintln!(
800                    "Skipping vertex buffer slot {buffer_slot} due to base offset {} >= size {buffer_size}",
801                    binding.base_offset
802                );
803                continue;
804            }
805            encoder.set_vertex_buffer(buffer_slot, buffer.slice(binding.base_offset..buffer_size));
806            buffer_slot += 1;
807        }
808
809        // Bind index buffer if present
810        if let Some(indexes) = &self.impl_.indexes {
811            let indexes = indexes.borrow();
812            if indexes.elements() > 0
813                && !indexes.get_dirty()
814                && let Some(index_buffer) =
815                    indexes.get_buffer().and_then(|b| b.as_any().downcast_ref::<IndexBuffer>())
816                && let Some(resource) = index_buffer.buffer.get_resource::<IndexBufferResource>()
817            {
818                let buffer_resource = resource.get_buffer();
819                if let Some(buffer) = buffer_resource.get_buffer() {
820                    // Always use Uint16 format for now
821                    encoder.set_index_buffer(
822                        buffer.slice(0..buffer_resource.get_size_in_bytes() as u64),
823                        wgpu::IndexFormat::Uint16,
824                    );
825                }
826            }
827        }
828
829        // Set bind groups
830        for record in &self.impl_.bind_groups {
831            encoder.set_bind_group(record.slot, &record.handle, &[]);
832        }
833
834        // Handle depth and stencil states (like Metal does). For 3D mode,
835        // stenciling is handled by the layer group.
836        if !self.base.is_3d {
837            if self.base.enable_stencil {
838                if let Some(tile_id) = self.base.tile_id {
839                    let expected_stencil = parameters.stencil_mode_for_clipping(&tile_id.to_unwrapped());
840                    if hash_stencil_mode(&expected_stencil) != hash_stencil_mode(&self.impl_.stencil_mode) {
841                        debug_assert!(false, "stencil mismatch");
842                        eprintln!("WebGPU drawable stencil mismatch for '{}' tile={tile_id}", self.base.name);
843                    }
844                    encoder.set_stencil_reference(expected_stencil.ref_ as u32);
845                }
846            } else {
847                // Reset the reference so subsequent drawables that re-enable
848                // stencilling start from a known value.
849                encoder.set_stencil_reference(0);
850            }
851            if self.base.enable_depth {
852                #[cfg(debug_assertions)]
853                {
854                    let expected_depth =
855                        parameters.depth_mode_for_sublayer(self.base.sub_layer_index as u8, self.base.depth_type);
856                    debug_assert!(expected_depth.func == self.impl_.depth_mode.func);
857                    debug_assert!(expected_depth.mask == self.impl_.depth_mode.mask);
858                }
859            }
860        }
861
862        // Draw indexed geometry - loop through segments (exactly like Metal does)
863        let instance_count = match &self.base.instance_attributes {
864            Some(attrs) => attrs.borrow().get_min_count() as u32,
865            None => 1,
866        };
867        let mut draw_calls = 0;
868        for segment in &self.impl_.segments {
869            let ml_segment = segment.get_segment();
870            if ml_segment.index_length > 0 {
871                let index_offset = ml_segment.index_offset as u32;
872                let base_vertex = ml_segment.vertex_offset as i32;
873                let base_instance = 0u32;
874                encoder.draw_indexed(
875                    index_offset..index_offset + ml_segment.index_length as u32,
876                    base_vertex,
877                    base_instance..base_instance + instance_count,
878                );
879                draw_calls += 1;
880            }
881        }
882        drop(encoder_guard);
883        if draw_calls > 0 {
884            let mut stats = context.rendering_stats_mut();
885            stats.num_draw_calls += draw_calls;
886            stats.total_draw_calls += draw_calls;
887        }
888        let _ = draw_call_count;
889    }
890
891    fn update_vertex_attributes(
892        &mut self,
893        vertices: Option<VertexAttributeArrayPtr>,
894        vertex_count: usize,
895        mode: DrawMode,
896        indexes: Option<IndexVectorBasePtr>,
897        segments: &[SegmentBase],
898    ) {
899        // Store the vertex attributes (base class method)
900        drawable::Drawable::set_vertex_attributes(self, vertices);
901        // Store vertex count
902        self.impl_.vertex_count = vertex_count;
903        // Handle segments
904        let draw_segs: Vec<UniqueDrawSegment> =
905            segments.iter().map(|seg| Box::new(DrawSegment::new(mode, seg.copy()))).collect();
906        // Set the index data with segments
907        self.set_index_data(indexes, draw_segs);
908    }
909
910    fn set_vertices(&mut self, data: Vec<u8>, count: usize, data_type: AttributeDataType) {
911        self.impl_.vertex_count = count;
912        self.impl_.vertex_type = data_type;
913        if count != 0 && data_type != AttributeDataType::Invalid && !data.is_empty() {
914            let attrs = self.base.vertex_attributes.get_or_insert_with(VertexAttributeArray::new_ptr).clone();
915            let mut attrs = attrs.borrow_mut();
916            if let Some(attrib) = attrs.set(self.impl_.vertex_attr_id, /*index=*/ -1, data_type, 0) {
917                attrib.set_raw_data(data);
918                attrib.set_stride(VertexAttribute::get_stride_of(data_type));
919            } else {
920                eprintln!("Vertex attribute type mismatch: {} / {}", self.base.name, self.impl_.vertex_attr_id);
921                debug_assert!(false);
922            }
923        }
924    }
925
926    fn set_index_data(&mut self, indexes: Option<IndexVectorBasePtr>, segments: Vec<UniqueDrawSegment>) {
927        self.impl_.indexes = indexes;
928        self.impl_.segments = segments;
929    }
930
931    fn get_uniform_buffers(&self) -> &UniformBufferArray {
932        &self.impl_.uniform_buffers
933    }
934
935    fn mutable_uniform_buffers(&mut self) -> &mut UniformBufferArray {
936        &mut self.impl_.uniform_buffers
937    }
938
939    fn set_color_mode(&mut self, value: &ColorMode) {
940        self.base.color_mode = *value;
941        self.impl_.pipeline_state = None; // Rebuild pipeline to honour new color mode
942    }
943
944    fn set_enable_stencil(&mut self, value: bool) {
945        if self.base.enable_stencil == value {
946            return;
947        }
948        self.base.enable_stencil = value;
949        self.impl_.pipeline_state = None; // Force recreation with new stencil state
950    }
951
952    fn set_enable_depth(&mut self, value: bool) {
953        if self.base.enable_depth == value {
954            return;
955        }
956        self.base.enable_depth = value;
957        self.impl_.pipeline_state = None; // Force recreation with new depth state
958    }
959
960    fn set_sub_layer_index(&mut self, value: i32) {
961        if self.base.sub_layer_index == value {
962            return;
963        }
964        self.base.sub_layer_index = value;
965    }
966
967    fn set_depth_type(&mut self, value: DepthMaskType) {
968        if self.base.depth_type == value {
969            return;
970        }
971        self.base.depth_type = value;
972        self.impl_.pipeline_state = None; // Force recreation with new depth mask
973    }
974
975    fn set_shader(&mut self, value: Option<ShaderProgramBasePtr>) {
976        if same_shader(&self.base.shader, &value) {
977            return;
978        }
979        self.base.shader = value;
980        self.impl_.pipeline_state = None; // Reset pipeline when shader changes
981    }
982}