awsm-renderer 0.4.2

awsm-renderer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Mesh data and rendering helpers.

use awsm_renderer_core::{
    command::render_pass::RenderPassEncoder, pipeline::primitive::IndexFormat,
};

use crate::materials::MaterialKey;
use crate::meshes::error::AwsmMeshError;
use crate::meshes::MeshKey;
use crate::render::RenderContext;
use crate::render_passes::geometry::bind_group::GeometryBindGroups;
use crate::render_passes::geometry::pipeline::GeometryRenderPipelineKeyOpts;
use crate::transforms::TransformKey;
use crate::{bounds::Aabb, pipelines::render_pipeline::RenderPipelineKey};

use crate::error::Result;

// this is most like a "primitive" in gltf, not the containing "mesh"
// because for non-gltf naming, "mesh" makes more sense
/// Camera-facing rotation override applied in the geometry vertex shader.
///
/// Mirrors `BillboardMode` in `lockstep-game-data` and the `billboard_mode`
/// field on the WGSL `GeometryMeshMeta` struct. The shader picks one of three
/// paths after `apply_vertex` builds the world transform.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BillboardMode {
    /// No override — the mesh uses its authored rotation.
    #[default]
    None,
    /// Yaw-only — rotates around world `+Y` to face the camera, preserving the
    /// authored pitch / roll. Right pick for upright sprites (name tags, etc.).
    YAxis,
    /// Full — overrides the rotation so the mesh's local `+Z` points at the
    /// camera with the world-up reference for the secondary basis. Right pick
    /// for particle quads and generic billboards.
    Full,
}

impl BillboardMode {
    /// Encoding written into `GeometryMeshMeta::billboard_mode` for the
    /// vertex shader. Must match the WGSL constants in `apply_vertex.wgsl`.
    pub fn as_u32(self) -> u32 {
        match self {
            BillboardMode::None => 0,
            BillboardMode::YAxis => 1,
            BillboardMode::Full => 2,
        }
    }
}

/// Mesh instance metadata and render flags.
#[derive(Debug, Clone)]
pub struct Mesh {
    pub world_aabb: Option<Aabb>, // this is the transformed AABB, used for frustum culling and depth sorting
    pub transform_key: TransformKey,
    pub material_key: MaterialKey,
    pub double_sided: bool,
    pub instanced: bool,
    pub hud: bool,
    pub hidden: bool,
    /// Base instance index into the per-instance attribute storage buffer
    /// (`u32::MAX` = no per-instance attributes; identity tint at shading
    /// time). Set by `AwsmRenderer::set_mesh_instance_attrs` after writing
    /// the attribute slice via `Instances::attribute_insert`.
    pub instance_attr_base: u32,
    /// Camera-facing rotation override applied in the geometry vertex shader.
    /// Defaults to `BillboardMode::None`; sprite + particle meshes set it to
    /// `YAxis` / `Full` at construction time.
    pub billboard_mode: BillboardMode,
    /// Whether this mesh appears in the shadow-generation pass.
    /// Defaults to `true`; sprites/particles override to `false`.
    pub cast_shadows: bool,
    /// Whether this mesh is darkened by shadow sampling during shading.
    /// Defaults to `true`.
    pub receive_shadows: bool,
    /// Skinning update cadence in frames. `1` (the default) updates every
    /// frame; `2` updates every other frame; `4` quarter-rate, etc.
    /// Distance-LOD'd characters typically run at `2` or `4` past a few
    /// metres — the visual difference at that distance is below the per-
    /// pixel threshold and the GPU animation budget drops linearly.
    ///
    /// Pairs with the coverage-driven skinning skip (live in
    /// `Meshes::update_world` since the grace-period + BVH-visible
    /// override landed) — coverage answers "skip this frame
    /// entirely?", `skin_update_period` answers "what's the
    /// background cadence when not skipped?". The two stack: a
    /// `period = 4` skin that's also out-of-frustum runs *never*
    /// until either gate flips.
    pub skin_update_period: u8,
    /// Cheap material variant for low-coverage shading.
    /// When set, the renderer swaps `material_key` → this key for any
    /// frame where the mesh's last-frame coverage is below
    /// `cheap_material_pixel_threshold`. `None` (the default) opts out
    /// — the mesh always uses its full `material_key`.
    pub cheap_material_key: Option<MaterialKey>,
    /// Coverage threshold (in pixels) below which the cheap material
    /// variant takes over. Only consulted when `cheap_material_key` is
    /// `Some`. `None` falls back to the renderer's
    /// `default_cheap_material_pixel_threshold` (global knob; not
    /// tier-coupled). Per-mesh override stays on top so artists can
    /// dial individual props up / down without touching the global.
    pub cheap_material_pixel_threshold: Option<u32>,
    /// Whether projection decals can land on this
    /// mesh. Default `true`. The decal compute pass reads this from
    /// each pixel's `MaterialMeshMeta` and skips the per-decal
    /// volume test for non-receiving meshes — useful for sky-domes,
    /// HUD-like geometry, or surfaces the artist wants kept clean.
    pub receive_decals: bool,
    /// Whether this mesh was built with VISIBILITY geometry (the exploded
    /// per-pixel stream the geometry/opaque + shadow passes draw from).
    ///
    /// DERIVED by [`crate::meshes::Meshes::insert`] from whether visibility
    /// geometry data was provided — NOT a caller-set value (any value on the
    /// `Mesh` handed to `insert` is overwritten). `pub(crate)` + insert-derived
    /// so it can never disagree with the actual buffers: it is the ground truth
    /// for pass routing in `collect_renderables`, and a mesh routed to a pass it
    /// has no buffer for is a frame-killing `…GeometryBufferNotFound`.
    pub(crate) has_visibility_geometry: bool,
    /// Whether this mesh was built with TRANSPARENCY geometry (the
    /// forward-rendered stream the transparency pass draws from). Same
    /// insert-derived, `pub(crate)` contract as [`Self::has_visibility_geometry`].
    pub(crate) has_transparency_geometry: bool,
}

