2
0

WebGLDeferredRenderer.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. /**
  2. * @author alteredq / http://alteredqualia.com/
  3. * @author MPanknin / http://www.redplant.de/
  4. */
  5. THREE.WebGLDeferredRenderer = function ( parameters ) {
  6. var _this = this;
  7. var fullWidth = parameters.width !== undefined ? parameters.width : 800;
  8. var fullHeight = parameters.height !== undefined ? parameters.height : 600;
  9. var currentScale = parameters.scale !== undefined ? parameters.scale : 1;
  10. var scaledWidth = Math.floor( currentScale * fullWidth );
  11. var scaledHeight = Math.floor( currentScale * fullHeight );
  12. var brightness = parameters.brightness !== undefined ? parameters.brightness : 1;
  13. var tonemapping = parameters.tonemapping !== undefined ? parameters.tonemapping : THREE.SimpleOperator;
  14. var antialias = parameters.antialias !== undefined ? parameters.antialias : false;
  15. this.renderer = parameters.renderer;
  16. if ( this.renderer === undefined ) {
  17. this.renderer = new THREE.WebGLRenderer( { alpha: false, antialias: false } );
  18. this.renderer.setSize( fullWidth, fullHeight );
  19. this.renderer.setClearColorHex( 0x000000, 0 );
  20. this.renderer.autoClear = false;
  21. }
  22. this.domElement = this.renderer.domElement;
  23. //
  24. var gl = this.renderer.context;
  25. //
  26. var currentCamera = null;
  27. var positionVS = new THREE.Vector3();
  28. var directionVS = new THREE.Vector3();
  29. var tempVS = new THREE.Vector3();
  30. var rightVS = new THREE.Vector3();
  31. var normalVS = new THREE.Vector3();
  32. var upVS = new THREE.Vector3();
  33. //
  34. var geometryLightSphere = new THREE.SphereGeometry( 1, 16, 8 );
  35. var geometryLightPlane = new THREE.PlaneGeometry( 2, 2 );
  36. var black = new THREE.Color( 0x000000 );
  37. var colorShader = THREE.ShaderDeferred[ "color" ];
  38. var normalDepthShader = THREE.ShaderDeferred[ "normalDepth" ];
  39. //
  40. var emissiveLightShader = THREE.ShaderDeferred[ "emissiveLight" ];
  41. var pointLightShader = THREE.ShaderDeferred[ "pointLight" ];
  42. var spotLightShader = THREE.ShaderDeferred[ "spotLight" ];
  43. var directionalLightShader = THREE.ShaderDeferred[ "directionalLight" ];
  44. var hemisphereLightShader = THREE.ShaderDeferred[ "hemisphereLight" ];
  45. var areaLightShader = THREE.ShaderDeferred[ "areaLight" ];
  46. var compositeShader = THREE.ShaderDeferred[ "composite" ];
  47. //
  48. var compColor, compNormal, compDepth, compLight, compFinal;
  49. var passColor, passNormal, passDepth, passLightFullscreen, passLightProxy, compositePass;
  50. var effectFXAA;
  51. //
  52. var lightSceneFullscreen, lightSceneProxy;
  53. //
  54. var resizableMaterials = [];
  55. //
  56. var invisibleMaterial = new THREE.ShaderMaterial();
  57. invisibleMaterial.visible = false;
  58. var defaultNormalDepthMaterial = new THREE.ShaderMaterial( {
  59. uniforms: THREE.UniformsUtils.clone( normalDepthShader.uniforms ),
  60. vertexShader: normalDepthShader.vertexShader,
  61. fragmentShader: normalDepthShader.fragmentShader,
  62. blending: THREE.NoBlending
  63. } );
  64. //
  65. var initDeferredMaterials = function ( object ) {
  66. if ( object.material instanceof THREE.MeshFaceMaterial ) {
  67. var colorMaterials = [];
  68. var normalDepthMaterials = [];
  69. var materials = object.material.materials;
  70. for ( var i = 0, il = materials.length; i < il; i ++ ) {
  71. var deferredMaterials = createDeferredMaterials( materials[ i ] );
  72. if ( deferredMaterials.transparent ) {
  73. colorMaterials.push( invisibleMaterial );
  74. normalDepthMaterials.push( invisibleMaterial );
  75. } else {
  76. colorMaterials.push( deferredMaterials.colorMaterial );
  77. normalDepthMaterials.push( deferredMaterials.normalDepthMaterial );
  78. }
  79. }
  80. object.userData.colorMaterial = new THREE.MeshFaceMaterial( colorMaterials );
  81. object.userData.normalDepthMaterial = new THREE.MeshFaceMaterial( normalDepthMaterials );
  82. } else {
  83. var deferredMaterials = createDeferredMaterials( object.material );
  84. object.userData.colorMaterial = deferredMaterials.colorMaterial;
  85. object.userData.normalDepthMaterial = deferredMaterials.normalDepthMaterial;
  86. object.userData.transparent = deferredMaterials.transparent;
  87. }
  88. };
  89. var createDeferredMaterials = function ( originalMaterial ) {
  90. var deferredMaterials = {};
  91. // color material
  92. // -----------------
  93. // diffuse color
  94. // specular color
  95. // shininess
  96. // diffuse map
  97. // vertex colors
  98. // alphaTest
  99. // morphs
  100. var uniforms = THREE.UniformsUtils.clone( colorShader.uniforms );
  101. var defines = { "USE_MAP": !! originalMaterial.map, "USE_ENVMAP": !! originalMaterial.envMap, "GAMMA_INPUT": true };
  102. var material = new THREE.ShaderMaterial( {
  103. fragmentShader: colorShader.fragmentShader,
  104. vertexShader: colorShader.vertexShader,
  105. uniforms: uniforms,
  106. defines: defines,
  107. shading: originalMaterial.shading
  108. } );
  109. if ( originalMaterial instanceof THREE.MeshBasicMaterial ) {
  110. var diffuse = black;
  111. var emissive = originalMaterial.color;
  112. } else {
  113. var diffuse = originalMaterial.color;
  114. var emissive = originalMaterial.emissive !== undefined ? originalMaterial.emissive : black;
  115. }
  116. var specular = originalMaterial.specular !== undefined ? originalMaterial.specular : black;
  117. var shininess = originalMaterial.shininess !== undefined ? originalMaterial.shininess : 1;
  118. var wrapAround = originalMaterial.wrapAround !== undefined ? ( originalMaterial.wrapAround ? -1 : 1 ) : 1;
  119. var additiveSpecular = originalMaterial.metal !== undefined ? ( originalMaterial.metal ? 1 : -1 ) : -1;
  120. uniforms.emissive.value.copyGammaToLinear( emissive );
  121. uniforms.diffuse.value.copyGammaToLinear( diffuse );
  122. uniforms.specular.value.copyGammaToLinear( specular );
  123. uniforms.shininess.value = shininess;
  124. uniforms.wrapAround.value = wrapAround;
  125. uniforms.additiveSpecular.value = additiveSpecular;
  126. uniforms.map.value = originalMaterial.map;
  127. if ( originalMaterial.envMap ) {
  128. uniforms.envMap.value = originalMaterial.envMap;
  129. uniforms.useRefract.value = originalMaterial.envMap.mapping instanceof THREE.CubeRefractionMapping;
  130. uniforms.refractionRatio.value = originalMaterial.refractionRatio;
  131. uniforms.combine.value = originalMaterial.combine;
  132. uniforms.reflectivity.value = originalMaterial.reflectivity;
  133. uniforms.flipEnvMap.value = ( originalMaterial.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  134. uniforms.samplerNormalDepth.value = compNormalDepth.renderTarget2;
  135. uniforms.viewWidth.value = scaledWidth;
  136. uniforms.viewHeight.value = scaledHeight;
  137. resizableMaterials.push( { "material": material } );
  138. }
  139. material.vertexColors = originalMaterial.vertexColors;
  140. material.morphTargets = originalMaterial.morphTargets;
  141. material.morphNormals = originalMaterial.morphNormals;
  142. material.skinning = originalMaterial.skinning;
  143. material.alphaTest = originalMaterial.alphaTest;
  144. material.wireframe = originalMaterial.wireframe;
  145. // uv repeat and offset setting priorities
  146. // 1. color map
  147. // 2. specular map
  148. // 3. normal map
  149. // 4. bump map
  150. var uvScaleMap;
  151. if ( originalMaterial.map ) {
  152. uvScaleMap = originalMaterial.map;
  153. } else if ( originalMaterial.specularMap ) {
  154. uvScaleMap = originalMaterial.specularMap;
  155. } else if ( originalMaterial.normalMap ) {
  156. uvScaleMap = originalMaterial.normalMap;
  157. } else if ( originalMaterial.bumpMap ) {
  158. uvScaleMap = originalMaterial.bumpMap;
  159. }
  160. if ( uvScaleMap !== undefined ) {
  161. var offset = uvScaleMap.offset;
  162. var repeat = uvScaleMap.repeat;
  163. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  164. }
  165. deferredMaterials.colorMaterial = material;
  166. // normal + depth material
  167. // -----------------
  168. // vertex normals
  169. // morph normals
  170. // bump map
  171. // bump scale
  172. // clip depth
  173. if ( originalMaterial.morphTargets || originalMaterial.skinning || originalMaterial.bumpMap ) {
  174. var uniforms = THREE.UniformsUtils.clone( normalDepthShader.uniforms );
  175. var defines = { "USE_BUMPMAP": !!originalMaterial.bumpMap };
  176. var normalDepthMaterial = new THREE.ShaderMaterial( {
  177. uniforms: uniforms,
  178. vertexShader: normalDepthShader.vertexShader,
  179. fragmentShader: normalDepthShader.fragmentShader,
  180. shading: originalMaterial.shading,
  181. defines: defines,
  182. blending: THREE.NoBlending
  183. } );
  184. normalDepthMaterial.morphTargets = originalMaterial.morphTargets;
  185. normalDepthMaterial.morphNormals = originalMaterial.morphNormals;
  186. normalDepthMaterial.skinning = originalMaterial.skinning;
  187. if ( originalMaterial.bumpMap ) {
  188. uniforms.bumpMap.value = originalMaterial.bumpMap;
  189. uniforms.bumpScale.value = originalMaterial.bumpScale;
  190. var offset = originalMaterial.bumpMap.offset;
  191. var repeat = originalMaterial.bumpMap.repeat;
  192. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  193. }
  194. } else {
  195. var normalDepthMaterial = defaultNormalDepthMaterial.clone();
  196. }
  197. normalDepthMaterial.wireframe = originalMaterial.wireframe;
  198. normalDepthMaterial.vertexColors = originalMaterial.vertexColors;
  199. deferredMaterials.normalDepthMaterial = normalDepthMaterial;
  200. //
  201. deferredMaterials.transparent = originalMaterial.transparent;
  202. return deferredMaterials;
  203. };
  204. var updatePointLightProxy = function ( lightProxy ) {
  205. var light = lightProxy.userData.originalLight;
  206. var uniforms = lightProxy.material.uniforms;
  207. // skip infinite pointlights
  208. // right now you can't switch between infinite and finite pointlights
  209. // it's just too messy as they use different proxies
  210. var distance = light.distance;
  211. if ( distance > 0 ) {
  212. lightProxy.scale.set( 1, 1, 1 ).multiplyScalar( distance );
  213. uniforms[ "lightRadius" ].value = distance;
  214. positionVS.setFromMatrixPosition( light.matrixWorld );
  215. positionVS.applyMatrix4( currentCamera.matrixWorldInverse );
  216. uniforms[ "lightPositionVS" ].value.copy( positionVS );
  217. lightProxy.position.setFromMatrixPosition( light.matrixWorld );
  218. } else {
  219. uniforms[ "lightRadius" ].value = Infinity;
  220. }
  221. // linear space colors
  222. var intensity = light.intensity * light.intensity;
  223. uniforms[ "lightIntensity" ].value = intensity;
  224. uniforms[ "lightColor" ].value.copyGammaToLinear( light.color );
  225. };
  226. var createDeferredPointLight = function ( light ) {
  227. // setup light material
  228. var materialLight = new THREE.ShaderMaterial( {
  229. uniforms: THREE.UniformsUtils.clone( pointLightShader.uniforms ),
  230. vertexShader: pointLightShader.vertexShader,
  231. fragmentShader: pointLightShader.fragmentShader,
  232. blending: THREE.AdditiveBlending,
  233. depthWrite: false,
  234. transparent: true,
  235. side: THREE.BackSide
  236. } );
  237. // infinite pointlights use full-screen quad proxy
  238. // regular pointlights use sphere proxy
  239. var geometry;
  240. if ( light.distance > 0 ) {
  241. geometry = geometryLightSphere;
  242. } else {
  243. geometry = geometryLightPlane;
  244. materialLight.depthTest = false;
  245. materialLight.side = THREE.FrontSide;
  246. }
  247. materialLight.uniforms[ "viewWidth" ].value = scaledWidth;
  248. materialLight.uniforms[ "viewHeight" ].value = scaledHeight;
  249. materialLight.uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
  250. materialLight.uniforms[ 'samplerNormalDepth' ].value = compNormalDepth.renderTarget2;
  251. // create light proxy mesh
  252. var meshLight = new THREE.Mesh( geometry, materialLight );
  253. // keep reference for color and intensity updates
  254. meshLight.userData.originalLight = light;
  255. // keep reference for size reset
  256. resizableMaterials.push( { "material": materialLight } );
  257. // sync proxy uniforms to the original light
  258. updatePointLightProxy( meshLight );
  259. return meshLight;
  260. };
  261. var updateSpotLightProxy = function ( lightProxy ) {
  262. var light = lightProxy.userData.originalLight;
  263. var uniforms = lightProxy.material.uniforms;
  264. var viewMatrix = currentCamera.matrixWorldInverse;
  265. var modelMatrix = light.matrixWorld;
  266. positionVS.setFromMatrixPosition( modelMatrix );
  267. positionVS.applyMatrix4( viewMatrix );
  268. directionVS.setFromMatrixPosition( modelMatrix );
  269. tempVS.setFromMatrixPosition( light.target.matrixWorld );
  270. directionVS.sub( tempVS );
  271. directionVS.normalize();
  272. directionVS.transformDirection( viewMatrix );
  273. uniforms[ "lightPositionVS" ].value.copy( positionVS );
  274. uniforms[ "lightDirectionVS" ].value.copy( directionVS );
  275. uniforms[ "lightAngle" ].value = light.angle;
  276. uniforms[ "lightDistance" ].value = light.distance;
  277. // linear space colors
  278. var intensity = light.intensity * light.intensity;
  279. uniforms[ "lightIntensity" ].value = intensity;
  280. uniforms[ "lightColor" ].value.copyGammaToLinear( light.color );
  281. };
  282. var createDeferredSpotLight = function ( light ) {
  283. // setup light material
  284. var uniforms = THREE.UniformsUtils.clone( spotLightShader.uniforms );
  285. var materialLight = new THREE.ShaderMaterial( {
  286. uniforms: uniforms,
  287. vertexShader: spotLightShader.vertexShader,
  288. fragmentShader: spotLightShader.fragmentShader,
  289. blending: THREE.AdditiveBlending,
  290. depthWrite: false,
  291. depthTest: false,
  292. transparent: true
  293. } );
  294. uniforms[ "viewWidth" ].value = scaledWidth;
  295. uniforms[ "viewHeight" ].value = scaledHeight;
  296. uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
  297. uniforms[ 'samplerNormalDepth' ].value = compNormalDepth.renderTarget2;
  298. // create light proxy mesh
  299. var meshLight = new THREE.Mesh( geometryLightPlane, materialLight );
  300. // keep reference for color and intensity updates
  301. meshLight.userData.originalLight = light;
  302. // keep reference for size reset
  303. resizableMaterials.push( { "material": materialLight } );
  304. // sync proxy uniforms to the original light
  305. updateSpotLightProxy( meshLight );
  306. return meshLight;
  307. };
  308. var updateDirectionalLightProxy = function ( lightProxy ) {
  309. var light = lightProxy.userData.originalLight;
  310. var uniforms = lightProxy.material.uniforms;
  311. directionVS.setFromMatrixPosition( light.matrixWorld );
  312. tempVS.setFromMatrixPosition( light.target.matrixWorld );
  313. directionVS.sub( tempVS );
  314. directionVS.normalize();
  315. directionVS.transformDirection( currentCamera.matrixWorldInverse );
  316. uniforms[ "lightDirectionVS" ].value.copy( directionVS );
  317. // linear space colors
  318. var intensity = light.intensity * light.intensity;
  319. uniforms[ "lightIntensity" ].value = intensity;
  320. uniforms[ "lightColor" ].value.copyGammaToLinear( light.color );
  321. };
  322. var createDeferredDirectionalLight = function ( light ) {
  323. // setup light material
  324. var uniforms = THREE.UniformsUtils.clone( directionalLightShader.uniforms );
  325. var materialLight = new THREE.ShaderMaterial( {
  326. uniforms: uniforms,
  327. vertexShader: directionalLightShader.vertexShader,
  328. fragmentShader: directionalLightShader.fragmentShader,
  329. blending: THREE.AdditiveBlending,
  330. depthWrite: false,
  331. depthTest: false,
  332. transparent: true
  333. } );
  334. uniforms[ "viewWidth" ].value = scaledWidth;
  335. uniforms[ "viewHeight" ].value = scaledHeight;
  336. uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
  337. uniforms[ 'samplerNormalDepth' ].value = compNormalDepth.renderTarget2;
  338. // create light proxy mesh
  339. var meshLight = new THREE.Mesh( geometryLightPlane, materialLight );
  340. // keep reference for color and intensity updates
  341. meshLight.userData.originalLight = light;
  342. // keep reference for size reset
  343. resizableMaterials.push( { "material": materialLight } );
  344. // sync proxy uniforms to the original light
  345. updateDirectionalLightProxy( meshLight );
  346. return meshLight;
  347. };
  348. var updateHemisphereLightProxy = function ( lightProxy ) {
  349. var light = lightProxy.userData.originalLight;
  350. var uniforms = lightProxy.material.uniforms;
  351. directionVS.setFromMatrixPosition( light.matrixWorld );
  352. directionVS.normalize();
  353. directionVS.transformDirection( currentCamera.matrixWorldInverse );
  354. uniforms[ "lightDirectionVS" ].value.copy( directionVS );
  355. // linear space colors
  356. var intensity = light.intensity * light.intensity;
  357. uniforms[ "lightIntensity" ].value = intensity;
  358. uniforms[ "lightColorSky" ].value.copyGammaToLinear( light.color );
  359. uniforms[ "lightColorGround" ].value.copyGammaToLinear( light.groundColor );
  360. };
  361. var createDeferredHemisphereLight = function ( light ) {
  362. // setup light material
  363. var uniforms = THREE.UniformsUtils.clone( hemisphereLightShader.uniforms );
  364. var materialLight = new THREE.ShaderMaterial( {
  365. uniforms: uniforms,
  366. vertexShader: hemisphereLightShader.vertexShader,
  367. fragmentShader: hemisphereLightShader.fragmentShader,
  368. blending: THREE.AdditiveBlending,
  369. depthWrite: false,
  370. depthTest: false,
  371. transparent: true
  372. } );
  373. uniforms[ "viewWidth" ].value = scaledWidth;
  374. uniforms[ "viewHeight" ].value = scaledHeight;
  375. uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
  376. uniforms[ 'samplerNormalDepth' ].value = compNormalDepth.renderTarget2;
  377. // create light proxy mesh
  378. var meshLight = new THREE.Mesh( geometryLightPlane, materialLight );
  379. // keep reference for color and intensity updates
  380. meshLight.userData.originalLight = light;
  381. // keep reference for size reset
  382. resizableMaterials.push( { "material": materialLight } );
  383. // sync proxy uniforms to the original light
  384. updateHemisphereLightProxy( meshLight );
  385. return meshLight;
  386. };
  387. var updateAreaLightProxy = function ( lightProxy ) {
  388. var light = lightProxy.userData.originalLight;
  389. var uniforms = lightProxy.material.uniforms;
  390. var modelMatrix = light.matrixWorld;
  391. var viewMatrix = currentCamera.matrixWorldInverse;
  392. positionVS.setFromMatrixPosition( modelMatrix );
  393. positionVS.applyMatrix4( viewMatrix );
  394. uniforms[ "lightPositionVS" ].value.copy( positionVS );
  395. rightVS.copy( light.right );
  396. rightVS.transformDirection( modelMatrix );
  397. rightVS.transformDirection( viewMatrix );
  398. normalVS.copy( light.normal );
  399. normalVS.transformDirection( modelMatrix );
  400. normalVS.transformDirection( viewMatrix );
  401. upVS.crossVectors( rightVS, normalVS );
  402. upVS.normalize();
  403. uniforms[ "lightRightVS" ].value.copy( rightVS );
  404. uniforms[ "lightNormalVS" ].value.copy( normalVS );
  405. uniforms[ "lightUpVS" ].value.copy( upVS );
  406. uniforms[ "lightWidth" ].value = light.width;
  407. uniforms[ "lightHeight" ].value = light.height;
  408. uniforms[ "constantAttenuation" ].value = light.constantAttenuation;
  409. uniforms[ "linearAttenuation" ].value = light.linearAttenuation;
  410. uniforms[ "quadraticAttenuation" ].value = light.quadraticAttenuation;
  411. // linear space colors
  412. var intensity = light.intensity * light.intensity;
  413. uniforms[ "lightIntensity" ].value = intensity;
  414. uniforms[ "lightColor" ].value.copyGammaToLinear( light.color );
  415. };
  416. var createDeferredAreaLight = function ( light ) {
  417. // setup light material
  418. var uniforms = THREE.UniformsUtils.clone( areaLightShader.uniforms );
  419. var materialLight = new THREE.ShaderMaterial( {
  420. uniforms: uniforms,
  421. vertexShader: areaLightShader.vertexShader,
  422. fragmentShader: areaLightShader.fragmentShader,
  423. blending: THREE.AdditiveBlending,
  424. depthWrite: false,
  425. depthTest: false,
  426. transparent: true
  427. } );
  428. uniforms[ "viewWidth" ].value = scaledWidth;
  429. uniforms[ "viewHeight" ].value = scaledHeight;
  430. uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
  431. uniforms[ 'samplerNormalDepth' ].value = compNormalDepth.renderTarget2;
  432. // create light proxy mesh
  433. var meshLight = new THREE.Mesh( geometryLightPlane, materialLight );
  434. // keep reference for color and intensity updates
  435. meshLight.userData.originalLight = light;
  436. // keep reference for size reset
  437. resizableMaterials.push( { "material": materialLight } );
  438. // sync proxy uniforms to the original light
  439. updateAreaLightProxy( meshLight );
  440. return meshLight;
  441. };
  442. var createDeferredEmissiveLight = function () {
  443. // setup light material
  444. var materialLight = new THREE.ShaderMaterial( {
  445. uniforms: THREE.UniformsUtils.clone( emissiveLightShader.uniforms ),
  446. vertexShader: emissiveLightShader.vertexShader,
  447. fragmentShader: emissiveLightShader.fragmentShader,
  448. depthTest: false,
  449. depthWrite: false,
  450. blending: THREE.NoBlending
  451. } );
  452. materialLight.uniforms[ "viewWidth" ].value = scaledWidth;
  453. materialLight.uniforms[ "viewHeight" ].value = scaledHeight;
  454. materialLight.uniforms[ 'samplerColor' ].value = compColor.renderTarget2;
  455. // create light proxy mesh
  456. var meshLight = new THREE.Mesh( geometryLightPlane, materialLight );
  457. // keep reference for size reset
  458. resizableMaterials.push( { "material": materialLight } );
  459. return meshLight;
  460. };
  461. var initDeferredProperties = function ( object ) {
  462. if ( object.userData.deferredInitialized ) return;
  463. if ( object.material ) initDeferredMaterials( object );
  464. if ( object instanceof THREE.PointLight ) {
  465. var proxy = createDeferredPointLight( object );
  466. if ( object.distance > 0 ) {
  467. lightSceneProxy.add( proxy );
  468. } else {
  469. lightSceneFullscreen.add( proxy );
  470. }
  471. } else if ( object instanceof THREE.SpotLight ) {
  472. var proxy = createDeferredSpotLight( object );
  473. lightSceneFullscreen.add( proxy );
  474. } else if ( object instanceof THREE.DirectionalLight ) {
  475. var proxy = createDeferredDirectionalLight( object );
  476. lightSceneFullscreen.add( proxy );
  477. } else if ( object instanceof THREE.HemisphereLight ) {
  478. var proxy = createDeferredHemisphereLight( object );
  479. lightSceneFullscreen.add( proxy );
  480. } else if ( object instanceof THREE.AreaLight ) {
  481. var proxy = createDeferredAreaLight( object );
  482. lightSceneFullscreen.add( proxy );
  483. }
  484. object.userData.deferredInitialized = true;
  485. };
  486. //
  487. var setMaterialColor = function ( object ) {
  488. if ( object.material ) {
  489. if ( object.userData.transparent ) {
  490. object.material = invisibleMaterial;
  491. } else {
  492. object.material = object.userData.colorMaterial;
  493. }
  494. }
  495. };
  496. var setMaterialNormalDepth = function ( object ) {
  497. if ( object.material ) {
  498. if ( object.userData.transparent ) {
  499. object.material = invisibleMaterial;
  500. } else {
  501. object.material = object.userData.normalDepthMaterial;
  502. }
  503. }
  504. };
  505. // external API
  506. this.setAntialias = function ( enabled ) {
  507. antialias = enabled;
  508. if ( antialias ) {
  509. effectFXAA.enabled = true;
  510. compositePass.renderToScreen = false;
  511. } else {
  512. effectFXAA.enabled = false;
  513. compositePass.renderToScreen = true;
  514. }
  515. };
  516. this.getAntialias = function () {
  517. return antialias;
  518. };
  519. this.addEffect = function ( effect, normalDepthUniform, colorUniform ) {
  520. if ( effect.material && effect.uniforms ) {
  521. if ( normalDepthUniform ) effect.uniforms[ normalDepthUniform ].value = compNormalDepth.renderTarget2;
  522. if ( colorUniform ) effect.uniforms[ colorUniform ].value = compColor.renderTarget2;
  523. if ( normalDepthUniform || colorUniform ) {
  524. resizableMaterials.push( { "material": effect.material, "normalDepth": normalDepthUniform, "color": colorUniform } );
  525. }
  526. }
  527. compFinal.insertPass( effect, -1 );
  528. };
  529. this.setScale = function ( scale ) {
  530. currentScale = scale;
  531. scaledWidth = Math.floor( currentScale * fullWidth );
  532. scaledHeight = Math.floor( currentScale * fullHeight );
  533. compNormalDepth.setSize( scaledWidth, scaledHeight );
  534. compColor.setSize( scaledWidth, scaledHeight );
  535. compLight.setSize( scaledWidth, scaledHeight );
  536. compFinal.setSize( scaledWidth, scaledHeight );
  537. compColor.renderTarget2.shareDepthFrom = compNormalDepth.renderTarget2;
  538. compLight.renderTarget2.shareDepthFrom = compNormalDepth.renderTarget2;
  539. for ( var i = 0, il = resizableMaterials.length; i < il; i ++ ) {
  540. var materialEntry = resizableMaterials[ i ];
  541. var material = materialEntry.material;
  542. var uniforms = material.uniforms;
  543. var colorLabel = materialEntry.color !== undefined ? materialEntry.color : 'samplerColor';
  544. var normalDepthLabel = materialEntry.normalDepth !== undefined ? materialEntry.normalDepth : 'samplerNormalDepth';
  545. if ( uniforms[ colorLabel ] ) uniforms[ colorLabel ].value = compColor.renderTarget2;
  546. if ( uniforms[ normalDepthLabel ] ) uniforms[ normalDepthLabel ].value = compNormalDepth.renderTarget2;
  547. if ( uniforms[ 'viewWidth' ] ) uniforms[ "viewWidth" ].value = scaledWidth;
  548. if ( uniforms[ 'viewHeight' ] ) uniforms[ "viewHeight" ].value = scaledHeight;
  549. }
  550. compositePass.uniforms[ 'samplerLight' ].value = compLight.renderTarget2;
  551. effectFXAA.uniforms[ 'resolution' ].value.set( 1 / fullWidth, 1 / fullHeight );
  552. };
  553. this.setSize = function ( width, height ) {
  554. fullWidth = width;
  555. fullHeight = height;
  556. this.renderer.setSize( fullWidth, fullHeight );
  557. this.setScale( currentScale );
  558. };
  559. //
  560. function updateLightProxy ( proxy ) {
  561. var uniforms = proxy.material.uniforms;
  562. if ( uniforms[ "matProjInverse" ] ) uniforms[ "matProjInverse" ].value = currentCamera.projectionMatrixInverse;
  563. if ( uniforms[ "matView" ] ) uniforms[ "matView" ].value = currentCamera.matrixWorldInverse;
  564. var originalLight = proxy.userData.originalLight;
  565. if ( originalLight ) {
  566. proxy.visible = originalLight.visible;
  567. if ( originalLight instanceof THREE.PointLight ) {
  568. updatePointLightProxy( proxy );
  569. } else if ( originalLight instanceof THREE.SpotLight ) {
  570. updateSpotLightProxy( proxy );
  571. } else if ( originalLight instanceof THREE.DirectionalLight ) {
  572. updateDirectionalLightProxy( proxy );
  573. } else if ( originalLight instanceof THREE.HemisphereLight ) {
  574. updateHemisphereLightProxy( proxy );
  575. } else if ( originalLight instanceof THREE.AreaLight ) {
  576. updateAreaLightProxy( proxy );
  577. }
  578. }
  579. };
  580. this.render = function ( scene, camera ) {
  581. // setup deferred properties
  582. if ( ! scene.userData.lightSceneProxy ) {
  583. scene.userData.lightSceneProxy = new THREE.Scene();
  584. scene.userData.lightSceneFullscreen = new THREE.Scene();
  585. var meshLight = createDeferredEmissiveLight();
  586. scene.userData.lightSceneFullscreen.add( meshLight );
  587. }
  588. currentCamera = camera;
  589. lightSceneProxy = scene.userData.lightSceneProxy;
  590. lightSceneFullscreen = scene.userData.lightSceneFullscreen;
  591. passColor.camera = currentCamera;
  592. passNormalDepth.camera = currentCamera;
  593. passLightProxy.camera = currentCamera;
  594. passLightFullscreen.camera = THREE.EffectComposer.camera;
  595. passColor.scene = scene;
  596. passNormalDepth.scene = scene;
  597. passLightFullscreen.scene = lightSceneFullscreen;
  598. passLightProxy.scene = lightSceneProxy;
  599. scene.traverse( initDeferredProperties );
  600. // update scene graph only once per frame
  601. // (both color and normalDepth passes use exactly the same scene state)
  602. scene.autoUpdate = false;
  603. scene.updateMatrixWorld();
  604. // 1) g-buffer normals + depth pass
  605. scene.traverse( setMaterialNormalDepth );
  606. // clear shared depth buffer
  607. this.renderer.autoClearDepth = true;
  608. this.renderer.autoClearStencil = true;
  609. // write 1 to shared stencil buffer
  610. // for non-background pixels
  611. //gl.enable( gl.STENCIL_TEST );
  612. gl.stencilOp( gl.REPLACE, gl.REPLACE, gl.REPLACE );
  613. gl.stencilFunc( gl.ALWAYS, 1, 0xffffffff );
  614. gl.clearStencil( 0 );
  615. compNormalDepth.render();
  616. // just touch foreground pixels (stencil == 1)
  617. // both in color and light passes
  618. gl.stencilFunc( gl.EQUAL, 1, 0xffffffff );
  619. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  620. // 2) g-buffer color pass
  621. scene.traverse( setMaterialColor );
  622. // must use clean slate depth buffer
  623. // otherwise there are z-fighting glitches
  624. // not enough precision between two geometry passes
  625. // just to use EQUAL depth test
  626. this.renderer.autoClearDepth = true;
  627. this.renderer.autoClearStencil = false;
  628. compColor.render();
  629. // 3) light pass
  630. // do not clear depth buffer in this pass
  631. // depth from geometry pass is used for light culling
  632. // (write light proxy color pixel if behind scene pixel)
  633. this.renderer.autoClearDepth = false;
  634. scene.autoUpdate = true;
  635. gl.depthFunc( gl.GEQUAL );
  636. currentCamera.projectionMatrixInverse.getInverse( currentCamera.projectionMatrix );
  637. for ( var i = 0, il = lightSceneProxy.children.length; i < il; i ++ ) {
  638. var proxy = lightSceneProxy.children[ i ];
  639. updateLightProxy( proxy );
  640. }
  641. for ( var i = 0, il = lightSceneFullscreen.children.length; i < il; i ++ ) {
  642. var proxy = lightSceneFullscreen.children[ i ];
  643. updateLightProxy( proxy );
  644. }
  645. compLight.render();
  646. // 4) composite pass
  647. // return back to usual depth and stencil handling state
  648. this.renderer.autoClearDepth = true;
  649. this.renderer.autoClearStencil = true;
  650. gl.depthFunc( gl.LEQUAL );
  651. gl.disable( gl.STENCIL_TEST );
  652. compFinal.render( 0.1 );
  653. };
  654. //
  655. var createRenderTargets = function ( ) {
  656. var rtParamsFloatLinear = { minFilter: THREE.NearestFilter, magFilter: THREE.LinearFilter, stencilBuffer: true,
  657. format: THREE.RGBAFormat, type: THREE.FloatType };
  658. var rtParamsFloatNearest = { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, stencilBuffer: true,
  659. format: THREE.RGBAFormat, type: THREE.FloatType };
  660. var rtParamsUByte = { minFilter: THREE.NearestFilter, magFilter: THREE.LinearFilter, stencilBuffer: false,
  661. format: THREE.RGBFormat, type: THREE.UnsignedByteType };
  662. // g-buffers
  663. var rtColor = new THREE.WebGLRenderTarget( scaledWidth, scaledHeight, rtParamsFloatNearest );
  664. var rtNormalDepth = new THREE.WebGLRenderTarget( scaledWidth, scaledHeight, rtParamsFloatNearest );
  665. var rtLight = new THREE.WebGLRenderTarget( scaledWidth, scaledHeight, rtParamsFloatLinear );
  666. var rtFinal = new THREE.WebGLRenderTarget( scaledWidth, scaledHeight, rtParamsUByte );
  667. rtColor.generateMipmaps = false;
  668. rtNormalDepth.generateMipmaps = false;
  669. rtLight.generateMipmaps = false;
  670. rtFinal.generateMipmaps = false;
  671. // normal + depth composer
  672. passNormalDepth = new THREE.RenderPass();
  673. passNormalDepth.clear = true;
  674. compNormalDepth = new THREE.EffectComposer( _this.renderer, rtNormalDepth );
  675. compNormalDepth.addPass( passNormalDepth );
  676. // color composer
  677. passColor = new THREE.RenderPass();
  678. passColor.clear = true;
  679. compColor = new THREE.EffectComposer( _this.renderer, rtColor );
  680. compColor.addPass( passColor );
  681. compColor.renderTarget2.shareDepthFrom = compNormalDepth.renderTarget2;
  682. // light composer
  683. passLightFullscreen = new THREE.RenderPass();
  684. passLightFullscreen.clear = true;
  685. passLightProxy = new THREE.RenderPass();
  686. passLightProxy.clear = false;
  687. compLight = new THREE.EffectComposer( _this.renderer, rtLight );
  688. compLight.addPass( passLightFullscreen );
  689. compLight.addPass( passLightProxy );
  690. compLight.renderTarget2.shareDepthFrom = compNormalDepth.renderTarget2;
  691. // final composer
  692. compositePass = new THREE.ShaderPass( compositeShader );
  693. compositePass.uniforms[ 'samplerLight' ].value = compLight.renderTarget2;
  694. compositePass.uniforms[ 'brightness' ].value = brightness;
  695. compositePass.material.blending = THREE.NoBlending;
  696. compositePass.clear = true;
  697. var defines;
  698. switch ( tonemapping ) {
  699. case THREE.SimpleOperator: defines = { "TONEMAP_SIMPLE": true }; break;
  700. case THREE.LinearOperator: defines = { "TONEMAP_LINEAR": true }; break;
  701. case THREE.ReinhardOperator: defines = { "TONEMAP_REINHARD": true }; break;
  702. case THREE.FilmicOperator: defines = { "TONEMAP_FILMIC": true }; break;
  703. case THREE.UnchartedOperator: defines = { "TONEMAP_UNCHARTED": true }; break;
  704. }
  705. compositePass.material.defines = defines;
  706. // FXAA
  707. effectFXAA = new THREE.ShaderPass( THREE.FXAAShader );
  708. effectFXAA.uniforms[ 'resolution' ].value.set( 1 / fullWidth, 1 / fullHeight );
  709. effectFXAA.renderToScreen = true;
  710. //
  711. compFinal = new THREE.EffectComposer( _this.renderer, rtFinal );
  712. compFinal.addPass( compositePass );
  713. compFinal.addPass( effectFXAA );
  714. if ( antialias ) {
  715. effectFXAA.enabled = true;
  716. compositePass.renderToScreen = false;
  717. } else {
  718. effectFXAA.enabled = false;
  719. compositePass.renderToScreen = true;
  720. }
  721. };
  722. // init
  723. createRenderTargets();
  724. };
  725. // tonemapping operator types
  726. THREE.NoOperator = 0;
  727. THREE.SimpleOperator = 1;
  728. THREE.LinearOperator = 2;
  729. THREE.ReinhardOperator = 3;
  730. THREE.FilmicOperator = 4;
  731. THREE.UnchartedOperator = 5;