SSAOPass.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. import {
  2. AddEquation,
  3. Color,
  4. CustomBlending,
  5. DataTexture,
  6. DepthTexture,
  7. DstAlphaFactor,
  8. DstColorFactor,
  9. FloatType,
  10. HalfFloatType,
  11. MathUtils,
  12. MeshNormalMaterial,
  13. NearestFilter,
  14. NoBlending,
  15. RedFormat,
  16. DepthStencilFormat,
  17. UnsignedInt248Type,
  18. RepeatWrapping,
  19. ShaderMaterial,
  20. UniformsUtils,
  21. Vector3,
  22. WebGLRenderTarget,
  23. ZeroFactor
  24. } from 'three';
  25. import { Pass, FullScreenQuad } from './Pass.js';
  26. import { SimplexNoise } from '../math/SimplexNoise.js';
  27. import { SSAOBlurShader, SSAODepthShader, SSAOShader } from '../shaders/SSAOShader.js';
  28. import { CopyShader } from '../shaders/CopyShader.js';
  29. /**
  30. * A pass for a basic SSAO effect.
  31. *
  32. * {@link SAOPass} and {@link GTAPass} produce a more advanced AO but are also
  33. * more expensive.
  34. *
  35. * ```js
  36. * const ssaoPass = new SSAOPass( scene, camera, width, height );
  37. * composer.addPass( ssaoPass );
  38. * ```
  39. *
  40. * @augments Pass
  41. * @three_import import { SSAOPass } from 'three/addons/postprocessing/SSAOPass.js';
  42. */
  43. class SSAOPass extends Pass {
  44. /**
  45. * Constructs a new SSAO pass.
  46. *
  47. * @param {Scene} scene - The scene to compute the AO for.
  48. * @param {Camera} camera - The camera.
  49. * @param {number} [width=512] - The width of the effect.
  50. * @param {number} [height=512] - The height of the effect.
  51. * @param {number} [kernelSize=32] - The kernel size.
  52. */
  53. constructor( scene, camera, width = 512, height = 512, kernelSize = 32 ) {
  54. super();
  55. /**
  56. * The width of the effect.
  57. *
  58. * @type {number}
  59. * @default 512
  60. */
  61. this.width = width;
  62. /**
  63. * The height of the effect.
  64. *
  65. * @type {number}
  66. * @default 512
  67. */
  68. this.height = height;
  69. /**
  70. * Overwritten to perform a clear operation by default.
  71. *
  72. * @type {boolean}
  73. * @default true
  74. */
  75. this.clear = true;
  76. /**
  77. * Overwritten to disable the swap.
  78. *
  79. * @type {boolean}
  80. * @default false
  81. */
  82. this.needsSwap = false;
  83. /**
  84. * The camera.
  85. *
  86. * @type {Camera}
  87. */
  88. this.camera = camera;
  89. /**
  90. * The scene to render the AO for.
  91. *
  92. * @type {Scene}
  93. */
  94. this.scene = scene;
  95. /**
  96. * The kernel radius controls how wide the
  97. * AO spreads.
  98. *
  99. * @type {number}
  100. * @default 8
  101. */
  102. this.kernelRadius = 8;
  103. this.kernel = [];
  104. this.noiseTexture = null;
  105. /**
  106. * The output configuration.
  107. *
  108. * @type {number}
  109. * @default 0
  110. */
  111. this.output = 0;
  112. /**
  113. * Defines the minimum distance that should be
  114. * affected by the AO.
  115. *
  116. * @type {number}
  117. * @default 0.005
  118. */
  119. this.minDistance = 0.005;
  120. /**
  121. * Defines the maximum distance that should be
  122. * affected by the AO.
  123. *
  124. * @type {number}
  125. * @default 0.1
  126. */
  127. this.maxDistance = 0.1;
  128. this._visibilityCache = new Map();
  129. //
  130. this._generateSampleKernel( kernelSize );
  131. this._generateRandomKernelRotations();
  132. // depth texture
  133. const depthTexture = new DepthTexture();
  134. depthTexture.format = DepthStencilFormat;
  135. depthTexture.type = UnsignedInt248Type;
  136. // normal render target with depth buffer
  137. this.normalRenderTarget = new WebGLRenderTarget( this.width, this.height, {
  138. minFilter: NearestFilter,
  139. magFilter: NearestFilter,
  140. type: HalfFloatType,
  141. depthTexture: depthTexture
  142. } );
  143. // ssao render target
  144. this.ssaoRenderTarget = new WebGLRenderTarget( this.width, this.height, { type: HalfFloatType } );
  145. this.blurRenderTarget = this.ssaoRenderTarget.clone();
  146. // ssao material
  147. this.ssaoMaterial = new ShaderMaterial( {
  148. defines: Object.assign( {}, SSAOShader.defines ),
  149. uniforms: UniformsUtils.clone( SSAOShader.uniforms ),
  150. vertexShader: SSAOShader.vertexShader,
  151. fragmentShader: SSAOShader.fragmentShader,
  152. blending: NoBlending
  153. } );
  154. this.ssaoMaterial.defines[ 'KERNEL_SIZE' ] = kernelSize;
  155. this.ssaoMaterial.uniforms[ 'tNormal' ].value = this.normalRenderTarget.texture;
  156. this.ssaoMaterial.uniforms[ 'tDepth' ].value = this.normalRenderTarget.depthTexture;
  157. this.ssaoMaterial.uniforms[ 'tNoise' ].value = this.noiseTexture;
  158. this.ssaoMaterial.uniforms[ 'kernel' ].value = this.kernel;
  159. this.ssaoMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
  160. this.ssaoMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;
  161. this.ssaoMaterial.uniforms[ 'resolution' ].value.set( this.width, this.height );
  162. this.ssaoMaterial.uniforms[ 'cameraProjectionMatrix' ].value.copy( this.camera.projectionMatrix );
  163. this.ssaoMaterial.uniforms[ 'cameraInverseProjectionMatrix' ].value.copy( this.camera.projectionMatrixInverse );
  164. // normal material
  165. this.normalMaterial = new MeshNormalMaterial();
  166. this.normalMaterial.blending = NoBlending;
  167. // blur material
  168. this.blurMaterial = new ShaderMaterial( {
  169. defines: Object.assign( {}, SSAOBlurShader.defines ),
  170. uniforms: UniformsUtils.clone( SSAOBlurShader.uniforms ),
  171. vertexShader: SSAOBlurShader.vertexShader,
  172. fragmentShader: SSAOBlurShader.fragmentShader
  173. } );
  174. this.blurMaterial.uniforms[ 'tDiffuse' ].value = this.ssaoRenderTarget.texture;
  175. this.blurMaterial.uniforms[ 'resolution' ].value.set( this.width, this.height );
  176. // material for rendering the depth
  177. this.depthRenderMaterial = new ShaderMaterial( {
  178. defines: Object.assign( {}, SSAODepthShader.defines ),
  179. uniforms: UniformsUtils.clone( SSAODepthShader.uniforms ),
  180. vertexShader: SSAODepthShader.vertexShader,
  181. fragmentShader: SSAODepthShader.fragmentShader,
  182. blending: NoBlending
  183. } );
  184. this.depthRenderMaterial.uniforms[ 'tDepth' ].value = this.normalRenderTarget.depthTexture;
  185. this.depthRenderMaterial.uniforms[ 'cameraNear' ].value = this.camera.near;
  186. this.depthRenderMaterial.uniforms[ 'cameraFar' ].value = this.camera.far;
  187. // material for rendering the content of a render target
  188. this.copyMaterial = new ShaderMaterial( {
  189. uniforms: UniformsUtils.clone( CopyShader.uniforms ),
  190. vertexShader: CopyShader.vertexShader,
  191. fragmentShader: CopyShader.fragmentShader,
  192. transparent: true,
  193. depthTest: false,
  194. depthWrite: false,
  195. blendSrc: DstColorFactor,
  196. blendDst: ZeroFactor,
  197. blendEquation: AddEquation,
  198. blendSrcAlpha: DstAlphaFactor,
  199. blendDstAlpha: ZeroFactor,
  200. blendEquationAlpha: AddEquation
  201. } );
  202. // internals
  203. this._fsQuad = new FullScreenQuad( null );
  204. this._originalClearColor = new Color();
  205. }
  206. /**
  207. * Frees the GPU-related resources allocated by this instance. Call this
  208. * method whenever the pass is no longer used in your app.
  209. */
  210. dispose() {
  211. // dispose render targets
  212. this.normalRenderTarget.dispose();
  213. this.ssaoRenderTarget.dispose();
  214. this.blurRenderTarget.dispose();
  215. // dispose materials
  216. this.normalMaterial.dispose();
  217. this.blurMaterial.dispose();
  218. this.copyMaterial.dispose();
  219. this.depthRenderMaterial.dispose();
  220. // dispose full screen quad
  221. this._fsQuad.dispose();
  222. }
  223. /**
  224. * Performs the SSAO pass.
  225. *
  226. * @param {WebGLRenderer} renderer - The renderer.
  227. * @param {WebGLRenderTarget} writeBuffer - The write buffer. This buffer is intended as the rendering
  228. * destination for the pass.
  229. * @param {WebGLRenderTarget} readBuffer - The read buffer. The pass can access the result from the
  230. * previous pass from this buffer.
  231. * @param {number} deltaTime - The delta time in seconds.
  232. * @param {boolean} maskActive - Whether masking is active or not.
  233. */
  234. render( renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */ ) {
  235. // render normals and depth (honor only meshes, points and lines do not contribute to SSAO)
  236. this._overrideVisibility();
  237. this._renderOverride( renderer, this.normalMaterial, this.normalRenderTarget, 0x7777ff, 1.0 );
  238. this._restoreVisibility();
  239. // render SSAO
  240. this.ssaoMaterial.uniforms[ 'kernelRadius' ].value = this.kernelRadius;
  241. this.ssaoMaterial.uniforms[ 'minDistance' ].value = this.minDistance;
  242. this.ssaoMaterial.uniforms[ 'maxDistance' ].value = this.maxDistance;
  243. this._renderPass( renderer, this.ssaoMaterial, this.ssaoRenderTarget );
  244. // render blur
  245. this._renderPass( renderer, this.blurMaterial, this.blurRenderTarget );
  246. // output result to screen
  247. switch ( this.output ) {
  248. case SSAOPass.OUTPUT.SSAO:
  249. this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.ssaoRenderTarget.texture;
  250. this.copyMaterial.blending = NoBlending;
  251. this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : readBuffer );
  252. break;
  253. case SSAOPass.OUTPUT.Blur:
  254. this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.blurRenderTarget.texture;
  255. this.copyMaterial.blending = NoBlending;
  256. this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : readBuffer );
  257. break;
  258. case SSAOPass.OUTPUT.Depth:
  259. this._renderPass( renderer, this.depthRenderMaterial, this.renderToScreen ? null : readBuffer );
  260. break;
  261. case SSAOPass.OUTPUT.Normal:
  262. this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.normalRenderTarget.texture;
  263. this.copyMaterial.blending = NoBlending;
  264. this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : readBuffer );
  265. break;
  266. case SSAOPass.OUTPUT.Default:
  267. this.copyMaterial.uniforms[ 'tDiffuse' ].value = this.blurRenderTarget.texture;
  268. this.copyMaterial.blending = CustomBlending;
  269. this._renderPass( renderer, this.copyMaterial, this.renderToScreen ? null : readBuffer );
  270. break;
  271. default:
  272. console.warn( 'THREE.SSAOPass: Unknown output type.' );
  273. }
  274. }
  275. /**
  276. * Sets the size of the pass.
  277. *
  278. * @param {number} width - The width to set.
  279. * @param {number} height - The width to set.
  280. */
  281. setSize( width, height ) {
  282. this.width = width;
  283. this.height = height;
  284. this.ssaoRenderTarget.setSize( width, height );
  285. this.normalRenderTarget.setSize( width, height );
  286. this.blurRenderTarget.setSize( width, height );
  287. this.ssaoMaterial.uniforms[ 'resolution' ].value.set( width, height );
  288. this.ssaoMaterial.uniforms[ 'cameraProjectionMatrix' ].value.copy( this.camera.projectionMatrix );
  289. this.ssaoMaterial.uniforms[ 'cameraInverseProjectionMatrix' ].value.copy( this.camera.projectionMatrixInverse );
  290. this.blurMaterial.uniforms[ 'resolution' ].value.set( width, height );
  291. }
  292. // internals
  293. _renderPass( renderer, passMaterial, renderTarget, clearColor, clearAlpha ) {
  294. // save original state
  295. renderer.getClearColor( this._originalClearColor );
  296. const originalClearAlpha = renderer.getClearAlpha();
  297. const originalAutoClear = renderer.autoClear;
  298. renderer.setRenderTarget( renderTarget );
  299. // setup pass state
  300. renderer.autoClear = false;
  301. if ( ( clearColor !== undefined ) && ( clearColor !== null ) ) {
  302. renderer.setClearColor( clearColor );
  303. renderer.setClearAlpha( clearAlpha || 0.0 );
  304. renderer.clear();
  305. }
  306. this._fsQuad.material = passMaterial;
  307. this._fsQuad.render( renderer );
  308. // restore original state
  309. renderer.autoClear = originalAutoClear;
  310. renderer.setClearColor( this._originalClearColor );
  311. renderer.setClearAlpha( originalClearAlpha );
  312. }
  313. _renderOverride( renderer, overrideMaterial, renderTarget, clearColor, clearAlpha ) {
  314. renderer.getClearColor( this._originalClearColor );
  315. const originalClearAlpha = renderer.getClearAlpha();
  316. const originalAutoClear = renderer.autoClear;
  317. renderer.setRenderTarget( renderTarget );
  318. renderer.autoClear = false;
  319. clearColor = overrideMaterial.clearColor || clearColor;
  320. clearAlpha = overrideMaterial.clearAlpha || clearAlpha;
  321. if ( ( clearColor !== undefined ) && ( clearColor !== null ) ) {
  322. renderer.setClearColor( clearColor );
  323. renderer.setClearAlpha( clearAlpha || 0.0 );
  324. renderer.clear();
  325. }
  326. this.scene.overrideMaterial = overrideMaterial;
  327. renderer.render( this.scene, this.camera );
  328. this.scene.overrideMaterial = null;
  329. // restore original state
  330. renderer.autoClear = originalAutoClear;
  331. renderer.setClearColor( this._originalClearColor );
  332. renderer.setClearAlpha( originalClearAlpha );
  333. }
  334. _generateSampleKernel( kernelSize ) {
  335. const kernel = this.kernel;
  336. for ( let i = 0; i < kernelSize; i ++ ) {
  337. const sample = new Vector3();
  338. sample.x = ( Math.random() * 2 ) - 1;
  339. sample.y = ( Math.random() * 2 ) - 1;
  340. sample.z = Math.random();
  341. sample.normalize();
  342. let scale = i / kernelSize;
  343. scale = MathUtils.lerp( 0.1, 1, scale * scale );
  344. sample.multiplyScalar( scale );
  345. kernel.push( sample );
  346. }
  347. }
  348. _generateRandomKernelRotations() {
  349. const width = 4, height = 4;
  350. const simplex = new SimplexNoise();
  351. const size = width * height;
  352. const data = new Float32Array( size );
  353. for ( let i = 0; i < size; i ++ ) {
  354. const x = ( Math.random() * 2 ) - 1;
  355. const y = ( Math.random() * 2 ) - 1;
  356. const z = 0;
  357. data[ i ] = simplex.noise3d( x, y, z );
  358. }
  359. this.noiseTexture = new DataTexture( data, width, height, RedFormat, FloatType );
  360. this.noiseTexture.wrapS = RepeatWrapping;
  361. this.noiseTexture.wrapT = RepeatWrapping;
  362. this.noiseTexture.needsUpdate = true;
  363. }
  364. _overrideVisibility() {
  365. const scene = this.scene;
  366. const cache = this._visibilityCache;
  367. scene.traverse( function ( object ) {
  368. cache.set( object, object.visible );
  369. if ( object.isPoints || object.isLine ) object.visible = false;
  370. } );
  371. }
  372. _restoreVisibility() {
  373. const scene = this.scene;
  374. const cache = this._visibilityCache;
  375. scene.traverse( function ( object ) {
  376. const visible = cache.get( object );
  377. object.visible = visible;
  378. } );
  379. cache.clear();
  380. }
  381. }
  382. SSAOPass.OUTPUT = {
  383. 'Default': 0,
  384. 'SSAO': 1,
  385. 'Blur': 2,
  386. 'Depth': 3,
  387. 'Normal': 4
  388. };
  389. export { SSAOPass };