spi3der 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/APP.md +40 -0
  2. package/Dockerfile +4 -0
  3. package/MCP.md +149 -0
  4. package/PLAYER.md +136 -0
  5. package/README.md +35 -2
  6. package/api/mcp.mjs +31 -0
  7. package/api/store.mjs +158 -0
  8. package/bin/spi3der.mjs +20 -0
  9. package/emulator.html +17 -0
  10. package/engine/8fa668821759/bevel.js +265 -0
  11. package/engine/8fa668821759/camera.js +76 -0
  12. package/engine/8fa668821759/character.js +1019 -0
  13. package/engine/8fa668821759/check.js +83 -0
  14. package/engine/8fa668821759/csg.js +342 -0
  15. package/engine/8fa668821759/edit.js +48 -0
  16. package/engine/8fa668821759/galaxy.js +265 -0
  17. package/engine/8fa668821759/gl.js +798 -0
  18. package/engine/8fa668821759/gpu.js +1356 -0
  19. package/engine/8fa668821759/index.js +48 -0
  20. package/engine/8fa668821759/instances.js +41 -0
  21. package/engine/8fa668821759/joints.js +355 -0
  22. package/engine/8fa668821759/kernel-bytes.js +2 -0
  23. package/engine/8fa668821759/kernel.js +82 -0
  24. package/engine/8fa668821759/lathe.js +87 -0
  25. package/engine/8fa668821759/material.js +19 -0
  26. package/engine/8fa668821759/mesh.js +131 -0
  27. package/engine/8fa668821759/order.js +125 -0
  28. package/engine/8fa668821759/pick.js +85 -0
  29. package/engine/8fa668821759/place.js +17 -0
  30. package/engine/8fa668821759/planet.js +376 -0
  31. package/engine/8fa668821759/rig.js +417 -0
  32. package/engine/8fa668821759/saw.js +121 -0
  33. package/engine/8fa668821759/sky.js +428 -0
  34. package/engine/8fa668821759/svg.js +239 -0
  35. package/engine/8fa668821759/text.js +231 -0
  36. package/engine/8fa668821759/triangulate.js +72 -0
  37. package/engine/8fa668821759/types.js +2 -0
  38. package/engine/8fa668821759/vec.js +22 -0
  39. package/engine/8fa668821759/version.js +7 -0
  40. package/engine/8fa668821759/vrtsh.js +354 -0
  41. package/engine/8fa668821759/wire.js +346 -0
  42. package/favicon.svg +15 -0
  43. package/help.md +289 -0
  44. package/icons/apple-touch-icon.png +0 -0
  45. package/icons/favicon-32.png +0 -0
  46. package/icons/icon-192.png +0 -0
  47. package/icons/icon-512.png +0 -0
  48. package/icons/icon-maskable-512.png +0 -0
  49. package/icons/icon-maskable.svg +13 -0
  50. package/icons/icon.svg +15 -0
  51. package/index.html +13730 -0
  52. package/manifest.webmanifest +37 -0
  53. package/mcp/engine/bevel.js +265 -0
  54. package/mcp/engine/camera.js +76 -0
  55. package/mcp/engine/character.js +1019 -0
  56. package/mcp/engine/check.js +83 -0
  57. package/mcp/engine/csg.js +342 -0
  58. package/mcp/engine/edit.js +48 -0
  59. package/mcp/engine/galaxy.js +265 -0
  60. package/mcp/engine/gl.js +798 -0
  61. package/mcp/engine/gpu.js +1356 -0
  62. package/mcp/engine/index.js +48 -0
  63. package/mcp/engine/instances.js +41 -0
  64. package/mcp/engine/joints.js +355 -0
  65. package/mcp/engine/kernel-bytes.js +2 -0
  66. package/mcp/engine/kernel.js +82 -0
  67. package/mcp/engine/lathe.js +87 -0
  68. package/mcp/engine/material.js +19 -0
  69. package/mcp/engine/mesh.js +131 -0
  70. package/mcp/engine/order.js +125 -0
  71. package/mcp/engine/pick.js +85 -0
  72. package/mcp/engine/place.js +17 -0
  73. package/mcp/engine/planet.js +376 -0
  74. package/mcp/engine/rig.js +417 -0
  75. package/mcp/engine/saw.js +121 -0
  76. package/mcp/engine/sky.js +428 -0
  77. package/mcp/engine/svg.js +239 -0
  78. package/mcp/engine/text.js +231 -0
  79. package/mcp/engine/triangulate.js +72 -0
  80. package/mcp/engine/types.js +2 -0
  81. package/mcp/engine/vec.js +22 -0
  82. package/mcp/engine/version.js +7 -0
  83. package/mcp/engine/vrtsh.js +354 -0
  84. package/mcp/engine/wire.js +346 -0
  85. package/mcp/http.js +292 -0
  86. package/mcp/live.js +95 -0
  87. package/mcp/package.json +10 -0
  88. package/mcp/scene.js +1027 -0
  89. package/mcp/serve.js +87 -0
  90. package/mcp/server.js +97 -0
  91. package/media/face-of-spider.png +0 -0
  92. package/media/spider-paint-2015.png +0 -0
  93. package/media/spider-web.png +0 -0
  94. package/models/deepsky-lark.scene.json +1 -0
  95. package/models/deepsky.scene.json +1 -0
  96. package/models/globe.scene.json +1 -0
  97. package/models/lark-4.scene.json +1 -0
  98. package/models/lark.game.json +14 -0
  99. package/models/spider-build-v2.md +215 -0
  100. package/models/spider-build-v2.mjs +355 -0
  101. package/models/spider-build-v2.schema.json +1001 -0
  102. package/nginx.conf +12 -0
  103. package/package.json +45 -4
  104. package/player.html +274 -0
  105. package/sky.html +133 -0
  106. package/sky.md +285 -0
  107. package/src/demo.js +92 -0
  108. package/src/emulator/devices.js +22 -0
  109. package/src/emulator/xr.js +362 -0
  110. package/src/math.js +77 -0
  111. package/sw.js +37 -0
  112. package/xr-compare.html +332 -0
  113. package/xr-test.html +248 -0
