voxel-geometry-culled-faces-with-textures.html 9.2 KB

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