43 lines
1.3 KiB
Python
43 lines
1.3 KiB
Python
from perlin_noise import PerlinNoise
|
|
|
|
import log, worldrw
|
|
|
|
CHUNK_SIZE = 8
|
|
SEED = 0
|
|
NOISE_OCTAVES = 10
|
|
NOISE_SCALE = 1 / (NOISE_OCTAVES * 10)
|
|
|
|
class World:
|
|
def __init__(self, seed: int):
|
|
self.seed = seed
|
|
self.noise = PerlinNoise(octaves=NOISE_OCTAVES, seed=self.seed)
|
|
|
|
def get_chunk_data(self, x: int, z: int) -> bytes:
|
|
if worldrw.chunk_exists(x, z):
|
|
log.debug(f"Loading existing chunk {x}.{z}")
|
|
try:
|
|
return worldrw.get_chunk_data(x, z)
|
|
except RuntimeError:
|
|
log.critical(f"Error while loading chunk {x}.{z}", exc_info=True)
|
|
return b""
|
|
else:
|
|
log.info(f"Generating new chunk {x}.{z}")
|
|
data: bytes = self._generate_chunk(x, z)
|
|
worldrw.save_chunk_data(x, z, data)
|
|
return data
|
|
|
|
def _generate_chunk(self, x: int, z: int) -> bytes:
|
|
heights = [[0 for x in range(CHUNK_SIZE)] for z in range(CHUNK_SIZE)]
|
|
log.debug("Generating height map...")
|
|
for z in range(CHUNK_SIZE):
|
|
for x in range(CHUNK_SIZE):
|
|
heights[z][x] = int((self.noise([x * NOISE_SCALE, z * NOISE_SCALE]) + 1) * 128)
|
|
log.debug("Allocating chunk...")
|
|
chunk = bytearray(b"\x00" * CHUNK_SIZE * CHUNK_SIZE * 256)
|
|
log.debug("Generating chunk...")
|
|
for x, arr_row in enumerate(heights):
|
|
for z, height in enumerate(arr_row):
|
|
for y in range(0, height):
|
|
chunk[y * CHUNK_SIZE * CHUNK_SIZE + z * CHUNK_SIZE + x] = 1 # stone
|
|
return bytes(chunk)
|