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

use crate::{
    error::{
        draw::{ShaderError, VulkanError},
        textures::*,
    },
    prelude::{InstanceData, Texture, Vertex as GameVertex},
};

use anyhow::{Error, Result};
use derive_builder::Builder;
use std::sync::Arc;

use vulkano::{
    descriptor_set::{PersistentDescriptorSet, WriteDescriptorSet},
    pipeline::{
        graphics::{
            color_blend::{AttachmentBlend, ColorBlendAttachmentState, ColorBlendState},
            input_assembly::{InputAssemblyState, PrimitiveTopology},
            multisample::MultisampleState,
            rasterization::RasterizationState,
            vertex_input::{Vertex, VertexDefinition},
            viewport::ViewportState,
            GraphicsPipelineCreateInfo,
        },
        layout::PipelineDescriptorSetLayoutCreateInfo,
        DynamicState, GraphicsPipeline, Pipeline, PipelineLayout, PipelineShaderStageCreateInfo,
    },
    render_pass::Subpass,
    shader::{spirv::bytes_to_words, ShaderModule, ShaderModuleCreateInfo},
};

use super::RESOURCES;
// pub use vulkano::pipeline::graphics::rasterization::LineStipple;

/// 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.
///
/// It takes some time to make a new material.
#[derive(Clone, PartialEq)]
pub struct Material {
    pub(crate) pipeline: Arc<GraphicsPipeline>,
    pub(crate) instanced: bool,
    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("instanced", &self.instanced)
            .field("texture", &self.texture)
            .field("layer", &self.layer)
            .finish()
    }
}
/// Making
///
/// Right now it produces an error when the shaders don't have a main function.
impl Material {
    /// Creates a new material using the given shaders, settings and write operations.
    pub fn new_with_shaders(
        settings: MaterialSettings,
        shaders: &Shaders,
        instanced: bool,
        writes: Vec<WriteDescriptorSet>,
    ) -> Result<Self, VulkanError> {
        let vs = &shaders.vertex;
        let fs = &shaders.fragment;
        let vertex = vs
            .entry_point(&shaders.entry_point)
            .ok_or(VulkanError::ShaderError)?;
        let fragment = fs
            .entry_point(&shaders.entry_point)
            .ok_or(VulkanError::ShaderError)?;

        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 line_stipple = settings.line_stripple.map(StateMode::Fixed);

        let resources = &RESOURCES;
        let loader = resources.loader().lock();
        let vulkan = resources.vulkan();
        let pipeline_cache = loader.pipeline_cache.clone();
        let subpass = Subpass::from(vulkan.render_pass.clone(), 0)
            .ok_or(VulkanError::Other(Error::msg("Failed to make subpass.")))?;
        let allocator = &loader.descriptor_set_allocator;

        let input_assembly = InputAssemblyState {
            topology,
            ..Default::default()
        };
        let stages = [
            PipelineShaderStageCreateInfo::new(vertex.clone()),
            PipelineShaderStageCreateInfo::new(fragment.clone()),
        ];
        let layout = PipelineLayout::new(
            vulkan.device.clone(),
            PipelineDescriptorSetLayoutCreateInfo::from_stages(&stages)
                .into_pipeline_layout_create_info(vulkan.device.clone())
                .map_err(|e| VulkanError::Other(e.into()))?,
        )?;

        let vertex_input_state = if instanced {
            [GameVertex::per_vertex(), InstanceData::per_instance()]
                .definition(&vertex.info().input_interface)
                .map_err(|e| VulkanError::Validated(e.into()))?
        } else {
            GameVertex::per_vertex()
                .definition(&vertex.info().input_interface)
                .map_err(|e| VulkanError::Validated(e.into()))?
        };

        let pipeline = GraphicsPipeline::new(
            vulkan.device.clone(),
            Some(pipeline_cache.clone()),
            GraphicsPipelineCreateInfo {
                stages: stages.into_iter().collect(),
                vertex_input_state: Some(vertex_input_state),
                input_assembly_state: Some(input_assembly),
                viewport_state: Some(ViewportState::default()),
                rasterization_state: Some(RasterizationState {
                    line_width: settings.line_width,
                    // line_stipple,
                    ..RasterizationState::default()
                }),
                multisample_state: Some(MultisampleState::default()),
                color_blend_state: Some(ColorBlendState::with_attachment_states(
                    subpass.num_color_attachments(),
                    ColorBlendAttachmentState {
                        blend: Some(AttachmentBlend::alpha()),
                        ..Default::default()
                    },
                )),
                dynamic_state: [DynamicState::Viewport].into_iter().collect(),
                subpass: Some(subpass.into()),
                ..GraphicsPipelineCreateInfo::layout(layout)
            },
        )
        .map_err(VulkanError::Validated)?;
        let descriptor = if !writes.is_empty() {
            Some(PersistentDescriptorSet::new(
                allocator,
                pipeline
                    .layout()
                    .set_layouts()
                    .get(2) // on set 2
                    .ok_or(VulkanError::Other(Error::msg(
                        "Failed to get the second set of the pipeline layout.",
                    )))?
                    .clone(),
                writes,
                [],
            )?)
        } else {
            None
        };
        Ok(Self {
            pipeline,
            descriptor,
            instanced,
            layer: settings.initial_layer,
            texture: settings.texture,
        })
    }

    /// Makes a new default material.
    pub fn new(settings: MaterialSettings) -> Result<Material, VulkanError> {
        let resources = &RESOURCES;
        let shaders = resources.vulkan().clone().default_shaders;
        Self::new_with_shaders(settings, &shaders, false, vec![])
    }

