GridHelper.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { LineSegments } from '../objects/LineSegments.js';
  2. import { LineBasicMaterial } from '../materials/LineBasicMaterial.js';
  3. import { Float32BufferAttribute } from '../core/BufferAttribute.js';
  4. import { BufferGeometry } from '../core/BufferGeometry.js';
  5. import { Color } from '../math/Color.js';
  6. /**
  7. * The helper is an object to define grids. Grids are two-dimensional
  8. * arrays of lines.
  9. *
  10. * ```js
  11. * const size = 10;
  12. * const divisions = 10;
  13. *
  14. * const gridHelper = new THREE.GridHelper( size, divisions );
  15. * scene.add( gridHelper );
  16. * ```
  17. *
  18. * @augments LineSegments
  19. */
  20. class GridHelper extends LineSegments {
  21. /**
  22. * Constructs a new grid helper.
  23. *
  24. * @param {number} [size=10] - The size of the grid.
  25. * @param {number} [divisions=10] - The number of divisions across the grid.
  26. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  27. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  28. */
  29. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  30. color1 = new Color( color1 );
  31. color2 = new Color( color2 );
  32. const center = divisions / 2;
  33. const step = size / divisions;
  34. const halfSize = size / 2;
  35. const vertices = [], colors = [];
  36. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  37. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  38. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  39. const color = i === center ? color1 : color2;
  40. color.toArray( colors, j ); j += 3;
  41. color.toArray( colors, j ); j += 3;
  42. color.toArray( colors, j ); j += 3;
  43. color.toArray( colors, j ); j += 3;
  44. }
  45. const geometry = new BufferGeometry();
  46. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  47. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  48. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  49. super( geometry, material );
  50. this.type = 'GridHelper';
  51. }
  52. /**
  53. * Frees the GPU-related resources allocated by this instance. Call this
  54. * method whenever this instance is no longer used in your app.
  55. */
  56. dispose() {
  57. this.geometry.dispose();
  58. this.material.dispose();
  59. }
  60. }
  61. export { GridHelper };