@es3d/es3d 1.0.0 → 1.0.1

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 (79) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +86 -86
  3. package/docs/SPEC.md +417 -417
  4. package/package.json +1 -1
  5. package/scripts/es3d-cli.mjs +377 -377
  6. package/src/cache/geometry-store.js +392 -392
  7. package/src/cache/mesh-bundle.js +123 -123
  8. package/src/cache/sha256.js +73 -73
  9. package/src/format/ast.js +238 -238
  10. package/src/format/colors.js +93 -93
  11. package/src/format/compact-parser.js +171 -171
  12. package/src/format/compact-tokenizer.js +165 -165
  13. package/src/format/errors.js +247 -247
  14. package/src/format/json.js +55 -55
  15. package/src/format/limits.js +14 -14
  16. package/src/format/parse.js +92 -92
  17. package/src/format/schema.js +617 -617
  18. package/src/format/serializer.js +333 -333
  19. package/src/format/validator.js +330 -330
  20. package/src/format/value-error.js +12 -12
  21. package/src/format/value-format.js +314 -314
  22. package/src/format/values.js +459 -459
  23. package/src/format/xml-parser.js +136 -136
  24. package/src/format/xml-tokenizer.js +237 -237
  25. package/src/geometry/contour.js +86 -86
  26. package/src/geometry/extrude.js +175 -175
  27. package/src/geometry/gear.js +85 -85
  28. package/src/geometry/geometry-cache.js +159 -159
  29. package/src/geometry/lod-error.js +178 -178
  30. package/src/geometry/mesh.js +458 -458
  31. package/src/geometry/primitives.js +299 -299
  32. package/src/geometry/registry.js +645 -645
  33. package/src/geometry/revolve.js +136 -136
  34. package/src/geometry/sweep.js +441 -441
  35. package/src/index.js +47 -47
  36. package/src/io/compression.js +67 -67
  37. package/src/io/convert.js +236 -236
  38. package/src/io/download.js +13 -13
  39. package/src/io/external-scene.js +127 -127
  40. package/src/io/file-loader.js +28 -28
  41. package/src/io/gltf.js +630 -630
  42. package/src/io/mesh-import.js +104 -104
  43. package/src/io/obj.js +352 -352
  44. package/src/io/step-brep.js +439 -439
  45. package/src/io/step-exact.js +1149 -1149
  46. package/src/io/step.js +1418 -1418
  47. package/src/io/stl.js +193 -193
  48. package/src/io/svg-import.js +787 -787
  49. package/src/material/materials.js +154 -154
  50. package/src/math/mat4.js +475 -475
  51. package/src/math/random.js +30 -30
  52. package/src/math/trig.js +65 -65
  53. package/src/math/vec3.js +81 -81
  54. package/src/optimize/optimizer.js +579 -579
  55. package/src/path/path-flatten.js +322 -322
  56. package/src/path/path-parser.js +332 -332
  57. package/src/path/shapes.js +129 -129
  58. package/src/path/triangulate.js +517 -517
  59. package/src/pipeline.js +74 -74
  60. package/src/render/camera.js +168 -168
  61. package/src/render/frame-builder.js +362 -362
  62. package/src/render/geometry-pool.js +149 -149
  63. package/src/render/lighting.js +149 -149
  64. package/src/render/orbit-controls.js +237 -237
  65. package/src/render/renderer.js +258 -249
  66. package/src/render/scroll-timeline.js +104 -104
  67. package/src/render/shaders/glsl.js +285 -285
  68. package/src/render/shaders/wgsl.js +252 -252
  69. package/src/render/stage.js +364 -352
  70. package/src/render/texture-cache.js +40 -40
  71. package/src/render/textures.js +223 -223
  72. package/src/render/webgl2/webgl2-backend.js +586 -532
  73. package/src/render/webgpu/webgpu-backend.js +482 -480
  74. package/src/scene/flatten.js +754 -754
  75. package/src/scene/picking.js +161 -161
  76. package/src/scene/scene-graph.js +320 -320
  77. package/src/transform/transform.js +211 -211
  78. package/src/wasm/kernels-binary.js +3 -3
  79. package/src/wasm/kernels.js +385 -385
