ProgressiveLightMap.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. import { DoubleSide, FloatType, HalfFloatType, Mesh, MeshBasicMaterial, MeshPhongMaterial, PlaneGeometry, Scene, WebGLRenderTarget } from 'three';
  2. import { potpack } from '../libs/potpack.module.js';
  3. /**
  4. * Progressive Light Map Accumulator, by [zalo]{@link https://github.com/zalo/}.
  5. *
  6. * To use, simply construct a `ProgressiveLightMap` object,
  7. * `plmap.addObjectsToLightMap(object)` an array of semi-static
  8. * objects and lights to the class once, and then call
  9. * `plmap.update(camera)` every frame to begin accumulating
  10. * lighting samples.
  11. *
  12. * This should begin accumulating lightmaps which apply to
  13. * your objects, so you can start jittering lighting to achieve
  14. * the texture-space effect you're looking for.
  15. *
  16. * This class can only be used with {@link WebGLRenderer}.
  17. * When using {@link WebGPURenderer}, import from `ProgressiveLightMapGPU.js`.
  18. *
  19. * @three_import import { ProgressiveLightMap } from 'three/addons/misc/ProgressiveLightMap.js';
  20. */
  21. class ProgressiveLightMap {
  22. /**
  23. * Constructs a new progressive light map.
  24. *
  25. * @param {WebGLRenderer} renderer - The renderer.
  26. * @param {number} [res=1024] - The side-long dimension of the total lightmap.
  27. */
  28. constructor( renderer, res = 1024 ) {
  29. /**
  30. * The renderer.
  31. *
  32. * @type {WebGLRenderer}
  33. */
  34. this.renderer = renderer;
  35. /**
  36. * The side-long dimension of the total lightmap.
  37. *
  38. * @type {number}
  39. * @default 1024
  40. */
  41. this.res = res;
  42. // internals
  43. this.lightMapContainers = [];
  44. this.scene = new Scene();
  45. this.buffer1Active = false;
  46. this.firstUpdate = true;
  47. this.labelMesh = null;
  48. this.blurringPlane = null;
  49. // Create the Progressive LightMap Texture
  50. const format = /(Android|iPad|iPhone|iPod)/g.test( navigator.userAgent ) ? HalfFloatType : FloatType;
  51. this.progressiveLightMap1 = new WebGLRenderTarget( this.res, this.res, { type: format } );
  52. this.progressiveLightMap2 = new WebGLRenderTarget( this.res, this.res, { type: format } );
  53. this.progressiveLightMap2.texture.channel = 1;
  54. // Inject some spicy new logic into a standard phong material
  55. this.uvMat = new MeshPhongMaterial();
  56. this.uvMat.uniforms = {};
  57. this.uvMat.onBeforeCompile = ( shader ) => {
  58. // Vertex Shader: Set Vertex Positions to the Unwrapped UV Positions
  59. shader.vertexShader =
  60. 'attribute vec2 uv1;\n' +
  61. '#define USE_LIGHTMAP\n' +
  62. '#define LIGHTMAP_UV uv1\n' +
  63. shader.vertexShader.slice( 0, - 1 ) +
  64. ' gl_Position = vec4((LIGHTMAP_UV - 0.5) * 2.0, 1.0, 1.0); }';
  65. // Fragment Shader: Set Pixels to average in the Previous frame's Shadows
  66. const bodyStart = shader.fragmentShader.indexOf( 'void main() {' );
  67. shader.fragmentShader =
  68. '#define USE_LIGHTMAP\n' +
  69. shader.fragmentShader.slice( 0, bodyStart ) +
  70. ' uniform sampler2D previousShadowMap;\n uniform float averagingWindow;\n' +
  71. shader.fragmentShader.slice( bodyStart - 1, - 1 ) +
  72. `\nvec3 texelOld = texture2D(previousShadowMap, vLightMapUv).rgb;
  73. gl_FragColor.rgb = mix(texelOld, gl_FragColor.rgb, 1.0/averagingWindow);
  74. }`;
  75. // Set the Previous Frame's Texture Buffer and Averaging Window
  76. shader.uniforms.previousShadowMap = { value: this.progressiveLightMap1.texture };
  77. shader.uniforms.averagingWindow = { value: 100 };
  78. this.uvMat.uniforms = shader.uniforms;
  79. // Set the new Shader to this
  80. this.uvMat.userData.shader = shader;
  81. };
  82. }
  83. /**
  84. * Sets these objects' materials' lightmaps and modifies their uv1's.
  85. *
  86. * @param {Array<Object3D>} objects - An array of objects and lights to set up your lightmap.
  87. */
  88. addObjectsToLightMap( objects ) {
  89. // Prepare list of UV bounding boxes for packing later...
  90. this.uv_boxes = []; const padding = 3 / this.res;
  91. for ( let ob = 0; ob < objects.length; ob ++ ) {
  92. const object = objects[ ob ];
  93. // If this object is a light, simply add it to the internal scene
  94. if ( object.isLight ) {
  95. this.scene.attach( object ); continue;
  96. }
  97. if ( object.geometry.hasAttribute( 'uv' ) === false ) {
  98. console.warn( 'THREE.ProgressiveLightMap: All lightmap objects need uvs.' ); continue;
  99. }
  100. if ( this.blurringPlane === null ) {
  101. this._initializeBlurPlane( this.res, this.progressiveLightMap1 );
  102. }
  103. // Apply the lightmap to the object
  104. object.material.lightMap = this.progressiveLightMap2.texture;
  105. object.material.dithering = true;
  106. object.castShadow = true;
  107. object.receiveShadow = true;
  108. object.renderOrder = 1000 + ob;
  109. // Prepare UV boxes for potpack
  110. // TODO: Size these by object surface area
  111. this.uv_boxes.push( { w: 1 + ( padding * 2 ),
  112. h: 1 + ( padding * 2 ), index: ob } );
  113. this.lightMapContainers.push( { basicMat: object.material, object: object } );
  114. }
  115. // Pack the objects' lightmap UVs into the same global space
  116. const dimensions = potpack( this.uv_boxes );
  117. this.uv_boxes.forEach( ( box ) => {
  118. const uv1 = objects[ box.index ].geometry.getAttribute( 'uv' ).clone();
  119. for ( let i = 0; i < uv1.array.length; i += uv1.itemSize ) {
  120. uv1.array[ i ] = ( uv1.array[ i ] + box.x + padding ) / dimensions.w;
  121. uv1.array[ i + 1 ] = ( uv1.array[ i + 1 ] + box.y + padding ) / dimensions.h;
  122. }
  123. objects[ box.index ].geometry.setAttribute( 'uv1', uv1 );
  124. objects[ box.index ].geometry.getAttribute( 'uv1' ).needsUpdate = true;
  125. } );
  126. }
  127. /**
  128. * This function renders each mesh one at a time into their respective surface maps.
  129. *
  130. * @param {Camera} camera - The camera the scene is rendered with.
  131. * @param {number} [blendWindow=100] - When >1, samples will accumulate over time.
  132. * @param {boolean} [blurEdges=true] - Whether to fix UV Edges via blurring.
  133. */
  134. update( camera, blendWindow = 100, blurEdges = true ) {
  135. if ( this.blurringPlane === null ) {
  136. return;
  137. }
  138. // Store the original Render Target
  139. const oldTarget = this.renderer.getRenderTarget();
  140. // The blurring plane applies blur to the seams of the lightmap
  141. this.blurringPlane.visible = blurEdges;
  142. // Steal the Object3D from the real world to our special dimension
  143. for ( let l = 0; l < this.lightMapContainers.length; l ++ ) {
  144. this.lightMapContainers[ l ].object.oldScene =
  145. this.lightMapContainers[ l ].object.parent;
  146. this.scene.attach( this.lightMapContainers[ l ].object );
  147. }
  148. // Initialize everything
  149. if ( this.firstUpdate === true ) {
  150. this.renderer.compile( this.scene, camera );
  151. this.firstUpdate = false;
  152. }
  153. // Set each object's material to the UV Unwrapped Surface Mapping Version
  154. for ( let l = 0; l < this.lightMapContainers.length; l ++ ) {
  155. this.uvMat.uniforms.averagingWindow = { value: blendWindow };
  156. this.lightMapContainers[ l ].object.material = this.uvMat;
  157. this.lightMapContainers[ l ].object.oldFrustumCulled =
  158. this.lightMapContainers[ l ].object.frustumCulled;
  159. this.lightMapContainers[ l ].object.frustumCulled = false;
  160. }
  161. // Ping-pong two surface buffers for reading/writing
  162. const activeMap = this.buffer1Active ? this.progressiveLightMap1 : this.progressiveLightMap2;
  163. const inactiveMap = this.buffer1Active ? this.progressiveLightMap2 : this.progressiveLightMap1;
  164. // Render the object's surface maps
  165. this.renderer.setRenderTarget( activeMap );
  166. this.uvMat.uniforms.previousShadowMap = { value: inactiveMap.texture };
  167. this.blurringPlane.material.uniforms.previousShadowMap = { value: inactiveMap.texture };
  168. this.buffer1Active = ! this.buffer1Active;
  169. this.renderer.render( this.scene, camera );
  170. // Restore the object's Real-time Material and add it back to the original world
  171. for ( let l = 0; l < this.lightMapContainers.length; l ++ ) {
  172. this.lightMapContainers[ l ].object.frustumCulled =
  173. this.lightMapContainers[ l ].object.oldFrustumCulled;
  174. this.lightMapContainers[ l ].object.material = this.lightMapContainers[ l ].basicMat;
  175. this.lightMapContainers[ l ].object.oldScene.attach( this.lightMapContainers[ l ].object );
  176. }
  177. // Restore the original Render Target
  178. this.renderer.setRenderTarget( oldTarget );
  179. }
  180. /**
  181. * Draws the lightmap in the main scene. Call this after adding the objects to it.
  182. *
  183. * @param {boolean} visible - Whether the debug plane should be visible
  184. * @param {Vector3} [position] - Where the debug plane should be drawn
  185. */
  186. showDebugLightmap( visible, position = undefined ) {
  187. if ( this.lightMapContainers.length === 0 ) {
  188. console.warn( 'THREE.ProgressiveLightMap: Call .showDebugLightmap() after adding the objects.' );
  189. return;
  190. }
  191. if ( this.labelMesh === null ) {
  192. const labelMaterial = new MeshBasicMaterial( { map: this.progressiveLightMap1.texture, side: DoubleSide } );
  193. const labelGeometry = new PlaneGeometry( 100, 100 );
  194. this.labelMesh = new Mesh( labelGeometry, labelMaterial );
  195. this.labelMesh.position.y = 250;
  196. this.lightMapContainers[ 0 ].object.parent.add( this.labelMesh );
  197. }
  198. if ( position !== undefined ) {
  199. this.labelMesh.position.copy( position );
  200. }
  201. this.labelMesh.visible = visible;
  202. }
  203. /**
  204. * Creates the Blurring Plane.
  205. *
  206. * @private
  207. * @param {number} res - The square resolution of this object's lightMap.
  208. * @param {WebGLRenderTarget} [lightMap] - The lightmap to initialize the plane with.
  209. */
  210. _initializeBlurPlane( res, lightMap = null ) {
  211. const blurMaterial = new MeshBasicMaterial();
  212. blurMaterial.uniforms = { previousShadowMap: { value: null },
  213. pixelOffset: { value: 1.0 / res },
  214. polygonOffset: true, polygonOffsetFactor: - 1, polygonOffsetUnits: 3.0 };
  215. blurMaterial.onBeforeCompile = ( shader ) => {
  216. // Vertex Shader: Set Vertex Positions to the Unwrapped UV Positions
  217. shader.vertexShader =
  218. '#define USE_UV\n' +
  219. shader.vertexShader.slice( 0, - 1 ) +
  220. ' gl_Position = vec4((uv - 0.5) * 2.0, 1.0, 1.0); }';
  221. // Fragment Shader: Set Pixels to 9-tap box blur the current frame's Shadows
  222. const bodyStart = shader.fragmentShader.indexOf( 'void main() {' );
  223. shader.fragmentShader =
  224. '#define USE_UV\n' +
  225. shader.fragmentShader.slice( 0, bodyStart ) +
  226. ' uniform sampler2D previousShadowMap;\n uniform float pixelOffset;\n' +
  227. shader.fragmentShader.slice( bodyStart - 1, - 1 ) +
  228. ` gl_FragColor.rgb = (
  229. texture2D(previousShadowMap, vUv + vec2( pixelOffset, 0.0 )).rgb +
  230. texture2D(previousShadowMap, vUv + vec2( 0.0 , pixelOffset)).rgb +
  231. texture2D(previousShadowMap, vUv + vec2( 0.0 , -pixelOffset)).rgb +
  232. texture2D(previousShadowMap, vUv + vec2(-pixelOffset, 0.0 )).rgb +
  233. texture2D(previousShadowMap, vUv + vec2( pixelOffset, pixelOffset)).rgb +
  234. texture2D(previousShadowMap, vUv + vec2(-pixelOffset, pixelOffset)).rgb +
  235. texture2D(previousShadowMap, vUv + vec2( pixelOffset, -pixelOffset)).rgb +
  236. texture2D(previousShadowMap, vUv + vec2(-pixelOffset, -pixelOffset)).rgb)/8.0;
  237. }`;
  238. // Set the LightMap Accumulation Buffer
  239. shader.uniforms.previousShadowMap = { value: lightMap.texture };
  240. shader.uniforms.pixelOffset = { value: 0.5 / res };
  241. blurMaterial.uniforms = shader.uniforms;
  242. // Set the new Shader to this
  243. blurMaterial.userData.shader = shader;
  244. };
  245. this.blurringPlane = new Mesh( new PlaneGeometry( 1, 1 ), blurMaterial );
  246. this.blurringPlane.name = 'Blurring Plane';
  247. this.blurringPlane.frustumCulled = false;
  248. this.blurringPlane.renderOrder = 0;
  249. this.blurringPlane.material.depthWrite = false;
  250. this.scene.add( this.blurringPlane );
  251. }
  252. /**
  253. * Frees all internal resources.
  254. */
  255. dispose() {
  256. this.progressiveLightMap1.dispose();
  257. this.progressiveLightMap2.dispose();
  258. this.uvMat.dispose();
  259. if ( this.blurringPlane !== null ) {
  260. this.blurringPlane.geometry.dispose();
  261. this.blurringPlane.material.dispose();
  262. }
  263. if ( this.labelMesh !== null ) {
  264. this.labelMesh.geometry.dispose();
  265. this.labelMesh.material.dispose();
  266. }
  267. }
  268. }
  269. export { ProgressiveLightMap };