wgpu-core 31.0.1

Core implementation logic of wgpu, the cross-platform, safe, pure-rust graphics API
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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
use alloc::string::ToString as _;
use alloc::{
    borrow::{Cow, ToOwned},
    boxed::Box,
    string::String,
    sync::Arc,
    vec::Vec,
};
use core::{marker::PhantomData, mem::ManuallyDrop, num::NonZeroU32};

use arrayvec::ArrayVec;
use naga::error::ShaderError;
use thiserror::Error;
use wgt::error::{ErrorType, WebGpuError};

pub use crate::pipeline_cache::PipelineCacheValidationError;
use crate::ray_tracing_pipeline::RayTracingPipelineError;
use crate::{
    api_log,
    binding_model::{
        BindGroupLayout, CreateBindGroupLayoutError, CreatePipelineLayoutError,
        GetBindGroupLayoutError, PipelineLayout,
    },
    command::ColorAttachmentError,
    device::{
        AttachmentData, Device, DeviceError, MissingDownlevelFlags, MissingFeatures,
        RenderPassContext,
    },
    pipeline_cache,
    resource::{InvalidResourceError, Labeled, ResourceState, TrackingData},
    resource_log, validation, FastHashSet, Label, LabelHelpers as _,
};

/// Information about buffer bindings, which
/// is validated against the shader (and pipeline)
/// at draw time as opposed to initialization time.
#[derive(Debug, Default)]
pub(crate) struct LateSizedBufferGroup {
    /// Shader-required sizes of `BindGroupLayout::late_sized_bindings`, in the same order.
    pub(crate) shader_sizes: Vec<wgt::BufferAddress>,
}

#[allow(clippy::large_enum_variant)]
pub enum ShaderModuleSource<'a> {
    #[cfg(feature = "wgsl")]
    Wgsl(Cow<'a, str>),
    #[cfg(feature = "glsl")]
    Glsl(Cow<'a, str>, naga::front::glsl::Options),
    #[cfg(feature = "spirv")]
    SpirV(Cow<'a, [u32]>, naga::front::spv::Options),
    Naga(Cow<'static, naga::Module>),
    /// Dummy variant because `Naga` doesn't have a lifetime and without enough active features it
    /// could be the last one active.
    #[doc(hidden)]
    Dummy(PhantomData<&'a ()>),
}

#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ShaderModuleDescriptor<'a> {
    pub label: Label<'a>,
    #[cfg_attr(feature = "serde", serde(default))]
    pub runtime_checks: wgt::ShaderRuntimeChecks,
}

pub type ShaderModuleDescriptorPassthrough<'a> =
    wgt::CreateShaderModuleDescriptorPassthrough<'a, Label<'a>>;

#[derive(Debug)]
pub struct PassthroughInterface {
    pub entry_point_names: FastHashSet<String>,
}

// Most shaders will use a standard interface which is very large.
// Passthrough shaders have a much smaller interface. No reason to
// box the standard interface though.
#[expect(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum ShaderModuleState {
    /// A Naga module, from which we generate a `wgpu_hal` shader module
    /// for each pipeline stage that uses it.
    NagaModule {
        shader: hal::NagaShader,
        runtime_checks: wgt::ShaderRuntimeChecks,
    },
    Passthrough {
        raw: Box<dyn hal::DynShaderModule>,
        interface: PassthroughInterface,
    },
}

#[derive(Debug)]
pub struct ShaderModule {
    pub(crate) state: ResourceState<ShaderModuleState>,
    pub(crate) device: Arc<Device>,
    /// The `label` from the descriptor used to create the resource.
    pub(crate) label: String,
    pub(crate) compilation_info: wgt::CompilationInfo,
}

impl Drop for ShaderModule {
    #[allow(trivial_casts)]
    fn drop(&mut self) {
        profiling::scope!("ShaderModule::drop");
        api_log!("ShaderModule::drop {:?}", self as *const _);
        resource_log!("Destroy raw {}", self.error_ident());
        #[cfg(feature = "trace")]
        if let Some(t) = self.device.trace.lock().as_mut() {
            use crate::device::trace::{to_trace, Action};

            t.add(Action::DropShaderModule(unsafe { to_trace(self) }));
        }
        let ResourceState::Valid(state) =
            core::mem::replace(&mut self.state, ResourceState::Invalid)
        else {
            return;
        };
        match state {
            ShaderModuleState::NagaModule { .. } => {}
            ShaderModuleState::Passthrough { raw, .. } => unsafe {
                self.device.raw().destroy_shader_module(raw);
            },
        }
    }
}

crate::impl_resource_type!(ShaderModule);
crate::impl_labeled!(ShaderModule);
crate::impl_parent_device!(ShaderModule);
crate::impl_storage_item!(ShaderModule);

impl ShaderModule {
    pub(crate) fn state(&self) -> Result<&ShaderModuleState, InvalidResourceError> {
        let ResourceState::Valid(state) = &self.state else {
            return Err(InvalidResourceError(self.error_ident()));
        };
        Ok(state)
    }

    pub(crate) fn invalid(
        device: Arc<Device>,
        label: String,
        compilation_info: wgt::CompilationInfo,
    ) -> Arc<Self> {
        Arc::new(Self {
            state: ResourceState::Invalid,
            device,
            label,
            compilation_info,
        })
    }

    pub fn compilation_info(&self) -> &wgt::CompilationInfo {
        &self.compilation_info
    }

    /// Select an entry point name, given an optional name and a shader stage.
    ///
    /// This function resolves an `Option<&str>`
    /// [`ProgrammableStageDescriptor::entry_point`][ep] value to the name of an
    /// entry point in `self`.
    ///
    /// If `entry_point` is given, verify that `self` has an entry point by that
    /// name for `stage`, and then return the name as an owned `String`.
    ///
    /// If `entry_point` is `None`, verify that `self` has exactly one entry
    /// point for `stage`, and return its name.
    ///
    /// Passthrough modules do not record entry points' stages, so for those,
    /// `stage` is ignored.
    ///
    /// [ep]: crate::pipeline::ProgrammableStageDescriptor::entry_point
    pub(crate) fn finalize_entry_point_name(
        &self,
        stage: naga::ShaderStage,
        entry_point: Option<&str>,
    ) -> Result<String, validation::StageError> {
        let state = self.state()?;
        match state {
            ShaderModuleState::NagaModule { ref shader, .. } => {
                finalize_naga_entry_point_name(&shader.module, stage, entry_point)
            }
            ShaderModuleState::Passthrough { ref interface, .. } => {
                finalize_passthrough_entry_point_name(interface, entry_point)
            }
        }
    }
}

fn finalize_naga_entry_point_name(
    module: &naga::Module,
    stage: naga::ShaderStage,
    entry_point: Option<&str>,
) -> Result<String, validation::StageError> {
    let mut candidates = module.entry_points.iter().filter(|ep| ep.stage == stage);
    if let Some(name) = entry_point {
        return match candidates.find(|ep| ep.name == name) {
            Some(ep) => Ok(ep.name.clone()),
            None => Err(validation::StageError::NoEntryPointWithNameForStage {
                stage,
                name: name.to_owned(),
            }),
        };
    }

    let Some(first) = candidates.next() else {
        return Err(validation::StageError::NoEntryPointForStage(stage));
    };
    if candidates.next().is_some() {
        return Err(validation::StageError::AmbiguousEntryPointForStage(stage));
    }
    Ok(first.name.clone())
}

fn finalize_passthrough_entry_point_name(
    interface: &PassthroughInterface,
    entry_point: Option<&str>,
) -> Result<String, validation::StageError> {
    if let Some(ep) = entry_point {
        return if interface.entry_point_names.contains(ep) {
            Ok(ep.to_owned())
        } else {
            Err(validation::StageError::NoEntryPointWithName(ep.to_owned()))
        };
    }

    match interface.entry_point_names.len() {
        0 => Err(validation::StageError::NoEntryPoints),
        1 => Ok(interface
            .entry_point_names
            .iter()
            .next()
            .unwrap()
            .to_owned()),
        _ => Err(validation::StageError::AmbiguousEntryPoint),
    }
}

//Note: `Clone` would require `WithSpan: Clone`.
#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum CreateShaderModuleError {
    // These variants deliberately don't forward to `ShaderError`'s `Display`,
    // which would include the shader source text and detailed compiler messages:
    // per the WebGPU specification <https://gpuweb.github.io/gpuweb/#dom-gpudevice-createshadermodule>,
    // the message of the validation error raised by `createShaderModule` should not include those details,
    // since they are accessible via `getCompilationInfo()`.
    #[cfg(feature = "wgsl")]
    #[error("Shader '{label}' parsing error. Concrete error is available via `get_compilation_info`", label = _0.label.as_deref().unwrap_or_default())]
    Parsing(ShaderError<naga::front::wgsl::ParseError>),

    #[cfg(feature = "glsl")]
    #[error("Shader '{label}' parsing error. Concrete error is available via `get_compilation_info`", label = _0.label.as_deref().unwrap_or_default())]
    ParsingGlsl(ShaderError<naga::front::glsl::ParseErrors>),

    #[cfg(feature = "spirv")]
    #[error("Shader '{label}' parsing error. Concrete error is available via `get_compilation_info`", label = _0.label.as_deref().unwrap_or_default())]
    ParsingSpirV(ShaderError<naga::front::spv::Error>),

    #[error("Failed to generate the backend-specific code")]
    Generation,

    #[error(transparent)]
    Device(#[from] DeviceError),

    #[error("Shader '{label}' validation error. Concrete error is available via `get_compilation_info`", label = _0.label.as_deref().unwrap_or_default())]
    Validation(ShaderError<naga::WithSpan<naga::valid::ValidationError>>),

    #[error(transparent)]
    MissingFeatures(#[from] MissingFeatures),

    #[error(
        "Shader global {bind:?} uses a group index {group} that exceeds the max_bind_groups limit of {limit}."
    )]
    InvalidGroupIndex {
        bind: naga::ResourceBinding,
        group: u32,
        limit: u32,
    },

    #[error("Generic shader passthrough does not contain any code compatible with this backend.")]
    NotCompiledForBackend,

    #[error(
        "Generic passthrough shaders which use GLSL or DXIL must contain exactly one entry point."
    )]
    IncorrectPassthroughEntryPointCount,
}

impl WebGpuError for CreateShaderModuleError {
    fn webgpu_error_type(&self) -> ErrorType {
        match self {
            Self::Device(e) => e.webgpu_error_type(),
            Self::MissingFeatures(e) => e.webgpu_error_type(),

            Self::Generation => ErrorType::Internal,

            Self::Validation(..)
            | Self::InvalidGroupIndex { .. }
            | Self::IncorrectPassthroughEntryPointCount
            | Self::NotCompiledForBackend => ErrorType::Validation,
            #[cfg(feature = "wgsl")]
            Self::Parsing(..) => ErrorType::Validation,
            #[cfg(feature = "glsl")]
            Self::ParsingGlsl(..) => ErrorType::Validation,
            #[cfg(feature = "spirv")]
            Self::ParsingSpirV(..) => ErrorType::Validation,
        }
    }
}

#[cfg(feature = "wgsl")]
pub(crate) fn wgsl_to_compilation_info(
    value: &ShaderError<naga::front::wgsl::ParseError>,
) -> wgt::CompilationInfo {
    use alloc::{string::ToString, vec};
    wgt::CompilationInfo {
        messages: vec![wgt::CompilationMessage {
            message: value.to_string(),
            message_type: wgt::CompilationMessageType::Error,
            location: value
                .inner
                .location(&value.source)
                .as_ref()
                .map(naga_to_source_location),
        }],
    }
}
#[cfg(feature = "glsl")]
pub(crate) fn glsl_to_compilation_info(
    value: &ShaderError<naga::front::glsl::ParseErrors>,
) -> wgt::CompilationInfo {
    use alloc::string::ToString;
    let messages = value
        .inner
        .errors
        .iter()
        .map(|err| wgt::CompilationMessage {
            message: err.to_string(),
            message_type: wgt::CompilationMessageType::Error,
            location: err
                .location(&value.source)
                .as_ref()
                .map(naga_to_source_location),
        })
        .collect();
    wgt::CompilationInfo { messages }
}

#[cfg(feature = "spirv")]
pub(crate) fn spirv_to_compilation_info(
    value: &ShaderError<naga::front::spv::Error>,
) -> wgt::CompilationInfo {
    use alloc::{string::ToString, vec};
    wgt::CompilationInfo {
        messages: vec![wgt::CompilationMessage {
            message: value.to_string(),
            message_type: wgt::CompilationMessageType::Error,
            location: None,
        }],
    }
}

pub(crate) fn naga_to_compilation_info(
    value: &ShaderError<naga::WithSpan<naga::valid::ValidationError>>,
) -> wgt::CompilationInfo {
    use alloc::{string::ToString, vec};
    wgt::CompilationInfo {
        messages: vec![wgt::CompilationMessage {
            message: value.to_string(),
            message_type: wgt::CompilationMessageType::Error,
            location: value
                .inner
                .location(&value.source)
                .as_ref()
                .map(naga_to_source_location),
        }],
    }
}