impl Mesh {
    /// Creates a mesh with the given properties.
    pub fn new(
        transform_key: TransformKey,
        material_key: MaterialKey,
        double_sided: bool,
        instanced: bool,
        hud: bool,
        hidden: bool,
    ) -> Self {
        Self {
            transform_key,
            material_key,
            double_sided,
            instanced,
            hud,
            world_aabb: None,
            hidden,
            instance_attr_base: u32::MAX,
            billboard_mode: BillboardMode::None,
            cast_shadows: true,
            receive_shadows: true,
            skin_update_period: 1,
            cheap_material_key: None,
            cheap_material_pixel_threshold: None,
            receive_decals: true,
            // Placeholders only — `Meshes::insert` derives both from the
            // geometry data actually provided, overwriting whatever is set here.
            // A constructor can't know the mesh's real geometry shape, so it
            // doesn't get to assert one; `insert` is the single source of truth.
            has_visibility_geometry: false,
            has_transparency_geometry: false,
        }
    }

    /// Effective material to use for this frame given last-frame
    /// coverage. Returns `cheap_material_key` when it's set AND the
    /// mesh's last-frame coverage is below
    /// `cheap_material_pixel_threshold` (falling back to
    /// `default_threshold` when `None`); otherwise the authored
    /// `material_key`.
    ///
    /// Called once per frame per mesh by
    /// `Meshes::refresh_cheap_material_routing`, which patches the
    /// resolved key's GPU offset into
    /// `MaterialMeshMeta.material_offset` so the shader sees the same
    /// material the renderable pool routed the mesh through. Safety
    /// constraint (validated by `AwsmRenderer::set_mesh_cheap_material`):
    /// the cheap variant must share the authored material's shader_id
    /// AND transparency-pass classification, so the per-frame swap
    /// is a single 4-byte patch instead of a full pass-pool / pipeline
    /// migration.
    pub fn effective_material_key(
        &self,
        mesh_key: MeshKey,
        coverage: &crate::coverage::MeshCoverage,
        default_threshold: u32,
    ) -> MaterialKey {
        if let Some(cheap) = self.cheap_material_key {
            let threshold = self
                .cheap_material_pixel_threshold
                .unwrap_or(default_threshold);
            if coverage.is_below_threshold(mesh_key, threshold) {
                return cheap;
            }
        }
        self.material_key
    }

    /// Returns the geometry render pipeline key for this mesh.
    pub fn geometry_render_pipeline_key(&self, ctx: &RenderContext) -> Result<RenderPipelineKey> {
        ctx.render_passes
            .geometry
            .pipelines
            .get_render_pipeline_key(GeometryRenderPipelineKeyOpts {
                anti_aliasing: ctx.anti_aliasing,
                instancing: self.instanced,
                // Only non-instanced meshes branch on the meta-binding
                // shape; the instanced path always uses
                // uniform-with-dynamic-offset (see `pipeline.rs`).
                meta_storage_array: !self.instanced
                    && ctx.features.indirect_first_instance_enabled(),
                cull_mode: if self.double_sided {
                    awsm_renderer_core::pipeline::primitive::CullMode::None
                } else {
                    awsm_renderer_core::pipeline::primitive::CullMode::Back
                },
            })
    }

