Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
"predecoder": "npm run bundle:standalone",
"preverify:exports": "npm run bundle:standalone",
"prelint": "npm run bundle:standalone",
"build:package": "npm run bundle:standalone && node scripts/build-package.mjs",
"build:package": "node scripts/build-standalone.mjs --force && node scripts/build-package.mjs",
"prepack": "npm run build:package",
"prepublishOnly": "npm run check"
},
Expand Down
78 changes: 59 additions & 19 deletions scripts/build-standalone.mjs
Original file line number Diff line number Diff line change
@@ -1,26 +1,66 @@
// Bundles the browser viewer (renderer + runtime) into a string module that
// exporters embed into standalone HTML exhibits.
//
// npm pre-scripts call this before almost every command, so it skips the build
// when nothing the bundle reads has changed since the last run. The stamp lists
// every local source file esbuild read, plus the lockfile and this script.
// Pass --force to rebuild regardless.
import { build } from 'esbuild';
import { createHash } from 'node:crypto';
import { existsSync, readFileSync } from 'node:fs';
import { mkdir, writeFile } from 'node:fs/promises';

const result = await build({
entryPoints: ['src/engine/standalone.ts'],
bundle: true,
platform: 'browser',
format: 'iife',
target: 'es2022',
write: false,
minify: true,
legalComments: 'inline',
define: { 'process.env.NODE_ENV': '"production"' },
});
const OUT = 'src/generated/standalone.ts';
const STAMP = 'src/generated/standalone.stamp.json';
const ALWAYS = ['package-lock.json', 'scripts/build-standalone.mjs'];

const js = result.outputFiles[0].text;
if (!js.length) throw new Error('Empty standalone bundle');
const hashFile = (file) => {
try {
return createHash('sha256').update(readFileSync(file)).digest('hex');
} catch {
return null;
}
};

await mkdir('src/generated', { recursive: true });
await writeFile(
'src/generated/standalone.ts',
`// Generated by scripts/build-standalone.mjs. Do not edit.\nexport const standaloneBundle = ${JSON.stringify(js)};\n`,
);
console.log(`Standalone bundle: ${js.length} characters`);
function upToDate() {
if (process.argv.includes('--force') || !existsSync(OUT) || !existsSync(STAMP)) return false;
try {
const stamp = JSON.parse(readFileSync(STAMP, 'utf8'));
const files = Object.entries(stamp.inputs ?? {});
return files.length > 0 && files.every(([file, hash]) => hashFile(file) === hash);
} catch {
return false;
}
}

if (upToDate()) {
console.log('Standalone bundle: up to date');
} else {
const result = await build({
entryPoints: ['src/engine/standalone.ts'],
bundle: true,
platform: 'browser',
format: 'iife',
target: 'es2022',
write: false,
minify: true,
metafile: true,
legalComments: 'inline',
define: { 'process.env.NODE_ENV': '"production"' },
});

const js = result.outputFiles[0].text;
if (!js.length) throw new Error('Empty standalone bundle');

await mkdir('src/generated', { recursive: true });
await writeFile(
OUT,
`// Generated by scripts/build-standalone.mjs. Do not edit.\nexport const standaloneBundle = ${JSON.stringify(js)};\n`,
);

// node_modules inputs are covered by the lockfile hash.
const local = Object.keys(result.metafile.inputs).filter((file) => !file.includes('node_modules/'));
const inputs = Object.fromEntries([...local, ...ALWAYS].map((file) => [file, hashFile(file)]));
await writeFile(STAMP, `${JSON.stringify({ inputs }, null, 2)}\n`);
console.log(`Standalone bundle: ${js.length} characters`);
}
90 changes: 90 additions & 0 deletions skills/decoder/GEOMETRY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Geometry vocabulary

Every component's `geometry` is `{ "type": ..., "params": { ... } }`, optionally with `modifiers` and `booleans`. Sizes are in scene units, the same units as `transform.position`. Each shape is centred on its own origin; round shapes stand along the Y axis, so rotate the component to lay them along X or Z.

Any param you leave out takes the default shown. Unknown params are ignored silently, so spell them exactly. Source of truth: `buildPrimitive` in `src/engine/geometry.ts`.

## Basic solids

