webgl_tiled_forward.html 11 KB

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