voxel-geometry-culled-faces-ui.html 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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 - UI</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. #ui {
  19. position: absolute;
  20. left: 10px;
  21. top: 10px;
  22. background: rgba(0, 0, 0, 0.8);
  23. padding: 5px;
  24. }
  25. #ui input[type=radio] {
  26. width: 0;
  27. height: 0;
  28. display: none;
  29. }
  30. #ui input[type=radio] + label {
  31. background-image: url('resources/images/minecraft/flourish-cc-by-nc-sa.png');
  32. background-size: 1600% 400%;
  33. image-rendering: pixelated;
  34. width: 64px;
  35. height: 64px;
  36. display: inline-block;
  37. }
  38. #ui input[type=radio]:checked + label {
  39. outline: 3px solid red;
  40. }
  41. @media (max-width: 600px), (max-height: 600px) {
  42. #ui input[type=radio] + label {
  43. width: 32px;
  44. height: 32px;
  45. }
  46. }
  47. </style>
  48. </head>
  49. <body>
  50. <canvas id="c"></canvas>
  51. <div id="ui">
  52. <div class="tiles">
  53. <input type="radio" name="voxel" id="voxel1" value="1"><label for="voxel1" style="background-position: -0% -0%"></label>
  54. <input type="radio" name="voxel" id="voxel2" value="2"><label for="voxel2" style="background-position: -100% -0%"></label>
  55. <input type="radio" name="voxel" id="voxel3" value="3"><label for="voxel3" style="background-position: -200% -0%"></label>
  56. <input type="radio" name="voxel" id="voxel4" value="4"><label for="voxel4" style="background-position: -300% -0%"></label>
  57. <input type="radio" name="voxel" id="voxel5" value="5"><label for="voxel5" style="background-position: -400% -0%"></label>
  58. <input type="radio" name="voxel" id="voxel6" value="6"><label for="voxel6" style="background-position: -500% -0%"></label>
  59. <input type="radio" name="voxel" id="voxel7" value="7"><label for="voxel7" style="background-position: -600% -0%"></label>
  60. <input type="radio" name="voxel" id="voxel8" value="8"><label for="voxel8" style="background-position: -700% -0%"></label>
  61. </div>
  62. <div class="tiles">
  63. <input type="radio" name="voxel" id="voxel9" value="9" ><label for="voxel9" style="background-position: -800% -0%"></label>
  64. <input type="radio" name="voxel" id="voxel10" value="10"><label for="voxel10" style="background-position: -900% -0%"></label>
  65. <input type="radio" name="voxel" id="voxel11" value="11"><label for="voxel11" style="background-position: -1000% -0%"></label>
  66. <input type="radio" name="voxel" id="voxel12" value="12"><label for="voxel12" style="background-position: -1100% -0%"></label>
  67. <input type="radio" name="voxel" id="voxel13" value="13"><label for="voxel13" style="background-position: -1200% -0%"></label>
  68. <input type="radio" name="voxel" id="voxel14" value="14"><label for="voxel14" style="background-position: -1300% -0%"></label>
  69. <input type="radio" name="voxel" id="voxel15" value="15"><label for="voxel15" style="background-position: -1400% -0%"></label>
  70. <input type="radio" name="voxel" id="voxel16" value="16"><label for="voxel16" style="background-position: -1500% -0%"></label>
  71. </div>
  72. </div>
  73. </body>
  74. <script type="module">
  75. import * as THREE from '../../build/three.module.js';
  76. import {OrbitControls} from '../../examples/jsm/controls/OrbitControls.js';
  77. class VoxelWorld {
  78. constructor(options) {
  79. this.cellSize = options.cellSize;
  80. this.tileSize = options.tileSize;
  81. this.tileTextureWidth = options.tileTextureWidth;
  82. this.tileTextureHeight = options.tileTextureHeight;
  83. const {cellSize} = this;
  84. this.cellSliceSize = cellSize * cellSize;
  85. this.cells = {};
  86. }
  87. computeVoxelOffset(x, y, z) {
  88. const {cellSize, cellSliceSize} = this;
  89. const voxelX = THREE.MathUtils.euclideanModulo(x, cellSize) | 0;
  90. const voxelY = THREE.MathUtils.euclideanModulo(y, cellSize) | 0;
  91. const voxelZ = THREE.MathUtils.euclideanModulo(z, cellSize) | 0;
  92. return voxelY * cellSliceSize +
  93. voxelZ * cellSize +
  94. voxelX;
  95. }
  96. computeCellId(x, y, z) {
  97. const {cellSize} = this;
  98. const cellX = Math.floor(x / cellSize);
  99. const cellY = Math.floor(y / cellSize);
  100. const cellZ = Math.floor(z / cellSize);
  101. return `${cellX},${cellY},${cellZ}`;
  102. }
  103. addCellForVoxel(x, y, z) {
  104. const cellId = this.computeCellId(x, y, z);
  105. let cell = this.cells[cellId];
  106. if (!cell) {
  107. const {cellSize} = this;
  108. cell = new Uint8Array(cellSize * cellSize * cellSize);
  109. this.cells[cellId] = cell;
  110. }
  111. return cell;
  112. }
  113. getCellForVoxel(x, y, z) {
  114. return this.cells[this.computeCellId(x, y, z)];
  115. }
  116. setVoxel(x, y, z, v, addCell = true) {
  117. let cell = this.getCellForVoxel(x, y, z);
  118. if (!cell) {
  119. if (!addCell) {
  120. return;
  121. }
  122. cell = this.addCellForVoxel(x, y, z);
  123. }
  124. const voxelOffset = this.computeVoxelOffset(x, y, z);
  125. cell[voxelOffset] = v;
  126. }
  127. getVoxel(x, y, z) {
  128. const cell = this.getCellForVoxel(x, y, z);
  129. if (!cell) {
  130. return 0;
  131. }
  132. const voxelOffset = this.computeVoxelOffset(x, y, z);
  133. return cell[voxelOffset];
  134. }
  135. generateGeometryDataForCell(cellX, cellY, cellZ) {
  136. const {cellSize, tileSize, tileTextureWidth, tileTextureHeight} = this;
  137. const positions = [];
  138. const normals = [];
  139. const uvs = [];
  140. const indices = [];
  141. const startX = cellX * cellSize;
  142. const startY = cellY * cellSize;
  143. const startZ = cellZ * cellSize;
  144. for (let y = 0; y < cellSize; ++y) {
  145. const voxelY = startY + y;
  146. for (let z = 0; z < cellSize; ++z) {
  147. const voxelZ = startZ + z;
  148. for (let x = 0; x < cellSize; ++x) {
  149. const voxelX = startX + x;
  150. const voxel = this.getVoxel(voxelX, voxelY, voxelZ);
  151. if (voxel) {
  152. // voxel 0 is sky (empty) so for UVs we start at 0
  153. const uvVoxel = voxel - 1;
  154. // There is a voxel here but do we need faces for it?
  155. for (const {dir, corners, uvRow} of VoxelWorld.faces) {
  156. const neighbor = this.getVoxel(
  157. voxelX + dir[0],
  158. voxelY + dir[1],
  159. voxelZ + dir[2]);
  160. if (!neighbor) {
  161. // this voxel has no neighbor in this direction so we need a face.
  162. const ndx = positions.length / 3;
  163. for (const {pos, uv} of corners) {
  164. positions.push(pos[0] + x, pos[1] + y, pos[2] + z);
  165. normals.push(...dir);
  166. uvs.push(
  167. (uvVoxel + uv[0]) * tileSize / tileTextureWidth,
  168. 1 - (uvRow + 1 - uv[1]) * tileSize / tileTextureHeight);
  169. }
  170. indices.push(
  171. ndx, ndx + 1, ndx + 2,
  172. ndx + 2, ndx + 1, ndx + 3,
  173. );
  174. }
  175. }
  176. }
  177. }
  178. }
  179. }
  180. return {
  181. positions,
  182. normals,
  183. uvs,
  184. indices,
  185. };
  186. }
  187. // from
  188. // https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.42.3443&rep=rep1&type=pdf
  189. intersectRay(start, end) {
  190. let dx = end.x - start.x;
  191. let dy = end.y - start.y;
  192. let dz = end.z - start.z;
  193. const lenSq = dx * dx + dy * dy + dz * dz;
  194. const len = Math.sqrt(lenSq);
  195. dx /= len;
  196. dy /= len;
  197. dz /= len;
  198. let t = 0.0;
  199. let ix = Math.floor(start.x);
  200. let iy = Math.floor(start.y);
  201. let iz = Math.floor(start.z);
  202. const stepX = (dx > 0) ? 1 : -1;
  203. const stepY = (dy > 0) ? 1 : -1;
  204. const stepZ = (dz > 0) ? 1 : -1;
  205. const txDelta = Math.abs(1 / dx);
  206. const tyDelta = Math.abs(1 / dy);
  207. const tzDelta = Math.abs(1 / dz);
  208. const xDist = (stepX > 0) ? (ix + 1 - start.x) : (start.x - ix);
  209. const yDist = (stepY > 0) ? (iy + 1 - start.y) : (start.y - iy);
  210. const zDist = (stepZ > 0) ? (iz + 1 - start.z) : (start.z - iz);
  211. // location of nearest voxel boundary, in units of t
  212. let txMax = (txDelta < Infinity) ? txDelta * xDist : Infinity;
  213. let tyMax = (tyDelta < Infinity) ? tyDelta * yDist : Infinity;
  214. let tzMax = (tzDelta < Infinity) ? tzDelta * zDist : Infinity;
  215. let steppedIndex = -1;
  216. // main loop along raycast vector
  217. while (t <= len) {
  218. const voxel = this.getVoxel(ix, iy, iz);
  219. if (voxel) {
  220. return {
  221. position: [
  222. start.x + t * dx,
  223. start.y + t * dy,
  224. start.z + t * dz,
  225. ],
  226. normal: [
  227. steppedIndex === 0 ? -stepX : 0,
  228. steppedIndex === 1 ? -stepY : 0,
  229. steppedIndex === 2 ? -stepZ : 0,
  230. ],
  231. voxel,
  232. };
  233. }
  234. // advance t to next nearest voxel boundary
  235. if (txMax < tyMax) {
  236. if (txMax < tzMax) {
  237. ix += stepX;
  238. t = txMax;
  239. txMax += txDelta;
  240. steppedIndex = 0;
  241. } else {
  242. iz += stepZ;
  243. t = tzMax;
  244. tzMax += tzDelta;
  245. steppedIndex = 2;
  246. }
  247. } else {
  248. if (tyMax < tzMax) {
  249. iy += stepY;
  250. t = tyMax;
  251. tyMax += tyDelta;
  252. steppedIndex = 1;
  253. } else {
  254. iz += stepZ;
  255. t = tzMax;
  256. tzMax += tzDelta;
  257. steppedIndex = 2;
  258. }
  259. }
  260. }
  261. return null;
  262. }
  263. }
  264. VoxelWorld.faces = [
  265. { // left
  266. uvRow: 0,
  267. dir: [ -1, 0, 0, ],
  268. corners: [
  269. { pos: [ 0, 1, 0 ], uv: [ 0, 1 ], },
  270. { pos: [ 0, 0, 0 ], uv: [ 0, 0 ], },
  271. { pos: [ 0, 1, 1 ], uv: [ 1, 1 ], },
  272. { pos: [ 0, 0, 1 ], uv: [ 1, 0 ], },
  273. ],
  274. },
  275. { // right
  276. uvRow: 0,
  277. dir: [ 1, 0, 0, ],
  278. corners: [
  279. { pos: [ 1, 1, 1 ], uv: [ 0, 1 ], },
  280. { pos: [ 1, 0, 1 ], uv: [ 0, 0 ], },
  281. { pos: [ 1, 1, 0 ], uv: [ 1, 1 ], },
  282. { pos: [ 1, 0, 0 ], uv: [ 1, 0 ], },
  283. ],
  284. },
  285. { // bottom
  286. uvRow: 1,
  287. dir: [ 0, -1, 0, ],
  288. corners: [
  289. { pos: [ 1, 0, 1 ], uv: [ 1, 0 ], },
  290. { pos: [ 0, 0, 1 ], uv: [ 0, 0 ], },
  291. { pos: [ 1, 0, 0 ], uv: [ 1, 1 ], },
  292. { pos: [ 0, 0, 0 ], uv: [ 0, 1 ], },
  293. ],
  294. },
  295. { // top
  296. uvRow: 2,
  297. dir: [ 0, 1, 0, ],
  298. corners: [
  299. { pos: [ 0, 1, 1 ], uv: [ 1, 1 ], },
  300. { pos: [ 1, 1, 1 ], uv: [ 0, 1 ], },
  301. { pos: [ 0, 1, 0 ], uv: [ 1, 0 ], },
  302. { pos: [ 1, 1, 0 ], uv: [ 0, 0 ], },
  303. ],
  304. },
  305. { // back
  306. uvRow: 0,
  307. dir: [ 0, 0, -1, ],
  308. corners: [
  309. { pos: [ 1, 0, 0 ], uv: [ 0, 0 ], },
  310. { pos: [ 0, 0, 0 ], uv: [ 1, 0 ], },
  311. { pos: [ 1, 1, 0 ], uv: [ 0, 1 ], },
  312. { pos: [ 0, 1, 0 ], uv: [ 1, 1 ], },
  313. ],
  314. },
  315. { // front
  316. uvRow: 0,
  317. dir: [ 0, 0, 1, ],
  318. corners: [
  319. { pos: [ 0, 0, 1 ], uv: [ 0, 0 ], },
  320. { pos: [ 1, 0, 1 ], uv: [ 1, 0 ], },
  321. { pos: [ 0, 1, 1 ], uv: [ 0, 1 ], },
  322. { pos: [ 1, 1, 1 ], uv: [ 1, 1 ], },
  323. ],
  324. },
  325. ];
  326. function main() {
  327. const canvas = document.querySelector('#c');
  328. const renderer = new THREE.WebGLRenderer({canvas});
  329. const cellSize = 32;
  330. const fov = 75;
  331. const aspect = 2; // the canvas default
  332. const near = 0.1;
  333. const far = 1000;
  334. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  335. camera.position.set(-cellSize * .3, cellSize * .8, -cellSize * .3);
  336. const controls = new OrbitControls(camera, canvas);
  337. controls.target.set(cellSize / 2, cellSize / 3, cellSize / 2);
  338. controls.update();
  339. const scene = new THREE.Scene();
  340. scene.background = new THREE.Color('lightblue');
  341. const tileSize = 16;
  342. const tileTextureWidth = 256;
  343. const tileTextureHeight = 64;
  344. const loader = new THREE.TextureLoader();
  345. const texture = loader.load('resources/images/minecraft/flourish-cc-by-nc-sa.png', render);
  346. texture.magFilter = THREE.NearestFilter;
  347. texture.minFilter = THREE.NearestFilter;
  348. function addLight(x, y, z) {
  349. const color = 0xFFFFFF;
  350. const intensity = 1;
  351. const light = new THREE.DirectionalLight(color, intensity);
  352. light.position.set(x, y, z);
  353. scene.add(light);
  354. }
  355. addLight(-1, 2, 4);
  356. addLight( 1, -1, -2);
  357. const world = new VoxelWorld({
  358. cellSize,
  359. tileSize,
  360. tileTextureWidth,
  361. tileTextureHeight,
  362. });
  363. const material = new THREE.MeshLambertMaterial({
  364. map: texture,
  365. side: THREE.DoubleSide,
  366. alphaTest: 0.1,
  367. transparent: true,
  368. });
  369. const cellIdToMesh = {};
  370. function updateCellGeometry(x, y, z) {
  371. const cellX = Math.floor(x / cellSize);
  372. const cellY = Math.floor(y / cellSize);
  373. const cellZ = Math.floor(z / cellSize);
  374. const cellId = world.computeCellId(x, y, z);
  375. let mesh = cellIdToMesh[cellId];
  376. const geometry = mesh ? mesh.geometry : new THREE.BufferGeometry();
  377. const {positions, normals, uvs, indices} = world.generateGeometryDataForCell(cellX, cellY, cellZ);
  378. const positionNumComponents = 3;
  379. geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(positions), positionNumComponents));
  380. const normalNumComponents = 3;
  381. geometry.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), normalNumComponents));
  382. const uvNumComponents = 2;
  383. geometry.setAttribute('uv', new THREE.BufferAttribute(new Float32Array(uvs), uvNumComponents));
  384. geometry.setIndex(indices);
  385. geometry.computeBoundingSphere();
  386. if (!mesh) {
  387. mesh = new THREE.Mesh(geometry, material);
  388. mesh.name = cellId;
  389. cellIdToMesh[cellId] = mesh;
  390. scene.add(mesh);
  391. mesh.position.set(cellX * cellSize, cellY * cellSize, cellZ * cellSize);
  392. }
  393. }
  394. const neighborOffsets = [
  395. [ 0, 0, 0], // self
  396. [-1, 0, 0], // left
  397. [ 1, 0, 0], // right
  398. [ 0, -1, 0], // down
  399. [ 0, 1, 0], // up
  400. [ 0, 0, -1], // back
  401. [ 0, 0, 1], // front
  402. ];
  403. function updateVoxelGeometry(x, y, z) {
  404. const updatedCellIds = {};
  405. for (const offset of neighborOffsets) {
  406. const ox = x + offset[0];
  407. const oy = y + offset[1];
  408. const oz = z + offset[2];
  409. const cellId = world.computeCellId(ox, oy, oz);
  410. if (!updatedCellIds[cellId]) {
  411. updatedCellIds[cellId] = true;
  412. updateCellGeometry(ox, oy, oz);
  413. }
  414. }
  415. }
  416. for (let y = 0; y < cellSize; ++y) {
  417. for (let z = 0; z < cellSize; ++z) {
  418. for (let x = 0; x < cellSize; ++x) {
  419. const height = (Math.sin(x / cellSize * Math.PI * 2) + Math.sin(z / cellSize * Math.PI * 3)) * (cellSize / 6) + (cellSize / 2);
  420. if (y < height) {
  421. world.setVoxel(x, y, z, randInt(1, 17));
  422. }
  423. }
  424. }
  425. }
  426. function randInt(min, max) {
  427. return Math.floor(Math.random() * (max - min) + min);
  428. }
  429. updateVoxelGeometry(1, 1, 1); // 0,0,0 will generate
  430. function resizeRendererToDisplaySize(renderer) {
  431. const canvas = renderer.domElement;
  432. const width = canvas.clientWidth;
  433. const height = canvas.clientHeight;
  434. const needResize = canvas.width !== width || canvas.height !== height;
  435. if (needResize) {
  436. renderer.setSize(width, height, false);
  437. }
  438. return needResize;
  439. }
  440. let renderRequested = false;
  441. function render() {
  442. renderRequested = undefined;
  443. if (resizeRendererToDisplaySize(renderer)) {
  444. const canvas = renderer.domElement;
  445. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  446. camera.updateProjectionMatrix();
  447. }
  448. controls.update();
  449. renderer.render(scene, camera);
  450. }
  451. render();
  452. function requestRenderIfNotRequested() {
  453. if (!renderRequested) {
  454. renderRequested = true;
  455. requestAnimationFrame(render);
  456. }
  457. }
  458. let currentVoxel = 0;
  459. let currentId;
  460. document.querySelectorAll('#ui .tiles input[type=radio][name=voxel]').forEach((elem) => {
  461. elem.addEventListener('click', allowUncheck);
  462. });
  463. function allowUncheck() {
  464. if (this.id === currentId) {
  465. this.checked = false;
  466. currentId = undefined;
  467. currentVoxel = 0;
  468. } else {
  469. currentId = this.id;
  470. currentVoxel = parseInt(this.value);
  471. }
  472. }
  473. function getCanvasRelativePosition(event) {
  474. const rect = canvas.getBoundingClientRect();
  475. return {
  476. x: (event.clientX - rect.left) * canvas.width / rect.width,
  477. y: (event.clientY - rect.top ) * canvas.height / rect.height,
  478. };
  479. }
  480. function placeVoxel(event) {
  481. const pos = getCanvasRelativePosition(event);
  482. const x = (pos.x / canvas.width ) * 2 - 1;
  483. const y = (pos.y / canvas.height) * -2 + 1; // note we flip Y
  484. const start = new THREE.Vector3();
  485. const end = new THREE.Vector3();
  486. start.setFromMatrixPosition(camera.matrixWorld);
  487. end.set(x, y, 1).unproject(camera);
  488. const intersection = world.intersectRay(start, end);
  489. if (intersection) {
  490. const voxelId = event.shiftKey ? 0 : currentVoxel;
  491. // the intersection point is on the face. That means
  492. // the math imprecision could put us on either side of the face.
  493. // so go half a normal into the voxel if removing (currentVoxel = 0)
  494. // our out of the voxel if adding (currentVoxel > 0)
  495. const pos = intersection.position.map((v, ndx) => {
  496. return v + intersection.normal[ndx] * (voxelId > 0 ? 0.5 : -0.5);
  497. });
  498. world.setVoxel(...pos, voxelId);
  499. updateVoxelGeometry(...pos);
  500. requestRenderIfNotRequested();
  501. }
  502. }
  503. const mouse = {
  504. x: 0,
  505. y: 0,
  506. };
  507. function recordStartPosition(event) {
  508. mouse.x = event.clientX;
  509. mouse.y = event.clientY;
  510. mouse.moveX = 0;
  511. mouse.moveY = 0;
  512. }
  513. function recordMovement(event) {
  514. mouse.moveX += Math.abs(mouse.x - event.clientX);
  515. mouse.moveY += Math.abs(mouse.y - event.clientY);
  516. }
  517. function placeVoxelIfNoMovement(event) {
  518. if (mouse.moveX < 5 && mouse.moveY < 5) {
  519. placeVoxel(event);
  520. }
  521. window.removeEventListener('pointermove', recordMovement);
  522. window.removeEventListener('pointerup', placeVoxelIfNoMovement);
  523. }
  524. canvas.addEventListener('pointerdown', (event) => {
  525. event.preventDefault();
  526. recordStartPosition(event);
  527. window.addEventListener('pointermove', recordMovement);
  528. window.addEventListener('pointerup', placeVoxelIfNoMovement);
  529. }, {passive: false});
  530. canvas.addEventListener('touchstart', (event) => {
  531. // prevent scrolling
  532. event.preventDefault();
  533. }, {passive: false});
  534. controls.addEventListener('change', requestRenderIfNotRequested);
  535. window.addEventListener('resize', requestRenderIfNotRequested);
  536. }
  537. main();
  538. </script>
  539. </html>