Raymarching.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { varying, vec4, modelWorldMatrixInverse, cameraPosition, positionGeometry, float, Fn, Loop, max, min, vec2, vec3 } from 'three/tsl';
  2. /** @module Raymarching */
  3. const hitBox = /*@__PURE__*/ Fn( ( { orig, dir } ) => {
  4. const box_min = vec3( - 0.5 );
  5. const box_max = vec3( 0.5 );
  6. const inv_dir = dir.reciprocal();
  7. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  8. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  9. const tmin = min( tmin_tmp, tmax_tmp );
  10. const tmax = max( tmin_tmp, tmax_tmp );
  11. const t0 = max( tmin.x, max( tmin.y, tmin.z ) );
  12. const t1 = min( tmax.x, min( tmax.y, tmax.z ) );
  13. return vec2( t0, t1 );
  14. } );
  15. /**
  16. * TSL function for performing raymarching in a box-area using the specified number of steps
  17. * and a callback function.
  18. *
  19. * ```js
  20. * RaymarchingBox( count, ( { positionRay } ) => {
  21. *
  22. * } );
  23. * ```
  24. *
  25. * @tsl
  26. * @function
  27. * @param {number|Node} steps - The number of steps for raymarching.
  28. * @param {Function|FunctionNode} callback - The callback function to execute at each step.
  29. */
  30. export const RaymarchingBox = ( steps, callback ) => {
  31. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  32. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  33. const rayDir = vDirection.normalize();
  34. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  35. bounds.x.greaterThan( bounds.y ).discard();
  36. bounds.assign( vec2( max( bounds.x, 0.0 ), bounds.y ) );
  37. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  38. const delta = float( min( inc.x, min( inc.y, inc.z ) ) ).toVar( 'rayDelta' ); // used 'rayDelta' name in loop
  39. delta.divAssign( float( steps ) );
  40. const positionRay = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  41. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= rayDelta' }, () => {
  42. callback( { positionRay } );
  43. positionRay.addAssign( rayDir.mul( delta ) );
  44. } );
  45. };
粤ICP备19079148号