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
use crate::core::*;
use crate::renderer::*;
pub struct Sprites {
context: Context,
position_buffer: VertexBuffer,
uv_buffer: VertexBuffer,
center_buffer: InstanceBuffer,
transformation: Mat4,
direction: Option<Vec3>,
}
impl Sprites {
pub fn new(context: &Context, centers: &[Vec3], direction: Option<Vec3>) -> ThreeDResult<Self> {
let position_buffer = VertexBuffer::new_with_data(
&context,
&[
vec3(-1.0, -1.0, 0.0),
vec3(1.0, -1.0, 0.0),
vec3(1.0, 1.0, 0.0),
vec3(1.0, 1.0, 0.0),
vec3(-1.0, 1.0, 0.0),
vec3(-1.0, -1.0, 0.0),
],
)?;
let uv_buffer = VertexBuffer::new_with_data(
&context,
&[
vec2(0.0, 0.0),
vec2(1.0, 0.0),
vec2(1.0, 1.0),
vec2(1.0, 1.0),
vec2(0.0, 1.0),
vec2(0.0, 0.0),
],
)?;
Ok(Self {
context: context.clone(),
position_buffer,
uv_buffer,
center_buffer: InstanceBuffer::new_with_data(context, centers)?,
transformation: Mat4::identity(),
direction,
})
}
pub fn transformation(&self) -> Mat4 {
self.transformation
}
pub fn set_transformation(&mut self, transformation: Mat4) {
self.transformation = transformation;
}
pub fn set_direction(&mut self, direction: Option<Vec3>) {
self.direction = direction;
}
pub fn set_centers(&mut self, centers: &[Vec3]) -> ThreeDResult<()> {
self.center_buffer.fill(centers)
}
}
impl Geometry for Sprites {
fn render_with_material(
&self,
material: &dyn Material,
camera: &Camera,
lights: &[&dyn Light],
) -> ThreeDResult<()> {
let fragment_shader_source = material.fragment_shader_source(false, lights);
self.context.program(
&include_str!("shaders/sprites.vert"),
&fragment_shader_source,
|program| {
material.use_uniforms(program, camera, lights)?;
program.use_uniform_block("Camera", camera.uniform_buffer())?;
program.use_uniform("transformation", self.transformation)?;
program.use_vertex_attribute("position", &self.position_buffer)?;
program.use_vertex_attribute("uv_coordinate", &self.uv_buffer)?;
program.use_instance_attribute("center", &self.center_buffer)?;
program.use_uniform("direction", self.direction.unwrap_or(vec3(0.0, 0.0, 0.0)))?;
program.draw_arrays_instanced(
material.render_states(),
camera.viewport(),
6,
self.center_buffer.instance_count(),
)
},
)
}
fn aabb(&self) -> AxisAlignedBoundingBox {
AxisAlignedBoundingBox::INFINITE
}
}