    /// Makes a new default material.
    pub fn new_instanced(settings: MaterialSettings) -> Result<Material, VulkanError> {
        let resources = &RESOURCES;
        let shaders = resources.vulkan().clone().default_instance_shaders;
        Self::new_with_shaders(settings, &shaders, true, vec![])
    }

    /// Creates a simple material made just for showing a texture.
    pub fn new_default_textured(texture: &Texture) -> Material {
        let resources = &RESOURCES;
        let default = if texture.layers() == 1 {
            resources.vulkan().textured_material.clone()
        } else {
            resources.vulkan().texture_array_material.clone()
        };
        Material {
            texture: Some(texture.clone()),
            ..default
        }
    }
    pub fn new_default_textured_instance(texture: &Texture) -> Material {
        let resources = &RESOURCES;
        let default = if texture.layers() == 1 {
            resources.vulkan().textured_instance_material.clone()
        } else {
            resources.vulkan().texture_array_instance_material.clone()
        };
        Material {
            texture: Some(texture.clone()),
            ..default
        }
    }
}
impl Material {
    /// Writes to the material changing the variables for the shaders.
    ///
    /// # Safety
    /// The program will crash in case in case the data input here is not as the shader wants it.
    pub unsafe fn write(&mut self, descriptor: Vec<WriteDescriptorSet>) -> Result<()> {
        let resources = &RESOURCES;
        let loader = resources.loader().lock();
        self.descriptor = Some(PersistentDescriptorSet::new(
            &loader.descriptor_set_allocator,
            self.pipeline
                .layout()
                .set_layouts()
                .get(1)
                .ok_or(Error::msg(
                    "Could not obtain the second set layout of this write.",
                ))?
                .clone(),
            descriptor,
            [],
        )?);
        Ok(())
    }

    /// Sets the layer of the texture in case it has a texture with layers.
    pub fn set_layer(&mut self, id: u32) -> Result<(), TextureError> {
        if let Some(texture) = &self.texture {
            if id > texture.layers() - 1 {
                return Err(TextureError::Layer(format!(
                    "Given: {}, Highest: {}",
                    id,
                    texture.layers() - 1
                )));
            }
        } else {
            return Err(TextureError::NoTexture);
        }
        self.layer = id;
        Ok(())
    }

    /// Returns the layer of the texture in case the material is textured.
    pub fn layer(&self) -> u32 {
        self.layer
    }

    /// Goes to the next frame of the texture.
    ///
    /// Returns an error if it reached the limit.
    pub fn next_frame(&mut self) -> Result<(), TextureError> {
        if let Some(texture) = &self.texture {
            if texture.layers() <= self.layer + 1 {
                return Err(TextureError::Layer(
                    "You are already at the last frame.".to_string(),
                ));
            }
        } else {
            return Err(TextureError::NoTexture);
        }
        self.layer += 1;
        Ok(())
    }

    /// Goes back a frame of the texture.
    ///
    /// Returns an error if the layer is already on 0.
    pub fn last_frame(&mut self) -> Result<(), TextureError> {
        if self.texture.is_some() {
            if self.layer == 0 {
                return Err(TextureError::Layer(
                    "You are already on the first frame".to_string(),
                ));
            }
        } else {
            return Err(TextureError::NoTexture);
        }
        self.layer -= 1;
        Ok(())
    }

    /// Returns the texture.
    pub fn 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 {
    /// The usage way of the vertices and indices given in the model.
    #[builder(setter(into), default = "Topology::TriangleList")]
    pub topology: Topology,
    /// The width of the line in case the topology was set to something with lines.
    #[builder(setter(into), default = "1.0")]
    pub line_width: f32,
    // /// The stipple of the line.
    // #[builder(setter(into), default = "None")]
    // pub line_stripple: Option<LineStipple>,
    /// The optional texture of the material.
    #[builder(setter(into), default = "None")]
    pub texture: Option<Texture>,
    /// If the texture has multiple layers this is the layer it starts at.
    #[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>,
    entry_point: Box<str>,
}

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 unsafe fn from_bytes(
        vertex_bytes: &[u8],
        fragment_bytes: &[u8],
        entry_point: &str,
        // layout: &[Box<dyn BufferContents + Any>],
    ) -> Result<Self, ShaderError> {
        let resources = &RESOURCES;
        let device = resources.vulkan().clone().device;
        let vertex_words = bytes_to_words(vertex_bytes)?;
        let fragment_words = bytes_to_words(fragment_bytes)?;
        let vertex: Arc<ShaderModule> = unsafe {
            ShaderModule::new(device.clone(), ShaderModuleCreateInfo::new(&vertex_words))?
        };
        let fragment: Arc<ShaderModule> = unsafe {
            ShaderModule::new(device.clone(), ShaderModuleCreateInfo::new(&fragment_words))?
        };
        vertex
            .entry_point(entry_point)
            .ok_or(ShaderError::ShaderEntryPoint)?;
        fragment
            .entry_point(entry_point)
            .ok_or(ShaderError::ShaderEntryPoint)?;
        Ok(Self {
            vertex,
            fragment,
            entry_point: entry_point.into(),
        })
    }
    pub fn from_modules(
        vertex: Arc<ShaderModule>,
        fragment: Arc<ShaderModule>,
        entry_point: impl Into<Box<str>>,
    ) -> Self {
        Self {
            vertex,
            fragment,
            entry_point: entry_point.into(),
        }
    }
}