Less buggy Kivy 1.7 hackery
[erdslangetjie.git] / erdslangetjie / data.py
1 '''Simple data loader module.
2
3 Loads data files from the "data" directory shipped with a game.
4
5 Enhancing this to handle caching etc. is left as an exercise for the reader.
6
7 Note that pyglet users should probably just add the data directory to the
8 pyglet.resource search path.
9 '''
10
11 import os
12 from kivy.core.image import ImageLoader
13 from kivy.core.audio import SoundLoader
14 from kivy.cache import Cache
15
16 data_py = os.path.abspath(os.path.dirname(__file__))
17 data_dir = os.path.normpath(os.path.join(data_py, '..', 'data'))
18 imageloader = ImageLoader()
19 soundloader = SoundLoader()
20 Cache.register('bane', limit=200)
21
22
23 def filepath(filename):
24     '''Determine the path to a file in the data directory.
25     '''
26     filename = os.path.join(*filename.split('/'))
27     return os.path.join(data_dir, filename)
28
29
30 def load(filename, mode='rb'):
31     '''Open a file in the data directory.
32
33     "mode" is passed as the second arg to open().
34     '''
35     return open(filepath(filename), mode)
36
37
38 def _cache_load(filename, loader):
39     '''Load an object either from disk or from the cache.
40
41        We rely on kivy's caching infrastructure'''
42     path = filepath(filename)
43     obj = Cache.get('bane', path)
44     if obj is None:
45         obj = loader.load(path)
46         Cache.append('bane', path, obj)
47     return obj
48
49
50 def load_image(filename):
51     return _cache_load(filename, imageloader)
52
53
54 def load_sound(filename):
55     return _cache_load(filename, soundloader)