fn naga_to_source_location(value: &naga::SourceLocation) -> wgt::SourceLocation {
    wgt::SourceLocation {
        length: value.length,
        offset: value.offset,
        line_number: value.line_number,
        line_position: value.line_position,
    }
}

pub(crate) fn shader_module_error_into_compilation_info(
    value: &CreateShaderModuleError,
) -> wgt::CompilationInfo {
    match value {
        #[cfg(feature = "wgsl")]
        CreateShaderModuleError::Parsing(v) => wgsl_to_compilation_info(v),
        #[cfg(feature = "glsl")]
        CreateShaderModuleError::ParsingGlsl(v) => glsl_to_compilation_info(v),
        #[cfg(feature = "spirv")]
        CreateShaderModuleError::ParsingSpirV(v) => spirv_to_compilation_info(v),
        CreateShaderModuleError::Validation(v) => naga_to_compilation_info(v),
        // Device errors are reported through the error sink, and are not compilation errors.
        // Same goes for native shader module generation errors.
        CreateShaderModuleError::Device(_) | CreateShaderModuleError::Generation => {
            wgt::CompilationInfo {
                messages: Vec::new(),
            }
        }
        // Everything else is an error message without location information.
        _ => wgt::CompilationInfo {
            messages: alloc::vec![wgt::CompilationMessage {
                message: value.to_string(),
                message_type: wgt::CompilationMessageType::Error,
                location: None,
            }],
        },
    }
}

/// Describes a programmable pipeline stage.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// cbindgen:ignore
pub struct ProgrammableStageDescriptor<'a, SM = Arc<ShaderModule>> {
    /// The compiled shader module for this stage.
    pub module: SM,

    /// The name of the entry point in `module` that this stage should use.
    ///
    /// - If this is `Some(name)`, `module` must contain an entry point with the
    ///   given name.
    ///
    /// - If this is `None`, `module` must have only one entry point for this
    ///   stage; we use that one.
    pub entry_point: Option<Cow<'a, str>>,

    /// Values for pipeline-overridable constants in `module` that this stage
    /// should use.
    ///
    /// If an `@id` attribute was specified on the declaration,
    /// the key must be the pipeline constant ID as a decimal ASCII number; if not,
    /// the key must be the constant's identifier name.
    ///
    /// The value may represent any of WGSL's concrete scalar types.
    pub constants: naga::back::PipelineConstants,

    /// Whether variables in the workgroup address space will be initialized
    /// with zero values for this stage.
    ///
    /// The WebGPU spec requires variables in the workgroup address space to be
    /// zeroed. However, initialization does impose some overhead, and
    /// non-browser applications may not need it.
    pub zero_initialize_workgroup_memory: bool,
}

