particle_system.rs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. use specs::prelude::*;
  2. use super::{ Rltk, ParticleLifetime, Position, Renderable };
  3. use rltk::RGB;
  4. pub fn cull_dead_particles(ecs : &mut World, ctx : &Rltk) {
  5. let mut dead_particles : Vec<Entity> = Vec::new();
  6. {
  7. // Age out particles
  8. let mut particles = ecs.write_storage::<ParticleLifetime>();
  9. let entities = ecs.entities();
  10. for (entity, mut particle) in (&entities, &mut particles).join() {
  11. particle.lifetime_ms -= ctx.frame_time_ms;
  12. if particle.lifetime_ms < 0.0 {
  13. dead_particles.push(entity);
  14. }
  15. }
  16. }
  17. for dead in dead_particles.iter() {
  18. ecs.delete_entity(*dead).expect("Particle will not die");
  19. }
  20. }
  21. struct ParticleRequest {
  22. x: i32,
  23. y: i32,
  24. fg: RGB,
  25. bg: RGB,
  26. glyph: u8,
  27. lifetime: f32
  28. }
  29. pub struct ParticleBuilder {
  30. requests : Vec<ParticleRequest>
  31. }
  32. impl ParticleBuilder {
  33. pub fn new() -> ParticleBuilder {
  34. ParticleBuilder{ requests : Vec::new() }
  35. }
  36. pub fn request(&mut self, x:i32, y:i32, fg: RGB, bg:RGB, glyph: u8, lifetime: f32) {
  37. self.requests.push(
  38. ParticleRequest{
  39. x, y, fg, bg, glyph, lifetime
  40. }
  41. );
  42. }
  43. }
  44. pub struct ParticleSpawnSystem {}
  45. impl<'a> System<'a> for ParticleSpawnSystem {
  46. #[allow(clippy::type_complexity)]
  47. type SystemData = (
  48. Entities<'a>,
  49. WriteStorage<'a, Position>,
  50. WriteStorage<'a, Renderable>,
  51. WriteStorage<'a, ParticleLifetime>,
  52. WriteExpect<'a, ParticleBuilder>
  53. );
  54. fn run(&mut self, data : Self::SystemData) {
  55. let (entities, mut positions, mut renderables, mut particles, mut particle_builder) = data;
  56. for new_particle in particle_builder.requests.iter() {
  57. let p = entities.create();
  58. positions.insert(p, Position{ x: new_particle.x, y: new_particle.y }).expect("Unable to inser position");
  59. renderables.insert(p, Renderable{ fg: new_particle.fg, bg: new_particle.bg, glyph: new_particle.glyph, render_order: 0 }).expect("Unable to insert renderable");
  60. particles.insert(p, ParticleLifetime{ lifetime_ms: new_particle.lifetime }).expect("Unable to insert lifetime");
  61. }
  62. particle_builder.requests.clear();
  63. }
  64. }