VertexNormalsHelper.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import {
  2. BufferGeometry,
  3. Float32BufferAttribute,
  4. LineSegments,
  5. LineBasicMaterial,
  6. Matrix3,
  7. Vector3
  8. } from 'three';
  9. const _v1 = new Vector3();
  10. const _v2 = new Vector3();
  11. const _normalMatrix = new Matrix3();
  12. class VertexNormalsHelper extends LineSegments {
  13. constructor( object, size = 1, color = 0xff0000 ) {
  14. const geometry = new BufferGeometry();
  15. const nNormals = object.geometry.attributes.normal.count;
  16. const positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  17. geometry.setAttribute( 'position', positions );
  18. super( geometry, new LineBasicMaterial( { color, toneMapped: false } ) );
  19. this.object = object;
  20. this.size = size;
  21. this.type = 'VertexNormalsHelper';
  22. //
  23. this.matrixAutoUpdate = false;
  24. this.update();
  25. }
  26. update() {
  27. this.object.updateMatrixWorld( true );
  28. _normalMatrix.getNormalMatrix( this.object.matrixWorld );
  29. const matrixWorld = this.object.matrixWorld;
  30. const position = this.geometry.attributes.position;
  31. //
  32. const objGeometry = this.object.geometry;
  33. if ( objGeometry && objGeometry.isGeometry ) {
  34. console.error( 'THREE.VertexNormalsHelper no longer supports Geometry. Use BufferGeometry instead.' );
  35. return;
  36. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  37. const objPos = objGeometry.attributes.position;
  38. const objNorm = objGeometry.attributes.normal;
  39. let idx = 0;
  40. // for simplicity, ignore index and drawcalls, and render every normal
  41. for ( let j = 0, jl = objPos.count; j < jl; j ++ ) {
  42. _v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  43. _v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  44. _v2.applyMatrix3( _normalMatrix ).normalize().multiplyScalar( this.size ).add( _v1 );
  45. position.setXYZ( idx, _v1.x, _v1.y, _v1.z );
  46. idx = idx + 1;
  47. position.setXYZ( idx, _v2.x, _v2.y, _v2.z );
  48. idx = idx + 1;
  49. }
  50. }
  51. position.needsUpdate = true;
  52. }
  53. }
  54. export { VertexNormalsHelper };