anvilkit-render 0.1.0

Cross-platform rendering system built on wgpu and winit for AnvilKit game engine
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
//! # 渲染管线管理
//! 
//! 提供渲染管线的创建、配置和管理功能。

use wgpu::{
    RenderPipeline, RenderPipelineDescriptor, VertexState, FragmentState,
    PrimitiveState, MultisampleState, PipelineLayoutDescriptor,
    ShaderModule, ShaderModuleDescriptor, ShaderSource,
    ColorTargetState, BlendState, ColorWrites,
    PrimitiveTopology, FrontFace, PolygonMode,
    TextureFormat, Device,
};
use log::{info, debug};

use crate::renderer::RenderDevice;
use anvilkit_core::error::{AnvilKitError, Result};

/// 渲染管线构建器
/// 
/// 提供流式 API 来配置和创建渲染管线。
/// 
/// # 设计理念
/// 
/// - **流式配置**: 使用构建器模式简化管线配置
/// - **默认值**: 提供合理的默认配置参数
/// - **类型安全**: 编译时检查配置的正确性
/// - **灵活性**: 支持自定义着色器和状态配置
/// 
/// # 示例
/// 
/// ```rust,no_run
/// use anvilkit_render::renderer::{RenderDevice, RenderPipelineBuilder};
/// use wgpu::TextureFormat;
/// 
/// # async fn example(device: &RenderDevice) -> anvilkit_core::error::Result<()> {
/// let pipeline = RenderPipelineBuilder::new()
///     .with_vertex_shader("vertex_shader.wgsl")
///     .with_fragment_shader("fragment_shader.wgsl")
///     .with_format(TextureFormat::Bgra8UnormSrgb)
///     .build(device)?;
/// # Ok(())
/// # }
/// ```
pub struct RenderPipelineBuilder {
    /// 顶点着色器源码
    vertex_shader: Option<String>,
    /// 片段着色器源码
    fragment_shader: Option<String>,
    /// 渲染目标格式
    format: Option<TextureFormat>,
    /// 图元拓扑
    topology: PrimitiveTopology,
    /// 多重采样状态
    multisample_count: u32,
    /// 标签
    label: Option<String>,
    /// 顶点缓冲区布局
    vertex_layouts: Vec<wgpu::VertexBufferLayout<'static>>,
    /// 深度纹理格式(None = 不启用深度测试)
    depth_format: Option<TextureFormat>,
    /// Bind group 布局
    bind_group_layouts: Vec<wgpu::BindGroupLayout>,
}

impl Default for RenderPipelineBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl RenderPipelineBuilder {
    /// 创建新的渲染管线构建器
    /// 
    /// # 示例
    /// 
    /// ```rust
    /// use anvilkit_render::renderer::RenderPipelineBuilder;
    /// 
    /// let builder = RenderPipelineBuilder::new();
    /// ```
    pub fn new() -> Self {
        Self {
            vertex_shader: None,
            fragment_shader: None,
            format: None,
            topology: PrimitiveTopology::TriangleList,
            multisample_count: 1,
            label: None,
            vertex_layouts: Vec::new(),
            depth_format: None,
            bind_group_layouts: Vec::new(),
        }
    }
    
    /// 设置顶点着色器
    /// 
    /// # 参数
    /// 
    /// - `source`: 着色器源码
    /// 
    /// # 示例
    /// 
    /// ```rust
    /// use anvilkit_render::renderer::RenderPipelineBuilder;
    /// 
    /// let builder = RenderPipelineBuilder::new()
    ///     .with_vertex_shader("vertex_shader.wgsl");
    /// ```
    pub fn with_vertex_shader<S: Into<String>>(mut self, source: S) -> Self {
        self.vertex_shader = Some(source.into());
        self
    }
    
    /// 设置片段着色器
    /// 
    /// # 参数
    /// 
    /// - `source`: 着色器源码
    /// 
    /// # 示例
    /// 
    /// ```rust
    /// use anvilkit_render::renderer::RenderPipelineBuilder;
    /// 
    /// let builder = RenderPipelineBuilder::new()
    ///     .with_fragment_shader("fragment_shader.wgsl");
    /// ```
    pub fn with_fragment_shader<S: Into<String>>(mut self, source: S) -> Self {
        self.fragment_shader = Some(source.into());
        self
    }
    
