InstanceNode.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import Node from '../core/Node.js';
  2. import {
  3. vec3,
  4. mat3,
  5. mul,
  6. assign,
  7. buffer,
  8. element,
  9. dot,
  10. div,
  11. temp,
  12. instanceIndex,
  13. positionLocal,
  14. normalLocal
  15. } from '../shadernode/ShaderNodeBaseElements.js';
  16. class InstanceNode extends Node {
  17. constructor( instanceMesh ) {
  18. super( 'void' );
  19. this.instanceMesh = instanceMesh;
  20. //
  21. const instanceBufferNode = buffer( instanceMesh.instanceMatrix.array, 'mat4', instanceMesh.count );
  22. this.instanceMatrixNode = temp( element( instanceBufferNode, instanceIndex ) ); // @TODO: a possible caching issue here?
  23. }
  24. generate( builder ) {
  25. const { instanceMatrixNode } = this;
  26. // POSITION
  27. const instancePosition = mul( instanceMatrixNode, positionLocal ).xyz;
  28. // NORMAL
  29. const m = mat3( instanceMatrixNode[ 0 ].xyz, instanceMatrixNode[ 1 ].xyz, instanceMatrixNode[ 2 ].xyz );
  30. const transformedNormal = div( normalLocal, vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) ) );
  31. const instanceNormal = mul( m, transformedNormal ).xyz;
  32. // ASSIGNS
  33. assign( positionLocal, instancePosition ).build( builder );
  34. assign( normalLocal, instanceNormal ).build( builder );
  35. }
  36. }
  37. export default InstanceNode;