@bigmistqke/view.gl 0.7.0 → 0.8.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.
- package/README.md +27 -0
- package/dist/{chunk-H4K75BIR.mjs → chunk-7Z5UULAB.mjs} +35 -13
- package/dist/chunk-7Z5UULAB.mjs.map +1 -0
- package/dist/{chunk-BZDGEIOT.mjs → chunk-TQWPUDQI.mjs} +57 -13
- package/dist/chunk-TQWPUDQI.mjs.map +1 -0
- package/dist/gl.d.mts +1 -1
- package/dist/gl.mjs +1 -1
- package/dist/index.d.mts +40 -3
- package/dist/index.mjs +13 -3
- package/dist/tag.d.mts +1 -1
- package/dist/tag.mjs +2 -2
- package/dist/{types-Dar3fLfd.d.mts → types-DZbMcty2.d.mts} +25 -0
- package/package.json +2 -2
- package/src/errors.ts +58 -0
- package/src/gl.ts +11 -10
- package/src/index.ts +17 -11
- package/src/utils.ts +3 -2
- package/test/errors.test.ts +189 -0
- package/dist/chunk-BZDGEIOT.mjs.map +0 -1
- package/dist/chunk-H4K75BIR.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -39,6 +39,7 @@
|
|
|
39
39
|
- 🏗️ [createProgram](#️-createprogram)
|
|
40
40
|
- 🖼️ [createTexture](#️-createtexture)
|
|
41
41
|
- 🖥️ [createFramebuffer](#️-createframebuffer)
|
|
42
|
+
- 🚨 [Errors](#-errors)
|
|
42
43
|
- 🔍 [WebGL Type Compatibility](#-webgl-type-compatibility)
|
|
43
44
|
- 🎯 [Uniform Types](#-uniform-types)
|
|
44
45
|
- 📝 [Attribute Types](#-attribute-types)
|
|
@@ -910,6 +911,32 @@ Pass a `texture` to attach one you already have — ping-ponging a pair of
|
|
|
910
911
|
framebuffers over shared textures, say. `dispose()` then deletes the framebuffer
|
|
911
912
|
and leaves that texture alone, because it is not the framebuffer's to delete.
|
|
912
913
|
|
|
914
|
+
## 🚨 Errors
|
|
915
|
+
|
|
916
|
+
Every error view.gl throws for a GL call that failed is a class exported from `@bigmistqke/view.gl`, carrying what the GL answered:
|
|
917
|
+
|
|
918
|
+
| Error | Thrown when | Carries |
|
|
919
|
+
| --- | --- | --- |
|
|
920
|
+
| `ShaderCompileError` | a shader does not compile | `stage`, `infoLog` (`string \| null`, as the driver answered it), `glError` |
|
|
921
|
+
| `ProgramLinkError` | a program does not link | `infoLog` (`string \| null`), `glError` |
|
|
922
|
+
| `GLCreateError` | a `create*` call answers `null` | `resource`: `'shader'`, `'program'`, `'buffer'`, `'vertexArray'`, `'texture'` or `'framebuffer'` |
|
|
923
|
+
| `AttributeNotFoundError` | `getAttribLocation` answers -1 | `attribute` |
|
|
924
|
+
|
|
925
|
+
A lost WebGL context answers every call with a default: `null` from a `create*`, -1 for an attribute, `false` with an empty or `null` log for a compile or link. So an empty `infoLog` or a `GLCreateError` carries no cause, where a non-empty `infoLog` is the driver's own reason.
|
|
926
|
+
|
|
927
|
+
```typescript
|
|
928
|
+
import { createProgram } from '@bigmistqke/view.gl/gl'
|
|
929
|
+
import { ShaderCompileError } from '@bigmistqke/view.gl'
|
|
930
|
+
|
|
931
|
+
try {
|
|
932
|
+
createProgram(gl, vertex, fragment)
|
|
933
|
+
} catch (error) {
|
|
934
|
+
if (error instanceof ShaderCompileError && error.infoLog?.trim()) {
|
|
935
|
+
console.error(`${error.stage} shader rejected:`, error.infoLog)
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
```
|
|
939
|
+
|
|
913
940
|
## 🔍 WebGL Type Compatibility
|
|
914
941
|
|
|
915
942
|
### 🎯 Uniform Types
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
|
+
AttributeNotFoundError,
|
|
2
3
|
assertedNotNullish,
|
|
3
4
|
createUpsertMap,
|
|
5
|
+
created,
|
|
4
6
|
forEachObject,
|
|
5
7
|
getInstancedArrays,
|
|
6
8
|
getVertexArrayObject,
|
|
@@ -10,7 +12,7 @@ import {
|
|
|
10
12
|
kindToUniformFnName,
|
|
11
13
|
mapObject,
|
|
12
14
|
once
|
|
13
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-TQWPUDQI.mjs";
|
|
14
16
|
|
|
15
17
|
// src/index.ts
|
|
16
18
|
var index = 0;
|
|
@@ -72,7 +74,7 @@ function bindDefaultVertexArray(gl) {
|
|
|
72
74
|
return () => {
|
|
73
75
|
};
|
|
74
76
|
}
|
|
75
|
-
const previous = gl
|
|
77
|
+
const previous = readVertexArrayBinding(gl);
|
|
76
78
|
feature.bindVertexArray(null);
|
|
77
79
|
return () => feature.bindVertexArray(previous);
|
|
78
80
|
}
|
|
@@ -89,8 +91,8 @@ function vaoView(gl, participants, { signal } = {}) {
|
|
|
89
91
|
dispose() {
|
|
90
92
|
}
|
|
91
93
|
} : (() => {
|
|
92
|
-
const vertexArray =
|
|
93
|
-
const previous = gl
|
|
94
|
+
const vertexArray = created(feature.createVertexArray(), "vertexArray");
|
|
95
|
+
const previous = readVertexArrayBinding(gl);
|
|
94
96
|
feature.bindVertexArray(vertexArray);
|
|
95
97
|
for (const participant of participants) {
|
|
96
98
|
participant.applyToVertexArray();
|
|
@@ -98,9 +100,7 @@ function vaoView(gl, participants, { signal } = {}) {
|
|
|
98
100
|
feature.bindVertexArray(previous);
|
|
99
101
|
return {
|
|
100
102
|
bind() {
|
|
101
|
-
const previousVertexArray = gl
|
|
102
|
-
VERTEX_ARRAY_BINDING
|
|
103
|
-
);
|
|
103
|
+
const previousVertexArray = readVertexArrayBinding(gl);
|
|
104
104
|
feature.bindVertexArray(vertexArray);
|
|
105
105
|
participants.forEach((participant) => participant.applyToContext?.());
|
|
106
106
|
return once(() => feature.bindVertexArray(previousVertexArray));
|
|
@@ -203,6 +203,10 @@ function handleAttribute(gl, location, size, stride, offset, glType, isIntegerKi
|
|
|
203
203
|
}
|
|
204
204
|
var VERTEX_ATTRIB_ARRAY_DIVISOR = 35070;
|
|
205
205
|
var VERTEX_ARRAY_BINDING = 34229;
|
|
206
|
+
function readVertexArrayBinding(gl) {
|
|
207
|
+
const bound = gl.getParameter(VERTEX_ARRAY_BINDING);
|
|
208
|
+
return typeof bound === "object" ? bound : null;
|
|
209
|
+
}
|
|
206
210
|
function readDivisor(gl, location) {
|
|
207
211
|
return getInstancedArrays(gl) ? gl.getVertexAttrib(location, VERTEX_ATTRIB_ARRAY_DIVISOR) : 0;
|
|
208
212
|
}
|
|
@@ -211,10 +215,10 @@ function attributeView(gl, program, schema, { signal } = {}) {
|
|
|
211
215
|
schema,
|
|
212
216
|
({ kind, format, normalized = false, instanced, buffer: providedBuffer }, key) => {
|
|
213
217
|
const name = toID(key);
|
|
214
|
-
const buffer = providedBuffer ??
|
|
218
|
+
const buffer = providedBuffer ?? created(gl.createBuffer(), "buffer");
|
|
215
219
|
const location = gl.getAttribLocation(program, name);
|
|
216
220
|
if (location < 0) {
|
|
217
|
-
throw new
|
|
221
|
+
throw new AttributeNotFoundError(name);
|
|
218
222
|
}
|
|
219
223
|
const size = kindToSize(kind);
|
|
220
224
|
const resolvedFormat = format ?? defaultFormat(kind);
|
|
@@ -248,6 +252,16 @@ function attributeView(gl, program, schema, { signal } = {}) {
|
|
|
248
252
|
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
|
|
249
253
|
gl.bufferData(gl.ARRAY_BUFFER, data, gl[usage]);
|
|
250
254
|
return this;
|
|
255
|
+
},
|
|
256
|
+
allocate(length, usage = "STATIC_DRAW") {
|
|
257
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
|
|
258
|
+
gl.bufferData(gl.ARRAY_BUFFER, length * FORMAT_BYTE_SIZE[resolvedFormat], gl[usage]);
|
|
259
|
+
return this;
|
|
260
|
+
},
|
|
261
|
+
write(data, offset) {
|
|
262
|
+
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
|
|
263
|
+
gl.bufferSubData(gl.ARRAY_BUFFER, offset * FORMAT_BYTE_SIZE[resolvedFormat], data);
|
|
264
|
+
return this;
|
|
251
265
|
}
|
|
252
266
|
};
|
|
253
267
|
}
|
|
@@ -315,7 +329,7 @@ function interleavedAttributeView(gl, program, schema, { signal } = {}) {
|
|
|
315
329
|
const name = toID(layout2.key);
|
|
316
330
|
const location = gl.getAttribLocation(program, name);
|
|
317
331
|
if (location < 0) {
|
|
318
|
-
throw new
|
|
332
|
+
throw new AttributeNotFoundError(name);
|
|
319
333
|
}
|
|
320
334
|
locations.push(location);
|
|
321
335
|
const size = kindToSize(layout2.kind);
|
|
@@ -338,7 +352,7 @@ function interleavedAttributeView(gl, program, schema, { signal } = {}) {
|
|
|
338
352
|
);
|
|
339
353
|
});
|
|
340
354
|
const stride = index2;
|
|
341
|
-
const buffer =
|
|
355
|
+
const buffer = created(gl.createBuffer(), "buffer");
|
|
342
356
|
function applyToVertexArray(divisor) {
|
|
343
357
|
const previousDivisors = locations.map(
|
|
344
358
|
(location) => [location, readDivisor(gl, location)]
|
|
@@ -401,7 +415,7 @@ function interleavedAttributeView(gl, program, schema, { signal } = {}) {
|
|
|
401
415
|
}
|
|
402
416
|
function bufferView(gl, schema, { signal } = {}) {
|
|
403
417
|
const buffers = mapObject(schema, ({ target = "ARRAY_BUFFER", usage = "STATIC_DRAW" }) => {
|
|
404
|
-
const buffer =
|
|
418
|
+
const buffer = created(gl.createBuffer(), "buffer");
|
|
405
419
|
function applyToVertexArray() {
|
|
406
420
|
const previousBuffer = gl.getParameter(gl[`${target}_BINDING`]);
|
|
407
421
|
gl.bindBuffer(gl[target], buffer);
|
|
@@ -423,6 +437,14 @@ function bufferView(gl, schema, { signal } = {}) {
|
|
|
423
437
|
set(data) {
|
|
424
438
|
gl.bindBuffer(gl[target], buffer);
|
|
425
439
|
gl.bufferData(gl[target], data, gl[usage]);
|
|
440
|
+
},
|
|
441
|
+
allocate(byteLength) {
|
|
442
|
+
gl.bindBuffer(gl[target], buffer);
|
|
443
|
+
gl.bufferData(gl[target], byteLength, gl[usage]);
|
|
444
|
+
},
|
|
445
|
+
write(data, byteOffset) {
|
|
446
|
+
gl.bindBuffer(gl[target], buffer);
|
|
447
|
+
gl.bufferSubData(gl[target], byteOffset, data);
|
|
426
448
|
}
|
|
427
449
|
};
|
|
428
450
|
});
|
|
@@ -441,4 +463,4 @@ export {
|
|
|
441
463
|
interleavedAttributeView,
|
|
442
464
|
bufferView
|
|
443
465
|
};
|
|
444
|
-
//# sourceMappingURL=chunk-
|
|
466
|
+
//# sourceMappingURL=chunk-7Z5UULAB.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { AttributeNotFoundError, created } from './errors'\nimport { getInstancedArrays, getVertexArrayObject } from './gl'\nimport type {\n AttributeFormat,\n AttributeKind,\n AttributeMethods,\n AttributeSchema,\n AttributeView,\n BufferSchema,\n BufferView,\n GL,\n UniformView as InferUniformView,\n GLUsage,\n InterleavedAttributeLayout,\n InterleavedAttributeMethods,\n InterleavedAttributeSchema,\n InterleavedAttributeView,\n UniformSchema,\n VertexArrayMethods,\n VertexArrayParticipant,\n View,\n ViewOptions,\n ViewSchema,\n} from './types'\nimport {\n isSamplerKind,\n kindToUniformFnName,\n isMatKind,\n assertedNotNullish,\n kindToSize,\n forEachObject,\n once,\n} from './utils'\nimport { createUpsertMap, mapObject } from './utils'\nexport * from './errors'\nexport * from './types'\n// Documented under Utils but reachable from nowhere until now: utils is not a\n// build entry, and named rather than star so the internal helpers stay internal.\nexport { createFramebuffer, createTexture } from './utils'\n\n/**********************************************************************************/\n/* */\n/* To ID */\n/* */\n/**********************************************************************************/\n\nlet index = 0\nconst PREFIX = 'VIEW_GL_ALIAS'\n// Firefox has currently a bug where it can not handle symbol as WeakRef / key for WeakMap\n// see https://bugzilla.mozilla.org/show_bug.cgi?id=1710433\nconst HAS_WEAK_SYMBOL = (() => {\n try {\n const symbol = Symbol()\n new WeakMap().set(symbol, '')\n return true\n } catch {\n return false\n }\n})()\n// NOTE: fallback to Map will currently cause a minor memory leak.\nconst SYMBOL_MAP = createUpsertMap(HAS_WEAK_SYMBOL ? WeakMap<symbol, string> : Map<symbol, string>)\n\nexport function toID(key: string | number | symbol) {\n if (typeof key === 'string') {\n return key\n }\n if (typeof key === 'symbol') {\n return SYMBOL_MAP.getOrInsert(key, () => `${PREFIX}_${index++}`)\n }\n return key.toString()\n}\n\n/**********************************************************************************/\n/* */\n/* View */\n/* */\n/**********************************************************************************/\n\nexport function view<TSchema extends ViewSchema>(\n gl: GL,\n program: WebGLProgram,\n schema: TSchema,\n { signal }: ViewOptions = {},\n): View<TSchema> {\n // The sub-views are built without the signal and the view wires disposal\n // once, so that `dispose()` and aborting do the same thing rather than each\n // doing half of it.\n const attributes = !schema.attributes ? undefined : attributeView(gl, program, schema.attributes)\n const interleavedAttributes = !schema.interleavedAttributes\n ? undefined\n : interleavedAttributeView(gl, program, schema.interleavedAttributes)\n // Owned by the view, on the view's signal. This is the line the split was\n // really about: it used to read `bufferView(gl, schema.buffers)` with the\n // options dropped, so a view's buffers were the only resources that still\n // needed disposing by hand. That was a missing argument rather than a wrong\n // model — a buffer whose lifetime IS the view's belongs with it.\n const buffers = !schema.buffers ? undefined : bufferView(gl, schema.buffers)\n\n // Vertex arrays are made on demand rather than declared, so they are the one\n // thing the view cannot dispose from the schema alone. Held until disposed —\n // by the view or by the caller — and dropped either way, so a view that hands\n // out an array per frame does not accumulate them.\n const vertexArrays = new Set<VertexArrayMethods>()\n\n const dispose = once(() => {\n if (attributes) forEachObject(attributes, value => value.dispose())\n if (interleavedAttributes) forEachObject(interleavedAttributes, value => value.dispose())\n if (buffers) forEachObject(buffers, value => value.dispose())\n vertexArrays.forEach(vertexArray => vertexArray.dispose())\n vertexArrays.clear()\n })\n\n signal?.addEventListener('abort', dispose)\n\n return {\n uniforms: !schema.uniforms ? undefined : uniformView(gl, program, schema.uniforms),\n attributes,\n interleavedAttributes,\n buffers,\n vao(participants: VertexArrayParticipant[]) {\n const vertexArray = vaoView(gl, participants)\n vertexArrays.add(vertexArray)\n return {\n ...vertexArray,\n dispose: once(() => {\n vertexArrays.delete(vertexArray)\n vertexArray.dispose()\n }),\n }\n },\n dispose,\n } as View<TSchema>\n}\n\n/**********************************************************************************/\n/* */\n/* Vertex Array */\n/* */\n/**********************************************************************************/\n\n/**\n * Bind the default vertex array, returning a disposer that puts the previous\n * one back. The pointer calls name no destination, so anything applied without\n * a vertex array of its own has to say which one it means — and a vertex array\n * keeps what it is given, so writing into a caller's array by accident would\n * outlive the call that did it.\n */\nfunction bindDefaultVertexArray(gl: GL): () => void {\n const feature = getVertexArrayObject(gl)\n if (!feature) {\n return () => {}\n }\n const previous = readVertexArrayBinding(gl)\n feature.bindVertexArray(null)\n return () => feature.bindVertexArray(previous)\n}\n\n/**\n * A vertex array over the participants one draw needs.\n *\n * Where the context has vertex arrays, each participant writes itself in once,\n * here, and `bind()` is a single `bindVertexArray`. Where it does not — WebGL1\n * without `OES_vertex_array_object` — there is nowhere to keep the state, so\n * `bind()` re-applies every participant and the disposer puts back what they\n * displaced. Same contract, and the emulation is why the name still fits.\n */\nexport function vaoView(\n gl: GL,\n participants: VertexArrayParticipant[],\n { signal }: ViewOptions = {},\n): VertexArrayMethods {\n const feature = getVertexArrayObject(gl)\n\n const methods: VertexArrayMethods = !feature\n ? {\n bind() {\n const restores = participants.map(participant => participant.applyToVertexArray())\n participants.forEach(participant => participant.applyToContext?.())\n return once(() => restores.forEach(restore => restore()))\n },\n unbind() {},\n dispose() {},\n }\n : (() => {\n const vertexArray = created(feature.createVertexArray(), 'vertexArray')\n const previous = readVertexArrayBinding(gl)\n feature.bindVertexArray(vertexArray)\n // Discarding the restorers is the point: the state lives in this array\n // now, and the array is thrown away whole.\n for (const participant of participants) {\n participant.applyToVertexArray()\n }\n feature.bindVertexArray(previous)\n\n return {\n bind() {\n const previousVertexArray = readVertexArrayBinding(gl)\n feature.bindVertexArray(vertexArray)\n // Context state the array cannot hold — see applyToContext.\n participants.forEach(participant => participant.applyToContext?.())\n return once(() => feature.bindVertexArray(previousVertexArray))\n },\n unbind() {\n feature.bindVertexArray(null)\n },\n dispose: once(() => feature.deleteVertexArray(vertexArray)),\n }\n })()\n\n signal?.addEventListener('abort', () => methods.dispose())\n\n return methods\n}\n\n/**********************************************************************************/\n/* */\n/* Uniform View */\n/* */\n/**********************************************************************************/\n\nexport function uniformView<T extends UniformSchema>(\n gl: GL,\n program: WebGLProgram,\n schema: T,\n): InferUniformView<T> {\n // @ts-expect-error - conditional return type based on size is hard to infer\n return mapObject(schema, ({ kind, size }, key) => {\n const name = toID(key)\n\n if (isSamplerKind(kind)) {\n const location = gl.getUniformLocation(program, name)\n return {\n set(arg: number) {\n gl.uniform1i(location, arg)\n },\n }\n }\n\n // Array uniform - support both bulk set and indexed access\n if (size) {\n const bulkFnName = `uniform${kindToUniformFnName(kind)}v`\n // @ts-ignore FIX WEBGL/WEBGL2 TYPES\n const bulkFn = gl[bulkFnName].bind(gl)\n const bulkLocation = gl.getUniformLocation(program, name)\n\n const elementFnName = `uniform${kindToUniformFnName(kind)}`\n // @ts-ignore FIX WEBGL/WEBGL2 TYPES\n const elementFn = gl[elementFnName].bind(gl)\n\n // Build array of element setters\n const elements: Array<{ set(...args: any[]): void }> = []\n for (let i = 0; i < size; i++) {\n const location = gl.getUniformLocation(program, `${name}[${i}]`)\n elements[i] = {\n set(...args: any[]) {\n elementFn(location, ...args)\n },\n }\n }\n\n // Return array-like object with bulk set\n return Object.assign(elements, {\n set(arg: Float32Array) {\n bulkFn(bulkLocation, arg)\n },\n })\n }\n\n // Non-array uniform\n const location = gl.getUniformLocation(program, name)\n const fnName = `uniform${kindToUniformFnName(kind)}`\n\n // @ts-ignore FIX WEBGL/WEBGL2 TYPES\n const fn = gl[fnName].bind(gl)\n\n if (isMatKind(kind)) {\n return {\n set(...args: any[]) {\n fn(location, false, args[0])\n },\n }\n }\n\n return {\n set(...args: any[]) {\n fn(location, ...args)\n },\n }\n })\n}\n\n/**********************************************************************************/\n/* */\n/* Attribute View */\n/* */\n/**********************************************************************************/\n\ntype GLType =\n | 'FLOAT'\n | 'INT'\n | 'UNSIGNED_INT'\n | 'SHORT'\n | 'UNSIGNED_SHORT'\n | 'BYTE'\n | 'UNSIGNED_BYTE'\n\nconst FORMAT_TO_GL_TYPE: Record<AttributeFormat, GLType> = {\n float32: 'FLOAT',\n int32: 'INT',\n uint32: 'UNSIGNED_INT',\n int16: 'SHORT',\n uint16: 'UNSIGNED_SHORT',\n int8: 'BYTE',\n uint8: 'UNSIGNED_BYTE',\n}\n\nconst FORMAT_BYTE_SIZE: Record<AttributeFormat, number> = {\n float32: 4,\n int32: 4,\n uint32: 4,\n int16: 2,\n uint16: 2,\n int8: 1,\n uint8: 1,\n}\n\nfunction defaultFormat(kind: AttributeKind): AttributeFormat {\n if (kind.startsWith('u')) return 'uint32'\n if (kind.startsWith('i')) return 'int32'\n return 'float32'\n}\n\n// Shared attribute helper functions\n// between attributeView and interleavedAttributeView\nfunction handleAttribute(\n gl: GL,\n location: number,\n size: number,\n stride: number,\n offset: number,\n glType: GLType,\n isIntegerKind: boolean,\n normalized: boolean,\n instanced?: boolean,\n) {\n gl.enableVertexAttribArray(location)\n if (isIntegerKind) {\n ;(gl as WebGL2RenderingContext).vertexAttribIPointer(location, size, gl[glType], stride, offset)\n } else {\n gl.vertexAttribPointer(location, size, gl[glType], normalized, stride, offset)\n }\n\n // Always stated, never inherited: the divisor belongs to the location rather\n // than to the program, so a location left at 1 by an earlier instanced\n // attribute would feed one value to every vertex here.\n // Get instanced-arrays-feature: extension if webgl, gl if webgl2\n const instancedArrays = getInstancedArrays(gl)\n if (instanced) {\n assertedNotNullish(instancedArrays).vertexAttribDivisor(location, 1)\n } else if (instancedArrays) {\n instancedArrays.vertexAttribDivisor(location, 0)\n }\n}\n\n// Same enum in webgl2 and in the webgl1 extensions, which expose no constants\nconst VERTEX_ATTRIB_ARRAY_DIVISOR = 0x88fe\nconst VERTEX_ARRAY_BINDING = 0x85b5\n\n// Anything but an array or null would make the restore throw a TypeError.\nfunction readVertexArrayBinding(gl: GL): WebGLVertexArrayObject | null {\n const bound: unknown = gl.getParameter(VERTEX_ARRAY_BINDING)\n return typeof bound === 'object' ? (bound as WebGLVertexArrayObject | null) : null\n}\n\n// Reads the divisor currently attached to a location, 0 where instancing is\n// unavailable and nothing can have set one\nfunction readDivisor(gl: GL, location: number): number {\n return getInstancedArrays(gl)\n ? (gl.getVertexAttrib(location, VERTEX_ATTRIB_ARRAY_DIVISOR) as number)\n : 0\n}\n\nexport function attributeView<T extends AttributeSchema>(\n gl: GL,\n program: WebGLProgram,\n schema: T,\n { signal }: ViewOptions = {},\n): AttributeView<T> {\n const attributes = mapObject(\n schema,\n (\n { kind, format, normalized = false, instanced, buffer: providedBuffer },\n key,\n ): AttributeMethods => {\n const name = toID(key)\n\n // Whoever made the buffer deletes it. A schema can name a buffer that\n // belongs to another view — the quad `compile.toQuad` shares across every\n // program on a context, an attribute two programs step over — and\n // deleting one of those would take it out from under its owner.\n const buffer = providedBuffer ?? created(gl.createBuffer(), 'buffer')\n\n const location = gl.getAttribLocation(program, name)\n if (location < 0) {\n throw new AttributeNotFoundError(name)\n }\n\n const size = kindToSize(kind)\n const resolvedFormat = format ?? defaultFormat(kind)\n const glType = FORMAT_TO_GL_TYPE[resolvedFormat]\n const isIntKind = kind.startsWith('i') || kind.startsWith('u')\n\n function applyToVertexArray() {\n // Snapshot before the change, restore in the disposer\n const previousDivisor = readDivisor(gl, location)\n // vertexAttribPointer captures whatever is bound to ARRAY_BUFFER when\n // it runs, so this binding is the setup for the pointer, not a lasting\n // part of the vertex array's state.\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n handleAttribute(gl, location, size, 0, 0, glType, isIntKind, normalized, instanced)\n return once(() => {\n getInstancedArrays(gl)?.vertexAttribDivisor(location, previousDivisor)\n })\n }\n\n return {\n buffer,\n applyToVertexArray,\n bind() {\n const restoreVertexArray = bindDefaultVertexArray(gl)\n const restore = applyToVertexArray()\n return once(() => {\n restore()\n restoreVertexArray()\n })\n },\n dispose: once(() => {\n if (!providedBuffer) {\n gl.deleteBuffer(buffer)\n }\n }),\n set(data, usage = 'STATIC_DRAW') {\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n gl.bufferData(gl.ARRAY_BUFFER, data, gl[usage])\n return this\n },\n allocate(length, usage = 'STATIC_DRAW') {\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n gl.bufferData(gl.ARRAY_BUFFER, length * FORMAT_BYTE_SIZE[resolvedFormat], gl[usage])\n return this\n },\n write(data, offset) {\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n gl.bufferSubData(gl.ARRAY_BUFFER, offset * FORMAT_BYTE_SIZE[resolvedFormat], data)\n return this\n },\n }\n },\n )\n\n signal?.addEventListener('abort', function dispose() {\n forEachObject(attributes, value => value.dispose())\n })\n\n return attributes\n}\n\n/**********************************************************************************/\n/* */\n/* Interleaved Attribute View */\n/* */\n/**********************************************************************************/\n\n/**\n * The other place an attribute's value can come from: not a buffer, but the\n * context's current generic vertex attribute values, which an attribute reads\n * for every vertex when its array is disabled.\n *\n * A constant is a uniform in all but name — one value for the whole draw, set\n * by a function chosen from the kind — so it gets the setters a uniform gets,\n * off the same layout the buffer source uses.\n *\n * `vertexAttrib*` tops out at four floats and has no matrix form, so a layout\n * key that is fine in a buffer can be impossible as a constant. That is a hard\n * limit of the API rather than a choice, and it is worth saying so out loud at\n * the point someone reaches for it.\n */\nfunction constantSource(gl: GL, layout: InterleavedAttributeLayout[], locations: number[]) {\n const setters = layout.map((entry, index) => {\n const size = kindToSize(entry.kind)\n const name = toID(entry.key)\n if (isMatKind(entry.kind) || size > 4) {\n throw new Error(\n `'${name}' is a ${entry.kind}, which cannot be a constant attribute: vertexAttrib* takes at most 4 floats and has no matrix form. Use the buffer source for it.`,\n )\n }\n // The values are context state, not vertex-array state, so they are held\n // here and written again on every bind — see applyToContext.\n let values: number[] = []\n const fn = gl[`vertexAttrib${size as 1 | 2 | 3 | 4}f`].bind(gl)\n return {\n name,\n location: locations[index]!,\n write: () => {\n if (values.length) {\n ;(fn as (location: number, ...args: number[]) => void)(locations[index]!, ...values)\n }\n },\n methods: {\n set(...args: number[]) {\n values = args\n },\n },\n }\n })\n\n return Object.assign(Object.fromEntries(setters.map(setter => [setter.name, setter.methods])), {\n applyToVertexArray() {\n const restores = setters.map(({ location }) => {\n const wasEnabled = gl.getVertexAttrib(location, gl.VERTEX_ATTRIB_ARRAY_ENABLED) as boolean\n gl.disableVertexAttribArray(location)\n return () => (wasEnabled ? gl.enableVertexAttribArray(location) : undefined)\n })\n return once(() => restores.forEach(restore => restore()))\n },\n applyToContext() {\n setters.forEach(setter => setter.write())\n },\n bind() {\n const restoreVertexArray = bindDefaultVertexArray(gl)\n const restore = this.applyToVertexArray()\n this.applyToContext()\n return once(() => {\n restore()\n restoreVertexArray()\n })\n },\n })\n}\n\nexport function interleavedAttributeView<T extends InterleavedAttributeSchema>(\n gl: GL,\n program: WebGLProgram,\n schema: T,\n { signal }: ViewOptions = {},\n): InterleavedAttributeView<T> {\n // Initialize interleaved attributes\n const interleavedAttributes = mapObject(schema, ({ layout }) => {\n // Increment number to keep track of offset\n let index = 0\n\n // Calculate layout information\n const locations: number[] = []\n const handles = layout.map(layout => {\n const name = toID(layout.key)\n\n const location = gl.getAttribLocation(program, name)\n\n if (location < 0) {\n throw new AttributeNotFoundError(name)\n }\n\n locations.push(location)\n\n const size = kindToSize(layout.kind)\n const offset = index\n const resolvedFormat = layout.format ?? defaultFormat(layout.kind)\n const glType = FORMAT_TO_GL_TYPE[resolvedFormat]\n const isIntKind = layout.kind.startsWith('i') || layout.kind.startsWith('u')\n const normalized = layout.normalized ?? false\n index += size * FORMAT_BYTE_SIZE[resolvedFormat]\n\n return (divisor: 0 | 1) =>\n handleAttribute(\n gl,\n location,\n size,\n stride,\n offset,\n glType,\n isIntKind,\n normalized,\n divisor === 1,\n )\n })\n\n // Set stride to final index\n const stride = index\n\n // Create a buffer\n const buffer = created(gl.createBuffer(), 'buffer')\n\n // This layout used to create a vertex array of its own, here, which is why\n // the other participants in a draw had to be bound after it to be included\n // — the array they landed in was whichever one happened to be current.\n // Arrays are `vao()`'s job now; a layout is a layout and a buffer.\n function applyToVertexArray(divisor: 0 | 1) {\n const previousDivisors = locations.map(\n location => [location, readDivisor(gl, location)] as const,\n )\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n for (const handle of handles) {\n handle(divisor)\n }\n return once(() => {\n const instancedArrays = getInstancedArrays(gl)\n previousDivisors.forEach(([location, previous]) => {\n instancedArrays?.vertexAttribDivisor(location, previous)\n })\n })\n }\n\n let constant: ReturnType<typeof constantSource> | undefined\n\n /** One layout, one buffer, but a divisor per draw rather than per schema. */\n function bufferSource(divisor: 0 | 1) {\n const apply = () => applyToVertexArray(divisor)\n return {\n applyToVertexArray: apply,\n bind() {\n const restoreVertexArray = bindDefaultVertexArray(gl)\n const restore = apply()\n return once(() => {\n restore()\n restoreVertexArray()\n })\n },\n }\n }\n\n return {\n buffer: Object.assign(bufferSource(0), {\n /** The same buffer, stepped once per instance instead of once per vertex. */\n perInstance: bufferSource(1),\n set(value: Float32Array, usage: GLUsage = 'STATIC_DRAW') {\n // Uploading is storage, not binding: ARRAY_BUFFER is not vertex-array\n // state, so this touches no array, whichever one is bound.\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n gl.bufferData(gl.ARRAY_BUFFER, value, gl[usage])\n },\n allocate(length: number, usage: GLUsage = 'STATIC_DRAW') {\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n gl.bufferData(gl.ARRAY_BUFFER, length * Float32Array.BYTES_PER_ELEMENT, gl[usage])\n },\n write(data: Float32Array, offset: number) {\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n gl.bufferSubData(gl.ARRAY_BUFFER, offset * Float32Array.BYTES_PER_ELEMENT, data)\n },\n }),\n // Lazy: a layout key can be perfectly good in a buffer and impossible as\n // a constant, and finding that out should wait until someone asks for one.\n get constant() {\n return (constant ??= constantSource(gl, layout, locations))\n },\n dispose: once(() => gl.deleteBuffer(buffer)),\n } satisfies InterleavedAttributeMethods\n })\n\n signal?.addEventListener('abort', function dispose() {\n forEachObject(interleavedAttributes, value => value.dispose())\n })\n\n return interleavedAttributes\n}\n\n/**********************************************************************************/\n/* */\n/* Buffer View */\n/* */\n/**********************************************************************************/\n\nexport function bufferView<T extends BufferSchema>(\n gl: GL,\n schema: T,\n { signal }: ViewOptions = {},\n): BufferView<T> {\n // Initialize buffers\n const buffers = mapObject(schema, ({ target = 'ARRAY_BUFFER', usage = 'STATIC_DRAW' }) => {\n const buffer = created(gl.createBuffer(), 'buffer')\n\n function applyToVertexArray() {\n // Snapshot before the change, restore in the disposer. Restoring the\n // previous buffer rather than null matters for ELEMENT_ARRAY_BUFFER,\n // whose binding is recorded in the bound vertex array: clearing it\n // would strip the index buffer from an array the caller may not own.\n const previousBuffer = gl.getParameter(gl[`${target}_BINDING`]) as WebGLBuffer | null\n gl.bindBuffer(gl[target], buffer)\n return once(() => {\n gl.bindBuffer(gl[target], previousBuffer)\n })\n }\n\n return {\n applyToVertexArray,\n bind() {\n // ELEMENT_ARRAY_BUFFER's binding belongs to the bound vertex array, so\n // like the attributes this has to say which array it means. ARRAY_BUFFER\n // is context state and unaffected either way.\n const restoreVertexArray = bindDefaultVertexArray(gl)\n const restore = applyToVertexArray()\n return once(() => {\n restore()\n restoreVertexArray()\n })\n },\n dispose: once(() => gl.deleteBuffer(buffer)),\n set(data: Float32Array) {\n gl.bindBuffer(gl[target], buffer)\n gl.bufferData(gl[target], data, gl[usage])\n },\n allocate(byteLength: number) {\n gl.bindBuffer(gl[target], buffer)\n gl.bufferData(gl[target], byteLength, gl[usage])\n },\n write(data: Float32Array | Uint16Array | Uint32Array, byteOffset: number) {\n gl.bindBuffer(gl[target], buffer)\n gl.bufferSubData(gl[target], byteOffset, data)\n },\n }\n })\n\n signal?.addEventListener('abort', function dispose() {\n forEachObject(buffers, value => value.dispose())\n })\n\n return buffers\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8C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,MAAM;AAChB,WAAG,WAAW,GAAG,MAAM,GAAG,cAAc;AAAA,MAC1C,CAAC;AAAA,IACH;AAEA,WAAO;AAAA,MACL;AAAA,MACA,OAAO;AAIL,cAAM,qBAAqB,uBAAuB,EAAE;AACpD,cAAM,UAAU,mBAAmB;AACnC,eAAO,KAAK,MAAM;AAChB,kBAAQ;AACR,6BAAmB;AAAA,QACrB,CAAC;AAAA,MACH;AAAA,MACA,SAAS,KAAK,MAAM,GAAG,aAAa,MAAM,CAAC;AAAA,MAC3C,IAAI,MAAoB;AACtB,WAAG,WAAW,GAAG,MAAM,GAAG,MAAM;AAChC,WAAG,WAAW,GAAG,MAAM,GAAG,MAAM,GAAG,KAAK,CAAC;AAAA,MAC3C;AAAA,MACA,SAAS,YAAoB;AAC3B,WAAG,WAAW,GAAG,MAAM,GAAG,MAAM;AAChC,WAAG,WAAW,GAAG,MAAM,GAAG,YAAY,GAAG,KAAK,CAAC;AAAA,MACjD;AAAA,MACA,MAAM,MAAgD,YAAoB;AACxE,WAAG,WAAW,GAAG,MAAM,GAAG,MAAM;AAChC,WAAG,cAAc,GAAG,MAAM,GAAG,YAAY,IAAI;AAAA,MAC/C;AAAA,IACF;AAAA,EACF,CAAC;AAED,UAAQ,iBAAiB,SAAS,SAAS,UAAU;AACnD,kBAAc,SAAS,WAAS,MAAM,QAAQ,CAAC;AAAA,EACjD,CAAC;AAED,SAAO;AACT;","names":["location","index","layout"]}
|
|
@@ -1,3 +1,42 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var ShaderCompileError = class extends Error {
|
|
3
|
+
constructor(stage, infoLog, glError) {
|
|
4
|
+
super(`Failed to compile ${stage} shader: ${infoLog}`);
|
|
5
|
+
this.stage = stage;
|
|
6
|
+
this.infoLog = infoLog;
|
|
7
|
+
this.glError = glError;
|
|
8
|
+
}
|
|
9
|
+
name = "ShaderCompileError";
|
|
10
|
+
};
|
|
11
|
+
var ProgramLinkError = class extends Error {
|
|
12
|
+
constructor(infoLog, glError) {
|
|
13
|
+
super(`Failed to link program: ${infoLog}`);
|
|
14
|
+
this.infoLog = infoLog;
|
|
15
|
+
this.glError = glError;
|
|
16
|
+
}
|
|
17
|
+
name = "ProgramLinkError";
|
|
18
|
+
};
|
|
19
|
+
var GLCreateError = class extends Error {
|
|
20
|
+
constructor(resource) {
|
|
21
|
+
super(`Failed to create ${resource}`);
|
|
22
|
+
this.resource = resource;
|
|
23
|
+
}
|
|
24
|
+
name = "GLCreateError";
|
|
25
|
+
};
|
|
26
|
+
var AttributeNotFoundError = class extends Error {
|
|
27
|
+
constructor(attribute) {
|
|
28
|
+
super(`Attribute '${attribute}' not found`);
|
|
29
|
+
this.attribute = attribute;
|
|
30
|
+
}
|
|
31
|
+
name = "AttributeNotFoundError";
|
|
32
|
+
};
|
|
33
|
+
function created(value, resource) {
|
|
34
|
+
if (value === null) {
|
|
35
|
+
throw new GLCreateError(resource);
|
|
36
|
+
}
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
|
|
1
40
|
// src/utils.ts
|
|
2
41
|
function assertedNotNullish(value, message) {
|
|
3
42
|
if (value === void 0 || value === null) throw new Error(message);
|
|
@@ -67,7 +106,7 @@ function createTexture(gl, {
|
|
|
67
106
|
width,
|
|
68
107
|
height
|
|
69
108
|
}, data, { signal } = {}) {
|
|
70
|
-
const texture =
|
|
109
|
+
const texture = created(gl.createTexture(), "texture");
|
|
71
110
|
function getTextureConstant(name) {
|
|
72
111
|
if (!(name in gl)) {
|
|
73
112
|
throw new Error(`Attempted to create webgl2-only texture (${name}) in webgl1`);
|
|
@@ -126,7 +165,7 @@ var FramebufferError = class extends Error {
|
|
|
126
165
|
};
|
|
127
166
|
function createFramebuffer(gl, { attachment, texture: providedTexture, ...definition }, { signal } = {}) {
|
|
128
167
|
const texture = providedTexture ?? createTexture(gl, definition);
|
|
129
|
-
const framebuffer =
|
|
168
|
+
const framebuffer = created(gl.createFramebuffer(), "framebuffer");
|
|
130
169
|
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
|
|
131
170
|
gl.framebufferTexture2D(
|
|
132
171
|
gl.FRAMEBUFFER,
|
|
@@ -191,33 +230,33 @@ function isWebGL2RenderingContext(gl) {
|
|
|
191
230
|
return typeof WebGL2RenderingContext !== "undefined" && gl instanceof WebGL2RenderingContext;
|
|
192
231
|
}
|
|
193
232
|
function createShader(gl, type, source) {
|
|
194
|
-
const shader = gl.createShader(type);
|
|
195
|
-
if (!shader) throw new Error("Failed to create shader");
|
|
233
|
+
const shader = created(gl.createShader(type), "shader");
|
|
196
234
|
gl.shaderSource(shader, source);
|
|
197
235
|
gl.compileShader(shader);
|
|
198
236
|
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
237
|
+
const error = new ShaderCompileError(
|
|
238
|
+
type === gl.VERTEX_SHADER ? "vertex" : "fragment",
|
|
239
|
+
gl.getShaderInfoLog(shader),
|
|
240
|
+
gl.getError()
|
|
203
241
|
);
|
|
242
|
+
gl.deleteShader(shader);
|
|
243
|
+
throw error;
|
|
204
244
|
}
|
|
205
245
|
return shader;
|
|
206
246
|
}
|
|
207
247
|
function createProgram(gl, vertexSource, fragmentSource, { signal } = {}) {
|
|
208
|
-
const program = gl.createProgram();
|
|
209
|
-
if (!program) throw new Error("Failed to create WebGL program");
|
|
248
|
+
const program = created(gl.createProgram(), "program");
|
|
210
249
|
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexSource);
|
|
211
250
|
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentSource);
|
|
212
251
|
gl.attachShader(program, vertexShader);
|
|
213
252
|
gl.attachShader(program, fragmentShader);
|
|
214
253
|
gl.linkProgram(program);
|
|
215
254
|
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
|
|
216
|
-
const
|
|
255
|
+
const error = new ProgramLinkError(gl.getProgramInfoLog(program), gl.getError());
|
|
217
256
|
gl.deleteProgram(program);
|
|
218
257
|
gl.deleteShader(vertexShader);
|
|
219
258
|
gl.deleteShader(fragmentShader);
|
|
220
|
-
throw
|
|
259
|
+
throw error;
|
|
221
260
|
}
|
|
222
261
|
gl.deleteShader(vertexShader);
|
|
223
262
|
gl.deleteShader(fragmentShader);
|
|
@@ -259,6 +298,11 @@ function getVertexArrayObject(gl) {
|
|
|
259
298
|
}
|
|
260
299
|
|
|
261
300
|
export {
|
|
301
|
+
ShaderCompileError,
|
|
302
|
+
ProgramLinkError,
|
|
303
|
+
GLCreateError,
|
|
304
|
+
AttributeNotFoundError,
|
|
305
|
+
created,
|
|
262
306
|
assertedNotNullish,
|
|
263
307
|
once,
|
|
264
308
|
kindToUniformFnName,
|
|
@@ -275,4 +319,4 @@ export {
|
|
|
275
319
|
getInstancedArrays,
|
|
276
320
|
getVertexArrayObject
|
|
277
321
|
};
|
|
278
|
-
//# sourceMappingURL=chunk-
|
|
322
|
+
//# sourceMappingURL=chunk-TQWPUDQI.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/utils.ts","../src/gl.ts"],"sourcesContent":["/**\n * A shader that did not compile. `infoLog` is what the driver answered, `null`\n * and `''` kept apart; `glError` is `getError()` read at the failure.\n */\nexport class ShaderCompileError extends Error {\n override name = 'ShaderCompileError'\n\n constructor(\n readonly stage: 'vertex' | 'fragment',\n readonly infoLog: string | null,\n readonly glError: number,\n ) {\n super(`Failed to compile ${stage} shader: ${infoLog}`)\n }\n}\n\n/**\n * A program that did not link. `infoLog` is what the driver answered, `null`\n * and `''` kept apart; `glError` is `getError()` read at the failure.\n */\nexport class ProgramLinkError extends Error {\n override name = 'ProgramLinkError'\n\n constructor(\n readonly infoLog: string | null,\n readonly glError: number,\n ) {\n super(`Failed to link program: ${infoLog}`)\n }\n}\n\nexport type GLResource = 'shader' | 'program' | 'buffer' | 'vertexArray' | 'texture' | 'framebuffer'\n\n/** A `create*` call that answered `null`. */\nexport class GLCreateError extends Error {\n override name = 'GLCreateError'\n\n constructor(readonly resource: GLResource) {\n super(`Failed to create ${resource}`)\n }\n}\n\n/** A program with no active attribute of that name: `getAttribLocation` answered -1. */\nexport class AttributeNotFoundError extends Error {\n override name = 'AttributeNotFoundError'\n\n constructor(readonly attribute: string) {\n super(`Attribute '${attribute}' not found`)\n }\n}\n\n/** Throws a {@link GLCreateError} for a `create*` that answered `null`. */\nexport function created<T>(value: T | null, resource: GLResource): T {\n if (value === null) {\n throw new GLCreateError(resource)\n }\n return value\n}\n","import { created } from './errors'\nimport type {\n AttributeKind,\n FramebufferDefinition,\n GL,\n KIND_TO_SIZE_MAP,\n KIND_TO_UNIFORM_FN_NAME_MAP,\n TextureDefinition,\n UniformKind,\n ViewOptions,\n} from './types'\n\nexport function assertedNotNullish<T>(value: T, message?: string): NonNullable<T> {\n if (value === undefined || value === null) throw new Error(message)\n return value\n}\n\n/**\n * Wraps a teardown so it runs once.\n *\n * Two reasons, and both bite. A disposer is per `bind()`, and undoing twice\n * would put back state a later `bind()` is relying on. And a `dispose()` that\n * deletes twice invalidates a handle someone else may still be holding — the\n * object survives while it is bound, so the fault surfaces later, somewhere\n * else. Idempotent is the only safe shape for either.\n */\nexport function once(teardown: () => void): () => void {\n let done = false\n return () => {\n if (done) return\n done = true\n teardown()\n }\n}\n\n/**********************************************************************************/\n/* */\n/* Kind To Uniform Name */\n/* */\n/**********************************************************************************/\n\nexport const kindToUniformFnName = <T extends UniformKind>(\n kind: T,\n): KIND_TO_UNIFORM_FN_NAME_MAP[T] => {\n switch (kind[0]) {\n // mat\n case 'm':\n return ('Matrix' + kind.slice(3) + 'fv') as KIND_TO_UNIFORM_FN_NAME_MAP[T]\n // sampler/booleans/integer\n case 's':\n case 'b':\n case 'i':\n return ((kind.match(/\\d/)?.[0] ?? '1') + 'i') as KIND_TO_UNIFORM_FN_NAME_MAP[T]\n // unsigned integers\n case 'u':\n return ((kind[4] || '1') + 'ui') as KIND_TO_UNIFORM_FN_NAME_MAP[T]\n // vec\n case 'v':\n return (kind[3] + 'f') as KIND_TO_UNIFORM_FN_NAME_MAP[T]\n default:\n switch (kind) {\n case 'float':\n return '1f' as KIND_TO_UNIFORM_FN_NAME_MAP[T]\n case 'uint':\n return '1ui' as KIND_TO_UNIFORM_FN_NAME_MAP[T]\n default:\n return '1i' as KIND_TO_UNIFORM_FN_NAME_MAP[T]\n }\n }\n}\n\n/**********************************************************************************/\n/* */\n/* Kind To Size */\n/* */\n/**********************************************************************************/\n\nexport const kindToSize = <T extends UniformKind>(kind: T): KIND_TO_SIZE_MAP[T] => {\n switch (kind[0]) {\n case 'm':\n const [a, b] = kind.match(/\\d+/g)!.map(Number) as [number, number?]\n return (a * (b ?? a)) as KIND_TO_SIZE_MAP[T]\n case 'v':\n case 'i':\n case 'b':\n case 'u':\n const match = kind.match(/\\d/) as [string] | undefined\n return (match ? +match[0] : 1) as KIND_TO_SIZE_MAP[T]\n default:\n return 1 as KIND_TO_SIZE_MAP[T]\n }\n}\n\n/**********************************************************************************/\n/* */\n/* Guards */\n/* */\n/**********************************************************************************/\n\nexport const isMatKind = <\n T extends UniformKind | AttributeKind,\n TPrefix extends string,\n TPostfix extends string,\n>(\n kind: T,\n): kind is T & `${TPrefix}mat${TPostfix}` => kind.includes('mat')\n\nexport const isSamplerKind = <TPrefix extends string, TPostfix extends string>(\n kind: UniformKind,\n): kind is UniformKind & `${TPrefix}sampler${TPostfix}` => kind.includes('sampler')\n\nexport const isVecKind = <TPrefix extends string, TPostfix extends string>(\n kind: UniformKind,\n): kind is UniformKind & `${TPrefix}vec${TPostfix}` => kind.includes('vec')\n\n/**********************************************************************************/\n/* */\n/* Create Texture */\n/* */\n/**********************************************************************************/\n\nexport function createTexture(\n gl: GL,\n {\n target = 'TEXTURE_2D',\n internalFormat = 'RGBA',\n format = 'RGBA',\n type = 'UNSIGNED_BYTE',\n minFilter = 'NEAREST',\n magFilter = 'NEAREST',\n wrapS = 'CLAMP_TO_EDGE',\n wrapT = 'CLAMP_TO_EDGE',\n width,\n height,\n }: TextureDefinition,\n data?: ArrayBufferView | null,\n { signal }: ViewOptions = {},\n): WebGLTexture {\n const texture = created(gl.createTexture(), 'texture')\n\n function getTextureConstant(name: string) {\n if (!(name in gl)) {\n throw new Error(`Attempted to create webgl2-only texture (${name}) in webgl1`)\n }\n return gl[name as keyof typeof gl] as any\n }\n\n gl.bindTexture(gl[target], texture)\n gl.texImage2D(\n gl[target],\n 0,\n getTextureConstant(internalFormat),\n width,\n height,\n 0,\n getTextureConstant(format),\n getTextureConstant(type),\n data ?? null,\n )\n\n // Set texture parameters\n gl.texParameteri(gl[target], gl.TEXTURE_MIN_FILTER, gl[minFilter])\n gl.texParameteri(gl[target], gl.TEXTURE_MAG_FILTER, gl[magFilter])\n gl.texParameteri(gl[target], gl.TEXTURE_WRAP_S, gl[wrapS])\n gl.texParameteri(gl[target], gl.TEXTURE_WRAP_T, gl[wrapT])\n\n signal?.addEventListener(\n 'abort',\n once(() => gl.deleteTexture(texture)),\n )\n\n return texture\n}\n\n/**********************************************************************************/\n/* */\n/* Create Framebuffer */\n/* */\n/**********************************************************************************/\n\nconst FRAMEBUFFER_ATTACHMENT_MAP = {\n color: 'COLOR_ATTACHMENT0',\n depth: 'DEPTH_ATTACHMENT',\n stencil: 'STENCIL_ATTACHMENT',\n depthStencil: 'DEPTH_STENCIL_ATTACHMENT',\n} as const\n\nclass FramebufferError extends Error {\n constructor(gl: GL, status: number) {\n let errorMessage = 'Framebuffer not complete. Status: '\n switch (status) {\n case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:\n errorMessage += 'FRAMEBUFFER_INCOMPLETE_ATTACHMENT'\n break\n case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:\n errorMessage += 'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'\n break\n case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:\n errorMessage += 'FRAMEBUFFER_INCOMPLETE_DIMENSIONS'\n break\n case gl.FRAMEBUFFER_UNSUPPORTED:\n errorMessage += 'FRAMEBUFFER_UNSUPPORTED'\n break\n default:\n errorMessage += `Unknown (${status})`\n }\n super(errorMessage)\n }\n}\n\nexport function createFramebuffer(\n gl: GL,\n { attachment, texture: providedTexture, ...definition }: FramebufferDefinition,\n { signal }: ViewOptions = {},\n) {\n // Create texture for the framebuffer, unless one was handed in. Which one it\n // is decides who deletes it below — the same rule the attribute buffers follow.\n const texture = providedTexture ?? createTexture(gl, definition)\n\n // Create framebuffer\n const framebuffer = created(gl.createFramebuffer(), 'framebuffer')\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer)\n\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER,\n // Determine attachment point based on attachment kind\n gl[FRAMEBUFFER_ATTACHMENT_MAP[attachment]],\n gl.TEXTURE_2D,\n texture,\n 0,\n )\n\n // Check framebuffer completeness\n const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER)\n if (status !== gl.FRAMEBUFFER_COMPLETE) {\n throw new FramebufferError(gl, status)\n }\n\n const dispose = once(() => {\n gl.deleteFramebuffer(framebuffer)\n // A texture handed in belongs to whoever made it — it commonly outlives the\n // framebuffer, ping-ponged between two of them.\n if (!providedTexture) {\n gl.deleteTexture(texture)\n }\n })\n\n signal?.addEventListener('abort', dispose)\n\n return {\n texture,\n framebuffer,\n dispose,\n }\n}\n\n/**********************************************************************************/\n/* */\n/* Create Upsert */\n/* */\n/**********************************************************************************/\n\ntype UpsertMapKind<T, U> = Map<T, U> | (T extends WeakKey ? WeakMap<T, U> : never)\n\nexport function createUpsertMap<T extends UpsertMapKind<any, any> = Map<any, any>>(\n constructor?: new () => T,\n) {\n const map = new (constructor ?? Map)() as T\n return Object.assign(map, {\n getOrInsert(\n key: T extends UpsertMapKind<infer U, any> ? U : never,\n value: T extends UpsertMapKind<any, infer U> ? () => U : never,\n ) {\n let result = map.get(key)\n if (result) {\n return result\n }\n result = value()\n map.set(key, result)\n return result\n },\n })\n}\n\nexport function forEachObject<T extends Record<string, any>>(\n value: T,\n callback: (value: T[keyof T], key: keyof T, index: number) => void,\n) {\n let index = 0\n for (const key in value) {\n callback(value[key], key, index)\n index++\n }\n for (const key of Object.getOwnPropertySymbols(value)) {\n callback(value[key as keyof T], key as keyof T, index)\n index++\n }\n}\n\nexport function mapObject<T extends Record<string, any>, TReturn>(\n value: T,\n callback: (value: T[keyof T], key: keyof T, index: number) => TReturn,\n): { [TKey in keyof T]: TReturn } {\n const result = {} as { [TKey in keyof T]: TReturn }\n\n forEachObject(value, (value, key, index) => {\n result[key] = callback(value, key, index)\n })\n\n return result\n}\n","import { RemoveSuffix } from './type-utils'\nimport type { GL, ViewOptions } from './types'\nimport { created, ProgramLinkError, ShaderCompileError } from './errors'\nimport { once } from './utils'\n\nfunction isWebGL2RenderingContext(\n gl: WebGLRenderingContext | WebGL2RenderingContext,\n): gl is WebGL2RenderingContext {\n return typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext\n}\n\n/**********************************************************************************/\n/* */\n/* Create Shader */\n/* */\n/**********************************************************************************/\n\nexport function createShader(gl: GL, type: number, source: string): WebGLShader {\n const shader = created(gl.createShader(type), 'shader')\n\n gl.shaderSource(shader, source)\n gl.compileShader(shader)\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n const error = new ShaderCompileError(\n type === gl.VERTEX_SHADER ? 'vertex' : 'fragment',\n gl.getShaderInfoLog(shader),\n gl.getError(),\n )\n gl.deleteShader(shader)\n throw error\n }\n\n return shader\n}\n\n/**********************************************************************************/\n/* */\n/* Create Program */\n/* */\n/**********************************************************************************/\n\nexport function createProgram(\n gl: GL,\n vertexSource: string,\n fragmentSource: string,\n { signal }: ViewOptions = {},\n): WebGLProgram {\n const program = created(gl.createProgram(), 'program')\n\n const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexSource)\n const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentSource)\n\n gl.attachShader(program, vertexShader)\n gl.attachShader(program, fragmentShader)\n gl.linkProgram(program)\n\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n const error = new ProgramLinkError(gl.getProgramInfoLog(program), gl.getError())\n gl.deleteProgram(program)\n gl.deleteShader(vertexShader)\n gl.deleteShader(fragmentShader)\n throw error\n }\n\n // Clean up shaders after linking\n gl.deleteShader(vertexShader)\n gl.deleteShader(fragmentShader)\n\n signal?.addEventListener(\n 'abort',\n once(() => gl.deleteProgram(program)),\n )\n\n return program\n}\n\n/**********************************************************************************/\n/* */\n/* Get Instanced Arrays */\n/* */\n/**********************************************************************************/\n\nconst INSTANCED_ARRAYS_WRAPPER_MAP = new WeakMap<\n GL,\n RemoveSuffix<\n Pick<\n ANGLE_instanced_arrays,\n 'drawArraysInstancedANGLE' | 'drawElementsInstancedANGLE' | 'vertexAttribDivisorANGLE'\n >,\n 'ANGLE'\n > | null\n>()\nexport function getInstancedArrays(gl: GL) {\n if (isWebGL2RenderingContext(gl)) return gl\n\n const cached = INSTANCED_ARRAYS_WRAPPER_MAP.get(gl)\n if (cached) return cached\n\n const ext = gl.getExtension('ANGLE_instanced_arrays')\n if (!ext) return undefined\n\n const wrapper = {\n drawArraysInstanced: ext.drawArraysInstancedANGLE.bind(ext),\n drawElementsInstanced: ext.drawElementsInstancedANGLE.bind(ext),\n vertexAttribDivisor: ext.vertexAttribDivisorANGLE.bind(ext),\n }\n INSTANCED_ARRAYS_WRAPPER_MAP.set(gl, wrapper)\n\n return wrapper\n}\n\n/**********************************************************************************/\n/* */\n/* Get Vertex Array Object */\n/* */\n/**********************************************************************************/\n\nconst VERTEX_ARRAY_OBJECT_WRAPPER_MAP = new WeakMap<\n GL,\n RemoveSuffix<\n Pick<\n OES_vertex_array_object,\n 'bindVertexArrayOES' | 'createVertexArrayOES' | 'deleteVertexArrayOES'\n >,\n 'OES'\n > | null\n>()\nexport function getVertexArrayObject(gl: GL) {\n if (isWebGL2RenderingContext(gl)) return gl\n\n const cached = VERTEX_ARRAY_OBJECT_WRAPPER_MAP.get(gl)\n if (cached) return cached\n\n const ext = gl.getExtension('OES_vertex_array_object')\n if (!ext) return null\n\n const wrapper = {\n bindVertexArray: ext.bindVertexArrayOES.bind(ext),\n createVertexArray: ext.createVertexArrayOES.bind(ext),\n deleteVertexArray: ext.deleteVertexArrayOES.bind(ext),\n }\n VERTEX_ARRAY_OBJECT_WRAPPER_MAP.set(gl, wrapper)\n\n return wrapper\n}\n"],"mappings":";AAIO,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAG5C,YACW,OACA,SACA,SACT;AACA,UAAM,qBAAqB,KAAK,YAAY,OAAO,EAAE;AAJ5C;AACA;AACA;AAAA,EAGX;AAAA,EARS,OAAO;AASlB;AAMO,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAG1C,YACW,SACA,SACT;AACA,UAAM,2BAA2B,OAAO,EAAE;AAHjC;AACA;AAAA,EAGX;AAAA,EAPS,OAAO;AAQlB;AAKO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EAGvC,YAAqB,UAAsB;AACzC,UAAM,oBAAoB,QAAQ,EAAE;AADjB;AAAA,EAErB;AAAA,EAJS,OAAO;AAKlB;AAGO,IAAM,yBAAN,cAAqC,MAAM;AAAA,EAGhD,YAAqB,WAAmB;AACtC,UAAM,cAAc,SAAS,aAAa;AADvB;AAAA,EAErB;AAAA,EAJS,OAAO;AAKlB;AAGO,SAAS,QAAW,OAAiB,UAAyB;AACnE,MAAI,UAAU,MAAM;AAClB,UAAM,IAAI,cAAc,QAAQ;AAAA,EAClC;AACA,SAAO;AACT;;;AC7CO,SAAS,mBAAsB,OAAU,SAAkC;AAChF,MAAI,UAAU,UAAa,UAAU,KAAM,OAAM,IAAI,MAAM,OAAO;AAClE,SAAO;AACT;AAWO,SAAS,KAAK,UAAkC;AACrD,MAAI,OAAO;AACX,SAAO,MAAM;AACX,QAAI,KAAM;AACV,WAAO;AACP,aAAS;AAAA,EACX;AACF;AAQO,IAAM,sBAAsB,CACjC,SACm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;AAAA,IACA,KAAK,MAAM,GAAG,cAAc,OAAO,CAAC;AAAA,EACtC;AAEA,SAAO;AACT;AAQA,IAAM,+BAA+B,oBAAI,QASvC;AACK,SAAS,mBAAmB,IAAQ;AACzC,MAAI,yBAAyB,EAAE,EAAG,QAAO;AAEzC,QAAM,SAAS,6BAA6B,IAAI,EAAE;AAClD,MAAI,OAAQ,QAAO;AAEnB,QAAM,MAAM,GAAG,aAAa,wBAAwB;AACpD,MAAI,CAAC,IAAK,QAAO;AAEjB,QAAM,UAAU;AAAA,IACd,qBAAqB,IAAI,yBAAyB,KAAK,GAAG;AAAA,IAC1D,uBAAuB,IAAI,2BAA2B,KAAK,GAAG;AAAA,IAC9D,qBAAqB,IAAI,yBAAyB,KAAK,GAAG;AAAA,EAC5D;AACA,+BAA6B,IAAI,IAAI,OAAO;AAE5C,SAAO;AACT;AAQA,IAAM,kCAAkC,oBAAI,QAS1C;AACK,SAAS,qBAAqB,IAAQ;AAC3C,MAAI,yBAAyB,EAAE,EAAG,QAAO;AAEzC,QAAM,SAAS,gCAAgC,IAAI,EAAE;AACrD,MAAI,OAAQ,QAAO;AAEnB,QAAM,MAAM,GAAG,aAAa,yBAAyB;AACrD,MAAI,CAAC,IAAK,QAAO;AAEjB,QAAM,UAAU;AAAA,IACd,iBAAiB,IAAI,mBAAmB,KAAK,GAAG;AAAA,IAChD,mBAAmB,IAAI,qBAAqB,KAAK,GAAG;AAAA,IACpD,mBAAmB,IAAI,qBAAqB,KAAK,GAAG;AAAA,EACtD;AACA,kCAAgC,IAAI,IAAI,OAAO;AAE/C,SAAO;AACT;","names":["value"]}
|
package/dist/gl.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { G as GL, V as ViewOptions, R as RemoveSuffix } from './types-
|
|
1
|
+
import { G as GL, V as ViewOptions, R as RemoveSuffix } from './types-DZbMcty2.mjs';
|
|
2
2
|
|
|
3
3
|
/**********************************************************************************/
|
|
4
4
|
/**********************************************************************************/
|
package/dist/gl.mjs
CHANGED
package/dist/index.d.mts
CHANGED
|
@@ -1,5 +1,42 @@
|
|
|
1
|
-
import { G as GL, F as FramebufferDefinition, V as ViewOptions, T as TextureDefinition, a as ViewSchema, b as View, c as VertexArrayParticipant, d as VertexArrayMethods, U as UniformSchema, e as UniformView, A as AttributeSchema, f as AttributeView, I as InterleavedAttributeSchema, g as InterleavedAttributeView, B as BufferSchema, h as BufferView } from './types-
|
|
2
|
-
export { D as AttributeDefinition, C as AttributeFormat, z as AttributeKind, E as AttributeMethods, y as AttributeShortHand, ac as AttributeToken, ad as AttributeTokenFn, P as BufferDefinition, Q as BufferMethods, L as BufferSource, ak as CompileResult, M as ConstantAttributeMethods, N as ConstantSource, ai as FlattenSlots, a3 as Format, W as Framebuffer, a9 as GLSL, a7 as GLSLResult, a8 as GLSLSlot, ah as GLSLSlotsToSchema, af as GLSLToSchema, ag as GLSLToView, i as GLTarget, n as GLTextureFilter, l as GLTextureFormat, k as GLTextureTarget, m as GLTextureType, o as GLTextureWrap, j as GLUsage, ae as InterleaveToken, J as InterleavedAttributeDefinition, H as InterleavedAttributeLayout, O as InterleavedAttributeMethods, a2 as InternalFormat, p as KIND_TO_SIZE_MAP, K as KIND_TO_UNIFORM_FN_NAME_MAP, aj as MergeGLSLSchema, a4 as PixelType, S as Source, a5 as TexImage2DOptions, Z as TextureMethods, $ as TextureParameterName, a0 as TextureParameterValue, a1 as TextureParameters, Y as TextureSchema, X as TextureTarget, _ as TextureView, v as UniformArrayMethods, t as UniformDefinition, u as UniformElementMethods, q as UniformFnName, r as UniformKind, s as UniformKindMap, w as UniformMethods, aa as UniformToken, ab as UniformTokenFn, x as UniformValue, a6 as ViewSchemaPartial } from './types-
|
|
1
|
+
import { G as GL, F as FramebufferDefinition, V as ViewOptions, T as TextureDefinition, a as ViewSchema, b as View, c as VertexArrayParticipant, d as VertexArrayMethods, U as UniformSchema, e as UniformView, A as AttributeSchema, f as AttributeView, I as InterleavedAttributeSchema, g as InterleavedAttributeView, B as BufferSchema, h as BufferView } from './types-DZbMcty2.mjs';
|
|
2
|
+
export { D as AttributeDefinition, C as AttributeFormat, z as AttributeKind, E as AttributeMethods, y as AttributeShortHand, ac as AttributeToken, ad as AttributeTokenFn, P as BufferDefinition, Q as BufferMethods, L as BufferSource, ak as CompileResult, M as ConstantAttributeMethods, N as ConstantSource, ai as FlattenSlots, a3 as Format, W as Framebuffer, a9 as GLSL, a7 as GLSLResult, a8 as GLSLSlot, ah as GLSLSlotsToSchema, af as GLSLToSchema, ag as GLSLToView, i as GLTarget, n as GLTextureFilter, l as GLTextureFormat, k as GLTextureTarget, m as GLTextureType, o as GLTextureWrap, j as GLUsage, ae as InterleaveToken, J as InterleavedAttributeDefinition, H as InterleavedAttributeLayout, O as InterleavedAttributeMethods, a2 as InternalFormat, p as KIND_TO_SIZE_MAP, K as KIND_TO_UNIFORM_FN_NAME_MAP, aj as MergeGLSLSchema, a4 as PixelType, S as Source, a5 as TexImage2DOptions, Z as TextureMethods, $ as TextureParameterName, a0 as TextureParameterValue, a1 as TextureParameters, Y as TextureSchema, X as TextureTarget, _ as TextureView, v as UniformArrayMethods, t as UniformDefinition, u as UniformElementMethods, q as UniformFnName, r as UniformKind, s as UniformKindMap, w as UniformMethods, aa as UniformToken, ab as UniformTokenFn, x as UniformValue, a6 as ViewSchemaPartial } from './types-DZbMcty2.mjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* A shader that did not compile. `infoLog` is what the driver answered, `null`
|
|
6
|
+
* and `''` kept apart; `glError` is `getError()` read at the failure.
|
|
7
|
+
*/
|
|
8
|
+
declare class ShaderCompileError extends Error {
|
|
9
|
+
readonly stage: 'vertex' | 'fragment';
|
|
10
|
+
readonly infoLog: string | null;
|
|
11
|
+
readonly glError: number;
|
|
12
|
+
name: string;
|
|
13
|
+
constructor(stage: 'vertex' | 'fragment', infoLog: string | null, glError: number);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* A program that did not link. `infoLog` is what the driver answered, `null`
|
|
17
|
+
* and `''` kept apart; `glError` is `getError()` read at the failure.
|
|
18
|
+
*/
|
|
19
|
+
declare class ProgramLinkError extends Error {
|
|
20
|
+
readonly infoLog: string | null;
|
|
21
|
+
readonly glError: number;
|
|
22
|
+
name: string;
|
|
23
|
+
constructor(infoLog: string | null, glError: number);
|
|
24
|
+
}
|
|
25
|
+
type GLResource = 'shader' | 'program' | 'buffer' | 'vertexArray' | 'texture' | 'framebuffer';
|
|
26
|
+
/** A `create*` call that answered `null`. */
|
|
27
|
+
declare class GLCreateError extends Error {
|
|
28
|
+
readonly resource: GLResource;
|
|
29
|
+
name: string;
|
|
30
|
+
constructor(resource: GLResource);
|
|
31
|
+
}
|
|
32
|
+
/** A program with no active attribute of that name: `getAttribLocation` answered -1. */
|
|
33
|
+
declare class AttributeNotFoundError extends Error {
|
|
34
|
+
readonly attribute: string;
|
|
35
|
+
name: string;
|
|
36
|
+
constructor(attribute: string);
|
|
37
|
+
}
|
|
38
|
+
/** Throws a {@link GLCreateError} for a `create*` that answered `null`. */
|
|
39
|
+
declare function created<T>(value: T | null, resource: GLResource): T;
|
|
3
40
|
|
|
4
41
|
/**********************************************************************************/
|
|
5
42
|
/**********************************************************************************/
|
|
@@ -33,4 +70,4 @@ declare function interleavedAttributeView<T extends InterleavedAttributeSchema>(
|
|
|
33
70
|
/**********************************************************************************/
|
|
34
71
|
declare function bufferView<T extends BufferSchema>(gl: GL, schema: T, { signal }?: ViewOptions): BufferView<T>;
|
|
35
72
|
|
|
36
|
-
export { AttributeSchema, AttributeView, BufferSchema, BufferView, FramebufferDefinition, GL, InterleavedAttributeSchema, InterleavedAttributeView, TextureDefinition, UniformSchema, UniformView, VertexArrayMethods, VertexArrayParticipant, View, ViewOptions, ViewSchema, attributeView, bufferView, createFramebuffer, createTexture, interleavedAttributeView, toID, uniformView, vaoView, view };
|
|
73
|
+
export { AttributeNotFoundError, AttributeSchema, AttributeView, BufferSchema, BufferView, FramebufferDefinition, GL, GLCreateError, type GLResource, InterleavedAttributeSchema, InterleavedAttributeView, ProgramLinkError, ShaderCompileError, TextureDefinition, UniformSchema, UniformView, VertexArrayMethods, VertexArrayParticipant, View, ViewOptions, ViewSchema, attributeView, bufferView, createFramebuffer, createTexture, created, interleavedAttributeView, toID, uniformView, vaoView, view };
|
package/dist/index.mjs
CHANGED
|
@@ -6,16 +6,26 @@ import {
|
|
|
6
6
|
uniformView,
|
|
7
7
|
vaoView,
|
|
8
8
|
view
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-7Z5UULAB.mjs";
|
|
10
10
|
import {
|
|
11
|
+
AttributeNotFoundError,
|
|
12
|
+
GLCreateError,
|
|
13
|
+
ProgramLinkError,
|
|
14
|
+
ShaderCompileError,
|
|
11
15
|
createFramebuffer,
|
|
12
|
-
createTexture
|
|
13
|
-
|
|
16
|
+
createTexture,
|
|
17
|
+
created
|
|
18
|
+
} from "./chunk-TQWPUDQI.mjs";
|
|
14
19
|
export {
|
|
20
|
+
AttributeNotFoundError,
|
|
21
|
+
GLCreateError,
|
|
22
|
+
ProgramLinkError,
|
|
23
|
+
ShaderCompileError,
|
|
15
24
|
attributeView,
|
|
16
25
|
bufferView,
|
|
17
26
|
createFramebuffer,
|
|
18
27
|
createTexture,
|
|
28
|
+
created,
|
|
19
29
|
interleavedAttributeView,
|
|
20
30
|
toID,
|
|
21
31
|
uniformView,
|
package/dist/tag.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a8 as GLSLSlot, a9 as GLSL, ab as UniformTokenFn, ad as AttributeTokenFn, ac as AttributeToken, z as AttributeKind, D as AttributeDefinition, ae as InterleaveToken, a6 as ViewSchemaPartial, ak as CompileResult, al as Prettify, af as GLSLToSchema, G as GL } from './types-
|
|
1
|
+
import { a8 as GLSLSlot, a9 as GLSL, ab as UniformTokenFn, ad as AttributeTokenFn, ac as AttributeToken, z as AttributeKind, D as AttributeDefinition, ae as InterleaveToken, a6 as ViewSchemaPartial, ak as CompileResult, al as Prettify, af as GLSLToSchema, G as GL } from './types-DZbMcty2.mjs';
|
|
2
2
|
|
|
3
3
|
declare function glsl<TSlot extends GLSLSlot, const TSlots extends TSlot[]>(template: TemplateStringsArray, ...slots: [...TSlots]): GLSL<TSlots>;
|
|
4
4
|
declare const uniform: {
|
package/dist/tag.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
toID,
|
|
3
3
|
view
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-7Z5UULAB.mjs";
|
|
5
5
|
import {
|
|
6
6
|
createProgram,
|
|
7
7
|
createUpsertMap,
|
|
8
8
|
once
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-TQWPUDQI.mjs";
|
|
10
10
|
|
|
11
11
|
// src/tag.ts
|
|
12
12
|
function glsl(template, ...slots) {
|
|
@@ -253,6 +253,21 @@ interface AttributeMethods<T extends AttributeDefinition = AttributeDefinition>
|
|
|
253
253
|
set(data: FormatToArray[ResolvedFormat<T>], usage?: GLUsage): {
|
|
254
254
|
bind(): () => void;
|
|
255
255
|
};
|
|
256
|
+
/**
|
|
257
|
+
* Sizes the buffer to `length` elements of the attribute's format, contents
|
|
258
|
+
* undefined, discarding what it held.
|
|
259
|
+
*/
|
|
260
|
+
allocate(length: number, usage?: GLUsage): {
|
|
261
|
+
bind(): () => void;
|
|
262
|
+
};
|
|
263
|
+
/**
|
|
264
|
+
* Overwrites the elements from `offset` on with `data`, leaving the rest as
|
|
265
|
+
* it is. Counts in elements of the attribute's format; the range must fit
|
|
266
|
+
* inside the buffer's current size.
|
|
267
|
+
*/
|
|
268
|
+
write(data: FormatToArray[ResolvedFormat<T>], offset: number): {
|
|
269
|
+
bind(): () => void;
|
|
270
|
+
};
|
|
256
271
|
/**
|
|
257
272
|
* Delete the buffer, if this attribute is the one that made it.
|
|
258
273
|
*
|
|
@@ -343,6 +358,16 @@ interface BufferDefinition {
|
|
|
343
358
|
type BufferSchema = Record<string | symbol, BufferDefinition>;
|
|
344
359
|
interface BufferMethods extends VertexArrayParticipant {
|
|
345
360
|
set(data: Float32Array | Uint16Array | Uint32Array): void;
|
|
361
|
+
/**
|
|
362
|
+
* Sizes the buffer to `byteLength` bytes, contents undefined, discarding what
|
|
363
|
+
* it held. In bytes: the buffer has no element type of its own.
|
|
364
|
+
*/
|
|
365
|
+
allocate(byteLength: number): void;
|
|
366
|
+
/**
|
|
367
|
+
* Overwrites the bytes from `byteOffset` on with `data`, leaving the rest as
|
|
368
|
+
* it is. The range must fit inside the buffer's current size.
|
|
369
|
+
*/
|
|
370
|
+
write(data: Float32Array | Uint16Array | Uint32Array, byteOffset: number): void;
|
|
346
371
|
/** Binds the buffer, returning a disposer that restores the previous binding */
|
|
347
372
|
bind(): () => void;
|
|
348
373
|
dispose(): void;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bigmistqke/view.gl",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"description": "👀 Utilities for managing WebGL resources.",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": {
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"dev": "vite serve dev",
|
|
26
26
|
"format": "prettier -w \"src/**/*.{js,ts,json,css,tsx,jsx}\" \"dev/**/*.{js,ts,json,css,tsx,jsx}\"",
|
|
27
27
|
"lint:types": "tsc --noEmit",
|
|
28
|
-
"
|
|
28
|
+
"prepublishOnly": "pnpm test && pnpm build",
|
|
29
29
|
"test:coverage": "vitest run --coverage",
|
|
30
30
|
"test:ui": "vitest --ui",
|
|
31
31
|
"test": "vitest --run"
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A shader that did not compile. `infoLog` is what the driver answered, `null`
|
|
3
|
+
* and `''` kept apart; `glError` is `getError()` read at the failure.
|
|
4
|
+
*/
|
|
5
|
+
export class ShaderCompileError extends Error {
|
|
6
|
+
override name = 'ShaderCompileError'
|
|
7
|
+
|
|
8
|
+
constructor(
|
|
9
|
+
readonly stage: 'vertex' | 'fragment',
|
|
10
|
+
readonly infoLog: string | null,
|
|
11
|
+
readonly glError: number,
|
|
12
|
+
) {
|
|
13
|
+
super(`Failed to compile ${stage} shader: ${infoLog}`)
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A program that did not link. `infoLog` is what the driver answered, `null`
|
|
19
|
+
* and `''` kept apart; `glError` is `getError()` read at the failure.
|
|
20
|
+
*/
|
|
21
|
+
export class ProgramLinkError extends Error {
|
|
22
|
+
override name = 'ProgramLinkError'
|
|
23
|
+
|
|
24
|
+
constructor(
|
|
25
|
+
readonly infoLog: string | null,
|
|
26
|
+
readonly glError: number,
|
|
27
|
+
) {
|
|
28
|
+
super(`Failed to link program: ${infoLog}`)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export type GLResource = 'shader' | 'program' | 'buffer' | 'vertexArray' | 'texture' | 'framebuffer'
|
|
33
|
+
|
|
34
|
+
/** A `create*` call that answered `null`. */
|
|
35
|
+
export class GLCreateError extends Error {
|
|
36
|
+
override name = 'GLCreateError'
|
|
37
|
+
|
|
38
|
+
constructor(readonly resource: GLResource) {
|
|
39
|
+
super(`Failed to create ${resource}`)
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A program with no active attribute of that name: `getAttribLocation` answered -1. */
|
|
44
|
+
export class AttributeNotFoundError extends Error {
|
|
45
|
+
override name = 'AttributeNotFoundError'
|
|
46
|
+
|
|
47
|
+
constructor(readonly attribute: string) {
|
|
48
|
+
super(`Attribute '${attribute}' not found`)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Throws a {@link GLCreateError} for a `create*` that answered `null`. */
|
|
53
|
+
export function created<T>(value: T | null, resource: GLResource): T {
|
|
54
|
+
if (value === null) {
|
|
55
|
+
throw new GLCreateError(resource)
|
|
56
|
+
}
|
|
57
|
+
return value
|
|
58
|
+
}
|
package/src/gl.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { RemoveSuffix } from './type-utils'
|
|
2
2
|
import type { GL, ViewOptions } from './types'
|
|
3
|
+
import { created, ProgramLinkError, ShaderCompileError } from './errors'
|
|
3
4
|
import { once } from './utils'
|
|
4
5
|
|
|
5
6
|
function isWebGL2RenderingContext(
|
|
@@ -15,18 +16,19 @@ function isWebGL2RenderingContext(
|
|
|
15
16
|
/**********************************************************************************/
|
|
16
17
|
|
|
17
18
|
export function createShader(gl: GL, type: number, source: string): WebGLShader {
|
|
18
|
-
const shader = gl.createShader(type)
|
|
19
|
-
if (!shader) throw new Error('Failed to create shader')
|
|
19
|
+
const shader = created(gl.createShader(type), 'shader')
|
|
20
20
|
|
|
21
21
|
gl.shaderSource(shader, source)
|
|
22
22
|
gl.compileShader(shader)
|
|
23
23
|
|
|
24
24
|
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
25
|
+
const error = new ShaderCompileError(
|
|
26
|
+
type === gl.VERTEX_SHADER ? 'vertex' : 'fragment',
|
|
27
|
+
gl.getShaderInfoLog(shader),
|
|
28
|
+
gl.getError(),
|
|
29
29
|
)
|
|
30
|
+
gl.deleteShader(shader)
|
|
31
|
+
throw error
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
return shader
|
|
@@ -44,8 +46,7 @@ export function createProgram(
|
|
|
44
46
|
fragmentSource: string,
|
|
45
47
|
{ signal }: ViewOptions = {},
|
|
46
48
|
): WebGLProgram {
|
|
47
|
-
const program = gl.createProgram()
|
|
48
|
-
if (!program) throw new Error('Failed to create WebGL program')
|
|
49
|
+
const program = created(gl.createProgram(), 'program')
|
|
49
50
|
|
|
50
51
|
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexSource)
|
|
51
52
|
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentSource)
|
|
@@ -55,11 +56,11 @@ export function createProgram(
|
|
|
55
56
|
gl.linkProgram(program)
|
|
56
57
|
|
|
57
58
|
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
|
|
58
|
-
const
|
|
59
|
+
const error = new ProgramLinkError(gl.getProgramInfoLog(program), gl.getError())
|
|
59
60
|
gl.deleteProgram(program)
|
|
60
61
|
gl.deleteShader(vertexShader)
|
|
61
62
|
gl.deleteShader(fragmentShader)
|
|
62
|
-
throw
|
|
63
|
+
throw error
|
|
63
64
|
}
|
|
64
65
|
|
|
65
66
|
// Clean up shaders after linking
|
package/src/index.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { AttributeNotFoundError, created } from './errors'
|
|
1
2
|
import { getInstancedArrays, getVertexArrayObject } from './gl'
|
|
2
3
|
import type {
|
|
3
4
|
AttributeFormat,
|
|
@@ -31,6 +32,7 @@ import {
|
|
|
31
32
|
once,
|
|
32
33
|
} from './utils'
|
|
33
34
|
import { createUpsertMap, mapObject } from './utils'
|
|
35
|
+
export * from './errors'
|
|
34
36
|
export * from './types'
|
|
35
37
|
// Documented under Utils but reachable from nowhere until now: utils is not a
|
|
36
38
|
// build entry, and named rather than star so the internal helpers stay internal.
|
|
@@ -148,7 +150,7 @@ function bindDefaultVertexArray(gl: GL): () => void {
|
|
|
148
150
|
if (!feature) {
|
|
149
151
|
return () => {}
|
|
150
152
|
}
|
|
151
|
-
const previous = gl
|
|
153
|
+
const previous = readVertexArrayBinding(gl)
|
|
152
154
|
feature.bindVertexArray(null)
|
|
153
155
|
return () => feature.bindVertexArray(previous)
|
|
154
156
|
}
|
|
@@ -180,8 +182,8 @@ export function vaoView(
|
|
|
180
182
|
dispose() {},
|
|
181
183
|
}
|
|
182
184
|
: (() => {
|
|
183
|
-
const vertexArray =
|
|
184
|
-
const previous = gl
|
|
185
|
+
const vertexArray = created(feature.createVertexArray(), 'vertexArray')
|
|
186
|
+
const previous = readVertexArrayBinding(gl)
|
|
185
187
|
feature.bindVertexArray(vertexArray)
|
|
186
188
|
// Discarding the restorers is the point: the state lives in this array
|
|
187
189
|
// now, and the array is thrown away whole.
|
|
@@ -192,9 +194,7 @@ export function vaoView(
|
|
|
192
194
|
|
|
193
195
|
return {
|
|
194
196
|
bind() {
|
|
195
|
-
const previousVertexArray = gl
|
|
196
|
-
VERTEX_ARRAY_BINDING,
|
|
197
|
-
) as WebGLVertexArrayObject | null
|
|
197
|
+
const previousVertexArray = readVertexArrayBinding(gl)
|
|
198
198
|
feature.bindVertexArray(vertexArray)
|
|
199
199
|
// Context state the array cannot hold — see applyToContext.
|
|
200
200
|
participants.forEach(participant => participant.applyToContext?.())
|
|
@@ -366,6 +366,12 @@ function handleAttribute(
|
|
|
366
366
|
const VERTEX_ATTRIB_ARRAY_DIVISOR = 0x88fe
|
|
367
367
|
const VERTEX_ARRAY_BINDING = 0x85b5
|
|
368
368
|
|
|
369
|
+
// Anything but an array or null would make the restore throw a TypeError.
|
|
370
|
+
function readVertexArrayBinding(gl: GL): WebGLVertexArrayObject | null {
|
|
371
|
+
const bound: unknown = gl.getParameter(VERTEX_ARRAY_BINDING)
|
|
372
|
+
return typeof bound === 'object' ? (bound as WebGLVertexArrayObject | null) : null
|
|
373
|
+
}
|
|
374
|
+
|
|
369
375
|
// Reads the divisor currently attached to a location, 0 where instancing is
|
|
370
376
|
// unavailable and nothing can have set one
|
|
371
377
|
function readDivisor(gl: GL, location: number): number {
|
|
@@ -392,11 +398,11 @@ export function attributeView<T extends AttributeSchema>(
|
|
|
392
398
|
// belongs to another view — the quad `compile.toQuad` shares across every
|
|
393
399
|
// program on a context, an attribute two programs step over — and
|
|
394
400
|
// deleting one of those would take it out from under its owner.
|
|
395
|
-
const buffer = providedBuffer ??
|
|
401
|
+
const buffer = providedBuffer ?? created(gl.createBuffer(), 'buffer')
|
|
396
402
|
|
|
397
403
|
const location = gl.getAttribLocation(program, name)
|
|
398
404
|
if (location < 0) {
|
|
399
|
-
throw new
|
|
405
|
+
throw new AttributeNotFoundError(name)
|
|
400
406
|
}
|
|
401
407
|
|
|
402
408
|
const size = kindToSize(kind)
|
|
@@ -551,7 +557,7 @@ export function interleavedAttributeView<T extends InterleavedAttributeSchema>(
|
|
|
551
557
|
const location = gl.getAttribLocation(program, name)
|
|
552
558
|
|
|
553
559
|
if (location < 0) {
|
|
554
|
-
throw new
|
|
560
|
+
throw new AttributeNotFoundError(name)
|
|
555
561
|
}
|
|
556
562
|
|
|
557
563
|
locations.push(location)
|
|
@@ -582,7 +588,7 @@ export function interleavedAttributeView<T extends InterleavedAttributeSchema>(
|
|
|
582
588
|
const stride = index
|
|
583
589
|
|
|
584
590
|
// Create a buffer
|
|
585
|
-
const buffer =
|
|
591
|
+
const buffer = created(gl.createBuffer(), 'buffer')
|
|
586
592
|
|
|
587
593
|
// This layout used to create a vertex array of its own, here, which is why
|
|
588
594
|
// the other participants in a draw had to be bound after it to be included
|
|
@@ -670,7 +676,7 @@ export function bufferView<T extends BufferSchema>(
|
|
|
670
676
|
): BufferView<T> {
|
|
671
677
|
// Initialize buffers
|
|
672
678
|
const buffers = mapObject(schema, ({ target = 'ARRAY_BUFFER', usage = 'STATIC_DRAW' }) => {
|
|
673
|
-
const buffer =
|
|
679
|
+
const buffer = created(gl.createBuffer(), 'buffer')
|
|
674
680
|
|
|
675
681
|
function applyToVertexArray() {
|
|
676
682
|
// Snapshot before the change, restore in the disposer. Restoring the
|
package/src/utils.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { created } from './errors'
|
|
1
2
|
import type {
|
|
2
3
|
AttributeKind,
|
|
3
4
|
FramebufferDefinition,
|
|
@@ -135,7 +136,7 @@ export function createTexture(
|
|
|
135
136
|
data?: ArrayBufferView | null,
|
|
136
137
|
{ signal }: ViewOptions = {},
|
|
137
138
|
): WebGLTexture {
|
|
138
|
-
const texture =
|
|
139
|
+
const texture = created(gl.createTexture(), 'texture')
|
|
139
140
|
|
|
140
141
|
function getTextureConstant(name: string) {
|
|
141
142
|
if (!(name in gl)) {
|
|
@@ -217,7 +218,7 @@ export function createFramebuffer(
|
|
|
217
218
|
const texture = providedTexture ?? createTexture(gl, definition)
|
|
218
219
|
|
|
219
220
|
// Create framebuffer
|
|
220
|
-
const framebuffer =
|
|
221
|
+
const framebuffer = created(gl.createFramebuffer(), 'framebuffer')
|
|
221
222
|
|
|
222
223
|
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer)
|
|
223
224
|
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
|
2
|
+
import { createProgram, createShader } from '../src/gl'
|
|
3
|
+
import {
|
|
4
|
+
AttributeNotFoundError,
|
|
5
|
+
GLCreateError,
|
|
6
|
+
ProgramLinkError,
|
|
7
|
+
ShaderCompileError,
|
|
8
|
+
attributeView,
|
|
9
|
+
bufferView,
|
|
10
|
+
createFramebuffer,
|
|
11
|
+
createTexture,
|
|
12
|
+
interleavedAttributeView,
|
|
13
|
+
vaoView,
|
|
14
|
+
} from '../src/index'
|
|
15
|
+
import type { AttributeSchema } from '../src/types'
|
|
16
|
+
import { createMockCanvas } from './mocks/webgl'
|
|
17
|
+
|
|
18
|
+
let gl: WebGL2RenderingContext
|
|
19
|
+
let program: WebGLProgram
|
|
20
|
+
|
|
21
|
+
beforeEach(() => {
|
|
22
|
+
gl = createMockCanvas().gl
|
|
23
|
+
program = gl.createProgram()!
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
describe('ShaderCompileError', () => {
|
|
27
|
+
it('carries the stage, the info log as given and the GL error', () => {
|
|
28
|
+
gl.getShaderParameter = vi.fn(() => false)
|
|
29
|
+
gl.getShaderInfoLog = vi.fn(() => "ERROR: 0:1: 'x' : undeclared identifier")
|
|
30
|
+
gl.getError = vi.fn(() => 0x0502)
|
|
31
|
+
|
|
32
|
+
const error = catchError(() => createShader(gl, gl.FRAGMENT_SHADER, 'void main() {}'))
|
|
33
|
+
|
|
34
|
+
expect(error).toBeInstanceOf(ShaderCompileError)
|
|
35
|
+
expect(error).toMatchObject({
|
|
36
|
+
name: 'ShaderCompileError',
|
|
37
|
+
stage: 'fragment',
|
|
38
|
+
infoLog: "ERROR: 0:1: 'x' : undeclared identifier",
|
|
39
|
+
glError: 0x0502,
|
|
40
|
+
message: "Failed to compile fragment shader: ERROR: 0:1: 'x' : undeclared identifier",
|
|
41
|
+
})
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
it.each([
|
|
45
|
+
['null', null],
|
|
46
|
+
['empty', ''],
|
|
47
|
+
])('keeps a %s info log as it came', (_, infoLog) => {
|
|
48
|
+
gl.getShaderParameter = vi.fn(() => false)
|
|
49
|
+
gl.getShaderInfoLog = vi.fn(() => infoLog)
|
|
50
|
+
|
|
51
|
+
const error = catchError(() => createShader(gl, gl.VERTEX_SHADER, ''))
|
|
52
|
+
|
|
53
|
+
expect(error).toMatchObject({ stage: 'vertex', infoLog })
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('is thrown from createProgram for either stage', () => {
|
|
57
|
+
gl.getShaderParameter = vi.fn(() => false)
|
|
58
|
+
|
|
59
|
+
expect(() => createProgram(gl, '', '')).toThrow(ShaderCompileError)
|
|
60
|
+
})
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
describe('ProgramLinkError', () => {
|
|
64
|
+
it('carries the info log as given and the GL error', () => {
|
|
65
|
+
gl.getProgramParameter = vi.fn(() => false)
|
|
66
|
+
gl.getProgramInfoLog = vi.fn(() => null)
|
|
67
|
+
gl.getError = vi.fn(() => 0)
|
|
68
|
+
|
|
69
|
+
const error = catchError(() => createProgram(gl, '', ''))
|
|
70
|
+
|
|
71
|
+
expect(error).toBeInstanceOf(ProgramLinkError)
|
|
72
|
+
expect(error).toMatchObject({
|
|
73
|
+
name: 'ProgramLinkError',
|
|
74
|
+
infoLog: null,
|
|
75
|
+
glError: 0,
|
|
76
|
+
message: 'Failed to link program: null',
|
|
77
|
+
})
|
|
78
|
+
})
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
describe('GLCreateError', () => {
|
|
82
|
+
it.each([
|
|
83
|
+
[
|
|
84
|
+
'shader',
|
|
85
|
+
() => ((gl.createShader = vi.fn(() => null)), createShader(gl, gl.VERTEX_SHADER, '')),
|
|
86
|
+
],
|
|
87
|
+
['program', () => ((gl.createProgram = vi.fn(() => null)), createProgram(gl, '', ''))],
|
|
88
|
+
[
|
|
89
|
+
'buffer',
|
|
90
|
+
() => (
|
|
91
|
+
(gl.createBuffer = vi.fn(() => null)),
|
|
92
|
+
bufferView(gl, { b_index: { target: 'ELEMENT_ARRAY_BUFFER' } })
|
|
93
|
+
),
|
|
94
|
+
],
|
|
95
|
+
[
|
|
96
|
+
'buffer',
|
|
97
|
+
() => (
|
|
98
|
+
(gl.createBuffer = vi.fn(() => null)),
|
|
99
|
+
attributeView(gl, program, { a_corner: { kind: 'vec2' } } satisfies AttributeSchema)
|
|
100
|
+
),
|
|
101
|
+
],
|
|
102
|
+
[
|
|
103
|
+
'buffer',
|
|
104
|
+
() => (
|
|
105
|
+
(gl.createBuffer = vi.fn(() => null)),
|
|
106
|
+
interleavedAttributeView(gl, program, {
|
|
107
|
+
a_instance: { layout: [{ key: 'a_position', kind: 'vec2' }] },
|
|
108
|
+
})
|
|
109
|
+
),
|
|
110
|
+
],
|
|
111
|
+
['vertexArray', () => ((gl.createVertexArray = vi.fn(() => null)), vaoView(gl, []))],
|
|
112
|
+
[
|
|
113
|
+
'texture',
|
|
114
|
+
() => ((gl.createTexture = vi.fn(() => null)), createTexture(gl, { width: 1, height: 1 })),
|
|
115
|
+
],
|
|
116
|
+
[
|
|
117
|
+
'framebuffer',
|
|
118
|
+
() => (
|
|
119
|
+
(gl.createFramebuffer = vi.fn(() => null)),
|
|
120
|
+
createFramebuffer(gl, { width: 1, height: 1, attachment: 'color' })
|
|
121
|
+
),
|
|
122
|
+
],
|
|
123
|
+
])('names the %s whose create answered null', (resource, build) => {
|
|
124
|
+
const error = catchError(build)
|
|
125
|
+
|
|
126
|
+
expect(error).toBeInstanceOf(GLCreateError)
|
|
127
|
+
expect(error).toMatchObject({
|
|
128
|
+
name: 'GLCreateError',
|
|
129
|
+
resource,
|
|
130
|
+
message: `Failed to create ${resource}`,
|
|
131
|
+
})
|
|
132
|
+
})
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
describe('AttributeNotFoundError', () => {
|
|
136
|
+
it.each([
|
|
137
|
+
[
|
|
138
|
+
'attributeView',
|
|
139
|
+
() => attributeView(gl, program, { a_missing: { kind: 'vec2' } } satisfies AttributeSchema),
|
|
140
|
+
],
|
|
141
|
+
[
|
|
142
|
+
'interleavedAttributeView',
|
|
143
|
+
() =>
|
|
144
|
+
interleavedAttributeView(gl, program, {
|
|
145
|
+
a_instance: { layout: [{ key: 'a_missing', kind: 'vec2' }] },
|
|
146
|
+
}),
|
|
147
|
+
],
|
|
148
|
+
])('names the attribute %s could not find', (_, build) => {
|
|
149
|
+
gl.getAttribLocation = vi.fn(() => -1)
|
|
150
|
+
|
|
151
|
+
const error = catchError(build)
|
|
152
|
+
|
|
153
|
+
expect(error).toBeInstanceOf(AttributeNotFoundError)
|
|
154
|
+
expect(error).toMatchObject({
|
|
155
|
+
name: 'AttributeNotFoundError',
|
|
156
|
+
attribute: 'a_missing',
|
|
157
|
+
message: "Attribute 'a_missing' not found",
|
|
158
|
+
})
|
|
159
|
+
})
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
describe('restoring the vertex array binding', () => {
|
|
163
|
+
it.each([
|
|
164
|
+
['a number', 0],
|
|
165
|
+
['undefined', undefined],
|
|
166
|
+
])('restores null when the binding reads back as %s', (_, binding) => {
|
|
167
|
+
gl.getParameter = vi.fn(() => binding)
|
|
168
|
+
gl.bindVertexArray = vi.fn((array: unknown) => {
|
|
169
|
+
if (array !== null && typeof array !== 'object') {
|
|
170
|
+
throw new TypeError("parameter 1 is not of type 'WebGLVertexArrayObject'")
|
|
171
|
+
}
|
|
172
|
+
})
|
|
173
|
+
|
|
174
|
+
const vao = vaoView(gl, [])
|
|
175
|
+
const unbind = vao.bind()
|
|
176
|
+
unbind()
|
|
177
|
+
|
|
178
|
+
expect(gl.bindVertexArray).toHaveBeenLastCalledWith(null)
|
|
179
|
+
})
|
|
180
|
+
})
|
|
181
|
+
|
|
182
|
+
function catchError(fn: () => unknown): unknown {
|
|
183
|
+
try {
|
|
184
|
+
fn()
|
|
185
|
+
} catch (error) {
|
|
186
|
+
return error
|
|
187
|
+
}
|
|
188
|
+
throw new Error('expected a throw')
|
|
189
|
+
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils.ts","../src/gl.ts"],"sourcesContent":["import type {\n AttributeKind,\n FramebufferDefinition,\n GL,\n KIND_TO_SIZE_MAP,\n KIND_TO_UNIFORM_FN_NAME_MAP,\n TextureDefinition,\n UniformKind,\n ViewOptions,\n} from './types'\n\nexport function assertedNotNullish<T>(value: T, message?: string): NonNullable<T> {\n if (value === undefined || value === null) throw new Error(message)\n return value\n}\n\n/**\n * Wraps a teardown so it runs once.\n *\n * Two reasons, and both bite. A disposer is per `bind()`, and undoing twice\n * would put back state a later `bind()` is relying on. And a `dispose()` that\n * deletes twice invalidates a handle someone else may still be holding — the\n * object survives while it is bound, so the fault surfaces later, somewhere\n * else. Idempotent is the only safe shape for either.\n */\nexport function once(teardown: () => void): () => void {\n let done = false\n return () => {\n if (done) return\n done = true\n teardown()\n }\n}\n\n/**********************************************************************************/\n/* */\n/* Kind To Uniform Name */\n/* */\n/**********************************************************************************/\n\nexport const kindToUniformFnName = <T extends UniformKind>(\n kind: T,\n): KIND_TO_UNIFORM_FN_NAME_MAP[T] => {\n switch (kind[0]) {\n // mat\n case 'm':\n return ('Matrix' + kind.slice(3) + 'fv') as KIND_TO_UNIFORM_FN_NAME_MAP[T]\n // sampler/booleans/integer\n case 's':\n case 'b':\n case 'i':\n return ((kind.match(/\\d/)?.[0] ?? '1') + 'i') as KIND_TO_UNIFORM_FN_NAME_MAP[T]\n // unsigned integers\n case 'u':\n return ((kind[4] || '1') + 'ui') as KIND_TO_UNIFORM_FN_NAME_MAP[T]\n // vec\n case 'v':\n return (kind[3] + 'f') as KIND_TO_UNIFORM_FN_NAME_MAP[T]\n default:\n switch (kind) {\n case 'float':\n return '1f' as KIND_TO_UNIFORM_FN_NAME_MAP[T]\n case 'uint':\n return '1ui' as KIND_TO_UNIFORM_FN_NAME_MAP[T]\n default:\n return '1i' as KIND_TO_UNIFORM_FN_NAME_MAP[T]\n }\n }\n}\n\n/**********************************************************************************/\n/* */\n/* Kind To Size */\n/* */\n/**********************************************************************************/\n\nexport const kindToSize = <T extends UniformKind>(kind: T): KIND_TO_SIZE_MAP[T] => {\n switch (kind[0]) {\n case 'm':\n const [a, b] = kind.match(/\\d+/g)!.map(Number) as [number, number?]\n return (a * (b ?? a)) as KIND_TO_SIZE_MAP[T]\n case 'v':\n case 'i':\n case 'b':\n case 'u':\n const match = kind.match(/\\d/) as [string] | undefined\n return (match ? +match[0] : 1) as KIND_TO_SIZE_MAP[T]\n default:\n return 1 as KIND_TO_SIZE_MAP[T]\n }\n}\n\n/**********************************************************************************/\n/* */\n/* Guards */\n/* */\n/**********************************************************************************/\n\nexport const isMatKind = <\n T extends UniformKind | AttributeKind,\n TPrefix extends string,\n TPostfix extends string,\n>(\n kind: T,\n): kind is T & `${TPrefix}mat${TPostfix}` => kind.includes('mat')\n\nexport const isSamplerKind = <TPrefix extends string, TPostfix extends string>(\n kind: UniformKind,\n): kind is UniformKind & `${TPrefix}sampler${TPostfix}` => kind.includes('sampler')\n\nexport const isVecKind = <TPrefix extends string, TPostfix extends string>(\n kind: UniformKind,\n): kind is UniformKind & `${TPrefix}vec${TPostfix}` => kind.includes('vec')\n\n/**********************************************************************************/\n/* */\n/* Create Texture */\n/* */\n/**********************************************************************************/\n\nexport function createTexture(\n gl: GL,\n {\n target = 'TEXTURE_2D',\n internalFormat = 'RGBA',\n format = 'RGBA',\n type = 'UNSIGNED_BYTE',\n minFilter = 'NEAREST',\n magFilter = 'NEAREST',\n wrapS = 'CLAMP_TO_EDGE',\n wrapT = 'CLAMP_TO_EDGE',\n width,\n height,\n }: TextureDefinition,\n data?: ArrayBufferView | null,\n { signal }: ViewOptions = {},\n): WebGLTexture {\n const texture = assertedNotNullish(gl.createTexture(), 'Failed to create texture')\n\n function getTextureConstant(name: string) {\n if (!(name in gl)) {\n throw new Error(`Attempted to create webgl2-only texture (${name}) in webgl1`)\n }\n return gl[name as keyof typeof gl] as any\n }\n\n gl.bindTexture(gl[target], texture)\n gl.texImage2D(\n gl[target],\n 0,\n getTextureConstant(internalFormat),\n width,\n height,\n 0,\n getTextureConstant(format),\n getTextureConstant(type),\n data ?? null,\n )\n\n // Set texture parameters\n gl.texParameteri(gl[target], gl.TEXTURE_MIN_FILTER, gl[minFilter])\n gl.texParameteri(gl[target], gl.TEXTURE_MAG_FILTER, gl[magFilter])\n gl.texParameteri(gl[target], gl.TEXTURE_WRAP_S, gl[wrapS])\n gl.texParameteri(gl[target], gl.TEXTURE_WRAP_T, gl[wrapT])\n\n signal?.addEventListener(\n 'abort',\n once(() => gl.deleteTexture(texture)),\n )\n\n return texture\n}\n\n/**********************************************************************************/\n/* */\n/* Create Framebuffer */\n/* */\n/**********************************************************************************/\n\nconst FRAMEBUFFER_ATTACHMENT_MAP = {\n color: 'COLOR_ATTACHMENT0',\n depth: 'DEPTH_ATTACHMENT',\n stencil: 'STENCIL_ATTACHMENT',\n depthStencil: 'DEPTH_STENCIL_ATTACHMENT',\n} as const\n\nclass FramebufferError extends Error {\n constructor(gl: GL, status: number) {\n let errorMessage = 'Framebuffer not complete. Status: '\n switch (status) {\n case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:\n errorMessage += 'FRAMEBUFFER_INCOMPLETE_ATTACHMENT'\n break\n case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:\n errorMessage += 'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'\n break\n case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:\n errorMessage += 'FRAMEBUFFER_INCOMPLETE_DIMENSIONS'\n break\n case gl.FRAMEBUFFER_UNSUPPORTED:\n errorMessage += 'FRAMEBUFFER_UNSUPPORTED'\n break\n default:\n errorMessage += `Unknown (${status})`\n }\n super(errorMessage)\n }\n}\n\nexport function createFramebuffer(\n gl: GL,\n { attachment, texture: providedTexture, ...definition }: FramebufferDefinition,\n { signal }: ViewOptions = {},\n) {\n // Create texture for the framebuffer, unless one was handed in. Which one it\n // is decides who deletes it below — the same rule the attribute buffers follow.\n const texture = providedTexture ?? createTexture(gl, definition)\n\n // Create framebuffer\n const framebuffer = assertedNotNullish(gl.createFramebuffer(), 'Failed to create framebuffer')\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer)\n\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER,\n // Determine attachment point based on attachment kind\n gl[FRAMEBUFFER_ATTACHMENT_MAP[attachment]],\n gl.TEXTURE_2D,\n texture,\n 0,\n )\n\n // Check framebuffer completeness\n const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER)\n if (status !== gl.FRAMEBUFFER_COMPLETE) {\n throw new FramebufferError(gl, status)\n }\n\n const dispose = once(() => {\n gl.deleteFramebuffer(framebuffer)\n // A texture handed in belongs to whoever made it — it commonly outlives the\n // framebuffer, ping-ponged between two of them.\n if (!providedTexture) {\n gl.deleteTexture(texture)\n }\n })\n\n signal?.addEventListener('abort', dispose)\n\n return {\n texture,\n framebuffer,\n dispose,\n }\n}\n\n/**********************************************************************************/\n/* */\n/* Create Upsert */\n/* */\n/**********************************************************************************/\n\ntype UpsertMapKind<T, U> = Map<T, U> | (T extends WeakKey ? WeakMap<T, U> : never)\n\nexport function createUpsertMap<T extends UpsertMapKind<any, any> = Map<any, any>>(\n constructor?: new () => T,\n) {\n const map = new (constructor ?? Map)() as T\n return Object.assign(map, {\n getOrInsert(\n key: T extends UpsertMapKind<infer U, any> ? U : never,\n value: T extends UpsertMapKind<any, infer U> ? () => U : never,\n ) {\n let result = map.get(key)\n if (result) {\n return result\n }\n result = value()\n map.set(key, result)\n return result\n },\n })\n}\n\nexport function forEachObject<T extends Record<string, any>>(\n value: T,\n callback: (value: T[keyof T], key: keyof T, index: number) => void,\n) {\n let index = 0\n for (const key in value) {\n callback(value[key], key, index)\n index++\n }\n for (const key of Object.getOwnPropertySymbols(value)) {\n callback(value[key as keyof T], key as keyof T, index)\n index++\n }\n}\n\nexport function mapObject<T extends Record<string, any>, TReturn>(\n value: T,\n callback: (value: T[keyof T], key: keyof T, index: number) => TReturn,\n): { [TKey in keyof T]: TReturn } {\n const result = {} as { [TKey in keyof T]: TReturn }\n\n forEachObject(value, (value, key, index) => {\n result[key] = callback(value, key, index)\n })\n\n return result\n}\n","import { RemoveSuffix } from './type-utils'\nimport type { GL, ViewOptions } from './types'\nimport { once } from './utils'\n\nfunction isWebGL2RenderingContext(\n gl: WebGLRenderingContext | WebGL2RenderingContext,\n): gl is WebGL2RenderingContext {\n return typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext\n}\n\n/**********************************************************************************/\n/* */\n/* Create Shader */\n/* */\n/**********************************************************************************/\n\nexport function createShader(gl: GL, type: number, source: string): WebGLShader {\n const shader = gl.createShader(type)\n if (!shader) throw new Error('Failed to create shader')\n\n gl.shaderSource(shader, source)\n gl.compileShader(shader)\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n const info = gl.getShaderInfoLog(shader)\n gl.deleteShader(shader)\n throw new Error(\n `Failed to compile ${type === gl.VERTEX_SHADER ? 'vertex' : 'fragment'} shader: ${info}`,\n )\n }\n\n return shader\n}\n\n/**********************************************************************************/\n/* */\n/* Create Program */\n/* */\n/**********************************************************************************/\n\nexport function createProgram(\n gl: GL,\n vertexSource: string,\n fragmentSource: string,\n { signal }: ViewOptions = {},\n): WebGLProgram {\n const program = gl.createProgram()\n if (!program) throw new Error('Failed to create WebGL program')\n\n const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexSource)\n const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentSource)\n\n gl.attachShader(program, vertexShader)\n gl.attachShader(program, fragmentShader)\n gl.linkProgram(program)\n\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n const info = gl.getProgramInfoLog(program)\n gl.deleteProgram(program)\n gl.deleteShader(vertexShader)\n gl.deleteShader(fragmentShader)\n throw new Error(`Failed to link program: ${info}`)\n }\n\n // Clean up shaders after linking\n gl.deleteShader(vertexShader)\n gl.deleteShader(fragmentShader)\n\n signal?.addEventListener(\n 'abort',\n once(() => gl.deleteProgram(program)),\n )\n\n return program\n}\n\n/**********************************************************************************/\n/* */\n/* Get Instanced Arrays */\n/* */\n/**********************************************************************************/\n\nconst INSTANCED_ARRAYS_WRAPPER_MAP = new WeakMap<\n GL,\n RemoveSuffix<\n Pick<\n ANGLE_instanced_arrays,\n 'drawArraysInstancedANGLE' | 'drawElementsInstancedANGLE' | 'vertexAttribDivisorANGLE'\n >,\n 'ANGLE'\n > | null\n>()\nexport function getInstancedArrays(gl: GL) {\n if (isWebGL2RenderingContext(gl)) return gl\n\n const cached = INSTANCED_ARRAYS_WRAPPER_MAP.get(gl)\n if (cached) return cached\n\n const ext = gl.getExtension('ANGLE_instanced_arrays')\n if (!ext) return undefined\n\n const wrapper = {\n drawArraysInstanced: ext.drawArraysInstancedANGLE.bind(ext),\n drawElementsInstanced: ext.drawElementsInstancedANGLE.bind(ext),\n vertexAttribDivisor: ext.vertexAttribDivisorANGLE.bind(ext),\n }\n INSTANCED_ARRAYS_WRAPPER_MAP.set(gl, wrapper)\n\n return wrapper\n}\n\n/**********************************************************************************/\n/* */\n/* Get Vertex Array Object */\n/* */\n/**********************************************************************************/\n\nconst VERTEX_ARRAY_OBJECT_WRAPPER_MAP = new WeakMap<\n GL,\n RemoveSuffix<\n Pick<\n OES_vertex_array_object,\n 'bindVertexArrayOES' | 'createVertexArrayOES' | 'deleteVertexArrayOES'\n >,\n 'OES'\n > | null\n>()\nexport function getVertexArrayObject(gl: GL) {\n if (isWebGL2RenderingContext(gl)) return gl\n\n const cached = VERTEX_ARRAY_OBJECT_WRAPPER_MAP.get(gl)\n if (cached) return cached\n\n const ext = gl.getExtension('OES_vertex_array_object')\n if (!ext) return null\n\n const wrapper = {\n bindVertexArray: ext.bindVertexArrayOES.bind(ext),\n createVertexArray: ext.createVertexArrayOES.bind(ext),\n deleteVertexArray: ext.deleteVertexArrayOES.bind(ext),\n }\n VERTEX_ARRAY_OBJECT_WRAPPER_MAP.set(gl, wrapper)\n\n return wrapper\n}\n"],"mappings":";AAWO,SAAS,mBAAsB,OAAU,SAAkC;AAChF,MAAI,UAAU,UAAa,UAAU,KAAM,OAAM,IAAI,MAAM,OAAO;AAClE,SAAO;AACT;AAWO,SAAS,KAAK,UAAkC;AACrD,MAAI,OAAO;AACX,SAAO,MAAM;AACX,QAAI,KAAM;AACV,WAAO;AACP,aAAS;AAAA,EACX;AACF;AAQO,IAAM,sBAAsB,CACjC,SACmC;AACnC,UAAQ,KAAK,CAAC,GAAG;AAAA;AAAA,IAEf,KAAK;AACH,aAAQ,WAAW,KAAK,MAAM,CAAC,IAAI;AAAA;AAAA,IAErC,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,cAAS,KAAK,MAAM,IAAI,IAAI,CAAC,KAAK,OAAO;AAAA;AAAA,IAE3C,KAAK;AACH,cAAS,KAAK,CAAC,KAAK,OAAO;AAAA;AAAA,IAE7B,KAAK;AACH,aAAQ,KAAK,CAAC,IAAI;AAAA,IACpB;AACE,cAAQ,MAAM;AAAA,QACZ,KAAK;AACH,iBAAO;AAAA,QACT,KAAK;AACH,iBAAO;AAAA,QACT;AACE,iBAAO;AAAA,MACX;AAAA,EACJ;AACF;AAQO,IAAM,aAAa,CAAwB,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qBAAqB,IAAI,yBAAyB,KAAK,GAAG;AAAA,EAC5D;AACA,+BAA6B,IAAI,IAAI,OAAO;AAE5C,SAAO;AACT;AAQA,IAAM,kCAAkC,oBAAI,QAS1C;AACK,SAAS,qBAAqB,IAAQ;AAC3C,MAAI,yBAAyB,EAAE,EAAG,QAAO;AAEzC,QAAM,SAAS,gCAAgC,IAAI,EAAE;AACrD,MAAI,OAAQ,QAAO;AAEnB,QAAM,MAAM,GAAG,aAAa,yBAAyB;AACrD,MAAI,CAAC,IAAK,QAAO;AAEjB,QAAM,UAAU;AAAA,IACd,iBAAiB,IAAI,mBAAmB,KAAK,GAAG;AAAA,IAChD,mBAAmB,IAAI,qBAAqB,KAAK,GAAG;AAAA,IACpD,mBAAmB,IAAI,qBAAqB,KAAK,GAAG;AAAA,EACtD;AACA,kCAAgC,IAAI,IAAI,OAAO;AAE/C,SAAO;AACT;","names":["value"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { getInstancedArrays, getVertexArrayObject } from './gl'\nimport type {\n AttributeFormat,\n AttributeKind,\n AttributeMethods,\n AttributeSchema,\n AttributeView,\n BufferSchema,\n BufferView,\n GL,\n UniformView as InferUniformView,\n GLUsage,\n InterleavedAttributeLayout,\n InterleavedAttributeMethods,\n InterleavedAttributeSchema,\n InterleavedAttributeView,\n UniformSchema,\n VertexArrayMethods,\n VertexArrayParticipant,\n View,\n ViewOptions,\n ViewSchema,\n} from './types'\nimport {\n isSamplerKind,\n kindToUniformFnName,\n isMatKind,\n assertedNotNullish,\n kindToSize,\n forEachObject,\n once,\n} from './utils'\nimport { createUpsertMap, mapObject } from './utils'\nexport * from './types'\n// Documented under Utils but reachable from nowhere until now: utils is not a\n// build entry, and named rather than star so the internal helpers stay internal.\nexport { createFramebuffer, createTexture } from './utils'\n\n/**********************************************************************************/\n/* */\n/* To ID */\n/* */\n/**********************************************************************************/\n\nlet index = 0\nconst PREFIX = 'VIEW_GL_ALIAS'\n// Firefox has currently a bug where it can not handle symbol as WeakRef / key for WeakMap\n// see https://bugzilla.mozilla.org/show_bug.cgi?id=1710433\nconst HAS_WEAK_SYMBOL = (() => {\n try {\n const symbol = Symbol()\n new WeakMap().set(symbol, '')\n return true\n } catch {\n return false\n }\n})()\n// NOTE: fallback to Map will currently cause a minor memory leak.\nconst SYMBOL_MAP = createUpsertMap(HAS_WEAK_SYMBOL ? WeakMap<symbol, string> : Map<symbol, string>)\n\nexport function toID(key: string | number | symbol) {\n if (typeof key === 'string') {\n return key\n }\n if (typeof key === 'symbol') {\n return SYMBOL_MAP.getOrInsert(key, () => `${PREFIX}_${index++}`)\n }\n return key.toString()\n}\n\n/**********************************************************************************/\n/* */\n/* View */\n/* */\n/**********************************************************************************/\n\nexport function view<TSchema extends ViewSchema>(\n gl: GL,\n program: WebGLProgram,\n schema: TSchema,\n { signal }: ViewOptions = {},\n): View<TSchema> {\n // The sub-views are built without the signal and the view wires disposal\n // once, so that `dispose()` and aborting do the same thing rather than each\n // doing half of it.\n const attributes = !schema.attributes ? undefined : attributeView(gl, program, schema.attributes)\n const interleavedAttributes = !schema.interleavedAttributes\n ? undefined\n : interleavedAttributeView(gl, program, schema.interleavedAttributes)\n // Owned by the view, on the view's signal. This is the line the split was\n // really about: it used to read `bufferView(gl, schema.buffers)` with the\n // options dropped, so a view's buffers were the only resources that still\n // needed disposing by hand. That was a missing argument rather than a wrong\n // model — a buffer whose lifetime IS the view's belongs with it.\n const buffers = !schema.buffers ? undefined : bufferView(gl, schema.buffers)\n\n // Vertex arrays are made on demand rather than declared, so they are the one\n // thing the view cannot dispose from the schema alone. Held until disposed —\n // by the view or by the caller — and dropped either way, so a view that hands\n // out an array per frame does not accumulate them.\n const vertexArrays = new Set<VertexArrayMethods>()\n\n const dispose = once(() => {\n if (attributes) forEachObject(attributes, value => value.dispose())\n if (interleavedAttributes) forEachObject(interleavedAttributes, value => value.dispose())\n if (buffers) forEachObject(buffers, value => value.dispose())\n vertexArrays.forEach(vertexArray => vertexArray.dispose())\n vertexArrays.clear()\n })\n\n signal?.addEventListener('abort', dispose)\n\n return {\n uniforms: !schema.uniforms ? undefined : uniformView(gl, program, schema.uniforms),\n attributes,\n interleavedAttributes,\n buffers,\n vao(participants: VertexArrayParticipant[]) {\n const vertexArray = vaoView(gl, participants)\n vertexArrays.add(vertexArray)\n return {\n ...vertexArray,\n dispose: once(() => {\n vertexArrays.delete(vertexArray)\n vertexArray.dispose()\n }),\n }\n },\n dispose,\n } as View<TSchema>\n}\n\n/**********************************************************************************/\n/* */\n/* Vertex Array */\n/* */\n/**********************************************************************************/\n\n/**\n * Bind the default vertex array, returning a disposer that puts the previous\n * one back. The pointer calls name no destination, so anything applied without\n * a vertex array of its own has to say which one it means — and a vertex array\n * keeps what it is given, so writing into a caller's array by accident would\n * outlive the call that did it.\n */\nfunction bindDefaultVertexArray(gl: GL): () => void {\n const feature = getVertexArrayObject(gl)\n if (!feature) {\n return () => {}\n }\n const previous = gl.getParameter(VERTEX_ARRAY_BINDING) as WebGLVertexArrayObject | null\n feature.bindVertexArray(null)\n return () => feature.bindVertexArray(previous)\n}\n\n/**\n * A vertex array over the participants one draw needs.\n *\n * Where the context has vertex arrays, each participant writes itself in once,\n * here, and `bind()` is a single `bindVertexArray`. Where it does not — WebGL1\n * without `OES_vertex_array_object` — there is nowhere to keep the state, so\n * `bind()` re-applies every participant and the disposer puts back what they\n * displaced. Same contract, and the emulation is why the name still fits.\n */\nexport function vaoView(\n gl: GL,\n participants: VertexArrayParticipant[],\n { signal }: ViewOptions = {},\n): VertexArrayMethods {\n const feature = getVertexArrayObject(gl)\n\n const methods: VertexArrayMethods = !feature\n ? {\n bind() {\n const restores = participants.map(participant => participant.applyToVertexArray())\n participants.forEach(participant => participant.applyToContext?.())\n return once(() => restores.forEach(restore => restore()))\n },\n unbind() {},\n dispose() {},\n }\n : (() => {\n const vertexArray = assertedNotNullish(feature.createVertexArray())\n const previous = gl.getParameter(VERTEX_ARRAY_BINDING) as WebGLVertexArrayObject | null\n feature.bindVertexArray(vertexArray)\n // Discarding the restorers is the point: the state lives in this array\n // now, and the array is thrown away whole.\n for (const participant of participants) {\n participant.applyToVertexArray()\n }\n feature.bindVertexArray(previous)\n\n return {\n bind() {\n const previousVertexArray = gl.getParameter(\n VERTEX_ARRAY_BINDING,\n ) as WebGLVertexArrayObject | null\n feature.bindVertexArray(vertexArray)\n // Context state the array cannot hold — see applyToContext.\n participants.forEach(participant => participant.applyToContext?.())\n return once(() => feature.bindVertexArray(previousVertexArray))\n },\n unbind() {\n feature.bindVertexArray(null)\n },\n dispose: once(() => feature.deleteVertexArray(vertexArray)),\n }\n })()\n\n signal?.addEventListener('abort', () => methods.dispose())\n\n return methods\n}\n\n/**********************************************************************************/\n/* */\n/* Uniform View */\n/* */\n/**********************************************************************************/\n\nexport function uniformView<T extends UniformSchema>(\n gl: GL,\n program: WebGLProgram,\n schema: T,\n): InferUniformView<T> {\n // @ts-expect-error - conditional return type based on size is hard to infer\n return mapObject(schema, ({ kind, size }, key) => {\n const name = toID(key)\n\n if (isSamplerKind(kind)) {\n const location = gl.getUniformLocation(program, name)\n return {\n set(arg: number) {\n gl.uniform1i(location, arg)\n },\n }\n }\n\n // Array uniform - support both bulk set and indexed access\n if (size) {\n const bulkFnName = `uniform${kindToUniformFnName(kind)}v`\n // @ts-ignore FIX WEBGL/WEBGL2 TYPES\n const bulkFn = gl[bulkFnName].bind(gl)\n const bulkLocation = gl.getUniformLocation(program, name)\n\n const elementFnName = `uniform${kindToUniformFnName(kind)}`\n // @ts-ignore FIX WEBGL/WEBGL2 TYPES\n const elementFn = gl[elementFnName].bind(gl)\n\n // Build array of element setters\n const elements: Array<{ set(...args: any[]): void }> = []\n for (let i = 0; i < size; i++) {\n const location = gl.getUniformLocation(program, `${name}[${i}]`)\n elements[i] = {\n set(...args: any[]) {\n elementFn(location, ...args)\n },\n }\n }\n\n // Return array-like object with bulk set\n return Object.assign(elements, {\n set(arg: Float32Array) {\n bulkFn(bulkLocation, arg)\n },\n })\n }\n\n // Non-array uniform\n const location = gl.getUniformLocation(program, name)\n const fnName = `uniform${kindToUniformFnName(kind)}`\n\n // @ts-ignore FIX WEBGL/WEBGL2 TYPES\n const fn = gl[fnName].bind(gl)\n\n if (isMatKind(kind)) {\n return {\n set(...args: any[]) {\n fn(location, false, args[0])\n },\n }\n }\n\n return {\n set(...args: any[]) {\n fn(location, ...args)\n },\n }\n })\n}\n\n/**********************************************************************************/\n/* */\n/* Attribute View */\n/* */\n/**********************************************************************************/\n\ntype GLType =\n | 'FLOAT'\n | 'INT'\n | 'UNSIGNED_INT'\n | 'SHORT'\n | 'UNSIGNED_SHORT'\n | 'BYTE'\n | 'UNSIGNED_BYTE'\n\nconst FORMAT_TO_GL_TYPE: Record<AttributeFormat, GLType> = {\n float32: 'FLOAT',\n int32: 'INT',\n uint32: 'UNSIGNED_INT',\n int16: 'SHORT',\n uint16: 'UNSIGNED_SHORT',\n int8: 'BYTE',\n uint8: 'UNSIGNED_BYTE',\n}\n\nconst FORMAT_BYTE_SIZE: Record<AttributeFormat, number> = {\n float32: 4,\n int32: 4,\n uint32: 4,\n int16: 2,\n uint16: 2,\n int8: 1,\n uint8: 1,\n}\n\nfunction defaultFormat(kind: AttributeKind): AttributeFormat {\n if (kind.startsWith('u')) return 'uint32'\n if (kind.startsWith('i')) return 'int32'\n return 'float32'\n}\n\n// Shared attribute helper functions\n// between attributeView and interleavedAttributeView\nfunction handleAttribute(\n gl: GL,\n location: number,\n size: number,\n stride: number,\n offset: number,\n glType: GLType,\n isIntegerKind: boolean,\n normalized: boolean,\n instanced?: boolean,\n) {\n gl.enableVertexAttribArray(location)\n if (isIntegerKind) {\n ;(gl as WebGL2RenderingContext).vertexAttribIPointer(location, size, gl[glType], stride, offset)\n } else {\n gl.vertexAttribPointer(location, size, gl[glType], normalized, stride, offset)\n }\n\n // Always stated, never inherited: the divisor belongs to the location rather\n // than to the program, so a location left at 1 by an earlier instanced\n // attribute would feed one value to every vertex here.\n // Get instanced-arrays-feature: extension if webgl, gl if webgl2\n const instancedArrays = getInstancedArrays(gl)\n if (instanced) {\n assertedNotNullish(instancedArrays).vertexAttribDivisor(location, 1)\n } else if (instancedArrays) {\n instancedArrays.vertexAttribDivisor(location, 0)\n }\n}\n\n// Same enum in webgl2 and in the webgl1 extensions, which expose no constants\nconst VERTEX_ATTRIB_ARRAY_DIVISOR = 0x88fe\nconst VERTEX_ARRAY_BINDING = 0x85b5\n\n// Reads the divisor currently attached to a location, 0 where instancing is\n// unavailable and nothing can have set one\nfunction readDivisor(gl: GL, location: number): number {\n return getInstancedArrays(gl)\n ? (gl.getVertexAttrib(location, VERTEX_ATTRIB_ARRAY_DIVISOR) as number)\n : 0\n}\n\nexport function attributeView<T extends AttributeSchema>(\n gl: GL,\n program: WebGLProgram,\n schema: T,\n { signal }: ViewOptions = {},\n): AttributeView<T> {\n const attributes = mapObject(\n schema,\n (\n { kind, format, normalized = false, instanced, buffer: providedBuffer },\n key,\n ): AttributeMethods => {\n const name = toID(key)\n\n // Whoever made the buffer deletes it. A schema can name a buffer that\n // belongs to another view — the quad `compile.toQuad` shares across every\n // program on a context, an attribute two programs step over — and\n // deleting one of those would take it out from under its owner.\n const buffer = providedBuffer ?? assertedNotNullish(gl.createBuffer())\n\n const location = gl.getAttribLocation(program, name)\n if (location < 0) {\n throw new Error(`Attribute '${name}' not found`)\n }\n\n const size = kindToSize(kind)\n const resolvedFormat = format ?? defaultFormat(kind)\n const glType = FORMAT_TO_GL_TYPE[resolvedFormat]\n const isIntKind = kind.startsWith('i') || kind.startsWith('u')\n\n function applyToVertexArray() {\n // Snapshot before the change, restore in the disposer\n const previousDivisor = readDivisor(gl, location)\n // vertexAttribPointer captures whatever is bound to ARRAY_BUFFER when\n // it runs, so this binding is the setup for the pointer, not a lasting\n // part of the vertex array's state.\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n handleAttribute(gl, location, size, 0, 0, glType, isIntKind, normalized, instanced)\n return once(() => {\n getInstancedArrays(gl)?.vertexAttribDivisor(location, previousDivisor)\n })\n }\n\n return {\n buffer,\n applyToVertexArray,\n bind() {\n const restoreVertexArray = bindDefaultVertexArray(gl)\n const restore = applyToVertexArray()\n return once(() => {\n restore()\n restoreVertexArray()\n })\n },\n dispose: once(() => {\n if (!providedBuffer) {\n gl.deleteBuffer(buffer)\n }\n }),\n set(data, usage = 'STATIC_DRAW') {\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n gl.bufferData(gl.ARRAY_BUFFER, data, gl[usage])\n return this\n },\n }\n },\n )\n\n signal?.addEventListener('abort', function dispose() {\n forEachObject(attributes, value => value.dispose())\n })\n\n return attributes\n}\n\n/**********************************************************************************/\n/* */\n/* Interleaved Attribute View */\n/* */\n/**********************************************************************************/\n\n/**\n * The other place an attribute's value can come from: not a buffer, but the\n * context's current generic vertex attribute values, which an attribute reads\n * for every vertex when its array is disabled.\n *\n * A constant is a uniform in all but name — one value for the whole draw, set\n * by a function chosen from the kind — so it gets the setters a uniform gets,\n * off the same layout the buffer source uses.\n *\n * `vertexAttrib*` tops out at four floats and has no matrix form, so a layout\n * key that is fine in a buffer can be impossible as a constant. That is a hard\n * limit of the API rather than a choice, and it is worth saying so out loud at\n * the point someone reaches for it.\n */\nfunction constantSource(gl: GL, layout: InterleavedAttributeLayout[], locations: number[]) {\n const setters = layout.map((entry, index) => {\n const size = kindToSize(entry.kind)\n const name = toID(entry.key)\n if (isMatKind(entry.kind) || size > 4) {\n throw new Error(\n `'${name}' is a ${entry.kind}, which cannot be a constant attribute: vertexAttrib* takes at most 4 floats and has no matrix form. Use the buffer source for it.`,\n )\n }\n // The values are context state, not vertex-array state, so they are held\n // here and written again on every bind — see applyToContext.\n let values: number[] = []\n const fn = gl[`vertexAttrib${size as 1 | 2 | 3 | 4}f`].bind(gl)\n return {\n name,\n location: locations[index]!,\n write: () => {\n if (values.length) {\n ;(fn as (location: number, ...args: number[]) => void)(locations[index]!, ...values)\n }\n },\n methods: {\n set(...args: number[]) {\n values = args\n },\n },\n }\n })\n\n return Object.assign(Object.fromEntries(setters.map(setter => [setter.name, setter.methods])), {\n applyToVertexArray() {\n const restores = setters.map(({ location }) => {\n const wasEnabled = gl.getVertexAttrib(location, gl.VERTEX_ATTRIB_ARRAY_ENABLED) as boolean\n gl.disableVertexAttribArray(location)\n return () => (wasEnabled ? gl.enableVertexAttribArray(location) : undefined)\n })\n return once(() => restores.forEach(restore => restore()))\n },\n applyToContext() {\n setters.forEach(setter => setter.write())\n },\n bind() {\n const restoreVertexArray = bindDefaultVertexArray(gl)\n const restore = this.applyToVertexArray()\n this.applyToContext()\n return once(() => {\n restore()\n restoreVertexArray()\n })\n },\n })\n}\n\nexport function interleavedAttributeView<T extends InterleavedAttributeSchema>(\n gl: GL,\n program: WebGLProgram,\n schema: T,\n { signal }: ViewOptions = {},\n): InterleavedAttributeView<T> {\n // Initialize interleaved attributes\n const interleavedAttributes = mapObject(schema, ({ layout }) => {\n // Increment number to keep track of offset\n let index = 0\n\n // Calculate layout information\n const locations: number[] = []\n const handles = layout.map(layout => {\n const name = toID(layout.key)\n\n const location = gl.getAttribLocation(program, name)\n\n if (location < 0) {\n throw new Error(`Attribute '${name}' not found`)\n }\n\n locations.push(location)\n\n const size = kindToSize(layout.kind)\n const offset = index\n const resolvedFormat = layout.format ?? defaultFormat(layout.kind)\n const glType = FORMAT_TO_GL_TYPE[resolvedFormat]\n const isIntKind = layout.kind.startsWith('i') || layout.kind.startsWith('u')\n const normalized = layout.normalized ?? false\n index += size * FORMAT_BYTE_SIZE[resolvedFormat]\n\n return (divisor: 0 | 1) =>\n handleAttribute(\n gl,\n location,\n size,\n stride,\n offset,\n glType,\n isIntKind,\n normalized,\n divisor === 1,\n )\n })\n\n // Set stride to final index\n const stride = index\n\n // Create a buffer\n const buffer = assertedNotNullish(gl.createBuffer())\n\n // This layout used to create a vertex array of its own, here, which is why\n // the other participants in a draw had to be bound after it to be included\n // — the array they landed in was whichever one happened to be current.\n // Arrays are `vao()`'s job now; a layout is a layout and a buffer.\n function applyToVertexArray(divisor: 0 | 1) {\n const previousDivisors = locations.map(\n location => [location, readDivisor(gl, location)] as const,\n )\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n for (const handle of handles) {\n handle(divisor)\n }\n return once(() => {\n const instancedArrays = getInstancedArrays(gl)\n previousDivisors.forEach(([location, previous]) => {\n instancedArrays?.vertexAttribDivisor(location, previous)\n })\n })\n }\n\n let constant: ReturnType<typeof constantSource> | undefined\n\n /** One layout, one buffer, but a divisor per draw rather than per schema. */\n function bufferSource(divisor: 0 | 1) {\n const apply = () => applyToVertexArray(divisor)\n return {\n applyToVertexArray: apply,\n bind() {\n const restoreVertexArray = bindDefaultVertexArray(gl)\n const restore = apply()\n return once(() => {\n restore()\n restoreVertexArray()\n })\n },\n }\n }\n\n return {\n buffer: Object.assign(bufferSource(0), {\n /** The same buffer, stepped once per instance instead of once per vertex. */\n perInstance: bufferSource(1),\n set(value: Float32Array, usage: GLUsage = 'STATIC_DRAW') {\n // Uploading is storage, not binding: ARRAY_BUFFER is not vertex-array\n // state, so this touches no array, whichever one is bound.\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n gl.bufferData(gl.ARRAY_BUFFER, value, gl[usage])\n },\n allocate(length: number, usage: GLUsage = 'STATIC_DRAW') {\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n gl.bufferData(gl.ARRAY_BUFFER, length * Float32Array.BYTES_PER_ELEMENT, gl[usage])\n },\n write(data: Float32Array, offset: number) {\n gl.bindBuffer(gl.ARRAY_BUFFER, buffer)\n gl.bufferSubData(gl.ARRAY_BUFFER, offset * Float32Array.BYTES_PER_ELEMENT, data)\n },\n }),\n // Lazy: a layout key can be perfectly good in a buffer and impossible as\n // a constant, and finding that out should wait until someone asks for one.\n get constant() {\n return (constant ??= constantSource(gl, layout, locations))\n },\n dispose: once(() => gl.deleteBuffer(buffer)),\n } satisfies InterleavedAttributeMethods\n })\n\n signal?.addEventListener('abort', function dispose() {\n forEachObject(interleavedAttributes, value => value.dispose())\n })\n\n return interleavedAttributes\n}\n\n/**********************************************************************************/\n/* */\n/* Buffer View */\n/* */\n/**********************************************************************************/\n\nexport function bufferView<T extends BufferSchema>(\n gl: GL,\n schema: T,\n { signal }: ViewOptions = {},\n): BufferView<T> {\n // Initialize buffers\n const buffers = mapObject(schema, ({ target = 'ARRAY_BUFFER', usage = 'STATIC_DRAW' }) => {\n const buffer = assertedNotNullish(gl.createBuffer())\n\n function applyToVertexArray() {\n // Snapshot before the change, restore in the disposer. Restoring the\n // previous buffer rather than null matters for ELEMENT_ARRAY_BUFFER,\n // whose binding is recorded in the bound vertex array: clearing it\n // would strip the index buffer from an array the caller may not own.\n const previousBuffer = gl.getParameter(gl[`${target}_BINDING`]) as WebGLBuffer | null\n gl.bindBuffer(gl[target], buffer)\n return once(() => {\n gl.bindBuffer(gl[target], previousBuffer)\n })\n }\n\n return {\n applyToVertexArray,\n bind() {\n // ELEMENT_ARRAY_BUFFER's binding belongs to the bound vertex array, so\n // like the attributes this has to say which array it means. ARRAY_BUFFER\n // is context state and unaffected either way.\n const restoreVertexArray = bindDefaultVertexArray(gl)\n const restore = applyToVertexArray()\n return once(() => {\n restore()\n restoreVertexArray()\n })\n },\n dispose: once(() => gl.deleteBuffer(buffer)),\n set(data: Float32Array) {\n gl.bindBuffer(gl[target], buffer)\n gl.bufferData(gl[target], data, gl[usage])\n },\n }\n })\n\n signal?.addEventListener('abort', function dispose() {\n forEachObject(buffers, value => value.dispose())\n })\n\n return buffers\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4CA,IAAI,QAAQ;AACZ,IAAM,SAAS;AAGf,IAAM,mBAAmB,MAAM;AAC7B,MAAI;AACF,UAAM,SAAS,OAAO;AACtB,yBAAI,QAAQ,GAAE,IAAI,QAAQ,EAAE;AAC5B,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF,GAAG;AAEH,IAAM,aAAa,gBAAgB,kBAAkB,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