    /// 设置渲染目标格式
    /// 
    /// # 参数
    /// 
    /// - `format`: 纹理格式
    /// 
    /// # 示例
    /// 
    /// ```rust
    /// use anvilkit_render::renderer::RenderPipelineBuilder;
    /// use wgpu::TextureFormat;
    /// 
    /// let builder = RenderPipelineBuilder::new()
    ///     .with_format(TextureFormat::Bgra8UnormSrgb);
    /// ```
    pub fn with_format(mut self, format: TextureFormat) -> Self {
        self.format = Some(format);
        self
    }
    
    /// 设置图元拓扑
    /// 
    /// # 参数
    /// 
    /// - `topology`: 图元拓扑类型
    /// 
    /// # 示例
    /// 
    /// ```rust
    /// use anvilkit_render::renderer::RenderPipelineBuilder;
    /// use wgpu::PrimitiveTopology;
    /// 
    /// let builder = RenderPipelineBuilder::new()
    ///     .with_topology(PrimitiveTopology::LineList);
    /// ```
    pub fn with_topology(mut self, topology: PrimitiveTopology) -> Self {
        self.topology = topology;
        self
    }
    
    /// 设置多重采样数量
    /// 
    /// # 参数
    /// 
    /// - `count`: 采样数量
    /// 
    /// # 示例
    /// 
    /// ```rust
    /// use anvilkit_render::renderer::RenderPipelineBuilder;
    /// 
    /// let builder = RenderPipelineBuilder::new()
    ///     .with_multisample_count(4);
    /// ```
    pub fn with_multisample_count(mut self, count: u32) -> Self {
        self.multisample_count = count;
        self
    }
    
    /// 设置标签
    /// 
    /// # 参数
    /// 
    /// - `label`: 管线标签
    /// 
    /// # 示例
    /// 
    /// ```rust
    /// use anvilkit_render::renderer::RenderPipelineBuilder;
    /// 
    /// let builder = RenderPipelineBuilder::new()
    ///     .with_label("My Render Pipeline");
    /// ```
    pub fn with_label<S: Into<String>>(mut self, label: S) -> Self {
        self.label = Some(label.into());
        self
    }

    /// 设置顶点缓冲区布局
    ///
    /// # 参数
    ///
    /// - `layouts`: 顶点缓冲区布局列表
    ///
    /// # 示例
    ///
    /// ```rust
    /// use anvilkit_render::renderer::{RenderPipelineBuilder, buffer::ColorVertex, Vertex};
    ///
    /// let builder = RenderPipelineBuilder::new()
    ///     .with_vertex_layouts(vec![ColorVertex::layout()]);
    /// ```
    pub fn with_vertex_layouts(mut self, layouts: Vec<wgpu::VertexBufferLayout<'static>>) -> Self {
        self.vertex_layouts = layouts;
        self
    }

    /// 设置深度纹理格式,启用深度测试
    ///
    /// # 参数
    ///
    /// - `format`: 深度纹理格式(如 `TextureFormat::Depth32Float`)
    pub fn with_depth_format(mut self, format: TextureFormat) -> Self {
        self.depth_format = Some(format);
        self
    }

    /// 设置 Bind Group 布局
    ///
    /// # 参数
    ///
    /// - `layouts`: Bind Group 布局列表(用于 Uniform Buffer、纹理等)
    pub fn with_bind_group_layouts(mut self, layouts: Vec<wgpu::BindGroupLayout>) -> Self {
        self.bind_group_layouts = layouts;
        self
    }

