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
use crate::core::*;
use crate::renderer::*;
use std::collections::HashMap;
#[derive(Clone, Debug, Default)]
pub struct Particles {
pub start_positions: Vec<Vec3>,
pub start_velocities: Vec<Vec3>,
pub texture_transforms: Option<Vec<Mat3>>,
pub colors: Option<Vec<Color>>,
}
impl Particles {
pub fn validate(&self) -> Result<(), RendererError> {
let instance_count = self.count();
let buffer_check = |length: Option<usize>, name: &str| -> Result<(), RendererError> {
if let Some(length) = length {
if length < instance_count as usize {
Err(RendererError::InvalidBufferLength(
name.to_string(),
instance_count as usize,
length,
))?;
}
}
Ok(())
};
buffer_check(
self.texture_transforms.as_ref().map(|b| b.len()),
"texture transforms",
)?;
buffer_check(self.colors.as_ref().map(|b| b.len()), "colors")?;
buffer_check(Some(self.start_positions.len()), "start_positions")?;
buffer_check(Some(self.start_velocities.len()), "start_velocities")?;
Ok(())
}
pub fn count(&self) -> u32 {
self.start_positions.len() as u32
}
}
pub struct ParticleSystem {
context: Context,
vertex_buffers: HashMap<String, VertexBuffer>,
instance_buffers: HashMap<String, InstanceBuffer>,
index_buffer: Option<ElementBuffer>,
pub acceleration: Vec3,
instance_count: u32,
transformation: Mat4,
texture_transform: Mat3,
pub time: f32,
}
impl ParticleSystem {
pub fn new(context: &Context, particles: &Particles, cpu_mesh: &CpuMesh) -> Self {
#[cfg(debug_assertions)]
cpu_mesh.validate().expect("invalid cpu mesh");
let mut particles_system = Self {
context: context.clone(),
index_buffer: super::index_buffer_from_mesh(context, cpu_mesh),
vertex_buffers: super::vertex_buffers_from_mesh(context, cpu_mesh),
instance_buffers: HashMap::new(),
acceleration: vec3(0.0, -9.82, 0.0),
instance_count: 0,
transformation: Mat4::identity(),
texture_transform: Mat3::identity(),
time: 0.0,
};
particles_system.set_particles(particles);
particles_system
}
pub fn transformation(&self) -> Mat4 {
self.transformation
}
pub fn set_transformation(&mut self, transformation: Mat4) {
self.transformation = transformation;
}
pub fn texture_transform(&self) -> &Mat3 {
&self.texture_transform
}
pub fn set_texture_transform(&mut self, texture_transform: Mat3) {
self.texture_transform = texture_transform;
}
pub fn set_particles(&mut self, particles: &Particles) {
#[cfg(debug_assertions)]
particles.validate().expect("invalid particles");
self.instance_count = particles.count();
self.instance_buffers.clear();
self.instance_buffers.insert(
"start_position".to_string(),
InstanceBuffer::new_with_data(&self.context, &particles.start_positions),
);
self.instance_buffers.insert(
"start_velocity".to_string(),
InstanceBuffer::new_with_data(&self.context, &particles.start_velocities),
);
if let Some(texture_transforms) = &particles.texture_transforms {
let mut instance_tex_transform1 = Vec::new();
let mut instance_tex_transform2 = Vec::new();
for texture_transform in texture_transforms.iter() {
instance_tex_transform1.push(vec3(
texture_transform.x.x,
texture_transform.y.x,
texture_transform.z.x,
));
instance_tex_transform2.push(vec3(
texture_transform.x.y,
texture_transform.y.y,
texture_transform.z.y,
));
}
self.instance_buffers.insert(
"tex_transform_row1".to_string(),
InstanceBuffer::new_with_data(&self.context, &instance_tex_transform1),
);
self.instance_buffers.insert(
"tex_transform_row2".to_string(),
InstanceBuffer::new_with_data(&self.context, &instance_tex_transform2),
);
}
if let Some(instance_colors) = &particles.colors {
self.instance_buffers.insert(
"instance_color".to_string(),
InstanceBuffer::new_with_data(&self.context, &instance_colors),
);
}
}
fn draw(&self, program: &Program, render_states: RenderStates, camera: &Camera) {
program.use_uniform("viewProjection", camera.projection() * camera.view());
program.use_uniform("modelMatrix", &self.transformation);
program.use_uniform("acceleration", &self.acceleration);
program.use_uniform("time", &self.time);
program.use_uniform_if_required("textureTransform", &self.texture_transform);
program.use_uniform_if_required(
"normalMatrix",
&self.transformation.invert().unwrap().transpose(),
);
for attribute_name in ["position", "normal", "tangent", "color", "uv_coordinates"] {
if program.requires_attribute(attribute_name) {
program.use_vertex_attribute(
attribute_name,
self.vertex_buffers
.get(attribute_name).expect(&format!("the render call requires the {} vertex buffer which is missing on the given geometry", attribute_name))
);
}
}
for attribute_name in [
"start_position",
"start_velocity",
"tex_transform_row1",
"tex_transform_row2",
"instance_color",
] {
if program.requires_attribute(attribute_name) {
program.use_instance_attribute(
attribute_name,
self.instance_buffers
.get(attribute_name).expect(&format!("the render call requires the {} instance buffer which is missing on the given geometry", attribute_name))
);
}
}
if let Some(ref index_buffer) = self.index_buffer {
program.draw_elements_instanced(
render_states,
camera.viewport(),
index_buffer,
self.instance_count,
)
} else {
program.draw_arrays_instanced(
render_states,
camera.viewport(),
self.vertex_buffers.get("position").unwrap().vertex_count() as u32,
self.instance_count,
)
}
}
fn vertex_shader_source(&self, fragment_shader_source: &str) -> String {
let use_positions = fragment_shader_source.find("in vec3 pos;").is_some();
let use_normals = fragment_shader_source.find("in vec3 nor;").is_some();
let use_tangents = fragment_shader_source.find("in vec3 tang;").is_some();
let use_uvs = fragment_shader_source.find("in vec2 uvs;").is_some();
let use_colors = fragment_shader_source.find("in vec4 col;").is_some();
format!(
"#define PARTICLES\n{}{}{}{}{}{}{}{}",
if use_positions {
"#define USE_POSITIONS\n"
} else {
""
},
if use_normals {
"#define USE_NORMALS\n"
} else {
""
},
if use_tangents {
if fragment_shader_source.find("in vec3 bitang;").is_none() {
panic!("if the fragment shader defined 'in vec3 tang' it also needs to define 'in vec3 bitang'");
}
"#define USE_TANGENTS\n"
} else {
""
},
if use_uvs { "#define USE_UVS\n" } else { "" },
if use_colors {
if self.instance_buffers.contains_key("instance_color")
&& self.vertex_buffers.contains_key("color")
{
"#define USE_COLORS\n#define USE_VERTEX_COLORS\n#define USE_INSTANCE_COLORS\n"
} else if self.instance_buffers.contains_key("instance_color") {
"#define USE_COLORS\n#define USE_INSTANCE_COLORS\n"
} else {
"#define USE_COLORS\n#define USE_VERTEX_COLORS\n"
}
} else {
""
},
if self.instance_buffers.contains_key("tex_transform_row1") {
"#define USE_INSTANCE_TEXTURE_TRANSFORMATION\n"
} else {
""
},
include_str!("../../core/shared.frag"),
include_str!("shaders/mesh.vert"),
)
}
}
impl<'a> IntoIterator for &'a ParticleSystem {
type Item = &'a dyn Geometry;
type IntoIter = std::iter::Once<&'a dyn Geometry>;
fn into_iter(self) -> Self::IntoIter {
std::iter::once(self)
}
}
impl Geometry for ParticleSystem {
fn aabb(&self) -> AxisAlignedBoundingBox {
AxisAlignedBoundingBox::INFINITE
}
fn render_with_material(
&self,
material: &dyn Material,
camera: &Camera,
lights: &[&dyn Light],
) {
let fragment_shader_source = material.fragment_shader_source(
self.vertex_buffers.contains_key("color")
|| self.instance_buffers.contains_key("instance_color"),
lights,
);
self.context
.program(
&self.vertex_shader_source(&fragment_shader_source),
&fragment_shader_source,
|program| {
material.use_uniforms(program, camera, lights);
self.draw(program, material.render_states(), camera);
},
)
.expect("Failed compiling shader")
}
fn render_with_post_material(
&self,
material: &dyn PostMaterial,
camera: &Camera,
lights: &[&dyn Light],
color_texture: Option<ColorTexture>,
depth_texture: Option<DepthTexture>,
) {
let fragment_shader_source =
material.fragment_shader_source(lights, color_texture, depth_texture);
self.context
.program(
&self.vertex_shader_source(&fragment_shader_source),
&fragment_shader_source,
|program| {
material.use_uniforms(program, camera, lights, color_texture, depth_texture);
self.draw(program, material.render_states(), camera);
},
)
.expect("Failed compiling shader")
}
}