wgpu_render_manager 0.2.13

Cached Render/Compute Manager for wgpu (pipelines + bind groups + procedural textures automated)
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
use std::borrow::Cow;
use crate::bind_groups::{LayoutKey, MaterialBindGroups};
use crate::compute_system::{BufferSet, ComputePipelineOptions, ComputeSystem};
use crate::fullscreen::{DebugVisualization, DepthDebugParams, FullscreenRenderer};
use crate::generator::{TextureGenerator, TextureKey};
use crate::pipelines::{PipelineCache, PipelineOptions};
use std::collections::HashMap;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::path::{Path, PathBuf};
use wgpu::{BindGroup, BindGroupLayout, Buffer, CommandEncoder, Device, Queue, RenderPass, TextureView};

#[derive(Clone, Hash, PartialEq, Eq)]
struct UniformBindGroupKey(u64);

impl UniformBindGroupKey {
    fn from_buffers(buffers: &[&Buffer]) -> Self {
        let mut hasher = DefaultHasher::default();
        for buffer in buffers {
            buffer.hash(&mut hasher);
        }

        Self(hasher.finish())
    }
}
struct TextureArrayData {
    texture: wgpu::Texture,
    view: TextureView,
    current_size: u32,
}
impl TextureArrayData {
    fn empty(device: &Device, array_size: u32) -> Self {
        const TEXTURE_RES: u32 = 512;
        let mip_count = wgpu::Extent3d {
            width: TEXTURE_RES,
            height: TEXTURE_RES,
            depth_or_array_layers: 1,
        }.max_mips(wgpu::TextureDimension::D2);

        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("Procedural Texture Array"),
            size: wgpu::Extent3d {
                width: TEXTURE_RES,
                height: TEXTURE_RES,
                depth_or_array_layers: array_size,
            },
            mip_level_count: mip_count,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format: wgpu::TextureFormat::Rgba8Unorm,
            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC,
            view_formats: &[],
        });

        let view = texture.create_view(&wgpu::TextureViewDescriptor {
            label: Some("Procedural Texture Array View"),
            dimension: Some(wgpu::TextureViewDimension::D2Array),
            ..Default::default()
        });

        TextureArrayData {
            texture,
            view,
            current_size: 0,
        }
    }
}
/// High-level render manager combining texture generation, pipeline caching,
/// material bind groups, and fullscreen debug rendering.
///
/// `RenderManager` is designed to remove most of the boilerplate involved in
/// setting up render pipelines and bind groups when working with `wgpu`,
/// while still keeping behavior explicit and predictable.
///
/// ## Responsibilities
/// - Procedural texture generation via compute shaders
/// - Render pipeline creation and caching
/// - Automatic material bind group creation
/// - Optional uniform bind group management
/// - Fullscreen debug visualization of textures
///
/// ## What this does *not* do
/// - It does not manage render passes or frame submission
/// - It does not hide `wgpu` concepts like bind groups or pipelines
/// - It does not perform draw calls for you (except fullscreen debug)
///
/// ## Design goals
/// - Minimal boilerplate for common rendering paths
/// - Explicit control over layouts and bindings
/// - Safe reuse of pipelines and bind groups
///
/// Most users will interact with this type as their primary entry point
/// into the crate.
pub struct RenderManager {
    device: Device,
    queue: Queue,
    generator: TextureGenerator,
    pipeline_cache: PipelineCache,
    fullscreen: FullscreenRenderer,
    materials: MaterialBindGroups,
    compute_system: ComputeSystem,
    uniform_bind_groups: HashMap<UniformBindGroupKey, BindGroup>,
    defines: HashMap<String, bool>,
    texture_array: TextureArrayData,
    texture_array_map: HashMap<TextureKey, u32>,
}

