threejs-voxel-geometry.js 1.7 KB

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