@@ -1,40 +1,40 @@
1
- // Backend-independent texture bookkeeping: each distinct texture spec (by key
2
- // and usage) is generated or downloaded once; backends turn ready pixel data
3
- // into GPU textures. Failures are reported, never silently ignored.
4
-
5
- import { texturePixels } from './textures.js';
6
-
7
- export class TextureCache {
8
- constructor() {
9
- this.entries = new Map(); // `${kind}:${key}` -> {status, pixels, error, gpu, spec, kind}
10
- this.onReady = null; // called when an async texture finishes (request a redraw)
11
- this.onError = null;
12
- }
13
-
14
- /** Get (and start loading) a texture; returns the entry (status 'pending'|'ready'|'failed'). */
15
- get(spec, kind) {
16
- const id = `${kind}:${spec.key}`;
17
- let e = this.entries.get(id);
18
- if (e) return e;
19
- e = { id, spec, kind, status: 'pending', pixels: null, error: null, gpu: null };
20
- this.entries.set(id, e);
21
- texturePixels(spec, kind).then(
22
- (px) => {
23
- e.pixels = px;
24
- e.status = 'ready';
25
- if (this.onReady) this.onReady(e);
26
- },
27
- (err) => {
28
- e.status = 'failed';
29
- e.error = err;
30
- if (this.onError) this.onError(e, err);
31
- },
32
- );
33
- return e;
34
- }
35
-
36
- clear(destroy) {
37
- for (const e of this.entries.values()) if (e.gpu && destroy) destroy(e.gpu);
38
- this.entries.clear();
39
- }
40
- }
1
+ // Backend-independent texture bookkeeping: each distinct texture spec (by key
2
+ // and usage) is generated or downloaded once; backends turn ready pixel data
3
+ // into GPU textures. Failures are reported, never silently ignored.
4
+
5
+ import { texturePixels } from './textures.js';
6
+
7
+ export class TextureCache {
8
+ constructor() {
9
+ this.entries = new Map(); // `${kind}:${key}` -> {status, pixels, error, gpu, spec, kind}
10
+ this.onReady = null; // called when an async texture finishes (request a redraw)
11
+ this.onError = null;
12
+ }
13
+
14
+ /** Get (and start loading) a texture; returns the entry (status 'pending'|'ready'|'failed'). */
15
+ get(spec, kind) {
16
+ const id = `${kind}:${spec.key}`;
17
+ let e = this.entries.get(id);
18
+ if (e) return e;
19
+ e = { id, spec, kind, status: 'pending', pixels: null, error: null, gpu: null };
20
+ this.entries.set(id, e);
21
+ texturePixels(spec, kind).then(
22
+ (px) => {
23
+ e.pixels = px;
24
+ e.status = 'ready';
25
+ if (this.onReady) this.onReady(e);
26
+ },
27
+ (err) => {
28
+ e.status = 'failed';
29
+ e.error = err;
30
+ if (this.onError) this.onError(e, err);
31
+ },
32
+ );
33
+ return e;
34
+ }
35
+
36
+ clear(destroy) {
37
+ for (const e of this.entries.values()) if (e.gpu && destroy) destroy(e.gpu);
38
+ this.entries.clear();
39
+ }
40
+ }
@@ -1,223 +1,223 @@
1
- // Texture sources: procedural textures generated on the CPU (portable, no
2
- // image files needed) and image URLs (browser only). Procedural textures are
3
- // tileable so they repeat seamlessly with uvScale.
4
-
5
- import { hash2 } from '../math/random.js';
6
-
7
- const SIZE = 256;
8
-
9
- function rgba8(c) {
10
- return [Math.round(c[0] * 255), Math.round(c[1] * 255), Math.round(c[2] * 255), Math.round((c[3] ?? 1) * 255)];
11
- }
12
-
13
- function smoothstep(a, b, x) {
14
- const t = Math.max(0, Math.min(1, (x - a) / (b - a)));
15
- return t * t * (3 - 2 * t);
16
- }
17
-
18
- /** Tileable value noise (period = `period` cells) with fBm octaves. */
19
- function valueNoise(u, v, period, seed) {
20
- const x = u * period, y = v * period;
21
- const x0 = Math.floor(x), y0 = Math.floor(y);
22
- const fx = x - x0, fy = y - y0;
23
- const sx = fx * fx * (3 - 2 * fx), sy = fy * fy * (3 - 2 * fy);
24
- const h = (i, j) => hash2(((i % period) + period) % period, ((j % period) + period) % period, seed);
25
- const a = h(x0, y0), b = h(x0 + 1, y0), c = h(x0, y0 + 1), d = h(x0 + 1, y0 + 1);
26
- return a + (b - a) * sx + (c - a) * sy + (a - b - c + d) * sx * sy;
27
- }
28
-
29
- function fbm(u, v, period, seed) {
30
- let sum = 0, amp = 0.5, p = Math.max(1, Math.round(period)), norm = 0;
31
- for (let o = 0; o < 5; o++) {
32
- sum += valueNoise(u, v, p, seed + o * 17) * amp;
33
- norm += amp;
34
- amp *= 0.5;
35
- p *= 2;
36
- }
37
- return sum / norm;
38
- }
39
-
40
- function fill(size, fn) {
41
- const data = new Uint8ClampedArray(size * size * 4);
42
- for (let y = 0; y < size; y++) {
43
- for (let x = 0; x < size; x++) {
44
- const c = fn((x + 0.5) / size, (y + 0.5) / size);
45
- const o = (y * size + x) * 4;
46
- data[o] = c[0];
47
- data[o + 1] = c[1];
48
- data[o + 2] = c[2];
49
- data[o + 3] = c[3];
50
- }
51
- }
52
- return { width: size, height: size, data };
53
- }
54
-
55
- function mix(a, b, t) {
56
- return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t, a[3] + (b[3] - a[3]) * t];
57
- }
58
-
59
- /** Base color textures (sRGB values). */
60
- export function proceduralColor(spec, size = SIZE) {
61
- const p = spec.params;
62
- switch (spec.fn) {
63
- case 'checker': {
64
- const a = rgba8(p.color1), b = rgba8(p.color2);
65
- const n = Math.max(1, Math.round(p.count));
66
- return fill(size, (u, v) => ((Math.floor(u * n) + Math.floor(v * n)) % 2 === 0 ? a : b));
67
- }
68
- case 'stripes': {
69
- const a = rgba8(p.color1), b = rgba8(p.color2);
70
- const n = Math.max(1, Math.round(p.count));
71
- return fill(size, (u) => (Math.floor(u * n * 2) % 2 === 0 ? a : b));
72
- }
73
- case 'grid': {
74
- const line = rgba8(p.line), bg = rgba8(p.background);
75
- const n = Math.max(1, Math.round(p.count));
76
- const w = p.width / 2;
77
- return fill(size, (u, v) => {
78
- const fu = (u * n) % 1, fv = (v * n) % 1;
79
- const d = Math.min(fu, 1 - fu, fv, 1 - fv);
80
- return mix(line, bg, smoothstep(w * 0.6, w, d));
81
- });
82
- }
83
- case 'noise': {
84
- const a = rgba8(p.color1), b = rgba8(p.color2);
85
- return fill(size, (u, v) => mix(b, a, fbm(u, v, p.scale, p.seed)));
86
- }
87
- case 'bricks': {
88
- const brick = rgba8(p.brick), mortar = rgba8(p.mortar);
89
- const rows = Math.max(1, Math.round(p.count));
90
- return fill(size, (u, v) => {
91
- const row = Math.floor(v * rows);
92
- const uu = (u * rows * 0.5 + (row % 2) * 0.5) % 1;
93
- const fv = (v * rows) % 1;
94
- const d = Math.min(uu, 1 - uu, fv, 1 - fv);
95
- const shade = 0.88 + 0.24 * hash2(Math.floor(u * rows * 0.5 + (row % 2) * 0.5), row, 7);
96
- const b = [brick[0] * shade, brick[1] * shade, brick[2] * shade, 255];
97
- return mix(mortar, b, smoothstep(0.03, 0.06, d));
98
- });
99
- }
100
- default:
101
- throw new Error(`unknown procedural texture ${spec.fn}`);
102
- }
103
- }
104
-
105
- /** Height functions for normal maps (0..1 range, tileable). */
106
- function heightFn(spec) {
107
- const p = spec.params;
108
- switch (spec.fn) {
109
- case 'bumps': {
110
- const n = Math.max(1, Math.round(p.count));
111
- return (u, v) => {
112
- const fu = (u * n) % 1 - 0.5, fv = (v * n) % 1 - 0.5;
113
- const r = Math.hypot(fu, fv) * 2.4;
114
- return r < 1 ? Math.sqrt(1 - r * r) : 0;
115
- };
116
- }
117
- case 'tiles': {
118
- const n = Math.max(1, Math.round(p.count));
119
- return (u, v) => {
120
- const fu = (u * n) % 1, fv = (v * n) % 1;
121
- const d = Math.min(fu, 1 - fu, fv, 1 - fv);
122
- return smoothstep(p.gap * 0.5, p.gap * 1.5, d);
123
- };
124
- }
125
- case 'noise':
126
- return (u, v) => fbm(u, v, p.scale, p.seed);
127
- case 'waves': {
128
- const n = Math.max(1, Math.round(p.count));
129
- return (u) => 0.5 + 0.5 * Math.sin(u * n * Math.PI * 2);
130
- }
131
- case 'bricks': {
132
- const rows = Math.max(1, Math.round(p.count));
133
- return (u, v) => {
134
- const row = Math.floor(v * rows);
135
- const uu = (u * rows * 0.5 + (row % 2) * 0.5) % 1;
136
- const fv = (v * rows) % 1;
137
- return smoothstep(0.02, 0.07, Math.min(uu, 1 - uu, fv, 1 - fv));
138
- };
139
- }
140
- default:
141
- throw new Error(`unknown procedural normal map ${spec.fn}`);
142
- }
143
- }
144
-
145
- /** Tangent-space normal map (RGB = n * 0.5 + 0.5) from a procedural height field. */
146
- export function proceduralNormal(spec, size = SIZE) {
147
- const h = heightFn(spec);
148
- const strength = spec.params.strength ?? 1;
149
- const heights = new Float32Array(size * size);
150
- for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) heights[y * size + x] = h((x + 0.5) / size, (y + 0.5) / size);
151
- const data = new Uint8ClampedArray(size * size * 4);
152
- const scale = strength * size * 0.02;
153
- for (let y = 0; y < size; y++) {
154
- for (let x = 0; x < size; x++) {
155
- const at = (i, j) => heights[((j + size) % size) * size + ((i + size) % size)];
156
- const dx = (at(x + 1, y) - at(x - 1, y)) * scale;
157
- const dy = (at(x, y + 1) - at(x, y - 1)) * scale;
158
- // image row y corresponds to texture coordinate v, so the tangent-space
159
- // normal of the height field h(u, v) is (-dh/du, -dh/dv, 1)
160
- let nx = -dx, ny = -dy, nz = 1;
161
- const l = Math.hypot(nx, ny, nz);
162
- nx /= l;
163
- ny /= l;
164
- nz /= l;
165
- const o = (y * size + x) * 4;
166
- data[o] = Math.round((nx * 0.5 + 0.5) * 255);
167
- data[o + 1] = Math.round((ny * 0.5 + 0.5) * 255);
168
- data[o + 2] = Math.round((nz * 0.5 + 0.5) * 255);
169
- data[o + 3] = 255;
170
- }
171
- }
172
- return { width: size, height: size, data };
173
- }
174
-
175
- /** Box-filtered mip chain (level 0 is the input). */
176
- export function buildMips(img) {
177
- const levels = [img];
178
- let cur = img;
179
- while (cur.width > 1 || cur.height > 1) {
180
- const w = Math.max(1, cur.width >> 1), h = Math.max(1, cur.height >> 1);
181
- const out = new Uint8ClampedArray(w * h * 4);
182
- for (let y = 0; y < h; y++) {
183
- for (let x = 0; x < w; x++) {
184
- for (let c = 0; c < 4; c++) {
185
- let s = 0, k = 0;
186
- for (let dy = 0; dy < 2; dy++) {
187
- for (let dx = 0; dx < 2; dx++) {
188
- const sx = Math.min(cur.width - 1, x * 2 + dx), sy = Math.min(cur.height - 1, y * 2 + dy);
189
- s += cur.data[(sy * cur.width + sx) * 4 + c];
190
- k++;
191
- }
192
- }
193
- out[(y * w + x) * 4 + c] = s / k;
194
- }
195
- }
196
- }
197
- cur = { width: w, height: h, data: out };
198
- levels.push(cur);
199
- }
200
- return levels;
201
- }
202
-
203
- /** Load an image URL into RGBA pixels (browser only). */
204
- export async function loadImagePixels(url) {
205
- const res = await fetch(url);
206
- if (!res.ok) throw new Error(`HTTP ${res.status} for ${url}`);
207
- const blob = await res.blob();
208
- const bmp = await createImageBitmap(blob);
209
- // power-of-two size keeps mipmapping and repeat wrapping valid everywhere
210
- const pot = (v) => Math.min(2048, 2 ** Math.round(Math.log2(Math.max(1, v))));
211
- const w = pot(bmp.width), h = pot(bmp.height);
212
- const canvas = typeof OffscreenCanvas !== 'undefined' ? new OffscreenCanvas(w, h) : Object.assign(document.createElement('canvas'), { width: w, height: h });
213
- const ctx = canvas.getContext('2d');
214
- ctx.drawImage(bmp, 0, 0, w, h);
215
- const id = ctx.getImageData(0, 0, w, h);
216
- return { width: w, height: h, data: id.data };
217
- }
218
-
219
- /** Resolve a texture spec into pixels (sync for procedural, async for URLs). */
220
- export function texturePixels(spec, kind) {
221
- if (spec.kind === 'procedural') return Promise.resolve(kind === 'normal' ? proceduralNormal(spec) : proceduralColor(spec));
222
- return loadImagePixels(spec.url);
223
- }
1
+ // Texture sources: procedural textures generated on the CPU (portable, no
2
+ // image files needed) and image URLs (browser only). Procedural textures are
3
+ // tileable so they repeat seamlessly with uvScale.
4
+
5
+ import { hash2 } from '../math/random.js';
6
+
7
+ const SIZE = 256;
8
+
9
+ function rgba8(c) {
10
+ return [Math.round(c[0] * 255), Math.round(c[1] * 255), Math.round(c[2] * 255), Math.round((c[3] ?? 1) * 255)];
11
+ }
12
+
13
+ function smoothstep(a, b, x) {
14
+ const t = Math.max(0, Math.min(1, (x - a) / (b - a)));
15
+ return t * t * (3 - 2 * t);
16
+ }
17
+
18
+ /** Tileable value noise (period = `period` cells) with fBm octaves. */
19
+ function valueNoise(u, v, period, seed) {
20
+ const x = u * period, y = v * period;
21
+ const x0 = Math.floor(x), y0 = Math.floor(y);
22
+ const fx = x - x0, fy = y - y0;
23
+ const sx = fx * fx * (3 - 2 * fx), sy = fy * fy * (3 - 2 * fy);
24
+ const h = (i, j) => hash2(((i % period) + period) % period, ((j % period) + period) % period, seed);
25
+ const a = h(x0, y0), b = h(x0 + 1, y0), c = h(x0, y0 + 1), d = h(x0 + 1, y0 + 1);
26
+ return a + (b - a) * sx + (c - a) * sy + (a - b - c + d) * sx * sy;
27
+ }
28
+
29
+ function fbm(u, v, period, seed) {
30
+ let sum = 0, amp = 0.5, p = Math.max(1, Math.round(period)), norm = 0;
31
+ for (let o = 0; o < 5; o++) {
32
+ sum += valueNoise(u, v, p, seed + o * 17) * amp;
33
+ norm += amp;
34
+ amp *= 0.5;
35
+ p *= 2;
36
+ }
37
+ return sum / norm;
38
+ }
39
+
40
+ function fill(size, fn) {
41
+ const data = new Uint8ClampedArray(size * size * 4);
42
+ for (let y = 0; y < size; y++) {
43
+ for (let x = 0; x < size; x++) {
44
+ const c = fn((x + 0.5) / size, (y + 0.5) / size);
45
+ const o = (y * size + x) * 4;
46
+ data[o] = c[0];
47
+ data[o + 1] = c[1];
48
+ data[o + 2] = c[2];
49
+ data[o + 3] = c[3];
50
+ }
51
+ }
52
+ return { width: size, height: size, data };
53
+ }
54
+
55
+ function mix(a, b, t) {
56
+ return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t, a[3] + (b[3] - a[3]) * t];
57
+ }
58
+
59
+ /** Base color textures (sRGB values). */
60
+ export function proceduralColor(spec, size = SIZE) {
61
+ const p = spec.params;
62
+ switch (spec.fn) {
63
+ case 'checker': {
64
+ const a = rgba8(p.color1), b = rgba8(p.color2);
65
+ const n = Math.max(1, Math.round(p.count));
66
+ return fill(size, (u, v) => ((Math.floor(u * n) + Math.floor(v * n)) % 2 === 0 ? a : b));
67
+ }
68
+ case 'stripes': {
69
+ const a = rgba8(p.color1), b = rgba8(p.color2);
70
+ const n = Math.max(1, Math.round(p.count));
71
+ return fill(size, (u) => (Math.floor(u * n * 2) % 2 === 0 ? a : b));
72
+ }
73
+ case 'grid': {
74
+ const line = rgba8(p.line), bg = rgba8(p.background);
75
+ const n = Math.max(1, Math.round(p.count));
76
+ const w = p.width / 2;
77
+ return fill(size, (u, v) => {
78
+ const fu = (u * n) % 1, fv = (v * n) % 1;
79
+ const d = Math.min(fu, 1 - fu, fv, 1 - fv);
80
+ return mix(line, bg, smoothstep(w * 0.6, w, d));
81
+ });
82
+ }
83
+ case 'noise': {
84
+ const a = rgba8(p.color1), b = rgba8(p.color2);
85
+ return fill(size, (u, v) => mix(b, a, fbm(u, v, p.scale, p.seed)));
86
+ }
87
+ case 'bricks': {
88
+ const brick = rgba8(p.brick), mortar = rgba8(p.mortar);
89
+ const rows = Math.max(1, Math.round(p.count));
90
+ return fill(size, (u, v) => {
91
+ const row = Math.floor(v * rows);
92
+ const uu = (u * rows * 0.5 + (row % 2) * 0.5) % 1;
93
+ const fv = (v * rows) % 1;
94
+ const d = Math.min(uu, 1 - uu, fv, 1 - fv);
95
+ const shade = 0.88 + 0.24 * hash2(Math.floor(u * rows * 0.5 + (row % 2) * 0.5), row, 7);
96
+ const b = [brick[0] * shade, brick[1] * shade, brick[2] * shade, 255];
97
+ return mix(mortar, b, smoothstep(0.03, 0.06, d));
98
+ });
99
+ }
100
+ default:
101
+ throw new Error(`unknown procedural texture ${spec.fn}`);
102
+ }
103
+ }
104
+
105
+ /** Height functions for normal maps (0..1 range, tileable). */
106
+ function heightFn(spec) {
107
+ const p = spec.params;
108
+ switch (spec.fn) {
109
+ case 'bumps': {
110
+ const n = Math.max(1, Math.round(p.count));
111
+ return (u, v) => {
112
+ const fu = (u * n) % 1 - 0.5, fv = (v * n) % 1 - 0.5;
113
+ const r = Math.hypot(fu, fv) * 2.4;
114
+ return r < 1 ? Math.sqrt(1 - r * r) : 0;
115
+ };
116
+ }
117
+ case 'tiles': {
118
+ const n = Math.max(1, Math.round(p.count));
119
+ return (u, v) => {
120
+ const fu = (u * n) % 1, fv = (v * n) % 1;
121
+ const d = Math.min(fu, 1 - fu, fv, 1 - fv);
122
+ return smoothstep(p.gap * 0.5, p.gap * 1.5, d);
123
+ };
124
+ }
125
+ case 'noise':
126
+ return (u, v) => fbm(u, v, p.scale, p.seed);
127
+ case 'waves': {
128
+ const n = Math.max(1, Math.round(p.count));
129
+ return (u) => 0.5 + 0.5 * Math.sin(u * n * Math.PI * 2);
130
+ }
131
+ case 'bricks': {
132
+ const rows = Math.max(1, Math.round(p.count));
133
+ return (u, v) => {
134
+ const row = Math.floor(v * rows);
135
+ const uu = (u * rows * 0.5 + (row % 2) * 0.5) % 1;
136
+ const fv = (v * rows) % 1;
137
+ return smoothstep(0.02, 0.07, Math.min(uu, 1 - uu, fv, 1 - fv));
138
+ };
139
+ }
140
+ default:
141
+ throw new Error(`unknown procedural normal map ${spec.fn}`);
142
+ }
143
+ }
144
+
145
+ /** Tangent-space normal map (RGB = n * 0.5 + 0.5) from a procedural height field. */
146
+ export function proceduralNormal(spec, size = SIZE) {
147
+ const h = heightFn(spec);
148
+ const strength = spec.params.strength ?? 1;
149
+ const heights = new Float32Array(size * size);
150
+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) heights[y * size + x] = h((x + 0.5) / size, (y + 0.5) / size);
151
+ const data = new Uint8ClampedArray(size * size * 4);
152
+ const scale = strength * size * 0.02;
153
+ for (let y = 0; y < size; y++) {
154
+ for (let x = 0; x < size; x++) {
155
+ const at = (i, j) => heights[((j + size) % size) * size + ((i + size) % size)];
156
+ const dx = (at(x + 1, y) - at(x - 1, y)) * scale;
157
+ const dy = (at(x, y + 1) - at(x, y - 1)) * scale;
158
+ // image row y corresponds to texture coordinate v, so the tangent-space
159
+ // normal of the height field h(u, v) is (-dh/du, -dh/dv, 1)
160
+ let nx = -dx, ny = -dy, nz = 1;
161
+ const l = Math.hypot(nx, ny, nz);
162
+ nx /= l;
163
+ ny /= l;
164
+ nz /= l;
165
+ const o = (y * size + x) * 4;
166
+ data[o] = Math.round((nx * 0.5 + 0.5) * 255);
167
+ data[o + 1] = Math.round((ny * 0.5 + 0.5) * 255);
168
+ data[o + 2] = Math.round((nz * 0.5 + 0.5) * 255);
169
+ data[o + 3] = 255;
170
+ }
171
+ }
172
+ return { width: size, height: size, data };
173
+ }
174
+
175
+ /** Box-filtered mip chain (level 0 is the input). */
176
+ export function buildMips(img) {
177
+ const levels = [img];
178
+ let cur = img;
179
+ while (cur.width > 1 || cur.height > 1) {
180
+ const w = Math.max(1, cur.width >> 1), h = Math.max(1, cur.height >> 1);
181
+ const out = new Uint8ClampedArray(w * h * 4);
182
+ for (let y = 0; y < h; y++) {
183
+ for (let x = 0; x < w; x++) {
184
+ for (let c = 0; c < 4; c++) {
185
+ let s = 0, k = 0;
186
+ for (let dy = 0; dy < 2; dy++) {
187
+ for (let dx = 0; dx < 2; dx++) {
188
+ const sx = Math.min(cur.width - 1, x * 2 + dx), sy = Math.min(cur.height - 1, y * 2 + dy);
189
+ s += cur.data[(sy * cur.width + sx) * 4 + c];
190
+ k++;
191
+ }
192
+ }
193
+ out[(y * w + x) * 4 + c] = s / k;
194
+ }
195
+ }
196
+ }
197
+ cur = { width: w, height: h, data: out };
198
+ levels.push(cur);
199
+ }
200
+ return levels;
201
+ }
202
+
203
+ /** Load an image URL into RGBA pixels (browser only). */
204
+ export async function loadImagePixels(url) {
205
+ const res = await fetch(url);
206
+ if (!res.ok) throw new Error(`HTTP ${res.status} for ${url}`);
207
+ const blob = await res.blob();
208
+ const bmp = await createImageBitmap(blob);
209
+ // power-of-two size keeps mipmapping and repeat wrapping valid everywhere
210
+ const pot = (v) => Math.min(2048, 2 ** Math.round(Math.log2(Math.max(1, v))));
211
+ const w = pot(bmp.width), h = pot(bmp.height);
212
+ const canvas = typeof OffscreenCanvas !== 'undefined' ? new OffscreenCanvas(w, h) : Object.assign(document.createElement('canvas'), { width: w, height: h });
213
+ const ctx = canvas.getContext('2d');
214
+ ctx.drawImage(bmp, 0, 0, w, h);
215
+ const id = ctx.getImageData(0, 0, w, h);
216
+ return { width: w, height: h, data: id.data };
217
+ }
218
+
219
+ /** Resolve a texture spec into pixels (sync for procedural, async for URLs). */
220
+ export function texturePixels(spec, kind) {
221
+ if (spec.kind === 'procedural') return Promise.resolve(kind === 'normal' ? proceduralNormal(spec) : proceduralColor(spec));
222
+ return loadImagePixels(spec.url);
223
+ }