impl RenderManager {
    /// Create a new `RenderManager`.
    ///
    /// Procedural texture compute shaders will be loaded from
    /// `texture_shader_dir`. The directory is watched logically, meaning
    /// shaders can later be reloaded without recreating the manager.
    ///
    /// The provided `device` and `queue` are cloned internally and reused
    /// by all sub-systems.
    /// Cloning `device` and `queue` is very cheap, as they are just handles in wgpu.
    pub fn new(device: &Device, queue: &Queue, texture_shader_dir: PathBuf) -> Self {
        let generator = TextureGenerator::new(device.clone(), queue.clone(), texture_shader_dir);
        let pipeline_cache = PipelineCache::new(device.clone());
        let fullscreen = FullscreenRenderer::new(device.clone(), queue.clone());
        let materials = MaterialBindGroups::new(device.clone());
        let compute_system = ComputeSystem::new(device, queue);
        Self {
            device: device.clone(),
            queue: queue.clone(),
            generator,
            pipeline_cache,
            fullscreen,
            materials,
            compute_system,
            uniform_bind_groups: HashMap::new(),
            defines: HashMap::new(),
            texture_array: TextureArrayData::empty(device, 32),
            texture_array_map: HashMap::new(),
        }
    }

    /// Returns a reference to the underlying `wgpu::Device`.
    pub fn device(&self) -> &Device {
        &self.device
    }

    /// Returns a reference to the underlying `wgpu::Queue`.
    pub fn queue(&self) -> &Queue {
        &self.queue
    }

    /// Access the procedural texture generator.
    ///
    /// This allows manual creation, inspection, or reuse of generated
    /// texture views outside the high-level render APIs.
    pub fn generator(&mut self) -> &mut TextureGenerator {
        &mut self.generator
    }

    /// Access the internal render pipeline cache.
    ///
    /// Useful for advanced use cases such as manual pipeline preloading
    /// or shader hot-reloading.
    pub fn pipeline_cache(&mut self) -> &mut PipelineCache {
        &mut self.pipeline_cache
    }

    /// Access the fullscreen debug renderer.
    ///
    /// This renderer is used internally by
    /// [`render_fullscreen_debug`](Self::render_fullscreen_debug),
    /// but can also be used directly for custom debug workflows.
    pub fn fullscreen(&mut self) -> &mut FullscreenRenderer {
        &mut self.fullscreen
    }

    /// Access the compute system.
    ///
    /// This renderer is used internally.
    pub fn compute_system(&mut self) -> &mut ComputeSystem {
        &mut self.compute_system
    }

    /// Render using procedurally generated textures.
    ///
    /// This method resolves textures using the internal
    /// [`TextureGenerator`] and sets up the render pipeline
    /// and bind groups automatically.
    ///
    /// Only pipeline and bind groups are set.
    /// You must call `pass.draw()` yourself.
    ///
    /// Uses [`render_with_textures()`](Self::render_with_textures) underneath.
    /// ## Texture loading
    /// Each [`TextureKey`] resolves to a compute shader where:
    /// - `shader_id` is lowercased
    /// - `.wgsl` is appended
    ///
    /// ## Parameters
    /// - `texture_keys`: Keys describing which textures to generate or reuse
    /// - `shader_path`: Path to the render shader
    /// - `options`: Pipeline configuration options
    /// - `uniforms`: Uniform buffers bound after material bindings
    /// - `pass`: Active render pass
    ///
    /// ## Shader Binding layout
    /// - `@group(0) @binding(0)`: trilinear sampler
    /// - `@group(0) @binding(1)`: textures as texture_2d_array, used with [`ensure_textures()`](Self::ensure_textures)
    /// - `@group(0) @binding(2..n)`: textures as texture_2d<f32> or texture_multisampled_2d<f32> (Rgba8Unorm)
    /// - `@group(0) @binding(n+1)`: (optional) shadow_sampler
    /// - `@group(0) @binding(n+2)`: (optional) shadow textures as texture_depth_2d_array
    /// - `@group(1) @binding(0..n)`: uniforms, in the same order as input
    ///
    /// WGSL shaders are compiled via [`compile_wgsl()`](crate::shader_preprocessing::compile_wgsl), which adds a small
    /// compile-time preprocessing layer (`#ifdef`, `#include`) on top of
    /// standard WGSL before passing it to wgpu.
    /// ## Example
    /// ```no_run
    /// // Inside a render pass
    /// render_manager.render_with_textures(
    ///     &texture_keys.as_slice(),  // Texture Keys
    ///     shader_path.as_path(),     // Shader Path
    ///     options,                   // Pipeline Options
    ///     &[&uniforms_buffer],       // Buffers
    ///     &mut render_pass,          // Render Pass
    /// );
    /// ```
    pub fn render(
        &mut self,
        texture_keys: &[TextureKey],
        shader_path: &Path,
        options: &PipelineOptions,
        uniforms: &[&Buffer],
        pass: &mut RenderPass,
    ) {
        // Cloning TextureView is cheap — it's just a handle to the underlying GPU object.
        let mut owned_views: Vec<TextureView> = Vec::with_capacity(texture_keys.len());
        for key in texture_keys {
            let v_ref = self.generator.get_or_create(key);
            owned_views.push(v_ref.clone());
        }

        let view_refs: Vec<&TextureView> = owned_views.iter().collect();

        self.render_with_textures(&view_refs, shader_path, options, uniforms, pass);
    }

    /// Render using pre-existing texture views.
    ///
    /// Use this when textures originate from sources other than the
    /// procedural texture generator, such as render targets or external
    /// textures.
    ///
    /// This method automatically:
    /// - Creates or reuses a material bind group
    /// - Sets up optional shadow bindings
    /// - Handles uniform bind groups if provided
    ///
    /// Like [`render`](Self::render), this does not issue a draw call.
    ///
    /// ## Shader Binding layout
    /// - `@group(0) @binding(0)`: trilinear sampler
    /// - `@group(0) @binding(1)`: textures as texture_2d_array, used with [`ensure_textures()`](Self::ensure_textures)
    /// - `@group(0) @binding(2..n)`: textures as texture_2d<f32> or texture_multisampled_2d<f32>
    /// - `@group(0) @binding(n+1)`: (optional) shadow_sampler
    /// - `@group(0) @binding(n+2)`: (optional) shadow textures as texture_depth_2d_array
    /// - `@group(1) @binding(0..n)`: uniforms, in the same order as input
    ///
    /// WGSL shaders are compiled via [`compile_wgsl()`](crate::shader_preprocessing::compile_wgsl), which adds a small
    /// compile-time preprocessing layer (`#ifdef`, `#include`) on top of
    /// standard WGSL before passing it to wgpu.
    /// ## Example
    /// ```no_run
    /// // Inside a render pass
    /// render_manager.render_with_textures(
    ///     &texture_views.as_slice(), // Texture Views
    ///     shader_path.as_path(),     // Shader Path
    ///     options,                   // Pipeline Options
    ///     &[&uniforms_buffer],       // Buffers
    ///     &mut render_pass,          // Render Pass
    /// );
    /// ```
    pub fn render_with_textures(
        &mut self,
        texture_views: &[&TextureView],
        shader_path: &Path,
        options: &PipelineOptions,
        uniforms: &[&Buffer],
        pass: &mut RenderPass,
    ) {
        // Shadow pulled explicitly from pipeline options
        let shadow = options.shadow.as_ref().map(|s| (&s.sampler, &s.view));
        let has_shadow = shadow.is_some();

        // Ensure material layout exists and clone handle
        let _ = self.materials.layout(texture_views, has_shadow);
        let material_layout_handle = self
            .materials
            .layouts
            .get(&LayoutKey::from_views(texture_views, has_shadow))
            .expect("material layout must exist")
            .clone();

        // Uniform layout
        let uniform_count = uniforms.len();
        let mut owned_bgls: Vec<BindGroupLayout> =
            Vec::with_capacity(if uniform_count > 0 { 2 } else { 1 });

        owned_bgls.push(material_layout_handle);

        if uniform_count > 0 {
            let _ = self.pipeline_cache.uniform_layout(uniform_count);
            let uniform_layout_handle = self
                .pipeline_cache
                .uniform_layouts
                .get(&uniform_count)
                .expect("uniform layout must exist")
                .clone();
            owned_bgls.push(uniform_layout_handle);
        }

        // Local references only
        let bind_group_layout_refs: Vec<Option<&BindGroupLayout>> = owned_bgls.iter().map(|bgl| Some(bgl)).collect::<Vec<_>>();

        // Pipeline
        let pipeline_ref = self
            .pipeline_cache
            .get_or_create(shader_path, &bind_group_layout_refs, options, &self.defines);
        let pipeline = pipeline_ref.clone();
        pass.set_pipeline(&pipeline);

        // Material bind group
        let material_bg = self.materials.get_or_create(texture_views, shadow, &options.sampler, &self.texture_array.view);
        pass.set_bind_group(0, material_bg, &[]);

        // Uniform bind group
        if uniform_count > 0 {
            let uniform_bg = self.get_or_create_uniform_bind_group(uniforms);
            pass.set_bind_group(1, uniform_bg, &[]);
        }
    }


