summaryrefslogtreecommitdiff
path: root/src/texture_manager.rs
blob: 32a61a0523c6886a1cd7c0ab5c19045c1804cb93 (plain) (blame)
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
use std::collections::HashMap;
use std::path::Path;

use sdl2::image::LoadTexture;
use sdl2::render::{Texture, TextureCreator};

pub const ASSET_PATH_STR: &str = "assets";

pub struct TextureManager<T>
{
    texture_creator: TextureCreator<T>,
    textures:        HashMap<String, Texture>,
}

impl<T> TextureManager<T>
{
    pub fn new(texture_creator: TextureCreator<T>) -> Self
    {
        Self {
            texture_creator,
            textures: HashMap::new(),
        }
    }

    pub fn preload<S>(&mut self, filename: S) -> Result<(), String>
    where
        S: AsRef<Path>,
    {
        let filename_str = filename
            .as_ref()
            .to_str()
            .expect("Only filenames with valid Unicode are allowed.");
        if self.textures.contains_key(filename_str) {
            return Ok(());
        }

        let texture = self
            .texture_creator
            .load_texture(Path::new(ASSET_PATH_STR).join(&filename))?;
        self.textures.insert(filename_str.to_string(), texture);
        Ok(())
    }

    pub fn get<S>(&mut self, filename: S) -> Result<&Texture, String>
    where
        S: AsRef<Path>,
    {
        self.preload(&filename)?;

        Ok(self
            .textures
            .get(filename.as_ref().to_str().unwrap())
            .unwrap())
    }

    pub fn get_never_load<S>(&self, filename: S) -> Option<&Texture>
    where
        S: AsRef<Path>,
    {
        self.textures.get(filename.as_ref().to_str().unwrap())
    }
}