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,48 @@
1
+ // 3Draft: minimalist AI first 3D engine.
2
+ // Current stage: points, edges and flat faces rendered to deterministic SVG
3
+ // from four fixed cameras, plus surface picking (point, normal, distance) and
4
+ // a target cross that lies on the surface under the cursor. No textures, no
5
+ // shading yet.
6
+ export const name = '3draft';
7
+ export const version = '26.11.18029';
8
+ export { box, extrude, merge, rotate, bounds, faceNormal, faceCenter } from './mesh.js';
9
+ export { validate } from './check.js';
10
+ export { boolean, union, subtract, intersect, health, splitParts } from './csg.js';
11
+ export { bevel } from './bevel.js';
12
+ export { lathe } from './lathe.js';
13
+ export { textMesh, faceFrame, GLYPHS, STROKE as TEXT_STROKE, mergeFlat } from './text.js';
14
+ export { saw, planeThroughLine, planeThroughTriangle, sectionSegments } from './saw.js';
15
+ export { extrudeFace, moveVertices } from './edit.js';
16
+ export { VIEW_ORDER, makeCamera, orbit, project, ray } from './camera.js';
17
+ export { pick, crosshair } from './pick.js';
18
+ export { instantiate, lodLevel } from './instances.js';
19
+ export { standOn } from './place.js';
20
+ export { createTsh, readHands, handGestures, TSH_JOINTS, TSH_BONES } from './vrtsh.js';
21
+ export { makeJoint, jointNow, hingeTo, pivotTo, pivotTurn, railTo, railNear, springStep, springMesh, carried, holderOf, moveMesh, applyRigid, frameOf, toWorld, toLocal, closestOnPath, pathLength, pointAlong, axisAngle, pickFrame, ID3 } from './joints.js';
22
+ export { paintOrder } from './order.js';
23
+ export { createGpu, viewProjection, buildVertices, cornerNormals, buildInstances, buildSkinVertices, MAX_BONES, SKIN_FLOATS, buildScreenQuads, SCREEN_FLOATS, defaultLight, defaultMaterial, mul4 } from './gpu.js';
24
+ export { createGl } from './gl.js';
25
+ export { renderView, renderViews, renderSheet } from './svg.js';
26
+ export { surfaceOf, DEFAULTS as MATERIAL_DEFAULTS } from './material.js';
27
+ export { displayVersion } from './version.js';
28
+ /** Short, machine-readable description of the current state of the package. */
29
+ export const info = () => ({
30
+ name,
31
+ version,
32
+ stage: 'pre-alpha',
33
+ goals: [
34
+ 'single palette texture, UVs point at one texel per face',
35
+ 'WASM core (HEXAW / Rust) behind a thin ABI',
36
+ 'WebGPU renderer with WebGL2 fallback',
37
+ 'deterministic SVG preview for AI feedback loops',
38
+ ],
39
+ });
40
+ export { initKernel } from './kernel.js';
41
+ export { insertVertex, cutFace, moveVertex, fillLoop, addLine, findLoop, nearestSurface, wireFromSegments, moveVertexSet, reshape, outlineOf } from './wire.js';
42
+ export { triangulate } from './triangulate.js';
43
+ export { galaxyPoints } from './galaxy.js';
44
+ export { planetInstances, inv4, PLANET_FLOATS } from './planet.js';
45
+ export { skyScene, skyPrototypes, skyAt, starClass, starTint, exoClass, exoRecipe, EXO_RECIPES, SKY_PALETTE, SKY_TYPES, STAR_CLASSES, LY_PER_PC, LY_PER_AU, LY_PER_KM, SUN_RADIUS_LY, EARTH_RADIUS_LY } from './sky.js';
46
+ export { buildEdges, buildMarks, MARK_FLOATS, sceneEdges } from './gpu.js';
47
+ export { humanoidRig, posed, posedJoints, boneMatrices, poseLift, walkPose, HUMANOID_POSES, HUMANOID_JOINTS } from './rig.js';
48
+ export { buildCharacter, normalizeCharacter, variateCharacter, CHARACTER_VERSION, CHARACTER_PRESETS, CHARACTER_RANGES, CHARACTER_PARTS, FACE_SHAPES, HAIR_STYLES, BEARD_STYLES, OUTFITS, PROPS, CHARACTER_MATERIALS, CHARACTER_SKINS, CHARACTER_HAIRS, CHARACTER_CLOTHS, characterPalette } from './character.js';
@@ -0,0 +1,41 @@
1
+ // Prototypes and instances. A PROTOTYPE is a list of meshes of the same thing in decreasing detail (level of detail:
2
+ // lods[0] is the finest), all of unit size and centred on the origin, with material SLOTS in `Face.mat` ('core', 'halo'...).
3
+ // An INSTANCE is the prototype placed with a position, a size (one number, or one per slot) and its own slot -> palette
4
+ // map, so a scene file stores the shape once and one short record per star. The detail used on screen follows the size
5
+ // the thing has in pixels, so a far star costs a few faces and a near one a few dozen.
6
+ /** A copy of the prototype mesh, scaled, moved and given its materials. Slots must not share vertices when scaled apart. */
7
+ export const instantiate = (proto, p) => {
8
+ const slotOf = [];
9
+ for (const f of proto.faces)
10
+ for (const i of f.v)
11
+ slotOf[i] ??= f.mat ?? '';
12
+ const size = (slot) => (typeof p.scale === 'number' ? p.scale : (p.scale[slot] ?? p.scale['*'] ?? 1));
13
+ const positions = proto.positions.map((q, i) => {
14
+ const k = size(slotOf[i] ?? '');
15
+ let [x, y, z] = [q[0] * k, q[1] * k, q[2] * k];
16
+ if (p.rot) {
17
+ const [a, b] = p.rot;
18
+ [y, z] = [y * Math.cos(a) - z * Math.sin(a), y * Math.sin(a) + z * Math.cos(a)];
19
+ [x, z] = [x * Math.cos(b) + z * Math.sin(b), -x * Math.sin(b) + z * Math.cos(b)];
20
+ }
21
+ return [x + p.at[0], y + p.at[1], z + p.at[2]];
22
+ });
23
+ const faces = proto.faces.map((f) => {
24
+ const out = { v: f.v };
25
+ const mat = f.mat === undefined ? undefined : (p.mats?.[f.mat] ?? f.mat);
26
+ if (mat !== undefined)
27
+ out.mat = mat;
28
+ const color = p.color ?? f.color;
29
+ if (color !== undefined)
30
+ out.color = color;
31
+ return out;
32
+ });
33
+ return { positions, faces };
34
+ };
35
+ /** Which level of detail to draw for something that is `px` pixels across (its radius); `limits` are the pixel sizes where the next finer level starts. */
36
+ export const lodLevel = (px, levels, limits = [60, 22, 8, 3, 1]) => {
37
+ let level = 0;
38
+ while (level < levels - 1 && level < limits.length && px < limits[level])
39
+ level++;
40
+ return level;
41
+ };
@@ -0,0 +1,355 @@
1
+ // Groups and joints: the basic mechanics. Objects carry no transform (only meshes), so a joint keeps its geometry in the
2
+ // FRAME of an object's mesh: three of its vertices (well spread) give an origin, three axes and a scale, which every rigid move,
3
+ // turn and uniform size of that mesh carries along. So the anchors (a hinge's line, a rail, a pivot) follow their object
4
+ // without any bookkeeping, and undo comes for free.
5
+ //
6
+ // Joint kinds (a = the holder, b = the held part):
7
+ // glue a and b move together; `contact` (points, a line or a face, in a's frame) records where they touch
8
+ // pivot b turns about a point (a ball joint), with limits per axis (degrees, round the axes of `basis`, from the rest pose)
9
+ // hinge b turns about a line (its own edge: a door's vertical side), with a limit (degrees from the rest pose)
10
+ // rail b slides along a polyline of a (its `slider` point on the line), between `limit` (distances along the rail)
11
+ // spring b hangs on a spring between a point of a and a point of b: rest length, stiffness, damping; each end glued or
12
+ // pivoting; an optional spring object is stretched between the two ends
13
+ // The held part follows the holder (a moves → b moves along); moving b itself is what the joint allows.
14
+ // ---- small vector and matrix helpers (plain, so the viewer and the MCP server share them)
15
+ export const v3 = {
16
+ add: (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]],
17
+ sub: (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]],
18
+ mul: (a, s) => [a[0] * s, a[1] * s, a[2] * s],
19
+ dot: (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2],
20
+ cross: (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]],
21
+ len: (a) => Math.hypot(a[0], a[1], a[2]),
22
+ norm: (a) => {
23
+ const l = Math.hypot(a[0], a[1], a[2]);
24
+ return l > 0 ? [a[0] / l, a[1] / l, a[2] / l] : [0, 0, 0];
25
+ },
26
+ };
27
+ const { add, sub, mul, dot, cross, norm } = v3;
28
+ const mT = (m) => [[m[0][0], m[1][0], m[2][0]], [m[0][1], m[1][1], m[2][1]], [m[0][2], m[1][2], m[2][2]]];
29
+ const mMul = (a, b) => a.map((r) => [0, 1, 2].map((j) => r[0] * b[0][j] + r[1] * b[1][j] + r[2] * b[2][j]));
30
+ const mVec = (m, v) => [dot(m[0], v), dot(m[1], v), dot(m[2], v)];
31
+ /** The rotation matrix round the unit axis by angle (radians). */
32
+ export const axisAngle = (u, t) => {
33
+ const [x, y, z] = norm(u), c = Math.cos(t), s = Math.sin(t), C = 1 - c;
34
+ return [
35
+ [c + x * x * C, x * y * C - z * s, x * z * C + y * s],
36
+ [y * x * C + z * s, c + y * y * C, y * z * C - x * s],
37
+ [z * x * C - y * s, z * y * C + x * s, c + z * z * C],
38
+ ];
39
+ };
40
+ /** Euler angles (radians) of R = Rz · Ry · Rx. */
41
+ const eulerXYZ = (R) => {
42
+ const sy = Math.max(-1, Math.min(1, -R[2][0]));
43
+ const y = Math.asin(sy);
44
+ if (Math.abs(sy) > 0.99999)
45
+ return [Math.atan2(-R[1][2], R[1][1]), y, 0];
46
+ return [Math.atan2(R[2][1], R[2][2]), y, Math.atan2(R[1][0], R[0][0])];
47
+ };
48
+ const fromEuler = ([x, y, z]) => mMul(axisAngle([0, 0, 1], z), mMul(axisAngle([0, 1, 0], y), axisAngle([1, 0, 0], x)));
49
+ // ---- mesh frames
50
+ /** Three well spread vertices of a mesh: the first, the farthest from it, the farthest from their line. */
51
+ export const pickFrame = (mesh) => {
52
+ const P = mesh.positions;
53
+ if (P.length < 3)
54
+ throw new Error('a joint needs objects of at least 3 vertices');
55
+ let i1 = 0, d1 = -1;
56
+ P.forEach((p, i) => {
57
+ const d = v3.len(sub(p, P[0]));
58
+ if (d > d1)
59
+ ((d1 = d), (i1 = i));
60
+ });
61
+ const u = norm(sub(P[i1], P[0]));
62
+ let i2 = 0, d2 = -1;
63
+ P.forEach((p, i) => {
64
+ const w = sub(p, P[0]);
65
+ const d = v3.len(sub(w, mul(u, dot(w, u))));
66
+ if (d > d2)
67
+ ((d2 = d), (i2 = i));
68
+ });
69
+ if (d1 <= 0 || d2 <= 1e-9 * d1)
70
+ throw new Error('a joint needs objects that are not flat lines or points');
71
+ return [0, i1, i2];
72
+ };
73
+ export const frameOf = (mesh, idx) => {
74
+ const [p0, p1, p2] = idx.map((i) => mesh.positions[i]);
75
+ const x = norm(sub(p1, p0));
76
+ const z = norm(cross(x, sub(p2, p0)));
77
+ const y = cross(z, x);
78
+ return { o: p0, R: [x, y, z], s: v3.len(sub(p1, p0)) };
79
+ };
80
+ export const toLocal = (f, p) => mul(mVec(f.R, sub(p, f.o)), 1 / f.s);
81
+ export const toWorld = (f, l) => add(f.o, mul(mVec(mT(f.R), l), f.s));
82
+ export const dirLocal = (f, d) => mVec(f.R, d);
83
+ export const dirWorld = (f, d) => mVec(mT(f.R), d);
84
+ /** b's axes in a's frame (the relative rotation). */
85
+ const relative = (fa, fb) => mMul(fa.R, mT(fb.R));
86
+ export const makeJoint = (spec, meshA, meshB) => {
87
+ const frameA = pickFrame(meshA), frameB = pickFrame(meshB);
88
+ const fa = frameOf(meshA, frameA), fb = frameOf(meshB, frameB);
89
+ const j = { name: spec.name, type: spec.type, a: spec.a, b: spec.b, frameA, frameB, rest: relative(fa, fb) };
90
+ const L = (p) => toLocal(fa, p);
91
+ switch (spec.type) {
92
+ case 'glue':
93
+ if (spec.contact?.length)
94
+ j.contact = spec.contact.map(L);
95
+ else if (spec.at)
96
+ j.contact = [L(spec.at)];
97
+ break;
98
+ case 'pivot':
99
+ if (!spec.at)
100
+ throw new Error('a pivot needs its point (at)');
101
+ j.at = L(spec.at);
102
+ j.basis = (spec.basis ?? [[1, 0, 0], [0, 1, 0], [0, 0, 1]]).map((d) => dirLocal(fa, norm(d)));
103
+ if (spec.limits)
104
+ j.limits = spec.limits;
105
+ break;
106
+ case 'hinge':
107
+ if (!spec.axis || v3.len(sub(spec.axis[1], spec.axis[0])) <= 0)
108
+ throw new Error('a hinge needs its line (two different points)');
109
+ j.axis = [L(spec.axis[0]), L(spec.axis[1])];
110
+ if (spec.limit)
111
+ j.limit = spec.limit;
112
+ break;
113
+ case 'rail': {
114
+ if (!spec.path || spec.path.length < 2)
115
+ throw new Error('a rail needs a path of at least 2 points');
116
+ j.path = spec.path.map(L);
117
+ const slider = spec.slider ?? nearestVertexTo(meshB, spec.path);
118
+ j.bAt = toLocal(fb, slider);
119
+ j.scaleA = fa.s;
120
+ if (spec.limit)
121
+ j.limit = spec.limit;
122
+ break;
123
+ }
124
+ case 'spring': {
125
+ if (!spec.at || !spec.bAt)
126
+ throw new Error('a spring needs its two ends: at (on a) and at_b (on b)');
127
+ j.at = L(spec.at);
128
+ j.bAt = toLocal(fb, spec.bAt);
129
+ j.restLength = spec.restLength ?? v3.len(sub(spec.bAt, spec.at));
130
+ j.stiffness = spec.stiffness ?? 40;
131
+ j.damping = spec.damping ?? 3;
132
+ j.ends = spec.ends ?? ['glue', 'glue'];
133
+ j.scaleA = fa.s;
134
+ if (spec.spring) {
135
+ const m = spec.spring.mesh;
136
+ const line = spec.spring.line ?? longestLine(m);
137
+ j.spring = { object: spec.spring.object, line, mesh: m, ends: [spec.at, spec.bAt] };
138
+ }
139
+ break;
140
+ }
141
+ default:
142
+ throw new Error(`unknown joint type "${spec.type}"`);
143
+ }
144
+ return j;
145
+ };
146
+ const nearestVertexTo = (mesh, path) => {
147
+ let best = mesh.positions[0], bd = Infinity;
148
+ for (const p of mesh.positions) {
149
+ const d = v3.len(sub(p, closestOnPath(path, p).point));
150
+ if (d < bd)
151
+ ((bd = d), (best = p));
152
+ }
153
+ return best;
154
+ };
155
+ // the two vertices of a mesh farthest apart along its longest bounding-box side
156
+ const longestLine = (m) => {
157
+ const lo = [0, 1, 2].map((k) => Math.min(...m.positions.map((p) => p[k])));
158
+ const hi = [0, 1, 2].map((k) => Math.max(...m.positions.map((p) => p[k])));
159
+ const k = [0, 1, 2].reduce((b, a) => (hi[a] - lo[a] > hi[b] - lo[b] ? a : b), 0);
160
+ let i0 = 0, i1 = 0;
161
+ m.positions.forEach((p, i) => {
162
+ if (p[k] < m.positions[i0][k])
163
+ i0 = i;
164
+ if (p[k] > m.positions[i1][k])
165
+ i1 = i;
166
+ });
167
+ return [i0, i1];
168
+ };
169
+ /** The nearest point of a polyline: the point, the distance along the line from its start, the segment's direction. */
170
+ export const closestOnPath = (path, p) => {
171
+ let best = { point: path[0], s: 0, dir: norm(sub(path[1], path[0])) }, bd = Infinity, run = 0;
172
+ for (let i = 0; i + 1 < path.length; i++) {
173
+ const a = path[i], d = sub(path[i + 1], a), L = v3.len(d);
174
+ if (L <= 0)
175
+ continue;
176
+ const t = Math.max(0, Math.min(L, dot(sub(p, a), d) / L));
177
+ const q = add(a, mul(d, t / L));
178
+ const dd = v3.len(sub(p, q));
179
+ if (dd < bd)
180
+ ((bd = dd), (best = { point: q, s: run + t, dir: mul(d, 1 / L) }));
181
+ run += L;
182
+ }
183
+ return best;
184
+ };
185
+ export const pathLength = (path) => path.slice(1).reduce((t, p, i) => t + v3.len(sub(p, path[i])), 0);
186
+ export const pointAlong = (path, s) => {
187
+ let run = 0;
188
+ for (let i = 0; i + 1 < path.length; i++) {
189
+ const L = v3.len(sub(path[i + 1], path[i]));
190
+ if (s <= run + L || i + 2 === path.length)
191
+ return add(path[i], mul(sub(path[i + 1], path[i]), L > 0 ? Math.max(0, Math.min(1, (s - run) / L)) : 0));
192
+ run += L;
193
+ }
194
+ return path[path.length - 1];
195
+ };
196
+ const deltaOf = (j, fa, fb) => mMul(relative(fa, fb), mT(j.rest)); // the turn since rest, in a's frame
197
+ const signedAngle = (u, D) => {
198
+ const ref = Math.abs(u[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0];
199
+ const v = norm(cross(u, ref));
200
+ const w = mVec(D, v);
201
+ return Math.atan2(dot(u, cross(v, w)), dot(v, w));
202
+ };
203
+ export const jointNow = (j, meshA, meshB) => {
204
+ const fa = frameOf(meshA, j.frameA), fb = frameOf(meshB, j.frameB);
205
+ const W = (l) => toWorld(fa, l);
206
+ const D = deltaOf(j, fa, fb);
207
+ switch (j.type) {
208
+ case 'hinge': {
209
+ const u = norm(sub(j.axis[1], j.axis[0]));
210
+ return { type: 'hinge', angle: (signedAngle(u, D) * 180) / Math.PI, axis: [W(j.axis[0]), W(j.axis[1])] };
211
+ }
212
+ case 'pivot': {
213
+ const B = j.basis;
214
+ const e = eulerXYZ(mMul(B, mMul(D, mT(B))));
215
+ return { type: 'pivot', angles: e.map((t) => (t * 180) / Math.PI), point: W(j.at) };
216
+ }
217
+ case 'rail': {
218
+ const path = j.path.map(W);
219
+ const s = closestOnPath(path, toWorld(fb, j.bAt)).s;
220
+ return { type: 'rail', position: s, path };
221
+ }
222
+ case 'spring': {
223
+ const ends = [W(j.at), toWorld(fb, j.bAt)];
224
+ return { type: 'spring', length: v3.len(sub(ends[1], ends[0])), ends };
225
+ }
226
+ default:
227
+ return { type: 'glue', ...(j.contact ? { path: j.contact.map(W) } : {}) };
228
+ }
229
+ };
230
+ export const ID3 = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
231
+ export const applyRigid = (m, p) => add(add(mVec(m.R, sub(p, m.about)), m.about), m.t);
232
+ export const moveMesh = (mesh, m) => ({ ...mesh, positions: mesh.positions.map((p) => applyRigid(m, p)) });
233
+ const clamp = (v, r) => (r ? Math.max(Math.min(r[0], r[1]), Math.min(Math.max(r[0], r[1]), v)) : v);
234
+ /** Set a hinge to an angle (degrees from rest, clamped to its limit): the move of b. */
235
+ export const hingeTo = (j, meshA, meshB, deg) => {
236
+ const now = jointNow(j, meshA, meshB);
237
+ const goal = clamp(deg, j.limit);
238
+ const [p0, p1] = now.axis;
239
+ return { move: { R: axisAngle(norm(sub(p1, p0)), ((goal - now.angle) * Math.PI) / 180), about: p0, t: [0, 0, 0] }, angle: goal };
240
+ };
241
+ /** Set a pivot to angles (degrees round its basis axes from rest, each clamped). */
242
+ export const pivotTo = (j, meshA, meshB, deg) => {
243
+ const fa = frameOf(meshA, j.frameA), fb = frameOf(meshB, j.frameB);
244
+ const L = j.limits ?? {};
245
+ const goal = [clamp(deg[0], L.x), clamp(deg[1], L.y), clamp(deg[2], L.z)];
246
+ const B = j.basis;
247
+ const Dgoal = mMul(mT(B), mMul(fromEuler(goal.map((d) => (d * Math.PI) / 180)), B)); // in a's frame
248
+ const D = deltaOf(j, fa, fb);
249
+ const turnA = mMul(Dgoal, mT(D)); // a's frame
250
+ const R = mMul(mT(fa.R), mMul(turnA, fa.R)); // world
251
+ return { move: { R, about: toWorld(fa, j.at), t: [0, 0, 0] }, angles: goal };
252
+ };
253
+ /** Turn a pivot by a world turn (axis, degrees), kept inside its limits. */
254
+ export const pivotTurn = (j, meshA, meshB, axis, deg) => {
255
+ const fa = frameOf(meshA, j.frameA), fb = frameOf(meshB, j.frameB);
256
+ const turnW = axisAngle(axis, (deg * Math.PI) / 180);
257
+ const turnA = mMul(fa.R, mMul(turnW, mT(fa.R)));
258
+ const D2 = mMul(turnA, deltaOf(j, fa, fb));
259
+ const B = j.basis;
260
+ const e = eulerXYZ(mMul(B, mMul(D2, mT(B)))).map((t) => (t * 180) / Math.PI);
261
+ return pivotTo(j, meshA, meshB, e);
262
+ };
263
+ /** Slide a rail's slider to the rail point nearest `p` (world), inside its limit: the move of b. */
264
+ export const railTo = (j, meshA, meshB, s) => {
265
+ const fa = frameOf(meshA, j.frameA), fb = frameOf(meshB, j.frameB);
266
+ const path = j.path.map((l) => toWorld(fa, l));
267
+ const k = fa.s / (j.scaleA ?? fa.s); // (the limit scales with the object)
268
+ const lim = j.limit ? [j.limit[0] * k, j.limit[1] * k] : [0, pathLength(path)];
269
+ const goal = clamp(s, lim);
270
+ const from = toWorld(fb, j.bAt);
271
+ return { move: { R: ID3, about: [0, 0, 0], t: sub(pointAlong(path, goal), from) }, position: goal };
272
+ };
273
+ export const railNear = (j, meshA, meshB, p) => {
274
+ const fa = frameOf(meshA, j.frameA);
275
+ return railTo(j, meshA, meshB, closestOnPath(j.path.map((l) => toWorld(fa, l)), p).s);
276
+ };
277
+ /** One step of a spring (b's translation): where its end is pulled towards the rest length; v is its velocity (world units / s). */
278
+ export const springStep = (j, meshA, meshB, v, dt) => {
279
+ const fa = frameOf(meshA, j.frameA), fb = frameOf(meshB, j.frameB);
280
+ const A = toWorld(fa, j.at), Bp = toWorld(fb, j.bAt);
281
+ const d = sub(Bp, A), len = v3.len(d);
282
+ const k = fa.s / (j.scaleA ?? fa.s);
283
+ const restL = (j.restLength ?? len) * k;
284
+ const dir = len > 1e-12 ? mul(d, 1 / len) : [0, -1, 0];
285
+ const stretch = len - restL;
286
+ // semi-implicit Euler, in small steps
287
+ let vel = v, x = [0, 0, 0];
288
+ const n = Math.max(1, Math.ceil(dt / 0.008));
289
+ const h = dt / n;
290
+ for (let i = 0; i < n; i++) {
291
+ const cur = add(d, x), cl = v3.len(cur);
292
+ const cd = cl > 1e-12 ? mul(cur, 1 / cl) : dir;
293
+ const f = sub(mul(cd, -(j.stiffness ?? 40) * (cl - restL)), mul(vel, j.damping ?? 3));
294
+ vel = add(vel, mul(f, h));
295
+ x = add(x, mul(vel, h));
296
+ }
297
+ const rest = Math.abs(stretch) < 1e-4 * Math.max(restL, 1e-3) && v3.len(vel) < 1e-3 * Math.max(restL, 1e-3);
298
+ return { move: { R: ID3, about: [0, 0, 0], t: rest ? mul(dir, -stretch) : x }, v: rest ? [0, 0, 0] : vel, rest };
299
+ };
300
+ /** The spring object stretched between the spring's two ends now. */
301
+ export const springMesh = (j, meshA, meshB) => {
302
+ if (!j.spring)
303
+ return null;
304
+ const fa = frameOf(meshA, j.frameA), fb = frameOf(meshB, j.frameB);
305
+ const A = toWorld(fa, j.at), Bp = toWorld(fb, j.bAt);
306
+ const m = j.spring.mesh;
307
+ const [r0, r1] = j.spring.ends;
308
+ const d0 = sub(r1, r0), L0 = v3.len(d0), d1 = sub(Bp, A), L1 = v3.len(d1);
309
+ if (L0 <= 0 || L1 <= 0)
310
+ return m;
311
+ const u0 = mul(d0, 1 / L0), u1 = mul(d1, 1 / L1);
312
+ const c = dot(u0, u1), ax = cross(u0, u1), sn = v3.len(ax);
313
+ const R = sn < 1e-9 ? (c > 0 ? ID3 : axisAngle(Math.abs(u0[0]) < 0.9 ? norm(cross(u0, [1, 0, 0])) : norm(cross(u0, [0, 1, 0])), Math.PI)) : axisAngle(mul(ax, 1 / sn), Math.atan2(sn, c));
314
+ const k = L1 / L0;
315
+ return {
316
+ ...m,
317
+ positions: m.positions.map((p) => {
318
+ const w = sub(p, r0), along = dot(w, u0);
319
+ const stretched = add(w, mul(u0, along * (k - 1))); // stretch along the line only
320
+ return add(A, mVec(R, stretched));
321
+ }),
322
+ };
323
+ };
324
+ /**
325
+ * The objects that move rigidly with `roots` when they are moved freely: their groups, everything glued to them (both ways) and
326
+ * everything they hold by a pivot, hinge or rail (and so on down). Springs are not rigid: their held parts follow by the spring.
327
+ */
328
+ export const carried = (roots, objects, joints) => {
329
+ const groupOf = new Map(objects.map((o) => [o.name, o.group]));
330
+ const set = new Set(roots);
331
+ const stack = [...roots];
332
+ while (stack.length) {
333
+ const n = stack.pop();
334
+ const g = groupOf.get(n);
335
+ const more = [];
336
+ if (g)
337
+ for (const o of objects)
338
+ if (o.group === g)
339
+ more.push(o.name);
340
+ for (const j of joints) {
341
+ if (j.type === 'spring')
342
+ continue;
343
+ if (j.a === n)
344
+ more.push(j.b);
345
+ if (j.type === 'glue' && j.b === n)
346
+ more.push(j.a);
347
+ }
348
+ for (const m of more)
349
+ if (!set.has(m))
350
+ (set.add(m), stack.push(m));
351
+ }
352
+ return [...set];
353
+ };
354
+ /** The joint that holds `name` (it is the b of a pivot, hinge or rail), if any. */
355
+ export const holderOf = (name, joints) => joints.find((j) => j.b === name && (j.type === 'pivot' || j.type === 'hinge' || j.type === 'rail'));
@@ -0,0 +1,2 @@
1
+ // Generated by scripts/build-kernel.mjs from kernel/pick.hexaw. Do not edit.
2
+ export const KERNEL_BYTES = 'AGFzbQEAAAABDwFgCnx8fHx8fH9/f38BfwMCAQAFBQEBAYACBxECBHBpY2sAAAZtZW1vcnkCAAqpBAGmBAIGfxl8QQAhCkF/IQ9EnHUAiDzkN34hEAJAA0AgCiAITg0BIAcgCkEEdGohCyALKAIAQRhsIAZqIQwgCygCBEEYbCAGaiENIAsoAghBGGwgBmohDgJAIAwrAwAhESAMKwMIIRIgDCsDECETIA0rAwAgEaEhFCANKwMIIBKhIRUgDSsDECAToSEWIA4rAwAgEaEhFyAOKwMIIBKhIRggDisDECAToSEZIAQgGaIgBSAYoqEhGiAFIBeiIAMgGaKhIRsgAyAYoiAEIBeioSEcIBQgGqIgFSAboqAgFiAcoqAhHSAUIBSiIBUgFaKgIBYgFqKgIBcgF6IgGCAYoqAgGSAZoqCiISggHSAdokSnjqiZwlfzOiAoomUNACAJIB1EAAAAAAAAAABlcQ0ARAAAAAAAAPA/IB2jIR4gACARoSEfIAEgEqEhICACIBOhISEgHiAfIBqiICAgG6KgICEgHKKgoiEiICJEAAAAAAAAAABjICJEAAAAAAAA8D9kcg0AICAgFqIgISAVoqEhIyAhIBSiIB8gFqKhISQgHyAVoiAgIBSioSElIB4gAyAjoiAEICSioCAFICWioKIhJiAmRAAAAAAAAAAAYyAiICagRAAAAAAAAPA/ZHINACAeIBcgI6IgGCAkoqAgGSAloqCiIScgJ0QAAAAAAAAAAGUNACAnIBBmDQAgJyEQIAsoAgwhDwsgCkEBaiEKDAALC0EAIBA5AwAgDws=';
@@ -0,0 +1,82 @@
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 { triangulate } from './triangulate.js';
7
+ import { ray } from './camera.js';
8
+ import { KERNEL_BYTES } from './kernel-bytes.js';
9
+ const POS = 64; // vertices start here, 24 bytes each (f64 x y z)
10
+ const decode = (b64) => {
11
+ if (typeof Buffer !== 'undefined')
12
+ return new Uint8Array(Buffer.from(b64, 'base64'));
13
+ const s = atob(b64);
14
+ return Uint8Array.from(s, (c) => c.charCodeAt(0));
15
+ };
16
+ export const initKernel = async () => {
17
+ if (typeof WebAssembly === 'undefined')
18
+ throw new Error('WebAssembly is not available');
19
+ const { instance } = (await WebAssembly.instantiate(decode(KERNEL_BYTES)));
20
+ const { pick: kPick, memory } = instance.exports;
21
+ let uploaded = null; // the mesh now in the kernel's memory
22
+ let triBase = 0;
23
+ let triCount = 0;
24
+ const upload = (mesh) => {
25
+ const nv = mesh.positions.length;
26
+ let nt = 0;
27
+ for (const f of mesh.faces)
28
+ nt += Math.max(0, f.v.length - 2);
29
+ triBase = (POS + nv * 24 + 7) & ~7;
30
+ const need = Math.ceil((triBase + nt * 16 + 8) / 65536);
31
+ const have = memory.buffer.byteLength / 65536;
32
+ if (need > have)
33
+ memory.grow(need - have);
34
+ // grow() detaches the old buffer, so the views are made after it
35
+ const f64 = new Float64Array(memory.buffer, POS, nv * 3);
36
+ for (let i = 0; i < nv; i++) {
37
+ const p = mesh.positions[i];
38
+ f64[i * 3] = p[0];
39
+ f64[i * 3 + 1] = p[1];
40
+ f64[i * 3 + 2] = p[2];
41
+ }
42
+ // faces are cut into triangles (a fan, or ear clipping for a concave one), each remembering its face number
43
+ const i32 = new Int32Array(memory.buffer, triBase, nt * 4);
44
+ let at = 0;
45
+ mesh.faces.forEach((f, face) => {
46
+ for (const [a, b, c] of triangulate(f.v.map((k) => mesh.positions[k]))) {
47
+ i32[at] = f.v[a];
48
+ i32[at + 1] = f.v[b];
49
+ i32[at + 2] = f.v[c];
50
+ i32[at + 3] = face;
51
+ at += 4;
52
+ }
53
+ });
54
+ triCount = nt;
55
+ uploaded = mesh;
56
+ };
57
+ /**
58
+ * The nearest surface under panel pixel (x, y), or null: the same result as pick() in pick.js,
59
+ * { face, distance, point, normal, front, color }.
60
+ */
61
+ const pick = (mesh, cam, x, y, { cull = true } = {}) => {
62
+ if (mesh !== uploaded)
63
+ upload(mesh);
64
+ const { origin: o, dir: d } = ray(cam, x, y);
65
+ const face = kPick(o[0], o[1], o[2], d[0], d[1], d[2], POS, triBase, triCount, cull ? 1 : 0);
66
+ if (face < 0)
67
+ return null;
68
+ const distance = new Float64Array(memory.buffer, 0, 1)[0];
69
+ const f = mesh.faces[face];
70
+ const outward = norm(faceNormal(f.v.map((k) => mesh.positions[k])));
71
+ const front = dot(outward, d) < 0;
72
+ return {
73
+ face,
74
+ distance,
75
+ point: plus(o)(times(distance)(d)),
76
+ normal: front ? outward : times(-1)(outward),
77
+ front,
78
+ color: f.color,
79
+ };
80
+ };
81
+ return { pick, get loaded() { return uploaded; }, instance };
82
+ };
@@ -0,0 +1,87 @@
1
+ // The lathe: a contour drawn on a plane is turned round an axis into a solid. Pure geometry, one closed mesh.
2
+ // The axis is a line in the plane (for the app: the bottom line of the face the contour was drawn on); the contour is a list of
3
+ // [u, r] points: u along the axis, r the distance from it (0 = on the axis). Both ends are closed: an end off the axis gets a flat disc,
4
+ // an end on the axis is a point (a tip).
5
+ import { add, scale as mul, dot } from './vec.js';
6
+ export const lathe = (contour, frame, segments = 7, { mat, color = '#c8c8c8' } = {}) => {
7
+ if (!Number.isInteger(segments) || segments < 3)
8
+ throw new Error('a lathe needs 3 or more segments');
9
+ const span = Math.max(...contour.map(([, r]) => Math.abs(r)), 1e-9);
10
+ const eps = span * 1e-6;
11
+ // the same point twice in a row is one point
12
+ const pts = [];
13
+ for (const q of contour) {
14
+ const last = pts[pts.length - 1];
15
+ if (!last || Math.hypot(q[0] - last[0], q[1] - last[1]) > eps)
16
+ pts.push([q[0], q[1]]);
17
+ }
18
+ if (pts.length < 2)
19
+ throw new Error('the contour needs 2 different points');
20
+ if (pts.some(([, r]) => r < -eps))
21
+ throw new Error('the contour must stay on one side of the axis (r >= 0)');
22
+ const on = pts.map(([, r]) => r <= eps);
23
+ // which way is the inside: the sign of the area between the contour and the axis
24
+ const loop = [...pts, [pts[pts.length - 1][0], 0], [pts[0][0], 0]];
25
+ let area = 0;
26
+ for (let i = 0; i < loop.length; i++) {
27
+ const a = loop[i];
28
+ const b = loop[(i + 1) % loop.length];
29
+ area += a[0] * b[1] - b[0] * a[1];
30
+ }
31
+ if (Math.abs(area) < eps * span)
32
+ throw new Error('the contour and the axis enclose nothing');
33
+ const sgn = area > 0 ? 1 : -1;
34
+ const ang = (j) => (2 * Math.PI * j) / segments;
35
+ const radial = (t) => add(mul(frame.up, Math.cos(t)), mul(frame.normal, Math.sin(t)));
36
+ const positions = [];
37
+ const ring = pts.map(([u, r], i) => {
38
+ if (on[i]) {
39
+ positions.push(add(frame.origin, mul(frame.right, u)));
40
+ return [positions.length - 1];
41
+ }
42
+ return Array.from({ length: segments }, (_, j) => {
43
+ positions.push(add(add(frame.origin, mul(frame.right, u)), mul(radial(ang(j)), r)));
44
+ return positions.length - 1;
45
+ });
46
+ });
47
+ const faces = [];
48
+ const put = (v, want) => {
49
+ // wound so that the face looks the way it should (its Newell normal agrees with `want`)
50
+ const n = [0, 0, 0];
51
+ for (let k = 0; k < v.length; k++) {
52
+ const a = positions[v[k]];
53
+ const b = positions[v[(k + 1) % v.length]];
54
+ n[0] += (a[1] - b[1]) * (a[2] + b[2]);
55
+ n[1] += (a[2] - b[2]) * (a[0] + b[0]);
56
+ n[2] += (a[0] - b[0]) * (a[1] + b[1]);
57
+ }
58
+ faces.push({ v: dot(n, want) < 0 ? [...v].reverse() : v, color, ...(mat ? { mat } : {}) });
59
+ };
60
+ for (let i = 0; i + 1 < pts.length; i++) {
61
+ if (on[i] && on[i + 1])
62
+ continue; // a piece of the axis itself: no surface
63
+ const du = pts[i + 1][0] - pts[i][0];
64
+ const dr = pts[i + 1][1] - pts[i][1];
65
+ const n2 = [sgn * dr, -sgn * du]; // outward, in the plane of the contour
66
+ for (let j = 0; j < segments; j++) {
67
+ const want = add(mul(frame.right, n2[0]), mul(radial(ang(j + 0.5)), n2[1]));
68
+ const a = ring[i];
69
+ const b = ring[i + 1];
70
+ const j2 = (j + 1) % segments;
71
+ if (on[i])
72
+ put([a[0], b[j], b[j2]], want);
73
+ else if (on[i + 1])
74
+ put([a[j], a[j2], b[0]], want);
75
+ else
76
+ put([a[j], a[j2], b[j2], b[j]], want);
77
+ }
78
+ }
79
+ // the two ends: a disc where the contour does not end on the axis
80
+ const first = pts[0];
81
+ const last = pts[pts.length - 1];
82
+ if (!on[0])
83
+ put(ring[0], mul(frame.right, sgn * first[1]));
84
+ if (!on[pts.length - 1])
85
+ put(ring[pts.length - 1], mul(frame.right, -sgn * last[1]));
86
+ return { positions, faces };
87
+ };
@@ -0,0 +1,19 @@
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 clamp = (n, fallback, max = 1) => (typeof n === 'number' && Number.isFinite(n) ? Math.max(0, Math.min(max, n)) : fallback);
5
+ export const EMIT_MAX = 5;
6
+ export const FALLBACK_COLOR = '#c8c8c8';
7
+ export const DEFAULTS = { metal: 0, rough: 0.7, alpha: 1, emit: 0, soft: 0 };
8
+ /** The surface of a face: its palette entry when it names one, else just its color with default properties. */
9
+ export const surfaceOf = (face, palette) => {
10
+ const m = face.mat !== undefined ? palette?.[face.mat] : undefined;
11
+ return {
12
+ color: m?.color ?? face.color ?? FALLBACK_COLOR,
13
+ metal: clamp(m?.metal, DEFAULTS.metal),
14
+ rough: clamp(m?.rough, DEFAULTS.rough),
15
+ alpha: clamp(m?.alpha, DEFAULTS.alpha),
16
+ emit: clamp(m?.emit, DEFAULTS.emit, EMIT_MAX),
17
+ soft: clamp(m?.soft, DEFAULTS.soft),
18
+ };
19
+ };