main.js 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465
  1. const { mat4, mat3, vec2, vec3, vec4, quat } = glMatrix;
  2. let GL = null;
  3. const _OPAQUE_VS = `#version 300 es
  4. precision highp float;
  5. uniform mat3 normalMatrix;
  6. uniform mat4 modelMatrix;
  7. uniform mat4 modelViewMatrix;
  8. uniform mat4 projectionMatrix;
  9. in vec3 position;
  10. in vec3 normal;
  11. in vec3 tangent;
  12. in vec4 colour;
  13. in vec2 uv0;
  14. out vec2 vUV0;
  15. out vec4 vColour;
  16. void main(void) {
  17. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  18. vColour = colour;
  19. vUV0 = uv0;
  20. }
  21. `;
  22. const _OPAQUE_FS = `#version 300 es
  23. precision highp float;
  24. uniform sampler2D diffuseTexture;
  25. uniform sampler2D normalTexture;
  26. uniform sampler2D gBuffer_Light;
  27. uniform vec4 resolution;
  28. in vec4 vColour;
  29. in vec2 vUV0;
  30. layout(location = 0) out vec4 out_FragColour;
  31. void main(void) {
  32. vec2 uv = gl_FragCoord.xy / resolution.xy;
  33. vec4 lightSample = texture(gBuffer_Light, uv);
  34. vec4 albedo = texture(diffuseTexture, vUV0);
  35. out_FragColour = (albedo * vec4(lightSample.xyz, 1.0) +
  36. lightSample.w * vec4(0.3, 0.6, 0.1, 0.0));
  37. }
  38. `;
  39. const _QUAD_VS = `#version 300 es
  40. precision highp float;
  41. uniform mat4 modelViewMatrix;
  42. uniform mat4 projectionMatrix;
  43. in vec3 position;
  44. in vec2 uv0;
  45. void main(void) {
  46. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  47. }
  48. `;
  49. const _QUAD_FS = `#version 300 es
  50. precision highp float;
  51. uniform sampler2D gBuffer_Normal;
  52. uniform sampler2D gBuffer_Position;
  53. uniform vec3 lightColour;
  54. #define _LIGHT_TYPE_POINT
  55. #ifdef _LIGHT_TYPE_DIRECTIONAL
  56. uniform vec3 lightDirection;
  57. #endif
  58. uniform vec3 lightPosition;
  59. uniform vec3 lightAttenuation;
  60. uniform vec3 cameraPosition;
  61. uniform vec4 resolution;
  62. out vec4 out_FragColour;
  63. #define saturate(a) clamp(a, 0.0, 1.0)
  64. float _SmootherStep(float x, float a, float b) {
  65. x = x * x * x * (x * (x * 6.0 - 15.0) + 10.0);
  66. return x * (b - a) + a;
  67. }
  68. vec2 _CalculatePhong(vec3 lightDirection, vec3 cameraPosition, vec3 position, vec3 normal) {
  69. vec3 viewDirection = normalize(cameraPosition - position);
  70. vec3 H = normalize(lightDirection.xyz + viewDirection);
  71. float NdotH = dot(normal.xyz, H);
  72. float specular = saturate(pow(NdotH, 32.0));
  73. float diffuse = saturate(dot(lightDirection.xyz, normal.xyz));
  74. return vec2(diffuse, diffuse * specular);
  75. }
  76. vec4 _CalculateLight_Directional(
  77. vec3 lightDirection, vec3 lightColour, vec3 position, vec3 normal) {
  78. vec2 lightSample = _CalculatePhong(-lightDirection, cameraPosition, position, normal);
  79. return vec4(lightSample.x * lightColour, lightSample.y);
  80. }
  81. vec4 _CalculateLight_Point(
  82. vec3 lightPosition, vec3 lightAttenuation, vec3 lightColour, vec3 position, vec3 normal) {
  83. vec3 dirToLight = lightPosition - position;
  84. float lightDistance = length(dirToLight);
  85. dirToLight = normalize(dirToLight);
  86. vec2 lightSample = _CalculatePhong(dirToLight, cameraPosition, position, normal);
  87. float falloff = saturate((lightDistance - lightAttenuation.x) / lightAttenuation.y);
  88. lightSample *= _SmootherStep(falloff, 1.0, 0.0);
  89. return vec4(lightSample.x * lightColour, lightSample.y);
  90. }
  91. void main(void) {
  92. vec2 uv = gl_FragCoord.xy / resolution.xy;
  93. vec4 normal = texture(gBuffer_Normal, uv);
  94. vec4 position = texture(gBuffer_Position, uv);
  95. #ifdef _LIGHT_TYPE_DIRECTIONAL
  96. vec4 lightSample = _CalculateLight_Directional(
  97. lightDirection, lightColour, position.xyz, normal.xyz);
  98. #elif defined(_LIGHT_TYPE_POINT)
  99. vec4 lightSample = _CalculateLight_Point(
  100. lightPosition, lightAttenuation, lightColour, position.xyz, normal.xyz);
  101. #endif
  102. out_FragColour = lightSample;
  103. }
  104. `;
  105. const _QUAD_COLOUR_VS = `#version 300 es
  106. precision highp float;
  107. uniform mat4 modelViewMatrix;
  108. uniform mat4 projectionMatrix;
  109. in vec3 position;
  110. in vec2 uv0;
  111. void main(void) {
  112. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  113. }
  114. `;
  115. const _QUAD_COLOUR_FS = `#version 300 es
  116. precision highp float;
  117. uniform sampler2D gQuadTexture;
  118. uniform vec4 resolution;
  119. out vec4 out_FragColour;
  120. void main(void) {
  121. vec2 uv = gl_FragCoord.xy / resolution.xy;
  122. out_FragColour = texture(gQuadTexture, uv);
  123. }
  124. `;
  125. const _SIMPLE_VS = `#version 300 es
  126. precision highp float;
  127. uniform mat3 normalMatrix;
  128. uniform mat4 modelMatrix;
  129. uniform mat4 modelViewMatrix;
  130. uniform mat4 projectionMatrix;
  131. in vec3 position;
  132. in vec3 normal;
  133. in vec3 tangent;
  134. in vec2 uv0;
  135. out vec4 vWSPosition;
  136. out vec3 vNormal;
  137. out vec3 vTangent;
  138. out vec2 vUV0;
  139. void main(void) {
  140. gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  141. vNormal = normalize(normalMatrix * normal);
  142. vTangent = normalize(normalMatrix * tangent);
  143. vWSPosition = modelMatrix * vec4(position, 1.0);
  144. vUV0 = uv0;
  145. }
  146. `;
  147. const _SIMPLE_FS = `#version 300 es
  148. precision highp float;
  149. uniform sampler2D normalTexture;
  150. in vec4 vWSPosition;
  151. in vec3 vNormal;
  152. in vec3 vTangent;
  153. in vec2 vUV0;
  154. layout(location = 0) out vec4 out_Normals;
  155. layout(location = 1) out vec4 out_Position;
  156. void main(void) {
  157. vec3 bitangent = normalize(cross(vTangent, vNormal));
  158. mat3 tbn = mat3(vTangent, bitangent, vNormal);
  159. vec3 normalSample = normalize(texture(normalTexture, vUV0).xyz * 2.0 - 1.0);
  160. vec3 vsNormal = normalize(tbn * normalSample);
  161. out_Normals = vec4(vsNormal, 1.0);
  162. out_Position = vWSPosition;
  163. }
  164. `;
  165. class Shader {
  166. constructor(vsrc, fsrc, defines) {
  167. defines = defines || [];
  168. this._Init(vsrc, fsrc, defines);
  169. }
  170. _Init(vsrc, fsrc, defines) {
  171. this._defines = defines;
  172. vsrc = this._ModifySourceWithDefines(vsrc, defines);
  173. fsrc = this._ModifySourceWithDefines(fsrc, defines);
  174. this._vsSource = vsrc;
  175. this._fsSource = fsrc;
  176. this._vsProgram = this._Load(GL.VERTEX_SHADER, vsrc);
  177. this._fsProgram = this._Load(GL.FRAGMENT_SHADER, fsrc);
  178. this._shader = GL.createProgram();
  179. GL.attachShader(this._shader, this._vsProgram);
  180. GL.attachShader(this._shader, this._fsProgram);
  181. GL.linkProgram(this._shader);
  182. if (!GL.getProgramParameter(this._shader, GL.LINK_STATUS)) {
  183. return null;
  184. }
  185. this.attribs = {
  186. positions: GL.getAttribLocation(this._shader, 'position'),
  187. normals: GL.getAttribLocation(this._shader, 'normal'),
  188. tangents: GL.getAttribLocation(this._shader, 'tangent'),
  189. uvs: GL.getAttribLocation(this._shader, 'uv0'),
  190. colours: GL.getAttribLocation(this._shader, 'colour'),
  191. };
  192. this.uniforms = {
  193. projectionMatrix: {
  194. type: 'mat4',
  195. location: GL.getUniformLocation(this._shader, 'projectionMatrix')
  196. },
  197. modelViewMatrix: {
  198. type: 'mat4',
  199. location: GL.getUniformLocation(this._shader, 'modelViewMatrix'),
  200. },
  201. modelMatrix: {
  202. type: 'mat4',
  203. location: GL.getUniformLocation(this._shader, 'modelMatrix'),
  204. },
  205. normalMatrix: {
  206. type: 'mat3',
  207. location: GL.getUniformLocation(this._shader, 'normalMatrix'),
  208. },
  209. resolution: {
  210. type: 'vec4',
  211. location: GL.getUniformLocation(this._shader, 'resolution'),
  212. },
  213. lightColour: {
  214. type: 'vec3',
  215. location: GL.getUniformLocation(this._shader, 'lightColour'),
  216. },
  217. lightDirection: {
  218. type: 'vec3',
  219. location: GL.getUniformLocation(this._shader, 'lightDirection'),
  220. },
  221. lightPosition: {
  222. type: 'vec3',
  223. location: GL.getUniformLocation(this._shader, 'lightPosition'),
  224. },
  225. lightAttenuation: {
  226. type: 'vec3',
  227. location: GL.getUniformLocation(this._shader, 'lightAttenuation'),
  228. },
  229. cameraPosition: {
  230. type: 'vec3',
  231. location: GL.getUniformLocation(this._shader, 'cameraPosition'),
  232. },
  233. diffuseTexture: {
  234. type: 'texture',
  235. location: GL.getUniformLocation(this._shader, 'diffuseTexture'),
  236. },
  237. normalTexture: {
  238. type: 'texture',
  239. location: GL.getUniformLocation(this._shader, 'normalTexture'),
  240. },
  241. gBuffer_Light: {
  242. type: 'texture',
  243. location: GL.getUniformLocation(this._shader, 'gBuffer_Light'),
  244. },
  245. gBuffer_Colour: {
  246. type: 'texture',
  247. location: GL.getUniformLocation(this._shader, 'gBuffer_Colour'),
  248. },
  249. gBuffer_Normal: {
  250. type: 'texture',
  251. location: GL.getUniformLocation(this._shader, 'gBuffer_Normal'),
  252. },
  253. gBuffer_Position: {
  254. type: 'texture',
  255. location: GL.getUniformLocation(this._shader, 'gBuffer_Position'),
  256. },
  257. gQuadTexture: {
  258. type: 'texture',
  259. location: GL.getUniformLocation(this._shader, 'gQuadTexture'),
  260. }
  261. };
  262. }
  263. _ModifySourceWithDefines(src, defines) {
  264. const lines = src.split('\n');
  265. const defineStrings = defines.map(d => '#define ' + d);
  266. lines.splice(3, 0, defineStrings);
  267. return lines.join('\n');
  268. }
  269. _Load(type, source) {
  270. const shader = GL.createShader(type);
  271. GL.shaderSource(shader, source);
  272. GL.compileShader(shader);
  273. if (!GL.getShaderParameter(shader, GL.COMPILE_STATUS)) {
  274. console.log(GL.getShaderInfoLog(shader));
  275. console.log(source);
  276. GL.deleteShader(shader);
  277. return null;
  278. }
  279. return shader;
  280. }
  281. Bind() {
  282. GL.useProgram(this._shader);
  283. }
  284. }
  285. class ShaderInstance {
  286. constructor(shader) {
  287. this._shaderData = shader;
  288. this._uniforms = {};
  289. for (let k in shader.uniforms) {
  290. this._uniforms[k] = {
  291. location: shader.uniforms[k].location,
  292. type: shader.uniforms[k].type,
  293. value: null
  294. };
  295. }
  296. this._attribs = {...shader.attribs};
  297. }
  298. SetMat4(name, m) {
  299. this._uniforms[name].value = m;
  300. }
  301. SetMat3(name, m) {
  302. this._uniforms[name].value = m;
  303. }
  304. SetVec4(name, v) {
  305. this._uniforms[name].value = v;
  306. }
  307. SetVec3(name, v) {
  308. this._uniforms[name].value = v;
  309. }
  310. SetTexture(name, t) {
  311. this._uniforms[name].value = t;
  312. }
  313. Bind(constants) {
  314. this._shaderData.Bind();
  315. let textureIndex = 0;
  316. for (let k in this._uniforms) {
  317. const v = this._uniforms[k];
  318. let value = constants[k];
  319. if (v.value) {
  320. value = v.value;
  321. }
  322. if (value && v.location) {
  323. const t = v.type;
  324. if (t == 'mat4') {
  325. GL.uniformMatrix4fv(v.location, false, value);
  326. } else if (t == 'mat3') {
  327. GL.uniformMatrix3fv(v.location, false, value);
  328. } else if (t == 'vec4') {
  329. GL.uniform4fv(v.location, value);
  330. } else if (t == 'vec3') {
  331. GL.uniform3fv(v.location, value);
  332. } else if (t == 'texture') {
  333. value.Bind(textureIndex);
  334. GL.uniform1i(v.location, textureIndex);
  335. textureIndex++;
  336. }
  337. }
  338. }
  339. }
  340. }
  341. class Texture {
  342. constructor() {
  343. }
  344. Load(src) {
  345. this._name = src;
  346. this._Load(src);
  347. return this;
  348. }
  349. _Load(src) {
  350. this._texture = GL.createTexture();
  351. GL.bindTexture(GL.TEXTURE_2D, this._texture);
  352. GL.texImage2D(GL.TEXTURE_2D, 0, GL.RGBA,
  353. 1, 1, 0, GL.RGBA, GL.UNSIGNED_BYTE,
  354. new Uint8Array([0, 0, 255, 255]));
  355. const img = new Image();
  356. img.src = src;
  357. img.onload = () => {
  358. GL.bindTexture(GL.TEXTURE_2D, this._texture);
  359. GL.texImage2D(GL.TEXTURE_2D, 0, GL.RGBA, GL.RGBA, GL.UNSIGNED_BYTE, img);
  360. GL.generateMipmap(GL.TEXTURE_2D);
  361. GL.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.LINEAR_MIPMAP_LINEAR);
  362. GL.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, GL.LINEAR);
  363. GL.bindTexture(GL.TEXTURE_2D, null);
  364. };
  365. }
  366. Bind(index) {
  367. if (!this._texture) {
  368. return;
  369. }
  370. GL.activeTexture(GL.TEXTURE0 + index);
  371. GL.bindTexture(GL.TEXTURE_2D, this._texture);
  372. }
  373. Unbind() {
  374. GL.bindTexture(GL.TEXTURE_2D, null);
  375. }
  376. }
  377. class Mesh {
  378. constructor() {
  379. this._buffers = {};
  380. this._OnInit();
  381. }
  382. _BufferData(info, name) {
  383. if (name == 'index') {
  384. info.buffer = GL.createBuffer();
  385. GL.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, info.buffer);
  386. GL.bufferData(GL.ELEMENT_ARRAY_BUFFER, new Uint16Array(info.data), GL.STATIC_DRAW);
  387. } else {
  388. info.buffer = GL.createBuffer();
  389. GL.bindBuffer(GL.ARRAY_BUFFER, info.buffer);
  390. GL.bufferData(GL.ARRAY_BUFFER, new Float32Array(info.data), GL.STATIC_DRAW);
  391. }
  392. this._buffers[name] = info;
  393. }
  394. Bind(shader) {
  395. for (let k in this._buffers) {
  396. if (shader._attribs[k] == -1) {
  397. continue;
  398. }
  399. const b = this._buffers[k];
  400. if (k == 'index') {
  401. GL.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, b.buffer);
  402. } else {
  403. GL.bindBuffer(GL.ARRAY_BUFFER, b.buffer);
  404. GL.vertexAttribPointer(shader._attribs[k], b.size, GL.FLOAT, false, 0, 0);
  405. GL.enableVertexAttribArray(shader._attribs[k]);
  406. }
  407. }
  408. }
  409. Draw() {
  410. const vertexCount = this._buffers.index.data.length;
  411. GL.drawElements(GL.TRIANGLES, vertexCount, GL.UNSIGNED_SHORT, 0);
  412. }
  413. }
  414. class MeshInstance {
  415. constructor(mesh, shaders, shaderParams) {
  416. this._mesh = mesh;
  417. this._shaders = shaders;
  418. shaderParams = shaderParams || {};
  419. for (let sk in shaders) {
  420. const s = shaders[sk];
  421. for (let k in shaderParams) {
  422. s.SetTexture(k, shaderParams[k]);
  423. }
  424. }
  425. this._position = vec3.create();
  426. this._scale = vec3.fromValues(1, 1, 1);
  427. this._rotation = quat.create();
  428. }
  429. SetPosition(x, y, z) {
  430. vec3.set(this._position, x, y, z);
  431. }
  432. RotateX(rad) {
  433. quat.rotateX(this._rotation, this._rotation, rad);
  434. }
  435. RotateY(rad) {
  436. quat.rotateY(this._rotation, this._rotation, rad);
  437. }
  438. Scale(x, y, z) {
  439. vec3.set(this._scale, x, y, z);
  440. }
  441. Bind(constants, pass) {
  442. const modelMatrix = mat4.create();
  443. mat4.fromRotationTranslationScale(
  444. modelMatrix, this._rotation, this._position, this._scale);
  445. // TODO View matrix
  446. const viewMatrix = constants['viewMatrix'];
  447. const modelViewMatrix = mat4.create();
  448. mat4.multiply(modelViewMatrix, viewMatrix, modelMatrix);
  449. const normalMatrix = mat3.create();
  450. mat3.fromMat4(normalMatrix, modelMatrix);
  451. mat3.invert(normalMatrix, normalMatrix);
  452. mat3.transpose(normalMatrix, normalMatrix);
  453. const s = this._shaders[pass];
  454. s.SetMat4('modelViewMatrix', modelViewMatrix);
  455. s.SetMat4('modelMatrix', modelMatrix);
  456. s.SetMat3('normalMatrix', normalMatrix);
  457. s.Bind(constants);
  458. this._mesh.Bind(s);
  459. }
  460. Draw() {
  461. this._mesh.Draw();
  462. }
  463. }
  464. class Box extends Mesh {
  465. constructor() {
  466. super();
  467. }
  468. _OnInit() {
  469. const positions = [
  470. // Front face
  471. -1.0, -1.0, 1.0,
  472. 1.0, -1.0, 1.0,
  473. 1.0, 1.0, 1.0,
  474. -1.0, 1.0, 1.0,
  475. // Back face
  476. -1.0, -1.0, -1.0,
  477. -1.0, 1.0, -1.0,
  478. 1.0, 1.0, -1.0,
  479. 1.0, -1.0, -1.0,
  480. // Top face
  481. -1.0, 1.0, -1.0,
  482. -1.0, 1.0, 1.0,
  483. 1.0, 1.0, 1.0,
  484. 1.0, 1.0, -1.0,
  485. // Bottom face
  486. -1.0, -1.0, -1.0,
  487. 1.0, -1.0, -1.0,
  488. 1.0, -1.0, 1.0,
  489. -1.0, -1.0, 1.0,
  490. // Right face
  491. 1.0, -1.0, -1.0,
  492. 1.0, 1.0, -1.0,
  493. 1.0, 1.0, 1.0,
  494. 1.0, -1.0, 1.0,
  495. // Left face
  496. -1.0, -1.0, -1.0,
  497. -1.0, -1.0, 1.0,
  498. -1.0, 1.0, 1.0,
  499. -1.0, 1.0, -1.0,
  500. ];
  501. const uvs = [
  502. // Front face
  503. 0.0, 0.0,
  504. 1.0, 0.0,
  505. 1.0, 1.0,
  506. 0.0, 1.0,
  507. // Back face
  508. 0.0, 0.0,
  509. 1.0, 0.0,
  510. 1.0, 1.0,
  511. 0.0, 1.0,
  512. // Top face
  513. 0.0, 0.0,
  514. 1.0, 0.0,
  515. 1.0, 1.0,
  516. 0.0, 1.0,
  517. // Bottom face
  518. 0.0, 0.0,
  519. 1.0, 0.0,
  520. 1.0, 1.0,
  521. 0.0, 1.0,
  522. // Right face
  523. 0.0, 0.0,
  524. 1.0, 0.0,
  525. 1.0, 1.0,
  526. 0.0, 1.0,
  527. // Left face
  528. 0.0, 0.0,
  529. 1.0, 0.0,
  530. 1.0, 1.0,
  531. 0.0, 1.0,
  532. ];
  533. const normals = [
  534. // Front face
  535. 0.0, 0.0, 1.0,
  536. 0.0, 0.0, 1.0,
  537. 0.0, 0.0, 1.0,
  538. 0.0, 0.0, 1.0,
  539. // Back face
  540. 0.0, 0.0, -1.0,
  541. 0.0, 0.0, -1.0,
  542. 0.0, 0.0, -1.0,
  543. 0.0, 0.0, -1.0,
  544. // Top face
  545. 0.0, 1.0, 0.0,
  546. 0.0, 1.0, 0.0,
  547. 0.0, 1.0, 0.0,
  548. 0.0, 1.0, 0.0,
  549. // Bottom face
  550. 0.0, -1.0, 0.0,
  551. 0.0, -1.0, 0.0,
  552. 0.0, -1.0, 0.0,
  553. 0.0, -1.0, 0.0,
  554. // Right face
  555. 1.0, 0.0, 0.0,
  556. 1.0, 0.0, 0.0,
  557. 1.0, 0.0, 0.0,
  558. 1.0, 0.0, 0.0,
  559. // Left face
  560. -1.0, 0.0, 0.0,
  561. -1.0, 0.0, 0.0,
  562. -1.0, 0.0, 0.0,
  563. -1.0, 0.0, 0.0,
  564. ];
  565. const tangents = [
  566. // Front face
  567. -1.0, 0.0, 0.0,
  568. -1.0, 0.0, 0.0,
  569. -1.0, 0.0, 0.0,
  570. -1.0, 0.0, 0.0,
  571. // Back face
  572. 0.0, 1.0, 0.0,
  573. 0.0, 1.0, 0.0,
  574. 0.0, 1.0, 0.0,
  575. 0.0, 1.0, 0.0,
  576. // Top face
  577. 0.0, 0.0, 1.0,
  578. 0.0, 0.0, 1.0,
  579. 0.0, 0.0, 1.0,
  580. 0.0, 0.0, 1.0,
  581. // Bottom face
  582. -1.0, 0.0, 0.0,
  583. -1.0, 0.0, 0.0,
  584. -1.0, 0.0, 0.0,
  585. -1.0, 0.0, 0.0,
  586. // Right face
  587. 0.0, 1.0, 0.0,
  588. 0.0, 1.0, 0.0,
  589. 0.0, 1.0, 0.0,
  590. 0.0, 1.0, 0.0,
  591. // Left face
  592. 0.0, 0.0, -1.0,
  593. 0.0, 0.0, -1.0,
  594. 0.0, 0.0, -1.0,
  595. 0.0, 0.0, -1.0,
  596. ];
  597. const faceColors = [
  598. [1.0, 1.0, 1.0, 1.0], // Front face: white
  599. [1.0, 0.0, 0.0, 1.0], // Back face: red
  600. [0.0, 1.0, 0.0, 1.0], // Top face: green
  601. [0.0, 0.0, 1.0, 1.0], // Bottom face: blue
  602. [1.0, 1.0, 0.0, 1.0], // Right face: yellow
  603. [1.0, 0.0, 1.0, 1.0], // Left face: purple
  604. ];
  605. // Convert the array of colors into a table for all the vertices.
  606. let colours = [];
  607. for (var j = 0; j < faceColors.length; ++j) {
  608. const c = faceColors[j];
  609. // Repeat each color four times for the four vertices of the face
  610. colours = colours.concat(c, c, c, c);
  611. }
  612. const indices = [
  613. 0, 1, 2, 0, 2, 3, // front
  614. 4, 5, 6, 4, 6, 7, // back
  615. 8, 9, 10, 8, 10, 11, // top
  616. 12, 13, 14, 12, 14, 15, // bottom
  617. 16, 17, 18, 16, 18, 19, // right
  618. 20, 21, 22, 20, 22, 23, // left
  619. ];
  620. this._BufferData({size: 3, data: positions}, 'positions');
  621. this._BufferData({size: 3, data: normals}, 'normals');
  622. this._BufferData({size: 3, data: tangents}, 'tangents');
  623. this._BufferData({size: 4, data: colours}, 'colours');
  624. this._BufferData({size: 2, data: uvs}, 'uvs');
  625. this._BufferData({data: indices}, 'index');
  626. }
  627. }
  628. class Quad extends Mesh {
  629. constructor() {
  630. super();
  631. }
  632. _OnInit() {
  633. const positions = [
  634. -0.5, -0.5, 1.0,
  635. 0.5, -0.5, 1.0,
  636. 0.5, 0.5, 1.0,
  637. -0.5, 0.5, 1.0,
  638. ];
  639. const normals = [
  640. 0.0, 0.0, 1.0,
  641. 0.0, 0.0, 1.0,
  642. 0.0, 0.0, 1.0,
  643. 0.0, 0.0, 1.0,
  644. ];
  645. const tangents = [
  646. -1.0, 0.0, 0.0,
  647. -1.0, 0.0, 0.0,
  648. -1.0, 0.0, 0.0,
  649. -1.0, 0.0, 0.0,
  650. ];
  651. const uvs = [
  652. 0.0, 0.0,
  653. 1.0, 0.0,
  654. 1.0, 1.0,
  655. 0.0, 1.0,
  656. ];
  657. const indices = [
  658. 0, 1, 2,
  659. 0, 2, 3,
  660. ];
  661. this._BufferData({size: 3, data: positions}, 'positions');
  662. this._BufferData({size: 3, data: normals}, 'normals');
  663. this._BufferData({size: 3, data: tangents}, 'tangents');
  664. this._BufferData({size: 2, data: uvs}, 'uvs');
  665. this._BufferData({data: indices}, 'index');
  666. }
  667. }
  668. class Camera {
  669. constructor() {
  670. this._position = vec3.create();
  671. this._target = vec3.create();
  672. this._viewMatrix = mat4.create();
  673. this._cameraMatrix = mat4.create();
  674. }
  675. SetPosition(x, y, z) {
  676. vec3.set(this._position, x, y, z);
  677. }
  678. SetTarget(x, y, z) {
  679. vec3.set(this._target, x, y, z);
  680. }
  681. UpdateConstants(constants) {
  682. mat4.lookAt(this._viewMatrix, this._position, this._target, vec3.fromValues(0, 1, 0));
  683. mat4.invert(this._cameraMatrix, this._viewMatrix);
  684. constants['projectionMatrix'] = this._projectionMatrix;
  685. constants['viewMatrix'] = this._viewMatrix;
  686. constants['cameraMatrix'] = this._cameraMatrix;
  687. constants['cameraPosition'] = this._position;
  688. }
  689. }
  690. class PerspectiveCamera extends Camera {
  691. constructor(fov, aspect, zNear, zFar) {
  692. super();
  693. this._projectionMatrix = mat4.create();
  694. this._fov = fov;
  695. this._aspect = aspect;
  696. this._zNear = zNear;
  697. this._zFar = zFar;
  698. mat4.perspective(this._projectionMatrix, fov * Math.PI / 180.0, aspect, zNear, zFar);
  699. }
  700. GetUp() {
  701. const v = vec4.fromValues(0, 0, 1, 0);
  702. vec4.transformMat4(v, v, this._cameraMatrix);
  703. return v;
  704. }
  705. GetRight() {
  706. const v = vec4.fromValues(1, 0, 0, 0);
  707. vec4.transformMat4(v, v, this._cameraMatrix);
  708. return v;
  709. }
  710. }
  711. class OrthoCamera extends Camera {
  712. constructor(l, r, b, t, n, f) {
  713. super();
  714. this._projectionMatrix = mat4.create();
  715. mat4.ortho(this._projectionMatrix, l, r, b, t, n, f);
  716. }
  717. }
  718. class Light {
  719. constructor() {
  720. }
  721. UpdateConstants() {
  722. }
  723. }
  724. class DirectionalLight extends Light {
  725. constructor() {
  726. super();
  727. this._colour = vec3.fromValues(1, 1, 1);
  728. this._direction = vec3.fromValues(1, 0, 0);
  729. }
  730. get Type() {
  731. return 'Directional';
  732. }
  733. SetColour(r, g, b) {
  734. vec3.set(this._colour, r, g, b);
  735. }
  736. SetDirection(x, y, z) {
  737. vec3.set(this._direction, x, y, z);
  738. vec3.normalize(this._direction, this._direction);
  739. }
  740. UpdateConstants(constants) {
  741. constants['lightDirection'] = this._direction;
  742. constants['lightColour'] = this._colour;
  743. }
  744. }
  745. class PointLight extends Light {
  746. constructor() {
  747. super();
  748. this._colour = vec3.fromValues(1, 1, 1);
  749. this._position = vec3.create();
  750. this._attenuation = vec3.create();
  751. }
  752. get Type() {
  753. return 'Point';
  754. }
  755. SetColour(r, g, b) {
  756. vec3.set(this._colour, r, g, b);
  757. }
  758. SetPosition(x, y, z) {
  759. vec3.set(this._position, x, y, z);
  760. }
  761. SetRadius(r1, r2) {
  762. vec3.set(this._attenuation, r1, r2, 0);
  763. }
  764. UpdateConstants(constants) {
  765. constants['lightPosition'] = this._position;
  766. constants['lightColour'] = this._colour;
  767. constants['lightAttenuation'] = this._attenuation;
  768. }
  769. }
  770. class Renderer {
  771. constructor() {
  772. this._Init();
  773. }
  774. _Init() {
  775. this._canvas = document.createElement('canvas');
  776. document.body.appendChild(this._canvas);
  777. GL = this._canvas.getContext('webgl2');
  778. if (GL === null) {
  779. alert("Unable to initialize WebGL. Your browser or machine may not support it.");
  780. return;
  781. }
  782. this._constants = {};
  783. this._textures = {};
  784. this._textures['test-diffuse'] = new Texture().Load('./resources/rough-wet-cobble-albedo-1024.png');
  785. this._textures['test-normal'] = new Texture().Load('./resources/rough-wet-cobble-normal-1024.jpg');
  786. this._textures['worn-bumpy-rock-albedo'] = new Texture().Load(
  787. './resources/worn-bumpy-rock-albedo-1024.png');
  788. this._textures['worn-bumpy-rock-normal'] = new Texture().Load(
  789. './resources/worn-bumpy-rock-normal-1024.jpg');
  790. this._shaders = {};
  791. this._shaders['z'] = new Shader(_SIMPLE_VS, _SIMPLE_FS);
  792. this._shaders['default'] = new Shader(_OPAQUE_VS, _OPAQUE_FS);
  793. this._shaders['post-quad-colour'] = new Shader(
  794. _QUAD_COLOUR_VS, _QUAD_COLOUR_FS);
  795. this._shaders['post-quad-directional'] = new Shader(
  796. _QUAD_VS, _QUAD_FS, ['_LIGHT_TYPE_DIRECTIONAL']);
  797. this._shaders['post-quad-point'] = new Shader(
  798. _QUAD_VS, _QUAD_FS, ['_LIGHT_TYPE_POINT']);
  799. this._camera = new PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1.0, 1000.0);
  800. this._camera.SetPosition(0, 20, 10);
  801. this._camera.SetTarget(0, 0, -20);
  802. this._postCamera = new OrthoCamera(0.0, 1.0, 0.0, 1.0, 1.0, 1000.0);
  803. this._meshes = [];
  804. this._lights = [];
  805. this._quadDirectional = new MeshInstance(
  806. new Quad(),
  807. {light: new ShaderInstance(this._shaders['post-quad-directional'])});
  808. this._quadDirectional.SetPosition(0.5, 0.5, -10.0);
  809. this._quadPoint = new MeshInstance(
  810. new Quad(),
  811. {light: new ShaderInstance(this._shaders['post-quad-point'])});
  812. this._quadPoint.SetPosition(0.5, 0.5, -10.0);
  813. this._quadColour = new MeshInstance(
  814. new Quad(),
  815. {colour: new ShaderInstance(this._shaders['post-quad-colour'])});
  816. this._quadColour.SetPosition(0.5, 0.5, -10.0);
  817. this._InitGBuffer();
  818. this.Resize(window.innerWidth, window.innerHeight);
  819. }
  820. _InitGBuffer() {
  821. // Float textures have only been around for like 15 years.
  822. // So of course make them an extension.
  823. GL.getExtension('EXT_color_buffer_float');
  824. this._depthBuffer = GL.createRenderbuffer();
  825. GL.bindRenderbuffer(GL.RENDERBUFFER, this._depthBuffer);
  826. GL.renderbufferStorage(
  827. GL.RENDERBUFFER,
  828. GL.DEPTH_COMPONENT24,
  829. window.innerWidth, window.innerHeight);
  830. GL.bindRenderbuffer(GL.RENDERBUFFER, null);
  831. this._normalBuffer = GL.createTexture();
  832. GL.bindTexture(GL.TEXTURE_2D, this._normalBuffer);
  833. GL.texImage2D(
  834. GL.TEXTURE_2D, 0, GL.RGBA32F, window.innerWidth, window.innerHeight,
  835. 0, GL.RGBA, GL.FLOAT, null);
  836. GL.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.NEAREST);
  837. GL.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, GL.NEAREST);
  838. GL.bindTexture(GL.TEXTURE_2D, null);
  839. this._positionBuffer = GL.createTexture();
  840. GL.bindTexture(GL.TEXTURE_2D, this._positionBuffer);
  841. GL.texImage2D(
  842. GL.TEXTURE_2D, 0, GL.RGBA32F, window.innerWidth, window.innerHeight,
  843. 0, GL.RGBA, GL.FLOAT, null);
  844. GL.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.NEAREST);
  845. GL.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, GL.NEAREST);
  846. GL.bindTexture(GL.TEXTURE_2D, null);
  847. this._lightBuffer = GL.createTexture();
  848. GL.bindTexture(GL.TEXTURE_2D, this._lightBuffer);
  849. GL.texImage2D(
  850. GL.TEXTURE_2D, 0, GL.RGBA32F, window.innerWidth, window.innerHeight,
  851. 0, GL.RGBA, GL.FLOAT, null);
  852. GL.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.NEAREST);
  853. GL.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, GL.NEAREST);
  854. GL.bindTexture(GL.TEXTURE_2D, null);
  855. this._colourBuffer = GL.createTexture();
  856. GL.bindTexture(GL.TEXTURE_2D, this._colourBuffer);
  857. GL.texImage2D(
  858. GL.TEXTURE_2D, 0, GL.RGBA32F, window.innerWidth, window.innerHeight,
  859. 0, GL.RGBA, GL.FLOAT, null);
  860. GL.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.NEAREST);
  861. GL.texParameteri(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, GL.NEAREST);
  862. GL.bindTexture(GL.TEXTURE_2D, null);
  863. // Create the FBO's for each pass
  864. this._zFBO = GL.createFramebuffer();
  865. GL.bindFramebuffer(GL.FRAMEBUFFER, this._zFBO);
  866. GL.framebufferRenderbuffer(
  867. GL.FRAMEBUFFER, GL.DEPTH_ATTACHMENT, GL.RENDERBUFFER, this._depthBuffer);
  868. GL.framebufferTexture2D(
  869. GL.DRAW_FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.TEXTURE_2D, this._normalBuffer, 0);
  870. GL.framebufferTexture2D(
  871. GL.DRAW_FRAMEBUFFER, GL.COLOR_ATTACHMENT1, GL.TEXTURE_2D, this._positionBuffer, 0);
  872. GL.bindFramebuffer(GL.FRAMEBUFFER, null);
  873. this._lightFBO = GL.createFramebuffer();
  874. GL.bindFramebuffer(GL.FRAMEBUFFER, this._lightFBO);
  875. GL.framebufferRenderbuffer(
  876. GL.FRAMEBUFFER, GL.DEPTH_ATTACHMENT, GL.RENDERBUFFER, this._depthBuffer);
  877. GL.framebufferTexture2D(
  878. GL.DRAW_FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.TEXTURE_2D, this._lightBuffer, 0);
  879. GL.bindFramebuffer(GL.FRAMEBUFFER, null);
  880. this._colourFBO = GL.createFramebuffer();
  881. GL.bindFramebuffer(GL.FRAMEBUFFER, this._colourFBO);
  882. GL.framebufferRenderbuffer(
  883. GL.FRAMEBUFFER, GL.DEPTH_ATTACHMENT, GL.RENDERBUFFER, this._depthBuffer);
  884. GL.framebufferTexture2D(
  885. GL.DRAW_FRAMEBUFFER, GL.COLOR_ATTACHMENT0, GL.TEXTURE_2D, this._colourBuffer, 0);
  886. GL.bindFramebuffer(GL.FRAMEBUFFER, null);
  887. // GROSS
  888. this._normalTexture = new Texture();
  889. this._normalTexture._texture = this._normalBuffer;
  890. this._positionTexture = new Texture();
  891. this._positionTexture._texture = this._positionBuffer;
  892. this._lightTexture = new Texture();
  893. this._lightTexture._texture = this._lightBuffer;
  894. this._colourTexture = new Texture();
  895. this._colourTexture._texture = this._colourBuffer;
  896. }
  897. CreateMeshInstance(mesh, shaderParams) {
  898. const params = {};
  899. for (let k in shaderParams.params) {
  900. params[k] = this._textures[shaderParams.params[k]];
  901. }
  902. const m = new MeshInstance(
  903. mesh,
  904. {
  905. z: new ShaderInstance(this._shaders['z']),
  906. colour: new ShaderInstance(this._shaders[shaderParams.shader])
  907. }, params);
  908. this._meshes.push(m);
  909. return m;
  910. }
  911. CreateLight(type) {
  912. let l = null;
  913. if (type == 'directional') {
  914. l = new DirectionalLight();
  915. } else if (type == 'point') {
  916. l = new PointLight();
  917. }
  918. if (!l) {
  919. return null;
  920. }
  921. this._lights.push(l);
  922. return l;
  923. }
  924. Resize(w, h) {
  925. this._canvas.width = w;
  926. this._canvas.height = h;
  927. GL.viewport(0, 0, w, h);
  928. }
  929. _SetQuadSizeForLight(quad, light) {
  930. const wvp = mat4.create();
  931. const w = mat4.create();
  932. mat4.fromTranslation(w, light._position);
  933. const viewMatrix = this._camera._viewMatrix;
  934. const projectionMatrix = this._camera._projectionMatrix;
  935. const _TransformToScreenSpace = (p) => {
  936. const screenPos = vec4.fromValues(
  937. p[0], p[1], p[2], 1.0);
  938. vec4.transformMat4(screenPos, screenPos, projectionMatrix);
  939. screenPos[0] = (screenPos[0] / screenPos[3]) * 0.5 + 0.5;
  940. screenPos[1] = (screenPos[1] / screenPos[3]) * 0.5 + 0.5;
  941. return screenPos;
  942. };
  943. const lightRadius = (light._attenuation[0] + light._attenuation[1]);
  944. const lightDistance = vec3.distance(this._camera._position, light._position);
  945. if (lightDistance < lightRadius) {
  946. quad.SetPosition(0.5, 0.5, -10);
  947. quad.Scale(1, 1, 1);
  948. } else {
  949. const viewSpaceCenter = vec3.clone(light._position);
  950. vec3.transformMat4(viewSpaceCenter, viewSpaceCenter, viewMatrix);
  951. const rightPos = vec3.clone(viewSpaceCenter);
  952. const upPos = vec3.clone(viewSpaceCenter);
  953. vec3.add(rightPos, rightPos, vec3.fromValues(lightRadius, 0, 0));
  954. vec3.add(upPos, upPos, vec3.fromValues(0, -lightRadius, 0));
  955. const center = _TransformToScreenSpace(light._position);
  956. const up = _TransformToScreenSpace(upPos);
  957. const right = _TransformToScreenSpace(rightPos);
  958. const radius = 2 * Math.max(
  959. vec2.distance(center, up), vec2.distance(center, right));
  960. quad.SetPosition(center[0], center[1], -10);
  961. quad.Scale(radius, radius, 1);
  962. }
  963. }
  964. Render(timeElapsed) {
  965. this._constants['resolution'] = vec4.fromValues(
  966. window.innerWidth, window.innerHeight, 0, 0);
  967. this._camera.UpdateConstants(this._constants);
  968. this._constants['gBuffer_Normal'] = null;
  969. this._constants['gBuffer_Position'] = null;
  970. this._constants['gBuffer_Colour'] = null;
  971. this._constants['gBuffer_Light'] = null;
  972. // Z-Prepass + normals
  973. GL.bindFramebuffer(GL.FRAMEBUFFER, this._zFBO);
  974. GL.drawBuffers([GL.COLOR_ATTACHMENT0, GL.COLOR_ATTACHMENT1]);
  975. GL.clearColor(0.0, 0.0, 0.0, 0.0);
  976. GL.clearDepth(1.0);
  977. GL.enable(GL.DEPTH_TEST);
  978. GL.depthMask(true);
  979. GL.depthFunc(GL.LEQUAL);
  980. GL.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT);
  981. this._camera.UpdateConstants(this._constants);
  982. for (let m of this._meshes) {
  983. m.Bind(this._constants, 'z');
  984. m.Draw();
  985. }
  986. GL.useProgram(null);
  987. GL.bindTexture(GL.TEXTURE_2D, null);
  988. // Light buffer generation
  989. GL.bindFramebuffer(GL.FRAMEBUFFER, this._lightFBO);
  990. GL.drawBuffers([GL.COLOR_ATTACHMENT0]);
  991. GL.clear(GL.COLOR_BUFFER_BIT);
  992. GL.disable(GL.DEPTH_TEST);
  993. GL.enable(GL.BLEND);
  994. GL.blendFunc(GL.ONE, GL.ONE);
  995. this._postCamera.UpdateConstants(this._constants);
  996. this._constants['gBuffer_Normal'] = this._normalTexture;
  997. this._constants['gBuffer_Position'] = this._positionTexture;
  998. for (let l of this._lights) {
  999. l.UpdateConstants(this._constants);
  1000. let quad = null;
  1001. if (l.Type == 'Directional') {
  1002. quad = this._quadDirectional;
  1003. } else if (l.Type == 'Point') {
  1004. quad = this._quadPoint;
  1005. // Calculate screenspace size
  1006. this._SetQuadSizeForLight(quad, l);
  1007. }
  1008. quad.Bind(this._constants, 'light');
  1009. quad.Draw();
  1010. }
  1011. GL.useProgram(null);
  1012. GL.bindTexture(GL.TEXTURE_2D, null);
  1013. // Colour pass
  1014. GL.bindFramebuffer(GL.FRAMEBUFFER, this._colourFBO);
  1015. GL.drawBuffers([GL.COLOR_ATTACHMENT0]);
  1016. GL.disable(GL.BLEND);
  1017. GL.depthMask(false);
  1018. GL.enable(GL.DEPTH_TEST);
  1019. this._camera.UpdateConstants(this._constants);
  1020. this._constants['gBuffer_Colour'] = null;
  1021. this._constants['gBuffer_Light'] = this._lightTexture;
  1022. this._constants['gBuffer_Normal'] = null;
  1023. this._constants['gBuffer_Position'] = null;
  1024. for (let m of this._meshes) {
  1025. m.Bind(this._constants, 'colour');
  1026. m.Draw();
  1027. }
  1028. GL.useProgram(null);
  1029. GL.bindTexture(GL.TEXTURE_2D, null);
  1030. GL.disable(GL.BLEND);
  1031. // Now just draw directly to screen
  1032. GL.bindFramebuffer(GL.FRAMEBUFFER, null);
  1033. GL.disable(GL.DEPTH_TEST);
  1034. GL.disable(GL.BLEND);
  1035. this._postCamera.UpdateConstants(this._constants);
  1036. // Really fucking hate JavaScript sometimes.
  1037. this._constants['gQuadTexture'] = this._colourTexture;
  1038. this._quadColour.Bind(this._constants, 'colour');
  1039. this._quadColour.Draw();
  1040. }
  1041. }
  1042. class LightPrepassDemo {
  1043. constructor() {
  1044. this._Initialize();
  1045. }
  1046. _Initialize() {
  1047. this._renderer = new Renderer();
  1048. window.addEventListener('resize', () => {
  1049. this._OnWindowResize();
  1050. }, false);
  1051. this._Init();
  1052. this._previousRAF = null;
  1053. this._RAF();
  1054. }
  1055. _OnWindowResize() {
  1056. this._renderer.Resize(window.innerWidth, window.innerHeight);
  1057. }
  1058. _Init() {
  1059. this._CreateLights();
  1060. this._CreateMeshes();
  1061. }
  1062. _CreateLights() {
  1063. this._lights = [];
  1064. for (let i = -9; i <= 9; i++) {
  1065. let l = this._renderer.CreateLight('point');
  1066. const v = vec3.fromValues(Math.random(), Math.random(), Math.random());
  1067. vec3.normalize(v, v);
  1068. const p = vec3.fromValues(
  1069. (Math.random() * 2 - 1) * 10,
  1070. 3,
  1071. -Math.random() * 10 - 10);
  1072. l.SetColour(v[0], v[1], v[2]);
  1073. l.SetPosition(p[0], p[1], p[2]);
  1074. l.SetRadius(4, 1);
  1075. this._lights.push({
  1076. light: l,
  1077. position: p,
  1078. acc: Math.random() * 10.0,
  1079. accSpeed: Math.random() * 0.5 + 0.5,
  1080. });
  1081. }
  1082. }
  1083. _CreateMeshes() {
  1084. this._meshes = [];
  1085. let m = this._renderer.CreateMeshInstance(
  1086. new Quad(),
  1087. {
  1088. shader: 'default',
  1089. params: {
  1090. diffuseTexture: 'worn-bumpy-rock-albedo',
  1091. normalTexture: 'worn-bumpy-rock-normal',
  1092. }
  1093. });
  1094. m.SetPosition(0, -2, -10);
  1095. m.RotateX(-Math.PI * 0.5);
  1096. m.Scale(50, 50, 1);
  1097. for (let x = -5; x < 5; x++) {
  1098. for (let y = 0; y < 20; y++) {
  1099. let m = this._renderer.CreateMeshInstance(
  1100. new Box(),
  1101. {
  1102. shader: 'default',
  1103. params: {
  1104. diffuseTexture: 'test-diffuse',
  1105. normalTexture: 'test-normal',
  1106. }
  1107. });
  1108. m.SetPosition(x * 4, 0, -y * 4);
  1109. this._meshes.push(m);
  1110. }
  1111. }
  1112. }
  1113. _RAF() {
  1114. requestAnimationFrame((t) => {
  1115. if (this._previousRAF === null) {
  1116. this._previousRAF = t;
  1117. }
  1118. this._RAF();
  1119. this._Step(t - this._previousRAF);
  1120. this._previousRAF = t;
  1121. });
  1122. }
  1123. _Step(timeElapsed) {
  1124. const timeElapsedS = timeElapsed * 0.001;
  1125. for (let m of this._meshes) {
  1126. m.RotateY(timeElapsedS);
  1127. }
  1128. for (let l of this._lights) {
  1129. l.acc += timeElapsed * 0.001 * l.accSpeed;
  1130. l.light.SetPosition(
  1131. l.position[0] + 10 * Math.cos(l.acc),
  1132. l.position[1],
  1133. l.position[2] + 10 * Math.sin(l.acc));
  1134. }
  1135. this._renderer.Render(timeElapsedS);
  1136. }
  1137. }
  1138. let _APP = null;
  1139. window.addEventListener('DOMContentLoaded', () => {
  1140. _APP = new LightPrepassDemo();
  1141. });