khora_core/renderer/api/
shader.rs

1// Copyright 2025 eraflo
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Defines data structures for representing shader modules.
16
17use std::borrow::Cow;
18
19/// Represents the source code for a shader module.
20///
21/// This enum allows for future expansion to other shader languages (like GLSL or SPIR-V)
22/// while maintaining a unified API.
23#[derive(Debug, Clone)]
24pub enum ShaderSourceData<'a> {
25    /// The shader source is provided as a WGSL (WebGPU Shading Language) string.
26    Wgsl(Cow<'a, str>),
27}
28
29/// A descriptor used to create a [`ShaderModuleId`].
30///
31/// This struct provides all the necessary information for the `GraphicsDevice` to
32/// compile a piece of shader code into a usable, backend-specific shader module.
33#[derive(Debug, Clone)]
34pub struct ShaderModuleDescriptor<'a> {
35    /// An optional debug label for the shader module.
36    pub label: Option<&'a str>,
37    /// The source code of the shader.
38    pub source: ShaderSourceData<'a>,
39}
40
41/// An opaque handle to a compiled shader module.
42///
43/// This ID is returned by [`GraphicsDevice::create_shader_module`] and is used to
44/// reference the shader in a [`RenderPipelineDescriptor`].
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
46pub struct ShaderModuleId(pub usize);
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51    use std::borrow::Cow;
52
53    #[test]
54    fn shader_module_id_creation_and_equality() {
55        let id1 = ShaderModuleId(1);
56        let id2 = ShaderModuleId(2);
57        let id1_again = ShaderModuleId(1);
58
59        assert_eq!(id1, id1_again);
60        assert_ne!(id1, id2);
61    }
62
63    #[test]
64    fn shader_module_descriptor_creation() {
65        let source_code = "fn main() {}";
66        let descriptor = ShaderModuleDescriptor {
67            label: Some("test_shader"),
68            source: ShaderSourceData::Wgsl(Cow::Borrowed(source_code)),
69        };
70
71        assert_eq!(descriptor.label, Some("test_shader"));
72        let ShaderSourceData::Wgsl(ref cow) = descriptor.source;
73        assert_eq!(cow.as_ref(), source_code);
74    }
75}