BlueGit

timfa frameworkv3

Merge branch 'optimisations' into 'master'

engine optimisations

See merge request Timfa/frameworkv3!10

timfa Tim Falken · pushed by timfa

Authored 2026-08-13 · 3 months ago

Hash
291668f6478b65e8817184e755b08d54c73fe712
11 files changed +377 −94
framework/engine/gl/builtinShaders.js +15 −4
@@ -109,7 +109,8 @@ Shader.Builtin.BLOOM_COMBINE_FRAG = [
109 109 * - colorPreserve: 0–1 tint bloom with the original sprite hue
110 110 * - smallSources: dilate tiny bright pixels before blur (good for 3–4px bullets)
111 111 * - dilate: explicit dilate radius in texels (overrides smallSources default)
112 * - scales: number of H/V blur scale pairs (default 3 with smallSources, else 2)
112 * - scales: number of H/V blur scale pairs (default 2 with smallSources, else 1)
113 * - halfRes: blur at half resolution when true (default true); tags blur passes with scale: 0.5
113 114 */
114 115 Shader.getBloomPostChain = function (options)
115 116 {
@@ -130,7 +131,10 @@ Shader.getBloomPostChain = function (options)
130 131
131 132 const scales = options.scales != null
132 133 ? options.scales
133 : (smallSources ? 3 : 2);
134 : (smallSources ? 2 : 1);
135
136 // Blur at half resolution (~4× less fill). Bright/dilate/combine stay full-res.
137 const halfResBlur = options.halfRes !== false;
134 138
135 139 if (!Shader._bloomBright)
136 140 {
@@ -156,8 +160,15 @@ Shader.getBloomPostChain = function (options)
156 160 for (let i = 0; i < scales; i++)
157 161 {
158 162 const size = blurSize * scaleFactors[Math.min(i, scaleFactors.length - 1)];
159 chain.push({ shader: Shader._bloomBlur, uniforms: { u_direction: [1, 0], u_blurSize: size } });
160 chain.push({ shader: Shader._bloomBlur, uniforms: { u_direction: [0, 1], u_blurSize: size } });
163 const blurPass = halfResBlur ? { scale: 0.5 } : {};
164 chain.push(Object.assign({
165 shader: Shader._bloomBlur,
166 uniforms: { u_direction: [1, 0], u_blurSize: size }
167 }, blurPass));
168 chain.push(Object.assign({
169 shader: Shader._bloomBlur,
170 uniforms: { u_direction: [0, 1], u_blurSize: size }
171 }, blurPass));
161 172 }
162 173
163 174 chain.push({
@@ -109,7 +109,8 @@ Shader.Builtin.BLOOM_COMBINE_FRAG = [
109 * - colorPreserve: 0–1 tint bloom with the original sprite hue
109 * - colorPreserve: 0–1 tint bloom with the original sprite hue
110 * - smallSources: dilate tiny bright pixels before blur (good for 3–4px bullets)
110 * - smallSources: dilate tiny bright pixels before blur (good for 3–4px bullets)
111 * - dilate: explicit dilate radius in texels (overrides smallSources default)
111 * - dilate: explicit dilate radius in texels (overrides smallSources default)
112 * - scales: number of H/V blur scale pairs (default 3 with smallSources, else 2)
112 * - scales: number of H/V blur scale pairs (default 2 with smallSources, else 1)
113 * - halfRes: blur at half resolution when true (default true); tags blur passes with scale: 0.5
113 */
114 */
114Shader.getBloomPostChain = function (options)
115Shader.getBloomPostChain = function (options)
115{
116{
@@ -130,7 +131,10 @@ Shader.getBloomPostChain = function (options)
130
131
131 const scales = options.scales != null
132 const scales = options.scales != null
132 ? options.scales
133 ? options.scales
133 : (smallSources ? 3 : 2);
134 : (smallSources ? 2 : 1);
135
136 // Blur at half resolution (~4× less fill). Bright/dilate/combine stay full-res.
137 const halfResBlur = options.halfRes !== false;
134
138
135 if (!Shader._bloomBright)
139 if (!Shader._bloomBright)
136 {
140 {
@@ -156,8 +160,15 @@ Shader.getBloomPostChain = function (options)
156 for (let i = 0; i < scales; i++)
160 for (let i = 0; i < scales; i++)
157 {
161 {
158 const size = blurSize * scaleFactors[Math.min(i, scaleFactors.length - 1)];
162 const size = blurSize * scaleFactors[Math.min(i, scaleFactors.length - 1)];
159 chain.push({ shader: Shader._bloomBlur, uniforms: { u_direction: [1, 0], u_blurSize: size } });
163 const blurPass = halfResBlur ? { scale: 0.5 } : {};
160 chain.push({ shader: Shader._bloomBlur, uniforms: { u_direction: [0, 1], u_blurSize: size } });
164 chain.push(Object.assign({
165 shader: Shader._bloomBlur,
166 uniforms: { u_direction: [1, 0], u_blurSize: size }
167 }, blurPass));
168 chain.push(Object.assign({
169 shader: Shader._bloomBlur,
170 uniforms: { u_direction: [0, 1], u_blurSize: size }
171 }, blurPass));
161 }
172 }
162
173
163 chain.push({
174 chain.push({
framework/engine/gl/glContext.js +90 −28
@@ -6,7 +6,8 @@ class GLContext
6 6 {
7 7 this.canvas = canvas;
8 8
9 const attrs = { alpha: true, premultipliedAlpha: false, antialias: true };
9 // 2D sprites do not benefit from MSAA; disabling avoids extra GPU cost.
10 const attrs = { alpha: true, premultipliedAlpha: false, antialias: false };
10 11 this.gl = canvas.getContext("webgl", attrs) || canvas.getContext("experimental-webgl", attrs);
11 12
12 13 if (!this.gl)
@@ -22,6 +23,10 @@ class GLContext
22 23 this.screenCopyShader = new Shader(Shader.SCREEN_VERT, Shader.SCREEN_COPY_FRAG);
23 24 this.textures = new WeakMap();
24 25
26 // Reused per-sprite uploads (avoid allocating Float32Array every draw).
27 this._uvData = new Float32Array(8);
28 this._matrixData = new Float32Array(16);
29
25 30 this.positionBuffer = gl.createBuffer();
26 31 gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
27 32 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
@@ -32,6 +37,8 @@ class GLContext
32 37 ]), gl.STATIC_DRAW);
33 38
34 39 this.texCoordBuffer = gl.createBuffer();
40 gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer);
41 gl.bufferData(gl.ARRAY_BUFFER, this._uvData, gl.DYNAMIC_DRAW);
35 42
36 43 // Fullscreen NDC quad (triangle strip) + UVs (v=0 at bottom, matches FBO sampling).
37 44 this.screenPositionBuffer = gl.createBuffer();
@@ -52,12 +59,15 @@ class GLContext
52 59 1, 1
53 60 ]), gl.STATIC_DRAW);
54 61
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];
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];
58 66 this._offscreenIndex = 0;
59 67 this._lastWidth = 0;
60 68 this._lastHeight = 0;
69 this._halfWidth = 0;
70 this._halfHeight = 0;
61 71 this.setSize(canvas.width, canvas.height);
62 72 }
63 73
@@ -71,6 +81,8 @@ class GLContext
71 81 {
72 82 this._lastWidth = width;
73 83 this._lastHeight = height;
84 this._halfWidth = Math.max(1, width >> 1);
85 this._halfHeight = Math.max(1, height >> 1);
74 86 gl.viewport(0, 0, width, height);
75 87 this._rebuildFramebuffers(width, height);
76 88 }
@@ -100,15 +112,21 @@ class GLContext
100 112 const gl = this.gl;
101 113 this._destroyFramebuffers();
102 114
103 for (let i = 0; i < 3; i++)
115 this._halfWidth = Math.max(1, width >> 1);
116 this._halfHeight = Math.max(1, height >> 1);
117
118 for (let i = 0; i < 5; i++)
104 119 {
120 const texW = i < 3 ? width : this._halfWidth;
121 const texH = i < 3 ? height : this._halfHeight;
122
105 123 const texture = gl.createTexture();
106 124 gl.bindTexture(gl.TEXTURE_2D, texture);
107 125 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
108 126 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
109 127 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
110 128 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);
129 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texW, texH, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
112 130
113 131 const fb = gl.createFramebuffer();
114 132 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
@@ -173,6 +191,7 @@ class GLContext
173 191 const toCanvas = !!options.toCanvas;
174 192 const sceneTexture = this.colorTextures[0];
175 193 let read = 0;
194 let readIsHalf = false;
176 195
177 196 gl.disable(gl.BLEND);
178 197
@@ -180,32 +199,62 @@ class GLContext
180 199 {
181 200 const pass = passes[i];
182 201 const isLast = i === passes.length - 1;
202 const wantHalf = pass.scale != null && pass.scale < 1;
183 203
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; }
204 let write;
205 let writeW;
206 let writeH;
207
208 if (wantHalf)
209 {
210 // Half-res ping-pong on indices 3/4.
211 if (readIsHalf)
212 { write = (read === 3) ? 4 : 3; }
213 else
214 { write = 3; }
215
216 writeW = this._halfWidth;
217 writeH = this._halfHeight;
218 }
219 else
220 {
221 // Full-res ping-pong on 1/2 (never overwrite scene buffer 0).
222 // When leaving half-res, read half texture into a full write target.
223 if (read === 1)
224 { write = 2; }
225 else if (read === 2)
226 { write = 1; }
227 else
228 { write = 1; }
229
230 writeW = this._lastWidth;
231 writeH = this._lastHeight;
232 }
190 233
191 234 if (isLast && toCanvas)
192 235 {
193 236 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
237 writeW = this._lastWidth;
238 writeH = this._lastHeight;
194 239 }
195 240 else
196 241 {
197 242 gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[write]);
198 243 }
199 244
200 gl.viewport(0, 0, this._lastWidth, this._lastHeight);
245 gl.viewport(0, 0, writeW, writeH);
201 246 gl.clearColor(0, 0, 0, 0);
202 247 gl.clear(gl.COLOR_BUFFER_BIT);
203 248
204 249 const uniforms = Object.assign({}, builtins, pass.uniforms || {});
250 uniforms.u_resolution = [writeW, writeH];
205 251 this.drawFullscreen(pass.shader, this.colorTextures[read], uniforms, sceneTexture);
206 252
207 253 if (!isLast || !toCanvas)
208 { read = write; }
254 {
255 read = write;
256 readIsHalf = wantHalf && !(isLast && toCanvas);
257 }
209 258 }
210 259
211 260 this._offscreenIndex = read;
@@ -334,13 +383,13 @@ class GLContext
334 383 }
335 384
336 385 const uv = options.uvRect || { u0: 0, v0: 0, u1: 1, v1: 1 };
386 const uvData = this._uvData;
387 uvData[0] = uv.u0; uvData[1] = uv.v0;
388 uvData[2] = uv.u1; uvData[3] = uv.v0;
389 uvData[4] = uv.u0; uvData[5] = uv.v1;
390 uvData[6] = uv.u1; uvData[7] = uv.v1;
337 391 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);
392 gl.bufferSubData(gl.ARRAY_BUFFER, 0, uvData);
344 393
345 394 if (info.attribs.texCoord >= 0)
346 395 {
@@ -353,7 +402,8 @@ class GLContext
353 402 options.w, options.h,
354 403 options.rotationDeg || 0,
355 404 options.mirrorX, options.mirrorY,
356 width, height
405 width, height,
406 this._matrixData
357 407 );
358 408
359 409 this._setUniform(info, "u_matrix", matrix);
@@ -511,7 +561,7 @@ class GLContext
511 561 }
512 562
513 563 // Column-major mat4: projection (canvas Y-down) * T * R * S
514 static _buildSpriteMatrix (x, y, w, h, rotationDeg, mirrorX, mirrorY, canvasW, canvasH)
564 static _buildSpriteMatrix (x, y, w, h, rotationDeg, mirrorX, mirrorY, canvasW, canvasH, out)
515 565 {
516 566 const sx = (mirrorX ? -1 : 1) * w;
517 567 const sy = (mirrorY ? -1 : 1) * h;
@@ -532,12 +582,24 @@ class GLContext
532 582 const pr12 = -1;
533 583 const pr13 = 1;
534 584
585 const matrix = out || new Float32Array(16);
535 586 // 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 ]);
587 matrix[0] = pr0 * m00;
588 matrix[1] = pr5 * m10;
589 matrix[2] = 0;
590 matrix[3] = 0;
591 matrix[4] = pr0 * m01;
592 matrix[5] = pr5 * m11;
593 matrix[6] = 0;
594 matrix[7] = 0;
595 matrix[8] = 0;
596 matrix[9] = 0;
597 matrix[10] = -1;
598 matrix[11] = 0;
599 matrix[12] = pr0 * m30 + pr12;
600 matrix[13] = pr5 * m31 + pr13;
601 matrix[14] = 0;
602 matrix[15] = 1;
603 return matrix;
542 604 }
543 605 }
@@ -6,7 +6,8 @@ class GLContext
6 {
6 {
7 this.canvas = canvas;
7 this.canvas = canvas;
8
8
9 const attrs = { alpha: true, premultipliedAlpha: false, antialias: true };
9 // 2D sprites do not benefit from MSAA; disabling avoids extra GPU cost.
10 const attrs = { alpha: true, premultipliedAlpha: false, antialias: false };
10 this.gl = canvas.getContext("webgl", attrs) || canvas.getContext("experimental-webgl", attrs);
11 this.gl = canvas.getContext("webgl", attrs) || canvas.getContext("experimental-webgl", attrs);
11
12
12 if (!this.gl)
13 if (!this.gl)
@@ -22,6 +23,10 @@ class GLContext
22 this.screenCopyShader = new Shader(Shader.SCREEN_VERT, Shader.SCREEN_COPY_FRAG);
23 this.screenCopyShader = new Shader(Shader.SCREEN_VERT, Shader.SCREEN_COPY_FRAG);
23 this.textures = new WeakMap();
24 this.textures = new WeakMap();
24
25
26 // Reused per-sprite uploads (avoid allocating Float32Array every draw).
27 this._uvData = new Float32Array(8);
28 this._matrixData = new Float32Array(16);
29
25 this.positionBuffer = gl.createBuffer();
30 this.positionBuffer = gl.createBuffer();
26 gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
31 gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer);
27 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
32 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
@@ -32,6 +37,8 @@ class GLContext
32 ]), gl.STATIC_DRAW);
37 ]), gl.STATIC_DRAW);
33
38
34 this.texCoordBuffer = gl.createBuffer();
39 this.texCoordBuffer = gl.createBuffer();
40 gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer);
41 gl.bufferData(gl.ARRAY_BUFFER, this._uvData, gl.DYNAMIC_DRAW);
35
42
36 // Fullscreen NDC quad (triangle strip) + UVs (v=0 at bottom, matches FBO sampling).
43 // Fullscreen NDC quad (triangle strip) + UVs (v=0 at bottom, matches FBO sampling).
37 this.screenPositionBuffer = gl.createBuffer();
44 this.screenPositionBuffer = gl.createBuffer();
@@ -52,12 +59,15 @@ class GLContext
52 1, 1
59 1, 1
53 ]), gl.STATIC_DRAW);
60 ]), gl.STATIC_DRAW);
54
61
55 // [0] = scene (stable during post), [1]/[2] = ping-pong for effect passes.
62 // [0] = scene (stable during post), [1]/[2] = full-res ping-pong,
56 this.framebuffers = [null, null, null];
63 // [3]/[4] = half-res ping-pong for pass.scale < 1 blur.
57 this.colorTextures = [null, null, null];
64 this.framebuffers = [null, null, null, null, null];
65 this.colorTextures = [null, null, null, null, null];
58 this._offscreenIndex = 0;
66 this._offscreenIndex = 0;
59 this._lastWidth = 0;
67 this._lastWidth = 0;
60 this._lastHeight = 0;
68 this._lastHeight = 0;
69 this._halfWidth = 0;
70 this._halfHeight = 0;
61 this.setSize(canvas.width, canvas.height);
71 this.setSize(canvas.width, canvas.height);
62 }
72 }
63
73
@@ -71,6 +81,8 @@ class GLContext
71 {
81 {
72 this._lastWidth = width;
82 this._lastWidth = width;
73 this._lastHeight = height;
83 this._lastHeight = height;
84 this._halfWidth = Math.max(1, width >> 1);
85 this._halfHeight = Math.max(1, height >> 1);
74 gl.viewport(0, 0, width, height);
86 gl.viewport(0, 0, width, height);
75 this._rebuildFramebuffers(width, height);
87 this._rebuildFramebuffers(width, height);
76 }
88 }
@@ -100,15 +112,21 @@ class GLContext
100 const gl = this.gl;
112 const gl = this.gl;
101 this._destroyFramebuffers();
113 this._destroyFramebuffers();
102
114
103 for (let i = 0; i < 3; i++)
115 this._halfWidth = Math.max(1, width >> 1);
116 this._halfHeight = Math.max(1, height >> 1);
117
118 for (let i = 0; i < 5; i++)
104 {
119 {
120 const texW = i < 3 ? width : this._halfWidth;
121 const texH = i < 3 ? height : this._halfHeight;
122
105 const texture = gl.createTexture();
123 const texture = gl.createTexture();
106 gl.bindTexture(gl.TEXTURE_2D, texture);
124 gl.bindTexture(gl.TEXTURE_2D, texture);
107 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
125 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);
126 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);
127 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
110 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
128 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);
129 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, texW, texH, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
112
130
113 const fb = gl.createFramebuffer();
131 const fb = gl.createFramebuffer();
114 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
132 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
@@ -173,6 +191,7 @@ class GLContext
173 const toCanvas = !!options.toCanvas;
191 const toCanvas = !!options.toCanvas;
174 const sceneTexture = this.colorTextures[0];
192 const sceneTexture = this.colorTextures[0];
175 let read = 0;
193 let read = 0;
194 let readIsHalf = false;
176
195
177 gl.disable(gl.BLEND);
196 gl.disable(gl.BLEND);
178
197
@@ -180,32 +199,62 @@ class GLContext
180 {
199 {
181 const pass = passes[i];
200 const pass = passes[i];
182 const isLast = i === passes.length - 1;
201 const isLast = i === passes.length - 1;
202 const wantHalf = pass.scale != null && pass.scale < 1;
183
203
184 // Never overwrite the scene buffer (index 0); ping-pong on 1/2.
204 let write;
185 let write = 1;
205 let writeW;
186 if (read === 1)
206 let writeH;
187 { write = 2; }
207
188 else if (read === 2)
208 if (wantHalf)
189 { write = 1; }
209 {
210 // Half-res ping-pong on indices 3/4.
211 if (readIsHalf)
212 { write = (read === 3) ? 4 : 3; }
213 else
214 { write = 3; }
215
216 writeW = this._halfWidth;
217 writeH = this._halfHeight;
218 }
219 else
220 {
221 // Full-res ping-pong on 1/2 (never overwrite scene buffer 0).
222 // When leaving half-res, read half texture into a full write target.
223 if (read === 1)
224 { write = 2; }
225 else if (read === 2)
226 { write = 1; }
227 else
228 { write = 1; }
229
230 writeW = this._lastWidth;
231 writeH = this._lastHeight;
232 }
190
233
191 if (isLast && toCanvas)
234 if (isLast && toCanvas)
192 {
235 {
193 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
236 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
237 writeW = this._lastWidth;
238 writeH = this._lastHeight;
194 }
239 }
195 else
240 else
196 {
241 {
197 gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[write]);
242 gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffers[write]);
198 }
243 }
199
244
200 gl.viewport(0, 0, this._lastWidth, this._lastHeight);
245 gl.viewport(0, 0, writeW, writeH);
201 gl.clearColor(0, 0, 0, 0);
246 gl.clearColor(0, 0, 0, 0);
202 gl.clear(gl.COLOR_BUFFER_BIT);
247 gl.clear(gl.COLOR_BUFFER_BIT);
203
248
204 const uniforms = Object.assign({}, builtins, pass.uniforms || {});
249 const uniforms = Object.assign({}, builtins, pass.uniforms || {});
250 uniforms.u_resolution = [writeW, writeH];
205 this.drawFullscreen(pass.shader, this.colorTextures[read], uniforms, sceneTexture);
251 this.drawFullscreen(pass.shader, this.colorTextures[read], uniforms, sceneTexture);
206
252
207 if (!isLast || !toCanvas)
253 if (!isLast || !toCanvas)
208 { read = write; }
254 {
255 read = write;
256 readIsHalf = wantHalf && !(isLast && toCanvas);
257 }
209 }
258 }
210
259
211 this._offscreenIndex = read;
260 this._offscreenIndex = read;
@@ -334,13 +383,13 @@ class GLContext
334 }
383 }
335
384
336 const uv = options.uvRect || { u0: 0, v0: 0, u1: 1, v1: 1 };
385 const uv = options.uvRect || { u0: 0, v0: 0, u1: 1, v1: 1 };
386 const uvData = this._uvData;
387 uvData[0] = uv.u0; uvData[1] = uv.v0;
388 uvData[2] = uv.u1; uvData[3] = uv.v0;
389 uvData[4] = uv.u0; uvData[5] = uv.v1;
390 uvData[6] = uv.u1; uvData[7] = uv.v1;
337 gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer);
391 gl.bindBuffer(gl.ARRAY_BUFFER, this.texCoordBuffer);
338 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
392 gl.bufferSubData(gl.ARRAY_BUFFER, 0, uvData);
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
393
345 if (info.attribs.texCoord >= 0)
394 if (info.attribs.texCoord >= 0)
346 {
395 {
@@ -353,7 +402,8 @@ class GLContext
353 options.w, options.h,
402 options.w, options.h,
354 options.rotationDeg || 0,
403 options.rotationDeg || 0,
355 options.mirrorX, options.mirrorY,
404 options.mirrorX, options.mirrorY,
356 width, height
405 width, height,
406 this._matrixData
357 );
407 );
358
408
359 this._setUniform(info, "u_matrix", matrix);
409 this._setUniform(info, "u_matrix", matrix);
@@ -511,7 +561,7 @@ class GLContext
511 }
561 }
512
562
513 // Column-major mat4: projection (canvas Y-down) * T * R * S
563 // Column-major mat4: projection (canvas Y-down) * T * R * S
514 static _buildSpriteMatrix (x, y, w, h, rotationDeg, mirrorX, mirrorY, canvasW, canvasH)
564 static _buildSpriteMatrix (x, y, w, h, rotationDeg, mirrorX, mirrorY, canvasW, canvasH, out)
515 {
565 {
516 const sx = (mirrorX ? -1 : 1) * w;
566 const sx = (mirrorX ? -1 : 1) * w;
517 const sy = (mirrorY ? -1 : 1) * h;
567 const sy = (mirrorY ? -1 : 1) * h;
@@ -532,12 +582,24 @@ class GLContext
532 const pr12 = -1;
582 const pr12 = -1;
533 const pr13 = 1;
583 const pr13 = 1;
534
584
585 const matrix = out || new Float32Array(16);
535 // P * M (only 2D affine terms matter)
586 // P * M (only 2D affine terms matter)
536 return new Float32Array([
587 matrix[0] = pr0 * m00;
537 pr0 * m00, pr5 * m10, 0, 0,
588 matrix[1] = pr5 * m10;
538 pr0 * m01, pr5 * m11, 0, 0,
589 matrix[2] = 0;
539 0, 0, -1, 0,
590 matrix[3] = 0;
540 pr0 * m30 + pr12, pr5 * m31 + pr13, 0, 1
591 matrix[4] = pr0 * m01;
541 ]);
592 matrix[5] = pr5 * m11;
593 matrix[6] = 0;
594 matrix[7] = 0;
595 matrix[8] = 0;
596 matrix[9] = 0;
597 matrix[10] = -1;
598 matrix[11] = 0;
599 matrix[12] = pr0 * m30 + pr12;
600 matrix[13] = pr5 * m31 + pr13;
601 matrix[14] = 0;
602 matrix[15] = 1;
603 return matrix;
542 }
604 }
543}
605}
framework/engine/image.js +9 −15
@@ -32,27 +32,18 @@ class image
32 32
33 33 draw (scene, dx, dy, dw, dh, rotation, mirrorX, mirrorY, alpha, subImage, shader, uniforms, textures, lights)
34 34 {
35 var shouldDraw = true;
36
37 if (dx < -Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
38 { shouldDraw = false; }
39
40 if (dy < -Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
41 { shouldDraw = false; }
42
43 if (dx > scene.real_size.x + Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
44 { shouldDraw = false; }
45
46 if (dy > scene.real_size.y + Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
47 { shouldDraw = false; }
35 if (!scene.glContext || !this.g_image)
36 { return; }
48 37
49 if (!shouldDraw || !scene.glContext || !this.g_image)
38 // One hypot for frustum pad (was computed 4× per sprite).
39 const pad = Math.sqrt(dw * dw + dh * dh);
40 if (dx < -pad || dy < -pad || dx > scene.real_size.x + pad || dy > scene.real_size.y + pad)
50 41 { return; }
51 42
52 43 const subImageData = this.getSubImage(subImage);
53 44 const imgW = this.g_image.width;
54 45 const imgH = this.g_image.height;
55 const glTextures = {};
46 let glTextures = null;
56 47
57 48 if (textures)
58 49 {
@@ -65,6 +56,9 @@ class image
65 56 if (!src)
66 57 { continue; }
67 58
59 if (!glTextures)
60 { glTextures = {}; }
61
68 62 const htmlImage = src.g_image || src;
69 63 glTextures[name] = scene.glContext.getTexture(htmlImage);
70 64 }
@@ -32,27 +32,18 @@ class image
32
32
33 draw (scene, dx, dy, dw, dh, rotation, mirrorX, mirrorY, alpha, subImage, shader, uniforms, textures, lights)
33 draw (scene, dx, dy, dw, dh, rotation, mirrorX, mirrorY, alpha, subImage, shader, uniforms, textures, lights)
34 {
34 {
35 var shouldDraw = true;
35 if (!scene.glContext || !this.g_image)
36
36 { return; }
37 if (dx < -Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
38 { shouldDraw = false; }
39
40 if (dy < -Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
41 { shouldDraw = false; }
42
43 if (dx > scene.real_size.x + Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
44 { shouldDraw = false; }
45
46 if (dy > scene.real_size.y + Math.sqrt(Math.pow(dw, 2) + Math.pow(dh, 2)))
47 { shouldDraw = false; }
48
37
49 if (!shouldDraw || !scene.glContext || !this.g_image)
38 // One hypot for frustum pad (was computed 4× per sprite).
39 const pad = Math.sqrt(dw * dw + dh * dh);
40 if (dx < -pad || dy < -pad || dx > scene.real_size.x + pad || dy > scene.real_size.y + pad)
50 { return; }
41 { return; }
51
42
52 const subImageData = this.getSubImage(subImage);
43 const subImageData = this.getSubImage(subImage);
53 const imgW = this.g_image.width;
44 const imgW = this.g_image.width;
54 const imgH = this.g_image.height;
45 const imgH = this.g_image.height;
55 const glTextures = {};
46 let glTextures = null;
56
47
57 if (textures)
48 if (textures)
58 {
49 {
@@ -65,6 +56,9 @@ class image
65 if (!src)
56 if (!src)
66 { continue; }
57 { continue; }
67
58
59 if (!glTextures)
60 { glTextures = {}; }
61
68 const htmlImage = src.g_image || src;
62 const htmlImage = src.g_image || src;
69 glTextures[name] = scene.glContext.getTexture(htmlImage);
63 glTextures[name] = scene.glContext.getTexture(htmlImage);
70 }
64 }
framework/engine/objectComponents/collider.js +5 −0
@@ -20,6 +20,11 @@ class Collider
20 20 this.checkCollisions();
21 21 }
22 22
23 // Bullets/FX have no click handlers — skip per-object mouse work entirely.
24 const obj = this.gameObject;
25 if (!obj.onClick && !obj.onMouseHeld)
26 { return; }
27
23 28 const pressed = GameInput.mousePressed();
24 29 const held = GameInput.mouseHeld();
25 30
@@ -20,6 +20,11 @@ class Collider
20 this.checkCollisions();
20 this.checkCollisions();
21 }
21 }
22
22
23 // Bullets/FX have no click handlers — skip per-object mouse work entirely.
24 const obj = this.gameObject;
25 if (!obj.onClick && !obj.onMouseHeld)
26 { return; }
27
23 const pressed = GameInput.mousePressed();
28 const pressed = GameInput.mousePressed();
24 const held = GameInput.mouseHeld();
29 const held = GameInput.mouseHeld();
25
30
framework/engine/objectComponents/renderer.js +9 −5
@@ -120,11 +120,15 @@ class Renderer
120 120 this.g_subImgOld = this.subImage;
121 121 }
122 122
123 const textures = {};
124 if (this.bumpMap)
125 { textures.u_bump = this.bumpMap; }
126 if (this.secondaryMap)
127 { textures.u_secondary = this.secondaryMap; }
123 let textures = null;
124 if (this.bumpMap || this.secondaryMap)
125 {
126 textures = {};
127 if (this.bumpMap)
128 { textures.u_bump = this.bumpMap; }
129 if (this.secondaryMap)
130 { textures.u_secondary = this.secondaryMap; }
131 }
128 132
129 133 this.sprite.draw(
130 134 this.gameObject.scene,
@@ -120,11 +120,15 @@ class Renderer
120 this.g_subImgOld = this.subImage;
120 this.g_subImgOld = this.subImage;
121 }
121 }
122
122
123 const textures = {};
123 let textures = null;
124 if (this.bumpMap)
124 if (this.bumpMap || this.secondaryMap)
125 { textures.u_bump = this.bumpMap; }
125 {
126 if (this.secondaryMap)
126 textures = {};
127 { textures.u_secondary = this.secondaryMap; }
127 if (this.bumpMap)
128 { textures.u_bump = this.bumpMap; }
129 if (this.secondaryMap)
130 { textures.u_secondary = this.secondaryMap; }
131 }
128
132
129 this.sprite.draw(
133 this.sprite.draw(
130 this.gameObject.scene,
134 this.gameObject.scene,
framework/engine/objectComponents/transform.js +9 −2
@@ -96,8 +96,15 @@ class Transform
96 96
97 97 update (deltaTime)
98 98 {
99 this.position = this.position.add(this.velocity.stretch(deltaTime));
100 this.rotation += this.angularVelocity * deltaTime;
99 const vel = this.velocity;
100 if (vel.x !== 0 || vel.y !== 0)
101 {
102 this.position.x += vel.x * deltaTime;
103 this.position.y += vel.y * deltaTime;
104 }
105
106 if (this.angularVelocity !== 0)
107 { this.rotation += this.angularVelocity * deltaTime; }
101 108 }
102 109
103 110 pointTowards (point)
@@ -96,8 +96,15 @@ class Transform
96
96
97 update (deltaTime)
97 update (deltaTime)
98 {
98 {
99 this.position = this.position.add(this.velocity.stretch(deltaTime));
99 const vel = this.velocity;
100 this.rotation += this.angularVelocity * deltaTime;
100 if (vel.x !== 0 || vel.y !== 0)
101 {
102 this.position.x += vel.x * deltaTime;
103 this.position.y += vel.y * deltaTime;
104 }
105
106 if (this.angularVelocity !== 0)
107 { this.rotation += this.angularVelocity * deltaTime; }
101 }
108 }
102
109
103 pointTowards (point)
110 pointTowards (point)
framework/engine/scene.js +41 −14
@@ -14,6 +14,8 @@ class Scene
14 14 quadTree = null;
15 15
16 16 pendingRemoval = [];
17 _sortedActiveObjects = null;
18 _sortDirty = true;
17 19
18 20 g_primary = false;
19 21
@@ -209,6 +211,7 @@ class Scene
209 211 { return; }
210 212
211 213 this.activeObjects.push(obj);
214 this._sortDirty = true;
212 215 obj.scene = this;
213 216 obj.initQuadtree(this.quadTree);
214 217 obj.checkQuadtree();
@@ -224,6 +227,8 @@ class Scene
224 227 {
225 228 if (!this.pendingRemoval.contains(obj))
226 229 { this.pendingRemoval.push(obj); }
230
231 this._sortDirty = true;
227 232 }
228 233
229 234 if (this.quadTree === obj.quadTree)
@@ -341,7 +346,10 @@ class Scene
341 346 }
342 347 else if (entry.shader)
343 348 {
344 passes.push({ shader: entry.shader, uniforms: entry.uniforms || null });
349 const pass = { shader: entry.shader, uniforms: entry.uniforms || null };
350 if (entry.scale != null)
351 { pass.scale = entry.scale; }
352 passes.push(pass);
345 353 }
346 354 }
347 355
@@ -394,7 +402,33 @@ class Scene
394 402 gl.clearTransparent();
395 403 }
396 404
397 const sortedActiveObjects = this.activeObjects.slice().sort((a, b) => a.layer - b.layer);
405 if (this._sortDirty || !this._sortedActiveObjects)
406 {
407 this._sortedActiveObjects = this.activeObjects.slice().sort((a, b) => a.layer - b.layer);
408 this._sortDirty = false;
409 }
410
411 const sortedActiveObjects = this._sortedActiveObjects;
412
413 // Bucket visible objects once so empty bloom layers can be skipped entirely.
414 const byLayer = Object.create(null);
415 for (let i = 0; i < sortedActiveObjects.length; i++)
416 {
417 const obj = sortedActiveObjects[i];
418 if (obj.destroyed || !obj.renderer || !obj.renderer.visible)
419 { continue; }
420
421 const name = obj.renderer.layerName;
422 let bucket = byLayer[name];
423 if (!bucket)
424 {
425 bucket = [];
426 byLayer[name] = bucket;
427 }
428
429 bucket.push(obj);
430 }
431
398 432 const builtins = {
399 433 u_resolution: [gl._lastWidth, gl._lastHeight],
400 434 u_time: this.postTime
@@ -403,22 +437,15 @@ class Scene
403 437 for (let li = 0; li < layers.length; li++)
404 438 {
405 439 const renderLayer = layers[li];
406 const layerName = renderLayer.name;
440 const layerObjects = byLayer[renderLayer.name];
441 if (!layerObjects || !layerObjects.length)
442 { continue; }
407 443
408 444 gl.beginOffscreenPass();
409 445 gl.clearTransparent();
410 446
411 for (let i = 0; i < sortedActiveObjects.length; i++)
412 {
413 const obj = sortedActiveObjects[i];
414 if (obj.destroyed || !obj.renderer || !obj.renderer.visible)
415 { continue; }
416
417 if (obj.renderer.layerName !== layerName)
418 { continue; }
419
420 obj.draw(this.context);
421 }
447 for (let i = 0; i < layerObjects.length; i++)
448 { layerObjects[i].draw(this.context); }
422 449
423 450 const postPasses = this.getPostPassesForLayer(renderLayer);
424 451 let texture = gl.colorTextures[0];
@@ -14,6 +14,8 @@ class Scene
14 quadTree = null;
14 quadTree = null;
15
15
16 pendingRemoval = [];
16 pendingRemoval = [];
17 _sortedActiveObjects = null;
18 _sortDirty = true;
17
19
18 g_primary = false;
20 g_primary = false;
19
21
@@ -209,6 +211,7 @@ class Scene
209 { return; }
211 { return; }
210
212
211 this.activeObjects.push(obj);
213 this.activeObjects.push(obj);
214 this._sortDirty = true;
212 obj.scene = this;
215 obj.scene = this;
213 obj.initQuadtree(this.quadTree);
216 obj.initQuadtree(this.quadTree);
214 obj.checkQuadtree();
217 obj.checkQuadtree();
@@ -224,6 +227,8 @@ class Scene
224 {
227 {
225 if (!this.pendingRemoval.contains(obj))
228 if (!this.pendingRemoval.contains(obj))
226 { this.pendingRemoval.push(obj); }
229 { this.pendingRemoval.push(obj); }
230
231 this._sortDirty = true;
227 }
232 }
228
233
229 if (this.quadTree === obj.quadTree)
234 if (this.quadTree === obj.quadTree)
@@ -341,7 +346,10 @@ class Scene
341 }
346 }
342 else if (entry.shader)
347 else if (entry.shader)
343 {
348 {
344 passes.push({ shader: entry.shader, uniforms: entry.uniforms || null });
349 const pass = { shader: entry.shader, uniforms: entry.uniforms || null };
350 if (entry.scale != null)
351 { pass.scale = entry.scale; }
352 passes.push(pass);
345 }
353 }
346 }
354 }
347
355
@@ -394,7 +402,33 @@ class Scene
394 gl.clearTransparent();
402 gl.clearTransparent();
395 }
403 }
396
404
397 const sortedActiveObjects = this.activeObjects.slice().sort((a, b) => a.layer - b.layer);
405 if (this._sortDirty || !this._sortedActiveObjects)
406 {
407 this._sortedActiveObjects = this.activeObjects.slice().sort((a, b) => a.layer - b.layer);
408 this._sortDirty = false;
409 }
410
411 const sortedActiveObjects = this._sortedActiveObjects;
412
413 // Bucket visible objects once so empty bloom layers can be skipped entirely.
414 const byLayer = Object.create(null);
415 for (let i = 0; i < sortedActiveObjects.length; i++)
416 {
417 const obj = sortedActiveObjects[i];
418 if (obj.destroyed || !obj.renderer || !obj.renderer.visible)
419 { continue; }
420
421 const name = obj.renderer.layerName;
422 let bucket = byLayer[name];
423 if (!bucket)
424 {
425 bucket = [];
426 byLayer[name] = bucket;
427 }
428
429 bucket.push(obj);
430 }
431
398 const builtins = {
432 const builtins = {
399 u_resolution: [gl._lastWidth, gl._lastHeight],
433 u_resolution: [gl._lastWidth, gl._lastHeight],
400 u_time: this.postTime
434 u_time: this.postTime
@@ -403,22 +437,15 @@ class Scene
403 for (let li = 0; li < layers.length; li++)
437 for (let li = 0; li < layers.length; li++)
404 {
438 {
405 const renderLayer = layers[li];
439 const renderLayer = layers[li];
406 const layerName = renderLayer.name;
440 const layerObjects = byLayer[renderLayer.name];
441 if (!layerObjects || !layerObjects.length)
442 { continue; }
407
443
408 gl.beginOffscreenPass();
444 gl.beginOffscreenPass();
409 gl.clearTransparent();
445 gl.clearTransparent();
410
446
411 for (let i = 0; i < sortedActiveObjects.length; i++)
447 for (let i = 0; i < layerObjects.length; i++)
412 {
448 { layerObjects[i].draw(this.context); }
413 const obj = sortedActiveObjects[i];
414 if (obj.destroyed || !obj.renderer || !obj.renderer.visible)
415 { continue; }
416
417 if (obj.renderer.layerName !== layerName)
418 { continue; }
419
420 obj.draw(this.context);
421 }
422
449
423 const postPasses = this.getPostPassesForLayer(renderLayer);
450 const postPasses = this.getPostPassesForLayer(renderLayer);
424 let texture = gl.colorTextures[0];
451 let texture = gl.colorTextures[0];
framework/util/input.js +13 −2
@@ -153,6 +153,9 @@ var GameInput =
153 153 { return GameInput.g_pKeyStatus[keyCode]; }
154 154 },
155 155
156 _pressedState: { left: false, middle: false, right: false },
157 _heldState: { left: false, middle: false, right: false },
158
156 159 mousePressed: function (btn)
157 160 {
158 161 switch (btn)
@@ -162,7 +165,11 @@ var GameInput =
162 165 case GameInput.MouseButtons.Right: return GameInput.g_altMouseDownThisFrame;
163 166 }
164 167
165 return { left: GameInput.g_mouseDownThisFrame, middle: GameInput.g_middleMouseDownThisFrame, right: GameInput.g_altMouseDownThisFrame };
168 const state = GameInput._pressedState;
169 state.left = GameInput.g_mouseDownThisFrame;
170 state.middle = GameInput.g_middleMouseDownThisFrame;
171 state.right = GameInput.g_altMouseDownThisFrame;
172 return state;
166 173 },
167 174
168 175 mouseHeld: function (btn)
@@ -174,6 +181,10 @@ var GameInput =
174 181 case GameInput.MouseButtons.Right: return GameInput.g_altMouseDown;
175 182 }
176 183
177 return { left: GameInput.g_mouseDown, middle: GameInput.g_middleMouseDown, right: GameInput.g_altMouseDown };
184 const state = GameInput._heldState;
185 state.left = GameInput.g_mouseDown;
186 state.middle = GameInput.g_middleMouseDown;
187 state.right = GameInput.g_altMouseDown;
188 return state;
178 189 }
179 190 };//
@@ -153,6 +153,9 @@ var GameInput =
153 { return GameInput.g_pKeyStatus[keyCode]; }
153 { return GameInput.g_pKeyStatus[keyCode]; }
154 },
154 },
155
155
156 _pressedState: { left: false, middle: false, right: false },
157 _heldState: { left: false, middle: false, right: false },
158
156 mousePressed: function (btn)
159 mousePressed: function (btn)
157 {
160 {
158 switch (btn)
161 switch (btn)
@@ -162,7 +165,11 @@ var GameInput =
162 case GameInput.MouseButtons.Right: return GameInput.g_altMouseDownThisFrame;
165 case GameInput.MouseButtons.Right: return GameInput.g_altMouseDownThisFrame;
163 }
166 }
164
167
165 return { left: GameInput.g_mouseDownThisFrame, middle: GameInput.g_middleMouseDownThisFrame, right: GameInput.g_altMouseDownThisFrame };
168 const state = GameInput._pressedState;
169 state.left = GameInput.g_mouseDownThisFrame;
170 state.middle = GameInput.g_middleMouseDownThisFrame;
171 state.right = GameInput.g_altMouseDownThisFrame;
172 return state;
166 },
173 },
167
174
168 mouseHeld: function (btn)
175 mouseHeld: function (btn)
@@ -174,6 +181,10 @@ var GameInput =
174 case GameInput.MouseButtons.Right: return GameInput.g_altMouseDown;
181 case GameInput.MouseButtons.Right: return GameInput.g_altMouseDown;
175 }
182 }
176
183
177 return { left: GameInput.g_mouseDown, middle: GameInput.g_middleMouseDown, right: GameInput.g_altMouseDown };
184 const state = GameInput._heldState;
185 state.left = GameInput.g_mouseDown;
186 state.middle = GameInput.g_middleMouseDown;
187 state.right = GameInput.g_altMouseDown;
188 return state;
178 }
189 }
179};//
190};//
framework/util/quadTree.js +156 −20
@@ -17,6 +17,11 @@ class QuadTree
17 17
18 18 this.width = width;
19 19 this.height = height;
20
21 // Reused across queries (results are valid until the next query).
22 this._queryNodes = [];
23 this._queryResult = [];
24 this._queryScored = [];
20 25 }
21 26
22 27 /**
@@ -34,11 +39,12 @@ class QuadTree
34 39 dirOfOob = this.outOfBounds(object);
35 40 }
36 41
37 // Node.add may split and move the object into a descendant leaf.
38 // Always re-resolve node afterwards — assigning the pre-split leaf
39 // leaves object.node pointing at an empty branch and breaks remove().
40 this.findNodeFromRoot(object).add(object);
41 object.node = this.findNodeFromRoot(object);
42 // Node.add may split and move the object into a descendant leaf
43 // (divide sets object.node). Otherwise assign the leaf we inserted into.
44 const node = this.findNodeFromRoot(object);
45 node.add(object);
46 if (!object.node)
47 { object.node = node; }
42 48 }
43 49
44 50 /**
@@ -80,7 +86,7 @@ class QuadTree
80 86 * @returns {GameObject[]} result
81 87 */
82 88
83 getObjectsOfTypesInRange (position, range, types)
89 getObjectsOfTypesInRange (position, range, types, options)
84 90 {
85 91 const typeFilter = Array.isArray(types)
86 92 ? types.filter(t => t != null)
@@ -91,11 +97,17 @@ class QuadTree
91 97 if (typeFilter.length === 0)
92 98 { return true; }
93 99
94 return typeFilter.some(t => obj instanceof t);
95 });
100 for (let i = 0, len = typeFilter.length; i < len; i++)
101 {
102 if (obj instanceof typeFilter[i])
103 { return true; }
104 }
105
106 return false;
107 }, options);
96 108 }
97 109
98 getObjectsWithTagInRange (position, range, tags)
110 getObjectsWithTagInRange (position, range, tags, options)
99 111 {
100 112 const tagFilter = Array.isArray(tags)
101 113 ? tags.filter(t => t != null)
@@ -110,14 +122,138 @@ class QuadTree
110 122 if (!objTags || objTags.length === 0)
111 123 { return false; }
112 124
113 return tagFilter.some(t => objTags.some(tag => tag == t));
125 for (let i = 0, len = tagFilter.length; i < len; i++)
126 {
127 const want = tagFilter[i];
128 for (let j = 0, jl = objTags.length; j < jl; j++)
129 {
130 if (objTags[j] == want)
131 { return true; }
132 }
133 }
134
135 return false;
136 }, options);
137 }
138
139 getClosestObjectWithTagInRange (position, range, tags)
140 {
141 const tagFilter = Array.isArray(tags)
142 ? tags.filter(t => t != null)
143 : (tags != null ? [tags] : []);
144
145 return this.getClosestObjectInRange(position, range, (obj) =>
146 {
147 if (tagFilter.length === 0)
148 { return true; }
149
150 const objTags = obj.tags;
151 if (!objTags || objTags.length === 0)
152 { return false; }
153
154 for (let i = 0, len = tagFilter.length; i < len; i++)
155 {
156 const want = tagFilter[i];
157 for (let j = 0, jl = objTags.length; j < jl; j++)
158 {
159 if (objTags[j] == want)
160 { return true; }
161 }
162 }
163
164 return false;
114 165 });
115 166 }
116 167
117 collectInRange (position, range, predicate)
168 /**
169 * @param {vector} position
170 * @param {number} range
171 * @param {Function} predicate
172 * @param {{ sort?: boolean }} [options] - sort defaults true (closest first)
173 * @returns {GameObject[]} reused buffer — consume before the next query
174 */
175 collectInRange (position, range, predicate, options)
176 {
177 const sort = !options || options.sort !== false;
178 const rangeSq = range * range;
179 const result = this._queryResult;
180 result.length = 0;
181
182 const nodes = this._queryNodes;
183 nodes.length = 0;
184 nodes.push(this.root);
185
186 if (!sort)
187 {
188 while (nodes.length > 0)
189 {
190 const node = nodes.pop();
191
192 if (!this.isInRange(position, range, node))
193 { continue; }
194
195 if (node.hasChildren)
196 {
197 nodes.push(node.topleft, node.topright, node.bottomleft, node.bottomright);
198 continue;
199 }
200
201 const objects = node.objects;
202 for (let i = 0, len = objects.length; i < len; i++)
203 {
204 const obj = objects[i];
205 const distSq = obj.transform.position.distanceToSq(position);
206 if (distSq > 0 && distSq < rangeSq && predicate(obj))
207 { result.push(obj); }
208 }
209 }
210
211 return result;
212 }
213
214 const scored = this._queryScored;
215 scored.length = 0;
216
217 while (nodes.length > 0)
218 {
219 const node = nodes.pop();
220
221 if (!this.isInRange(position, range, node))
222 { continue; }
223
224 if (node.hasChildren)
225 {
226 nodes.push(node.topleft, node.topright, node.bottomleft, node.bottomright);
227 continue;
228 }
229
230 const objects = node.objects;
231 for (let i = 0, len = objects.length; i < len; i++)
232 {
233 const obj = objects[i];
234 const distSq = obj.transform.position.distanceToSq(position);
235 if (distSq > 0 && distSq < rangeSq && predicate(obj))
236 { scored.push({ obj, dist: distSq }); }
237 }
238 }
239
240 if (scored.length > 1)
241 { scored.sort((a, b) => a.dist - b.dist); }
242
243 for (let i = 0, len = scored.length; i < len; i++)
244 { result.push(scored[i].obj); }
245
246 return result;
247 }
248
249 getClosestObjectInRange (position, range, predicate)
118 250 {
119 const scored = [];
120 const nodes = [this.root];
251 const rangeSq = range * range;
252 const nodes = this._queryNodes;
253 nodes.length = 0;
254 nodes.push(this.root);
255 let closest = null;
256 let closestDistSq = rangeSq;
121 257
122 258 while (nodes.length > 0)
123 259 {
@@ -128,24 +264,24 @@ class QuadTree
128 264
129 265 if (node.hasChildren)
130 266 {
131 nodes.push(...node.getChildren());
267 nodes.push(node.topleft, node.topright, node.bottomleft, node.bottomright);
132 268 continue;
133 269 }
134 270
135 const objects = node.getObjects();
271 const objects = node.objects;
136 272 for (let i = 0, len = objects.length; i < len; i++)
137 273 {
138 274 const obj = objects[i];
139 const dist = obj.transform.position.distanceTo(position);
140 if (dist > 0 && dist < range && predicate(obj))
275 const distSq = obj.transform.position.distanceToSq(position);
276 if (distSq > 0 && distSq < closestDistSq && predicate(obj))
141 277 {
142 scored.push({ obj, dist });
278 closestDistSq = distSq;
279 closest = obj;
143 280 }
144 281 }
145 282 }
146 283
147 scored.sort((a, b) => a.dist - b.dist);
148 return scored.map(entry => entry.obj);
284 return closest;
149 285 }
150 286
151 287 isInRange (vector, range, node)
@@ -17,6 +17,11 @@ class QuadTree
17
17
18 this.width = width;
18 this.width = width;
19 this.height = height;
19 this.height = height;
20
21 // Reused across queries (results are valid until the next query).
22 this._queryNodes = [];
23 this._queryResult = [];
24 this._queryScored = [];
20 }
25 }
21
26
22 /**
27 /**
@@ -34,11 +39,12 @@ class QuadTree
34 dirOfOob = this.outOfBounds(object);
39 dirOfOob = this.outOfBounds(object);
35 }
40 }
36
41
37 // Node.add may split and move the object into a descendant leaf.
42 // Node.add may split and move the object into a descendant leaf
38 // Always re-resolve node afterwards — assigning the pre-split leaf
43 // (divide sets object.node). Otherwise assign the leaf we inserted into.
39 // leaves object.node pointing at an empty branch and breaks remove().
44 const node = this.findNodeFromRoot(object);
40 this.findNodeFromRoot(object).add(object);
45 node.add(object);
41 object.node = this.findNodeFromRoot(object);
46 if (!object.node)
47 { object.node = node; }
42 }
48 }
43
49
44 /**
50 /**
@@ -80,7 +86,7 @@ class QuadTree
80 * @returns {GameObject[]} result
86 * @returns {GameObject[]} result
81 */
87 */
82
88
83 getObjectsOfTypesInRange (position, range, types)
89 getObjectsOfTypesInRange (position, range, types, options)
84 {
90 {
85 const typeFilter = Array.isArray(types)
91 const typeFilter = Array.isArray(types)
86 ? types.filter(t => t != null)
92 ? types.filter(t => t != null)
@@ -91,11 +97,17 @@ class QuadTree
91 if (typeFilter.length === 0)
97 if (typeFilter.length === 0)
92 { return true; }
98 { return true; }
93
99
94 return typeFilter.some(t => obj instanceof t);
100 for (let i = 0, len = typeFilter.length; i < len; i++)
95 });
101 {
102 if (obj instanceof typeFilter[i])
103 { return true; }
104 }
105
106 return false;
107 }, options);
96 }
108 }
97
109
98 getObjectsWithTagInRange (position, range, tags)
110 getObjectsWithTagInRange (position, range, tags, options)
99 {
111 {
100 const tagFilter = Array.isArray(tags)
112 const tagFilter = Array.isArray(tags)
101 ? tags.filter(t => t != null)
113 ? tags.filter(t => t != null)
@@ -110,14 +122,138 @@ class QuadTree
110 if (!objTags || objTags.length === 0)
122 if (!objTags || objTags.length === 0)
111 { return false; }
123 { return false; }
112
124
113 return tagFilter.some(t => objTags.some(tag => tag == t));
125 for (let i = 0, len = tagFilter.length; i < len; i++)
126 {
127 const want = tagFilter[i];
128 for (let j = 0, jl = objTags.length; j < jl; j++)
129 {
130 if (objTags[j] == want)
131 { return true; }
132 }
133 }
134
135 return false;
136 }, options);
137 }
138
139 getClosestObjectWithTagInRange (position, range, tags)
140 {
141 const tagFilter = Array.isArray(tags)
142 ? tags.filter(t => t != null)
143 : (tags != null ? [tags] : []);
144
145 return this.getClosestObjectInRange(position, range, (obj) =>
146 {
147 if (tagFilter.length === 0)
148 { return true; }
149
150 const objTags = obj.tags;
151 if (!objTags || objTags.length === 0)
152 { return false; }
153
154 for (let i = 0, len = tagFilter.length; i < len; i++)
155 {
156 const want = tagFilter[i];
157 for (let j = 0, jl = objTags.length; j < jl; j++)
158 {
159 if (objTags[j] == want)
160 { return true; }
161 }
162 }
163
164 return false;
114 });
165 });
115 }
166 }
116
167
117 collectInRange (position, range, predicate)
168 /**
169 * @param {vector} position
170 * @param {number} range
171 * @param {Function} predicate
172 * @param {{ sort?: boolean }} [options] - sort defaults true (closest first)
173 * @returns {GameObject[]} reused buffer — consume before the next query
174 */
175 collectInRange (position, range, predicate, options)
176 {
177 const sort = !options || options.sort !== false;
178 const rangeSq = range * range;
179 const result = this._queryResult;
180 result.length = 0;
181
182 const nodes = this._queryNodes;
183 nodes.length = 0;
184 nodes.push(this.root);
185
186 if (!sort)
187 {
188 while (nodes.length > 0)
189 {
190 const node = nodes.pop();
191
192 if (!this.isInRange(position, range, node))
193 { continue; }
194
195 if (node.hasChildren)
196 {
197 nodes.push(node.topleft, node.topright, node.bottomleft, node.bottomright);
198 continue;
199 }
200
201 const objects = node.objects;
202 for (let i = 0, len = objects.length; i < len; i++)
203 {
204 const obj = objects[i];
205 const distSq = obj.transform.position.distanceToSq(position);
206 if (distSq > 0 && distSq < rangeSq && predicate(obj))
207 { result.push(obj); }
208 }
209 }
210
211 return result;
212 }
213
214 const scored = this._queryScored;
215 scored.length = 0;
216
217 while (nodes.length > 0)
218 {
219 const node = nodes.pop();
220
221 if (!this.isInRange(position, range, node))
222 { continue; }
223
224 if (node.hasChildren)
225 {
226 nodes.push(node.topleft, node.topright, node.bottomleft, node.bottomright);
227 continue;
228 }
229
230 const objects = node.objects;
231 for (let i = 0, len = objects.length; i < len; i++)
232 {
233 const obj = objects[i];
234 const distSq = obj.transform.position.distanceToSq(position);
235 if (distSq > 0 && distSq < rangeSq && predicate(obj))
236 { scored.push({ obj, dist: distSq }); }
237 }
238 }
239
240 if (scored.length > 1)
241 { scored.sort((a, b) => a.dist - b.dist); }
242
243 for (let i = 0, len = scored.length; i < len; i++)
244 { result.push(scored[i].obj); }
245
246 return result;
247 }
248
249 getClosestObjectInRange (position, range, predicate)
118 {
250 {
119 const scored = [];
251 const rangeSq = range * range;
120 const nodes = [this.root];
252 const nodes = this._queryNodes;
253 nodes.length = 0;
254 nodes.push(this.root);
255 let closest = null;
256 let closestDistSq = rangeSq;
121
257
122 while (nodes.length > 0)
258 while (nodes.length > 0)
123 {
259 {
@@ -128,24 +264,24 @@ class QuadTree
128
264
129 if (node.hasChildren)
265 if (node.hasChildren)
130 {
266 {
131 nodes.push(...node.getChildren());
267 nodes.push(node.topleft, node.topright, node.bottomleft, node.bottomright);
132 continue;
268 continue;
133 }
269 }
134
270
135 const objects = node.getObjects();
271 const objects = node.objects;
136 for (let i = 0, len = objects.length; i < len; i++)
272 for (let i = 0, len = objects.length; i < len; i++)
137 {
273 {
138 const obj = objects[i];
274 const obj = objects[i];
139 const dist = obj.transform.position.distanceTo(position);
275 const distSq = obj.transform.position.distanceToSq(position);
140 if (dist > 0 && dist < range && predicate(obj))
276 if (distSq > 0 && distSq < closestDistSq && predicate(obj))
141 {
277 {
142 scored.push({ obj, dist });
278 closestDistSq = distSq;
279 closest = obj;
143 }
280 }
144 }
281 }
145 }
282 }
146
283
147 scored.sort((a, b) => a.dist - b.dist);
284 return closest;
148 return scored.map(entry => entry.obj);
149 }
285 }
150
286
151 isInRange (vector, range, node)
287 isInRange (vector, range, node)
framework/util/vector.js +20 −4
@@ -15,6 +15,11 @@ class vector
15 15 return Math.sqrt((this.x * this.x) + (this.y * this.y));
16 16 }
17 17
18 get lengthSq ()
19 {
20 return (this.x * this.x) + (this.y * this.y);
21 }
22
18 23 getLength ()
19 24 {
20 25 return Math.sqrt((this.x * this.x) + (this.y * this.y));
@@ -39,10 +44,10 @@ class vector
39 44 normalize ()
40 45 {
41 46 var newVector = this.getCopy();
47 var length = newVector.length;
42 48
43 if (newVector.length != 0)
49 if (length != 0)
44 50 {
45 var length = newVector.length;
46 51 newVector.x /= length;
47 52 newVector.y /= length;
48 53 }
@@ -58,13 +63,24 @@ class vector
58 63 return this.add(delta.stretch(t));
59 64 }
60 65
66 lerpToInto (otherVector, t, out)
67 {
68 out.x = this.x + (otherVector.x - this.x) * t;
69 out.y = this.y + (otherVector.y - this.y) * t;
70 return out;
71 }
72
61 73
62 distanceTo (otherVector)
74 distanceToSq (otherVector)
63 75 {
64 76 var dX = this.x - otherVector.x;
65 77 var dY = this.y - otherVector.y;
78 return (dX * dX) + (dY * dY);
79 }
66 80
67 return new vector(dX, dY).length;
81 distanceTo (otherVector)
82 {
83 return Math.sqrt(this.distanceToSq(otherVector));
68 84 }
69 85
70 86
@@ -15,6 +15,11 @@ class vector
15 return Math.sqrt((this.x * this.x) + (this.y * this.y));
15 return Math.sqrt((this.x * this.x) + (this.y * this.y));
16 }
16 }
17
17
18 get lengthSq ()
19 {
20 return (this.x * this.x) + (this.y * this.y);
21 }
22
18 getLength ()
23 getLength ()
19 {
24 {
20 return Math.sqrt((this.x * this.x) + (this.y * this.y));
25 return Math.sqrt((this.x * this.x) + (this.y * this.y));
@@ -39,10 +44,10 @@ class vector
39 normalize ()
44 normalize ()
40 {
45 {
41 var newVector = this.getCopy();
46 var newVector = this.getCopy();
47 var length = newVector.length;
42
48
43 if (newVector.length != 0)
49 if (length != 0)
44 {
50 {
45 var length = newVector.length;
46 newVector.x /= length;
51 newVector.x /= length;
47 newVector.y /= length;
52 newVector.y /= length;
48 }
53 }
@@ -58,13 +63,24 @@ class vector
58 return this.add(delta.stretch(t));
63 return this.add(delta.stretch(t));
59 }
64 }
60
65
66 lerpToInto (otherVector, t, out)
67 {
68 out.x = this.x + (otherVector.x - this.x) * t;
69 out.y = this.y + (otherVector.y - this.y) * t;
70 return out;
71 }
72
61
73
62 distanceTo (otherVector)
74 distanceToSq (otherVector)
63 {
75 {
64 var dX = this.x - otherVector.x;
76 var dX = this.x - otherVector.x;
65 var dY = this.y - otherVector.y;
77 var dY = this.y - otherVector.y;
78 return (dX * dX) + (dY * dY);
79 }
66
80
67 return new vector(dX, dY).length;
81 distanceTo (otherVector)
82 {
83 return Math.sqrt(this.distanceToSq(otherVector));
68 }
84 }
69
85
70
86
glbuild.sh +10 −0
@@ -36,6 +36,16 @@ printf "Build started, output file: %s\n" "$BUILD_FILE"
36 36 rm -f "$BUILD_FILE"
37 37 mkdir -p "$(dirname "$BUILD_FILE")"
38 38
39 cat >> "$BUILD_FILE" <<'EOF'
40 /*
41 * AUTO-GENERATED FILE — DO NOT EDIT BY HAND.
42 *
43 * Built by glbuild.sh from the modular sources in this repository.
44 * Make changes in the framework/ source tree, then rebuild.
45 * Upstream: https://gitlab.com/Timfa/frameworkv3
46 */
47 EOF
48
39 49 for file in "${FILES[@]}"
40 50 do
41 51 if [[ ! -f "$file" ]]
@@ -36,6 +36,16 @@ printf "Build started, output file: %s\n" "$BUILD_FILE"
36rm -f "$BUILD_FILE"
36rm -f "$BUILD_FILE"
37mkdir -p "$(dirname "$BUILD_FILE")"
37mkdir -p "$(dirname "$BUILD_FILE")"
38
38
39cat >> "$BUILD_FILE" <<'EOF'
40/*
41 * AUTO-GENERATED FILE — DO NOT EDIT BY HAND.
42 *
43 * Built by glbuild.sh from the modular sources in this repository.
44 * Make changes in the framework/ source tree, then rebuild.
45 * Upstream: https://gitlab.com/Timfa/frameworkv3
46 */
47EOF
48
39for file in "${FILES[@]}"
49for file in "${FILES[@]}"
40do
50do
41 if [[ ! -f "$file" ]]
51 if [[ ! -f "$file" ]]