    /// Render using fully custom bind group layouts and bind groups.
    ///
    /// This is an advanced API intended for cases where automatic
    /// material or uniform handling is insufficient.
    ///
    /// No assumptions are made about binding order or layout structure.
    /// Bind groups are bound sequentially starting at index 0.
    ///
    /// WGSL shaders are compiled via [`compile_wgsl()`](crate::shader_preprocessing::compile_wgsl), which adds a small
    /// compile-time preprocessing layer (`#ifdef`, `#include`) on top of
    /// standard WGSL before passing it to wgpu.
    pub fn render_with_layouts(
        &mut self,
        shader_path: &Path,
        bind_group_layouts: &[&BindGroupLayout],
        bind_groups: &[&BindGroup],
        options: &PipelineOptions,
        pass: &mut RenderPass,
    ) {
        let pipeline = self.pipeline_cache.get_or_create(shader_path, bind_group_layouts.iter().map(|bgl| Some(*bgl)).collect::<Vec<_>>().as_slice(), options, &self.defines);
        pass.set_pipeline(pipeline);

        for (i, bg) in bind_groups.iter().enumerate() {
            pass.set_bind_group(i as u32, *bg, &[]);
        }
    }

    /// Render using pre-existing texture views and manual bind groups.
    ///
    /// Use this when textures originate from sources other than the
    /// procedural texture generator, such as render targets or external
    /// textures.
    ///
    /// Render using custom bind group layouts and bind groups.
    ///
    /// This method automatically:
    /// - Creates or reuses a material bind group
    /// - Sets up optional shadow bindings
    /// - Handles uniform bind groups if provided
    ///
    /// Like [`render`](Self::render), this does not issue a draw call.
    ///
    /// ## Shader Binding layout
    /// - `@group(0) @binding(0)`: trilinear sampler
    /// - `@group(0) @binding(1)`: textures as texture_2d_array, used with [`ensure_textures()`](Self::ensure_textures)
    /// - `@group(0) @binding(2..n)`: textures as texture_2d<f32> or texture_multisampled_2d<f32> (Rgba8Unorm)
    /// - `@group(0) @binding(n+1)`: (optional) shadow_sampler
    /// - `@group(0) @binding(n+2)`: (optional) shadow textures as texture_depth_2d_array
    /// - `@group(1) @binding(0..n)`: uniforms, in the same order as input
    /// - `@group(2..n) @binding(0..n)`: Manual Bind groups
    ///
    /// WGSL shaders are compiled via [`compile_wgsl()`](crate::shader_preprocessing::compile_wgsl), which adds a small
    /// compile-time preprocessing layer (`#ifdef`, `#include`) on top of
    /// standard WGSL before passing it to wgpu.
    ///
    /// ## Example
    /// ```no_run
    /// // Inside a render pass
    /// render_manager.render_with_layouts_and_textures(
    ///     &texture_views.as_slice(), // Texture Views
    ///     shader_path.as_path(),     // Shader Path
    ///     bind_group_layouts,        // BGLs
    ///     bind_groups,               // BGs
    ///     options,                   // Pipeline Options
    ///     &[&uniforms_buffer],       // Buffers
    ///     &mut render_pass,          // Render Pass
    /// );
    /// ```
    pub fn render_with_layouts_and_textures(
        &mut self,
        texture_views: &[&TextureView],
        shader_path: &Path,
        bind_group_layouts: &[&BindGroupLayout],
        bind_groups: &[&BindGroup],
        options: &PipelineOptions,
        uniforms: &[&Buffer],
        pass: &mut RenderPass,
    ) {
        // Shadow pulled explicitly from pipeline options
        let shadow = options.shadow.as_ref().map(|s| (&s.sampler, &s.view));
        let has_shadow = shadow.is_some();

        // Ensure material layout exists and clone handle
        let _ = self.materials.layout(texture_views, has_shadow);
        let material_layout_handle = self
            .materials
            .layouts
            .get(&LayoutKey::from_views(texture_views, has_shadow))
            .expect("material layout must exist")
            .clone();

        // Uniform layout
        let uniform_count = uniforms.len();
        let mut owned_bgls: Vec<BindGroupLayout> =
            Vec::with_capacity(if uniform_count > 0 { 2 } else { 1 } + bind_group_layouts.len());

        owned_bgls.push(material_layout_handle);

        if uniform_count > 0 {
            let _ = self.pipeline_cache.uniform_layout(uniform_count);
            let uniform_layout_handle = self
                .pipeline_cache
                .uniform_layouts
                .get(&uniform_count)
                .expect("uniform layout must exist")
                .clone();
            owned_bgls.push(uniform_layout_handle);
        }

        // Combine auto-managed layouts with manual layouts
        let mut all_layout_refs: Vec<Option<&BindGroupLayout>> =
            owned_bgls.iter().map(|bgl| Some(bgl)).collect();
        for bgl in bind_group_layouts.iter() {
            all_layout_refs.push(Some(*bgl));
        }

        // Pipeline
        let pipeline = self
            .pipeline_cache
            .get_or_create(shader_path, &all_layout_refs, options, &self.defines)
            .clone();
        pass.set_pipeline(&pipeline);

        // Material bind group at group 0
        let material_bg = self.materials.get_or_create(texture_views, shadow, &options.sampler, &self.texture_array.view);
        pass.set_bind_group(0, material_bg, &[]);

        // Uniform bind group at group 1
        if uniform_count > 0 {
            let uniform_bg = self.get_or_create_uniform_bind_group(uniforms);
            pass.set_bind_group(1, uniform_bg, &[]);
        }

        // Manual bind groups starting at group 2
        for (i, bg) in bind_groups.iter().enumerate() {
            pass.set_bind_group(i as u32 + 2, *bg, &[]);
        }
    }
    /// Render using fully custom bind group layouts and bind groups with holes.
    ///
    /// Same as [`render_with_layouts()`](crate::renderer::RenderManager::render_with_layouts), but allows holes in the bind group layouts since wgpu 29.0.0 allows this.
    pub fn render_with_layouts_holed(
        &mut self,
        shader_path: &Path,
        bind_group_layouts: &[Option<&BindGroupLayout>],
        bind_groups: &[&BindGroup],
        options: &PipelineOptions,
        pass: &mut RenderPass,
    ) {
        let pipeline = self.pipeline_cache.get_or_create(shader_path, bind_group_layouts, options, &self.defines);
        pass.set_pipeline(pipeline);

        for (i, bg) in bind_groups.iter().enumerate() {
            pass.set_bind_group(i as u32, *bg, &[]);
        }
    }
    /// Render a fullscreen debug visualization of a texture.
    ///
    /// This is primarily intended for inspecting intermediate render
    /// targets, depth buffers, or compute outputs.
    ///
    /// ## Depth
    /// For depth texture visualizations, it is highly recommended to update the depth params using [`update_depth_params()`](Self::update_depth_params).
    ///
    pub fn render_fullscreen_debug(
        &mut self,
        texture: &TextureView,
        visualization_type: DebugVisualization,
        target_view: &TextureView,
        pass: &mut RenderPass,
    ) {
        self.fullscreen.render(texture, visualization_type, target_view, pass);
    }

