1
0

VertexNormalsHelper.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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 ) {
  34. const objPos = objGeometry.attributes.position;
  35. const objNorm = objGeometry.attributes.normal;
  36. let idx = 0;
  37. // for simplicity, ignore index and drawcalls, and render every normal
  38. for ( let j = 0, jl = objPos.count; j < jl; j ++ ) {
  39. _v1.fromBufferAttribute( objPos, j ).applyMatrix4( matrixWorld );
  40. _v2.fromBufferAttribute( objNorm, j );
  41. _v2.applyMatrix3( _normalMatrix ).normalize().multiplyScalar( this.size ).add( _v1 );
  42. position.setXYZ( idx, _v1.x, _v1.y, _v1.z );
  43. idx = idx + 1;
  44. position.setXYZ( idx, _v2.x, _v2.y, _v2.z );
  45. idx = idx + 1;
  46. }
  47. }
  48. position.needsUpdate = true;
  49. }
  50. dispose() {
  51. this.geometry.dispose();
  52. this.material.dispose();
  53. }
  54. }
  55. export { VertexNormalsHelper };