| type | params (default) |
| ----------------------------- | ------------------------------------------------------------------------------------------------------- |
| `box` | `width` 0.5, `height` 0.5, `depth` 0.5. Edges get a small automatic round unless a side is under 0.014. |
| `rounded_box` | `width` 0.5, `height` 0.5, `depth` 0.5, `radius` 0.05 (corner radius) |
| `cylinder` | `radius` 0.25, `height` 0.6, `segments` 44 (min 24) |
| `tapered_cylinder` | `radiusTop` 0.18, `radiusBottom` 0.3, `height` 0.6, `segments` 44 |
| `sphere` | `radius` 0.3, `widthSegments` 40, `heightSegments` 28 |
| `ellipsoid` | `rx` 0.3, `ry` 0.4, `rz` 0.25 (semi-axes) |
| `cone` | `radius` 0.3, `height` 0.6 |
| `dome` | `radius` 0.35 (upper hemisphere) |
| `torus` | `radius` 0.35 (ring), `tube` 0.08 (thickness), `segments` 64 |
| `hollow_vessel`, `thin_shell` | `outerRadius` 0.35, `innerRadius` 0.28, `height` 0.7, `openTop` true |

## Profiles and paths

| type | params (default) |
| --------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `extrude` | `points` [[x,y], ...] closed 2D outline (default 0.6 × 0.4 rectangle), `depth` 0.2, `bevel` true, `bevelThickness` 0.016, `bevelSize` 0.016. Centred after extrusion. |
| `revolve` | `points` [[r,y], ...] half-profile turned about Y (r is distance from the axis), `segments` 48, `smooth` false (true splines the profile) |
| `loft` | `sections` [{ `y`, `points` [[x,z], ...] }, ...]: at least 2, each with the same point count |
| `sweep` | `path` [[x,y,z], ...] (smooth curve through the points), `radius` 0.05 |
| `tube`, `pipe_network`, `flexible_hose` | `points` [[x,y,z], ...], `radius` 0.04, `closed` false. Adds collars at the joints. |
| `rib` | `width` 0.4, `height` 0.25, `thickness` 0.04 (right-triangle gusset) |
| `custom_mesh` | `vertices` flat [x,y,z, ...], `indices` flat triangle list. Use sparingly; normals are computed. |

## Mechanical parts

| type | params (default) |
| -------------------- | ------------------------------------------------------------------------------------------------------- |
| `gear` | `teeth` 18 (min 6), `module` 0.04 (pitch diameter = teeth × module), `thickness` 0.1, `boreRadius` 0.08 |
| `gear_train` | `count` 3 (min 2), `module` 0.035. Meshed gears of 12 and 20 teeth alternating along X. |
| `spring` | `radius` 0.18 (coil), `wireRadius` 0.022, `height` 0.5, `coils` 6 |
| `thread` | `radius` 0.14, `pitch` 0.018 (ridge thickness, not the lead), `height` 0.4, `turns` 8 |
| `bearing` | `outerRadius` 0.32, `innerRadius` 0.16, `width` 0.12, `balls` 10 (min 6) |
| `fastener` | `radius` 0.025 (shank), `headHeight` 0.024, `length` 0.06 |
| `flange` | `outerRadius` 0.28, `innerRadius` 0.1, `thickness` 0.055, `bolts` 6 (min 3) |
| `gasket_ring` | `radius` 0.24, `tube` 0.016, `segments` 44 (lies flat in XZ) |
| `piston_cylinder` | `radius` 0.32, `height` 0.36. A piston with ring lands, rings, pin and bosses. |
| `pump_unit` | `radius` 0.22, `length` 0.6 (lies along X) |
| `electric_motor` | `radius` 0.35, `length` 0.85 (lies along X, finned, shaft out both ends) |
| `hydraulic_manifold` | `width` 0.65, `height` 0.28, `depth` 0.35 |
| `heat_exchanger` | `width` 0.7, `height` 0.5, `depth` 0.35, `fins` 11 (min 4) |

## Electronic, layered and organic

