Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- public class VoxelRender : MonoBehaviour {
- //Expects a cubic number of elements
- private string world = "11111111";
- struct Voxel {
- public readonly int x;
- public readonly int y;
- public readonly int z;
- public Voxel (int x, int y, int z)
- {
- this.x = x;
- this.y = y;
- this.z = z;
- }
- public Voxel add(int x, int y, int z) {
- return new Voxel (this.x + x, this.y + y, this.z + z);
- }
- }
- void Start() {
- DrawWorld (world);
- }
- private void DrawWorld(string world) {
- var voxel = new Voxel (0, 0, 0);
- var worldDataLength = world.Length;
- Debug.Log ("WORLD DATA LENGTH " + worldDataLength);
- var worldSize = Mathf.RoundToInt(Mathf.Pow (worldDataLength, (1.0f / 3.0f)));
- Debug.Log ("WORLD SIZE " + worldSize);
- DrawBoxRecursively (world, worldSize, voxel, worldSize);
- }
- private void DrawBoxRecursively(string world, int worldSize, Voxel lowestXYZ, int size) {
- if (IsBoxFilled (world, worldSize, lowestXYZ, size)) {
- DrawBox(lowestXYZ, size);
- }
- else if(size > 1) {
- size = size / 2;
- var v = lowestXYZ;
- var voxels = new Voxel[] {
- v.add(0,0,0),
- v.add(size, 0, 0),
- v.add(0, size, 0),
- v.add(0, 0, size),
- v.add(size, 0, size),
- v.add(size, size, 0),
- v.add(0, size, size),
- v.add(size, size, size)
- };
- foreach(var voxel in voxels) {
- DrawBoxRecursively(world, worldSize, voxel, size);
- }
- }
- }
- private void DrawBox(Voxel lowestXYZ, int size) {
- var center = new Vector3 ((float)lowestXYZ.x + size * 0.5f, (float)lowestXYZ.y + size * 0.5f, (float)lowestXYZ.z + size * 0.5f);
- var transform = GameObject.CreatePrimitive (PrimitiveType.Cube).transform;
- transform.position = center;
- transform.localScale = new Vector3 (size - 0.1f, size - 0.1f, size - 0.1f);
- }
- private bool IsBoxFilled(string world, int worldSize, Voxel lowestXYZ, int size) {
- for(var x = lowestXYZ.x; x < lowestXYZ.x + size; x++) {
- for(var y = lowestXYZ.y; y < lowestXYZ.y + size; y++) {
- for(var z = lowestXYZ.z; z < lowestXYZ.z + size; z++) {
- if(!IsVoxelFilled(world, worldSize, new Voxel(x, y, z))) {
- return false;
- }
- }
- }
- }
- return true;
- }
- private bool IsVoxelFilled(string world, int worldSize, Voxel v) {
- var index = worldSize * worldSize * v.x + worldSize * v.y + v.z;
- return world[index] == '1';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement