@bigmistqke/view.gl 0.1.13 → 0.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/.claude/settings.local.json +4 -9
  2. package/.vscode/settings.json +2 -0
  3. package/dist/{chunk-Z4F7UTKN.mjs → chunk-4YLGYQ3G.mjs} +36 -111
  4. package/dist/chunk-4YLGYQ3G.mjs.map +1 -0
  5. package/dist/chunk-BZU5QEWD.mjs +72 -0
  6. package/dist/chunk-BZU5QEWD.mjs.map +1 -0
  7. package/dist/gl.d.mts +12 -0
  8. package/dist/gl.mjs +13 -0
  9. package/dist/gl.mjs.map +1 -0
  10. package/dist/index.d.mts +2 -2
  11. package/dist/index.mjs +2 -1
  12. package/dist/tag.d.mts +1 -1
  13. package/dist/tag.mjs +4 -2
  14. package/dist/tag.mjs.map +1 -1
  15. package/dist/{types-Cggy6Gkm.d.mts → types-lm9fTTy8.d.mts} +4 -1
  16. package/package.json +5 -1
  17. package/src/gl.ts +128 -0
  18. package/src/index.ts +11 -19
  19. package/src/tag.ts +2 -1
  20. package/src/{utils/index.ts → utils.ts} +29 -47
  21. package/tsup.config.ts +1 -1
  22. package/dev/dist/404.html +0 -19
  23. package/dev/dist/assets/bezier-DuLTb2d1.js +0 -294
  24. package/dev/dist/assets/game_of_life-D7qHdFcv.js +0 -202
  25. package/dev/dist/assets/grid-Ie22U_9K.js +0 -173
  26. package/dev/dist/assets/index-0qrXMlfv.js +0 -109
  27. package/dev/dist/assets/index-C2N3u8wj.css +0 -12
  28. package/dev/dist/assets/main-BZ1N6pp6.js +0 -32
  29. package/dev/dist/assets/overview-DAxtMIw5.js +0 -78
  30. package/dev/dist/assets/pix_sim-DIhzM_vu.js +0 -501
  31. package/dev/dist/assets/symbol-BouRL-Ni.js +0 -65
  32. package/dev/dist/assets/tag-C_bg62fD.js +0 -516
  33. package/dev/dist/assets/tetris-IMnkSi9p.js +0 -344
  34. package/dev/dist/assets/utils-CvCgsM08.js +0 -50
  35. package/dev/dist/index.html +0 -51
  36. package/dist/chunk-Z4F7UTKN.mjs.map +0 -1
  37. package/src/features.ts +0 -60
  38. package/src/utils/object.ts +0 -27
@@ -1,202 +0,0 @@
1
- import { b as createFramebuffer, a as attribute, g as glsl, u as uniform, c as compile, v as view } from './tag-C_bg62fD.js';
2
-
3
- let playing = false;
4
- const canvas = document.createElement("canvas");
5
- const gl = canvas.getContext("webgl", { antialias: false });
6
- if (!gl) {
7
- throw new Error("WebGL not supported");
8
- }
9
- document.body.append(canvas);
10
- function spray() {
11
- return Math.floor(Math.random() * 8) * (Math.random() < 0.5 ? 1 : -1);
12
- }
13
- canvas.addEventListener("mousedown", (event) => {
14
- const rect = canvas.getBoundingClientRect();
15
- const controller = new AbortController();
16
- playing = false;
17
- window.addEventListener(
18
- "mousemove",
19
- (event2) => {
20
- const x = Math.floor((event2.clientX - rect.left - spray()) * (canvas.width / rect.width));
21
- const y = Math.floor((rect.bottom - event2.clientY - spray()) * (canvas.height / rect.height));
22
- const dimensions = [2, 2];
23
- const data = new Uint8Array(
24
- function* () {
25
- for (let i = 0; i < dimensions[0] * dimensions[1]; i++) {
26
- yield 255;
27
- yield 0;
28
- yield 0;
29
- yield 255;
30
- }
31
- }()
32
- );
33
- gl.bindTexture(gl.TEXTURE_2D, read.texture);
34
- gl.texSubImage2D(
35
- gl.TEXTURE_2D,
36
- 0,
37
- x,
38
- y,
39
- dimensions[0],
40
- dimensions[1],
41
- gl.RGBA,
42
- gl.UNSIGNED_BYTE,
43
- data
44
- );
45
- gl.bindTexture(gl.TEXTURE_2D, write.texture);
46
- gl.texSubImage2D(
47
- gl.TEXTURE_2D,
48
- 0,
49
- x,
50
- y,
51
- dimensions[0],
52
- dimensions[1],
53
- gl.RGBA,
54
- gl.UNSIGNED_BYTE,
55
- data
56
- );
57
- render();
58
- },
59
- controller
60
- );
61
- window.addEventListener(
62
- "mouseup",
63
- () => {
64
- controller.abort();
65
- playing = true;
66
- animate();
67
- },
68
- controller
69
- );
70
- });
71
- canvas.width = 256 * 2;
72
- canvas.height = 256 * 2;
73
- const WIDTH = canvas.width;
74
- const HEIGHT = canvas.height;
75
- const vertex = glsl`
76
- ${attribute.vec2("a_vertex")}
77
- varying vec2 v_uv;
78
- void main() {
79
- v_uv = a_vertex * 0.5 + 0.5;
80
- gl_Position = vec4(a_vertex, 0, 1);
81
- }
82
- `;
83
- const stepFragment = glsl`
84
- precision mediump float;
85
- varying vec2 v_uv;
86
- ${uniform.sampler2D("u_texture")}
87
- ${uniform.vec2("u_texelSize")}
88
-
89
- int getCell(vec2 uv) {
90
- // Wrap around (toroidal)
91
- uv = mod(uv, 1.0);
92
- float val = texture2D(u_texture, uv).r;
93
- return int(step(0.5, val));
94
- }
95
-
96
- void main() {
97
- int sum = 0;
98
- // Iterate neighbors -1,0,1
99
- for (int y = -1; y <= 1; y++) {
100
- for (int x = -1; x <= 1; x++) {
101
- if (x == 0 && y == 0) continue;
102
- sum += getCell(v_uv + vec2(float(x), float(y)) * u_texelSize);
103
- }
104
- }
105
- int current = getCell(v_uv);
106
-
107
- int nextState = 0;
108
- if (current == 1) {
109
- if (sum == 2 || sum == 3) nextState = 1;
110
- else nextState = 0;
111
- } else {
112
- if (sum == 3) nextState = 1;
113
- else nextState = 0;
114
- }
115
-
116
- gl_FragColor = vec4(float(nextState), 0.0, 0.0, 1.0);
117
- }`;
118
- const renderFragment = glsl`
119
- precision mediump float;
120
- varying vec2 v_uv;
121
- ${uniform.sampler2D("u_texture")}
122
-
123
- void main() {
124
- float cell = texture2D(u_texture, v_uv).r;
125
- gl_FragColor = vec4(vec3(cell), 1.0);
126
- }`;
127
- const { program: stepProgram, schema: stepSchema } = compile(gl, vertex, stepFragment);
128
- const stepView = view(gl, stepProgram, stepSchema);
129
- const { program: renderProgram, schema: renderSchema } = compile(gl, vertex, renderFragment);
130
- const renderView = view(gl, renderProgram, {
131
- ...renderSchema,
132
- attributes: {
133
- ...renderSchema.attributes,
134
- a_vertex: {
135
- ...renderSchema.attributes.a_vertex,
136
- buffer: stepView.attributes.a_vertex.buffer
137
- }
138
- }
139
- });
140
- stepView.attributes.a_vertex.set(new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]));
141
- const framebufferOptions = {
142
- attachment: "color",
143
- width: WIDTH,
144
- height: HEIGHT,
145
- type: "UNSIGNED_BYTE",
146
- magFilter: "NEAREST",
147
- minFilter: "NEAREST"
148
- };
149
- let read = createFramebuffer(gl, framebufferOptions);
150
- let write = createFramebuffer(gl, framebufferOptions);
151
- gl.bindTexture(gl.TEXTURE_2D, read.texture);
152
- gl.texSubImage2D(
153
- gl.TEXTURE_2D,
154
- 0,
155
- 0,
156
- 0,
157
- WIDTH,
158
- HEIGHT,
159
- gl.RGBA,
160
- gl.UNSIGNED_BYTE,
161
- new Uint8Array(
162
- function* () {
163
- for (let i = 0; i < WIDTH * HEIGHT; i++) {
164
- yield 0;
165
- yield 0;
166
- yield 0;
167
- yield 255;
168
- }
169
- }()
170
- )
171
- );
172
- function step() {
173
- gl.bindFramebuffer(gl.FRAMEBUFFER, write.framebuffer);
174
- gl.viewport(0, 0, WIDTH, HEIGHT);
175
- gl.useProgram(stepProgram);
176
- gl.activeTexture(gl.TEXTURE0);
177
- gl.bindTexture(gl.TEXTURE_2D, read.texture);
178
- stepView.uniforms.u_texture.set(0);
179
- stepView.uniforms.u_texelSize.set(1 / WIDTH, 1 / HEIGHT);
180
- stepView.attributes.a_vertex.bind();
181
- gl.drawArrays(gl.TRIANGLES, 0, 6);
182
- }
183
- function render() {
184
- gl.bindFramebuffer(gl.FRAMEBUFFER, null);
185
- gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
186
- gl.useProgram(renderProgram);
187
- gl.activeTexture(gl.TEXTURE0);
188
- gl.bindTexture(gl.TEXTURE_2D, write.texture);
189
- renderView.uniforms.u_texture.set(0);
190
- renderView.attributes.a_vertex.bind();
191
- gl.drawArrays(gl.TRIANGLES, 0, 6);
192
- }
193
- function animate() {
194
- if (playing) {
195
- step();
196
- render();
197
- [read, write] = [write, read];
198
- requestAnimationFrame(animate);
199
- }
200
- }
201
- playing = true;
202
- animate();
@@ -1,173 +0,0 @@
1
- import { a as attribute, u as uniform, g as glsl, c as compile, v as view } from './tag-C_bg62fD.js';
2
- import { c as createElement, a as cursor } from './utils-CvCgsM08.js';
3
-
4
- const canvas = createElement("canvas", { width: window.innerWidth, height: window.innerHeight });
5
- const gl = canvas.getContext("webgl2", { antialias: false });
6
- if (!gl) {
7
- throw new Error("WebGL not supported");
8
- }
9
- const state = {
10
- position: { x: 0, y: 0 },
11
- scale: 1,
12
- elements: []
13
- };
14
- const container = createElement("div");
15
- state.elements.push(createGridElement({ x: 100, y: 100 }));
16
- function createGridElement(position = { x: 0, y: 0 }) {
17
- position = {
18
- x: (position.x - state.position.x) / state.scale,
19
- y: (position.y - state.position.y) / state.scale
20
- };
21
- const element = createElement("div", {
22
- innerText: "HALLO WORLD",
23
- style: `position: fixed;
24
- z-index: 10;
25
- left: 0px;
26
- top: 0px;
27
- transform-origin: top left;
28
- background: white;
29
- padding: 2px;
30
- border-radius: 2px;`,
31
- parentElement: container
32
- });
33
- function update() {
34
- element.style.transform = `translate3d(${state.position.x + position.x * state.scale}px,${state.position.y + position.y * state.scale}px,0) scale(${state.scale})`;
35
- }
36
- update();
37
- return {
38
- element,
39
- position,
40
- update
41
- };
42
- }
43
- canvas.addEventListener("pointerdown", (event) => {
44
- cursor(event, (event2) => {
45
- state.position.x -= event2.deltaX;
46
- state.position.y -= event2.deltaY;
47
- render();
48
- });
49
- });
50
- canvas.addEventListener("dblclick", (event) => {
51
- state.elements.push(
52
- createGridElement({
53
- x: event.clientX,
54
- y: event.clientY
55
- })
56
- );
57
- });
58
- window.addEventListener(
59
- "wheel",
60
- (event) => {
61
- const rect = canvas.getBoundingClientRect();
62
- const mouseX = event.clientX - rect.left;
63
- const mouseY = event.clientY - rect.top;
64
- const scaleFactor = event.deltaY > 0 ? 0.95 : 1.05;
65
- const oldScale = state.scale;
66
- const newScale = Math.max(0.1, Math.min(10, oldScale * scaleFactor));
67
- const gridX = (mouseX - state.position.x) / oldScale;
68
- const gridY = (mouseY - state.position.y) / oldScale;
69
- state.scale = newScale;
70
- state.position.x = mouseX - gridX * newScale;
71
- state.position.y = mouseY - gridY * newScale;
72
- render();
73
- },
74
- { passive: true }
75
- );
76
- window.addEventListener("resize", render);
77
- const vertex = glsl`#version 300 es
78
- ${attribute.vec2("a_vertex")}
79
- ${uniform.vec2("u_screenSize")}
80
- ${uniform.vec2("u_pos")}
81
- ${uniform.float("u_scale")}
82
- out vec2 v_gridCoord;
83
-
84
- // Direct mapping: (-1,-1) is bottom-left, (1,1) is top-right in clip space
85
- // We want (0,0) to be top-left in pixel space
86
- vec2 project(vec2 pos, vec2 size){
87
- return vec2(
88
- (pos.x + 1.0),
89
- (1.0 - pos.y)
90
- ) * size * 0.5;
91
- }
92
-
93
- void main() {
94
- vec2 pixelPos = project(a_vertex, u_screenSize);
95
-
96
- // Apply offset and scale to get grid coordinates
97
- v_gridCoord = (pixelPos - u_pos) / u_scale;
98
-
99
- gl_Position = vec4(a_vertex, 0, 1);
100
- }`;
101
- const renderFragment = glsl`#version 300 es
102
- precision highp float;
103
- in vec2 v_gridCoord;
104
- out vec4 fragColor;
105
- ${uniform.float("u_thickness")}
106
-
107
- float grid(vec2 coord, float thickness) {
108
- vec2 cell = mod(coord, 100.0);
109
- vec2 derivative = fwidth(coord);
110
-
111
- // Convert thickness from screen pixels to grid space
112
- vec2 screenThickness = derivative * thickness;
113
-
114
- // Ensure minimum thickness to prevent lines from disappearing
115
- vec2 minThickness = max(screenThickness, derivative * 0.5);
116
-
117
- // Create hard edges by checking if we're within thickness of a grid line
118
- float lineX = step(cell.x, minThickness.x) + step(100.0 - minThickness.x, cell.x);
119
- float lineY = step(cell.y, minThickness.y) + step(100.0 - minThickness.y, cell.y);
120
-
121
- // Clamp to 0-1 range and return maximum (union of lines)
122
- return max(min(lineX, 1.0), min(lineY, 1.0));
123
- }
124
-
125
- void main() {
126
- // Create grid pattern with adjustable thickness
127
- float gridPattern = grid(v_gridCoord, u_thickness);
128
-
129
- // Grid colors
130
- vec3 backgroundColor = vec3(0.1, 0.1, 0.15);
131
- vec3 gridColor = vec3(0.3, 0.3, 0.4);
132
- vec3 color = mix(backgroundColor, gridColor, gridPattern);
133
-
134
- fragColor = vec4(color, 1.0);
135
- }`;
136
- const { program, schema } = compile(gl, vertex, renderFragment);
137
- const { attributes, uniforms } = view(gl, program, schema);
138
- attributes.a_vertex.set(new Float32Array([
139
- -1,
140
- -1,
141
- // bottom-left
142
- 1,
143
- -1,
144
- // bottom-right
145
- -1,
146
- 1,
147
- // top-left
148
- -1,
149
- 1,
150
- // top-left
151
- 1,
152
- -1,
153
- // bottom-right
154
- 1,
155
- 1
156
- // top-right
157
- ]));
158
- function render() {
159
- gl.useProgram(program);
160
- canvas.width = window.innerWidth;
161
- canvas.height = window.innerHeight;
162
- gl.viewport(0, 0, canvas.width, canvas.height);
163
- gl.clearColor(0, 0, 0, 1);
164
- gl.clear(gl.COLOR_BUFFER_BIT);
165
- attributes.a_vertex.bind();
166
- uniforms.u_screenSize.set(canvas.width, canvas.height);
167
- uniforms.u_pos.set(state.position.x, state.position.y);
168
- uniforms.u_scale.set(state.scale);
169
- uniforms.u_thickness.set(1);
170
- state.elements.forEach((element) => element.update());
171
- gl.drawArrays(gl.TRIANGLES, 0, 6);
172
- }
173
- render();
@@ -1,109 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/bezier-DuLTb2d1.js","assets/tag-C_bg62fD.js","assets/utils-CvCgsM08.js","assets/game_of_life-D7qHdFcv.js","assets/grid-Ie22U_9K.js","assets/overview-DAxtMIw5.js","assets/pix_sim-DIhzM_vu.js","assets/symbol-BouRL-Ni.js","assets/tetris-IMnkSi9p.js"])))=>i.map(i=>d[i]);
2
- import { c as createElement } from './utils-CvCgsM08.js';
3
-
4
- const scriptRel = 'modulepreload';const assetsURL = function(dep) { return "/"+dep };const seen = {};const __vitePreload = function preload(baseModule, deps, importerUrl) {
5
- let promise = Promise.resolve();
6
- if (true && deps && deps.length > 0) {
7
- document.getElementsByTagName("link");
8
- const cspNonceMeta = document.querySelector("meta[property=csp-nonce]");
9
- const cspNonce = cspNonceMeta?.nonce || cspNonceMeta?.getAttribute("nonce");
10
- function allSettled(promises$2) {
11
- return Promise.all(promises$2.map((p$1) => Promise.resolve(p$1).then((value$1) => ({
12
- status: "fulfilled",
13
- value: value$1
14
- }), (reason) => ({
15
- status: "rejected",
16
- reason
17
- }))));
18
- }
19
- promise = allSettled(deps.map((dep) => {
20
- dep = assetsURL(dep);
21
- if (dep in seen) return;
22
- seen[dep] = true;
23
- const isCss = dep.endsWith(".css");
24
- const cssSelector = isCss ? "[rel=\"stylesheet\"]" : "";
25
- if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) return;
26
- const link = document.createElement("link");
27
- link.rel = isCss ? "stylesheet" : scriptRel;
28
- if (!isCss) link.as = "script";
29
- link.crossOrigin = "";
30
- link.href = dep;
31
- if (cspNonce) link.setAttribute("nonce", cspNonce);
32
- document.head.appendChild(link);
33
- if (isCss) return new Promise((res, rej) => {
34
- link.addEventListener("load", res);
35
- link.addEventListener("error", () => rej(/* @__PURE__ */ new Error(`Unable to preload CSS for ${dep}`)));
36
- });
37
- }));
38
- }
39
- function handlePreloadError(err$2) {
40
- const e$1 = new Event("vite:preloadError", { cancelable: true });
41
- e$1.payload = err$2;
42
- window.dispatchEvent(e$1);
43
- if (!e$1.defaultPrevented) throw err$2;
44
- }
45
- return promise.then((res) => {
46
- for (const item of res || []) {
47
- if (item.status !== "rejected") continue;
48
- handlePreloadError(item.reason);
49
- }
50
- return baseModule().catch(handlePreloadError);
51
- });
52
- };
53
-
54
- const css = "/assets/index-C2N3u8wj.css";
55
-
56
- const iframe = document.querySelector("iframe");
57
- const nav = document.querySelector("nav");
58
- createElement("h3", { innerText: "Examples", parentElement: nav });
59
- const urls = Object.fromEntries(
60
- Object.entries(/* #__PURE__ */ Object.assign({"./examples/bezier.ts": () => __vitePreload(() => import('./bezier-DuLTb2d1.js'),true ?__vite__mapDeps([0,1,2]):void 0),"./examples/game_of_life.ts": () => __vitePreload(() => import('./game_of_life-D7qHdFcv.js'),true ?__vite__mapDeps([3,1]):void 0),"./examples/grid.ts": () => __vitePreload(() => import('./grid-Ie22U_9K.js'),true ?__vite__mapDeps([4,1,2]):void 0),"./examples/overview.ts": () => __vitePreload(() => import('./overview-DAxtMIw5.js'),true ?__vite__mapDeps([5,1]):void 0),"./examples/pix_sim.ts": () => __vitePreload(() => import('./pix_sim-DIhzM_vu.js'),true ?__vite__mapDeps([6,1,2]):void 0),"./examples/symbol.ts": () => __vitePreload(() => import('./symbol-BouRL-Ni.js'),true ?__vite__mapDeps([7,1,2]):void 0),"./examples/tetris.ts": () => __vitePreload(() => import('./tetris-IMnkSi9p.js'),true ?__vite__mapDeps([8,1]):void 0)})).map(([key, entry]) => {
61
- const name = key.split("/").pop().replace(".ts", "");
62
- const chunk = entry.toString().match(/import\(['"]([^'"]+)['"]/)[1];
63
- return [name, chunk];
64
- })
65
- );
66
- Object.entries(urls).forEach(([name, localUrl]) => {
67
- createElement("button", {
68
- onclick(event) {
69
- event.preventDefault();
70
- load(name, localUrl);
71
- },
72
- innerHTML: name,
73
- parentElement: nav,
74
- "data-route": name
75
- });
76
- });
77
- function load(name, url) {
78
- window.location.hash = name;
79
- URL.revokeObjectURL(iframe.src);
80
- nav.querySelectorAll("button").forEach((button) => {
81
- if (button.getAttribute("data-route") === name) {
82
- button.classList.add("active");
83
- } else {
84
- button.classList.remove("active");
85
- }
86
- });
87
- iframe.src = URL.createObjectURL(
88
- new Blob(
89
- [
90
- `<head>
91
- <link rel="stylesheet" href="${new URL(css, import.meta.url).href}"></link>
92
- <script type="module" src="${new URL(url, import.meta.url).href}"><\/script></head>`
93
- ],
94
- {
95
- type: "text/html"
96
- }
97
- )
98
- );
99
- }
100
- const hash = window.location.hash.slice(1);
101
- if (hash && hash in urls) {
102
- load(hash, urls[hash]);
103
- }
104
- window.addEventListener("hashchange", () => {
105
- const hash2 = window.location.hash.slice(1);
106
- if (hash2 && hash2 in urls) {
107
- load(hash2, urls[hash2]);
108
- }
109
- });
@@ -1,12 +0,0 @@
1
- body {
2
- display: flex;
3
- justify-content: center;
4
- align-items: center;
5
- margin: 0px;
6
- height: 100%;
7
- overscroll-behavior-y: none;
8
- }
9
- canvas {
10
- margin: auto;
11
- image-rendering: pixelated;
12
- }
@@ -1,32 +0,0 @@
1
- import './index-0qrXMlfv.js';
2
- import './utils-CvCgsM08.js';
3
-
4
- true &&(function polyfill() {
5
- const relList = document.createElement("link").relList;
6
- if (relList && relList.supports && relList.supports("modulepreload")) return;
7
- for (const link of document.querySelectorAll("link[rel=\"modulepreload\"]")) processPreload(link);
8
- new MutationObserver((mutations) => {
9
- for (const mutation of mutations) {
10
- if (mutation.type !== "childList") continue;
11
- for (const node of mutation.addedNodes) if (node.tagName === "LINK" && node.rel === "modulepreload") processPreload(node);
12
- }
13
- }).observe(document, {
14
- childList: true,
15
- subtree: true
16
- });
17
- function getFetchOpts(link) {
18
- const fetchOpts = {};
19
- if (link.integrity) fetchOpts.integrity = link.integrity;
20
- if (link.referrerPolicy) fetchOpts.referrerPolicy = link.referrerPolicy;
21
- if (link.crossOrigin === "use-credentials") fetchOpts.credentials = "include";
22
- else if (link.crossOrigin === "anonymous") fetchOpts.credentials = "omit";
23
- else fetchOpts.credentials = "same-origin";
24
- return fetchOpts;
25
- }
26
- function processPreload(link) {
27
- if (link.ep) return;
28
- link.ep = true;
29
- const fetchOpts = getFetchOpts(link);
30
- fetch(link.href, fetchOpts);
31
- }
32
- }());
@@ -1,78 +0,0 @@
1
- import { i as interleave, a as attribute, u as uniform, g as glsl, c as compile, v as view } from './tag-C_bg62fD.js';
2
-
3
- const canvas = document.createElement("canvas");
4
- canvas.width = 800;
5
- canvas.height = 600;
6
- document.body.append(canvas);
7
- const gl = canvas.getContext("webgl2");
8
- gl.viewport(0, 0, canvas.width, canvas.height);
9
- const vertex = glsl`
10
- precision mediump float;
11
-
12
- ${interleave("instancedData", [attribute.vec2("a_pos"), attribute.vec3("a_color")], {
13
- instanced: true
14
- })}
15
- ${attribute.vec2("a_vertex")}
16
- ${uniform.float("u_time")}
17
-
18
- varying vec3 v_color;
19
-
20
- void main() {
21
- float s = sin(u_time);
22
- float c = cos(u_time);
23
- mat2 rotation = mat2(
24
- c, -s,
25
- s, c
26
- );
27
- vec2 position = a_pos + a_vertex * rotation;
28
- gl_Position = vec4(position, 0.0, 1.0);
29
-
30
- v_color = a_color;
31
- }`;
32
- const fragment = glsl`
33
- precision mediump float;
34
-
35
- varying vec3 v_color;
36
-
37
- void main() {
38
- gl_FragColor = vec4(v_color, 1.0);
39
- }`;
40
- const { program, schema } = compile(gl, vertex, fragment);
41
- const {
42
- attributes: { a_vertex },
43
- uniforms: { u_time },
44
- interleavedAttributes: { instancedData }
45
- } = view(gl, program, schema);
46
- instancedData.set(
47
- new Float32Array(
48
- function* () {
49
- for (let i = 0; i < 100; i++) {
50
- yield (Math.random() - 0.5) * 2;
51
- yield (Math.random() - 0.5) * 2;
52
- yield Math.random();
53
- yield Math.random();
54
- yield Math.random();
55
- }
56
- }()
57
- )
58
- );
59
- instancedData.bind();
60
- a_vertex.set(
61
- new Float32Array([
62
- // top
63
- 0,
64
- 1,
65
- // bottom left
66
- -1,
67
- -1,
68
- // bottom right
69
- 1,
70
- -1
71
- ])
72
- ).bind();
73
- gl.useProgram(program);
74
- requestAnimationFrame(function draw(delta) {
75
- requestAnimationFrame(draw);
76
- u_time.set(delta / 1e3);
77
- gl.drawArraysInstanced(gl.TRIANGLES, 0, 3, 100);
78
- });