| type | params (default) |
| ---------------------------------------- | ------------------------------------------------------------------------------- |
| `circuit_board` | `width` 1.0, `height` 0.04 (board thickness), `depth` 0.7, `chips` 5 (min 2) |
| `processor_die` | `width` 1.4, `height` 0.08, `depth` 1.4, `cores` 4 (min 2) |
| `layered_surface` | `layers` 4 (min 2), `width` 1.0, `depth` 1.0, `layerThickness` 0.04, `gap` 0.02 |
| `branching_structure`, `vascular_branch` | `length` 0.9, `radius` 0.09, `branches` 3 (min 2) |
| `molecular_lattice` | `atoms` 8 (min 4), `radius` 0.35 (ring radius) |

## `instanced`

A small repeated part; the shape depends on which params you give:

- `coils` set: spring (`radius` 0.1, `wireRadius` 0.015, `height` 0.25, `coils`).
- else `tube` set: torus (`radius` 0.14, `tube`, `segments` 40).
- else `width` or `depth` set: rounded box (`width` 0.12, `height` 0.06, `depth` 0.08).
- otherwise: cylinder (`radius` 0.05, `height` 0.05).

An unknown `type` renders a 0.4 placeholder cube; `validate` reports it.

## Modifiers

`modifiers` is a list of `{ "kind": ..., ... }` applied in order. Shared fields: `axis` (`x`, `y` or `z`; default `y`) and `offset` [x,y,z].

| kind | fields (default) |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
| `perforation` | `count` 4 (1 to 20), `radius` 0.04, `depth` 1.2, `width` 0.25 (hole spacing) |
| `slot`, `groove` | `width` 0.1, `depth` 0.08, `length` 0.6 |
| `seam` | with `radius`: a ring seam (`depth` 0.008). Without: a flat seam (`width` 0.65, `depth` 0.012, `length` 0.65). |
| `fasteners` | `count` 4 (1 to 16), `boltRadius` 0.02. With `radius`: a bolt circle. Without: corner bolts across `width` 0.4 × `length` 0.4. |
| `gasket`, `o_ring` | `radius` 0.24, `width` 0.015 (cord thickness) |
| `ribs` | `count` 6 (2 to 16), `radius` 0.26, `width` 0.06, `depth` 0.14, `length` 0.022 (rib thickness) |
| `knurling` | `radius` 0.17, `count` 10 (4 to 24), `length` 0.4, `depth` 0.006 |
| `chamfer`, `bevel` | `radius` 0.2, `depth` 0.024 (adds a chamfered collar) |

## Booleans

`booleans` is a list of `{ "op": "union" | "subtract" | "intersect", "target": <geometry spec>, "transform": <optional transform> }`, applied after modifiers. Use `subtract` for real bores and cut-outs (a cutaway, a hollow handle). Booleans are slower than modifiers, so prefer a modifier when one fits.
5 changes: 3 additions & 2 deletions skills/decoder/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,14 @@ Never edit renderer, Studio or runtime code to represent a subject. Everything a
Study a built-in exhibit in `src/projects/` that is close to the subject before writing your own.