#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum CreatePipelineError {
    #[error(transparent)]
    Device(#[from] DeviceError),
    #[error("Unable to derive an implicit layout")]
    Implicit(#[from] ImplicitLayoutError),
    #[error("Error matching {stage:?} shader requirements against the pipeline")]
    Stage {
        stage: wgt::ShaderStages,
        #[source]
        error: validation::StageError,
    },
    #[error("Internal error in {stage:?} shader: {message}")]
    Internal {
        stage: wgt::ShaderStages,
        message: String,
    },
    #[error("Pipeline constant error in {stage:?} shader: {message}")]
    PipelineConstants {
        stage: wgt::ShaderStages,
        message: String,
    },
    #[error(transparent)]
    MissingFeatures(#[from] MissingFeatures),
    #[error(transparent)]
    MissingDownlevelFlags(#[from] MissingDownlevelFlags),
    #[error(transparent)]
    InvalidResource(#[from] InvalidResourceError),
    #[error(transparent)]
    Render(#[from] RenderError),
    #[error(transparent)]
    RayTracing(#[from] RayTracingPipelineError),
}

impl From<ColorAttachmentError> for CreatePipelineError {
    fn from(error: ColorAttachmentError) -> Self {
        Self::Render(error.into())
    }
}

impl From<DepthStencilStateError> for CreatePipelineError {
    fn from(error: DepthStencilStateError) -> Self {
        Self::Render(error.into())
    }
}

impl CreatePipelineError {
    /// Convert a [`hal::PipelineError`] to a [`CreatePipelineError`], without noting device loss.
    ///
    /// If you have a [`Device`] handy, prefer to call
    /// [`Device::handle_hal_pipeline_error`] instead, since that checks for
    /// device loss errors and sets the device's lost flag accordingly.
    ///
    /// This is deliberately not a `From` impl, so that `?` cannot silently skip
    /// device-loss handling.
    pub(crate) fn from_hal_without_device_loss(error: hal::PipelineError) -> Self {
        match error {
            hal::PipelineError::Device(error) => {
                CreatePipelineError::Device(DeviceError::from_hal(error))
            }
            hal::PipelineError::Linkage(stage, message) => {
                CreatePipelineError::Internal { stage, message }
            }
            hal::PipelineError::EntryPoint(stage) => CreatePipelineError::Internal {
                stage: hal::auxil::map_naga_stage(stage),
                message: crate::device::ENTRYPOINT_FAILURE_ERROR.to_string(),
            },
            hal::PipelineError::PipelineConstants(stage, message) => {
                CreatePipelineError::PipelineConstants { stage, message }
            }
        }
    }
}

/// Number of implicit bind groups derived at pipeline creation.
pub type ImplicitBindGroupCount = u8;

#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum ImplicitLayoutError {
    #[error(transparent)]
    BindGroup(#[from] CreateBindGroupLayoutError),
    #[error(transparent)]
    Pipeline(#[from] CreatePipelineLayoutError),
    #[error("Unable to create implicit pipeline layout from passthrough shader stage: {0:?}")]
    Passthrough(wgt::ShaderStages),
}

impl WebGpuError for ImplicitLayoutError {
    fn webgpu_error_type(&self) -> ErrorType {
        match self {
            Self::BindGroup(e) => e.webgpu_error_type(),
            Self::Pipeline(e) => e.webgpu_error_type(),
            Self::Passthrough(_) => ErrorType::Validation,
        }
    }
}

/// Describes a compute pipeline.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// cbindgen:ignore
pub struct ComputePipelineDescriptor<
    'a,
    PLL = Arc<PipelineLayout>,
    SM = Arc<ShaderModule>,
    PLC = Arc<PipelineCache>,
> {
    pub label: Label<'a>,
    /// The layout of bind groups for this pipeline.
    pub layout: Option<PLL>,
    /// The compiled compute stage and its entry point.
    pub stage: ProgrammableStageDescriptor<'a, SM>,
    /// The pipeline cache to use when creating this pipeline.
    pub cache: Option<PLC>,
}

impl WebGpuError for CreatePipelineError {
    fn webgpu_error_type(&self) -> ErrorType {
        match self {
            Self::Device(e) => e.webgpu_error_type(),
            Self::InvalidResource(e) => e.webgpu_error_type(),
            Self::MissingFeatures(e) => e.webgpu_error_type(),
            Self::MissingDownlevelFlags(e) => e.webgpu_error_type(),
            Self::Implicit(e) => e.webgpu_error_type(),
            Self::Stage { error: e, .. } => e.webgpu_error_type(),
            Self::Internal { .. } => ErrorType::Internal,
            Self::PipelineConstants { .. } => ErrorType::Validation,
            Self::Render(e) => e.webgpu_error_type(),
            Self::RayTracing(e) => e.webgpu_error_type(),
        }
    }
}

#[derive(Debug)]
pub struct ComputePipelineState {
    pub(crate) raw: ManuallyDrop<Box<dyn hal::DynComputePipeline>>,
    pub(crate) layout: Arc<PipelineLayout>,
    pub(crate) _shader_module: Arc<ShaderModule>,
}

#[derive(Debug)]
pub struct ComputePipeline {
    pub(crate) state: ResourceState<ComputePipelineState>,
    pub(crate) device: Arc<Device>,
    pub(crate) late_sized_buffer_groups: ArrayVec<LateSizedBufferGroup, { hal::MAX_BIND_GROUPS }>,
    pub(crate) immediate_slots_required: naga::valid::ImmediateSlots,
    /// The `label` from the descriptor used to create the resource.
    pub(crate) label: String,
    pub(crate) tracking_data: TrackingData,
}

impl Drop for ComputePipeline {
    #[allow(trivial_casts)]
    fn drop(&mut self) {
        profiling::scope!("ComputePipeline::drop");
        api_log!("ComputePipeline::drop {:?}", self as *const _);
        resource_log!("Destroy raw {}", self.error_ident());
        #[cfg(feature = "trace")]
        {
            use crate::device::trace;
            if let Some(t) = self.device.trace.lock().as_mut() {
                t.add(trace::Action::DropComputePipeline(unsafe {
                    trace::to_trace(self)
                }));
            }
        }
        let ResourceState::Valid(state) = &mut self.state else {
            return;
        };
        // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
        let raw = unsafe { ManuallyDrop::take(&mut state.raw) };
        unsafe {
            self.device.raw().destroy_compute_pipeline(raw);
        }
    }
}

crate::impl_resource_type!(ComputePipeline);
crate::impl_labeled!(ComputePipeline);
crate::impl_parent_device!(ComputePipeline);
crate::impl_storage_item!(ComputePipeline);
crate::impl_trackable!(ComputePipeline);

impl ComputePipeline {
    pub(crate) fn raw(&self) -> Result<&dyn hal::DynComputePipeline, InvalidResourceError> {
        let ResourceState::Valid(state) = &self.state else {
            return Err(InvalidResourceError(self.error_ident()));
        };
        Ok(state.raw.as_ref())
    }

    pub(crate) fn layout(&self) -> Result<&Arc<PipelineLayout>, InvalidResourceError> {
        let ResourceState::Valid(state) = &self.state else {
            return Err(InvalidResourceError(self.error_ident()));
        };
        Ok(&state.layout)
    }

    pub(crate) fn check_valid(&self) -> Result<(), InvalidResourceError> {
        let ResourceState::Valid(_) = &self.state else {
            return Err(InvalidResourceError(self.error_ident()));
        };
        Ok(())
    }

    pub(crate) fn invalid(device: Arc<Device>, label: String) -> Arc<Self> {
        Arc::new(Self {
            tracking_data: TrackingData::new(device.tracker_indices.compute_pipelines.clone()),
            state: ResourceState::Invalid,
            device,
            late_sized_buffer_groups: ArrayVec::new(),
            immediate_slots_required: naga::valid::ImmediateSlots::default(),
            label,
        })
    }

    pub fn get_bind_group_layout_inner(
        self: &Arc<Self>,
        index: u32,
    ) -> Result<Arc<BindGroupLayout>, GetBindGroupLayoutError> {
        self.layout()?.get_bind_group_layout(index, self.into())
    }

    pub fn get_bind_group_layout(self: &Arc<Self>, index: u32) -> Arc<BindGroupLayout> {
        let bgl = self
            .get_bind_group_layout_inner(index)
            .unwrap_or_else(|err| {
                self.device
                    .handle_error_nolabel(err, "ComputePipeline::get_bind_group_layout");
                BindGroupLayout::invalid(&self.device, String::new())
            });
        #[cfg(feature = "trace")]
        if let Some(ref mut trace) = *self.device.trace.lock() {
            use crate::device::trace;
            use trace::IntoTrace;
            trace.add(trace::Action::GetComputePipelineBindGroupLayout {
                id: bgl.to_trace(),
                pipeline: self.to_trace(),
                index,
            });
        };
        bgl
    }

    pub fn get_subgroup_size(self: &Arc<Self>) -> Option<u32> {
        if !self
            .device
            .features
            .contains(wgt::Features::COMPUTE_PIPELINE_SUBGROUP_SIZE)
        {
            return None;
        }
        self.raw()
            .ok()
            .and_then(hal::DynComputePipeline::get_subgroup_size)
    }
}

#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum CreatePipelineCacheError {
    #[error(transparent)]
    Device(#[from] DeviceError),
    #[error("Pipeline cache validation failed")]
    Validation(#[from] PipelineCacheValidationError),
    #[error(transparent)]
    MissingFeatures(#[from] MissingFeatures),
}

impl WebGpuError for CreatePipelineCacheError {
    fn webgpu_error_type(&self) -> ErrorType {
        match self {
            Self::Device(e) => e.webgpu_error_type(),
            Self::Validation(e) => e.webgpu_error_type(),
            Self::MissingFeatures(e) => e.webgpu_error_type(),
        }
    }
}

#[derive(Debug)]
pub struct PipelineCache {
    pub(crate) raw: ResourceState<Box<dyn hal::DynPipelineCache>>,
    pub(crate) device: Arc<Device>,
    /// The `label` from the descriptor used to create the resource.
    pub(crate) label: String,
}

impl Drop for PipelineCache {
    #[allow(trivial_casts)]
    fn drop(&mut self) {
        profiling::scope!("PipelineCache::drop");
        api_log!("PipelineCache::drop {:?}", self as *const _);
        #[cfg(feature = "trace")]
        if let Some(t) = self.device.trace.lock().as_mut() {
            use crate::device::trace::{to_trace, Action};
            t.add(Action::DropPipelineCache(unsafe { to_trace(self) }));
        }
        resource_log!("Destroy raw {}", self.error_ident());
        if let ResourceState::Valid(raw) = core::mem::replace(&mut self.raw, ResourceState::Invalid)
        {
            unsafe {
                self.device.raw().destroy_pipeline_cache(raw);
            }
        }
    }
}

crate::impl_resource_type!(PipelineCache);
crate::impl_labeled!(PipelineCache);
crate::impl_parent_device!(PipelineCache);
crate::impl_storage_item!(PipelineCache);

impl PipelineCache {
    pub(crate) fn raw(&self) -> Result<&dyn hal::DynPipelineCache, InvalidResourceError> {
        self.raw
            .as_ref()
            .valid()
            .map(|raw| raw.as_ref())
            .ok_or_else(|| InvalidResourceError(self.error_ident()))
    }

    pub(crate) fn check_is_valid(&self) -> Result<(), InvalidResourceError> {
        self.raw().map(|_| ())
    }

    pub(crate) fn invalid(device: Arc<Device>, desc: &PipelineCacheDescriptor) -> Arc<Self> {
        Arc::new(Self {
            raw: ResourceState::Invalid,
            device,
            label: desc.label.to_string(),
        })
    }

    pub fn get_data(self: &Arc<Self>) -> Option<Vec<u8>> {
        api_log!("PipelineCache::get_data");

        let ResourceState::Valid(raw) = &self.raw else {
            return None;
        };

        if !self.device.is_valid() {
            return None;
        }
        let mut vec = unsafe { self.device.raw().pipeline_cache_get_data(raw.as_ref()) }?;
        let validation_key = self.device.raw().pipeline_cache_validation_key()?;

        let mut header_contents = [0; pipeline_cache::HEADER_LENGTH];
        pipeline_cache::add_cache_header(
            &mut header_contents,
            &vec,
            &self.device.adapter.raw.info,
            validation_key,
        );

        let deleted = vec.splice(..0, header_contents).collect::<Vec<_>>();
        debug_assert!(deleted.is_empty());

        Some(vec)
    }
}

/// Describes how the vertex buffer is interpreted.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct VertexBufferLayout<'a> {
    /// The stride, in bytes, between elements of this buffer.
    pub array_stride: wgt::BufferAddress,
    /// How often this vertex buffer is "stepped" forward.
    pub step_mode: wgt::VertexStepMode,
    /// The list of attributes which comprise a single vertex.
    pub attributes: Cow<'a, [wgt::VertexAttribute]>,
}

/// A null vertex buffer layout that may be placed in unused slots.
impl Default for VertexBufferLayout<'_> {
    fn default() -> Self {
        Self {
            array_stride: Default::default(),
            step_mode: Default::default(),
            attributes: Cow::Borrowed(&[]),
        }
    }
}

/// Describes the vertex process in a render pipeline.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// cbindgen:ignore
pub struct VertexState<'a, SM = Arc<ShaderModule>> {
    /// The compiled vertex stage and its entry point.
    pub stage: ProgrammableStageDescriptor<'a, SM>,
    /// The format of any vertex buffers used with this pipeline.
    pub buffers: Cow<'a, [Option<VertexBufferLayout<'a>>]>,
}

/// Describes fragment processing in a render pipeline.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// cbindgen:ignore
pub struct FragmentState<'a, SM = Arc<ShaderModule>> {
    /// The compiled fragment stage and its entry point.
    pub stage: ProgrammableStageDescriptor<'a, SM>,
    /// The effect of draw calls on the color aspect of the output target.
    pub targets: Cow<'a, [Option<wgt::ColorTargetState>]>,
}

/// Describes the task shader in a mesh shader pipeline.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TaskState<'a, SM = Arc<ShaderModule>> {
    /// The compiled task stage and its entry point.
    pub stage: ProgrammableStageDescriptor<'a, SM>,
}

/// Describes the mesh shader in a mesh shader pipeline.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MeshState<'a, SM = Arc<ShaderModule>> {
    /// The compiled mesh stage and its entry point.
    pub stage: ProgrammableStageDescriptor<'a, SM>,
}

/// Describes a vertex processor for either a conventional or mesh shading
/// pipeline architecture.
///
/// This is not a public API. It is for use by `player` only. The public APIs
/// are [`VertexState`], [`TaskState`], and [`MeshState`].
///
/// cbindgen:ignore
#[doc(hidden)]
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum RenderPipelineVertexProcessor<'a, SM = Arc<ShaderModule>> {
    Vertex(VertexState<'a, SM>),
    Mesh(Option<TaskState<'a, SM>>, MeshState<'a, SM>),
}

/// Describes a render (graphics) pipeline.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RenderPipelineDescriptor<
    'a,
    PLL = Arc<PipelineLayout>,
    SM = Arc<ShaderModule>,
    PLC = Arc<PipelineCache>,
> {
    pub label: Label<'a>,
    /// The layout of bind groups for this pipeline.
    pub layout: Option<PLL>,
    /// The vertex processing state for this pipeline.
    pub vertex: VertexState<'a, SM>,
    /// The properties of the pipeline at the primitive assembly and rasterization level.
    #[cfg_attr(feature = "serde", serde(default))]
    pub primitive: wgt::PrimitiveState,
    /// The effect of draw calls on the depth and stencil aspects of the output target, if any.
    #[cfg_attr(feature = "serde", serde(default))]
    pub depth_stencil: Option<wgt::DepthStencilState>,
    /// The multi-sampling properties of the pipeline.
    #[cfg_attr(feature = "serde", serde(default))]
    pub multisample: wgt::MultisampleState,
    /// The fragment processing state for this pipeline.
    pub fragment: Option<FragmentState<'a, SM>>,
    /// If the pipeline will be used with a multiview render pass, this indicates how many array
    /// layers the attachments will have.
    pub multiview_mask: Option<NonZeroU32>,
    /// The pipeline cache to use when creating this pipeline.
    pub cache: Option<PLC>,
}
/// Describes a mesh shader pipeline.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MeshPipelineDescriptor<
    'a,
    PLL = Arc<PipelineLayout>,
    SM = Arc<ShaderModule>,
    PLC = Arc<PipelineCache>,
> {
    pub label: Label<'a>,
    /// The layout of bind groups for this pipeline.
    pub layout: Option<PLL>,
    /// The task processing state for this pipeline.
    pub task: Option<TaskState<'a, SM>>,
    /// The mesh processing state for this pipeline
    pub mesh: MeshState<'a, SM>,
    /// The properties of the pipeline at the primitive assembly and rasterization level.
    #[cfg_attr(feature = "serde", serde(default))]
    pub primitive: wgt::PrimitiveState,
    /// The effect of draw calls on the depth and stencil aspects of the output target, if any.
    #[cfg_attr(feature = "serde", serde(default))]
    pub depth_stencil: Option<wgt::DepthStencilState>,
    /// The multi-sampling properties of the pipeline.
    #[cfg_attr(feature = "serde", serde(default))]
    pub multisample: wgt::MultisampleState,
    /// The fragment processing state for this pipeline.
    pub fragment: Option<FragmentState<'a, SM>>,
    /// If the pipeline will be used with a multiview render pass, this indicates how many array
    /// layers the attachments will have.
    pub multiview: Option<NonZeroU32>,
    /// The pipeline cache to use when creating this pipeline.
    pub cache: Option<PLC>,
}

/// Describes a render (graphics) pipeline, with either conventional or mesh
/// shading architecture.
///
/// This is not a public API. It is for use by `player` only. The public APIs
/// are [`RenderPipelineDescriptor`] and [`MeshPipelineDescriptor`].
///
/// cbindgen:ignore
#[doc(hidden)]
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GeneralRenderPipelineDescriptor<
    'a,
    PLL = Arc<PipelineLayout>,
    SM = Arc<ShaderModule>,
    PLC = Arc<PipelineCache>,
> {
    pub label: Label<'a>,
    /// The layout of bind groups for this pipeline.
    pub layout: Option<PLL>,
    /// The vertex processing state for this pipeline.
    pub vertex: RenderPipelineVertexProcessor<'a, SM>,
    /// The properties of the pipeline at the primitive assembly and rasterization level.
    #[cfg_attr(feature = "serde", serde(default))]
    pub primitive: wgt::PrimitiveState,
    /// The effect of draw calls on the depth and stencil aspects of the output target, if any.
    #[cfg_attr(feature = "serde", serde(default))]
    pub depth_stencil: Option<wgt::DepthStencilState>,
    /// The multi-sampling properties of the pipeline.
    #[cfg_attr(feature = "serde", serde(default))]
    pub multisample: wgt::MultisampleState,
    /// The fragment processing state for this pipeline.
    pub fragment: Option<FragmentState<'a, SM>>,
    /// If the pipeline will be used with a multiview render pass, this indicates how many array
    /// layers the attachments will have.
    pub multiview_mask: Option<NonZeroU32>,
    /// The pipeline cache to use when creating this pipeline.
    pub cache: Option<PLC>,
}
impl<'a, PLL, SM, PLC> From<RenderPipelineDescriptor<'a, PLL, SM, PLC>>
    for GeneralRenderPipelineDescriptor<'a, PLL, SM, PLC>
{
    fn from(value: RenderPipelineDescriptor<'a, PLL, SM, PLC>) -> Self {
        Self {
            label: value.label,
            layout: value.layout,
            vertex: RenderPipelineVertexProcessor::Vertex(value.vertex),
            primitive: value.primitive,
            depth_stencil: value.depth_stencil,
            multisample: value.multisample,
            fragment: value.fragment,
            multiview_mask: value.multiview_mask,
            cache: value.cache,
        }
    }
}
impl<'a, PLL, SM, PLC> From<MeshPipelineDescriptor<'a, PLL, SM, PLC>>
    for GeneralRenderPipelineDescriptor<'a, PLL, SM, PLC>
{
    fn from(value: MeshPipelineDescriptor<'a, PLL, SM, PLC>) -> Self {
        Self {
            label: value.label,
            layout: value.layout,
            vertex: RenderPipelineVertexProcessor::Mesh(value.task, value.mesh),
            primitive: value.primitive,
            depth_stencil: value.depth_stencil,
            multisample: value.multisample,
            fragment: value.fragment,
            multiview_mask: value.multiview,
            cache: value.cache,
        }
    }
}

/// Not a public API. For use by `player` only.
///
/// cbindgen:ignore
pub type ResolvedGeneralRenderPipelineDescriptor<'a> =
    GeneralRenderPipelineDescriptor<'a, Arc<PipelineLayout>, Arc<ShaderModule>, Arc<PipelineCache>>;

#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PipelineCacheDescriptor<'a> {
    pub label: Label<'a>,
    pub data: Option<Cow<'a, [u8]>>,
    pub fallback: bool,
}

#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum ColorStateError {
    #[error("Format {0:?} is not renderable")]
    FormatNotRenderable(wgt::TextureFormat),
    #[error("Format {0:?} is not blendable")]
    FormatNotBlendable(wgt::TextureFormat),
    #[error("Format {0:?} does not have a color aspect")]
    FormatNotColor(wgt::TextureFormat),
    #[error("Sample count {0} is not supported by format {1:?} on this device. The WebGPU spec guarantees {2:?} samples are supported by this format. With the TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES feature your device supports {3:?}.")]
    InvalidSampleCount(u32, wgt::TextureFormat, Vec<u32>, Vec<u32>),
    #[error("Output format {pipeline} is incompatible with the shader {shader}")]
    IncompatibleFormat {
        pipeline: validation::NumericType,
        shader: validation::NumericType,
    },
    #[error("Invalid write mask {0:?}")]
    InvalidWriteMask(wgt::ColorWrites),
    #[error("Using the blend factor {factor:?} for render target {target} is not possible. Only the first render target may be used when dual-source blending.")]
    BlendFactorOnUnsupportedTarget {
        factor: wgt::BlendFactor,
        target: u32,
    },
    #[error("The {which} blend factor {factor:?} is not valid because the shader output does not have an alpha channel.")]
    InvalidAlphaBlend {
        which: &'static str,
        factor: wgt::BlendFactor,
    },
    #[error(
        "Blend factor {factor:?} for render target {target} is not valid. Blend factor must be `one` when using min/max blend operations."
    )]
    InvalidMinMaxBlendFactor {
        factor: wgt::BlendFactor,
        target: u32,
    },
    #[error("Shader does not produce an output at this index")]
    OutputNotPresent,
}

