BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / gl / glContext.js

glContext.js

glContext.js 14.2 KiB Download Raw
1class GLContext
2{
3 static MAX_LIGHTS = 16;
4
5 constructor (canvas)
6 {
7 this.canvas = canvas;
8
9 const attrs = { alpha: true, premultipliedAlpha: false, antialias: true };
10 this.gl = canvas.getContext("webgl", attrs) || canvas.getContext("experimental-webgl", attrs);
11
12 if (!this.gl)
13 { throw new Error("WebGL is not supported in this browser."); }
14
15 const gl = this.gl;
16 gl.enable(gl.BLEND);
17 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
18 gl.disable(gl.DEPTH_TEST);
19 gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
20
21 this.defaultShader = new Shader(Shader.DEFAULT_VERT, Shader.DEFAULT_FRAG);
22 this.screenCopyShader = new Shader(Shader.SCREEN_VERT, Shader.SCREEN_COPY_FRAG);
23 this.textures = new WeakMap();
24
25 this.positionBuffer = gl.createBuffer();
26 gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
27 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
28 -0.5, -0.5,
29 0.5, -0.5,
30 -0.5, 0.5,
31 0.5, 0.5
32 ]), gl.STATIC_DRAW);
33
34 this.texCoordBuffer = gl.createBuffer();
35
36 // Fullscreen NDC quad (triangle strip) + UVs (v=0 at bottom, matches FBO sampling).
37 this.screenPositionBuffer = gl.createBuffer();
38 gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer);
39 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
40 -1, -1,
41 1, -1,
42 -1, 1,
43 1, 1
44 ]), gl.STATIC_DRAW);
45
46 this.screenTexCoordBuffer = gl.createBuffer();
47 gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer);
48 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
49 0, 0,
50 1, 0,
51 0, 1,
52 1, 1
53 ]), gl.STATIC_DRAW);
54
55 // [0] = scene (stable during post), [1]/[2] = ping-pong for effect passes.
56 this.framebuffers = [null, null, null];
57 this.colorTextures = [null, null, null];
58 this._offscreenIndex = 0;
59 this._lastWidth = 0;
60 this._lastHeight = 0;
61 this.setSize(canvas.width, canvas.height);
62 }
63
64 setSize (width, height)
65 {
66 const gl = this.gl;
67 width = Math.max(1, width | 0);
68 height = Math.max(1, height | 0);
69
70 if (width !== this._lastWidth || height !== this._lastHeight)
71 {
72 this._lastWidth = width;
73 this._lastHeight = height;
74 gl.viewport(0, 0, width, height);
75 this._rebuildFramebuffers(width, height);
76 }
77 }
78
79 _destroyFramebuffers ()
80 {
81 const gl = this.gl;
82 for (let i = 0; i < this.framebuffers.length; i++)
83 {
84 if (this.framebuffers[i])
85 {
86 gl.deleteFramebuffer(this.framebuffers[i]);
87 this.framebuffers[i] = null;
88 }
89
90 if (this.colorTextures[i])
91 {
92 gl.deleteTexture(this.colorTextures[i]);
93 this.colorTextures[i] = null;
94 }
95 }
96 }
97
98 _rebuildFramebuffers (width, height)
99 {
100 const gl = this.gl;
101 this._destroyFramebuffers();
102
103 for (let i = 0; i < 3; i++)
104 {
105 const texture = gl.createTexture();
106 gl.bindTexture(gl.TEXTURE_2D, texture);
107 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
108 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
109 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
110 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
111 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
112
113 const fb = gl.createFramebuffer();
114 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
115 gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
116
117 const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
118 if (status !== gl.FRAMEBUFFER_COMPLETE)
119 {
120 console.error("Framebuffer incomplete:", status);
121 }
122
123 this.framebuffers[i] = fb;
124 this.colorTextures[i] = texture;
125 }
126
127 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
128 gl.bindTexture(gl.TEXTURE_2D, null);
129 }
130
131 clear (r, g, b, a = 1)
132 {
133 const gl = this.gl;
134 gl.clearColor(r / 255, g / 255, b / 255, a);
135 gl.clear(gl.COLOR_BUFFER_BIT);
136 }
137
138 clearTransparent ()
139 {
140 const gl = this.gl;
141 gl.clearColor(0, 0, 0, 0);
142 gl.clear(gl.COLOR_BUFFER_BIT);
143 }
144
145 beginOffscreenPass ()
146 {
147 const gl = this.gl;
148 this._offscreenIndex = 0;
149 gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[0]);
150 gl.viewport(0, 0, this._lastWidth, this._lastHeight);
151 gl.enable(gl.BLEND);
152 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
153 }
154
155 endOffscreenPass ()
156 {
157 const gl = this.gl;
158 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
159 }
160
161 /**
162 * @param {Array} passes
163 * @param {Object} builtins
164 * @param {{ toCanvas?: boolean }} options - toCanvas true writes the last pass to the canvas.
165 * @returns {WebGLTexture|null} final color texture when not drawing to canvas
166 */
167 applyPostShaders (passes, builtins = {}, options = {})
168 {
169 if (!passes || !passes.length)
170 { return this.colorTextures[0]; }
171
172 const gl = this.gl;
173 const toCanvas = !!options.toCanvas;
174 const sceneTexture = this.colorTextures[0];
175 let read = 0;
176
177 gl.disable(gl.BLEND);
178
179 for (let i = 0; i < passes.length; i++)
180 {
181 const pass = passes[i];
182 const isLast = i === passes.length - 1;
183
184 // Never overwrite the scene buffer (index 0); ping-pong on 1/2.
185 let write = 1;
186 if (read === 1)
187 { write = 2; }
188 else if (read === 2)
189 { write = 1; }
190
191 if (isLast && toCanvas)
192 {
193 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
194 }
195 else
196 {
197 gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[write]);
198 }
199
200 gl.viewport(0, 0, this._lastWidth, this._lastHeight);
201 gl.clearColor(0, 0, 0, 0);
202 gl.clear(gl.COLOR_BUFFER_BIT);
203
204 const uniforms = Object.assign({}, builtins, pass.uniforms || {});
205 this.drawFullscreen(pass.shader, this.colorTextures[read], uniforms, sceneTexture);
206
207 if (!isLast || !toCanvas)
208 { read = write; }
209 }
210
211 this._offscreenIndex = read;
212 gl.enable(gl.BLEND);
213 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
214 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
215
216 return toCanvas ? null : this.colorTextures[read];
217 }
218
219 blitToCanvas (texture, composite = "alpha")
220 {
221 if (!texture)
222 { return; }
223
224 const gl = this.gl;
225 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
226 gl.viewport(0, 0, this._lastWidth, this._lastHeight);
227 gl.enable(gl.BLEND);
228
229 if (composite === "add")
230 { gl.blendFunc(gl.ONE, gl.ONE); }
231 else
232 { gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); }
233
234 this.drawFullscreen(this.screenCopyShader, texture, null, null);
235
236 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
237 }
238
239 drawFullscreen (shader, texture, uniforms, sceneTexture)
240 {
241 const gl = this.gl;
242 const info = shader.getProgramInfo(gl);
243 if (!info || !texture)
244 { return; }
245
246 gl.useProgram(info.program);
247
248 gl.bindBuffer(gl.ARRAY_BUFFER, this.screenPositionBuffer);
249 if (info.attribs.position >= 0)
250 {
251 gl.enableVertexAttribArray(info.attribs.position);
252 gl.vertexAttribPointer(info.attribs.position, 2, gl.FLOAT, false, 0, 0);
253 }
254
255 gl.bindBuffer(gl.ARRAY_BUFFER, this.screenTexCoordBuffer);
256 if (info.attribs.texCoord >= 0)
257 {
258 gl.enableVertexAttribArray(info.attribs.texCoord);
259 gl.vertexAttribPointer(info.attribs.texCoord, 2, gl.FLOAT, false, 0, 0);
260 }
261
262 gl.activeTexture(gl.TEXTURE0);
263 gl.bindTexture(gl.TEXTURE_2D, texture);
264 this._setUniform(info, "u_texture", 0);
265 this._setUniform(info, "u_alpha", 1);
266
267 if (sceneTexture && info.uniforms.u_scene)
268 {
269 gl.activeTexture(gl.TEXTURE1);
270 gl.bindTexture(gl.TEXTURE_2D, sceneTexture);
271 this._setUniform(info, "u_scene", 1);
272 }
273
274 if (uniforms)
275 {
276 for (const name in uniforms)
277 {
278 if (!Object.prototype.hasOwnProperty.call(uniforms, name))
279 { continue; }
280
281 this._setUniform(info, name, uniforms[name]);
282 }
283 }
284
285 gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
286 }
287
288 getTexture (htmlImage)
289 {
290 if (!htmlImage)
291 { return null; }
292
293 let texture = this.textures.get(htmlImage);
294 if (texture)
295 { return texture; }
296
297 const gl = this.gl;
298 texture = gl.createTexture();
299 gl.bindTexture(gl.TEXTURE_2D, texture);
300 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
301 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
302 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
303 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
304 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, htmlImage);
305
306 this.textures.set(htmlImage, texture);
307 return texture;
308 }
309
310 drawSprite (options)
311 {
312 const gl = this.gl;
313 const width = this._lastWidth;
314 const height = this._lastHeight;
315 if (width <= 0 || height <= 0)
316 { return; }
317
318 const shader = options.shader || this.defaultShader;
319 const info = shader.getProgramInfo(gl);
320 if (!info)
321 { return; }
322
323 const texture = options.texture;
324 if (!texture)
325 { return; }
326
327 gl.useProgram(info.program);
328
329 gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
330 if (info.attribs.position >= 0)
331 {
332 gl.enableVertexAttribArray(info.attribs.position);
333 gl.vertexAttribPointer(info.attribs.position, 2, gl.FLOAT, false, 0, 0);
334 }
335
336 const uv = options.uvRect || { u0: 0, v0: 0, u1: 1, v1: 1 };
337 gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer);
338 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
339 uv.u0, uv.v0,
340 uv.u1, uv.v0,
341 uv.u0, uv.v1,
342 uv.u1, uv.v1
343 ]), gl.DYNAMIC_DRAW);
344
345 if (info.attribs.texCoord >= 0)
346 {
347 gl.enableVertexAttribArray(info.attribs.texCoord);
348 gl.vertexAttribPointer(info.attribs.texCoord, 2, gl.FLOAT, false, 0, 0);
349 }
350
351 const matrix = GLContext._buildSpriteMatrix(
352 options.x, options.y,
353 options.w, options.h,
354 options.rotationDeg || 0,
355 options.mirrorX, options.mirrorY,
356 width, height
357 );
358
359 this._setUniform(info, "u_matrix", matrix);
360 this._setUniform(info, "u_alpha", options.alpha == null ? 1 : options.alpha);
361 this._setUniform(info, "u_worldCenter", [options.x, options.y]);
362 this._setUniform(info, "u_worldSize", [options.w, options.h]);
363 this._setUniform(info, "u_rotationRad", (options.rotationDeg || 0) * Math.PI / 180);
364
365 gl.activeTexture(gl.TEXTURE0);
366 gl.bindTexture(gl.TEXTURE_2D, texture);
367 this._setUniform(info, "u_texture", 0);
368
369 let nextUnit = 1;
370 if (options.textures)
371 {
372 for (const name in options.textures)
373 {
374 if (!Object.prototype.hasOwnProperty.call(options.textures, name))
375 { continue; }
376
377 const extra = options.textures[name];
378 if (!extra)
379 { continue; }
380
381 gl.activeTexture(gl.TEXTURE0 + nextUnit);
382 gl.bindTexture(gl.TEXTURE_2D, extra);
383 this._setUniform(info, name, nextUnit);
384 nextUnit++;
385 }
386 }
387
388 if (options.lights)
389 { this._setLights(info, options.lights); }
390 else if (info.uniforms.u_lightCount)
391 { this._setUniform(info, "u_lightCount", 0); }
392
393 // Sensible bump defaults when the shader asks for them.
394 if (info.uniforms.u_ambient && (!options.uniforms || options.uniforms.u_ambient == null))
395 { this._setUniform(info, "u_ambient", 0.35); }
396 if (info.uniforms.u_specular && (!options.uniforms || options.uniforms.u_specular == null))
397 { this._setUniform(info, "u_specular", 0.25); }
398 if (info.uniforms.u_bumpMode && (!options.uniforms || options.uniforms.u_bumpMode == null))
399 { this._setUniform(info, "u_bumpMode", 1); }
400
401 if (options.uniforms)
402 {
403 for (const name in options.uniforms)
404 {
405 if (!Object.prototype.hasOwnProperty.call(options.uniforms, name))
406 { continue; }
407
408 this._setUniform(info, name, options.uniforms[name]);
409 }
410 }
411
412 gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
413 }
414
415 _setLights (info, lights)
416 {
417 const gl = this.gl;
418 const max = GLContext.MAX_LIGHTS;
419 const count = Math.max(0, Math.min(lights.length, max));
420 this._setUniform(info, "u_lightCount", count);
421
422 const posEntry = info.uniforms["u_lightPos[0]"] || info.uniforms.u_lightPos;
423 const colEntry = info.uniforms["u_lightColor[0]"] || info.uniforms.u_lightColor;
424 if (!posEntry || !colEntry || count === 0)
425 {
426 if (count === 0)
427 { this._setUniform(info, "u_lightCount", 0); }
428 return;
429 }
430
431 const pos = new Float32Array(max * 2);
432 const col = new Float32Array(max * 3);
433
434 for (let i = 0; i < count; i++)
435 {
436 const light = lights[i] || {};
437 pos[i * 2] = light.x != null ? light.x : (light.position ? light.position.x : 0);
438 pos[i * 2 + 1] = light.y != null ? light.y : (light.position ? light.position.y : 0);
439
440 const c = light.color != null ? light.color : [1, 1, 1];
441 if (Array.isArray(c))
442 {
443 col[i * 3] = c[0] != null ? c[0] : 0;
444 col[i * 3 + 1] = c[1] != null ? c[1] : 0;
445 col[i * 3 + 2] = c[2] != null ? c[2] : 0;
446 }
447 else
448 {
449 col[i * 3] = (c.r != null ? c.r : 1);
450 col[i * 3 + 1] = (c.g != null ? c.g : 1);
451 col[i * 3 + 2] = (c.b != null ? c.b : 1);
452 }
453
454 // Allow 0–255 style colors.
455 if (col[i * 3] > 1 || col[i * 3 + 1] > 1 || col[i * 3 + 2] > 1)
456 {
457 col[i * 3] /= 255;
458 col[i * 3 + 1] /= 255;
459 col[i * 3 + 2] /= 255;
460 }
461 }
462
463 gl.uniform2fv(posEntry.location, pos);
464 gl.uniform3fv(colEntry.location, col);
465 }
466
467 _setUniform (info, name, value)
468 {
469 const entry = info.uniforms[name];
470 if (!entry || entry.location == null)
471 { return; }
472
473 const gl = this.gl;
474 const loc = entry.location;
475
476 if (typeof value === "number")
477 {
478 if (entry.type === gl.INT || entry.type === gl.SAMPLER_2D)
479 { gl.uniform1i(loc, value); }
480 else
481 { gl.uniform1f(loc, value); }
482 return;
483 }
484
485 if (value instanceof Float32Array)
486 {
487 if (value.length === 16)
488 { gl.uniformMatrix4fv(loc, false, value); }
489 else if (value.length === 9)
490 { gl.uniformMatrix3fv(loc, false, value); }
491 else if (value.length === 4)
492 { gl.uniform4fv(loc, value); }
493 else if (value.length === 3)
494 { gl.uniform3fv(loc, value); }
495 else if (value.length === 2)
496 { gl.uniform2fv(loc, value); }
497 return;
498 }
499
500 if (Array.isArray(value))
501 {
502 if (value.length === 4)
503 { gl.uniform4fv(loc, value); }
504 else if (value.length === 3)
505 { gl.uniform3fv(loc, value); }
506 else if (value.length === 2)
507 { gl.uniform2fv(loc, value); }
508 else if (value.length === 1)
509 { gl.uniform1f(loc, value[0]); }
510 }
511 }
512
513 // Column-major mat4: projection (canvas Y-down) * T * R * S
514 static _buildSpriteMatrix (x, y, w, h, rotationDeg, mirrorX, mirrorY, canvasW, canvasH)
515 {
516 const sx = (mirrorX ? -1 : 1) * w;
517 const sy = (mirrorY ? -1 : 1) * h;
518 const rad = rotationDeg * Math.PI / 180;
519 const c = Math.cos(rad);
520 const s = Math.sin(rad);
521
522 // Model maps unit quad [-0.5,0.5] into pixel space.
523 const m00 = c * sx;
524 const m01 = -s * sy;
525 const m10 = s * sx;
526 const m11 = c * sy;
527 const m30 = x;
528 const m31 = y;
529
530 const pr0 = 2 / canvasW;
531 const pr5 = -2 / canvasH;
532 const pr12 = -1;
533 const pr13 = 1;
534
535 // P * M (only 2D affine terms matter)
536 return new Float32Array([
537 pr0 * m00, pr5 * m10, 0, 0,
538 pr0 * m01, pr5 * m11, 0, 0,
539 0, 0, -1, 0,
540 pr0 * m30 + pr12, pr5 * m31 + pr13, 0, 1
541 ]);
542 }
543}