threejs-voxel-geometry.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. /* global THREE, threejsLessonUtils */
  3. {
  4. const darkMatcher = window.matchMedia('(prefers-color-scheme: dark)');
  5. const isDarkMode = darkMatcher.matches;
  6. const darkColors = {
  7. wire: '#DDD',
  8. };
  9. const lightColors = {
  10. wore: '#000',
  11. };
  12. const colors = isDarkMode ? darkColors : lightColors;
  13. threejsLessonUtils.addDiagrams({
  14. mergedCubes: {
  15. create() {
  16. const geometries = [];
  17. const width = 3;
  18. const height = 2;
  19. const depth = 2;
  20. for (let y = 0; y < height; ++y) {
  21. for (let z = 0; z < depth; ++z) {
  22. for (let x = 0; x < width; ++x) {
  23. const geometry = new THREE.BoxBufferGeometry(1, 1, 1);
  24. geometry.applyMatrix((new THREE.Matrix4()).makeTranslation(x, y, z));
  25. geometries.push(geometry);
  26. }
  27. }
  28. }
  29. const mergedGeometry = THREE.BufferGeometryUtils.mergeBufferGeometries(geometries, false);
  30. const material = new THREE.MeshBasicMaterial({
  31. color: colors.wire,
  32. wireframe: true,
  33. });
  34. const mesh = new THREE.Mesh(mergedGeometry, material);
  35. mesh.position.set(
  36. 0.5 - width / 2,
  37. 0.5 - height / 2,
  38. 0.5 - depth / 2);
  39. const base = new THREE.Object3D();
  40. base.add(mesh);
  41. base.scale.setScalar(3.5);
  42. return base;
  43. },
  44. },
  45. culledCubes: {
  46. create() {
  47. const geometry = new THREE.BoxBufferGeometry(3, 2, 2, 3, 2, 2);
  48. const material = new THREE.MeshBasicMaterial({
  49. color: colors.wire,
  50. wireframe: true,
  51. });
  52. const mesh = new THREE.Mesh(geometry, material);
  53. mesh.scale.setScalar(3.5);
  54. return mesh;
  55. },
  56. },
  57. });
  58. }