#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum DepthStencilStateError {
    #[error("Format {0:?} is not renderable")]
    FormatNotRenderable(wgt::TextureFormat),
    #[error("Format {0:?} is not a depth/stencil format")]
    FormatNotDepthOrStencil(wgt::TextureFormat),
    #[error("Format {0:?} does not have a depth aspect, but depth test/write is enabled")]
    FormatNotDepth(wgt::TextureFormat),
    #[error("Format {0:?} does not have a stencil aspect, but stencil test/write is enabled")]
    FormatNotStencil(wgt::TextureFormat),
    #[error("Sample count {0} is not supported by format {1:?} on this device. The WebGPU spec guarantees {2:?} samples are supported by this format. With the TEXTURE_ADAPTER_SPECIFIC_FORMAT_FEATURES feature your device supports {3:?}.")]
    InvalidSampleCount(u32, wgt::TextureFormat, Vec<u32>, Vec<u32>),
    #[error("Depth bias is not compatible with non-triangle topology {0:?}")]
    DepthBiasWithIncompatibleTopology(wgt::PrimitiveTopology),
    #[error("Depth compare function must be specified for depth format {0:?}")]
    MissingDepthCompare(wgt::TextureFormat),
    #[error("Depth write enabled must be specified for depth format {0:?}")]
    MissingDepthWriteEnabled(wgt::TextureFormat),
}

