ProgressiveLightMap.js 11 KB

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