ProgressiveLightMap.js 12 KB

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