/// Errors specific to render pipeline creation.
///
/// These are usually returned as [`CreatePipelineError::Render`].
#[derive(Clone, Debug, Error)]
#[non_exhaustive]
pub enum RenderError {
    #[error(transparent)]
    ColorAttachment(#[from] ColorAttachmentError),
    #[error("Color state [{0}] is invalid")]
    ColorState(u8, #[source] ColorStateError),
    #[error("Depth/stencil state is invalid")]
    DepthStencilState(#[from] DepthStencilStateError),
    #[error("Invalid sample count {0}")]
    InvalidSampleCount(u32),
    #[error("The number of vertex buffers {given} exceeds the limit {limit}")]
    TooManyVertexBuffers { given: u32, limit: u32 },
    #[error("The number of bind groups + vertex buffers {given} exceeds the limit {limit}")]
    TooManyBindGroupsPlusVertexBuffers { given: u32, limit: u32 },
    #[error("The number of vertex-stage buffers and acceleration structures {given} exceeds the limit {limit}")]
    TooManyBuffersAndAccelerationStructuresInVertexStage { given: u32, limit: u32 },
    #[error("The total number of vertex attributes {given} exceeds the limit {limit}")]
    TooManyVertexAttributes { given: u32, limit: u32 },
    #[error("Vertex attribute location {given} must be less than limit {limit}")]
    VertexAttributeLocationTooLarge { given: u32, limit: u32 },
    #[error("Vertex buffer {index} stride {given} exceeds the limit {limit}")]
    VertexStrideTooLarge { index: u32, given: u32, limit: u32 },
    #[error("Vertex attribute at location {location} stride {given} exceeds the limit {limit}")]
    VertexAttributeStrideTooLarge {
        location: wgt::ShaderLocation,
        given: u32,
        limit: u32,
    },
    #[error("Vertex buffer {index} stride {stride} does not respect `VERTEX_ALIGNMENT`")]
    UnalignedVertexStride {
        index: u32,
        stride: wgt::BufferAddress,
    },
    #[error("Vertex attribute at location {location} has invalid offset {offset}")]
    InvalidVertexAttributeOffset {
        location: wgt::ShaderLocation,
        offset: wgt::BufferAddress,
    },
    #[error("Two or more vertex attributes were assigned to the same location in the shader: {0}")]
    ShaderLocationClash(u32),
    #[error("Strip index format was not set to None but to {strip_index_format:?} while using the non-strip topology {topology:?}")]
    StripIndexFormatForNonStripTopology {
        strip_index_format: Option<wgt::IndexFormat>,
        topology: wgt::PrimitiveTopology,
    },
    #[error("Conservative Rasterization is only supported for wgt::PolygonMode::Fill")]
    ConservativeRasterizationNonFillPolygonMode,
    #[error("In the provided shader, the type given for group {group} binding {binding} has a size of {size}. As the device does not support `DownlevelFlags::BUFFER_BINDINGS_NOT_16_BYTE_ALIGNED`, the type must have a size that is a multiple of 16 bytes.")]
    UnalignedShader { group: u32, binding: u32, size: u64 },
    #[error("Dual-source blending requires exactly one color target, but {count} color targets are present")]
    DualSourceBlendingWithMultipleColorTargets { count: usize },
    #[error("{}", concat!(
        "At least one color attachment or depth-stencil attachment was expected, ",
        "but no render target for the pipeline was specified."
    ))]
    NoTargetSpecified,
}