    pub fn render_fullscreen_debug_texture(
        &mut self,
        texture_key: &TextureKey,
        visualization_type: DebugVisualization,
        target_view: &TextureView,
        pass: &mut RenderPass,
    ) {
        // Cloning TextureView is cheap — it's just a handle to the underlying GPU object.
        let texture_view = &self.generator.get_or_create(texture_key).clone();

        self.fullscreen.render(texture_view, visualization_type, target_view, pass);
    }

    /// Execute a compute shader, optionally using an existing command encoder.
    ///
    /// This method creates (or reuses) a cached compute pipeline, sets up bind groups,
    /// and dispatches workgroups.
    ///
    /// If `encoder` is `Some(&mut encoder)`, the compute pass is recorded into the provided
    /// encoder (no finish/submit is performed).
    ///
    /// If `encoder` is `None`, a new command encoder is created, used for the pass,
    /// finished, and immediately submitted to the queue.
    ///
    /// ### SYNCHRONIZATION WARNING
    /// Creating a new encoder (i.e. passing `None`) while other command encoders are still
    /// open is **extremely dangerous**. It can cause GPU timeline desynchronization,
    /// resource hazards, validation layer errors, crashes, or silent corruption if the
    /// operations touch overlapping resources without explicit barriers.
    ///
    /// **ALWAYS prefer passing an existing encoder** when you're doing multiple
    /// compute/render operations in the same frame. Only use `None` for isolated,
    /// one-off dispatches.
    ///
    /// In debug builds, a loud runtime warning will be printed if you create a new
    /// encoder while others are active.
    ///
    /// ## Bind group layout
    /// - `@group(0)`: input textures + sampler
    ///   - `binding 0..n`: input texture views
    ///   - `binding n`: shared sampler
    /// - `@group(1)`: output storage textures
    ///   - `binding 0..m`: output texture views
    /// - `@group(2)`: uniform/storage(read/read_write) buffers
    ///   - `binding 0..k`: uniform/storage(read/read_write) buffers
    ///
    /// Empty input/output/uniform/storage(read/read_write) lists create empty bind groups for those slots.
    ///
    /// ## Texture handling
    /// - MSAA input textures are auto-detected via `sample_count`
    /// - Depth textures use depth sampling where applicable
    ///
    /// ## Parameters
    /// - `encoder`: Optional existing encoder to record into
    /// - `label`: Debug label for the encoder (if created) and compute pass
    /// - `input_views`: Read-only input texture views
    /// - `output_views`: Write-only storage texture views
    /// - `shader_path`: Path to the WGSL compute shader
    /// - `options`: Compute pipeline and dispatch configuration
    /// - `buffer_sets`: Optional uniform/storage(read/read_write) buffers
    ///
    /// ## Notes
    /// - Shader entry point must be `main`
    /// - Dispatch size comes from `options.dispatch_size`
    ///
    /// ## WGSL expectations
    /// - Entry point: `@compute @workgroup_size(...) fn main()`
    /// - Input textures must match the order given
    /// - Output textures must be `texture_storage_2d<... , write>`
    /// - Uniforms/Storage(read_write) must match binding indices exactly
    ///
    /// WGSL shaders are compiled via [`compile_wgsl()`](crate::shader_preprocessing::compile_wgsl), which adds a small
    /// compile-time preprocessing layer (`#ifdef`, `#include`) on top of
    /// standard WGSL before passing it to wgpu.
    pub fn compute(
        &mut self,
        encoder: Option<&mut CommandEncoder>,
        label: &str,
        input_views: Vec<&TextureView>,
        output_views: Vec<&TextureView>,
        shader_path: &PathBuf,
        options: ComputePipelineOptions,
        buffer_sets: &[BufferSet],
    ) {
        self.compute_system.compute(encoder, label, input_views, output_views, shader_path, options, buffer_sets, &self.defines);
    }

