GTAONode.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705
  1. import { DataTexture, RenderTarget, RepeatWrapping, Vector2, Vector3, TempNode, QuadMesh, NodeMaterial, RendererUtils, RedFormat } from 'three/webgpu';
  2. import { reference, logarithmicDepthToViewZ, viewZToPerspectiveDepth, getNormalFromDepth, getViewPosition, getScreenPositionFromClip, nodeObject, Fn, float, NodeUpdateType, uv, uniform, Loop, vec2, vec3, vec4, int, dot, max, min, pow, abs, If, textureSize, sin, cos, PI, texture, passTexture, mat3, normalize, cross, mix, acos, clamp, interleavedGradientNoise, screenCoordinate, rand } from 'three/tsl';
  3. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  4. const _size = /*@__PURE__*/ new Vector2();
  5. // From Activision GTAO paper: https://www.activision.com/cdn/research/s2016_pbs_activision_occlusion.pptx
  6. const _temporalRotations = [ 60, 300, 180, 240, 120, 0 ];
  7. const _spatialOffsets = [ 0, 0.5, 0.25, 0.75 ];
  8. let _rendererState;
  9. /**
  10. * Post processing node for applying Ground Truth Ambient Occlusion (GTAO) to a scene.
  11. * ```js
  12. * const renderPipeline = new THREE.RenderPipeline( renderer );
  13. *
  14. * // pre-pass for normals and depth
  15. *
  16. * const prePass = pass( scene, camera );
  17. * prePass.setMRT( mrt( {
  18. * output: normalView
  19. * } ) );
  20. *
  21. * const prePassNormal = prePass.getTextureNode();
  22. * const prePassDepth = prePass.getTextureNode( 'depth' );
  23. *
  24. * // scene pass
  25. *
  26. * const scenePass = pass( scene, camera );
  27. *
  28. * // ao
  29. *
  30. * const aoPass = ao( prePassDepth, prePassNormal, camera );
  31. * const aoPassOutput = aoPass.getTextureNode();
  32. *
  33. * // apply the ambient occlusion to the scene
  34. *
  35. * scenePass.contextNode = builtinAOContext( aoPassOutput.sample( screenUV ).r );
  36. *
  37. * renderPipeline.outputNode = scenePass;
  38. * ```
  39. *
  40. * Reference: [Practical Real-Time Strategies for Accurate Indirect Occlusion](https://www.activision.com/cdn/research/Practical_Real_Time_Strategies_for_Accurate_Indirect_Occlusion_NEW%20VERSION_COLOR.pdf).
  41. *
  42. * @augments TempNode
  43. * @three_import import { ao } from 'three/addons/tsl/display/GTAONode.js';
  44. */
  45. class GTAONode extends TempNode {
  46. static get type() {
  47. return 'GTAONode';
  48. }
  49. /**
  50. * Constructs a new GTAO node.
  51. *
  52. * @param {Node<float>} depthNode - A node that represents the scene's depth.
  53. * @param {?Node<vec3>} normalNode - A node that represents the scene's normals.
  54. * @param {Camera} camera - The camera the scene is rendered with.
  55. */
  56. constructor( depthNode, normalNode, camera ) {
  57. super( 'float' );
  58. /**
  59. * A node that represents the scene's depth.
  60. *
  61. * @type {Node<float>}
  62. */
  63. this.depthNode = depthNode;
  64. /**
  65. * A node that represents the scene's normals. If no normals are passed to the
  66. * constructor (because MRT is not available), normals can be automatically
  67. * reconstructed from depth values in the shader.
  68. *
  69. * @type {?Node<vec3>}
  70. */
  71. this.normalNode = normalNode;
  72. /**
  73. * The resolution scale. By default the effect is rendered in full resolution
  74. * for best quality but a value of `0.5` should be sufficient for most scenes.
  75. *
  76. * @type {number}
  77. * @default 1
  78. */
  79. this.resolutionScale = 1;
  80. /**
  81. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders
  82. * its effect once per frame in `updateBefore()`.
  83. *
  84. * @type {string}
  85. * @default 'frame'
  86. */
  87. this.updateBeforeType = NodeUpdateType.FRAME;
  88. /**
  89. * The render target the ambient occlusion is rendered into.
  90. *
  91. * @private
  92. * @type {RenderTarget}
  93. */
  94. this._aoRenderTarget = new RenderTarget( 1, 1, { depthBuffer: false, format: RedFormat } );
  95. this._aoRenderTarget.texture.name = 'GTAONode.AO';
  96. // uniforms
  97. /**
  98. * The radius of the ambient occlusion.
  99. *
  100. * @type {UniformNode<float>}
  101. */
  102. this.radius = uniform( 0.25 );
  103. /**
  104. * The thickness of the ambient occlusion.
  105. *
  106. * @type {UniformNode<float>}
  107. */
  108. this.thickness = uniform( 1 );
  109. /**
  110. * @deprecated since r186. The new distance model "Quadratic Ray Stepping"
  111. * does not need it anymore.
  112. *
  113. * @type {UniformNode<float>}
  114. */
  115. this.distanceExponent = uniform( 1 );
  116. /**
  117. * @deprecated since r186. The new distance model "Quadratic Ray Stepping"
  118. * does not need it anymore.
  119. *
  120. * @type {UniformNode<float>}
  121. */
  122. this.distanceFallOff = uniform( 1 );
  123. /**
  124. * The scale of the ambient occlusion.
  125. *
  126. * @type {UniformNode<float>}
  127. */
  128. this.scale = uniform( 1 );
  129. /**
  130. * How many samples are used to compute the AO.
  131. * A higher value results in better quality but also
  132. * in a more expensive runtime behavior.
  133. *
  134. * Note: Changing this member triggers a shader recompilation.
  135. *
  136. * @type {UniformNode<float>}
  137. */
  138. this.samples = uniform( 16 );
  139. /**
  140. * Whether to use temporal filtering or not. Setting this property to
  141. * `true` requires the usage of `TRAANode`. This will help to reduce noise
  142. * although it introduces typical TAA artifacts like ghosting and temporal
  143. * instabilities.
  144. *
  145. * If setting this property to `false`, a manual denoise via `DenoiseNode`
  146. * might be required.
  147. *
  148. * @type {boolean}
  149. * @default false
  150. */
  151. this.useTemporalFiltering = false;
  152. /**
  153. * The resolution of the effect. Can be scaled via `resolutionScale`.
  154. *
  155. * @private
  156. * @type {UniformNode<vec2>}
  157. */
  158. this._resolution = uniform( new Vector2() );
  159. /**
  160. * The node represents the internal noise texture used by the AO.
  161. *
  162. * @private
  163. * @type {TextureNode}
  164. */
  165. this._noiseNode = texture( generateMagicSquareNoise() );
  166. /**
  167. * Represents the projection matrix of the scene's camera.
  168. *
  169. * @private
  170. * @type {UniformNode<mat4>}
  171. */
  172. this._cameraProjectionMatrix = uniform( camera.projectionMatrix );
  173. /**
  174. * Represents the inverse projection matrix of the scene's camera.
  175. *
  176. * @private
  177. * @type {UniformNode<mat4>}
  178. */
  179. this._cameraProjectionMatrixInverse = uniform( camera.projectionMatrixInverse );
  180. /**
  181. * Represents the near value of the scene's camera.
  182. *
  183. * @private
  184. * @type {ReferenceNode<float>}
  185. */
  186. this._cameraNear = reference( 'near', 'float', camera );
  187. /**
  188. * Represents the far value of the scene's camera.
  189. *
  190. * @private
  191. * @type {ReferenceNode<float>}
  192. */
  193. this._cameraFar = reference( 'far', 'float', camera );
  194. /**
  195. * Temporal direction that influences the rotation angle for each slice.
  196. *
  197. * @private
  198. * @type {UniformNode<float>}
  199. */
  200. this._temporalDirection = uniform( 0 );
  201. /**
  202. * Temporal offset added to the initial ray step.
  203. *
  204. * @private
  205. * @type {UniformNode<float>}
  206. */
  207. this._temporalOffset = uniform( 0 );
  208. /**
  209. * Resolution scale uniform.
  210. *
  211. * @private
  212. * @type {UniformNode<float>}
  213. */
  214. this._resolutionScale = uniform( 0 );
  215. /**
  216. * The TSL function that computes the AO. Required for rebuild.
  217. *
  218. * @private
  219. * @type {?Function}
  220. * @default null
  221. */
  222. this._ao = null;
  223. /**
  224. * The sample count currently baked into the shader.
  225. *
  226. * @private
  227. * @type {number}
  228. */
  229. this._currentSamples = - 1;
  230. /**
  231. * The shared builder context. Required for rebuild.
  232. *
  233. * @private
  234. * @type {?Object}
  235. * @default null
  236. */
  237. this._sharedContext = null;
  238. /**
  239. * The material that is used to render the effect.
  240. *
  241. * @private
  242. * @type {NodeMaterial}
  243. */
  244. this._material = new NodeMaterial();
  245. this._material.name = 'GTAO';
  246. /**
  247. * The result of the effect is represented as a separate texture node.
  248. *
  249. * @private
  250. * @type {PassTextureNode}
  251. */
  252. this._textureNode = passTexture( this, this._aoRenderTarget.texture );
  253. }
  254. /**
  255. * Returns the result of the effect as a texture node.
  256. *
  257. * @return {PassTextureNode} A texture node that represents the result of the effect.
  258. */
  259. getTextureNode() {
  260. return this._textureNode;
  261. }
  262. /**
  263. * Sets the size of the effect.
  264. *
  265. * @param {number} width - The width of the effect.
  266. * @param {number} height - The height of the effect.
  267. */
  268. setSize( width, height ) {
  269. width = Math.round( this.resolutionScale * width );
  270. height = Math.round( this.resolutionScale * height );
  271. this._resolutionScale.value = this.resolutionScale;
  272. this._resolution.value.set( width, height );
  273. this._aoRenderTarget.setSize( width, height );
  274. }
  275. /**
  276. * This method is used to render the effect once per frame.
  277. *
  278. * @param {NodeFrame} frame - The current node frame.
  279. */
  280. updateBefore( frame ) {
  281. const { renderer } = frame;
  282. _rendererState = RendererUtils.resetRendererState( renderer, _rendererState );
  283. // update temporal uniforms
  284. if ( this.useTemporalFiltering === true ) {
  285. const frameId = frame.frameId;
  286. this._temporalDirection.value = _temporalRotations[ frameId % 6 ] / 360;
  287. this._temporalOffset.value = _spatialOffsets[ frameId % 4 ];
  288. } else {
  289. this._temporalDirection.value = 0;
  290. this._temporalOffset.value = 1;
  291. }
  292. // rebuild the material if the sample count has changed
  293. if ( this.samples.value !== this._currentSamples ) {
  294. this._currentSamples = this.samples.value;
  295. this._material.fragmentNode = this._ao().context( this._sharedContext );
  296. this._material.needsUpdate = true;
  297. }
  298. //
  299. const size = renderer.getDrawingBufferSize( _size );
  300. this.setSize( size.width, size.height );
  301. _quadMesh.material = this._material;
  302. _quadMesh.name = 'AO';
  303. // clear
  304. renderer.setClearColor( 0xffffff, 1 );
  305. // ao
  306. renderer.setRenderTarget( this._aoRenderTarget );
  307. _quadMesh.render( renderer );
  308. // restore
  309. RendererUtils.restoreRendererState( renderer, _rendererState );
  310. }
  311. /**
  312. * This method is used to setup the effect's TSL code.
  313. *
  314. * @param {NodeBuilder} builder - The current node builder.
  315. * @return {PassTextureNode}
  316. */
  317. setup( builder ) {
  318. const uvNode = uv();
  319. const linearizeDepth = ( depth ) => {
  320. if ( builder.renderer.logarithmicDepthBuffer === true ) {
  321. const viewZ = logarithmicDepthToViewZ( depth, this._cameraNear, this._cameraFar );
  322. return viewZToPerspectiveDepth( viewZ, this._cameraNear, this._cameraFar );
  323. }
  324. return depth;
  325. };
  326. const sampleDepth = ( uv ) => linearizeDepth( this.depthNode.sample( uv ).r );
  327. const sampleCenterDepth = ( uv ) => {
  328. // Sidestep the nearest-rounding during depth access for the unjittered center pixel to avoid banding
  329. const g = this.depthNode.gather().sample( uv );
  330. const depth = min( min( g.x, g.y ), min( g.z, g.w ) );
  331. return linearizeDepth( depth );
  332. };
  333. const sampleNoise = ( uv ) => this._noiseNode.sample( uv );
  334. const sampleNormal = ( uv ) => ( this.normalNode !== null ) ? this.normalNode.sample( uv ).rgb.normalize() : getNormalFromDepth( uv, this.depthNode.value, this._cameraProjectionMatrixInverse );
  335. this._ao = Fn( () => {
  336. const depth = this._resolutionScale.lessThan( 1 ).select( sampleCenterDepth( uvNode ), sampleDepth( uvNode ) ).toConst();
  337. depth.greaterThanEqual( 1.0 ).discard();
  338. const viewPosition = getViewPosition( uvNode, depth, this._cameraProjectionMatrixInverse ).toConst();
  339. const viewNormal = sampleNormal( uvNode ).toConst();
  340. const radius = this.radius;
  341. const invRadius = radius.reciprocal().toConst();
  342. const viewDir = normalize( viewPosition.xyz.negate() ).toConst();
  343. const clipPosition = this._cameraProjectionMatrix.mul( vec4( viewPosition, 1.0 ) ).toConst();
  344. const noiseResolution = textureSize( this._noiseNode, 0 );
  345. let noiseUv = vec2( uvNode.x, uvNode.y.oneMinus() );
  346. noiseUv = noiseUv.mul( this._resolution.div( noiseResolution ) );
  347. const noiseTexel = sampleNoise( noiseUv );
  348. const randomVec = noiseTexel.xyz.mul( 2.0 ).sub( 1.0 );
  349. const tangent = vec3( randomVec.xy, 0.0 ).normalize();
  350. const bitangent = vec3( tangent.y.mul( - 1.0 ), tangent.x, 0.0 );
  351. const kernelMatrix = mat3( tangent, bitangent, vec3( 0.0, 0.0, 1.0 ) );
  352. // The sample count is baked into the shader so loop unrolling works
  353. const SAMPLES = this.samples.value;
  354. const DIRECTIONS = SAMPLES < 30 ? 3 : 5;
  355. const STEPS = Math.ceil( SAMPLES / DIRECTIONS );
  356. const invSteps = 1 / STEPS;
  357. const ao = float( 0 ).toVar();
  358. // Each iteration analyzes one vertical "slice" of the 3D space around the fragment.
  359. // Per-step phase jitter for spatio-temporal decorrelation.
  360. const noiseJitterIdx = this._temporalDirection.mul( 0.02 );
  361. const stepJitter = interleavedGradientNoise( screenCoordinate.add( this._temporalOffset ) ).add( rand( uvNode.add( noiseJitterIdx ).mul( 2 ).sub( 1 ) ) );
  362. Loop( { start: int( 0 ), end: int( DIRECTIONS ), type: 'int', condition: '<' }, ( { i } ) => {
  363. const angle = float( i ).div( DIRECTIONS ).mul( PI ).add( this._temporalDirection ).toConst();
  364. const sampleDir = kernelMatrix.mul( vec3( cos( angle ), sin( angle ), 0 ) ).toConst();
  365. const clipDirRadius = this._cameraProjectionMatrix.mul( vec4( sampleDir, 0.0 ) ).mul( radius ).toConst();
  366. const sliceBitangent = normalize( cross( sampleDir, viewDir ) ).toConst();
  367. const sliceTangent = cross( sliceBitangent, viewDir ).toConst();
  368. // Project the view normal onto the slice plane (remove component along sliceBitangent).
  369. // The unnormalized length is the foreshortening weight applied at slice integration.
  370. // (Activision GTAO paper, Section 3.2 "Per-pixel sampling".)
  371. const projNRaw = viewNormal.sub( sliceBitangent.mul( dot( viewNormal, sliceBitangent ) ) ).toConst();
  372. const projNLen = projNRaw.length().toConst();
  373. const projN = projNRaw.div( max( projNLen, float( 0.0001 ) ) ).toConst();
  374. // γ — angle of projN within the slice plane, signed by the tangent direction.
  375. const nSin = dot( projN, sliceTangent ).toConst();
  376. const nCos = clamp( dot( projN, viewDir ), 0, 1 ).toConst();
  377. const signNSin = nSin.greaterThanEqual( 0 ).select( float( 1 ), float( - 1 ) );
  378. const angleN = signNSin.mul( acos( nCos ) ).toConst();
  379. const tangentToNormalInSlice = cross( projN, sliceBitangent ).toConst();
  380. const cosHorizon = dot( viewDir, tangentToNormalInSlice ).toConst();
  381. const cosHorizons = vec2( cosHorizon, cosHorizon.negate() ).toVar();
  382. // For each slice, the inner loop performs ray marching to find the horizons.
  383. Loop( { end: int( STEPS ), type: 'int', name: 'j', condition: '<' }, ( { j } ) => {
  384. // Quadratic step distribution ( sampleDist = t² ) concentrates samples in the
  385. // near-field. (Blender's Eevee adaptation)
  386. const t = float( j ).add( 1.0 ).add( stepJitter ).mul( invSteps ).toConst();
  387. const sampleDist = t.mul( t );
  388. const clipOffset = clipDirRadius.mul( sampleDist ).toConst();
  389. // The loop marches in two opposite directions (x and y) along the slice's line to find the horizon on both sides.
  390. // x
  391. const sampleScreenPositionX = getScreenPositionFromClip( clipPosition.add( clipOffset ) ).toConst();
  392. const sampleDepthX = sampleDepth( sampleScreenPositionX ).toConst();
  393. const sampleSceneViewPositionX = getViewPosition( sampleScreenPositionX, sampleDepthX, this._cameraProjectionMatrixInverse ).toConst();
  394. const viewDeltaX = sampleSceneViewPositionX.sub( viewPosition ).toConst();
  395. const lenX = viewDeltaX.length().toConst();
  396. // Manual normalize guards against zero-length delta.
  397. const sHX = dot( viewDir, viewDeltaX ).div( max( lenX, float( 0.0001 ) ) );
  398. // Sphere falloff: ( dist / radius )² fades the sample's horizon contribution
  399. // back toward the prior horizon as it approaches the radius boundary.
  400. // (squared variant of the paper's near-field attenuation;
  401. // Activision GTAO paper, Section 4.3 "Bounding the sampling area")
  402. const distFacX = min( lenX.mul( invRadius ), 1 );
  403. const distFacSqX = distFacX.mul( distFacX );
  404. If( abs( viewDeltaX.z ).lessThan( this.thickness ), () => {
  405. cosHorizons.x.assign( mix( max( cosHorizons.x, sHX ), cosHorizons.x, distFacSqX ) );
  406. } );
  407. // y
  408. const sampleScreenPositionY = getScreenPositionFromClip( clipPosition.sub( clipOffset ) ).toConst();
  409. const sampleDepthY = sampleDepth( sampleScreenPositionY ).toConst();
  410. const sampleSceneViewPositionY = getViewPosition( sampleScreenPositionY, sampleDepthY, this._cameraProjectionMatrixInverse ).toConst();
  411. const viewDeltaY = sampleSceneViewPositionY.sub( viewPosition ).toConst();
  412. const lenY = viewDeltaY.length().toConst();
  413. const sHY = dot( viewDir, viewDeltaY ).div( max( lenY, float( 0.0001 ) ) );
  414. const distFacY = min( lenY.mul( invRadius ), 1 );
  415. const distFacSqY = distFacY.mul( distFacY );
  416. If( abs( viewDeltaY.z ).lessThan( this.thickness ), () => {
  417. cosHorizons.y.assign( mix( max( cosHorizons.y, sHY ), cosHorizons.y, distFacSqY ) );
  418. } );
  419. } );
  420. // Cosine-weighted inner integral, closed-form (Activision GTAO paper, Eq. 7).
  421. // Per horizon h_i: term_i = −cos( 2 h_i − γ ) + cos( γ ) + 2 h_i sin( γ )
  422. // The 0.25 factor is ½ (integral normalization) × ½ (averaging the two horizons).
  423. //
  424. // In this slice setup `sliceTangent = cross( sliceBitangent, viewDir )` works out
  425. // opposite to `sampleDir`, so the +sampleDir samples (cosHorizons.x) live on the
  426. // −T side of the slice and −sampleDir samples (cosHorizons.y) on the +T side.
  427. // γ is signed by +T (sliceTangent), so hPos must read from cosHorizons.y.
  428. const hPos = acos( cosHorizons.y ).toConst();
  429. const hNeg = acos( cosHorizons.x ).negate().toConst();
  430. const termPos = cos( hPos.mul( 2 ).sub( angleN ) ).negate().add( nCos ).add( hPos.mul( 2 ).mul( nSin ) );
  431. const termNeg = cos( hNeg.mul( 2 ).sub( angleN ) ).negate().add( nCos ).add( hNeg.mul( 2 ).mul( nSin ) );
  432. const a = termPos.add( termNeg ).mul( 0.25 );
  433. // |projN| is the foreshortening weight from the per-slice normal projection.
  434. ao.addAssign( projNLen.mul( a ) );
  435. } );
  436. ao.assign( clamp( ao.div( DIRECTIONS ), 0, 1 ) );
  437. ao.assign( pow( ao, this.scale ) );
  438. return ao;
  439. } );
  440. this._sharedContext = builder.getSharedContext();
  441. this._currentSamples = this.samples.value;
  442. this._material.fragmentNode = this._ao().context( this._sharedContext );
  443. this._material.needsUpdate = true;
  444. //
  445. return this._textureNode;
  446. }
  447. /**
  448. * Frees internal resources. This method should be called
  449. * when the effect is no longer required.
  450. */
  451. dispose() {
  452. this._aoRenderTarget.dispose();
  453. this._material.dispose();
  454. }
  455. }
  456. export default GTAONode;
  457. /**
  458. * Generates the AO's noise texture for the given size.
  459. *
  460. * @param {number} [size=5] - The noise size.
  461. * @return {DataTexture} The generated noise texture.
  462. */
  463. function generateMagicSquareNoise( size = 5 ) {
  464. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  465. const magicSquare = generateMagicSquare( noiseSize );
  466. const noiseSquareSize = magicSquare.length;
  467. const data = new Uint8Array( noiseSquareSize * 4 );
  468. for ( let inx = 0; inx < noiseSquareSize; ++ inx ) {
  469. const iAng = magicSquare[ inx ];
  470. const angle = ( 2 * Math.PI * iAng ) / noiseSquareSize;
  471. const randomVec = new Vector3(
  472. Math.cos( angle ),
  473. Math.sin( angle ),
  474. 0
  475. ).normalize();
  476. data[ inx * 4 ] = ( randomVec.x * 0.5 + 0.5 ) * 255;
  477. data[ inx * 4 + 1 ] = ( randomVec.y * 0.5 + 0.5 ) * 255;
  478. data[ inx * 4 + 2 ] = 127;
  479. data[ inx * 4 + 3 ] = 255;
  480. }
  481. const noiseTexture = new DataTexture( data, noiseSize, noiseSize );
  482. noiseTexture.wrapS = RepeatWrapping;
  483. noiseTexture.wrapT = RepeatWrapping;
  484. noiseTexture.needsUpdate = true;
  485. return noiseTexture;
  486. }
  487. /**
  488. * Computes an array of magic square values required to generate the noise texture.
  489. *
  490. * @param {number} size - The noise size.
  491. * @return {Array<number>} The magic square values.
  492. */
  493. function generateMagicSquare( size ) {
  494. const noiseSize = Math.floor( size ) % 2 === 0 ? Math.floor( size ) + 1 : Math.floor( size );
  495. const noiseSquareSize = noiseSize * noiseSize;
  496. const magicSquare = Array( noiseSquareSize ).fill( 0 );
  497. let i = Math.floor( noiseSize / 2 );
  498. let j = noiseSize - 1;
  499. for ( let num = 1; num <= noiseSquareSize; ) {
  500. if ( i === - 1 && j === noiseSize ) {
  501. j = noiseSize - 2;
  502. i = 0;
  503. } else {
  504. if ( j === noiseSize ) {
  505. j = 0;
  506. }
  507. if ( i < 0 ) {
  508. i = noiseSize - 1;
  509. }
  510. }
  511. if ( magicSquare[ i * noiseSize + j ] !== 0 ) {
  512. j -= 2;
  513. i ++;
  514. continue;
  515. } else {
  516. magicSquare[ i * noiseSize + j ] = num ++;
  517. }
  518. j ++;
  519. i --;
  520. }
  521. return magicSquare;
  522. }
  523. /**
  524. * TSL function for creating a Ground Truth Ambient Occlusion (GTAO) effect.
  525. *
  526. * @tsl
  527. * @function
  528. * @param {Node<float>} depthNode - A node that represents the scene's depth.
  529. * @param {?Node<vec3>} normalNode - A node that represents the scene's normals.
  530. * @param {Camera} camera - The camera the scene is rendered with.
  531. * @returns {GTAONode}
  532. */
  533. export const ao = ( depthNode, normalNode, camera ) => new GTAONode( nodeObject( depthNode ), nodeObject( normalNode ), camera );
粤ICP备19079148号