impl WebGpuError for RenderError {
    fn webgpu_error_type(&self) -> ErrorType {
        match self {
            Self::ColorAttachment(_)
            | Self::ColorState(_, _)
            | Self::DepthStencilState(_)
            | Self::InvalidSampleCount(_)
            | Self::TooManyVertexBuffers { .. }
            | Self::TooManyBindGroupsPlusVertexBuffers { .. }
            | Self::TooManyBuffersAndAccelerationStructuresInVertexStage { .. }
            | Self::TooManyVertexAttributes { .. }
            | Self::VertexAttributeLocationTooLarge { .. }
            | Self::VertexStrideTooLarge { .. }
            | Self::UnalignedVertexStride { .. }
            | Self::InvalidVertexAttributeOffset { .. }
            | Self::ShaderLocationClash(_)
            | Self::StripIndexFormatForNonStripTopology { .. }
            | Self::ConservativeRasterizationNonFillPolygonMode
            | Self::UnalignedShader { .. }
            | Self::DualSourceBlendingWithMultipleColorTargets { .. }
            | Self::NoTargetSpecified
            | Self::VertexAttributeStrideTooLarge { .. } => ErrorType::Validation,
        }
    }
}

bitflags::bitflags! {
    #[repr(transparent)]
    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
    pub struct PipelineFlags: u32 {
        const BLEND_CONSTANT = 1 << 0;
        const STENCIL_REFERENCE = 1 << 1;
        const WRITES_DEPTH = 1 << 2;
        const WRITES_STENCIL = 1 << 3;
    }
}

/// How a render pipeline will retrieve attributes from a particular vertex buffer.
#[derive(Clone, Copy, Debug)]
pub struct VertexStep {
    /// The byte stride in the buffer between one attribute value and the next.
    pub stride: wgt::BufferAddress,

    /// The byte size required to fit the last vertex in the stream.
    pub last_stride: wgt::BufferAddress,

    /// Whether the buffer is indexed by vertex number or instance number.
    pub mode: wgt::VertexStepMode,
}

impl Default for VertexStep {
    fn default() -> Self {
        Self {
            stride: 0,
            last_stride: 0,
            mode: wgt::VertexStepMode::Vertex,
        }
    }
}

