BumpMapNode.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import TempNode from '../core/TempNode.js';
  2. import { addNodeClass } from '../core/Node.js';
  3. import { uv } from '../accessors/UVNode.js';
  4. import { normalView } from '../accessors/NormalNode.js';
  5. import { positionView } from '../accessors/PositionNode.js';
  6. import { faceDirection } from './FrontFacingNode.js';
  7. import { addNodeElement, tslFn, nodeProxy, float, vec2 } from '../shadernode/ShaderNode.js';
  8. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  9. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  10. const dHdxy_fwd = tslFn( ( { textureNode, bumpScale } ) => {
  11. // It's used to preserve the same TextureNode instance
  12. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  13. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  14. return vec2(
  15. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  16. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  17. ).mul( bumpScale );
  18. } );
  19. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  20. const perturbNormalArb = tslFn( ( inputs ) => {
  21. const { surf_pos, surf_norm, dHdxy } = inputs;
  22. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  23. const vSigmaX = surf_pos.dFdx().normalize();
  24. const vSigmaY = surf_pos.dFdy().normalize();
  25. const vN = surf_norm; // normalized
  26. const R1 = vSigmaY.cross( vN );
  27. const R2 = vN.cross( vSigmaX );
  28. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  29. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  30. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  31. } );
  32. class BumpMapNode extends TempNode {
  33. constructor( textureNode, scaleNode = null ) {
  34. super( 'vec3' );
  35. this.textureNode = textureNode;
  36. this.scaleNode = scaleNode;
  37. }
  38. setup() {
  39. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  40. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  41. return perturbNormalArb( {
  42. surf_pos: positionView,
  43. surf_norm: normalView,
  44. dHdxy
  45. } );
  46. }
  47. }
  48. export default BumpMapNode;
  49. export const bumpMap = nodeProxy( BumpMapNode );
  50. addNodeElement( 'bumpMap', bumpMap );
  51. addNodeClass( 'BumpMapNode', BumpMapNode );