-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpriteCache.java
More file actions
50 lines (40 loc) · 1.62 KB
/
Copy pathSpriteCache.java
File metadata and controls
50 lines (40 loc) · 1.62 KB
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
package io.github.moonslanding.tlm.engine;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class SpriteCache {
private static SpriteCache instance;
private final Map<String, Sprite> loadedSprites = new HashMap<>();
private final ClassLoader classLoader = getClass().getClassLoader();
private SpriteCache() {
}
private static void initialize() {
if (instance != null) return;
instance = new SpriteCache();
}
public static Map<String, Sprite> getLoadedSprites() {
initialize();
return instance.loadedSprites;
}
public static Sprite loadSprite(String spriteName) {
// Try to load a sprite from the cache.
initialize();
Map<String, Sprite> presentMap = getLoadedSprites();
if (presentMap.containsKey(spriteName)) return presentMap.get(spriteName);
System.out.println("loading new sprite: " + spriteName);
try {
loadFromResource(spriteName);
return getLoadedSprites().get(spriteName);
} catch (IOException e) {
System.out.println(spriteName + " cannot be loaded!");
return null;
}
}
private static void loadFromResource(String spriteName) throws IOException {
InputStream stream = instance.classLoader.getResourceAsStream("sprites/" + spriteName + ".png");
if (stream == null) throw new FileNotFoundException("sprite asset: " + spriteName + " not found!");
getLoadedSprites().put(spriteName, Sprite.fromInputStream(stream));
}
}