webgl_tiled_forward.html 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - tiled forward lighting</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  7. <style>
  8. body {
  9. font-family: Monospace;
  10. background-color: #101010;
  11. color: #fff;
  12. margin: 0px;
  13. overflow: hidden;
  14. }
  15. a { color: #f00; }
  16. #info {
  17. position: absolute;
  18. left: 0;
  19. top: 0px; width: 100%;
  20. padding: 5px;
  21. display: inline-block;
  22. text-align:center;
  23. }
  24. </style>
  25. </head>
  26. <body>
  27. <div id="info">
  28. <a href="http://threejs.org" target="_blank" rel="noopener">threejs</a> - Tiled forward lighting<br/>
  29. Created by <a href="https://github.com/wizgrav" target="_blank" rel="noopener">wizgrav</a>.
  30. </div>
  31. <script src="../build/three.js"></script>
  32. <script src="js/loaders/OBJLoader.js"></script>
  33. <script src="js/controls/OrbitControls.js"></script>
  34. <script src="js/postprocessing/EffectComposer.js"></script>
  35. <script src="js/postprocessing/RenderPass.js"></script>
  36. <script src="js/postprocessing/MaskPass.js"></script>
  37. <script src="js/postprocessing/ShaderPass.js"></script>
  38. <script src="js/shaders/CopyShader.js"></script>
  39. <script src="js/shaders/ConvolutionShader.js"></script>
  40. <script src="js/shaders/LuminosityHighPassShader.js"></script>
  41. <script src="js/postprocessing/UnrealBloomPass.js"></script>
  42. <script src="js/WebGL.js"></script>
  43. <script src="js/libs/stats.min.js"></script>
  44. <script>
  45. // Simple form of tiled forward lighting
  46. // using texels as bitmasks of 32 lights
  47. var RADIUS = 75;
  48. THREE.ShaderChunk[ 'lights_pars_begin' ] += [
  49. '#if defined TILED_FORWARD',
  50. 'uniform vec4 tileData;',
  51. 'uniform sampler2D tileTexture;',
  52. 'uniform sampler2D lightTexture;',
  53. '#endif'
  54. ].join( '\n' );
  55. THREE.ShaderChunk[ 'lights_fragment_end' ] += [
  56. '',
  57. '#if defined TILED_FORWARD',
  58. 'vec2 tUv = floor(gl_FragCoord.xy / tileData.xy * 32.) / 32. + tileData.zw;',
  59. 'vec4 tile = texture2D(tileTexture, tUv);',
  60. 'for (int i=0; i < 4; i++) {',
  61. ' float tileVal = tile.x * 255.;',
  62. ' tile.xyzw = tile.yzwx;',
  63. ' if(tileVal == 0.){ continue; }',
  64. ' float tileDiv = 128.;',
  65. ' for (int j=0; j < 8; j++) {',
  66. ' if (tileVal < tileDiv) { tileDiv *= 0.5; continue; }',
  67. ' tileVal -= tileDiv;',
  68. ' tileDiv *= 0.5;',
  69. ' PointLight pointlight;',
  70. ' float uvx = (float(8 * i + j) + 0.5) / 32.;',
  71. ' vec4 lightData = texture2D(lightTexture, vec2(uvx, 0.));',
  72. ' vec4 lightColor = texture2D(lightTexture, vec2(uvx, 1.));',
  73. ' pointlight.position = lightData.xyz;',
  74. ' pointlight.distance = lightData.w;',
  75. ' pointlight.color = lightColor.rgb;',
  76. ' pointlight.decay = lightColor.a;',
  77. ' getPointDirectLightIrradiance( pointlight, geometry, directLight );',
  78. ' RE_Direct( directLight, geometry, material, reflectedLight );',
  79. ' }',
  80. '}',
  81. '#endif'
  82. ].join( '\n' );
  83. var lights = [];
  84. var State = {
  85. rows: 0,
  86. cols: 0,
  87. width: 0,
  88. height: 0,
  89. tileData: { value: null },
  90. tileTexture: { value: null },
  91. lightTexture: {
  92. value: new THREE.DataTexture( new Float32Array( 32 * 2 * 4 ), 32, 2, THREE.RGBAFormat, THREE.FloatType )
  93. },
  94. };
  95. function resizeTiles() {
  96. var width = window.innerWidth;
  97. var height = window.innerHeight;
  98. State.width = width;
  99. State.height = height;
  100. State.cols = Math.ceil( width / 32 );
  101. State.rows = Math.ceil( height / 32 );
  102. State.tileData.value = [ width, height, 0.5 / Math.ceil( width / 32 ), 0.5 / Math.ceil( height / 32 ) ];
  103. State.tileTexture.value = new THREE.DataTexture( new Uint8Array( State.cols * State.rows * 4 ), State.cols, State.rows );
  104. }
  105. // Generate the light bitmasks and store them in the tile texture
  106. function tileLights( renderer, scene, camera ) {
  107. if ( ! camera.projectionMatrix ) return;
  108. var d = State.tileTexture.value.image.data;
  109. var ld = State.lightTexture.value.image.data;
  110. var viewMatrix = camera.matrixWorldInverse;
  111. d.fill( 0 );
  112. var vector = new THREE.Vector3();
  113. lights.forEach( function ( light, index ) {
  114. vector.setFromMatrixPosition( light.matrixWorld );
  115. var bs = lightBounds( camera, vector, light._light.radius );
  116. vector.applyMatrix4( viewMatrix );
  117. vector.toArray( ld, 4 * index );
  118. ld[ 4 * index + 3 ] = light._light.radius;
  119. light._light.color.toArray( ld, 32 * 4 + 4 * index );
  120. ld[ 32 * 4 + 4 * index + 3 ] = light._light.decay;
  121. if ( bs[ 1 ] < 0 || bs[ 0 ] > State.width || bs[ 3 ] < 0 || bs[ 2 ] > State.height ) return;
  122. if ( bs[ 0 ] < 0 ) bs[ 0 ] = 0;
  123. if ( bs[ 1 ] > State.width ) bs[ 1 ] = State.width;
  124. if ( bs[ 2 ] < 0 ) bs[ 2 ] = 0;
  125. if ( bs[ 3 ] > State.height ) bs[ 3 ] = State.height;
  126. var i4 = Math.floor( index / 8 ), i8 = 7 - ( index % 8 );
  127. for ( var i = Math.floor( bs[ 2 ] / 32 ); i <= Math.ceil( bs[ 3 ] / 32 ); i ++ ) {
  128. for ( var j = Math.floor( bs[ 0 ] / 32 ); j <= Math.ceil( bs[ 1 ] / 32 ); j ++ ) {
  129. d[ ( State.cols * i + j ) * 4 + i4 ] |= 1 << i8;
  130. }
  131. }
  132. } );
  133. State.tileTexture.value.needsUpdate = true;
  134. State.lightTexture.value.needsUpdate = true;
  135. }
  136. // Screen rectangle bounds from light sphere's world AABB
  137. var lightBounds = function () {
  138. var v = new THREE.Vector3();
  139. return function ( camera, pos, r ) {
  140. var minX = State.width, maxX = 0, minY = State.height, maxY = 0, hw = State.width / 2, hh = State.height / 2;
  141. for ( var i = 0; i < 8; i ++ ) {
  142. v.copy( pos );
  143. v.x += i & 1 ? r : - r;
  144. v.y += i & 2 ? r : - r;
  145. v.z += i & 4 ? r : - r;
  146. var vector = v.project( camera );
  147. var x = ( vector.x * hw ) + hw;
  148. var y = ( vector.y * hh ) + hh;
  149. minX = Math.min( minX, x );
  150. maxX = Math.max( maxX, x );
  151. minY = Math.min( minY, y );
  152. maxY = Math.max( maxY, y );
  153. }
  154. return [ minX, maxX, minY, maxY ];
  155. };
  156. }();
  157. // Rendering
  158. var container = document.createElement( 'div' );
  159. document.body.appendChild( container );
  160. var camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 2000 );
  161. camera.position.set( 0.0, 0.0, 240.0 );
  162. var scene = new THREE.Scene();
  163. scene.background = new THREE.Color( 0x111111 );
  164. var renderer = new THREE.WebGLRenderer();
  165. renderer.toneMapping = THREE.LinearToneMapping;
  166. container.appendChild( renderer.domElement );
  167. var renderTarget = new THREE.WebGLRenderTarget();
  168. scene.add( new THREE.AmbientLight( 0xffffff, 0.33 ) );
  169. // At least one regular Pointlight is needed to activate light support
  170. scene.add( new THREE.PointLight( 0xff0000, 0.1, 0.1 ) );
  171. var bloom = new THREE.UnrealBloomPass( new THREE.Vector2(), 0.8, 0.6, 0.8 );
  172. bloom.renderToScreen = true;
  173. var stats = new Stats();
  174. container.appendChild( stats.dom );
  175. var controls = new THREE.OrbitControls( camera, renderer.domElement );
  176. controls.minDistance = 120;
  177. controls.maxDistance = 320;
  178. var materials = [];
  179. var Heads = [
  180. { type: 'physical', uniforms: { diffuse: 0x888888, metalness: 1.0, roughness: 0.66 }, defines: {} },
  181. { type: 'standard', uniforms: { diffuse: 0x666666, metalness: 0.1, roughness: 0.33 }, defines: {} },
  182. { type: 'phong', uniforms: { diffuse: 0x777777, shininess: 20 }, defines: {} },
  183. { type: 'phong', uniforms: { diffuse: 0x555555, shininess: 10 }, defines: { TOON: 1 } }
  184. ];
  185. function init( geom ) {
  186. var sphereGeom = new THREE.SphereBufferGeometry( 0.5, 32, 32 );
  187. var tIndex = Math.round( Math.random() * 3 );
  188. Object.keys( Heads ).forEach( function ( t, index ) {
  189. var g = new THREE.Group();
  190. var conf = Heads[ t ];
  191. var ml = THREE.ShaderLib[ conf.type ];
  192. var mtl = new THREE.ShaderMaterial( {
  193. lights: true,
  194. fragmentShader: ml.fragmentShader,
  195. vertexShader: ml.vertexShader,
  196. uniforms: THREE.UniformsUtils.clone( ml.uniforms ),
  197. defines: conf.defines,
  198. transparent: tIndex === index ? true : false,
  199. } );
  200. mtl.uniforms.opacity.value = tIndex === index ? 0.9 : 1;
  201. mtl.uniforms.tileData = State.tileData;
  202. mtl.uniforms.tileTexture = State.tileTexture;
  203. mtl.uniforms.lightTexture = State.lightTexture;
  204. for ( var u in conf.uniforms ) {
  205. var vu = conf.uniforms[ u ];
  206. if ( mtl.uniforms[ u ].value.set ) {
  207. mtl.uniforms[ u ].value.set( vu );
  208. } else {
  209. mtl.uniforms[ u ].value = vu;
  210. }
  211. }
  212. mtl.defines[ 'TILED_FORWARD' ] = 1;
  213. materials.push( mtl );
  214. var obj = new THREE.Mesh( geom, mtl );
  215. obj.position.y = - 37;
  216. mtl.side = tIndex === index ? THREE.FrontSide : THREE.DoubleSide;
  217. g.rotation.y = index * Math.PI / 2;
  218. g.position.x = Math.sin( index * Math.PI / 2 ) * RADIUS;
  219. g.position.z = Math.cos( index * Math.PI / 2 ) * RADIUS;
  220. g.add( obj );
  221. for ( var i = 0; i < 8; i ++ ) {
  222. var color = new THREE.Color().setHSL( Math.random(), 1.0, 0.5 );
  223. var l = new THREE.Group();
  224. l.add( new THREE.Mesh(
  225. sphereGeom,
  226. new THREE.MeshBasicMaterial( {
  227. color: color
  228. } )
  229. ) );
  230. l.add( new THREE.Mesh(
  231. sphereGeom,
  232. new THREE.MeshBasicMaterial( {
  233. color: color,
  234. transparent: true,
  235. opacity: 0.033
  236. } )
  237. ) );
  238. l.children[ 1 ].scale.set( 6.66, 6.66, 6.66 );
  239. l._light = {
  240. color: color,
  241. radius: RADIUS,
  242. decay: 1,
  243. sy: Math.random(),
  244. sr: Math.random(),
  245. sc: Math.random(),
  246. py: Math.random() * Math.PI,
  247. pr: Math.random() * Math.PI,
  248. pc: Math.random() * Math.PI,
  249. dir: Math.random() > 0.5 ? 1 : - 1
  250. };
  251. lights.push( l );
  252. g.add( l );
  253. }
  254. scene.add( g );
  255. } );
  256. }
  257. function update( now ) {
  258. lights.forEach( function ( l ) {
  259. var ld = l._light;
  260. var radius = 0.8 + 0.2 * Math.sin( ld.pr + ( 0.6 + 0.3 * ld.sr ) * now );
  261. l.position.x = ( Math.sin( ld.pc + ( 0.8 + 0.2 * ld.sc ) * now * ld.dir ) ) * radius * RADIUS;
  262. l.position.z = ( Math.cos( ld.pc + ( 0.8 + 0.2 * ld.sc ) * now * ld.dir ) ) * radius * RADIUS;
  263. l.position.y = Math.sin( ld.py + ( 0.8 + 0.2 * ld.sy ) * now ) * radius * 32;
  264. } );
  265. }
  266. function resize() {
  267. renderer.setPixelRatio( window.devicePixelRatio );
  268. renderer.setSize( window.innerWidth, window.innerHeight );
  269. renderTarget.setSize( window.innerWidth, window.innerHeight );
  270. bloom.setSize( window.innerWidth, window.innerHeight );
  271. camera.aspect = window.innerWidth / window.innerHeight;
  272. camera.updateProjectionMatrix();
  273. resizeTiles();
  274. }
  275. function postEffect( renderer ) {
  276. bloom.render( renderer, null, renderTarget );
  277. }
  278. scene.onBeforeRender = tileLights;
  279. scene.onAfterRender = postEffect;
  280. var loader = new THREE.OBJLoader();
  281. loader.load( 'models/obj/walt/WaltHead.obj', function ( object ) {
  282. var geometry = object.children[ 0 ].geometry;
  283. window.addEventListener( 'resize', resize );
  284. init( geometry );
  285. resize();
  286. renderer.setAnimationLoop( function ( time ) {
  287. update( time / 1000 );
  288. stats.begin();
  289. renderer.render( scene, camera, renderTarget );
  290. stats.end();
  291. } );
  292. } );
  293. </script>
  294. </body>
  295. </html>