2. **Describe three synchronised layers.**
- `components`: nested parts, each with `geometry`, `materialId`, `transform`, `disassembly` and `evidence`.
- `components`: nested parts, each with `geometry`, `materialId`, `transform`, `disassembly` and `evidence`. Every geometry type, its params and defaults, plus modifiers and booleans, are listed in [GEOMETRY.md](GEOMETRY.md). Unknown params are ignored silently, so check spelling there.
- `relationships`: typed edges between parts: `force`, `torque`, `rotation`, `translation`, `electrical_power`, `information`, `signal`, `liquid_flow`, `gas_flow`, `heat`, `chemical_exchange`, `optical_transmission`, `control`, `feedback`, `logical_dependency`.
- `effects`: illustrative particles, glows and rays. `radius` is particle size, not coverage; keep it small (a few hundredths of the model's size) and use `path` and `density` to cover an area.
- `simulation` and `behaviours`: safe declarative expressions (`sin`, `cos`, `clamp`, `lerp`, `if`, `mod`, `sliderCrank`, `conrodAngle`, lookup tables, ODEs and state machines). No code is ever evaluated.

3. **Validate until clean.**
`npm run decoder -- validate <name>.decoder.json`
Fix every error on the component it names (`MISSING_MATERIAL`, `INVALID_GEOMETRY_DIMENSION`, `INVALID_EXPRESSION`, `BROKEN_PARENT_REFERENCE` and so on). Treat warnings as work to do, not noise.
Fix every error on the component it names (`MISSING_MATERIAL`, `UNKNOWN_GEOMETRY_TYPE`, `INVALID_GEOMETRY_DIMENSION`, `INVALID_EXPRESSION`, `BROKEN_PARENT_REFERENCE` and so on). Treat warnings as work to do, not noise.

4. **Inspect and simulate.**
`npm run decoder -- inspect <name>.decoder.json` prints diagnostics, bounds and the disassembly plan.
Expand Down
2 changes: 1 addition & 1 deletion src/components/ui/labels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export function formatNumber(value: number, step?: number): string {
/** Splits a runtime readout ("9.0 bar") into its number and unit. */
export function splitReadout(formatted: string, unit: MeasurementUnit): { value: string; unit: string } {
const [value] = formatted.split(' ');
return { value, unit: unitText(unit) };
return { value: unit === '%' ? value.replace(/%$/, '') : value, unit: unitText(unit) };
}

export const LIGHTING_LABELS: Record<LightingPresetId, string> = {
Expand Down
35 changes: 35 additions & 0 deletions src/engine/engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,38 @@ test('technical illustrations are well-formed SVG markup for every aesthetic', (
);
}
});

test('validation warns when an effect radius swamps the model, and not at normal sizes', () => {
const sdk = new DecoderSDK();
const p = structuredClone(BUILTIN_EXHIBITS[0]);
assert.ok(p.effects.length > 0);
assert.ok(!sdk.validate(p).issues.some((i) => i.code === 'EFFECT_RADIUS_TOO_LARGE'));
p.effects[0].radius = 1.5;
const issue = sdk.validate(p).issues.find((i) => i.code === 'EFFECT_RADIUS_TOO_LARGE');
assert.equal(issue?.severity, 'warning');
assert.equal(issue?.path, `/effects/${p.effects[0].id}/radius`);
sdk.dispose();
});

test('percent outputs read as 42.5% and split into number and unit', async () => {
const { splitReadout, unitText } = await import('../components/ui/labels');
const p = structuredClone(BUILTIN_EXHIBITS[0]);
p.simulation.outputs = [{ id: 'duty', label: 'Duty', expression: '42.5', unit: '%', precision: 1 }];
const sdk = new DecoderSDK();
const out = sdk.simulateStep(p, 0).outputs[0];
assert.equal(out.formatted, '42.5%');
assert.deepEqual(splitReadout(out.formatted, '%'), { value: '42.5', unit: '%' });
assert.equal(unitText('%'), '%');
sdk.dispose();
});

test('validation rejects an unknown geometry type instead of drawing a placeholder', () => {
const sdk = new DecoderSDK();
const p = structuredClone(BUILTIN_EXHIBITS[0]);
const comp = p.components.find((c) => c.geometry)!;
(comp.geometry as { type: string }).type = 'blob';
const issue = sdk.validate(p).issues.find((i) => i.code === 'UNKNOWN_GEOMETRY_TYPE');
assert.equal(issue?.severity, 'error');
assert.equal(issue?.componentId, comp.id);
sdk.dispose();
});
2 changes: 1 addition & 1 deletion src/engine/geometry.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as THREE from 'three';
import { ADDITION, Brush, Evaluator, INTERSECTION, SUBTRACTION } from 'three-bvh-csg';
import { ADDITION, Brush, Evaluator, INTERSECTION, SUBTRACTION } from 'three-bvh-csg/src/index.js';
import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js';
import type {
ComponentNode,
Expand Down
5 changes: 4 additions & 1 deletion src/engine/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,10 @@ export class DecoderRuntime {
label: out.label,
value: val,
unit: out.unit as MeasurementUnit,
formatted: `${val.toFixed(prec)} ${out.unit === 'unitless' ? '' : out.unit}`.trim(),
formatted:
out.unit === '%'
? `${val.toFixed(prec)}%`
: `${val.toFixed(prec)} ${out.unit === 'unitless' ? '' : out.unit}`.trim(),
};
});

Expand Down
1 change: 1 addition & 0 deletions src/engine/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export type MeasurementUnit =
| 'N'
| 'Nm'
| 'ratio'
| '%'
| 'unitless';

export type EvidenceClassification = 'observed' | 'documented' | 'inferred' | 'illustrative' | 'unknown';
Expand Down
Loading
Loading