@n3rdw1z4rd/core 0.18.4 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +72 -10
  2. package/dist/astar.d.ts +44 -0
  3. package/dist/astar.js +118 -0
  4. package/dist/canvas-renderer.d.ts +154 -0
  5. package/dist/canvas-renderer.js +200 -0
  6. package/dist/clock.d.ts +69 -0
  7. package/dist/clock.js +108 -0
  8. package/dist/color-palette.d.ts +25 -0
  9. package/dist/color-palette.js +112 -0
  10. package/dist/color.d.ts +90 -0
  11. package/dist/color.js +224 -0
  12. package/dist/css/main.css +1 -3
  13. package/dist/disposable.d.ts +27 -0
  14. package/dist/disposable.js +32 -0
  15. package/dist/dungeon-generator.d.ts +142 -0
  16. package/dist/dungeon-generator.js +288 -0
  17. package/dist/ecs.d.ts +87 -0
  18. package/dist/ecs.js +101 -0
  19. package/dist/emitter.d.ts +40 -0
  20. package/dist/emitter.js +54 -0
  21. package/dist/event-queue.d.ts +29 -0
  22. package/dist/event-queue.js +40 -0
  23. package/dist/index.cjs +3813 -0
  24. package/dist/index.d.cts +2655 -0
  25. package/dist/index.d.ts +35 -873
  26. package/dist/index.js +34 -3986
  27. package/dist/input/action-map.d.ts +79 -0
  28. package/dist/input/action-map.js +131 -0
  29. package/dist/input/bindings.d.ts +273 -0
  30. package/dist/input/bindings.js +250 -0
  31. package/dist/input/gestures.d.ts +108 -0
  32. package/dist/input/gestures.js +159 -0
  33. package/dist/input/index.d.ts +5 -0
  34. package/dist/input/index.js +5 -0
  35. package/dist/input/input.d.ts +297 -0
  36. package/dist/input/input.js +695 -0
  37. package/dist/log.d.ts +8 -0
  38. package/dist/log.js +9 -0
  39. package/dist/map2d.d.ts +83 -0
  40. package/dist/map2d.js +120 -0
  41. package/dist/map3d-CHDJiq5T.d.cts +236 -0
  42. package/dist/map3d.d.ts +94 -0
  43. package/dist/map3d.js +148 -0
  44. package/dist/math.d.ts +176 -0
  45. package/dist/math.js +206 -0
  46. package/dist/misc.d.ts +46 -0
  47. package/dist/misc.js +71 -0
  48. package/dist/observable.d.ts +43 -0
  49. package/dist/observable.js +53 -0
  50. package/dist/particle-renderer.d.ts +47 -0
  51. package/dist/particle-renderer.js +82 -0
  52. package/dist/particle-system-2d.d.ts +60 -0
  53. package/dist/particle-system-2d.js +147 -0
  54. package/dist/random.d.ts +46 -0
  55. package/dist/random.js +74 -0
  56. package/dist/rectangle.d.ts +44 -0
  57. package/dist/rectangle.js +69 -0
  58. package/dist/rng.d.ts +72 -0
  59. package/dist/rng.js +152 -0
  60. package/dist/signal.d.ts +34 -0
  61. package/dist/signal.js +41 -0
  62. package/dist/spatial-partition-2d.d.ts +42 -0
  63. package/dist/spatial-partition-2d.js +52 -0
  64. package/dist/spatial-partition-3d-Ba-VBveM.cjs +1324 -0
  65. package/dist/spatial-partition-3d.d.ts +44 -0
  66. package/dist/spatial-partition-3d.js +57 -0
  67. package/dist/three/asteroid-mesh.d.ts +41 -0
  68. package/dist/three/asteroid-mesh.js +44 -0
  69. package/dist/three/camera-rig.d.ts +140 -0
  70. package/dist/three/camera-rig.js +197 -0
  71. package/dist/three/cube-sphere-geometry.d.ts +55 -0
  72. package/dist/three/cube-sphere-geometry.js +239 -0
  73. package/dist/three/ecs.d.ts +75 -0
  74. package/dist/three/ecs.js +64 -0
  75. package/dist/three/index.d.ts +12 -0
  76. package/dist/three/index.js +12 -0
  77. package/dist/three/particle-system-3d.d.ts +53 -0
  78. package/dist/three/particle-system-3d.js +224 -0
  79. package/dist/three/renderer.d.ts +38 -0
  80. package/dist/three/renderer.js +57 -0
  81. package/dist/three/starfield.d.ts +23 -0
  82. package/dist/three/starfield.js +64 -0
  83. package/dist/three/texture-atlas.d.ts +76 -0
  84. package/dist/three/texture-atlas.js +84 -0
  85. package/dist/three/texture-utils.d.ts +31 -0
  86. package/dist/three/texture-utils.js +44 -0
  87. package/dist/three/voxel-geometry.d.ts +72 -0
  88. package/dist/three/voxel-geometry.js +231 -0
  89. package/dist/three/voxel-mesh.d.ts +67 -0
  90. package/dist/three/voxel-mesh.js +71 -0
  91. package/dist/three.cjs +1307 -0
  92. package/dist/three.d.cts +655 -0
  93. package/dist/tilemap.d.ts +17 -0
  94. package/dist/tilemap.js +26 -0
  95. package/dist/types.d.ts +34 -0
  96. package/dist/types.js +0 -0
  97. package/dist/vector.d.ts +78 -0
  98. package/dist/vector.js +169 -0
  99. package/dist/webgl-renderer.d.ts +89 -0
  100. package/dist/webgl-renderer.js +140 -0
  101. package/dist/webgl.d.ts +357 -0
  102. package/dist/webgl.js +628 -0
  103. package/dist/worker-interface.d.ts +30 -0
  104. package/dist/worker-interface.js +39 -0
  105. package/package.json +55 -13
  106. package/dist/css/index.ts +0 -1
  107. package/dist/index.css +0 -104
  108. package/dist/index.d.mts +0 -873
  109. package/dist/index.mjs +0 -3982
