webgl_tiled_forward.html 11 KB

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