VertexNormalsHelper.js 1.8 KB

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