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
//! Material related settings that determine the way the scene gets rendered.

use crate::{
    error::textures::*,
    resources::{Texture, Vulkan},
    Vertex as GameVertex,
};
use derive_builder::Builder;
use std::sync::Arc;

use vulkano::descriptor_set::{
    allocator::StandardDescriptorSetAllocator, PersistentDescriptorSet, WriteDescriptorSet,
};
use vulkano::pipeline::{
    cache::PipelineCache,
    graphics::{
        color_blend::ColorBlendState,
        input_assembly::{InputAssemblyState, PrimitiveTopology},
        rasterization::RasterizationState,
        vertex_input::Vertex,
        viewport::ViewportState,
    },
    GraphicsPipeline, Pipeline, StateMode,
};
use vulkano::render_pass::Subpass;
use vulkano::shader::ShaderModule;

/// The way in which an object gets drawn using it's vertices and indices.
#[derive(Debug, Clone, Copy)]
pub enum Topology {
    /// Creates triangles using every 3 vertices for one triangle.
    TriangleList,
    /// Creates triangles using 3 vertices for the first triangle and every next triangle using the next vertex and the 2 vertices before that.
    TriangleStrip,
    /// Creates a line using every 2 vertices.
    LineList,
    /// Creates a line using the vertices as guiding points where to go next.
    LineStrip,
    /// Creates a pixel for every vertex.
    PointList,
}

/// A material holding the way an object should be drawn.
///
/// Takes some time.
#[derive(Clone, PartialEq)]
pub struct Material {
    pub(crate) pipeline: Arc<GraphicsPipeline>,
    pub(crate) descriptor: Option<Arc<PersistentDescriptorSet>>,
    pub(crate) texture: Option<Texture>,
    pub(crate) layer: u32,
}

impl std::fmt::Debug for Material {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Material")
            .field("texture", &self.texture)
            .field("layer", &self.layer)
            .finish()
    }
}

impl Material {
    /// Makes a new material.
    pub(crate) fn new(
        settings: MaterialSettings,
        shaders: &Shaders,
        descriptor: Vec<WriteDescriptorSet>,
        vulkan: &Vulkan,
        pipeline_cache: Arc<PipelineCache>,
        subpass: Subpass,
        allocator: &StandardDescriptorSetAllocator,
    ) -> Self {
        let vs = &shaders.vertex;
        let fs = &shaders.fragment;

        let topology: PrimitiveTopology = match settings.topology {
            Topology::TriangleList => PrimitiveTopology::TriangleList,
            Topology::TriangleStrip => PrimitiveTopology::TriangleStrip,
            Topology::LineList => PrimitiveTopology::LineList,
            Topology::LineStrip => PrimitiveTopology::LineStrip,
            Topology::PointList => PrimitiveTopology::PointList,
        };

        let pipeline: Arc<GraphicsPipeline> = GraphicsPipeline::start()
            .vertex_input_state(GameVertex::per_vertex())
            .input_assembly_state(InputAssemblyState::new().topology(topology))
            .rasterization_state(RasterizationState {
                line_width: StateMode::Fixed(settings.line_width),
                ..RasterizationState::new()
            })
            .vertex_shader(vs.entry_point("main").unwrap(), ())
            .viewport_state(ViewportState::viewport_dynamic_scissor_irrelevant())
            .fragment_shader(fs.entry_point("main").unwrap(), ())
            .color_blend_state(ColorBlendState::new(subpass.num_color_attachments()).blend_alpha())
            .render_pass(subpass)
            .build_with_cache(pipeline_cache)
            .build(vulkan.device.clone())
            .unwrap();
        let descriptor = if !descriptor.is_empty() {
            Some(
                PersistentDescriptorSet::new(
                    allocator,
                    pipeline
                        .layout()
                        .set_layouts()
                        .get(2) // on set 2
                        .unwrap()
                        .clone(),
                    descriptor,
                )
                .unwrap(),
            )
        } else {
            None
        };
        Self {
            pipeline,
            descriptor,
            layer: settings.initial_layer,
            texture: settings.texture,
        }
    }

    /// Writes to the material changing the variables for the shaders.
    pub fn write(
        &mut self,
        descriptor: Vec<WriteDescriptorSet>,
        allocator: &StandardDescriptorSetAllocator,
    ) {
        self.descriptor = Some(
            PersistentDescriptorSet::new(
                allocator,
                self.pipeline.layout().set_layouts().get(1).unwrap().clone(),
                descriptor,
            )
            .unwrap(),
        );
    }

    /// Sets the layer of the texture in case it has a texture with layers.
    pub fn set_layer(&mut self, id: u32) -> Result<(), Box<dyn std::error::Error>> {
        if let Some(texture) = &self.texture {
            if id > texture.layers - 1 {
                return Err(Box::new(TextureIDError));
            }
        } else {
            return Err(Box::new(NoTextureError));
        }
        self.layer = id;
        Ok(())
    }

    pub fn get_layer(&self) -> u32 {
        self.layer
    }

    /// Goes to the next frame of the layer.
    ///
    /// Returns an error if it reached the limit.
    pub fn next_frame(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        if let Some(texture) = &self.texture {
            if texture.layers <= self.layer + 1 {
                return Err(Box::new(TextureIDError));
            }
        } else {
            return Err(Box::new(NoTextureError));
        }
        self.layer += 1;
        Ok(())
    }

    /// Goes to the last frame of the layer.
    ///
    /// Returns an error if the layer is 0.
    pub fn last_frame(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        if self.texture.is_some() {
            if self.layer == 0 {
                return Err(Box::new(TextureIDError));
            }
        } else {
            return Err(Box::new(NoTextureError));
        }
        self.layer -= 1;
        Ok(())
    }

    /// Returns the texture.
    pub fn get_texture(&self) -> Option<Texture> {
        self.texture.clone()
    }

    /// Sets the texture.
    pub fn set_texture(&mut self, texture: Option<Texture>) {
        self.texture = texture;
    }
}

/// Vertex and fragment shaders of a material
/// as well as the topology and line width, if the topology is set to LineList or LineStrip.
#[derive(Builder, Clone, Debug)]
pub struct MaterialSettings {
    #[builder(setter(into), default = "Topology::TriangleList")]
    pub topology: Topology,
    #[builder(setter(into), default = "1.0")]
    pub line_width: f32,
    #[builder(setter(into), default = "None")]
    pub texture: Option<Texture>,
    #[builder(setter(into), default = "0")]
    pub initial_layer: u32,
}

/// Holds compiled shaders in form of ShaderModules to use in a material.
#[derive(Clone, Debug, PartialEq)]
pub struct Shaders {
    pub(crate) vertex: Arc<ShaderModule>,
    pub(crate) fragment: Arc<ShaderModule>,
}

impl Shaders {
    /// Creates a shader from SpirV bytes.
    ///
    /// # Safety
    ///
    /// When loading those shaders the engine doesn't know if they are right.
    /// So when they are wrong I'm not sure what will happen. Make it right!
    pub(crate) unsafe fn from_bytes(
        vertex_bytes: &[u8],
        fragment_bytes: &[u8],
        vulkan: &Vulkan,
    ) -> Self {
        let vertex: Arc<ShaderModule> =
            unsafe { ShaderModule::from_bytes(vulkan.device.clone(), vertex_bytes).unwrap() };
        let fragment: Arc<ShaderModule> =
            unsafe { ShaderModule::from_bytes(vulkan.device.clone(), fragment_bytes).unwrap() };
        Self { vertex, fragment }
    }
}