webgl_tiled_forward.html 11 KB

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