    /// Pushes geometry pass draw commands for this mesh.
    ///
    /// Two non-instanced variants exist, picked by
    /// `features.indirect_first_instance_enabled()`:
    /// - **storage-array meta** (feature on): single shared
    ///   `@group(2)` storage binding across every non-instanced draw;
    ///   the slot identity lives in `IndirectDrawArgs.first_instance`
    ///   (compaction) or in CPU `firstInstance` (legacy path), with
    ///   the vertex shader's `geometry_mesh_metas[instance_index]`
    ///   resolving to the right slot. Cheapest at the per-draw site
    ///   (no `setBindGroup` call).
    /// - **uniform-with-dynamic-offset meta** (feature off, portable):
    ///   the same shape the instanced path uses. CPU calls
    ///   `setBindGroup(2, group, &[meta_offset])` per draw; the args
    ///   buffer's `first_instance` stays at 0 (required —
    ///   `indirect-first-instance` is unavailable). One extra binding
    ///   set per draw vs. the storage-array path, but no other cost.
    ///
    /// Instanced meshes always use uniform-with-dynamic-offset (their
    /// `instance_index` range across the actual instances would
    /// collide with neighbouring meshes' meta slots in a shared
    /// storage array).
    pub fn push_geometry_pass_commands(
        &self,
        ctx: &RenderContext,
        mesh_key: MeshKey,
        render_pass: &RenderPassEncoder,
        bind_groups: &GeometryBindGroups,
        masked: bool,
    ) -> Result<()> {
        let meta_offset = ctx.meshes.meta.geometry_buffer_offset(mesh_key)? as u32;
        // Mesh slot index = byte offset / aligned slot size. The
        // geometry meta uses `GEOMETRY_MESH_META_BYTE_ALIGNMENT`
        // (256 B) per slot.
        let mesh_meta_idx = meta_offset
            / crate::meshes::meta::geometry_meta::GEOMETRY_MESH_META_BYTE_ALIGNMENT as u32;

        // Bind-group selection mirrors the pipeline-variant selection
        // in `geometry_render_pipeline_key`. The masked (alpha-tested)
        // variant always takes the portable non-instanced uniform-meta
        // CPU-recorded path (its pipeline is compiled only for that shape),
        // so force the uniform-meta binding + the plain indexed draw below.
        let use_storage_meta =
            !masked && !self.instanced && ctx.features.indirect_first_instance_enabled();
        if use_storage_meta {
            render_pass.set_bind_group(2, bind_groups.meta.get_storage_bind_group()?, None)?;
        } else {
            render_pass.set_bind_group(
                2,
                bind_groups.meta.get_uniform_bind_group()?,
                Some(&[meta_offset]),
            )?;
        }

        render_pass.set_vertex_buffer(
            0,
            ctx.meshes.visibility_geometry_data_gpu_buffer(),
            Some(
                ctx.meshes
                    .visibility_geometry_data_buffer_offset(mesh_key)? as u64,
            ),
            None,
        );

        if self.instanced {
            let offset = ctx.instances.transform_buffer_offset(self.transform_key)?;
            render_pass.set_vertex_buffer(
                1,
                ctx.instances.gpu_transform_buffer(),
                Some(offset as u64),
                None,
            );
        }

        // Cluster-LOD per-cluster cut (Phase B, B.3): if this is the cluster
        // render mesh M, draw the GPU-compacted cut stream instead of M's own
        // full index buffer — `set_index_buffer(compacted_indices)` +
        // `drawIndexedIndirect(draw_args)`. M's exploded vertex buffer + the
        // storage-meta bind group (group 2) are already bound above, and
        // `draw_args.first_instance == M.mesh_meta_idx` routes the material.
        // Requires the storage-meta path; gated on `mesh_key == M` ⇒ no effect on
        // any other mesh, and inert while M is hidden.
        #[cfg(feature = "lod")]
        if use_storage_meta {
            if let Some(state) = ctx
                .render_passes
                .cluster_lod
                .as_ref()
                .and_then(|cp| cp.state(mesh_key))
            {
                render_pass.set_index_buffer(
                    &state.buffers.compacted_indices_buffer,
                    IndexFormat::Uint32,
                    None,
                    None,
                );
                render_pass.draw_indexed_indirect_with_f64(&state.buffers.draw_args_buffer, 0.0);
                return Ok(());
            }
        }

        let buffer_info = ctx.meshes.buffer_info(mesh_key)?;

        render_pass.set_index_buffer(
            ctx.meshes.visibility_geometry_index_gpu_buffer(),
            IndexFormat::Uint32,
            Some(
                ctx.meshes
                    .visibility_geometry_index_buffer_offset(mesh_key)? as u64,
            ),
            None,
        );

        let index_count = buffer_info.triangles.vertex_attribute_indices.count as u32;

        if self.instanced {
            let instance_count = ctx
                .instances
                .transform_instance_count(self.transform_key)
                .ok_or(AwsmMeshError::InstancingMissingTransforms(mesh_key))?;
            render_pass.draw_indexed_with_instance_count(index_count, instance_count as u32);
        } else if !masked
            && ctx.frame_optimizations.get().indirect_geometry
            && self.world_aabb.is_some()
            && !self.hud
        {
            // HUD meshes (gizmo, point handles, overlay primitives)
            // ALWAYS take the CPU-recorded path. The compaction shader
            // that populates `IndirectDrawArgs[mesh_meta_idx]` only sees
            // `renderables.opaque` in `render.rs::opaque_snapshots` —
            // HUD meshes are deliberately excluded so they don't
            // participate in BVH-driven occlusion culling. That
            // exclusion is correct for occlusion (HUD is always shown)
            // but means the HUD slot in `args_buffer` stays zero, so
            // the indirect draw below would dispatch `instance_count = 0`
            // and write nothing to `visibility_data` — breaking GPU
            // picking on HUD geometry (the gizmo handles couldn't be
            // grabbed). Forcing HUD through the portable
            // `set_first_instance` / dynamic-offset path bypasses the
            // empty args slot and keeps the per-HUD-mesh
            // `material_mesh_meta_offset` in visibility_data so the
            // picker compute can resolve the right mesh key.
            // drawIndirect path. The compaction shader
            // populated `IndirectDrawArgs[mesh_meta_idx]` *last frame*
            // — static fields (`index_count`, `first_instance`) and
            // `instance_count` are all GPU-written; this is the one-
            // frame-latent visibility set.
            //
            // Gates:
            // - `frame_optimizations.indirect_geometry` — the per-frame
            //   policy decision rolls up `gpu_occlusion && args_ready`.
            //   `args_ready` is false on frame 0, after any
            //   `ensure_capacity` resize (which zeroes the args
            //   buffer), or after `gpu_occlusion` flipped off (the
            //   policy poisons args_ready on disengage). The
            //   `gpu_occlusion` side rolls up the `Off / Auto /
            //   Force` runtime knob — see
            //   `crate::optimization_policy`.
            // - `self.world_aabb.is_some()` — `collect_renderables`
            //   conservatively keeps no-AABB opaque meshes visible,
            //   but `opaque_snapshots` in render.rs filters them out
            //   (no AABB → can't be cull-tested), so the compaction
            //   shader never writes their args slot. Without this
            //   gate, drawIndirect would consume zeroed args and
            //   render nothing for the no-AABB case.
            let args_buffer = ctx
                .compaction_buffers
                .expect("compaction buffers missing despite gpu_culling feature on")
                .args_buffer
                .clone();
            let args_offset = (mesh_meta_idx as u64)
                * crate::render_passes::occlusion::compaction::INDIRECT_DRAW_ARGS_STRIDE as u64;
            render_pass.draw_indexed_indirect_with_f64(&args_buffer, args_offset as f64);
        } else if use_storage_meta {
            // CPU-recorded path with storage-array meta. `first_instance`
            // carries the slot index so the vertex shader's
            // `geometry_mesh_metas[instance_index]` resolves to this
            // mesh's meta.
            render_pass
                .draw_indexed_with_instance_count_and_first_index_and_base_vertex_and_first_instance(
                    index_count,
                    1,
                    0,
                    0,
                    mesh_meta_idx,
                );
        } else {
            // CPU-recorded path with uniform-with-dynamic-offset meta.
            // The bind-group dynamic offset above already pointed the
            // uniform at this mesh's meta slot; `first_instance` stays
            // at 0 (portable shape, no `indirect-first-instance`
            // feature requirement).
            render_pass.draw_indexed_with_instance_count(index_count, 1);
        }

        Ok(())
    }

