RoundedBoxBufferGeometry.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import {
  2. BoxBufferGeometry,
  3. Vector3
  4. } from "../../../build/three.module.js";
  5. class RoundedBoxBufferGeometry extends BoxBufferGeometry {
  6. constructor( width = 1, height = 1, depth = 1, segments = 1, radius = 1 ) {
  7. super( width, height, depth, segments, segments, segments );
  8. const geometry2 = this.toNonIndexed();
  9. this.index = null;
  10. this.attributes.position = geometry2.attributes.position;
  11. this.attributes.normal = geometry2.attributes.normal;
  12. this.attributes.uv = geometry2.attributes.uv;
  13. //
  14. const position = new Vector3();
  15. const normal = new Vector3();
  16. const box = new Vector3( width, height, depth ).divideScalar( 2 ).subScalar( radius );
  17. const positions = this.attributes.position.array;
  18. const normals = this.attributes.normal.array;
  19. const uvs = this.attributes.uv.array;
  20. const faceTris = positions.length / 6;
  21. for ( let i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  22. position.fromArray( positions, i );
  23. normal.copy( position ).normalize();
  24. positions[ i + 0 ] = box.x * Math.sign( position.x ) + normal.x * radius;
  25. positions[ i + 1 ] = box.y * Math.sign( position.y ) + normal.y * radius;
  26. positions[ i + 2 ] = box.z * Math.sign( position.z ) + normal.z * radius;
  27. normals[ i + 0 ] = normal.x;
  28. normals[ i + 1 ] = normal.y;
  29. normals[ i + 2 ] = normal.z;
  30. const side = Math.floor( i / faceTris );
  31. switch ( side ) {
  32. case 0: // right
  33. uvs[ j + 0 ] = 0.5 - ( positions[ i + 2 ] / ( depth - radius ) );
  34. uvs[ j + 1 ] = 0.5 + ( positions[ i + 1 ] / ( height - radius ) );
  35. break;
  36. case 1: // left
  37. uvs[ j + 0 ] = 0.5 + ( positions[ i + 2 ] / ( depth - radius ) );
  38. uvs[ j + 1 ] = 0.5 + ( positions[ i + 1 ] / ( height - radius ) );
  39. break;
  40. case 2: // top
  41. uvs[ j + 0 ] = 0.5 + ( positions[ i + 0 ] / ( width - radius ) );
  42. uvs[ j + 1 ] = 0.5 - ( positions[ i + 2 ] / ( depth - radius ) );
  43. break;
  44. case 3: // bottom
  45. uvs[ j + 0 ] = 0.5 + ( positions[ i + 0 ] / ( width - radius ) );
  46. uvs[ j + 1 ] = 0.5 + ( positions[ i + 2 ] / ( depth - radius ) );
  47. break;
  48. case 4: // front
  49. uvs[ j + 0 ] = 0.5 + ( positions[ i + 0 ] / ( width - radius ) );
  50. uvs[ j + 1 ] = 0.5 + ( positions[ i + 1 ] / ( height - radius ) );
  51. break;
  52. case 5: // back
  53. uvs[ j + 0 ] = 0.5 - ( positions[ i + 0 ] / ( width - radius ) );
  54. uvs[ j + 1 ] = 0.5 + ( positions[ i + 1 ] / ( height - radius ) );
  55. break;
  56. }
  57. }
  58. }
  59. }
  60. export { RoundedBoxBufferGeometry };