package/dist/webgl.js ADDED
@@ -0,0 +1,628 @@
1
+ //#region src/webgl.ts
2
+ /**
3
+ * Literal GLenum values, so importing this module doesn't require `WebGL2RenderingContext` to exist.
4
+ *
5
+ * @category WebGL
6
+ */
7
+ let ShaderType = /* @__PURE__ */ function(ShaderType) {
8
+ /** gl.VERTEX_SHADER */
9
+ ShaderType[ShaderType["VERTEX"] = 35633] = "VERTEX";
10
+ /** gl.FRAGMENT_SHADER */
11
+ ShaderType[ShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
12
+ return ShaderType;
13
+ }({});
14
+ /**
15
+ * Creates a WebGL2 context. Throws (instead of returning null) when WebGL2 isn't available.
16
+ *
17
+ * @param canvas defaults to a new canvas element
18
+ *
19
+ * @category WebGL
20
+ */
21
+ function CreateWebGlContext(canvas, attributes) {
22
+ const gl = (canvas ?? document.createElement("canvas")).getContext("webgl2", attributes);
23
+ if (!gl) throw new Error("WebGL2 is not available (unsupported browser or GPU, or the context was lost)");
24
+ return gl;
25
+ }
26
+ /**
27
+ * Sizes the drawing buffer to `width` x `height` CSS pixels times the pixel ratio (sharp on
28
+ * high-DPI screens) and sets the viewport. Without a size, uses the canvas's parent (or its own)
29
+ * size on the page. Returns whether the size changed.
30
+ *
31
+ * @category WebGL
32
+ */
33
+ function ResizeWebGlContext(gl, width, height, pixelRatio = globalThis.devicePixelRatio ?? 1) {
34
+ const canvas = gl.canvas;
35
+ if (width === void 0 || height === void 0) {
36
+ const element = canvas;
37
+ const rect = element.parentElement?.getBoundingClientRect?.() ?? element.getBoundingClientRect?.();
38
+ width ??= rect?.width ?? canvas.width;
39
+ height ??= rect?.height ?? canvas.height;
40
+ }
41
+ const bufferWidth = Math.max(1, Math.round(width * pixelRatio));
42
+ const bufferHeight = Math.max(1, Math.round(height * pixelRatio));
43
+ if (canvas.width === bufferWidth && canvas.height === bufferHeight) return false;
44
+ canvas.width = bufferWidth;
45
+ canvas.height = bufferHeight;
46
+ gl.viewport(0, 0, bufferWidth, bufferHeight);
47
+ return true;
48
+ }
49
+ function describeShaderError(log, source) {
50
+ const lines = source.split("\n");
51
+ const errorLines = new Set([...log.matchAll(/ERROR:\s*\d+:(\d+):/g)].map((m) => Number(m[1])));
52
+ const excerpt = [];
53
+ for (const line of [...errorLines].sort((a, b) => a - b)) {
54
+ for (let n = Math.max(1, line - 2); n <= Math.min(lines.length, line + 2); n++) excerpt.push(`${n === line ? ">" : " "} ${String(n).padStart(4)} | ${lines[n - 1]}`);
55
+ excerpt.push("");
56
+ }
57
+ return [
58
+ log.trim(),
59
+ "",
60
+ ...excerpt
61
+ ].join("\n").trimEnd();
62
+ }
63
+ /**
64
+ * Compiles a shader; throws an Error quoting the failing source lines.
65
+ *
66
+ * @category WebGL
67
+ */
68
+ function CompileShader(gl, type, source) {
69
+ const shader = gl.createShader(type);
70
+ if (!shader) throw new Error("CompileShader: could not create a shader (context lost?)");
71
+ gl.shaderSource(shader, source);
72
+ gl.compileShader(shader);
73
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
74
+ const log = gl.getShaderInfoLog(shader) ?? "";
75
+ const kind = type === 35633 ? "vertex" : "fragment";
76
+ gl.deleteShader(shader);
77
+ throw new Error(`CompileShader: ${kind} shader failed to compile:\n${describeShaderError(log, source)}`);
78
+ }
79
+ return shader;
80
+ }
81
+ /**
82
+ * Links a program from shader sources (or compiled shaders). Shaders compiled here are deleted
83
+ * after linking; ones passed in are left to the caller.
84
+ *
85
+ * @category WebGL
86
+ */
87
+ function CreateProgram(gl, vertexShader, fragmentShader) {
88
+ const vs = typeof vertexShader === "string" ? CompileShader(gl, 35633, vertexShader) : vertexShader;
89
+ let fs;
90
+ try {
91
+ fs = typeof fragmentShader === "string" ? CompileShader(gl, 35632, fragmentShader) : fragmentShader;
92
+ } catch (error) {
93
+ if (typeof vertexShader === "string") gl.deleteShader(vs);
94
+ throw error;
95
+ }
96
+ const program = gl.createProgram();
97
+ if (!program) throw new Error("CreateProgram: could not create a program (context lost?)");
98
+ gl.attachShader(program, vs);
99
+ gl.attachShader(program, fs);
100
+ gl.linkProgram(program);
101
+ const linked = gl.getProgramParameter(program, gl.LINK_STATUS);
102
+ const log = linked ? "" : gl.getProgramInfoLog(program) ?? "";
103
+ for (const [shader, owned] of [[vs, typeof vertexShader === "string"], [fs, typeof fragmentShader === "string"]]) {
104
+ gl.detachShader(program, shader);
105
+ if (owned) gl.deleteShader(shader);
106
+ }
107
+ if (!linked) {
108
+ gl.deleteProgram(program);
109
+ throw new Error(`CreateProgram: failed to link:\n${log.trim()}`);
110
+ }
111
+ return program;
112
+ }
113
+ function isSamplerType(gl, type) {
114
+ return samplerTarget(gl, type) !== void 0;
115
+ }
116
+ /** The texture target a sampler type binds to (TEXTURE_2D, TEXTURE_3D, ...), or undefined if it isn't a sampler. */
117
+ function samplerTarget(gl, type) {
118
+ switch (type) {
119
+ case gl.SAMPLER_2D:
120
+ case gl.SAMPLER_2D_SHADOW:
121
+ case gl.INT_SAMPLER_2D:
122
+ case gl.UNSIGNED_INT_SAMPLER_2D: return gl.TEXTURE_2D;
123
+ case gl.SAMPLER_3D:
124
+ case gl.INT_SAMPLER_3D:
125
+ case gl.UNSIGNED_INT_SAMPLER_3D: return gl.TEXTURE_3D;
126
+ case gl.SAMPLER_CUBE:
127
+ case gl.SAMPLER_CUBE_SHADOW:
128
+ case gl.INT_SAMPLER_CUBE:
129
+ case gl.UNSIGNED_INT_SAMPLER_CUBE: return gl.TEXTURE_CUBE_MAP;
130
+ case gl.SAMPLER_2D_ARRAY:
131
+ case gl.SAMPLER_2D_ARRAY_SHADOW:
132
+ case gl.INT_SAMPLER_2D_ARRAY:
133
+ case gl.UNSIGNED_INT_SAMPLER_2D_ARRAY: return gl.TEXTURE_2D_ARRAY;
134
+ }
135
+ }
136
+ /**
137
+ * Active attributes and uniforms of a linked program. Array uniforms are listed by their base
138
+ * name (`uLights[0]` -> `uLights`); samplers are given consecutive texture units.
139
+ *
140
+ * @category WebGL
141
+ */
142
+ function GetProgramLocations(gl, program) {
143
+ const attributes = {};
144
+ const uniforms = {};
145
+ const attributeCount = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
146
+ for (let i = 0; i < attributeCount; i++) {
147
+ const info = gl.getActiveAttrib(program, i);
148
+ if (info.name.startsWith("gl_")) continue;
149
+ attributes[info.name] = {
150
+ location: gl.getAttribLocation(program, info.name),
151
+ type: info.type,
152
+ size: info.size
153
+ };
154
+ }
155
+ const uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
156
+ let textureUnit = 0;
157
+ for (let i = 0; i < uniformCount; i++) {
158
+ const info = gl.getActiveUniform(program, i);
159
+ const location = gl.getUniformLocation(program, info.name);
160
+ if (!location) continue;
161
+ const name = info.name.endsWith("[0]") ? info.name.slice(0, -3) : info.name;
162
+ const uniform = {
163
+ location,
164
+ type: info.type,
165
+ size: info.size
166
+ };
167
+ if (isSamplerType(gl, info.type)) {
168
+ uniform.textureUnit = textureUnit;
169
+ textureUnit += info.size;
170
+ }
171
+ uniforms[name] = uniform;
172
+ }
173
+ return {
174
+ attributes,
175
+ uniforms
176
+ };
177
+ }
178
+ /**
179
+ * Links a program and collects its attribute and uniform info.
180
+ *
181
+ * @category WebGL
182
+ */
183
+ function CreateProgramInfo(gl, vertexShaderSource, fragmentShaderSource) {
184
+ const program = CreateProgram(gl, vertexShaderSource, fragmentShaderSource);
185
+ return {
186
+ program,
187
+ ...GetProgramLocations(gl, program)
188
+ };
189
+ }
190
+ /**
191
+ * Deletes the program.
192
+ *
193
+ * @category WebGL
194
+ */
195
+ function DeleteProgramInfo(gl, info) {
196
+ gl.deleteProgram(info.program);
197
+ }
198
+ const textureOf = (value) => {
199
+ if (value && typeof value === "object" && "texture" in value) return value.texture;
200
+ if (typeof WebGLTexture !== "undefined" && value instanceof WebGLTexture) return value;
201
+ };
202
+ /**
203
+ * Sets uniforms by name; the right `gl.uniform*` call comes from each uniform's declared type.
204
+ * Textures are bound to the sampler's texture unit. Names the program doesn't use (e.g. optimized
205
+ * away by the compiler) are ignored. Makes the program current.
206
+ *
207
+ * @category WebGL
208
+ */
209
+ function SetUniforms(gl, info, values) {
210
+ gl.useProgram(info.program);
211
+ for (const name in values) {
212
+ const uniform = info.uniforms[name];
213
+ if (uniform) SetUniform(gl, uniform, values[name]);
214
+ }
215
+ }
216
+ function SetUniform(gl, uniform, value) {
217
+ const { location, type } = uniform;
218
+ const target = samplerTarget(gl, type);
219
+ if (target !== void 0) {
220
+ const textures = Array.isArray(value) && value.length > 0 && typeof value[0] !== "number" ? value : [value];
221
+ const units = [];
222
+ textures.forEach((texture, i) => {
223
+ const unit = (uniform.textureUnit ?? 0) + i;
224
+ gl.activeTexture(gl.TEXTURE0 + unit);
225
+ gl.bindTexture(target, textureOf(texture) ?? null);
226
+ units.push(unit);
227
+ });
228
+ gl.uniform1iv(location, units);
229
+ return;
230
+ }
231
+ const data = typeof value === "number" ? [value] : typeof value === "boolean" ? [value ? 1 : 0] : value;
232
+ const f = data instanceof Float32Array ? data : new Float32Array(data);
233
+ switch (type) {
234
+ case gl.FLOAT:
235
+ gl.uniform1fv(location, f);
236
+ break;
237
+ case gl.FLOAT_VEC2:
238
+ gl.uniform2fv(location, f);
239
+ break;
240
+ case gl.FLOAT_VEC3:
241
+ gl.uniform3fv(location, f);
242
+ break;
243
+ case gl.FLOAT_VEC4:
244
+ gl.uniform4fv(location, f);
245
+ break;
246
+ case gl.INT:
247
+ case gl.BOOL:
248
+ gl.uniform1iv(location, Int32Array.from(data));
249
+ break;
250
+ case gl.INT_VEC2:
251
+ case gl.BOOL_VEC2:
252
+ gl.uniform2iv(location, Int32Array.from(data));
253
+ break;
254
+ case gl.INT_VEC3:
255
+ case gl.BOOL_VEC3:
256
+ gl.uniform3iv(location, Int32Array.from(data));
257
+ break;
258
+ case gl.INT_VEC4:
259
+ case gl.BOOL_VEC4:
260
+ gl.uniform4iv(location, Int32Array.from(data));
261
+ break;
262
+ case gl.UNSIGNED_INT:
263
+ gl.uniform1uiv(location, Uint32Array.from(data));
264
+ break;
265
+ case gl.UNSIGNED_INT_VEC2:
266
+ gl.uniform2uiv(location, Uint32Array.from(data));
267
+ break;
268
+ case gl.UNSIGNED_INT_VEC3:
269
+ gl.uniform3uiv(location, Uint32Array.from(data));
270
+ break;
271
+ case gl.UNSIGNED_INT_VEC4:
272
+ gl.uniform4uiv(location, Uint32Array.from(data));
273
+ break;
274
+ case gl.FLOAT_MAT2:
275
+ gl.uniformMatrix2fv(location, false, f);
276
+ break;
277
+ case gl.FLOAT_MAT3:
278
+ gl.uniformMatrix3fv(location, false, f);
279
+ break;
280
+ case gl.FLOAT_MAT4:
281
+ gl.uniformMatrix4fv(location, false, f);
282
+ break;
283
+ case gl.FLOAT_MAT2x3:
284
+ gl.uniformMatrix2x3fv(location, false, f);
285
+ break;
286
+ case gl.FLOAT_MAT2x4:
287
+ gl.uniformMatrix2x4fv(location, false, f);
288
+ break;
289
+ case gl.FLOAT_MAT3x2:
290
+ gl.uniformMatrix3x2fv(location, false, f);
291
+ break;
292
+ case gl.FLOAT_MAT3x4:
293
+ gl.uniformMatrix3x4fv(location, false, f);
294
+ break;
295
+ case gl.FLOAT_MAT4x2:
296
+ gl.uniformMatrix4x2fv(location, false, f);
297
+ break;
298
+ case gl.FLOAT_MAT4x3:
299
+ gl.uniformMatrix4x3fv(location, false, f);
300
+ break;
301
+ default: throw new Error(`SetUniforms: unsupported uniform type 0x${type.toString(16)}`);
302
+ }
303
+ }
304
+ /**
305
+ * Creates a buffer from data (a plain number array becomes a Float32Array) or with a byte size
306
+ * to fill later with UpdateBuffer.
307
+ *
308
+ * @category WebGL
309
+ */
310
+ function CreateBuffer(gl, data, options = {}) {
311
+ const target = options.target ?? gl.ARRAY_BUFFER;
312
+ const usage = options.usage ?? gl.STATIC_DRAW;
313
+ const buffer = gl.createBuffer();
314
+ if (!buffer) throw new Error("CreateBuffer: could not create a buffer (context lost?)");
315
+ gl.bindBuffer(target, buffer);
316
+ if (typeof data === "number") gl.bufferData(target, data, usage);
317
+ else gl.bufferData(target, Array.isArray(data) ? new Float32Array(data) : data, usage);
318
+ gl.bindBuffer(target, null);
319
+ return buffer;
320
+ }
321
+ /**
322
+ * Writes data into an existing buffer, starting at `byteOffset`.
323
+ *
324
+ * @category WebGL
325
+ */
326
+ function UpdateBuffer(gl, buffer, data, byteOffset = 0, target) {
327
+ const t = target ?? gl.ARRAY_BUFFER;
328
+ gl.bindBuffer(t, buffer);
329
+ gl.bufferSubData(t, byteOffset, Array.isArray(data) ? new Float32Array(data) : data);
330
+ gl.bindBuffer(t, null);
331
+ }
332
+ const BYTES = {
333
+ 5120: 1,
334
+ 5121: 1,
335
+ 5122: 2,
336
+ 5123: 2,
337
+ 5124: 4,
338
+ 5125: 4,
339
+ 5126: 4,
340
+ 5131: 2
341
+ };
342
+ function matrixColumns(gl, type) {
343
+ switch (type) {
344
+ case gl.FLOAT_MAT2:
345
+ case gl.FLOAT_MAT2x3:
346
+ case gl.FLOAT_MAT2x4: return 2;
347
+ case gl.FLOAT_MAT3:
348
+ case gl.FLOAT_MAT3x2:
349
+ case gl.FLOAT_MAT3x4: return 3;
350
+ case gl.FLOAT_MAT4:
351
+ case gl.FLOAT_MAT4x2:
352
+ case gl.FLOAT_MAT4x3: return 4;
353
+ }
354
+ return 1;
355
+ }
356
+ function isIntegerAttribute(gl, type) {
357
+ switch (type) {
358
+ case gl.INT:
359
+ case gl.INT_VEC2:
360
+ case gl.INT_VEC3:
361
+ case gl.INT_VEC4:
362
+ case gl.UNSIGNED_INT:
363
+ case gl.UNSIGNED_INT_VEC2:
364
+ case gl.UNSIGNED_INT_VEC3:
365
+ case gl.UNSIGNED_INT_VEC4: return true;
366
+ }
367
+ return false;
368
+ }
369
+ /**
370
+ * Records how the program's attributes read from buffers (and the index buffer) into a vertex
371
+ * array object. Integer attributes (int / uint / ivec / uvec) use vertexAttribIPointer
372
+ * automatically; matrix attributes (e.g. per-instance mat4) are spread over their columns.
373
+ * Attributes the program doesn't use are skipped.
374
+ *
375
+ * @param indices an index array (Uint16Array / Uint32Array / Uint8Array), or an existing buffer and its type
376
+ *
377
+ * @category WebGL
378
+ */
379
+ function CreateVertexArray(gl, info, attributes, indices) {
380
+ const vao = gl.createVertexArray();
381
+ if (!vao) throw new Error("CreateVertexArray: could not create a vertex array (context lost?)");
382
+ const result = {
383
+ vao,
384
+ buffers: []
385
+ };
386
+ let vertexCount = Infinity;
387
+ gl.bindVertexArray(vao);
388
+ for (const name in attributes) {
389
+ const attribute = info.attributes[name];
390
+ if (!attribute) continue;
391
+ const source = attributes[name];
392
+ const type = source.type ?? gl.FLOAT;
393
+ const columns = matrixColumns(gl, attribute.type);
394
+ const columnBytes = source.size * (BYTES[type] ?? 4);
395
+ const stride = source.stride ?? (columns > 1 ? columnBytes * columns : 0);
396
+ gl.bindBuffer(gl.ARRAY_BUFFER, source.buffer);
397
+ if (!result.buffers.includes(source.buffer)) result.buffers.push(source.buffer);
398
+ if (!source.divisor) {
399
+ const bytes = gl.getBufferParameter(gl.ARRAY_BUFFER, gl.BUFFER_SIZE);
400
+ const vertexBytes = columnBytes * columns;
401
+ const available = bytes - (source.offset ?? 0) - vertexBytes;
402
+ vertexCount = Math.min(vertexCount, available < 0 ? 0 : Math.floor(available / (stride || vertexBytes)) + 1);
403
+ }
404
+ for (let column = 0; column < columns; column++) {
405
+ const location = attribute.location + column;
406
+ const offset = (source.offset ?? 0) + column * columnBytes;
407
+ gl.enableVertexAttribArray(location);
408
+ if (isIntegerAttribute(gl, attribute.type)) gl.vertexAttribIPointer(location, source.size, type, stride, offset);
409
+ else gl.vertexAttribPointer(location, source.size, type, source.normalized ?? false, stride, offset);
410
+ if (source.divisor) gl.vertexAttribDivisor(location, source.divisor);
411
+ }
412
+ }
413
+ if (indices) {
414
+ if (ArrayBuffer.isView(indices)) {
415
+ result.indexBuffer = CreateBuffer(gl, indices, { target: gl.ELEMENT_ARRAY_BUFFER });
416
+ result.indexType = indices instanceof Uint32Array ? gl.UNSIGNED_INT : indices instanceof Uint8Array ? gl.UNSIGNED_BYTE : gl.UNSIGNED_SHORT;
417
+ result.count = indices.length;
418
+ result.buffers.push(result.indexBuffer);
419
+ } else {
420
+ result.indexBuffer = indices.buffer;
421
+ result.indexType = indices.type;
422
+ result.count = indices.count;
423
+ if (!result.buffers.includes(indices.buffer)) result.buffers.push(indices.buffer);
424
+ }
425
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, result.indexBuffer);
426
+ } else if (vertexCount < Infinity) result.count = vertexCount;
427
+ gl.bindVertexArray(null);
428
+ gl.bindBuffer(gl.ARRAY_BUFFER, null);
429
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
430
+ return result;
431
+ }
432
+ /**
433
+ * Deletes the vertex array; with `buffers`, also the buffers it reads from.
434
+ *
435
+ * @category WebGL
436
+ */
437
+ function DeleteVertexArray(gl, info, options = {}) {
438
+ gl.deleteVertexArray(info.vao);
439
+ if (options.buffers) for (const buffer of info.buffers) gl.deleteBuffer(buffer);
440
+ }
441
+ const sourceSize = (source) => {
442
+ const s = source;
443
+ return [s.naturalWidth || s.videoWidth || s.width, s.naturalHeight || s.videoHeight || s.height];
444
+ };
445
+ function uploadTexture(gl, info, source) {
446
+ const o = info.options;
447
+ gl.bindTexture(gl.TEXTURE_2D, info.texture);
448
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, o.flipY ?? false);
449
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, o.premultiplyAlpha ?? false);
450
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
451
+ if (!isImageSource(source)) {
452
+ const data = source;
453
+ info.width = data.width;
454
+ info.height = data.height;
455
+ gl.texImage2D(gl.TEXTURE_2D, 0, o.internalFormat ?? gl.RGBA8, data.width, data.height, 0, o.format ?? gl.RGBA, o.type ?? gl.UNSIGNED_BYTE, data.data ?? null);
456
+ } else {
457
+ [info.width, info.height] = sourceSize(source);
458
+ gl.texImage2D(gl.TEXTURE_2D, 0, o.internalFormat ?? gl.RGBA8, o.format ?? gl.RGBA, o.type ?? gl.UNSIGNED_BYTE, source);
459
+ }
460
+ if (o.mipmaps) gl.generateMipmap(gl.TEXTURE_2D);
461
+ gl.bindTexture(gl.TEXTURE_2D, null);
462
+ }
463
+ function isImageSource(source) {
464
+ for (const name of [
465
+ "HTMLImageElement",
466
+ "HTMLCanvasElement",
467
+ "HTMLVideoElement",
468
+ "ImageBitmap",
469
+ "ImageData",
470
+ "OffscreenCanvas",
471
+ "VideoFrame"
472
+ ]) {
473
+ const type = globalThis[name];
474
+ if (type && source instanceof type) return true;
475
+ }
476
+ return false;
477
+ }
478
+ /**
479
+ * Creates a 2D texture from an image / canvas / video / bitmap, or from raw data.
480
+ *
481
+ * @category WebGL
482
+ */
483
+ function CreateTexture(gl, source, options = {}) {
484
+ const texture = gl.createTexture();
485
+ if (!texture) throw new Error("CreateTexture: could not create a texture (context lost?)");
486
+ const info = {
487
+ texture,
488
+ width: 0,
489
+ height: 0,
490
+ options: { ...options }
491
+ };
492
+ const nearest = options.filter === "nearest";
493
+ const wrap = options.wrap === "repeat" ? gl.REPEAT : options.wrap === "mirror" ? gl.MIRRORED_REPEAT : gl.CLAMP_TO_EDGE;
494
+ const minFilter = options.mipmaps ? nearest ? gl.NEAREST_MIPMAP_NEAREST : gl.LINEAR_MIPMAP_LINEAR : nearest ? gl.NEAREST : gl.LINEAR;
495
+ gl.bindTexture(gl.TEXTURE_2D, texture);
496
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
497
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, nearest ? gl.NEAREST : gl.LINEAR);
498
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap);
499
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);
500
+ uploadTexture(gl, info, source);
501
+ return info;
502
+ }
503
+ /**
504
+ * Re-uploads a texture's contents (the size may change); regenerates mipmaps if it has them.
505
+ *
506
+ * @category WebGL
507
+ */
508
+ function UpdateTexture(gl, info, source) {
509
+ uploadTexture(gl, info, source);
510
+ }
511
+ /**
512
+ * Loads an image from a URL into a texture.
513
+ *
514
+ * @category WebGL
515
+ */
516
+ function LoadWebGlTexture(gl, url, options = {}) {
517
+ const image = new Image();
518
+ image.crossOrigin = "anonymous";
519
+ image.src = url;
520
+ return image.decode().then(() => CreateTexture(gl, image, options));
521
+ }
522
+ /**
523
+ * Deletes the texture.
524
+ *
525
+ * @category WebGL
526
+ */
527
+ function DeleteTexture(gl, info) {
528
+ gl.deleteTexture(info.texture);
529
+ }
530
+ /**
531
+ * An offscreen framebuffer with a color texture (and depth), for render-to-texture and post-processing.
532
+ *
533
+ * @category WebGL
534
+ */
535
+ function CreateRenderTarget(gl, width, height, options = {}) {
536
+ const texture = CreateTexture(gl, {
537
+ width,
538
+ height
539
+ }, options);
540
+ const framebuffer = gl.createFramebuffer();
541
+ if (!framebuffer) throw new Error("CreateRenderTarget: could not create a framebuffer (context lost?)");
542
+ const target = {
543
+ framebuffer,
544
+ texture,
545
+ width,
546
+ height
547
+ };
548
+ const previous = gl.getParameter(gl.FRAMEBUFFER_BINDING);
549
+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
550
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture.texture, 0);
551
+ if (options.depth ?? true) {
552
+ target.depth = gl.createRenderbuffer() ?? void 0;
553
+ gl.bindRenderbuffer(gl.RENDERBUFFER, target.depth ?? null);
554
+ gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH24_STENCIL8, width, height);
555
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, target.depth ?? null);
556
+ gl.bindRenderbuffer(gl.RENDERBUFFER, null);
557
+ }
558
+ const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
559
+ gl.bindFramebuffer(gl.FRAMEBUFFER, previous);
560
+ if (status !== gl.FRAMEBUFFER_COMPLETE) {
561
+ DeleteRenderTarget(gl, target);
562
+ throw new Error(`CreateRenderTarget: framebuffer incomplete (0x${status.toString(16)}); is this format renderable?`);
563
+ }
564
+ return target;
565
+ }
566
+ /**
567
+ * Reallocates the target's color texture (and depth buffer) at a new size, discarding their contents. Does nothing if the size is unchanged.
568
+ *
569
+ * @category WebGL
570
+ */
571
+ function ResizeRenderTarget(gl, target, width, height) {
572
+ if (target.width === width && target.height === height) return;
573
+ target.width = width;
574
+ target.height = height;
575
+ UpdateTexture(gl, target.texture, {
576
+ width,
577
+ height
578
+ });
579
+ if (target.depth) {
580
+ gl.bindRenderbuffer(gl.RENDERBUFFER, target.depth);
581
+ gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH24_STENCIL8, width, height);
582
+ gl.bindRenderbuffer(gl.RENDERBUFFER, null);
583
+ }
584
+ }
585
+ /**
586
+ * Draws into `target` (or the canvas, with null) and sets the viewport to match.
587
+ *
588
+ * @category WebGL
589
+ */
590
+ function BindRenderTarget(gl, target) {
591
+ gl.bindFramebuffer(gl.FRAMEBUFFER, target?.framebuffer ?? null);
592
+ gl.viewport(0, 0, target?.width ?? gl.drawingBufferWidth, target?.height ?? gl.drawingBufferHeight);
593
+ }
594
+ /**
595
+ * Deletes the framebuffer, its color texture and its depth buffer.
596
+ *
597
+ * @category WebGL
598
+ */
599
+ function DeleteRenderTarget(gl, target) {
600
+ gl.deleteFramebuffer(target.framebuffer);
601
+ DeleteTexture(gl, target.texture);
602
+ if (target.depth) gl.deleteRenderbuffer(target.depth);
603
+ }
604
+ /**
605
+ * Draws a vertex array with a program; indexed and instanced draws are picked automatically.
606
+ *
607
+ * @category WebGL
608
+ */
609
+ function Draw(gl, info, vertexArray, options = {}) {
610
+ const mode = options.mode ?? gl.TRIANGLES;
611
+ const count = options.count ?? vertexArray.count;
612
+ const offset = options.offset ?? 0;
613
+ const instances = options.instances ?? 0;
614
+ if (count === void 0) throw new Error("Draw: no count given and the vertex array has none");
615
+ gl.useProgram(info.program);
616
+ if (options.uniforms) SetUniforms(gl, info, options.uniforms);
617
+ gl.bindVertexArray(vertexArray.vao);
618
+ if (vertexArray.indexBuffer !== void 0) {
619
+ const type = vertexArray.indexType ?? gl.UNSIGNED_SHORT;
620
+ const byteOffset = offset * (type === gl.UNSIGNED_INT ? 4 : type === gl.UNSIGNED_BYTE ? 1 : 2);
621
+ if (instances > 0) gl.drawElementsInstanced(mode, count, type, byteOffset, instances);
622
+ else gl.drawElements(mode, count, type, byteOffset);
623
+ } else if (instances > 0) gl.drawArraysInstanced(mode, offset, count, instances);
624
+ else gl.drawArrays(mode, offset, count);
625
+ gl.bindVertexArray(null);
626
+ }
627
+ //#endregion
628
+ export { BindRenderTarget, CompileShader, CreateBuffer, CreateProgram, CreateProgramInfo, CreateRenderTarget, CreateTexture, CreateVertexArray, CreateWebGlContext, DeleteProgramInfo, DeleteRenderTarget, DeleteTexture, DeleteVertexArray, Draw, GetProgramLocations, LoadWebGlTexture, ResizeRenderTarget, ResizeWebGlContext, SetUniforms, ShaderType, UpdateBuffer, UpdateTexture };
@@ -0,0 +1,30 @@
1
+ import { Observable } from "./observable.js";
2
+ //#region src/worker-interface.d.ts
3
+ /**
4
+ * Thin wrapper around a module `Worker` that exposes its errors and messages as
5
+ * {@link Observable}s.
6
+ *
7
+ * ```ts
8
+ * const worker = new WorkerInterface<Result, Job>(new URL('./worker.ts', import.meta.url));
9
+ * worker.onMessage.subscribe((event) => console.log(event.data));
10
+ * worker.postMessage(job);
11
+ * ```
12
+ *
13
+ * @typeParam TReceive data the worker posts back (the type of `onMessage` events' `data`)
14
+ * @typeParam TSend data posted to the worker with `postMessage`
15
+ * @category Utilities
16
+ */
17
+ export declare class WorkerInterface<TReceive = any, TSend = any> {
18
+ private _worker;
19
+ /** notified with the worker's `error` events */
20
+ readonly onError: Observable<ErrorEvent>;
21
+ /** notified with every message the worker posts back */
22
+ readonly onMessage: Observable<MessageEvent<TReceive>>;
23
+ /** Starts a module worker (`{ type: 'module' }`) from `url`. */
24
+ constructor(url: string | URL);
25
+ /** Sends `message` to the worker (structured-cloned; `options.transfer` lists objects to transfer). */
26
+ postMessage(message: TSend, options?: StructuredSerializeOptions | undefined): void;
27
+ /** Stops the worker immediately. */
28
+ terminate(): void;
29
+ }
30
+ //#endregion
@@ -0,0 +1,39 @@
1
+ import { Observable } from "./observable.js";
2
+ //#region src/worker-interface.ts
3
+ /**
4
+ * Thin wrapper around a module `Worker` that exposes its errors and messages as
5
+ * {@link Observable}s.
6
+ *
7
+ * ```ts
8
+ * const worker = new WorkerInterface<Result, Job>(new URL('./worker.ts', import.meta.url));
9
+ * worker.onMessage.subscribe((event) => console.log(event.data));
10
+ * worker.postMessage(job);
11
+ * ```
12
+ *
13
+ * @typeParam TReceive data the worker posts back (the type of `onMessage` events' `data`)
14
+ * @typeParam TSend data posted to the worker with `postMessage`
15
+ * @category Utilities
16
+ */
17
+ var WorkerInterface = class {
18
+ _worker;
19
+ /** notified with the worker's `error` events */
20
+ onError = new Observable();
21
+ /** notified with every message the worker posts back */
22
+ onMessage = new Observable();
23
+ /** Starts a module worker (`{ type: 'module' }`) from `url`. */
24
+ constructor(url) {
25
+ this._worker = new Worker(url, { type: "module" });
26
+ this._worker.onerror = (error) => this.onError.notify(error);
27
+ this._worker.onmessage = (message) => this.onMessage.notify(message);
28
+ }
29
+ /** Sends `message` to the worker (structured-cloned; `options.transfer` lists objects to transfer). */
30
+ postMessage(message, options) {
31
+ this._worker.postMessage(message, options);
32
+ }
33
+ /** Stops the worker immediately. */
34
+ terminate() {
35
+ this._worker.terminate();
36
+ }
37
+ };
38
+ //#endregion
39
+ export { WorkerInterface };