BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine / gl / glContext.js

glContext.js

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