Advertisement
Guest User

Untitled

a guest
Dec 22nd, 2014
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class VoxelRender : MonoBehaviour {
  5. //Expects a cubic number of elements
  6. private string world = "11111111";
  7.  
  8. struct Voxel {
  9. public readonly int x;
  10. public readonly int y;
  11. public readonly int z;
  12.  
  13. public Voxel (int x, int y, int z)
  14. {
  15. this.x = x;
  16. this.y = y;
  17. this.z = z;
  18. }
  19.  
  20. public Voxel add(int x, int y, int z) {
  21. return new Voxel (this.x + x, this.y + y, this.z + z);
  22. }
  23. }
  24.  
  25. void Start() {
  26. DrawWorld (world);
  27. }
  28.  
  29. private void DrawWorld(string world) {
  30. var voxel = new Voxel (0, 0, 0);
  31. var worldDataLength = world.Length;
  32. Debug.Log ("WORLD DATA LENGTH " + worldDataLength);
  33. var worldSize = Mathf.RoundToInt(Mathf.Pow (worldDataLength, (1.0f / 3.0f)));
  34. Debug.Log ("WORLD SIZE " + worldSize);
  35. DrawBoxRecursively (world, worldSize, voxel, worldSize);
  36. }
  37.  
  38. private void DrawBoxRecursively(string world, int worldSize, Voxel lowestXYZ, int size) {
  39. if (IsBoxFilled (world, worldSize, lowestXYZ, size)) {
  40. DrawBox(lowestXYZ, size);
  41. }
  42. else if(size > 1) {
  43. size = size / 2;
  44. var v = lowestXYZ;
  45. var voxels = new Voxel[] {
  46. v.add(0,0,0),
  47. v.add(size, 0, 0),
  48. v.add(0, size, 0),
  49. v.add(0, 0, size),
  50. v.add(size, 0, size),
  51. v.add(size, size, 0),
  52. v.add(0, size, size),
  53. v.add(size, size, size)
  54. };
  55. foreach(var voxel in voxels) {
  56. DrawBoxRecursively(world, worldSize, voxel, size);
  57. }
  58. }
  59. }
  60.  
  61. private void DrawBox(Voxel lowestXYZ, int size) {
  62. var center = new Vector3 ((float)lowestXYZ.x + size * 0.5f, (float)lowestXYZ.y + size * 0.5f, (float)lowestXYZ.z + size * 0.5f);
  63. var transform = GameObject.CreatePrimitive (PrimitiveType.Cube).transform;
  64. transform.position = center;
  65. transform.localScale = new Vector3 (size - 0.1f, size - 0.1f, size - 0.1f);
  66. }
  67.  
  68. private bool IsBoxFilled(string world, int worldSize, Voxel lowestXYZ, int size) {
  69. for(var x = lowestXYZ.x; x < lowestXYZ.x + size; x++) {
  70. for(var y = lowestXYZ.y; y < lowestXYZ.y + size; y++) {
  71. for(var z = lowestXYZ.z; z < lowestXYZ.z + size; z++) {
  72. if(!IsVoxelFilled(world, worldSize, new Voxel(x, y, z))) {
  73. return false;
  74. }
  75. }
  76. }
  77. }
  78. return true;
  79. }
  80.  
  81. private bool IsVoxelFilled(string world, int worldSize, Voxel v) {
  82. var index = worldSize * worldSize * v.x + worldSize * v.y + v.z;
  83. return world[index] == '1';
  84. }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement