1use crate::{MeshLike, MraphicsID, RenderInstance};
2use std::collections::HashMap;
3
4pub struct Scene {
5 pub instances: Vec<RenderInstance>,
6 instance_map: HashMap<MraphicsID, usize>,
7}
8
9impl Scene {
10 pub fn new() -> Self {
11 Self {
12 instances: Vec::new(),
13 instance_map: HashMap::new(),
14 }
15 }
16
17 pub fn add_mesh<M: MeshLike>(&mut self, mesh: &mut M) {
18 mesh.update();
19
20 let mut instance = mesh.build_instance();
21 mesh.update_instance(&mut instance);
22
23 self.instances.push(instance);
24 self.instance_map
25 .insert(mesh.identifier(), self.instances.len() - 1);
26 }
27
28 pub fn remove_renderable(&mut self, identifier: MraphicsID) -> Option<RenderInstance> {
29 let remove_index = *self.instance_map.get(&identifier)?;
30 let swap_index = self.instances.len() - 1;
31
32 for index in self.instance_map.values_mut() {
33 if *index == swap_index {
34 *index = remove_index;
35 }
36 }
37
38 Some(self.instances.swap_remove(remove_index))
39 }
40
41 pub fn acquire_instance(&self, identifier: MraphicsID) -> Option<&RenderInstance> {
42 let index = self.instance_map.get(&identifier)?;
43 self.instances.get(*index)
44 }
45
46 pub fn acquire_instance_unchecked(&self, identifier: MraphicsID) -> &RenderInstance {
47 &self.instances[*self.instance_map.get(&identifier).unwrap()]
48 }
49
50 pub fn acquire_instance_mut(&mut self, identifier: MraphicsID) -> Option<&mut RenderInstance> {
51 let index = self.instance_map.get(&identifier)?;
52 self.instances.get_mut(*index)
53 }
54
55 pub fn acquire_instance_mut_unchecked(
56 &mut self,
57 identifier: MraphicsID,
58 ) -> &mut RenderInstance {
59 &mut self.instances[*self.instance_map.get(&identifier).unwrap()]
60 }
61}