Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add curve and text geometry

Nguyen Xuan An2e9b92ad0a25
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 216fdc15..680cfe0a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Add `curve` and `text` geometry (part of issue #45). `curve` sweeps a round or custom profile along a cubic Bezier chain with explicit or automatic handles, a taper along the length and flat caps; `text` extrudes the outlines of the bundled DejaVu Sans (printable ASCII, 20 KB, loaded on demand with its own `text` module and never in an entry) or of a font table added with `registerAgentSceneFont`, with size, depth, alignment, lines and curve resolution. Volume, area and bounds match Blender 5.2 to 2e-5 for two Bezier curves and for a letter and a word set in the same font. Recipes stay plain JSON with bounded, validated fields and vertex estimates checked before generation. The MCP schemas gain two strict entries in the geometry list (1.4 KB of the 190 KB across all tools; not offered as mesh bases or cutters); field types and limits live in `scene_capabilities` under `curveText`, and the MCP takes no font file or URL. The DejaVu licence is in `THIRD-PARTY-NOTICES.md`. Metaballs and NURBS surfaces are recorded as out of scope in `docs/parity.md`. Not done: a suite task in `bench/agent-modeling`, kerning, bevelled text, non-ASCII glyphs in the bundled font.
+
- Add render passes, depth of field and camera motion blur (issue #54, first slice). Render jobs of kind `image` or `stills` take `settings.passes` (`albedo`, `normal`, `emission`, `depth`, `objectId`) and write each as a raw, unantialiased PNG beside the lit image (`render-depth.png`, `frame-3-objectId.png`); depth is 16 bits over 100 m in red and green, object IDs are 24 bits with the part names in the job metrics. In code, `renderer.render({ pass })` draws a pass into its own non-multisampled target. `effects.depthOfField` (`blur`, `focusDistance`) and `effects.motionBlur` (`shutter`) are new recipe effects: fixed sample patterns and a per-pixel rotation from the pixel position, so a seek to a frame repeats the same pixels. They live in the new `67js/addons/camera-effects` entry; the preview installs it, and the core renderer only gains a stage hook and the pass branch (a compiled-out shader feature). Motion blur follows camera tracks only, sampled from time at `motion.start + elapsed - shutter`. Measured on SwiftShader through MCP (`npm run smoke:render-passes`): 8 stills with 5 passes each, then four seeks, all byte-identical to the same frame in the sequence. Temporal anti-aliasing, accumulation and the compositing graph of #54 are not part of this slice.
- Expose clip layers, bone masks and name retargeting through MCP, and morph clips in `createAssetPose` (issue #59, in part). An asset recipe's `motion.layers` (up to 8) plays the file's own clips at motion time with a bone `mask`, `weight`, `speed`, `offset`, `loop`, `additive` with `reference`, `bones` (clip track to another asset node) and `morph`, before tracks and IK, so a character walks and waves at once; everything is checked against the asset and bounded, and a seek equals playing. `morphClipFromGltfAnimation` and a layer's `morphs` put morph weights through `createAssetPose` (masks pick parts by their owning bone), `createAssetLayerEvaluator` serves hosts that stage the pose themselves, and `asset.stagePose` takes `morphWeights`. Add the `robot-walk-wave` task to the agent modeling suite and extend `npm run smoke:character`. Not done: foot tilt on slopes, full-body IK, and rest-pose retargeting from another asset through MCP. Raise `entry:skeleton-pose` to 19,000 and `entry:agent-asset` to 85,200 bytes gzip, and the tool schema budgets by 800 bytes (`scene_apply` to 47,800, `scene_create_asset` to 20,150, total to 190,700).
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index be64a19b..d67a2eae 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -87,3 +87,41 @@ Rapier is distributed under the Apache License, Version 2.0.
Its dependency package includes the complete license text.
Rapier's JavaScript and WASM code are not bundled into the 67.js library archive.
Source and license: https://github.com/dimforge/rapier.js.
+
+## DejaVu Sans 2.37 (3D text outlines, `src/font-default.js`)
+
+`src/font-default.js` holds the outlines of the printable ASCII characters of DejaVu Sans, extracted by `scripts/build-font.py`.
+They load on demand with the text geometry. Fonts are (c) Bitstream; changes by DejaVu are in the public domain.
+Only the Bitstream Vera and DejaVu glyphs of Basic Latin are used. The data is not renamed or edited, so the Vera licence applies as written:
+
+Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and
+associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation
+the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the
+Font Software is furnished to do so, subject to the following conditions:
+
+The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font
+Software typefaces.
+
+The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be
+modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either
+the words "Bitstream" or the word "Vera".
+
+This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed
+under the "Bitstream Vera" names.
+
+The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be
+sold by itself.
+
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT
+SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT,
+INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY
+TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE.
+
+Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or
+otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome
+Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org.
+
+Source: https://dejavu-fonts.github.io/ (version 2.37).
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index 212db5cc..e62e8e1e 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -11,7 +11,7 @@
"entry:motion": 13600,
"entry:canvas2d": 9400,
"entry:gltf": 48500,
- "entry:modeling": 6600,
+ "entry:modeling": 8500,
"entry:sculpt": 2500,
"entry:surface": 10100,
"entry:mesh-query": 15900,
@@ -28,16 +28,16 @@
"entry:grass": 4400,
"entry:clutter": 5300,
"entry:texture-set": 900,
- "entry:agent-scene": 59200,
- "entry:agent-scene+lazy": 169800,
+ "entry:agent-scene": 59800,
+ "entry:agent-scene+lazy": 180000,
"entry:agent-asset": 88700,
- "entry:agent-asset+lazy": 178900,
+ "entry:agent-asset+lazy": 188900,
"entry:hdri": 3300,
"entry:camera-effects": 8600,
"entry:render-passes": 1700,
"scene:lit-box": 58200,
"scene:gltf-box": 77800,
"scene:agent-scene": 87200,
- "scene:agent-scene+lazy": 197700
+ "scene:agent-scene+lazy": 207300
}
}
diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.json
index adde1006..a2b1cda9 100644
--- a/bench/tool-cost-budgets.json
+++ b/bench/tool-cost-budgets.json
@@ -1,16 +1,16 @@
{
- "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167)",
- "schemaTotalBytes": 189210,
+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities; curve and text geometry added as two strict schema entries in the geometry list only, field types and limits in scene_capabilities curveText (total 189673, under 190000, scene_capabilities result 6183)",
+ "schemaTotalBytes": 189700,
"schemaToolBytes": {
- "scene_create": 60495,
- "scene_apply": 46225,
- "mesh_edit": 33875,
+ "scene_create": 60930,
+ "scene_apply": 46730,
+ "mesh_edit": 33740,
"scene_create_asset": 19450,
"mesh_stack": 11335
},
"schemaOtherToolBytes": 4000,
"resultBytes": {
- "scene_capabilities": 5195,
+ "scene_capabilities": 6200,
"scene_create": 1400,
"scene_inspect": 1400,
"mesh_inspect": 1200,
diff --git a/docs/agent-scene.md b/docs/agent-scene.md
index f0c2eae0..4f74c81e 100644
--- a/docs/agent-scene.md
+++ b/docs/agent-scene.md
@@ -47,7 +47,7 @@ The normal frame loop can render retained parts without calling inspection or ex
### On-demand code
-Mesh editing, `lathe`, `extrude` and `tube` geometry, material `pattern` and `motion` load on demand, so a recipe of
+Mesh editing, `lathe`, `extrude`, `tube` and `curve` geometry, `text` geometry with its font, material `pattern` and `motion` load on demand, so a recipe of
primitives pays about half the bytes. `createAgentScene` and `apply` stay synchronous. When a recipe uses one of them,
load its code first; a missing module throws an error that names this call.
@@ -88,6 +88,10 @@ The generators also enforce their existing numeric and modeling constraints.
| `lathe` | `profile`, `segments`, `startAngle`, `sweep` | Required XY profile, `64`, `0`, `2π` |
| `extrude` | `contour`, `holes`, `depth`, `steps`, `bevel`, `bevelThickness`, `bevelSegments` | Required XY contour, `[]`, `1`, `1`, `0`, bevel, `3` |
| `tube` | `path`, `radius`, `segments`, `radialSegments`, `closed` | Required XYZ path, `0.1`, `64`, `12`, `false` |
+| `curve` | `points`, `closed`, `radius`, `taper`, `profile`, `resolution`, `radialSegments` | Required points, `false`, `0.05`, none, round, `12`, `8` |
+| `text` | `text`, `size`, `depth`, `font`, `align`, `curveSegments` | Required string, `1`, `0.2`, `default`, `left`, `4` |
+
+`curve` and `text` are described in full by `scene_capabilities` under `curveText.details`; see [modeling.md](modeling.md).
Modeling point inputs have a maximum of 4096 points.
An extrusion has at most 128 holes and 4096 total contour points.
diff --git a/docs/mcp.md b/docs/mcp.md
index cc91a362..8de0b01f 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -127,7 +127,7 @@ Every tool schema is read on every turn, so `node scripts/measure-tool-cost.mjs`
`mesh_inspect` lint adds warnings for `intersecting-parts`, `self-intersection`, `thin-wall`, `floating-part` and `asymmetric`. They never set `ok` to false, run within face budgets, and list any check they skipped in `skippedChecks`. `scene_inspect` returns a `diagnostics` list only when there is something to say: ignored material fields, blended transmission, unused materials or geometries, and for imported assets the decoder's not-drawn features, rigs with no joints or no skin, and assets with no clips. Each item has `kind`, `severity`, `target`, `message` and `fix`.
The recipe uses `format: '67js.scene'` and `schemaVersion: 1`.
-Supported geometry types are `box`, `cylinder`, `sphere`, `torus`, `lathe`, `extrude`, `tube`, and `mesh`.
+Supported geometry types are `box`, `cylinder`, `sphere`, `torus`, `lathe`, `extrude`, `tube`, `curve`, `text`, and `mesh`. The fields of `curve` and `text` are listed by `scene_capabilities` (`curveText.details`) and not repeated in every tool schema. Text uses the bundled font only; the MCP accepts no font file or URL.
A `mesh` geometry starts from one of the others as `base` and replays an edit log; see [mesh.md](mesh.md).
Geometry fields remain flat inside each geometry record.
Set operations use `set-node`, `set-material`, or `set-camera`, with fields directly on each command.
diff --git a/docs/modeling.md b/docs/modeling.md
index be891c3f..d088c1f2 100644
--- a/docs/modeling.md
+++ b/docs/modeling.md
@@ -50,6 +50,38 @@ Open tube ends have no caps. Paths can intersect themselves.
Segments range from 3 to 2048. Radial segments range from 3 to 128.
+## Curve
+
+`curve(points, { closed = false, radius = 0.05, taper, profile, resolution = 12, radialSegments = 8, maxVertices })`
+sweeps a cross-section along a chain of cubic Bezier spans, the way a Blender curve with a bevel does.
+
+- A point is `[x, y, z]`, which gets smooth automatic handles, or `{ position, handleIn, handleOut }` with handles as
+ absolute positions (Blender's convention). A lone handle is mirrored. Open curves need two points, closed ones three, at most 1024.
+- `resolution` is samples per span (1 to 64). The rings use the minimum-twist frames of `tube`.
+- `taper` is 2 to 64 radius factors, at least 0, spread evenly along the arc length: `[1, 0.2]` thins to a fifth.
+- `profile` is 3 to 256 `[x, y]` points of a closed cross-section in units of `radius`, either winding. Without it the
+ section is a circle of `radialSegments` sides (3 to 128). Corners sharper than 40 degrees stay flat shaded.
+- Open curves get flat caps with their own vertices, so the surface is closed and works with booleans.
+
+Volume, area and bounds match Blender 5.2 for an open and a closed Bezier curve with a round bevel to 2e-5
+(`tests/blender-curve-text.test.js`). A Blender bevel resolution of `n` is `radialSegments: 4 + 2n`.
+
+## Text
+
+`text(content, { size = 1, depth = 0.2, font = 'default', align = 'left', curveSegments = 4, maxVertices })`
+extrudes glyph outlines. The text lies in the XY plane with its first baseline on `y = 0`, reads along +X, faces +Z and is centred
+through its depth. `"\n"` starts a new line 1.2 em lower. `size` is the em height. At most 256 characters and 16 lines.
+
+- The bundled font is DejaVu Sans, printable ASCII only: 94 glyphs, 20 KB of data, about 7 KB gzipped. It loads on demand
+ with the text code and is never in the core, model or mesh entries. A character outside it throws.
+- `registerFont(name, table)` (or `await registerAgentSceneFont(name, table)` from the agent scene entry) adds a font table:
+ `{ unitsPerEm, ascender, descender, glyphs: { "A": [advance, contour...] } }` where a contour is `x, y, onCurve` repeated, in TrueType
+ quadratic points. `scripts/build-font.py` makes a table from a TrueType file with fontTools. A glyph is limited to 128 points, a font
+ to 2048 glyphs and 400000 points. The MCP never takes a font file or URL.
+- `curveSegments` straight pieces per outline curve (1 to 16). Rings inside an odd number of others become holes.
+- One glyph and a word match Blender 5.2 with the same font in volume, area and bounds to 2e-5. Blender's text size unit is not the em,
+ so the golden script calibrates it on the capital I. There is no kerning, bevel or text on a curve.
+
## Resource and precision limits
Each generator accepts at most 4096 input points. Extrusion applies that limit across its contour and holes.
diff --git a/docs/parity.md b/docs/parity.md
index 394ee19c..8943e819 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -33,7 +33,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| User Interface | out of scope | Interface for a person with a mouse. Agents use MCP tools. | | |
| Editors | out of scope | Interface for a person with a mouse. Agents use MCP tools, and people review images. | | |
| Scenes & Objects > Scenes | partial | One recipe holds one scene with its camera and environment. There are no scene units or linked scenes. | | |
-| Scenes & Objects > Objects > Object Types | partial | Mesh nodes and empty nodes exist. Lights are environment settings, and curves and text do not exist as objects. | | #45 |
+| Scenes & Objects > Objects > Object Types | partial | Mesh nodes and empty nodes exist, and `curve` and `text` geometry make curve-like and text objects as meshes. Lights are environment settings. Metaballs and NURBS surfaces are out of scope. | [curve-text](../tests/curve-text.test.js), [Blender comparison](../tests/blender-curve-text.test.js) | #45 |
| Scenes & Objects > Objects > Object Origin | partial | Code has pivots in the scene graph. Recipes have no pivot field. | | |
| Scenes & Objects > Objects > Selecting | out of scope | Selection by mouse. Tools address nodes by ID. | | |
| Scenes & Objects > Objects > Editing | partial | Agents add, change and remove nodes in atomic batches. There is no duplicate, join or separate. | | |
@@ -49,11 +49,11 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Meshes > UVs | partial | `uv_unwrap` with LSCM, axis charts and shelf packing. Patterns can not use the result yet. | | #50 |
| Modeling > Meshes > Mesh Analysis | partial | `lintMesh` reports topology problems. With `{ geometry: true }` (always on in `mesh_inspect`) it also warns of crossing parts, a solid cutting itself, thin walls, floating parts and near-symmetry, using the BVH within face budgets. Checks are heuristics on parts, not Blender's exact Select Non-Manifold or Intersect checks. | [tests/mesh-lint-geometry.test.js](../tests/mesh-lint-geometry.test.js), [src/mesh-lint-geometry.js](../src/mesh-lint-geometry.js) | #66 |
| Modeling > Meshes > Remeshing | partial | `remesh` rebuilds a closed mesh as an even quad surface on a voxel grid (surface nets over a BVH signed distance). Quad remesh and Instant Meshes style retopology are not here. | [blender golden](../tests/blender-golden.test.js) | #40 |
-| Modeling > Curves | partial | `tube` follows a curve and `extrude` follows a contour. There is no curve object. | | #45 |
+| Modeling > Curves | partial | The `curve` geometry sweeps a cubic Bezier chain with explicit or automatic handles, a round or custom profile, a taper along the length and flat caps. Volume, area and bounds match Blender for an open and a closed curve to 2e-5. There is no NURBS or poly spline, no handle types, no fill for flat curves, no offset or extrude, and no separate taper or bevel object. | [curve-text](../tests/curve-text.test.js), [Blender comparison](../tests/blender-curve-text.test.js) | #45 |
| Modeling > Curves (New) | missing | No hair curves. | | #63 |
| Modeling > Surfaces | out of scope | Issue #45 records NURBS surfaces as out of scope unless demand appears. | | |
| Modeling > Metaball | out of scope | Issue #45 records metaballs as out of scope unless demand appears. | | |
-| Modeling > Text | missing | No text objects. | | #45 |
+| Modeling > Text | partial | The `text` geometry extrudes outlines of the bundled DejaVu Sans (printable ASCII, 20 KB loaded on demand) or of a font table registered in code, with size, depth, alignment, lines and curve resolution. One glyph and a word match Blender 5.2 with the same font to 2e-5 in volume and area. There is no kerning, no bevel, no character styles, no text on a curve, no non-ASCII glyphs in the bundled font, and no font through MCP. | [curve-text](../tests/curve-text.test.js), [Blender comparison](../tests/blender-curve-text.test.js) | #45 |
| Modeling > Point Cloud | missing | No point clouds. | | #43 |
| Modeling > Volumes | missing | Depth-clipped volume fog exists. There are no volume objects. | | #63 |
| Modeling > Empties | done | A node with no geometry acts as an empty parent. | [agent-scene](../tests/agent-scene.test.js) | |
@@ -71,7 +71,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Modifiers > Generate > Bevel Modifier | done | Stack node and edit, with segments, profile and overlap clamp, on edges only. | [mesh-bevel](../tests/mesh-bevel.test.js), [Blender results](../tests/fixtures/blender/golden.json) | |
| Modeling > Modifiers > Generate > Boolean Modifier | partial | Manifold boolean as an edit. It is not a stack node. | [mesh-boolean](../tests/mesh-boolean.test.js), [Blender results](../tests/fixtures/blender/golden.json) | |
| Modeling > Modifiers > Generate > Build Modifier | missing | No equivalent. | | |
-| Modeling > Modifiers > Generate > Curve to Tube Modifier | partial | `tube` is a geometry type. It is not a stack node. | [modeling](../tests/modeling.test.js) | #45 |
+| Modeling > Modifiers > Generate > Curve to Tube Modifier | partial | `tube` and `curve` are geometry types, and `curve` has a taper and custom profile. Neither is a stack node. | [curve-text](../tests/curve-text.test.js), [Blender comparison](../tests/blender-curve-text.test.js) | #45 |
| Modeling > Modifiers > Generate > Decimate Modifier | partial | Collapse mode as `decimate` with a ratio, keeping open boundaries and tag borders; `generateMeshLods`, `generateGeometryLods` and `generateAssetLods` make levels with a measured error. Unsubdivide and planar modes, vertex-group weighting and symmetry are missing. Compared with Blender on 4 shared fixtures by volume, area and Hausdorff distance. | [blender golden](../tests/blender-golden.test.js), [decimate](../tests/mesh-decimate.test.js) | #40 |
| Modeling > Modifiers > Generate > Edge Split Modifier | missing | No equivalent. `smoothAngle` splits normals by angle. | | #42 |
| Modeling > Modifiers > Generate > Mask Modifier | missing | No equivalent. | | |
diff --git a/scripts/blender-golden.py b/scripts/blender-golden.py
index e0fccc77..7fb8d82f 100644
--- a/scripts/blender-golden.py
+++ b/scripts/blender-golden.py
@@ -2,6 +2,7 @@
# Run it when a case changes or Blender moves to a new release:
# blender -b --factory-startup --python scripts/blender-golden.py
import json
+import os
from math import cos, radians, sqrt
from pathlib import Path
@@ -537,6 +538,92 @@ def measure_surface(bm, reference):
}
+def evaluated_measure(curve_object):
+ bpy.context.view_layer.update()
+ evaluated = curve_object.evaluated_get(bpy.context.evaluated_depsgraph_get())
+ bm = bmesh.new()
+ bm.from_mesh(evaluated.to_mesh())
+ evaluated.to_mesh_clear()
+ refresh(bm)
+ triangulated = bm.copy()
+ bmesh.ops.triangulate(triangulated, faces=list(triangulated.faces))
+ measured = measure(triangulated)
+ positions = [vertex.co for vertex in bm.verts]
+ result = {
+ "vertexCount": len(bm.verts),
+ "volume": measured["volume"],
+ "area": measured["area"],
+ "boundsMin": [round(min(position[axis] for position in positions), 5) for axis in range(3)],
+ "boundsMax": [round(max(position[axis] for position in positions), 5) for axis in range(3)],
+ }
+ triangulated.free()
+ bm.free()
+ return result
+
+
+# A Bezier curve with a round bevel: the 67.js radialSegments 4 + 2n sides is Blender's bevel resolution n, and the
+# caps are filled. Handles are absolute positions in both.
+def run_curve_case(case):
+ spec = case["curve"]
+ curve_data = bpy.data.curves.new(case["id"], "CURVE")
+ curve_data.dimensions = "3D"
+ curve_data.resolution_u = spec["resolution"]
+ curve_data.bevel_depth = spec["radius"]
+ curve_data.bevel_resolution = (spec["radialSegments"] - 4) // 2
+ curve_data.fill_mode = "FULL"
+ curve_data.use_fill_caps = True
+ spline = curve_data.splines.new("BEZIER")
+ spline.bezier_points.add(len(spec["points"]) - 1)
+ spline.use_cyclic_u = spec.get("closed", False)
+ spline.resolution_u = spec["resolution"]
+ for bezier_point, knot in zip(spline.bezier_points, spec["points"]):
+ bezier_point.co = knot["position"]
+ bezier_point.handle_left_type = "FREE"
+ bezier_point.handle_right_type = "FREE"
+ bezier_point.handle_left = knot["handleIn"]
+ bezier_point.handle_right = knot["handleOut"]
+ curve_object = bpy.data.objects.new(case["id"], curve_data)
+ bpy.context.scene.collection.objects.link(curve_object)
+ return evaluated_measure(curve_object)
+
+
+# Blender's own default font is not DejaVu Sans, so the text cases load the font 67.js bundles. Get DejaVuSans.ttf with
+# "npm pack dejavu-fonts-ttf" (ttf/DejaVuSans.ttf in the package) and point DEJAVU_SANS_TTF at it.
+def bundled_font():
+ path = os.environ.get("DEJAVU_SANS_TTF")
+ if not path:
+ raise SystemExit("Set DEJAVU_SANS_TTF to the path of DejaVuSans.ttf (version 2.37) to run the text cases.")
+ return bpy.data.fonts.load(path)
+
+
+# Blender's text object extrudes both ways from the baseline plane, so its extrude is half the 67.js depth.
+def text_measure(name, body, size, extrude, curve_segments):
+ font_data = bpy.data.curves.new(name, "FONT")
+ font_data.font = bundled_font()
+ font_data.body = body
+ font_data.size = size
+ font_data.extrude = extrude
+ font_data.resolution_u = curve_segments
+ text_object = bpy.data.objects.new(name, font_data)
+ bpy.context.scene.collection.objects.link(text_object)
+ return evaluated_measure(text_object)
+
+
+# Blender 5.2 draws text smaller than the font's em for the same size. The unit is calibrated on the capital I, whose
+# height in DejaVu Sans is 1493 of 2048 units, so every other measure is compared at the same scale.
+DEJAVU_CAP_HEIGHT_EMS = 1493 / 2048
+
+
+def blender_size_for(size):
+ calibration = text_measure("Calibration", "I", 1.0, 0.1, 4)
+ return size * DEJAVU_CAP_HEIGHT_EMS / calibration["boundsMax"][1]
+
+
+def run_text_case(case):
+ spec = case["text"]
+ return text_measure(case["id"], spec["text"], blender_size_for(spec["size"]), spec["depth"] / 2, spec["curveSegments"])
+
+
def remove_all_objects():
for mesh_object in list(bpy.data.objects):
bpy.data.objects.remove(mesh_object)
@@ -561,7 +648,15 @@ def main():
else:
results[case["id"]] = measure(bm)
bm.free()
- output = {"blenderVersion": bpy.app.version_string, "results": results}
+ curves = {}
+ for case in fixture["curves"]:
+ remove_all_objects()
+ curves[case["id"]] = run_curve_case(case)
+ texts = {}
+ for case in fixture["texts"]:
+ remove_all_objects()
+ texts[case["id"]] = run_text_case(case)
+ output = {"blenderVersion": bpy.app.version_string, "results": results, "curves": curves, "texts": texts}
(FIXTURE_DIRECTORY / "golden.json").write_text(json.dumps(output, indent=1) + "\n", encoding="utf-8")
print(f"Wrote {len(results)} results from Blender {bpy.app.version_string}.")
diff --git a/scripts/build-font.py b/scripts/build-font.py
new file mode 100644
index 00000000..b731faa9
--- /dev/null
+++ b/scripts/build-font.py
@@ -0,0 +1,57 @@
+# Writes src/font-default.js, the outlines of the printable ASCII characters of one TrueType font, as plain integers.
+# uv run --no-project --with fonttools python scripts/build-font.py <font.ttf>
+# The bundled font is DejaVu Sans 2.37 (Bitstream Vera licence, public domain changes; notice in THIRD-PARTY-NOTICES.md).
+import json
+import sys
+from pathlib import Path
+
+from fontTools.ttLib import TTFont
+
+FIRST_CHARACTER = 32
+LAST_CHARACTER = 126
+OUTPUT = Path(__file__).resolve().parent.parent / "src" / "font-default.js"
+
+
+def glyph_record(font, name):
+ glyph = font["glyf"][name]
+ record = [font["hmtx"][name][0]]
+ if glyph.numberOfContours <= 0:
+ return record
+ coordinates, end_points, flags = glyph.getCoordinates(font["glyf"])
+ start = 0
+ for end in end_points:
+ contour = []
+ for index in range(start, end + 1):
+ x, y = coordinates[index]
+ contour.extend([int(x), int(y), flags[index] & 1])
+ # Some fonts keep a one-point contour as an anchor; it has no area.
+ if len(contour) >= 9:
+ record.append(contour)
+ start = end + 1
+ return record
+
+
+def main():
+ font = TTFont(sys.argv[1])
+ cmap = font.getBestCmap()
+ glyphs = {}
+ for code in range(FIRST_CHARACTER, LAST_CHARACTER + 1):
+ glyphs[chr(code)] = glyph_record(font, cmap[code])
+ table = {
+ "name": "DejaVu Sans",
+ "unitsPerEm": font["head"].unitsPerEm,
+ "ascender": font["hhea"].ascent,
+ "descender": font["hhea"].descent,
+ "glyphs": glyphs,
+ }
+ text = json.dumps(table, separators=(",", ":"))
+ header = (
+ "// DejaVu Sans 2.37, printable ASCII outlines, generated by scripts/build-font.py. Copyright (c) 2003 Bitstream, Inc.\n"
+ "// Changes by DejaVu are in the public domain. Licence text: THIRD-PARTY-NOTICES.md.\n"
+ "// Glyph: [advance, contour...]. Contour: x, y, onCurve repeated, in font units (TrueType quadratic points).\n"
+ )
+ OUTPUT.write_text(f"{header}export const DEFAULT_FONT_DATA = JSON.parse({json.dumps(text)});\n", encoding="utf-8")
+ print(f"Wrote {len(text)} bytes for {len(glyphs)} glyphs.")
+
+
+main()
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 0f88cba3..05e615a2 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -202,6 +202,15 @@ const shadow = z.strictObject({
near: bounded(0.001, 1e6).optional(),
far: bounded(0.001, 1e6).optional(),
}).describe('Directional shadow coverage. Backend checks Float32 view/projection consistency.');
+// Curve and text sit in the geometry list only, not in mesh bases or cutters. Value types and limits are checked by the
+// engine and listed in scene_capabilities curveText, because every tool that takes a recipe repeats this schema.
+const looseField = z.unknown().optional();
+function curveAndTextGeometries(id) {
+ return [
+ z.strictObject({ ...id, type: z.literal('curve'), points: z.array(z.unknown()).max(1024), closed: looseField, radius: looseField, taper: looseField, profile: looseField, resolution: looseField, radialSegments: looseField }).describe('Bezier sweep; see scene_capabilities curveText.'),
+ z.strictObject({ ...id, type: z.literal('text'), text: z.string().max(256), size: looseField, depth: looseField, font: looseField, align: looseField, curveSegments: looseField }).describe('3D text; see scene_capabilities curveText.'),
+ ];
+}
function primitiveGeometries(identified) {
const id = identified ? { id: identifier } : {};
return [
@@ -212,6 +221,7 @@ function primitiveGeometries(identified) {
z.strictObject({ ...id, type: z.literal('lathe'), profile: z.array(point2).min(2).max(4096), segments, startAngle: finite.optional(), sweep: finite.optional() }),
z.strictObject({ ...id, type: z.literal('extrude'), contour: ring, holes: z.array(ring).max(128).optional(), depth: finite.optional(), steps: detail(1, 256), bevel: finite.optional(), bevelThickness: finite.optional(), bevelSegments: detail(1, 32) }),
z.strictObject({ ...id, type: z.literal('tube'), path: z.array(vector3).min(2).max(4096), radius: finite.optional(), segments, radialSegments: detail(3, 128), closed: z.boolean().optional() }),
+ ...(identified ? curveAndTextGeometries(id) : []),
];
}
const selectRule = z.record(z.string(), z.unknown()).describe('Face selection rule: {"all":true}, {"tag":"top"}, {"normal":[0,1,0],"maxAngle":10} (degrees), {"inside":{"min":[x,y,z],"max":[x,y,z]}} (face centroids), {"faces":[indices]}, {"and":[rules]}, {"or":[rules]}, {"not":rule}, {"grow":rule,"steps":1}, {"boundary":rule}, {"field":expression} (faces where a field expression is nonzero, evaluated at face centroids). Tags come from the base (top, bottom, side, left, right, front, back) and from earlier edits (<name>.cap, <name>.side, <name>.rim, or a tag op).');
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index 5d5bff60..658392ea 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -36,6 +36,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- Static vertex wrapping uses optional `src/shrinkwrap.js` and the checkout's `docs/shrinkwrap.md`.
- A rigid accessory on a morphing or skinned surface uses optional `src/surface-attachment.js` and `docs/surface-attachment.md`.
- Agent scene recipes use optional `src/agent-scene.js` and `docs/agent-scene.md`. Verify source versus published availability before importing.
+- Signs, labels and piping use recipe geometry `text` (bundled DejaVu Sans, printable ASCII; faces +Z, baseline on y=0, size is the em height) and `curve` (cubic Bezier points with optional absolute handles, `radius`, `taper`, `profile`). Their fields come from `scene_capabilities` `curveText.details`, not the tool schema; the MCP takes no font file or URL. Give a sign a board box a little deeper than the text `depth`, and keep text under about 40 characters at `curveSegments: 4`. See "Curve" and "Text" in the checkout's `docs/modeling.md`.
- Polygon modeling by an agent (extrude, inset, loop cut, bevel, booleans, mirror, array, solidify) uses the recipe `mesh` geometry and the MCP tools `mesh_inspect`, `mesh_edit` and `mesh_stack`. Read [mesh-modeling.md](references/mesh-modeling.md) before the first edit; check that the checkout's `docs/mesh.md` exists, since it is unreleased after npm 0.10.0.
- A surface look in a recipe (wood, planks, bricks, tiles, marble, stone, concrete, metal, rust, fabric) uses the material `pattern` field, which needs no UVs. See "Material patterns" in the checkout's `docs/agent-scene.md`. Your own look (bricks from noise and a ramp, stripes, a pattern that follows `uv_unwrap`) is `pattern: { type: "graph", graph, mapping: "uv" }`: a bounded JSON node graph baked to textures, never shader text; see "Material graphs" there.
- Glass, water, gems, car paint and cloth in a recipe use the material layer fields `transmission` (with `thickness` and `ior`), `clearcoat`, `sheenColor` and `specular`. A transmissive material needs a nonzero `thickness` to bend the view behind it, and does not show blended surfaces. Ranges and limits are in "Material layers" in the checkout's `docs/material-maps.md`.
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 3c316689..53315c55 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -22,6 +22,16 @@ export const MATERIAL_GRAPH_OPERATORS = Object.freeze([
'add', 'sub', 'mul', 'div', 'min', 'max', 'pow', 'abs', 'floor', 'fract', 'sqrt', 'invert', 'clamp', 'smoothstep', 'mix',
]);
export const MATERIAL_GRAPH_LIMITS = Object.freeze({ maxNodes: MAX_FIELD_NODES, maxDepth: MAX_FIELD_DEPTH, maxStops: 8, maxWork: 30_000_000 });
+// Curve and text geometry. A text geometry is bounded by vertices per curve segment: the bundled font stays under
+// 640 per character and a registered font is held to 128 outline points per glyph (2400).
+export const CURVE_TEXT_LIMITS = Object.freeze({
+ maxCurvePoints: 1024, maxProfilePoints: 256, maxTextCharacters: 256, maxTextLines: 16,
+ verticesPerCharacterSegment: 640, verticesPerCustomCharacterSegment: 2400, maxPointsPerGlyph: 128,
+});
+export const CURVE_TEXT_DETAILS = Object.freeze({
+ curve: 'Cubic Bezier sweep. points: [x,y,z] (smooth automatic handles) or {position, handleIn?, handleOut?} with handles as absolute positions (a lone handle is mirrored). radius (0.05), taper: radius factors 0+ spread along the length, e.g. [1,0.2], profile: [[x,y]...] cross-section in radius units (default round, radialSegments 8; sharp corners stay flat shaded), resolution: samples per span (12), closed. Open curves get flat caps.',
+ text: 'Extruded text in the XY plane, first baseline on y=0, reading along +X, facing +Z, centred through depth. text (use \n for lines), size (1, em height), depth (0.2), align left|center|right, curveSegments 1-16 per outline curve (4), font (default DejaVu Sans, printable ASCII; other fonts come from registerAgentSceneFont in code, not MCP).',
+});
export const MATERIAL_MAPPINGS = Object.freeze(['box', 'uv']);
export const MATERIAL_GRAPH_NODES = Object.freeze({
outputs: 'color (linear RGB; a number is grey), roughness, metallic, emission (colour; defaults to 1), height (becomes a normal map).',
@@ -56,7 +66,7 @@ export const RENDER_PASS_DEPTH_RANGE = 100;
export const AGENT_SCENE_CAPABILITIES = Object.freeze({
format: '67js.scene', schemaVersion: 1,
- geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'mesh']),
+ geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'mesh']),
meshEdits: Object.freeze({ operations: Object.freeze(Object.keys(MESH_EDIT_OPERATIONS)), maxEdits: MAX_MESH_EDITS }),
meshStack: Object.freeze({ operations: STACK_OPERATIONS, maxNodes: MAX_STACK_NODES }),
fieldExpressions: Object.freeze({
@@ -74,6 +84,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
materialPatterns: MATERIAL_PATTERN_TYPES, maxMaterialPatterns: MAX_MATERIAL_PATTERNS,
materialMappings: MATERIAL_MAPPINGS,
renderPasses: Object.freeze({ names: RENDER_PASS_NAMES, files: 'render-<pass>.png or frame-N-<pass>.png, raw and unantialiased; opaque and cutout geometry only', depth: `16 bits in red and green over ${RENDER_PASS_DEPTH_RANGE} m`, objectId: '24 bits in RGB; the job result lists the part names' }),
+ curveText: Object.freeze({ ...CURVE_TEXT_LIMITS, details: CURVE_TEXT_DETAILS }),
materialGraph: Object.freeze({ outputs: MATERIAL_GRAPH_OUTPUTS, operators: MATERIAL_GRAPH_OPERATORS, ...MATERIAL_GRAPH_LIMITS, nodes: MATERIAL_GRAPH_NODES }),
fixedResources: false, dynamicTopology: true, checkpoints: true, positiveScaleOnly: true,
authoredLook: true, maxPointLights: 8,
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index 5358c49c..609ade74 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -6,6 +6,7 @@
const MODULE_LOADERS = {
mesh: () => import('./agent-mesh-engine.js'),
modeling: () => import('./modeling.js'),
+ text: () => import('./text-geometry.js'),
motion: () => import('./agent-motion.js'),
physics: () => import('./agent-physics.js'),
patterns: () => import('./material-patterns.js'),
@@ -19,7 +20,8 @@ let physicsLoader = null;
// Each test errs on the side of loading: a false positive costs a chunk, a false negative a clear error.
const MODULE_MARKERS = {
mesh: ['"type":"mesh"', '"instances"'],
- modeling: ['"type":"lathe"', '"type":"extrude"', '"type":"tube"'],
+ modeling: ['"type":"lathe"', '"type":"extrude"', '"type":"tube"', '"type":"curve"'],
+ text: ['"type":"text"'],
motion: ['"motion":{'],
physics: ['"physics":{'],
patterns: ['"pattern"'],
@@ -90,6 +92,12 @@ export function agentSceneModuleLoaded(name) {
return Boolean(loadedModules[name]);
}
+/** Add a font table that recipes can name in a text geometry. Loads the text code first. */
+export async function registerAgentSceneFont(name, fontData) {
+ const module = await loadModule('text');
+ module.registerFont(name, fontData);
+}
+
/** Replace how the Manifold module is imported. Applied when the mesh code loads, if it has not yet. */
export function setManifoldModuleLoader(loader) {
if (typeof loader !== 'function') throw new TypeError('The Manifold loader must be a function returning a module promise.');
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 8bdb0199..79d4392b 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -4,7 +4,7 @@ import { createSceneGraph } from './scene-graph.js';
import { applyProjection } from './camera.js';
import { normalizeAgentLook, environmentPatchWithSetup } from './agent-look.js';
import { agentSceneModule } from './agent-scene-modules.js';
-import { MESH_SMOOTH_ANGLE_DEFAULT, AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, MAX_MATERIAL_PATTERNS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';
+import { MESH_SMOOTH_ANGLE_DEFAULT, CURVE_TEXT_LIMITS, AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, MAX_MATERIAL_PATTERNS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';
import { MATERIAL_LAYER_FIELDS, validateMaterialLayers } from './material-layers.js';
import { recipeDiagnostics } from './agent-diagnostics.js';
import { armatureNodes, bakeRigExport, bindSkins, createSkinStages, normalizeArmatures, publishSkinPoses, restWorldMatrix, rigReport, stageSkinPoses, transformedBounds, withoutArmatureNodes } from './rig.js';
@@ -13,7 +13,7 @@ export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';
export {
needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader,
needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader,
- loadAgentSceneModules, loadAllAgentSceneModules, allAgentSceneModulesLoaded, agentSceneModulesNeeded,
+ loadAgentSceneModules, loadAllAgentSceneModules, registerAgentSceneFont, allAgentSceneModulesLoaded, agentSceneModulesNeeded,
} from './agent-scene-modules.js';
const DEFAULT_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;
@@ -340,6 +340,8 @@ const GEOMETRY_FIELDS = {
lathe: ['profile', 'segments', 'startAngle', 'sweep'],
extrude: ['contour', 'holes', 'depth', 'steps', 'bevel', 'bevelThickness', 'bevelSegments'],
tube: ['path', 'radius', 'segments', 'radialSegments', 'closed'],
+ curve: ['points', 'closed', 'radius', 'taper', 'profile', 'resolution', 'radialSegments'],
+ text: ['text', 'size', 'depth', 'font', 'align', 'curveSegments'],
mesh: ['base', 'edits', 'stack', 'smoothAngle'],
};
@@ -361,7 +363,7 @@ function geometryEstimate(value) {
return input.length;
}
for (const field of GEOMETRY_FIELDS[value.type]) {
- if (value[field] !== undefined && !['profile', 'contour', 'holes', 'path', 'closed', 'base', 'edits', 'stack'].includes(field)) {
+ if (value[field] !== undefined && !['profile', 'contour', 'holes', 'path', 'closed', 'base', 'edits', 'stack', 'points', 'taper', 'text', 'font', 'align'].includes(field)) {
finite(value[field], field);
}
}
@@ -382,6 +384,22 @@ function geometryEstimate(value) {
throw new TypeError('closed must be boolean.');
}
return (detail('segments', 64, 3, 2048) + 1) * (detail('radialSegments', 12, 3, 128) + 1);
+ case 'curve': {
+ const knots = value.points;
+ if (!Array.isArray(knots) || knots.length < 2 || knots.length > CURVE_TEXT_LIMITS.maxCurvePoints) {
+ throw new RangeError('Geometry point count exceeds its limit.');
+ }
+ const sides = value.profile === undefined ? detail('radialSegments', 8, 3, 128) : points(value.profile, 2, 3);
+ const rings = (value.closed ? knots.length : knots.length - 1) * detail('resolution', 12, 1, 64) + 1;
+ return rings * sides * 2 + 2 * (sides + 1);
+ }
+ case 'text': {
+ if (typeof value.text !== 'string') throw new TypeError('text must be a string.');
+ const visible = [...value.text].filter(character => !/\s/.test(character)).length;
+ const isDefaultFont = value.font === undefined || value.font === 'default';
+ const perSegment = isDefaultFont ? CURVE_TEXT_LIMITS.verticesPerCharacterSegment : CURVE_TEXT_LIMITS.verticesPerCustomCharacterSegment;
+ return visible * perSegment * detail('curveSegments', 4, 1, 16);
+ }
case 'extrude': {
const holes = value.holes ?? [];
if (!Array.isArray(holes) || holes.length > 128) {
@@ -441,6 +459,10 @@ function generateGeometry(value, maxVertices) {
return agentSceneModule('modeling').extrude(value.contour, { ...value, maxVertices });
case 'tube':
return agentSceneModule('modeling').tube(value.path, { ...value, maxVertices });
+ case 'curve':
+ return agentSceneModule('modeling').curve(value.points, { ...value, maxVertices });
+ case 'text':
+ return agentSceneModule('text').text(value.text, { ...value, maxVertices });
case 'mesh':
return agentSceneModule('mesh').generateMeshGeometry(() => generateGeometry(value.base, maxVertices), value.edits ?? [], {
maxVertices, smoothAngle: value.smoothAngle ?? MESH_SMOOTH_ANGLE_DEFAULT,
diff --git a/src/font-default.js b/src/font-default.js
new file mode 100644
index 00000000..c52d5cf7
--- /dev/null
+++ b/src/font-default.js
@@ -0,0 +1,4 @@
+// DejaVu Sans 2.37, printable ASCII outlines, generated by scripts/build-font.py. Copyright (c) 2003 Bitstream, Inc.
+// Changes by DejaVu are in the public domain. Licence text: THIRD-PARTY-NOTICES.md.
+// Glyph: [advance, contour...]. Contour: x, y, onCurve repeated, in font units (TrueType quadratic points).
+export const DEFAULT_FONT_DATA = JSON.parse("{\"name\":\"DejaVu Sans\",\"unitsPerEm\":2048,\"ascender\":1901,\"descender\":-483,\"glyphs\":{\" \":[651],\"!\":[821,[309,254,1,512,254,1,512,0,1,309,0,1],[309,1493,1,512,1493,1,512,838,1,492,481,1,330,481,1,309,838,1]],\"\\\"\":[942,[367,1493,1,367,938,1,197,938,1,197,1493,1],[745,1493,1,745,938,1,575,938,1,575,1493,1]],\"#\":[1716,[1047,901,1,756,901,1,672,567,1,965,567,1],[897,1470,1,793,1055,1,1085,1055,1,1190,1470,1,1350,1470,1,1247,1055,1,1559,1055,1,1559,901,1,1208,901,1,1126,567,1,1444,567,1,1444,414,1,1087,414,1,983,0,1,823,0,1,926,414,1,633,414,1,530,0,1,369,0,1,473,414,1,158,414,1,158,567,1,510,567,1,594,901,1,272,901,1,272,1055,1,633,1055,1,735,1470,1]],\"$\":[1303,[692,-301,1,592,-301,1,591,0,1,486,2,0,276,47,0,170,92,1,170,272,1,272,208,0,481,143,0,592,142,1,592,598,1,371,634,0,170,806,0,170,956,1,170,1119,0,388,1307,0,592,1321,1,592,1556,1,692,1556,1,692,1324,1,785,1320,0,959,1289,0,1042,1262,1,1042,1087,1,959,1129,0,784,1175,0,692,1179,1,692,752,1,919,717,0,1133,537,0,1133,381,1,1133,212,0,906,17,0,692,2,1],[592,770,1,592,1180,1,476,1167,0,354,1061,0,354,973,1,354,887,0,467,791,0],[692,578,1,692,145,1,819,162,0,948,272,0,948,362,1,948,450,0,825,554,0]],\"%\":[1946,[1489,657,1,1402,657,0,1303,509,0,1303,377,1,1303,247,0,1402,98,0,1489,98,1,1574,98,0,1673,247,0,1673,377,1,1673,508,0,1574,657,0],[1489,784,1,1647,784,0,1833,564,0,1833,377,1,1833,190,0,1646,-29,0,1489,-29,1,1329,-29,0,1143,190,0,1143,377,1,1143,565,0,1330,784,0],[457,1393,1,371,1393,0,272,1244,0,272,1114,1,272,982,0,370,834,0,457,834,1,544,834,0,643,982,0,643,1114,1,643,1243,0,543,1393,0],[1360,1520,1,1520,1520,1,586,-29,1,426,-29,1],[457,1520,1,615,1520,0,803,1301,0,803,1114,1,803,925,0,616,707,0,457,707,1,298,707,0,113,926,0,113,1114,1,113,1300,0,299,1520,0]],\"&\":[1597,[498,803,1,407,722,0,322,561,0,322,473,1,322,327,0,534,133,0,694,133,1,789,133,0,955,196,0,1028,260,1],[639,915,1,1147,395,1,1206,484,0,1272,687,0,1278,801,1,1464,801,1,1452,669,0,1348,411,0,1255,285,1,1534,0,1,1282,0,1,1139,147,1,1035,58,0,807,-29,0,676,-29,1,435,-29,0,129,246,0,129,461,1,129,589,0,263,814,0,397,913,1,349,976,0,299,1101,0,299,1161,1,299,1323,0,521,1520,0,705,1520,1,788,1520,0,953,1484,0,1038,1448,1,1038,1266,1,951,1313,0,793,1362,0,725,1362,1,620,1362,0,489,1251,0,489,1163,1,489,1112,0,548,1009,0]],\"'\":[563,[367,1493,1,367,938,1,197,938,1,197,1493,1]],\"(\":[799,[635,1554,1,501,1324,0,371,874,0,371,643,1,371,412,0,502,-41,0,635,-270,1,475,-270,1,325,-35,0,176,419,0,176,643,1,176,866,0,324,1318,0,475,1554,1]],\")\":[799,[164,1554,1,324,1554,1,474,1318,0,623,866,0,623,643,1,623,419,0,474,-35,0,324,-270,1,164,-270,1,297,-41,0,428,412,0,428,643,1,428,874,0,297,1324,0]],\"*\":[1024,[963,1247,1,604,1053,1,963,858,1,905,760,1,569,963,1,569,586,1,455,586,1,455,963,1,119,760,1,61,858,1,420,1053,1,61,1247,1,119,1346,1,455,1143,1,455,1520,1,569,1520,1,569,1143,1,905,1346,1]],\"+\":[1716,[942,1284,1,942,727,1,1499,727,1,1499,557,1,942,557,1,942,0,1,774,0,1,774,557,1,217,557,1,217,727,1,774,727,1,774,1284,1]],\",\":[651,[240,254,1,451,254,1,451,82,1,287,-238,1,158,-238,1,240,82,1]],\"-\":[739,[100,643,1,639,643,1,639,479,1,100,479,1]],\".\":[651,[219,254,1,430,254,1,430,0,1,219,0,1]],\"/\":[690,[520,1493,1,690,1493,1,170,-190,1,0,-190,1]],\"0\":[1303,[651,1360,1,495,1360,0,338,1053,0,338,745,1,338,438,0,495,131,0,651,131,1,808,131,0,965,438,0,965,745,1,965,1053,0,808,1360,0],[651,1520,1,902,1520,0,1167,1123,0,1167,745,1,1167,368,0,902,-29,0,651,-29,1,400,-29,0,135,368,0,135,745,1,135,1123,0,400,1520,0]],\"1\":[1303,[254,170,1,584,170,1,584,1309,1,225,1237,1,225,1421,1,582,1493,1,784,1493,1,784,170,1,1114,170,1,1114,0,1,254,0,1]],\"2\":[1303,[393,170,1,1098,170,1,1098,0,1,150,0,1,150,170,1,265,289,0,662,690,0,713,748,1,810,857,0,887,1008,0,887,1081,1,887,1200,0,720,1350,0,586,1350,1,491,1350,0,280,1284,0,160,1217,1,160,1421,1,282,1470,0,494,1520,0,582,1520,1,814,1520,0,1090,1288,0,1090,1094,1,1090,1002,0,1021,837,0,930,725,1,905,696,0,637,419,0]],\"3\":[1303,[831,805,1,976,774,0,1139,578,0,1139,434,1,1139,213,0,835,-29,0,555,-29,1,461,-29,0,262,8,0,156,45,1,156,240,1,240,191,0,440,141,0,549,141,1,739,141,0,938,291,0,938,434,1,938,566,0,753,715,0,588,715,1,414,715,1,414,881,1,596,881,1,745,881,0,903,1000,0,903,1112,1,903,1227,0,740,1350,0,588,1350,1,505,1350,0,315,1314,0,201,1276,1,201,1456,1,316,1488,0,517,1520,0,606,1520,1,836,1520,0,1104,1311,0,1104,1133,1,1104,1009,0,962,838,0]],\"4\":[1303,[774,1317,1,264,520,1,774,520,1],[721,1493,1,975,1493,1,975,520,1,1188,520,1,1188,352,1,975,352,1,975,0,1,774,0,1,774,352,1,100,352,1,100,547,1]],\"5\":[1303,[221,1493,1,1014,1493,1,1014,1323,1,406,1323,1,406,957,1,450,972,0,538,987,0,582,987,1,832,987,0,1124,713,0,1124,479,1,1124,238,0,824,-29,0,551,-29,1,457,-29,0,262,3,0,158,35,1,158,238,1,248,189,0,440,141,0,547,141,1,720,141,0,922,323,0,922,479,1,922,635,0,720,817,0,547,817,1,466,817,0,305,781,0,221,743,1]],\"6\":[1303,[676,827,1,540,827,0,381,641,0,381,479,1,381,318,0,540,131,0,676,131,1,812,131,0,971,318,0,971,479,1,971,641,0,812,827,0],[1077,1460,1,1077,1276,1,1001,1312,0,846,1350,0,770,1350,1,570,1350,0,359,1080,0,344,807,1,403,894,0,581,987,0,688,987,1,913,987,0,1174,714,0,1174,479,1,1174,249,0,902,-29,0,676,-29,1,417,-29,0,143,368,0,143,745,1,143,1099,0,479,1520,0,762,1520,1,838,1520,0,993,1490,0]],\"7\":[1303,[168,1493,1,1128,1493,1,1128,1407,1,586,0,1,375,0,1,885,1323,1,168,1323,1]],\"8\":[1303,[651,709,1,507,709,0,342,555,0,342,420,1,342,285,0,507,131,0,651,131,1,795,131,0,961,286,0,961,420,1,961,555,0,796,709,0],[449,795,1,319,827,0,174,1005,0,174,1133,1,174,1312,0,429,1520,0,651,1520,1,874,1520,0,1128,1312,0,1128,1133,1,1128,1005,0,983,827,0,854,795,1,1000,761,0,1163,563,0,1163,420,1,1163,203,0,898,-29,0,651,-29,1,404,-29,0,139,203,0,139,420,1,139,563,0,303,761,0],[375,1114,1,375,998,0,520,868,0,651,868,1,781,868,0,928,998,0,928,1114,1,928,1230,0,781,1360,0,651,1360,1,520,1360,0,375,1230,0]],\"9\":[1303,[225,31,1,225,215,1,301,179,0,457,141,0,532,141,1,732,141,0,943,410,0,958,684,1,900,598,0,722,506,0,614,506,1,390,506,0,129,777,0,129,1012,1,129,1242,0,401,1520,0,627,1520,1,886,1520,0,1159,1123,0,1159,745,1,1159,392,0,824,-29,0,541,-29,1,465,-29,0,309,1,0],[627,664,1,763,664,0,922,850,0,922,1012,1,922,1173,0,763,1360,0,627,1360,1,491,1360,0,332,1173,0,332,1012,1,332,850,0,491,664,0]],\":\":[690,[240,254,1,451,254,1,451,0,1,240,0,1],[240,1059,1,451,1059,1,451,805,1,240,805,1]],\";\":[690,[240,1059,1,451,1059,1,451,805,1,240,805,1],[240,254,1,451,254,1,451,82,1,287,-238,1,158,-238,1,240,82,1]],\"<\":[1716,[1499,1008,1,467,641,1,1499,276,1,1499,94,1,217,559,1,217,725,1,1499,1190,1]],\"=\":[1716,[217,930,1,1499,930,1,1499,762,1,217,762,1],[217,522,1,1499,522,1,1499,352,1,217,352,1]],\">\":[1716,[217,1008,1,217,1190,1,1499,725,1,1499,559,1,217,94,1,217,276,1,1247,641,1]],\"?\":[1087,[391,254,1,594,254,1,594,0,1,391,0,1],[588,401,1,397,401,1,397,555,1,397,656,0,453,786,0,543,872,1,633,961,1,690,1014,0,741,1108,0,741,1157,1,741,1246,0,610,1356,0,502,1356,1,423,1356,0,244,1286,0,147,1219,1,147,1407,1,241,1464,0,434,1520,0,537,1520,1,721,1520,0,944,1326,0,944,1167,1,944,1091,0,872,954,0,782,868,1,694,782,1,647,735,0,608,682,0,600,657,1,594,636,0,588,576,0,588,524,1]],\"@\":[2048,[762,537,1,762,394,0,904,231,0,1028,231,1,1151,231,0,1292,395,0,1292,537,1,1292,677,0,1148,842,0,1026,842,1,905,842,0,762,678,0],[1307,238,1,1247,161,0,1092,88,0,989,88,1,817,88,0,602,337,0,602,537,1,602,737,0,818,987,0,989,987,1,1092,987,0,1248,912,0,1307,836,1,1307,967,1,1450,967,1,1450,231,1,1596,253,0,1761,476,0,1761,653,1,1761,760,0,1698,948,0,1634,1028,1,1530,1159,0,1231,1298,0,1055,1298,1,932,1298,0,706,1233,0,610,1169,1,453,1067,0,276,736,0,276,543,1,276,384,0,391,106,0,500,0,1,605,-104,0,881,-213,0,1038,-213,1,1167,-213,0,1416,-126,0,1520,-45,1,1610,-156,1,1485,-253,0,1190,-356,0,1038,-356,1,853,-356,0,525,-225,0,397,-100,1,269,25,0,135,354,0,135,543,1,135,725,0,271,1055,0,397,1180,1,526,1307,0,864,1442,0,1053,1442,1,1265,1442,0,1628,1268,0,1751,1108,1,1826,1010,0,1905,780,0,1905,657,1,1905,394,0,1587,90,0,1307,84,1]],\"A\":[1401,[700,1294,1,426,551,1,975,551,1],[586,1493,1,815,1493,1,1384,0,1,1174,0,1,1038,383,1,365,383,1,229,0,1,16,0,1]],\"B\":[1405,[403,713,1,403,166,1,727,166,1,890,166,0,1047,301,0,1047,440,1,1047,580,0,890,713,0,727,713,1],[403,1327,1,403,877,1,702,877,1,850,877,0,995,988,0,995,1102,1,995,1215,0,850,1327,0,702,1327,1],[201,1493,1,717,1493,1,948,1493,0,1198,1301,0,1198,1124,1,1198,987,0,1070,825,0,946,805,1,1095,773,0,1260,570,0,1260,418,1,1260,218,0,988,0,0,737,0,1,201,0,1]],\"C\":[1430,[1319,1378,1,1319,1165,1,1217,1260,0,986,1354,0,856,1354,1,600,1354,0,328,1041,0,328,745,1,328,450,0,600,137,0,856,137,1,986,137,0,1217,231,0,1319,326,1,1319,115,1,1213,43,0,976,-29,0,844,-29,1,505,-29,0,115,386,0,115,745,1,115,1105,0,505,1520,0,844,1520,1,978,1520,0,1215,1449,0]],\"D\":[1577,[403,1327,1,403,166,1,647,166,1,956,166,0,1243,446,0,1243,748,1,1243,1048,0,956,1327,0,647,1327,1],[201,1493,1,616,1493,1,1050,1493,0,1456,1132,0,1456,748,1,1456,362,0,1048,0,0,616,0,1,201,0,1]],\"E\":[1294,[201,1493,1,1145,1493,1,1145,1323,1,403,1323,1,403,881,1,1114,881,1,1114,711,1,403,711,1,403,170,1,1163,170,1,1163,0,1,201,0,1]],\"F\":[1178,[201,1493,1,1059,1493,1,1059,1323,1,403,1323,1,403,883,1,995,883,1,995,713,1,403,713,1,403,0,1,201,0,1]],\"G\":[1587,[1219,213,1,1219,614,1,889,614,1,889,780,1,1419,780,1,1419,139,1,1302,56,0,1020,-29,0,860,-29,1,510,-29,0,115,380,0,115,745,1,115,1111,0,510,1520,0,860,1520,1,1006,1520,0,1269,1448,0,1380,1378,1,1380,1163,1,1268,1258,0,1016,1354,0,877,1354,1,603,1354,0,328,1048,0,328,745,1,328,443,0,603,137,0,877,137,1,984,137,0,1152,174,0]],\"H\":[1540,[201,1493,1,403,1493,1,403,881,1,1137,881,1,1137,1493,1,1339,1493,1,1339,0,1,1137,0,1,1137,711,1,403,711,1,403,0,1,201,0,1]],\"I\":[604,[201,1493,1,403,1493,1,403,0,1,201,0,1]],\"J\":[604,[201,1493,1,403,1493,1,403,104,1,403,-166,0,198,-410,0,-29,-410,1,-106,-410,1,-106,-240,1,-43,-240,1,91,-240,0,201,-90,0,201,104,1]],\"K\":[1343,[201,1493,1,403,1493,1,403,862,1,1073,1493,1,1333,1493,1,592,797,1,1386,0,1,1120,0,1,403,719,1,403,0,1,201,0,1]],\"L\":[1141,[201,1493,1,403,1493,1,403,170,1,1130,170,1,1130,0,1,201,0,1]],\"M\":[1767,[201,1493,1,502,1493,1,883,477,1,1266,1493,1,1567,1493,1,1567,0,1,1370,0,1,1370,1311,1,985,287,1,782,287,1,397,1311,1,397,0,1,201,0,1]],\"N\":[1532,[201,1493,1,473,1493,1,1135,244,1,1135,1493,1,1331,1493,1,1331,0,1,1059,0,1,397,1249,1,397,0,1,201,0,1]],\"O\":[1612,[807,1356,1,587,1356,0,328,1028,0,328,745,1,328,463,0,587,135,0,807,135,1,1027,135,0,1284,463,0,1284,745,1,1284,1028,0,1027,1356,0],[807,1520,1,1121,1520,0,1497,1099,0,1497,745,1,1497,392,0,1121,-29,0,807,-29,1,492,-29,0,115,391,0,115,745,1,115,1099,0,492,1520,0]],\"P\":[1235,[403,1327,1,403,766,1,657,766,1,798,766,0,952,912,0,952,1047,1,952,1181,0,798,1327,0,657,1327,1],[201,1493,1,657,1493,1,908,1493,0,1165,1266,0,1165,1047,1,1165,826,0,908,600,0,657,600,1,403,600,1,403,0,1,201,0,1]],\"Q\":[1612,[807,1356,1,587,1356,0,328,1028,0,328,745,1,328,463,0,587,135,0,807,135,1,1027,135,0,1284,463,0,1284,745,1,1284,1028,0,1027,1356,0],[1090,27,1,1356,-264,1,1112,-264,1,891,-25,1,858,-27,0,823,-29,0,807,-29,1,492,-29,0,115,392,0,115,745,1,115,1099,0,492,1520,0,807,1520,1,1121,1520,0,1497,1099,0,1497,745,1,1497,485,0,1288,115,0]],\"R\":[1423,[909,700,1,974,678,0,1097,534,0,1159,408,1,1364,0,1,1147,0,1,956,383,1,882,533,0,743,631,0,623,631,1,403,631,1,403,0,1,201,0,1,201,1493,1,657,1493,1,913,1493,0,1165,1279,0,1165,1063,1,1165,922,0,1034,736,0],[403,1327,1,403,797,1,657,797,1,803,797,0,952,932,0,952,1063,1,952,1194,0,803,1327,0,657,1327,1]],\"S\":[1300,[1096,1444,1,1096,1247,1,981,1302,0,777,1356,0,682,1356,1,517,1356,0,338,1228,0,338,1110,1,338,1011,0,457,910,0,623,879,1,745,854,1,971,811,0,1186,594,0,1186,412,1,1186,195,0,895,-29,0,614,-29,1,508,-29,0,269,19,0,141,66,1,141,274,1,264,205,0,500,135,0,614,135,1,787,135,0,975,271,0,975,397,1,975,507,0,840,631,0,686,662,1,563,686,1,337,731,0,135,923,0,135,1094,1,135,1292,0,414,1520,0,659,1520,1,764,1520,0,982,1482,0]],\"T\":[1251,[-6,1493,1,1257,1493,1,1257,1323,1,727,1323,1,727,0,1,524,0,1,524,1323,1,-6,1323,1]],\"U\":[1499,[178,1493,1,381,1493,1,381,586,1,381,346,0,555,135,0,750,135,1,944,135,0,1118,346,0,1118,586,1,1118,1493,1,1321,1493,1,1321,561,1,1321,269,0,1032,-29,0,750,-29,1,467,-29,0,178,269,0,178,561,1]],\"V\":[1401,[586,0,1,16,1493,1,227,1493,1,700,236,1,1174,1493,1,1384,1493,1,815,0,1]],\"W\":[2025,[68,1493,1,272,1493,1,586,231,1,899,1493,1,1126,1493,1,1440,231,1,1753,1493,1,1958,1493,1,1583,0,1,1329,0,1,1014,1296,1,696,0,1,442,0,1]],\"X\":[1403,[129,1493,1,346,1493,1,717,938,1,1090,1493,1,1307,1493,1,827,776,1,1339,0,1,1122,0,1,702,635,1,279,0,1,61,0,1,594,797,1]],\"Y\":[1251,[-4,1493,1,213,1493,1,627,879,1,1038,1493,1,1255,1493,1,727,711,1,727,0,1,524,0,1,524,711,1]],\"Z\":[1403,[115,1493,1,1288,1493,1,1288,1339,1,344,170,1,1311,170,1,1311,0,1,92,0,1,92,154,1,1036,1323,1,115,1323,1]],\"[\":[799,[176,1556,1,600,1556,1,600,1413,1,360,1413,1,360,-127,1,600,-127,1,600,-270,1,176,-270,1]],\"\\\\\":[690,[170,1493,1,690,-190,1,520,-190,1,0,1493,1]],\"]\":[799,[623,1556,1,623,-270,1,199,-270,1,199,-127,1,438,-127,1,438,1413,1,199,1413,1,199,1556,1]],\"^\":[1716,[956,1493,1,1499,936,1,1298,936,1,858,1331,1,418,936,1,217,936,1,760,1493,1]],\"_\":[1024,[1044,-340,1,1044,-483,1,-20,-483,1,-20,-340,1]],\"`\":[1024,[367,1638,1,649,1264,1,496,1264,1,170,1638,1]],\"a\":[1255,[702,563,1,479,563,0,307,461,0,307,338,1,307,240,0,436,125,0,547,125,1,700,125,0,885,342,0,885,522,1,885,563,1],[1069,639,1,1069,0,1,885,0,1,885,170,1,822,68,0,634,-29,0,498,-29,1,326,-29,0,123,164,0,123,326,1,123,515,0,376,707,0,627,707,1,885,707,1,885,725,1,885,852,0,718,991,0,567,991,1,471,991,0,289,945,0,205,899,1,205,1069,1,306,1108,0,496,1147,0,586,1147,1,829,1147,0,1069,895,0]],\"b\":[1300,[997,559,1,997,762,0,830,993,0,684,993,1,538,993,0,371,762,0,371,559,1,371,356,0,538,125,0,684,125,1,830,125,0,997,356,0],[371,950,1,429,1050,0,606,1147,0,729,1147,1,933,1147,0,1188,823,0,1188,559,1,1188,295,0,933,-29,0,729,-29,1,606,-29,0,429,68,0,371,168,1,371,0,1,186,0,1,186,1556,1,371,1556,1]],\"c\":[1126,[999,1077,1,999,905,1,921,948,0,764,991,0,684,991,1,505,991,0,307,764,0,307,559,1,307,354,0,505,127,0,684,127,1,764,127,0,921,170,0,999,213,1,999,43,1,922,7,0,757,-29,0,664,-29,1,411,-29,0,113,289,0,113,559,1,113,833,0,414,1147,0,676,1147,1,761,1147,0,923,1112,0]],\"d\":[1300,[930,950,1,930,1556,1,1114,1556,1,1114,0,1,930,0,1,930,168,1,872,68,0,695,-29,0,571,-29,1,368,-29,0,113,295,0,113,559,1,113,823,0,368,1147,0,571,1147,1,695,1147,0,872,1050,0],[303,559,1,303,356,0,470,125,0,616,125,1,762,125,0,930,356,0,930,559,1,930,762,0,762,993,0,616,993,1,470,993,0,303,762,0]],\"e\":[1260,[1151,606,1,1151,516,1,305,516,1,317,326,0,522,127,0,705,127,1,811,127,0,1010,179,0,1108,231,1,1108,57,1,1009,15,0,801,-29,0,694,-29,1,426,-29,0,113,283,0,113,549,1,113,824,0,410,1147,0,662,1147,1,888,1147,0,1151,856,0],[967,660,1,965,811,0,800,991,0,664,991,1,510,991,0,325,817,0,311,659,1]],\"f\":[721,[760,1556,1,760,1403,1,584,1403,1,485,1403,0,408,1323,0,408,1219,1,408,1120,1,711,1120,1,711,977,1,408,977,1,408,0,1,223,0,1,223,977,1,47,977,1,47,1120,1,223,1120,1,223,1198,1,223,1385,0,397,1556,0,586,1556,1]],\"g\":[1300,[930,573,1,930,773,0,765,993,0,616,993,1,468,993,0,303,773,0,303,573,1,303,374,0,468,154,0,616,154,1,765,154,0,930,374,0],[1114,139,1,1114,-147,0,860,-426,0,598,-426,1,501,-426,0,329,-397,0,248,-367,1,248,-188,1,329,-232,0,487,-274,0,569,-274,1,750,-274,0,930,-85,0,930,106,1,930,197,1,873,98,0,695,0,0,571,0,1,365,0,0,113,314,0,113,573,1,113,833,0,365,1147,0,571,1147,1,695,1147,0,873,1049,0,930,950,1,930,1120,1,1114,1120,1]],\"h\":[1298,[1124,676,1,1124,0,1,940,0,1,940,670,1,940,829,0,816,987,0,692,987,1,543,987,0,371,797,0,371,633,1,371,0,1,186,0,1,186,1556,1,371,1556,1,371,946,1,437,1047,0,616,1147,0,733,1147,1,926,1147,0,1124,908,0]],\"i\":[569,[193,1120,1,377,1120,1,377,0,1,193,0,1],[193,1556,1,377,1556,1,377,1323,1,193,1323,1]],\"j\":[569,[193,1120,1,377,1120,1,377,-20,1,377,-234,0,214,-426,0,33,-426,1,-37,-426,1,-37,-270,1,12,-270,1,117,-270,0,193,-173,0,193,-20,1],[193,1556,1,377,1556,1,377,1323,1,193,1323,1]],\"k\":[1186,[186,1556,1,371,1556,1,371,637,1,920,1120,1,1155,1120,1,561,596,1,1180,0,1,940,0,1,371,547,1,371,0,1,186,0,1]],\"l\":[569,[193,1556,1,377,1556,1,377,0,1,193,0,1]],\"m\":[1995,[1065,905,1,1134,1029,0,1326,1147,0,1456,1147,1,1631,1147,0,1821,902,0,1821,676,1,1821,0,1,1636,0,1,1636,670,1,1636,831,0,1522,987,0,1405,987,1,1262,987,0,1096,797,0,1096,633,1,1096,0,1,911,0,1,911,670,1,911,832,0,797,987,0,678,987,1,537,987,0,371,796,0,371,633,1,371,0,1,186,0,1,186,1120,1,371,1120,1,371,946,1,434,1049,0,610,1147,0,731,1147,1,853,1147,0,1024,1023,0]],\"n\":[1298,[1124,676,1,1124,0,1,940,0,1,940,670,1,940,829,0,816,987,0,692,987,1,543,987,0,371,797,0,371,633,1,371,0,1,186,0,1,186,1120,1,371,1120,1,371,946,1,437,1047,0,616,1147,0,733,1147,1,926,1147,0,1124,908,0]],\"o\":[1253,[627,991,1,479,991,0,307,760,0,307,559,1,307,358,0,478,127,0,627,127,1,774,127,0,946,359,0,946,559,1,946,758,0,774,991,0],[627,1147,1,867,1147,0,1141,835,0,1141,559,1,1141,284,0,867,-29,0,627,-29,1,386,-29,0,113,284,0,113,559,1,113,835,0,386,1147,0]],\"p\":[1300,[371,168,1,371,-426,1,186,-426,1,186,1120,1,371,1120,1,371,950,1,429,1050,0,606,1147,0,729,1147,1,933,1147,0,1188,823,0,1188,559,1,1188,295,0,933,-29,0,729,-29,1,606,-29,0,429,68,0],[997,559,1,997,762,0,830,993,0,684,993,1,538,993,0,371,762,0,371,559,1,371,356,0,538,125,0,684,125,1,830,125,0,997,356,0]],\"q\":[1300,[303,559,1,303,356,0,470,125,0,616,125,1,762,125,0,930,356,0,930,559,1,930,762,0,762,993,0,616,993,1,470,993,0,303,762,0],[930,168,1,872,68,0,695,-29,0,571,-29,1,368,-29,0,113,295,0,113,559,1,113,823,0,368,1147,0,571,1147,1,695,1147,0,872,1050,0,930,950,1,930,1120,1,1114,1120,1,1114,-426,1,930,-426,1]],\"r\":[842,[842,948,1,811,966,0,738,983,0,694,983,1,538,983,0,371,780,0,371,590,1,371,0,1,186,0,1,186,1120,1,371,1120,1,371,946,1,429,1048,0,615,1147,0,748,1147,1,767,1147,0,813,1142,0,841,1137,1]],\"s\":[1067,[907,1087,1,907,913,1,829,953,0,661,993,0,571,993,1,434,993,0,297,909,0,297,825,1,297,761,0,395,688,0,543,655,1,606,641,1,802,599,0,967,446,0,967,309,1,967,153,0,720,-29,0,504,-29,1,414,-29,0,219,6,0,111,41,1,111,231,1,213,178,0,411,125,0,508,125,1,638,125,0,778,214,0,778,295,1,778,370,0,677,450,0,506,487,1,442,502,1,271,538,0,119,687,0,119,817,1,119,975,0,343,1147,0,549,1147,1,651,1147,0,831,1117,0]],\"t\":[803,[375,1438,1,375,1120,1,754,1120,1,754,977,1,375,977,1,375,369,1,375,232,0,450,154,0,565,154,1,754,154,1,754,0,1,565,0,1,352,0,0,190,159,0,190,369,1,190,977,1,55,977,1,55,1120,1,190,1120,1,190,1438,1]],\"u\":[1298,[174,442,1,174,1120,1,358,1120,1,358,449,1,358,290,0,482,131,0,606,131,1,755,131,0,928,321,0,928,485,1,928,1120,1,1112,1120,1,1112,0,1,928,0,1,928,172,1,861,70,0,684,-29,0,567,-29,1,374,-29,0,174,211,0]],\"v\":[1212,[61,1120,1,256,1120,1,606,180,1,956,1120,1,1151,1120,1,731,0,1,481,0,1]],\"w\":[1675,[86,1120,1,270,1120,1,500,246,1,729,1120,1,946,1120,1,1176,246,1,1405,1120,1,1589,1120,1,1296,0,1,1079,0,1,838,918,1,596,0,1,379,0,1]],\"x\":[1212,[1124,1120,1,719,575,1,1145,0,1,928,0,1,602,440,1,276,0,1,59,0,1,494,586,1,96,1120,1,313,1120,1,610,721,1,907,1120,1]],\"y\":[1212,[659,-104,1,581,-304,0,433,-426,0,309,-426,1,162,-426,1,162,-272,1,270,-272,1,346,-272,0,430,-200,0,481,-66,1,514,18,1,61,1120,1,256,1120,1,606,244,1,956,1120,1,1151,1120,1]],\"z\":[1075,[113,1120,1,987,1120,1,987,952,1,295,147,1,987,147,1,987,0,1,88,0,1,88,168,1,780,973,1,113,973,1]],\"{\":[1303,[1047,-190,1,1047,-334,1,985,-334,1,736,-334,0,567,-186,0,567,35,1,567,274,1,567,425,0,459,541,0,317,541,1,256,541,1,256,684,1,317,684,1,460,684,0,567,799,0,567,948,1,567,1188,1,567,1409,0,736,1556,0,985,1556,1,1047,1556,1,1047,1413,1,979,1413,1,838,1413,0,752,1325,0,752,1184,1,752,936,1,752,779,0,661,637,0,551,612,1,662,585,0,752,443,0,752,287,1,752,39,1,752,-102,0,838,-190,0,979,-190,1]],\"|\":[690,[430,1565,1,430,-483,1,260,-483,1,260,1565,1]],\"}\":[1303,[256,-190,1,326,-190,1,466,-190,0,551,-104,0,551,39,1,551,287,1,551,443,0,641,585,0,752,612,1,641,637,0,551,779,0,551,936,1,551,1184,1,551,1326,0,466,1413,0,326,1413,1,256,1413,1,256,1556,1,319,1556,1,568,1556,0,735,1409,0,735,1188,1,735,948,1,735,799,0,843,684,0,985,684,1,1047,684,1,1047,541,1,985,541,1,843,541,0,735,425,0,735,274,1,735,35,1,735,-186,0,568,-334,0,319,-334,1,256,-334,1]],\"~\":[1716,[1499,817,1,1499,639,1,1394,560,0,1215,492,0,1118,492,1,1008,492,0,862,551,1,851,555,0,846,557,1,839,560,0,824,565,1,669,627,0,575,627,1,487,627,0,315,550,0,217,467,1,217,645,1,322,724,0,501,793,0,598,793,1,708,793,0,855,733,1,865,729,0,870,727,1,878,724,0,892,719,1,1047,657,0,1141,657,1,1227,657,0,1396,733,0]]}}");
diff --git a/src/modeling-bezier.js b/src/modeling-bezier.js
new file mode 100644
index 00000000..f5f2849d
--- /dev/null
+++ b/src/modeling-bezier.js
@@ -0,0 +1,233 @@
+// Bezier curve sweep: a chain of cubic Bezier spans with explicit or automatic handles, swept with a round or custom
+// profile that can taper along the curve. The ring frames use the minimum-twist transport of the tube generator.
+import { transportFrames } from './modeling-curve.js';
+
+const SMOOTH_NORMAL_COSINE = Math.cos(40 * Math.PI / 180);
+const ZERO_LENGTH = 1e-12;
+
+function add(first, second) {
+ return [first[0] + second[0], first[1] + second[1], first[2] + second[2]];
+}
+
+function subtract(first, second) {
+ return [first[0] - second[0], first[1] - second[1], first[2] - second[2]];
+}
+
+function scale(vector, factor) {
+ return [vector[0] * factor, vector[1] * factor, vector[2] * factor];
+}
+
+function lengthOf(vector) {
+ return Math.hypot(vector[0], vector[1], vector[2]);
+}
+
+/** Fills every missing handle: a lone handle is mirrored, a knot with none gets a smooth handle along its neighbours. */
+export function resolveHandles(knots, closed) {
+ const count = knots.length;
+ return knots.map((knot, index) => {
+ const previous = knots[closed ? (index + count - 1) % count : Math.max(index - 1, 0)].position;
+ const next = knots[closed ? (index + 1) % count : Math.min(index + 1, count - 1)].position;
+ const interior = closed || (index > 0 && index < count - 1);
+ const direction = interior ? scale(subtract(next, previous), 1 / 6) : null;
+ let handleOut = knot.handleOut;
+ let handleIn = knot.handleIn;
+ if (!handleOut && handleIn) handleOut = subtract(scale(knot.position, 2), handleIn);
+ if (!handleIn && handleOut) handleIn = subtract(scale(knot.position, 2), handleOut);
+ if (!handleOut) {
+ handleOut = direction ? add(knot.position, direction) : add(knot.position, scale(subtract(next, knot.position), 1 / 3));
+ handleIn = direction ? subtract(knot.position, direction) : add(knot.position, scale(subtract(previous, knot.position), 1 / 3));
+ }
+ return { position: knot.position, handleIn, handleOut };
+ });
+}
+
+function cubicPoint(start, controlStart, controlEnd, end, parameter) {
+ const remainder = 1 - parameter;
+ const weights = [remainder ** 3, 3 * remainder * remainder * parameter, 3 * remainder * parameter * parameter, parameter ** 3];
+ return [0, 1, 2].map(axis => weights[0] * start[axis] + weights[1] * controlStart[axis] + weights[2] * controlEnd[axis] + weights[3] * end[axis]);
+}
+
+function cubicDerivative(start, controlStart, controlEnd, end, parameter) {
+ const remainder = 1 - parameter;
+ return [0, 1, 2].map(axis => 3 * (
+ remainder * remainder * (controlStart[axis] - start[axis]) +
+ 2 * remainder * parameter * (controlEnd[axis] - controlStart[axis]) +
+ parameter * parameter * (end[axis] - controlEnd[axis])
+ ));
+}
+
+/** Points and unit tangents along the spans, `resolution` per span. A closed curve does not repeat its first sample. */
+export function sampleBezierSpans(handles, closed, resolution) {
+ const spans = closed ? handles.length : handles.length - 1;
+ const points = [];
+ const tangents = [];
+ for (let span = 0; span < spans; span++) {
+ const from = handles[span];
+ const to = handles[(span + 1) % handles.length];
+ for (let step = 0; step < resolution; step++) {
+ const parameter = step / resolution;
+ points.push(cubicPoint(from.position, from.handleOut, to.handleIn, to.position, parameter));
+ tangents.push(cubicDerivative(from.position, from.handleOut, to.handleIn, to.position, parameter));
+ }
+ }
+ if (!closed) {
+ const from = handles.at(-2);
+ const to = handles.at(-1);
+ points.push(to.position);
+ tangents.push(cubicDerivative(from.position, from.handleOut, to.handleIn, to.position, 1));
+ }
+ return { points, tangents: fillZeroTangents(points, tangents, closed) };
+}
+
+// A handle that sits on its knot makes the derivative zero there; the chord to a neighbour stands in.
+function fillZeroTangents(points, tangents, closed) {
+ const count = points.length;
+ const unit = tangents.map(tangent => {
+ const length = lengthOf(tangent);
+ return length > ZERO_LENGTH ? scale(tangent, 1 / length) : null;
+ });
+ return unit.map((tangent, index) => {
+ if (tangent) return tangent;
+ for (let offset = 1; offset < count; offset++) {
+ const neighbour = closed ? (index + offset) % count : index + offset;
+ if (neighbour >= count) break;
+ const chord = subtract(points[neighbour], points[index]);
+ const length = lengthOf(chord);
+ if (length > ZERO_LENGTH) return scale(chord, 1 / length);
+ }
+ throw new RangeError('The curve has no length. Move its points apart.');
+ });
+}
+
+function circleProfile(sides) {
+ return Array.from({ length: sides }, (_, side) => {
+ const angle = side / sides * Math.PI * 2;
+ return [-Math.cos(angle), Math.sin(angle)];
+ });
+}
+
+function signedArea(profile) {
+ let area = 0;
+ for (let index = 0; index < profile.length; index++) {
+ const next = profile[(index + 1) % profile.length];
+ area += profile[index][0] * next[1] - next[0] * profile[index][1];
+ }
+ return area;
+}
+
+/** Profile points counter-clockwise, with the flat normal of each edge and a smoothed normal at each corner. */
+function profileEdges(profile) {
+ const ordered = signedArea(profile) < 0 ? [...profile].reverse() : profile;
+ const edgeNormals = ordered.map((point, index) => {
+ const next = ordered[(index + 1) % ordered.length];
+ const dx = next[0] - point[0];
+ const dy = next[1] - point[1];
+ const length = Math.hypot(dx, dy);
+ if (length === 0) throw new RangeError('The profile cannot repeat a point.');
+ return [dy / length, -dx / length];
+ });
+ const cornerNormal = (before, after) => {
+ const cosine = before[0] * after[0] + before[1] * after[1];
+ if (cosine < SMOOTH_NORMAL_COSINE) return null;
+ const sum = [before[0] + after[0], before[1] + after[1]];
+ const length = Math.hypot(sum[0], sum[1]);
+ return [sum[0] / length, sum[1] / length];
+ };
+ return ordered.map((point, index) => {
+ const next = (index + 1) % ordered.length;
+ const before = edgeNormals[(index + ordered.length - 1) % ordered.length];
+ const after = edgeNormals[index];
+ const following = edgeNormals[next];
+ return {
+ start: ordered[index],
+ end: ordered[next],
+ startNormal: cornerNormal(before, after) ?? after,
+ endNormal: cornerNormal(after, following) ?? after,
+ };
+ });
+}
+
+function taperAt(taper, fraction) {
+ if (!taper) return 1;
+ const position = fraction * (taper.length - 1);
+ const lower = Math.min(Math.floor(position), taper.length - 2);
+ const weight = position - lower;
+ return taper[lower] * (1 - weight) + taper[lower + 1] * weight;
+}
+
+/**
+ * Sweeps the profile along the sampled curve. `profile` is a list of 2D points, or null for a round profile of
+ * `radialSegments` sides. Open curves get flat caps.
+ */
+export function buildBezierSweep({ handles, closed, radius, taper, profile, resolution, radialSegments }) {
+ const { points, tangents } = sampleBezierSpans(handles, closed, resolution);
+ const count = points.length;
+ const frames = transportFrames(closed ? [...tangents, tangents[0]] : tangents, closed);
+ const distances = [0];
+ for (let index = 1; index < count; index++) distances.push(distances[index - 1] + lengthOf(subtract(points[index], points[index - 1])));
+ const totalLength = closed ? distances[count - 1] + lengthOf(subtract(points[0], points[count - 1])) : distances[count - 1];
+ const edges = profileEdges(profile ?? circleProfile(radialSegments));
+ const positions = [];
+ const normals = [];
+ const uvs = [];
+ const indices = [];
+ const ringCount = closed ? count + 1 : count;
+ const verticesPerRing = edges.length * 2;
+ for (let ring = 0; ring < ringCount; ring++) {
+ const source = ring % count;
+ const { normal, binormal } = frames[source];
+ const fraction = totalLength > 0 ? distances[source] / totalLength : 0;
+ const along = ring === count ? 1 : fraction;
+ const size = radius * taperAt(taper, fraction);
+ const place = (planar, planarNormal, edgeFraction) => {
+ for (let axis = 0; axis < 3; axis++) {
+ positions.push(points[source][axis] + size * (planar[0] * normal[axis] + planar[1] * binormal[axis]));
+ normals.push(planarNormal[0] * normal[axis] + planarNormal[1] * binormal[axis]);
+ }
+ uvs.push(along, edgeFraction);
+ };
+ edges.forEach((edge, index) => {
+ place(edge.start, edge.startNormal, index / edges.length);
+ place(edge.end, edge.endNormal, (index + 1) / edges.length);
+ });
+ }
+ for (let ring = 1; ring < ringCount; ring++) {
+ for (let edge = 0; edge < edges.length; edge++) {
+ const a = (ring - 1) * verticesPerRing + edge * 2;
+ const b = ring * verticesPerRing + edge * 2;
+ indices.push(a, a + 1, b, b, a + 1, b + 1);
+ }
+ }
+ if (!closed) {
+ addCap(positions, normals, uvs, indices, { ring: 0, tangent: scale(tangents[0], -1), flip: true, ...capContext(edges, frames, points, radius, taper, 0) });
+ addCap(positions, normals, uvs, indices, { ring: count - 1, tangent: tangents[count - 1], flip: false, ...capContext(edges, frames, points, radius, taper, 1) });
+ }
+ return { positions: Float32Array.from(positions), normals: Float32Array.from(normals), uvs: Float32Array.from(uvs), indices: Uint32Array.from(indices) };
+}
+
+function capContext(edges, frames, points, radius, taper, fraction) {
+ const index = fraction === 0 ? 0 : points.length - 1;
+ return { edges, frame: frames[index], center: points[index], size: radius * taperAt(taper, fraction) };
+}
+
+// A fan from the profile centre, with its own vertices so the cap edge stays sharp.
+function addCap(positions, normals, uvs, indices, { tangent, flip, edges, frame, center, size }) {
+ const first = positions.length / 3;
+ const average = edges.reduce((sum, edge) => [sum[0] + edge.start[0], sum[1] + edge.start[1]], [0, 0]).map(value => value / edges.length);
+ const extent = Math.max(...edges.map(edge => Math.hypot(edge.start[0], edge.start[1]))) || 1;
+ const place = planar => {
+ for (let axis = 0; axis < 3; axis++) {
+ positions.push(center[axis] + size * (planar[0] * frame.normal[axis] + planar[1] * frame.binormal[axis]));
+ normals.push(tangent[axis]);
+ }
+ uvs.push(0.5 + planar[0] * 0.5 / extent, 0.5 + planar[1] * 0.5 / extent);
+ };
+ place(average);
+ edges.forEach(edge => place(edge.start));
+ for (let index = 0; index < edges.length; index++) {
+ const current = first + 1 + index;
+ const next = first + 1 + (index + 1) % edges.length;
+ if (flip) indices.push(first, next, current);
+ else indices.push(first, current, next);
+ }
+}
diff --git a/src/modeling-curve.js b/src/modeling-curve.js
index 7a6700b4..f2b577cc 100644
--- a/src/modeling-curve.js
+++ b/src/modeling-curve.js
@@ -139,7 +139,8 @@ function initialNormal(tangent) {
return crossProduct(tangent, normalize(crossProduct(tangent, reference)));
}
-function frames(tangents, closed) {
+/** Minimum-twist frames for unit tangents, one per tangent; a closed curve repeats its first tangent at the end and spreads the leftover twist. */
+export function transportFrames(tangents, closed) {
const segments = tangents.length - 1;
const normals = [initialNormal(tangents[0])];
for (let index = 1; index <= segments; index++) {
@@ -166,7 +167,7 @@ function frames(tangents, closed) {
export function sampleTubePath(points, closed, steps) {
const curve = createCurve(points, closed);
const tangents = Array.from({ length: steps + 1 }, (_, index) => curve.tangentAt(index / steps));
- const sampleFrames = frames(tangents, closed);
+ const sampleFrames = transportFrames(tangents, closed);
return sampleFrames.map((_, index) => {
const source = closed && index === steps ? 0 : index;
return { point: curve.pointAtFraction(source / steps), ...sampleFrames[source] };
diff --git a/src/modeling.js b/src/modeling.js
index 51165220..735ef578 100644
--- a/src/modeling.js
+++ b/src/modeling.js
@@ -1,4 +1,5 @@
import { buildLathe, buildExtrusion, buildTube } from './modeling-shapes.js';
+import { buildBezierSweep, resolveHandles } from './modeling-bezier.js';
const MAX_INPUT_POINTS = 4096;
const DEFAULT_VERTEX_LIMIT = 250_000;
@@ -25,6 +26,34 @@ function pointsFrom(input, size, minimum, name) {
return points;
}
+function vectorFrom(input, name) {
+ if (!Array.isArray(input) || input.length !== 3) throw new TypeError(`${name} needs three components.`);
+ return input.map(value => finite(value, name));
+}
+
+function knotFrom(input, index) {
+ if (Array.isArray(input)) return { position: vectorFrom(input, 'point') };
+ if (!input || typeof input !== 'object') throw new TypeError(`Curve point ${index} must be [x, y, z] or an object with position.`);
+ for (const key of Object.keys(input)) {
+ if (!['position', 'handleIn', 'handleOut'].includes(key)) throw new TypeError(`Unknown curve point field: ${key}.`);
+ }
+ return {
+ position: vectorFrom(input.position, 'position'),
+ ...(input.handleIn === undefined ? {} : { handleIn: vectorFrom(input.handleIn, 'handleIn') }),
+ ...(input.handleOut === undefined ? {} : { handleOut: vectorFrom(input.handleOut, 'handleOut') }),
+ };
+}
+
+function taperFrom(taper) {
+ if (taper === undefined) return null;
+ if (!Array.isArray(taper) || taper.length < 2 || taper.length > 64) throw new RangeError('taper needs 2 to 64 radius factors.');
+ return taper.map(factor => {
+ finite(factor, 'taper');
+ if (factor < 0) throw new RangeError('taper factors cannot be negative.');
+ return factor;
+ });
+}
+
function checkBudget(vertices, maximum) {
integer(maximum, 3, 1_000_000, 'maxVertices');
if (vertices > maximum) throw new RangeError(`Modeling requires up to ${vertices} vertices, exceeding maxVertices ${maximum}. Reduce detail.`);
@@ -241,6 +270,31 @@ export function extrude(contour, {
return closeTJunctions(meshFrom(buildExtrusion(outer, inner, { depth, steps, bevel, bevelThickness, bevelSegments }), maxVertices));
}
+/**
+ * Sweep a round or custom profile along a cubic Bezier curve. Points are [x, y, z] (smooth automatic handles) or
+ * { position, handleIn, handleOut } with absolute handle positions; `taper` lists radius factors spread along the length.
+ */
+export function curve(points, {
+ closed = false, radius = 0.05, taper, profile, resolution = 12, radialSegments = 8,
+ maxVertices = DEFAULT_VERTEX_LIMIT,
+} = {}) {
+ radius = finite(radius, 'radius');
+ if (radius <= 0 || typeof closed !== 'boolean') throw new RangeError('radius must be positive and closed must be boolean.');
+ integer(resolution, 1, 64, 'resolution');
+ integer(radialSegments, 3, 128, 'radialSegments');
+ if (!Array.isArray(points) || points.length < (closed ? 3 : 2) || points.length > 1024) {
+ throw new RangeError(`points needs ${closed ? 3 : 2} to 1024 entries.`);
+ }
+ const knots = points.map(knotFrom);
+ const profilePoints = profile === undefined ? null : pointsFrom(profile, 2, 3, 'profile');
+ if (profilePoints && profilePoints.length > 256) throw new RangeError('profile needs 3 to 256 points.');
+ const sides = profilePoints ? profilePoints.length : radialSegments;
+ const rings = (closed ? knots.length : knots.length - 1) * resolution + 1;
+ checkBudget(rings * sides * 2 + (closed ? 0 : 2 * (sides + 1)), maxVertices);
+ const handles = resolveHandles(knots, closed);
+ return meshFrom(buildBezierSweep({ handles, closed, radius, taper: taperFrom(taper), profile: profilePoints, resolution, radialSegments }), maxVertices);
+}
+
/** Sweep a circular tube along a centripetal Catmull-Rom curve. */
export function tube(path, {
radius = 0.1, segments = 64, radialSegments = 12, closed = false,
diff --git a/src/text-geometry.js b/src/text-geometry.js
new file mode 100644
index 00000000..2c027056
--- /dev/null
+++ b/src/text-geometry.js
@@ -0,0 +1,222 @@
+// 3D text: glyph outlines from a font table, flattened to polygons and extruded. The default font is DejaVu Sans
+// (printable ASCII only). This module loads on demand because its font data is the heaviest part of the engine.
+import { extrude } from './modeling.js';
+import { DEFAULT_FONT_DATA } from './font-default.js';
+import { CURVE_TEXT_LIMITS } from './agent-scene-capabilities.js';
+
+const DEFAULT_FONT_NAME = 'default';
+const MAX_TEXT_CHARACTERS = CURVE_TEXT_LIMITS.maxTextCharacters;
+const MAX_TEXT_LINES = CURVE_TEXT_LIMITS.maxTextLines;
+const MAX_GLYPHS_PER_FONT = 2048;
+const MAX_POINTS_PER_CONTOUR = 2048;
+const MAX_POINTS_PER_FONT = 400_000;
+const LINE_HEIGHT_EMS = 1.2;
+const ALIGNMENTS = ['left', 'center', 'right'];
+
+const fonts = new Map();
+
+function checkNumber(value, name) {
+ if (!Number.isFinite(value)) throw new TypeError(`${name} must be a finite number.`);
+}
+
+function validateGlyph(character, record) {
+ if (!Array.isArray(record) || record.length < 1 || record.length > 65) throw new TypeError(`Glyph ${JSON.stringify(character)} must be [advance, contour...] with up to 64 contours.`);
+ checkNumber(record[0], 'advance');
+ let points = 0;
+ for (const contour of record.slice(1)) {
+ if (!Array.isArray(contour) || contour.length % 3 !== 0 || contour.length < 9 || contour.length > MAX_POINTS_PER_CONTOUR * 3) {
+ throw new RangeError(`A contour of ${JSON.stringify(character)} needs 3 to ${MAX_POINTS_PER_CONTOUR} points as x, y, onCurve.`);
+ }
+ contour.forEach((value, index) => {
+ checkNumber(value, 'contour value');
+ if (index % 3 === 2 && value !== 0 && value !== 1) throw new TypeError('A contour onCurve flag must be 0 or 1.');
+ });
+ points += contour.length / 3;
+ }
+ if (points > CURVE_TEXT_LIMITS.maxPointsPerGlyph) throw new RangeError(`Glyph ${JSON.stringify(character)} has ${points} outline points; the limit is ${CURVE_TEXT_LIMITS.maxPointsPerGlyph}.`);
+ return points;
+}
+
+/** Add a font table (see scripts/build-font.py for how to make one from a TrueType file) under a name recipes can use. */
+export function registerFont(name, data) {
+ if (typeof name !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9 ._-]{0,47}$/.test(name)) throw new TypeError('A font name is 1 to 48 letters, digits, spaces, dots, dashes or underscores.');
+ if (!data || typeof data !== 'object' || !data.glyphs || typeof data.glyphs !== 'object') throw new TypeError('A font table needs unitsPerEm, ascender, descender and glyphs.');
+ if (!Number.isInteger(data.unitsPerEm) || data.unitsPerEm < 16 || data.unitsPerEm > 16384) throw new RangeError('unitsPerEm must be an integer from 16 to 16384.');
+ checkNumber(data.ascender, 'ascender');
+ checkNumber(data.descender, 'descender');
+ const characters = Object.keys(data.glyphs);
+ if (characters.length === 0 || characters.length > MAX_GLYPHS_PER_FONT) throw new RangeError(`A font holds 1 to ${MAX_GLYPHS_PER_FONT} glyphs.`);
+ let points = 0;
+ for (const character of characters) {
+ if ([...character].length !== 1) throw new TypeError('Each glyph key must be one character.');
+ points += validateGlyph(character, data.glyphs[character]);
+ }
+ if (points > MAX_POINTS_PER_FONT) throw new RangeError(`A font holds at most ${MAX_POINTS_PER_FONT} outline points.`);
+ fonts.set(name, data);
+}
+
+registerFont(DEFAULT_FONT_NAME, DEFAULT_FONT_DATA);
+
+function midpoint(first, second) {
+ return [(first[0] + second[0]) / 2, (first[1] + second[1]) / 2, 1];
+}
+
+// TrueType stores quadratic curves whose on-curve points may be left out between two off-curve points.
+function withImpliedPoints(flat) {
+ const points = [];
+ for (let index = 0; index < flat.length; index += 3) points.push([flat[index], flat[index + 1], flat[index + 2]]);
+ const expanded = [];
+ points.forEach((point, index) => {
+ expanded.push(point);
+ const next = points[(index + 1) % points.length];
+ if (!point[2] && !next[2]) expanded.push(midpoint(point, next));
+ });
+ const start = expanded.findIndex(point => point[2]);
+ if (start < 0) throw new RangeError('A contour has no on-curve point.');
+ return [...expanded.slice(start), ...expanded.slice(0, start)];
+}
+
+/** Polygon for one contour, `curveSegments` straight pieces per quadratic curve, in font units. */
+export function flattenContour(flat, curveSegments) {
+ const points = withImpliedPoints(flat);
+ const polygon = [[points[0][0], points[0][1]]];
+ let index = 1;
+ while (index <= points.length) {
+ const current = points[index - 1];
+ const next = points[index % points.length];
+ if (next[2]) {
+ polygon.push([next[0], next[1]]);
+ index += 1;
+ continue;
+ }
+ const end = points[(index + 1) % points.length];
+ for (let step = 1; step <= curveSegments; step++) {
+ const t = step / curveSegments;
+ const remainder = 1 - t;
+ polygon.push([
+ remainder * remainder * current[0] + 2 * remainder * t * next[0] + t * t * end[0],
+ remainder * remainder * current[1] + 2 * remainder * t * next[1] + t * t * end[1],
+ ]);
+ }
+ index += 2;
+ }
+ polygon.pop();
+ return polygon;
+}
+
+function insideRing(point, ring) {
+ let result = false;
+ for (let index = 0, previous = ring.length - 1; index < ring.length; previous = index++) {
+ const a = ring[index];
+ const b = ring[previous];
+ if ((a[1] > point[1]) !== (b[1] > point[1]) && point[0] < (b[0] - a[0]) * (point[1] - a[1]) / (b[1] - a[1]) + a[0]) result = !result;
+ }
+ return result;
+}
+
+function withoutRepeats(ring) {
+ const kept = ring.filter((point, index) => {
+ const next = ring[(index + 1) % ring.length];
+ return point[0] !== next[0] || point[1] !== next[1];
+ });
+ return kept;
+}
+
+/** Splits a glyph's rings into outlines with their holes: a ring inside an odd number of others is a hole. */
+export function groupRings(rings) {
+ const depths = rings.map((ring, index) => rings.filter((other, otherIndex) => otherIndex !== index && insideRing(ring[0], other)).length);
+ const outlines = [];
+ rings.forEach((ring, index) => {
+ if (depths[index] % 2 === 0) outlines.push({ contour: ring, holes: [], index });
+ });
+ rings.forEach((ring, index) => {
+ if (depths[index] % 2 === 0) return;
+ const containing = outlines.filter(outline => insideRing(ring[0], outline.contour));
+ const owner = containing.reduce((best, outline) => (depths[outline.index] > depths[best.index] ? outline : best));
+ owner.holes.push(ring);
+ });
+ return outlines;
+}
+
+function glyphMesh(record, unitsPerEm, { size, depth, curveSegments, maxVertices }) {
+ const factor = size / unitsPerEm;
+ const rings = record.slice(1).map(contour => withoutRepeats(flattenContour(contour, curveSegments).map(([x, y]) => [x * factor, y * factor])));
+ return groupRings(rings).map(({ contour, holes }) => extrude(contour, { holes, depth, maxVertices }));
+}
+
+function translated(mesh, offsetX, offsetY, offsetZ) {
+ const positions = Float32Array.from(mesh.positions);
+ for (let index = 0; index < positions.length; index += 3) {
+ positions[index] += offsetX;
+ positions[index + 1] += offsetY;
+ positions[index + 2] += offsetZ;
+ }
+ return { positions, normals: mesh.normals, uvs: mesh.uvs, indices: mesh.indices };
+}
+
+function merged(meshes) {
+ const vertexCount = meshes.reduce((total, mesh) => total + mesh.positions.length / 3, 0);
+ const indexCount = meshes.reduce((total, mesh) => total + mesh.indices.length, 0);
+ const result = {
+ positions: new Float32Array(vertexCount * 3), normals: new Float32Array(vertexCount * 3),
+ uvs: new Float32Array(vertexCount * 2), indices: new Uint32Array(indexCount),
+ };
+ let vertexOffset = 0;
+ let indexOffset = 0;
+ for (const mesh of meshes) {
+ result.positions.set(mesh.positions, vertexOffset * 3);
+ result.normals.set(mesh.normals, vertexOffset * 3);
+ result.uvs.set(mesh.uvs, vertexOffset * 2);
+ mesh.indices.forEach((vertex, index) => {
+ result.indices[indexOffset + index] = vertex + vertexOffset;
+ });
+ vertexOffset += mesh.positions.length / 3;
+ indexOffset += mesh.indices.length;
+ }
+ return result;
+}
+
+function lineWidth(line, font, factor) {
+ let width = 0;
+ for (const character of line) width += font.glyphs[character][0] * factor;
+ return width;
+}
+
+/**
+ * Text in the XY plane, its first baseline on y = 0, reading along +X and facing +Z, centred through its depth.
+ * Lines split at "\n". Every printable character must exist in the font.
+ */
+export function text(content, { size = 1, depth = 0.2, font: fontName = DEFAULT_FONT_NAME, align = 'left', curveSegments = 4, maxVertices = 250_000 } = {}) {
+ if (typeof content !== 'string' || content.length === 0 || [...content].length > MAX_TEXT_CHARACTERS) throw new RangeError(`text needs 1 to ${MAX_TEXT_CHARACTERS} characters.`);
+ checkNumber(size, 'size');
+ checkNumber(depth, 'depth');
+ if (size <= 0 || depth <= 0) throw new RangeError('size and depth must be positive.');
+ if (!Number.isInteger(curveSegments) || curveSegments < 1 || curveSegments > 16) throw new RangeError('curveSegments must be an integer from 1 to 16.');
+ if (!ALIGNMENTS.includes(align)) throw new RangeError(`align must be one of ${ALIGNMENTS.join(', ')}.`);
+ const font = fonts.get(fontName);
+ if (!font) throw new RangeError(`Unknown font ${JSON.stringify(fontName)}. Known fonts: ${[...fonts.keys()].join(', ')}.`);
+ const lines = content.split('\n');
+ if (lines.length > MAX_TEXT_LINES) throw new RangeError(`text has at most ${MAX_TEXT_LINES} lines.`);
+ const factor = size / font.unitsPerEm;
+ const cache = new Map();
+ const meshes = [];
+ let vertexCount = 0;
+ lines.forEach((line, lineIndex) => {
+ const width = lineWidth(line, font, factor);
+ let cursor = align === 'center' ? -width / 2 : align === 'right' ? -width : 0;
+ const baseline = -lineIndex * LINE_HEIGHT_EMS * size;
+ for (const character of line) {
+ const record = font.glyphs[character];
+ if (!record) throw new RangeError(`Font ${JSON.stringify(fontName)} has no glyph for ${JSON.stringify(character)}.`);
+ if (!cache.has(character)) cache.set(character, glyphMesh(record, font.unitsPerEm, { size, depth, curveSegments, maxVertices }));
+ for (const mesh of cache.get(character)) {
+ vertexCount += mesh.positions.length / 3;
+ if (vertexCount > maxVertices) throw new RangeError(`Text requires more than maxVertices ${maxVertices}. Shorten it or lower curveSegments.`);
+ meshes.push(translated(mesh, cursor, baseline, -depth / 2));
+ }
+ cursor += record[0] * factor;
+ }
+ });
+ if (meshes.length === 0) throw new RangeError('text has no visible characters.');
+ return merged(meshes);
+}
diff --git a/tests/blender-curve-text.test.js b/tests/blender-curve-text.test.js
new file mode 100644
index 00000000..d6ed8264
--- /dev/null
+++ b/tests/blender-curve-text.test.js
@@ -0,0 +1,81 @@
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import test from 'node:test';
+import { curve } from '../src/modeling.js';
+import { text } from '../src/text-geometry.js';
+
+// Curve and text objects are compared by volume, area and bounds, because Blender merges the seam vertices that
+// 67.js keeps for its UVs, so vertex counts differ by design. Cases and results come from tests/fixtures/blender,
+// written by scripts/blender-golden.py.
+const FIXTURE_DIRECTORY = new URL('./fixtures/blender/', import.meta.url);
+const readFixture = name => JSON.parse(readFileSync(new URL(name, FIXTURE_DIRECTORY), 'utf8'));
+const { curves: curveCases, texts: textCases } = readFixture('cases.json');
+const golden = readFixture('golden.json');
+
+// Measured differences are below 2e-5 for volume and area; these leave room for another Blender release.
+const CURVE_MEASURE_TOLERANCE = 1e-4;
+const TEXT_MEASURE_TOLERANCE = 1e-4;
+const BOUNDS_TOLERANCE = 1e-3;
+
+function subtract(first, second) {
+ return first.map((value, axis) => value - second[axis]);
+}
+
+function cross([ax, ay, az], [bx, by, bz]) {
+ return [ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx];
+}
+
+function dot(first, second) {
+ return first.reduce((sum, value, axis) => sum + value * second[axis], 0);
+}
+
+function measureSurface({ positions, indices }) {
+ let volume = 0;
+ let area = 0;
+ const lower = [Infinity, Infinity, Infinity];
+ const upper = [-Infinity, -Infinity, -Infinity];
+ const corner = index => [positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]];
+ for (let vertex = 0; vertex < positions.length / 3; vertex++) {
+ corner(vertex).forEach((value, axis) => {
+ lower[axis] = Math.min(lower[axis], value);
+ upper[axis] = Math.max(upper[axis], value);
+ });
+ }
+ for (let offset = 0; offset < indices.length; offset += 3) {
+ const first = corner(indices[offset]);
+ const second = corner(indices[offset + 1]);
+ const third = corner(indices[offset + 2]);
+ volume += dot(first, cross(second, third)) / 6;
+ area += Math.hypot(...cross(subtract(second, first), subtract(third, first))) / 2;
+ }
+ return { volume, area, boundsMin: lower, boundsMax: upper };
+}
+
+function compareToBlender(measured, expected, tolerance) {
+ for (const metric of ['volume', 'area']) {
+ const relative = Math.abs(measured[metric] - expected[metric]) / expected[metric];
+ assert.ok(relative <= tolerance, `${metric} ${measured[metric].toFixed(5)} against Blender's ${expected[metric].toFixed(5)}`);
+ }
+ for (const metric of ['boundsMin', 'boundsMax']) {
+ measured[metric].forEach((value, axis) => {
+ assert.ok(Math.abs(value - expected[metric][axis]) <= BOUNDS_TOLERANCE, `${metric}[${axis}] ${value.toFixed(5)} against Blender's ${expected[metric][axis]}`);
+ });
+ }
+}
+
+test('the golden file has a result for each curve and text case', () => {
+ assert.deepEqual(Object.keys(golden.curves).sort(), curveCases.map(({ id }) => id).sort());
+ assert.deepEqual(Object.keys(golden.texts).sort(), textCases.map(({ id }) => id).sort());
+});
+
+for (const { id, curve: spec } of curveCases) {
+ test(`${id} matches Blender's evaluated Bezier curve in volume, area and bounds`, () => {
+ compareToBlender(measureSurface(curve(spec.points, spec)), golden.curves[id], CURVE_MEASURE_TOLERANCE);
+ });
+}
+
+for (const { id, text: spec } of textCases) {
+ test(`${id} matches Blender's text object in volume, area and bounds, using the same font`, () => {
+ compareToBlender(measureSurface(text(spec.text, spec)), golden.texts[id], TEXT_MEASURE_TOLERANCE);
+ });
+}
diff --git a/tests/curve-text.test.js b/tests/curve-text.test.js
new file mode 100644
index 00000000..82dff3b4
--- /dev/null
+++ b/tests/curve-text.test.js
@@ -0,0 +1,273 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createAgentScene, agentSceneModulesNeeded, AGENT_SCENE_CAPABILITIES } from '../src/agent-scene.js';
+import { curve } from '../src/modeling.js';
+import { registerFont, text, flattenContour, groupRings } from '../src/text-geometry.js';
+import { DEFAULT_FONT_DATA } from '../src/font-default.js';
+
+const CIRCLE_HANDLE = 0.5522847498;
+
+function triangleMeasures({ positions, indices }) {
+ let volume = 0;
+ let area = 0;
+ for (let offset = 0; offset < indices.length; offset += 3) {
+ const [a, b, c] = [0, 1, 2].map(corner => Array.from(positions.subarray(indices[offset + corner] * 3, indices[offset + corner] * 3 + 3)));
+ volume += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6;
+ const first = b.map((value, axis) => value - a[axis]);
+ const second = c.map((value, axis) => value - a[axis]);
+ area += Math.hypot(first[1] * second[2] - first[2] * second[1], first[2] * second[0] - first[0] * second[2], first[0] * second[1] - first[1] * second[0]) / 2;
+ }
+ return { volume, area };
+}
+
+function bounds({ positions }) {
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (let index = 0; index < positions.length; index += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ minimum[axis] = Math.min(minimum[axis], positions[index + axis]);
+ maximum[axis] = Math.max(maximum[axis], positions[index + axis]);
+ }
+ }
+ return { minimum, maximum };
+}
+
+function unwelded(mesh) {
+ // Edges counted by rounded position: a closed surface uses every edge twice.
+ const key = index => Array.from(mesh.positions.subarray(index * 3, index * 3 + 3), value => value.toFixed(4)).join(',');
+ const uses = new Map();
+ for (let offset = 0; offset < mesh.indices.length; offset += 3) {
+ for (let side = 0; side < 3; side++) {
+ const from = key(mesh.indices[offset + side]);
+ const to = key(mesh.indices[offset + (side + 1) % 3]);
+ if (from === to) continue;
+ const edge = from < to ? `${from}|${to}` : `${to}|${from}`;
+ uses.set(edge, (uses.get(edge) ?? 0) + 1);
+ }
+ }
+ return [...uses.values()].filter(count => count !== 2).length;
+}
+
+const circlePoints = [
+ { position: [1, 0, 0], handleIn: [1, -CIRCLE_HANDLE, 0], handleOut: [1, CIRCLE_HANDLE, 0] },
+ { position: [0, 1, 0], handleIn: [CIRCLE_HANDLE, 1, 0], handleOut: [-CIRCLE_HANDLE, 1, 0] },
+ { position: [-1, 0, 0], handleIn: [-1, CIRCLE_HANDLE, 0], handleOut: [-1, -CIRCLE_HANDLE, 0] },
+ { position: [0, -1, 0], handleIn: [-CIRCLE_HANDLE, -1, 0], handleOut: [CIRCLE_HANDLE, -1, 0] },
+];
+
+test('a closed Bezier ring with a round profile has the volume of a torus and faces outward', () => {
+ const mesh = curve(circlePoints, { closed: true, radius: 0.1, radialSegments: 48, resolution: 24 });
+ const { volume } = triangleMeasures(mesh);
+ const torusVolume = 2 * Math.PI * Math.PI * 1 * 0.01;
+ assert.ok(volume > 0, 'faces point outward');
+ assert.ok(Math.abs(volume - torusVolume) / torusVolume < 0.01, `${volume} against ${torusVolume}`);
+ assert.equal(unwelded(mesh), 0, 'a closed curve has no open edge');
+});
+
+test('an open curve gets flat caps and is watertight', () => {
+ const mesh = curve([[0, 0, 0], [1, 1, 0], [2, 0, 0], [3, 1, 1]], { radius: 0.1, radialSegments: 8 });
+ assert.ok(triangleMeasures(mesh).volume > 0);
+ assert.equal(unwelded(mesh), 0);
+});
+
+test('taper scales the radius along the length: a cone has a third of the cylinder volume', () => {
+ const cone = curve([[0, 0, 0], [0, 3, 0]], { radius: 0.5, taper: [1, 0], radialSegments: 64, resolution: 32 });
+ const cylinder = curve([[0, 0, 0], [0, 3, 0]], { radius: 0.5, radialSegments: 64, resolution: 4 });
+ const ratio = triangleMeasures(cone).volume / triangleMeasures(cylinder).volume;
+ assert.ok(Math.abs(ratio - 1 / 3) < 0.01, `ratio ${ratio}`);
+});
+
+test('a custom profile sweeps its own cross-section whichever way it winds', () => {
+ const bar = [[-0.2, -0.1], [0.2, -0.1], [0.2, 0.1], [-0.2, 0.1]];
+ for (const profile of [bar, [...bar].reverse()]) {
+ const mesh = curve([[0, 0, 0], [0, 0, 2]], { radius: 1, profile });
+ assert.ok(Math.abs(triangleMeasures(mesh).volume - 0.4 * 0.2 * 2) < 1e-6);
+ assert.equal(unwelded(mesh), 0);
+ }
+ const { minimum, maximum } = bounds(curve([[0, 0, 0], [0, 0, 2]], { radius: 1, profile: bar }));
+ assert.ok(Math.abs(maximum[2] - minimum[2] - 2) < 1e-6);
+});
+
+test('handles: automatic ones are smooth, a lone handle is mirrored and explicit ones bend the span', () => {
+ const automatic = bounds(curve([[0, 0, 0], [1, 1, 0], [2, 0, 0]], { radius: 0.01, radialSegments: 3 }));
+ assert.ok(automatic.maximum[1] > 0.9 && automatic.maximum[1] < 1.2);
+ const mirrored = curve([{ position: [0, 0, 0], handleOut: [0, 1, 0] }, [4, 0, 0]], { radius: 0.01, radialSegments: 3 });
+ assert.ok(bounds(mirrored).maximum[1] > 0.4, 'the span leaves along the handle');
+ const straight = bounds(curve([[0, 0, 0], [4, 0, 0]], { radius: 0.01, radialSegments: 3 }));
+ assert.ok(straight.maximum[1] < 0.011);
+});
+
+test('curve rejects hostile or malformed input', () => {
+ const line = [[0, 0, 0], [1, 0, 0]];
+ const cases = [
+ () => curve([[0, 0, 0]], {}),
+ () => curve(Array.from({ length: 1025 }, (_, index) => [index, 0, 0]), {}),
+ () => curve(line, { radius: 0 }),
+ () => curve(line, { radius: NaN }),
+ () => curve(line, { radius: Infinity }),
+ () => curve(line, { resolution: 0 }),
+ () => curve(line, { resolution: 65 }),
+ () => curve(line, { radialSegments: 2 }),
+ () => curve(line, { taper: [1] }),
+ () => curve(line, { taper: [1, -1] }),
+ () => curve(line, { taper: Array.from({ length: 65 }, () => 1) }),
+ () => curve(line, { profile: [[0, 0], [1, 0]] }),
+ () => curve(line, { profile: Array.from({ length: 257 }, (_, index) => [Math.cos(index), Math.sin(index)]) }),
+ () => curve(line, { profile: [[0, 0], [1, 0], [0, 0]] }),
+ () => curve([[0, 0, 0], [0, 0, 0]], {}),
+ () => curve([[0, 0], [1, 0]], {}),
+ () => curve([{ position: [0, 0, 0], extra: 1 }, [1, 0, 0]], {}),
+ () => curve([{ position: [0, 0, 0], handleOut: 'x' }, [1, 0, 0]], {}),
+ () => curve(['a', 'b'], {}),
+ () => curve(line, { closed: 'yes' }),
+ () => curve(line, { closed: true }),
+ () => curve(line, { resolution: 64, radialSegments: 128, maxVertices: 1000 }),
+ () => curve(null, {}),
+ ];
+ cases.forEach((run, index) => assert.throws(run, Error, `case ${index} should throw`));
+});
+
+test('the bundled font builds every printable character and keeps counters open', () => {
+ for (let code = 33; code <= 126; code++) {
+ const character = String.fromCharCode(code);
+ const mesh = text(character, { size: 1, depth: 0.1, curveSegments: 3 });
+ assert.ok(triangleMeasures(mesh).volume > 0, `${character} faces outward`);
+ }
+ const solid = triangleMeasures(text('I', { depth: 1 })).volume;
+ const letterB = triangleMeasures(text('B', { depth: 1, curveSegments: 12 }));
+ assert.ok(letterB.volume > solid && letterB.volume < 0.5, 'B is area times depth, with two holes cut out');
+});
+
+test('text sits on its baseline, reads along +X, is centred through its depth and splits lines', () => {
+ const single = bounds(text('Hello', { size: 2, depth: 0.5 }));
+ assert.ok(Math.abs(single.minimum[2] + 0.25) < 1e-6 && Math.abs(single.maximum[2] - 0.25) < 1e-6);
+ assert.ok(single.minimum[1] > -0.1 * 2 && single.maximum[1] > 1.4 && single.maximum[1] < 1.6);
+ const advances = [...'Hello'].reduce((total, character) => total + DEFAULT_FONT_DATA.glyphs[character][0], 0) * 2 / DEFAULT_FONT_DATA.unitsPerEm;
+ assert.ok(single.maximum[0] < advances && single.maximum[0] > advances * 0.9);
+ const centered = bounds(text('Hello', { size: 2, depth: 0.5, align: 'center' }));
+ assert.ok(Math.abs((centered.minimum[0] + centered.maximum[0]) / 2) < advances * 0.1);
+ const right = bounds(text('Hello', { size: 2, align: 'right' }));
+ assert.ok(right.maximum[0] <= 1e-6);
+ const twoLines = bounds(text('Hi\nHi', { size: 1 }));
+ assert.ok(twoLines.minimum[1] < -1.1);
+});
+
+test('text rejects hostile or unsupported input', () => {
+ const cases = [
+ () => text('', {}),
+ () => text(42, {}),
+ () => text('a'.repeat(257), {}),
+ () => text('a\n'.repeat(17), {}),
+ () => text(' ', {}),
+ () => text('é', {}),
+ () => text('\u{1F600}', {}),
+ () => text('a', { size: 0 }),
+ () => text('a', { size: NaN }),
+ () => text('a', { depth: -1 }),
+ () => text('a', { depth: Infinity }),
+ () => text('a', { curveSegments: 0 }),
+ () => text('a', { curveSegments: 17 }),
+ () => text('a', { curveSegments: 2.5 }),
+ () => text('a', { align: 'justify' }),
+ () => text('a', { font: 'missing' }),
+ () => text('a', { font: '__proto__' }),
+ () => text('@'.repeat(200), { curveSegments: 16, maxVertices: 10_000 }),
+ ];
+ cases.forEach((run, index) => assert.throws(run, Error, `case ${index} should throw`));
+});
+
+test('registerFont validates a font table and the font becomes usable by name', () => {
+ const square = [0, 0, 1, 500, 0, 1, 500, 500, 1, 0, 500, 1];
+ const font = { unitsPerEm: 1000, ascender: 800, descender: -200, glyphs: { A: [600, square] } };
+ registerFont('Square', font);
+ const mesh = text('AA', { font: 'Square', size: 1, depth: 1 });
+ assert.ok(Math.abs(triangleMeasures(mesh).volume - 2 * 0.25) < 1e-5);
+ const invalid = [
+ ['bad/name', font],
+ ['', font],
+ ['ok', null],
+ ['ok', { ...font, unitsPerEm: 4 }],
+ ['ok', { ...font, unitsPerEm: 1000.5 }],
+ ['ok', { ...font, ascender: NaN }],
+ ['ok', { ...font, glyphs: {} }],
+ ['ok', { ...font, glyphs: { AB: [600, square] } }],
+ ['ok', { ...font, glyphs: { A: 'x' } }],
+ ['ok', { ...font, glyphs: { A: [600, [0, 0, 1, 1, 1, 1]] } }],
+ ['ok', { ...font, glyphs: { A: [600, [...square.slice(0, 11), 2]] } }],
+ ['ok', { ...font, glyphs: { A: [600, [...square.slice(0, 3), NaN, 0, 1, 1, 1, 1]] } }],
+ ['ok', { ...font, glyphs: { A: [600, Array.from({ length: 129 * 3 }, (_, index) => (index % 3 === 2 ? 1 : index))] } }],
+ ['ok', { ...font, glyphs: Object.fromEntries(Array.from({ length: 2049 }, (_, index) => [String.fromCodePoint(0x4e00 + index), [600, square]])) }],
+ ];
+ invalid.forEach(([name, table], index) => assert.throws(() => registerFont(name, table), Error, `font case ${index} should throw`));
+});
+
+test('contours flatten with implied points and group into outlines with holes', () => {
+ const ring = flattenContour([0, 0, 1, 100, 0, 0, 100, 100, 0, 0, 100, 1], 4);
+ assert.ok(ring.length >= 4 && ring.every(point => Number.isFinite(point[0])));
+ const outer = [[0, 0], [10, 0], [10, 10], [0, 10]];
+ const hole = [[2, 2], [2, 8], [8, 8], [8, 2]];
+ const island = [[4, 4], [6, 4], [6, 6], [4, 6]];
+ const grouped = groupRings([outer, hole, island]);
+ assert.equal(grouped.length, 2);
+ assert.equal(grouped[0].holes.length, 1);
+});
+
+const signRecipe = {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [
+ { id: 'board', type: 'box', bevel: 0 },
+ { id: 'letters', type: 'text', text: 'OPEN', size: 0.5, depth: 0.05, align: 'center' },
+ { id: 'pipe', type: 'curve', points: [[-1, 0, 0], { position: [0, 1, 0], handleIn: [-0.5, 1, 0], handleOut: [0.5, 1, 0] }, [1, 0, 0]], radius: 0.04, taper: [1, 0.5] },
+ ],
+ materials: [{ id: 'paint', color: [0.9, 0.8, 0.2] }, { id: 'metal', color: [0.6, 0.6, 0.65], metallic: 1, roughness: 0.3 }],
+ nodes: [
+ { id: 'board', geometry: 'board', material: 'paint', scale: [2, 1, 0.05] },
+ { id: 'letters', geometry: 'letters', material: 'metal', translation: [0, -0.2, 0.05] },
+ { id: 'pipe', geometry: 'pipe', material: 'metal' },
+ ],
+};
+
+test('a recipe draws a labelled sign and a piped curve', () => {
+ assert.deepEqual(agentSceneModulesNeeded(signRecipe), ['modeling', 'text']);
+ const scene = createAgentScene(signRecipe);
+ const letters = scene.parts.find(part => part.name === 'letters');
+ const pipe = scene.parts.find(part => part.name === 'pipe');
+ assert.ok(letters.geometry.indices.length > 0 && pipe.geometry.indices.length > 0);
+ assert.deepEqual(scene.exportRecipe().geometries.map(geometry => geometry.type), ['box', 'text', 'curve']);
+});
+
+test('recipe geometry validation rejects unknown fields, wrong types and oversized text before generating', () => {
+ const withGeometry = geometry => ({ ...signRecipe, geometries: [geometry], nodes: [{ id: 'n', geometry: 'g', material: 'paint' }] });
+ const bad = [
+ { id: 'g', type: 'text', text: 'A', unknown: 1 },
+ { id: 'g', type: 'text', text: 5 },
+ { id: 'g', type: 'text', text: 'A'.repeat(257) },
+ { id: 'g', type: 'text', text: 'A', size: 'big' },
+ { id: 'g', type: 'text', text: 'A', font: 7 },
+ { id: 'g', type: 'text', text: 'W'.repeat(255), curveSegments: 16 },
+ { id: 'g', type: 'curve', points: 'a' },
+ { id: 'g', type: 'curve', points: [[0, 0, 0]] },
+ { id: 'g', type: 'curve', points: [[0, 0, 0], [1, 0, 0]], resolution: 1000 },
+ { id: 'g', type: 'curve', points: [[0, 0, 0], [1, 0, 0]], profile: 4 },
+ { id: 'g', type: 'curve', points: [[0, 0, 0], [1, 0, 0]], radialSegments: 500 },
+ { id: 'g', type: 'curve', points: [[0, 0, 0], [1, 0, 0]], extra: true },
+ { id: 'g', type: 'curve', points: [{ position: [0, 0, 0], handleIn: [0, 0] }, [1, 0, 0]] },
+ ];
+ bad.forEach((geometry, index) => assert.throws(() => createAgentScene(withGeometry(geometry)), Error, `recipe case ${index} should throw`));
+});
+
+test('no bundled glyph exceeds the vertex bound the recipe estimate uses', () => {
+ const { verticesPerCharacterSegment } = AGENT_SCENE_CAPABILITIES.curveText;
+ for (const curveSegments of [1, 4, 16]) {
+ for (let code = 33; code <= 126; code++) {
+ const vertices = text(String.fromCharCode(code), { curveSegments }).positions.length / 3;
+ assert.ok(vertices <= verticesPerCharacterSegment * curveSegments, `${String.fromCharCode(code)} at ${curveSegments}: ${vertices}`);
+ }
+ }
+});
+
+test('capabilities list the new types with their limits and details', () => {
+ assert.ok(AGENT_SCENE_CAPABILITIES.geometryTypes.includes('curve') && AGENT_SCENE_CAPABILITIES.geometryTypes.includes('text'));
+ assert.equal(AGENT_SCENE_CAPABILITIES.curveText.maxTextCharacters, 256);
+ assert.match(AGENT_SCENE_CAPABILITIES.curveText.details.text, /baseline/);
+});
diff --git a/tests/fixtures/blender/cases.json b/tests/fixtures/blender/cases.json
index e7a3a22e..63f12aa9 100644
--- a/tests/fixtures/blender/cases.json
+++ b/tests/fixtures/blender/cases.json
@@ -122,5 +122,167 @@
{ "id": "decimate-bowl-half", "input": "bowl-open", "compare": "surface", "edit": {"op":"decimate","ratio":0.5} },
{ "id": "remesh-sphere", "input": "sphere-bumpy", "compare": "surface", "edit": {"op":"remesh","voxelSize":0.1} },
{ "id": "remesh-torus", "input": "torus-fine", "compare": "surface", "edit": {"op":"remesh","voxelSize":0.08} }
+ ],
+ "curves": [
+ {
+ "id": "bezier-pipe-open",
+ "curve": {
+ "points": [
+ {
+ "position": [
+ 0,
+ 0,
+ 0
+ ],
+ "handleIn": [
+ -0.5,
+ -0.5,
+ 0
+ ],
+ "handleOut": [
+ 0.6,
+ 0.8,
+ 0
+ ]
+ },
+ {
+ "position": [
+ 2,
+ 1,
+ 0.5
+ ],
+ "handleIn": [
+ 1.4,
+ 1.2,
+ 0.2
+ ],
+ "handleOut": [
+ 2.6,
+ 0.8,
+ 0.8
+ ]
+ },
+ {
+ "position": [
+ 3,
+ 0,
+ 1
+ ],
+ "handleIn": [
+ 2.9,
+ 0.5,
+ 1
+ ],
+ "handleOut": [
+ 3.2,
+ -0.4,
+ 1.2
+ ]
+ }
+ ],
+ "radius": 0.1,
+ "radialSegments": 8,
+ "resolution": 12
+ }
+ },
+ {
+ "id": "bezier-ring-closed",
+ "curve": {
+ "points": [
+ {
+ "position": [
+ 1,
+ 0,
+ 0
+ ],
+ "handleIn": [
+ 1,
+ -0.5522847498,
+ 0
+ ],
+ "handleOut": [
+ 1,
+ 0.5522847498,
+ 0
+ ]
+ },
+ {
+ "position": [
+ 0,
+ 1,
+ 0
+ ],
+ "handleIn": [
+ 0.5522847498,
+ 1,
+ 0
+ ],
+ "handleOut": [
+ -0.5522847498,
+ 1,
+ 0
+ ]
+ },
+ {
+ "position": [
+ -1,
+ 0,
+ 0
+ ],
+ "handleIn": [
+ -1,
+ 0.5522847498,
+ 0
+ ],
+ "handleOut": [
+ -1,
+ -0.5522847498,
+ 0
+ ]
+ },
+ {
+ "position": [
+ 0,
+ -1,
+ 0
+ ],
+ "handleIn": [
+ -0.5522847498,
+ -1,
+ 0
+ ],
+ "handleOut": [
+ 0.5522847498,
+ -1,
+ 0
+ ]
+ }
+ ],
+ "closed": true,
+ "radius": 0.1,
+ "radialSegments": 16,
+ "resolution": 16
+ }
+ }
+ ],
+ "texts": [
+ {
+ "id": "text-B",
+ "text": {
+ "text": "B",
+ "size": 1,
+ "depth": 0.2,
+ "curveSegments": 12
+ }
+ },
+ {
+ "id": "text-Hi",
+ "text": {
+ "text": "Hi",
+ "size": 1,
+ "depth": 0.2,
+ "curveSegments": 12
+ }
+ }
]
}
diff --git a/tests/fixtures/blender/golden.json b/tests/fixtures/blender/golden.json
index b887e059..656856c3 100644
--- a/tests/fixtures/blender/golden.json
+++ b/tests/fixtures/blender/golden.json
@@ -23261,5 +23261,69 @@
"area": 13.48201,
"hausdorff": 0.012668
}
+ },
+ "curves": {
+ "bezier-pipe-open": {
+ "vertexCount": 216,
+ "volume": 0.114057,
+ "area": 2.527249,
+ "boundsMin": [
+ -0.08,
+ -0.06,
+ -0.1
+ ],
+ "boundsMax": [
+ 3.09686,
+ 1.14908,
+ 1.09878
+ ]
+ },
+ "bezier-ring-closed": {
+ "vertexCount": 1024,
+ "volume": 0.192075,
+ "area": 3.919132,
+ "boundsMin": [
+ -1.1,
+ -1.1,
+ -0.1
+ ],
+ "boundsMax": [
+ 1.1,
+ 1.1,
+ 0.1
+ ]
+ }
+ },
+ "texts": {
+ "text-B": {
+ "vertexCount": 804,
+ "volume": 0.040713,
+ "area": 1.290173,
+ "boundsMin": [
+ 0.09814,
+ 0.0,
+ -0.1
+ ],
+ "boundsMax": [
+ 0.61524,
+ 0.72901,
+ 0.1
+ ]
+ },
+ "text-Hi": {
+ "vertexCount": 80,
+ "volume": 0.046583,
+ "area": 1.57423,
+ "boundsMin": [
+ 0.09814,
+ 0.0,
+ -0.1
+ ],
+ "boundsMax": [
+ 0.93604,
+ 0.75977,
+ 0.1
+ ]
+ }
}
}
diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.js
index 876dc49b..894a46ca 100644
--- a/tests/mcp-tools.test.js
+++ b/tests/mcp-tools.test.js
@@ -148,7 +148,7 @@ test('SDK advertises the complete strict JSON contract and truthful annotations'
assert.equal(recipeSchema.properties.materials.maxItems, 256);
assert.equal(recipeSchema.properties.geometries.maxItems, 256);
const variants = recipeSchema.properties.geometries.items.oneOf ?? recipeSchema.properties.geometries.items.anyOf;
- assert.deepEqual(variants.map(variant => variant.properties.type.const), ['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'mesh']);
+ assert.deepEqual(variants.map(variant => variant.properties.type.const), ['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'mesh']);
assert.ok(variants.every(variant => variant.additionalProperties === false));
assert.equal(recipeSchema.properties.environment.additionalProperties, false);
assert.equal(recipeSchema.properties.environment.properties.pointLights.maxItems, 8);