    /// Enables or disables a compile-time shader define.
    ///
    /// This updates the internal set of shader `defines` used during WGSL
    /// compilation. Defines control `#ifdef` / `#ifndef` blocks in shaders
    /// and are evaluated **at shader compile time**, not at runtime.
    ///
    /// When a define is enabled:
    /// - Shaders compiled afterward may select different code paths
    /// - Binding layouts may change
    /// - A new pipeline variant may be created
    ///
    /// When a define is disabled:
    /// - The corresponding `#ifdef` blocks are excluded
    ///
    /// ### Important
    ///
    /// - Changing a define does **not** retroactively affect already-created
    ///   pipelines or shader modules.
    /// - Call this **before** compiling or requesting a pipeline that depends
    ///   on the define.
    /// - This is typically used for feature toggles such as MSAA, shadows,
    ///   fog variants, or debug paths.
    ///
    /// ### Example
    ///
    /// ```text
    /// update_define("MSAA".into(), true);
    /// update_define("SSAO".into(), false);
    /// ```
    /// ## Used for:
    /// WGSL shaders are compiled via [`compile_wgsl()`](crate::shader_preprocessing::compile_wgsl), which adds a small
    /// compile-time preprocessing layer (`#ifdef`, `#include`) on top of
    /// standard WGSL before passing it to wgpu.
    pub fn update_define(&mut self, define: String, enabled: bool) { self.defines.insert(define, enabled); }
    /// Update parameters used for depth texture visualization.
    ///
    /// These parameters affect subsequent calls to
    /// [`render_fullscreen_debug`](Self::render_fullscreen_debug).
    pub fn update_depth_params(&mut self, params: DepthDebugParams) {
        self.fullscreen.update_depth_params(params);
    }

