VertexNormalsHelper.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. let nNormals = 0;
  8. const objGeometry = object.geometry;
  9. if ( objGeometry && objGeometry.isGeometry ) {
  10. console.error( 'THREE.VertexNormalsHelper no longer supports Geometry. Use THREE.BufferGeometry instead.' );
  11. return;
  12. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  13. nNormals = objGeometry.attributes.normal.count;
  14. } //
  15. const geometry = new THREE.BufferGeometry();
  16. const positions = new THREE.Float32BufferAttribute( nNormals * 2 * 3, 3 );
  17. geometry.setAttribute( 'position', positions );
  18. super( geometry, new THREE.LineBasicMaterial( {
  19. color,
  20. toneMapped: false
  21. } ) );
  22. this.object = object;
  23. this.size = size;
  24. this.type = 'VertexNormalsHelper'; //
  25. this.matrixAutoUpdate = false;
  26. this.update();
  27. }
  28. update() {
  29. this.object.updateMatrixWorld( true );
  30. _normalMatrix.getNormalMatrix( this.object.matrixWorld );
  31. const matrixWorld = this.object.matrixWorld;
  32. const position = this.geometry.attributes.position; //
  33. const objGeometry = this.object.geometry;
  34. if ( objGeometry && objGeometry.isGeometry ) {
  35. console.error( 'THREE.VertexNormalsHelper no longer supports Geometry. Use THREE.BufferGeometry instead.' );
  36. return;
  37. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  38. const objPos = objGeometry.attributes.position;
  39. const objNorm = objGeometry.attributes.normal;
  40. let idx = 0; // 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. THREE.VertexNormalsHelper = VertexNormalsHelper;
  55. } )();