witchcraft_renderer/types/
instance.rs

1/// An abstraction for an instance.
2#[derive(Clone, Copy)]
3pub struct Instance {
4    position: cgmath::Vector3<f32>,
5    rotation: cgmath::Quaternion<f32>,
6}
7impl Instance {
8    pub fn to_raw(&self) -> InstanceRaw {
9        InstanceRaw {
10            model: (cgmath::Matrix4::from_translation(self.position)
11                * cgmath::Matrix4::from(self.rotation))
12            .into(),
13        }
14    }
15}
16
17/// The raw representation of the `Instance` type.
18/// Used for bytemuck.
19#[repr(C)]
20#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
21pub struct InstanceRaw {
22    model: [[f32; 4]; 4],
23}
24impl InstanceRaw {
25    pub fn desc<'a>() -> wgpu::VertexBufferLayout<'a> {
26        wgpu::VertexBufferLayout {
27            array_stride: std::mem::size_of::<InstanceRaw>() as wgpu::BufferAddress,
28            step_mode: wgpu::VertexStepMode::Instance,
29            attributes: &[
30                wgpu::VertexAttribute {
31                    offset: 0,
32                    shader_location: 5,
33                    format: wgpu::VertexFormat::Float32x4,
34                },
35                wgpu::VertexAttribute {
36                    offset: std::mem::size_of::<[f32; 4]>() as wgpu::BufferAddress,
37                    shader_location: 6,
38                    format: wgpu::VertexFormat::Float32x4,
39                },
40                wgpu::VertexAttribute {
41                    offset: std::mem::size_of::<[f32; 8]>() as wgpu::BufferAddress,
42                    shader_location: 7,
43                    format: wgpu::VertexFormat::Float32x4,
44                },
45                wgpu::VertexAttribute {
46                    offset: std::mem::size_of::<[f32; 12]>() as wgpu::BufferAddress,
47                    shader_location: 8,
48                    format: wgpu::VertexFormat::Float32x4,
49                },
50            ],
51        }
52    }
53}