@@ -0,0 +1,798 @@
1
+ // WebGL2 renderer: the same picture as the WebGPU one (gpu.ts), for browsers and devices that have no WebGPU.
2
+ // Same options, same vertices (buildVertices), same light model: the shader below is a line-by-line port of the WGSL.
3
+ // It also runs on a software GL (SwiftShader), so a frame can be checked on a machine without a GPU.
4
+ import { norm } from './vec.js';
5
+ import { makeCamera } from './camera.js';
6
+ import { buildVertices, buildMarks, skinCache, SKIN_FLOATS, MAX_BONES, buildScreenQuads, SCREEN_FLOATS, MARK_FLOATS, sceneEdges, sceneLights, LIGHT_FLOATS, MAX_LIGHTS, viewProjection, nearPlane, defaultLight, defaultMaterial, mul4 } from './gpu.js';
7
+ import { planetInstances, PLANET_GLSL_VS, PLANET_GLSL_FS, PLANET_FLOATS, inv4 } from './planet.js';
8
+ const GL_FLOATS = 14; // position(3) normal(3) color(3) material(4: metal, rough, alpha, emit) soft(1)
9
+ const GL_INSTANCE_FLOATS = 15; // at(3) ex(3) ey(3) ez(3) color(3)
10
+ const GL_COMMON = /* glsl */ `#version 300 es
11
+ precision highp float;
12
+ uniform mat4 uVp;
13
+ uniform float uLd;
14
+ vec4 ld(vec4 p) { if (uLd > 0.0) p.z = log2(max(1e-6, uLd * p.w + 1.0)) / log2(uLd * 1e12 + 1.0) * p.w; return p; } // logarithmic depth (gpu.ts)
15
+ out vec3 vN; out vec3 vC; out vec3 vW; out vec4 vM; out float vS;
16
+ `;
17
+ const GL_VERT = `${GL_COMMON}
18
+ layout(location = 0) in vec3 aPos; layout(location = 1) in vec3 aNrm; layout(location = 2) in vec3 aCol;
19
+ layout(location = 3) in vec4 aMat; layout(location = 4) in float aSoft;
20
+ void main() {
21
+ vec4 p = ld(uVp * vec4(aPos, 1.0));
22
+ gl_Position = vec4(p.xy, p.z * 2.0 - p.w, p.w); // WebGPU depth is 0..1, GL wants -1..1
23
+ vN = aNrm; vC = aCol; vW = aPos; vM = aMat; vS = aSoft;
24
+ }`;
25
+ // a skinned figure: every vertex is moved by up to four joints (three rows of [cols | shift] per joint), mixed by its weights
26
+ const GL_VERT_SKIN = `${GL_COMMON}
27
+ uniform vec4 uBones[${3 * 64}];
28
+ uniform vec4 uEmission[16];
29
+ layout(location = 0) in vec3 aPos; layout(location = 1) in vec3 aNrm; layout(location = 2) in vec3 aCol;
30
+ layout(location = 3) in vec4 aMat; layout(location = 4) in float aSoft;
31
+ layout(location = 5) in vec4 aJ; layout(location = 6) in vec4 aW;
32
+ vec3 bone(int k, vec4 p) { return vec3(dot(uBones[k * 3], p), dot(uBones[k * 3 + 1], p), dot(uBones[k * 3 + 2], p)); }
33
+ void main() {
34
+ vec3 q = vec3(0.0);
35
+ vec3 n = vec3(0.0);
36
+ float emission = 0.0;
37
+ for (int c = 0; c < 4; c++) {
38
+ float w = aW[c];
39
+ if (w > 0.0) {
40
+ int k = int(aJ[c] + 0.5);
41
+ q += bone(k, vec4(aPos, 1.0)) * w;
42
+ n += bone(k, vec4(aNrm, 0.0)) * w;
43
+ emission += uEmission[k / 4][k % 4] * w;
44
+ }
45
+ }
46
+ vec4 p = ld(uVp * vec4(q, 1.0));
47
+ gl_Position = vec4(p.xy, p.z * 2.0 - p.w, p.w);
48
+ vN = n; vC = aCol; vW = q; vM = aMat; vS = aSoft;
49
+ vM.w *= emission;
50
+ }`;
51
+ // a screen: a picture on a quad, as it is (a display does not take the scene's light)
52
+ const GL_VERT_SCREEN = `#version 300 es
53
+ precision highp float;
54
+ uniform mat4 uVp;
55
+ uniform float uLd;
56
+ vec4 ld(vec4 p) { if (uLd > 0.0) p.z = log2(max(1e-6, uLd * p.w + 1.0)) / log2(uLd * 1e12 + 1.0) * p.w; return p; }
57
+ layout(location = 0) in vec3 aPos; layout(location = 1) in vec2 aUv;
58
+ out vec2 vUv;
59
+ void main() {
60
+ vec4 p = ld(uVp * vec4(aPos, 1.0));
61
+ gl_Position = vec4(p.xy, p.z * 2.0 - p.w, p.w);
62
+ vUv = aUv;
63
+ }`;
64
+ const GL_FRAG_HOLE = `#version 300 es
65
+ precision highp float;
66
+ in vec2 vUv;
67
+ out vec4 o;
68
+ void main() { o = vec4(0.0); }`;
69
+ const GL_FRAG_SCREEN = `#version 300 es
70
+ precision highp float;
71
+ uniform sampler2D uTex;
72
+ in vec2 vUv;
73
+ out vec4 o;
74
+ void main() { o = vec4(texture(uTex, vUv).rgb, 1.0); }`;
75
+ // the same prototype drawn many times: its frame (ex, ey, ez; scaled axes scale it) and position come per instance
76
+ const GL_VERT_INST = `${GL_COMMON}
77
+ layout(location = 0) in vec3 aPos; layout(location = 1) in vec3 aNrm;
78
+ layout(location = 5) in vec3 aAt; layout(location = 6) in vec3 aEx; layout(location = 7) in vec3 aEy; layout(location = 8) in vec3 aEz;
79
+ layout(location = 9) in vec3 aCol;
80
+ void main() {
81
+ vec3 w = aAt + aEx * aPos.x + aEy * aPos.y + aEz * aPos.z;
82
+ vec4 p = ld(uVp * vec4(w, 1.0));
83
+ gl_Position = vec4(p.xy, p.z * 2.0 - p.w, p.w);
84
+ vN = normalize(aEx) * aNrm.x + normalize(aEy) * aNrm.y + normalize(aEz) * aNrm.z;
85
+ vC = aCol; vW = w; vM = vec4(0.0, 0.7, 1.0, 0.0); vS = 0.0;
86
+ }`;
87
+ // the edge lines: 1 pixel, nudged a hair towards the eye so they win against the faces they lie on
88
+ const GL_VERT_LINE = `#version 300 es
89
+ precision highp float;
90
+ uniform mat4 uVp;
91
+ uniform float uLd;
92
+ vec4 ld(vec4 p) { if (uLd > 0.0) p.z = log2(max(1e-6, uLd * p.w + 1.0)) / log2(uLd * 1e12 + 1.0) * p.w; return p; }
93
+ layout(location = 0) in vec3 aPos;
94
+ void main() {
95
+ vec4 p = ld(uVp * vec4(aPos, 1.0));
96
+ gl_Position = vec4(p.xy, p.z * 2.0 - p.w - 0.0004 * p.w, p.w);
97
+ }`;
98
+ const GL_FRAG_LINE = `#version 300 es
99
+ precision mediump float;
100
+ out vec4 outColor;
101
+ uniform float uUnlit;
102
+ void main() { outColor = uUnlit > 0.5 ? vec4(0.85, 0.85, 0.85, 0.55) : vec4(0.0, 0.0, 0.0, 0.4); }`;
103
+ // the marks: thick round-capped segments expanded to screen-space quads, over everything (see the WGSL vsm/fsm)
104
+ const GL_VERT_MARK = `#version 300 es
105
+ precision highp float;
106
+ uniform mat4 uVp; uniform vec3 uRes; uniform float uLd; uniform float uFocal;
107
+ layout(location = 0) in vec3 aA; layout(location = 1) in vec3 aB; layout(location = 2) in vec4 aCol; layout(location = 3) in float aW; layout(location = 4) in vec3 aDash;
108
+ out vec2 vQ; out vec4 vCol; out vec2 vH; out vec2 vDash;
109
+ void main() {
110
+ // the points are relative to the eye (buildMarks, in doubles), uVp is the eye-centred view-projection
111
+ vec4 ca = uVp * vec4(aA, 1.0);
112
+ vec4 cb = uVp * vec4(aB, 1.0);
113
+ float sa = aDash.y, sb = aDash.z;
114
+ // the near cut: with log depth anything just in front of the eye is drawn, but never nearer than 1e-5 of the segment's far end:
115
+ // a point cut at w ~ 0 lands ~1e15 px away, where float32 loses the line's direction and stray lines flash across the screen
116
+ float e = max(uLd > 0.0 ? 1e-13 : 0.001, 1e-5 * max(ca.w, cb.w));
117
+ gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
118
+ if (ca.w < e && cb.w < e) return;
119
+ if (ca.w < e) { float k = (e - ca.w) / (cb.w - ca.w); ca = mix(ca, cb, k); sa = mix(sa, sb, k); }
120
+ if (cb.w < e) { float k = (e - cb.w) / (ca.w - cb.w); cb = mix(cb, ca, k); sb = mix(sb, sa, k); }
121
+ vec2 half_ = uRes.xy * 0.5;
122
+ vec2 pa = ca.xy / ca.w * half_;
123
+ vec2 pb = cb.xy / cb.w * half_;
124
+ // the screen guard band: the segment is cut to 4x the picture before the quad is built, so no corner lies far off screen (a real
125
+ // GPU's rasteriser may mangle a triangle with a corner ~1e12 px away: a stray line across the picture)
126
+ {
127
+ float G = max(half_.x, half_.y) * 4.0;
128
+ vec2 dd = pb - pa;
129
+ float t0 = 0.0, t1 = 1.0;
130
+ for (int k = 0; k < 4; k++) {
131
+ float pp = k == 0 ? -dd.x : k == 1 ? dd.x : k == 2 ? -dd.y : dd.y;
132
+ float qq = k == 0 ? pa.x + G : k == 1 ? G - pa.x : k == 2 ? pa.y + G : G - pa.y;
133
+ if (abs(pp) < 1e-20) { if (qq < 0.0) return; }
134
+ else { float r = qq / pp; if (pp < 0.0) t0 = max(t0, r); else t1 = min(t1, r); }
135
+ }
136
+ if (t0 > t1) return;
137
+ vec2 na = pa + dd * t0, nb = pa + dd * t1;
138
+ // the dash distance and the depth follow the cut (s / w is linear on screen)
139
+ float qa = sa / ca.w, qb = sb / cb.w;
140
+ float ia = 1.0 / ca.w, ib = 1.0 / cb.w;
141
+ float ja = mix(ia, ib, t0), jb = mix(ia, ib, t1);
142
+ sa = mix(qa, qb, t0) / ja; sb = mix(qa, qb, t1) / jb;
143
+ ca.w = 1.0 / ja; cb.w = 1.0 / jb;
144
+ pa = na; pb = nb;
145
+ }
146
+ float len = length(pb - pa);
147
+ vec2 d = len > 0.0001 ? (pb - pa) / len : vec2(1.0, 0.0);
148
+ float hw = aW * uRes.z * 0.5;
149
+ vec2 n = vec2(-d.y, d.x);
150
+ float cx[6] = float[6](0.0, 1.0, 0.0, 1.0, 1.0, 0.0);
151
+ float cy[6] = float[6](-1.0, -1.0, 1.0, -1.0, 1.0, 1.0);
152
+ float ext = hw + 1.0;
153
+ float along = mix(-ext, len + ext, cx[gl_VertexID]);
154
+ float across = cy[gl_VertexID] * ext;
155
+ vec2 pos = pa + d * along + n * across;
156
+ gl_Position = vec4(pos / half_, 0.0, 1.0);
157
+ vQ = vec2(along, across); vCol = aCol; vH = vec2(len, hw);
158
+ // the dash phase in pixels (length along the line / depth x focal length: linear on screen, so it runs on across joints)
159
+ float f = len > 0.0001 ? along / len : cx[gl_VertexID];
160
+ vDash = vec2(mix(sa / ca.w, sb / cb.w, f) * uFocal, aDash.x * uRes.z);
161
+ }`;
162
+ const GL_FRAG_MARK = `#version 300 es
163
+ precision highp float;
164
+ in vec2 vQ; in vec4 vCol; in vec2 vH; in vec2 vDash;
165
+ out vec4 outColor;
166
+ void main() {
167
+ float dx = max(max(-vQ.x, vQ.x - vH.x), 0.0);
168
+ float dist = length(vec2(dx, vQ.y));
169
+ float cov = clamp(vH.y + 0.5 - dist, 0.0, 1.0);
170
+ if (vDash.y > 0.0) {
171
+ float px = fract(vDash.x / (2.0 * vDash.y)) * 2.0 * vDash.y; // a dash, then a gap as long; half a pixel of soft edge
172
+ cov *= clamp(min(px, vDash.y - px) + 0.5, 0.0, 1.0);
173
+ }
174
+ outColor = vec4(vCol.rgb, vCol.a * cov);
175
+ }`;
176
+ const GL_FRAG = /* glsl */ `#version 300 es
177
+ precision highp float;
178
+ uniform vec4 uLight; uniform vec4 uSky; uniform vec4 uGround; uniform vec4 uEye; uniform vec4 uMat;
179
+ uniform vec4 uFx; uniform vec4 uFill; uniform vec4 uRim;
180
+ uniform vec4 uLP[16]; uniform vec4 uLC[16]; uniform float uLN;
181
+ in vec3 vN; in vec3 vC; in vec3 vW; in vec4 vM; in float vS;
182
+ out vec4 outColor;
183
+
184
+ vec3 toLinear(vec3 c) { return mix(pow((c + 0.055) / 1.055, vec3(2.4)), c / 12.92, vec3(lessThanEqual(c, vec3(0.04045)))); }
185
+ vec3 toSrgb(vec3 c) { return mix(1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, c * 12.92, vec3(lessThanEqual(c, vec3(0.0031308)))); }
186
+ // ACES filmic curve (Narkowicz fit): highlights roll off softly instead of clipping
187
+ vec3 aces(vec3 x) { return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), vec3(0.0), vec3(1.0)); }
188
+ // Glow: every emitting cluster is a local light with a smooth falloff to zero at its reach
189
+ vec3 glowAt(vec3 p, vec3 n) {
190
+ vec3 sum = vec3(0.0);
191
+ for (int k = 0; k < 16; k++) {
192
+ if (float(k) >= uLN) break;
193
+ vec3 d = uLP[k].xyz - p;
194
+ float dist = max(length(d), 0.001);
195
+ float x = dist / uLP[k].w;
196
+ float win = clamp(1.0 - x * x * x * x, 0.0, 1.0);
197
+ win = win * win;
198
+ float s = dist / (uLP[k].w * 0.25);
199
+ float wrap = max((dot(n, d / dist) + 0.3) / 1.3, 0.0);
200
+ sum += uLC[k].rgb * (win / (1.0 + s * s)) * wrap * 1.6;
201
+ }
202
+ return sum;
203
+ }
204
+
205
+ // Direct light, shared by both looks: x diffuse, y highlight, z scattered light (soft materials).
206
+ vec3 lights(vec3 n, vec3 v, float shin, float soft) {
207
+ vec3 key = normalize(uLight.xyz);
208
+ float ndl = dot(n, key);
209
+ float diff = max((ndl + soft) / (1.0 + soft), 0.0);
210
+ vec3 h = normalize(key + v);
211
+ float spec = pow(max(dot(n, h), 0.0), shin) * step(0.0, ndl);
212
+ float scat = soft * exp(-ndl * ndl * 5.0);
213
+ if (uFx.w > 0.5) {
214
+ diff = diff * 0.85;
215
+ vec3 fl = normalize(uFill.xyz);
216
+ diff = diff + max((dot(n, fl) + soft) / (1.0 + soft), 0.0) * uFill.w;
217
+ vec3 rl = normalize(uRim.xyz);
218
+ float edge = pow(1.0 - max(dot(n, v), 0.0), 2.5);
219
+ diff = diff + max(dot(n, rl), 0.0) * edge * uRim.w * 2.0;
220
+ vec3 rh = normalize(rl + v);
221
+ spec = spec + pow(max(dot(n, rh), 0.0), shin) * step(0.0, dot(n, rl)) * uRim.w * 0.6 * edge;
222
+ }
223
+ return vec3(diff, spec, scat);
224
+ }
225
+
226
+ vec4 filmic(vec3 n, vec3 v) {
227
+ float metal = vM.x;
228
+ float rough = vM.y;
229
+ vec3 albedo = toLinear(vC);
230
+ vec3 hemi = mix(toLinear(uGround.rgb), toLinear(uSky.rgb), n.y * 0.5 + 0.5) * uMat.x * (uFx.w > 0.5 ? 0.7 : 1.0);
231
+ float shin = mix(uMat.w * 7.0, uMat.w * 0.15, rough);
232
+ vec3 lt = lights(n, v, shin, vS);
233
+ float diff = lt.x * uMat.y * 1.6;
234
+ float spec = lt.y * mix(uMat.z, 1.0, metal) * mix(1.0, 0.35, rough) * 2.5;
235
+ vec3 r = reflect(-v, n);
236
+ vec3 f0 = mix(vec3(0.04), albedo, metal);
237
+ vec3 fres = f0 + (vec3(1.0) - f0) * pow(1.0 - max(dot(n, v), 0.0), 5.0) * (1.0 - rough);
238
+ vec3 env = mix(toLinear(uGround.rgb) * 1.2, toLinear(uSky.rgb) * 1.5, smoothstep(-0.25 - rough * 0.5, 0.25 + rough * 0.5, r.y));
239
+ vec3 lit = albedo * (hemi + vec3(diff)) * (1.0 - metal)
240
+ + albedo * env * metal * (1.0 - 0.6 * rough)
241
+ + env * fres * (1.0 - rough) * 0.5
242
+ + vec3(spec) * mix(vec3(1.0), albedo, metal);
243
+ lit = lit + albedo * vec3(1.0, 0.38, 0.26) * lt.z * 0.5 * (1.0 - metal);
244
+ lit = lit + albedo * glowAt(vW, n) * (1.0 - metal);
245
+ lit = lit + albedo * vM.w * uFx.z;
246
+ return vec4(toSrgb(aces(lit * uFx.y)), vM.z);
247
+ }
248
+
249
+ void main() {
250
+ vec3 n = normalize(vN);
251
+ if (!gl_FrontFacing) n = -n;
252
+ vec3 v = normalize(uEye.xyz - vW);
253
+ if (uLight.w > 0.5) {
254
+ vec3 g = glowAt(vW, n) * (1.0 - vM.x);
255
+ if (uFx.x > 0.5) { outColor = vec4(toSrgb(aces(toLinear(vC) * (vM.w * uFx.z + g) * uFx.y)), vM.z); return; }
256
+ outColor = vec4(clamp(vC * (min(vM.w, 1.0) + g), vec3(0.0), vec3(1.0)), vM.z); return;
257
+ }
258
+ if (uFx.x > 0.5) { outColor = filmic(n, v); return; }
259
+ float metal = vM.x;
260
+ float rough = vM.y;
261
+ vec3 hemi = mix(uGround.rgb, uSky.rgb, n.y * 0.5 + 0.5) * uMat.x * (uFx.w > 0.5 ? 0.7 : 1.0);
262
+ float shin = mix(uMat.w * 7.0, uMat.w * 0.15, rough);
263
+ vec3 lt = lights(n, v, shin, vS);
264
+ float diff = lt.x * uMat.y;
265
+ float spec = lt.y * mix(uMat.z, 1.0, metal) * mix(1.0, 0.35, rough);
266
+ vec3 r = reflect(-v, n);
267
+ vec3 env = mix(uGround.rgb * 1.2, uSky.rgb * 1.5, smoothstep(-0.25 - rough * 0.5, 0.25 + rough * 0.5, r.y));
268
+ vec3 lit = vC * (hemi + vec3(diff)) * (1.0 - metal)
269
+ + vC * env * metal * (1.0 - 0.6 * rough)
270
+ + vec3(spec) * mix(vec3(1.0), vC, metal)
271
+ + vC * vec3(1.0, 0.38, 0.26) * lt.z * 0.25 * (1.0 - metal);
272
+ lit = lit + vC * glowAt(vW, n) * (1.0 - metal);
273
+ lit = mix(lit, vC * 1.15, min(vM.w, 1.0));
274
+ outColor = vec4(clamp(lit, vec3(0.0), vec3(1.0)), vM.z);
275
+ }`;
276
+ /**
277
+ * Sets up WebGL2 on a canvas. Rejects when WebGL2 is not available. Same call and options as createGpu:
278
+ * returns { render(mesh, view, options), pixels(...), destroy() }. `device.lost` resolves when the context is lost.
279
+ */
280
+ export const createGl = async (canvas, { onError } = {}) => {
281
+ const gl = canvas.getContext('webgl2', { antialias: true, alpha: true, premultipliedAlpha: true, preserveDrawingBuffer: false }); // opaque but where a screen punches a hole as WebGL2RenderingContext | null;
282
+ if (!gl)
283
+ throw new Error('WebGL2 is not available in this browser');
284
+ const lost = new Promise((resolve) => canvas.addEventListener('webglcontextlost', (e) => (e.preventDefault(), resolve({ reason: 'lost', message: 'WebGL context lost' }))));
285
+ const program = (vs, fs) => {
286
+ const sh = (type, src) => {
287
+ const s = gl.createShader(type);
288
+ gl.shaderSource(s, src);
289
+ gl.compileShader(s);
290
+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
291
+ const message = `shader: ${gl.getShaderInfoLog(s)}`;
292
+ onError?.(message);
293
+ throw new Error(message);
294
+ }
295
+ return s;
296
+ };
297
+ const p = gl.createProgram();
298
+ gl.attachShader(p, sh(gl.VERTEX_SHADER, vs));
299
+ gl.attachShader(p, sh(gl.FRAGMENT_SHADER, fs));
300
+ gl.linkProgram(p);
301
+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) {
302
+ const message = `program: ${gl.getProgramInfoLog(p)}`;
303
+ onError?.(message);
304
+ throw new Error(message);
305
+ }
306
+ return p;
307
+ };
308
+ const meshProg = program(GL_VERT, GL_FRAG);
309
+ const instProg = program(GL_VERT_INST, GL_FRAG);
310
+ const skinProg = program(GL_VERT_SKIN, GL_FRAG);
311
+ const skinBones = gl.getUniformLocation(skinProg, 'uBones');
312
+ const skinEmission = gl.getUniformLocation(skinProg, 'uEmission');
313
+ const emission = new Float32Array(MAX_BONES);
314
+ const uni = (p) => {
315
+ const g = (n) => gl.getUniformLocation(p, n);
316
+ return { vp: g('uVp'), light: g('uLight'), sky: g('uSky'), ground: g('uGround'), eye: g('uEye'), mat: g('uMat'), fx: g('uFx'), fill: g('uFill'), rim: g('uRim'), lp: g('uLP'), lc: g('uLC'), ln: g('uLN'), ld: g('uLd') };
317
+ };
318
+ const lineProg = program(GL_VERT_LINE, GL_FRAG_LINE);
319
+ const lineVp = gl.getUniformLocation(lineProg, 'uVp');
320
+ const lineLd = gl.getUniformLocation(lineProg, 'uLd');
321
+ const lineUnlit = gl.getUniformLocation(lineProg, 'uUnlit');
322
+ const planetProg = program(PLANET_GLSL_VS, PLANET_GLSL_FS.replace('uniform vec4 uRes;', 'uniform vec4 uRes; uniform vec4 uOff;').replace('gl_FragCoord.x / uRes.x', '(gl_FragCoord.x - uOff.x) / uRes.x').replace('gl_FragCoord.y / uRes.y', '(gl_FragCoord.y - uOff.y) / uRes.y'));
323
+ const planetU = { inv: gl.getUniformLocation(planetProg, 'uInv'), vp: gl.getUniformLocation(planetProg, 'uVpR'), res: gl.getUniformLocation(planetProg, 'uRes'), off: gl.getUniformLocation(planetProg, 'uOff') };
324
+ const markProg = program(GL_VERT_MARK, GL_FRAG_MARK);
325
+ const markVp = gl.getUniformLocation(markProg, 'uVp');
326
+ const markLd = gl.getUniformLocation(markProg, 'uLd');
327
+ const markRes = gl.getUniformLocation(markProg, 'uRes');
328
+ const markFocal = gl.getUniformLocation(markProg, 'uFocal');
329
+ const meshU = uni(meshProg);
330
+ const instU = uni(instProg);
331
+ const skinU = uni(skinProg);
332
+ const screenProg = program(GL_VERT_SCREEN, GL_FRAG_SCREEN);
333
+ const screenVp = gl.getUniformLocation(screenProg, 'uVp');
334
+ const screenLd = gl.getUniformLocation(screenProg, 'uLd');
335
+ const screenTexU = gl.getUniformLocation(screenProg, 'uTex');
336
+ const screenTex = [];
337
+ const holeProg = program(GL_VERT_SCREEN, GL_FRAG_HOLE);
338
+ const holeVp = gl.getUniformLocation(holeProg, 'uVp');
339
+ const holeLd = gl.getUniformLocation(holeProg, 'uLd');
340
+ const stride = GL_FLOATS * 4;
341
+ const buffer = () => gl.createBuffer();
342
+ const vaoWith = (setup) => {
343
+ const v = gl.createVertexArray();
344
+ gl.bindVertexArray(v);
345
+ setup();
346
+ gl.bindVertexArray(null);
347
+ return v;
348
+ };
349
+ const attr = (loc, size, stride, offset, divisor = 0) => {
350
+ gl.enableVertexAttribArray(loc);
351
+ gl.vertexAttribPointer(loc, size, gl.FLOAT, false, stride, offset);
352
+ gl.vertexAttribDivisor(loc, divisor);
353
+ };
354
+ const solidBuf = buffer();
355
+ const glassBuf = buffer();
356
+ const protoBuf = buffer();
357
+ const instBuf = buffer();
358
+ const edgeBuf = buffer();
359
+ const edgeVao = vaoWith(() => {
360
+ gl.bindBuffer(gl.ARRAY_BUFFER, edgeBuf);
361
+ attr(0, 3, 12, 0);
362
+ });
363
+ const planetBuf = buffer();
364
+ const planetVao = vaoWith(() => {
365
+ gl.bindBuffer(gl.ARRAY_BUFFER, planetBuf);
366
+ for (let k = 0; k < 9; k++)
367
+ attr(k, 4, PLANET_FLOATS * 4, k * 16, 1);
368
+ });
369
+ const markBuf = buffer();
370
+ const markVao = vaoWith(() => {
371
+ gl.bindBuffer(gl.ARRAY_BUFFER, markBuf);
372
+ const s = MARK_FLOATS * 4;
373
+ attr(0, 3, s, 0, 1);
374
+ attr(1, 3, s, 12, 1);
375
+ attr(2, 4, s, 24, 1);
376
+ attr(3, 1, s, 40, 1);
377
+ attr(4, 3, s, 44, 1);
378
+ });
379
+ let markCount = 0;
380
+ let edgeCount = 0;
381
+ let edgeMesh = null;
382
+ let edgeParts;
383
+ let edgeOn = false;
384
+ const meshAttrs = (b) => () => {
385
+ gl.bindBuffer(gl.ARRAY_BUFFER, b);
386
+ attr(0, 3, stride, 0);
387
+ attr(1, 3, stride, 12);
388
+ attr(2, 3, stride, 24);
389
+ attr(3, 4, stride, 36);
390
+ attr(4, 1, stride, 52);
391
+ };
392
+ const solidVao = vaoWith(meshAttrs(solidBuf));
393
+ const skinSolidBuf = buffer();
394
+ const skinGlassBuf = buffer();
395
+ const skinAttrs = (b) => () => {
396
+ const st = SKIN_FLOATS * 4;
397
+ gl.bindBuffer(gl.ARRAY_BUFFER, b);
398
+ attr(0, 3, st, 0);
399
+ attr(1, 3, st, 12);
400
+ attr(2, 3, st, 24);
401
+ attr(3, 4, st, 36);
402
+ attr(4, 1, st, 52);
403
+ attr(5, 4, st, 56);
404
+ attr(6, 4, st, 72);
405
+ };
406
+ const skinSolidVao = vaoWith(skinAttrs(skinSolidBuf));
407
+ const skinGlassVao = vaoWith(skinAttrs(skinGlassBuf));
408
+ const skinVerts = skinCache();
409
+ const screenBuf = buffer();
410
+ const screenVao = vaoWith(() => {
411
+ gl.bindBuffer(gl.ARRAY_BUFFER, screenBuf);
412
+ attr(0, 3, SCREEN_FLOATS * 4, 0);
413
+ attr(1, 2, SCREEN_FLOATS * 4, 12);
414
+ });
415
+ let skinSolidCount = 0;
416
+ let skinGlassCount = 0;
417
+ const glassVao = vaoWith(meshAttrs(glassBuf));
418
+ const instVao = vaoWith(() => {
419
+ gl.bindBuffer(gl.ARRAY_BUFFER, protoBuf);
420
+ attr(0, 3, stride, 0);
421
+ attr(1, 3, stride, 12);
422
+ gl.bindBuffer(gl.ARRAY_BUFFER, instBuf);
423
+ [5, 6, 7, 8, 9].forEach((loc, k) => attr(loc, 3, GL_INSTANCE_FLOATS * 4, k * 12, 1));
424
+ });
425
+ // Geometry that did not change since the last frame is not rebuilt or uploaded again.
426
+ let uploaded = null;
427
+ let uploadedPalette;
428
+ let uploadedSmooth = 0;
429
+ let partCache = new WeakMap();
430
+ let partPalette;
431
+ let partSmooth = 0;
432
+ let vertexCount = 0;
433
+ let protoMesh = null;
434
+ let protoCount = 0;
435
+ let instData = null;
436
+ let instCount = 0;
437
+ let glassTris = [];
438
+ let glassSource = new Float32Array(0);
439
+ let glassCount = 0;
440
+ let glassEye = '';
441
+ let px = 0;
442
+ const upload = (b, data) => {
443
+ gl.bindBuffer(gl.ARRAY_BUFFER, b);
444
+ gl.bufferData(gl.ARRAY_BUFFER, data, gl.DYNAMIC_DRAW);
445
+ };
446
+ const draw = (mesh, view, { size = 400, fit, background = [0.98, 0.98, 0.97], transparent = false, light = {}, material = {}, palette, dpr = globalThis.devicePixelRatio || 1, instances, parts, tonemap = false, smooth = false, studio = false, edges = false, marks, unlit = false, glow = false, skin, screens, xr, logDepth = 0, planets } = {}) => {
447
+ const L = { ...defaultLight, ...light };
448
+ const filmic = tonemap ? { exposure: 1, emit: 2, ...(tonemap === true ? {} : tonemap) } : null;
449
+ const M = { ...defaultMaterial, ...material };
450
+ let cam = makeCamera(view, mesh, size, fit);
451
+ if (xr) {
452
+ // a WebXR eye: its axes from the rows of the view matrix (right, up, back), its place from the caller
453
+ const v = xr.view;
454
+ cam = { ...cam, eye: [...xr.eye], r: [v[0], v[4], v[8]], u: [v[1], v[5], v[9]], f: [-v[2], -v[6], -v[10]], ortho: false };
455
+ marks = undefined;
456
+ }
457
+ else {
458
+ const n = Math.max(1, Math.round(size * dpr));
459
+ if (n !== px) {
460
+ px = n;
461
+ canvas.width = n;
462
+ canvas.height = n;
463
+ }
464
+ }
465
+ const crease = smooth === true ? 40 : smooth || 0;
466
+ if (mesh !== uploaded || palette !== uploadedPalette || crease !== uploadedSmooth) {
467
+ uploadedSmooth = crease;
468
+ let all;
469
+ if (parts && parts.length) {
470
+ if (palette !== partPalette || crease !== partSmooth) {
471
+ partCache = new WeakMap();
472
+ partPalette = palette;
473
+ partSmooth = crease;
474
+ }
475
+ const built = parts.map((m) => {
476
+ let v = partCache.get(m);
477
+ if (!v)
478
+ partCache.set(m, (v = buildVertices(m, palette, { smooth: crease })));
479
+ return v;
480
+ });
481
+ all = new Float32Array(built.reduce((s, v) => s + v.length, 0));
482
+ let at = 0;
483
+ for (const v of built) {
484
+ all.set(v, at);
485
+ at += v.length;
486
+ }
487
+ }
488
+ else
489
+ all = buildVertices(mesh, palette, { smooth: crease });
490
+ // solid triangles first; triangles with alpha < 1 are kept apart and blended afterwards
491
+ const tri = 3 * GL_FLOATS;
492
+ const solid = new Float32Array(all.length);
493
+ let solidLen = 0;
494
+ glassTris = [];
495
+ for (let o = 0; o < all.length; o += tri) {
496
+ if (all[o + 11] < 1) {
497
+ const c = [0, 1, 2].map((k) => (all[o + k] + all[o + GL_FLOATS + k] + all[o + 2 * GL_FLOATS + k]) / 3);
498
+ glassTris.push({ c, at: o });
499
+ }
500
+ else {
501
+ solid.set(all.subarray(o, o + tri), solidLen);
502
+ solidLen += tri;
503
+ }
504
+ }
505
+ glassSource = all;
506
+ glassEye = '';
507
+ upload(solidBuf, solid.subarray(0, solidLen));
508
+ vertexCount = solidLen / GL_FLOATS;
509
+ uploaded = mesh;
510
+ uploadedPalette = palette;
511
+ }
512
+ if (!edges)
513
+ edgeCount = 0;
514
+ else if (mesh !== edgeMesh || parts !== edgeParts || !edgeOn) {
515
+ const e = sceneEdges(mesh, parts);
516
+ upload(edgeBuf, e);
517
+ edgeCount = e.length / 3;
518
+ edgeMesh = mesh;
519
+ edgeParts = parts;
520
+ }
521
+ edgeOn = edges;
522
+ if (instances?.mesh && instances.mesh !== protoMesh) {
523
+ const v = buildVertices(instances.mesh);
524
+ upload(protoBuf, v);
525
+ protoCount = v.length / GL_FLOATS;
526
+ protoMesh = instances.mesh;
527
+ }
528
+ if (instances?.data && instances.data !== instData) {
529
+ upload(instBuf, instances.data);
530
+ instData = instances.data;
531
+ instCount = instances.data.length / GL_INSTANCE_FLOATS;
532
+ }
533
+ if (!instances)
534
+ instCount = 0;
535
+ let bones = null;
536
+ if (skin && skin.meshes.length) {
537
+ const v = skinVerts(skin, palette, crease);
538
+ if (v.fresh) {
539
+ upload(skinSolidBuf, v.solid);
540
+ upload(skinGlassBuf, v.glass);
541
+ skinSolidCount = v.solid.length / SKIN_FLOATS;
542
+ skinGlassCount = v.glass.length / SKIN_FLOATS;
543
+ }
544
+ bones = skin.bones.subarray(0, MAX_BONES * 12);
545
+ }
546
+ else
547
+ skinSolidCount = skinGlassCount = 0;
548
+ const eyeKey = cam.eye.join(',');
549
+ if (glassTris.length && eyeKey !== glassEye) {
550
+ glassEye = eyeKey;
551
+ const [ex, ey, ez] = cam.eye;
552
+ const far = (t) => (t.c[0] - ex) ** 2 + (t.c[1] - ey) ** 2 + (t.c[2] - ez) ** 2;
553
+ const sorted = [...glassTris].sort((a, b) => far(b) - far(a)); // far first
554
+ const out = new Float32Array(sorted.length * 3 * GL_FLOATS);
555
+ sorted.forEach((t, k) => out.set(glassSource.subarray(t.at, t.at + 3 * GL_FLOATS), k * 3 * GL_FLOATS));
556
+ upload(glassBuf, out);
557
+ glassCount = sorted.length * 3;
558
+ }
559
+ if (!glassTris.length)
560
+ glassCount = 0;
561
+ // studio rig, relative to the camera: key upper left in front, fill from the right, rim from behind and above
562
+ const rig = (f, r, up) => norm([0, 1, 2].map((k) => -cam.f[k] * f + cam.r[k] * r + cam.u[k] * up));
563
+ const S = studio ? { fill: 0.4, rim: 1, ...(studio === true ? {} : studio) } : null;
564
+ const vp = xr ? mul4(xr.projection, xr.view) : viewProjection(cam, nearPlane(cam, mesh));
565
+ const ld = logDepth > 0 && !cam.ortho ? logDepth : 0; // logarithmic depth (GpuRenderOptions.logDepth)
566
+ const key = S ? rig(0.7, -0.5, 0.6) : norm(L.direction);
567
+ const fill = rig(0.6, 0.8, 0.1);
568
+ const rim = rig(-0.8, 0.3, 0.5);
569
+ const glowLights = glow ? sceneLights(mesh, parts, palette, skin) : new Float32Array(0);
570
+ const glowN = glowLights.length / LIGHT_FLOATS;
571
+ const glowPos = new Float32Array(MAX_LIGHTS * 4);
572
+ const glowCol = new Float32Array(MAX_LIGHTS * 4);
573
+ for (let k = 0; k < glowN; k++) {
574
+ glowPos.set(glowLights.subarray(k * LIGHT_FLOATS, k * LIGHT_FLOATS + 4), k * 4);
575
+ glowCol.set(glowLights.subarray(k * LIGHT_FLOATS + 4, k * LIGHT_FLOATS + 7), k * 4);
576
+ }
577
+ const setU = (u) => {
578
+ gl.uniformMatrix4fv(u.vp, false, vp);
579
+ gl.uniform1f(u.ld, ld);
580
+ gl.uniform4f(u.light, key[0], key[1], key[2], unlit ? 1 : 0);
581
+ gl.uniform4f(u.sky, L.sky[0], L.sky[1], L.sky[2], 0);
582
+ gl.uniform4f(u.ground, L.ground[0], L.ground[1], L.ground[2], 0);
583
+ gl.uniform4f(u.eye, cam.eye[0], cam.eye[1], cam.eye[2], 0);
584
+ gl.uniform4f(u.mat, M.ambient, M.diffuse, M.specular, M.shininess);
585
+ gl.uniform4f(u.fx, filmic ? 1 : 0, filmic ? filmic.exposure : 1, filmic ? filmic.emit : 0, S ? 1 : 0);
586
+ gl.uniform4f(u.fill, fill[0], fill[1], fill[2], S ? S.fill : 0);
587
+ gl.uniform4f(u.rim, rim[0], rim[1], rim[2], S ? S.rim : 0);
588
+ gl.uniform1f(u.ln, glowN);
589
+ if (glowN) {
590
+ gl.uniform4fv(u.lp, glowPos);
591
+ gl.uniform4fv(u.lc, glowCol);
592
+ }
593
+ };
594
+ if (xr) {
595
+ // into the XR layer's framebuffer, only this eye's part of it (the scissor keeps the other eye when clearing)
596
+ const [x, y, w, h] = xr.viewport;
597
+ gl.bindFramebuffer(gl.FRAMEBUFFER, xr.framebuffer);
598
+ gl.viewport(x, y, w, h);
599
+ gl.enable(gl.SCISSOR_TEST);
600
+ gl.scissor(x, y, w, h);
601
+ }
602
+ else {
603
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null);
604
+ gl.disable(gl.SCISSOR_TEST);
605
+ gl.viewport(0, 0, px, px);
606
+ }
607
+ gl.clearColor(transparent ? 0 : background[0], transparent ? 0 : background[1], transparent ? 0 : background[2], transparent ? 0 : 1);
608
+ gl.clearDepth(1);
609
+ gl.depthMask(true);
610
+ gl.disable(gl.BLEND);
611
+ gl.enable(gl.DEPTH_TEST);
612
+ gl.depthFunc(gl.LESS);
613
+ gl.disable(gl.CULL_FACE);
614
+ gl.clear(xr?.overlay ? gl.DEPTH_BUFFER_BIT : gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
615
+ if (vertexCount) {
616
+ gl.useProgram(meshProg);
617
+ setU(meshU);
618
+ gl.bindVertexArray(solidVao);
619
+ gl.drawArrays(gl.TRIANGLES, 0, vertexCount);
620
+ }
621
+ if (instCount && protoCount) {
622
+ gl.useProgram(instProg);
623
+ setU(instU);
624
+ gl.bindVertexArray(instVao);
625
+ gl.drawArraysInstanced(gl.TRIANGLES, 0, protoCount, instCount);
626
+ }
627
+ const drawSkin = (vao, count) => {
628
+ gl.useProgram(skinProg);
629
+ setU(skinU);
630
+ if (bones && bones.length)
631
+ gl.uniform4fv(skinBones, bones);
632
+ emission.fill(1);
633
+ if (skin?.emission)
634
+ emission.set(skin.emission.subarray(0, MAX_BONES));
635
+ gl.uniform4fv(skinEmission, emission);
636
+ gl.bindVertexArray(vao);
637
+ gl.drawArrays(gl.TRIANGLES, 0, count);
638
+ };
639
+ if (skinSolidCount)
640
+ drawSkin(skinSolidVao, skinSolidCount);
641
+ // screens: each picture into its texture, then its quad, depth tested like a face
642
+ const shown = (screens ?? []).map((sc, i) => ({ sc, i })).filter(({ sc }) => !sc.hole && (sc.source?.width | 0) > 0 && (sc.source?.height | 0) > 0);
643
+ const holes = (screens ?? []).map((sc, i) => ({ sc, i })).filter(({ sc }) => sc.hole);
644
+ if (holes.length) {
645
+ // holes: transparent pixels, depth tested (a page behind the canvas shows through)
646
+ upload(screenBuf, buildScreenQuads(screens));
647
+ gl.useProgram(holeProg);
648
+ gl.uniformMatrix4fv(holeVp, false, vp);
649
+ gl.uniform1f(holeLd, ld);
650
+ gl.bindVertexArray(screenVao);
651
+ for (const { i } of holes)
652
+ gl.drawArrays(gl.TRIANGLES, i * 6, 6);
653
+ }
654
+ if (shown.length) {
655
+ upload(screenBuf, buildScreenQuads(screens));
656
+ gl.useProgram(screenProg);
657
+ gl.uniformMatrix4fv(screenVp, false, vp);
658
+ gl.uniform1f(screenLd, ld);
659
+ gl.uniform1i(screenTexU, 0);
660
+ gl.activeTexture(gl.TEXTURE0);
661
+ gl.bindVertexArray(screenVao);
662
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
663
+ for (const { sc, i } of shown) {
664
+ let t = screenTex[i];
665
+ if (!t) {
666
+ t = screenTex[i] = gl.createTexture();
667
+ gl.bindTexture(gl.TEXTURE_2D, t);
668
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
669
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
670
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
671
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
672
+ }
673
+ else
674
+ gl.bindTexture(gl.TEXTURE_2D, t);
675
+ try {
676
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, sc.source);
677
+ gl.drawArrays(gl.TRIANGLES, i * 6, 6);
678
+ }
679
+ catch { }
680
+ }
681
+ }
682
+ // the shader planets (planet.ts): ray-traced over the scene, writing their depth
683
+ if (planets?.length && !cam.ortho) {
684
+ let vpRot;
685
+ let eye = cam.eye;
686
+ if (xr) {
687
+ const v = Float32Array.from(xr.view);
688
+ v[12] = v[13] = v[14] = 0;
689
+ vpRot = mul4(xr.projection, v);
690
+ eye = xr.eye;
691
+ }
692
+ else
693
+ vpRot = viewProjection({ ...cam, eye: [0, 0, 0] }, nearPlane(cam, mesh));
694
+ const inv = inv4(vpRot);
695
+ const pi = inv ? planetInstances(planets, eye, vpRot) : null;
696
+ if (pi?.count && inv) {
697
+ gl.bindBuffer(gl.ARRAY_BUFFER, planetBuf);
698
+ gl.bufferData(gl.ARRAY_BUFFER, pi.data, gl.DYNAMIC_DRAW);
699
+ gl.useProgram(planetProg);
700
+ gl.uniformMatrix4fv(planetU.inv, false, inv);
701
+ gl.uniformMatrix4fv(planetU.vp, false, vpRot);
702
+ const [vx, vy, vw, vh] = xr ? xr.viewport : [0, 0, px, px];
703
+ gl.uniform4f(planetU.res, vw, vh, ld, 0);
704
+ gl.uniform4f(planetU.off, vx, vy, 0, 0);
705
+ gl.enable(gl.BLEND);
706
+ gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
707
+ gl.bindVertexArray(planetVao);
708
+ gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, pi.count);
709
+ gl.disable(gl.BLEND);
710
+ }
711
+ }
712
+ if (edgeCount) {
713
+ gl.useProgram(lineProg);
714
+ gl.uniformMatrix4fv(lineVp, false, vp);
715
+ gl.uniform1f(lineLd, ld);
716
+ gl.uniform1f(lineUnlit, unlit ? 1 : 0);
717
+ gl.enable(gl.BLEND);
718
+ gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
719
+ gl.depthFunc(gl.LEQUAL);
720
+ gl.depthMask(false);
721
+ gl.bindVertexArray(edgeVao);
722
+ gl.drawArrays(gl.LINES, 0, edgeCount);
723
+ gl.depthMask(true);
724
+ gl.depthFunc(gl.LESS);
725
+ gl.disable(gl.BLEND);
726
+ }
727
+ if (glassCount) {
728
+ // after everything solid: see-through faces, far to near; they test depth but do not write it
729
+ gl.useProgram(meshProg);
730
+ setU(meshU);
731
+ gl.enable(gl.BLEND);
732
+ gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
733
+ gl.depthMask(false);
734
+ gl.bindVertexArray(glassVao);
735
+ gl.drawArrays(gl.TRIANGLES, 0, glassCount);
736
+ gl.depthMask(true);
737
+ gl.disable(gl.BLEND);
738
+ }
739
+ if (skinGlassCount) {
740
+ gl.enable(gl.BLEND);
741
+ gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
742
+ gl.depthMask(false);
743
+ drawSkin(skinGlassVao, skinGlassCount);
744
+ gl.depthMask(true);
745
+ gl.disable(gl.BLEND);
746
+ }
747
+ // the marks relative to the eye, drawn with the eye-centred matrix (an orbit far from the origin stays put near the camera)
748
+ const markEye = xr ? xr.eye : cam.eye;
749
+ const markData = marks?.length ? buildMarks(marks, markEye) : null;
750
+ markCount = markData ? markData.length / MARK_FLOATS : 0;
751
+ if (markCount && markData) {
752
+ let vpe;
753
+ if (xr) {
754
+ const v = Float32Array.from(xr.view);
755
+ v[12] = v[13] = v[14] = 0;
756
+ vpe = mul4(xr.projection, v);
757
+ }
758
+ else
759
+ vpe = viewProjection({ ...cam, eye: [0, 0, 0] }, nearPlane(cam, mesh));
760
+ gl.bindBuffer(gl.ARRAY_BUFFER, markBuf);
761
+ gl.bufferData(gl.ARRAY_BUFFER, markData, gl.DYNAMIC_DRAW);
762
+ gl.useProgram(markProg);
763
+ gl.uniformMatrix4fv(markVp, false, vpe);
764
+ gl.uniform1f(markFocal, cam.ortho ? 0 : cam.k * (px / size));
765
+ gl.uniform1f(markLd, ld);
766
+ gl.uniform3f(markRes, px, px, px / size);
767
+ gl.disable(gl.DEPTH_TEST);
768
+ gl.depthMask(false);
769
+ gl.enable(gl.BLEND);
770
+ gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
771
+ gl.bindVertexArray(markVao);
772
+ gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, markCount);
773
+ gl.disable(gl.BLEND);
774
+ gl.depthMask(true);
775
+ gl.enable(gl.DEPTH_TEST);
776
+ }
777
+ gl.bindVertexArray(null);
778
+ if (xr)
779
+ gl.disable(gl.SCISSOR_TEST);
780
+ };
781
+ const render = (mesh, view, options) => draw(mesh, view, options);
782
+ const pixels = (mesh, view, options) => {
783
+ draw(mesh, view, options);
784
+ const raw = new Uint8Array(px * px * 4);
785
+ gl.readPixels(0, 0, px, px, gl.RGBA, gl.UNSIGNED_BYTE, raw); // read in the same task as the draw, before the buffer is presented
786
+ const data = new Uint8ClampedArray(px * px * 4);
787
+ for (let y = 0; y < px; y++)
788
+ data.set(raw.subarray((px - 1 - y) * px * 4, (px - y) * px * 4), y * px * 4); // GL rows go bottom up
789
+ if (!options?.transparent)
790
+ for (let i = 3; i < data.length; i += 4)
791
+ data[i] = 255;
792
+ return Promise.resolve({ width: px, height: px, data });
793
+ };
794
+ const destroy = () => {
795
+ gl.getExtension('WEBGL_lose_context')?.loseContext();
796
+ };
797
+ return { render, pixels, destroy, device: { lost }, adapter: null, context: gl };
798
+ };