3draft 26.11.1013 → 26.11.3001

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/dist/gpu.js ADDED
@@ -0,0 +1,339 @@
1
+ // WebGPU renderer: flat-colored faces, one simple lit material, one global light.
2
+ // It draws the same scene through the same camera as the SVG renderer, so picking,
3
+ // the cross marks and the framing all stay valid. The pure helpers (viewProjection,
4
+ // buildVertices) need no GPU and are unit tested; createGpu() needs a browser.
5
+ import { dot, norm } from './vec.js';
6
+ import { faceNormal } from './mesh.js';
7
+ import { makeCamera } from './camera.js';
8
+ import { surfaceOf } from './material.js';
9
+ const FLOATS = 13; // position(3) normal(3) color(3) material(4: metal, rough, alpha, emit)
10
+ /**
11
+ * Column-major 4x4 matrix (for WebGPU, z in 0..1) that maps world points exactly
12
+ * like camera.project(): the same pixels, plus a depth between near and far.
13
+ */
14
+ export const viewProjection = (cam, near = 0.03, far = 1000) => {
15
+ const kk = cam.k / (cam.size / 2);
16
+ const row = (v, s) => [v[0] * s, v[1] * s, v[2] * s, -dot(v, cam.eye) * s];
17
+ const a = cam.ortho ? 1 / (far - near) : far / (far - near);
18
+ const zr = row(cam.f, a);
19
+ zr[3] -= a * near;
20
+ const rows = [row(cam.r, kk), row(cam.u, kk), zr, cam.ortho ? [0, 0, 0, 1] : row(cam.f, 1)];
21
+ const m = new Float32Array(16);
22
+ rows.forEach((r, i) => r.forEach((v, j) => (m[j * 4 + i] = v)));
23
+ return m;
24
+ };
25
+ const rgb = (color) => {
26
+ const h = String(color ?? '').replace('#', '');
27
+ const full = h.length === 3 ? [...h].map((c) => c + c).join('') : h;
28
+ if (!/^[0-9a-f]{6}$/i.test(full))
29
+ return [0.78, 0.78, 0.78];
30
+ return [0, 2, 4].map((i) => parseInt(full.slice(i, i + 2), 16) / 255);
31
+ };
32
+ /** Triangle list for the GPU: flat face normals, face colors and materials. Float32Array, 13 floats per vertex. */
33
+ export const buildVertices = (mesh, palette) => {
34
+ let tris = 0;
35
+ for (const f of mesh.faces)
36
+ tris += Math.max(0, f.v.length - 2);
37
+ const out = new Float32Array(tris * 3 * FLOATS);
38
+ let o = 0;
39
+ for (const face of mesh.faces) {
40
+ const pts = face.v.map((k) => mesh.positions[k]);
41
+ const n = norm(faceNormal(pts));
42
+ const s = surfaceOf(face, palette);
43
+ const c = rgb(s.color);
44
+ const mat = [s.metal, s.rough, s.alpha, s.emit];
45
+ for (let j = 1; j < pts.length - 1; j++) {
46
+ for (const p of [pts[0], pts[j], pts[j + 1]]) {
47
+ out.set([...p, ...n, ...c, ...mat], o);
48
+ o += FLOATS;
49
+ }
50
+ }
51
+ }
52
+ return out;
53
+ };
54
+ const INSTANCE_FLOATS = 15; // at(3) ex(3) ey(3) ez(3) color(3)
55
+ /**
56
+ * Per-instance data for drawInstances: one entry { at, axes: [ex, ey, ez], color } per copy of a
57
+ * prototype mesh (modelled around the origin). Float32Array, 15 floats per instance.
58
+ */
59
+ export const buildInstances = (items) => {
60
+ const out = new Float32Array(items.length * INSTANCE_FLOATS);
61
+ items.forEach((it, i) => out.set([...it.at, ...it.axes[0], ...it.axes[1], ...it.axes[2], ...rgb(it.color)], i * INSTANCE_FLOATS));
62
+ return out;
63
+ };
64
+ export const defaultLight = { direction: norm([0.5, 0.8, 0.6]), sky: [1, 0.97, 0.92], ground: [0.42, 0.38, 0.36] };
65
+ export const defaultMaterial = { ambient: 0.62, diffuse: 0.78, specular: 0.2, shininess: 30 };
66
+ const SHADER = /* wgsl */ `
67
+ struct U {
68
+ vp : mat4x4<f32>,
69
+ light : vec4<f32>, // xyz: direction towards the light
70
+ sky : vec4<f32>,
71
+ ground : vec4<f32>,
72
+ eye : vec4<f32>,
73
+ mat : vec4<f32>, // ambient, diffuse, specular, shininess
74
+ };
75
+ @group(0) @binding(0) var<uniform> u : U;
76
+
77
+ struct VIn { @location(0) pos : vec3<f32>, @location(1) nrm : vec3<f32>, @location(2) col : vec3<f32>, @location(8) mat : vec4<f32> };
78
+ struct VOut {
79
+ @builtin(position) p : vec4<f32>,
80
+ @location(0) n : vec3<f32>,
81
+ @location(1) c : vec3<f32>,
82
+ @location(2) w : vec3<f32>,
83
+ @location(3) m : vec4<f32>, // metal, rough, alpha, emit
84
+ };
85
+
86
+ @vertex fn vs(i : VIn) -> VOut {
87
+ var o : VOut;
88
+ o.p = u.vp * vec4<f32>(i.pos, 1.0);
89
+ o.n = i.nrm;
90
+ o.c = i.col;
91
+ o.w = i.pos;
92
+ o.m = i.mat;
93
+ return o;
94
+ }
95
+
96
+ struct IIn {
97
+ @location(0) pos : vec3<f32>, @location(1) nrm : vec3<f32>,
98
+ @location(3) at : vec3<f32>, @location(4) ex : vec3<f32>, @location(5) ey : vec3<f32>, @location(6) ez : vec3<f32>,
99
+ @location(7) col : vec3<f32>,
100
+ };
101
+
102
+ // the same prototype drawn many times: its frame (ex, ey, ez, scaled axes scale it) and position come per instance
103
+ @vertex fn vsi(i : IIn) -> VOut {
104
+ var o : VOut;
105
+ let w = i.at + i.ex * i.pos.x + i.ey * i.pos.y + i.ez * i.pos.z;
106
+ o.p = u.vp * vec4<f32>(w, 1.0);
107
+ // the axes may be scaled (a thin long bar from the same prototype): normals follow the unit axes
108
+ o.n = normalize(i.ex) * i.nrm.x + normalize(i.ey) * i.nrm.y + normalize(i.ez) * i.nrm.z;
109
+ o.c = i.col;
110
+ o.w = w;
111
+ o.m = vec4<f32>(0.0, 0.7, 1.0, 0.0);
112
+ return o;
113
+ }
114
+
115
+ @fragment fn fs(i : VOut, @builtin(front_facing) front : bool) -> @location(0) vec4<f32> {
116
+ var n = normalize(i.n);
117
+ if (!front) { n = -n; }
118
+ let l = normalize(u.light.xyz);
119
+ let v = normalize(u.eye.xyz - i.w);
120
+ let metal = i.m.x;
121
+ let rough = i.m.y;
122
+ let hemi = mix(u.ground.rgb, u.sky.rgb, n.y * 0.5 + 0.5) * u.mat.x;
123
+ let diff = max(dot(n, l), 0.0) * u.mat.y;
124
+ let h = normalize(l + v);
125
+ // roughness widens the highlight; metal makes it strong and tinted by the color
126
+ let shin = mix(u.mat.w * 7.0, u.mat.w * 0.15, rough);
127
+ let spec = pow(max(dot(n, h), 0.0), shin) * mix(u.mat.z, 1.0, metal) * mix(1.0, 0.35, rough) * step(0.0, dot(n, l));
128
+ // metal mirrors the sky above and the ground below, blurred by roughness
129
+ let r = reflect(-v, n);
130
+ let env = mix(u.ground.rgb * 1.2, u.sky.rgb * 1.5, smoothstep(-0.25 - rough * 0.5, 0.25 + rough * 0.5, r.y));
131
+ var lit = i.c * (hemi + vec3<f32>(diff)) * (1.0 - metal)
132
+ + i.c * env * metal * (1.0 - 0.6 * rough)
133
+ + vec3<f32>(spec) * mix(vec3<f32>(1.0), i.c, metal);
134
+ lit = mix(lit, i.c * 1.15, i.m.w);
135
+ return vec4<f32>(clamp(lit, vec3<f32>(0.0), vec3<f32>(1.0)), i.m.z);
136
+ }
137
+ `;
138
+ /**
139
+ * Sets up WebGPU on a canvas. Rejects when WebGPU is not available.
140
+ * Returns { render(mesh, view, options), destroy() }.
141
+ * render options: size (CSS px, the canvas is made size x size), fit, instances { mesh, data } (many copies of one
142
+ * prototype mesh, data from buildInstances; drawn after the mesh), background [r,g,b] 0..1,
143
+ * light { direction, sky, ground }, material { ambient, diffuse, specular, shininess }, dpr.
144
+ */
145
+ export const createGpu = async (canvas, { sampleCount = 4 } = {}) => {
146
+ if (!globalThis.navigator?.gpu)
147
+ throw new Error('WebGPU is not available in this browser');
148
+ const adapter = await navigator.gpu.requestAdapter();
149
+ if (!adapter)
150
+ throw new Error('No WebGPU adapter found');
151
+ const device = await adapter.requestDevice();
152
+ device.addEventListener('uncapturederror', (e) => console.error('WebGPU:', e.error?.message ?? e));
153
+ device.lost.then((info) => console.error('WebGPU device lost:', info.reason, info.message));
154
+ const context = canvas.getContext('webgpu');
155
+ if (!context)
156
+ throw new Error('Could not get a WebGPU canvas context');
157
+ const format = navigator.gpu.getPreferredCanvasFormat();
158
+ context.configure({ device, format, alphaMode: 'opaque', });
159
+ const module = device.createShaderModule({ code: SHADER });
160
+ const meshLayout = {
161
+ arrayStride: FLOATS * 4,
162
+ attributes: [
163
+ { shaderLocation: 0, offset: 0, format: 'float32x3' },
164
+ { shaderLocation: 1, offset: 12, format: 'float32x3' },
165
+ { shaderLocation: 2, offset: 24, format: 'float32x3' },
166
+ { shaderLocation: 8, offset: 36, format: 'float32x4' },
167
+ ],
168
+ };
169
+ const instanceLayout = {
170
+ arrayStride: INSTANCE_FLOATS * 4,
171
+ stepMode: 'instance',
172
+ attributes: [3, 4, 5, 6, 7].map((loc, k) => ({ shaderLocation: loc, offset: k * 12, format: 'float32x3' })),
173
+ };
174
+ const make = (entry, buffers) => device.createRenderPipeline({
175
+ layout: 'auto',
176
+ vertex: { module, entryPoint: entry, buffers },
177
+ fragment: { module, entryPoint: 'fs', targets: [{ format }] },
178
+ primitive: { topology: 'triangle-list', cullMode: 'none' },
179
+ depthStencil: { format: 'depth24plus', depthWriteEnabled: true, depthCompare: 'less' },
180
+ // the fragment alpha becomes coverage: a half transparent face covers half of the samples (one pass, no sorting)
181
+ multisample: sampleCount > 1 ? { count: sampleCount, alphaToCoverageEnabled: true } : { count: sampleCount },
182
+ });
183
+ const pipeline = make('vs', [meshLayout]);
184
+ // the instanced pipeline reads position and normal only from the prototype (locations 0, 1)
185
+ const instPipeline = make('vsi', [{ ...meshLayout, attributes: meshLayout.attributes.slice(0, 2) }, instanceLayout]);
186
+ const uniforms = device.createBuffer({ size: 144, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
187
+ const bind = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer: uniforms } }] });
188
+ const instBind = device.createBindGroup({ layout: instPipeline.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer: uniforms } }] });
189
+ // Geometry that did not change since the last frame is not rebuilt or uploaded again.
190
+ let uploaded = null; // the mesh now in vertexBuffer
191
+ let uploadedPalette; // and the palette it was built with
192
+ let vertexCount = 0;
193
+ let protoMesh = null;
194
+ let protoBuffer = null;
195
+ let protoCount = 0;
196
+ let instBuffer = null;
197
+ let instCapacity = 0;
198
+ let instData = null;
199
+ let instCount = 0;
200
+ let vertexBuffer = null;
201
+ let capacity = 0;
202
+ let px = 0;
203
+ let depth = null;
204
+ let color = null;
205
+ const targets = (n) => {
206
+ if (n === px)
207
+ return;
208
+ px = n;
209
+ canvas.width = n;
210
+ canvas.height = n;
211
+ depth?.destroy();
212
+ color?.destroy();
213
+ depth = device.createTexture({ size: [n, n], format: 'depth24plus', sampleCount, usage: GPUTextureUsage.RENDER_ATTACHMENT });
214
+ color = sampleCount > 1 ? device.createTexture({ size: [n, n], format, sampleCount, usage: GPUTextureUsage.RENDER_ATTACHMENT }) : null;
215
+ };
216
+ const draw = (mesh, view, { size = 400, fit, background = [0.98, 0.98, 0.97], light = {}, material = {}, palette, dpr = globalThis.devicePixelRatio || 1, instances } = {}, readback = false) => {
217
+ const L = { ...defaultLight, ...light };
218
+ const M = { ...defaultMaterial, ...material };
219
+ const cam = makeCamera(view, mesh, size, fit);
220
+ targets(Math.max(1, Math.round(size * dpr)));
221
+ if (mesh !== uploaded || palette !== uploadedPalette) {
222
+ const verts = buildVertices(mesh, palette);
223
+ if (verts.byteLength > capacity) {
224
+ vertexBuffer?.destroy();
225
+ capacity = Math.max(verts.byteLength, 4096);
226
+ vertexBuffer = device.createBuffer({ size: capacity, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
227
+ }
228
+ if (verts.byteLength)
229
+ device.queue.writeBuffer(vertexBuffer, 0, verts);
230
+ vertexCount = verts.length / FLOATS;
231
+ uploaded = mesh;
232
+ uploadedPalette = palette;
233
+ }
234
+ if (instances?.mesh && instances.mesh !== protoMesh) {
235
+ const v = buildVertices(instances.mesh);
236
+ protoBuffer?.destroy();
237
+ protoBuffer = device.createBuffer({ size: Math.max(v.byteLength, 256), usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
238
+ device.queue.writeBuffer(protoBuffer, 0, v);
239
+ protoCount = v.length / FLOATS;
240
+ protoMesh = instances.mesh;
241
+ }
242
+ if (instances?.data && instances.data !== instData) {
243
+ const d = instances.data;
244
+ if (d.byteLength > instCapacity) {
245
+ instBuffer?.destroy();
246
+ instCapacity = Math.max(d.byteLength, 4096);
247
+ instBuffer = device.createBuffer({ size: instCapacity, usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST });
248
+ }
249
+ if (d.byteLength)
250
+ device.queue.writeBuffer(instBuffer, 0, d);
251
+ instData = d;
252
+ instCount = d.length / INSTANCE_FLOATS;
253
+ }
254
+ if (!instances)
255
+ instCount = 0;
256
+ const u = new Float32Array(36);
257
+ u.set(viewProjection(cam), 0);
258
+ u.set([...(norm(L.direction)), 0], 16);
259
+ u.set([...L.sky, 0], 20);
260
+ u.set([...L.ground, 0], 24);
261
+ u.set([...cam.eye, 0], 28);
262
+ u.set([M.ambient, M.diffuse, M.specular, M.shininess], 32);
263
+ device.queue.writeBuffer(uniforms, 0, u);
264
+ const encoder = device.createCommandEncoder();
265
+ const offscreen = readback
266
+ ? device.createTexture({ size: [px, px], format, usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC })
267
+ : null;
268
+ const target = (offscreen ?? context.getCurrentTexture()).createView();
269
+ const pass = encoder.beginRenderPass({
270
+ colorAttachments: [
271
+ {
272
+ view: color ? color.createView() : target,
273
+ resolveTarget: color ? target : undefined,
274
+ clearValue: { r: background[0], g: background[1], b: background[2], a: 1 },
275
+ loadOp: 'clear',
276
+ storeOp: color ? 'discard' : 'store',
277
+ },
278
+ ],
279
+ depthStencilAttachment: { view: depth.createView(), depthClearValue: 1, depthLoadOp: 'clear', depthStoreOp: 'discard' },
280
+ });
281
+ if (vertexCount) {
282
+ pass.setPipeline(pipeline);
283
+ pass.setBindGroup(0, bind);
284
+ pass.setVertexBuffer(0, vertexBuffer);
285
+ pass.draw(vertexCount);
286
+ }
287
+ if (instCount && protoCount) {
288
+ pass.setPipeline(instPipeline);
289
+ pass.setBindGroup(0, instBind);
290
+ pass.setVertexBuffer(0, protoBuffer);
291
+ pass.setVertexBuffer(1, instBuffer);
292
+ pass.draw(protoCount, instCount);
293
+ }
294
+ pass.end();
295
+ if (!offscreen) {
296
+ device.queue.submit([encoder.finish()]);
297
+ return null;
298
+ }
299
+ const row = Math.ceil((px * 4) / 256) * 256;
300
+ const out = device.createBuffer({ size: row * px, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
301
+ encoder.copyTextureToBuffer({ texture: offscreen }, { buffer: out, bytesPerRow: row }, [px, px]);
302
+ device.queue.submit([encoder.finish()]);
303
+ return out.mapAsync(GPUMapMode.READ).then(() => {
304
+ const raw = new Uint8Array(out.getMappedRange());
305
+ const data = new Uint8ClampedArray(px * px * 4);
306
+ const swap = format.startsWith('bgra');
307
+ for (let y = 0; y < px; y++) {
308
+ for (let x = 0; x < px; x++) {
309
+ const i = y * row + x * 4;
310
+ const o = (y * px + x) * 4;
311
+ data[o] = raw[i + (swap ? 2 : 0)];
312
+ data[o + 1] = raw[i + 1];
313
+ data[o + 2] = raw[i + (swap ? 0 : 2)];
314
+ data[o + 3] = 255;
315
+ }
316
+ }
317
+ out.unmap();
318
+ out.destroy();
319
+ offscreen.destroy();
320
+ return { width: px, height: px, data };
321
+ });
322
+ };
323
+ /** Draws a frame onto the canvas. */
324
+ const render = (mesh, view, options) => {
325
+ draw(mesh, view, options);
326
+ };
327
+ /** Draws a frame into an offscreen texture and reads it back: Promise<{ width, height, data: RGBA }>. */
328
+ const pixels = (mesh, view, options) => draw(mesh, view, options, true);
329
+ const destroy = () => {
330
+ vertexBuffer?.destroy();
331
+ protoBuffer?.destroy();
332
+ instBuffer?.destroy();
333
+ depth?.destroy();
334
+ color?.destroy();
335
+ uniforms.destroy();
336
+ device.destroy();
337
+ };
338
+ return { render, pixels, destroy, device, adapter };
339
+ };
@@ -0,0 +1,33 @@
1
+ export declare const name: "3draft";
2
+ export declare const version = "26.11.3001";
3
+ export type { Vec3, Face, Mesh, Axes, ViewName, ViewSpec, Fit, Camera, Hit, Mark } from './types.js';
4
+ export { box, extrude, merge, rotate, bounds, faceNormal, faceCenter } from './mesh.js';
5
+ export type { BoxOptions } from './mesh.js';
6
+ export { validate } from './check.js';
7
+ export { boolean, union, subtract, intersect } from './csg.js';
8
+ export type { BooleanOp } from './csg.js';
9
+ export type { Validation } from './check.js';
10
+ export { extrudeFace, moveVertices } from './edit.js';
11
+ export { VIEW_ORDER, makeCamera, orbit, project, ray } from './camera.js';
12
+ export { pick, crosshair } from './pick.js';
13
+ export { standOn } from './place.js';
14
+ export type { StandOptions, Frame } from './place.js';
15
+ export { paintOrder } from './order.js';
16
+ export type { PaintItem } from './order.js';
17
+ export { createGpu, viewProjection, buildVertices, buildInstances, defaultLight, defaultMaterial } from './gpu.js';
18
+ export type { Gpu, GpuLight, GpuMaterial, GpuRenderOptions, Instance, Pixels } from './gpu.js';
19
+ export { renderView, renderViews, renderSheet } from './svg.js';
20
+ export type { RenderOptions } from './svg.js';
21
+ export { surfaceOf, DEFAULTS as MATERIAL_DEFAULTS } from './material.js';
22
+ export type { Material, Palette, Surface } from './material.js';
23
+ export { displayVersion } from './version.js';
24
+ export interface Info {
25
+ name: string;
26
+ version: string;
27
+ stage: 'pre-alpha';
28
+ goals: string[];
29
+ }
30
+ /** Short, machine-readable description of the current state of the package. */
31
+ export declare const info: () => Info;
32
+ export { initKernel } from './kernel.js';
33
+ export type { Kernel } from './kernel.js';
@@ -3,30 +3,30 @@
3
3
  // from four fixed cameras, plus surface picking (point, normal, distance) and
4
4
  // a target cross that lies on the surface under the cursor. No textures, no
5
5
  // shading yet.
6
-
7
6
  export const name = '3draft';
8
- export const version = '26.11.1013';
9
-
7
+ export const version = '26.11.3001';
10
8
  export { box, extrude, merge, rotate, bounds, faceNormal, faceCenter } from './mesh.js';
11
9
  export { validate } from './check.js';
10
+ export { boolean, union, subtract, intersect } from './csg.js';
12
11
  export { extrudeFace, moveVertices } from './edit.js';
13
12
  export { VIEW_ORDER, makeCamera, orbit, project, ray } from './camera.js';
14
13
  export { pick, crosshair } from './pick.js';
15
14
  export { standOn } from './place.js';
16
15
  export { paintOrder } from './order.js';
17
- export { createGpu, viewProjection, buildVertices, defaultLight, defaultMaterial } from './gpu.js';
16
+ export { createGpu, viewProjection, buildVertices, buildInstances, defaultLight, defaultMaterial } from './gpu.js';
18
17
  export { renderView, renderViews, renderSheet } from './svg.js';
18
+ export { surfaceOf, DEFAULTS as MATERIAL_DEFAULTS } from './material.js';
19
19
  export { displayVersion } from './version.js';
20
-
21
20
  /** Short, machine-readable description of the current state of the package. */
22
21
  export const info = () => ({
23
- name,
24
- version,
25
- stage: 'pre-alpha',
26
- goals: [
27
- 'single palette texture, UVs point at one texel per face',
28
- 'WASM core (HEXAW / Rust) behind a thin ABI',
29
- 'WebGPU renderer with WebGL2 fallback',
30
- 'deterministic SVG preview for AI feedback loops',
31
- ],
22
+ name,
23
+ version,
24
+ stage: 'pre-alpha',
25
+ goals: [
26
+ 'single palette texture, UVs point at one texel per face',
27
+ 'WASM core (HEXAW / Rust) behind a thin ABI',
28
+ 'WebGPU renderer with WebGL2 fallback',
29
+ 'deterministic SVG preview for AI feedback loops',
30
+ ],
32
31
  });
32
+ export { initKernel } from './kernel.js';
@@ -0,0 +1 @@
1
+ export declare const KERNEL_BYTES = "AGFzbQEAAAABDwFgCnx8fHx8fH9/f38BfwMCAQAFBQEBAYACBxECBHBpY2sAAAZtZW1vcnkCAAr/AwH8AwIGfxh8QQAhCkF/IQ9EnHUAiDzkN34hEAJAA0AgCiAITg0BIAcgCkEEdGohCyALKAIAQRhsIAZqIQwgCygCBEEYbCAGaiENIAsoAghBGGwgBmohDgJAIAwrAwAhESAMKwMIIRIgDCsDECETIA0rAwAgEaEhFCANKwMIIBKhIRUgDSsDECAToSEWIA4rAwAgEaEhFyAOKwMIIBKhIRggDisDECAToSEZIAQgGaIgBSAYoqEhGiAFIBeiIAMgGaKhIRsgAyAYoiAEIBeioSEcIBQgGqIgFSAboqAgFiAcoqAhHSAdmUSV1iboCy4RPmMNACAJIB1EAAAAAAAAAABlcQ0ARAAAAAAAAPA/IB2jIR4gACARoSEfIAEgEqEhICACIBOhISEgHiAfIBqiICAgG6KgICEgHKKgoiEiICJEAAAAAAAAAABjICJEAAAAAAAA8D9kcg0AICAgFqIgISAVoqEhIyAhIBSiIB8gFqKhISQgHyAVoiAgIBSioSElIB4gAyAjoiAEICSioCAFICWioKIhJiAmRAAAAAAAAAAAYyAiICagRAAAAAAAAPA/ZHINACAeIBcgI6IgGCAkoqAgGSAloqCiIScgJ0SV1iboCy4RPmUNACAnIBBmDQAgJyEQIAsoAgwhDwsgCkEBaiEKDAALC0EAIBA5AwAgDws=";
@@ -0,0 +1,2 @@
1
+ // Generated by scripts/build-kernel.mjs from kernel/pick.hexaw. Do not edit.
2
+ export const KERNEL_BYTES = 'AGFzbQEAAAABDwFgCnx8fHx8fH9/f38BfwMCAQAFBQEBAYACBxECBHBpY2sAAAZtZW1vcnkCAAr/AwH8AwIGfxh8QQAhCkF/IQ9EnHUAiDzkN34hEAJAA0AgCiAITg0BIAcgCkEEdGohCyALKAIAQRhsIAZqIQwgCygCBEEYbCAGaiENIAsoAghBGGwgBmohDgJAIAwrAwAhESAMKwMIIRIgDCsDECETIA0rAwAgEaEhFCANKwMIIBKhIRUgDSsDECAToSEWIA4rAwAgEaEhFyAOKwMIIBKhIRggDisDECAToSEZIAQgGaIgBSAYoqEhGiAFIBeiIAMgGaKhIRsgAyAYoiAEIBeioSEcIBQgGqIgFSAboqAgFiAcoqAhHSAdmUSV1iboCy4RPmMNACAJIB1EAAAAAAAAAABlcQ0ARAAAAAAAAPA/IB2jIR4gACARoSEfIAEgEqEhICACIBOhISEgHiAfIBqiICAgG6KgICEgHKKgoiEiICJEAAAAAAAAAABjICJEAAAAAAAA8D9kcg0AICAgFqIgISAVoqEhIyAhIBSiIB8gFqKhISQgHyAVoiAgIBSioSElIB4gAyAjoiAEICSioCAFICWioKIhJiAmRAAAAAAAAAAAYyAiICagRAAAAAAAAPA/ZHINACAeIBcgI6IgGCAkoqAgGSAloqCiIScgJ0SV1iboCy4RPmUNACAnIBBmDQAgJyEQIAsoAgwhDwsgCkEBaiEKDAALC0EAIBA5AwAgDws=';
@@ -0,0 +1,14 @@
1
+ import type { Camera, Hit, Mesh } from './types.js';
2
+ /**
3
+ * Starts the kernel. Resolves a picker { pick(mesh, cam, x, y, options), loaded } or rejects when
4
+ * WebAssembly is not available.
5
+ */
6
+ /** The HEXAW kernel (kernel/pick.hexaw compiled to WebAssembly): ray picking with the same results as pick(). */
7
+ export interface Kernel {
8
+ pick(mesh: Mesh, camera: Camera, x: number, y: number, options?: {
9
+ cull?: boolean;
10
+ }): Hit | null;
11
+ readonly loaded: Mesh | null;
12
+ instance: WebAssembly.Instance;
13
+ }
14
+ export declare const initKernel: () => Promise<Kernel>;
package/dist/kernel.js ADDED
@@ -0,0 +1,81 @@
1
+ // The HEXAW kernel: ray picking in WebAssembly written in HEXAW (kernel/pick.hexaw).
2
+ // The mesh is copied into the kernel's linear memory once, as long as it is the same object,
3
+ // then every pick is one call that walks all triangles. Same answers as pick() in pick.ts.
4
+ import { dot, norm, plus, times } from './vec.js';
5
+ import { faceNormal } from './mesh.js';
6
+ import { ray } from './camera.js';
7
+ import { KERNEL_BYTES } from './kernel-bytes.js';
8
+ const POS = 64; // vertices start here, 24 bytes each (f64 x y z)
9
+ const decode = (b64) => {
10
+ if (typeof Buffer !== 'undefined')
11
+ return new Uint8Array(Buffer.from(b64, 'base64'));
12
+ const s = atob(b64);
13
+ return Uint8Array.from(s, (c) => c.charCodeAt(0));
14
+ };
15
+ export const initKernel = async () => {
16
+ if (typeof WebAssembly === 'undefined')
17
+ throw new Error('WebAssembly is not available');
18
+ const { instance } = (await WebAssembly.instantiate(decode(KERNEL_BYTES)));
19
+ const { pick: kPick, memory } = instance.exports;
20
+ let uploaded = null; // the mesh now in the kernel's memory
21
+ let triBase = 0;
22
+ let triCount = 0;
23
+ const upload = (mesh) => {
24
+ const nv = mesh.positions.length;
25
+ let nt = 0;
26
+ for (const f of mesh.faces)
27
+ nt += Math.max(0, f.v.length - 2);
28
+ triBase = (POS + nv * 24 + 7) & ~7;
29
+ const need = Math.ceil((triBase + nt * 16 + 8) / 65536);
30
+ const have = memory.buffer.byteLength / 65536;
31
+ if (need > have)
32
+ memory.grow(need - have);
33
+ // grow() detaches the old buffer, so the views are made after it
34
+ const f64 = new Float64Array(memory.buffer, POS, nv * 3);
35
+ for (let i = 0; i < nv; i++) {
36
+ const p = mesh.positions[i];
37
+ f64[i * 3] = p[0];
38
+ f64[i * 3 + 1] = p[1];
39
+ f64[i * 3 + 2] = p[2];
40
+ }
41
+ // faces are fanned into triangles (v0, vj, vj+1), each remembering its face number
42
+ const i32 = new Int32Array(memory.buffer, triBase, nt * 4);
43
+ let at = 0;
44
+ mesh.faces.forEach((f, face) => {
45
+ for (let j = 1; j < f.v.length - 1; j++) {
46
+ i32[at] = f.v[0];
47
+ i32[at + 1] = f.v[j];
48
+ i32[at + 2] = f.v[j + 1];
49
+ i32[at + 3] = face;
50
+ at += 4;
51
+ }
52
+ });
53
+ triCount = nt;
54
+ uploaded = mesh;
55
+ };
56
+ /**
57
+ * The nearest surface under panel pixel (x, y), or null: the same result as pick() in pick.js,
58
+ * { face, distance, point, normal, front, color }.
59
+ */
60
+ const pick = (mesh, cam, x, y, { cull = true } = {}) => {
61
+ if (mesh !== uploaded)
62
+ upload(mesh);
63
+ const { origin: o, dir: d } = ray(cam, x, y);
64
+ const face = kPick(o[0], o[1], o[2], d[0], d[1], d[2], POS, triBase, triCount, cull ? 1 : 0);
65
+ if (face < 0)
66
+ return null;
67
+ const distance = new Float64Array(memory.buffer, 0, 1)[0];
68
+ const f = mesh.faces[face];
69
+ const outward = norm(faceNormal(f.v.map((k) => mesh.positions[k])));
70
+ const front = dot(outward, d) < 0;
71
+ return {
72
+ face,
73
+ distance,
74
+ point: plus(o)(times(distance)(d)),
75
+ normal: front ? outward : times(-1)(outward),
76
+ front,
77
+ color: f.color,
78
+ };
79
+ };
80
+ return { pick, get loaded() { return uploaded; }, instance };
81
+ };
@@ -0,0 +1,31 @@
1
+ import type { Face } from './types.js';
2
+ export interface Material {
3
+ /** #rrggbb. */
4
+ color: string;
5
+ /** 0 = paint, 1 = metal (reflects the sky and the ground, tinted by the color). */
6
+ metal?: number;
7
+ /** 0 = mirror-like, 1 = matte; widens the highlight. */
8
+ rough?: number;
9
+ /** 1 = solid, 0 = invisible. Drawn with alpha-to-coverage: one pass, no sorting. */
10
+ alpha?: number;
11
+ /** 0..1: how much the color glows on its own, unlit. */
12
+ emit?: number;
13
+ }
14
+ export type Palette = Record<string, Material>;
15
+ /** What a face is made of, all numbers filled in. */
16
+ export interface Surface {
17
+ color: string;
18
+ metal: number;
19
+ rough: number;
20
+ alpha: number;
21
+ emit: number;
22
+ }
23
+ export declare const FALLBACK_COLOR = "#c8c8c8";
24
+ export declare const DEFAULTS: {
25
+ readonly metal: 0;
26
+ readonly rough: 0.7;
27
+ readonly alpha: 1;
28
+ readonly emit: 0;
29
+ };
30
+ /** The surface of a face: its palette entry when it names one, else just its color with default properties. */
31
+ export declare const surfaceOf: (face: Pick<Face, "color" | "mat">, palette?: Palette) => Surface;
@@ -0,0 +1,17 @@
1
+ // Materials are data. A palette is a plain object { name: Material }; a face points at an entry by name
2
+ // (`face.mat`) and keeps its own `color` as a fallback, so a mesh still looks right without the palette.
3
+ // One shader draws all of them; the numbers below are the only knobs.
4
+ const clamp01 = (n, fallback) => (typeof n === 'number' && Number.isFinite(n) ? Math.max(0, Math.min(1, n)) : fallback);
5
+ export const FALLBACK_COLOR = '#c8c8c8';
6
+ export const DEFAULTS = { metal: 0, rough: 0.7, alpha: 1, emit: 0 };
7
+ /** The surface of a face: its palette entry when it names one, else just its color with default properties. */
8
+ export const surfaceOf = (face, palette) => {
9
+ const m = face.mat !== undefined ? palette?.[face.mat] : undefined;
10
+ return {
11
+ color: m?.color ?? face.color ?? FALLBACK_COLOR,
12
+ metal: clamp01(m?.metal, DEFAULTS.metal),
13
+ rough: clamp01(m?.rough, DEFAULTS.rough),
14
+ alpha: clamp01(m?.alpha, DEFAULTS.alpha),
15
+ emit: clamp01(m?.emit, DEFAULTS.emit),
16
+ };
17
+ };
package/dist/mesh.d.ts ADDED
@@ -0,0 +1,40 @@
1
+ import type { Axes, Mesh, Vec3 } from './types.js';
2
+ export interface BoxOptions {
3
+ size?: Vec3;
4
+ at?: Vec3;
5
+ color?: string;
6
+ /** Orthonormal local x/y/z axes (default: the world axes). */
7
+ axes?: Axes;
8
+ }
9
+ /** Box: 8 points, 12 edges, 6 quad faces. Axis-aligned unless `axes` turns it. */
10
+ export declare const box: ({ size, at, color, axes }?: BoxOptions) => Mesh;
11
+ /** Concatenate meshes into one, re-indexing the faces. */
12
+ export declare const merge: (...meshes: Mesh[]) => Mesh;
13
+ /** Bounding box center and bounding sphere radius around that center. */
14
+ export declare const bounds: (mesh: Mesh) => {
15
+ center: Vec3;
16
+ radius: number;
17
+ };
18
+ /**
19
+ * Turntable rotation: yaw around Y first, then pitch around X (radians),
20
+ * both around `center` (default: bounding-box center). Faces are shared.
21
+ */
22
+ export declare const rotate: (mesh: Mesh, { yaw, pitch }?: {
23
+ yaw?: number;
24
+ pitch?: number;
25
+ }, center?: Vec3) => Mesh;
26
+ /** Face normal (not normalized) by Newell's method; points CCW => outward. */
27
+ export declare const faceNormal: (pts: Vec3[]) => Vec3;
28
+ /** Mean of the face points. */
29
+ export declare const faceCenter: (pts: Vec3[]) => Vec3;
30
+ /**
31
+ * Prism from a convex footprint: `polygon` is [[x, z], ...] on the ground plane (any
32
+ * winding), it is extruded up from `y` by `height`. Faces: top, bottom, then one
33
+ * quad per footprint edge, all CCW from outside.
34
+ */
35
+ export declare const extrude: ({ polygon, height, y, color }: {
36
+ polygon: [number, number][];
37
+ height?: number;
38
+ y?: number;
39
+ color?: string;
40
+ }) => Mesh;