#!/usr/bin/env python3 import numpy as np from enum import Enum from typing import Tuple import json class Direction(Enum): Left = 0 Down = 1 Front = 2 Right = 3 Up = 4 Back = 5 class Chunk(object): """ This is a manager for Chunks. Raw Data (provided as 3D-Tensor of integers) is located in Chunk.block_data """ CHUNK_SIDELENGTH = 16 # 16 CHUNK_SIDELENGTH_SQRD = 256 # 16 * 16 CHUNK_BLOCKS = 4096 # 16 * 16 * 16 @staticmethod def Index2Coords(i: int) -> Tuple[int, int, int]: x = i % Chunk.CHUNK_SIDELENGTH y = (i // Chunk.CHUNK_SIDELENGTH) % Chunk.CHUNK_SIDELENGTH z = i // (Chunk.CHUNK_SIDELENGTH_SQRD) return x, y, z @staticmethod def Coords2Index(x: int, y: int, z: int) -> int: return x + y * Chunk.CHUNK_SIDELENGTH + z * Chunk.CHUNK_SIDELENGTH_SQRD @staticmethod def CreateFromJson(json_string: str) -> 'Chunk': # reading data fields from json d = json.loads(json_string) assert d['datatype'] == 'world_chunk' chunk_x, chunk_y, chunk_z = d['position'] c = Chunk(chunk_x, chunk_y, chunk_z) c.block_data[:, :, :] = np.array(d['data']).reshape( (Chunk.CHUNK_SIDELENGTH, Chunk.CHUNK_SIDELENGTH, Chunk.CHUNK_SIDELENGTH)) return c def toJson(self): # numpy array -> reshape to 1D -> to python list self.json_rep['data'] = self.block_data.reshape(-1).tolist() return json.dumps(self.json_rep) def __init__(self, chunk_x: int, chunk_y: int, chunk_z: int): self.block_data = np.zeros(shape=( Chunk.CHUNK_SIDELENGTH, Chunk.CHUNK_SIDELENGTH, Chunk.CHUNK_SIDELENGTH), dtype=int) self.chunk_position = [chunk_x, chunk_y, chunk_z] self.neighbor_chunks = [None, None, None, None, None, None] self.json_rep = {} # create empty json representation self.json_rep['datatype'] = 'world_chunk' self.json_rep['position'] = [chunk_x, chunk_y, chunk_z] self.json_rep['data'] = None def LinkToChunk(self, chunk: 'Chunk', direction: Direction) -> None: self.neighbor_chunks[direction.value] = chunk chunk.neighbor_chunks[(direction.value + 3) % 6] = self def __str__(self): return self.toJson() def __repr__(self): return self.__str__()