1# gcc -std=c99 -O3 -shared -o world \ 2# -I src -I deps/noise deps/noise/noise.c src/world.c 3 4from ctypes import CDLL, CFUNCTYPE, c_float, c_int, c_void_p 5from collections import OrderedDict 6 7dll = CDLL('/usr/local/lib/libcraft-world.so') 8 9WORLD_FUNC = CFUNCTYPE(None, c_int, c_int, c_int, c_int, c_void_p) 10 11def dll_seed(x): 12 dll.seed(x) 13 14def dll_create_world(p, q): 15 result = {} 16 def world_func(x, y, z, w, arg): 17 result[(x, y, z)] = w 18 dll.create_world(p, q, WORLD_FUNC(world_func), None) 19 return result 20 21dll.simplex2.restype = c_float 22dll.simplex2.argtypes = [c_float, c_float, c_int, c_float, c_float] 23def dll_simplex2(x, y, octaves=1, persistence=0.5, lacunarity=2.0): 24 return dll.simplex2(x, y, octaves, persistence, lacunarity) 25 26dll.simplex3.restype = c_float 27dll.simplex3.argtypes = [c_float, c_float, c_float, c_int, c_float, c_float] 28def dll_simplex3(x, y, z, octaves=1, persistence=0.5, lacunarity=2.0): 29 return dll.simplex3(x, y, z, octaves, persistence, lacunarity) 30 31class World(object): 32 def __init__(self, seed=None, cache_size=64): 33 self.seed = seed 34 self.cache = OrderedDict() 35 self.cache_size = cache_size 36 def create_chunk(self, p, q): 37 if self.seed is not None: 38 dll_seed(self.seed) 39 return dll_create_world(p, q) 40 def get_chunk(self, p, q): 41 try: 42 chunk = self.cache.pop((p, q)) 43 except KeyError: 44 chunk = self.create_chunk(p, q) 45 self.cache[(p, q)] = chunk 46 if len(self.cache) > self.cache_size: 47 self.cache.popitem(False) 48 return chunk 49