From 622e28937c48a8a389e981b9099a839d643f7678 Mon Sep 17 00:00:00 2001 From: Micha White Date: Sat, 19 Nov 2022 13:33:26 -0500 Subject: Added a load_from_file method --- alligator_resources/src/texture.rs | 60 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) (limited to 'alligator_resources/src') diff --git a/alligator_resources/src/texture.rs b/alligator_resources/src/texture.rs index 1bb7cb8..ac9e70f 100644 --- a/alligator_resources/src/texture.rs +++ b/alligator_resources/src/texture.rs @@ -176,6 +176,19 @@ impl Texture { TextureBuffer::Disk(file) => file.load(), } } + + fn unload(&mut self) { + if let TextureBuffer::Disk(file) = &mut self.buffer { + file.unload(); + } + } + + fn allocated_size(&self) -> usize { + match &self.buffer { + TextureBuffer::Memory(texture) => texture_size(texture), + TextureBuffer::Disk(file) => file.allocated_size(), + } + } } pub struct TextureRef<'a> { @@ -277,6 +290,28 @@ impl TextureManager { } } + fn can_load(&mut self, texture: &Texture) -> bool { + let mut textures: Vec<&mut Texture> = self.textures.values_mut().collect(); + textures.sort_by_key(|a| a.priority()); + textures.reverse(); + + let max_size = self.max_size; + let priority = texture.priority(); + let mut total_size = texture.allocated_size(); + + for texture in textures { + if total_size + texture.allocated_size() < max_size { + total_size += texture.allocated_size(); + } else if texture.priority() < priority { + texture.unload(); + } else { + return false; + } + } + + true + } + /// Loads a texture from memory in the given format. /// /// # Errors @@ -300,6 +335,31 @@ impl TextureManager { Ok(id) } + pub fn load_from_file( + &mut self, + path: impl AsRef, + priority: Priority, + ) -> Result { + let id = TextureId::new(); + let mut texture = Texture::from_path(path, priority); + + if priority == Priority::Urgent || self.can_load(&texture) { + match texture.load_texture() { + Ok(_) => { + self.textures.insert(id, texture); + } + Err(e) => { + self.textures.insert(id, texture); + return Err(e); + } + } + } else { + self.textures.insert(id, texture); + } + + Ok(id) + } + pub fn atlas(&mut self) -> &Rgba16Texture { let atlas = { profiling::scope!("export atlas"); -- cgit v1.2.3