    /// Pushes the **custom-vertex** geometry draw for this mesh. Same shape as
    /// the masked draw path (portable non-instanced uniform-with-dynamic-offset
    /// meta + plain indexed draw — the custom-vertex pipeline is compiled only
    /// for that shape today), plus it binds the shared zero uv0 buffer at the
    /// uv0 slot (slot 1) so the pipeline's `@location(10) uv0` attribute is
    /// satisfied.
    ///
    /// The vertex shader's `custom_displace_vertex` hook reads `uv0` (constant
    /// `vec2(0.0)` from the zero buffer) + position/normal/material data; the
    /// fragment is the plain visibility-writer. Restricted to non-instanced
    /// meshes — the caller (`collect_renderables`) only sets the custom-vertex
    /// key for `!instanced` meshes, so we don't bind the instancing buffer here.
    pub fn push_geometry_custom_vertex_pass_commands(
        &self,
        ctx: &RenderContext,
        mesh_key: MeshKey,
        render_pass: &RenderPassEncoder,
        bind_groups: &GeometryBindGroups,
        uv0_zero_buffer: &web_sys::GpuBuffer,
    ) -> Result<()> {
        let meta_offset = ctx.meshes.meta.geometry_buffer_offset(mesh_key)? as u32;

        // Uniform-with-dynamic-offset meta (the shape the custom-vertex pipeline
        // is compiled against), pointed at this mesh's slot.
        render_pass.set_bind_group(
            2,
            bind_groups.meta.get_uniform_bind_group()?,
            Some(&[meta_offset]),
        )?;

        // Slot 0: visibility geometry (locations 0-5).
        render_pass.set_vertex_buffer(
            0,
            ctx.meshes.visibility_geometry_data_gpu_buffer(),
            Some(
                ctx.meshes
                    .visibility_geometry_data_buffer_offset(mesh_key)? as u64,
            ),
            None,
        );

        // Slot 1: the shared zero uv0 buffer (location 10, `array_stride: 0` so
        // every vertex reads `vec2(0.0)`).
        render_pass.set_vertex_buffer(1, uv0_zero_buffer, None, None);

        let buffer_info = ctx.meshes.buffer_info(mesh_key)?;

        render_pass.set_index_buffer(
            ctx.meshes.visibility_geometry_index_gpu_buffer(),
            IndexFormat::Uint32,
            Some(
                ctx.meshes
                    .visibility_geometry_index_buffer_offset(mesh_key)? as u64,
            ),
            None,
        );

        let index_count = buffer_info.triangles.vertex_attribute_indices.count as u32;
        render_pass.draw_indexed_with_instance_count(index_count, 1);

        Ok(())
    }