    /// 构建渲染管线
    /// 
    /// # 参数
    /// 
    /// - `device`: 渲染设备
    /// 
    /// # 返回
    /// 
    /// 成功时返回 BasicRenderPipeline,失败时返回错误
    /// 
    /// # 示例
    /// 
    /// ```rust,no_run
    /// use anvilkit_render::renderer::{RenderDevice, RenderPipelineBuilder};
    /// use wgpu::TextureFormat;
    /// 
    /// # async fn example(device: &RenderDevice) -> anvilkit_core::error::Result<()> {
    /// let pipeline = RenderPipelineBuilder::new()
    ///     .with_vertex_shader("vertex_shader.wgsl")
    ///     .with_fragment_shader("fragment_shader.wgsl")
    ///     .with_format(TextureFormat::Bgra8UnormSrgb)
    ///     .build(device)?;
    /// # Ok(())
    /// # }
    /// ```
    /// 构建深度-only 渲染管线(无片段着色器,用于 shadow pass)
    pub fn build_depth_only(self, device: &RenderDevice) -> Result<BasicRenderPipeline> {
        let vertex_shader = self.vertex_shader
            .ok_or_else(|| AnvilKitError::render("缺少顶点着色器".to_string()))?;

        let depth_format = self.depth_format
            .ok_or_else(|| AnvilKitError::render("深度-only 管线需要深度格式".to_string()))?;

        let bind_group_layout_refs: Vec<&wgpu::BindGroupLayout> =
            self.bind_group_layouts.iter().collect();

        let wgpu_device = device.device();

        let vs_module = BasicRenderPipeline::create_shader_module(
            wgpu_device, &vertex_shader, Some("Shadow VS"),
        )?;

        let layout = wgpu_device.create_pipeline_layout(&PipelineLayoutDescriptor {
            label: Some("Shadow Pipeline Layout"),
            bind_group_layouts: &bind_group_layout_refs,
            push_constant_ranges: &[],
        });

        let pipeline = wgpu_device.create_render_pipeline(&RenderPipelineDescriptor {
            label: self.label.as_deref(),
            layout: Some(&layout),
            vertex: VertexState {
                module: &vs_module,
                entry_point: "vs_main",
                buffers: &self.vertex_layouts,
            },
            primitive: PrimitiveState {
                topology: self.topology,
                strip_index_format: None,
                front_face: FrontFace::Ccw,
                cull_mode: None, // disabled for glTF compatibility
                unclipped_depth: false,
                polygon_mode: PolygonMode::Fill,
                conservative: false,
            },
            depth_stencil: Some(wgpu::DepthStencilState {
                format: depth_format,
                depth_write_enabled: true,
                depth_compare: wgpu::CompareFunction::Less,
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: MultisampleState {
                count: 1,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            fragment: None, // depth-only, no fragment stage
            multiview: None,
        });

        // Create a dummy fragment shader module for the struct (required field)
        let dummy_fs = BasicRenderPipeline::create_shader_module(
            wgpu_device,
            "// dummy\n@fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(0.0); }",
            Some("Dummy FS"),
        )?;

        Ok(BasicRenderPipeline {
            pipeline,
            vertex_shader: vs_module,
            fragment_shader: dummy_fs,
        })
    }

    /// 构建带颜色输出的完整渲染管线
    pub fn build(self, device: &RenderDevice) -> Result<BasicRenderPipeline> {
        let vertex_shader = self.vertex_shader
            .ok_or_else(|| AnvilKitError::render("缺少顶点着色器".to_string()))?;
        
        let fragment_shader = self.fragment_shader
            .ok_or_else(|| AnvilKitError::render("缺少片段着色器".to_string()))?;
        
        let format = self.format
            .ok_or_else(|| AnvilKitError::render("缺少渲染目标格式".to_string()))?;
        
        let bind_group_layout_refs: Vec<&wgpu::BindGroupLayout> =
            self.bind_group_layouts.iter().collect();

        BasicRenderPipeline::new(
            device,
            &vertex_shader,
            &fragment_shader,
            format,
            self.topology,
            self.multisample_count,
            self.label.as_deref(),
            &self.vertex_layouts,
            self.depth_format,
            &bind_group_layout_refs,
        )
    }
}

/// 基础渲染管线
/// 
/// 封装 wgpu 渲染管线,提供基础的渲染功能。
/// 
/// # 示例
/// 
/// ```rust,no_run
/// use anvilkit_render::renderer::{RenderDevice, BasicRenderPipeline};
/// use wgpu::{TextureFormat, PrimitiveTopology};
///
/// # async fn example(device: &RenderDevice) -> anvilkit_core::error::Result<()> {
/// let pipeline = BasicRenderPipeline::new(
///     device,
///     "vertex_shader.wgsl",
///     "fragment_shader.wgsl",
///     TextureFormat::Bgra8UnormSrgb,
///     PrimitiveTopology::TriangleList,
///     1,
///     Some("Basic Pipeline"),
///     &[],
///     None,
///     &[],
/// )?;
/// # Ok(())
/// # }
/// ```
pub struct BasicRenderPipeline {
    /// wgpu 渲染管线
    pipeline: RenderPipeline,
    /// 顶点着色器模块
    vertex_shader: ShaderModule,
    /// 片段着色器模块
    fragment_shader: ShaderModule,
}

impl BasicRenderPipeline {
    /// 创建新的基础渲染管线
    /// 
    /// # 参数
    /// 
    /// - `device`: 渲染设备
    /// - `vertex_source`: 顶点着色器源码
    /// - `fragment_source`: 片段着色器源码
    /// - `format`: 渲染目标格式
    /// - `topology`: 图元拓扑
    /// - `multisample_count`: 多重采样数量
    /// - `label`: 可选的标签
    /// 
    /// # 返回
    /// 
    /// 成功时返回 BasicRenderPipeline,失败时返回错误
    pub fn new(
        device: &RenderDevice,
        vertex_source: &str,
        fragment_source: &str,
        format: TextureFormat,
        topology: PrimitiveTopology,
        multisample_count: u32,
        label: Option<&str>,
        vertex_layouts: &[wgpu::VertexBufferLayout<'_>],
        depth_format: Option<TextureFormat>,
        bind_group_layouts: &[&wgpu::BindGroupLayout],
    ) -> Result<Self> {
        info!("创建基础渲染管线: {:?}", label);
        
        let wgpu_device = device.device();
        
        // 创建着色器模块
        let vertex_shader = Self::create_shader_module(
            wgpu_device,
            vertex_source,
            Some("Vertex Shader"),
        )?;
        
        let fragment_shader = Self::create_shader_module(
            wgpu_device,
            fragment_source,
            Some("Fragment Shader"),
        )?;
        
        // 创建管线布局
        let layout = wgpu_device.create_pipeline_layout(&PipelineLayoutDescriptor {
            label: Some("Basic Pipeline Layout"),
            bind_group_layouts,
            push_constant_ranges: &[],
        });
        
        // 创建渲染管线
        let pipeline = wgpu_device.create_render_pipeline(&RenderPipelineDescriptor {
            label,
            layout: Some(&layout),
            vertex: VertexState {
                module: &vertex_shader,
                entry_point: "vs_main",
                buffers: vertex_layouts,
            },
            primitive: PrimitiveState {
                topology,
                strip_index_format: None,
                front_face: FrontFace::Ccw,
                cull_mode: None, // disabled for glTF compatibility
                unclipped_depth: false,
                polygon_mode: PolygonMode::Fill,
                conservative: false,
            },
            depth_stencil: depth_format.map(|format| wgpu::DepthStencilState {
                format,
                depth_write_enabled: true,
                depth_compare: wgpu::CompareFunction::Less,
                stencil: wgpu::StencilState::default(),
                bias: wgpu::DepthBiasState::default(),
            }),
            multisample: MultisampleState {
                count: multisample_count,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            fragment: Some(FragmentState {
                module: &fragment_shader,
                entry_point: "fs_main",
                targets: &[Some(ColorTargetState {
                    format,
                    blend: Some(BlendState::REPLACE),
                    write_mask: ColorWrites::ALL,
                })],
            }),
            multiview: None,
        });
        
        info!("基础渲染管线创建成功");
        
        Ok(Self {
            pipeline,
            vertex_shader,
            fragment_shader,
        })
    }
    
    /// 创建着色器模块
    /// 
    /// # 参数
    /// 
    /// - `device`: GPU 设备
    /// - `source`: 着色器源码
    /// - `label`: 可选的标签
    /// 
    /// # 返回
    /// 
    /// 成功时返回 ShaderModule,失败时返回错误
    fn create_shader_module(
        device: &Device,
        source: &str,
        label: Option<&str>,
    ) -> Result<ShaderModule> {
        debug!("创建着色器模块: {:?}", label);
        
        let shader = device.create_shader_module(ShaderModuleDescriptor {
            label,
            source: ShaderSource::Wgsl(source.into()),
        });
        
        Ok(shader)
    }
    
    /// 获取渲染管线
    /// 
    /// # 返回
    /// 
    /// 返回 wgpu 渲染管线的引用
    /// 
    /// # 示例
    /// 
    /// ```rust,no_run
    /// # use anvilkit_render::renderer::BasicRenderPipeline;
    /// # async fn example(pipeline: &BasicRenderPipeline) {
    /// let wgpu_pipeline = pipeline.pipeline();
    /// // 使用管线进行渲染
    /// # }
    /// ```
    pub fn pipeline(&self) -> &RenderPipeline {
        &self.pipeline
    }

    /// 消费 BasicRenderPipeline 并返回内部的 wgpu RenderPipeline
    pub fn into_pipeline(self) -> RenderPipeline {
        self.pipeline
    }
    
    /// 获取顶点着色器
    /// 
    /// # 返回
    /// 
    /// 返回顶点着色器模块的引用
    /// 
    /// # 示例
    /// 
    /// ```rust,no_run
    /// # use anvilkit_render::renderer::BasicRenderPipeline;
    /// # async fn example(pipeline: &BasicRenderPipeline) {
    /// let vertex_shader = pipeline.vertex_shader();
    /// # }
    /// ```
    pub fn vertex_shader(&self) -> &ShaderModule {
        &self.vertex_shader
    }
    
    /// 获取片段着色器
    /// 
    /// # 返回
    /// 
    /// 返回片段着色器模块的引用
    /// 
    /// # 示例
    /// 
    /// ```rust,no_run
    /// # use anvilkit_render::renderer::BasicRenderPipeline;
    /// # async fn example(pipeline: &BasicRenderPipeline) {
    /// let fragment_shader = pipeline.fragment_shader();
    /// # }
    /// ```
    pub fn fragment_shader(&self) -> &ShaderModule {
        &self.fragment_shader
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use wgpu::{TextureFormat, PrimitiveTopology};
    
    #[test]
    fn test_pipeline_builder_creation() {
        let builder = RenderPipelineBuilder::new()
            .with_vertex_shader("vertex.wgsl")
            .with_fragment_shader("fragment.wgsl")
            .with_format(TextureFormat::Bgra8UnormSrgb)
            .with_topology(PrimitiveTopology::LineList)
            .with_multisample_count(4)
            .with_label("Test Pipeline");
        
        assert_eq!(builder.vertex_shader.as_ref().unwrap(), "vertex.wgsl");
        assert_eq!(builder.fragment_shader.as_ref().unwrap(), "fragment.wgsl");
        assert_eq!(builder.format.unwrap(), TextureFormat::Bgra8UnormSrgb);
        assert_eq!(builder.topology, PrimitiveTopology::LineList);
        assert_eq!(builder.multisample_count, 4);
        assert_eq!(builder.label.as_ref().unwrap(), "Test Pipeline");
    }
    
    #[test]
    fn test_pipeline_builder_defaults() {
        let builder = RenderPipelineBuilder::new();

        assert!(builder.vertex_shader.is_none());
        assert!(builder.fragment_shader.is_none());
        assert!(builder.format.is_none());
        assert_eq!(builder.topology, PrimitiveTopology::TriangleList);
        assert_eq!(builder.multisample_count, 1);
        assert!(builder.label.is_none());
    }

    #[test]
    fn test_pipeline_builder_with_label() {
        let builder = RenderPipelineBuilder::new()
            .with_label("Test Pipeline");
        assert_eq!(builder.label.as_deref(), Some("Test Pipeline"));
    }

    #[test]
    fn test_pipeline_builder_with_format() {
        let builder = RenderPipelineBuilder::new()
            .with_format(TextureFormat::Bgra8UnormSrgb);
        assert_eq!(builder.format, Some(TextureFormat::Bgra8UnormSrgb));
    }

    #[test]
    fn test_pipeline_builder_with_topology() {
        let builder = RenderPipelineBuilder::new()
            .with_topology(PrimitiveTopology::LineList);
        assert_eq!(builder.topology, PrimitiveTopology::LineList);
    }

    #[test]
    fn test_pipeline_builder_with_multisample() {
        let builder = RenderPipelineBuilder::new()
            .with_multisample_count(4);
        assert_eq!(builder.multisample_count, 4);
    }

    #[test]
    fn test_pipeline_builder_chaining() {
        let builder = RenderPipelineBuilder::new()
            .with_label("Chained")
            .with_format(TextureFormat::Rgba8Unorm)
            .with_topology(PrimitiveTopology::TriangleStrip)
            .with_multisample_count(2);

        assert_eq!(builder.label.as_deref(), Some("Chained"));
        assert_eq!(builder.format, Some(TextureFormat::Rgba8Unorm));
        assert_eq!(builder.topology, PrimitiveTopology::TriangleStrip);
        assert_eq!(builder.multisample_count, 2);
    }
}