threejs-voxel-geometry-culled-faces-with-textures.html 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. <!-- Licensed under a BSD license. See license.html for license -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  7. <title>Three.js - Voxel Geometry - Textures</title>
  8. <style>
  9. body {
  10. margin: 0;
  11. }
  12. #c {
  13. width: 100vw;
  14. height: 100vh;
  15. display: block;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <canvas id="c"></canvas>
  21. </body>
  22. <script src="resources/threejs/r105/three.min.js"></script>
  23. <script src="resources/threejs/r105/js/controls/OrbitControls.js"></script>
  24. <script>
  25. 'use strict';
  26. /* global THREE */
  27. class VoxelWorld {
  28. constructor(options) {
  29. this.cellSize = options.cellSize;
  30. this.tileSize = options.tileSize;
  31. this.tileTextureWidth = options.tileTextureWidth;
  32. this.tileTextureHeight = options.tileTextureHeight;
  33. const {cellSize} = this;
  34. this.cellSliceSize = cellSize * cellSize;
  35. this.cell = new Uint8Array(cellSize * cellSize * cellSize);
  36. }
  37. computeVoxelOffset(x, y, z) {
  38. const {cellSize, cellSliceSize} = this;
  39. const voxelX = THREE.Math.euclideanModulo(x, cellSize) | 0;
  40. const voxelY = THREE.Math.euclideanModulo(y, cellSize) | 0;
  41. const voxelZ = THREE.Math.euclideanModulo(z, cellSize) | 0;
  42. return voxelY * cellSliceSize +
  43. voxelZ * cellSize +
  44. voxelX;
  45. }
  46. getCellForVoxel(x, y, z) {
  47. const {cellSize} = this;
  48. const cellX = Math.floor(x / cellSize);
  49. const cellY = Math.floor(y / cellSize);
  50. const cellZ = Math.floor(z / cellSize);
  51. if (cellX !== 0 || cellY !== 0 || cellZ !== 0) {
  52. return null;
  53. }
  54. return this.cell;
  55. }
  56. setVoxel(x, y, z, v) {
  57. const cell = this.getCellForVoxel(x, y, z);
  58. if (!cell) {
  59. return; // TODO: add a new cell?
  60. }
  61. const voxelOffset = this.computeVoxelOffset(x, y, z);
  62. cell[voxelOffset] = v;
  63. }
  64. getVoxel(x, y, z) {
  65. const cell = this.getCellForVoxel(x, y, z);
  66. if (!cell) {
  67. return 0;
  68. }
  69. const voxelOffset = this.computeVoxelOffset(x, y, z);
  70. return cell[voxelOffset];
  71. }
  72. generateGeometryDataForCell(cellX, cellY, cellZ) {
  73. const {cellSize, tileSize, tileTextureWidth, tileTextureHeight} = this;
  74. const positions = [];
  75. const normals = [];
  76. const uvs = [];
  77. const indices = [];
  78. const startX = cellX * cellSize;
  79. const startY = cellY * cellSize;
  80. const startZ = cellZ * cellSize;
  81. for (let y = 0; y < cellSize; ++y) {
  82. const voxelY = startY + y;
  83. for (let z = 0; z < cellSize; ++z) {
  84. const voxelZ = startZ + z;
  85. for (let x = 0; x < cellSize; ++x) {
  86. const voxelX = startX + x;
  87. const voxel = this.getVoxel(voxelX, voxelY, voxelZ);
  88. if (voxel) {
  89. // voxel 0 is sky (empty) so for UVs we start at 0
  90. const uvVoxel = voxel - 1;
  91. // There is a voxel here but do we need faces for it?
  92. for (const {dir, corners, uvRow} of VoxelWorld.faces) {
  93. const neighbor = this.getVoxel(
  94. voxelX + dir[0],
  95. voxelY + dir[1],
  96. voxelZ + dir[2]);
  97. if (!neighbor) {
  98. // this voxel has no neighbor in this direction so we need a face.
  99. const ndx = positions.length / 3;
  100. for (const {pos, uv} of corners) {
  101. positions.push(pos[0] + x, pos[1] + y, pos[2] + z);
  102. normals.push(...dir);
  103. uvs.push(
  104. (uvVoxel + uv[0]) * tileSize / tileTextureWidth,
  105. 1 - (uvRow + 1 - uv[1]) * tileSize / tileTextureHeight);
  106. }
  107. indices.push(
  108. ndx, ndx + 1, ndx + 2,
  109. ndx + 2, ndx + 1, ndx + 3,
  110. );
  111. }
  112. }
  113. }
  114. }
  115. }
  116. }
  117. return {
  118. positions,
  119. normals,
  120. uvs,
  121. indices,
  122. };
  123. }
  124. }
  125. VoxelWorld.faces = [
  126. { // left
  127. uvRow: 0,
  128. dir: [ -1, 0, 0, ],
  129. corners: [
  130. { pos: [ 0, 1, 0 ], uv: [ 0, 1 ], },
  131. { pos: [ 0, 0, 0 ], uv: [ 0, 0 ], },
  132. { pos: [ 0, 1, 1 ], uv: [ 1, 1 ], },
  133. { pos: [ 0, 0, 1 ], uv: [ 1, 0 ], },
  134. ],
  135. },
  136. { // right
  137. uvRow: 0,
  138. dir: [ 1, 0, 0, ],
  139. corners: [
  140. { pos: [ 1, 1, 1 ], uv: [ 0, 1 ], },
  141. { pos: [ 1, 0, 1 ], uv: [ 0, 0 ], },
  142. { pos: [ 1, 1, 0 ], uv: [ 1, 1 ], },
  143. { pos: [ 1, 0, 0 ], uv: [ 1, 0 ], },
  144. ],
  145. },
  146. { // bottom
  147. uvRow: 1,
  148. dir: [ 0, -1, 0, ],
  149. corners: [
  150. { pos: [ 1, 0, 1 ], uv: [ 1, 0 ], },
  151. { pos: [ 0, 0, 1 ], uv: [ 0, 0 ], },
  152. { pos: [ 1, 0, 0 ], uv: [ 1, 1 ], },
  153. { pos: [ 0, 0, 0 ], uv: [ 0, 1 ], },
  154. ],
  155. },
  156. { // top
  157. uvRow: 2,
  158. dir: [ 0, 1, 0, ],
  159. corners: [
  160. { pos: [ 0, 1, 1 ], uv: [ 1, 1 ], },
  161. { pos: [ 1, 1, 1 ], uv: [ 0, 1 ], },
  162. { pos: [ 0, 1, 0 ], uv: [ 1, 0 ], },
  163. { pos: [ 1, 1, 0 ], uv: [ 0, 0 ], },
  164. ],
  165. },
  166. { // back
  167. uvRow: 0,
  168. dir: [ 0, 0, -1, ],
  169. corners: [
  170. { pos: [ 1, 0, 0 ], uv: [ 0, 0 ], },
  171. { pos: [ 0, 0, 0 ], uv: [ 1, 0 ], },
  172. { pos: [ 1, 1, 0 ], uv: [ 0, 1 ], },
  173. { pos: [ 0, 1, 0 ], uv: [ 1, 1 ], },
  174. ],
  175. },
  176. { // front
  177. uvRow: 0,
  178. dir: [ 0, 0, 1, ],
  179. corners: [
  180. { pos: [ 0, 0, 1 ], uv: [ 0, 0 ], },
  181. { pos: [ 1, 0, 1 ], uv: [ 1, 0 ], },
  182. { pos: [ 0, 1, 1 ], uv: [ 0, 1 ], },
  183. { pos: [ 1, 1, 1 ], uv: [ 1, 1 ], },
  184. ],
  185. },
  186. ];
  187. function main() {
  188. const canvas = document.querySelector('#c');
  189. const renderer = new THREE.WebGLRenderer({canvas});
  190. const cellSize = 32;
  191. const fov = 75;
  192. const aspect = 2; // the canvas default
  193. const near = 0.1;
  194. const far = 1000;
  195. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  196. camera.position.set(-cellSize * .3, cellSize * .8, -cellSize * .3);
  197. const controls = new THREE.OrbitControls(camera, canvas);
  198. controls.target.set(cellSize / 2, cellSize / 3, cellSize / 2);
  199. controls.update();
  200. const scene = new THREE.Scene();
  201. scene.background = new THREE.Color('lightblue');
  202. function addLight(x, y, z) {
  203. const color = 0xFFFFFF;
  204. const intensity = 1;
  205. const light = new THREE.DirectionalLight(color, intensity);
  206. light.position.set(x, y, z);
  207. scene.add(light);
  208. }
  209. addLight(-1, 2, 4);
  210. addLight( 1, -1, -2);
  211. const loader = new THREE.TextureLoader();
  212. const texture = loader.load('resources/images/minecraft/flourish-cc-by-nc-sa.png', render);
  213. texture.magFilter = THREE.NearestFilter;
  214. texture.minFilter = THREE.NearestFilter;
  215. const tileSize = 16;
  216. const tileTextureWidth = 256;
  217. const tileTextureHeight = 64;
  218. const world = new VoxelWorld({
  219. cellSize,
  220. tileSize,
  221. tileTextureWidth,
  222. tileTextureHeight,
  223. });
  224. for (let y = 0; y < cellSize; ++y) {
  225. for (let z = 0; z < cellSize; ++z) {
  226. for (let x = 0; x < cellSize; ++x) {
  227. const height = (Math.sin(x / cellSize * Math.PI * 2) + Math.sin(z / cellSize * Math.PI * 3)) * (cellSize / 6) + (cellSize / 2);
  228. if (y < height) {
  229. world.setVoxel(x, y, z, randInt(1, 17));
  230. }
  231. }
  232. }
  233. }
  234. function randInt(min, max) {
  235. return Math.floor(Math.random() * (max - min) + min);
  236. }
  237. const {positions, normals, uvs, indices} = world.generateGeometryDataForCell(0, 0, 0);
  238. const geometry = new THREE.BufferGeometry();
  239. const material = new THREE.MeshLambertMaterial({
  240. map: texture,
  241. side: THREE.DoubleSide,
  242. alphaTest: 0.1,
  243. transparent: true,
  244. });
  245. const positionNumComponents = 3;
  246. const normalNumComponents = 3;
  247. const uvNumComponents = 2;
  248. geometry.addAttribute(
  249. 'position',
  250. new THREE.BufferAttribute(new Float32Array(positions), positionNumComponents));
  251. geometry.addAttribute(
  252. 'normal',
  253. new THREE.BufferAttribute(new Float32Array(normals), normalNumComponents));
  254. geometry.addAttribute(
  255. 'uv',
  256. new THREE.BufferAttribute(new Float32Array(uvs), uvNumComponents));
  257. geometry.setIndex(indices);
  258. const mesh = new THREE.Mesh(geometry, material);
  259. scene.add(mesh);
  260. function resizeRendererToDisplaySize(renderer) {
  261. const canvas = renderer.domElement;
  262. const width = canvas.clientWidth;
  263. const height = canvas.clientHeight;
  264. const needResize = canvas.width !== width || canvas.height !== height;
  265. if (needResize) {
  266. renderer.setSize(width, height, false);
  267. }
  268. return needResize;
  269. }
  270. let renderRequested = false;
  271. function render() {
  272. renderRequested = undefined;
  273. if (resizeRendererToDisplaySize(renderer)) {
  274. const canvas = renderer.domElement;
  275. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  276. camera.updateProjectionMatrix();
  277. }
  278. controls.update();
  279. renderer.render(scene, camera);
  280. }
  281. render();
  282. function requestRenderIfNotRequested() {
  283. if (!renderRequested) {
  284. renderRequested = true;
  285. requestAnimationFrame(render);
  286. }
  287. }
  288. controls.addEventListener('change', requestRenderIfNotRequested);
  289. window.addEventListener('resize', requestRenderIfNotRequested);
  290. }
  291. main();
  292. </script>
  293. </html>