    /// Clear cached material and uniform bind groups.
    ///
    /// Call this after window resize, swapchain recreation,
    /// or when underlying textures are replaced.
    pub fn invalidate_bind_groups(&mut self) {
        self.materials.clear();
        self.fullscreen.invalidate_bind_groups();
        self.uniform_bind_groups.clear();
    }

    /// Reload render shaders from disk.
    ///
    /// Existing pipelines using these shaders will be recreated
    /// on next use.
    ///
    /// Useful for shader hot-reloading
    pub fn reload_render_shaders(&mut self, paths: &[PathBuf]) {
        self.pipeline_cache.reload_shaders(paths, &self.defines);
    }

    /// Reload procedural texture shaders and clear the texture cache.
    pub fn reload_texture_shaders(&mut self) {
        self.generator.reload_shaders();
    }

    /// Clear all internal caches.
    ///
    /// This includes pipelines, generated textures, and bind groups.
    pub fn clear_all(&mut self) {
        self.pipeline_cache.clear();
        self.generator.clear_cache();
        self.invalidate_bind_groups();
    }

    fn get_or_create_uniform_bind_group(&mut self, uniforms: &[&Buffer]) -> &BindGroup {
        let key = UniformBindGroupKey::from_buffers(uniforms);

        if !self.uniform_bind_groups.contains_key(&key) {
            let bg = self.pipeline_cache.create_uniform_bind_group(uniforms, "uniform bind group");
            self.uniform_bind_groups.insert(key.clone(), bg);
        }

        self.uniform_bind_groups.get(&key).unwrap()
    }

    /// Ensure textures are loaded into the texture array and return their indices.
    ///
    /// This method populates the internal 512-layer texture_2d_array with procedurally
    /// generated textures. Each texture is copied into a layer, and its index is returned.
    /// Subsequent calls with the same key return the cached index.
    ///
    /// ## Texture array details
    /// - Format: Rgba8Unorm
    /// - Resolution: 512x512 per layer
    /// - Max layers: 512
    /// - Mipmaps: Yes (10 levels for 512x512)
    /// - Bound at: `@group(0) @binding(1)` in shaders
    ///
    /// ## Returns
    /// A `Vec<u32>` containing the layer index for each input `TextureKey`.
    /// These indices can be passed to vertex data for sampling in fragment shaders.
    ///
    /// ## Example
    /// ```no_run
    /// let keys = vec![
    ///     TextureKey::new("stone", params1),
    ///     TextureKey::new("wood", params2),
    /// ];
    /// let indices = render_manager.ensure_textures(&keys);
    /// // indices[0] is the layer for "stone"
    /// // indices[1] is the layer for "wood"
    /// ```
    pub fn ensure_textures(&mut self, keys: &[TextureKey]) -> Vec<u32> {
        let mut indices = Vec::with_capacity(keys.len());

        for key in keys {
            if let Some(&index) = self.texture_array_map.get(key) {
                indices.push(index);
            } else {
                let index = self.add_to_texture_array(key);
                indices.push(index);
            }
        }

        indices
    }

    fn add_to_texture_array(&mut self, key: &TextureKey) -> u32 {
        let current_size = self.texture_array.current_size;
        let index = current_size;
        let key = if key.resolution == 512 {
            Cow::Borrowed(key)
        } else {
            Cow::Owned({
                let mut k = key.clone();
                k.resolution = 512;
                k
            })
        };
        let source_texture = self.generator.get_or_create(&key).texture();

        // Resize if needed
        if current_size == self.texture_array.texture.depth_or_array_layers() {
            let old_array = self.texture_array.texture.clone();
            let old_layers = old_array.depth_or_array_layers();
            let mip_count = old_array.mip_level_count();

            let new_capacity = (current_size as f32 * 1.5) as u32 + 1;

            // Create new array
            let mut new_array = TextureArrayData::empty(&self.device, new_capacity);

            let mut encoder = self.device.create_command_encoder(
                &wgpu::CommandEncoderDescriptor {
                    label: Some("resize texture array"),
                },
            );

            // Copy ALL old layers into new texture
            for layer in 0..old_layers {
                for mip in 0..mip_count {
                    let mip_size = (512u32 >> mip).max(1);

                    encoder.copy_texture_to_texture(
                        wgpu::TexelCopyTextureInfo {
                            texture: &old_array,
                            mip_level: mip,
                            origin: wgpu::Origin3d {
                                x: 0,
                                y: 0,
                                z: layer,
                            },
                            aspect: wgpu::TextureAspect::All,
                        },
                        wgpu::TexelCopyTextureInfo {
                            texture: &new_array.texture,
                            mip_level: mip,
                            origin: wgpu::Origin3d {
                                x: 0,
                                y: 0,
                                z: layer,
                            },
                            aspect: wgpu::TextureAspect::All,
                        },
                        wgpu::Extent3d {
                            width: mip_size,
                            height: mip_size,
                            depth_or_array_layers: 1,
                        },
                    );
                }
            }

            self.queue.submit(std::iter::once(encoder.finish()));

            new_array.current_size = current_size;
            self.texture_array = new_array;
        }

        // Now insert the new texture
        let mut encoder = self.device.create_command_encoder(
            &wgpu::CommandEncoderDescriptor {
                label: Some("texture array copy"),
            },
        );

        let array_texture = &self.texture_array.texture;
        let mip_count = source_texture.mip_level_count();

        for mip in 0..mip_count {
            let mip_size = (512u32 >> mip).max(1);

            encoder.copy_texture_to_texture(
                wgpu::TexelCopyTextureInfo {
                    texture: source_texture,
                    mip_level: mip,
                    origin: wgpu::Origin3d::ZERO,
                    aspect: wgpu::TextureAspect::All,
                },
                wgpu::TexelCopyTextureInfo {
                    texture: array_texture,
                    mip_level: mip,
                    origin: wgpu::Origin3d {
                        x: 0,
                        y: 0,
                        z: index,
                    },
                    aspect: wgpu::TextureAspect::All,
                },
                wgpu::Extent3d {
                    width: mip_size,
                    height: mip_size,
                    depth_or_array_layers: 1,
                },
            );
        }

        self.queue.submit(std::iter::once(encoder.finish()));

        self.texture_array.current_size = index + 1;
        self.texture_array_map.insert(key.into_owned(), index);

        index
    }
}