    /// Pushes transparent material pass commands for this mesh.
    pub fn push_material_transparent_pass_commands(
        &self,
        ctx: &RenderContext,
        mesh_key: MeshKey,
        render_pass: &RenderPassEncoder,
        mesh_material_bind_group: &web_sys::GpuBindGroup,
    ) -> Result<()> {
        let geometry_meta_offset = ctx.meshes.meta.geometry_buffer_offset(mesh_key)? as u32;
        let material_meta_offset = ctx.meshes.meta.material_buffer_offset(mesh_key)? as u32;
        let buffer_info = ctx.meshes.buffer_info(mesh_key)?;

        render_pass.set_bind_group(
            3,
            mesh_material_bind_group,
            Some(&[geometry_meta_offset, material_meta_offset]),
        )?;

        // Geometry stuff Slot 0 (locations 0-4)
        render_pass.set_vertex_buffer(
            0,
            ctx.meshes.transparency_geometry_data_gpu_buffer(),
            Some(
                ctx.meshes
                    .transparency_geometry_data_buffer_offset(mesh_key)? as u64,
            ),
            None,
        );

        // Instancing Slot 1 (locations 5-8)
        let attribute_slot = if self.instanced {
            let offset = ctx.instances.transform_buffer_offset(self.transform_key)?;
            render_pass.set_vertex_buffer(
                1,
                ctx.instances.gpu_transform_buffer(),
                Some(offset as u64),
                None,
            );

            2
        } else {
            1
        };

        // Attributes
        // If instanced: slot 2 (locations 9+)
        // If not instanced: slot 1 (locations 5+)
        render_pass.set_vertex_buffer(
            attribute_slot,
            ctx.meshes.custom_attribute_data_gpu_buffer(),
            Some(ctx.meshes.custom_attribute_data_buffer_offset(mesh_key)? as u64),
            None,
        );

        render_pass.set_index_buffer(
            ctx.meshes.transparency_geometry_index_gpu_buffer(),
            IndexFormat::Uint32,
            Some(
                ctx.meshes
                    .transparency_geometry_index_buffer_offset(mesh_key)? as u64,
            ),
            None,
        );

        let index_count = buffer_info.triangles.vertex_attribute_indices.count as u32;

        if self.instanced {
            let instance_count = ctx
                .instances
                .transform_instance_count(self.transform_key)
                .ok_or(AwsmMeshError::InstancingMissingTransforms(mesh_key))?;
            render_pass.draw_indexed_with_instance_count(index_count, instance_count as u32);
        } else {
            render_pass.draw_indexed(index_count);
        }

        Ok(())
    }
}