#[derive(Debug)]
pub(crate) struct RenderPipelineState {
    pub(crate) raw: ManuallyDrop<Box<dyn hal::DynRenderPipeline>>,
    pub(crate) layout: Arc<PipelineLayout>,
}

#[derive(Debug)]
pub struct RenderPipeline {
    pub(crate) state: ResourceState<RenderPipelineState>,
    pub(crate) device: Arc<Device>,
    pub(crate) _shader_modules: ArrayVec<Arc<ShaderModule>, { hal::MAX_CONCURRENT_SHADER_STAGES }>,
    pub(crate) pass_context: RenderPassContext,
    pub(crate) flags: PipelineFlags,
    pub(crate) topology: wgt::PrimitiveTopology,
    pub(crate) strip_index_format: Option<wgt::IndexFormat>,
    pub(crate) vertex_steps: Vec<Option<VertexStep>>,
    pub(crate) late_sized_buffer_groups: ArrayVec<LateSizedBufferGroup, { hal::MAX_BIND_GROUPS }>,
    pub(crate) immediate_slots_required: naga::valid::ImmediateSlots,
    /// The `label` from the descriptor used to create the resource.
    pub(crate) label: String,
    pub(crate) tracking_data: TrackingData,
    /// Whether this is a mesh shader pipeline
    pub(crate) is_mesh: bool,
    pub(crate) has_task_shader: bool,
}

impl Drop for RenderPipeline {
    #[allow(trivial_casts)]
    fn drop(&mut self) {
        profiling::scope!("RenderPipeline::drop");
        api_log!("RenderPipeline::drop {:?}", self as *const _);
        resource_log!("Destroy raw {}", self.error_ident());
        #[cfg(feature = "trace")]
        {
            use crate::device::trace;
            if let Some(t) = self.device.trace.lock().as_mut() {
                t.add(trace::Action::DropRenderPipeline(unsafe {
                    trace::to_trace(self)
                }));
            }
        }
        let ResourceState::Valid(state) = &mut self.state else {
            return;
        };
        // SAFETY: We are in the Drop impl and we don't use self.raw anymore after this point.
        let raw = unsafe { ManuallyDrop::take(&mut state.raw) };
        unsafe {
            self.device.raw().destroy_render_pipeline(raw);
        }
    }
}

crate::impl_resource_type!(RenderPipeline);
crate::impl_labeled!(RenderPipeline);
crate::impl_parent_device!(RenderPipeline);
crate::impl_storage_item!(RenderPipeline);
crate::impl_trackable!(RenderPipeline);

impl RenderPipeline {
    pub(crate) fn raw(&self) -> Result<&dyn hal::DynRenderPipeline, InvalidResourceError> {
        let ResourceState::Valid(state) = &self.state else {
            return Err(InvalidResourceError(self.error_ident()));
        };
        Ok(state.raw.as_ref())
    }

    pub(crate) fn layout(&self) -> Result<&Arc<PipelineLayout>, InvalidResourceError> {
        let ResourceState::Valid(state) = &self.state else {
            return Err(InvalidResourceError(self.error_ident()));
        };
        Ok(&state.layout)
    }

    pub(crate) fn check_valid(&self) -> Result<(), InvalidResourceError> {
        let ResourceState::Valid(_) = &self.state else {
            return Err(InvalidResourceError(self.error_ident()));
        };
        Ok(())
    }

    pub(crate) fn invalid(device: Arc<Device>, label: String) -> Arc<Self> {
        Arc::new(Self {
            tracking_data: TrackingData::new(device.tracker_indices.render_pipelines.clone()),
            state: ResourceState::Invalid,
            device,
            _shader_modules: ArrayVec::new(),
            pass_context: RenderPassContext {
                attachments: AttachmentData {
                    colors: ArrayVec::new(),
                    resolves: ArrayVec::new(),
                    depth_stencil: None,
                },
                sample_count: 0,
                multiview_mask: None,
            },
            flags: PipelineFlags::empty(),
            topology: wgt::PrimitiveTopology::TriangleList,
            strip_index_format: None,
            vertex_steps: Vec::new(),
            late_sized_buffer_groups: ArrayVec::new(),
            immediate_slots_required: naga::valid::ImmediateSlots::default(),
            label,
            is_mesh: false,
            has_task_shader: false,
        })
    }

    pub fn get_bind_group_layout_inner(
        self: &Arc<Self>,
        index: u32,
    ) -> Result<Arc<BindGroupLayout>, GetBindGroupLayoutError> {
        self.layout()?.get_bind_group_layout(index, self.into())
    }

    pub fn get_bind_group_layout(self: &Arc<Self>, index: u32) -> Arc<BindGroupLayout> {
        let bgl = self
            .get_bind_group_layout_inner(index)
            .unwrap_or_else(|err| {
                self.device
                    .handle_error_nolabel(err, "RenderPipeline::get_bind_group_layout");
                BindGroupLayout::invalid(&self.device, String::new())
            });
        #[cfg(feature = "trace")]
        if let Some(ref mut trace) = *self.device.trace.lock() {
            use crate::device::trace;
            use trace::IntoTrace;
            trace.add(trace::Action::GetRenderPipelineBindGroupLayout {
                id: bgl.to_trace(),
                pipeline: self.to_trace(),
                index,
            });
        };
        bgl
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn passthrough_interface(entry_point_names: &[&str]) -> PassthroughInterface {
        PassthroughInterface {
            entry_point_names: entry_point_names
                .iter()
                .map(|name| (*name).to_owned())
                .collect(),
        }
    }

    #[test]
    fn select_implicit_passthrough_entry_point() {
        let empty = passthrough_interface(&[]);
        assert!(matches!(
            finalize_passthrough_entry_point_name(&empty, None),
            Err(validation::StageError::NoEntryPoints)
        ));

        let single = passthrough_interface(&["main"]);
        assert_eq!(
            finalize_passthrough_entry_point_name(&single, None).unwrap(),
            "main"
        );

        let multiple = passthrough_interface(&["vertex", "fragment"]);
        assert!(matches!(
            finalize_passthrough_entry_point_name(&multiple, None),
            Err(validation::StageError::AmbiguousEntryPoint)
        ));
    }

    #[test]
    fn select_explicit_passthrough_entry_point() {
        let interface = passthrough_interface(&["main"]);
        assert_eq!(
            finalize_passthrough_entry_point_name(&interface, Some("main")).unwrap(),
            "main"
        );
        assert!(matches!(
            finalize_passthrough_entry_point_name(&interface, Some("missing")),
            Err(validation::StageError::NoEntryPointWithName(name)) if name == "missing"
        ));
    }
}