# BaroCSS CAD — Complete Public Documentation > Generated deterministically from `apps/library-docs/docs/`. For kernel algorithm deep dives see `/how/`. --- # Hardware Showcase Explore real manufacturable workflows you can design, inspect, and export right in your browser — from parametric brackets and WebGPU manufacturability checks to 6-axis robotic arms exported directly to MuJoCo and ROS 2. ## Next steps - Open [Quick-Fit Mode](/studio/quick-fit) to adjust built-in hardware templates with live sliders and instant STEP/3MF/STL export. - Read [Compare CAD Tools](/compare/) to see how BaroCSS CAD stacks up against other browser and desktop CAD platforms. - Building your own 3D or AI CAD product? Try the live TypeScript kernel playground in [SDK & API](/packages/cad/). --- # How BaroCSS CAD Compares Modern browser and AI-native CAD tools solve very different parts of the hardware engineering stack. This page compares **BaroCSS CAD** against the leading emerging and established CAD platforms on factual architectural dimensions — including where another tool is the better fit. ## Architecture & Workflow Matrix | Capability | BaroCSS CAD | SolidCraft | Zoo Design Studio | Adam / CADAM | Tau / OwlCAD | Onshape / FreeCAD | | :--- | :--- | :--- | :--- | :--- | :--- | :--- | | **Geometry Kernel** | **Pure TypeScript B-Rep & NURBS** (zero WASM) | Pure Rust B-Rep (WASM in browser) | Proprietary cloud/native B-Rep + KCL | OpenSCAD CSG (WASM) + CAD plugins | Multi-kernel WASM | Parasolid (cloud) / OCCT (desktop C++) | | **Browser Startup** | **0 ms WASM** — instant JS/TS module load | WASM download + init (or native desktop app) | Cloud engine session / desktop app | OpenSCAD WASM worker | Kernel WASM workers | Cloud streaming / desktop install | | **Modeling & Surfacing** | **Parametric B-Rep + Freeform Surfacing** (Patch, Ruled, Boundary Fill, Emboss) + **Mesh → Analytic B-Rep** + Enclosure & CNC Joinery | Parametric B-Rep + timeline | B-Rep + KCL scripting | OpenSCAD CSG | Code-first parametric | Full commercial / OCCT B-Rep | | **2D Engineering Drawings** | **Built-in exact 2D HLR** (4-view, Detail, Dimetric/Trimetric, Baseline/Ordinate, GD&T, Vector PDF/SVG/DXF) | Roadmap / basic export | Basic views / API focus | Plugin sync to host CAD | Basic / STL-3MF focus | Mature full drafting | | **AI Editing Pattern** | **⌘K 3D Spatial Pin** + Floating Proposals + Parallel Variants + Visual Self-Check | MCP + assistant panel | Zookeeper AI + KCL sync | Text → OpenSCAD + deterministic sliders | Text → multi-kernel code | Third-party copilots (e.g., MecAgent) | | **MCP / Automation** | **Headless CLI & Structured MCP Server** + L1–L4 guardrails | Built-in CLI MCP | API + MCP paths | Web / Slack / IDE triggers | CLI / MCP | REST API / Python macros | | **DFM & Manufacturing** | **Manufacture workspace** (WebGPU thickness/draft/Zebra, Print, Sheet, Frame, Mould, CAM Beta) | STEP / IGES / STL / 3MF export | Mass properties + STEP/glTF | STEP / STL / BOM graph | 3D print checks | Full commercial / plugin CAM | | **Hardware PR Review** | **BaroCSS Review** (3D/2D Before-After Diff, Live Spec Evidence, 2D HLR fallback) | Cloud version history | KCL Git diffs | PLM / BOM graph | Git code diffs | Built-in branching / external PDM | | **Robotics & Sim2Real** | **Built-in URDF, MJCF, SDF, USD** + auto joint-tree + gravity torque | External conversion | External conversion | External conversion | External conversion | Plugins / manual export | | **Embeddable Web SDK** | **Modular TypeScript & React SDK** + Three/Babylon/GLB adapters | Rust crates / app | Hosted API / KCL | Open-source web app | Open-source web app | No client-side B-Rep SDK | | **License & Lock-In** | **MIT Open Source**, local-first `.bcad` | MIT / Apache-2.0 | Proprietary kernel / open client | Open-source CADAM / commercial Adam | Open-source | Commercial SaaS / LGPL | ## Five Architectural Differentiators ### 1. Zero-WASM Pure TypeScript B-Rep Kernel Most browser CAD tools compile a C++ or Rust kernel to a multi-megabyte WebAssembly binary. BaroCSS CAD implements analytic & NURBS B-Rep modeling, Booleans, rolling-ball and G2 fillets, exact planar arithmetic, hidden-line removal, and STEP export **directly in TypeScript**: - No WebAssembly heap limits, cross-boundary marshaling overhead, or multi-second cold-start downloads. - Embeddable directly in modern web apps, React UIs, Three.js/Babylon.js scenes, or Node.js automation via [SDK & API](/packages/cad/). - Inspectable down to the algorithm: browse [77 interactive visualizers](/how/) running on the same geometry engine. ### 2. Full 5-Workspace Pipeline (Not Just Part Generation) Many Text-to-CAD tools stop at generating a single STL or parametric part. BaroCSS CAD covers the complete engineering loop inside one unified browser workspace: - **Design** (parametric B-Rep, freeform surfacing, Mesh → Analytic B-Rep, enclosure & CNC joinery, Quick-Fit sliders, SubD) - **Assemble** (mating, gear/rack/screw/path/slot motion links, collision contact-stop, robotics URDF/MJCF) - **Draw** (exact 2D HLR multi-view & detail sheets, baseline/ordinate dimensions, GD&T, vector PDF/SVG/DXF) - **Manufacture** (WebGPU thickness/draft/Zebra analysis, 3D Print Face & Slicer handoff, Sheet Metal, Frames, Mould, CAM Beta) - **Render** (WebGPU PBR materials, path tracing, Render Compare wipe slider, saved cameras, turntables) ### 3. Spatial, Verifiable AI Copilot (Never Silent Hallucination) Instead of regenerating triangle meshes on every prompt, BaroCSS CAD binds AI edits to exact B-Rep faces and persistent topology naming: - Click a face or edge, press **⌘K**, and review every structural proposal in the **Floating Proposal Review Bar** with configurable autonomy guardrails. - Spin up parallel candidates in the **Generative Variant Explorer** and compare mass, volume, and bounds before promoting a winner. - Every invalid geometric operation raises a clear [typed refusal code](/reference/refusals) with deterministic recovery guidance rather than producing broken geometry. ### 4. Pull-Request Style Hardware Review (`BaroCSS Review`) Share read-only `.bcad` bundles with mechanical teammates or suppliers in [BaroCSS Review](/studio/review): - Toggle **Before / After** proposal diffs with live volume, mass, and bounding-box deltas. - Inspect live specification checks and SHA-256 **Release Evidence Packs**. - Works even on non-WebGPU browsers (Firefox, Safari, VMs) via automatic **2D HLR interactive projection fallback**. ### 5. Native Robotics & Sim2Real Export Mated assemblies decompose automatically into kinematic joint trees with live gravity holding-torque readouts and one-click **URDF, MJCF, SDF, and USD** export with revision-pinned source records. See [Robotics & Export](/studio/robots). ## When Another Tool May Fit Better We prefer honest boundaries over marketing claims: - **Need a native offline Rust desktop binary today?** Check out **SolidCraft**, which compiles natively for Windows, macOS, Linux, and FreeBSD. - **Standardized on SolidWorks / NX / CATIA enterprise PLM?** A native desktop copilot like **MecAgent** or **Adam's** in-CAD plugins integrates directly into existing legacy feature trees. - **Already authoring Python `build123d` or OpenSCAD scripts?** **Tau** and **CADAM** provide multi-kernel script environments tailored to those ecosystems. - **Need decades-old enterprise surfacing, massive 10,000-part assemblies, or certified aerospace drafting?** **Onshape**, **SolidWorks**, or **FreeCAD** remain the established choice. ## Try It Yourself in 10 Seconds - [Try Quick-Fit Live in Browser →](/studio/quick-fit) - [Explore BaroCSS Review & 3D Diff →](/studio/review) - [Explore Hardware Showcase →](/showcase/) - [Read the 60-Second Quickstart →](/guide/getting-started) --- # Getting started Design, prompt, and export your first manufacturable part in 60 seconds — right in the browser with pure TypeScript and WebGPU, zero WASM install. ## Launch Studio From the repository root, use Node 22 and pnpm: ```bash pnpm install pnpm dev ``` Studio opens at `http://127.0.0.1:52020`. It runs directly from the workspace TypeScript sources with no build step required. ::: tip Renderer support The viewport renders with WebGPU when available and falls back automatically to WebGL2. Add `?renderer=webgl2` to the URL to force WebGL2. Analysis heatmaps and the Render workspace require WebGPU; see [Limits](/reference/limits). ::: ## First 60 seconds: Quickstart or Quick-Fit When Studio opens, you can jump straight into real geometry: - **Templates & Quickstart.** Pick a ready-to-edit hardware starter such as **Sensor Enclosure**, **NEMA-17 Bracket**, or **Cable Guide Adapter**, or open a blank part with **New part**. - **Quick-Fit URL mode.** Append `?mode=quickfit&preset=nema17` to tune exposed parameters with live sliders and export immediately — see [Quick-Fit & Casual Studio](/studio/quick-fit). ## Build a parametric part 1. Click **New part** in the top bar. 2. Press B for a box. Set **Width X** to `64`, **Depth Y** to `32`, and **Height Z** to `8`. The viewport previews live as you type. ![The box's fields in the HUD, previewed in the viewport](/shots/guide/getting-started/box-hud.jpg) 3. Press Enter to commit. The feature history records `Box 64×32×8` and the **Tree** panel lists one body. 4. Click **Top** in the view bar, then click the top face. The right inspector displays `SELECTION · FACE`. 5. Press H for a hole. Set **Diameter** to `8`, **Centre X** to `32`, and **Centre Y** to `16`. Wait for `preview`, then press Enter. ![The hole's preview on the top face, seen from the top, with its fields in the HUD](/shots/guide/getting-started/hole-preview.jpg) ### Add a tapped hole with verified Shop Rows BaroCSS CAD never guesses thread drills or fastener standards silently — sizes come from explicit **Shop rows** with supplier provenance: 1. Select the top face, press H, and set **Type** to **Tapped**. Without loaded rows, Studio refuses transparently with `[FASTENER_SIZE_ROW]`. ![The HUD refusing the tapped hole: no row for M6](/shots/guide/getting-started/tapped-refused.png) 2. Press Escape, open **Library**, and click **Load sample fastener sizes**. **Fastener sizes** loads `M3` through `M12` with source citations. ![The library with the sample fastener sizes loaded](/shots/guide/getting-started/library-rows.jpg) 3. Add the tapped hole again away from the first hole — Studio resolves the exact `M6×1` thread and Ø5 tap drill. ![The tapped hole's fields with the M6 row: an M6×1 thread](/shots/guide/getting-started/tapped-hole.png) See [Shop rows](/studio/rows) for all supported manufacturing tables. ## Prompt with the AI Copilot (3 runtime modes) Studio ships a provider-agnostic AI runtime with three connection modes in the Chat header: 1. **Browser AI Runner (BYOK).** Run directly in the browser with your own API key (Anthropic, OpenAI, or Gemini), including automatic multi-angle visual self-verification. 2. **Local CLI bridge.** Connect Studio to your local CLI session for workspace-assisted workflows. 3. **External coding agents (MCP).** Connect Claude Code or other MCP-compatible agents directly to `.bcad` files — see [AI Copilot & Spatial Pin](/agent/) or the [Headless CLI & MCP guide](/agent/cli). Press ⌘K (`Ctrl+K`) with any face or edge selected to open the **3D Spatial Pin** inline prompt, or open **Chat** to describe larger changes: - Value-only parameter tweaks apply immediately at default autonomy (`L2`) when all hard requirements pass. - Structural changes arrive in the **Floating Proposal Review Bar** with **Preview**, **Accept**, and **Reject**, or open side-by-side in the [Generative Variant Explorer](/agent/variants). ## Save, review, and export - **Save & Open.** Save native `.bcad` documents with full parametric history, or import STEP, IGES, STL, and OBJ files. - **Export menu.** Use the consolidated **Export** menu in the top bar for STEP, IGES, STL, 3MF, and robot packages (URDF, MJCF, SDF, USD). - **Draw workspace.** Switch to **Draw** in the top workspace bar for exact 2D HLR engineering sheets with auto-dimensions and SVG, PDF, or DXF export. ![The Draw workspace: orthographic views, title block, and sheet settings](/shots/guide/getting-started/drawing.jpg) - **BaroCSS Review.** Share read-only `.bcad` files and Before/After approval diffs with teammates right in the browser — see [BaroCSS Review](/studio/review). --- # Embedding & Self-Hosting BaroCSS CAD ships as a **100% static client-side bundle** — no backend geometry servers, no database migrations, and no WebAssembly build quirks. You can embed interactive 3D CAD directly inside documentation, product configurators, or internal portals, or deploy the entire unified site on any static host. ## 1. Unified Static Build (`pnpm build:site`) Running `pnpm build:site` executes `scripts/build-static-site.mjs` and assembles a single static directory (`dist-site/`): | Route | Source App | Role | | :--- | :--- | :--- | | `/` | `apps/library-docs` | Product showcase, documentation, 77 `/how/` visualizers, Live TS Playground | | `/app/` | `apps/cad-studio` | Full 5-Workspace CAD Studio + `?embed=1` Quick-Fit mode | | `/review/` | `apps/cad-viewer` | Shareable BaroCSS Review (`.bcad` 3D/2D diff + automatic 2D HLR fallback) | | `/llms*.txt` | `generate-llms.mjs` | AI-Ready context indexes (`llms.txt`, `llms-sdk.txt`, `llms-mcp.txt`, `llms-full.txt`) | ### Root Domain vs Subpath Hosting (`SITE_BASE`) ```bash # Custom root domain (official site: https://cad.barocss.com/) pnpm build:library pnpm build:site # writes dist-site/CNAME = cad.barocss.com SITE_CNAME=cad.example.com pnpm build:site # self-hosted custom domain SITE_CNAME= pnpm build:site # skip the CNAME file # Subpath hosting (e.g. https://barocss.github.io/cad/) SITE_BASE=/cad/ SITE_ORIGIN=https://barocss.github.io pnpm build:site ``` `build-static-site.mjs` automatically configures: - VitePress `base` and sitemap/OpenGraph URLs - `cad-studio` `VITE_BASE` (`/app/` or `/cad/app/`) - Base-prefixed `dist-site/llms.txt` links (without mutating repo-tracked `docs/public/llms.txt`) - `_headers` with strict `frame-ancestors` CSP and immutable asset caching for Cloudflare Pages / Netlify ### Static Host Recipes - **GitHub Pages**: Already automated via `.github/workflows/deploy-site.yml` (`actions/configure-pages@v5` automatically injects `SITE_BASE` and `SITE_ORIGIN`). Enable **Settings → Pages → Source: GitHub Actions**. - **Cloudflare Pages / Netlify**: Set build command to `pnpm build:library && pnpm build:site` and output directory to `dist-site`. - **Vercel**: Set build command to `pnpm build:library && pnpm build:site` and output directory to `dist-site`. ## 2. Embedding Quick-Fit Studio (`?embed=1`) Embed a live, interactive parametric part configurator in any webpage with a single ` ``` ### Supported Query Parameters | Parameter | Values | Behavior | | :--- | :--- | :--- | | `embed` | `1` \| `true` | Enables embed mode: hides top navigation chrome and uses an **ephemeral session** so embedded previews never overwrite a visitor's saved Studio workspace | | `mode` | `quickfit` | Opens directly in Quick-Fit parametric slider mode | | `preset` | `nema17` \| `enclosure` \| `adapter` | Loads a built-in parametric B-Rep preset | | `chrome` | `none` \| `minimal` | `minimal` shows the Quick-Fit parameter panel and `Open in Studio ↗` handoff button; `none` renders a pure 3D canvas | | `theme` | `dark` \| `light` | Matches host page appearance | | `renderer` | `auto` \| `webgl2` | Forces WebGL2 when WebGPU is unavailable (recommended fallback after probing `navigator.gpu?.requestAdapter()`) | ## 3. Controlling the Embed via `postMessage` (`barocss-embed-v1`) The Studio iframe exposes a typed, origin-checked `postMessage` bridge on channel `'barocss-embed-v1'`: ### Messages Sent by Studio → Host ```ts type EmbedChildToHost = | { channel: 'barocss-embed-v1'; type: 'ready'; renderer: 'webgpu' | 'webgl2'; preset: string } | { channel: 'barocss-embed-v1'; type: 'metrics'; volumeMm3: number | null; massG: number | null; boundsMm: [number, number, number] | null; health: 'healthy' | 'warning' | 'error'; parameters: Record; } | { channel: 'barocss-embed-v1'; type: 'error'; code: string; message: string }; ``` ### Messages Sent by Host → Studio ```ts const frame = document.querySelector('#cad-embed'); // Switch parametric preset live without reloading the iframe frame?.contentWindow?.postMessage( { channel: 'barocss-embed-v1', type: 'setPreset', preset: 'enclosure' }, '*', ); // Update a single named parameter deterministically frame?.contentWindow?.postMessage( { channel: 'barocss-embed-v1', type: 'setParam', name: 'thickness', value: 8 }, '*', ); // Reframe the 3D camera frame?.contentWindow?.postMessage( { channel: 'barocss-embed-v1', type: 'fitCamera' }, '*', ); ``` Incoming host messages are validated against `isAllowedEmbedOrigin` (same-origin, `localhost` / `127.0.0.1`, `barocss.dev`, `barocss.com` (incl. `cad.barocss.com`), `*.pages.dev`, `*.vercel.app`). When self-hosting on a custom domain, keep the embed on the **same origin** (`/app/` alongside `/`) so origin validation passes automatically with zero CORS or cross-origin friction. ## 4. Embedding BaroCSS Review (`/review/?embed=1`) To embed an interactive `.bcad` pull-request review with Before/After geometry diffs, approval evidence, and Quick-Fit sliders: ```html ``` On browsers without WebGPU (Firefox, Safari, VMs, headless environments), BaroCSS Review automatically switches to **interactive 2D HLR projection fallback** (`Iso | Front | Top | Right | 4-View` + clickable edges/faces) so proposal diffs and spec verification remain 100% functional. ## Related Pages - [Quick-Fit & Casual Studio](/studio/quick-fit) - [BaroCSS Review](/studio/review) - [React CAD SDK (`@barocss/cad-react/sdk`)](/packages/cad-react/sdk) - [Browser Support & FAQ](/guide/faq) --- # Browser Support, Privacy & FAQ ## Browser Compatibility Matrix BaroCSS CAD runs **100% client-side in your browser** with zero WebAssembly download. Graphics rendering adapts automatically to each browser's capabilities: | Browser / Environment | CAD Studio (`Design`, `Assemble`, `Draw`, `Manufacture`) | Studio `Render` Workspace (PBR / Path Tracing) | BaroCSS Review (`.bcad` PR Diff) | | :--- | :--- | :--- | :--- | | **Chrome / Edge / Arc / Brave** (Desktop, WebGPU enabled) | **Full WebGPU** (GPU thickness/draft/Zebra maps + shadows) | **Full WebGPU** (PBR + Path Tracing + Render Compare) | **3D WebGPU** + 2D HLR inspector | | **Firefox** (Desktop) | **WebGL2 automatic fallback** (full parametric B-Rep + Draw) | Notice shown (WebGPU required for path tracing) | **Interactive 2D HLR Fallback** (`Iso` / `Front` / `Top` / `Right` / `4-View` + Proposal Diff + Quick-Fit) | | **Safari / WebKit** (macOS / iPadOS) | **WebGL2 automatic fallback** | WebGPU when enabled in Safari | **Interactive 2D HLR Fallback** (or 3D when WebGPU enabled) | | **Headless / Remote VM / Software GPU** | **WebGL2 (`?renderer=webgl2`)** | Unavailable | **Interactive 2D HLR Fallback** | > **Tip:** If a workstation GPU blocklist prevents WebGPU initialization, open Studio with `?renderer=webgl2` to switch cleanly to WebGL2. ## Local-First Storage, Reliability & Privacy - **Zero mandatory cloud account.** Design parts, generate 2D engineering drawings, inspect DFM maps, and export STEP, 3MF, STL, DXF, URDF, or MJCF without signing up. - **Local browser persistence & save guard.** Local projects and version history are stored in your browser's private file storage with crash recovery, save round-trip verification, and dirty-state protection if a save is cancelled. See [Projects, Versions & Release Evidence](/studio/projects). - **Resilient long operations & GPU recovery.** Heavy evaluations run on a cancelable progress pipeline, lost graphics contexts recover automatically without losing document edits, and large assemblies stay responsive with virtualized outliner trees. - **Ephemeral embedded previews.** Embedded Quick-Fit previews run in isolated sessions so experimenting on a webpage never touches your saved Studio workspace. - **Bring your own AI key or local agent.** Use your own API key directly in the browser, or connect local coding agents over MCP without uploading proprietary `.bcad` files to third-party CAD servers. ## End-to-End Workflow Recipes 1. **Bracket from Sketch to Approved Release (10 min)** - Build and constrain the part in [60-Second Quickstart](/guide/getting-started) and [Modeling Workflow](/studio/modeling) - Iterate with [⌘K 3D Spatial Pin & Variant Explorer](/agent/variants) - Generate a 4-view sheet in [Drawings Workflow](/studio/drawing-workflows) - Share and sign off in [BaroCSS Review](/studio/review) with a signed [Release Evidence Pack](/studio/projects) 2. **Robotic Mechanism to MuJoCo & ROS 2** - Mate links in [Assemblies & Mates](/studio/assemblies) - Inspect kinematic joint trees, clearance sweeps, and gravity holding torque in [Robotics & Export](/studio/robots) - Export URDF, MJCF, SDF, or USD with revision-pinned source records 3. **Build Your Own CAD Web App or Agent Integration** - Explore the TypeScript & React libraries in [SDK & API](/packages/cad/) - Embed Quick-Fit or BaroCSS Review in 5 lines of HTML via [Embedding & Self-Hosting](/guide/embedding) ## Troubleshooting Common Refusals BaroCSS CAD follows a strict **"Correct or Refused"** contract — invalid geometry raises a clear typed refusal with recovery guidance instead of silently returning a broken mesh. | Symptom / Code | Why It Happened | Fastest Fix | | :--- | :--- | :--- | | `FILLET_RADIUS` / `FILLET_CONFLICT` | Fillet radius exceeds the adjacent face width or collides with a nearby hole or edge | Reduce the fillet radius below half the narrowest adjacent face, or reorder the hole after the fillet | | `SKETCH_OVERLAP` / `PROFILE_OPEN` | Self-intersecting sketch curves or an unclosed contour loop | Trim overlapping segments and close endpoints; place nested islands inside a hole in a separate sketch | | `MATE_CONTRADICTION` / `MATE_FACES` | Two mates demand conflicting positions or incompatible face kinds were paired | Inspect the coupled DOF contradiction callout in the Mates panel, flip orientation, or relax one redundant constraint | | `MOUNT_RANGE` / `MOUNT_FACE` | Motor/servo mount extends past the plate edge or target face is not planar and axis-aligned | Widen the plate parameter or pick a flat ±X/±Y/±Z face | | `WEBGPU_UNAVAILABLE` / `NO_ADAPTER` | Browser lacks a hardware WebGPU adapter | Use `?renderer=webgl2` in Studio; BaroCSS Review automatically renders in interactive 2D HLR mode | For the complete searchable refusal index, see [Refusal Codes](/reference/refusals). For explicit boundaries, see [Capability Boundaries](/reference/limits). --- # Concepts A few rules run through every part of BaroCSS CAD. Knowing them makes the rest of these pages, and the studio's messages, easier to read. ## Units and coordinates - **Lengths are millimetres.** A document records `units: 'mm'`, and every length field and readout in the studio is in millimetres. - **Angles are degrees** in the studio's fields. A few machine-facing outputs convert, for example robot exports, which write metres and radians as their formats expect. - **Z is up.** The XY plane is the ground, and the camera orbits about Z. **Top** looks down Z, and a box's **Height Z** grows upward. - **Density is in g/cm³** for modeling mass properties. Volume is in mm³, mass in g, and centroidal inertia in g·mm². For a manual mass check, convert mm³ to cm³ before multiplying by density. The API already returns grams; do not convert its mass again. See the [numerical unit check](/packages/cad/modeling#a-numerical-unit-check). ## Face and edge names Selections use face and edge names, rather than display triangle numbers. A face name combines its feature and role; an edge name combines the names of its adjoining faces. These names let a fillet or chamfer follow parameter edits that keep the topology. Splitting, removing or replacing faces can change that topology, so a saved name alone does not guarantee the same selection. See [Names](/packages/cad/modeling#names). The Studio document stores geometry signatures with supported face and edge references. On open, it compares those signatures with the available geometry. A clear replacement is marked as re-matched for review. A missing or ambiguous match is reported; the affected feature can be held while the rest of the document builds. Review a re-matched selection, or pick the intended geometry again. This check concerns what a reference selects. It is separate from the document revision and export source records described below. ## Correct or refused When the kernel or the document model can't produce a result it can stand behind, it refuses with a reason. It doesn't return an approximate body or quietly skip a step. - **Kernel refusals.** These are a `CadPartError` with a code, such as `RADIUS_EXCEEDS_FACE`, and a category: `FORMAT`, `INPUT`, `PARAMETER`, `REFERENCE`, `SELECTION`, `CAPABILITY` or `GEOMETRY`. They name the feature they come from, and their message says what went wrong, for example that two inputs graze within the merge radius. - **Typed refusals** from the document model and the agent's tools begin with a code in brackets, so people and agents can both act on them. For example, `[FASTENER_SIZE_ROW] no row for M6 — load your fastener sizes …`. - **Unknown, not passed.** A check that lacks what it needs reports `unknown`, never `pass`. For example, a casting check with no casting rules loaded. [Refusal codes](/reference/refusals) lists them, and [How it is verified](/reference/verification) describes how results are checked against independent answers. ## Sizes come from your rows Nothing standard-like is built in: no thread table, no fastener catalogue, no casting allowances. Sizes come from **shop rows**, JSON files a person supplies, with each value naming its source. - In the studio, you load rows in **Library**, from your own file or from the samples that ship with `@barocss/cad-model` (`samples/rows/`). - In the chat, you attach the file. - The agent can suggest a file, but it can't load rows no person supplied. It is refused with `[ROWS_NOT_FROM_PERSON]`. - Each loaded row keeps a receipt naming its file. A placed part uses the rows of the document it is placed in. - Without the row a command needs, it is refused. A reading that has no row says so: no thread is drawn, no tap drill is given, and the position tolerance is an estimate. The samples are examples taken from the sources each row names, not a standard. Check them against your supplier before you use a part for manufacture. [Shop rows](/studio/rows) covers every row kind. ## The library's own values Library parts, such as an extrusion profile, a slot nut or an enclosure boss, carry their own dimensions, marked as the library's own estimates. They are not read from your rows. The T-slot parts' holes equal common M5 sizes; when your loaded fastener sizes give a different M5 value, the part's notes say so and name both. ## Revisions and sources - **A revision** is a 16-digit hex name for the state of the document that results depend on: - its features, parameters and outputs; - its rows, including fastener sizes and casting rules; - its frames and placed parts; - its brief, requirements and references; - its process, printing, moulding, machining and casting settings. Looks, such as appearances and render settings, aren't part of it. The same content always has the same revision. - **Every export names the revision it was made from.** - **STEP** has it in its `FILE_DESCRIPTION`. - **3MF** has it as `barocss:SourceRevision` metadata. - **A drawing's** title block has it as an **SRC** line beside your own REV. - **STL**, and the **URDF**, **MJCF**, **SDF** and **USD** robot exports, can't carry it in their bytes. They get a `.source.json` record beside them instead, which holds: - the revision; - a SHA-256 of the same canonical input content used for the revision, rather than the exported file's bytes; - the files it describes; - for a robot, the values set by hand: the base link and the joints' limits and ratings. Exporting the same part twice gives the same source. A STEP file differs only in its time stamp. - **A late result never replaces a newer one.** Each request to the modelling engine is tied to the thing it replaces: a command's preview, the section view, a part's drawing, one placed part's bodies. When a newer request for the same thing goes out, an older reply comes back stale and is dropped, whatever order the replies arrive in. Dragging a section plane fast leaves the last cut on screen, not an earlier one. --- # Robot motion: from a path to a pose Physics supports [continuous primitive rotation](/packages/physics/profiles-and-lifecycle#isolated-noncubic-rotor) for admitted boxes, spheres and capsules. This does not qualify connected robot joint dynamics. CAD proxy conversion, kinematic pose calculation and control accuracy require their own evidence. Use CAD Model to prescribe joint motion, calculate link poses and inspect limits. Use Physics to predict motion from initial conditions and applied loads within an admitted physical model. These operations have different inputs, outputs and verification requirements. The former `@barocss/motion` package is retired. The functions on this page belong to `@barocss/cad-model`. A sampled pose is not a command to a motor. ## Choose the calculation | Calculation | Input | Output | What it does not establish | |---|---|---|---| | Forward kinematics (FK) | Joint values and a joint tree | Link and tool poses | Forces, contact response or stability | | Inverse kinematics (IK) | A tool target, joint tree and optional start values | Joint values, residuals and `reached` | A clear path to the target or a unique solution | | Timed path | Joint waypoints and velocity/acceleration limits, with optional jerk | Duration and joint values at a time | Whether an actuator can follow that motion | | Clearance or sweep | Geometry and selected poses or a path | Distances, contact, or an incomplete check | Physical contact forces | | Statics and inverse dynamics | Mass/inertia, gravity and a prescribed pose or motion | Required joint holding effort or motion loads | Free motion from those loads | | Forward dynamics | A supported physical model, initial state and loads | State after a time step | General robot, controller or hardware acceptance | See [the Robot API](/packages/cad-model/#assembly-and-robot-motions), [the Studio robot workflow](/studio/robots) and [the kinematics algorithms](/how/cad-model#_2-robots) for their full contracts. ## Keep the units and frame explicit The `Robot` object uses **degrees for turns and mm for slides**. Path times are seconds. Velocity, acceleration and jerk use the joint's own units per second, second squared and second cubed. A `default` rate has each joint's own unit; a named joint rate overrides it. `RobotPath.poseAt(t)` returns joint inputs. Pass them to `robot.pose(values)` to obtain link positions in mm and rotations in degrees. These placements use the assembly's coordinates. Missing joint values mean zero at the solved home pose, rather than the previous waypoint's value. The lower-level FK/IK and timed-path functions use radians for turns and mm for slides and point positions. IK reports its position residual in metres and angle residual in radians. Do not pass degree values to `solveIk`, or convert a public `RobotPath.poseAt` reply a second time before `Robot.pose`. Read [Robot unit boundaries](/studio/robots#robot-unit-boundaries) before combining public MMGS mass/inertia reports with SI dynamics. Declare the gravity vector and frame; the robot gravity default is along -Z, while many Physics examples use -Y. A display adapter must make any frame change explicit. ## Time a turn and a slide together The following repository sample opens the shipped SCARA document. It uses its first turning joint and the quill's sliding joint. Other joints stay at their zero values. The file path is relative to `apps/library-docs/samples`; an application can instead supply its own `.bcad` document. ```js import assert from 'node:assert/strict'; import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { assembly, part, BarocssError } from '@barocss/cad-model/api'; ``` ```js // Repository sample: this file runs from apps/library-docs/samples. const samplePath = resolve(import.meta.dirname, '../../../packages/barocss-cad-model/samples/robots/scara.bcad'); const scaraDocument = JSON.parse(readFileSync(samplePath, 'utf8')); const scara = assembly('scara', part('scara', scaraDocument)).robot().setJoints({ joints: { 'base~arm1': { lower: -90, upper: 90, velocity: 60 }, 'arm2~quill': { lower: -40, upper: 40, velocity: 15 }, } }); const turn = 'base~arm1', slide = 'arm2~quill'; ``` Set the joint limits separately from the timing rates. Limits describe the allowed joint range. Rates describe how this particular path is timed. `setJoints` and `withMotion` return new robot objects; they keep the originals. ```js const waypoints = [ { [turn]: 0, [slide]: 0 }, { [turn]: 0, [slide]: 0 }, // Repeated waypoint: zero duration. { [turn]: 60, [slide]: -30 }, { [turn]: 0, [slide]: 0 }, ]; const limits = { default: { velocity: 60, acceleration: 120 }, // deg/s and deg/s² for a turn. [slide]: { velocity: 15, acceleration: 30 }, // mm/s and mm/s² for this slide. }; const path = scara.path(waypoints, { profile: 'trapezoid', limits }); const recorded = scara.withMotion('turn-and-lower', path); const motion = recorded.motion('turn-and-lower'); assert.deepEqual(motion.problems(), []); // The limiting slide takes 30/15 + 15/30 = 2.5 s, each way. assert.ok(Math.abs(motion.duration() - 5) <= 1e-12); ``` The turn travels 60° at a maximum 60°/s and 120°/s². The slide travels 30 mm at 15 mm/s and 30 mm/s². Each segment uses one normalized progress function shared by both joints. The tighter slide rate limits that progress to 0.5/s and its acceleration to 1/s². For a rest-to-rest trapezoid with distance d, speed v and acceleration a, duration is `d/v + v/a` when `d >= v²/a`. Here the slide takes `30/15 + 15/30 = 2.5 s`. The return takes another 2.5 s. The repeated initial waypoint adds zero time. Every nonzero segment starts and ends at rest; a waypoint join is not a blended robot corner. ### Read the joint inputs, then obtain the pose ```js const values = motion.poseAt(1.25); // Seconds. Returns degrees and mm. assert.ok(Math.abs(values[turn] - 30) <= 1e-9); assert.ok(Math.abs(values[slide] + 15) <= 1e-9); const pose = recorded.pose(values); // Link positions in mm, rotations in degrees. const quill = pose.links.find(link => link.link === 'quill'); assert.deepEqual(pose.out_of_limits, []); // After solving the mates, the quill origin is (225,25,-30), with pivot (40,40). const angle = 30 * Math.PI / 180; const analyticPoint = [40 + 185 * Math.cos(angle) + 15 * Math.sin(angle), 40 + 185 * Math.sin(angle) - 15 * Math.cos(angle), -45]; // Public pose positions are reported to six decimal places in mm. const expected = analyticPoint.map(value => Math.round(value * 1e6) / 1e6); quill.position.forEach((value, axis) => assert.ok(Math.abs(value - expected[axis]) <= 1e-9)); ``` At 1.25 s, the shared progress is one half: 30° and -15 mm. The example compares the quill origin with an independent rotation about the first joint's off-origin pivot. The mate solve places the home quill origin at `(225,25,-30)` mm; this differs from the document's initial unsolved instance position. Public link positions are rounded to six decimal places in mm. The example compares the analytic point at that same reporting precision, with a 1e-9 mm comparison tolerance. It records the difference from the unrounded analytic point separately. This does not establish full-precision FK accuracy from a rounded reply. That separate reporting difference must be at most 0.5e-6 mm per component, the half-step bound for six decimal places. It is not a wider numerical FK tolerance. The tests also sample both outward and return segments. This checks the stated kinematics and timing; it does not qualify a physical SCARA arm or certify clearance. Finite times before the start or after the end return the corresponding endpoint. Negative finite time is valid. NaN and infinite query times are refused. A zero-distance segment has no dwell time; add a separate supported timing or application rule if the operation needs a physical pause. ### Choose an S-curve when jerk is constrained ```js const smooth = scara.path([{ [turn]: 0, [slide]: 0 }, { [turn]: 60, [slide]: -30 }], { profile: 's-curve', limits: { default: { velocity: 60, acceleration: 120, jerk: 240 }, [slide]: { velocity: 15, acceleration: 30, jerk: 60 }, }, }); assert.deepEqual(smooth.problems(), []); const duration = smooth.duration(); const middle = smooth.poseAt(duration / 2); assert.ok(Math.abs(middle[turn] - 30) <= 1e-9); assert.ok(Math.abs(middle[slide] + 15) <= 1e-9); ``` An S-curve also needs positive jerk limits for every moving joint. It keeps the same joint-space line and synchronized start/end values, but changes the progress in time. This example takes 3 s rather than 2.5 s for the outward segment. A slower profile does not by itself establish acceptable motor torque, reducer life or control tracking. ### Inspect refusals before playback ```js const beyondTravel = scara.path([{}, { [slide]: -41 }], { limits }); assert.deepEqual(beyondTravel.problems().map(problem => problem.code), ['JOINT_LIMIT']); assert.throws(() => beyondTravel.poseAt(0), error => error instanceof BarocssError && error.code === 'JOINT_LIMIT'); assert.throws(() => motion.poseAt(NaN), error => error instanceof BarocssError && error.code === 'VALUE'); // A direct pose preview reports an out-of-limit value; it does not clamp it. assert.deepEqual(scara.pose({ [slide]: -41 }).out_of_limits, [slide]); ``` `problems()` returns path findings. `duration()` and `poseAt()` refuse an invalid path. A direct `robot.pose(...)` preview has a different contract: it reports out-of-limit joints and keeps the requested values. Inspect `out_of_limits` before treating a pose as admissible. Nonfinite joint values use `VALUE`. Nonfinite supplied rates use `LIMITS_BAD`. Missing or nonpositive required rates use `LIMITS_MISSING`. These codes are not a physical failure measurement. See [refusal codes](/reference/refusals). ## Solve a tool target with IK The `Robot` facade has no `ik()` method. The public `robot/ik` subpath exposes `solveIk(tree,target,start?)` for a joint tree. Its target is a rigid motion from the solved home pose, evaluated at the home tool point. It is not an absolute link placement record from `Robot.pose`. The following separate analytic tree has a Z turn and an X slide. It has no body geometry or collision model. The tool is 40 mm from the pivot at home. Its analytic target position is `[(40+s) cos(theta), (40+s) sin(theta), 0]` mm. ```js import { solveIk } from '@barocss/cad-model/robot/ik'; import { applyTo, forwardKinematics } from '@barocss/cad-model/robot/fk'; ``` ```js // A separate analytic RP tree. This is not the SCARA assembly or a collision model. const tree = { version: 1, base: 'base', links: ['base', 'arm', 'tool'].map(id => ({ id, name: id, part: id })), joints: [ { key: 'turn', type: 'revolute', parent: 'base', child: 'arm', origin: [0, 0, 0], axis: [0, 0, 1], limit: { lower: -Math.PI / 2, upper: Math.PI / 2 }, mates: [] }, { key: 'slide', type: 'prismatic', parent: 'arm', child: 'tool', origin: [40, 0, 0], axis: [1, 0, 0], limit: { lower: -20, upper: 80 }, mates: [] }, ], loops: [], couplings: [], problems: [], notes: [], }; const tool = [40, 0, 0]; // The tool point at the solved home pose, in mm. function targetMotion(angleRad, slideMm) { const c = Math.cos(angleRad), s = Math.sin(angleRad); return { R: Float64Array.of(c, -s, 0, s, c, 0, 0, 0, 1), t: Float64Array.of(slideMm * c, slideMm * s, 0) }; } ``` Inspect residuals and joint bounds, including when the target is reachable. The example checks three different targets, rather than accepting one successful pose as general IK qualification. ```js const metrics = []; for (const [degrees, travel] of [[-60, 25], [0, -10], [45, 60]]) { const angle = degrees * Math.PI / 180; const result = solveIk(tree, { link: 'tool', tool, motion: targetMotion(angle, travel) }); const q = result.q; // Radians for turn, mm for slide. const expectedPoint = [(40 + travel) * Math.cos(angle), (40 + travel) * Math.sin(angle), 0]; const actualPoint = [(40 + q.slide) * Math.cos(q.turn), (40 + q.slide) * Math.sin(q.turn), 0]; const errorM = Math.hypot(...actualPoint.map((v, i) => v - expectedPoint[i])) / 1000; const errorRad = Math.abs(Math.atan2(Math.sin(q.turn - angle), Math.cos(q.turn - angle))); assert.equal(result.reached, true); assert.ok(errorM <= 1e-4 && errorRad <= 1e-3); assert.ok(q.turn >= -Math.PI / 2 && q.turn <= Math.PI / 2); assert.ok(q.slide >= -20 && q.slide <= 80); assert.ok(Math.abs(result.errorM - errorM) <= 1e-9); assert.ok(Math.abs(result.errorRad - errorRad) <= 1e-7); const fk = forwardKinematics(tree, q); applyTo(fk.motions.get('tool'), tool).forEach((v, i) => assert.ok(Math.abs(v - actualPoint[i]) <= 1e-9)); assert.deepEqual(fk.outOfLimits, []); metrics.push({ targetDegrees: degrees, slideMm: travel, errorM, errorRad, fkErrorMm: Math.max(...applyTo(fk.motions.get('tool'), tool).map((v, i) => Math.abs(v - actualPoint[i]))) }); } ``` The example uses the solver's existing acceptance limits: 1e-4 m position and 1e-3 rad orientation. It calculates residuals from the returned joint values with independent scalar geometry. The tests also compare FK at those joint values and the solver's reported residuals. ### Retain an unreachable result ```js const targetAngle = Math.PI / 6; const result = solveIk(tree, { link: 'tool', tool, motion: targetMotion(targetAngle, 120) }); const q = result.q; const errorM = Math.hypot((40 + q.slide) * Math.cos(q.turn) - 160 * Math.cos(targetAngle), (40 + q.slide) * Math.sin(q.turn) - 160 * Math.sin(targetAngle)) / 1000; assert.equal(result.reached, false); assert.ok(errorM >= 0.0399); // At least about40mm outside the allowed radius. assert.deepEqual(forwardKinematics(tree, q).outOfLimits, []); ``` The requested slide is 120 mm, but its upper limit is 80 mm. The target radius is 160 mm; the allowed radius is at most 120 mm. The independent position residual remains at least about 40 mm. `reached:false` is a result to handle, not a reason to apply the target pose. Check `errorM`, `errorRad`, joint limits and singularity information for each solve. Reachability still does not establish a collision-free transition. ## Check geometry separately Use `RobotPath.check()` for its supported straight joint-space sweeps. Read each reply's `clear`, contact, `skipped` and possible `exhausted` fields. An empty path problem list does not run that sweep. A budget-exhausted sweep is incomplete, rather than clear. The facade's looped path check still refuses with `LOOP_OPEN`, even when looped playback is supported. For a current assembly pose, `assembly.clearance({near})` is asynchronous and reports display-mesh distances and any pending exact-overlap distinction. It is a separate calculation from path timing and physical collision response. See [assembly clearance](/packages/cad-model/#checking-assembly-clearance) and [robot path limits](/studio/robots#moving-it) before interpreting either result. ## Keep loads, dynamics and control separate `robot.gravity(...)` calculates the effort needed to hold the prescribed pose. Motion-load and actuator-sizing tools calculate demands along a prescribed trajectory. They do not advance free motion from applied torque. Their assumptions, material inputs and sourced ratings remain part of the result. Physics advances its admitted models from initial conditions and loads. Its reduced one-coordinate planar pendulum is separate from PhysicsWorld's joint solver. Numerical checks of that ODE do not implement the planned CAD-bound pendulum experiment workflow or arbitrary connected robot dynamics. Contact requires its own geometry and impulse checks. Feedback control also requires a defined plant, controller, sensing and tracking criteria. Sending commands to hardware adds its own calibration and measured acceptance. None of those stages follows from path playback, IK success or an export file. The original eight-box and two-hinge NO_GO records remain. Narrow contact construction checks do not establish long-term stack stability. Existing Physics, Studio and manufacturing HOLDs stay in force. Read [limits](/reference/limits#planned-physical-experiments) and [experiment evidence stages](/reference/verification#planned-experiment-evidence) before using a calculated motion as a physical prediction. --- # @barocss/cad The CAD kernel. It is a boundary-representation (B-rep) modeller with NURBS curves and surfaces, written in TypeScript, with no WebAssembly and no external geometry library. The studio, the document model and the agent's tools all run on it. - **Exact surfaces.** Planes, cylinders, cones, tori and B-spline surfaces stay exact through Booleans, fillets and offsets. - STEP is written from them. - Mass properties are integrated over them. The few curved bodies the quadrature can't integrate fall back to the tessellation, and their result says so (`method: 'tessellated'`), with an error bound. - **Stable names.** A part is a list of features. Faces are named by the feature and role that made them, such as `p.top` or `h.side0`. Those names are kept through every later feature, and through parameter edits that keep the topology. - **Correct or refused.** An operation gives a valid body, or a `CadPartError` saying why it can't. It doesn't return an approximate body. See [B-rep, robustness and refusals](/packages/cad/robustness). - **Meshes too.** Imported STL, OBJ and tessellated STEP bodies are faceted B-reps, with their own Booleans, holes and splits. ## Status and install Use `@barocss/cad` from the repository workspace. - **From the repository.** Use it from a checkout, as a workspace package. - **TypeScript sources.** Its entry point is the TypeScript source itself (`./src/index.ts`). Use it with a bundler or a TypeScript-aware runtime; there is no build step to run first. - **Two entry points.** - `@barocss/cad` is the core: the part document, its evaluation, and everything else the kernel does. - `@barocss/cad/api` is the [object facade](/packages/api) over it, for writing parts in code. ```js import { part } from '@barocss/cad/api'; // the object facade import { evaluateCadPart, CadPartError, checkOutput, reevaluate, massPropertiesOf } from '@barocss/cad'; // the core: the part document and its evaluation ``` ## A part in code A part is a JSON document: its units, its parameters, and its features in order. The facade's `part()` writes one, verb by verb, and `.doc` is the document. `evaluateCadPart` evaluates a document and returns a snapshot. Its `outputs` are the bodies no later feature consumes. ```js // A 60 × 40 × 8 plate with a Ø8 hole through it. const plate = part('plate') .box({ w: 60, d: 40, h: 8 }) .hole(body => body.faces().facing('+z'), { d: 8, x: 30, y: 20 }); const doc = plate.doc; // the part document: its features in order assert.deepEqual(doc.features.map(f => [f.id, f.kind]), [['sketch1', 'sketch'], ['extrude1', 'extrude'], ['hole1', 'hole']]); const snapshot = evaluateCadPart(doc); // what the facade evaluates const [body] = snapshot.outputs; // the parts no later feature consumes ``` The facade gives the results as plain data, in millimetres and grams. Each output of the snapshot also checks itself: ```js const mass = plate.mass({ density: 2.7 }); // aluminium: mm³, g, mm, g·mm² assert.ok(Math.abs(mass.volume - (60 * 40 * 8 - Math.PI * 16 * 8)) < 1e-6); assert.ok(Math.abs(mass.mass - mass.volume * 2.7e-3) < 1e-9); assert.equal(checkOutput(body).valid, true); // strict B-rep validity, on the core's output assert.match(plate.step(), /^ISO-10303-21;/); const stl = plate.stl(); // binary STL of the display tessellation assert.equal(stl.length, 84 + 50 * new DataView(stl.buffer, stl.byteOffset).getUint32(80, true)); ``` These samples run in `apps/library-docs` (`pnpm test:samples`), against the package's sources. ## Where next - [Modeling API](/packages/cad/modeling): the part document, evaluating, outputs and tessellation. - [B-rep, robustness and refusals](/packages/cad/robustness): what the kernel guarantees, and what it refuses. - [Exchange formats](/packages/cad/formats): STEP, IGES, STL and DXF. - [@barocss/cad-model](/packages/cad-model/): the studio's document model on top of the kernel. --- # Modeling API ## The part document A part is a `barocss-cad-part` document: ```json { "format": "barocss-cad-part", "version": 1, "units": "mm", "parameters": { "t": 8 }, "features": [ { "id": "s", "kind": "sketch", "profile": "rectangle", "min": [0, 0], "max": [60, 40] }, { "id": "p", "kind": "extrude", "sketch": "s", "height": { "parameter": "t" } } ] } ``` - **Features in order.** Each feature has an `id` and a `kind`, and names the features it builds on by their ids: `sketch`, `target`, `tool`. - **Dimensions.** A dimension is a number, or `{ "parameter": "name" }` bound to one of the document's parameters. - **Units.** Lengths are millimetres. Public and document angles are degrees. Z is up. - **The reference.** The full set of kinds and their fields is the `CadPartFeature` type, which the package exports. Sketch profile points use local XY coordinates. Without `plane`, these are part XY at Z = 0. With `plane`, local X follows `xAxis`, local Y follows `normal × xAxis`, and local Z follows `normal`, from `origin`. An `extrude` runs from local Z = `from` (default 0) to `from + height`; these are offsets along the sketch normal. A negative `height` extrudes in the opposite direction. Zero height is refused. The kinds, by family: | Family | Kinds | |---|---| | Sketches and solids from them | `sketch` (rectangle, circle, polygon and loop profiles of lines and arcs, with holes, on a plane), `extrude`, `revolve`, `sweep`, `sweep-curve`, `loft` | | Booleans | `union`, `difference`, `intersect` | | Holes and finishing | `hole`, `thread`, `fillet`, `chamfer`, `draft`, `shell`, `thicken`, `split`, `split-face` | | Copies and moves | `linear-pattern`, `circular-pattern`, `mirror`, `translate`, `rotate`, `scale` | | Meshes and imports | `mesh`, `decimate`, `sew`, `separate`, `import` (a STEP file) | | Smooth shapes | `subd` (a subdivision cage, as exact B-spline faces) | | Sheet metal | `sheet-base`, `sheet-flange`, `sheet-path-flange`, `sheet-bead`, `sheet-perforate`, `sheet-contour`, `sheet-corner-relief` | | Frames and weldments | `frame`, `frame-member`, `gusset`, `end-cap`, `weld-bead` | | Machine elements | `spur-gear`, `spur-rack`, `internal-gear`, `bevel-gear`, `worm`, `worm-wheel`, `shaft`, `key`, `keyway`, `pin`, `retaining-ring`, `bearing`, `oring`, `oring-gland`, `pulley`, `sprocket`, `belt`, `spring`, `cam`, `coupling`, `connector-body`, `connector-opening` | ### Names - **Faces.** A face is named `.`, for example `p.top`, `p.side0` or `h.side0`. - **Splits and copies.** When a later feature splits a face, its pieces are `#k`. Copies are `@k` (patterns) and `@m` (kept mirrors). - **Edges.** An edge is named by its two faces: `p.side0|p.top`. - **References.** A feature's `id` means all of its parts, and `id/k` means part `k`, one side of a split. Fillets and chamfers pick edges by these names, so a selection survives parameter edits that keep the topology. ### Boolean algorithms `union`, `difference` and `intersect` select solid material from a target and a tool. Their implementation depends on the input representation: height-wise 2D arrangements, rational polyhedral operations, trimmed-surface intersections, or a mixed mesh path. See [Boolean operations](/packages/cad/robustness#boolean-operations) for a tested example, the algorithm stages, tolerances and refusal conditions. ## Evaluating ```ts evaluateCadPart(document, previous?, options?): CadPartSnapshot loadCadPart(text): CadPartSnapshot // JSON text, at most 4 MiB emptyCadPart(): CadPartDocument ``` A snapshot holds: - `outputs`: the parts no later feature consumes, in feature order. `outputOf(snapshot, id)` gets one by id. - `features`: each feature's id, kind and dependencies. - `recomputation`: the features computed in this evaluation, and those reused unchanged. Snapshots and outputs are plain data. Import these functions from `@barocss/cad`: - `reevaluate(snapshot, { parameters: edits })`: evaluates new parameter values and reuses unchanged features. - `reevaluate(snapshot, { document })`: evaluates another document and reuses unchanged features. - `saveCadPart(snapshot)`: returns the document as text. ```js const thicker = reevaluate(first, { parameters: { t: 10 } }); assert.ok(Math.abs(massPropertiesOf(thicker.outputs[0], 2.7).volume - 60 * 40 * 10) < 1e-6); assert.deepEqual(thicker.recomputation.evaluated, ['p']); // only the extrude ran again ``` ## Outputs Each output is one body, or several with `bodyCount`, as a B-rep (`brep`). - **Representation.** It is one of: - `upright`: a Z-prismatic solid, with closed-form mass; - `planar`; - `curved`; - `faceted`: a mesh body. - **Mass properties.** `massPropertiesOf(output, density)` takes density in g/cm³ and returns: - `volume` in mm³, `mass` in g and `centroid` in mm; - `inertia` in g·mm², about the centroid; - `method`: `closed-form`, `planar-exact`, `quadrature` or `tessellated`. A tessellated result carries `volumeBound`, its estimated volume error in mm³. - **Validity.** `checkOutput(output)` gives the strict validity report: `valid`, the first `issues`, the counts and topology, and the largest gaps. - **Surface area.** `surfaceAreaOf(output)` is in mm², over the exact surfaces. - **STEP.** `exportStep(output, { name })` writes the exact B-rep as STEP AP214. - **STL.** `exportStl(output, { segmentsPerQuarter })` writes the display tessellation as binary STL. - **Sheet metal.** `flatPatternOf(output, { fixedFace, kFactor })` returns a sheet-metal flat pattern. - **Reports.** Gears, racks and other generated parts carry a report of their own, such as `gear`. ### Moment of inertia about an axis Import `momentOfInertiaAboutAxis` and the `MassInertiaAxis` type from `@barocss/cad`. The function takes mass properties and an axis, and returns a number in g·mm². Supply a full 3 × 3 inertia tensor about the centre of mass in g·mm², positive finite mass in g and the centroid in mm. The axis requires a `point` in mm and a finite, nonzero `direction`. Use dense arrays of finite numbers: three components per vector and three rows of three for the tensor. Use the same XYZ frame for the axis and mass properties. The function normalizes the direction, so its magnitude does not change the axis. With unit direction `u` and offset `d = centroid − point`, the result is `uᵀ I_COM u + mass × |d × u|²`. The second term shifts the moment from the parallel axis through the centre of mass to the requested line. Invalid input arrays, non-finite arithmetic or a negative central inertia projection give `SOLID_MASS`. This query uses the supplied mass properties; it provides no frame or SI conversion, B-rep evaluation, motion simulation or physical validation. ### A numerical unit check For a 10 × 10 × 10 mm cube at density 2.7 g/cm³: - Volume is 1000 mm³. - Mass is 1000 × 2.7 / 1000 = 2.7 g. - The centroid is [5, 5, 5] mm. - Each diagonal centroidal inertia is 2.7 × (10² + 10²) / 12 = 45 g·mm². Off-diagonal terms are zero. The kernel already returns these units. Do not convert its mass or inertia a second time. ```js const snapshot = evaluateCadPart(cube); const body = outputOf(snapshot, 'p'); const result = massPropertiesOf(body, 2.7); // density g/cm³ near(result.volume, 1000); // mm³ near(result.mass, 2.7); // g result.centroid.forEach(value => near(value, 5)); // mm result.inertia.forEach((row, i) => row.forEach((value, j) => near(value, i === j ? 45 : 0))); // g·mm² ``` ## Tessellation The display mesh, and the STL written from it, is a tessellation of the exact surfaces. `segmentsPerQuarter` sets how finely curves are divided. Measurements and STEP never use the tessellation, except for a `tessellated` mass result. --- # B-rep, robustness and refusals ## Booleans, fillets and offsets on exact surfaces Each solid output is a B-rep: surfaces, boundary curves and the topology that joins them. Native faces retain their surfaces; mesh inputs retain faceted faces. The Boolean algorithm depends on that representation. - **Booleans.** `union`, `difference` and `intersect` use a prismatic, polyhedral, analytic or mixed mesh path, as described below. - **Fillets and chamfers** roll a ball along the named edges, or cut them back, on the exact faces either side. - **Offsets.** `shell`, `thicken` and `draft` offset or tilt faces on their surfaces. In a kernel part document, `draft` accepts `pull: 'x'`, `'y'`, `'z'`, `'-x'`, `'-y'` or `'-z'` for a signed world coordinate axis. Omitting `pull` selects +Z. A positive `angle` leans into the material; a negative angle leans out. `neutral` is the plane's coordinate in mm on the selected world X, Y or Z axis, not a distance from the picked face. If omitted, it uses the body's minimum coordinate for a positive pull or maximum coordinate for a negative pull. Do not negate an explicit `neutral` value just because the pull axis is negative. Arbitrary pull vectors remain unsupported. These axis choices do not establish general curved-face support or manufacturing validation. For the standalone `kind: 'draft'` feature, `angle` must be finite and satisfy `0 < |angle| < 45` degrees; otherwise it gives `INPUT`. The neutral plane must be at or below the entire selected face for a positive pull, or at or above it for a negative pull, within the existing 1e-6 mm plane tolerance. The face must extend a positive distance from that plane along the pull direction; violations of these placement or height conditions give `SELECTION`. ### Mesh conversion values `brepFromTriangles` creates its own planar faces. It fixes properties on the returned B-rep, face and surface records, plus the face list and knot arrays. Record properties such as `edges`, `vertices`, `controlPoints` and `weights` cannot be rebound. The remaining nested data, including coordinate and weight arrays, is not frozen by this step. The input positions and indices are not frozen. Create a deep copy before changing its face, degree or knot structure, for example with `structuredClone(brep)`. A shallow copy can still share the fixed records and knot arrays. Copies and transforms are checked independently. Existing numeric caches treat a B-rep as a value; use a new value after editing coordinates too. The fixed structure lets the kernel exclude this mesh conversion from one specific boundary check without reading every face again. It does not certify its geometry, mass or general surface bindings. Caller-created B-reps and faceted patches retain their existing ownership. A separate exact lower-bound check rejects a supported extruded piecewise-linear graph when a straight incident edge is proved farther from the surface than its declared tolerance. Other surface families keep their existing checks. ### A draft calculated from its dimensions Calculated geometry; the diagram is not an API render. Start with a rectangle from `[0, 0]` to `[20, 20]` mm and extrude it 10 mm along +Z. The box occupies `0 ≤ x ≤ 20`, `0 ≤ y ≤ 20`, `0 ≤ z ≤ 10`. Its initial volume is 4000 mm³. The sketch has ID `s`, its extrusion has ID `e`, and the draft has its own ID `d`. The draft's `target: 'e'` selects the extrusion to modify; `faces: ['e.side0']` selects one of its faces. This is a kernel part-document input, not a new Studio control. ```json { "format": "barocss-cad-part", "version": 1, "units": "mm", "parameters": {}, "features": [ { "id": "s", "kind": "sketch", "profile": "rectangle", "min": [0, 0], "max": [20, 20] }, { "id": "e", "kind": "extrude", "sketch": "s", "height": 10 }, { "id": "d", "kind": "draft", "target": "e", "faces": ["e.side0"], "angle": 10, "pull": "z", "neutral": 0 } ] } ``` The extrusion consumes sketch `s`; the draft consumes extrusion `e`. The final solid output is `d`, not a second independent copy of `e`. The first rectangle edge runs from `[0, 0]` to `[20, 0]`, so `e.side0` is the face at y = 0 with outward normal −Y. The positive draft removes material: the upper edge moves toward +Y, into the box. X coordinates do not change. ![Calculated Y–Z section, not an API result](/diagrams/cad/draft-section.svg) For the ideal neutral plane z = 0, the drafted face is `y = z tan(10°)`. At z = 10 mm, its inward movement is `10 tan(10°) ≈ 1.763270 mm`. The remaining top width along Y is about 18.236730 mm. The removed triangular prism has volume `½ × 10 × 1.763269807 × 20 ≈ 176.326981 mm³`. The nominal remaining volume is about 3823.673019 mm³. These are calculated values, not values returned by an API call. The implementation shifts the cutting plane slightly below the specified neutral plane to avoid line-only contact. Here `R = √(20² + 20² + 10²) + 2 = 32 mm` and `lift = 10⁻⁶ R = 0.000032 mm`. Its cutting plane therefore follows `y = (z + 0.000032) tan(10°)`, not exactly the ideal hinge line. The source plane predicts about 0.000005642 mm inward movement at z = 0 and 1.763275450 mm at z = 10. Integrating this shifted plane gives about 3823.671891 mm³ before Boolean and numerical effects. Both volumes are analytical calculations. An evaluated kernel result also includes Boolean and numerical effects. The selected face must be planar, parallel to the pull direction and have no holes. This example changes only one face. It does not claim support for adjacent selected draft faces, arbitrary pull vectors or negative pull axes. ## Guided conic lofts A `loft` document feature can use one `guide` with `kind: 'quadratic-bezier'` and exactly three world-space `controlPoints`, in mm. Each section must be a full circle or an inline ellipse. Use exactly two explicit frames with identical `xAxis` and `yAxis`, and positive separation along their common normal. Put `guide` on the `loft` feature beside `id`, `kind` and `sections`. Each section needs its own `frame` with `origin`, `xAxis` and `yAxis`. The axes must be perpendicular unit vectors. For a circle, use `sketch` to reference an existing circle sketch. For an inline ellipse, use `profile` with `kind: 'ellipse'`, `center` and two positive `radii`. Use either `sketch` or `profile` in each section, never both. These sections do not use `z`. The guide object accepts only `kind` and `controlPoints`. Each control point must contain exactly three finite numbers. The guide starts and ends at the sections' positive local X seams. Both endpoints must match exactly. Its middle control point must lie exactly on the plane halfway between the section planes. The kernel does not snap or project these points. The guide adds a quadratic transverse displacement to each intermediate section. The section stays circular or elliptical, with radii that vary linearly between the caps. The side surfaces retain exact rational conic curves and quadratic control points along the guide. Mass properties use section integrals, not the display mesh. For example, unit circles at Z = 0 and Z = 3 can use guide controls `[[1, 0, 0], [3, 0, 1.5], [1, 0, 3]]`. At the middle section, the circle centre is `[1, 0, 1.5]`. The guide's middle control point is not a point that the curve passes through. This option rejects polygon or mixed profiles, legacy `z` sections, differing frame axes, `smooth: true`, more than two sections, and multiple or general rails. All controls and generated surface controls must remain within the existing modeling coordinate range. ### Candidate: three-section conic lofts A source candidate extends the unguided conic loft to three sections. It is not yet integrated into the product or verified by execution. The two-section guided contract above is unchanged. Each section is a full circle or inline ellipse on an explicit frame. All three frames must have identical `xAxis` and `yAxis`, with positive separation between each adjacent pair of planes. The candidate joins each adjacent pair with ruled sides. Both spans share the middle section's boundary; only the first and last sections have caps, forming one solid rather than two separately capped bodies. The three-section path rejects a guide, `smooth: true`, polygon or mixed profiles, and legacy `z` sections. It does not provide a general multi-section or smooth loft. In particular, adding a third section does not extend the quadratic guide to three sections. ## Boolean operations Let A be the target body and B the tool body. The operation selects the solid material to keep: | Document feature | Object API method | Material kept | |---|---|---| | `union` | `union(tool)` | Material in A or B, counting the overlap once | | `difference` | `subtract(tool)` | Material in A that is outside B; reversing A and B changes the result | | `intersect` | `intersect(tool)` | Material common to A and B | ### From numbers to a solid result Start with a box whose X, Y and Z coordinates each run from 0 to 10 mm. Its six plane boundaries enclose 1000 mm³. The tool is another box, or a cylinder defined by its XY centre, radius and height. Move B along X and choose an operation. The solid view shows the inputs; the XY view shows the material selected by the operation. For the cylinder at its initial centre (8, 5) with radius 3, the wall meets the box's X = 10 plane where `(10 − 8)² + (y − 5)² = 9`: at Y = 5 ± √5, or about 2.764 and 7.236 mm. These crossing points split the boundaries. The inside/outside rule then selects regions, and their 10 mm height turns the selected area into volume. ### Build the result in 3D, one stage at a time Choose a fixed 3D example and an operation below. Start at **Input solids**, then follow the five pictures to the final shape. Drag the large view to rotate it. The same camera direction is used for every picture, so you can compare the cuts. These fixed cases have separate dimensions from the moving section example above. ### A checked code example For two 10 × 10 × 10 mm cubes offset 5 mm along X, the overlap is 5 × 10 × 10 = 500 mm³. The union is 1000 + 1000 − 500 = 1500 mm³; the difference and intersection are each 500 mm³. This example runs with the site's samples and checks the three resulting bodies' validity: ```js import { part as cadPart } from '@barocss/cad/api'; ``` The helper below is an independent volume oracle for these boxes. Their planar display triangles have integer coordinates. Summing signed tetrahedra with integer arithmetic checks the volumes without a floating-point equality test on the mass result. It is not a general volume method for curved bodies or non-integer meshes. ```js // Independent volume check for this integer-coordinate, planar example only. // Each oriented triangle contributes det(a, b, c) / 6, the signed volume to the origin. function integerMeshVolume(p) { let six = 0n; for (const mesh of p.meshes()) { const P = []; for (const x of mesh.positions) { assert.ok(Number.isSafeInteger(x)); P.push(BigInt(x)); } for (let t = 0; t < mesh.indices.length; t += 3) { const a = 3 * mesh.indices[t], b = 3 * mesh.indices[t + 1], c = 3 * mesh.indices[t + 2]; six += P[a] * (P[b + 1] * P[c + 2] - P[b + 2] * P[c + 1]) - P[a + 1] * (P[b] * P[c + 2] - P[b + 2] * P[c]) + P[a + 2] * (P[b] * P[c + 1] - P[b + 1] * P[c]); } } assert.equal(six % 6n, 0n); return Number((six < 0n ? -six : six) / 6n); } ``` ```js const target = cadPart('overlap').box({ w: 10, d: 10, h: 10 }); const tool = p => p.box({ w: 10, d: 10, h: 10, x: 5 }); const joined = target.union(tool); const cut = target.subtract(tool); // the document's difference const common = target.intersect(tool); assert.equal(integerMeshVolume(joined), 1500); assert.equal(integerMeshVolume(cut), 500); assert.equal(integerMeshVolume(common), 500); assert.equal(integerMeshVolume(target), 1000); // the input is unchanged ``` The callback adds the tool to the target's document. Each operation returns a new part. See [Several bodies](/packages/api#several-bodies) for tools by body name and the callback rules. An intersection of disjoint solids is empty. Empty operands keep the set rules: union with empty keeps the other operand, subtracting empty keeps A, and intersection with empty is empty. An empty target minus B stays empty. ## How the kernel chooses the algorithm The part evaluator chooses from the current representations, rather than from the feature's name alone. A rotated or imported body can therefore take a different path from an upright extrusion. | Inputs | Path | |---|---| | Both represented as Z-prismatic solids | Split into height intervals; run a 2D Boolean on each pair of sections | | Both have planar faces with straight edges | Try the exact rational polyhedral Boolean | | Other native B-reps | Intersect surface pairs, split their face domains, classify and stitch the retained pieces | | A mesh target with a native tool | Cut out the mesh region near the tool, process it with the native tool and rejoin the far mesh | The mixed path also handles union and intersection with the mesh on the tool side, by swapping operands. Subtraction keeps operand order. A native target minus a mesh tool, or two mesh operands, instead expands facet faces into planar triangles before the remaining dispatch. This expansion is limited to 16,000 triangles per expanded operand in a normal evaluation; a preview can set a lower limit. Larger cases are refused. ### 1. Z-prismatic solids: Boolean sections, then rebuild the boundary A prismatic solid is a stack of height intervals. Each interval has a constant XY section made of lines and circular arcs, including holes. 1. Collect every bottom and top height from both operands and sort the distinct levels. 2. For each interval between adjacent levels, read A's and B's sections. Run the requested 2D Boolean on them. 3. In the 2D arrangement, split curves at their crossings and merge coincident pieces. Order the directed edges around each vertex, trace regions and propagate winding counts from the outside region. Select regions by the operation. 4. Merge adjacent height intervals with equal sections. Build walls from their boundary curves, and horizontal caps where the section changes. Join shared edges into shells and assign cavity shells to their containing solids. Circular boundaries stay circular. Their intersections can be irrational numbers, so the 2D arrangement uses binary64 arithmetic and the scale-dependent numeric tolerance. This reduction avoids a general 3D surface-intersection search; it does not make every coordinate calculation rational or error-free. Step by step, with figures: [Booleans of upright extrusions](/how/prismatic). ### 2. Planar polyhedra: split, classify and stitch with rational arithmetic This path works on planar faces bounded by straight edges, including non-convex faces, holes and cavities. 1. For each pair of faces that meet, compute the intersection of their planes. Clip that line to both faces to obtain cut segments. Coplanar faces cut each other along their boundary edges. 2. Split each face by its cut segments using a planar arrangement. 3. Classify an interior point of each face piece against the other solid. Ray-crossing parity decides inside or outside; a degenerate ray is retried. Coincident pieces are also classified by their orientation. 4. Keep the pieces selected by the operation. Reverse retained tool-side pieces for subtraction, so cavity walls face the right way. Split T-junctions, join matching edges and form shells. Negative-volume shells become cavities of the smallest containing shell. Coordinates enter as their exact binary64 values, converted to integer fractions with `BigInt`. The polyhedral path uses exact rational predicates and intersections for those values. Results return to stored numeric coordinates; this does not recover precision already lost before the operation. Step by step, with figures: [Exact arithmetic for planar solids](/how/exact-boolean). A nominally planar face rotated in floating-point arithmetic can have corners that are no longer exactly coplanar. Only the `NOT_PLANAR_WITHIN_FLOAT` failure retries the pair through the analytic path. Other polyhedral failures are passed through. ### 3. Curved B-reps: intersect the surfaces and trim their face domains The analytic path retains each face's surface and changes the boundary that trims it. It first rejects face pairs whose bounding boxes do not meet, then computes cuts for the remaining pairs. - Plane/plane and supported plane/cylinder or cylinder/cylinder pairs use their geometric intersection formulas. Their curves can be lines, circles, ellipses or parametrised branches. - General surface pairs use a surface-intersection search. Coarse patch triangles supply candidate starting points. Each point is refined onto both surfaces. A predictor follows the intersection tangent, the cross product of the two surface normals; a Newton corrector returns the point to both surfaces. Tracing continues in both directions until it reaches a domain boundary or closes a loop. - Each cut is mapped into both faces' 2D parameter domains. A plane uses a local plane frame; a cylinder uses angle scaled by radius and axial height; a general surface uses scaled U/V coordinates. The curve arrangement splits each trimmed domain into pieces. - The pieces are classified against the other solid and selected as below. Matching boundary pieces are joined into shells. The code handles coincident surfaces separately, so their boundaries are not kept twice. | Operation | Pieces away from coincident boundaries | |---|---| | Union | Keep each operand's pieces outside the other | | Intersection | Keep each operand's pieces inside the other | | Difference A − B | Keep A's outside pieces and B's inside pieces; reverse B's pieces | For a same-oriented coincident patch, union and intersection retain one copy. Difference removes that shared patch; an oppositely oriented contact on A is handled separately. Tangencies need additional classification and manifold checks. The surface remains a native surface, but a general intersection edge can be a fitted cubic Bézier chain. The path uses binary64 calculations, Newton iteration and numeric tolerances; it is not an exact-arithmetic solution for every NURBS pair. A tighter requested edge fit is checked and can refuse the result; it does not relax topology tolerances. Step by step, with figures: [Booleans of curved solids](/how/boolean). ### 4. Mesh with a native tool: process the nearby mesh For a mesh target with a native tool, the mixed algorithm limits the expensive face operation to the affected region: 1. Split the mesh against a padded box around the tool. Keep the far triangles aside and cap the nearby region for the Boolean. 2. Convert the nearby triangles to planar faces and run the analytic Boolean with the native tool. A normal evaluation admits at most 16,000 nearby mesh triangles; the total mesh can be larger. Open or self-intersecting meshes are refused. 3. Tessellate the nearby result, remove temporary caps and join it to the far mesh. Intersection discards the far mesh. 4. Repair boundary T-junctions and rebuild the facet body. Restore native tool surfaces on the faces that came from them; the rim against the mesh remains a polyline with recorded chord-deviation tolerances. This path preserves the mesh representation of the input. It does not turn a scanned surface into an exact smooth surface. The nearby-triangle limit and the facet-expansion limit above apply to different stages. Step by step, with figures: [Meshes, native tools and the BVH](/how/mesh-boolean). ### More complex shapes: what changes The five 3D examples show three sources of complexity: - **Different height ranges.** Two offset boxes do not use one shared section for the whole height. In the first 3D example the levels are 0, 2, 10 and 12 mm. Only the middle interval contains both solids. Its overlap is 5 × 7 × 8 = 280 mm³. Rebuilding the boundary must also close the steps at Z = 2 and Z = 10. - **Several loops and bodies.** The plate example uses `A − (B₁ ∪ B₂)`. Its cap is one outer rectangle with two inner circles. The hole walls must connect the two caps with reversed cutter-side orientation. The plate remains one body; its intersection with the two cutters has two bodies. A single feature result can therefore contain several bodies. - **A section that changes continuously.** Tilting a circular cutter makes elliptical cuts on the plate caps. For the 30° cutter shown above, each ellipse has semiaxes 2 / cos 30° ≈ 2.309 mm and 2 mm. Its centre is at X = (Z − 4) tan 30°: about −2.309 mm on the bottom and +2.309 mm on the top. One constant XY section is insufficient. The **crossing cylinders** example goes further. Their wall equations are `x² + y² = 16` and `y² + z² = 6.25`. Subtracting them gives `x² − z² = 9.75`. Points on their common curve must satisfy both original equations. The curve runs through space on two curved faces. Each cylinder needs its own angle/height coordinates to split its face domain. The final model retains cylindrical surfaces bounded by these spatial curves; the viewer displays triangles. For a general pair of smooth B-spline or NURBS faces, a single circle or ellipse formula may not exist. The kernel uses candidate patches, refinement and tracing as described in [Curved B-reps](#_3-curved-b-reps-intersect-the-surfaces-and-trim-their-face-domains). A surface intersection point must lie on both surfaces: `Sₐ(u,v) = Sᵦ(s,t)`. Tracing uses both parameter pairs. The cross product of their surface normals gives a tangent direction when those normals are not parallel. Tangencies, small loops, seams and a curve leaving a trimmed domain need separate handling. Unsupported cases can refuse. For scanned or faceted shapes, use the [mixed mesh path](#_4-mesh-with-a-native-tool-process-the-nearby-mesh). A dense scan has many candidate triangles; clipping the nearby region limits the work. A mesh cutter still has planar facets. Adding display triangles does not recover an exact cylinder or smooth surface from that mesh. Boolean order also matters. `A − (B ∪ C)` cuts both tools from A. `(A − B) ∪ C` adds C after the first cut. An empty result, a disconnected result, a cavity and an invalid self-touching boundary are different outcomes. A successful picture for one fixed case does not establish support for all inputs of that surface family. ### Result names, contact and tolerances Retained faces keep their source names. Split pieces receive `#k` suffixes, and edges are named from their two faces. These names let later operations refer to the result, subject to the reference checks described under [Names](/packages/cad/modeling#names). Separate lumps that meet only at an edge or point can remain separate bodies in one output. A single boundary that touches itself and cannot form a manifold solid is refused. A tolerance used to compare points is different from a recorded edge-fit error; neither is a licence to accept an unsupported topology. Display tessellation density controls the display and STL. It does not select the native Boolean algorithm. The mesh path has its own sampling and tolerance work because a mesh is already part of its input. ### Implementation map These are the current source paths under `packages/barocss-cad/src/`: | Source | Responsibility | |---|---| | `part/part-model.ts` | Dispatch, empty operands, planar retry and mixed mesh operand order | | `features/prismatic-solid.ts` | Height intervals and B-rep reconstruction | | `brep/curved-arrangement.ts` | Line, arc and parametric-curve arrangements in 2D | | `brep/polyhedral-boolean.ts` | Rational planar intersections, classification and shell assembly | | `brep/analytic-boolean.ts` | Surface cuts, face-domain splitting, classification and stitching | | `intersect/surface-intersection.ts` | Predictor/corrector intersection tracing | | `mesh/facet-boolean.ts` | Nearby mesh/native processing and reconstruction | ## Candidate: small-cap conical chamfer A source candidate adds a chamfer to the complete outer rim where the smaller planar cap meets the conical wall of one solid frustum. It is not integrated into the product, and its execution checks have not been completed. Select a named edge on that closed circular rim. If the rim is represented by joined edge pieces, selecting one piece applies the finish around the complete circle; it does not request a partial chamfer. The distance is in mm, measured from the original corner along each adjoining face in the axial section. It must be finite and positive. Both contact points must stay strictly inside their faces, with clearance from the other cap and the rotation axis. A distance equal to a support limit is refused; reaching the axis is not allowed. This candidate excludes partial revolutions, the larger bottom rim, concave corners, hollow bodies and bodies that are not one closed solid frustum. Here “top” means the smaller cap relative to the frustum's axis, not world Z. The direct finishing operation reports an unsupported scope as `GEOMETRY` with `CONE_TOP_CHAMFER_SCOPE` in its message, and an inadmissible distance as `INPUT` with `CONE_TOP_CHAMFER_SIZE` in its message. These message tags do not replace the error's `code`. Other conical edges remain outside this candidate's supported scope. ## Strict validity and typed refusals `checkOutput(output)` runs the strict check on an output. It checks: - the topology: closed shells, each edge used twice; - that edges lie on their surfaces; - that loops don't cross; - that there are no slivers; - that tolerances stay under their cap. The report gives `valid`, the first issues, the counts, each body's topology (shells and genus) and the largest gaps. An operation the kernel can't complete correctly throws a `CadPartError` instead. It has: - **`code`**: the specific code its message starts with in brackets, such as `RADIUS_EXCEEDS_FACE`, or, when it has none, its category; - **`details.category`**: one of `FORMAT`, `INPUT`, `PARAMETER`, `REFERENCE`, `SELECTION`, `CAPABILITY` or `GEOMETRY`; - **`feature`**: the id of the feature it comes from; - **a message** saying what went wrong, and what would work. ```js const tooLarge = refusal(part([...block('a', [0, 0], [10, 10]), { id: 'f', kind: 'fillet', target: 'a', edges: ['a.side0|a.top'], radius: 50 }])); assert.equal(tooLarge.code, 'RADIUS_EXCEEDS_FACE'); // the specific code its message carries assert.equal(tooLarge.details.category, 'PARAMETER'); // and the kind of refusal it is assert.equal(tooLarge.feature, 'f'); assert.match(tooLarge.message, /\[RADIUS_EXCEEDS_FACE\] edge a\.side0\|a\.top: fillet 50 mm is too large for walls of 10 and 10 mm/); const missing = refusal(part([...block('a', [0, 0], [10, 10]), { id: 'f', kind: 'fillet', target: 'a', edges: ['a.side9|a.top'], radius: 1 }])); assert.equal(missing.code, 'SELECTION'); // no specific code: the category assert.equal(missing.details.category, 'SELECTION'); assert.match(missing.message, /no edge named a\.side9\|a\.top; edges: a\.bottom\|a\.side0, /); // and the edges there are ``` An unsupported native operation is refused instead of silently replacing the body with a display mesh. Supported curve fitting and mesh operations keep their own numeric tolerances, as described above. ## Touching lumps as separate bodies When a Boolean leaves pieces that touch only along an edge or at a point, they stay separate bodies of one output. They aren't welded into a body whose edge is shared by four faces, and they aren't refused. ```js const snapshot = evaluateCadPart(part([...block('a', [0, 0], [10, 10]), ...block('b', [10, 10], [20, 20]), { id: 'u', kind: 'union', target: 'a', tool: 'b' }])); const [joined] = snapshot.outputs; assert.equal(joined.bodyCount, 2); // not welded along the shared edge assert.equal(checkOutput(joined).valid, true); ``` The studio carries this through: such a body exports as one STL file per piece, or as separate 3MF objects. ## How it is checked - **Conformance.** `conformance/` holds over 400 cases in folders named by the roadmap step that added them. A case that a later step superseded is kept as the record, but not run. - Each case is a part document and what any correct implementation must produce: volume, centroid, area, bodies, topology, face names, a watertight tessellation, a STEP round trip, sheet-metal and frame reports, or the error it is refused with. - Each case says where its expected values come from: closed form, an independent tool, or this kernel. - `test/conformance.test.mjs` checks every case. - **The robustness runner** (`pnpm rb`) puts every conformance case and the seed corpus (`robustness/corpus/`) through the kernel. Each case runs in a worker under a time limit. The runner prints pass rates by stage and category, marks known failures as TODO, and fails on any failure that is new. - **Properties** (`pnpm rb:props`): generated inputs checked against stated properties, with the smallest counterexample when one fails. - **The fuzz** (`pnpm rb:fuzz`): - It runs seeded random CSG trees, each checked against an independent ray-casting oracle: valid, watertight, and with its volume and centroid within the oracle's bounds. - Each case is OK, KNOWN or REFUSED (counted by code). Anything else is a finding: WRONG, INVALID, CRASH or TIMEOUT. - A finding is shrunk to its smallest tree and can be saved as a replayable case. These need the built package (`pnpm build:library`). [How it is verified](/reference/verification) covers the studio's checks too. --- # Exchange formats ## File contents and reports from code These functions work on caller-supplied data. They do not open files, download results or save a document. Keep the report with the result; a report object is not the file content. | Function | Result and units | Failure boundary | |---|---|---| | `exportIGES(model, ids)` | `{ iges, report }`: `iges` is file text; the report declares mm, scale 1 and non-solid geometry | Requires a version-0 millimetre model with 1–16 objects and 1–16 distinct selected IDs; invalid model or selection is refused | | `importIGES(text, options)` | `{ request, source, model, metadata, entities, report }`: native model/source data and import provenance, not a B-rep solid | Unsupported input throws `IGESImportError` with a diagnostic `code`; it is not a successful report with missing geometry | | `writeDxf(drawing, options)` | `{ text, bytes, report }`: `bytes` is `Uint8Array` in Windows-1252; extents and chord distances use the drawing's units | Throws a typed refusal; use `isDxfWriteError(error)` to identify its code | The bounded IGES importer requires `sourceId`, `modelName`, `idPrefix`, `maximumEntities: 16` and `maximumRecords: 8192`. It accepts its supported millimetre profile without unit conversion. Its returned `source` is native model source, not the original IGES file text; `request.iges` retains that input text. For DXF, write the returned `bytes` when you need the writer's file encoding. Encoding `text` as UTF-8 can produce different bytes for non-ASCII characters. In R12, `report.r12` records conversions and whether units were omitted; the chord tolerance uses drawing units, not a fixed millimetre value. ```ts import { writeDxf, isDxfWriteError, type DxfDocument } from '@barocss/cad'; // The caller supplies drawing data and handles file I/O. export function prepareDxf(drawing: DxfDocument) { try { const result = writeDxf(drawing, { version: 'AC1015' }); return { bytes: result.bytes, report: result.report }; } catch (error: unknown) { if (isDxfWriteError(error)) return { error: error.code }; throw error; } } ``` ## STEP - **Writing.** An output's `exportStep(options)`, or `exportStep(brep | breps, options)`, writes the exact B-rep as STEP AP214: planes, B-spline surfaces and curves. Its options: - `name`: the product's name. - `timestamp`: the header's time; the default is now. - `description`: the header's `FILE_DESCRIPTION` entries. The default is `'BaroCSS CAD part'`; the studio adds its source revision. - `validationProperties`: CAx-IF geometric validation properties (volume, area, centroid and bounding box), written by default so a reader can check what it imported. - `meshes`, for mesh bodies: - `tessellated`: AP242 triangulated faces, compact; - `planar`: the triangles as planar faces, readable by any STEP reader, but large; - `auto` (the default): planar up to 5,000 triangles a body, tessellated above. Planar faces past 250,000 triangles a body are refused. - **Reading.** `importStep(text)`, or the `import` feature in a part, reads B-rep solids: - **surfaces:** planes, cylinders, cones, spheres and tori as exact rational patches, B-spline surfaces as they are, and surfaces of linear extrusion and of revolution; - **offset surfaces:** one level of `OFFSET_SURFACE` over direct `PLANE`, `CYLINDRICAL_SURFACE`, `SPHERICAL_SURFACE`, `CONICAL_SURFACE` (including exact-zero identity and nonzero cone offsets away from apex collapse/crossing), `TOROIDAL_SURFACE` (away from collapse and spindle pinch), and `B_SPLINE_SURFACE*` bases. Analytic offsets certify boundary curves explicitly; NURBS offsets check curvature fold bounds and disclose fitted deviation in `importStepWithReport(...).offsetApproximations`; - **curves and periodic bounds:** lines, circles and ellipses as rational arcs, B-spline curves (including exact domain splits and `TRIMMED_CURVE` bounds), `VERTEX_LOOP` pole/apex bounds on singular carriers, seam-crossing holes, and once-round swept/revolution/periodic carriers. A face that goes once round its axis is cut into seamless halves. Other offset bases, nested offsets, binary64 cone-offset underflows, pinched/collapsed offsets, non-singular `VERTEX_LOOP` pinholes and separated boundary curves are explicitly refused by name (`GEOMETRY` for proved boundary separation, `CAPABILITY` / `INPUT` otherwise). `stepMeshes(text)` reads a file of AP242 tessellated meshes only. - **Multi-level STEP assemblies.** STEP import and export preserve multi-level assembly definitions, shared part instances, and rigid placement transforms across round-trips rather than flattening every occurrence into unlinked bodies. - **Zero-RegExp Part 21 parsing.** STEP real/point formatting and Part 21 token parsing run on a dedicated scanner with zero RegExp backtracking overhead for large assemblies. ```js const [body] = evaluateCadPart(plate).outputs; const step = exportStep(body, { name: 'plate' }); // exact B-rep, AP214 const back = evaluateCadPart({ format: 'barocss-cad-part', version: 1, units: 'mm', parameters: {}, features: [{ id: 'i', kind: 'import', step }] }); // a STEP file as a feature const [read] = back.outputs; assert.ok(Math.abs(massPropertiesOf(read, 2.7).volume - massPropertiesOf(body, 2.7).volume) < 1e-6); assert.equal(checkOutput(read).valid, true); ``` With `each: true`, the `import` feature makes each solid in the file its own part (`id/k`), in file order. ## IGES `exportIGES` writes curves and surfaces as rational B-spline entities (126 and 128). `importIGES` reads the same profile: untransformed rational B-spline curves and surfaces in IGES 5.3. It gives typed diagnostics for anything else. In the studio, IGES is for curves and surfaces you edit directly, not solids. Native IGES exchange is verified end-to-end across `@barocss/cad`, `@barocss/cad-model`, and `@barocss/viewer` with strict bounds validation and refusal diagnostics. See [Files and exports](/studio/files). ## STL - **Writing.** An output's `exportStl({ segmentsPerQuarter })` writes its display tessellation as binary STL, in millimetres. `encodeBinaryStl(positions, indices)` writes any triangle mesh. - **Reading.** `readStl(bytes)` reads binary or ASCII STL triangles, and `readObj` reads OBJ. The `mesh` feature takes triangles as a faceted body. STL carries triangles only: no units, colours, names or exact curves. - **Unit scaling and malformed refusal.** Binary and ASCII STL readers support explicit unit scaling (`mm`, `cm`, `m`, `in`) and refuse truncated buffers, non-finite coordinates, or malformed headers with typed diagnostics instead of silently dropping triangles. - **Approximation disclosure.** Exporting a curved B-rep to STL approximates exact analytic/NURBS faces as triangles; Studio surfaces triangle count and chordal approximation metadata alongside the export. Omitting `segmentsPerQuarter` from `exportStl` uses 16. This dimensionless tessellation setting is not a millimetre tolerance or a guarantee of geometric error. It does not change the on-screen mesh; see [STL export choices](/studio/files#exports) for the studio controls. ## DXF `writeDxf(document, { version })` writes a 2D drawing: - **The input** is a plain document of layers, line types, text styles, blocks and entities. - **The versions** are DXF 2000 (`AC1015`, the default) and R12 (`AC1009`). - **Same document, same file.** The output has no time stamps, so the same document always gives the same bytes. - **R12's limits.** R12 has no ellipses, splines, hatches or multi-line text: - polylines and text are rewritten exactly; - ellipses and splines become polylines only within a chord tolerance you give; - anything else is refused, typed. The report counts every such change, so nothing is approximated silently. The document may also supply `dimensionStyle` with all three fields: a finite positive `textHeight` in the drawing's units, `textPlacement` (`above` or `center`) and `textOrientation` (`aligned` or `horizontal`). Both versions write these dimension-style defaults. Omitting the object preserves the existing defaults and bytes. Invalid values throw a typed DXF write error. The fields do not rebuild anonymous dimension display blocks or guarantee an external editor's regenerated layout. ```js const sheet = { units: 'mm', entities: [ { type: 'line', a: [0, 0], b: [60, 0] }, { type: 'line', a: [60, 0], b: [60, 40] }, { type: 'line', a: [60, 40], b: [0, 40] }, { type: 'line', a: [0, 40], b: [0, 0] }, { type: 'circle', center: [30, 20], radius: 4 }, ] }; const a = writeDxf(sheet), b = writeDxf(sheet); // DXF 2000 (AC1015) by default assert.equal(a.text, b.text); // no time stamps: the same document, the same file assert.deepEqual(a.report.modelSpace, { LINE: 4, CIRCLE: 1 }); const r12 = writeDxf(sheet, { version: 'AC1009' }); // R12 assert.match(r12.text, /AC1009/); ``` Sheet metal's flat pattern has its own DXF writer, `flatPatternDxf`. Reading a DXF sketch is the document model's job: see [@barocss/cad-model](/packages/cad-model/). --- # @barocss/cad-projection Headless, deterministic CPU hidden-line CAD geometry projection with exact SVG vector export and CPU-rendered PNG output — with **zero browser, GPU, DOM, canvas, React, or Studio dependencies**. `@barocss/cad-projection` builds on `@barocss/cad`'s exact B-rep hidden-line removal (`projectBrepHiddenLines`) and adds mixed-scene adaptation (B-rep solids, NURBS curves, UV-trimmed surfaces, triangle meshes, Direct sources), exact 2D fill visibility clipping, compact SVG export, and pure-CPU PNG rasterization for CI visual checks and multimodal AI verification (`query.render`). ## Quick start ```js import { evaluateCadPart } from '@barocss/cad'; import { part } from '@barocss/cad/api'; import { projectGeometry, projectGeometryFourViews, renderSvg, renderPng, } from '@barocss/cad-projection'; ``` ```js const bracket = part('Bracket') .box({ w: 80, d: 40, h: 10 }) .hole(p => p.faces().facing('+z').first(), { d: 8, x: 20, y: 20 }); const snapshot = evaluateCadPart(bracket.doc); const brep = snapshot.outputs[0].brep; const items = [{ id: 'bracket', kind: 'brep', brep }]; const doc = projectGeometry(items, { camera: { position: [240, -320, 220], target: [40, 20, 5], up: [0, 0, 1] }, fills: [{ item: 'bracket', color: '#dbeafe' }], }); const svg = renderSvg(doc, { compactFills: true, hiddenLines: true }); const png = await renderPng(doc, { hiddenLines: true, width: 320, height: 240 }); const fourView = projectGeometryFourViews(items); ``` This sample runs directly in CI via `pnpm --filter @barocss/library-docs test:samples`. ## Entry points | Subpath | Purpose | | --- | --- | | `@barocss/cad-projection` | Scene & B-rep projection (`projectGeometry`, `projectGeometryFourViews`, `projectBreps`, `projectDirectGeometry`, `projectModel`) + `renderSvg` / `renderPng` | | `@barocss/cad-projection/compression` | Zero-dependency `crc32`, `compress`, and `deflateZlib` utilities | | `@barocss/cad-projection/inspect` | Diagnostic inspection helpers for projected curves, visibility intervals, and coverage receipts | ## Supported input coverage | Input kind | Item descriptor | Routing & notes | | --- | --- | --- | | Solid / sheet / facet B-rep | `{ id, kind: 'brep', brep }` | Exact kernel HLR (`projectBrepHiddenLines`) | | Free NURBS curve | `{ id, kind: 'curve', curve, interval? }` | Analytic lines & circles preserved; general curves adaptively sampled | | UV-trimmed NURBS surface | `{ id, kind: 'surface', surface, trims? }` | Exact UV slab arrangement decomposition | | Triangle mesh / soup | `{ id, kind: 'mesh', positions, indices, open? }` | Native facet adapter with non-manifold triangle-sheet fallback | | Direct / compiled model | `projectDirectGeometry` / `projectModel` | Atomic validation (`ProjectionSourceError`) without Studio imports | ## Rendering options & boundaries - **`renderSvg(doc, options?)`**: Preserves exact lines and affine elliptical arcs (`transform="matrix(...)"`), optional `hiddenLines`, `faceGuideStyle` (`'illustration' | 'continuous'`), and `compactFills` (directed-edge cancellation). Also powers semantic SVG hit metadata in [`@barocss/cad-react/sdk`](/packages/cad-react/sdk) ``. - **`renderPng(doc, options?)`**: Deterministic RGB PNG (`Promise`) rasterized on CPU using standard `CompressionStream`. - **Camera & pixel limits**: Cameras are strictly orthographic (`position - target` sets view direction, auto-fitted to bounds), supporting standard orthographic, isometric, dimetric, trimetric, and magnified detail views. Image dimensions must be positive integers up to `8192` per side and `32,000,000` total pixels. - **Scope separation**: ISO/ASME title blocks, baseline/ordinate dimensions, GD&T callouts, and vector PDF/DXF sheet export live in [`@barocss/cad-model`](/packages/cad-model/); interactive WebGPU 3D rendering lives in [`@barocss/gpu`](/packages/gpu/). --- # @barocss/cad-interop `@barocss/cad-interop` bridges exact `@barocss/cad` B-Rep geometry and native face/curve packets into third-party WebGL/WebGPU scene graphs (**Three.js**, **Babylon.js**, **Pixi3D**) and binary **glTF / GLB** preview assets. Use `@barocss/cad-interop` when your application already renders with Three.js, Babylon.js, or Pixi3D and wants to embed BaroCSS CAD's pure-TypeScript B-Rep modeling engine without replacing your existing 3D engine. ## Core Capabilities | Entry Point | Target Engine / Format | What It Provides | | :--- | :--- | :--- | | `@barocss/cad-interop` | Engine-agnostic packets & GLB | `copyCadPreviewPacket`, `prepareCadPreviewMesh`, `prepareOwnNativeFaceMesh`, `encodeCadPreviewGlb`, `encodeOwnNativeFaceMeshGlb` | | `@barocss/cad-interop/three` | **Three.js** (`three`) | Direct BufferGeometry & scene adapters (`/three-document`, `/three-assembly`, `/three-boolean-mesh`, `/three-uniform-curve`, `/qualified-body-boundary-mesh-three`) | | `@barocss/cad-interop/babylon` | **Babylon.js** (`@babylonjs/core`) | Babylon mesh & assembly adapters (`/babylon-document`, `/babylon-assembly`, `/babylon-boolean-mesh`, `/babylon-uniform-curve`, `/qualified-body-boundary-mesh-babylon`) | | `@barocss/cad-interop/pixi3d` | **Pixi3D** (`pixi3d`) | Pixi3D mesh & document adapters (`/pixi3d-document`, `/pixi3d-assembly`, `/pixi3d-boolean-mesh`, `/qualified-body-boundary-mesh-pixi3d`) | | `@barocss/cad-interop/document-glb` | **glTF 2.0 Binary (`.glb`)** | Document, boolean mesh (`/boolean-mesh-glb`), and boolean extrusion (`/boolean-extrusion-glb`) GLB encoders | | `@barocss/cad-interop/native` | **Native CAD loaders** | Qualified body, native uniform curve (`/native-uniform-curve`), assembly (`/assembly`), and model-set (`/model-set`) loaders | All engine peer dependencies (`three`, `@babylonjs/core`, `pixi.js`, `pixi3d`) are optional — install only the renderer your app uses. ## Engine-Agnostic Packet & GLB Export The root entry point prepares detached, bounds-verified preview meshes and encodes binary `.glb` buffers directly from pure TypeScript: ```ts import { prepareCadPreviewMesh, encodeCadPreviewGlb, type CadPreviewPacket, } from '@barocss/cad-interop'; export function buildPreviewGlb(packet: CadPreviewPacket): Uint8Array { // Validates & normalizes positions, normals, indices, and metadata const prepared = prepareCadPreviewMesh(packet); // Encodes a self-contained binary glTF 2.0 (.glb) buffer in memory return encodeCadPreviewGlb(prepared); } ``` ## Cross-Format Interchange Reporting When exporting across formats (STEP, IGES, STL, 3MF, GLB), `@barocss/cad-interop` and Studio attach structured interchange reports (`interchange-report`) declaring the exact export target, output units, body count, and any representation loss (such as analytic B-Rep surfaces approximated into triangle meshes for STL/GLB) so downstream recipients never receive silent format degradation. ## Choosing Between `@barocss/cad-interop` and `@barocss/cad-react/sdk` - **Already using Three.js, Babylon.js, or Pixi3D?** Use `@barocss/cad-interop` adapters to mount exact BaroCSS B-Rep solids, curves, and assemblies into your existing camera, lighting, and shader pipeline. - **Building a CAD viewer or product configurator in React from scratch?** Use [`@barocss/cad-react/sdk`](/packages/cad-react/sdk) (`` + ``) powered by BaroCSS's native WebGPU renderer and exact 2D HLR projection. - **Need manufacturing exchange formats (STEP, IGES, DXF, STL)?** Those live directly in [`@barocss/cad` Exchange formats](/packages/cad/formats). ## Related Pages - [Exchange formats (STEP, IGES, STL, DXF)](/packages/cad/formats) - [React CAD SDK (`@barocss/cad-react/sdk`)](/packages/cad-react/sdk) - [WebGPU Renderer (`@barocss/gpu`)](/packages/gpu/) - [Viewer SDK (`@barocss/viewer`)](/packages/viewer/) --- # @barocss/cad-worker `@barocss/cad-worker` moves heavy B-Rep evaluation, mass properties, 2D proposal callouts, robotics workspace sweeps, and parallel generative variants off the browser main thread using standard Web Workers and zero-copy transferable buffers. Because the underlying `@barocss/cad` kernel is pure TypeScript with zero WebAssembly, the same worker modules run identically in browser Web Workers, Vite/esbuild apps, or synchronous in-process test ports. ## Subpath Entry Points | Entry Point | Purpose | | :--- | :--- | | `@barocss/cad-worker` | Main barrel exporting `EngineClient`, `Lanes`, ports, analysis router, robot tasks, and `VariantWorkerPool` | | `@barocss/cad-worker/client` | `EngineClient` RPC wrapper over a Web Worker with typed replies (`MassReply`, `VolumeReply`, `FootprintReply`, `RobotSweepReply`, `ProposalOverlay`) | | `@barocss/cad-worker/worker` | Ready-to-bundle `engine.worker.ts` entry point | | `@barocss/cad-worker/analysis` | `createAnalysisWorkerRouter` for modular auxiliary analysis workers (`faces`, `print`, `clearance`, `cam`) | | `@barocss/cad-worker/port` | `createDefaultEnginePort`, `createWorkerEnginePort`, and `createSyncEnginePort` (`CadEnginePort` abstraction) | | `@barocss/cad-worker/lanes` | `Lanes` request-lane coordinator (latest-wins cancellation for live slider dragging vs queued exports) | | `@barocss/cad-worker/variantPool` | `VariantWorkerPool`, `evaluateVariants`, `buildParametricVariantCandidates`, `computeSafeParameterBounds`, and `projectVariantThumbnail` | | `@barocss/cad-worker/robotTasks` | `collectRobotPartMeshes`, `runRobotSweep`, and `runRobotWorkspace` | | `@barocss/cad-worker/proposalDrawingCallouts` | `proposalDrawingCallouts` for computing 2D drawing annotation diffs on AI proposals | | `@barocss/cad-worker/stepMetadata` | `stepMetadata` / `receiveStepMetadata` for STEP provenance inspection | | `@barocss/cad-worker/mouldView` | `mouldView` parting-line and draft loop computation | ## Choosing an Engine Port (`CadEnginePort`) Use `@barocss/cad-worker/port` when your UI or SDK wants automatic Web Worker acceleration in browsers while falling back seamlessly to synchronous execution in Node.js or unit tests: ```ts import { createDefaultEnginePort, createSyncEnginePort, createWorkerEnginePort, } from '@barocss/cad-worker/port'; // Browser: spawns a Web Worker when available; Node/SSR: falls back to synchronous evaluation. const port = createDefaultEnginePort(); // Explicit synchronous port for deterministic CI tests or CLI tooling: const syncPort = createSyncEnginePort(); ``` ### Request Lanes (`Lanes`) Interactive CAD sliders fire dozens of updates per second. `Lanes` separates high-frequency interactive preview requests from authoritative operations: - **Latest-wins lanes** supersede stale in-flight slider evaluations so the UI never queues behind obsolete drag frames. - **Authoritative lanes** preserve ordering for saves, exports, and proposal acceptance. ## Parallel Generative Variants (`VariantWorkerPool`) The [Generative Variant Explorer](/agent/variants) uses `@barocss/cad-worker/variantPool` to evaluate multiple parameter and topology candidates in parallel without blocking viewport orbiting: ```ts import { buildParametricVariantCandidates, evaluateVariants, applyCandidateToDoc, type VariantCandidateInput, } from '@barocss/cad-worker/variantPool'; // 1. Derive safe bounded parameter candidates around the active document const candidates: VariantCandidateInput[] = buildParametricVariantCandidates(doc, { preset: 'lightweight', count: 4, }); // 2. Evaluate all candidates in parallel (B-Rep mass, bounds, DFM, checkSpec, 2D thumbnails) const batch = await evaluateVariants(doc, candidates); // 3. Promote the winning candidate into an editable document revision const winner = batch.results.find(r => r.ok && r.specs?.hardFailing === 0); if (winner) { const nextDoc = applyCandidateToDoc(doc, winner.candidate); } ``` Each `VariantCandidateResult` carries: - `VariantBaselineMetrics` deltas (mass, volume, bounding box) - `VariantSpecSummary` (`checkSpec` pass/fail counts) - `VariantDfmSummary` & `VariantPhysicsSummary` - `VariantThumbnail` lightweight 2D projection segments for side-by-side card previews ## Auxiliary Analysis Router (`createAnalysisWorkerRouter`) Heavy inspection tasks — print slice previews, clearance checks, face queries, and CAM toolpaths — run on isolated auxiliary workers routed through `createAnalysisWorkerRouter`: ```ts import { createAnalysisWorkerRouter } from '@barocss/cad-worker/analysis'; const router = createAnalysisWorkerRouter({ print: () => import('./printLane'), clearance: () => import('./clearanceLane'), cam: () => import('./camLane'), }); ``` ## Related Pages - [Generative Variant Explorer & Self-Verification](/agent/variants) - [`@barocss/cad` Core Kernel](/packages/cad/) - [React CAD SDK (`@barocss/cad-react/sdk`)](/packages/cad-react/sdk) - [Embedding & Self-Hosting Guide](/guide/embedding) --- # Object API > **Quick jump:** [Start with CAD Model API](#start-with-the-cad-model-api) · [Interactive 3D API Results](#see-actual-api-results) · [CAD Kernel Part](#parts) · [Studio / Model Part](#studio-parts) · [Parameters & Configs](#parameters-configurations-and-suppression) · [Assemblies](#assemblies) · [Manufacturing](#manufacturing-inputs-and-outputs) · [Scenes](#scenes) · [Errors](#errors) ## Start with the CAD model API For ordinary modeling, start with `@barocss/cad-model/api`. It builds the model document used for editing, materials, assemblies and drawings. The same API works in code without the Studio editor. This sample makes a bracket, then reads its mass, STEP and meshes: ```js import { part, assembly, Location, param, BarocssError } from '@barocss/cad-model/api'; ``` ```js // 3. The facade: the same command names, the same value names (no unit suffix), the selectors in place of // the names. const bracket = part('bracket') .box({ w: 80, d: 40, h: 10 }) .hole(body => body.faces().facing('+z'), { d: 8, x: 20, y: 20 }) .fillet(body => body.edges().along('z'), { radius: 2 }); const mass = bracket.mass('al6061'); // or mass({ density: 2.7 }); native results also report method and an optional volumeBasis const step = bracket.step(); // STEP AP214 text const meshes = bracket.meshes(); // [{ key, positions, normals, indices }], one a body ``` The kernel examples later on this page show its lower-level document and results. They are useful when working with the kernel directly; they are not the default entry point for the complete model document. Each of the three packages has an object facade over its own data-and-functions core: | Package | Entry | Over | For | |---|---|---|---| | @barocss/cad | `@barocss/cad/api` | The kernel's `CadPartDocument` and `evaluateCadPart` | Using the kernel on its own. It replaced the older `createCadModel()`, retired in R7.3d. | | @barocss/cad-model | `@barocss/cad-model/api` | The CAD model document, its evaluation, mass, STEP and assemblies | Materials by id, assemblies, variants and frames, in code or in Studio | | @barocss/gpu | `@barocss/gpu/api` | The `Viewer` and its geometry and material data | Putting parts on screen | Both Part APIs build and evaluate a model. Choose the document and workflow you need: | | CAD kernel part | CAD model part | |---|---|---| | Import | `@barocss/cad/api` | `@barocss/cad-model/api` | | Document returned by `.doc` | `CadPartDocument`, format `barocss-cad-part`, with `features` | `StudioDoc`, format `barocss-cad-model`, with `nodes` and `outputs` | | Use it when | You need the CAD kernel and its feature document in code. | You need the CAD model document, materials, configurations or drawing and manufacturing outputs. | | Shared modeling | Box, hole, fillet, Boolean operations, mass, meshes and STEP | These modeling and result methods use the CAD model document | | Additional operations | Supply a density for mass; export STL from this part API. | Set a material id; save configurations; generate drawings and manufacturing outputs. The model part also provides gear, spring and fastener commands. | The modeling calls can look the same, but the two `.doc` values have different formats: ```js import { part as kernelPart } from '@barocss/cad/api'; import { part as modelPart } from '@barocss/cad-model/api'; const kernel = kernelPart('plate').box({ w: 80, d: 40, h: 10 }); const model = modelPart('plate').box({ w: 80, d: 40, h: 10 }); console.log(kernel.doc.format); // 'barocss-cad-part' console.log(model.doc.format); // 'barocss-cad-model' ``` Each facade is an API for code. CAD Model's document type is named `StudioDoc` in the source. It is a data model that code can use independently; Studio is an editor that also uses that model and its core. The CAD model part facade writes commands into the document. Calling the facade does not control an open Studio screen. The agent works through its JSON tools. ## The shared rules - **Immutable objects.** Modeling methods return a new object and leave the original unchanged. Result methods such as `mass()` and `meshes()` return result data. - **One plain-JSON accessor.** - The two parts and the assembly have `.doc`, the document a person or the agent could have written by hand. - gpu's scene has `.data`. - Typed arrays appear only in mesh data. - **Modeling methods** write changes to a new document and use the core to evaluate it. Query and result methods read the document or return data; they do not add a feature. - **Modeling units.** Lengths are in millimetres, angles in degrees and density in g/cm³. Mass results use millimetres and grams. The confirmed R7 [robot contract](/studio/robots#robot-unit-boundaries) extends these units to public replies and stored joint settings. It uses N·mm for turning effort, mm/s² for gravity and seconds for time. Robot samples check angular metadata, B1 inertia/gravity and the CLI's shared B2 duty/report adapters. Further field changes and final combined checks are pending. Native robot files retain their format-specific SI units. - **Results are plain data.** Mass results contain `volume` in mm³, `mass` in g, `centroid` in mm and `inertia` in g·mm² about the centre of mass. A numeric `density` is in g/cm³. Density must be positive and finite; both facades refuse other numeric densities with `BarocssError`, code `DENSITY`, from `facade`. Native producers also report optional `method` provenance: `closed-form`, `planar-exact`, `quadrature` or `tessellated`. `planar-exact` describes the represented planar or facet boundary; it does not recover a smooth source from a mesh. `quadrature` describes numerical integration over the represented surfaces. These method names are not accuracy certificates. Legacy or custom Model bodies without producer metadata omit `method`; the facade does not infer it from the body's family or a missing estimate. A reported tessellated result can include `volumeBasis: { method: 'tessellated', bound }`. Despite its existing field name, `bound` is an estimate of volume error in mm³, derived from the mesh refinement change, rather than a certified error bound. `null` means no estimate was supplied; zero remains a reported zero estimate. Other native methods omit this basis. Density changes mass and inertia, while the method and volume estimate remain unchanged. The returned basis is detached from the producer's record. - **The agent's words.** The modelling verbs are the agent's v2 command names, and their options are that command's value names, with no unit in the name: `box({ w, d, h })`, `hole(face, { d, x, y })`, `fillet(edges, { radius })`. Where no command names a value, the option is named for it: `mass({ density })`. Two verbs are named for their studio palette entry instead: `box`, which has no v2 command, and `subtract`, whose command is `difference`. - **One part, two documents.** Both packages' parts are one implementation (cad's `Part`). Each verb is checked once, and a backend writes it into its own document: cad's as kernel features, cad-model's through the studio's own command, as the agent's `run_command` does. - **The same selectors.** `edges()` and `faces()`, with typed filters and no string selectors: - the kernel fills them from the B-rep, and cad-model from its display mesh; - both hand back the persistent names a feature stores. - **One error shape.** `BarocssError { code, message, where, details }`, where the message starts with `[CODE]`: - the facade's own codes cover only how it was called, with `where: 'facade'`; - a core refusal is passed through with its code and words, with `where: 'evaluate'` or `'export'`. - **Z-up, as given.** Meshes from either part go into a gpu scene unconverted: the Viewer is Z-up already. - **The oracle.** Each package's tests check every method two ways: its `.doc` equals the hand-written document, and its results equal the core's on that document, byte for byte. cad-model's `.doc` also equals what the agent's tools write for the same calls. ## See actual API results These three saved cases follow the public `@barocss/cad/api`: an 80 × 40 × 10 mm box, a through hole, then four rounded vertical edges. Each operation returns a new part. The earlier parts stay unchanged. The coordinates are Z-up, in mm. Mass uses a density of 2.7 g/cm³. The 3D view draws the actual Float32 tessellated mesh returned by the public API; the JPEGs show those saved meshes. Display triangles approximate curved surfaces and do not guarantee the kernel's geometric tolerance. This is a documentation view of fixed API results. Choose a case to read its executed code, inputs and returned mass properties. **Source bundle provenance** records the source and generation conditions. Missing result data is shown as `NOT_RUN`, not a successful API run. ### 01 · Box Create the box with `box({ w: 80, d: 40, h: 10 })`. ![Public API result: an 80 by 40 by 10 mm box, Z up](/shots/api-results/box.jpg)

{{ resultSummary('box') }}

### 02 · Through hole From the box, select the +Z face and make a diameter 8 mm through hole at face coordinates `(20, 20)`. ![Public API result: the box after a diameter 8 mm through hole at 20, 20](/shots/api-results/holed.jpg)

{{ resultSummary('holed') }}

### 03 · Rounded vertical edges From the holed part, select its four vertical edges and apply a 2 mm fillet radius. ![Public API result: the holed box after rounding four vertical edges with radius 2 mm](/shots/api-results/rounded.jpg)

{{ resultSummary('rounded') }}

## CAD kernel part {#parts} ```js import { part, sketch, Plane, Location, param, withParameters, BarocssError } from '@barocss/cad/api'; ``` A CAD kernel part is an immutable object over a `CadPartDocument`. Use it to work with the CAD kernel in code: ```js const bracket = part('bracket') .box({ w: 80, d: 40, h: 10 }) .hole(body => body.faces().facing('+z'), { d: 8, x: 20, y: 20 }) .fillet(body => body.edges().along('z'), { radius: 2 }); const mass = bracket.mass({ density: 2.7 }); // a density: the kernel keeps no material library const step = bracket.step(); // STEP AP214 text const stl = bracket.stl(); // binary STL const meshes = bracket.meshes(); // [{ key, positions, normals, indices }], one a body ``` The document it builds is the one you would write by hand. Feature ids are assigned in order: `sketch1`, `extrude1`, `hole1`… The hole keeps the face it went into by name, `face: 'extrude1.top'`, as the studio writes it. ```js // The CadPartDocument it builds: string ids the facade assigns in feature order, each feature naming its target, and // the hole the face it went into. const doc = { format: 'barocss-cad-part', version: 1, units: 'mm', parameters: {}, features: [ { id: 'sketch1', kind: 'sketch', profile: 'rectangle', min: [0, 0], max: [80, 40] }, { id: 'extrude1', kind: 'extrude', sketch: 'sketch1', height: 10 }, { id: 'hole1', kind: 'hole', target: 'extrude1', center: [20, 20], radius: 4, face: 'extrude1.top' }, { id: 'fillet1', kind: 'fillet', target: 'hole1', edges: ['extrude1.side0|extrude1.side1', 'extrude1.side0|extrude1.side3', 'extrude1.side1|extrude1.side2', 'extrude1.side2|extrude1.side3'], radius: 2 }, ] }; assert.equal(JSON.stringify(bracket.doc), JSON.stringify(doc)); // byte for byte ``` `part(name, doc)` continues a saved document, or another part's `.doc`: it is evaluated once, and the verbs add to it. ### Verbs Each verb makes a body of its own, or acts on the part's body. | Verb | v2 command | What it does | |---|---|---| | `box({ w, d, h, x?, y?, z? })` | (palette: Box) | A block, its least corner at (x, y, z) | | `cylinder({ r, h, x?, y?, z? })` | `cylinder` | A round bar standing on z about (x, y) | | `extrude(sketch, { h, draft? })` | `extrude` | A finished sketch pulled along its plane's normal | | `revolve(sketch, { axis?, deg? })` | `revolve` | A finished sketch turned about its plane's Y axis (or X), a full turn by default | | `hole(face, { d, x, y, type?, depth? })` | `hole` | A hole into the one flat face the selector picks, at (x, y) on that face's plane; through unless `'blind'` with a `depth` | | `fillet(edges, { radius, endRadius? })` | `fillet` | Rounds the selected edges with a constant radius or assigns two endpoint radii to one supported edge | | `chamfer(edges, { distance })` | `chamfer` | Cuts them back at 45° | | `shell(open?, { t })` | `shell` | Hollows the body to walls t thick, leaving the faces the selector picks open; with no selector, a closed hollow | | `union(tool)`, `subtract(tool)`, `intersect(tool)` | `union`, `difference`, `intersect` | Combines the body with a tool body | | `linearPattern({ axis, spacing, count })` | `linear-pattern` | Copies in a row, joined into one body | | `circularPattern({ axis?, count, span?, px?, py? })` | `circular-pattern` | Copies round an axis, joined into one body | | `mirror({ plane, at? })` | `mirror` | Joins the body with its image across the plane `'yz'`, `'xz'` or `'xy'`, through `at` on its axis (0 unless given) | | `scale({ factor, pivot? })` | `scale` | Scales the body by the factor, about the pivot (the origin unless given) | | `split({ axis, at })`, `split({ normal, at })` | `split` | Cuts the body in two by a plane, each side a body of its own | | `moved(location)` | `rotate`, then `move` | Turns the body about X, then Y, then Z through the origin, then moves it | - **Each verb evaluates its result.** A feature the core refuses is refused at its verb, with the core's code, and the part is unchanged. - **Patterns.** About X or Y the copies are quarter turns, 2 to 4 of them; anything else is refused, typed. - **No `rotate` verb.** The studio's rotate command turns about the body's centre by default, and the kernel's about the origin. `moved()` always turns about the origin. - **Mirror and scale** work about the origin unless given `at` or `pivot`. A mirror plane off the origin is written as the studio writes it: a move, the mirror, and a move back. ```js const block = () => part().box({ w: 10, d: 20, h: 5 }); const both = block().mirror({ plane: 'yz' }); // joined with its image across x = 0: 20 × 20 × 5 const big = block().scale({ factor: 2 }); // about the origin: 20 × 40 × 10 const halves = block().split({ axis: 'x', at: 4 }); // cut across x = 4, each side a body ``` ### Fillet with two endpoint radii Both TypeScript backends accept `endRadius` on one named straight open edge or a supported convex 90° circular rim. The circular rim joins a planar cap to a coaxial cylinder and ends at two outward radial planes. The radius starts at the selected edge's `a` endpoint and ends at `b`. Use at least 0.1 mm at each end. An equal numeric pair uses the constant-radius operation. ```ts import { part, sketch } from '@barocss/cad/api'; const sector = sketch().moveTo([0, 0]).lineTo([8, 0]).arcTo([0, 8], { center: [0, 0] }).close(); const rounded = part('Quarter rim').extrude(sector, { h: 10 }).fillet( body => body.edges().curved().where(edge => edge.a[2] === 10 && edge.b[2] === 10), { radius: 0.6, endRadius: 1.2 }, ); ``` Import `part` from `@barocss/cad-model/api` to make a Studio document. Encode it with `encodeStudioFile(rounded.doc)` from `@barocss/cad-model/engine/container` to open it as a `.bcad` file. Use Studio History to edit the end radius. ### Sketches, planes and locations `sketch(plane?)` starts a sketch on a `Plane`, XY by default. It gives `.rectangle({ w, d, x?, y? })`, `.circle({ r, x?, y? })`, `.polygon(points)`, or a chain `.moveTo(p).lineTo(p).arcTo(p, { center, direction? })` ended by `.close()`. - **Planes.** `Plane.XY`, `Plane.XZ` (its normal −Y, so its Y is world Z), `Plane.YZ`, `.offset(distance)`, and `Plane.of({ origin, normal, xAxis })`, which refuses vectors that aren't unit length and square to each other. - **Locations.** `Location.of({ position, rotation })` and `Location.at(position)`: the documents' pose, turned about X, then Y, then Z, through the origin, then moved. - **Plain data.** A sketch, a plane and a location are immutable, and each has `.data`, the shape the documents carry. - **Stable side names.** Every side of a facade sketch is tagged (`e1`, `e2` …), as the studio's sketcher tags the sketches it draws. So its walls keep their names when a vertex is added to the sketch later. ```js // A 20 × 30 section on XZ, turned a full turn about Z: a Ø40 × 30 drum. Hollowed to 2 mm walls, its top left open. const cup = part('cup') .revolve(sketch(Plane.XZ).polygon([[0, 0], [20, 0], [20, 30], [0, 30]])) .shell(body => body.faces().facing('+z'), { t: 2 }); const { volume } = cup.mass({ density: 1 }); assert.ok(Math.abs(volume - Math.PI * (20 ** 2 * 30 - 18 ** 2 * 28)) < 1e-6 * volume); // A tab from a loop of lines and an arc, on XY lifted 5, pulled 6 with a 3° draft. const tab = part('tab').extrude(sketch(Plane.XY.offset(5)) .moveTo([0, 0]).lineTo([30, 0]).arcTo([30, 20], { center: [30, 10] }).lineTo([0, 20]).close(), { h: 6, draft: 3 }); assert.deepEqual(tab.doc.features.map(f => f.kind), ['sketch', 'extrude']); ``` ### Several bodies - **`bodies()`** lists the part's bodies in the core's order: the kernel's output ids (`extrude1`, `fillet1` …), or the studio's keys (`b1`, `b3` …). - **`body(name)`** returns the same part with its verbs, `select()` and `mass()` acting on that body. `.doc` doesn't change: the choice is the facade's view, never written. It follows its body through a verb that replaces it. - **With several bodies and none chosen,** a verb refuses with `BODY_AMBIGUOUS`. `step()` writes every body, and `meshes()` gives every body. - **A Boolean's tool** is a body of the part by name, or a callback that adds it. The callback builds in the part's own document, so the tool's features take the next ids. It must add exactly one body. Its verbs after the first act on the body it made, so a callback can pattern or round its tool before the Boolean. ```js const two = part('pegged') .box({ w: 30, d: 30, h: 10 }) .cylinder({ r: 5, h: 30, x: 15, y: 15 }); // a peg standing through the block assert.deepEqual(two.bodies(), ['extrude1', 'extrude2']); assert.throws(() => two.mass({ density: 1 }), e => e.code === 'BODY_AMBIGUOUS'); const joined = two.body('extrude1').union('extrude2'); // the block, joined with the peg by name assert.deepEqual(joined.bodies(), ['union1']); // A tool added by a callback, in the part's own document: a Ø8 bore cut through a plate. const bored = part('plate').box({ w: 60, d: 40, h: 8 }) .subtract(p => p.cylinder({ r: 4, h: 20, x: 30, y: 20, z: -6 })); ``` #### Split a body and inspect each result Start with a 10 × 20 × 5 mm box at the origin. The plane `x = 4` cuts it into two bodies: ```text x = 0 x = 4 x = 10 |-----------|--------------------| 4 mm 6 mm split1/0 split1/1 ``` ```js import { part } from '@barocss/cad/api'; const divided = part('block') .box({ w: 10, d: 20, h: 5 }) .split({ axis: 'x', at: 4 }); const names = divided.bodies(); // For this document: ['split1/0', 'split1/1'] const results = names.map(name => ({ name, mass: divided.body(name).mass({ density: 1 }), })); ``` For this box, the expected volumes from its dimensions are 400 mm³ and 600 mm³. At 1 g/cm³, the expected masses are 0.4 g and 0.6 g. These are calculated expectations, not a new captured API run. The sample test above checks the two volumes. Names use the split feature id and a side index; call `bodies()` to get the names for your own part. `body(name)` selects one result without changing the document. With two bodies and no selection, `mass()` and other single-body operations refuse with `BODY_AMBIGUOUS`. `meshes()` still returns all bodies, each with a `key`, so use the key to associate a display mesh with a body. You can also set an oblique plane with `split({ normal: [1, 1, 0], at: 10 })`: it is the plane `x + y = 10`. In general, the plane is `normal · [x, y, z] = at`; changing the scale of the normal changes that equation unless `at` is scaled by the same factor. The normal must be finite and have length greater than `1e-9`. A split plane that does not cross the target body is refused. ```js // A 20 mm cube with three 40 × 40 × 2 fins: the callback adds one fin and patterns it, and the patterned tool is joined. const finned = part('finned').box({ w: 20, d: 20, h: 20, x: -10, y: -10 }) .union(p => p.box({ w: 40, d: 40, h: 2, x: -20, y: -20, z: 4 }).linearPattern({ axis: 'z', spacing: 6, count: 3 })); const expected = 20 ** 3 + 3 * (40 * 40 - 20 * 20) * 2; ``` Two separate parts aren't combined: merging two documents would renumber one's ids, and so its names. ```js const ring = part('ring') .box({ w: 10, d: 10, h: 5, x: 20 }) .circularPattern({ count: 6 }) // six round Z, joined into one body .linearPattern({ axis: 'z', spacing: 10, count: 2 }) // two tiers .moved(Location.of({ position: [0, 0, 5], rotation: [90, 0, 0] })); // turned about X, then lifted assert.deepEqual(ring.doc.features.map(f => f.kind), ['sketch', 'extrude', 'circular-pattern', 'linear-pattern', 'rotate', 'translate']); ``` ### Results - `.mass({ density })` gives the chosen body's mass properties. The kernel keeps no material library, so it takes a density; cad-model's part also takes a material id. - `.step(name?)` writes every body as one STEP AP214 file and returns its text. - `.stepReport(name?)` uses the same name, all-body selection and export rules, and returns `{ text, source, omitted? }` when the backend supports reports. On the CAD model backend, `source` is the source document revision string. It does not identify a native or mesh representation. `omitted` contains the existing exporter's applicable loss messages, such as feature history, parameters, flattened assemblies, names, appearance, drawings, datums, infill or missing bounding-box validation. An absent list does not certify a loss-free interchange. The returned object and its optional list are detached data. Band sheets still cause the same typed export refusal; reporting does not enable a partial band-sheet export. The kernel CAD backend and external backends without this optional capability refuse with `UNAVAILABLE`; they do not invent a report from the legacy text. Other backends define their own source provenance string. - `.stl()` writes the body as binary STL. It's on the kernel part only. - `.meshes()` gives each body's display mesh as `{ key, positions, normals, indices, lines }`. `lines` are the display edges as segment pairs: the edges a selector offers, with seams and smooth joins left out. ```js const [mesh] = part().box({ w: 10, d: 20, h: 30 }).meshes(); assert.equal(mesh.lines.length, 12 * 2 * 3); // the box's 12 edges, each a segment of two points ``` ### Selectors - **Edges:** `along(axis)`, `straight()`, `curved()`, `on(face)`, `where(test)`, `sortBy(axis)`, `first(n)`, `last(n)`, `count`, `list()` and `names()`. - **Faces:** `facing('+z')`, `planar()` and `curved()`, the same filters and sorts, and `edges()`. - **What they offer:** the edges a person could pick in the studio, and nothing else. A cylinder's seam and the joint between a hole's two half-cylinders are left out, since there is no corner there to round. - **Names, not indices.** A selector resolves to the edges' persistent names, such as `n1.side0|n1.side1`, when the verb runs. Editing an earlier feature keeps the names, so the feature follows the same edges, or is refused, typed, when they are gone. It is never given other edges. ```js const plate = part('plate').box({ w: 60, d: 40, h: 8 }); const top = plate.select().faces().facing('+z'); assert.deepEqual(top.names(), ['n1.top']); assert.equal(top.edges().count, 4); // the top face's four edges assert.equal(plate.select().edges().along('z').count, 4); // the four vertical edges ``` ## CAD model part {#studio-parts} ```js import { part, assembly, Location, param, BarocssError } from '@barocss/cad-model/api'; ``` `@barocss/cad-model/api`'s `part()` builds a CAD model part over a `StudioDoc`. It shares the modeling interface with the CAD kernel part and adds document, material, drawing and manufacturing features. The same bracket can be written three ways as a CAD model document. The sample checks that all three ways give the same document, byte for byte. 1. **The document**, as the studio's commands write it. Besides the shape, it keeps: - the box's values (`made`), so picking it in the studio edits them again; - the face the hole went into (`face`); - each filleted edge's geometry where it was picked (`sigs`), so the fillet can find its edges again after an edit. ```js // 1. The document, as the studio's commands write it: the box's values remembered (`made`), the face the hole went // into, and each filleted edge's geometry where it was picked (`sigs`). const EDGES = ['n1.side0|n1.side1', 'n1.side0|n1.side3', 'n1.side1|n1.side2', 'n1.side2|n1.side3']; const raw = { format: 'barocss-cad-model', schema: 3, units: 'mm', parameters: {}, nodes: [ { kind: 'sketch', profile: 'rectangle', min: [0, 0], max: [80, 40], id: 'n0' }, { kind: 'extrude', sketch: 0, height: 10, id: 'n1', made: { command: 'box', values: { w: 80, d: 40, h: 10, x: 0, y: 0, z: 0 } } }, { kind: 'hole', parent: { node: 1, side: 'solid' }, radius: 4, center: [20, 20], face: 'n1.top', id: 'n2' }, { kind: 'fillet', parent: { node: 2, side: 'solid' }, edges: EDGES, radius: 2, id: 'n3', sigs: { 'n1.side0|n1.side1': { k: 'line', p: [80, 0, 5], d: [0, 0, 1], s: 10 }, 'n1.side0|n1.side3': { k: 'line', p: [0, 0, 5], d: [0, 0, 1], s: 10 }, 'n1.side1|n1.side2': { k: 'line', p: [80, 40, 5], d: [0, 0, 1], s: 10 }, 'n1.side2|n1.side3': { k: 'line', p: [0, 40, 5], d: [0, 0, 1], s: 10 }, } }, ], outputs: { b3: { node: 3, side: 'solid' } }, nextId: 4 }; ``` 2. **The agent's commands.** `run_command`, the features tool's `command`, with the faces and edges by persistent name. Written this way, each name has to be read from the result before it. ```js // 2. The agent's v2 commands (the features tool's `command`, run_command): the faces and edges by persistent name. const commands = [ { command: 'box', values: { w: 80, d: 40, h: 10, x: 0, y: 0, z: 0 } }, { command: 'hole', faces: ['n1.top'], values: { type: 'through', d: 8, x: 20, y: 20 } }, { command: 'fillet', edges: EDGES, values: { radius: 2 } }, ]; ``` 3. **The facade.** For this bracket, it uses the same command names and value names, with selectors in place of names. These calls run the studio's commands, as `run_command` does. ```js // 3. The facade: the same command names, the same value names (no unit suffix), the selectors in place of // the names. const bracket = part('bracket') .box({ w: 80, d: 40, h: 10 }) .hole(body => body.faces().facing('+z'), { d: 8, x: 20, y: 20 }) .fillet(body => body.edges().along('z'), { radius: 2 }); const mass = bracket.mass('al6061'); // or mass({ density: 2.7 }); native results also report method and an optional volumeBasis const step = bracket.step(); // STEP AP214 text const meshes = bracket.meshes(); // [{ key, positions, normals, indices }], one a body ``` - **Immutability.** ```js const plate = part('plate').box({ w: 60, d: 40, h: 8 }); const holed = plate.hole(body => body.faces().facing('+z'), { d: 6, x: 30, y: 20 }); assert.equal(plate.doc.nodes.length, 2); // the sketch and its extrude, still assert.equal(holed.doc.nodes.length, 3); const copy = holed.doc; copy.nodes.length = 0; assert.equal(holed.doc.nodes.length, 3); // changing the copy changes nothing ``` - **Materials.** `.mass()` takes a material id from the library, such as `al6061`, or `{ density }`. `.material(id)` sets the chosen body's material, or every body's, as the agent's `set_material` writes it. `.mass()` with no argument then weighs the body in it, and `.meshes()` carries the id for a scene to look up. ```js const plate = part('plate').box({ w: 60, d: 40, h: 8 }).material('al6061'); // as set_material writes it assert.equal(JSON.stringify(plate.mass()), JSON.stringify(plate.mass('al6061'))); // weighed in its own material assert.equal(plate.meshes()[0].material, 'al6061'); // for a scene to look up ``` ### Text from a font file `StudioPart.text(font, text, options)` creates a new independent output. `size` is the em height in mm and `h` is a positive extrusion height. `tolerance` is the explicit outline chord bound (default 0.01 mm). Optional `tracking` adds mm between scalars; optional `plane` supplies `origin`, `normal` and `xAxis`. Size, height and tracking can use the existing `Dim` parameter binding. Separate glyph components can remain several physical bodies in one output. ```js import { readFile } from 'node:fs/promises'; import { fontFromBytes, part } from '@barocss/cad-model/api'; const bytes = new Uint8Array(await readFile('./font.ttf')); const font = await fontFromBytes(bytes, { filename: 'font.ttf' }); const label = part('label').text(font, 'A', { size: 10, h: 2, tolerance: 0.002, tracking: 0.2, }); const doc = label.doc; ``` Supply an admitted static TrueType original. Optional `source` and `license` metadata are preserved as supplied; they are not inferred. The recipe keeps the original string, source and dimensions, while the blob store keeps the original bytes for the existing `.bcad` container path. There is no OS font lookup or fallback substitution. This call does not join existing bodies. Shaping, kerning, bidi, normalization and text wrap are not implemented. The separate bounded modifier below embosses or engraves a supported top face. See [Text from font outlines](/how/text) for input limits and refusals. ### Text relief on a top face `StudioPart.textRelief(selector, font, text, options)` modifies the selected body. The selector must return one exact unmerged +Z top face, for example `b => b.faces().facing('+z')`. The native target must be one closed line-only upright slab with one physical solid. Every filled text component must fit within both its actual material and that selected face's trim, with clearance for flatness and native policy. Overlap/contact between components, unsupported source representations and ambiguous face names are refused. ```js // Reuse the imported font source from the example above. const plate = part('label plate').box({ w: 40, d: 30, h: 10 }); const raised = plate.textRelief(b => b.faces().facing('+z'), font, 'A', { size: 10, depth: 2, at: [5, 5], mode: 'emboss', tolerance: 0.002, }); const pocket = plate.textRelief(b => b.faces().facing('+z'), font, 'A', { size: 10, depth: 2, at: [5, 5], mode: 'engrave', tolerance: 0.002, }); ``` Required options are `size`, positive `depth`, world-XY baseline `at:[x,y]`, and `mode:'emboss'|'engrave'`. Optional `tolerance` defaults to 0.01 mm and `tracking` to zero. Size, depth, both baseline coordinates and tracking accept existing `Dim` bindings. There is no plane option. Engrave must leave a bottom web above the existing native linear tolerance; emboss needs a represented positive raised height and seat. The result is one physical solid. The original font/string/recipe remains editable and uses the existing `.bcad` asset path. The selected Korean `가한` Model fixtures pass at size 10, at `[5,5]`, depth 2 and the default tolerance 0.01. The tighter Myeongjo engrave fixture at 0.002 explicitly refuses the unchanged work budget and keeps its requested tolerance. The API does not increase tolerance to force success. The source `plate` is unchanged. See [Text relief](/how/text#emboss-or-engrave-a-top-face) for limits and refusals. ### The studio's own commands The CAD model part provides these Studio commands as methods. For these calls, it writes what the agent's `run_command` writes. The kernel part has no `gear()`, `gearMesh()`, `spring()` or `fastener()` method. The CAD kernel also provides lower-level gear and spring functions through `@barocss/cad`; those functions have their own inputs and outputs. | Verb | v2 command | What it does | |---|---|---| | `gear({ m, teeth, b, shift?, helix?, hand?, bore?, x?, y?, z? })` | `gear` | An involute spur or helical gear, a body of its own | | `gearMesh({ teeth, dir, bore?, shift? })` | `gear-mesh` | A gear meshing with the chosen one, `dir` degrees from +X | | `spring({ type, d, D, n, p, ends, hand, … })` | `spring` | A coil spring of round wire, by the command's values | | `fastener({ kind, size, length?, joint?, grip?, x?, y?, z?, model? })` | `fastener` | A bolt, screw, nut or washer, from the document's fastener-size rows | ```js // A module-1.5 spur gear of 20 teeth, 10 wide, with a Ø20 bore; then a 40-tooth gear meshing with it along +X. const pair = part('pair') .gear({ m: 1.5, teeth: 20, b: 10, bore: 20 }) .gearMesh({ teeth: 40, dir: 0, bore: 16 }); const [pinion, wheel] = pair.bodies(); const centre = pair.body(wheel).mass({ density: 1 }).centroid; assert.ok(Math.abs(centre[0] - 1.5 * (20 + 40) / 2) < 1e-6); // the centre distance, m (z1 + z2) / 2 = 45 const spring = part('spring').spring({ type: 'compression', d: 2.5, D: 18, n: 5, p: 6, ends: 'closed-ground', hand: 'right' }); ``` - **Rows come from a person's file.** `loadRows(kind, { name, text })` loads a rows file as the studio's Library does, with a receipt naming the file. The facade never writes rows itself, and nothing is built in, so `fastener` is refused until fastener sizes are loaded. The same file always loads the same bytes. The sample uses the rows cad-model ships under `samples/rows/`. ```js // The fastener sizes cad-model ships as a sample; your own file loads the same way. None is built in. const sizes = { name: 'fastener-sizes.json', text: readFileSync(resolve(import.meta.dirname, '../../../packages/barocss-cad-model/samples/rows/fastener-sizes.json'), 'utf8') }; assert.throws(() => part('bolt').fastener({ kind: 'hex-bolt', size: 'M8', length: '60' }), e => e instanceof BarocssError && e.code === 'FASTENER_SIZE_ROW'); // no rows loaded: refused const bolt = part('bolt') .loadRows('fastener-sizes', sizes) // its receipt names the file, as the studio's Library writes it .fastener({ kind: 'hex-bolt', size: 'M8', length: '60' }); assert.equal(bolt.bodies().length, 1); ``` The CAD model part also has `loft()` for a solid through closed sections. See [Solid lofts with a copied guide](/packages/cad-model/#solid-lofts-with-a-copied-guide) for its inputs, limits and example. ## Parameters, configurations and suppression A parameter is a named value in the document's `parameters`, and a dimension follows it as the documents' own reference, `{ parameter: 'W' }`. `param('W')` writes one. Both parts write the document a person would make: the kernel part writes the reference into its feature, and the CAD model part binds it as the studio's feature editor does. ```js // An 80 × 40 × 10 plate, its width W and its corners' radius R parameters. const plate = part('plate').parameter('W', 80).parameter('R', 2) .box({ w: param('W'), d: 40, h: 10 }) .fillet(body => body.edges().along('z'), { radius: param('R') }); assert.deepEqual(plate.doc.parameters, { W: 80, R: 2 }); assert.deepEqual(plate.doc.features[0].max, [{ parameter: 'W' }, 40]); // the document's own reference const narrow = plate.withParameters({ W: 60 }); // a new part; the plate is unchanged assert.deepEqual(withParameters(plate.doc, { W: 60 }).parameters, { W: 60, R: 2 }); // the same, on a plain document // A 60-wide plate with its four corners rounded 2. const expected = 60 * 40 * 10 - 4 * (2 ** 2 - Math.PI * 2 ** 2 / 4) * 10; assert.ok(Math.abs(narrow.mass({ density: 1 }).volume - expected) < 1e-6 * expected); ``` - **`parameter(name, value)`** adds or sets a parameter. A name is a letter, then letters, digits and `_`, up to 32. `parameters()` lists them. - **`withParameters({ name: value })`** returns a new part at the new values. A document with features is re-evaluated before the method returns; its features keep the faces and edges they stored. The separate `withParameters(doc, edits)` function updates a plain document without evaluating it. - **Which options can follow a parameter.** Only one that lands as it is in one place in the document, the same rule as the studio's feature editor: - `box`: `w` and `d` while `x` and `y` are 0, and `h`; - `cylinder`: `x`, `y` and `h` (not `r`: the studio's editor edits the diameter); - `extrude`: `h`; `hole`: `x` and `y` (not `d`: the hole is stored by its radius); - `fillet`: `radius`; `chamfer`: `distance`; `shell`: `t`; `linearPattern`: `spacing`; `split`: `at`; - in the CAD model part also `revolve`'s `deg`, `linearPattern`'s `count` and `scale`'s `factor`, which a kernel document holds as plain numbers. Any other option given a parameter is refused with `PARAMETER_UNBINDABLE`, naming the ones that bind. A number is never written in its place. Sketch sizes and a `Location` take numbers only. ```js const p = plate(); assert.deepEqual(p.parameters(), { W: 80, R: 2 }); assert.deepEqual(p.doc.nodes[0].max, [{ parameter: 'W' }, 40]); // the sketch's far corner follows W assert.deepEqual(p.doc.nodes[2].radius, { parameter: 'R' }); // the fillet's radius follows R const narrow = p.withParameters({ W: 60, R: 3 }); assert.ok(near(volume(narrow), plateVolume(60, 3))); // the shape built with the new numbers assert.deepEqual(narrow.doc.nodes[2].edges, p.doc.nodes[2].edges); // the same named edges ``` - **Configurations** are the CAD model part's saved sets of parameter values. `configuration(name)` saves the current values, as the Parameters panel's Save; `withConfiguration(name)` applies them, as its Apply; `configurations()` lists them. ```js const p = plate().configuration('wide') // the current values, as the panel's Save .withParameters({ W: 60 }).configuration('narrow'); assert.deepEqual(p.configurations(), { wide: { W: 80, R: 2 }, narrow: { W: 60, R: 2 } }); const wide = p.withConfiguration('wide'); // its values applied, as the panel's Apply assert.deepEqual(wide.parameters(), { W: 80, R: 2 }); ``` - **Features and suppression.** `features()` lists each feature's `{ id, kind, label }`, the last one being the feature the last verb added. `suppressed(id)` switches a feature off and `suppressed(id, false)` back on, as the History panel's toggle does. A sketch, a split or a separate can't be switched off. It's the CAD model part's: the kernel document has no suppression yet, so the kernel part refuses it with `UNAVAILABLE`. ```js const p = plate(); assert.deepEqual(p.features().map(f => [f.id, f.kind]), [['n0', 'sketch'], ['n1', 'extrude'], ['n2', 'fillet']]); const sharp = p.suppressed('n2'); // as the History panel's toggle writes it assert.ok(near(volume(sharp), 80 * 40 * 10)); // the unrounded plate assert.equal(JSON.stringify(sharp.suppressed('n2', false).doc), JSON.stringify(p.doc)); // back, byte for byte ``` - **No expressions.** Neither document can store one, such as `W / 2`, so a dimension follows one parameter as it is. ## Assemblies `assembly(name, base?)` is an immutable assembly over the CAD model document. The base part is fixed at the origin. Placed parts are instances, each with its own document, and mates relate their faces. A supplied base and each `addPart` argument must be a `StudioPart` instance from the same loaded `@barocss/cad-model/api` package. Create it with that package's `part()` function. A kernel part or a plain document is not accepted; the facade refuses it with `VALUE`. The base argument can be omitted. ```js // A 60 × 40 × 8 plate with a Ø10 bore at (20, 20), and a Ø10 pin 30 long. const plate = part('plate').box({ w: 60, d: 40, h: 8 }).hole(b => b.faces().facing('+z'), { d: 10, x: 20, y: 20 }); const pin = part('pin').cylinder({ r: 5, h: 30 }); const fixture = assembly('fixture', plate) // the base part, fixed at the origin .addPart('pin', pin, { at: Location.at([100, 0, 0]) }) // placed off to the side .addMate('concentric', { part: 'base', face: b => b.faces().curved() }, { part: 'pin', face: b => b.faces().curved() }) .addMate('distance', { part: 'base', face: b => b.faces().facing('-z') }, { part: 'pin', face: b => b.faces().facing('-z') }, { distance: 0, flip: true }) // the bottoms flush .inputs({ depth: { type: 'number', unit: 'mm', default: 0, min: -10, max: 10, bindings: [{ to: 'mate', mate: 'm2', field: 'distance' }] } }) // an input driving the second mate .variants({ low: { depth: -5 } }) .frames({ tip: { link: 'pin', at: Location.at([0, 0, 30]), kind: 'tool' } }); assert.deepEqual(fixture.placements()[0].position, [20, 20, 0]); // solved: in the bore assert.deepEqual(fixture.variant({ depth: -5 }).placements()[0].position, [20, 20, 5]); assert.deepEqual(fixture.framePoses()[0].position, [20, 20, 30]); // the tip, on the pin's top assert.deepEqual(fixture.meshes().map(m => m.key), ['base/b2', 'p1/b2']); // each part where it stands ``` - **The verbs carry the agent's assembly action names.** Each writes what that action writes, and the assembly is solved again after it: - `addPart(name, part, { at?, grounded? })` is `add_part`, with the part's document as it is; - `place(name, { at?, grounded? })` is `place_part`; - `addMate(kind, a, b, { distance?, angle?, flip? })` is `add_mate`. Each end is `{ part, face, body? }`: the part is `'base'` or a placed part by its name, and the face is a selector picking one face, or a face name; - `inputs({ name: input | null })` and `variants({ name: values | null }, active?)` are `set_inputs` and `set_variants`. Bindings name parts and mates by id: `parts()` lists the parts' ids, and mates are `m1`, `m2` … in order; - `frames({ name: { link, at?, kind? } | null })` is `set_frames`. The link is a part by name, and `at` is a Location in that part's own coordinates. - `lock(name, to?)` fixes a placed part to another part, the base by default, at its current placement. For a face-selector callback, supply `body` with that part's body key when it has several bodies. With no `body`, only a single-body part is selected automatically. An unavailable or ambiguous body gives `NO_BODY` or `BODY_AMBIGUOUS`; a callback selecting zero or several faces gives `SELECTION_ONE`. A string face name does not use this callback body-selection step. Distance mates require a finite distance in mm. Angle mates require a finite angle from 0° to 180°, inclusive. Missing or non-finite facade values give `VALUE`; an out-of-range angle is refused with `MATE_FACES`. `addMate` normally moves the second end's part. If it is fixed and the first is free, the ends swap. Two fixed ends give `MATE_BOTH_FIXED`; ends on the same part give `MATE_SAME_PART`. `place` re-solves the mates, and `grounded: true` on a part already moved by a mate gives `PART_MATED`. - **Its results are plain data:** - `parts()`; - `placements()`: each placed part's id, name, `position` (mm), `rotation` (degrees) and grounding; - `problems()`: the mates left unmet; - `variant(values)`: an assembly with those input values, the master unchanged; - `framePoses()`: each frame's world pose, as `position` and `rotation`; - `meshes()`: `base/` and `/`, each part where it stands; - `part(name)`: a placed part as a CAD model part, in its own coordinates. - **`robot()`** gives the assembly's joints, kinematics, motion checks and robot exports. See [Robots](/studio/robots) for the supported joints and motion limits. - **Not yet in the facade:** editing a placed part in place; deleting or editing parts and mates; library parts; an assembly's STEP. ## Manufacturing inputs and outputs The CAD model part can set its manufacturing inputs and produce the same outputs as the agent's tools. These methods call the studio core. They keep its typed refusals. | Method | What it writes or returns | |---|---| | `process(id, { pull? })` | The part's process and, for a casting, its pull direction | | `casting(options)` | The pattern inputs, including machined faces, gate and shrinkage | | `drawingSettings(options)` | The drawing settings | | `autoDimension()` | Dimensions added by the drawing core | | `bought()` | The part's bodies marked as bought | | `named(name)` | The chosen body's display name | | `drawing()` | The sheet, its issues, and SVG, DXF and PDF files | | `await manufacturability(options?)` | The process report, as `check_printability` returns it | | `await camPackage(options?)` | The 2.5D CAM preview reply from `output_cam_package`, not for production | An assembly also has `drawingSettings(options)` and `drawing()`. Its `await bom()` returns the `output_bom` reply; `await purchaseCsv(withMade?)` returns the `output_purchase_csv` reply. The purchase list leaves out made parts unless `withMade` is true. A report can contain failed rules. Receiving it does not mean the part passed its checks. A CAM package needs stock rows from a person's file; without them it refuses with `STOCK_NONE_LOADED`. No stock table is built in. ### Product example: single-cylinder engine The repository's `examples/products/engine-1cyl/` uses the studio facade to build a single-cylinder four-stroke engine. Its merged milestone 3 includes manufacturing inputs, dimensioned drawings, reports, the BOM and the purchase list. The saved assembly is `engine.bcad`. `build.ts` constructs it; `check.ts` checks a saved document, regardless of how it was built. `engine.test.mjs` checks the saved build and includes a negative case with the piston's bore mate removed. The example's checks cover parts, assembly constraints, the slider-crank cycle, timing, sweep, masses, balance and outputs. Its unit tests omit the sweep; the full runner includes it. These are scripted checks. They do not establish live-agent or manufacturing acceptance. The example still has limits: - **Missing rows (PG-2).** The spark-plug thread and main bearings need rows from a source the owner supplies. The plain plug hole and bearing stand-ins do not establish a catalogue fit. - **Evaluation cost (PG-3).** The engine head and valve spring still need profiling. - **Example workarounds.** Although the core now supports cam mates, locked-gear coupling, running-fit contact and closed-loop motions, this saved example still builds gears into their shafts, parks its followers and uses its own cycle and sweep checks. Those newer core features do not by themselves verify a rebuilt engine. - **CAM waits (PG-9).** No stock list ships with the example. The output check accepts `STOCK_NONE_LOADED` as a named wait, so a passing check can still have no CAM package. - **Base-body names (PG-10).** The BOM still lists the base part's bodies by key, even when their display names are set. See [Shop rows](/studio/rows), [Manufacturing](/studio/manufacturing) and [BOM and quotes](/studio/bom) for the inputs these outputs need. ## Errors ```js const block = part().box({ w: 10, d: 10, h: 10 }); assert.throws(() => part().mass({ density: 2.7 }), e => e instanceof BarocssError && e.code === 'NO_BODY'); assert.throws(() => block.mass({ density: -1 }), e => e instanceof BarocssError && e.code === 'DENSITY'); assert.throws(() => part().box({ w: -1, d: 10, h: 10 }), e => e instanceof BarocssError && e.code === 'VALUE'); // A hole goes into one face: two picked is refused before the kernel. assert.throws(() => block.hole(body => body.faces().planar(), { d: 2, x: 5, y: 5 }), e => e instanceof BarocssError && e.code === 'SELECTION_ONE'); // A fillet too large for its walls: the kernel's refusal, with the feature it came from. assert.throws(() => block.fillet(body => body.edges().along('z'), { radius: 50 }).mass({ density: 2.7 }), e => e instanceof BarocssError && e.code === 'RADIUS_EXCEEDS_FACE' && e.where === 'evaluate' && e.details?.feature === 'fillet1' && e.message.startsWith('[RADIUS_EXCEEDS_FACE] ')); ``` - **The facade's own codes,** checked before the core: - the part: `NO_BODY`, `BODY_AMBIGUOUS`, `BODY_UNKNOWN`, `SELECTION_EMPTY`, `SELECTION_ONE` (a hole's selector picked more than one face, or a tool callback added more than one body), `FACE_NOT_FLAT`, `VALUE` (a value out of its range or type), `DENSITY`, `PARAMETER_NAME`, `PARAMETER_UNKNOWN`, `PARAMETER_UNBINDABLE` and `FEATURE_UNKNOWN`; - the CAD model part: `SELECTION_UNKNOWN` (a name not on the part), `UNAVAILABLE` (the studio's command can't run here), `MATERIAL_UNKNOWN`, `MASS_UNKNOWN` and `CONFIGURATION_UNKNOWN`; - the assembly: `NAME_TAKEN` and `PART_UNKNOWN`. - **The core's refusals pass through** with their own code and words. A kernel refusal keeps the feature it came from in `details.feature`; a studio one keeps the core's own words in `details.friendly`. A fillet too large for its walls is refused as `RADIUS_EXCEEDS_FACE` by both parts. ```js assert.throws(() => part().hole(body => body.faces().facing('+z'), { d: 4, x: 0, y: 0 }), e => e instanceof BarocssError && e.code === 'NO_BODY' && e.where === 'facade' && e.message.startsWith('[NO_BODY] ')); assert.throws(() => part().box({ w: 10, d: 10, h: 10 }).mass('unobtainium'), e => e instanceof BarocssError && e.code === 'MATERIAL_UNKNOWN'); // A fillet too large for its walls: the kernel's own code, with the core's words. assert.throws(() => part().box({ w: 10, d: 10, h: 10 }).fillet(body => body.edges().along('z'), { radius: 50 }).mass('al6061'), e => e instanceof BarocssError && e.code === 'RADIUS_EXCEEDS_FACE' && e.where === 'evaluate' && !!e.details?.friendly); ``` ## Scenes ```js import { scene, LINE_MATERIAL, BarocssError } from '@barocss/gpu/api'; import { part } from '@barocss/cad/api'; import { part as studioPart } from '@barocss/cad-model/api'; ``` A scene is an immutable description of meshes, each with its material, lights, a background and a camera view: ```js const bracket = part('bracket') .box({ w: 80, d: 40, h: 10 }) .hole(body => body.faces().facing('+z'), { d: 8, x: 20, y: 20 }); const view = scene() .add(bracket.meshes(), { color: '#c8ccd2', roughness: 0.5 }) .light({ kind: 'directional', direction: [-0.4, 0.6, -1] }) .background('#ffffff'); const data = view.data; assert.equal(data.frame, 'z-up'); // CAD coordinates as given, no conversion assert.equal(data.meshes.length, 1); assert.ok(data.meshes[0].positions instanceof Float32Array); // typed arrays only in the meshes (Float32, the common shape) assert.deepEqual(data.lights, [{ kind: 'directional', direction: [-0.4, 0.6, -1] }]); // show(viewer, view) clears the viewer, sets its lights and background, adds each mesh and fits the view. ``` - **Building it.** - `scene()` makes an empty scene. - `.add(meshes, material?, { lines? })` takes one mesh, or a part's `.meshes()`. The material is a Material, or the id of one the scene registered; without one, each mesh takes the scene material its body names. `lines: true` (or a Material) also adds each mesh's display lines as line geometry, keyed `/lines`, thin and dark by default (`LINE_MATERIAL`). - `.material(id, look)` registers a Material under an id: a part's material id, such as `al6061`, or one of your own. No look is built in for a material id. - `.light(light)` takes a directional, point or spot light, in the Viewer's own terms. - `.background(value)` takes a colour, a gradient or `'transparent'`. - `.camera(view, { projection?, fovY? })` takes `'iso'`, `'front'`, `'back'`, `'right'`, `'left'`, `'top'`, `'bottom'`, or `{ direction, up? }`: the direction from the scene to the eye. The top and bottom views keep +Y up, the others +Z. - **`.data`** is the plain description, with `frame: 'z-up'`. Material ids stay ids in it, and the looks are under `materials`. - **`show(viewer, scene)`** presents it through the Viewer's public methods only. It: - clears the viewer; - sets the lights and background, when the scene has them; - adds each mesh under its key, with its material resolved; - when the scene has a camera view, sets the camera's projection, field of view and up, and puts the eye along the view's direction; - fits the view. The Viewer stays the one stateful object. ```js const plate = studioPart('plate').box({ w: 60, d: 40, h: 8 }).material('al6061'); const view = scene() .material('al6061', { color: '#b8bcc2', metallic: 1, roughness: 0.35 }) // a look for the part's material id .add(plate.meshes(), undefined, { lines: true }) // each mesh in the look its body names, and its lines .camera('iso', { projection: 'orthographic' }); const { meshes, materials, camera } = view.data; assert.deepEqual(meshes.map(m => [m.key, m.topology ?? 'triangles', m.material]), [['b1', 'triangles', 'al6061'], ['b1/lines', 'lines', LINE_MATERIAL]]); assert.deepEqual(Object.keys(materials), ['al6061']); // the ids stay in the data; show() resolves them assert.deepEqual(camera.up, [0, 0, 1]); ``` - **Its errors.** `MESH_INVALID`, `LIGHT_INVALID`, `MATERIAL_UNKNOWN`, `MATERIAL_INVALID` and `CAMERA_INVALID`, in gpu's own `BarocssError` of the same shape: gpu imports neither cad package. ```js const empty = scene(), lit = empty.light({ kind: 'directional', direction: [0, 0, -1] }); assert.equal(empty.data.lights, undefined); // the first scene is unchanged assert.equal(lit.data.lights.length, 1); assert.throws(() => scene().add({ positions: new Float64Array([0, 0]) }), e => e instanceof BarocssError && e.code === 'MESH_INVALID'); ``` `show()` needs a browser with WebGPU, so this site's samples stop at `.data`. gpu's own tests check `show()` two ways: - against a stand-in viewer, for the calls it makes, in order; - in Chrome's WebGPU, on a hardware adapter and on SwiftShader. A plate with a bore is drawn from the top, orthographic: its top in al6061's registered look, the background through the bore, and a display line on the bore's rim. ## Not in the facades yet - **Expressions** in dimensions, and feature names of your own: the stable ids (`n3`, `fillet1`) serve. - **Suppression in the kernel part,** until the kernel document carries it. - **More of the assembly,** as listed under [Assemblies](#assemblies). --- # @barocss/cad-model For joint timing, pose sampling and the boundary with dynamics, see [Robot motion](/guide/robot-motion). The studio's model layer, on top of [the kernel](/packages/cad/). It holds: - the document and its evaluation; - the modelling commands; - the analyses and manufacturability checks; - drawings, BOMs, robots and libraries; - the agent's tools. It has no UI: no React, no DOM and no browser storage. An app, such as the studio, supplies those. ## Importing by path Prefer the curated domain entrypoints for new code: - `@barocss/cad-model/api` - `@barocss/cad-model/doc` - `@barocss/cad-model/engine` - `@barocss/cad-model/sketch` - `@barocss/cad-model/assembly` - `@barocss/cad-model/drawing` - `@barocss/cad-model/chat` - `@barocss/cad-model/versions` - `@barocss/cad-model/app` - `@barocss/cad-model/mfg` - `@barocss/cad-model/robot` Legacy per-file subpaths remain temporarily available during migration; the package's own root entry exports nothing. ```js import { part } from '@barocss/cad-model/api'; // the object facade import { evaluateDoc, exportStudioStep } from '@barocss/cad-model/engine/evaluate'; // the core, module by module import { encodeStudioFile, readStudioFile } from '@barocss/cad-model/engine/container'; import { revisionOf } from '@barocss/cad-model/util/revision'; ``` - **Version.** It is `0.0.0` and unreleased. Its API can change between versions: there is no compatibility promise yet. - **TypeScript sources.** Its modules are the TypeScript sources themselves, as with the kernel. - **Data files.** JSON data is imported by path too, such as `@barocss/cad-model/library/builtin/materials.json`, and the shipped sample rows are under `@barocss/cad-model/samples/rows/`. The `engine/font/trueType` reader takes a copied, bounded static TTF input and returns metrics and unhinted quadratic contours. `engine/font/source` stores original bytes with supplied filename/source/license metadata; `engine/font/profiles` converts admitted glyphs to component profiles at an explicit chord tolerance. The `kind: 'text'` recipe and `part().text()` build an independent native solid that stays editable after Save/Open. One authored output can hold several physical bodies. No top-level font registry or new document/container version is added. Studio supplies font upload and the Text HUD; the original test fonts are not runtime defaults. The separate `text-relief` modifier and `part().textRelief()` share the source/profile path for bounded +Z cap emboss or engrave; they retain one physical target solid and require actual material/selected-face containment. Shaping, kerning, bidi, normalization, general/curved face relief and text wrap remain unsupported. See [Text from font outlines](/how/text) and the [Text API example](/packages/api#text-from-a-font-file). | Module | What it holds | |---|---| | `api/` | The object facade over the data-and-functions core, imported as `@barocss/cad-model/api`. `part()` makes an immutable studio part and `assembly()` an immutable assembly, each method returning a new one, with typed edge and face selectors, `.doc`, plain results and one error class, `BarocssError`. See [Object API](/packages/api) | | `doc/` | Pure document data types (`StudioDoc`, `ModelNode`, domain, drawing, report and workflow types), node graph helpers, ids, labels, materials and validation | | `schema/` | Single-source Zod runtime schemas for document primitives, feature nodes and agent tool inputs, with JSON Schema export | | `history/` | Command-pattern undo/redo stack (`CommandStack`) for deterministic document mutations | | `engine/` | The studio document compat barrel (`doc`), its evaluation into bodies and meshes, ids, mesh blobs, the `.bcad` container, shop rows and their sources, flattening an assembly | | `engine/schema/` | The types of the brief, questions, references, drafts, requirements and proposals; their functions are in `chat/` | | `sketch/` | Sketch profiles, constraints, trim, offset, corners, splines, reading a DXF and its underlay | | `app/` | The modelling commands as data: shapes, edits, holes, fasteners and threads, sheet metal, mass, measure, materials | | `assembly/` | Placed parts and mates: solving, shared definitions and revisions, drag, exploded views | | `subd/` | Editing a SubD cage | | `frames/` | Frames and weldments: sections, skeletons and 3D sketches, welds, nesting into stock lengths | | `chat/` | The agent's tool layer: the handlers, the 13 tools (`toolset`, `groups`), the contract, the script language, and the brief's, questions' and proposals' functions | | `drawing/` | The 2D drawing: views, sections, dimensions, tolerances, tables, issues | | `print/` | The manufacturability report, 3D printing's rules and preparation, and 3MF | | `mould/` | Injection moulding: draft, undercuts, walls, the parting line, the quote package | | `machining/` | CNC milling and turning: holes, pockets, access and setups, stock, a 2.5D preview (not for production) | | `casting/` | Die and sand casting: the report and the pattern, from your casting rules | | `robot/` | The mates as a robot: joints, kinematics, inertia, dynamics, actuator sizing, URDF, MJCF, SDF and USD | | `library/` | Materials, process profiles, and standard and team part libraries, as data | | `standards/` | Values derived from standards, with their sources and licences | | `versions/` | Named versions of a document and its branches: making, listing and restoring versions, compare (what changed, feature by feature) and a three-way merge with typed conflicts | | `team/` | Export sources, several agents on one part, baselines, freshness, change requests, bundles | | `analysis/` | The analyses the agent asks for (mass properties, interference and clearance, sections, wall thickness, draft), and alignment against a reference part | | `bom/` | The bill of materials | | `io/` | Output formats: the drawing's SVG, PDF and DXF, and a zip writer with no dependencies | | `util/` | Small shared helpers: unit factors, guards, ids, rounding, SHA-256 digests, the document revision | ## Drawing text layout `tableSize` and `tableLayout` in `@barocss/cad-model/drawing/table` accept an optional final `textHeight` argument, in sheet millimetres. Pass the same height to both helpers so the reserved size matches the drawn table. `tableLayout` keeps its existing third `corner` argument; `textHeight` is fourth. `symbolMarks` and `weldSymbols` in `@barocss/cad-model/drawing/welds` also accept an optional final `textHeight`. Weld label placement measures the resulting text at that height. All four helpers default to 2.5 mm, and reject a non-finite or non-positive height with `RangeError`. `buildSheet` supplies 3 mm for these ordinary labels under its ASME preset. See [Drawing standard](/studio/drawings#drawing-standard) for the preset's scope and limits. ## Reading saved render settings Import `readRender` and `validateRenderShadowLights` from `@barocss/cad-model/engine/render`. `readRender(value)` returns `RenderSettings` with the reader's existing defaults and clamps. For a supplied `lights` array, it reads only the first 12 input entries, before skipping unknown light kinds. It then applies the shadow-field checks. Invalid shadow fields or caster counts throw `VALUE`. `validateRenderShadowLights(lights)` returns `void` without changing the supplied lights. It checks point/spot shadow fields and eligible caster counts. It does not validate GPU position, direction or range inputs. Invalid shadow fields or caster counts throw `VALUE`. See [Saved render light fields](/reference/document#saved-render-light-fields) for the stored fields, eligibility limits and radius rules. ## Transforming one body A studio part inherits `moved(location)` from the shared Part API. It returns a new part with transform features; it does not set an absolute assembly placement. Keep the returned part. Calling `moved` on that returned part applies the transform again to its current geometry, while the original part stays unchanged. Use `part.bodies()` to obtain current body keys. With several bodies, first choose `part.body(key)`; `moved` acts on that body, not every body in the document. A missing body gives `NO_BODY`, no choice among several gives `BODY_AMBIGUOUS`, and an unknown key passed to `body(key)` gives `BODY_UNKNOWN`. ```ts import { Location, type StudioPart } from '@barocss/cad-model/api'; function turnAndMove(part: StudioPart, bodyKey: string): StudioPart { return part.body(bodyKey).moved(Location.of({ rotation: [0, 0, 90], position: [30, 0, 0], })); } ``` `Location` rotations use degrees about the document origin, in X, then Y, then Z order. Translation follows in world XYZ millimetres. It does not rotate about the body's centre or use its bounding box as a pivot. For the location above, an illustrative point on the body follows this calculation: | Step | Point in mm | |---|---| | Input | `[10, 0, 0]` | | Rotate +90° about Z | `[0, 10, 0]` | | Translate by `[30, 0, 0]` | `[30, 10, 0]` | | Apply the same location again | `[20, 30, 0]` | ![A body point is rotated about the origin before translation; repeating moved applies another transform](/diagrams/part-transform-order.svg) [Open the diagram at full size](/diagrams/part-transform-order.svg). The diagram is a coordinate calculation, not an API render or a construction check. For placement of an assembly instance, use [the assembly API](/packages/api#assemblies); for other body transforms, see [Object API](/packages/api#parts). ## Writing a root body's STL Import `evaluateDoc` and `stlFor` from `@barocss/cad-model/engine/evaluate`. `stlFor` takes a `StudioDoc`, a root body's key from that document's evaluated bodies, and optional `segmentsPerQuarter` settings. This helper selects only the first evaluated root body: ```ts import type { StudioDoc } from '@barocss/cad-model/engine/doc'; import { evaluateDoc, stlFor } from '@barocss/cad-model/engine/evaluate'; function firstRootStl(doc: StudioDoc, revision: number): Uint8Array | null { const r = evaluateDoc(doc, revision); if (!r.ok || r.bodies.length === 0) return null; return stlFor(doc, r.bodies[0].key, { segmentsPerQuarter: 16 }); } ``` Supply `revision` as the caller's numeric evaluation tag; it is not the saved source-record revision. A successful evaluation can still produce `null` from `stlFor`, so check the helper's result before writing a file. A missing root body, a non-finite `segmentsPerQuarter`, or an unavailable tessellation returns `null`. The helper throws a `BarocssError` with code `STL_FLOAT32_COLLAPSE` if a valid triangle becomes degenerate in Float32, or `STL_FLOAT32_RANGE` if a coordinate cannot be written as a finite Float32. Surface these errors before writing files. The studio's [display-mesh fallback](/studio/files#exports) is a separate UI policy. ### STL and its source record To keep an STL with its source information, create both from the same document and pass the STL's exact filename to `sourceRecord`. The following helper returns two named files in memory; it does not write or download them. It returns `null` when evaluation fails, there is no root body, or tessellation is unavailable. It propagates the Float32 errors from `stlFor`. ```ts import type { StudioDoc } from '@barocss/cad-model/engine/doc'; import { evaluateDoc, stlFor } from '@barocss/cad-model/engine/evaluate'; import { sourceRecord, sourceBytes, sourceName } from '@barocss/cad-model/team/source'; type MemoryFile = { name: string; bytes: Uint8Array }; function firstRootStlFiles( doc: StudioDoc, revision: number, stlName = 'part.stl', ): [MemoryFile, MemoryFile] | null { const result = evaluateDoc(doc, revision); if (!result.ok || result.bodies.length === 0) return null; const bytes = stlFor(doc, result.bodies[0].key, { segmentsPerQuarter: 16 }); if (bytes === null) return null; const source = sourceRecord(doc, [stlName]); return [ { name: stlName, bytes }, { name: sourceName(stlName), bytes: sourceBytes(source) }, ]; } ``` The caller's numeric `revision` tags the evaluation. The source record's string `revision` instead identifies the document's canonical revision content. Its `digest` is the SHA-256 of that input content, not a checksum of the STL bytes or a certificate of geometric accuracy. `sourceName('part.stl')` gives `part.source.json`. Keep the returned pair together; after changing the document, produce a new pair rather than reusing the old record. ![STL bytes and their separate source-record JSON from the same document](/diagrams/stl-source-pair.svg) ### Reading a source record `sourceRecord(doc, files, options)` from `@barocss/cad-model/team/source` returns these fields: | Field | Meaning | |---|---| | `format` | The literal `barocss-source`. | | `version` | Record version `1`. | | `revision` | The 16-character hexadecimal revision from `revisionOf(doc)`, for detecting stale input. It covers the revision fields, not every saved document field. | | `digest` | SHA-256 of the UTF-8 canonical content used for that revision. It is not a checksum of the exported files. | | `files` | A copy of the supplied file-name list. It contains names, not file contents or checksums. | | `handSet` | Robot base-link and joint settings, included only with `{ robot: true }`. It is omitted by default. | `sourceBytes(record)` encodes the record as JSON bytes. `sourceName(name)` replaces the last extension with `.source.json`, or appends that suffix when there is no matching extension. It only derives a name; it does not validate a file name or make it safe for a destination path. When reading the JSON, treat `revision` and `digest` as identifiers for the recorded input content. Reading the record does not verify the named export files, authenticate the author, or establish physical accuracy. For robot exports, read `handSet` when present; its omission does not mean the robot used zero limits or ratings. Keep the record with the files it names and keep the editable `.bcad` document separately. The record is not a saved document and cannot reconstruct the model from its revision or digest. ## Bounded cylindrical wrap The Model facade selects the usual merged cylinder wall. The operation uses its original +Y half, first native quarter, and stores that individual native face and its signature. ```ts import { part } from '@barocss/cad-model/api'; const wrapped = part('Wrapped cylinder') .cylinder({ r: 10, h: 30 }) .cylindricalWrap(body => body.faces().curved(), { u0: 0.1, u1: 0.4, v0: 0.2, v1: 0.7, height: 10, }); const doc = wrapped.doc; ``` This supports one rectangle on an original upright cylinder at any XY center. Original UV must satisfy `0 < u0 < u1 < 0.5` and `0 < v0 < v1 < 1`; height can be any positive value within the modeling range. Mass comes from the evaluated closed reference. Literal stored-coefficient closure/mass and native-SI accuracy are not certified. Downstream features can consume the resulting solid. Reopening the recipe rebuilds its provider; a copied output cannot supply mass authority. See the [Studio flow and remaining limits](/studio/features#cylindrical-wrap). ## Solid lofts with a copied guide `part(...).loft(sections, options)` builds a solid from closed sketches. It returns a new part with the new body selected. Use that returned part or its `.doc`. The separate `directOps.loft()` operation below adds a surface to direct geometry. Supply sections in the intended order. Each section takes a `sketch` and exactly one of `z` or `frame`. A legacy `z` is a finite height in mm. Use one sketch plane and strictly increasing `z` values for that form. An explicit frame gives a world-mm `origin` and perpendicular unit `xAxis` and `yAxis` vectors. The single quadratic or cubic Bézier guide uses explicit frames. Its control points are in world mm. ```ts import { part, sketch, Plane } from '@barocss/cad-model/api'; const frame = (z: number) => ({ origin: [0, 0, z] as [number, number, number], xAxis: [1, 0, 0] as [number, number, number], yAxis: [0, 1, 0] as [number, number, number], }); const model = part('Cubic guided loft').loft([ { sketch: sketch(Plane.XY).circle({ r: 1 }), frame: frame(0) }, { sketch: sketch(Plane.XY.offset(3)).circle({ r: 4 }), frame: frame(3) }, ], { guide: { kind: 'cubic-bezier', controlPoints: [[1, 0, 0], [4, 0, 1], [2, 0, 2], [4, 0, 3]], }, }); const doc = model.doc; ``` The circles have radii of 1 and 4 mm on parallel caps 3 mm apart. The guide starts at `[1, 0, 0]` and ends at `[4, 0, 3]`, exactly at the caps' +X seams. Its inner controls lie on the planes at one-third and two-thirds of the cap separation: here, z = 1 and 2 mm. A `quadratic-bezier` guide takes exactly three finite control points, with its middle control on the exact cap midplane. A `cubic-bezier` guide takes exactly four, with its inner controls on the exact one-third and two-thirds planes. Both require exact seam endpoints. This is one bounded seam guide for two sections on parallel frames with identical axes. The Kernel checks the supported conic or homothetic mixed line/arc profiles and the existing coordinate limits. A refused loft leaves the previous part and inputs unchanged. To use the existing height-based path without a guide, omit the API `guide` option and supply `z` sections. Do not pass `null` or the string `'None'` as an API guide. In Studio, Shift-click two finished section sketches in the intended order, open **Loft**, then choose an available curve from **Guide (copied)**. Use that list: picking the curve separately in the viewport clears the sketch selection. A guided loft keeps the picked section order and their frames. **None**, the default, uses the existing section heights and height sorting. An imported guide must be one world-mm quadratic or cubic Bézier span, with exactly three or four controls, clamped end knots, no internal knots, and finite positive equal weights. Trimmed objects, unbaked transforms, and nonconstant rational weights are refused. Frames and guide controls are copied snapshots. A separately imported source curve does not become a live reference. Later changes to that curve or the caller's arrays do not update the stored loft. This construction does not certify manufacturing suitability. A polynomial `guide: { kind: 'nurbs', degree, knots, controlPoints }` uses the separate 2–8 ruled-height-section path. It supports degree 1–5 and up to 64 controls under the original monotone-height and section-vertex rules. A common non-XY sketch plane is supported. Raw explicit frames also admit two to eight ruled line/arc sections with identical certified rigid axes, positive ordered separation and exact world/local reconstruction of origins and guide controls. Circle and mixed arc profiles retain their original correspondence rules; inline ellipse objects, different axes and failed reconstruction witnesses are refused. The adapter builds and places the loft once, preserving the mass method and existing native SI `transformed` refusal. Studio can reopen the recipe and edit the source profile through existing Width/Depth fields. The source is copied without a new schema. See the [tested polynomial example and actual Studio preview](/how/loft-sweep#one-polynomial-guide-on-height-sections). ### Two guides between rectangular sections Pass `guides` with two quadratic Bézier curves and two axis-aligned rectangular sections on a common XY sketch plane. Use `z` for the section heights. The sections can have different sizes. Their depth-to-width ratio changes linearly with height. Express the guide controls in world mm. Use the minimum-Y corners from minimum X to maximum X. Both guides go from the lower section to the upper section. Put both middle controls at the halfway height. Keep the second middle control to the right of the first. ```ts import { part, sketch } from '@barocss/cad-model/api'; const rectangle = sketch().rectangle({ w: 10, d: 6, x: 0, y: 0 }); const model = part('Two-guide loft').loft([ { sketch: rectangle, z: 0 }, { sketch: rectangle, z: 12 }, ], { guides: [ { kind: 'quadratic-bezier', controlPoints: [[0, 0, 0], [2, 0, 6], [0, 0, 12]] }, { kind: 'quadratic-bezier', controlPoints: [[10, 0, 0], [14, 0, 6], [10, 0, 12]] }, ], }); const doc = model.doc; ``` Studio History can edit the middle X and Y of each copied guide. Use either `guide` or `guides` in one Loft. Use ruled sections with `guides`. ## Direct sweep and loft surfaces `directOps` from `@barocss/cad-model/engine/direct` works on direct curves. Its sweep and loft add a surface and return a new `DirectGeometry`; use the returned value. These operations differ from the [solid features made from sketches](/studio/features#from-a-sketch). - `directOps.sweep(direct, profileId, railId)` uses the first curve as the profile and the second as the rail. In authored XYZ coordinates, in mm, its surface follows `P(u) + R(v) - R(vMin)`. The profile translates without turning to follow the rail. This is not the feature Sweep that keeps a sketch square to its path. - `directOps.loft(direct, curveIds)` passes through 2–15 curves in the supplied order. It aligns degrees and interior knots, but the parameter-domain endpoints must already match within `1e-12`. This tolerance is in parameter values, not mm. A mismatch gives `DIRECT_RANGE`; trim or rebuild the curves to one parameter range. A curve count outside 2–15 gives `DIRECT_LOFT`. ```ts import { directOps, type DirectGeometry } from '@barocss/cad-model/engine/direct'; export function sweptSurface(direct: DirectGeometry, profileId: string, railId: string): DirectGeometry { return directOps.sweep(direct, profileId, railId); } export function loftedSurface(direct: DirectGeometry, orderedCurveIds: string[]): DirectGeometry { return directOps.loft(direct, orderedCurveIds); } ``` Supply IDs from the current direct geometry. Neither helper above commits a Studio document. ![A straight profile keeps its X direction as a curved rail translates it through three world-coordinate positions](/diagrams/direct-sweep-surface.svg) [Open the direct sweep diagram at full size](/diagrams/direct-sweep-surface.svg). The diagram is a calculated coordinate example, not an API render. For `P(u) = [10u, 0, 0]` and `R(v) = [0, 20v, 20v²]`, with `u` and `v` from 0 to 1, the rail starts at `[0, 0, 0]` mm. At `v = 0.5`, the profile runs from `[0, 10, 5]` to `[10, 10, 5]` mm; at `v = 1`, it runs from `[0, 20, 20]` to `[10, 20, 20]` mm. Its direction stays along X. This calculation does not establish that arbitrary input curves will pass the construction checks. ## Route bundles in code Import the route-bundle helpers from `@barocss/cad-model/engine/routeBundle`. A bundle ties one interior control pole on each of two curves to one translation in world millimetres. It does not join the curves or move each whole curve. The input must contain exactly two distinct direct curves. Each curve must be an open, clamped cubic with positive weights. Each member selects an existing interior pole by its numeric string `handleKey` and names an existing active `sweep-curve` feature and its earlier circular sketch profile. The profile must have a finite positive radius; associated or placed profiles, extra regions, and holes are outside this contract. Each copied sweep path must already match its direct curve. Members must use distinct curves, source geometries, profiles, and sweeps. A document can contain one bundle; nested bundle metadata is not supported. | Helper | Result and meaning | | --- | --- | | `createRouteBundle(doc, input)` | Returns a copied `StudioDoc` candidate with schema `4`, one tie, two members, and markers on the two sweeps. It uses existing inputs; it does not create the curves, profiles, or sweeps. | | `moveRouteBundle(frozenStart, bundleId, totalDeltaMM, expectedDocumentIdentity)` | Returns a candidate measured from the unchanged drag-start document. Both selected poles and the tie anchor receive the same total delta. Endpoints and all other poles remain fixed. The copied sweep paths are updated to match. | | `detachRouteBundle(doc, bundleId, expectedDocumentIdentity)` | Removes the bundle and its sweep markers, and returns a schema `3` candidate. It keeps the current curve coordinates and copied sweep paths. | | `assertRouteBundleDocument(input)` | Returns `void` if the route-bundle admission checks accept the input. It does not evaluate the whole model. | | `routeBundleDocumentIdentity(doc)` | Returns the full canonical document identity used by these helpers. Use this exact string, not `revisionOf(doc)` or a revision label. | `createRouteBundle` receives `expectedDocumentIdentity` in its input object. Move and detach receive it as their last argument. A stale identity or an invalid bundle input is refused with `BAD_REFERENCE`. The stored source binding and copied path must still match the current direct curve. The following helpers take IDs and selections from the caller's existing document. They return candidates only. Evaluate the whole candidate and commit it only after that evaluation succeeds. For a drag, also check that the accepted document still has `baseIdentity` before commit; discard the candidate if the document has changed. ```ts import type { StudioDoc } from '@barocss/cad-model/engine/doc'; import { assertRouteBundleDocument, createRouteBundle, detachRouteBundle, moveRouteBundle, routeBundleDocumentIdentity, type CreateRouteBundleInput, } from '@barocss/cad-model/engine/routeBundle'; type DeltaMM = [number, number, number]; type NewBundle = Omit; export function createRouteCandidate( accepted: StudioDoc, input: NewBundle, ): StudioDoc { assertRouteBundleDocument(accepted); return createRouteBundle(accepted, { ...input, expectedDocumentIdentity: routeBundleDocumentIdentity(accepted), }); } // Call once at drag start, after the bundle candidate has been accepted. export function beginRouteDrag(accepted: StudioDoc, bundleId: string) { const frozenStart = structuredClone(accepted); const baseIdentity = routeBundleDocumentIdentity(frozenStart); return { baseIdentity, candidateFromTotal(totalDeltaMM: DeltaMM): StudioDoc { return moveRouteBundle( frozenStart, bundleId, totalDeltaMM, baseIdentity, ); }, }; } export function detachRouteCandidate( accepted: StudioDoc, bundleId: string, ): StudioDoc { return detachRouteBundle( accepted, bundleId, routeBundleDocumentIdentity(accepted), ); } ``` For every drag update, call the same `candidateFromTotal` function with displacement from the drag start. Do not add frame deltas or use the previous candidate as a new start. The tie stores each selected pole's offset from its anchor; it does not force both poles onto the anchor. These helpers do not certify clearance, bend radius, sweep validity, or manufacturing suitability. See [the control-point diagram and Studio steps](/studio/features#route-bundles) and [the saved fields](/reference/document#route-bundle-fields). ### When a route edit is refused Route helper admission failures use `BAD_REFERENCE` with a `Route bundle:` message. They reject an invalid binding or candidate; they are not results from evaluating the complete model. | What failed | What to change | |---|---| | The accepted document identity changed, or a captured curve/source binding is stale. | Discard the old candidate. Start from the current accepted document and select the current curve and copied sweep again. Do not replace only the stored revision or canonical string to bypass the check. | | A copied sweep path does not match its current direct curve, or its sweep/profile ID is missing or ambiguous. | Restore a consistent document, make a matching copied sweep from the current curve, and select its current independent circular profile. An old copied path is not a fallback. | | The selected point is an endpoint, or the source is not an open clamped cubic with finite coordinates, valid knots and positive matching weights. | Choose an existing interior control point on a supported millimetre curve. Correct the source geometry before creating the binding. | | Members repeat an ID, curve, sweep, profile, or the same source/geometry pair through different object names. | Choose two distinct curve sources, each with its own sweep and profile. Renaming an alias does not make it a second source. | | Bundle data has the wrong schema, is nested in a placed/pending part, or has missing or orphan member markers. | Keep bundle data in one valid schema-4 base document with two matching members and markers. Detach a valid bundle before placing its document as a part; changing the schema number alone does not repair the bindings. | | Binding admission succeeds, but complete candidate evaluation fails. | Keep the accepted document and inspect the evaluation error. Correct the model or reduce the proposed edit, then evaluate the whole candidate again before committing. This failure is not necessarily a route admission `BAD_REFERENCE`. | The helpers return private candidates. The caller owns complete evaluation and commit; the Studio keeps the accepted document when a route preview or final check fails. These checks do not establish collision clearance, general constraint solvability or manufacturing suitability. ## Assembly and robot motions Use the `api/` facade's `assembly(...).robot()` to read an assembly as a robot. `robot.path(...)` takes at least two waypoints; `robot.motion(name)` reads a saved path. Joint inputs use degrees for turns and mm for slides. Velocity and acceleration limits use deg/s and deg/s², or mm/s and mm/s². ### Checking assembly clearance Call `clearance()` on an existing assembly to read its current clearance map. The method is asynchronous: ```js const result = await myAssembly.clearance({ near: 2 }); // mm console.log(result.map); console.log(result.files.find(file => file.path === 'clearance.json')); ``` Omit `near` to use 1 mm. A supplied value must be finite, greater than 0 and at most 10,000 mm; otherwise the call rejects with `OUTPUT_INPUT`. Evaluation failures also reject the call. It includes the base and visible placed parts; hidden placed parts are excluded. | Result | Meaning | |---|---| | `revision` | The document revision used for this output. | | `shopRows` | The resolved shop-row provenance for the assembly. | | `map` | The clearance map: its own `revision`, `near`, `pairs`, `pending` count and `timing`. The map revision identifies the pair poses; it is separate from the document revision. | | `files` | One `clearance.json` file with map fields, document revision and shop-row provenance. Its entry includes UTF-8 `text`, byte count and SHA-256 digest. The file's `revision` is the document revision: it replaces the map revision. Keep `result.map.revision` separately if you need the map revision. | The map measures the least gap on display meshes. It first selects candidates using bounding boxes expanded by the near distance. A candidate can have state `clear` when its measured gap is greater than `near`, so do not assume that every returned pair is within the band. Each pair identifies its bodies as `a` and `b` and includes `minGap` in mm, closest points in the respective body-local frames, face names and a pose key. `near` means the measured gap is positive and within the requested distance. `contact` means the mesh gap is zero, but it does not yet distinguish touching from a volume overlap. When exact solids are available, `overlap.pending` is `true` until a separate exact overlap check fills it; awaiting `clearance()` does not run that fill. If an exact solid is unavailable, `overlap.refused` explains why the distinction was not made. A `designed` pair identifies a declared seat or fit; it is not an approval of the assembly. Inspect both the pair states and pending or refused overlap fields. An empty pending count alone does not establish that an assembly has no interference. ### Reading pose and path results `poseAt(t)` returns joint inputs, not link placements. Pass that record to `robot.pose(...)` to obtain the pose. A pose reply has no overall `ok` flag; inspect the fields needed by your caller: | Result | Read it as | |---|---| | `robot.pose(values).values` | The resolved joint values, including followers, in degrees or mm. | | `links`, optional `frames` | Named link/frame positions in mm and rotations in degrees, in the assembly coordinates. | | `out_of_limits` | Joint keys outside their stored limits. A direct pose preview keeps those values rather than clamping them; a returned pose alone is not a readiness check. | | `path.check()` | An array with one sweep reply for each adjacent waypoint pair, in waypoint order, for supported open-chain paths. Read each reply's `clear`, optional `contact`, and `minClearance`. A reply whose sample budget ran out carries `exhausted` (with `clear: false` and no `contact`): that segment is not certified, neither clear nor in contact. | Given a robot and waypoints from the caller's current joint keys: ```ts import type { Robot } from '@barocss/cad-model/api/robot'; function sampleMotion( robot: Robot, waypoints: Record[], limits: Record, seconds: number, ) { const path = robot.path(waypoints, { limits }); const values = path.poseAt(seconds); return robot.pose(values); } ``` Supply positive velocity and acceleration limits for each moving joint, or a `default` entry. Use deg/s and deg/s² for turns, or mm/s and mm/s² for slides. Path timing does not read those rates from the document's joint settings. `poseAt` can refuse invalid paths; inspect `path.problems()` before playback. The two coordinates returned by these APIs have different meanings: `poseAt` takes time in seconds, while a sweep's `contact.s` and `minClearance.fraction` locate a dimensionless fraction of that waypoint segment. `contact.values` uses degrees/mm; `minClearance.value` is in mm. They do not give elapsed contact time. `minClearance` can be `null`, and `contact` is absent when no contact is returned. Do not treat missing data as zero. ![Robot path inputs become a pose reply; separate per-segment checks use a fraction rather than time](/diagrams/robot-motion-result-flow.svg) [Open the motion result diagram at full size](/diagrams/robot-motion-result-flow.svg). For supported looped paths, supply driving-joint values only. `duration()` returns seconds. `poseAt(t)` returns the driving values at time `t` in seconds; pass them to `robot.pose(...)` to obtain solved passive-joint values and link placements. `problems()` returns `[]` for a supported, closable path or reports a typed refusal. Extra passive-joint waypoint inputs give `LOOP_PASSIVE`; finite passive loop-joint bounds remain unsupported. Timing and loop closure do not certify collision clearance. `RobotPath.check()` still refuses looped paths with `LOOP_OPEN`: its sweep and continuous collision checks do not follow the closed motion. See [Robots in code](/studio/robots#in-code) for the motion contract and [Moving it](/studio/robots#moving-it) for the agent's supported loop checks and playback limits. `robot.inertia()` returns `{ links }`. Each link's `mass` and counted `bodies[].mass` use g; `centroid` uses mm. `inertia` is a nested 3×3 matrix about the centre of mass, expressed in the link frame, in g·mm². The centroid uses that same link frame. `principal.moments` uses g·mm²; `frame.origin` uses mm in the part's coordinates. Check each link's `bodies` and `issues` before using its totals. A body is excluded with `NO_VOLUME` when `volume` is `null`, or centroid or inertia data is absent. If no bodies are counted or their total mass is not positive, `NO_BODY` accompanies an empty `bodies` list and zero mass and inertia. Other issues identify assumed materials or failed inertia checks; a returned total alone does not establish a usable model. `robot.gravity(values, g)` returns joint-keyed `torques` and `generalized`; read `units[key]` for N·mm on turns or N on slides. Its returned `gravity` is a magnitude in mm/s², not the input vector. See [Robot unit boundaries](/studio/robots#robot-unit-boundaries) for the full public unit contract. ### Static gravity experiment `robot.gravityExperiment({ values, gravity })` captures one prescribed static pose and its gravity holding-torque report. Supply exactly one joint angle in degrees and an explicit finite three-component gravity vector in mm/s²; there is no gravity default. The profile admits exactly one connected open revolute or continuous joint, with no loops or couplings. Nested part occurrences in the moving part are outside this profile. Every moving body needs an explicit known material and positive finite mass. The moving link must have resolved inertia with finite components and no reported issues. The report's torque uses N·mm. It uses the existing Model link-inertia and gravity calculation. In this report, `inputs.gravity` is the supplied document world XYZ vector in mm/s², while `result.gravity` is its scalar magnitude in mm/s². The returned object's `report` getter gives a deep copy. Use `matches(doc, options)` to compare the complete captured document and explicit inputs with the current ones. If their canonical contents differ, `matches` returns false and the report is stale. This check does not rerun the calculation or certify integrity. The profile reports static holding torque, not free motion, contact, actuator suitability or physical validation. It does not change the Studio document schema. Studio's STATIC GRAVITY panel requires explicit joint, angle and world XYZ gravity inputs. Calculation leaves the viewport pose unchanged. Results stay local to the panel. Changed document or input contents mark them stale; a refused calculation can keep the previous result visible. This control calculates holding torque at a prescribed static pose; it does not simulate free motion. Call `record()` to keep an independent JSON record of the past calculation. Its envelope has format `barocss-gravity-experiment-record` and schema `1`. `toJSON()` returns an object; serialize it with `JSON.stringify()` and restore the text with `GravityExperimentRecord.parse()`. Studio document Save and Open are separate from this record JSON. With the supported `robot` and explicit `options` described above: ```js import { GravityExperimentRecord } from '@barocss/cad-model/api/experimentRecord'; const record = robot.gravityExperiment(options).record(); const data = record.toJSON(); const text = JSON.stringify(data); const restored = GravityExperimentRecord.parse(text); const preview = restored.preview; // Typed display fields, including torque in N·mm. const pastReport = restored.report; // unknown; the full past report. const inputsMatch = restored.matches(robot.doc, options); ``` `preview` and `report` return copies. Parsing rejects unsupported format, schema, calculation profile or units, non-finite JSON numbers, and invalid required structure or inconsistent bindings. It does not validate the complete inertia schema. A record describes a past calculation: parsing does not recalculate it, prove authenticity, or check compatibility with the current producer code or material catalogue. Consistent finite changes to numerical results can pass these checks. `matches(doc, options)` compares the full canonical document and explicit inputs; if either canonical content differs, it returns false and the record is stale. A matching record does not establish a new result. When present, a counted body's optional `materialSnapshot` retains `bodyMaterialId`, `inputMaterialId`, `resolvedMaterialId` and `fallback` (`none`, `unset` or `unknown-id`) from the calculation. `densityGPerCm3` is the density used, in g/cm³; it can differ from the declared `catalogueDensityGPerCm3` (number or null). The catalogue 0.7.0 version, source ID/text/page and estimate fields describe the declared row; they do not certify the used density, authenticity or measured properties. `inertiaSource` distinguishes `mmgs-density-scaled` from an actually applied `callback-override`. The mass density does not establish the source of the callback's inertia tensor. Older schema 1 records can omit these fields: no current catalogue values are filled in. The full `report` remains `unknown`. Each read of the separate `record.materialPreview` getter returns a detached typed copy of recorded material fields with link and body IDs. It returns `null` when `inertia.links` is absent. Missing per-body `materialSnapshot` or `inertiaSource` becomes `null`; empty bodies stay empty. For otherwise accepted records, material-field shape errors raise `VALUE` on getter access; `parse` keeps its existing finite-JSON checks. The existing `preview`, unknown `report`, `matches` and schema `1` remain unchanged. The getter does not fill missing fields from the current catalogue or certify authenticity, measured properties or current compatibility. Reading or displaying these historical fields does not recalculate the result or turn it into a new measurement. In Studio's STATIC GRAVITY panel, use the Download button to export the displayed record as independent JSON. Use `Open gravity record` to load it as a historical record, not a recalculated result, even when document and inputs match. Opening a valid record fills the joint, angle and world XYZ gravity fields. Choose `Calculate holding torque` to calculate again. An invalid file reports an error and preserves the previous record and input fields. These controls do not save or open a Studio document. Expand **Recorded material inputs** to read the recorded metadata. Missing metadata is marked **Not recorded**; invalid material metadata makes only this section unavailable. This does not change the existing Historical/Match/Stale status or the record operations. Use **Pin this record** to keep the displayed record for comparison, **Replace pinned record** to replace it explicitly, and **Unpin record** to clear it. Expand **Compare records** to inspect the pinned and current entries. Each entry checks the current document at that record's own saved inputs; the panel's Match/Stale status instead compares the current form inputs too. A finite recorded torque difference (current − pinned), in N·mm, appears only when joint, occurrence, coordinate frame, axis origin and axis direction match exactly. Historical records remain **not recalculated** even when document and inputs match. A difference does not establish cause, accuracy, measured validation or producer compatibility. The pin is local to the mounted panel and is cleared when that panel is removed. It is separate from document Save and record Download/Open. ### Experiment setup | Artifact | Save | Open | |---|---|---| | Studio document | Document Save keeps the model document. | Document Open restores it separately from experiment setups and records. | | Experiment setup | **Save setup** downloads the current form inputs and their document binding as JSON. | **Open setup** previews settings without changing the form, results or pinned record. | | Past result record | The existing record Download keeps a past calculation. | **Open gravity record** restores that historical record; it does not calculate again. | Under **Experiment setup**, the steps remain separate: - **Use inputs** copies the loaded setup inputs into the form without calculating. - **Run saved setup** uses the loaded inputs even when the form differs. After a document match and a successful calculation, it replaces the current result and updates the form to those inputs. A failed run keeps the previous form and result. - **Bind setup to current design** makes new loaded settings bound to the current document, keeping their inputs. It does not change the form, download a file or calculate. - **Save setup** always uses the form. To download rebound settings with the loaded inputs, first choose **Use inputs**, then **Save setup**. An invalid setup file keeps the previous loaded setup, form and result. Loaded settings are local to the panel and are lost when it is removed. Past record objects and the pinned record remain unchanged. In code, `create` and `parse` do not calculate. `toJSON()` and `options` return independent copies. For caller-supplied Studio documents and the explicit options described above: ```js import { GravityExperimentDefinition } from '@barocss/cad-model/api/experimentDefinition'; const definition = GravityExperimentDefinition.create(doc, options); const text = JSON.stringify(definition.toJSON()); const opened = GravityExperimentDefinition.parse(text); const copiedInputs = opened.options; if (opened.matches(currentDoc)) { const freshResult = opened.run(currentDoc); // Explicit calculation; it can still refuse. const newRecord = freshResult.record(); } const rebound = opened.rebind(changedDoc); // New settings, no calculation; opened is unchanged. ``` `matches(doc)` compares the full canonical document using the saved inputs; it does not establish execution readiness. `run(doc)` uses the caller's current document and refuses a mismatch with `VALUE` before calculation. It does not execute the stored document text. `rebind(doc)` keeps the inputs in a new definition. Only explicit `run` attempts a new result under the existing static-gravity limits; past records are unchanged. Setup input `units` has exactly two keys: `angle: 'degree'` and `gravity: 'mm/s²'`. The result report has six: `angle: 'degree'`, `length: 'mm'`, `mass: 'g'`, `inertia: 'g·mm²'`, `gravity: 'mm/s²'` and `torque: 'N·mm'`. Keep result units and calculated fields out of a setup. The existing result-record schema `1` and parser are unchanged. ### Input contracts Constructors, getters and operations follow the input rules below. These rules do not extend the supported motion contract above. - Direct `RobotPath` construction copies nested waypoints and limits; its getters return copies. - `Robot`, `RobotPath` and `Assembly` constructors also copy their input document. Changing that input later does not change the stored snapshot. `Robot.doc` and `Assembly.doc` return copies, as do the path's motion getters. Copying cost has not been measured. Inputs that cannot be cloned may fail at construction rather than later use. - Open-chain `duration()` checks the path on its robot's tree before timing it, as `poseAt()` does. Typed refusals use the first finding's code and message, with the findings in `details.problems`. - `robot.withMotion(name, path)` checks the destination robot's tree, including paths from another robot. It permits zero- or one-waypoint and untimed recording drafts; saving does not make them ready to play. For loops, it checks closure at each saved waypoint separately. This does not certify the intervening path, continuation through earlier seams, finite passive-joint bounds or sweep/CCD. - Motion waypoints must be records of finite numeric joint values. Malformed paths and path options give `VALUE`; malformed limits or explicitly supplied non-finite `velocity`, `acceleration` or `jerk` give `LIMITS_BAD`. Missing recording limits remain absent; this does not remove the draft allowance above or certify a whole path. - A studio part's `meshes()` returns copies of positions, normals, indices and lines. Editing those typed arrays does not change the core's cached mesh data. Passing them to a GPU Scene still shares those returned arrays with that Scene, as described in the [Scene input contract](/packages/gpu/#scene-geometry-input-candidate). - A process `pull` must have exactly three finite coordinates and match one of the existing six unit directions: positive or negative X, Y or Z. Other vectors give `VALUE`; this does not add arbitrary pull directions. - Material lookup for an unknown body gives `NO_BODY`. Locking an unknown child or target gives `NO_PART`; an unknown target is not treated as the base part. - Library-part options must be a non-null object, not an array, with a non-empty `face` string. `point` and an optional `xDirection` each require exactly three finite numbers. Malformed inputs give `VALUE`. ## The studio document The document is a `barocss-cad-model` file in millimetres. Ordinary documents use schema 3; an explicit route bundle uses schema 4: - **The model.** Its `nodes` are the features in order, with its parameters and outputs. - **Everything else on the part:** - placed parts and mates; - the drawing; - shop rows with their sources; - the process settings; - the brief and requirements; - proposals and history. [The .bcad document](/reference/document) lists the fields. The model converts to the kernel's part document to evaluate. In code, the [object facade](/packages/api) writes the document as the studio's own commands do, and the core evaluates it: ```js // A 40 × 20 × 5 plate, then a Ø6 hole through it. const plate = part('plate') .box({ w: 40, d: 20, h: 5 }) .hole(body => body.faces().facing('+z'), { d: 6, x: 10, y: 10 }); const doc = plate.doc; // the studio document, as the studio's own commands write it const result = evaluateDoc(doc, 1); // the core: the bodies, their display meshes and masses assert.ok(result.ok); const [body] = result.bodies; assert.ok(Math.abs(body.volume - (40 * 20 * 5 - Math.PI * 9 * 5)) < 1e-6); assert.equal(plate.mass('al6061').volume, body.volume); const step = exportStudioStep(doc, { name: 'plate' }); // the exact solids, naming the revision they came from assert.equal(step.source, revisionOf(doc)); ``` ## Evaluation and its caches `evaluateDoc(doc, revision)` evaluates a document into bodies. Each body has: - its key (`b`, from the feature that made it); - its display mesh, with its faces and edges; - its volume, mass and centroid; - its surface area; - its notes. The last evaluation is kept, and the next one reuses every kernel feature whose definition is unchanged, so editing one value re-runs only what depends on it. In the studio this runs in a worker, and a newer request makes an older reply stale (see [Revisions and sources](/guide/concepts#revisions-and-sources)). ```js const bytes = encodeStudioFile(doc); // plain JSON, or the BCADPACK container when it holds mesh data const back = await readStudioFile(bytes); assert.ok('doc' in back); assert.equal(revisionOf(back.doc), revisionOf(doc)); ``` ## Data rules - **Sources.** Every catalogue or standard value names its source: a public page with its address and the date read, a value derived by a stated rule, or an estimate marked as one. - **Your lists.** Lists a shop owns, such as stock, fastener sizes or casting rules, are yours to load. None is built in (see [Shop rows](/studio/rows)). - **No copied standards.** No standard's text or tables are copied. ## The agent's tools `chat/` is the tool layer the chat, `cad-mcp` and `cad-cli` serve: - `chat/toolset`: the 13 tools and the system prompt; - `chat/groups`: each action and its handler; - `chat/tools`: the dispatcher, with its autonomy and approval gates. See [Tools](/agent/tools). --- # CAD React `@barocss/cad-react` is a private workspace package. It describes CAD geometry with ordinary React components, lowers the committed geometry to the existing [CAD Model](/packages/cad-model/) document, and can connect an injected engine to the existing [Viewer](/packages/viewer/). The current package is TypeScript source in this repository. It is not a published npm package, a portable engine client, a distribution build or a standalone Worker. The host application supplies the engine, Worker setup and mass integration. Add it to a workspace consumer with `workspace:*`. ## What you can compose | Operation | Components | Result | |---|---|---| | Closed planar profile | `Rectangle`, `Circle`, `Polygon`, `Loop`, `Profile` | Profile input for Extrude or Revolve | | Solid extrusion | `Extrude` | Existing native extrusion of one profile | | Solid revolution | `Revolve` | Existing sketch-axis revolution of one closed profile | | Solid union | `Union` | Join at least two realized solids | | Ordered subtraction | `Difference`, `Target`, `Tools` | Subtract tools from one target | | Rigid placement | `Translate`, `Rotate` | Existing Model body-transform nodes | | Reuse | `Definitions`, typed object refs | Share a declared profile or solid within one Part | | Model lifecycle | `Part`, `ModelHost` | Commit declarations and coordinate an injected engine | | Display | `ExistingViewerHost` | Send engine display meshes to the existing Viewer | Read the [component catalog](/packages/cad-react/components), [references and compiler](/packages/cad-react/references), [engine and Viewer integration](/packages/cad-react/engine-viewer), [examples](/packages/cad-react/examples) and [support boundaries](/packages/cad-react/limits). ## A Part is a model root ```tsx import { Part, Extrude, Rectangle, type ModelLifecycle, } from '@barocss/cad-react'; export function Plate({ lifecycle }: { lifecycle: ModelLifecycle }) { return ; } ``` This declaration produces a model. It does not create an engine or a visible canvas by itself. Pass an appropriate lifecycle, such as a connected `ModelHost`, and provide the [display integration](/packages/cad-react/engine-viewer). React runs normal function components and hooks. Committed hidden DOM markers record membership and sibling order. The compiler does not call your component functions manually and does not infer their output from `React.Children` alone. Native feature IDs are automatic; no manual Sketch IDs or native body references are required. For the complete existing ModelNode inventory and the missing adapter backlog, read the [CAD Model support map](/packages/cad-react/support-map). Existing backend operations are broader than this first React subset; this page does not claim full CAD React coverage. ## Public entry points | Entry point | Runtime exports | |---|---| | `@barocss/cad-react` | `Part`, `Rectangle`, `Circle`, `Polygon`, `Loop`, `LineSegment`, `ArcSegment`, `Profile`, `Outer`, `Voids`, `Extrude`, `Revolve`, `Union`, `Difference`, `Target`, `Tools`, `Definitions`, `Translate`, `Rotate`, `CompositionCompiler`, `IrError` | | `@barocss/cad-react/engine` | `ModelHost` | | `@barocss/cad-react/viewer` | `ExistingViewerHost` | All public type exports are listed with their contracts on the component, references and engine pages. The package also exposes `@barocss/cad-react/sdk` (``, ``) used by BaroCSS Review and embedded CAD experiences. Examples use standard React hooks (`useRef`, `useState`, `useEffect`). --- # Components and props Import these components from `@barocss/cad-react`. Coordinates and lengths are in millimetres. Profiles are local XY geometry; extrusion and transforms lower to the existing Model operations. A React wrapper may return a compatible realized output: validation concerns the committed geometry, not the raw JSX child count. ## Detailed component pages Each supported React element has its own props, complete example, logical/native role, validation and measured-scope page. | Root and profiles | Solid operations | Operand slots and reuse | Placement | |---|---|---|---| | [Part](/packages/cad-react/components/part) | [Extrude](/packages/cad-react/components/extrude) | [Target](/packages/cad-react/components/target) | [Translate](/packages/cad-react/components/translate) | | [Rectangle](/packages/cad-react/components/rectangle) | [Union](/packages/cad-react/components/union) | [Tools](/packages/cad-react/components/tools) | [Rotate](/packages/cad-react/components/rotate) | | [Circle](/packages/cad-react/components/circle) | [Difference](/packages/cad-react/components/difference) | [Definitions](/packages/cad-react/components/definitions) | | | [Polygon](/packages/cad-react/components/polygon) | [Revolve](/packages/cad-react/components/revolve) | | | ## Part | Prop | Contract | |---|---| | `lifecycle` | Required `ModelLifecycle` object | | `admission` | Required literal `"synchronous"`; caller promises the supported synchronous composition boundary | | `units` | Optional `"mm"`, default `"mm"` | | `children` | Required React children producing exactly one solid output outside Definitions | `ModelLifecycle` has `dirty():void`, `invalid(error:unknown):void`, `complete(model:Compiled):void` and `detached():void`. A connected `ModelHost` implements this interface. Each Part is a separate model root; nested Parts are not geometry operands. `Part` is not a canvas and does not create a Worker. ## Profiles | Component | Props | Output | |---|---|---| | `Rectangle` | `min:[x,y]`, `max:[x,y]`, optional `ref:ProfileRef` | Closed profile with strictly positive X/Y extents | | `Circle` | `center:[x,y]`, positive finite `radius`, optional `ref:ProfileRef` | Closed circular profile | | `Polygon` | `points:readonly [x,y][]` with 3..1024 dense finite pairs, optional `ref:ProfileRef` | Closed ordered profile | Supply dense finite coordinate tuples. These components are profile producers, not standalone solid bodies. They do not expose a native face, a selected region, an arbitrary wire or a sketch-constraint editor. ## Polygon [Polygon](/packages/cad-react/components/polygon) accepts a readonly array of 3..1024 ordered dense finite coordinate pairs and optional `ProfileRef`. It produces one closed profile through existing polygon sketch storage. `PolygonProps` is exported. Native validity and refusal remain authoritative; no points are repaired, removed or resampled. ## Extrude | Prop | Contract | |---|---| | `distance` | Required finite nonzero length; positive and negative values lower to the existing native height | | `from` | Optional finite start coordinate along the local extrusion direction; omitted by default | | `children` | Exactly one realized profile, exclusive with `profile` | | `profile` | `ProfileRef`, exclusive with `children` | | `ref` | Optional `SolidRef` for the resulting solid | `ExtrudeProps` is the public prop type. The input is profile geometry. An internal Sketch node is a document-storage detail, not a public `sketch={...}` prop. Native face/region extrusion available elsewhere in Studio is not automatically a source capability here. ## Revolve Revolve accepts one closed profile child or typed `profile` reference, required sketch `axis="x"|"y"`, required finite angle in `(0,360]` degrees and optional finite two-coordinate origin. It returns a solid reference. The adapter lowers the existing Model node; it adds no native math. Declaration/types/lint checks and the selected rectangle90/180/360/Reset 90 actual flow pass; broader profile/axis/origin combinations remain unqualified. Read the [Revolve contract](/packages/cad-react/components/revolve). ## Union and Difference | Component | Props | Contract | |---|---|---| | `Union` | `children`, optional `ref:SolidRef` | At least two realized solid operands; combines them in declared order | | `Difference` | `children`, optional `ref:SolidRef` | Exactly one `Target` and one `Tools` group | | `Target` | One solid child **or** `solid:SolidRef` | The solid to cut; `TargetProps` is exported | | `Tools` | `children` | One or more realized solid tools, subtracted in declared order | ```tsx import { Difference, Target, Tools, Extrude, Rectangle, Circle } from '@barocss/cad-react'; export function HoledPlate() { return ; } ``` This is existing CAD Boolean evaluation, with the backend's native geometry/refusal limits. The JSX layer does not implement a new Boolean kernel or certify every operand arrangement. ## Translate and Rotate | Component | Required props | Optional props | |---|---|---| | `Translate` | `offset:[x,y,z]`, one solid input | `ref:SolidRef` | | `Rotate` | `axis:"x"|"y"|"z"`, `angle` in degrees, one solid input | `pivot:[x,y,z]`, `ref:SolidRef` | A solid input is exactly one realized solid child or `solid:SolidRef`. `SolidInput`, `TranslateProps` and `RotateProps` are exported. Offset and explicit pivot require three finite coordinates, including all three indexed array elements. Sparse arrays refuse. Angle must be finite with absolute value at most 3600; zero is allowed. An omitted pivot remains omitted and uses the existing backend origin default. ```tsx import { Translate, Rotate, Extrude, Rectangle } from '@barocss/cad-react'; export function PositionedPlate() { return ; } ``` The inner Rotate lowers before the outer Translate. No matrix or trigonometry is computed by the React layer. Accepted axes/angles are API input rules; they do not expand the finite [runtime evidence](/packages/cad-react/limits). ## Definitions, refs and standard React behavior `Definitions` takes `children` declaring profiles or solids for typed reuse. Its definitions do not add independent Part outputs. See [references](/packages/cad-react/references) for `ProfileHandle`, `SolidHandle`, `ProfileRef` and `SolidRef`. Normal function components, props, hooks, Fragments and keyed arrays can compose these components within synchronous admission. React keys and mounted identities preserve supported feature identity; remounting creates new identity. No component has a public native-ID prop. Internal Suspense/Offscreen/async behavior is outside admission, including when a wrapper hides it. ## Profile composition `Loop`, `LineSegment`, `ArcSegment`, `Profile`, `Outer`, and `Voids` compose multi-segment closed profiles with optional inner cutouts. | Component | Input and role | | --- | --- | | [Loop](/packages/cad-react/components/loop) | Ordered 1..1024 exact segment descriptors; optional profile ref | | [LineSegment](/packages/cad-react/components/line-segment) | Finite start pair inside Loop; no native ID or ref | | [ArcSegment](/packages/cad-react/components/arc-segment) | Finite start/center and explicit ccw/cw direction inside Loop | | [Profile](/packages/cad-react/components/profile) | Exactly one Outer, optional one Voids; optional profile ref | | [Outer](/packages/cad-react/components/outer) | Exactly one single-loop child or profile reference | | [Voids](/packages/cad-react/components/voids) | 1..64 single-loop children or dense profile references | `Profile` and `Loop` produce typed profile data; `Outer`/`Voids` and `LineSegment`/`ArcSegment` are structural descriptors rather than independent native features. Composite `Profile` emits one consumed sketch cleanly, `Circle` converts via exact loops, and `Extrude` admits explicit voids within native bounds. ## Hole [Hole](/packages/cad-react/components/hole) cuts an existing solid with numeric center/radius and optional axis, side and flat-bottom depth. Supply one solid child or `SolidRef`. Omitted depth requests a through hole. Native geometry and refusal remain authoritative. This component does not expose face selection, pointed drilling, threads or patterns. ## Declarative JSX DSL features (`@barocss/cad-react/dsl`) In addition to the synchronous host components above, `@barocss/cad-react/dsl` exposes a pure-functional JSX modeling DSL compiled by `compileCadElement` / `evaluateCadElement`, including parametric `param('name')` references and six advanced solid modeling components: | Component | Purpose | Key Props | | --- | --- | --- | | `Draft` | Taper selected faces about a neutral plane | `angle`, `pull` (`CadDraftPull`), `neutral`, `selector` (`CadFaceSelector`) or `select` callback | | `Mirror` | Mirror a solid across a plane (`'xy' \| 'xz' \| 'yz'`) | `plane` (`CadMirrorPlane`), `at`, optional `keep` | | `Split` | Conserved planar split along an axis or oblique normal | `axis` or `normal: [x, y, z]`, `at` | | `Loft` & `LoftSection` | Blend two or more planar or framed profile sections | `smooth`, child `` or `` | | `Sweep` | Sweep a `Circle` or `Profile` along a stepped path or NURBS rail | `path` (`straight` / `bend` segments) or `curve` (`CadSweepCurvePath`), `mode` | | `Rib` | Add a stiffening rib solid between bounding coordinates on a parent solid | `min: [x, y, z]`, `max: [x, y, z]` | ```tsx import { Part, Box, Draft, Mirror, Split, Loft, LoftSection, Sweep, Rib, Rectangle, Circle, param, evaluateCadElement, } from '@barocss/cad-react/dsl'; const bracket = ( ); const snapshot = evaluateCadElement(bracket); ``` --- # Part The model root and declaration lifecycle. Part is a logical React element, not a native feature node or a visible canvas. Import `Part` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `lifecycle` | Required ModelLifecycle | dirty, invalid, complete and detached callbacks; a connected ModelHost implements them. | | `admission` | Required "synchronous" | Explicit caller contract for supported synchronous composition. | | `units` | Optional "mm"; default "mm" | All source lengths are millimetres. | | `children` | Required ReactNode | Exactly one realized solid output outside any Definitions groups. | ## Example ```tsx import { Part, Extrude, Rectangle, type ModelLifecycle } from '@barocss/cad-react'; export function PlateModel({ lifecycle }: { lifecycle: ModelLifecycle }) { return ; } ``` The example includes its Part context and accepts a real lifecycle from its caller. It creates no Worker or canvas. ## Composition and validation React executes wrappers and hooks. Part records committed descendants and sends lifecycle changes; it neither calls component functions manually nor constructs a Worker. Supply the separate engine/Viewer integration to evaluate and display the model. Two solids outside Definitions refuse; combine them through Union or Difference. A profile alone is not a solid output. Nested Parts, portals and unsupported async boundaries are not model operands. A wrapper-hidden Suspense boundary is still outside synchronous admission. ## References and identity Mounted features use automatic IDs. Invalid declarations retain the compiler's last accepted document while the lifecycle retires freshness; previous visible geometry is not current success. Part does not reconnect source identity after reload. ## Measured boundary Original App/Bracket widths80→100→80 and the selected transformed W80 flow exercise this root with the real injected engine/Viewer. This does not cover arbitrary React scheduling or geometry. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Rectangle A closed axis-aligned profile in the local XY plane. The compiler lowers it to a native sketch-storage record when a consumer needs it; the logical component is a profile producer, not a solid. Import `Rectangle` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `min` | Required readonly [x,y] | Finite local XY millimetres. | | `max` | Required readonly [x,y] | Both coordinates must exceed the corresponding min coordinate. | | `ref` | Optional ProfileRef | Object token for reuse within this Part; no evaluated geometry is returned. | ## Example ```tsx import { Rectangle, Extrude } from '@barocss/cad-react'; export function RectangularPlate() { return ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation Place Rectangle under Extrude, or declare it in Definitions and pass its ProfileRef to an extrusion. Coordinates are local geometry, not pixel positions or a native face selection. Zero or reversed extents refuse. Supply dense finite two-coordinate tuples. A Rectangle cannot be a Union/Target/transform solid input and cannot be the sole solid output of Part. Rectangle has no arbitrary-polygon, rounded-corner or sketch-constraint prop. Use the separate Polygon producer for an ordered closed outline; its native geometry limits and evidence scope remain separate. ## References and identity Its optional ref has kind rectangle. Standard mounted identity and React keys support ID retention; there is no public id or sketch-ID prop. ## Measured boundary Floor, wall and window-tool rectangles are exercised by the measured Bracket examples. The positive-extents/API contract is broader than those selected measured sizes. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Circle A closed circular profile in local XY. It lowers to existing sketch storage for extrusion, not to a solid hole feature by itself. Import `Circle` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `center` | Required readonly [x,y] | Finite local XY millimetres. | | `radius` | Required positive finite number | Radius in millimetres, not diameter. | | `ref` | Optional ProfileRef | Object token whose handle kind is circle. | ## Example ```tsx import { Circle, Extrude } from '@barocss/cad-react'; export function CircularTool() { return ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation Circle produces a profile. Extrude turns it into a solid; place that solid in Tools to cut a target. Circle alone does not subtract material and does not infer a hole direction or depth. Nonfinite or nonpositive radius refuses. Supply a dense finite center tuple. A circle profile cannot be supplied where a solid ref or solid child is required. Native circular-face queries and selected planar regions are separate unsupported source capabilities. ## References and identity A ProfileRef may be forwarded through ordinary components or Definitions. Pass the object token, not ref.current; the handle contains kind metadata, not synchronous native geometry. ## Measured boundary The four radius3 floor-hole tools in the original and transformed Bracket flows are measured. This is not a certificate for every radius, placement or Boolean arrangement. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Polygon `Polygon` declares one closed planar profile from an ordered list of points. It lowers to the existing Model polygon sketch storage. It adds no Boolean, tolerance, triangulation or geometry-repair algorithm. ## Props | Prop | Contract | |---|---| | `points` | Required readonly array of 3 to 1024 dense finite `[x,y]` coordinate pairs | | `ref` | Optional `ProfileRef`, for reuse within the same Part | Coordinates are in mm on the current local XY plane. Points are copied in declared order. The final edge returns to the first point. Do not repeat the first point to ask the adapter to close or repair a loop. No point is removed, snapped or resampled. Native geometry validation can refuse degenerate, crossing, contacting or otherwise unsupported outlines after declaration validation succeeds. `PolygonProps` is exported. Polygon produces a profile, not a solid, face selection, wire, mesh or sketch-constraint scope. There is no public native-ID prop. Holes, regions, arbitrary planes and constraints remain separate source capabilities. ## Direct child ```tsx import {Polygon,Extrude} from '@barocss/cad-react'; export function PolygonPlate({width}:{width:number}) { return ; } ``` Place this component inside an existing Part and supply the existing engine/Viewer integration. Changing width changes the declared polygon and requests the existing native recalculation. This component adds no visible explanatory UI. ## Forward reference through an ordinary component ```tsx import * as React from 'react'; import {Polygon,Extrude,Definitions,type ProfileRef,type ProfileHandle} from '@barocss/cad-react'; function Outline({ref,width}:{ref?:ProfileRef;width:number}) { return ; } export function SharedPolygon({width}:{width:number}) { const outline=React.useRef(null); return <> ; } ``` The ref is optional. Pass the object token, not `.current`. Normal React props, state, wrappers and stable keys provide reuse and identity. A Polygon profile can also feed the existing Revolve child/ref contract. That type compatibility does not qualify every revolved outline. ## Validation and current evidence Counts outside 3..1024, missing array elements, inherited array elements, missing coordinates, nonfinite values and malformed coordinate pairs refuse. A rejected declaration retains the prior immutable compiled document and retires its freshness. A mounted feature keeps its IDs on supported updates; remounting creates a new identity. The current PolygonApp measures the pentagon shown above at widths 60 and 80 mm and an extrusion height of 8 mm. Public Width changes, blank-input refusal, valid recovery and Reset pass with the existing Worker and Viewer. The exact returned width-60 document opens through public Studio Open and Frame all. These selected convex plates have independent native volume, centroid, boundary and topology evidence. A separate settled-error observation confirms the visible coordinate error and retained previous frame without an extra native request. The package has 57 controlled tests, package/API-example types and lint passing. The native 3 to 1024 point budget is not a certificate for every outline, concave polygon or Polygon-based Revolve. See the support boundaries for the separate declaration and physical results. --- # Loop D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. ## Inputs and output children:1..1024realized LineSegment/ArcSegment descriptors; optional ref:ProfileRef. One closed localXY profile. Segment end is the next segment start; the last ends at the first start. A one-arc full circle is expressible. Geometry closure/radius/self-contact/native validity remain engine authority. Coordinates are millimetres on one localXY plane. Source values are copied, never snapped, repaired, deduplicated or resampled. Ordinary React wrappers, props, state, Fragments and keys remain supported under the existing synchronous Part contract. Typed refs are optional same-Part object tokens, not synchronous geometry queries. ```tsx import {Loop,LineSegment,Extrude} from '@barocss/cad-react'; export function LoopedPlate(){return ;} ``` Insert this composition under an existing Part with the existing engine/Viewer lifecycle. Part produces one logical named Model result, which can contain multiple native pieces. This does not select one native body or guarantee connected material. Future SolidSet describes multiple named Model outputs; Regions remains proposed and unexported. Missing/excess slots, incompatible realized kinds, mixed child/ref sources, missing/wrong-scope/duplicate/cyclic tokens and malformed new descriptor fields refuse. A rejected declaration retains the prior accepted immutable Doc and retires its freshness. Geometry-dependent touching/outside/clipping rules remain native and differ between Extrude and Revolve. No universal containment/contact refusal is claimed. The measured canonical case is a60×40×8 mm plate: one Loop of four LineSegments as Outer and one Loop with a full CCW ArcSegment as Voids, centered at[30,20], radius6→8→Reset6. All six new elements are realized. Two native captures and two exact-Doc reuses bind four original GUI consumers; one native body/one shell/genus1 is proved only for these states. Blank NaN input waits for visible Error and finite-coordinate alert, submits no extra engine call, retires freshness and retains the preceding radius8 frame. Collapse/reopen/idle/Reset also pass. Recorded Studio Open/F and its fresh Worker binding pass for the exact returned document at that source checkpoint, with source and cleanup verification. Full viewport fitting and raster precision are NOT_MEASURED; the Studio palette can occlude the plate. No general topology, face/UV, NURBS, arbitrary-hole, release or mobile qualification follows. The example above is a declaration example. Physical evidence comes from the pinned all-six SegmentedProfiledPlate recipe; equal dimensions do not create an additional producer certificate. --- # LineSegment D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. ## Inputs and output start:required dense finite readonly[x,y] pair. No ref, end or native ID prop. A descriptor inside Loop. It does not create a native sketch, profile, solid or persistent native edge by itself. The next segment start defines its end. Coordinates are millimetres on one localXY plane. Source values are copied, never snapped, repaired, deduplicated or resampled. Ordinary React wrappers, props, state, Fragments and keys remain supported under the existing synchronous Part contract. Typed refs are optional same-Part object tokens, not synchronous geometry queries. ```tsx import {Loop,LineSegment} from '@barocss/cad-react'; export function Boundary(){return ;} ``` Place this segment inside Loop; consume that Loop through Extrude, or as an Outer/Voids input inside Profile consumed by Extrude. Mount the complete solid recipe under Part with the existing engine/Viewer lifecycle. Part produces one logical named Model result, which can contain multiple native pieces. This does not select one native body or guarantee connected material. Future SolidSet describes multiple named Model outputs; Regions remains proposed and unexported. Missing/excess slots, incompatible realized kinds, mixed child/ref sources, missing/wrong-scope/duplicate/cyclic tokens and malformed new descriptor fields refuse. A rejected declaration retains the prior accepted immutable Doc and retires its freshness. Geometry-dependent touching/outside/clipping rules remain native and differ between Extrude and Revolve. No universal containment/contact refusal is claimed. The measured canonical case is a60×40×8 mm plate: one Loop of four LineSegments as Outer and one Loop with a full CCW ArcSegment as Voids, centered at[30,20], radius6→8→Reset6. All six new elements are realized. Two native captures and two exact-Doc reuses bind four original GUI consumers; one native body/one shell/genus1 is proved only for these states. Blank NaN input waits for visible Error and finite-coordinate alert, submits no extra engine call, retires freshness and retains the preceding radius8 frame. Collapse/reopen/idle/Reset also pass. Recorded Studio Open/F and its fresh Worker binding pass for the exact returned document at that source checkpoint, with source and cleanup verification. Full viewport fitting and raster precision are NOT_MEASURED; the Studio palette can occlude the plate. No general topology, face/UV, NURBS, arbitrary-hole, release or mobile qualification follows. The example above is a declaration example. Physical evidence comes from the pinned all-six SegmentedProfiledPlate recipe; equal dimensions do not create an additional producer certificate. --- # ArcSegment D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. ## Inputs and output start and center:required dense finite readonly[x,y] pairs; direction:required ccw|cw. No angle, ref or native ID prop. An exact native arc descriptor inside Loop. No tessellation or inferred tangent/radius is computed by React. A single arc returns to its own start as a full circle; native validity remains separate. Coordinates are millimetres on one localXY plane. Source values are copied, never snapped, repaired, deduplicated or resampled. Ordinary React wrappers, props, state, Fragments and keys remain supported under the existing synchronous Part contract. Typed refs are optional same-Part object tokens, not synchronous geometry queries. ```tsx import {Loop,ArcSegment} from '@barocss/cad-react'; export function CircularVoid(){return ;} ``` Place this segment inside Loop; consume that Loop through Extrude, or as an Outer/Voids input inside Profile consumed by Extrude. Mount the complete solid recipe under Part with the existing engine/Viewer lifecycle. Part produces one logical named Model result, which can contain multiple native pieces. This does not select one native body or guarantee connected material. Future SolidSet describes multiple named Model outputs; Regions remains proposed and unexported. Missing/excess slots, incompatible realized kinds, mixed child/ref sources, missing/wrong-scope/duplicate/cyclic tokens and malformed new descriptor fields refuse. A rejected declaration retains the prior accepted immutable Doc and retires its freshness. Geometry-dependent touching/outside/clipping rules remain native and differ between Extrude and Revolve. No universal containment/contact refusal is claimed. The measured canonical case is a60×40×8 mm plate: one Loop of four LineSegments as Outer and one Loop with a full CCW ArcSegment as Voids, centered at[30,20], radius6→8→Reset6. All six new elements are realized. Two native captures and two exact-Doc reuses bind four original GUI consumers; one native body/one shell/genus1 is proved only for these states. Blank NaN input waits for visible Error and finite-coordinate alert, submits no extra engine call, retires freshness and retains the preceding radius8 frame. Collapse/reopen/idle/Reset also pass. Recorded Studio Open/F and its fresh Worker binding pass for the exact returned document at that source checkpoint, with source and cleanup verification. Full viewport fitting and raster precision are NOT_MEASURED; the Studio palette can occlude the plate. No general topology, face/UV, NURBS, arbitrary-hole, release or mobile qualification follows. The example above is a declaration example. Physical evidence comes from the pinned all-six SegmentedProfiledPlate recipe; equal dimensions do not create an additional producer certificate. --- # Profile D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. ## Inputs and output children:exactly one Outer and at most one Voids; optional ref:ProfileRef. Closed profile data with explicit void loops. It emits only its own native sketch when an operation consumes it; descriptor sources are not emitted merely to assemble this profile. No Regions, arbitrary plane, raw Model, face or constraint prop. Coordinates are millimetres on one localXY plane. Source values are copied, never snapped, repaired, deduplicated or resampled. Ordinary React wrappers, props, state, Fragments and keys remain supported under the existing synchronous Part contract. Typed refs are optional same-Part object tokens, not synchronous geometry queries. ```tsx import {Profile,Outer,Voids,Rectangle,Circle,Extrude} from '@barocss/cad-react'; export function BoredPlate({radius}:{radius:number}){return ;} ``` Insert this composition under an existing Part with the existing engine/Viewer lifecycle. Part produces one logical named Model result, which can contain multiple native pieces. This does not select one native body or guarantee connected material. Future SolidSet describes multiple named Model outputs; Regions remains proposed and unexported. Missing/excess slots, incompatible realized kinds, mixed child/ref sources, missing/wrong-scope/duplicate/cyclic tokens and malformed new descriptor fields refuse. A rejected declaration retains the prior accepted immutable Doc and retires its freshness. Geometry-dependent touching/outside/clipping rules remain native and differ between Extrude and Revolve. No universal containment/contact refusal is claimed. The measured canonical case is a60×40×8 mm plate: one Loop of four LineSegments as Outer and one Loop with a full CCW ArcSegment as Voids, centered at[30,20], radius6→8→Reset6. All six new elements are realized. Two native captures and two exact-Doc reuses bind four original GUI consumers; one native body/one shell/genus1 is proved only for these states. Blank NaN input waits for visible Error and finite-coordinate alert, submits no extra engine call, retires freshness and retains the preceding radius8 frame. Collapse/reopen/idle/Reset also pass. Recorded Studio Open/F and its fresh Worker binding pass for the exact returned document at that source checkpoint, with source and cleanup verification. Full viewport fitting and raster precision are NOT_MEASURED; the Studio palette can occlude the plate. No general topology, face/UV, NURBS, arbitrary-hole, release or mobile qualification follows. The example above is a declaration example. Physical evidence comes from the pinned all-six SegmentedProfiledPlate recipe; equal dimensions do not create an additional producer certificate. --- # Outer D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. ## Inputs and output exactly one realized single-loop profile child OR profile:ProfileRef; never both. Structural Profile slot. Rectangle/Circle/Polygon/Loop or a Profile without holes can supply it. A nested profile with holes refuses instead of losing its holes. No native node/ID/ref of its own. Coordinates are millimetres on one localXY plane. Source values are copied, never snapped, repaired, deduplicated or resampled. Ordinary React wrappers, props, state, Fragments and keys remain supported under the existing synchronous Part contract. Typed refs are optional same-Part object tokens, not synchronous geometry queries. ```tsx import * as React from 'react'; import {Profile,Outer,Rectangle,Definitions,Extrude,type ProfileHandle} from '@barocss/cad-react'; export function ReusedOuter(){const outline=React.useRef(null);return <> ;} ``` Insert this composition under an existing Part with the existing engine/Viewer lifecycle. Part produces one logical named Model result, which can contain multiple native pieces. This does not select one native body or guarantee connected material. Future SolidSet describes multiple named Model outputs; Regions remains proposed and unexported. Missing/excess slots, incompatible realized kinds, mixed child/ref sources, missing/wrong-scope/duplicate/cyclic tokens and malformed new descriptor fields refuse. A rejected declaration retains the prior accepted immutable Doc and retires its freshness. Geometry-dependent touching/outside/clipping rules remain native and differ between Extrude and Revolve. No universal containment/contact refusal is claimed. The measured canonical case is a60×40×8 mm plate: one Loop of four LineSegments as Outer and one Loop with a full CCW ArcSegment as Voids, centered at[30,20], radius6→8→Reset6. All six new elements are realized. Two native captures and two exact-Doc reuses bind four original GUI consumers; one native body/one shell/genus1 is proved only for these states. Blank NaN input waits for visible Error and finite-coordinate alert, submits no extra engine call, retires freshness and retains the preceding radius8 frame. Collapse/reopen/idle/Reset also pass. Recorded Studio Open/F and its fresh Worker binding pass for the exact returned document at that source checkpoint, with source and cleanup verification. Full viewport fitting and raster precision are NOT_MEASURED; the Studio palette can occlude the plate. No general topology, face/UV, NURBS, arbitrary-hole, release or mobile qualification follows. The example above is a declaration example. Physical evidence comes from the pinned all-six SegmentedProfiledPlate recipe; equal dimensions do not create an additional producer certificate. --- # Voids D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. ## Inputs and output 1..64realized single-loop profile children OR profiles:readonly ProfileRef[]; never both. Reference list must be dense. Structural Profile slot that uses existing exact Model loopOf conversion. A Circle becomes one full CCW arc; it is not sampled. Omit Voids entirely for no holes; an empty live Voids refuses. No inferred containment, Regions, native IDs or own ref. Coordinates are millimetres on one localXY plane. Source values are copied, never snapped, repaired, deduplicated or resampled. Ordinary React wrappers, props, state, Fragments and keys remain supported under the existing synchronous Part contract. Typed refs are optional same-Part object tokens, not synchronous geometry queries. ```tsx import * as React from 'react'; import {Profile,Outer,Voids,Rectangle,Circle,Definitions,Extrude,type ProfileHandle} from '@barocss/cad-react'; export function ReusedVoid(){const bore=React.useRef(null);return <> ;} ``` Insert this composition under an existing Part with the existing engine/Viewer lifecycle. Part produces one logical named Model result, which can contain multiple native pieces. This does not select one native body or guarantee connected material. Future SolidSet describes multiple named Model outputs; Regions remains proposed and unexported. Missing/excess slots, incompatible realized kinds, mixed child/ref sources, missing/wrong-scope/duplicate/cyclic tokens and malformed new descriptor fields refuse. A rejected declaration retains the prior accepted immutable Doc and retires its freshness. Geometry-dependent touching/outside/clipping rules remain native and differ between Extrude and Revolve. No universal containment/contact refusal is claimed. The measured canonical case is a60×40×8 mm plate: one Loop of four LineSegments as Outer and one Loop with a full CCW ArcSegment as Voids, centered at[30,20], radius6→8→Reset6. All six new elements are realized. Two native captures and two exact-Doc reuses bind four original GUI consumers; one native body/one shell/genus1 is proved only for these states. Blank NaN input waits for visible Error and finite-coordinate alert, submits no extra engine call, retires freshness and retains the preceding radius8 frame. Collapse/reopen/idle/Reset also pass. Recorded Studio Open/F and its fresh Worker binding pass for the exact returned document at that source checkpoint, with source and cleanup verification. Full viewport fitting and raster precision are NOT_MEASURED; the Studio palette can occlude the plate. No general topology, face/UV, NURBS, arbitrary-hole, release or mobile qualification follows. The example above is a declaration example. Physical evidence comes from the pinned all-six SegmentedProfiledPlate recipe; equal dimensions do not create an additional producer certificate. --- # Extrude Turns one supported closed profile into a solid using the existing Model extrusion. Sketch lowering is internal storage; there is no public sketch prop. Import `Extrude` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `distance` | Required finite nonzero number | Signed extrusion height in millimetres; no default. | | `from` | Optional finite number | Local starting coordinate; omission preserves the existing backend default at the local origin. | | `children` | Exactly one realized profile | Exclusive with profile. | | `profile` | ProfileRef | Exclusive with children. | | `ref` | Optional SolidRef | Reuse the resulting solid within this Part. | ## Example ```tsx import { Extrude, Rectangle } from '@barocss/cad-react'; export function Floor() { return ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation Extrude accepts Rectangle/Circle/Polygon output and, in the D509 implementation, Loop/Profile output, including a compatible output returned by a synchronous wrapper or resolved ProfileRef. ExtrudeProps names the public exclusive-input type. The result can feed Union, Difference or a rigid transform. Zero/nonfinite distance or nonfinite from refuses. Both child and profile, multiple profiles, a solid token as profile, and arbitrary face/region descriptors refuse. Surface/face extrusion supported elsewhere in Studio is not automatically admitted here. ## References and identity The result is a solid handle of kind extrude. Feature IDs and the profile sketch linkage are automatic; source props do not expose native node indices. ## Measured boundary The Polygon producer uses the same profile child/ref contract. D504 qualifies the selected convex pentagon at widths 60 and 80 mm and an extrusion height of 8 mm, with current native, Worker, Viewer and returned-document Studio evidence. Other outlines remain outside that physical proof. Numeric declaration checks do not replace native outline validity. The measured Bracket uses floor6, wall56 and declared overcut tools, with original widths80/100 and selected W80 transforms. Positive/negative distance input support is not a runtime certificate for all heights/directions. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). ## D509 profile composition D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. Loop and Profile produce closed-profile data. Outer/Voids and LineSegment/ArcSegment are structural descriptors, not extra native features. Extrude.profile, old Rectangle/Circle/Polygon lowerings and staged identities remain compatible. Exact circle conversion uses the existing helper with no sampling. Regions, arbitrary plane/face inputs, constraints and Sweep/Loft adapters remain unexported. Holed Revolve keeps its own native admission and remains physically unqualified by this Extrude case. No universal contact/containment repair or refusal is promised. Part remains one logical Model result that can contain multiple native pieces. --- # Revolve Revolve turns one closed profile into a solid through the existing CAD Model revolve node. Provide a profile, a sketch axis and an angle. The result is a solid that other operations can use. The selected rectangle example below has current browser, native geometry and Studio Open evidence. Import `Revolve` from `@barocss/cad-react`. The package is private, version `0.0.0`; it is not a published portable install. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `axis` | Required `x` or `y` | Axis in the existing sketch plane convention. | | `angle` | Required finite number greater than 0 and at most 360 | Degrees. There is no adapter default. | | `origin` | Optional readonly `[x,y]` | Explicit finite sketch coordinates in mm; omission stays omitted. Existing backend supplies `[0,0]`. | | `children` | One realized profile | Exclusive with `profile`. | | `profile` | Typed ProfileRef | Exclusive with children; scoped to the same Part. | | `ref` | Optional SolidRef | Resulting solid handle has kind `revolve`. | ## Example ```tsx import { Rectangle, Revolve } from '@barocss/cad-react'; export function RevolvedSection({ angle = 90 }: { angle?: number }) { return ; } ``` Place this composition as the single output inside a Part with a connected lifecycle. It lowers to an automatically identified sketch and revolve node. The React component and profile references are logical declarations, not public native sketch IDs. ## Composition and validation Rectangle, Circle and Polygon are the prior closed profile adapters. The D509 implementation adds Loop/Profile sources; holed Revolve remains subject to its separate native limits and is not physically qualified by the selected Extrude case. Use one child or one profile reference. Definitions can hold a referenced profile; Boolean operations and Translate/Rotate can consume the resulting solid. Declaration tests for those combinations do not qualify every combination as a native physical case. Angles that are zero, negative, nonfinite or greater than 360° are refused. Invalid axes, sparse/nonfinite explicit origins, missing/wrong-kind references, mixed child/ref and wrong cardinality refuse. Staged native IDs commit only on accepted compilation. Compiler refusal retains its prior accepted source; ModelHost invalidation clears its current desired document. A stale visible shape does not establish current acceptance. Polygon can feed this profile contract, but no Polygon Revolve physical certificate is claimed by D504. There is no public sketch ID, arbitrary vector axis, direction, selected face, open wire or native-face provider prop. Existing backend geometry restrictions still apply. ## Runtime boundary The actual checks use only the rectangle shown above, the y axis and the omitted origin. They measure 90°, 180° and 360°, then use Reset to return to 90°. Source review confirms the existing convention sweeps this positive-X rectangle toward positive Z. Partial states have radial end caps and genus 0; the full 360° state has no radial end caps and genus 1. Current native B-reps satisfy those distinct partial/full topology contracts. Output mass and independent B-rep mass agree with the polar integral: volumes of 2250π, 4500π and 9000π mm³; centroids `[k,35,k]`, `[0,35,k]`, `[0,35,0]`, with `k=280/(9π)` mm. Native relative volume and absolute centroid/boundary/normal budgets remain 1e-9. The browser uses working Angle and Reset controls, public group collapse/reopen and a 1200 ms idle sample. Those panel actions preserve the exact document and current geometry ownership. Reset returns the exact original document and rendered frame. Public Studio Open and Frame all consume that returned 90° document with fresh root Worker values. Three native captures plus two exact 90° subproof reuses bind five fresh consumers; they are not five native captures. The standalone code block is the measured geometry recipe, but the physical proof also depends on the current connected host and source pins. The x axis, Circle, explicit origin and downstream combinations remain outside actual physical qualification until separately measured. D463 is historical Studio evidence; it is not current React native proof. No new kernel algorithm, tolerance, face/UV, asynchronous admission or general SDK guarantee follows. ## D509 profile composition D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. Loop and Profile produce closed-profile data. Outer/Voids and LineSegment/ArcSegment are structural descriptors, not extra native features. Extrude.profile, old Rectangle/Circle/Polygon lowerings and staged identities remain compatible. Exact circle conversion uses the existing helper with no sampling. Regions, arbitrary plane/face inputs, constraints and Sweep/Loft adapters remain unexported. Holed Revolve keeps its own native admission and remains physically unqualified by this Extrude case. No universal contact/containment repair or refusal is promised. Part remains one logical Model result that can contain multiple native pieces. --- # Union Joins realized solid operands in declared order through existing Model union nodes. The React group may lower to more than one native node. Import `Union` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `children` | Required; at least two realized solids | Compatible synchronous wrappers are allowed. | | `ref` | Optional SolidRef | The combined solid handle has kind union. | ## Example ```tsx import { Union, Extrude, Rectangle } from '@barocss/cad-react'; export function BracketTarget() { return ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation Union folds its operands through the existing backend in source order. Use it to make the single target for a Difference or the single Part output. It does not join unrelated React nodes or execute user component functions. Fewer than two realized solids refuses. Profile inputs are incompatible. There is no solid prop on Union; reuse refs through components that accept a solid input. Backend Boolean refusals and native tolerances remain authoritative. ## References and identity Stable React keys retain supported mounted operand IDs across reorder; the current order still determines native parent refs. A remounted key creates new identity. ## Measured boundary The floor/wall union is part of the independently measured Bracket. That selected Boolean arrangement is not general union robustness or geometric-equivalence proof. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Difference Subtracts an ordered list of solid tools from one solid target. Difference is logical composition and can lower to multiple existing native difference nodes. Import `Difference` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `children` | Exactly one Target and one Tools group | No other direct realized slots are accepted. | | `ref` | Optional SolidRef | The final cut solid handle has kind difference. | ## Example ```tsx import { Difference, Target, Tools, Extrude, Rectangle, Circle } from '@barocss/cad-react'; export function HoledPlate() { return ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation One Target establishes the initial solid. Each tool is subtracted from the running result in declared order. An overcut tool outside the target does not count as removed target material. Missing/duplicate slots, empty Tools or incompatible operands refuse. Difference does not accept a target or tools prop in place of its logical child groups. It adds no new Boolean algorithm, tolerance policy or mesh fallback. ## References and identity The outer Difference may expose one SolidRef. Target and Tools are operand slots, not native body handles or independent Part outputs. IDs/parent links are generated by the compiler. ## Measured boundary The original and transformed Bracket measure four floor cuts and the wall window. The standalone example above is a complete typechecked usage pattern, not an additional independent physical qualification. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Target Selects the single solid operand for its parent Difference. Target is a logical slot and creates no native feature node of its own. Import `Target` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `children` | One realized solid child | Exclusive with solid. | | `solid` | SolidRef | Exclusive with children; forward refs are supported after commit. | ## Example ```tsx import * as React from 'react'; import { Definitions, Difference, Target, Tools, Extrude, Rectangle, Circle, type SolidHandle } from '@barocss/cad-react'; export function ReusedTarget() { const plate = React.useRef(null); return <> ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation Use Target directly inside Difference. It accepts a compatible solid from an ordinary wrapper or one typed SolidRef. TargetProps is the public exclusive-input type. Both child and solid, zero/multiple solids, a ProfileRef or missing/cyclic reference refuse. Target has no own output ref or native-ID prop. It is not a valid standalone Part solid. ## References and identity A referenced solid belongs to the same Part and must have one binding owner. Pass the object ref, not its current handle; lookup resolves the committed graph. ## Measured boundary Measured Bracket targets use ordinary child composition; controlled compiler/ReactDOM/type tests cover typed reference resolution. These are distinct proof channels. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Tools Groups the ordered solid cutters for Difference. Tools is a logical slot, not a native feature or a union of its children. Import `Tools` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `children` | Required; one or more realized solids | Each tool is subtracted in the current declared order. | ## Example ```tsx import { Difference, Target, Tools, Extrude, Rectangle, Circle } from '@barocss/cad-react'; export function TwoHolePlate() { return {[10,70].map(x => )} ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation Tools belongs directly under Difference beside exactly one Target. Keyed arrays and compatible synchronous wrappers can produce its cutters. The cutter order is preserved rather than silently merged. An empty group refuses. Profiles must first be extruded to solids. Tools has no ref, solid, geometry-query or implicit-depth prop and cannot be the standalone Part output. More than one Tools slot is invalid. ## References and identity React keys provide mounted cutter identity during supported reorder/update. Tool source identity is separate from physical intersection success; native IDs are generated without author-supplied values. ## Measured boundary The actual Bracket cuts four radius3 floor holes followed by its window. The two-tool sample is a complete API pattern grounded in those source/tests, not an additional measured geometry domain. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Definitions Declares reusable profiles and solids without adding independent Part outputs. It is a logical registry group, not a native modeling operation. Import `Definitions` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `children` | Required ReactNode | Supported profile or solid declarations with optional typed object refs. | ## Example ```tsx import * as React from 'react'; import { Definitions, Circle, Extrude, type ProfileHandle } from '@barocss/cad-react'; export function SharedProfile() { const profile = React.useRef(null); return <> ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation Place Definitions alongside the single Part output. A consumer may appear earlier in JSX: the compiler resolves references in the committed graph. Use ProfileRef for an extrusion source and SolidRef for a target or transform source. Rectangle, Circle and Polygon, plus Loop and Profile, can declare profile tokens in this group. A synchronous ordinary component can pass its optional ref to Polygon. D504 controlled tests cover Polygon forward references through ordinary React components. This reference support does not qualify every native outline. Definitions alone is not a Part solid output. Missing, duplicate, cross-Part, wrong-kind and cyclic references refuse. Callback refs and ref.current are not dependency tokens. Definitions has no own ref or native-ID prop. ## References and identity React.useRef creates the supported object token; no useGeometryRef hook is exported. Handles expose kind metadata only. Reuse does not create persistent source-code links after saved-document reload. ## Measured boundary Controlled compiler and real ReactDOM tests cover forward refs, scoped lookup, typed kinds and invalid retention. No separate unmeasured native face/region producer is added by this registry. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). ## D509 profile composition D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. Loop and Profile produce closed-profile data. Outer/Voids and LineSegment/ArcSegment are structural descriptors, not extra native features. Extrude.profile, old Rectangle/Circle/Polygon lowerings and staged identities remain compatible. Exact circle conversion uses the existing helper with no sampling. Regions, arbitrary plane/face inputs, constraints and Sweep/Loft adapters remain unexported. Holed Revolve keeps its own native admission and remains physically unqualified by this Extrude case. No universal contact/containment repair or refusal is promised. Part remains one logical Model result that can contain multiple native pieces. --- # Translate Places one solid with the existing Model body-translation node. It adds the authored XYZ offset to the parent solid in model coordinates; no frontend transform math is introduced. Import `Translate` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `offset` | Required readonly [x,y,z] | Three explicit finite millimetre coordinates; sparse arrays refuse. | | `children` | One realized solid | Exclusive with solid. | | `solid` | SolidRef | Exclusive with children. | | `ref` | Optional SolidRef | Resulting handle kind translate. | ## Example ```tsx import { Translate, Extrude, Rectangle } from '@barocss/cad-react'; export function MovedPlate() { return ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation TranslateProps uses SolidInput. A nested child is lowered first, then its resulting solid becomes the translation parent. Wrap Rotate in Translate to rotate first and then apply the world offset, as the TransformApp recipe does. Missing coordinates, nonfinite/sparse offset, incompatible profile input, both child and solid or wrong cardinality refuse. Zero coordinates are valid; offset is not a destination bounding-box or unit-conversion command. ## References and identity Mounted transforms preserve supported IDs when offset changes; invalid declarations do not consume committed IDs. The optional ref remains scoped to this Part, with no geometry or matrix exposed on its handle. ## Measured boundary Actual W80 Bracket states use dx30/50,y40,z5 after Z90/180 origin rotation. Global translation plus automatic framing can produce identical pixels; current world Doc/centroid/bounds and owners establish the change, not forced framebuffer differences. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Rotate Rotates one solid with the existing Model body-rotation node. The component declares parameters; native backend code performs the transformation. Import `Rotate` from `@barocss/cad-react`. This private workspace API is not a published installable package. ## Props and output | Prop | Input/default | Meaning | |---|---|---| | `axis` | Required x/y/z | Existing axis vocabulary. | | `angle` | Required finite number; abs≤3600 | Degrees; zero is valid. | | `pivot` | Optional readonly [x,y,z] | Explicit finite mm coordinates; omission stays omitted and uses the existing backend origin default. | | `children` | One realized solid | Exclusive with solid. | | `solid` | SolidRef | Exclusive with children. | | `ref` | Optional SolidRef | Resulting handle kind rotate. | ## Example ```tsx import { Rotate, Translate, Extrude, Rectangle } from '@barocss/cad-react'; export function PlacedPlate() { return ; } ``` Insert the returned composition as the single output of a Part with a connected lifecycle. Any Definitions in the example remain logical siblings of that output; Target/Tools are used only inside Difference. ## Composition and validation RotateProps uses SolidInput. The inner Rotate above lowers before the outer Translate. Provide an explicit pivot when that placement matters; an omitted pivot is not silently written into the authored document. Invalid axis, nonfinite/out-of-limit angle, sparse/nonfinite explicit pivot, incompatible profile input, mixed child/ref or wrong cardinality refuse. There is no quaternion/matrix, camera, arbitrary-axis vector or selected-face rotation prop. ## References and identity Mounted transform identity and refs follow the same Part-scoped rules as other solids. Compiler validation retains prior accepted source on refusal; it does not make that old visible shape current. ## Measured boundary API axes/±3600 input acceptance is broader than independent actual proof. D497 measures only W80 Bracket, Z90°/180°, explicit origin pivot and selected dx30/50 translations. No arbitrary-angle or non-origin-pivot accuracy certificate follows. The complete code block uses current public exports; its extracted type-check result is recorded separately. Type/compiler checks do not by themselves evaluate this standalone example as a new native case. Read the [component catalog](/packages/cad-react/components), [refs and compiler](/packages/cad-react/references), [engine integration](/packages/cad-react/engine-viewer) and [current support limits](/packages/cad-react/limits). --- # Hole Cuts one solid with the existing native Hole operation. Import Hole and HoleProps from @barocss/cad-react. This is a private workspace API. | Prop | Contract | |---|---| | center | Required dense finite coordinate pair in mm. Axis z uses XY; x uses YZ; y uses ZX. | | radius | Required positive finite mm. | | axis | Optional x, y or z. Omission keeps the native z default. | | side | Optional min or max along the axis. Omission keeps native max. | | depth | Optional positive finite mm. Omit for through; supplied depth uses the existing flat-bottom cut. | | children / solid | Exactly one realized solid child or SolidRef, exclusive. | | ref | Optional SolidRef for the resulting Hole. | ```tsx import { Hole, Extrude, Rectangle } from '@barocss/cad-react'; export function BlindPlate({depth = 6}: {depth?: number}) { return ; } ``` Place this output inside Part with a connected lifecycle. A solid ref can replace the child, including a forward ref declared inside Definitions. Mounted identity follows the existing scoped solid rules. The compiler checks numeric inputs, input kind, cardinality and reference ownership. Native code decides whether the cut fits its stock. It receives omitted fields unchanged. Invalid declarations retain the preceding accepted document and frame while retiring freshness; valid recovery submits current geometry again. A flat-bottom Hole differs from the native blind-drill-hole operation with a drill point. No face selection, thread, pattern, countersink, drill angle or manual native ID is exposed here. A solid output can contain native pieces; this component adds no universal connected-solid guarantee. The desktop verification changes the blind depth and radius in React, checks the current native body and Viewer frame, then edits and reopens the returned Hole in Studio. The through and alternate-axis props have focused compiler coverage. This desktop verification uses one upper-face blind Hole. --- # References, identity and compiler results Native IDs are generated automatically. Use a typed object ref when another branch must consume declared geometry. A handle describes a supported kind; it does not contain synchronous evaluated CAD geometry. ## Share a profile ```tsx import * as React from 'react'; import { Definitions, Circle, Extrude, type ProfileHandle } from '@barocss/cad-react'; export function SharedProfile() { const profile = React.useRef(null); return <> ; } ``` Place this component inside a Part. Pass the ref object itself, not `profile.current`. The example declares the producer after its consumer: lookup resolves the committed model, so this is a supported forward reference. Do not read a handle during render to obtain geometry. ## Share a solid ```tsx import * as React from 'react'; import { Definitions, Extrude, Rectangle, Rotate, Translate, type SolidHandle } from '@barocss/cad-react'; export function SharedSolid() { const source = React.useRef(null); return <> ; } ``` A profile token cannot be used as a solid operand, and a solid token cannot be an extrusion profile. References are scoped to one Part. Missing, wrong-kind, duplicate or cyclic bindings refuse. Callback refs are not graph dependency tokens. Passing both a child and a source ref is invalid. | Public type | Meaning | |---|---| | `ProfileHandle` | Readonly kind `rectangle`, `circle` or `polygon` | | `SolidHandle` | Readonly kind `extrude`, `revolve`, `union`, `difference`, `translate` or `rotate` | | `ProfileRef` | React object ref containing `ProfileHandle|null` | | `SolidRef` | React object ref containing `SolidHandle|null` | | `ModelLifecycle` | Declaration dirty/invalid/complete/detached callbacks | | `ExtrudeProps`, `RevolveProps` | Exclusive one-profile child or ProfileRef input; their numeric operation parameters differ | | `TargetProps` | Exclusive one-solid child or SolidRef input | | `TranslateProps`, `RotateProps`, `SolidInput` | Existing body-transform and exclusive solid-input contracts | Extrude and Revolve share the child-or-profile-reference rule. Their exported prop types express that union directly; there is no public `ProfileInput` type export. Revolve outputs a SolidRef and can take part in Definitions, Boolean and rigid-transform declarations. Controlled composition checks do not qualify every combined shape as a new native case. ## Identity and invalid declarations Mounted feature identity and ordinary React keys retain native IDs through supported prop updates and reorders. Removal/remount creates a new identity. A ref object or an automatic native ID does not reconnect source code to a saved document after page reload. The compiler stages IDs until a declaration succeeds. An invalid declaration retains the prior accepted compiler result. That does not make prior displayed geometry current: dirty/invalid/detached lifecycle changes retire freshness in the host. Applications must distinguish previous visible geometry from a ready current result. ## CompositionCompiler and IrError `CompositionCompiler` is a public lower-level utility for inert realized descriptors. It does not execute React functions, native geometry or rendering. Most React hosts should use Part rather than manually construct descriptors. ```ts import { CompositionCompiler } from '@barocss/cad-react'; const result = new CompositionCompiler().compile({ kind: 'part', units: 'mm', children: [{ kind: 'extrude', distance: 6, children: [{ kind: 'rectangle', min: [0,0], max: [80,60], }], }], }); if (result.ok) { const document = result.value.doc; void document; // A compiled model document, not an evaluated B-rep. } else { console.error(result.error.code, result.error.message); } ``` | Public type | Fields | |---|---| | `Compiled` | `revision`, `doc`, `fingerprint`, `sourceIds` provenance | | `CompileResult` | Success `{ok:true,changed,value}` or failure `{ok:false,error,previous}` | | `ErrorCode` | The finite compiler refusal-code union below | Treat compiled results as immutable. Logical compiler outputs may be normalized by the existing Model reader; do not assume a compiler output key is already the accepted engine body key. `IrError` extends Error and exposes `code`. Current compiler codes are `CARDINALITY`, `TYPE`, `CYCLE`, `MISSING_REFERENCE`, `DUPLICATE_BINDING`, `DUPLICATE_ALIAS`, `DUPLICATE_KEY`, `INVALID_PARAMETER`, `EXCLUSIVE_INPUT` and `UNSUPPORTED_CAPABILITY`. These are declaration errors, not a replacement for the CAD engine's native refusal and tolerance contracts. ## D509 profile composition D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. Loop and Profile produce closed-profile data. Outer/Voids and LineSegment/ArcSegment are structural descriptors, not extra native features. Extrude.profile, old Rectangle/Circle/Polygon lowerings and staged identities remain compatible. Exact circle conversion uses the existing helper with no sampling. Regions, arbitrary plane/face inputs, constraints and Sweep/Loft adapters remain unexported. Holed Revolve keeps its own native admission and remains physically unqualified by this Extrude case. No universal contact/containment repair or refusal is promised. Part remains one logical Model result that can contain multiple native pieces. --- # React CAD SDK (`@barocss/cad-react/sdk`) While the root `@barocss/cad-react` entry provides declarative JSX geometry authoring (``, ``, ``), **`@barocss/cad-react/sdk`** ships ready-to-mount React components and hooks for building CAD viewers, configurators, and 2D drawing inspectors — the exact SDK powering [BaroCSS Review](/studio/review). ## Public exports | Export | Kind | Purpose | | --- | --- | --- | | `CadViewport` | Component | Embeddable WebGPU/WebGL2 3D CAD viewport bound to evaluated display meshes or snapshots | | `CadDrawing` | Component | Interactive 2D HLR engineering drawing SVG view with semantic edge/face/item hit callbacks | | `useCadDocument` | Hook | Manages reactive `.bcad` / part document state, parameter overrides, and worker evaluation | | `useCadSelection` | Hook | Tracks typed 3D/2D entity selection (`surface`, `curve`, `edge`, `item`) across views | | `renderCadDrawingSvg` | Function | Headless SVG rendering helper over `@barocss/cad-projection` with semantic `data-*` attributes | | `extractDrawingHit` | Function | Maps pointer events on a `CadDrawing` SVG element to typed `CadDrawingHit` payloads | | `snapshotToDisplayMeshes` | Function | Converts an evaluated kernel/model snapshot into `CadViewport` display mesh packets | ## Interactive 3D + 2D cross-highlighting Combine `CadViewport` and `CadDrawing` with `useCadSelection` to build split 3D/2D review surfaces: ```tsx import { useState } from 'react'; import { CadViewport, CadDrawing, useCadSelection, type CadDrawingHit, type ProjectionItem, } from '@barocss/cad-react/sdk'; export function PartReviewCard({ items }: { items: readonly ProjectionItem[] }) { const selection = useCadSelection(); const [lastHit, setLastHit] = useState(null); return (
{ setLastHit(hit); if (hit?.itemId) selection.select({ kind: 'item', id: hit.itemId }); }} /> {lastHit &&
{JSON.stringify(lastHit)}
}
); } ``` ## Semantic 2D SVG hit callbacks `CadDrawing` wraps [`@barocss/cad-projection`](/packages/cad-projection/) and annotates projected paths with semantic metadata (`CadDrawingEdgeHit`, `CadDrawingFaceHit`, `CadDrawingItemHit`). Clicking a hidden line, silhouette edge, or filled face invokes `onHit` with the originating B-rep item and edge classification so inspectors and 3D viewports stay synchronized without DOM coordinate heuristics. ## Headless JSX DSL (`@barocss/cad-react/dsl`) For server-side or worker-side declarative part generation without a DOM, import the headless compiler from `@barocss/cad-react/dsl`. For standard component props and compiler rules, see [Components and props](/packages/cad-react/components). --- # Engine and Viewer integration The package does not create a Worker or ship an engine client. Supply an existing implementation of `EnginePort`, a provenance-aware mass merger and a Viewer sink. Give one ModelHost exclusive evaluation use of its injected engine. `EngineClient` in the Studio source and the repository's `connectHost` example helper are application integration examples, not exports from `@barocss/cad-react`. A private Studio import is not a portable public client. ## Connect an existing engine This is an application helper built from current public exports. The caller provides engine/massPolicy and later disposes the returned host. Pass that host as Part's lifecycle. ```ts import { ModelHost, type EnginePort, type MassPolicy } from '@barocss/cad-react/engine'; import { ExistingViewerHost } from '@barocss/cad-react/viewer'; export async function connectCADView( canvas: HTMLCanvasElement, engine: EnginePort, massPolicy: MassPolicy, ): Promise { const sink = await ExistingViewerHost.create(canvas); let host: ModelHost|undefined; try { host = new ModelHost({ engine, ownership: 'borrowed', massPolicy, sink, ownsSink: true }); host.connect(); return host; } catch (error) { try { if (host) host.dispose(); else sink.dispose(); } catch { /* Retain connection error. */ } throw error; } } ``` Construct/connect after React commit, such as in an owning effect, and clean up when the application unmounts. Guard an asynchronous Viewer creation against an already-retired mount; the repository App examples show this pattern. ModelHost's constructor is inert: `connect()` installs subscriptions. Keep the engine, massPolicy and lifecycle identities stable for the intended lifetime. A Worker failure after a successful frame also makes `ModelHost.read()` report `failed`, with readable title, hint and detail. It does not restart the borrowed engine or resubmit automatically. In the repository `App` and `ProfileApp` examples, the engine owner can provide an optional `onRestart` callback that calls its existing client's `restart()` and returns whether it succeeded. The private Retry button uses that explicit callback, then rerenders the current declaration with the same Part, host, parameter values and feature IDs. A refused or thrown restart keeps the failure visible. Reset changes only the example's parameter. A Viewer startup failure has no connected host and does not offer Worker Retry; recreating that Viewer remains the caller's responsibility. ## Required ports and ownership Import these public types from `@barocss/cad-react/engine`: | Type | Required contract | |---|---| | `EnginePort` | `evaluate(doc,revision)`, `restart()`, `dispose()`, `onFailure(listener)`, `onMasses(listener)` | | `MassPatch` | `ref`, `fields`, and original `nativeMass` provenance envelope | | `MassPolicy` | `merge(bodies,patches)` using the existing provenance-aware native-mass policy | | `Owner` | Readonly `hostEpoch`, `declaration`, `evaluationRevision`, `fingerprint` | | `ExistingViewerSink` | Async `show(bodies,owner,stillCurrent)`, `snapshot()`, `dispose()` | | `ModelHostOptions` | `engine`, `ownership`, `massPolicy`, `sink`, `ownsSink` | `EnginePort.evaluate` returns a Promise of the existing CAD Model evaluation result or null. Failure/mass subscription methods return unsubscribe functions. `restart` returns a boolean. The host application owns the engine's Worker URL, protocol, CSP and caches; this package does not duplicate them. Do not merge mass patches only because numeric refs happen to match. Inject the existing native provenance checks. This is part of the port contract, not an optional performance optimization. `ownership:'borrowed'` leaves the engine with its caller. `ownership:'owned'` transfers its disposal policy to the host. `ownsSink` separately controls sink disposal. Host disposal removes subscriptions; applications must dispose their borrowed resources at their own boundary. ## ModelHost and readiness `ModelHost` implements the public `ModelLifecycle` interface. Part supplies `dirty`, `invalid`, `complete` and `detached` events; ordinary application components should not manufacture those events to inject a document. `connect()`, `read()` and `dispose()` serve integration and observation. `read()` reports status, pending declaration state, current accepted document/JSON, fingerprint, native/rendered owners, current native body diagnostics and the sink snapshot. Status is `pending`, `ready`, `failed` or `disposed`. A ready state requires current native and completed presentation ownership. A previous mesh may remain visible while the latest declaration is pending or invalid. Its visibility is not current acceptance. Each `read()` detaches the host-owned current document (including nested values), submitted request array and records, native centroid/bounds arrays, and the adapter's outer state. Mutating these returned copies does not change the host or a later observation. A held observation does not acquire later submitted requests. Volume, centroid, bounds and other numeric values keep their existing units and meaning. Owner tokens retain the same identity across reads. Tokens issued by `EngineAdapter` are frozen; a caller-provided Owner passed to `ExistingViewerHost.show()` is neither copied nor frozen by the sink. The adapter's `error: unknown` payload and a custom sink's `snapshot(): unknown` result are extension-owned values: their original identities and extension contracts remain in effect, and they are not deep-cloned. These boundaries allow callbacks and other non-cloneable extension data. The complete observation is not an immutable deep snapshot. Readiness separates declaration, evaluation revision, native mass readiness and display completion. Equivalent valid checkpoints may reuse a current request/result; invalid/failure recovery requires current ownership again. The existing Model reader normalizes accepted output keys. Diagnostic volume/centroid and mesh bounds do not replace independent native physical validation. ## ExistingViewerHost Import `ExistingViewerHost` from `@barocss/cad-react/viewer`. `create(canvas)` creates the existing Viewer sink and attaches the Viewer's pointer/keyboard controls. `show` sends render-only body meshes with right-handed Z-up/mm source metadata to the public Viewer facade, then observes frame completion under the supplied owner. `snapshot()` reports Viewer/camera/display-mesh metadata, mounted/frame owners and pixel diagnostics. `dispose()` releases its controls and Viewer. The sink detaches its own pixel-diagnostic record (`bytes`, `nonBackgroundPixels`, `sha256`) on each observation; this does not copy render meshes or raw image buffers. Viewer-provided camera and display metadata keep the existing Viewer facade's contract. Meshes have approximate-display authority. They are not native Face/UV geometry, pick provenance or physical B-rep authority. Frame-owner/pixel observations show a displayed current result; they are not an accuracy oracle. Global translation plus automatic framing may leave pixels identical while the document and world-space bounds change. The existing [Viewer documentation](/packages/viewer/) covers its separate public review/file/control features. Those APIs are not new CAD React exports, and saving a Viewer review does not save or reconnect JSX source. --- # Examples These examples use current public package exports. The repository examples provide the complete injected-engine application: `packages/barocss-cad-react/examples/App.tsx`, `Bracket.tsx`, `TransformApp.tsx`, `TransformedBracket.tsx` and the application helper `connect-host.ts`. The latter is not a package export. No public engine client or standalone Worker is implied. ## A bracket with ordered cutting tools ```tsx import { Difference, Target, Tools, Union, Extrude, Rectangle, Circle } from '@barocss/cad-react'; export function Bracket({ width }: { width: number }) { const holes = [ { key: 'front-left', at: [10,10] as const }, { key: 'front-right', at: [width-10,10] as const }, { key: 'rear-left', at: [10,44] as const }, { key: 'rear-right', at: [width-10,44] as const }, ]; return {holes.map(hole => )} ; } ``` The two target extrusions make the floor and wall. Four keyed tools cut floor holes. The last tool cuts a wall window. Extrusion overcut outside the target is not extra removed material. Place Bracket under Part with a connected lifecycle to evaluate/display it. This follows the current Bracket source. The original measured package flow changes width80→100→80 through its public input, using the real existing Worker and Viewer. That finite proof is not a width-range certificate or a promise that all Boolean compositions succeed. ## Rotate first, then translate ```tsx import { Translate, Rotate } from '@barocss/cad-react'; import { Bracket } from './Bracket'; export function TransformedBracket({ dx, angle }: { dx: number; angle: number }) { return ; } ``` `./Bracket` is the preceding example saved as `Bracket.tsx`, not a package export. Nested ordering matters: the W80 bracket is rotated around the origin before its world translation. The measured transform states are A(dx30,90°), B(dx50,90°), C(dx50,180°), then returned A. The public Translation X and Rotation Z inputs belong to the desktop TransformApp example. For the90° state, a source point[x,y,z] becomes[dx−y,40+x,5+z]. For180°, it becomes[dx−x,40−y,5+z]. Those are exact cardinal expectation rules used for these states, not a frontend transform implementation. The backend performs the native transformations. ## State updates through normal React ```tsx import * as React from 'react'; import { Part, type ModelLifecycle } from '@barocss/cad-react'; import { TransformedBracket } from './TransformedBracket'; export function PlacementControls({ lifecycle }: { lifecycle: ModelLifecycle }) { const [dx, setDx] = React.useState(30); const [angle, setAngle] = React.useState(90); return <> ; } ``` This code changes model props through ordinary React state. It needs the separately connected engine/Viewer integration; it does not create a canvas or a Worker. Blank/nonfinite input is an invalid declaration, not authorization to treat old visible geometry as fresh. Use the lifecycle/readiness state when presenting current results. ## Current desktop controls The repository App, TransformApp and RevolveApp share a right inspector with compact numeric fields, collapsible groups, actual host status and Reset. Folding controls leaves Part mounted. Status polling is owned by a separate inspector child and stops on unmount; the measured idle interval changes no document, request, checkpoint or owner. The Width example measures 80→100→Reset80. Transform measures A(30,90°)→B(50,90°)→C(50,180°)→ResetA. Reset restores the actual initial props. Source/request counts are observed, not assumed from the number of control edits. Canvas buffer 1000×700 and displayed 10:7 aspect are retained. See [validation limits](/packages/cad-react/limits) for current native/consumer evidence and finite scope. Global translation followed by automatic framing may leave pixels identical. The proof checks world document, centroid/bounds and fresh owners instead of forcing a pixel difference. Exact return document/frame is a finite observation, not general raster precision. ## Polygon inspector `examples/PolygonApp.tsx` uses the same existing engine/Viewer lifecycle and InspectorGroup/NumericField controls. Its Width prop drives a pentagonal plate; Reset restores 60 mm. The selected sequence uses 60 mm, 80 mm, blank-input refusal, valid 80 mm recovery and Reset to 60 mm. Current Worker/Viewer ownership, public collapse/reopen, idle behavior and the returned-document Studio Open pass. Separate settled-error UI proof retains the previous frame without an extra request. This adds no explanatory overlay or new renderer. ## Revolved section inspector `examples/RevolveApp.tsx` connects the same existing engine/Viewer lifecycle to `RevolvedSection`. The [complete Revolve recipe](/packages/cad-react/components/revolve) uses rectangle `[10,20]..[20,50]`, axis y and omitted origin. The actual Angle field measures 90°→180°→360°→public Reset 90°. Working collapse/reopen and 1200 ms idle leave the geometry and owners stable. The returned document opens through public Studio Open and Frame all. No arbitrary-axis, Circle or explicit-origin physical certificate follows from these selected states. See [current evidence](/packages/cad-react/limits#current-evidence); final saved-data review passes 41014 saved checks plus five post-write 64-hex document checks. ## Composite profile composition `examples/ProfileApp.tsx` demonstrates `SegmentedProfiledPlate` combining `Profile`, `Outer`, `Voids`, `Loop`, `LineSegment`, and `ArcSegment` in a single declarative `Part`. `Loop` and `Profile` produce closed-profile data with exact circle conversion and no orphan sketch emission, while remaining composable with `Extrude.profile` and typed refs. --- # CAD Model to React support map CAD React is the first adapter subset, not a complete React facade over CAD Model. The D509 implementation has nineteen logical elements: six operation adapters (Extrude, Revolve, Union, Difference, Translate, Rotate), five profile producers (Rectangle, Circle, Polygon, Loop, Profile), two segment descriptors (LineSegment, ArcSegment) and six structural elements (Part, Target, Tools, Definitions, Outer, Voids). The prior thirteen remain. Current76controls/types/lint/semanticmutants and selected native/Viewer proof pass; Studio Open/F and current Worker binding pass and freshdocs proof is NOT_RUN. This count is not a CAD-completeness percentage. All three packages currently identify as `0.0.0`. This map reads `packages/barocss-cad-model/src/engine/doc.ts` (`ModelNode = ModelNodeBase & NodeExtras`), current React `src/index.ts`/`components.tsx`/`compiler.ts`, and the existing public tests. The exact Model source SHA256 is `b35d4dedc69cb4921489084cd1c52e6fe0770b03916fd5000553b6728fdbe799`. A source AST inventory finds 75 distinct top-level ModelNode kind strings. That is a schema inventory, not 75 independently runtime-qualified capabilities. It excludes nested path/parameter tags from the count. ## Read the status correctly - ADAPTER: a named current React element lowers to the existing operation. It does not extend backend support or independently qualify all parameters. - PARTIAL: only a bounded part of a Model node's input vocabulary is exposed. - UNEXPOSED: the Model declaration exists, but no current public React component lowers it. This does not mean the CAD backend feature is absent. - GATED: a relevant existing owner HOLD still applies. Unexposed features are not all automatically held, and this document does not authorize an implementation or release a HOLD. `Part`, `Target`, `Tools` and `Definitions` are logical structure, not extra native feature kinds. Rectangle/Circle/Polygon are profiles lowered into sketch storage; there is no public Sketch-only prop or `` component. Conversely, a normal user function returning geometry is React composition, not an additional shipped element. ## Complete current ModelNode-kind inventory Every top-level kind appears exactly once below. Source locations refer to the current `packages/barocss-cad-model/src/engine/doc.ts`; they identify declarations, not validation receipts. | Model family | Existing Model kinds | React bridge | Boundary / missing contract | Declaration lines | |---|---|---|---|---| | Profile storage | `sketch` | PARTIAL | Rectangle/Circle/Polygon and Loop/Profile expose bounded closed-profile data and explicit holes. Band, regions, constraints, plane/face association and other SketchNode fields remain unexported. | `doc.ts:358` | | Current operation adapters | `extrude`, `revolve`, `union`, `difference`, `translate`, `rotate` | ADAPTER | Current Extrude/Revolve/Union/Difference/Translate/Rotate lower these existing nodes. Revolve adds selected rectangle/y-axis/omitted-origin 90/180/360 actual evidence; broader parameters remain outside physical qualification. Native limits and finite evidence remain separate. | `doc.ts:383, 385, 400, 402, 386, 388` | | Other profile solids | `sweep`, `sweep-curve`, `loft` | UNEXPOSED | No current component export. A bridge needs explicit profile/path/section/source/refusal contracts; existing backend is not missing. | `doc.ts:410, 412, 415` | | Other Boolean/body operations | `intersect`, `mirror`, `scale`, `split`, `separate` | UNEXPOSED | No current component export. Preserve existing output cardinality and body/reference identity before adding a bridge. | `doc.ts:401, 389, 391, 408, 652` | | Body patterns | `linear-pattern`, `circular-pattern` | UNEXPOSED | No current array/pattern component. Counts, placement, skipped occurrences and identity need a defined adapter contract. | `doc.ts:392, 399` | | Feature patterns | `linear-feature-pattern`, `fill-feature-pattern`, `curve-feature-pattern`, `rectangular-feature-pattern` | UNEXPOSED | Reference/selection-driven feature patterns require their own producer and ownership contract; existing typed refusal boundaries stay. | `doc.ts:394, 395, 396, 397` | | Finishing and holes | `thread`, `shell`, `chamfer`, `draft`, `full-round`, `face-fillet`, `face-thread`, `split-face`, `fillet`, `hole` | UNEXPOSED | No React selection-based finishing component. Edge/face source authority, rematch/refusal and current native support must be addressed; no fake handle/query is available. | `doc.ts:430, 432, 434, 639, 641, 643, 645, 647, 649, 660` | | Profile/detail text operations | `rib`, `rectangular-relief`, `text`, `text-relief`, `cylindrical-wrap` | UNEXPOSED | No current component or portable font/face-selection adapter. Backend/model declarations do not automatically expose these inputs. | `doc.ts:404, 406, 83, 85, 216` | | Imported/mesh data | `import`, `mesh`, `decimate` | UNEXPOSED | No source-file/mesh/import component. File/blob ownership, IO, provenance and display-vs-native authority remain separate. | `doc.ts:418, 424, 658` | | Sheet metal | `sheet-base`, `sheet-contour`, `sheet-corner-relief`, `sheet-flange` | UNEXPOSED | No current sheet component. Manufacturing and independently held workflows are not activated by a JSX adapter. | `doc.ts:441, 442, 448, 449` | | Frames and skeletons | `skeleton`, `frame`, `frame-member` | UNEXPOSED | No current structural graph component. These existing Model records are not ordinary React wrapper functions. | `doc.ts:463, 468, 469` | | Advanced surfaces | `band-surface`, `thicken`, `subd`, `sew` | UNEXPOSED / GATED | No current component. In particular #2258 public-thicken/fitter and #2266 widening remain held; this inventory releases neither gate. | `doc.ts:477, 478, 635, 637` | | Library and generated mechanical parts | `library`, `rack`, `internal-gear`, `bevel-gear`, `worm-wheel`, `spring`, `cam`, `sprocket`, `pulley`, `belt`, `coupling`, `shaft`, `oring-gland`, `oring`, `connector-opening`, `connector-body`, `gusset`, `end-cap`, `bearing`, `key`, `keyway`, `retaining-ring`, `pin`, `worm`, `gear` | UNEXPOSED | No current catalog/generator component. Existing generator versions, estimates, assembly/engineering claims and owner gates retain their own boundaries. | `doc.ts:501, 510, 516, 529, 546, 556, 566, 575, 576, 577, 578, 584, 603, 604, 611, 612, 619, 620, 621, 622, 623, 624, 625, 626, 627` | The sketch kind has rectangle/circle/polygon/loop/band variants; current baseline JSX exposes Rectangle/Circle numeric inputs and ordered Polygon points; D509 implements exact Loop segments and Profile outer/void composition. D504 Polygon has current tests and selected width-60/80 pentagon native/Worker/Viewer and returned-document Studio evidence. Other outlines remain outside that finite physical proof. The React package also does not expose general Model parameters (`Dim`), NodeExtras suppression/held/rematch fields or a source-code restoration system. Assemblies, mates, BOM, drawings, versions and robot settings are additional document APIs outside this ModelNode table; their existence is not a React API. ## Proposed bridge backlog, not new exports The existing D445 order remains C1 everyday parts, C2 ordinary robustness, C3 handoff, C4 static assemblies, then later/gated breadth. A reproduced C1/C2 blocker can change the order. The following is source-grounded selection guidance, not a promise to implement all candidates now. | Order | Candidate existing capability | Why it is useful / required adapter work | |---|---|---| | Delivered subset | Revolve | The existing-node adapter has declaration/types/lint checks and a current real React rectangle90/180/360/Reset 90 workflow plus returned-document Studio Open. This does not qualify arbitrary profiles, axes, origins or downstream combinations. | | 2 | Ordinary finishing: Hole, Chamfer, Shell, Fillet | C1/C2 daily tasks already exist (`doc.ts:660/434/432/649`). Define Hole parent/center/depth inputs and, where required, Chamfer/Fillet edge and Shell open-face selection sources with reference ownership. Current handles contain kind only; no new native Face/UV/query API is implied. | | 3 | Ordinary Sweep and Loft | Existing copied path/section workflows (`doc.ts:410/415`, `part/part-profile-solid.ts`). Define typed path/section frames, ordering, copied-source semantics and refusal before JSX surface. Curve sweep and broad surface/general-guide variants are separate. | | 4 | Body patterns, then feature patterns | C2 repetition requires stable occurrences, count/skip/placement/history and source refs. Body patterns (`doc.ts:392/399`) are a smaller boundary than selection-driven feature patterns (`394–397`). Do not treat an ordinary `.map()` of JSX as already implementing a native pattern feature. | | 5 | Other ordinary body/Boolean adapters | Intersect, Mirror and Scale already exist (`doc.ts:401/389/391`). Define exact solid inputs, output cardinality and retained native parameters rather than inventing new JSX math or implicit geometry equivalence. | The unexposed candidates describe possible bridges, not current exports. Revolve is now an export with the narrower qualification status stated above. Select the next bridge through the CAD roadmap and source audit after the present item; ordinary implementation is already authorized. Existing HOLD releases and gated downloads retain their specific owner requirements. There is no authority here to create dozens of placeholder components or call source inspection a runtime PASS. ## Holds and proof limits #2258 public-thicken/fitter, #2266 widening, manufacturing P2/PG11, new Physics/Motion, schema widening, browser CI, downloads and release retain their recorded gates. Existing accepted workflows and research history stay intact. The owner-authorized React example inspector does not lift the separate Studio UI redesign hold. Current React physical evidence includes the original Bracket widths 80/100, the selected W80 cardinal transforms and the selected rectangle Revolve 90/180/360, each with its recorded returned-document Studio Open boundary. It does not qualify all ModelNode kinds, angles, faces, profiles or generator families. Read [current support limits](/packages/cad-react/limits), the [component catalog](/packages/cad-react/components), the broader [CAD Model](/packages/cad-model/) API and [CAD modeling](/packages/cad/modeling) documentation for their separate contracts. --- # Support and validation boundaries The package is private workspace source, version `0.0.0`. Current code accepts more parameter combinations than have independent actual geometry evidence. Keep declaration support, controlled tests, real Worker/Viewer behavior and native physical accuracy separate. ## React admission Use `admission="synchronous"` for ordinary synchronous components, props, hooks, Fragments and keyed arrays. Current controlled tests cover normal registration, references, reorder, invalid retention, lifecycle cleanup and StrictMode replay. The compiler never calls a user function to guess its geometry. Portaled geometry and directly supplied unsupported async builtins refuse. A wrapper can hide an internal Suspense boundary whose fallback happens to leave a valid smaller model. The ordinary DOM registry cannot universally detect that hidden intent. Internal Suspense, Offscreen and async transitions remain unsupported, even when hidden by a wrapper. Resolve async inputs outside the complete Part before mounting it. There is no general whole-intent atomicity guarantee or custom reconciler. ## Geometry and references Supported sources include Rectangle/Circle/Polygon and D509 Loop/Profile data, profile-based Extrude/Revolve, Union/Difference and existing Model Translate/Rotate nodes. Outer/Voids and segment descriptors supply explicit composition. Typed refs and Definitions reuse outputs within one Part. Profiles and solids have different kinds. Child and ref input are exclusive. IDs track supported mounted identities and keys, not persistent source-code identity after reload. No native face/UV producer, arbitrary region/open-wire source, face query, sketch-constraint graph, surface extrusion, general topology picking or source-to-saved-document reconnection is exposed by this API. The backend may have capabilities that this package does not expose. The React layer adds no Boolean, transform, B-rep, numerical-tolerance or renderer algorithm. ## API inputs versus measured states | Capability | Current source contract | Independent actual scope | |---|---|---| | Bracket props | Ordinary component prop updates | Original width80→100→80 example | | Rotate | Existing x/y/z axis, finite angle with absolute value≤3600; optional finite pivot | W80 bracket, Z90°/Z180°, explicit origin pivot | | Translate | Three finite coordinates, explicit indexed checks | dx30/50 with y40,z5, after that rotation | | Revolve | Closed profile child/ref; required sketch x/y axis, finite angle in `(0,360]`, optional finite2D origin | Rectangle `[10,20]..[20,50]`, y axis, omitted origin,90°/180°/360° and public Reset90° | | Polygon | One closed ordered profile; 3..1024 dense finite coordinate pairs; optional ProfileRef; native outline validity remains authoritative | Selected convex pentagon widths 60/80, height 8; public invalid recovery, Reset and returned-document Studio Open pass | | Source restore | Supported mounted identity/key reuse | Exact original/returned finite example Doc/frame | | Studio handoff | Existing document reader/normalization | Public Open of the exact returned actual document | No general arbitrary-angle, arbitrary-width, arbitrary-component, full parameter-domain or inertia-accuracy certificate follows. Native sampling is finite. Worker mesh bounds/frame pixels are consumer observations, not a replacement for original native B-rep geometry. Polygon adds no repair or tolerance rules. The native length, area, simplicity and contact limits still decide whether a declared outline can produce a solid. A valid points array does not certify a valid native outline. D504 measures only a convex pentagonal plate at widths 60 and 80 mm, with omitted plane/from and an extrusion distance of 8 mm. That selected native/Worker/Viewer/Studio proof passes; broader outlines remain outside it. ## Current evidence The D495 checkpoint records24 unique controlled tests, package/API types, lint and final Model types PASS. Three actual browser states, one public Studio Open and two new native captures/two physical-oracle runs plus two exact 80 subproof reuses bind four current consumers. Original test fixture/type and Studio preflight failures remain in its record. The D497 transform checkpoint has 34 controlled tests, package/API types and lint PASS. Actual A/B/C/returned-A and public Studio Open pass at the selected profile. Three native captures and three independent physical-oracle runs plus two exact-A subproof reuses bind five current consumers. The retained budgets are absolute volume1e-6mm³, density1 mass1e-9g, centroid/bounds1e-8mm and carriers1e-7mm. No numerical budget is weakened for the React path. High final saved-data review passes 7959 hash/cardinal-arithmetic checks, separate from the 34 product tests. Maximum world-volume error is 4.37e-11 mm³ and centroid error is 7.11e-14 mm; the retained limits are unchanged. The first pre-inspector transform run recorded ready revisions1,2,3,5: two return-control edits retired an intermediate declaration. The current inspector uses a public Reset that batches initial values. Its selected Transform ready revisions/requests are1,2,3,4; Width records1,2,3. These observations do not promise one Worker request per prop change or qualify every intermediate state. The new inspector has seven fresh ready UI consumers across the two examples. Public collapse/reopen,1200 ms idle, functional Reset, current owners, real Ready status, right280px panel,10:7 canvas aspect and no document overflow pass. The seven current whole documents bind seven saved native physical subproofs at unchanged eligible producer source; this UI-only step runs zero new native captures or physical oracles. The saved UI audit passes 20132 hash/ownership/arithmetic checks, separate from product test counts. Its first binder stopped on descriptive statusTimer wording; saved-only correction preserves that FAIL without browser/native replay. Global translation with automatic fit yields identical A/B pixels in this measurement. A fresh visible frame, matching owners and correct world geometry are required. Some retained Studio palette occlusion remains outside a full fit/raster-precision claim. Mesh display authority is approximate; native Face/UV authority is not added. The D499 Revolve checkpoint has 44 unique controlled tests, package/API types and lint PASS. The original test run passed 43 and stopped one test on duplicate sibling keys in its two-profile fixture. Assigning only the second fixture key uniquely preserves validation order and its intended cardinality expectation; that named test then passes. The prior 43 passes are reused, not rerun as 44 new executions. Four selected GUI states and public Studio Open pass. Collapse/reopen and 1200 ms idle preserve document/checkpoints/requests/owners/frame. Three current native captures plus two exact 90° subproof reuses bind five fresh consumers. Native output mass and independent B-rep mass, trimmed physical bounds and the partial/full closure contracts are checked at relative volume 1e-9 and absolute centroid/boundary/normal 1e-9. The full 360° state is a genus 1 annular tube with no radial end caps;90°/180° are genus 0 partial solids. This is not general x-axis/Circle/nonzero-origin/angle or downstream-operation qualification. Final independent saved-data audit passes 41014 saved checks plus five post-write 64-hex document checks, separate from 44 product tests. ## Packaging and operations There is no npm publication, portable engine implementation, standalone packaged Worker or distribution output at this checkpoint. The package manifest declares the existing React19.2.3 peer environment. The consumer owns engine construction, exclusive evaluation use, mass provenance, Worker URL/CSP/cache setup and borrowed-resource cleanup. Internal application helpers and Studio imports are not public package exports. No mobile validation, PDF/export convenience, standards/manufacturing acceptance, full-kernel/baseline suite, browser CI, deployment or release is claimed here. A documentation category is not publication of the package or site. Existing project HOLDs and physical proof boundaries remain in force. ## Polygon checkpoint The package has 57 controlled tests, package/API-example types and lint PASS. The current positive sequence is width 60 → 80 → blank-input refusal → valid 80 recovery → Reset 60, with four Ready GUI observations. The exact returned document opens through public Studio Open and Frame all. Two native captures and three exact-document subproof reuses bind five positive consumers, including that Studio observation. These are not five native captures. The selected convex pentagon is `[[0,0],[width,0],[width,50],[10,50],[0,40]]`, extruded by 8 mm. At widths 60 and 80, independent areas are 2950 and 3950 mm², volumes 23600 and 31600 mm³, and centroid Z is 4 mm. Each native result has seven faces, fifteen edges, ten vertices, genus 0 and thirty observed pcurves. Separate output mass and actual B-rep integration satisfy unchanged relative-volume and absolute centroid/boundary/pcurve/D1/normal budgets of 1e-9. Maximum relative volume error is 2.303e-16 and centroid error is 1.422e-14 mm. This is finite native evidence, not an inertia, arbitrary-outline, concave-polygon, Polygon-Revolve or all-75-kinds certificate. The immediate invalid-input capture retained the previous frame but sampled the inspector before it settled from Ready. A separate public UI observation waits for Error, retains the visible finite-coordinate alert and previous frame, and submits no extra native request. Its two Ready states are antecedents only: it adds zero physical captures, oracles, reuses or consumer bindings. Its first self-pin/private-tmp alias preflight stopped before any browser or output; a corrected expected-hash config preserved the code and original evidence. The primary integrated flow passed on its first execution. D504 qualified24 actual Markdown examples against its then-current API. D509 preserves those24 fence bodies and adds6, for30 actual fences across26pages. All30 actual fences are inputs to a separate fresh whole-program docs check, seven navigation tests, site check/build and26desktop-route preview; results are recorded in their canonical receipts. The current19 logical elements are6operations,5profile producers,2segment descriptors and6structural elements. The75-kind table is source inventory, not completion. ## D509 profile composition D509 implements Loop, LineSegment, ArcSegment, Profile, Outer and Voids. The existing thirteen logical elements remain; the package now has nineteen. The 76 source-checkpoint controls (65 reused with unchanged inputs and 11 newly run), package/API types, lint and four semantic mutation controls pass. The selected all-six SegmentedProfiledPlate passes four original Viewer states and native proof. Returned-document Studio Open/F and the separate compound-metadata consumer pass at their saved source checkpoints. Current-source Studio continuation and fresh documentation verification are recorded separately from geometry evidence. Loop and Profile produce closed-profile data. Outer/Voids and LineSegment/ArcSegment are structural descriptors, not extra native features. Extrude.profile, old Rectangle/Circle/Polygon lowerings and staged identities remain compatible. Exact circle conversion uses the existing helper with no sampling. Regions, arbitrary plane/face inputs, constraints and Sweep/Loft adapters remain unexported. Holed Revolve keeps its own native admission and remains physically unqualified by this Extrude case. No universal contact/containment repair or refusal is promised. Part remains one logical Model result that can contain multiple native pieces. D509 selected physical scope: The measured canonical case is a60×40×8 mm plate: one Loop of four LineSegments as Outer and one Loop with a full CCW ArcSegment as Voids, centered at[30,20], radius6→8→Reset6. All six new elements are realized. Two native captures and two exact-Doc reuses bind four original GUI consumers; one native body/one shell/genus1 is proved only for these states. Blank NaN input waits for visible Error and finite-coordinate alert, submits no extra engine call, retires freshness and retains the preceding radius8 frame. Collapse/reopen/idle/Reset also pass. Recorded Studio Open/F and its fresh Worker binding pass for the exact returned document at that source checkpoint, with source and cleanup verification. Full viewport fitting and raster precision are NOT_MEASURED; the Studio palette can occlude the plate. No general topology, face/UV, NURBS, arbitrary-hole, release or mobile qualification follows. --- # @barocss/physics Physics advances an admitted numerical model from initial state and applied loads. The caller supplies the clock and displays each accepted state. The rigid world uses spheres, boxes and capsules. It does not use the exact CAD Surface as its collision shape. The common World supports [continuous primitive rotation](./profiles-and-lifecycle#isolated-noncubic-rotor) within its input and numerical limits. Dynamic noncubic boxes use their COM inertia, not constant world angular velocity. Contact, CCD and joint limits remain separate. A CAD proxy conversion does not certify its physical accuracy. This guide describes the workspace package. Local implementation and numerical evidence do not establish active CAD adoption, publication, hardware validation or manufacturing acceptance. Existing HOLD and historical NO_GO decisions remain in force. See [Physics verification](/reference/physics-verification). For CAD, GPU and Viewer host ownership, see [host integration](./host-integration). ## Current contact verification The current contact coherence implementation passes the original two-cube and three-cube512-step numerical campaigns in Source and actual compiled World, with unchanged tolerances. Its extended three-cube campaign still fails at866: lateral error1.0037318971762749e-10m exceeds1e-10m. The library is not complete. New-provider full desktop HiDPI remains unrun; the gallery and earlier Viewer results below belong to their recorded providers. See the [roadmap evidence](/physics-evidence/api-roadmap.txt). All first failures and Studio/manufacturing/equipment HOLDs remain. No deployment. ## Run the local sample gallery The repository gallery has six independently checked finite examples: projectile, elastic box, sphere sliding/rolling, one sphere CCD event, principal anisotropic spin before contact, and two-cube floor support. Select a case, then use Step or Run. Reset restores the authored initial model. Worker owns the sole World; Viewer receives accepted poses. The desktop HiDPI tests compare complete Native states and commands as well as actual GPU pixel changes. With workspace dependencies present and Physics already built, run from the repository root: ```sh node examples/physics-sample-gallery-2276/dev.mjs ``` If `packages/barocss-physics/dist/index.js` is absent, first run `pnpm --filter @barocss/physics build:library`. The preview uses that compiled package only; it does not install dependencies or build Physics automatically. Open the loopback address printed by the server. Numerical qualification uses a separate authenticated verification entry, not saved answers as animation. This is a local library and Viewer host. The three-cube long horizon remains NO_GO. It does not qualify arbitrary CAD contact, mechanisms, physical fluid/cloth coupling, Studio or real equipment. Existing HOLDs remain. ## Choose the owning API | Need | Owning entry or API | Scope | | --- | --- | --- | | Rigid forward dynamics | `createPhysicsWorld` from `@barocss/physics` | Fixed-step primitive bodies, contacts, bounded joints and queries. Choose an admitted profile. | | One planar pendulum | Independent `examples/physics-planar-pendulum-reference/pendulum.ts` | Local one-coordinate ODE, separate from the rigid world and its joint solver. | | Static-box capsule sweep | `createUprightCapsuleQuery` from the root | Geometric query; no dynamic body or hidden clock. | | Upright capsule movement | `createUprightCapsuleController` from the root | Fixed upright capsule and immutable bounded box scene. No general character dynamics. | | CAD proxy admission and display mapping | `admitCadSurfaceProxy`, `assertCadProxyCurrent`, `cadProxyPose` from `@barocss/physics/cad-proxy` | Source-bound control-net sphere or box approximation. | | Accepted command-log replay | `createPhysicsRecorder`, `restorePhysicsRecording` from `@barocss/physics/replay` | Attach at step0; bounded indexed recording; no arbitrary state loading. | | Visual water | Root `createPhysicsWorld(model, options)` | Fixed 256-particle basin; visual settings, no calibrated fluid material. | | Visual sheet | Root `createPhysicsWorld(model, options)` | Fixed 289-vertex pinned sheet and static sphere. | | CAD obstacle in visual water | `admitCadFluidStaticData` data adapter, then root World | One static axis-aligned CAD box proxy in version 1 water. | ## Fixed cloth and fluid model data These visual profiles use the same World clock, guard and state contract. P5a private kernels passed their bounded two-step source/native gates. P5b public source and actual native runtime checks also pass for the named fixtures and horizons in [verification](/reference/physics-verification#p5-common-world-visual-profiles). Strict source/native consumers and the selected four-profile source example pass. Native host compilation keeps the missing rendering SDKs external; their implementation and product execution remain unverified. Site checks have separate receipts. [Download the inert model asset](/physics/model-data.mjs). It contains explicit public PhysicsModel data, not another World factory. Copy it into your application and import it locally. The repository sample uses that same asset. ```js import assert from 'node:assert/strict'; import { createPhysicsWorld } from '@barocss/physics'; import { createPhysicsRecorder } from '@barocss/physics/replay'; import { copyPhysicsModelPreset } from '../docs/public/physics/model-data.mjs'; ``` ```js function acceptVisualStep(profile) { const input=copyPhysicsModelPreset(profile),original=structuredClone(input.model); const world=createPhysicsWorld(input.model,input.options); try { const before=world.getState(); assert.throws(()=>createPhysicsRecorder(world),error=>error.code===(profile.startsWith('cloth')?'WORLD_LIMIT':'INVALID_SNAPSHOT')); assert.deepEqual(world.getState(),before); const submitted=input.model.cloths[0]?.initialPositionsM ?? input.model.fluids[0].initialPositionsM; submitted[0][0]=999; assert.deepEqual(world.getModel(),original); const state=world.step([]),domain=state.cloths[0]??state.fluids[0]; return {stepIndex:state.stepIndex,timeSeconds:state.timeSeconds,positionsM:domain.positionsM}; } finally { world.dispose(); } } ``` Cloth topology, pins, physical vertex masses and ordered constraints remain in `getModel().cloths[0]`. Copied positions/velocities and diagnostics are in `getState().cloths[0]`; fluid data uses the corresponding `fluids[0]` entry. Do not pass time to step. Host reset means dispose and recreate a root World. Only empty commands are supported for these fixed visual profiles. Profiles are `cloth-pinned-sphere-visual-v1`, `fluid-basin-visual-v1`, `fluid-basin-xsph-visual-v1`, and `fluid-static-box-visual-v1`, all with `domain-fixed` broad phase and1/120s. The fluid smoothing radius is the original computed binary64 value `0.09000000000000001`, not literal `0.09`. These are visual settings, without calibrated fabric, viscosity, pressure or P6 coupling. Domain recording is explicitly refused. Cloth exceeds the unchanged128KiB model cap (`WORLD_LIMIT`); fluid profiles use `INVALID_SNAPSHOT` until actual wire/budget/restore closure is qualified. The failed attach changes no owner or accepted state. Preserve1MiB/512frames/4096commands; no JSON wire fallback. For CAD-derived static data, keep its admitted proxy and call the existing current-source check before each World step. SourceBinding alone cannot prove current source. No CAD Studio/Viewer UI or release action is implied here. Robot FK, IK, timed paths and prescribed-motion loads belong to [CAD Model](/packages/cad-model/). Read the [robot motion guide](/guide/robot-motion) and [Studio robot documentation](/studio/robots). A sampled robot path gives joint values over time. It does not predict free motion from force. Motion is a capability here; there is no new installable Motion package. Viewer applies display poses. ## Import and advance a free body Workspace imports resolve TypeScript source. Use the documentation sample runner or a TypeScript-capable bundler. Plain Node cannot resolve the source's internal `.js` imports to `.ts`. The package's `publishConfig` selects compiled `dist` entries for a release. A source sample does not verify that compiled package graph or a published package. ```js import { createPhysicsWorld, PhysicsError } from '@barocss/physics'; import { admitCadSurfaceProxy, cadProxyPose } from '@barocss/physics/cad-proxy'; ``` Use SI values at the Physics boundary. This fixture has a 2 kg sphere, an initial +X speed of 1 m/s, and no other body. Its radius is 0.1 m. Keep conversion code outside the step loop. ```js const dt = 1 / 120; const worldOptions = { profile: 'rigid-discrete-v1', fixedStepSeconds: dt, broadPhase: 'direct' }; const freeBody = () => ({ id: 'part:ball', kind: 'dynamic', massKg: 2, inertia: { kind: 'primitive-com', about: 'com', frame: 'body-local' }, initial: { positionM: [0, 2, 0], orientationXYZW: [0, 0, 0, 1], velocityMps: [1, 0, 0], angularVelocityRadps: [0, 0, 0] }, }); const freeModel = (gravityMps2 = [0, -9.81, 0]) => ({ format: 'barocss-physics-model', version: 1, revision: 'docsFlight1', frame: { id: 'world', basis: 'right-handed-xyz', rotation: 'local-to-world-xyzw' }, units: { length: 'm', mass: 'kg', time: 's', angle: 'rad' }, gravityMps2, bodies: [freeBody()], colliders: [{ id: 'collider:ball', bodyId: 'part:ball', geometry: { kind: 'sphere', radiusM: 0.1 }, local: { positionM: [0, 0, 0], orientationXYZW: [0, 0, 0, 1] }, material: { restitution: 0, friction: { static: 0, dynamic: 0 } }, sensor: false, ccd: false, filter: { categoryBits: 1, maskBits: 65535 } }], joints: [], cloths: [], fluids: [], sourceBindings: [], }); ``` Pass `createPhysicsWorld(model, options)` a complete model and an explicit profile. The model separates rigid bodies, colliders and source bindings. Each body has an `initial` transform and motion. Each collider has its own geometry, local transform, material and filter. The options declare the fixed step and broad phase. `getModel()` returns a copy of the admitted input; `getState()` returns the accepted state and its identity. `step(commands?)` advances that configured step and takes no time argument. The world uses a configured fixed step. The sample compares 12 free-flight steps with the discrete semi-implicit Euler solution. Its position oracle includes the integrator's time-discretization term; it is not the continuous expression `p = p0 + v0*t + g*t²/2`. ```js const world = createPhysicsWorld(freeModel(), worldOptions); try { const n = 12; for (let i = 0; i < n; i++) world.step(); const state = world.getState(); // Semi-implicit Euler: v_n = v_0 + n*g*dt; // p_n = p_0 + n*v_0*dt + g*dt²*n*(n+1)/2. vectorNear(state.bodies[0].velocityMps, [1, -9.81 * n * dt, 0]); vectorNear(state.bodies[0].positionM, [n * dt, 2 - 9.81 * dt ** 2 * n * (n + 1) / 2, 0]); near(state.timeSeconds, n * dt); assert.equal(state.contacts.length, 0); } finally { world.dispose(); } ``` The sample helper `vectorNear` compares each finite component with absolute tolerance `1e-12` unless a tolerance is supplied. It uses `node:assert/strict`. The source is in `apps/library-docs/samples/physics-docs.test.mjs` and runs with the site's `test:samples` command. A separate sample test compares the same physical time, 0.1 s, with the continuous ballistic solution at steps 1/120 and 1/240 s. Its position-error gate is 0.0041 m and its refinement-ratio gate is 1.99–2.01; velocity is checked within 1e-12 m/s. This distinguishes integrator agreement from physical-time accuracy. These examples supply no contact, browser or hardware result. ## Apply a force or an impulse `step(commands)` validates the commands before it advances a candidate. A `force` acts for this one step, so its velocity change is `forceN * dt / massKg`. An `impulse` changes velocity once by `impulseNs / massKg`. Supply a force on each step when you need a sustained load. ```js const world = createPhysicsWorld(freeModel([0, 0, 0]), worldOptions); try { const first = world.step([ { kind: 'impulse', bodyId: 'part:ball', impulseNs: [2, 0, 0] }, { kind: 'force', bodyId: 'part:ball', forceN: [0, 24, 0] }, ]); // Mass is 2 kg: J/m = 1 m/s; F*dt/m = 0.1 m/s. vectorNear(first.bodies[0].velocityMps, [2, 0.1, 0]); vectorNear(first.bodies[0].positionM, [2 * dt, 2 + 0.1 * dt, 0]); const second = world.step(); vectorNear(second.bodies[0].velocityMps, [2, 0.1, 0]); vectorNear(second.bodies[0].positionM, [4 * dt, 2 + 0.2 * dt, 0]); } finally { world.dispose(); } ``` The command order in the input array does not select the integration order. Physics applies linear impulse, then gravity and force, then position, followed by collision and joint response. Torque and angular impulse use world-frame vectors and the body's orientation-transformed inverse inertia. `kinematicTarget` supplies an absolute metre position for one kinematic-body step. A kinematic body holds its position and reports zero velocity when the next step has no target. ## Reduced planar pendulum The independent example reference `createPlanarPendulum` solves one angle about a fixed +Z pivot at the origin, with gravity along −Y. It admits no contact geometry, motor, damping or joint network. It uses velocity Verlet and explicit COM or pivot inertia. Read the [unit and frame contract](./units-and-frames). ```js // Independent reduced ODE reference, outside the public Physics package. import { createPlanarPendulum } from '../../../examples/physics-planar-pendulum-reference/pendulum.ts'; ``` ```js // Imported from examples/physics-planar-pendulum-reference/pendulum.ts, not the package root. const pendulum = createPlanarPendulum({ massKg: 1, comDistanceM: 0.5, inertia: { about: 'com', kgM2: 0.02 }, gravityMps2: 9.81, initialAngleRad: 0, initialAngularVelocityRadps: 0, fixedStepSeconds: dt, maxSteps: 2, }); const state = pendulum.step(dt); near(state.angleRad, 0); near(state.energyJ, 0); vectorNear(state.comPositionM, [0, -0.5, 0]); assert.throws(() => pendulum.step(dt / 2), hasCode('INVALID_STEP')); assert.deepEqual(pendulum.getState(), state); pendulum.dispose(); assert.throws(() => pendulum.getState(), hasCode('DISPOSED')); ``` This sample checks the zero-angle equilibrium and an expected refusal. The separate foundation experiment records period, matched-time state, convergence and energy-envelope checks; see [Physics verification](/reference/physics-verification). The pendulum interface has `getState()`, `step(dt)` and `dispose()`. Create a new instance for a new initial state. The reference is outside the public package root. It does not establish adoption by the active CAD checkout. The CAD-bound workflow that authors a hinge, applies loads and displays free motion remains a separate product gate. It does not activate the original eight-box or two-hinge experiments. ## Select a bounded profile before creating a world The `rigid-discrete-v1` profile admits 1–32 bodies and uses one contact point per pair. The opt-in `rigid-persistent-box-v1` profile admits at most four bodies. `rigid-large-v1` admits up to 64 bodies with required AABB broad phase and excludes joints, CCD and persistent boxes. These capacities are admission bounds. They are not interchangeable stack-stability guarantees. Use [profiles and lifecycle](./profiles-and-lifecycle) for the exact combinations, step limits, typed refusals, copied state and replay rules. Use [units and frames](./units-and-frames) before connecting a CAD or Robot host. Contact impulses and joint projection reactions are numerical solver outputs. They are not calibrated mechanical loads. Source owners for this guide are `packages/barocss-physics/package.json` and `src/{index,types,world,limits,cad-proxy,replay}.ts` in that package. The [verification page](/reference/physics-verification) keeps numerical evidence, geometry-only receipts, failed trajectories and product acceptance separate. ## Common World transition The current rigid root uses the [model/state/command/failure contract](/physics-evidence/p0-contract.txt): `createPhysicsWorld(model, options)`, copied `getModel()` and `getState()`, `step(commands?)`, tagged `query(input)` and `dispose()`. State includes model, configuration and provider digests. It identifies bodies and colliders separately. The old root config and root reduced-pendulum factory are removed. There is no compatibility engine. Cloth and fluid now use the common World. The removed `/cloth`, `/fluid` and `/fluid-cad` factories have no compatibility path. Each admitted visual model contains one domain and its fixed static colliders. Dynamic mixtures and force exchange with a moving rigid body remain unsupported. The replay service attaches to the common World through `createPhysicsRecorder(world)` at step0 and owns advancing commands while attached. Recorder disposal detaches it; the caller also disposes the World. CAD admission emits a body, collider and source binding; it never steps a world. The [roadmap](/physics-evidence/api-roadmap.txt) and [migration contract](/physics-evidence/p0-migration.txt) separate these later transitions from this rigid root change. This API change does not establish coupling or a new numerical, Viewer, hardware or product acceptance result. ## P1b local evidence status The rigid model/options cutover has selected source 8 / emitted 8 public checks,21 focused probes in each graph and a native local published-map runtime/declaration receipt (`examples/physics-world-p1b-2276/evidence/native-04`). These are checks of named providers, not a new numerical qualification. Five foundation entries pass 21 tests; documentation samples pass 174/174 and source mapping passes (`mapping-02`). Documentation build, site and scoped link checks pass. README examples compile and execute (`native-05`). Current host callsites bundle with the absent Viewer SDK explicitly external; full Viewer/DOM execution remains NOT_RUN. Independent reduced-ODE receipts remain reference results. P2_DONE_LOCALSELECTED has public source05/emitted05 checks11/11 each, test-only preparation-fault checks12/12 each, and native published-map/runtime/type checks. These historical receipts apply to their named providers; whole-engine acceptance remains NO_GO. At that checkpoint, final recording callers passed3 per graph and docs samples174/174. Current P5 results are separate in [verification](/reference/physics-verification#p5-common-world-visual-profiles). Existing HOLD and NO_GO decisions stay in force. ## Physics Lab on desktop The local Physics Lab uses the public World and recorder with the existing WebGPU Viewer. From the repository root, run: ```sh node examples/physics-lab/server.mjs ``` Open `http://127.0.0.1:52889`. Select box, sphere or capsule, change mass and initial spin, apply world torque or a one-time angular impulse, then save, restore and continue. The existing512-frame recording limit remains visible. The fixed0.1s comparison uses six shared times at60/120/240Hz against saved independent directed reference data. Live torque work is marked approximate; it is not the independent comparison result. Desktop browser checks cover actual controls, Viewer pose agreement, GPU pixels and failure retention. This sample does not resume Studio or qualify contact/stack/device behavior. --- # Physics units and frames Declare the unit system and coordinate frame before you connect a Robot, a CAD proxy and a Physics world. Convert each value once at its boundary. Do not convert Physics output again before you use it as input to the next Physics step. This page describes the current unreleased branch. See the [package overview](./) and [robot motion guide](/guide/robot-motion) for API ownership. The existing [Robot unit boundaries](/studio/robots#robot-unit-boundaries) remain the Robot facade contract. ## Conversion and frame contract | Quantity or boundary | Source convention | Physics or destination convention | Required conversion or declaration | | --- | --- | --- | --- | | Public Robot turn input/output | Degrees | Internal joint calculations use radians | `rad = deg * Math.PI / 180`. The facade owns this conversion; do not preconvert facade turn inputs. | | Public Robot slide input/output | mm | Internal Robot joint calculations also use mm | No conversion inside the Robot facade. Convert mm to m when passing length to Physics. | | Timed Robot joint limits | Joint units per second, squared second or cubed second | Public turn limits use degrees; internal turn math uses radians. Slide limits use mm. | Match the API layer and each joint's unit. A playback speed is a display setting. | | CAD/Viewer length and Robot MMGS length | mm | Physics length in m | Multiply by `1e-3`; return Physics display positions to mm with `1e3`. Thus 100 mm is 0.1 m. | | Robot facade MMGS mass | g | kg | Multiply by `1e-3`. | | Robot facade MMGS inertia | g·mm² | kg·m² | Multiply by `1e-9`. State the inertia origin and axis as well. | | Robot reported moment | N·mm | N·m | Multiply by `1e-3`. Force in N needs no scale change. | | Physics time, angles and loads | s, rad, N, N·m | Same SI units in Physics state and commands | Linear impulse is N·s; angular impulse is N·m·s. Do not treat either as a force or torque. | | World frame | Host declares right-handed XYZ and CAD orientation | Physics body positions and velocities use that declared world frame | There is no universal CAD up axis. These Physics examples use −Y gravity; Robot statics default to −Z. Rotate vectors explicitly when connecting these frames. | | Body rotation | Local-to-world quaternion | `[x, y, z, w]`, right-handed | The input and state field is `orientationXYZW`; identity is `[0,0,0,1]`. Rigid admission requires norm within `1e-6` of one and normalizes it. `cadProxyPose` requires norm within `1e-9`. | | Body axes and angular input | Shape dimensions and joint anchors are body-local | Torque and angular velocity are world-frame vectors | A capsule's segment uses its local Y axis. `axisWorld` is a world hinge axis. | | Contact convention | Pair IDs sorted as A, B | `normalAtoB` points from A to B; `pointM` is world metres | Positive normal impulse acts along the normal on B and against it on A. `tangentImpulseOnBNs` is the accumulated world-vector impulse on B, opposite on A. | | Independent pendulum reference inertia | `inertia: {about:'com'|'pivot', kgM2}` | Moment about the +Z axis through the named origin | For COM input, Physics adds `massKg * comDistanceM²` once. For pivot input, include this term yourself. | | CAD proxy display | Source points and `sourceCenterMM` in mm; body centre in m | Viewer translation in mm and unchanged XYZW orientation | `translation = 1000 * bodyPositionM - R * sourceCenterMM`. Rotate around the source centre, then place that centre at the body position. | For continuous primitive rotation, angular impulse acts instantaneously at step start. Torque is constant in world coordinates during that step, then expires. The independent reference checks `Lend=Lbefore+J+tau*dt` and integrated torque work, not final momentum alone. The old full-kick/free G1d PASS remains a historical discrete-map result; the current World integrates continuous torque. The rigid world's sphere inertia is `2*m*r²/5`; a dynamic sphere can declare `inertia:{kind:'sphere-isotropic',about:'com',frame:'body-local',kgM2}` to supply that scalar. Other admitted primitive bodies use explicit `inertia:{kind:'primitive-com',about:'com',frame:'body-local'}`. Its box inertia is the local COM diagonal `m/3 * [hy²+hz², hx²+hz², hx²+hy²]`. Capsule inertia integrates a uniform cylinder and two hemispheres. For radius `r`, half centreline length `h`, cylinder mass `mc=m*3h/(3h+2r)` and cap mass `ms=m-mc`, its local Y moment is `mc*r²/2 + 2*ms*r²/5`. The X/Z moments are `mc*(r²/4+h²/3) + ms*(2*r²/5+h²+3*h*r/4)`. These primitive models do not recover exact CAD mass properties. Supply the correct mass and model before interpreting the motion. For the independent pendulum example, `comDistanceM` is the pivot-to-COM distance. Its state angle is zero when the COM is below the origin on −Y. Positive angle turns about +Z, and `comPositionM = [L*sin(angle), -L*cos(angle), 0]`. The pivot equation is `I_pivot * angleAcceleration = -massKg * gravityMps2 * L * sin(angle)`. A COM moment and a pivot moment cannot be substituted without the parallel-axis term. ## Off-origin CAD proxy example The public adapter admits one selected native Surface from the exact source text and revision. It returns `body:RigidBody`, `collider:Collider` and `binding:SourceBinding`. Add these values to the model's `bodies`, `colliders` and `sourceBindings` arrays. The binding has source revision/digest, occurrence/model IDs, numerical entity references and approximation metadata. Exact source text and native bounds remain with the adapter. They do not enter the numerical World. The body's input position is `proxy.body.initial.positionM`; geometry is `proxy.collider.geometry`. The accepted body state uses `orientationXYZW`. `cadProxyPose` reads that state and returns the display pose's `rotation`, also XYZW. The fixture below has source bounds `[20,-30,40]` to `[120,10,100]` mm. Its centre is `[70,-10,70]` mm. The admitted box half extents are `[0.05,0.02,0.03]` m. A +0.1 m X offset places its body centre at `[0.17,-0.01,0.07]` m. ```js import { createPhysicsWorld, PhysicsError } from '@barocss/physics'; import { admitCadSurfaceProxy, cadProxyPose } from '@barocss/physics/cad-proxy'; ``` ```js const source = `@model units_fixture { version: 0; length-unit: mm; @surface #asymmetric_panel { type: nurbs; degree-u: 1; degree-v: 1; knots-u: [0,0,1,1]; knots-v: [0,0,1,1]; control-points: [[[20,-30,40],[20,-30,100]],[[120,10,40],[120,10,100]]]; weights: [[1,1],[1,1]]; } }`; ``` Turn the body +90° about Z while keeping that body centre. The literal quarter-turn matrix gives `R*[x,y,z] = [-y,x,z]`, so `R*sourceCenterMM = [10,70,70]` mm. The display translation is therefore `[170,-10,70] - [10,70,70] = [160,-80,0]` mm. A translation of `[100,0,0]` mm alone is correct only for this fixture's identity orientation. ```js const proxy = admitCadSurfaceProxy(source, { sourceVersion: 0, sourceRevision: 'unitsRev1', modelId: 'units_fixture', surfaceId: 'asymmetric_panel', kind: 'dynamic', proxy: 'box', massKg: 1, initialOffsetM: [0.1, 0, 0], }); vectorNear(proxy.sourceCenterMM, [70, -10, 70], 1e-6); assert.equal(proxy.collider.bodyId, proxy.body.id); assert.deepEqual(proxy.binding.entityIds, [proxy.body.id, proxy.collider.id]); assert.equal(proxy.binding.sourceRevision, 'unitsRev1'); assert.match(proxy.binding.sourceDigest, /^sha256:[0-9a-f]{64}$/); assert.equal(proxy.collider.geometry.kind, 'box'); vectorNear(proxy.collider.geometry.halfExtentsM, [0.05, 0.02, 0.03], 1e-9); vectorNear(proxy.body.initial.positionM, [0.17, -0.01, 0.07], 1e-9); const body = { id: proxy.bodyId, positionM: [...proxy.body.initial.positionM], orientationXYZW: [0, 0, Math.SQRT1_2, Math.SQRT1_2] }; const pose = cadProxyPose(proxy, body, source, 'unitsRev1'); vectorNear(pose.translation, [160, -80, 0], 1e-6); // Independent +90° Z matrix: (x,y,z) -> (-y,x,z). const original = [[20, -30, 40], [20, -30, 100], [120, 10, 40], [120, 10, 100]]; const expected = [[190, -60, 40], [190, -60, 100], [150, 40, 40], [150, 40, 100]]; original.forEach(([x, y, z], i) => { const displayed = [-y + pose.translation[0], x + pose.translation[1], z + pose.translation[2]]; vectorNear(displayed, expected[i], 1e-6); vectorNear([displayed[1] + 80, 160 - displayed[0], displayed[2]], original[i], 1e-6); }); ``` The four expected display points are literal coordinates. The sample uses the quarter-turn matrix and an inverse transform rather than the adapter's quaternion helper to calculate its oracle. It compares admission lengths at `1e-9` m and display/inverse coordinates at `1e-6` mm. The source centre maps to the body centre `[170,-10,70]` mm under the same transform. The returned pose is a display transform of the original Surface. It is not a replacement collision mesh. A box proxy uses the Surface control-net AABB with minimum half extent; a sphere encloses that AABB. Keep the returned `lossLabel` with the simulation record. These source-adapter checks do not establish a compiled CAD consumer, a Viewer frame or exact Surface collision. ## Keep the source identity with the pose `assertCadProxyCurrent(proxy, currentSource, currentRevision)` and `cadProxyPose(...)` compare the complete source string and the caller revision. A changed string with an unchanged revision still gives `STALE_SOURCE`. A changed revision with the original string also gives `STALE_SOURCE`. An unknown or malformed binding is not permission to display a guessed pose. Keep the last accepted world state and frame after refusal. Re-admit the selected Surface explicitly when the source changes, then let the host replace the world and display binding. Do not silently reuse an old centre or apply the scale conversion twice. The documentation sample checks both stale cases and reuse of the original valid binding without changing retained input. For the numerical and product evidence boundaries, see [Physics verification](/reference/physics-verification). For command timing and state retention, see [profiles and lifecycle](./profiles-and-lifecycle). --- # Physics profiles and lifecycle Choose the numerical profile before creating a world. A larger body-count limit does not enable all smaller-profile features. Admission limits describe allowed inputs; numerical evidence covers the named cases only. This page describes the current unreleased branch, without a publication or active CAD adoption claim. Start with the [package overview](./) and [unit contract](./units-and-frames). ## Rigid world profiles All rigid-world profiles use `createPhysicsWorld(model, options)` from `@barocss/physics`. Unless a narrower profile fixes the step, `fixedStepSeconds` is in `[1/240, 1/30]` s. `step(commands?)` uses the configured value and takes no time argument. The limit is 3600 accepted steps. At least one dynamic body is required. | Selection | Capacity and combinations | Numerical scope and evidence route | | --- | --- | --- | | `profile:'rigid-discrete-v1'` | 1–32 spheres, oriented boxes or capsules; optional `broadPhase:'aabb'` | One contact point per pair and eight solver passes. Primitive contacts are not exact CAD collision. See [verification](/reference/physics-verification). | | `profile:'rigid-persistent-box-v1'` | At most four bodies; no `large-v1` or box-pair CCD | Awake, unfiltered dynamic/static boxes with zero restitution/friction and no joints/sensors/CCD use one global normal and all-pair position solve, with `broadPhase:'direct'` required and no failure fallback. Other material/role combinations retain their bounded manifold/contact laws. Minimum material restitution applies above the strict 0.5 m/s closing-speed switch. Selected centered and offset fixtures do not qualify arbitrary stacks. | | `profile:'rigid-stationary-cube-stack-v1'` | Exactly eight1kg half0.25m cubes and the original static floor;1200steps; direct broad phase, dt1/120, g=[0,-9.81,0], yaw-only poses, zero motion, original materials and empty commands | Exact32-point stationary witness; no fallback. Original three equilibrium scenes pass independent1200-step checks, public Source/compiled paths and actual desktop body-word parity. Unsupported contact chains refuse. This maintains equilibrium; falling, bounce, frictional settling and collapse are outside this profile. | | `profile:'rigid-large-v1'` | 1–64 bodies; requires `broadPhase:'aabb'`; requires an empty `joints` array; excludes CCD and persistent-box contact | Fixed collision filters and contact-island sleep. The named 63-sphere floor probe is a capacity case, not a general 64-body stack certificate. | | Anchored fixed or hinge joints | At most eight records. Each static/kinematic A connects to a uniquely jointed dynamic B | Body-local initial anchors must coincide within `1e-6` m. A hinge uses unit `axisWorld` and limits within ±π/2 that include zero. Connected bodies do not collide. | | One dynamic fixed joint | Exactly two dynamic spheres, no other bodies or joints | Inverse mass/inertia distribute corrections. The recorded equal-mass impulse fixture does not qualify general joint networks. | | One concentric dynamic hinge | Exactly two dynamic spheres at the same centre; zero gravity, zero initial motion, identity orientation, zero local anchors | Planar angular commands along the hinge axis only. An optional motor drives relative B/A speed with equal and opposite impulses. | | One offset dynamic hinge | Exactly two 1 kg spheres of radius 0.1 m; centres at ±0.1 m on X; opposing 0.1 m local X anchors | Fixed +Z hinge, limits `[-0.8,0.8]`, zero gravity and 1/120 s step. Motor target 0.5 rad/s, impulse cap 0.0001 N·m·s and reaction cap 0.01 N·m·s. This is one fixture. | | Two disjoint dynamic hinges | Exactly four 1 kg spheres of radius 0.1 m, forming the offset pair at Z=0 and Z=1 m | `rigid-discrete-v1`, direct broad phase, zero gravity, exact identity initial quaternions, zero initial motion, restitution 0, friction 1/0.7. Both hinges use the offset limits/motor above. Only empty commands; cross-component contact refuses. See the bounded evidence below. | | Sphere/static-box CCD | One CCD dynamic sphere and 1–8 static nonsensor oriented boxes; no joints or other bodies | Euclidean rounded-box sweep with selected independent face/edge/vertex/grazing evidence. Initial touch/overlap remains discrete-owned; arbitrary numerical scales and rotating fixtures are not qualified. | | Dynamic-sphere-pair CCD | Exactly two nonsensor dynamic spheres, exactly one with `ccd:true`; zero gravity, no joints | Exact represented endpoint/radius predicates with finite independent head-on/grazing/miss/initial/endpoint evidence. Both 5e-10 m inward biases remain. Extreme output accuracy and remaining-time integration are separate. `colliderId` denotes the other dynamic sphere's collider. | | Axis-aligned-box-pair CCD | One CCD dynamic box and one static nonsensor box, both axis-aligned; no joints or persistent boxes | Both signs of the identity quaternion are admitted with the same orientation/angular thresholds. Finite centered face-event boundaries have separate numerical and desktop proof. Nonzero angular commands refuse. Contact-induced rotation refuses the candidate. General rotation and tied-axis/corner events remain unqualified. | CCD stops at the earliest admitted hit with a `1e-9` m inward offset. It does not integrate the remaining fraction of that step. Initial overlap/touch uses the discrete path. Capsule CCD, general oriented-box CCD and arbitrary moving-body networks are outside these profiles. An anchored hinge motor uses `motor:{targetSpeedRadps,maxImpulseNms,maxReactionNms}`. Target speed is within ±2 rad/s. Its positive motor impulse cap is at most 0.05 N·m·s and its positive reaction cap is at most 1 N·m·s. It stops pushing outward at a hinge limit. Exceeding the reaction cap gives `NUMERIC_LIMIT`; it is not a material break-strength model. The offset profile fixes narrower values. Discrete static friction now solves both tangent constraints. Centered anisotropic cuboid impacts and original sphere/static-box branch inputs have separate numerical and desktop proof. The persistent manifold friction solver has its own cache/iteration law and is not qualified by those discrete results. General off-center normal/tangent coupling remains unqualified. The public persistent-box limit remains four bodies. The separate stationary cube profile uses the sole common World API and qualifies only the named equilibrium cases. It does not extend moving persistent-box dynamics. The disjoint-hinge profile has a separate qualification; it does not admit connected two-link mechanisms. Keep historical NO_GO results and unresolved causes alongside later bounded results in [Physics verification](/reference/physics-verification). The changing-normal persistent friction qualification currently has a public NO_GO: its accepted aggregate tangent is not in the reported normal plane, and the accepted paired contact witness fails independent native geometry. Existing centered impact and support results remain bounded proofs. No general tilted contact, contact-cache accuracy or stable-stack claim follows from admission. ### Two cubes and a floor The zero-friction island shares the common World, clock and recorder. Supply only initial conditions and commands. Render the accepted body state after a step. The renderer does not solve contacts or advance time. ```js const initial = positionM => ({ positionM, orientationXYZW: [0, 0, 0, 1], velocityMps: [0, 0, 0], angularVelocityRadps: [0, 0, 0] }); const cube = (id, y) => ({ id, kind: 'dynamic', massKg: 2, inertia: { kind: 'primitive-com', about: 'com', frame: 'body-local' }, initial: initial([0, y, 0]) }); const model = { format: 'barocss-physics-model', version: 1, revision: 'docsCoupledCubes1', frame: { id: 'world', basis: 'right-handed-xyz', rotation: 'local-to-world-xyzw' }, units: { length: 'm', mass: 'kg', time: 's', angle: 'rad' }, gravityMps2: [0, -9.81, 0], bodies: [cube('lower', 0.5), cube('upper', 1.75), { id: 'floor', kind: 'static', initial: { positionM: [0, -0.5, 0], orientationXYZW: [0, 0, 0, 1] } }], colliders: ['lower', 'upper', 'floor'].map(bodyId => ({ id: `hull:${bodyId}`, bodyId, geometry: { kind: 'box', halfExtentsM: bodyId === 'floor' ? [2, 0.5, 2] : [0.5, 0.5, 0.5] }, local: { positionM: [0, 0, 0], orientationXYZW: [0, 0, 0, 1] }, material: { restitution: 0, friction: { static: 0, dynamic: 0 } }, sensor: false, ccd: false, filter: { categoryBits: 1, maskBits: 65535 }, })), joints: [], cloths: [], fluids: [], sourceBindings: [], }; const options = { profile: 'rigid-persistent-box-v1', fixedStepSeconds: 1 / 120, broadPhase: 'direct' }; ``` ```js const world = createPhysicsWorld(model, options); try { for (let i = 0; i < 32; i++) world.step([]); const state = world.getState(); // Render state.bodies; rendering does not advance the World. assert.equal(state.stepIndex, 32); assert.equal(state.timeSeconds, 32 / 120); assert.equal(state.contacts.length, 2); for (const [id, height] of [['lower', 0.5], ['upper', 1.5]]) { const body = state.bodies.find(value => value.id === id); assert.ok(Math.abs(body.positionM[1] - height) <= 1e-10); assert.ok(Math.abs(body.velocityMps[1]) <= 1e-10); } } finally { world.dispose(); } ``` This executable example covers two aligned2kg cubes, a prescribed static floor, gravity−9.81m/s², zero restitution/friction and a1/120s step. The32/256-step Source and actual compiled World checks pass the unchanged independent global projection and1e-12m representative-geometry gates. The original step27 failure is preserved. Actual restore/continuation, failure recovery and same-Native desktop rendering also pass, with separate receipts in [Physics verification](/reference/physics-verification). Admission alone does not qualify arbitrary mass ratios, tilted boxes, friction, simultaneous elastic impact or moving eight-body stacks. The island prepares every body's tensor. Its historical rotated-anisotropic precontact refusal is preserved. The later symmetric tensor construction passes the bounded precontact cases below; this does not qualify general tilted contact. The isolated rotor example further below uses `rigid-discrete-v1` and has separate G1 evidence. The same World also passes the aligned three-cube/floor case within the existing four-body cap. Lower and middle supports start at step1; the falling top joins the chain at27. Source/compiled256-step results pass an independent3DOF global reference and actual same-Native desktop state/word/pixel checks. This extends the stated equal2kg, zero-friction/restitution120Hz family only. ```js const chain = structuredClone(model); chain.revision = 'docsThreeCubes1'; chain.bodies.find(body => body.id === 'upper').initial.positionM[1] = 2.75; chain.bodies.push(cube('middle', 1.5)); chain.colliders.push({ ...structuredClone(chain.colliders[0]), id: 'hull:middle', bodyId: 'middle' }); const world = createPhysicsWorld(chain, options); try { for (let i = 0; i < 32; i++) world.step([]); const state = world.getState(); assert.equal(state.stepIndex, 32); assert.equal(state.contacts.length, 3); for (const [id, height] of [['lower', 0.5], ['middle', 1.5], ['upper', 2.5]]) { const body = state.bodies.find(value => value.id === id); assert.ok(Math.abs(body.positionM[1] - height) <= 1e-10); assert.ok(Math.abs(body.velocityMps[1]) <= 1e-10); } } finally { world.dispose(); } ``` The numerical case has0 restore calls; earlier two-cube recorder restoration is separate evidence. General four-body topology and moving8 remain unqualified. ### Rotated noncubic box before contact The same `rigid-persistent-box-v1` World now advances the original rotated 2 kg box without its old precontact tensor-symmetry refusal. Primitive COM, direct broad phase and existing limits remain. This executable example runs a single noncubic box for 12 contact-free steps: ```js const model = orientationXYZW => ({ format: 'barocss-physics-model', version: 1, revision: 'docsAnisotropic1', frame: { id: 'world', basis: 'right-handed-xyz', rotation: 'local-to-world-xyzw' }, units: { length: 'm', mass: 'kg', time: 's', angle: 'rad' }, gravityMps2: [0, -9.81, 0], bodies: [{ id: 'box', kind: 'dynamic', massKg: 2, inertia: { kind: 'primitive-com', about: 'com', frame: 'body-local' }, initial: { positionM: [0, 5, 0], orientationXYZW, velocityMps: [0, 0, 0], angularVelocityRadps: [0, 0, 0] } }], colliders: [{ id: 'boxHull', bodyId: 'box', geometry: { kind: 'box', halfExtentsM: [0.25, 0.5, 0.75] }, local: { positionM: [0, 0, 0], orientationXYZW: [0, 0, 0, 1] }, material: { restitution: 0, friction: { static: 0, dynamic: 0 } }, sensor: false, ccd: false, filter: { categoryBits: 1, maskBits: 65535 } }], joints: [], cloths: [], fluids: [], sourceBindings: [], }); const options = { profile: 'rigid-persistent-box-v1', fixedStepSeconds: 1 / 120, broadPhase: 'direct' }; ``` A world-frame angular impulse acts once. The example maps body X to world Y and checks the analytic principal-axis speed of 3/13 rad/s: ```js const world = createPhysicsWorld(model([0, 0, Math.SQRT1_2, Math.SQRT1_2]), options); try { world.step([{ kind: 'angularImpulse', bodyId: 'box', angularImpulseNms: [0, 1 / 8, 0] }]); for (let n = 1; n < 12; n++) world.step([]); const state = world.getState(), body = state.bodies[0]; // Body X is world Y in this initial pose. I_x = 13/24 kg·m². assert.ok(Math.abs(body.angularVelocityRadps[1] - 3 / 13) <= 1e-10); assert.equal(state.stepIndex, 12); assert.equal(state.contacts.length, 0); } finally { world.dispose(); } ``` Separate Source/actual compiled verification uses a lower cube and floor as well: 64-step natural and principal-spin cases, both at three matched-time step sizes, rollback/restore and actual desktop state-word/GPU checks pass. Upper clearance stays positive. This proves precontact motion and selected lower-floor support, not anisotropic impact, general contact or friction. Continuous gravity position error at 64/120 s is 0.0218 m; dt refinement confirms first-order kick-drift. See [verification](/reference/physics-verification#rotated-anisotropic-precontact-repair). ### Isolated noncubic rotor The common World accepts primitive-COM noncubic boxes within the existing mass, dimension, pose and fixed-step ranges. There is no literal rotor whitelist or one-step horizon. Sphere, cube and capsule inertia use the same angular flow; capsules now use uniform-volume cylinder and hemisphere moments about their COM. Existing contact, joint and CCD admission limits remain separate. Use `freeModel()` and `worldOptions` from the [overview](./) with this example. Its mass, half extents and loads are sample values, not required constants: ```js const isolatedRotorModel = () => ({ ...freeModel([0, 0, 0]), revision: 'docsRotor1', bodies: [{ id: 'rotor', kind: 'dynamic', massKg: 1, inertia: { kind: 'primitive-com', about: 'com', frame: 'body-local' }, initial: { positionM: [0, 0, 0], orientationXYZW: [0, 0, 0, 1], velocityMps: [0, 0, 0], angularVelocityRadps: [1, 1, 1] } }], colliders: [{ ...freeModel().colliders[0], id: 'rotorHull', bodyId: 'rotor', geometry: { kind: 'box', halfExtentsM: [0.1, 0.2, 0.3] } }], }); ``` J acts once at step start. World-frame torque acts continuously during that step and expires. The next call advances the same World and configured clock: ```js const world = createPhysicsWorld(isolatedRotorModel(), worldOptions); try { const accepted = world.step([ { kind: 'angularImpulse', bodyId: 'rotor', angularImpulseNms: [1 / 1024, -1 / 2048, 1 / 4096] }, { kind: 'torque', bodyId: 'rotor', torqueNm: [1 / 128, -1 / 256, 1 / 512] }, ]); assert.equal(accepted.stepIndex, 1); const continued = world.step(); assert.equal(continued.stepIndex, 2); near(continued.timeSeconds, 2 * dt); assert.notDeepEqual(continued.bodies[0].orientationXYZW, accepted.bodies[0].orientationXYZW); near(continued.bodies[0].orientationXYZW.reduce((sum, x) => sum + x * x, 0), 1); assert.ok(continued.bodies[0].angularVelocityRadps.every(Number.isFinite)); assert.deepEqual(world.getState(), continued); } finally { world.dispose(); } ``` The free solver uses eighth-order geometric composition. Constant-torque integration uses eighth-order modified-midpoint extrapolation. A priori subdivisions are capped at64; finite-arithmetic, movement or conditioning failures return `NUMERIC_LIMIT` without committing state or recording. This cap is not a change to contact iterations or physical tolerances. See [Physics verification](/reference/physics-verification#g1-general-continuous-rotation) for the measured profiles and preserved initial failures. Long-time conservation does not prove long-time phase accuracy. No integrator option or compatibility World exists. ### Use the selected disjoint-hinge model Both directed pairs have local anchors `[0.1,0,0]` and `[-0.1,0,0]` m. The centres are `[-0.1,0,0]`, `[0.1,0,0]`, `[-0.1,0,1]` and `[0.1,0,1]` m. Initial quaternions must be exactly `[+0,+0,+0,1]`; normalization aliases and negative-zero quaternion components refuse. No body is shared between joints. The existing common World owns both pairs and one accepted clock. ```js const disjointHingeModel = () => { const model = freeModel([0, 0, 0]); model.revision = 'docsHinge2'; const ids = ['pairA0', 'pairB0', 'pairA1', 'pairB1']; model.bodies = ids.map((id, index) => ({ ...freeBody(), id, massKg: 1, initial: { positionM: [index % 2 === 0 ? -0.1 : 0.1, 0, Math.floor(index / 2)], orientationXYZW: [0, 0, 0, 1], velocityMps: [0, 0, 0], angularVelocityRadps: [0, 0, 0] } })); model.colliders = ids.map(id => ({ ...freeModel().colliders[0], id: `collider:${id}`, bodyId: id, material: { restitution: 0, friction: { static: 1, dynamic: 0.7 } } })); model.joints = [0, 1].map(index => ({ id: `hinge${index}`, kind: 'hinge', bodyAId: ids[index * 2], bodyBId: ids[index * 2 + 1], anchorALocalM: [0.1, 0, 0], anchorBLocalM: [-0.1, 0, 0], axisWorld: [0, 0, 1], limitRad: [-0.8, 0.8], motor: { targetSpeedRadps: 0.5, maxImpulseNms: 0.0001, maxReactionNms: 0.01 } })); return model; }; ``` Use the imports and `worldOptions` from the [overview](./). The helper above also uses its `freeModel()` and `freeBody()` data builders. Empty arrays are the supported command input for this profile. Nonempty angular commands along the axis also refuse. Do not substitute a prescribed motion path. ```js const world = createPhysicsWorld(disjointHingeModel(), worldOptions); try { world.step([]); const state = world.step([]); assert.equal(state.stepIndex, 2); assert.equal(state.timeSeconds, 2 / 120); assert.equal(state.joints.length, 2); assert.equal(state.contacts.length, 0); } finally { world.dispose(); } ``` This short example verifies API use. The separate original 1,200-step campaign and its precise source/emitted boundaries are in [verification](/reference/physics-verification#p3-disjoint-hinge-qualification). It does not establish arbitrary joint networks, contact coupling, a convergence order, cross-runtime equality or measured machine accuracy. ### Rigid input bounds The model declares all entity arrays, including empty `joints`, `cloths`, `fluids` and `sourceBindings`. Rigid profiles refuse nonempty cloth/fluid arrays. Each rigid body has exactly one collider with an identity local transform. `ccd`, sensor flags, geometry, material and collision filters belong to the collider. The body declares mass/inertia for dynamics and its explicit `initial` state. State carries numerical motion; read copied `getModel()` data for initial conditions, collider geometry and source bindings. Body IDs are unique ASCII identifiers with at most 64 characters and a starting letter. Each position component is within ±10000 m. Velocity components are within ±1000 m/s and gravity components within ±1000 m/s². Mass is `1e-6`–`1e6` kg. Sphere radius, box half extents and capsule length parameters are `1e-4`–1000 m. Restitution is 0–1. Explicit material friction satisfies `0 <= dynamic <= static <= 2`; supply both coefficients, including zero values. A step accepts at most 64 dense plain-object commands. Each body can receive one command of each applicable kind. Force and torque components are bounded by ±`1e6` N or N·m; linear and angular impulse components by ±`1e5` N·s or N·m·s. Angular velocity components are within ±1000 rad/s. A candidate refuses movement or measured penetration above 10 m, or angular displacement above 10 rad per step. Limits are numerical guards, not recommended physical operating conditions. ## Visual domains, recording and independent helpers Cloth and fluid use the root common World. They share its fixed clock, candidate commit and idempotent disposal. Their selected profiles admit one domain plus fixed static colliders. They refuse dynamic mixtures and do not exchange forces with moving rigid bodies or with each other. The old domain factory subpaths are removed. CAD data admission is not another simulation owner. | Entry and selection | Step and capacity | Boundary | | --- | --- | --- | | Root World, `fluid-basin-visual-v1` or `fluid-basin-xsph-visual-v1` | Exactly256 particles in a0.7 ×1.3 ×0.5m basin;1/120s;3600-step admission cap | Qualified horizon720steps. XSPH coefficient0.15 is a visual parameter. No calibrated viscosity, emitters or moving obstacles. | | Root World, `cloth-pinned-sphere-visual-v1` | Fixed289vertices and512triangles;1/120s;240host steps | Two pinned corners and one static sphere. No fabric calibration, self-collision, tearing or arbitrary mesh admission. | | `admitCadFluidStaticData`, then root `fluid-static-box-visual-v1` | Version1 water and one static axis-aligned CAD box proxy | Qualified horizon240steps. Caller checks exact current source/revision before stepping. No XSPH combination or moving CAD obstacle. | | `/replay` |512frames,4096total commands,128KiB canonical model and1MiB binary recording including8-byte magic | Bounded accepted rigid command log. Cloth attach refuses `WORLD_LIMIT`; fluid attach refuses `INVALID_SNAPSHOT`. No domain restore is qualified. | | Independent example `createPlanarPendulum`, outside the public root | Step1e-6–1/30s; dt × natural frequency ≤0.05;1–1000000steps | One reduced angle, velocity Verlet, no contacts, motors or damping. Pivot+Z, gravity−Y. | | Root `createUprightCapsuleQuery`, `upright-capsule-box-v1` |0–32immutable static boxes; query displacement norm≤2m | Fixed upright capsule: radius0.15m, half segment0.35m. Scene box centres±10m, half extents0.0001–5m; query centres±5m. Query does not advance a World. | | Root `createUprightCapsuleController`, `upright-capsule-controller-v1` | Exactly1/120s; at most240steps | Bounded capsule query,−Y gravity,0.002m skin,0.1m step limit and10°walkable slope. No general dynamic obstacles. | See the [fixed visual model example](./#fixed-cloth-and-fluid-model-data) and [verification](/reference/physics-verification#p5-common-world-visual-profiles). An admission cap is separate from the executed horizon. ## Own the clock and retain accepted state `PhysicsWorld.step(commands?)` advances one configured step. It does not read wall time or change the step size to match display refresh. The host can accumulate elapsed display time and request whole fixed steps, subject to its own work budget. A dropped display frame does not authorize a larger Physics step. `getState()` and successful `step()` return independent copies, including nested body vectors, contacts, events, joints, CCD hits and pair counts. Editing returned arrays does not edit the world. The world commits only an accepted candidate. An invalid command or numerical candidate leaves the last accepted state available. Do not hide refusal with an automatic retry or a changed gate. ```js const world = createPhysicsWorld(freeModel([0, 0, 0]), worldOptions); const accepted = world.step(); assert.throws(() => world.step(dt / 2), hasCode('INVALID_COMMAND')); assert.deepEqual(world.getState(), accepted); accepted.bodies[0].positionM[0] = 999; accepted.bodies[0].orientationXYZW[3] = 0; const copied = world.getState(); const modelCopy = world.getModel(); modelCopy.bodies[0].initial.positionM[1] = 999; near(world.getModel().bodies[0].initial.positionM[1], 2); const hit = world.query({ kind: 'overlap-sphere', centerM: copied.bodies[0].positionM, radiusM: 0.01, includeSensors: false }); assert.deepEqual(hit, { kind: 'overlap-sphere', colliderIds: ['collider:ball'] }); assert.throws(() => world.query({ kind: 'overlap-sphere', centerM: [NaN, 0, 0], radiusM: 0.01, includeSensors: false }), hasCode('INVALID_QUERY')); assert.deepEqual(world.getState(), copied); near(copied.bodies[0].positionM[0], dt); assert.deepEqual(copied.bodies[0].orientationXYZW, [0, 0, 0, 1]); world.dispose(); world.dispose(); // Idempotent. assert.throws(() => world.getState(), hasCode('DISPOSED')); assert.throws(() => world.step(), hasCode('DISPOSED')); ``` This sample uses the imports, `dt`, `worldOptions` and `freeModel()` fixture shown on the [overview](./). Its `hasCode(code)` helper accepts only `error instanceof PhysicsError && error.code === code`. The test checks refusal after one accepted step, edits returned data, then checks the retained world. `dispose()` is idempotent. Later reads, queries and steps give `DISPOSED`. The rigid world has no public reset or arbitrary state setter. Create a new world for a new initial condition. ## Handle typed refusals | Code | Caller action | | --- | --- | | `INVALID_CONFIG` | Correct the input model or select a supported profile before creating another instance. | | `INVALID_STEP` | For numerical helpers and independent reference APIs that take `dt`, supply their configured step. A numeric argument to common World `step` gives `INVALID_COMMAND`. | | `INVALID_COMMAND` / `INVALID_QUERY` | Correct the command or query; do not alter accepted state to conceal the refusal. | | `WORLD_LIMIT` | The admitted step, frame or command budget is exhausted. Choose an explicit new session. | | `NUMERIC_LIMIT` | Stop advancing this model. Record the first failed input and the retained state before investigating. | | `STALE_SOURCE` | Re-admit the CAD source/revision explicitly before replacing the binding. | | `WORLD_OWNED` | Advance through the attached recorder; reads and queries remain available. | | `STALE_SNAPSHOT` | Model, source, configuration or provider identity differs. Restore only against the intended matching identity. | | `INVALID_SNAPSHOT` | Reject malformed, unsupported or damaged replay data. | | `INITIAL_OVERLAP` / `ITERATION_LIMIT` | Capsule-query refusal: initial penetration or unresolved bounded search. This is not a partial valid sweep. | | `DISPOSED` | Create a new instance. A disposed object cannot resume. | State has `identity`, tagged query results use collider IDs, and bodies report `orientationXYZW`. Contacts use `bodyAId`, `bodyBId`, `colliderAId`, `colliderBId`, `normalImpulseNs` and `tangentImpulseOnBNs`. Joint reactions use `linearImpulseOnBNs` and `angularImpulseOnBNms`. `PhysicsError.details` identifies the operation, phase, domain, entity IDs and last accepted step/time. Use `PhysicsError.code` for branching. Error messages supply context and are not a stable protocol. The root and its replay/CAD adapter entries share the error constructor within one installed package instance. Do not assume `instanceof` identity across versions, realms or separate source/compiled bundles. ## Restore a command log, not arbitrary state Attach `createPhysicsRecorder(world)` at step0, before any World step. The recorder supplies `step(commands?)`, `getState()`, copied `saveRecording()` and `dispose()`. The configured `dt` owns time; `step` takes no step-size argument. A direct or cached `world.step` call and a second attachment refuse with `WORLD_OWNED`. World reads and queries remain available. Recorder disposal detaches it without disposing the World. Dispose both objects when finished. World disposal invalidates its recorder. Disposal releases recording/options references; no garbage-collection timing or out-of-memory recovery guarantee follows. An advanced World cannot acquire a new recording history. `restorePhysicsRecording(recording,{model,options,providerDigest})` validates complete recording shape and bounds before expected model, configuration and provider identity. Source revisions are model `sourceBindings` data. Use the intended current World's `getState().identity.providerDigest` as the external expected provider digest. Restore reconstructs an isolated World, replays indexed accepted commands and compares final state at `1e-12` absolute/relative numeric tolerance. It returns `{world,recorder}` only on success. Dispose both objects. The command frame and log budgets are checked before candidate calculation. Final state, returned copy and complete bounded encoding are prepared before the nonthrowing shared physical/log commit. Changed identity gives `STALE_SNAPSHOT`; damaged data gives `INVALID_SNAPSHOT`. Persist with `serializePhysicsRecording(recording):Uint8Array` and read with `deserializePhysicsRecording(bytes)`. The wire format is ASCII `BCPHREC1` followed by bounded canonical typed encoding. It preserves binary64 number bits, including `-0`. The decoder refuses JSON, unknown tags, nonfinite numbers, truncated/trailing bytes and unsupported versions. Record keys use canonical ASCII order; arrays retain their order. There is no old-version migration, arbitrary body-state import or bitwise cross-platform trajectory promise. ```js import { createPhysicsRecorder, restorePhysicsRecording, serializePhysicsRecording, deserializePhysicsRecording } from '@barocss/physics/replay'; ``` ```js const model = freeModel([-0, 0, 0]); const world = createPhysicsWorld(model, worldOptions); const session = createPhysicsRecorder(world); const expected = { model, options: worldOptions, providerDigest: world.getState().identity.providerDigest }; let restored; try { session.step([{ kind: 'impulse', bodyId: 'part:ball', impulseNs: [2, 0, 0] }]); const recording = session.saveRecording(); const bytes = serializePhysicsRecording(recording); assert.equal(Buffer.from(bytes.subarray(0, 8)).toString('ascii'), 'BCPHREC1'); const decoded = deserializePhysicsRecording(bytes); assert.ok(Object.is(decoded.model.gravityMps2[0], -0)); restored = restorePhysicsRecording(decoded, expected); assert.deepEqual(restored.recorder.getState(), session.getState()); assert.deepEqual(restored.recorder.step(), session.step()); recording.frames[0].commands[0].impulseNs[0] = 999; near(session.saveRecording().frames[0].commands[0].impulseNs[0], 2); assert.throws(() => deserializePhysicsRecording(bytes.subarray(0, -1)), hasCode('INVALID_SNAPSHOT')); } finally { restored?.recorder.dispose(); restored?.world.dispose(); session.dispose(); world.dispose(); } ``` P2_DONE_LOCALSELECTED: public source05/emitted05 pass11/11 each; test-only preparation faults pass15/15 each across four step preparation points plus attach output preparation, each in three rigid profiles. Native03 passes staged published maps, strict positive/negative declarations, shared ownership registry, CAD release consumer and four README blocks. Ordinary probes and foundation checks pass21 per source/emitted graph; documentation samples pass174/174 in run03. Final recording callers pass3 per graph; documentation build/site/link receipts are docs-check/build/links-01. Historical P1b receipts apply only to their original providers. Whole-engine acceptance remains NO_GO. Keep a source-run receipt separate from a compiled-consumer receipt. Workspace aliases can resolve source even after a build. A compiled check must resolve each transitive package through its published entry map; the compiled root also needs sibling `dist/types.js`. See [Physics verification](/reference/physics-verification) for provenance and the accepted evidence stages. Neither replay equality nor a plausible animation validates contact loads, control hardware or manufacturing. --- # Connect CAD and Viewer Use one Physics World for one simulation. CAD, rendering and React do not own another numerical World. This page describes the current unreleased branch and the host boundary. CAD React is owned by a separate Work and is not inspected or changed here. This page does not establish CAD Studio integration. Existing Studio, manufacturing and equipment HOLDs stay. ## Data ownership | Layer | Owns | Sends to the next layer | | --- | --- | --- | | `@barocss/cad` | Native geometry and geometric queries | Stable geometry references, bounds and display tessellation | | `@barocss/cad-model/api` | Authored part definitions, IDs, units and available mass properties | A revision-bound model for an explicit Physics admission adapter | | Host admission adapter | Unit/frame conversion, supported collision approximation and body-to-part binding | A supported SI `PhysicsModel` and `WorldOptions` | | `@barocss/physics` | Accepted model/state, commands, fixed-step advancement and numerical failure | `PhysicsState`; optionally the existing recorder owns stepping | | Display adapter | Mapping accepted body IDs and poses to display objects | A Viewer motion frame or GPU transform data | | `@barocss/viewer` / `@barocss/gpu` | Camera, display resources, picking and drawing | Pixels and display interaction; no physics advancement | | React or Studio host | Lifecycle, user commands, selection and subscription | Commands to the sole simulation owner; display requests from accepted snapshots | Do not tessellate or rebuild CAD after every physics step. Keep the authored CAD model and reusable display meshes. Apply transient accepted poses to those meshes. A user command to commit a final pose to CAD would need its own document edit/undo contract; it is outside the current simulation work. The current CAD proxy entry is `@barocss/physics/cad-proxy`. `admitCadSurfaceProxy` admits a selected Source-v0 Surface as a bounded box or sphere approximation. `assertCadProxyCurrent` rejects a changed source or revision. These APIs do not provide exact B-rep collision or a general solid- mass/full-tensor import. CAD-model root exports no API; use the `/api` subpath. Generic COM offsets, principal axes, full tensors and collider-local offsets remain the G3 prerequisite before a general CAD part importer. ## Convert units and frames once CAD lengths use mm. The CAD-model mass API uses g and g·mm². Physics uses m, kg, s and radians. Convert length and mass by `1e-3`, inertia by `1e-9`. Return positions to mm only in the display adapter. Keep body-local dimensions and world-frame angular velocity, gravity, torque and impulses distinct. For an off-origin CAD proxy, use `cadProxyPose`; translation is not just the body centre in mm. It includes `-R(q) * sourceCenterMM`. See the independently checked [off-origin example](./units-and-frames#off-origin-cad-proxy-example). Viewer's `applyMotionFrame` and `applyGeometryMotionFrame` require an explicit `{basis:'part-xyz-matches-rhyup'}` agreement and use translation in mm with XYZW rotation. That flag does not perform a basis conversion. Choose and verify the host frame first. Changing the camera up vector alone does not convert model positions, rotations, gravity or inertia. The current contact examples use Y gravity. The earlier CAD consumer kept CAD XYZ and explicitly used Z gravity; that consumer is not proof of a general CAD-to-Viewer frame converter. For loaded primitive Surface packets, the existing Viewer call shape is: ```ts const pose = cadProxyPose(proxy, acceptedBody, source, revision); viewer.applyMotionFrame( { contextId: 'simulation', timeSeconds: acceptedState.timeSeconds, poses: [pose] }, [{ contextId: 'simulation', targetId: proxy.bodyId, ref: { modelId: proxy.modelId, surfaceId: proxy.surfaceId } }], { basis: 'part-xyz-matches-rhyup' }, ); ``` This excerpt shows the existing API boundary. The host must have loaded matching geometry, verified its basis and retained its binding. It is not a complete React component or an arbitrary CAD assembly adapter. The current primitive packet path admits at most four geometry entries. Viewer currently refuses overriding authored assembly poses. `examples/physics-lab/display.mjs` contains an actual accepted-state-to-Viewer implementation for its display proxies. ## Desktop display density `Viewer.resize(width,height)` takes backing-store device pixels. The host owns CSS layout and DPR. A fixed640×360 backing store stretched across a desktop canvas looks blurred even when the physics and pose tests pass. The contact sample uses the canvas's CSS content size times actual browser DPR, up to DPR2. It scales both axes together to retain the current public Viewer limits: at most4096 per axis and4194304 total pixels. It floors the final device pixel dimensions. Thus a large desktop may use a lower effective scale than2; this does not change numerical dt, state or solver tolerance. Resize and DPR changes must leave the accepted Physics state and clock unchanged. Actual native `Viewer.readPixels()` covers that backing store. The sample's 640×360 nearest-centre pixel sample is only a bounded test observer; it is not the display resolution or a second renderer. Native dimensions and byte counts must be checked separately. Desktop DPR1 and2, layout changes, real GPU pixels and state-word comparison belong to separate checks. Mobile is outside scope. ## Viewer and the current Studio viewport `@barocss/viewer` already exposes `applyMotionFrame` for loaded primitive Surface packets and `applyGeometryMotionFrame` for loaded primitive Surface/curve data. The common World can feed those APIs through an explicit accepted-pose adapter. Do not add another physics solver to Viewer or GPU. Viewer owns presentation; Physics owns the numerical state and commands. The current Studio does not use `@barocss/viewer`. Its `apps/cad-studio/src/viewport/gpuRenderer.ts` uses `@barocss/gpu/viewer` and has a host method `setInstanceTransforms`; `Viewport.tsx` supplies its `instanceTransforms` map. A future Studio adapter should target that existing host path. Adopting Physics does not require replacing the Studio renderer. `setInstanceTransforms` is a Studio host method, not a new public Physics/GPU API. Before Studio integration, define body-to-instance IDs, model revision, units, frame and absolute-versus-relative placement. Kinematic/FK preview and dynamics must not both write the same instance pose. Late Worker replies from an old revision must not replace the current display. Camera and picking must not step physics. No Studio source, dependency, build or screen test is changed here; its HOLD remains. CAD React belongs to another Work. It can later consume the same accepted-pose contract through its own lifecycle adapter. That does not create a second World or authorize changes to that Work in this task. ## Integrate in this order First qualify the selected numerical profile through the public World. Next verify a Viewer adapter with the same accepted states, independent transform checks and actual desktop GPU pixels. CAD React lifecycle work remains with its separate owner. A future Studio adapter should reuse the same pose contract with Studio's existing GPU viewport, only within an authorized integration scope. Existing Studio work stays on HOLD; this sequence does not resume its workers or change app dependencies. Keep kinematic playback separate from dynamics. CAD-model Robot/FK paths replay joint-space poses; they do not establish dynamic forces or contact accuracy. Exact CAD collision, arbitrary connected mechanisms, moving eight-body contact, real-equipment prediction and manufacturing approval remain outside the current qualified profile. See [verification](/reference/physics-verification) and [profiles and lifecycle](./profiles-and-lifecycle). --- # @barocss/gpu The studio's WebGPU viewer, and a small CSS-shaped scene and material language. It depends only on `@barocss/cad`. This package supplies the low-level canvas renderer. For the `Viewer` SDK class and its review-state API, see [`@barocss/viewer`](/packages/viewer/). - **Workspace use.** Source imports use TypeScript. The library build emits JavaScript and declarations. - **How the studio uses it.** The studio draws with this viewer when the browser has WebGPU. Its WebGL2 fallback is the studio's own renderer, not part of this package (see [WebGPU and WebGL2](#webgpu-and-webgl2)). - **In code.** `@barocss/gpu/api` describes a scene as an immutable object: a part's meshes, their materials, lights and a camera view. `show(viewer, scene)` puts it in the viewer below. See [Object API](/packages/api#scenes). ### Model meshes in a scene Pass a CAD part's or CAD Model assembly's `meshes()` to `scene().add()`. Use `{ lines: true }` to add its display edges. The meshes use the model's Z-up coordinates in mm. `Assembly.meshes()` includes the base and visible placed parts; it omits hidden instances. Its keys are `base/` or `/`. An `explode` value offsets placed meshes for display only; it does not change the assembly's placements or mates. `Scene.add()` returns a new Scene but shares the supplied geometry arrays. Treat those arrays as read-only. A model change does not update an existing Scene or Viewer automatically. Get `meshes()` from the updated part or assembly, build a new Scene with the desired settings, and call `show(viewer, newScene)` to display it. The show operation clears the Viewer before adding the new meshes and fitting the view. ## The viewer `@barocss/gpu/viewer` is one WebGPU renderer for a canvas. It: - owns one device and canvas context; - keeps geometry in long-lived buffers; - draws on demand, at most one frame per animation frame; - follows the canvas's size and pixel ratio; - replaces a lost device and uploads the scene again. ```js import { createViewer } from '@barocss/gpu/viewer'; const viewer = await createViewer(canvas, { background: { top: '#2e3035', bottom: '#18191b' }, grid: true }); const box = viewer.add({ positions, normals, indices, faces }, { material: { color: '#c0c4cc', roughness: 0.5 } }); viewer.add({ positions: edgeSegments, topology: 'lines' }, { material: { color: '#111111', unlit: true, lineWidth: 1.5 } }); viewer.lights = [{ kind: 'directional', direction: [-0.4, 0.6, -1], castShadow: true }]; viewer.environment = { ambientOcclusion: { strength: 1 } }; viewer.fit(); const hit = viewer.raycast(x, y); // the mesh, triangle, face, instance and point, on the CPU const gpuHit = await viewer.pick(x, y); // the same from the GPU's id and depth targets box.outline = '#e8c25a'; // a selection outline round the visible part ``` This example is the package README's. It needs a browser with WebGPU, so it isn't one of this site's samples. The package's own browser tests drive it in Chrome. - **Camera.** - Perspective, with an infinite far plane, or orthographic. - Reversed depth, and clip planes fitted to the scene. - `fit()`, and rays from the cursor. - Orbit, pan, and zoom to the point under the cursor; `controls: false` lets you drive the camera yourself. - **Materials.** - Metal–roughness, lit by directional, point and spot lights and a hemisphere ambient; or unlit. - Vertex colours, colour maps with mipmaps, transparency drawn back to front, shadow catchers. - Shader materials, below. - **Lines.** Screen-space width, segment ids, and `pickLine()`. - **The scene.** - Instancing (one draw for many copies) and frustum culling. - Directional, spot and point shadows within the [light limits below](#light-and-shadow-limits). - Ambient occlusion, a gradient or transparent background, and a ground grid. - Contact shadows: `environment.contactShadows: { length?, strength? }` darkens where the depth buffer blocks a short ray toward the first shadow caster among the first four directional lights, in the creases the shadow map is too coarse for. - Bloom: `environment.bloom: { strength?, threshold?, knee? }` adds a glow from pixels above a linear-light threshold before tone mapping. Defaults are strength 0.05, threshold 1 and a soft knee one quarter of the threshold. Set `bloom` to false, omit it, or set strength to 0 to turn it off. A half-resolution prefilter and a downsample/upsample chain spread the highlights; the targets are recreated on resize and released with the viewer. - 4× MSAA, exposure and ACES tone mapping in a linear half-float pipeline. - Clip planes and cap hatching for sections. ### PBR data maps Triangle materials accept `normalMap`, `roughnessMap` and `metallicMap` through the geometry's UVs, in raster rendering and progressive stills. Create these textures with `{ srgb: false }`: they hold linear data, not colour. This SDK example assumes an existing `viewer`, triangle `box`, matching `uvs` and RGBA pixel arrays: ```js const normalMap = viewer.createTexture({ width, height, data: normalPixels }, { srgb: false }); const packed = viewer.createTexture({ width, height, data: packedPixels }, { srgb: false }); box.geometry.setUVs(uvs); box.material = { normalMap, normalScale: [1, 1], roughnessMap: packed, roughness: 1, metallicMap: packed, metallic: 1, }; viewer.requestRender(); ``` Normal RGB encodes a tangent-space +Y normal. `normalScale` scales X/Y and defaults to `[1, 1]`; use a negative Y scale for the opposite convention. A missing or degenerate UV frame keeps the original surface normal. The roughness map's green channel and metallic map's blue channel multiply their material values, so one packed texture can serve both roles. Set a map to `null` to remove it. For a uniform RGBA8 data texture `[255, 128, 64, 255]` created with `{ srgb: false }`, the green and blue samples are `128/255` and `64/255`. With material roughness `0.8` and metallic `0.6`, the parameters become: | Parameter | Calculation | Approximate result | | --- | --- | --- | | Roughness | `0.8 × (128/255)` | `0.401569` | | Metallic | `0.6 × (64/255)` | `0.150588` | These are parameter calculations before lighting, not final pixel RGB values or captured API results. Byte `128` is `128/255`, not exactly `0.5`. Filtering can mix samples from a non-uniform texture. Data maps require live textures and triangle geometry. They cannot be combined with a scalar-field `Mesh.colorMap`. A data map that is not a live `ImageTexture` with `srgb: false` refuses with `TEXTURE_INVALID`. A `normalScale` without exactly two finite f32 numbers refuses with `MATERIAL_INVALID`, as do data maps on non-triangle geometry or in combination with a scalar-field colour map. Disposing an accepted map restores the raster material's unmapped value. An existing frozen still retains its own pixels and material snapshot; remove or replace disposed references before creating another still. ### Surface analysis shaders (Zebra, Draft and Curvature) The WebGPU viewer provides real-time surface continuity and manufacturability inspection shaders through `SurfaceAnalysisOptions` (`mode: 'none' | 'zebra' | 'draft' | 'curvature'`). When `mode` is `'none'` (the default), the standard PBR surface shader runs untouched. | Mode | Purpose | Options & Defaults | | --- | --- | --- | | `'zebra'` | View-space reflection stripes for G0/G1/G2 surface continuity inspection | `stripeCount` (`16`, clamped `1..128`), `axis` (`'horizontal' \| 'vertical' \| 'diagonal'`), `contrast` (`0.92`, `0..1`) | | `'draft'` | World-space mold pull-angle classification | `pullAxis` (`'x' \| 'y' \| 'z' \| '-x' \| '-y' \| '-z'`, default `'z'`), `draftAngle` (`3°`, clamped `0.1..45°`) | | `'curvature'` | Screen-space surface curvature heatmap | `curvatureScale` (`0.5` `1/world-unit`, clamped `0.01..100`) | ```js // Inspect fillet continuity with diagonal Zebra reflection stripes viewer.surfaceAnalysis = { mode: 'zebra', stripeCount: 24, axis: 'diagonal', contrast: 0.92 }; // Switch to mold draft-angle inspection along +Z with a 2° minimum threshold viewer.surfaceAnalysis = { mode: 'draft', pullAxis: 'z', draftAngle: 2 }; // Switch to curvature heatmap, or pass null / { mode: 'none' } to return to PBR viewer.surfaceAnalysis = { mode: 'curvature', curvatureScale: 0.8 }; ``` Unsupported mode or axis strings and non-finite numeric values refuse with `ViewerError('MATERIAL_INVALID')`. ### Light and shadow limits The renderer uses the first lights of each kind in `viewer.lights`, not the first lights with shadows enabled. Set `castShadow: true` on a light within that set. `viewer.shadowMapSize` sets each shadow map's resolution. Setting `intensity: 0` still uses a light slot and does not disable shadow checks. If its `castShadow` is true, a point light still counts toward the one-caster limit. Set `castShadow: false` to disable its shadow. PCF averages nearby shadow-map comparisons. PCSS searches for blockers and varies the filter radius with blocker and receiver depth. | Light kind | Lights used | Shadow support and softness | | --- | --- | --- | | Directional | First 4 | Each can cast a shadow. `environment.softShadows` sets their shared angular size in degrees for PCSS. Zero or omission retains the hard, 3×3-filtered edge. | | Spot | First 4 | Each can cast a shadow. Zero or omitted `shadowRadius` uses PCF; a positive radius enables bounded PCSS. | | Point | First 8 | At most one can cast a shadow, using six 90-degree faces. Zero or omitted `shadowRadius` uses PCF; a positive radius enables bounded PCSS. A second enabled caster causes `LIGHT_INVALID`. | For an enabled spot shadow, position and direction must be finite f32 vectors, and direction must be nonzero. The cone half-angle is in degrees and must be strictly between 0 and 90; the default is 30. Range must be finite and nonnegative; zero or omission fits the shadow depth to the scene. `shadowRadius` is a light disk radius in scene world units, not degrees or CSS pixels. It must be finite, nonnegative and representable in f32 without rounding a positive value to zero. Invalid enabled inputs refuse with `LIGHT_INVALID`. `penumbra` is a separate 0–1 share of the cone used to fade its lighting edge. It does not set shadow softness. Spot PCSS uses bounded blocker-search and filter radii; it approximates a disk light, not an area-light renderer. `environment.softShadows` applies to directional shadows, not spot or point shadows. These SDK settings use the existing spot and point examples. They assume an existing WebGPU viewer and scene; the positions, range and radius use that scene's world units, which are not automatically mm. ```js // Spot example: source [5, -3, 7], aimed at [0, 0, 0.6]. viewer.lights = [{ kind: 'spot', position: [5, -3, 7], direction: [-5, 3, -6.4], angle: 30, penumbra: 0.2, shadowRadius: 0.4, range: 18, intensity: 80, castShadow: true }]; viewer.requestRender(); // Alternative point example: this assignment replaces the light list. viewer.lights = [{ kind: 'point', position: [1, -1, 3.5], range: 18, intensity: 100, shadowRadius: 0.25, castShadow: true }]; viewer.requestRender(); ``` For an enabled point shadow, position must be a finite f32 vector. Both `range` and `shadowRadius` must be finite, nonnegative and representable in f32 without rounding a positive value to zero. A positive range keeps the spherical lighting cutoff and limits each face's far plane; zero or omission fits the faces to the scene and cap bounds. Inputs that cannot form a finite f32 depth projection refuse with `LIGHT_INVALID`. These shadow admission checks apply only to enabled casters among the first four spot lights or first eight point lights. Point PCSS approximates the emitter with a disk perpendicular to each receiver ray. It uses the six shadow faces with bounded blocker-search and filter radii. The radius uses the scene's world units. It is not an area-light simulation. The Viewer checks shadow inputs during creation and before each draw. Direct assignment to `viewer.lights` does not run these checks. ### Capture pixels and release the viewer `viewer.capture()` draws a frame and returns a promise for `{ width, height, data }`. The dimensions are `canvas.width` and `canvas.height`: canvas backing pixels, not CSS pixels or model units. `data` is a `Uint8Array` of packed RGBA bytes. Rows run from top to bottom; each pixel has four consecutive bytes. | Returned data | Byte layout | | --- | --- | | One pixel at `(x, y)` | R, G, B, A at offsets `4 * (y * width + x)` through `4 * (y * width + x) + 3` | | One row | `width * 4` bytes, with no row padding in the returned array | | A 640 × 480 backing image | `640 * 480 * 4 = 1,228,800` bytes | ![Calculated RGBA row layout for a 640 by 480 backing image; this is not an API capture](/diagrams/capture-rows.svg) [Open the byte layout at full size](/diagrams/capture-rows.svg). The renderer removes GPU readback row padding and converts BGRA to RGBA when needed. The result is raw pixels, not a PNG file. A caller must encode them to create an image file. Studio's image export adds that encoding step with `ImageData` and an `OffscreenCanvas`. | Method | Caller action and result | | --- | --- | | `requestRender()` | Request a draw after changing public camera or light fields. Built-in scheduling combines requests into one frame. With `onRequestRender`, each request calls that callback instead. | | `frame()` | Request a frame and return `Promise` for the frame waiter. It can also resolve after GPU-work failure or disposal; it returns no image bytes. | | `capture()` | Draw and read the RGBA bytes; handle its asynchronous failure separately. | | `dispose()` | Release the viewer when its canvas is no longer needed. Repeated calls are safe. | `dispose()` cancels scheduled work, removes controls and resize observation, and releases GPU resources. After disposal, `capture()` rejects with `DISPOSED`, while `requestRender()` returns without scheduling work. Disposal also releases pending frame waiters; a resolved `frame()` promise alone is not proof of a successful capture. Keep the viewer alive until operations that need it have finished. ### Progressive still images `viewer.createPathTrace()` creates a separate offscreen still with frozen scene, camera, materials and lighting. Later viewer edits do not update it; create another session for the edited scene. Raster controls remain independent. Width and height are output backing pixels, independent of the interactive canvas; omission uses the canvas size. `bounces` is an integer from 1 to 16 and defaults to 6. This SDK example uses an existing populated WebGPU viewer: ```js const still = await viewer.createPathTrace({ width: 640, height: 480, bounces: 6 }); try { await still.sample(8); const raw = await still.capture(false); await still.start(samples => { if (samples >= 32) still.stop(); }); const frame = await still.capture(true); console.log(frame.width, frame.height, frame.samples, frame.data); console.log(raw.samples); // Remains 8 after the later sampling. } finally { still.dispose(); } ``` Each manual `sample()` batch accepts 1–64 samples. Stop progressive sampling before calling it; an active session refuses manual sampling with `PATH_TRACE_BUSY`. `start()` resolves after sampling stops; `stop()` ends progressive sampling. Sample before capture: capture with no completed samples also refuses with `PATH_TRACE_BUSY`. Unlike raster `viewer.capture()`, `still.capture()` returns `{ width, height, samples, data }`. Its top-to-bottom RGBA `Uint8Array` is raw pixels, not PNG data. `capture(false)` skips denoising; `capture(true)` uses geometry-aware denoising. `frame.samples` is fixed for those pixels when the queued capture starts. The live `still.samples` can advance later, so use `frame.samples` when labelling or exporting the image. Dispose each session when finished. The still includes visible, bounded triangle surfaces. Active section clips and caps, custom material shaders, scalar maps and contours refuse with `PATH_TRACE_UNSUPPORTED`. Lines, labels, overlays and raster shadow catchers are not included. Raster effects such as depth of field, bloom, SSAO, contact shadows and outlines do not apply. ### Depth of field The low-level viewer accepts `environment.depthOfField` as `false` or `{ focus, blur? }`: ```js viewer.environment = { ...viewer.environment, depthOfField: { focus: 160, blur: 6 }, }; ``` `focus` is a positive distance along the camera's view axis in the scene's world units. `blur` is a maximum radius in CSS pixels. Omitting `blur` uses 8; positive values are capped at 24. The renderer scales CSS pixels by the device pixel ratio. Omitting the effect, setting it to `false`, or using zero blur disables it. Non-finite or non-positive focus, and non-finite or non-positive blur, do not enable the effect. The example assumes an existing WebGPU viewer and its scene units; 160 is not automatically 160 mm. Studio stores its focus distance in mm and both its focus and blur values, as described under [Focus and blur](/studio/rendering#focus-and-blur). These are image settings, not geometric or physical accuracy bounds. ![View-axis focus depth is 80 mm while eye-to-point distance is 100 mm; blur is a separate CSS-pixel value](/diagrams/focus-distance.svg) [Open the focus diagram at full size](/diagrams/focus-distance.svg). This coordinate example uses Studio mm; use the GPU scene's own world unit when applying the same view-axis rule. ## The scene and material language The Render tab's props and its authored materials are written in this language. It runs on the CPU, so these samples run in Node: ```js // The Render tab's props: a plinth under the part. const props = compileGpu({ kind: 'scene', source: `@scene props { version: 0; box #plinth; } #plinth { size: 9 .4 6; translate: 3.2 -.25 -1.6; color: #6d727a; }` }); assert.equal(props.ok, true); const cone = compileGpu({ kind: 'scene', source: '@scene s {\n version: 0;\n cone #c;\n}\n' }); assert.equal(cone.ok, false); assert.deepEqual(cone.diagnostics[0], { code: 'VALIDATION', severity: 'error', message: 'Unsupported scene declaration', range: { start: 27, end: 31, line: 3, column: 3 } }); ``` ```js const paint = materialShader(`@shader #paint { @uniform amount: float(0, 1, .35); @fragment { color: mix(#d0643c, #3c78b4, amount); } }`); assert.equal(paint.ok, true); assert.deepEqual(paint.uniforms, [{ name: 'amount', min: 0, max: 1, default: 0.35, index: 0 }]); assert.equal(paint.usesUV, false); assert.match(paint.shader.declarations, /fn material_mix/); // WGSL the viewer draws with ``` - **Scenes.** - A scene has exactly one `@scene`, a version, and objects styled by type or id selectors. - It has no classes, inheritance, expressions or scripts. - Anything it doesn't take is refused, with its line and column. Nothing is silently ignored. - **Materials.** An `@shader` material declares its uniforms and a fragment colour, and lowers to the WGSL the viewer draws with. - **Showing a scene.** `showScene(viewer, source, options?)` returns a `SceneView`. If the first source fails to compile, it throws `SceneViewError` with code `SCENE_VIEW` and its `diagnostics`. `view.meshes` maps object IDs to meshes; `view.result` holds the last successful compile result. `view.update(source)` returns `{ ok: true }` after showing a successfully compiled source. A compile failure returns `{ ok: false, diagnostics }` and keeps the previous displayed scene, meshes and `result`. This preservation applies to compile failure; it does not guarantee recovery from every rendering or GPU error. `view.dispose()` removes its meshes and disposes its cached geometry; calling it again does nothing. It does not dispose the viewer. After disposal, `view.update(source)` throws `SceneViewError` with code `SCENE_VIEW` and a `STATE` diagnostic instead of returning `{ ok: false, diagnostics }`. The package README is the language's full reference. ## Errors gpu refuses with its own `BarocssError`, of the same shape as the other packages': a `code`, and a message that starts with it in brackets. gpu imports neither cad package, so the class is its own. Each error class is one of these, and some codes are shared by several classes, so tell refusals apart by `code`. - **The viewer's input** is refused with a `ViewerError`: | Code | What it refuses | |---|---| | `GEOMETRY_INVALID` | Geometry input: positions, indices, topology counts, normals, faces, edges, UVs, labels, colours and their range, scalar fields | | `INSTANCES_INVALID` | Instance transforms or colours of the wrong length, or instancing a mesh that isn't triangles | | `TRANSFORM_INVALID` | A transform that isn't 16 numbers | | `COLOR_MAP_INVALID` | A colour map with fewer than two stops, or stops that don't rise | | `COLOR_INVALID` | A colour that isn't hex, when a frame is drawn | | `MATERIAL_INVALID` | A shader material with more than 16 parameters, when a frame is drawn | | `CLIP_INVALID` | Too many clip planes, or a plane without a normal or a finite offset | | `TEXTURE_INVALID` | A texture without a size, or data that isn't width × height RGBA | | `SIZE_INVALID` | A backing size under 1 × 1 | | `MATRIX_SINGULAR` | Inverting a matrix that has no inverse | When it can't start or draw, it refuses with `WEBGPU_UNAVAILABLE`, `NO_ADAPTER`, `NO_CONTEXT`, `SHADER`, `PIPELINE`, `DEVICE_LOST` or `DISPOSED`. - **The package entry's inputs** are refused with a `GpuInputError`, with the same words as before its code. Where it wraps a check, its cause is that check's own error: | Code | Entry | |---|---| | `SCENE_INVALID` | `parseScene`, `compileScene` | | `MESH_PACKET_INVALID` | `validatePreviewPacket` | | `MESH_OPTIONS_INVALID` | `validateMeshOptions` | | `MESH_INVALID` | `prepareMesh` | | `CAMERA_INVALID` | `validateMeshCamera`, `prepareCamera` | | `FACE_PREVIEW_INVALID` | `prepareKernelFacePreview`, `resolveKernelFaceReference` | | `PRIMITIVE_FRAME_INVALID` | `preparePrimitiveSceneFrame` | | `BOOLEAN_BUFFERS_INVALID` | `prepareCoplanarBooleanBuffers`, `prepareBooleanShellBuffers` | | `GPU_BVH_DEPTH` | A hierarchy too deep for a GPU analysis (`computeExperimental`) | - **Compiling the language** doesn't throw: `compileGpu` and `materialShader` return `{ ok: false, diagnostics }`, each diagnostic with its code and where it is. - **The object facade's** codes are on [Object API](/packages/api#scenes). ## WebGPU and WebGL2 The studio keeps one interface over two renderers: - **WebGPU** is this package's viewer, used when the browser has an adapter. - **WebGL2** is the studio's own renderer (`apps/cad-studio/src/viewport/renderer.ts`): a multisampled scene pass, screen-space ambient occlusion and an id pass for picking. Both draw the model, the display modes, sections, overlays and placed parts. The analysis maps and the mould's halves draw only with WebGPU; on WebGL2 their buttons are disabled and say why. `?renderer=webgl2` forces WebGL2. ## Compute analyses `computeExperimental` runs analyses on the GPU: - **Wall thickness:** for each display triangle, a ray inward from its centre to the next wall. The local thickness is the sphere that fits there. - **3-axis access:** from each sample, a ray along each of ±X, ±Y and ±Z, and whether it leaves the part. Both trace the kernel's triangle hierarchy, packed for WGSL, and each has a CPU mirror. They are for display only: the exact values a report uses stay the CPU's. The namespace may change before its API is stabilized. ## Frame costs With `viewer.costs` on, each mesh counts what the last frame cost it: - its draw calls; - the triangles, lines and points they drew; - its draws by pass: `shadow`, `surface`, `transparent`, `oit`, `hiddenLines`, `caps` and `outlineMask`. These are work counts, not times; a frame's CPU time is in its stats. The studio reads them per body and display mode, but doesn't show them yet. ### Measured The studio's heaviest scenes were measured on both renderers: an orbit per display mode, at 1440 × 900 on an Apple M-series machine in headless Chrome, with other work running. The scenes ranged from a 38-body assembly and a 120-bracket pattern to a 114,000-triangle spring. - **Frame rate.** Every scene held 60 Hz: the frame interval's median was 16.7 ms. - **Headroom.** - The main thread's work stayed under about 4 ms a frame. - On WebGPU, the GPU's time stayed under about 5 ms a submit. That leaves at least three times the 16.7 ms budget. The full tables are in `apps/cad-studio/handover/notes/g11-scene-profile.md`. Times depend on the machine. Only the counts are the same everywhere. How the viewer renders, step by step: [Rendering a model on the GPU](/how/gpu). --- # Studio BaroCSS CAD Studio is the browser application for parametric B-Rep modeling, AI-assisted design, kinematic assemblies, 2D engineering drawings, DFM inspection, and WebGPU rendering. Start with the [60-Second Quickstart](/guide/getting-started) or read the [Tour & 5-Workspace IA](/studio/tour) for shortcuts and layout details. ![BaroCSS CAD Studio viewport with a parametric part and inspector dock](/shots/home/studio.jpg) ## Five task-intent workspaces Studio organizes every CAD task into five focused workspaces in the top bar, paired with a clean 3-panel layout (`Tree` / `Specs` / `Versions` on the left, viewport in the centre, inspector on the right): | Workspace | Purpose | Start here | | --- | --- | --- | | **Design** | Sketch, extrude, fillet, parameters, Quick-Fit sliders & SubD | [Modeling](/studio/modeling) | | **Assemble** | Place parts, mates, interference clearance & kinematic robots | [Assemblies and robots](/studio/assembly-workflows) | | **Draw** | Exact 2D HLR sheets, 6-flyout tools, auto-dimensions & GD&T | [Drawings and manufacturing](/studio/drawing-workflows) | | **Manufacture** | Consolidated `Print`, `Sheet`, `Frame`, `Mould` & `CAM` (Beta) checks, BOM & Shop Rows | [Manufacturing](/studio/manufacturing) | | **Render** | Real-time WebGPU PBR materials, lighting, cameras & turntable stills | [Display and rendering](/studio/display-workflows) | ### Opt-in Domain Packs Specialized vertical toolsets stay out of the way until you enable them in **Domain Packs**: - **Robotics & URDF** — joint trees, gravity holding torques, path sweep checks, and URDF/MJCF/SDF/USD export. - **Structural Frames & Welds** — 3D sketches, structural members, gussets, end caps, and cut lists. - **Mould** — parting line, core/cavity halves, and draft checks (WebGPU). - **SubD** — subdivision cage editing lowered to exact B-splines. - **Developer** — kernel diagnostics, raw `.bcad` inspection, and agent trace tools. ## Companion workflows - **Quick-Fit & Casual Studio:** Tune exposed parameters with live sliders and shareable `?mode=quickfit` URLs — see [Quick-Fit & Casual Studio](/studio/quick-fit). - **BaroCSS Review:** Share read-only `.bcad` models, Before/After 3D diffs, and 2D HLR drawings with reviewers — see [BaroCSS Review](/studio/review). - **AI Copilot & Variant Explorer:** Prompt directly on 3D faces with `⌘K` Spatial Pin or compare parallel worker variants — see [AI Copilot](/agent/) and [Generative Variant Explorer](/agent/variants). - **Files, versions & branches:** Keep immutable snapshots, compare 3D diffs, and resolve branch merges — see [Files and projects](/studio/file-workflows). ## Deterministic editing & Design Health Every command previews before mutating the document. The **Design Health** indicator in the top bar surfaces broken features or failed requirements immediately, and clicking an issue highlights the exact 3D entity with 1-click deterministic or AI-assisted repair. Mass properties calculate asynchronously after fast display-mesh updates; the inspector shows `…` until exact B-Rep integration finishes (never `0` or stale numbers). For complete capability boundaries and typed refusal guarantees, see [Verification](/reference/verification) and [Limits](/reference/limits). ## For developers Building your own 3D web configurator, CAD pipeline, or AI agent integration? Explore the modular TypeScript libraries, React viewport components, headless CLI, and MCP server in [SDK & API](/packages/cad/) and [Embedding & Self-Hosting](/guide/embedding). --- # Tour of the studio ## 5-Workspace IA and 3-panel layout ![The Studio workspace layout showing the viewport, tool rail, feature history bar, and right inspector dock](/shots/studio/tour/layout.jpg) Studio uses a focused **3-panel layout** built around five task-intent workspaces: - **Top bar:** - **Workspace switcher:** **Design**, **Assemble**, **Draw**, **Manufacture** (`Print`, `Sheet`, `Frame`, `Mould`, `CAM`), and **Render**. - **Design Health Pill:** Live status badge showing geometry validity and requirement checks; click any error to highlight the failing 3D face/edge and run 1-click deterministic or AI repair. - **Document & Export menu:** **New part**, **Templates**, **Open**, **Save**, **Undo**/**Redo**, **Quick-Fit** toggle, and a consolidated **Export** menu (STEP, IGES, STL, 3MF, URDF/MJCF/SDF/USD). - **Domain Packs:** Toggle specialized command groups (**Robotics & URDF**, **Structural Frames & Welds**, **Mould**, **SubD**, **Developer**) on demand without cluttering the core toolbar. - **Left panel (3 collapsible tabs):** - **Tree:** Bodies, placed assembly instances, drafts, reference geometry, and feature hierarchy. - **Specs:** Parameters, configurations, design brief, hard/soft requirements, and Shop Rows. - **Versions:** Local/project snapshots, branches, 3D visual diff comparisons, and merge tools. - **Chat & AI Copilot:** Opens as a resizable side column (320–520 px) with provider switcher, autonomy selector (`L1`–`L4`), and proposal history. - **Centre viewport & overlays:** - **Tools rail:** Context-aware modeling or sketch tools along the left edge of the canvas. - **Floating parameter sliders:** Quick numeric scrubbing right over the viewport. - **⌘K 3D Spatial Pin & Floating Proposal Bar:** Inline face/edge AI prompts and instant **Preview** / **Accept** / **Reject** controls without leaving the 3D stage. - **Heads-up display (HUD):** Live numeric inputs and `preview` / `refused` status for the active command. - **Feature history & view bar:** Chronological feature strip at the bottom plus **Display**, standard camera views (**Iso**, **Top**, **Front**, **Right**), **Ortho**, **AO**, **Analyse**, **Maps**, selection filters, and **Snap**. - **Right inspector dock:** - Context-sensitive geometry inspector (`SELECTION · FACE`, `SELECTION · EDGE`, or overall part mass, centre of mass, and bounding box). - Mass and volume display `…` while B-Rep integration runs asynchronously, never `0` or stale values. - Hosts active command parameters, measurement tools, joints, mates, and **Preview & analysis** panels. ## Commands and keys Press Space to open the command palette, ⌘K (`Ctrl+K`) for the 3D Spatial Pin inline AI prompt, or ? to view all shortcuts. ![The command palette, searching for fillet](/shots/studio/tour/palette.png) | Key | Command | Key | Command | |---|---|---|---| | S | Sketch | E | Extrude | | B | Box | Y | Cylinder | | H | Hole | C | Chamfer | | Shift F | Fillet | P | Linear pattern | | M | Mirror | A | Align | | G | Move | R | Rotate | | U / D / I | Union / Subtract / Intersect | Shift M | Measure | While a command is active: - Enter commits the preview. - Shift Enter commits and repeats the same command. - Esc cancels the command, or clears selection when idle. General shortcuts: | Key | Action | |---|---| | ⌘ K | Open 3D Spatial Pin inline AI prompt on selected entity | | ⌘ Z / ⇧ ⌘ Z | Undo / redo | | ⌘ S | Save document | | ⌘ D | Duplicate body | | ⌘ C / ⌘ V | Copy / paste body | | Del | Delete selection | | Arrow keys / PgUp / PgDn | Nudge picked body 1 mm (Shift: 10 mm) in X/Y or Z | | F | Fit camera to selection or entire model | | Shift R | Repeat last command | | Ctrl B | Print Face — orient selected planar face flat onto the 3D print bed | ## Picking and navigation | Mouse | Action | |---|---| | Click | Pick face or edge | | Shift-click | Add to selection | | Drag | Window select (left-to-right: enclosed; right-to-left: crossing) | | Double-click face | Select entire body | | Double-click edge | Select tangent edge chain | | Double-click name | Rename body | | Right-click | Open contextual actions | | Right-drag or Alt-drag | Orbit (or customizable right-drag Mouse Gesture Ring when enabled) | | Middle-drag, Space-drag, or Shift-right-drag | Pan | | Wheel | Zoom | Power-user navigation, selection, and quick inspection controls: - CAD navigation presets, Free Orbit, cursor-centered pivot, and Space-bar panning can be configured in Studio navigation preferences. - Selection tools include Select Other (cycle occluded faces/edges under the pointer), Freehand Lasso, and Select Sharp Edges. - Selecting two entities or an edge/face displays a live Quick Measurement readout directly in the viewport status bar (distance, radius, diameter, length, or angle). ## WebGPU and WebGL2 The viewport uses WebGPU automatically when available and falls back cleanly to WebGL2 (force via `?renderer=webgl2`). Both backends render all 5 display modes, sections, overlays, and assemblies. WebGPU unlocks GPU compute analysis maps (wall thickness, draft, 3-axis access, mould parting/halves) and the **Render** workspace. --- # Quick-Fit and Casual Studio Not every hardware change requires opening a full feature tree or sketch solver. BaroCSS CAD provides two streamlined paths for fitting an existing parametric design to new dimensions: **Quick-Fit** inside Studio and the lightweight **Casual Studio** workspace. ## Quick-Fit mode inside Studio Quick-Fit switches Studio into a distraction-free parameter configurator powered by background workers. Teammates, fabricators, or customers can open a shareable link, scrub exposed numeric sliders, inspect updated mass and bounds, and download STEP, STL, 3MF, or `.bcad` immediately. ### Built-in hardware presets | Preset | Name | Exposed fit workflow | | --- | --- | --- | | `enclosure` | **Sensor Enclosure** | Fit board width, depth, height, and wall thickness | | `nema17` | **NEMA-17 Bracket** | Fit plate dimensions, pilot bore, and M3 mounting pattern | | `adapter` | **Cable Guide Adapter** | Fit dual mount holes and plate thickness | ### Shareable preset links Quick-Fit share links work with built-in named presets (`enclosure`, `nema17`, `adapter`). Shared links carry the preset and exact numeric parameter overrides so a customized part can be bookmarked or sent to a teammate without rounding drift: ```text ?mode=quickfit&preset=nema17&p.plate_width=72&p.thickness=8 ``` When you open Quick-Fit from an existing part in Studio (**Current part**) or from a local `.bcad` file, Studio keeps your local history private rather than encoding it in the URL. Export a native `.bcad` copy or **STEP** / **3MF** / **STL** from the Quick-Fit sidebar to hand off custom parts. Click **Open Studio** at any time to transition into the full [5-Workspace Studio](/studio/tour) with the complete parametric feature history intact. ## Casual Studio For lightweight, guided parametric customization outside full Studio, Casual Studio offers two focused entry points: - **Start from an example:** Pick a parametric template, click a hole or feature directly on the canvas, adjust its exposed dimension, preview before/after changes, and export. - **Create from a recipe:** Write a short declarative parametric recipe with live validation and two-way canvas synchronization. Exported `.bcad` files open directly in full CAD Studio with native parametric features. --- # BaroCSS Review **BaroCSS Review** is the standalone read-only review application for inspecting CAD designs and approval bundles in any browser. Share `.bcad` documents so teammates, mechanical leads, and manufacturing partners can review geometry, compare proposals, and verify specifications without altering source files. ## Try BaroCSS Review Launch the live interactive sample below or open BaroCSS Review in a dedicated tab: On browsers without WebGPU (such as Firefox, Safari, or remote workstations), BaroCSS Review automatically renders an interactive 2D hidden-line projection (`Iso`, `Front`, `Top`, `Right`, and `4-View`) so proposal diffs, specification checks, and Quick-Fit previews stay fully functional. ## What reviewers can inspect - **3D & 2D geometry viewport:** Orbit, section, measure point-to-point distances, toggle visibility, and inspect multi-body `.bcad` documents, STEP/IGES assemblies, and saved review views. - **Proposal Before/After Diff Inspector:** Toggle between baseline and proposed geometry, inspect exact volume, mass, and bounding-box deltas, review omitted features, and verify revision provenance. - **Interactive 2D Engineering Drawing Panel:** Inspect exact hidden-line-removed orthographic drawings alongside the 3D view. Clicking projected edges or faces cross-highlights matching geometry in the inspector. - **Approval Evidence & Requirements:** Review live pass/fail engineering checks, design requirements, and manufacturing notes attached to the bundle. - **Non-mutating Quick-Fit preview:** Test parameter adjustments interactively in read-only mode to verify clearances or fit before requesting edits. - **Open in Studio handoff:** Jump straight into [CAD Studio](/studio/) with the reviewed `.bcad` document whenever design edits are needed. ## For developers Want to embed BaroCSS Review inside an internal portal or build a custom review UI? See [Embedding & Self-Hosting](/guide/embedding) and the [Embeddable React SDK](/packages/cad-react/sdk). --- # Modeling workflow Use this guide to choose the next modeling step. The detailed pages explain each tool and its supported inputs. ## Goal Build an editable part from a profile and solid features. Use parameters for shared sizes. Use a frame when the design needs separate structural members. ## Inputs - A sketch plane and a profile for the intended feature. - Sizes for the feature, and named parameters if sizes must change together. - For a frame, a skeleton and a typed section or section rows from your own file. ## Example: one plate with a through hole Use the Box route for this example from [Getting started](/guide/getting-started#a-first-part). The later sections explain sketch-based features and frames as other construction choices. 1. Choose New part, then press B for Box. Set Width X to 64, Depth Y to 32 and Height Z to 8 mm. Keep At X, At Y and At Z at 0, then press Enter. 2. Choose Top in the view buttons, then click the plate's top face. 3. Press H. Set Type to Through and Diameter to 8 mm. Set Centre X to 32 and Centre Y to 16 mm. Wait for the HUD to say preview, then press Enter. 4. Open Parameters. Enter the name `T` and value `8`, then choose Add. 5. Open the box feature in the history. Select `T` from the Distance field's ƒ list, then choose Apply. This binds the plate thickness to `T`; inspect the accepted result. 6. Choose Save to keep the editable `.bcad` document. With a project open, it is saved in that project. Otherwise, the browser downloads it. See [Files and exports](/studio/files#the-bcad-document). ![Existing Getting started image: the top-face hole preview and its input fields](/shots/guide/getting-started/hole-preview.jpg) This image is reused from Getting started. It is not a new run of these parameter and save steps. For the initial dimensions, the ideal box volume is `64 × 32 × 8 = 16,384 mm³`. A straight Ø8 through hole removes `π × 4² × 8 = 128π mm³`. The ideal remaining volume is about `15,981.876 mm³`. These are calculations from dimensions, not API results or measurements from a new Studio run. ## Work sequence ### 1. Draw and finish a profile Choose Sketch. With nothing selected, the sketch starts on XY. Select a flat face first to sketch on that face. Draw the profile, then add the required dimensions and constraints. Read the remaining freedom in the sketch panel. Fully defined means the sketch has no freedom left. Choose Finish sketch when the profile is ready. ![Existing Studio image: a dimensioned rectangle and its sketch constraints](/shots/studio/sketches/rectangle.jpg) This image is reused from the sketch guide. It is not a new result from this workflow. ### 2. Make a solid feature Choose Extrude for a profile pulled along its normal. For a sketch attached to a body face, use **Operation** to choose **Join to body**, **New body** or **Cut from body**. An independent rectangular XY sketch starts as a new body. For a positive distance with zero draft, Studio offers **Join to** with the body name when the part has one visible upright solid and the two solids overlap in volume. Choose that target to merge the bodies. Contact at a face or edge leaves the bodies separate. Revolve turns a profile about an axis. Sweep follows a path. Loft connects profiles. Use the feature history to edit a feature; the features after it rebuild. See [Part features](/studio/features#from-a-sketch) before choosing another construction method. ### 3. Bind sizes that must change together Open Parameters and add a named, finite value. In a feature editor, choose a supported field's parameter from its ƒ list, then Apply. The field follows that parameter while it is bound. When editing an existing parameter, submit its value with Enter or by leaving its field. Typing alone changes the draft. Numeric fields in the HUD and feature editors also evaluate inline math expressions (for example `48 / 2`, `plate_width - 12`, or `wall * 2`) and offer a HUD parameter picker for direct binding. In the viewport, single-click a command handle value box to type an exact dimension directly on the 3D gizmo, and check the mass summary for any excluded or unavailable bodies before signing off on mass properties. Precision placement tools include arbitrary-normal face align (with in-plane spin and gap), point/edge snap move, normal-aligned place-on-face / drag-on-surface attachment, multi-body align (min/center/max) and distribute (X/Y/Z), center between two faces, multi-target snap copy, smart selection, and collision-aware contact stop during gizmo dragging. Named driven dimensions measure exact native edge curve lengths and stay readable across feature edits, and auto-finish sketch lets you jump straight from a closed profile into a solid command. Check the accepted result. A refused change keeps the accepted parameters, part and references. Use Configurations to save and apply sets of parameter values. A configuration does not change suppression or replace assembly components. ### 4. Choose a frame for structural members A frame is a different construction: each member is a separate body along a skeleton. Use Frame for a skeleton with shared sections. Use Structural member for one member. Choose the section and joint treatment, then inspect the member ends. Picked edges copies straight edge endpoints; it does not make a live link to those edges. Use Skeletons when the frame's 3D sketch needs constraints or parameter bindings. ## Check the result - Confirm the profile and plane before making the feature. - Inspect the resulting bodies and the feature history after an edit. - Check which fields follow each parameter and which values remain accepted. - For a frame, inspect the members and use Cut list for lengths, end cuts and quantities. A sketch defines a flat profile. A solid feature uses geometry to build or change a body. A parameter supplies a named value. A frame builds members along a skeleton. Choose these by their role; a frame is not an assembly of inserted part files. ## Refusals and support Overlapping sketch shapes are refused. A closed shape inside a hole needs a separate sketch. Invalid parameter names, duplicate names and non-finite values are refused. Only fields that can store one direct parameter reference offer a binding. Frame Picked edges requires straight edges. Its copied skeleton does not follow later edge edits. Section rows come from your files; prefilled section radii are estimates. Read the detailed refusal before changing the input. Do not treat an unsuccessful rebuild as an accepted part. ## Related details - [Sketches](/studio/sketches): planes, drawing tools, constraints and profile limits. - [Part features](/studio/features): solid operations and feature history. - [Parameters and configurations](/studio/parameters): bindings and accepted values. - [Frames and weldments](/studio/frames): sections, skeletons, joints and cut lists. --- # Sketches A sketch is a flat profile on a plane. Features such as extrude, revolve and sweep are made from it. ## Start a sketch Press S (**Sketch**). - With nothing picked, the sketch lies on the XY plane. - With a flat face picked, it lies on that face; the sketch panel says so, for example `SKETCH · Y 0 · on face`. - In the sketch panel, **Plane offset** lifts the plane along its normal (`SKETCH · Z 5`) and **Plane angle** tips it about its X axis (`SKETCH · 30° tilted plane`). The shapes keep their coordinates on the plane. Finish the sketch with Enter or **Finish sketch** in the top bar. ## Drawing tools ![A rectangle drawn in a sketch on XY: its two dimensions, its constraints and "Fully defined" in the sketch panel](/shots/studio/sketches/rectangle.jpg) | Key | Tool | How | |---|---|---| | R | Rectangle | Click two corners | | C | Circle | Click the centre, then the radius | | L | Line | Click points; click the first point to close. A switches to arcs | | A | Arc | Click the arc's end, move to bend it, click to place. L goes back to lines | | Q | Centre arc | Click the centre, then the start (the radius), then turn to the end and click | | I | Ellipse | Click the centre, the end of the first axis, then a point that sets the other semi-axis; it is kept as tangent arcs and keeps its definition | | O | Slot | Click both centres, then the width | | P | Spline | Click points the curve runs smoothly through; it is kept as tangent arcs and keeps its fit points | | B | Bézier | Click control points: three make a quadratic, a fourth a cubic; the curve does not pass through the middle points | | T | Trim | Click a piece to cut it back to where it crosses others | | E | Extend | Click near an open end to run it on to the next piece it meets | | K | Split | Click a line, arc or circle to split it in two there | | S | Select | Click points and edges (Shift adds), then constrain them in the panel | | D | Dimension | Click an edge, an arc or two points, type the value, Enter. Double-click a dimension to edit it | X toggles construction geometry, which guides the sketch but doesn't become part of the profile. A tool's key still works while a number box has focus; it leaves the box. A shape drawn inside another becomes a hole in it, so a rectangle with a circle inside extrudes as a plate with a bore. Shapes that overlap are refused. A spline keeps its fit points. After closing it (or reopening the sketch), the **SPLINE** section lists each fit point's X and Y and its handle: the curve's direction there, in degrees. Type a value and press Enter (or leave the box) to apply it; leave a handle empty for the automatic direction. A handle or point that leaves no arc pair the model can build to the next point is refused. On a closed spline with **Select**, drag a handle end to turn its tangent (whole degrees, Shift for 0.1°) or a fit point to move it (grid step, 1 mm by default; Shift for 0.01 mm). The drag starts after the pointer moves 3 px, so a plain click still picks. Releasing applies it as one step (none if nothing changed), Escape cancels, and a position with no buildable arc pair keeps the last valid one. The arc radius chips are hidden on a closed spline so they do not cover its handles; lock a radius in the panel grid instead. A spline is driven only by its fit points and handles: a dimension or relation on it, or an edit of its outline points, turns it into an ordinary outline. An ellipse is drawn with three clicks: the centre, the end of the first axis (which sets **Rx** and the angle), and any point whose distance from that axis line sets **Ry**. A dashed circle and then the ellipse follow the pointer; Escape drops the draft. The **ELLIPSE** section then lists **Centre X**, **Centre Y**, **Rx**, **Ry** (semi-axes in mm) and **Angle** (the Rx axis, degrees anticlockwise from +X); type a value and press Enter (or leave the box) to apply it, and a value the model cannot build shows the reason and changes nothing. The profile is a closed outline of 192 tangent arcs through 96 points of the true ellipse, so it extrudes, cuts and keeps its side names whatever you edit; it stays within 1e-5 of the longer semi-axis of the true ellipse (0.0005 mm at Rx 50), and its area is within 1e-5 of π·Rx·Ry. An ellipse narrower than 1 : 5 is refused (draw a slot or a spline instead), as is one whose points or arc centres leave ±10000 mm or whose arcs are under 0.01 mm radius (a large, narrow ellipse has far arc centres: 5000 × 1000 mm is refused, 5000 × 4000 mm is fine). Make curves turns it into the exact ellipse: one degree-2 rational curve (the circle's four quarter spans mapped by the ellipse's axes), not the outline's arcs. The outline's radius labels, joints and arc pairs are not listed while it is an ellipse (the Constraints list shows one "Ellipse · 192 tangent arcs" row), and a dimension on it is refused (the solver takes 64 segments); moving one of its outline points, or rounding a corner, turns it into an ordinary outline of 192 arcs, which Make curves refuses. The angle is stored between 0° and 360° (−90° becomes 270°), and an angle that is not a usable number is refused. The definition is kept only when the ellipse is the sketch's main shape: as a hole or an extra region it becomes a plain 192-arc outline when you finish the sketch, and Make curves then refuses it. Fillets and chamfers on an ellipse's side edges (the edges of the faces made from a kept ellipse outline) are refused with a reason, because each of the 192 arcs is a face and the rounding would take minutes: fillet a circle or a slot instead, or make the shape from the exact curve with Make curves. The edges of other faces of the same body, and of an ellipse hole (a plain arc outline after Finish), are not refused. This covers extrudes, revolves and sweeps of the ellipse. A document made before this limit, with a fillet or chamfer on an ellipse's side edges, still opens and evaluates, slowly (minutes per such fillet). A Bézier curve is drawn from its control points: the dashed control polygon joins them and the solid curve runs from the first to the last, leaving along the first leg and arriving along the last. It does not pass through the middle points. The third click makes a quadratic; a fourth makes it cubic and ends it. A click on the previous point is ignored, and poles that make no curve (all on one point, or both ends on one point with every pole on a line) are refused with the reason. While it is the current shape the **BÉZIER** section lists each **Control point** X and Y; type a value and press Enter (or leave the box) to apply it. An edit that would leave no curve shows the reason and changes nothing. What holds for a Bézier curve: - It is kept with the sketch and comes back when an ordinary (non-linked) sketch is reopened. Once another shape is drawn, or after a reopen, it is shown but is no longer the editable current shape: its control points are not listed in the panel. - It is never part of the profile, so it never needs to close; **Finish sketch** still needs a closed profile. - It is not a trim, split or extend boundary, and is not offset or constrained. - It is always a Bézier curve: the Construction mode does not make it a construction line. - It is not written to a DXF export. - **Make curves of the sketch** turns it into one polynomial curve, exact up to the 1e-9 mm decimal form of the curve source, which a Loft can copy as its **Guide** (a single quadratic or cubic span keeps the two-frame path). Degenerate curves, and coordinates beyond 1e6 mm, are refused with a message. A closed shape inside a hole is not supported in the same sketch. **Finish sketch** refuses it; draw that shape in a separate sketch. ## Fillet and chamfer sketch corners {#chamfer-a-sketch-corner} With **Select**, pick a corner on an independent closed outline. Choose **Fillet** for a tangent arc or **Chamfer** for a straight bevel. Set the radius or distance in mm. Check the preview and choose **Apply**. Use Shift to add corners or select a chain of straight sides. A pair of selected sides targets the vertex where they meet. The preview marks every target. Each corner follows the local turn of the outline, including convex and reflex corners in the same selection. One **Apply** changes the whole group and one **Undo** restores the previous outline. If the edits would consume a shared side, overlap or remove a protected constraint or parameter binding, the outline stays intact. After **Finish sketch**, the edited corners and retained side IDs reopen with the native document. ## Reusing a face and offsetting a shape When the sketch is on a selected face with zero plane offset and angle, the **FACE** section offers two copy actions: - **Use its outline** adds the face's outer boundary and holes as sketch shapes. - **As references** adds those edges as construction shapes. You can snap to them, but they do not form the profile. These actions and older outline sketches remain copies; they do not follow later face edits automatically. For an empty face sketch at zero plane offset and angle, choose **Link face outline + inset**. Use a finite positive **Offset distance** in mm; this creates one inward inset, regardless of **In**/**Out**. Choose one named planar face of an earlier single exact solid in the same document, with one straight outer loop and no holes. The linked source defines the profile; the sketch's default Join/Cut body target is stored separately. Source edits regenerate the outline and inset. Missing or ambiguous sources/faces, curved boundaries and collapsed insets are refused. Geometry or plane edits detach the link. Reopening or cancelling an edit keeps the stored link. The link does not support placed parts, assemblies, automatic rematching of duplicated sources or frames following the sketch. To draw a wall, close a shape and enter **Offset distance** in mm in the **OFFSET** section. Choose **Out** for an outward copy or **In** for an inward copy. The direction button determines the side; the distance supplies its magnitude. The current closed shape is used first; otherwise, the newest finished, non-construction closed shape is used. The original stays, and the region between the nested outlines forms the profile. With no closed shape, the studio reports **Nothing to offset**. An offset that collapses a shape or reverses an outline edge is refused as **Cannot offset**; reduce the distance. A refusal leaves the sketch as it was. ## Bands A **band** is the closed outline that wraps two or more convex shapes, such as a belt round pulleys. Draw the shapes (rectangles, circles, slots and convex outlines), pick them with the **Band** tool, set the optional **Offset** (mm, the band stands off the shapes by that much) and **Width** (mm, empty makes a filled band; a width makes a strip), and press **Make band**. The picked shapes become construction shapes, the band's sources. The outline is exact: arcs of the sources joined by common outer tangents. The band is regenerated from its sources wherever the sketch is used. Move a source, change a source's radius or centre (in the sketch or as a feature value of the Extrude), or bind a value to a parameter, and the body follows. Its walls keep their names while the shape of the outline stays the same (a source that wins twice names its second piece by the source before it, for example `b1_e1-e2`, so the names do not swap when the sources move round). A band sketch holds only the band and its construction sources: draw other shapes in their own sketch. A band that cannot be made is refused by name (for example **Sketch 1 band b1: sources e1 and e2 overlap**: sources that overlap, touch, lie inside one another or are not convex) and the sketch's body is not kept as it was. A band is not available to the agent, and not in a linked sketch. ## Constraints and dimensions Pick points or edges with **Select**, then add a constraint from the panel: **Horizontal**, **Vertical**, **Parallel**, **Perpendicular**, **Equal**, **Coincident**, **Tangent**, **Symmetric** or **Fix**. The **Dimension** tool adds lengths, distances, radii and angles. With **Select** or **Dimension**, drag a straight driving length label toward or away from its edge. The dimension line follows the label. The endpoints and the length stay fixed. Press Escape during a drag to cancel it. Use the reset control beside a moved label to restore its automatic position. A new sketch editing session starts with automatic positions. Double-click the number when you want to edit the length. The status line counts what is still free, for example `2 DOF`, until the sketch reads **Fully defined**. A constraint the others already imply is refused, and the message says why: for example, `Vertical edge 4 is already implied by the other constraints — adding it would over-define the sketch`. A contradiction can be refused as a proven **Conflict** when the sketch has only horizontal and vertical straight edges, their lengths, axis distances (dx/dy) and fixed points (point 1 is fixed at its drawn position) — no arcs, circles or other rules anywhere in the sketch — the values are more than a few 10⁻⁷ mm from consistent, and the exact search finishes within its budget. Typed lengths stay locked while the solver moves the rest. Otherwise a refusal that does not converge says so without claiming a conflict: failure to converge does not prove one. A refused constraint edit keeps the previous outline. A successful solve keeps its accepted point coordinates without decimal rounding. Some constraints are inferred as you draw: an arc that meets a line smoothly is tangent to it, and a radius you lock keeps it so. ## Using the sketch After you finish a sketch, the profile feeds a feature: - E **Extrude** pulls the profile into a solid. When the part already has a body, **Operation** chooses **Join to body**, **New body** or **Cut from body**, and a cut's **Depth** is a **Distance** or **Through all**. - **Revolve**, **Sweep** and **Loft** are in the command palette (Space). Revolve turns a profile about an axis, sweep runs it along a path, and loft blends from one profile to another. A profile may run along the Revolve axis on whole straight segments; zero-length edges remain invalid. It must not cross the axis or touch it inside an arc; a full turn must not pinch to a point between two walls. A sketch you finished can be reopened from the feature editor, with its constraints. Changes are written back in place, and the features made from it update. A reopened sketch keeps its main profile: a circle stays the main profile even when you edit or dimension a rectangle beside it, or the circle itself. Reopening a sketch whose values are bound shows each at its parameter's current value. Finishing keeps each binding whose value you left as it was. A rectangle's or circle's bound value stays bound when you change its other sizes (changing the height keeps a bound width), and becomes a plain number only when you change that value itself. In an outline of points, a binding stays only while the outline's other points are unchanged: move a corner, add or remove points or swap the main shape and the bindings in that outline become plain numbers. Finish says which. A driving dimension edited from the feature editor follows the same rule, without a notice. If the sketch uses a parameter the document no longer has, or one with no finite value, it won't reopen and says which one. Driving dimensions and geometric constraints are qualified beyond bounded XY profiles across offset, tilted, and face-attached sketch planes as well as mixed line-arc profiles. Dimension fields accept linear and arithmetic parameter expressions, surface structured solver diagnostics when constraints over-constrain or conflict, and block Apply whenever a HUD formula draft is invalid or uncommitted. Additional parametric sketch tools: - Auto-scale on first dimension proportionally scales an unconstrained sketch to match the first dimension you enter so the profile keeps its intended shape. - Equation Curve generates parametric sketch curves directly from mathematical expressions, verified against dense formula samples to prevent periodic aliasing. - Explode Text converts sketch text outlines into editable sketch curves for direct extrude, cut, or constraint operations. --- # Part features Every command adds a feature to the part's history. Each feature is kept as data — its kind, its values and what it is built on — so the part can be edited and rebuilt. Start a command from its key, from the shapes in the top bar, from the **Tools** rail or from the command palette (Space). While the part is computing, wait or use **Cancel** before making another document change. The app refuses that change before adding it to history. Camera and workspace controls remain available. Cancel takes back only the accepted change that started the computation. If the computation has no accepted change to take back, the document stays unchanged and the view remains out of date until recomputed. ## Shapes **Box**, **Cylinder**, **Sphere**, **Cone**, **Torus**, **Tube**, **Wedge** and **Polygon prism** make a body from their sizes. The HUD shows the fields, and the viewport shows handles you can drag. ## Text **Text** creates an independent solid from an original static `.ttf` file. Enter **Text**, load **Font file**, then set **Em size**, positive **Height**, **Curve tolerance** and **Tracking**. Preview the result and choose **Apply**. Em size is the font em height, not its visible letter height. One history feature/output can contain separate physical bodies, such as letters, dots and Korean components. Edit the Text feature in history to change the original string or dimensions. Bound dimensions stay bound; change their numbers in **Parameters**. Undo/Redo and `.bcad` Save/Open keep the recipe and original font bytes, so reopened text remains editable. Font-bearing templates are currently refused; use a `.bcad` file. The selected Latin and precomposed Korean examples use outline data, not browser-rendered glyphs. Shaping, kerning, bidi, Unicode normalization and text wrapping are not implemented. The separate bounded **Text relief** modifier below embosses or engraves a supported top face. Missing glyphs and unsupported font/profile cases are refused. See [Text from font outlines](/how/text) for the admitted range. ### Text relief Pick one flat, uniquely named top face facing +Z and choose **Text relief**. Set the original font and text, **Em size**, positive **Depth**, **Curve tolerance**, **Tracking**, **Baseline X** and **Baseline Y** and **Operation**: **Emboss** or **Engrave**. Baseline X/Y are world XY coordinates in the part. Preview the candidate, then **Apply** or **Cancel**. The source must be one physical solid with one straight-sided native upright slab. Every stroke must fit in the actual material and selected face, clear of outer edges and holes by the required margin. Components that overlap or touch are refused. Engrave must leave a bottom web; both operations keep one physical solid. The source top is derived again after an ordinary height edit, rather than stored as an absolute Z coordinate. Edit the relief in history to change its original recipe. Change bound dimension numbers in **Parameters**. Font source, selected face/signature and dimensions use the existing Undo/Redo and `.bcad` paths. A smaller curve tolerance can exceed the fixed work budget and be refused. It is never automatically increased. Curved, tilted or side-face relief and text wrap remain unsupported. See [Text relief](/how/text#emboss-or-engrave-a-top-face). ### Profile relief Pick one flat, uniquely named top face facing +Z and choose **Profile relief**. Choose **Profile sketch** (1–64 closed line-only sketches), set positive **Depth**, optional **Edge clearance** (or **Clearance** when editing in history) and **Operation**: **Emboss** or **Engrave**. Preview, then choose **Apply** or **Cancel**. Like text relief, the source must be one physical solid with a straight-sided native upright slab, and every stroke must fit inside the selected face with positive web thickness remaining under cuts. ## From a sketch | Command | What it makes | |---|---| | **Extrude** (E) | Pulls a flat face or a finished sketch along its normal: join, a new body, or a cut to a distance or through all | | **Thin extrude** | Pulls a constant-thickness wall from an open curve (line, arc, polyline, spline) or closed outer loop, with side, end-cap, extent (`blind`, `symmetric`, `two-sided`, `to-object`), draft and boolean options | | **Revolve** | Turns a finished sketch about an axis: a sketch axis or a straight edge you click | | **Sweep** | Carries a finished sketch along a curve, square to it as it goes | | **Pipe** | Carries a finished sketch along a run, a bend and a run | | **Loft** | A solid through two or more sketches on parallel planes (Shift-click to pick them) | ### Thin extrude **Thin extrude** creates constant-thickness walls from either open sketch chains (lines, circular arcs, polylines, splines, or direct NURBS curves) or closed outer sketch loops without holes. Set positive **Thickness** (`wallThickness`), **Side** (**One side**, **Other side**, or **Symmetric**), open **End cap** (**Miter**, **Round**, or **Square**), **Extent** (**Distance**, **Symmetric**, **Two sides**, or **To object**), optional **Start offset** and **Draft** angles, and **Operation** (**New body**, **Join**, **Cut**, or **Intersect**). An open chain stays open without closing back onto its start point, and existing `thin` mode on `extrude` follows the same offset and validation rules. In **Loft**, **Guide (copied)** selects one polynomial direct curve. A general B-spline guide (degree 1–5) takes 2–8 ruled sections on parallel planes and must pass through a vertex of each section. The guide is copied; later curve edits do not update the loft. A single quadratic or cubic Bézier span keeps the two-frame path. A section sketch with parameter-bound sizes is copied at the parameters' values then (the Sizes step lists them, as "Copied at W = 40"): later parameter changes do not update the loft. See [Lofts and guides](/how/loft-sweep#one-polynomial-guide-on-height-sections) for the input rules and limits. For two axis-aligned rectangular sections facing +Z, select **Guide (copied)** and **Second guide (copied)**. Choose two quadratic Bézier curves that go from the lower section to the upper section. For the first guide, use the minimum X corner of each section. For the second guide, use the maximum X corner. All four corners must be at minimum Y. Put both middle controls halfway between the sections in Z. Put the second guide's middle control to the right of the first. The two rectangles can have different widths and depths. The depth-to-width ratio changes linearly with height. Edit the middle X and Y in Loft History to change the shape between the sections. ## Route bundles **Route bundle** ties one interior control point on each of two direct curves. Both selected points move by the same world XYZ displacement; the other control points and curve endpoints stay fixed. It does not translate the whole curves or solve general mates or free-form curve constraints. ![Two selected curve control points move by the same displacement while endpoints stay fixed](/diagrams/route-bundle-poles.svg) The diagram uses two unit-weight cubic curves in the world XY plane. Both selected points move by `[8, 5, 0]` mm. [Open the coordinate diagram at full size](/diagrams/route-bundle-poles.svg). Prepare two distinct open, clamped cubic curves in millimetres. Each needs its own matching copied **Sweep** and an independent, positive circular sketch in the default XY plane, without holes or extra regions. Placed or associative profiles and placed or trimmed curve objects are outside this tool's scope. 1. Select the two direct curves and choose **Route bundle**. If a bundle already exists, open the same tool and choose it under **Active bundle**. The tool requires an up-to-date document and no other active edit. 2. For a new bundle, enter **Bundle name**. For each member, choose **Curve**, **Control point** and **Copied sweep**. The control point must be interior; use different curves, sweeps and profiles for the two members. Enter finite world XYZ coordinates in **Tie anchor**, in mm, then choose **Create**. This prepares a draft preview. Wait for **Preview ready. Apply to keep this edit.**, then choose **Apply** to create the bundle. 3. For the accepted bundle, enter **Total translation** in mm and choose **Preview**. Values are measured from the start of this edit, not added to the previous preview. The app prepares a preview and then evaluates the complete candidate document. Wait for **Preview ready. Apply to keep this edit.**, then choose **Apply** to keep the candidate. 4. Choose **Cancel**, press **Escape**, or close the panel to discard the uncommitted edit. An error clears the candidate display and keeps the accepted document. If the document, bindings or draft changes, preview the current draft again; an old evaluation reply cannot make it ready to apply. **Detach** prepares removal of the link while keeping the current curves and copied sweeps. It also needs a successful check and **Apply**. Reopening a bundle starts a new edit from its accepted state. The source curve primitives come from the document's direct CAD geometry. They are not complete Studio model documents. The route helpers create private Studio document candidates; the app owns full-document evaluation and commit. A valid binding alone does not establish that every resulting sweep can be evaluated. For the public helpers, see [Route bundles in code](/packages/cad-model/#route-bundles-in-code). ## Holes ![Hole with Copies set to On a circle: four holes previewed round the plate's centre](/shots/studio/features/holes-on-a-circle.jpg) **Hole** (H) cuts a round hole into a flat face: through, to a depth, counterbored, countersunk or tapped. Place it by its centre, or by dimensions from an outline's corner, an edge or another hole. **Copies** makes them **In a row** or **On a circle**, with a **Count**. On a circle, the first hole must sit away from the circle's centre, since the copies turn round it. A tapped hole and a **Fastener** (a bolt, cap screw, nut or washer fitted to a hole's rim) take their sizes from the fastener sizes you have loaded; without them they are refused with `[FASTENER_SIZE_ROW]`. See [Shop rows](/studio/rows). ## Modify | Command | What it does | |---|---| | **Fillet** (Shift F) | One entry with Edge, Face and Full round types | | **Chamfer** (C) | Bevel the picked edges; a picked face takes all its edges | | **Shell** | Hollows a body, leaving the picked faces open | | **Draft** | Tapers the picked side faces for a pull along Z | | **Offset face** | Moves a flat face along its normal, adding or taking off material | | **Split** | Cuts a body in two along a plane | | **Move** (G), **Rotate** (R), **Scale**, **Align** (A) | Place a body: by the gizmo, by typed values, or by putting one face on another | | **Hollow for printing**, **Fill with a lattice**, **Split to fit the bed** | Prepare a part for 3D printing | | **Simplify mesh** | Fewer triangles on a mesh body, such as an STL or a scan | ### Fillet types Wait for the part to finish updating, choose **Fillet**, then choose **Type** and pick the required edges or faces. - **Edge** rounds picked edges; a picked face takes all its edges. **Radius mode** is **Constant** or **Varying**; varying mode also shows the end radius. The existing circular, conic and G2 section choices remain. - **Face** rounds between two picked faces. Meeting polynomial Bezier sides of a guided loft can use the rolling ball; unsupported free-form pairs are refused. See [Face fillets](/how/fillets). - **Full round** rounds the flat top of a rib or wall. It retains the existing Along choice and geometry limits. Changing Type replaces the unapplied preview and keeps only a selection valid for the new type. Set the values after choosing the type. Apply remains unavailable until the current type has valid input. When editing an existing feature, its Type stays fixed. Palette searches for **Face fillet** or **Full round** open the same Fillet interface with that type chosen; the existing search words and shortcuts remain available. ### Cylindrical wrap Select an original upright cylinder wall and choose **Cylindrical wrap**. This profile adds one rectangular pad to the first native quarter of the original +Y half on an upright cylinder at any XY center. The selected display wall keeps its usual merged appearance; the feature stores the individual original half and its reference signature. Set **U start (native)** and **U end (native)** with `0 < start < end < 0.5`. Set **V start (native)** and **V end (native)** with `0 < start < end < 1`. These are the original surface parameters. Set **Height** to any positive value within the modeling range. Preview the pad, then Apply. Edit its bounds or height from History; Undo/Redo and Save/Open retain the same recipe and individual face reference. The reported mass uses the closed wrap reference. Surface joins retain the model tolerance. This profile has no holes, text or engraving. Downstream features (transforms, booleans, holes, fillets and exports) can consume the resulting solid; uncertified native SI inertia exports remain refused. A saved document rebuilds the evaluated mass provider when it opens; a copied output alone does not carry that provider. ![Editing a reopened cylindrical wrap in Studio at 1024 by 768 pixels](/shots/studio/cylindrical-wrap.png) ### Qualified solid profiles, draft, loft and split boundaries - Bounded countersink and counterbore hole profiles validate depth, angle, and diameter bounds deterministically and refuse self-intersecting or under-thick cuts rather than clipping geometry. - Blind drill holes (118° drill tip) are supported on solids that already contain holes, draft faces, or multi-loop faces, and planar B-spline SubD/NURBS faces are recognized directly by Hole. - Solid chamfer edge profiles support editable feature history alongside rolling-ball fillets (including G2 curvature-continuous fillets with canonical face numbering and tangent miters, fillet rollover with top-edge preservation, L-shape closed top-loop miters, and custom 90° threads). - Thin Extrude builds uniform-wall solids from both open and closed sketch profiles, including drafted terminations onto oblique target planes. - Remove History freezes a solid body into a clean base feature when you want to detach or simplify upstream history. - Draft supports arbitrary sketch planes, non-tangent line-arc joints, holed regions, and adjacent planar wall groups while preserving exact analytic/NURBS surfaces; Shell after Fillet is also supported on drafted extrusions. - Open NURBS sweeps and general 3D sweep curves emit smooth B-spline skins and support in-place path edits from feature history; both Sweep and Loft accept multi-loop (holed) sketches, and Loft also accepts flat solid faces directly. - Two-guide lofts are qualified beyond rectangular profiles across general smooth and multi-segment profile chains, with minimum-twist seam alignment on mixed-profile circular lofts. - Conserved solid splits support constant-X, constant-Z, and oblique planar cuts while conserving exact solid volume, refusing out-of-envelope or unreachable cuts cleanly, and preserving split-face references across save/open round-trips and assembly flattening. - Feature patterns and transformed copies generalize beyond difference cuts with zero-effect diagnostics and 360° circular-pattern overlap warnings; curve-driven body patterns support tangent-following, surface-normal, and bank-twist alignment. - Sheet metal flange length and angle drag handles orient automatically to the selected sheet edge, sheet metal supports Path Flange and Formed Beads alongside standard bends, and profile reliefs and weld beads are stored natively in `.bcad` documents. ### Extended construction planes Beyond the default XY/XZ/YZ planes and flat face sketches, Studio supports five extended construction planes: tangent plane, plane at angle, 3-point plane, midplane (preserving shallow nonparallel tilts), and plane along path. ### Freeform surfacing, direct editing and reverse engineering - Freeform surfacing tools build and edit open B-Rep sheets with surface patch, ruled surface, trim/extend surface, boundary fill, and open-sheet STEP round-trip support. - Project curve onto surface creates exact 3D wall-riding curves, while conformal surface emboss, deboss, and split-face project features cleanly onto curved faces (refusing partial solid intersections). - Direct face transform edits move or rotate faces while validating adjacent loops, and SubD surfaces expose configurable refinement steps. - Reverse engineering converts imported triangle meshes into analytic B-Rep solids and fits exact section curves directly in the browser. ### Injection-molded enclosure features and CNC joinery - Enclosure design tools generate parametric mounting bosses, lip-and-groove joints, snap-fit hooks, and vent/grill arrays directly on solid shells. - Fabrication joinery tools build tab-and-slot, finger-joint, and CNC dogbone corner reliefs with clearance validation that refuses overlapping clearance-expanded slots. ## Patterns and Booleans - **Linear pattern** (P), **Circular pattern** and **Mirror** (M) copy a body in a row, round an axis or across a plane. **Duplicate** (⌘ D) makes one copy. - **Union** (U), **Subtract** (D) and **Intersect** (I) combine two picked bodies. Results can be combined again, and a hole can go into a combined body. Two bodies that touch only along an edge or at a point stay two bodies after a union; the manufacturing checks warn that they only touch, and exports keep them as separate pieces. See [Boolean operations](/packages/cad/robustness#boolean-operations) for the set rules, a tested example, and how the kernel chooses and runs its prismatic, polyhedral, curved-surface or mixed mesh algorithm. ## Machine elements **Spur gear** (and helical), **Meshing gear**, **Gear rack**, **Cam**, **Shaft**, **Key**, **Keyway**, **Dowel pin**, **Retaining ring**, **Bearing**, **Coupling**, **O-ring gland** and **Connector opening**. **Pulley**, **Sprocket** and **Belt or chain** work from your own belt and chain rows; none are built in. **Mount** fixes a motor, a servo or a bearing unit to a flat face facing ±X, ±Y or ±Z, as one of your `mounts` rows says (see [Shop rows](/studio/rows)): - **Where.** Pick the row, then place its output axis with the two **Axis at** values, and **Turn** it a quarter at a time. **Pilot** is **Through**, or a recess of its depth. - **What it cuts.** Ordinary features: the bolt holes, the pilot and the shaft's clearance hole, or a servo's body cut through the face. The row the mount came from stays loaded while it is used. - **What is refused, never clipped.** - A mount that goes off the face, a recess as deep as the plate, or a bearing that isn't loaded or has another bore is refused with `[MOUNT_RANGE]`. - A face that isn't flat and square to an axis is refused with `[MOUNT_FACE]`. - A row that isn't loaded is refused with `[MOUNT_ROW]`. - **The axis.** - The result reports the output axis, for a mate or a tool frame. - A concentric mate on the pilot puts a revolute joint on the motor's axis. - No frame is made automatically. - **Loading the rows.** The Library can't load mount rows yet. Attach the file in the chat and ask the agent to load it, then run **Mount** from the command palette. **Fit class** and **Fit pair** (under Inspect) declare tolerance classes and fits, with clearances from your tables. ## Sheet metal, frames and smooth shapes ### Sheet metal - **Sheet plate** and **Sheet profile** start a sheet-metal part. **Flange** adds a bend along a straight edge (with optional `cornerOverlap` `butt`/`partial`/`full`), **Path flange** sweeps a flange along connected lines and tangent arcs, **Bead** forms a stiffening rib along a path on a planar sheet face, **Perforate** punches hex, round, square, or slotted whole-hole arrays inside a planar sheet face or closed sketch boundary, and **Corner relief** cuts a corner free. - **The sheet's rules.** Each part carries its thickness, its bends' inner radius and its K-factor. - The prefilled rules (1.5 mm, R = T, K 0.5) are estimates, not material data, and their labels say so. - A bend table you load (the `bend` rows; see [Shop rows](/studio/rows)) gives each bend's K instead. - **The flat pattern.** A sheet body's properties show its **Flat pattern** size. **Show the flat pattern** draws it to scale: the outline, and each bend's centre line dashed, up and down in two colours, with its note. **Export flat DXF** writes it as DXF 2000 or R12. ### Frames **Frame**, **Structural member**, **Gusset** and **End cap** build welded frames. See [Frames and weldments](/studio/frames). ### Band surface **Band surface** joins two edge chains of two bodies with an exact ruled sheet that stays in step with them. Select the first chain (its edges, or a face for all its edges), choose **Band surface**, then click the second chain; both chains are open or both closed. Chains follow tangent edges by default (set **Chain** to **Single edge** to turn that off); clicking an edge again removes it. Unequal edge counts are paired by normalized length. **Flip** runs the second chain the other way. In the History edit, **Re-pick** replaces one side with your next clicks (a body made at or after the band cannot be picked: roll back first). The band's bodies stay bodies, and the sheet reports its boundary deviation from the source edges. The band stores the edges' persistent names and never follows a renamed edge on its own: a lost or moved edge refuses a lost or moved edge refuses the edit with the reason, a saved file that no longer has one opens with the band held (its reason shown) while the rest builds, and only your explicit choice in the reference decisions names another edge. A band cannot be placed in an assembly or a library part yet, and STEP export leaves the band sheet out and says so (the facade's STEP call refuses instead). Band thickening waits on exact thicken and is refused until then; a raw `band-surface` node is accepted through the checked `add_features`, with no chat command or facade verb yet. ### Freeform surfaces and boundary solids Complete freeform sheet workflows and turn enclosed sheets into solids: - **Surface patch** fills a closed 3D edge loop (2 to N sides) with a C0 or G1 smooth patch sheet (`continuity`, optional `bulge`). - **Ruled surface** sweeps straight rulings of a given **Length** and **Draft** angle along a selected edge chain or curves in `normal`, `tangent`, or explicit direction mode, with mitered or split corners. - **Trim surface** cuts a sheet body against an intersecting body, plane, or curve tool while keeping the selected side (and leaving solid cutter tools intact). - **Extend surface** lengthens open sheet boundary edges in **Linear (G1 tangent)** or **Natural (G2 curved)** mode along surface curvature. - **Boundary fill** finds all enclosed 3D volume cells partitioned by 2 or more intersecting surfaces, solids, or planes, and materializes selected cells into a watertight solid (optionally consuming source sheets). ### SubD and the cage editor **SubD box**, **SubD tube** and **SubD torus** make smooth bodies from a subdivision cage, with exact B-spline faces. ![A SubD box: one smooth body from a box cage](/shots/studio/features/subd-box.jpg) **Edit cage**, from the command palette, opens the **Cage editor** on a SubD feature: - **Pick** vertices, edges or faces with 1, 2 and 3. Double-click an edge for its loop, and Alt-double-click for its ring. - **Move** what is picked with the gizmo. Holding Shift as a drag starts extrudes instead. - **Show** the cage as **Box** or **Smooth** (Tab). - **Operations** on the picked items: | Operation | Key | What it does | |---|---|---| | **Extrude** | E | The picked faces, or boundary edges, out as a new region | | **Insert loop** | L | An edge loop across the ring through the picked edge | | **Bridge** | B | Quads between two boundary loops of as many edges | | **Fill** | F | One face over a hole | | **Weld** | W | The picked vertices merged at their middle; **Weld near** merges those within 0.01 mm | | **Crease** | C | The picked edges made sharp; **Smooth edges** takes creases off | | **Delete** | ⌫ | The picked faces removed, leaving a hole | - **Mirror** the cage **Across X**, **Y** or **Z**, or **None**. - **Checks.** The panel says what the cage's checks flag. - **Undo, Done and Cancel.** ⌘ Z steps back within the session. **Done** (Enter) writes the cage as one step of the part's history; **Cancel** (Esc) leaves it as it was. Moving vertices is a value edit of the feature; changing its faces or creases changes its structure. This matters for what the agent may change directly (see [Proposals and autonomy](/agent/proposals)). ### From a picture Attach an image in the chat, such as a logo, a character or an icon, and ask the agent to build it: - **Tracing.** The studio traces the image into outlines: the background is found, and the foreground is split into a few flat colours, each with its holes. - **Building.** The agent extrudes or inflates a traced layer, at the width you ask for. - **A draft.** Features made from a picture are a draft. Their dimensions stay unconfirmed until you confirm them, and an export says the part is a draft. See [Designing with the agent](/agent/). ## Inspect **Measure** (Shift M) gives distances, angles and sizes between picked faces and edges. **Interference** shows where bodies overlap, and by how much. ## Editing and the history - Click a feature in the history to open it in the feature editor, change its values or what it is built on, and apply. The features after it rebuild. - A sketch a feature is made from can be changed in the feature editor too. - ⌘ Z and ⇧ ⌘ Z step back and forward. - When a change can't be built, the HUD says why before you apply it. --- # Parameters and configurations A parameter is a named size the part depends on, such as `C = 3`. A feature's value can be bound to it, so changing the parameter changes every feature that uses it. A configuration is a saved set of parameter values, applied in one step. ## Named sizes Open **Parameters** in the top bar: - **Add one.** Give a name and a value, then **Add**. A name starts with a letter or `_`, and is at most 32 letters, digits or `_`. - **Change one.** Edit its value. The part is evaluated again with it. - **Rename one.** Change its name, and it is renamed everywhere it is used. - **Delete one.** Each feature that used it keeps its value as a plain number. - **Where it's used.** Each parameter shows how many features use it, as `1×`, and provides a reverse-reference `'Used by'` lookup that lists and selects every consuming feature or dimension directly. Parameter values are finite numbers. The panel does not evaluate a formula typed into a value field. Script expressions and library recipe expressions are separate features; a direct parameter binding stores a reference to one named value. The object facade's `param(name)` also names one parameter, not an expression. Invalid names, duplicate names and non-finite values are refused. A binding can also be refused when the selected field cannot store one parameter reference directly, such as a field that writes to several places or converts a diameter to a stored radius. Choose a field offered by the **ƒ** list instead. ![The Parameters panel in the dock: the parameter C used once, and the configurations small and large](/shots/studio/parameters/panel.jpg) ## When an edited value is accepted Typing in an existing parameter's value field changes the draft text only. Press Enter or leave the field to submit it. The Studio checks the proposed model and its existing references before accepting the change. If the change is refused, the accepted parameter values, part and references stay unchanged. For example, suppose a chamfer's Distance is bound to `C = 3` mm. Typing `5` does not yet replace that value. After submission, `C = 5` mm is accepted only if the candidate passes the checks. Otherwise the accepted value remains `3` mm. These numbers illustrate the edit flow; they do not predict whether a particular chamfer can be built. If **Parameters not changed** asks you to wait, let the accepted part finish evaluating and loading its mass results, then submit again. If it asks for unresolved references, make those choices first. A reference that disappears or changes kind can block a parameter change; a finite number alone is not enough to accept it. ![An existing value stays accepted while a draft is checked; a refused change keeps the old value](/diagrams/parameter-value-acceptance.svg) [Open the diagram at full size](/diagrams/parameter-value-acceptance.svg). ## Binding a value Bind a feature's value in its editor: click the feature in the history or the **Browser**, then pick a parameter from the **ƒ** list next to the value, and **Apply**. - While bound, the value follows the parameter and can't be typed. - Pick **ƒ** again to unbind it. The value stays as it is. - A bound sketch value reopens in the sketcher at the parameter's current value. **Finish** keeps each binding whose value you left as it was. A rectangle's or circle's bound value stays bound when you change its other sizes; in an outline of points, a binding stays only while the outline's other points are unchanged (move a corner, add or remove points, swap the main shape and they become plain numbers). A value you change yourself becomes a plain number too, and Finish says so. ![A chamfer's Distance bound to the parameter C in the feature editor](/shots/studio/parameters/bind.png) The agent can change parameter values too. At the default autonomy, a change to parameter values applies directly when every hard requirement still passes. Adding or removing a parameter is a proposal. See [Proposals and autonomy](/agent/proposals). ## Configurations Under **Configurations**: - **Save these values as…** names the current values, and **Save** keeps them as a configuration. - **Apply** a configuration to set all its values in one step. The panel marks the one the values match now. - A configuration can be deleted. Its values stay as they are. Applying a configuration changes the current numeric parameters; it does not create new parameters from names that have since been removed. It does not change feature suppression or replace assembly components. Feature suppression is a separate history setting: it disables a feature without deleting its definition. Assembly variants are separate again. Their declared inputs can drive part parameters, feature suppression, component choices or mate values in a derived document. Applying a saved parameter configuration is not the same operation as selecting an assembly variant. See [Assemblies](/studio/assemblies). ### Applying older saved values A configuration updates matching parameter names; it does not remove values added after it was saved. For example, save `small` when `C = 3`. Later change `C` to `5` and add `Wall = 2`. If applying `small` is accepted, the current values become `C = 3, Wall = 2`. `Wall` stays because `small` has no value for that name. These are illustrative values for length bindings in mm, not a geometry result. The panel adds `now` only when all current names and values match the saved configuration. In this example, `small` need not show `now` after **Apply**, because the current set also has `Wall`. Save a configuration with the complete current values if you want that set to match. Applying it does not unsuppress a feature; change suppression separately in the history when needed. ![Applying saved C equals 3 replaces current C equals 5 but keeps the later Wall equals 2; the name sets still differ](/diagrams/configuration-value-overlay.svg) [Open the configuration comparison at full size](/diagrams/configuration-value-overlay.svg). ## What a parameter drives - **The model.** A field that supports direct binding, such as an extrusion distance or a chamfer distance. - **The drawing.** It updates with the model. A revision whose model has changed says **Revision out of date**. See [Drawings](/studio/drawings). - **Exports.** Parameters are part of the document's revision, so exports made with other values name another source revision. See [Revisions and sources](/guide/concepts#revisions-and-sources). - **The kernel's own parameters.** A part document's dimensions can be `{ "parameter": "name" }` in code too. See the [Modeling API](/packages/cad/modeling). --- # Frames and weldments A frame is a set of structural members along a skeleton, each member a body of its own. The members share their section, and their joints are cut to fit. ## A frame ![A table frame of eight 40 × 40 × 3 tubes, each member its own body](/shots/studio/frames/table-frame.jpg) **Frame** builds members along a skeleton: - **Skeleton:** **Table (top and legs)**, **Box (12 edges)**, **Rectangle**, **L (two members)**, **T (through and branch)**, or **Picked edges** — the straight edges you pick on bodies, such as a layout box or a sketch. - **Width (X)**, **Depth (Y)** and the height size a preset skeleton. - **Section:** the member's profile (below). - **Corners:** **Mitre**, **Butt** (the larger section runs through) or **None (overlap)**. - A weld gap holds member ends apart. - Hole-saw and V cutters can replace the cope at one joint. A positive gap together with a notch isn't supported. **Structural member** places one member on its own: - **Member path:** **Straight**, **Arc by center**, **Arc through point** or **Tangent bend** (with its **Bend radius**). - **Start** and **End** points. - **Line through:** which point of the section the path runs through. - **Roll:** the section's turn about the path. Start, end and preset positions use the document's X, Y and Z coordinates in mm. A preset's position is its starting corner; width extends along X, depth along Y and height along Z. Roll uses degrees about the member path, not a rotation of the whole skeleton. For **Picked edges**, every selected edge must be straight. This command copies their endpoints into the new skeleton; it does not create a live link to those edges. ## Sections A section is either typed or taken from your library: - **Typed:** a **Rectangular tube**, **Round tube**, **Angle**, **Channel**, **I/H beam** or **T-slot** profile, by its dimensions. Corner, root and toe radii are prefilled as estimates and say so. - **From your library:** a row of your own frame sections. The section library holds your rows; you add, edit or load them from a file, each row with where its sizes come from or flagged as an estimate. None is built in. - Editing a row moves every frame that uses it. - A row a frame still uses can't be removed. ## Skeletons **Skeletons** edits a frame's 3D sketch: - draw and select on a work plane, with an axis lock; - the diagnosis says what is free, redundant or unmet; - add constraints and bind values to parameters; - **Apply** or **Cancel** the session. A saved 3D sketch keeps its point and segment arrays, constraints, parameter bindings and feature ID when opened again. A single point with no segment is also a valid saved sketch. Re-editing through the 3D sketch session keeps the existing ID and metadata; removing all constraints removes them from the stored node. Frames that follow the same skeleton retain that reference through edits, Undo/Redo and Save/Open. The file reader checks structure without solving or changing the stored points. When a frame follows a placed part's sketch, the link identifies that instance and the sketch's stable feature ID. Its points use the sketch plane, then the instance's rotation and position. A frame inside a placed part can follow its own features, but cannot follow a sibling part's sketch. This link accepts straight sketch outlines, not curves. ## Gussets, end caps and welds - **Gusset** puts a triangular plate in the corner of two picked members, with its legs, thickness, corner clip and offset. - **End cap** closes a member's end, either **Over the end** or **In the bore (a plug)**. - **Weld bead** places a modeled fillet weld on a square member end (**Leg size**, optional **Inner bore fillet**) or along a gusset's seams (**Leg size**), authored in history via **Weld bead** or the agent's weld action. When frame joint ownership is configured, each joint's bead is owned once, so shared seams aren't counted twice. Oblique-end beads are refused until there's an independent check for them. ## The cut list ![The cut list of the table frame: rows of identical members with their lengths, end cuts and masses](/shots/studio/frames/cut-list.png) **Cut list** groups identical members into rows: quantity, section, material, axis length, long point, each end's cut and mass, with the totals and a CSV. The densities are the materials library's estimates. With your stock lengths loaded, the pieces are nested into bars, with the waste and the kerf. On a drawing, the **Cut list table**, **Weld list table** and **Weld symbols** put the same information on the sheet. --- # Assembly workflow Use this guide to place reusable parts and decide whether the assembly can move. Assembly placement and robot motion have different support limits. ## Goal Place part instances, constrain them with mates and inspect the solved assembly. For a mechanism, continue to the supported robot pose and motion tools. ## Inputs - Part documents prepared as separate .bcad files, plus the document's own base-part bodies. - An intended position for each instance and compatible faces or references for its mates. - For robot work, mates that leave supported motion free and the required joint settings. ## Work sequence ### 1. Insert parts and place instances Choose Insert part to place a .bcad document as an instance. Select the instance in Browser to inspect its definition and bodies. Use its gizmo or typed position to place it. Copies share one part definition. Their placements remain separate. Use Make independent only when one copy needs a definition of its own. A newer revision waits for acceptance; loading the file does not replace all copies immediately. ### 2. Add mates and read the remaining freedom Select a face that stays, then a face on the part to move. Choose a compatible mate and inspect it in Mates. The base part and grounded parts stay fixed. Typed placement cannot override existing mates. Read the Freedom line and any Mate refused reason before adding another constraint. A solved mate can leave motion free; a part does not have to be fully fixed to be correctly assembled. ### 3. Check the current assembly Inspect the placements and resolve unmet mates. Use Interference to find overlap at the current placement. Use Clearance in Preview & analysis to distinguish designed contact, touching, overlap, near and clear. Explode changes the display only. It does not change the placements, mates or exports. These checks describe the current assembly; they do not establish clearance through a whole motion. ### 4. Continue to a supported robot pose Open Joints. The joint type follows the motion left free by the mates. Choose Base link to select the link that stays fixed. Use a joint slider, or submit a numeric pose with Apply or Enter. Home returns joints to zero, the pose solved by the mates. A pose is a preview. It is not saved and does not add an undo step. ![Existing Studio image: the Joints card and sliders for a two-link arm](/shots/studio/robots/joints.jpg) This image is reused from the robot guide. It is not a new result from this workflow. ## Check the result - Confirm which instances share a definition and which revision they use. - Check placements, remaining freedom and unmet mate reasons. - For robot work, confirm the joint tree and the pose before creating a path. - Use the path and motion tools described in [Robots](/studio/robots#moving-it) for movement checks. Gravity torques shown at one pose describe that pose. They do not establish loads during a motion. Motion checks need their own path, limits and inputs. Playing a preview does not save a motion. See [Limits and sizing](/studio/robots#limits-and-sizing) for duty and actuator checks. ## Refusals and support Two fixed parts cannot be mated. An unsolved mate is not an accepted placement constraint. A valid assembly mate can still be unsupported by the robot motion tree. For example, a solved Universal placement does not yet provide a supported robot joint or export. A numeric pose outside its set joint limits is refused and keeps the previous pose. Studio Check path still refuses looped motions; supported loop playback has a separate scope. Showing a variant also blocks modeling edits. Show the master before editing the assembly. ## Related details - [Assemblies and mates](/studio/assemblies): placement, definitions, mates and variants. - [Face and edge references](/studio/assemblies#face-and-edge-references): supported mate targets. - [Robots](/studio/robots): joint trees, poses, paths and export limits. - [Parameters and configurations](/studio/parameters#configurations): part configurations versus assembly variants. --- # Assemblies and mates An assembly is a document that places other parts as instances, positioned by mates or by typed values. The document's own bodies are the **base part**. ## Placing parts - **Insert part** in the top bar places another `.bcad` as an instance. - **Library** inserts catalogue parts and snaps them by their interfaces. - Pick an instance in the **Browser** to open its panel: its definition, its bodies and volume, **Duplicate** and **Remove**. - Drag an instance with its gizmo along an axis or round one, or type its position. Undo puts it back. ## Shared definitions and revisions Copies of a part share one definition. The instance panel says so, for example `Rev A · shared by 2`. - Load a newer file with **New revision file**. The panel shows **Revision waiting**, and nothing changes until you click **Accept Rev B**. Then every copy takes the new revision where it stands. **Keep Rev A** keeps the current one. - **Make independent** gives one copy a definition of its own, so later revisions of the shared one leave it as it is. ## Mates A mate ties a face of one part to a face of another. The **Mates** panel lists them; pick one to edit or delete it. To add one, pick a face that stays, then a face on the part to move. The base part and grounded parts stay fixed. If the second part is fixed and the first is free, their roles swap; two fixed parts cannot be mated. Typed placement is solved against the existing mates, so it cannot override them. | Mate | What it holds | |---|---| | **Coincident** | Two flat faces on one plane, a straight edge on a plane, or two straight edges on one line | | **Distance** | Two flat faces at a distance | | **Angle** | Two flat faces at an angle | | **Concentric** | Axes aligned for cylinders, cones, circular edges or straight edges; or two spheres with one centre | | **Tangent** | A cylinder touching a plane or another cylinder; or a sphere touching a plane | | **Lock** | One part fixed to another | | **Fastened** | Connector origins together, with their Z and X directions aligned by default; no free motion | | **Ball** | Connector origins together; three rotations remain free | | **Universal** | Connector origins together, with the fixed connector's Z perpendicular to the moving connector's X; two rotations remain free | | **Cam** | A follower's flat face riding a cam's lobe, from a face of the cam: see [Robots](/studio/robots#the-joint-tree) | | Path mate | A moving part constrained to follow a 3D curve or edge path | | Slot mate | A pin or face constrained to translate along a bounded slot | | Gear / Rack-and-Pinion / Screw | Mechanical motion link mates coupling rotation-to-rotation or rotation-to-translation ratios | Distance inputs use mm; angle inputs run from 0° to 180°, inclusive. Both must be finite numbers. Only compatible kinds are admitted. **Cam** is also admitted when the moving face is flat. Where offered, **Mate flip** changes the side or orientation for the chosen kind. Ball and universal mates do not offer this option. The panel's **Freedom** line says what the picked part can still do: fixed in place, placed by typed numbers, or the motion its mates leave free. A mate that can't be solved is refused, and **Mate refused** says why. ### Connector joints **Fastened**, **Ball** and **Universal** use a connector frame at each reference. Each frame supplies an origin and directions. Fastened aligns both frames by default; mate-level flip reverses Z while keeping X aligned. Ball aligns only their origins. Universal holds the origins together and keeps the fixed frame's Z direction perpendicular to the moving frame's X direction. Choose **Universal** when the connection must retain two rotations about axes attached to the two parts. Without a lock, the supported solve handles one universal mate on the moving part. Combining it with other mates on that part needs a coupled solve and is reported as an unmet mate. Do not treat that placement as solved. A lock keeps its captured placement; the universal mate is then checked at that placement. Universal does not accept a distance, alternate angle, pitch, ratio, relative pose, limits or mate-level flip. Ball also rejects those options. Fastened rejects the same options except flip. Unsupported options are refused with `VALUE`; they are not silently ignored. Connector settings and mate-level options are separate. A solved universal placement does not yet provide a robot joint. Its two-axis robot decomposition is unsupported, so it cannot be used as a supported robot motion or export. See [Robots](/studio/robots) for motion limits. ### Connector settings For a mate kind that supports connectors, each reference can store connector settings in `at`. `point` selects a supported point on its geometry: `centre` on faces, `start` or `end` along a cylinder or cone's computed axis span, `apex` on a cone, and `start`, `mid` or `end` on a straight edge. An arc also supports these three points when its endpoints are known. The default is `mid` for a straight edge and `centre` for other geometry. Connector `flip` reverses local Z first. `turn` then rotates about that Z in degrees. Finally, `offset` moves the origin by three distances in mm along the resulting local X, Y and Z axes. These settings do not replace mate-level flip. Editing a connector keeps its reference's persistent name and signature; removing it removes only `at`. An unavailable point gives `CONNECTOR_POINT`. Missing computed face centres or axis spans give `CONNECTOR_UNAVAILABLE`; the solver does not substitute an arbitrary point. ### Face and edge references The reference table includes planar, cylindrical, spherical and conical faces, plus straight and circular edges. The mate editor labels them as a sphere or socket, cone or conical seat, straight edge, arc edge or circular edge. The agent reads the table with `assembly.get` and `faces_of`, then passes the persistent name in each mate end's `face` field to `assembly.add_mate`. Edge names join their two face names with `|`. This does not add direct vertex references or a new viewport edge-picking workflow. The base part's plane and axis datums also appear under persistent names `datum:`. A plane datum supplies a plane; an axis datum supplies an axis with its fitted radius, or zero when no radius is stored. Point datums are not mate targets. A datum connector's `centre` uses the datum origin when it has no face centre or axis span. A cone or edge supplies an axis for a concentric mate; it does not impose contact along its whole shape. Two concentric spheres share a centre and retain three rotations. A sphere tangent to a plane retains three rotations and two slides. Unsupported pairs, such as a cone tangent to a circular edge, are refused with `MATE_FACES`. Spheres, cones and edges are classified from the B-rep with finite geometric samples and tolerance checks. This is not a proof that every arbitrary NURBS surface has one of those shapes. Stored signatures are checked on reopening. An assembly mate can be valid while its motion is unsupported: a sphere/plane tangent is refused by the motion tree with `MOTION_UNSUPPORTED`; unsupported loop mates use `LOOP_MATE_UNSUPPORTED`. The agent locks a part with `assembly.lock` (`part`, `to`): a lock mate that keeps the part where it stands in the other's coordinates, proposed for you to accept as its other assembly changes are. ### Coupled mate DOF and contradiction diagnostics When multiple mates act together on a moving instance, the assembly solver tracks coupled degrees of freedom (DOF) across the combined constraints rather than checking each mate in isolation. If a new or edited mate contradicts an earlier constraint, Studio surfaces the conflicting mate pair and recovery options while keeping the last accepted assembly placement intact. The freedom that mates leave is also what makes a mechanism move. [Robots](/studio/robots) reads the mates as joints. ## Interference and clearance ![Interference: a cylinder through a box, with the overlap's volume](/shots/studio/assemblies/interference.jpg) - **Interference** finds where bodies overlap and by how much. For example, a cylinder through a box gives `Box ∩ Cylinder` and its overlap volume. - **Clearance**, in the dock's **Preview & analysis**, classes every pair of bodies and draws it on the model: | State | Meaning | |---|---| | designed | A contact the design intends, such as a key in its keyseat | | touching | Faces meet with no gap | | overlap | The bodies overlap, with the volume | | near | Closer than the clearance threshold | | clear | Farther than the threshold | ## Exploded view **Explode** spreads the parts apart for display; each click steps the factor (`×0.5`, …), and the last turns it off. The placements don't change, so mates and exports are unaffected. ## Variants An assembly can have **inputs**, each driving a few things explicitly, and **variants**, named sets of input values. **Variants**, among the inspect tools, opens the **Variants** card in the dock: - **The list.** **Master** and each variant, the active one marked. **Show** shows one; **×** deletes a variant. - **Showing a variant.** - It is regenerated from the master, and the master isn't changed. - While it is shown, every modelling edit is refused: commands, the feature editor's **Apply**, moving placed parts, and **Parameters** edits. The message is **Can't change the part now**, with `Showing : show the master to edit.` **Show the master** goes back. - **The inputs.** Each input's value, with what it drives under it. Editing values doesn't write anything yet: the card counts the values that differ. - **Save these values as…** and **Save** keep them as a new variant. - **Update** writes them into the variant shown. - **Reset to** drops the edits. - **Unmet mates.** A mate the shown variant leaves unmet is listed, its reason behind a click. - **Undo.** Saving, updating, deleting and switching each go through the same action the agent uses, and are one undoable step. With no inputs yet, the card says so. Inputs are added by the agent's `assembly.inputs`, or written in the document. A part's own configurations stay in **Parameters** (see [Parameters and configurations](/studio/parameters)). - **The agent's actions:** - `assembly.inputs` sets the inputs. It changes the assembly's structure, so at L1 and L2 the agent proposes it, and from L3 it applies. - `assembly.variants` sets the named variants and which one is active. It applies from L2, and is proposed at L1. - The agent's summary of the part (`query.summary`) includes its variability. See [Tools](/agent/tools) and [Proposals and autonomy](/agent/proposals). - **In code:** `@barocss/cad-model/assembly/variability` regenerates a variant from the inputs: `variantOf` takes its values and `variantNamed` its name. - **Inputs.** An input has a name, a type (`number`, `boolean` or `choice`), an optional unit (`mm` or `deg`) and range, and a default. It drives one or more targets: - a part's **parameter**, as `scale · value + offset`; - a feature's **suppression**, when the value is the one given; - **which part** a placed instance uses, per choice: like another instance's part, or a part from a shipped library; - a **mate's** distance or angle. - **The master is the default.** The document as saved is the variant where every input is at its default. - A variant is made from the master by setting what its values drive, then solving the mates again. - It is never stored as a model of its own, and the master is never changed. - With every value at its default, the master itself comes back. - **What is refused.** The inputs are checked against the document, each refusal with its code: - two inputs with one name, or a variant naming an input that isn't there (`[INPUT_NAME]`); - a value outside its type or range (`[INPUT_RANGE]`), or a choice that isn't offered (`[INPUT_CHOICE]`); - an input that can't drive its target (`[INPUT_TYPE]`), or a target that isn't there (`[INPUT_TARGET]`); - two inputs driving one target (`[INPUT_CONFLICT]`); - a master that isn't what the defaults give (`[INPUT_DEFAULT]`); - a variant name that isn't there (`[VARIANT_UNKNOWN]`). See [Refusal codes](/reference/refusals). --- # Robots For joint timing, pose sampling and the boundary with dynamics, see [Robot motion](/guide/robot-motion). An assembly whose mates leave motion free is a mechanism. The **Joints** card reads it as a robot: links, joints and their limits. You can move it, check it and export it for simulators. ## The joint tree Each pair of parts with mates between them is one joint. The kind of joint is read from the motion the mates leave free, not from the mates' names: | Free motion | Joint | |---|---| | none | fixed | | one turn | revolute, or continuous without limits | | one slide | prismatic | | a turn and the slide along its axis (cylindrical), a plane's two slides and a turn, a ball's three turns | a chain of one-degree joints through extra links | Anything else, such as a screw motion or two turns about different axes, is refused with a typed reason. A part joined twice round the graph closes a loop; the tree keeps one path and lists the loop, which the **Loop** line shows. Some joints follow another instead of moving on their own: - **Gears.** Two spur gears meshing on one carrier's joints are coupled: the second follows the first at the gear ratio. A joint's gears are those of its part and of the parts fixed to it, so a gear locked to its shaft turns with the shaft's joint. A locked gear off the joint's axis is noted `GEAR_NOT_COUPLED` rather than left out. - **Cams.** A **Cam** mate, from a face of the cam part to the follower's flat face, makes the follower ride the lobe. The mate holds nothing itself: the follower's own mates place it in its guide, and its slide follows the cam's joint by the lobe's lift. A cam mate from the follower to another sliding part, such as a valve it pushes, moves that part with it, so chains like crank → gear → cam → follower → valve work. The Joints card says "follows *joint* on its cam (*mate*)". - The lobe is read from the cam's faces at the follower's face: flats and arcs along the cam's axis, such as an arc-and-line profile. Anything else is refused, `CAM_PROFILE_UNSUPPORTED`. - Nothing is coupled, and `CAM_NOT_SEATED` says why, when the cam has no joint to drive it, the follower doesn't slide, its face isn't flat or isn't across the cam's axis, the two are on different links, or the face is off the lobe at the solved pose (by how much). - The follower's face is taken as an infinite plane, so a face narrower than its contact's travel isn't caught. - **One leader each.** A joint follows one leader: a second cam or push on it is refused, `COUPLED_TWICE`. Couplings that lead back round to their own joint are cut where the cycle closes, `COUPLING_CYCLE`. **Base link** chooses which link stays put. Angles are in degrees and lengths in millimetres in the card; exports write metres and radians. ## Moving it ![The Joints card of a two-link arm: each joint with its slider](/shots/studio/robots/joints.jpg) - **Sliders.** Each joint's slider poses the robot, within its limits. **Home** returns every joint to zero, the pose the mates solve to. - **Numeric pose.** For an independent moving joint, enter turns in degrees or slides in mm. Choose **Apply** or press **Enter** to apply the value. Typing alone does not change the pose. Choose **Cancel** or press **Escape** to discard the edit and restore the displayed value. A value outside the joint's set lower or upper limit is refused; the previous pose stays unchanged. The slider's input window does not add physical joint limits. - **A pose is a preview.** It isn't saved, and it doesn't add undo steps. - **Links.** **Link masses** lists each link's mass and centre of mass, from its bodies and their materials. The card shows the gravity torques at the current pose. Right after an edit, these wait until the masses are worked out. - **Paths.** **Add waypoint** records poses. **Check path** sweeps the robot along them and reports the first collision, with continuous collision between samples. - **A sweep can run out of its sample budget.** The path is then neither clear nor in contact: Check path and the agent's `sweep_path` and `check_path` say "not certified" with how far the sweep got and the least clearance met (`exhausted` in the reply), and never report a collision or a time of impact for it. The default budget is 20,000 samples per sweep. For an open timed path, `maxSamples` applies to each timed segment. A closed-loop motion divides each timed segment into chords of at most 1° of rotation or 1 mm of travel. Each chord has its own `maxSamples` budget. The closed-loop budget is not shared across the timed segment or the whole motion. The returned `samples` is the total used; it can exceed `maxSamples`. `exhausted.samples` is the count in the segment, or closed-loop chord, that ran out of budget. - **Designed contact isn't a collision.** Some faces touch by design, and the sweep leaves those to the design while it still checks the rest of the same links. Each pair it skips says why. - Two meshing gears' teeth are the coupling's to hold. - Two links pinned in a planar loop can't cross where they're stacked. - A cam follower's face rides the lobe. The rest of the follower is checked against the cam. - A running fit: the two round faces of a concentric mate, such as a piston in its bore. The display meshes' facets cut inside a true circle, so a 0.1 mm clearance would read as contact. Within the facets' depth, plus 0.05 mm, the fit's faces don't count as touching; a boss past the bore still does. - The cam's and the fit's faces are checked at the sweep's steps, at most 1/90 of the move apart, not certified between them as the rest of the sweep is. - **Closed loops along a motion.** The agent's `play_motion` and `check_path` close a looped robot's loop at every pose: the motion names the driving joints, and the passive ones are solved. `check_path` cuts each segment into chords at most 1° (or 1 mm) of the drivers apart and certifies each one. A chord's middle isn't closed exactly, and the reply says by how much, as `loops: {chords, chordResidual}`, with `chordResidual` in mm. A waypoint that gives a passive joint is refused, `LOOP_PASSIVE`. In Studio, **Play motion** and the time scrubber close supported looped motions too. Studio's **Check path** still refuses a looped motion with `LOOP_OPEN`. - **Playing a motion.** **Play motion** plays the motion chosen in **Motion choice** in time. Its length shows before it plays. - The draft is the path above: from home, through the waypoints, to the pose shown. Each joint moves at its velocity limit, or at 180/π deg/s (about 57.3 deg/s) for a turn and 100 mm/s for a slide when it has none. - A saved motion plays as the document keeps it: its waypoints, profile and limits. - **Pause motion** holds it. The **Motion time** scrubber sets the pose at a time, **Loop motion** repeats it, and **Motion speed** plays it at 0.25× to 2×. - For a supported looped motion, the driving joints follow the path and the passive joints are solved. Seeking forward or backward keeps the assembled branch through earlier segment joins. A refused seek leaves the pose and time unchanged. Playing a single joint's preview on a looped robot is still refused with `LOOP_OPEN`; choose a supported motion in **Motion choice** instead. - For an open-chain motion, the first contact on the way is reported as "Contact *link* – *link* at t … s". From then on the two links are marked: outlined on WebGPU, tinted on WebGL2. - Playing saves nothing. Moving a slider, **Home**, a change to the waypoints or another choice stops it. ![The pan-tilt head's saved motion "look around" chosen in Motion choice, paused partway, its camera frame drawn](/shots/studio/robots/saved-motion.jpg) - **Saving a motion.** With the draft chosen, name it in **Motion name** and **Save as motion** keeps it in the document, in degrees and millimetres, and chooses it. A motion of the same name is replaced. Saving is an undo step; the pose shown and the play state are never saved. For a supported looped motion, **Add waypoint** and **Save as motion** keep only driving-joint values. The solved passive-joint values stay in the preview and are worked out again when the motion plays. - **Workspace.** **Workspace** (Map workspace) samples the reachable space and draws it as voxels, with a summary and the samples. **Download workspace** saves it. ## Limits and sizing Revolute and prismatic joints need their lower and upper limits, effort and velocity before they export. The agent and `cad-cli` can also run two checks: - **robot-check** works through the arm's duty: limits, sweeps, the torques at every pose, and the actuators against their ratings. It lists every margin. - **robot-size** raises actuators and ratings, or slows the profile, round by round until every margin is above zero, or stops with a typed reason when no sizing can fix the brief. ### Duty files and public reports A public duty file has `moves`. Each move supplies `from`, `to`, `profile` and limits. Turning values use degrees; sliding values use mm. Use `joint_limits` by joint key when a move mixes turns and slides. Velocity, acceleration and jerk use the corresponding units per second, second squared and second cubed. `dwell` and `serviceLife` use seconds, `clearance` uses mm, and `g` uses mm/s². `inertia_ratio_max` is dimensionless. The `actuators` map names catalogue motor and reducer ids by joint key. It does not supply new sourced hardware data. The CLI passes canonical `PublicDuty` directly to `robotCheckOfDoc`; sizing uses `robotSizeOfDoc`. Public `serviceLife` and `dwell` remain in seconds. The sample also uses the explicitly importable `robot/native/duty.readDuty` to decode the same public input into native operands, then calls `nativeRobotCheckOfDoc` and `nativeRobotSizeOfDoc` for comparison. Those native operands use radians, existing SI quantities and `life_h` in hours. The shared `dutyJson` adapter writes public values back. The sample compares the shared projections with the canonical results on the shipped SCARA document, including its turn and slide: ```js const output = dutyJson(tree, duty); assert.deepEqual(output.moves[0].to, { 'base~arm1': 10, 'arm2~quill': -5 }); // degrees, mm near(output.moves[0].joint_limits['base~arm1'].velocity, 60); // degree/s near(output.moves[0].joint_limits['arm2~quill'].velocity, 5); // mm/s assert.equal(output.moves[0].dwell, 0.5); // seconds assert.equal(output.serviceLife, 7200); // seconds assert.equal(output.clearance, 0.25); // mm assert.deepEqual(output.g, [0, 0, -9810]); // mm/s² ``` `robot-check` publishes the original harness result through `harnessJson`. A margin contains `value`, `limit`, `unit`, its dimensionless `margin`, its `source` and `ok`. Angles use `degree` or `degree/s`; turning effort uses N·mm and slide effort uses N. The adapter converts the original quantities before rounding. A non-finite quantity is `null`, not an invented finite measurement. Decisions, unknowns and sources keep their meaning. Project the original report before cloning or serializing it. A cloned margin has no raw quantity identity. Changing a margin's `value`, `limit` or `unit` also invalidates that identity. Projection then refuses with `HARNESS_RAW_PROVENANCE_UNAVAILABLE`: ```js const original = await nativeRobotCheckOfDoc(doc, bodies, evaluate, duty); const before = JSON.stringify(original); const report = harnessJson(tree, original); // project the original before cloning or serializing it assert.deepEqual(await canonicalRobotCheckOfDoc(doc, bodies, evaluate, input), report); const range = report.margins.find(m => m.check === 'joint range' && m.joint === 'base~arm1' && m.detail === 'to'); near(range.value, 10); // degrees near(range.limit, 130); // degrees, the sample's upper limit assert.equal(range.unit, 'degree'); ``` Consistency checks use dimensionless `errorRatio` and `limitRatio: 1`, and retain their original `ok` decision. Two zero quantities give an error ratio of 0. A positive error with a zero limit gives `null` and `reason: "zero-limit"`. Non-finite quantities or ratio overflow give `null` and `reason: "non-finite-ratio"`. The old mixed-unit `value` and `tol` fields are not public consistency fields. The scripted sizer's `sizedJson` result uses the same public boundaries for `tree`, `duty` and `report`. It retains `ok`, `rounds`, `trace` and any `stopped` reason. Trace text keeps its explicitly stated original units. The CLI writes the robot document and a public `.duty.json` file, and prints a summary. It does not print that whole result. These are the CLI's shared adapters, not new `Robot` facade methods. This sample limits sizing to zero rounds and checks the actual returned contract; it does not demonstrate a successful search for a hardware design: ```js const { sized } = await nativeRobotSizeOfDoc(doc, bodies, evaluate, duty, { maxRounds: 0 }); const output = sizedJson(sized); // actual producer output, using the same public projectors const canonical = await canonicalRobotSizeOfDoc(doc, bodies, evaluate, input, { maxRounds: 0 }); assert.ok(!('error' in canonical)); assert.deepEqual(canonical.sized, output); assert.equal(output.ok, sized.ok); assert.equal(output.rounds, sized.rounds); assert.deepEqual(output.trace, sized.trace); assert.equal(output.duty.serviceLife, 7200); near(output.tree.joints.find(j => j.key === 'base~arm1').limit.velocity, 180); near(output.tree.joints.find(j => j.key === 'base~arm1').limit.effort, 2000); // N·mm near(output.tree.joints.find(j => j.key === 'arm2~quill').limit.velocity, 100); // mm/s near(output.tree.joints.find(j => j.key === 'arm2~quill').limit.effort, 50); // N ``` Gravity torques, the sweep and inverse kinematics follow a cam's coupling. A move's torques through a cam are refused, `CAM_UNSUPPORTED`: the lift's second derivative isn't worked out yet. ## Exporting **Export URDF**, **Export MJCF**, **Export SDF** and **Export USD** write the robot with: - one link per part, the joint at the child; - the visual mesh and a convex hull for collision; - each link's mass in kg, centre of mass in m, and inertia tensor in kg·m². Rotations follow the file format. No format holds a cam coupling, so a robot with a cam follower is refused, `CAM_UNSUPPORTED`. The agent's `export_urdf` and `export_mjcf` take `leave_out: ["cam"]`, which writes the follower as a free joint and notes it. Every export is checked against its format's rules by our own reader before it is written. The URDF and MJCF outputs have also been read back by external tools — urdfdom's `check_urdf` and MuJoCo — and their kinematics match the studio's. ## Tool and sensor frames A frame is a named pose on a link: a tool's centre point, or a camera. It is kept with the robot's settings, beside the joints. - **In the viewport.** Each frame is drawn where the pose puts it, as an axis triad (X red, Y green, Z blue) with its name on a chip: a tool's in the accent colour, a sensor's in cyan. It moves with the joint sliders, and keeps its size as the arm moves. - **In the Joints card.** Each frame's origin (mm) and its Z axis at the pose shown, in the assembly's coordinates. - **Setting them.** The agent sets frames; the studio has no editor for them yet. - **Where a frame sits.** On a link, posed in that link's part's own coordinates: a position in mm, and a rotation in degrees about X, then Y, then Z, as a placed part's rotation. A frame may be a `tool` or a `sensor`. - **What uses it.** - Forward kinematics moves a frame with its link. - Inverse kinematics can reach a frame's pose, or only its position. - The workspace map of a frame is its link's, taken at the frame's origin. - **How each export writes it.** As a fixed child of its link, at its pose. A frame adds no mass, and with no frames every export is byte for byte as before. | Format | A frame is | |---|---| | URDF | A massless link on a fixed joint (`_fixed`), as ROS-Industrial's `tool0` | | SDF | A link with a tiny inertial (an SDF link without one would weigh 1 kg), fixed to its link | | MJCF | A body welded to its link, with no joint and no mass, and a `` of its name at its origin | | USD | An `Xform` beneath its link's prim | - **What is refused.** - `[FRAME_NAME]`: a name that isn't letters, digits and `_`, or that one of the export's own links or joints already uses. - `[FRAME_LINK_MISSING]`: a frame on a part that isn't in the assembly. - `[FRAME_LINK_STALE]`: a frame on a part that isn't a link of the robot as it stands. - `[FRAME_POSE]`: a pose that isn't three numbers. A frame is refused this way, never dropped. See [Refusal codes](/reference/refusals). - **The agent's action.** `assembly.frames` sets, changes or removes frames. Frames are part of the robot's settings, so the agent proposes every change, at any autonomy level. - **How it was checked.** - Read back with our own readers, each frame is where forward kinematics puts it, at 21 poses. - External tools read the frames too: MuJoCo 3.3.0 as sites, usd-core as prims beneath their links, and urdfdom's `check_urdf`. - SDF is checked only by our own reader. ## Sample robots `@barocss/cad-model` ships eight sample robots under `samples/robots/`, each a `.bcad` file you can open, with `index.json` listing them. They're built from blocks joined by the studio's mates. Each joint has an estimated rating, so every sample exports, and each carries one demo motion in its robot settings, in degrees and millimetres. | Sample | What it is | Joints | |---|---|---| | `arm-2r` | A planar arm | Two turns about parallel vertical axes, 40 mm apart, ±150° | | `scara` | A SCARA arm | Turn (±130°), turn (±145°), a slide of ±40 mm, turn (±360°) | | `arm-6r` | An industrial arm's chain | Six turns about Z, Y, Y, Z, Y and Z: waist, shoulder, elbow and a three-axis wrist, each with its limits | | `gantry-ppp` | A Cartesian gantry | Slides along X (0–200 mm), Y (0–120 mm) and Z (±40 mm) | | `pan-tilt` | A camera head | Pan about Z (±170°), tilt about X (±60°), and a `camera` sensor frame | | `gripper` | A gear-coupled gripper | The left finger turns ±30°; the right one follows on meshing 20-tooth gears, the other way | | `four-bar` | A four-bar linkage | Crank, coupler and rocker, closed in one loop | | `gear-joint` | A gear-driven joint | A 20-tooth gear driving a 30-tooth one, which turns two thirds as far, the other way | Open one from **Templates**, under **Samples · Robots**. It opens as Open would open its file, with its joints in the **Joints** card and its demo motion in **Motion choice**. ![The Templates menu, with the eight robot samples under Samples · Robots](/shots/studio/robots/samples-menu.png) Set a pose with the sliders, and **Play motion** plays the draft from home to it. Here three samples are paused half-way: ![The 6R arm half-way from home to a reach, its shoulder and elbow bent](/shots/studio/robots/arm-6r-motion.jpg) ![The SCARA arm half-way through a pick, its quill partly lowered](/shots/studio/robots/scara-motion.jpg) ![The Cartesian gantry half-way across its X and Y travel, its ram up](/shots/studio/robots/gantry-ppp-motion.jpg) ### In code The [object API](/packages/api) reads an assembly as a robot: `assembly(…).robot()`. It exposes `joints()`, `pose(values)`, `path(waypoints).check()`, `inertia()`, `gravity(values)`, and the robot export methods. The public contract below applies to the facade, agent replies and stored robot settings. For `Robot.pose(values)`, turning-joint inputs and the returned `values` are in degrees. Sliding-joint values are in millimetres. `RobotPath.waypoints` and `RobotPath.poseAt(t)` use the same units. Link and frame placements keep positions in mm and rotations in degrees. #### Robot unit boundaries ::: warning R7 contract preparation This section records the confirmed R7 public contract. Focused samples check angular metadata, B1 mass/gravity and the shared B2 duty/harness/sized boundaries. Further evaluation, orientation, print, CAM and material field changes and the final combined checks are pending. The full R7 contract is not yet product-qualified. ::: Use degrees for turning joints and mm for sliding joints. Resolve the joint type before you convert a value. | Interface or field | Turning joint | Sliding joint | |---|---|---| | `Robot.pose(values)` input and returned `values` | degrees | mm | | `RobotPath.waypoints`, `RobotPath.poseAt(t)` | degrees | mm | | `Robot.path(waypoints, { limits })` velocity and acceleration | deg/s, deg/s² | mm/s, mm/s² | | `Robot.joints()`, `Robot.setJoints()` and stored `RobotSettings.joints` lower/upper limits | degrees | mm | | Public and stored joint velocity | deg/s | mm/s | | Public acceleration and jerk | deg/s², deg/s³ | mm/s², mm/s³ | | Public and stored joint effort; reported torque or force | N·mm | N | | `RobotPath.check()` contact `values` | degrees | mm | The internal joint tree, kinematics and dynamics keep their radians and SI calculations. Adapters convert at the public boundary. Values that already use degrees, such as pose inputs and saved motion waypoints, need no second conversion. A value of `90` must remain a quarter turn after a save, read, pose or contact report. For a mimic relation, `follower = multiplier × leader + offset`. The offset uses the follower's unit. The multiplier uses the follower's unit divided by the leader's unit. It is dimensionless when both use the same unit. For a turn that drives a slide, a public multiplier of 0.1 mm/degree and an offset of 2 mm give 11 mm at 90 degrees. For the reverse relation, 10 degrees/mm and an offset of 5 degrees give 35 degrees at 3 mm. Convert both the multiplier and offset when you pass between public and internal units. Apply the same joint-type rule to cam and contact values. Nested gear placements `couplings[i].g1.rotation` and `g2.rotation` use degrees in the gear pair's common frame. The internal FK and `GearPlacement` keep radians. GearSpec pressure and helix angles already use degrees; do not convert them again. A pose's gear metadata uses `phase` and `homePhase` in degrees and `backlash` in mm. `loops.residual` is the pin distance in mm for a pin closer. For a general closer, it is the original norm of distance and rotation constraint rows, not a pure length. The four-bar pin-loop sample's checked motion reports `loops.chordResidual` in mm. **Public reports.** `Robot.inertia()` returns `{ links }`. Each link uses these fields, as does its agent report: | Field | Public unit | |---|---| | `links[i].mass` | g | | `links[i].centroid` | mm | | `links[i].inertia`, `links[i].principal.moments` | g·mm² | | `links[i].frame.origin` | mm | | `links[i].bodies[j].mass` | g | For `Robot.gravity(values, g)`, supply `g` in mm/s². The default is `[0, 0, -9806.65]`, which preserves the existing 9.80665 m/s² physical value. An explicit input of `[0, 0, -9810]` selects 9.81 m/s² instead. The reply's `gravity` is the magnitude in mm/s². It is not a returned vector. `torques` and `generalized` contain the holding moment or force by joint key. Read `units[key]`: a turn uses N·mm, and a slide uses N. Density remains g/cm³. A motion report uses `joints[key].peak`, `rms` and `unit` for moment or force. Its `distance`, `peakVelocity`, `peakAcceleration` and `peakJerk` use degrees or mm and the corresponding time derivatives. `at` is in seconds. These motion fields are separate from a gravity reply. The object facade exposes `path()` for motion; it has no `move()` or `size()` method. Public durations and timestamps use seconds. This includes `duration`, `time`, `at`, `moveDuration`, `cycleDuration` and `dwell`. `evaluationTime`, `builtTime` and `wallTime` convert former millisecond values by dividing by 1000. `serviceLife` converts former hours to seconds by multiplying by 3600. A turning joint's `stopDeceleration` uses deg/s². For a physical reference, take a solid 10 × 10 × 10 mm cube at density 2.7 g/cm³. Its mass is 2.7 g, centroid is [5, 5, 5] mm and each diagonal centroidal inertia is 45 g·mm². With the explicit test input `[0, 0, -9810]` mm/s², its weight is 0.026487 N. With its centre 5 mm perpendicular to a hinge axis, the holding torque magnitude is 0.132435 N·mm. The corresponding native SI values are 0.0027 kg, [0.005, 0.005, 0.005] m and 4.5 × 10⁻⁸ kg·m². The cube samples below check mass, inertia and slide force against these independent values. The hypothetical 5 mm hinge is a calculation only; the tested hinge below uses a drilled arm with a 20 mm lever. #### Calculate the sign of a holding torque Consider one moving link at a prescribed static pose. Its total mass is 100 g, its centre of mass is `r = [200, 0, 0]` mm from the hinge, and the hinge's positive axis is world `+Y`. All vectors below are in world coordinates. Use gravity `[0, 0, -9806.65]` mm/s² and no other applied loads. | Calculation | Value | |---|---| | Convert mass and acceleration | `100 g = 0.1 kg`; `-9806.65 mm/s² = -9.80665 m/s²` | | Gravity force, `F = m g` | `[0, 0, -0.980665]` N | | Gravity moment, `r × F`, with `r` in mm | `[0, +196.133, 0]` N·mm | | Holding moment, opposite to gravity | `[0, -196.133, 0]` N·mm | | Holding moment projected onto the `+Y` axis | `-196.133 N·mm` | The public gravity reply reports the holding value by joint key, so this single independent turning joint has `-196.133` in both `torques` and `generalized`, with unit `N·mm`. It does not report the positive gravity moment. The internal calculation uses a 0.2 m lever and gives `-0.196133 N·m`; the public conversion multiplies by 1000. A negative value means holding effort opposite to the joint's positive axis. It is not a negative mass or a failure. ![A 100 g moving mass at a 200 mm X lever, downward gravity force, and a hinge whose positive Y axis points into the XZ diagram](/diagrams/robot-holding-units.svg) [Open the holding-torque diagram at full size](/diagrams/robot-holding-units.svg). This is a calculated example and diagram, not an API execution, measurement, or validation result. It explains one static pose; it does not predict free motion, acceleration, contact forces, or actuator suitability. The bounded static gravity experiment still requires its supported one-joint model, explicit gravity input and known materials. #### Physical report examples The cube uses aluminium `al6061`, whose density is 2.7 g/cm³. The code calls the object facade, and compares its reply to closed-form values. The expected values are not taken from a conversion helper. ```js import { Robot, part, BarocssError } from '@barocss/cad-model/api'; ``` ```js const cube = () => part('cube').box({ w: 10, d: 10, h: 10 }).material('al6061'); ``` ```js const robot = new Robot(cube().doc), before = robot.doc; const [link] = robot.inertia().links; near(link.mass, cubeCase.mass); // 2.7 g link.centroid.forEach((value, i) => near(value, cubeCase.centroid[i])); // [5, 5, 5] mm link.inertia.forEach((row, i) => row.forEach((value, j) => near(value, cubeCase.inertia[i][j]))); // diag 45 g·mm² link.principal.moments.forEach((value, i) => near(value, cubeCase.moments[i])); link.frame.origin.forEach(value => near(value, 0)); // mm near(link.bodies[0].mass, cubeCase.mass); // the body's mass is also in g ``` The gravity input is a vector, and the returned `gravity` is its magnitude. A cube with no joint can check that magnitude, but supplies no joint holding-force result: ```js const robot = new Robot(cube().doc); const standard = robot.gravity(); const explicit = robot.gravity({}, [0, 0, -9810]); near(standard.gravity, 9806.65); // magnitude, mm/s² near(explicit.gravity, 9810); // this call supplies 9.81 m/s² ``` Add two perpendicular plane mates to constrain a second cube to a vertical slide. Its holding force is 0.026477955 N at the default gravity and 0.026487 N at the explicit 9810 mm/s². A 20 mm displacement does not change its weight: ```js function cubeSlide() { const block = cube().doc; return new Robot({ ...block, instances: [{ id: 'slide', name: 'slide', doc: block, position: [10, 10, 0], rotation: [0, 0, 0] }], mates: [ { id: 'x', kind: 'coincident', a: { part: 'base', face: 'n1.side1' }, b: { part: 'slide', face: 'n1.side3' } }, { id: 'y', kind: 'coincident', a: { part: 'base', face: 'n1.side2' }, b: { part: 'slide', face: 'n1.side0' } }, ], }); } ``` ```js for (const [gravity, expected] of [[undefined, 0.026477955], [cubeCase.gravity, cubeCase.force]]) { const reply = robot.gravity({ [joint.key]: 20 }, gravity); assert.equal(reply.units[joint.key], 'N'); near(reply.torques[joint.key], expected); // mass in kg × acceleration in m/s² near(reply.generalized[joint.key], expected); t.diagnostic(JSON.stringify({ gravity: reply.gravity, force: reply.torques[joint.key], expected })); } ``` For turning effort, use a 20 × 20 × 80 mm aluminium block. It has two blind bores of radius 4 mm and depth 8 mm, and two transverse bores of radius 4 mm and length 20 mm. None intersect. The concentric and plane mates make a hinge about +Y. The block's centre is 20 mm above that hinge at home. At 90 degrees, the lever is perpendicular to gravity. The holding moment is negative about +Y, in N·mm: ```js function drilledArm() { const block = part('block').box({ w: 20, d: 20, h: 80 }) .hole(b => b.faces().facing('+z'), { d: 8, type: 'blind', depth: 8, x: 10, y: 10 }) .hole(b => b.faces().facing('-z'), { d: 8, type: 'blind', depth: 8, x: 10, y: 10 }) .hole(b => b.faces().facing('+y'), { d: 8, x: 10, y: 20 }) .hole(b => b.faces().facing('+y'), { d: 8, x: 10, y: 60 }).material('al6061'); return new Robot({ ...block.doc, instances: [{ id: 'arm', name: 'arm', doc: block.doc, position: [0, 20, 40], rotation: [0, 0, 0] }], mates: [ { id: 'axis', kind: 'concentric', a: { part: 'base', face: 'n5.side0' }, b: { part: 'arm', face: 'n4.side0' } }, { id: 'seat', kind: 'coincident', a: { part: 'base', face: 'n1.side2' }, b: { part: 'arm', face: 'n1.side0' } }, ], }); } ``` ```js // Two blind bores (r=4, depth=8) and two transverse through bores (r=4, length=20), with no overlap. const volume = 20 * 20 * 80 - 2 * Math.PI * 4 ** 2 * 8 - 2 * Math.PI * 4 ** 2 * 20; const mass = volume * 2.7 / 1000; // g; closed-form geometry, not a report-derived oracle for (const gravity of [9806.65, 9810]) { const reply = gravity === 9806.65 ? robot.gravity({ [joint.key]: 90 }) : robot.gravity({ [joint.key]: 90 }, [0, 0, -gravity]); const expected = -mass * gravity / 1e6 * 20; // N × 20 mm, holding about +Y assert.equal(reply.units[joint.key], 'N·mm'); near(reply.torques[joint.key], expected); near(reply.generalized[joint.key], expected); t.diagnostic(JSON.stringify({ gravity, torque: reply.torques[joint.key], expected })); } ``` The samples also check a real sweep's initial contact at 45 degrees and −12.5 mm. A separate unit projection fixture covers all four turn/slide mimic combinations. That fixture checks conversion; it does not demonstrate four physically assembled coupling mechanisms. The duty/metadata samples above exercise actual shared producers; the final combined checks after the remaining field changes are still pending. [Native export files](#exporting) retain their format-specific SI units. Their frozen bytes need a separate check from public JSON quantities. Explicit source catalogue records such as `{ v, unit, src }` retain their source units and provenance. They do not change the units of public robot results. See [Unit and export comparisons](/reference/verification#unit-and-export-comparisons). ```js import { part, assembly } from '@barocss/cad-model/api'; ``` ```js /** A sample robot: its document (a plain-JSON .bcad) opened as a studio part, the assembly read as a robot. */ const open = id => assembly(id, part(id, read(`${id}.bcad`))).robot(); ``` - **The 2R arm:** its two turns, a pose, and a path checked for collisions. ```js const index = read('index.json'); // [{ id, title, about, file }] assert.deepEqual(index.map(s => s.id), ['arm-2r', 'scara', 'arm-6r', 'gantry-ppp', 'pan-tilt', 'gripper', 'four-bar', 'gear-joint']); const arm = open('arm-2r'); assert.deepEqual(arm.joints().joints.map(j => [j.key, j.type]), [['base~a', 'revolute'], ['a~b', 'revolute']]); const pose = arm.pose({ 'base~a': 90, 'a~b': -90 }); // degrees in; each link's place out assert.deepEqual(link(pose, 'a').rotation, [0, 0, 90]); assert.deepEqual(link(pose, 'b').rotation, [0, 0, 0]); // the turns add up: 90 − 90 const [sweep] = arm.path([{}, { 'base~a': 60, 'a~b': -90 }]).check(); assert.equal(sweep.clear, true); // nothing hit on the way ``` - **The SCARA arm:** the quill's slide. ```js const scara = open('scara'); assert.deepEqual(scara.joints().joints.map(j => j.type), ['revolute', 'revolute', 'prismatic', 'revolute']); const home = link(scara.pose(), 'quill').position, down = link(scara.pose({ 'arm2~quill': -30 }), 'quill').position; assert.deepEqual([down[0] - home[0], down[1] - home[1], down[2] - home[2]], [0, 0, -30]); // the quill slides 30 mm down ``` - **The 6R arm:** its axes, its demo motion swept, and its URDF read back. ```js const arm = open('arm-6r'); const axes = arm.joints().joints.map(j => 'XYZ'[j.axis.findIndex(v => Math.abs(v) > 0.5)]); assert.deepEqual(axes, ['Z', 'Y', 'Y', 'Z', 'Y', 'Z']); // waist, shoulder, elbow, a three-axis wrist const [reach] = read('arm-6r.bcad').robot.motions; // the sample's demo motion, in degrees assert.ok(arm.path(reach.path.waypoints).check().every(s => s.clear)); const urdf = arm.urdf('arm-6r'); // { urdf, files, notes, check } assert.deepEqual(urdf.check, []); // read back by our own URDF reader: nothing wrong ``` - **The gantry:** each slide carries the ones after it. ```js const gantry = open('gantry-ppp'); const home = gantry.pose(), moved = gantry.pose({ 'base~x': 150, 'x~y': 100, 'y~z': -30 }); const by = id => link(moved, id).position.map((v, k) => v - link(home, id).position[k]); assert.deepEqual(by('x'), [150, 0, 0]); // each slide carries the ones after it assert.deepEqual(by('y'), [150, 100, 0]); assert.deepEqual(by('z'), [150, 100, -30]); ``` - **The pan-tilt head:** its camera frame at a pose, and a pose past the tilt's limit. ```js const head = open('pan-tilt'); const [camera] = head.pose({ 'base~pan': 90, 'pan~tilt': 30 }).frames; assert.equal(camera.frame, 'camera'); // the sensor frame on the head assert.deepEqual(camera.rotation, [30, 0, 90]); assert.deepEqual(head.pose({ 'pan~tilt': 80 }).out_of_limits, ['pan~tilt']); // the tilt stops at ±60° ``` - **The gripper:** only the leader is given; the follower turns by the coupling. ```js const gripper = open('gripper'); const [coupling] = gripper.joints().couplings; assert.deepEqual([coupling.leader, coupling.follower, coupling.multiplier], ['base~left', 'base~right', -1]); const pose = gripper.pose({ 'base~left': 25 }); // only the leader is given assert.ok(near(pose.values['base~right'], -25)); assert.equal(pose.gears[0].held, true); // the teeth stay in mesh ``` - **The four-bar linkage:** the loop, and what a tree format leaves out. ```js const linkage = open('four-bar'); const { joints, loops } = linkage.joints(); assert.equal(joints.length, 3); // crank, coupler, rocker: a tree of three turns assert.equal(loops.length, 1); // and the coupler–rocker pin closing the loop const pose = linkage.pose({ 'base~crank': 60 }); // turn the crank: the others follow assert.ok(link(pose, 'rocker').rotation[2] !== 0 && link(pose, 'coupler').rotation[2] !== 0); assert.match(linkage.urdf('four-bar').notes[0], /closure \(Cc\) is not written/); // URDF is a tree format ``` - **The gear-driven joint:** the gear ratio. ```js const pose = open('gear-joint').pose({ 'base~g1': 30 }); assert.ok(near(pose.values['base~g2'], -20)); // two thirds as far, the other way ``` - **Motions:** a path timed and played, the sample's saved motion read, and a path saved as a motion. `path(waypoints, { profile?, limits? })` takes waypoints in degrees and millimetres, and limits per joint in deg/s and deg/s² (or mm/s and mm/s²). `duration()` gives its length in seconds. `poseAt(t)` returns the driving-joint values at a time in degrees or mm; pass them to `robot.pose(...)` for the solved passive values and link placements. `motion(name)` reads a saved motion, and `withMotion(name, path)` returns a robot with the path saved. - Supported looped paths, including the sample four-bar's saved `crank` motion, can use `duration()`, `poseAt(t)` and `problems()`. Supply driving joints only. Seeking keeps the assembled branch through preceding segment joins; a later seek cannot skip an unreachable or dead-point part of the path. - `problems()` returns `[]` for a supported, closable path, or lists its typed refusal. `duration()` and `poseAt(t)` throw the typed refusal when the required path cannot close. Finite lower or upper bounds on passive loop joints remain unsupported and give `LOOP_OPEN`. Extra passive-joint waypoint inputs give `LOOP_PASSIVE`. - An empty problem list describes the motion's timing and closure. Collision checking along that motion is separate. The four-bar example does not establish support for arbitrary mechanisms with several coupled loops. ```js const arm = open('arm-2r'); // Home to 60° on the first joint, at 90°/s and 180°/s²: a trapezoid of two half-second ramps and 1/6 s between. // (`default` limits every joint not named; a joint's own key limits that one.) const swing = arm.path([{}, { 'base~a': 60 }], { limits: { default: { velocity: 90, acceleration: 180 } } }); assert.deepEqual(swing.problems(), []); const T = swing.duration(); assert.ok(near(T, 1 + 1 / 6)); assert.ok(near(swing.poseAt(T / 2)['base~a'], 30)); // degrees: half-way at half the time assert.ok(near(swing.poseAt(T)['base~a'], 60)); const wave = arm.motion('wave'); // the sample's demo motion, saved in its robot settings assert.deepEqual(wave.waypoints, [{}, { 'base~a': 60, 'a~b': -90 }, { 'base~a': -45, 'a~b': 90 }, {}]); const saved = arm.withMotion('swing', swing); // a new robot, the motion kept in its document assert.deepEqual(saved.motion('swing').waypoints, swing.waypoints); ``` - **Checking a motion for contact.** The open-chain samples' demo motions are clear, and the gripper's meshing fingers are skipped as designed contact. For a looped motion, the object API's `check()` still refuses with `LOOP_OPEN`: its sweep and continuous collision checks do not yet follow the closed motion. Use the agent's `check_path` for the supported looped path, with the chord and residual contract described above. Studio's **Check path** has the same `LOOP_OPEN` boundary. Playback alone does not certify collision clearance. ```js // The four-bar plays with its loop closed; sweep/CCD is still refused for it. const LOOPED = ['four-bar']; for (const sample of read('index.json').filter(s => !LOOPED.includes(s.id))) { const [demo] = read(sample.file).robot.motions; assert.ok(open(sample.id).motion(demo.name).check().every(segment => segment.clear), sample.id); } // The gripper's fingers mesh: their teeth are the coupling's to hold, so that pair is skipped, with why. const [segment] = open('gripper').motion('grip').check(); assert.match(segment.skipped.find(p => p.links.join() === 'left,right').why, /^meshing gears/); // The first 60-degree move takes 7/6 s. At t=1 s, deceleration has 1/6 s left: // 60 - (180 / 2) * (1 / 6) ** 2 = 57.5 degrees. const crank = open('four-bar').motion('crank'); assert.throws(() => crank.check(), e => e.code === 'LOOP_OPEN'); const drivers = crank.poseAt(1); assert.deepEqual(Object.keys(drivers), ['base~crank']); assert.ok(near(drivers['base~crank'], 57.5)); assert.deepEqual(crank.problems(), []); ``` - **The exports**, each with what its reader found and what it had to assume. `check` lists what our own reader found wrong when reading the file back, and `notes` what the export assumed, such as aluminium for a body without a material. ```js const arm = open('arm-2r'); const urdf = arm.urdf('arm-2r'), mjcf = arm.mjcf('arm-2r'); assert.deepEqual(urdf.files.map(f => f.path), ['meshes/base.stl', 'meshes/base_collision.stl', 'meshes/a.stl', 'meshes/a_collision.stl', 'meshes/b.stl', 'meshes/b_collision.stl']); assert.deepEqual([urdf.check, mjcf.check], [[], []]); // each read back by our own reader assert.match(urdf.notes[0], /without a material, aluminium assumed/); // what the export had to assume assert.equal(arm.sdf('arm-2r').ok, true); assert.equal(arm.usd('arm-2r').ok, true); ``` --- # Prepare drawing and manufacturing files ## Goal Make a sheet from the current model, check its references, and prepare files for a recipient. Review the BOM and manufacturing report as separate results. ## Before you start - Have the part or assembly open in Studio. - Choose the material and manufacturing process needed for the report. - Load your shop rows when a feature or rule needs them. - Keep an editable `.bcad` copy of the model. Rows must come from a file that a person supplies. Sample rows are examples, not a built-in standard or supplier approval. ## Work through the document 1. Open the Drawing tab and choose Drawing scope. Select the base part, a placed part, or the assembly. Choose the scope before adding manual references. 2. Choose the sheet size, scale and projection. Review the front, top, right and isometric views. Show the hidden lines, tangent edges and centre lines that the sheet needs. 3. Use Auto under Dimensions to add automatic dimensions. It replaces its earlier automatic dimensions and keeps manual ones. Add the manual dimensions and notes that the sheet still needs. 4. Read Drawing issues after a model change. Review lost dimensions, unresolved datums and control frames. Apply a proposed fix only after you inspect the affected reference. 5. Open BOM and review quantities, sources and bought or made settings. Read estimate marks where a line has no shop row. Add the sheet's BOM table and balloons when the drawing needs them. 6. Check the selected process and its inputs in Library. Ask the agent to check the part for that process. Read each rule's value, limit, source and reason. 7. Export the sheet as SVG, PDF or DXF. Export a purchase list separately when the recipient needs bought quantities. Use Quote package for an injection-moulding request, then read its manifest. ![Existing Drawing example: automatic dimensions and a hole callout on a sheet](/shots/studio/drawings/auto-dimension.jpg) This image is reused from the Drawings guide. It illustrates a dimensioned sheet, not a new check of your model. ## Check the results - Check the drawing title, REV and SRC line. - If Revision out of date appears, review the model changes against that revision. - Check Drawing issues as well as the marks on the exported sheet. - Check PDF notes and title text if the export warns about `?` characters. - Read `pass`, `warn`, `fail`, `unknown` and `n/a` separately in the process report. - In a quote ZIP, read `open` and `complete`; check whether `part.step` is present. `unknown` marks a missing input or measurement in the process report. The purchase CSV is a quantity and sourcing list. It is not a price calculation. Do not add all displayed BOM line masses to recalculate the total. Element mass is already included in its part's mass. ## Keep these limits in view A scope change is refused while manual dimensions, datums, control frames or notes with leaders remain on the sheet. Keep that scope, or remove those references explicitly before changing it. An exported sheet can still have unresolved drawing issues. Tolerance annotations do not verify the part's geometric tolerances. A quote ZIP can contain open items or omit a failed STEP export. A complete quote request is not manufacturing approval. ## Continue with the detailed guides - [Sheet views and scope](/studio/drawings#the-sheet) - [Dimensions and notes](/studio/drawings#dimensions-and-notes) - [Drawing issues and exports](/studio/drawings#issues) - [BOM, mass and quote packages](/studio/bom) - [Processes and manufacturing reports](/studio/manufacturing) - [Load shop rows](/studio/rows#loading-rows-in-the-studio) - [Save the editable model](/studio/files#the-bcad-document) --- # Drawings The **Drawing** tab turns the part, or the assembly, into a dimensioned sheet. The sheet is computed from the model, so it follows every change; the dimensions and notes you add are kept with it. ## The sheet - **Drawing scope** chooses what is drawn: the base part, one placed part, or the assembly. - **Sheet size** is **A4 landscape** or **A3 landscape**. **Scale** is **Auto** or a fixed scale. **Projection** is **Third angle** or **First angle**. - The orthographic views are **Front**, **Top**, and **Right**; pictorial views include **Isometric**, **Dimetric** (ISO 5456-3, 1 : 1 : 0.5), and **Trimetric** (25° / 30°), all drawn as exact hidden-line projections, plus magnified detail views. **Hidden lines**, **Tangent edges** and **Centre lines** toggle what they show. - Orthographic dimensions, ordinate and baseline sets, datums, datum targets, standalone frames, broken views, detail views, and annotation leaders apply to orthographic views (and to sections and details where supported), not to pictorial views. - Dimension styles include standard linear, radial and angular callouts as well as baseline and ordinate chains, and PDF export writes crisp vector text alongside SVG and DXF sheets. - The title block carries the drawing's title and revision. **Next revision** steps it (A, B, …). When the model has changed since that revision, **Revision out of date** says so. - Beside your REV, the title block's **SRC** line names the document revision the sheet was drawn from, in every export of the sheet. See [Revisions and sources](/guide/concepts#revisions-and-sources). Changing the drawing scope is refused with `DRAWING_SCOPE_REFERENCES` while the sheet has manual dimensions, datums, datum targets, control frames or notes with leaders. Keep the scope, or remove those references explicitly first. A permitted scope change clears automatic dimensions; it does not transfer their references to the new part. Without an explicit scope, sheets with balloons or a BOM table use assembly scope. Other sheets use the base part. A part sheet normally draws made bodies only. Assembly scope keeps bought elements, and enabling balloons on a part sheet keeps those elements visible so the balloon can point to them. ### First angle and third angle Projection changes where the orthographic views are placed. In **Third angle**, the top view is above the front view and the right view is to its right. In **First angle**, the top view is below the front view and the right view is to its left. The front and top views keep the same horizontal mapping; the front and right views keep the same vertical mapping. For an unbroken box measuring 40 mm along X, 20 mm along Y and 10 mm along Z, use the default front view looking from −Y. At a fixed scale of **1:2**, the projected outlines have these sizes: | View | Model width × height | Size on the sheet at 1:2 | |---|---|---| | Front | 40 × 10 mm | 20 × 5 mm | | Top | 40 × 20 mm | 20 × 10 mm | | Right | 20 × 10 mm | 10 × 5 mm | These sizes are the same in both projection arrangements. They exclude labels, dimensions and the gaps between views. A different front orientation changes which model axes form the view's width and depth. ![Third-angle placement with top above front and right to its right, compared with first-angle placement with top below front and right to its left](/diagrams/drawing-projection-layout.svg) [Open the diagram at full size](/diagrams/drawing-projection-layout.svg). The diagram is a calculated layout schematic, not a captured drawing or a print-size reference. Its rectangles show the relative outline sizes; the app also reserves space for annotations when laying out the sheet. ### Drawing standard **Standard** (next to **Projection**) is **Not set**, **ISO** or **ASME**. Not set keeps the default drawing style. ISO and ASME each apply one preset; changing it is one undo step and the sheet is drawn again. The same preset reaches every export: the SVG, PDF and DXF sheets and the 3D annotations. In chat, `set_drawing` takes `standard` as `iso`, `asme` or `none`. | | Not set | ISO | ASME | |---|---|---|---| | Lettering height | 3.5 mm | 3.5 mm (ISO 3098) | 3 mm, 0.12 in (ASME Y14.2) | | Arrowhead | filled, 3 mm long, 1.2 mm across | filled 15°: 3 mm long, 0.8 mm across (ISO 129-1) | filled 3:1: 3 mm long, 1 mm across (ASME Y14.2) | | Dimension text | aligned with the line, above it | aligned with the line, above it (ISO 129-1) | horizontal, in a break of the dimension line (ASME Y14.5 unidirectional) | | Zeros (millimetres) | leading zero, trailing zeros dropped | `0.5`, `12`, `1.25` (ISO 129-1) | `0.5`, `12`, `1.25` (ASME Y14.5 metric) | | Projection symbol | the sheet's own small symbol | truncated cone, ends h and 2h across, 2h long, end view circles h and 2h, centre line; h = 3.5 mm (ISO 5456-2) | the same, h = 3 mm | | Datum feature triangle | filled | filled (ISO 5459) | filled (ASME Y14.5) | | Datum line target | phantom line | two crosses joined by a thin continuous line (ISO 5459) | phantom line (ASME Y14.5) | | Concentricity, symmetry | no advice | allowed | a **FRAME_RULE** warning: Y14.5-2018 dropped them, use position or profile | Under ASME the text is placed in a break of the dimension line, the break being the text's width and a millimetre either side. When the text does not fit between the arrowheads, it is set horizontally beside the line instead. The inch rule is under [Units](#units-inch-and-dual-dimensions). The ASME preset also uses 3 mm for ordinary view, section and detail labels, stacked tolerance deviations, table and BOM text, and weld text. Their spacing and layout use the same text height. Small title-block labels and glyphs inside symbols retain their own sizes; this preset does not certify a complete drawing against ASME. The ASME advice on concentricity and symmetry is a warning in **Drawing issues**, never a refusal: the frame can still be authored and an old one opens unchanged. In AutoCAD 2000 and R12 DXF, the ASME dimension style also records 3 mm text, centered placement and horizontal orientation. Each dimension's own drawing keeps its text height, arrowheads and placement. Plain and ISO dimension-style defaults stay unchanged. These style fields guide an external reader's defaults; they do not guarantee the same layout after that reader regenerates a dimension. DXF sheet coordinates stay in mm, including inch and dual display. The printed labels carry those display units; editable dimension-unit regeneration is a separate limitation. ### Units: inch and dual dimensions The part and every dimension value stay in millimetres; **Units** only changes how the sheet prints lengths. **Units** (next to **Standard**) is **mm** or **inch**; **Dual units** adds the other unit after each dimension in square brackets, primary first (ASME Y14.5 §1.6.4, Y14.2): `2.500 [63.5]` on an inch drawing, `63.5 [2.500]` on a mm one. **Details** (closed) holds **mm decimals** and **inch decimals**, each 0 to 6; empty keeps the default (mm as before, inch 3). Each change is one undo step, the sheet and its previews are drawn again, and the title block's **UNITS** cell reads `mm`, `inch`, `mm [inch]` or `inch [mm]`. In chat, `set_drawing` takes `units` (`mm` or `inch`), `dual` (true or false) and `precision` (`{mm?, inch?}`; `{}` resets); a value outside those is refused. - Inch numbers are the mm value divided by 25.4, with no leading zero and trailing zeros kept to the precision (ASME Y14.5 §1.6.2): 25.4 mm is `1.000`, 12.7 is `.500`, 0.127 is `.005`, 100 is `3.937`. ISO has no inch rule of its own, so the ISO and the unset drawings use this one too. - Millimetres follow the standard's rule as before (trailing zeros dropped); with an **mm decimals** value the number has exactly that many places (`12.0`). A tolerance in plain mm prints as entered, up to 4 places (`±0.005`, `±0.125`). - Numeric tolerance limits stay ordered and inside the authored zone. The dimension is rounded to nearest at the chosen decimals, and each deviation is then rounded inward from the true limit (the upper one down, the lower one up), so every printed limit lies inside the true zone. The decimals start at the drawing's (inch 3, or **mm decimals**; plain mm 2 or the decimals the tolerance was entered with) and rise, inch up to 5 and mm up to 4 (or an explicitly higher precision), until no nonzero deviation prints as zero and the zone keeps at least 80% of its width; the dimension gains zeros to the same decimals (ASME Y14.5 §1.6.2). Rounding can make a symmetric tolerance unequal, and then it prints as two deviations. 0.05 mm on 64 is `2.5197 ±.0019`, 0.005 mm is `2.51969 +.00019/-.00020`, +0.009/-0.004 mm on 8 is `.31496 +.00035/-.00015`, ±0.05 mm at 0 mm decimals is `64.00 ±0.05`, and 10.004 ±0.005 in plain mm is `10.004 ±0.005`. If even the most decimals cannot do it, an ordered numeric interval still prints at the most and **Drawing issues** shows `UNIT_PRECISION` naming the dimension. If no numeric interval can be represented, the sheet prints **tolerance not printable** and reports `UNIT_PRECISION`; it does not print inverted limits or collapse a positive-width zone to a point. An exact zero-width zone remains numeric when its endpoint is representable, including a deviation that compensates for rounding the nominal. The authored tolerance is unchanged. A fit class (`h7`, `H7/g6`) stays as written; its size and deviations print at common decimals by the same rule. An unrepresentable fit member shows **limits not printable** while other members remain numeric. An explicit tolerance and a fit on the same dimension share the displayed nominal precision. Exact decimal limits use the resolved model number: a small floating-point residue in a measured size can contract a printed limit by one final decimal step to keep it inside the authored zone. - Dual prints the dimension and its tolerance in both units: `2.5197 ±.0019 [64 ±0.05]`. Deviations that stack beside the value print on the line instead (`.3150 +.0039/-.0019 [8 +0.1/-0.05]`). A hole callout prints whole in both units. An angle never converts and never gets brackets. - A short linear label can use an outside position when its original region overlaps drawing marks. Nearby views, annotations, tables and the sheet/title regions are checked before choosing a position. Stacked deviations, basic boxes and attached control frames move with the label. Existing safe labels stay in place; the original dimension line, arrowheads, value, tolerance and authored placement stay unchanged. A label placed beyond an endpoint gets a connector to its dimension; a blocked connector makes that candidate unavailable. If no safe position is found, the original placement stays and **Drawing issues** reports `TEXT_OVER_LINES` or `OFF_SHEET` as applicable. Existing inline text gaps and radius, diameter, pitch-circle and angle labels keep their placement rules. - What converts: linear, radius, diameter and pitch circle values, tolerances, fit deviations, hole callouts (diameter, depth, counterbore, countersink), geometric tolerance frame values (a frame is not a dimension, so the decimals setting does not apply: in mm as entered; in inch a zone width rounds down and a projected zone height rounds up, each at 3 to 5 places keeping 80% of the value, and an unequal amount, which moves the zone, rounds to nearest within 5%; `UNIT_PRECISION` when 5 places are not enough), weld symbol sizes and the weld list's size column, datum target sizes, the bearing-ring width in element callouts, and the mm columns of a table made from the part (bend, cut list, spring, gland and weld tables; mass and counts stay). An element size line (a sentence of lengths) keeps its mm header, and a table with a section column adds the note `Section sizes are in mm`. Frames, datum targets and tables print the primary unit only, even when **Dual units** is on. - What stays in millimetres: a thread designation (`M6×1`), notes and a table you typed yourself, the element size lines and section names, the drawing check's messages, and the size fields in the editors (they take model millimetres). - Exports follow the sheet: the SVG and PDF text, the DXF dimension text (`2.520 ±.002 [64 ±0.05]`) and the 3D annotations (`text` in the primary unit, `alt` in the other, the `value` still in mm). ### Title blocks and revision history - **Title block** chooses **Basic** or **Extended**. Basic keeps the original layout. Extended adds **Organization**, **Drawing number**, **Drawn by**, **Checked by**, **Material** and **Finish** under **Title block fields**. These are entered text, not values taken from the part's material or process. The templates make no standards claim. - The extended block needs more sheet space. Long values are reduced in size and then shortened with an ellipsis to fit their cell; the full text stays in the document. Switching back to Basic keeps the fields for later use. - **Revision history** stores records you enter. Set the drawing's revision, enter **Date**, **Change** and optionally **By**, then click **Record revision**. This also turns on **Revision table**. Each revision label can appear once, with at most 50 records. **Remove** deletes one record; clearing the table checkbox hides the table and keeps its records. - The table shows revision, date, description and author in the order entered. It uses the same placement and issue checks as other drawing tables. The fields and table are included in the sheet's SVG, DXF and PDF exports. - Changing the active revision or clicking **Next revision** does not add a history record. A record does not change the active revision or establish approval. **Checked by** is also entered text, not a recorded approval action. - The agent sets `titleBlock` and `revisions` through `drawing.set` (`set_drawing`). The title block has a `template` of `basic` or `extended`, plus optional `organization`, `number`, `drawnBy`, `checkedBy`, `material` and `finish`. It replaces the previous title block. Each revision record has `revision`, `date` (`YYYY-MM-DD`), `description` and optional `by`. The list replaces the history; `[]` clears it, and omission keeps it. To show it, include a table with `from: 'revisions'`. Invalid fields, dates, duplicate labels and multiline text are refused with `DRAWING_OPTIONS`. - A record can also carry `eco`, an engineering change order number (1–20 characters, single-line). The revision table gains an **ECO** column only when at least one record has one; without any, the table is as it was. For authored revision history, supply a dense list with no empty slots. One invalid record refuses the update; it does not silently remove that record or clear the history. Revision labels allow 1–6 characters, descriptions 1–120 and authors 1–60. Optional title-block fields allow 1–120 characters. Omit an optional field if unused; an explicit empty or whitespace-only value is refused. Text must be single-line. Leading and trailing spaces count toward the length limit and are retained. Dates must be real calendar dates in `YYYY-MM-DD` form. Saved-file readers filter invalid or duplicate records. An authored update must pass the stricter checks above. ## Sections **Add section** places a cut through the part: section A–A, B–B and on, each with its cutting line in the view where the plane is edge-on, and the cut faces hatched. - A principal section is square to the front, top or right view. - An aligned section follows an off-axis feature, for example a keyway in a tilted bore. Its plane is square to the feature's axis, and its cutting line is drawn inclined. - **Export section DXF** writes one section on its own. When setting sections through the agent, a changed or removed section with dimensions, geometric control frames, or child detail views gives `DRAWING_SECTION_REFERENCES`. Remove those references explicitly before changing the section definition. In the 3D modelling viewport, persisted **Section views** (`sectionViews`) support up to `32` named views with `1` to `6` finite planes (`plane`, `planes`, `box`, or `cutout` modes) as display-only views that do not modify evaluated solid revision or model geometry. On drawing sheets, sections allow up to `20` ordered offset steps (`steps`) and explicit removed-section scale up to `1000:1`. ### Half and offset sections Each principal section's **Kind** includes **Full**, **Half** and **Offset (stepped)**. Half and offset sections are put together from exact plain sections, so each part is what a plain section or the uncut view shows there. - **Half.** The section on one side of a centreline and the uncut view on the other. Set the centreline's direction, where it lies and which side is cut; by default it runs up the middle of the view, cut to the right. The cutting line stays whole, and a centreline is drawn through the view, 3 mm past it. - **Offset (stepped).** The cut steps to other depths along the way, to pass through features that don't lie on one plane. Each step has where it starts and its depth; **Add step** adds one, and the steps run across or up the view. Each band is the plain section at its depth, and nothing is drawn where two bands meet. The cutting line steps with it, square across at each step, thick at its ends and bends. - **The agent.** It gives a section `half` or `steps` (with `along`) in `set_drawing`'s `sections`. Not both on one section, not on an aligned section, and steps must increase; otherwise the change is refused. - **Turning the drawing.** Choosing another front view is refused with `SECTION_KIND` while a half or offset section is on it. - **Not yet:** a half section's cutting line drawn over the cut half only, steps not square to the view's axis, and turning such sections with the drawing. ### Removed and revolved sections Choose **Removed** or **Revolved** in the section's **Kind** control to show only the cut face, with its outline and hatch. Geometry behind the cutting plane is left out. - **Removed.** The cut face is placed apart from the views, in free room on the sheet. Its cutting line stays on the view that shows the plane edge-on. The section's scale control uses **The sheet’s** scale by default, or a scale you choose. Its name includes the scale when it differs from the sheet's. - **Moving a removed section.** With **Select** (V), drag inside its box, away from a dimension. Its centre is saved at the new sheet position. Moving or rescaling it keeps the same cut, and its dimensions read model sizes. - **Revolved.** The cut face is turned a quarter turn about the cutting plane's trace and drawn on the view, centred on that trace. A front section is drawn on the top view; a top or right section is drawn on the front view. It uses that view's scale and has a centreline, with no separate section name or cutting line. - **Which sections.** A removed section can be principal or aligned. A revolved section must be principal. Neither can also be half or offset, and a section cannot be both removed and revolved. - **The agent.** In `set_drawing`'s `sections`, `removed` holds optional `at` and `scale` fields. Its `at` is the section centre, `[x, y]` in sheet mm; without it, placement is automatic. Its scale is absolute: 2 means 2:1, regardless of the sheet's scale. Without it, the sheet's scale is used. A section's outer `at` still sets the cutting depth in model mm. For a revolved section, set `revolved` to true instead. Invalid combinations are refused with `DRAWING_OPTIONS`. - **Issues.** `SECTION_NO_ROOM` means a removed section has no free room. Use a larger sheet, a smaller section scale, or place it by hand. `SECTION_NO_VIEW` means a revolved section has no view to receive it, so it is not drawn; use a removed section to show the same cut face. These issues have no automatic fix. - **Turning the drawing.** Choosing another front view is refused with `SECTION_KIND` while a removed or revolved section is present. Change it to **Full** first. ## Detail views A detail view enlarges a small region of a view or a section: the parent's exact projection, clipped to a circle or rectangle and drawn at its own scale. Nothing is approximated except a section's hatch boundary. ![Detail B of a plate's hole at 5:1, at the sheet's top right; its circle and letter on the top view, and the DETAILS card with its scale](/shots/studio/drawings/detail-view.jpg) - **Adding one.** Choose **Circle** or **Rect** crop shape, then use **Detail view** (E): click the centre of what to enlarge on a front, top, right, or section view, then click to set its circle radius or rectangle corner. It takes the next free letter from B; A stays reserved for the front section. - **What is drawn.** On the parent, a thin boundary circle or rectangle and the detail's letter. The detail itself shows the parent's hidden lines and a section's hatch inside its boundary, named as `DETAIL B (5:1)`. - **Its scale.** **Auto** is the smallest standard scale at least twice the sheet's. Past 10:1 it is twice the sheet's. The **DETAILS** card lists each detail with its scale (which you can set up to `1000:1`), a button to open the numerical **Edit crop** editor in model mm (disabled while annotations or another sheet reference the detail), and a button to remove it. - **Its place.** It's laid out in the first free room from the frame's top right. Drag it anywhere in its square or use **Auto-place** to return to automatic placement. - **Dimensions and frames.** They work in a detail as in a view. Their values come from the model, so a detail's dimension reads the true size, not the enlarged one. - **Issues.** `DETAIL_PARENT_MISSING`, when its view or section isn't on the sheet, and `DETAIL_EMPTY`, when its crop holds nothing. Both are fixed by removing the detail with its annotations (or moving an annotated empty detail boundary). `DETAIL_NO_ROOM` has no automatic fix. - **The agent.** It sets them with `set_drawing`'s `details`, each `{ id, view, center, radius, shape?, width?, height?, scale?, at? }`. A list replaces the details, and `[]` clears them. A detail's parent, crop geometry (`center`, `radius`, `shape`, `width`, `height`) can't change while it has dimensions or frames. - **On another sheet.** A detail can be drawn on a different sheet than its parent (see Drawing sets below). - **Not yet:** jagged or freehand detail boundaries, centre and thread marks inside a detail, and a detail of a pictorial view (`iso`, `dimetric`, `trimetric`). ## Broken views A long part, such as a shaft or a bar, can be drawn with a band of its length left out, so the views fit the sheet at a larger scale. ![A 500 × 20 × 20 bar broken from X 100 to 400, drawn at 1:1 on A4 without the isometric view: its front and top views shortened, break lines at the gap, the length dimension reading 500](/shots/studio/drawings/broken-view.jpg) - **The BREAKS card.** **Add break** leaves out the middle third of the part's longest axis, in whole millimetres. Each break then has its axis and its two ends, in model mm, which you can change, and a button to remove it. A change that would reverse a break or make two meet on one axis is refused. - **A break is along a model axis, not a view.** It applies to every orthographic view whose horizontal or vertical axis it is, and to their principal sections, so the views stay in projection. A view looking along that axis, the isometric view and aligned sections aren't broken. - **What is drawn.** The band is left out and closed to a 6 mm gap. A thin break line, with a small zig-zag, crosses the view at each side of the gap. - **Dimensions across a break.** They read the true length, though drawn shorter. So does everything placed on the view: centre marks, datums, leaders and balloons. - **The layout.** Each scale is worked out with the breaks, so **Auto** takes the larger scale a broken part allows. - **Issues.** `BREAK_NO_VIEW` when a break shortens no view on the sheet; its fix removes the break. - **The agent.** It sets them with `set_drawing`'s `breaks`, each `{ axis, from, to }`. A list replaces the breaks, and `[]` clears them. - **Not yet:** breaks in the isometric view, the curved break symbol for round bars, and a break inside a detail. ## Dimensions and notes ![A sheet after Auto-dimension: overall sizes, the hole's position and its callout](/shots/studio/drawings/auto-dimension.jpg) | Key | Tool | How | |---|---|---| | V | Select | Click a dimension to select it, drag to move it; Delete removes it | | D | Linear dimension | Click two points or one straight edge, then where the dimension goes | | O | Diameter (Ø) | Click a circle, then where its diameter goes | | R | Radius | Click a circle or an arc, then where its radius goes | | A | Angle | Click two straight edges, then the side of their corner | | N | Note | Click the paper for a note, or a view for a leader | | T | Datum target | Point: click a straight edge endpoint. Line: click its two ends. Area: click its centre. Then place the target symbol | **Auto** under **Dimensions** (Auto-dimension) lays out the views with room, picks a scale and sheet that read cleanly, then adds the overall sizes, steps, hole positions and callouts. It replaces its own earlier dimensions and keeps yours. A dimension goes where both its ends are visible: in a section when the section shows more than the view. For authored drawing data, a dimension's `place` uses the view's model coordinates in mm. A note's `at` instead uses sheet mm, while its optional `leader.at` uses the view's model coordinates. Do not scale model coordinates to match the sheet: the drawing applies the view scale. A leader follows its view; a note's text position stays on the sheet. ### Hole callouts from parameter values For code that prepares drawing annotations, `holeCallout` from `@barocss/cad-model/drawing/callout` takes the document's model nodes, a current edge name, and an optional numeric parameter map. Pass `doc.parameters` when a hole radius or depth refers to a parameter. The same map resolves the radius and depth of a following counterbore. Omitting the map uses an empty map; it does not read parameters from the document automatically. The result is annotation text or `null`, not a measured dimension or a drawing update. Lengths are in model mm, independent of sheet scale. The text uses diameter, `THRU` or depth, and available pattern, thread, counterbore, and countersink information. Resolved hole and counterbore radii and depths are rounded to three decimal places before formatting; the diameter is twice the rounded radius. A non-hole edge, an unresolved required parameter, or a required hole or counterbore length that is non-finite or non-positive before rounding gives `null`. Very small positive lengths can round to zero; the text is not a geometry-validity check. ```ts import type { ModelNode } from '@barocss/cad-model/engine/doc'; import { holeCallout } from '@barocss/cad-model/drawing/callout'; // Supply the current document's nodes and doc.parameters, plus an edge name // selected from that same model. No feature or geometry is created here. export function currentHoleAnnotation( nodes: readonly ModelNode[], parameters: Readonly>, edgeName: string, ): string | null { const text = holeCallout(nodes, edgeName, parameters); if (text === null) return null; // Leave this edge without a hole callout. return text; } ``` ## Tolerances **Tolerancing** is **± dimensions** or **Geometric (datums, position)**. **Tolerance suggestions** proposes the tolerances the part needs, such as hole positions and fits; **Accept** takes one and **Accept all suggestions** takes them all. - A tolerance from your fit or fastener rows cites the row. - One without a row is an estimate and says so. ### Datum references and control frames A datum stores one edge reference or one face reference. A face reference keeps the exact face name, including its assembly occurrence prefix. Its `near` point selects the nearest current boundary vertex of that face. A missing or ambiguous face stays unresolved; the drawing does not substitute another face or reuse the old point. A datum target (ASME Y14.5 section 7.24) marks where a part touches its datum. Open **Datum targets**, choose a **Kind**, choose **Add point target**, **Add line target** or **Add area target** (or press **T**), pick in a base view, then click where the symbol goes. Each target has a datum letter (A to Z without I, O and Q) and a number from 1 to 99, unique per letter, such as A1. The symbol is a circle split by a horizontal line: the letter and number below, an area's size above. - **Point** marks one endpoint of a straight B-rep edge with an X (supporting up to `200` datum targets across the whole drawing, letters `A`–`Z` excluding `I`, `O`, `Q`, and numbers `1`–`99`). Click the endpoint; if endpoints overlap, choose the exact edge and endpoint in the list. Circle centres and curved edges are not supported. Use **Apply target label** to edit the letter or number (unique across all sheets), **Move symbol** to relocate the symbol, **Moveable symbol** under **Details** (point targets only; draws tangent lines facing away from the leader), or **Reselect endpoint** to confirm a new endpoint. A saved point target with no recorded endpoint, or a number above 99, says what to repair before other point fields can change. - **Line** is two distinct points clicked in a view (`front`, `top`, `right`, or `iso`), drawn as a phantom (two-dot chain) line in that view with no X marks (following ASME; the X belongs to a point target); the leader ends on the line. With the **ISO** drawing standard set it is drawn as ISO 5459 does: two X marks joined by a thin continuous line. Edit a line target's letter/number with **Apply target label** or its symbol placement with **Move symbol** (its fixed `from`/`to` endpoints stay intact; remove and re-add to place new view coordinates). - **Area** is a circle (**Ø**) or a rectangle (**Width**, **Height**), in model mm, centred on a clicked point. It is drawn with a phantom outline and 45° hatching at the view's scale; the leader ends at a dot inside it. Its size is the upper half of the symbol (`Ø6` or `6×4`). Edit the letter, number, and size (`d` or `w`/`h`) on the target's row and apply with **Apply target label**, or move the symbol with **Move symbol**. A point target records the endpoint and the current edge signature. If the edge changes, is missing, or cannot be identified, the saved target stays unresolved; it does not move to another edge or use the old hint as its point. Show its view and choose **Reselect endpoint** to confirm a current endpoint. **Move symbol** changes only the symbol's position. A line or area target is placed by view points, so it does not follow the geometry; the issue list warns (`DATUM_TARGET_OUTSIDE`) when one lies partly outside the part as its view shows it. The drawing does not count targets per datum; whether a datum has enough targets is yours to judge. A frame that names a datum letter held only by targets is not reported as `DATUM_UNDEFINED`. Each datum has an `id` and a letter. A geometric control frame has its own `id` and names its datums by letter. An attached frame refers to a dimension by `dim`; there can be at most one frame per dimension. A standalone frame instead has a view and a position in that view's model mm. In **Standalone geometric controls**, choose a visible view, select **Add standalone frame**, then click where the frame goes. **Frame details** edits its characteristic, tolerance and datums; the controls also let you move or remove it. If its view is hidden, the frame is kept at its saved position, is not drawn and cannot be moved, and `VIEW_NEEDED` says which view to show. Saved files and the SVG export keep the frame at its position in the view. Authored inputs require unique datum ids, datum letters and frame ids. These symbols and modifiers are annotations; they do not solve or verify the part's geometric tolerances. A frame can also carry a spherical zone (`sphere`, drawn SØ, position only), a statistical tolerance (`statistical`, ST in a hexagon), an unequally disposed profile (`unequal`, the outward amount from 0 up to the value, drawn as a circled U and the amount) and `around` (`all-around` or `all-over`, a circle or double circle beside the frame; profile only). A profile frame can have a `composite` second segment like position, or a `stacked` frame: a second, independent frame of the same position or profile characteristic, drawn as a full frame with its own symbol directly below the first. A frame is composite or stacked, not both. In the frame editor the options that fit the chosen characteristic are shown; the rarer ones (statistical tolerance, the unequal amount) are under **Details**, and the problem with the frame is written under the controls. New and edited frames must follow the rules that ASME Y14.5 and ISO 1101 share, and are refused in plain words when they do not: - Form tolerances (straightness, flatness, circularity, cylindricity) take no datums. Maximum or least material is allowed on straightness and flatness only. - Orientation (parallelism, perpendicularity, angularity), concentricity, symmetry and runout need at least one datum. - Runout takes no material modifier on the tolerance or the datums; profile takes none on the tolerance; circularity and cylindricity take none. - A diameter zone is for position, straightness, orientation and concentricity. Runout takes none. - A projected zone is for position and orientation. A tangent plane is for orientation and profile, and is not combined with a diameter zone or a projected zone. - A composite second segment names some of the first segment's datums in the same order and has a smaller tolerance. Only rules that ASME Y14.5 and ISO 1101 share are enforced. What one standard drops, such as concentricity and symmetry in ASME Y14.5-2018, is advice under the drawing standard setting (see [Drawing standard](#drawing-standard)). A frame is refused only for a rule break it did not already have, so an old frame can be repaired one field at a time. Frame numbers show as authored, up to 4 decimals. A saved drawing that breaks one of these still opens unchanged: `FRAME_RULE` lists each broken rule, with no automatic fix. `DATUM_UNDEFINED` also counts a point datum target set as defining its letter. ## Drawing sets (several sheets) A drawing is one sheet until you add more. **Add sheet** (the **+** after the sheet tabs along the bottom of the drawing) makes an empty Sheet 2, and a tab for each sheet switches the paper shown. Everything you do — dimensions, notes, Auto layout, issues — applies to the sheet shown, and each edit is one undo step. - Which view is on which sheet. Under **Sheets** (a closed toggle in the panel) each view, removed section and detail has a *Move … to sheet* list. The first sheet holds every view that no other sheet lists. A section that is not removed is drawn in projection with its view, so it always stays on its view's sheet. A section or detail you move nowhere is on its parent's sheet. A view lives on exactly one sheet. Ticking **Right view**, **Isometric view**, **Dimetric view**, or **Trimetric view** while on a sheet moves that view to the sheet shown. Up to `12` sheets are supported per drawing. - Annotations follow their view. A dimension, datum feature, datum target, frame or note with a leader is on the sheet of the view it belongs to. A note without a leader stays on the sheet it was made on (a deleted sheet's notes go back to sheet 1). In v1, tables (the revision table, BOM and other source tables) and the title block's fields are on sheet 1. Balloons and weld symbols are drawing-level settings, ticked from any sheet: balloons are drawn on the sheet of the first of the isometric, front, top or right view that is shown, each weld symbol on the sheet of the view a single sheet would show it in (the first of the front, top or right view that is shown and sees the joint; an isometric view carries none). A joint seen in no shown view is warned once, on sheet 1. - Each sheet has its own title block, with SHEET reading `n OF N` and its size. Sheets after the first use the basic block (a continuation block): the title block's fields and the revision table are on sheet 1 only. Sheet 1 also carries a sheet index table (sheet, name, size) while there are two or more sheets. A sheet with no standard view reads `AS NOTED` for its scale. - Each sheet is laid out on its own: its own size, its own scale and its own room for dimensions. Auto lays out each sheet in turn. A sheet's scale and size are its own (the first sheet's are the drawing's `scale` and `sheet`). - A detail or removed section on another sheet than its view. Its circle (or cutting line) stays on the parent's sheet with the letter and `SEE SHEET 2`; the detail or section is drawn on the other sheet with `FROM SHEET 1` under its name. Zone references are not used. - Export. Export PDF writes one file with a page for each sheet, each at its own size. Export SVG and Export DXF write the sheet shown (the file name ends `-sheet-2` when the drawing has several sheets). - Issues. The issue list names the sheet it is for. What is missing — a hole's size or position, a step, an overall size, a view a hole shows round in — is judged on the whole drawing, so a dimension on one sheet counts for a view on another. So are datums and given-twice dimensions: a frame on one sheet may name a datum defined on another, and a repeated datum letter or dimension is reported once. Only placement checks (off the sheet, overlap) run sheet by sheet. `SHEET_SET` (a warning) reports a sheet with no view on it, and what a file lists that the drawing does not have. - Delete sheet removes the sheet shown (not the first): its views go back to sheet 1, a detail or section to its parent's sheet, its notes to sheet 1. A sheet id that a note still names is not given to a new sheet. - Open. A file that lists a section or detail the drawing no longer has, or a section that is not removed, keeps the entry and the first sheet's issue list says so; the entry has no effect. - The agent. `drawing.set` (`set_drawing`) takes `sheets`, the sheets after the first: `{ id, name?, size?: A4|A3, scale?, views: [...] }` with view ids `front`, `top`, `right`, `iso`, `dimetric`, `trimetric`, `section:B` (removed sections only) and `detail:C`. The list replaces the sheets; `[]` returns to one sheet. A view listed twice, an id that is not a view, a section or detail the drawing does not have, and a section that is not removed are refused with `DRAWING_OPTIONS`, in words that name the sheet and the view. The tool's own description is only a short hint, so use `describe` on the tool for the shape above. - Not yet: tables and balloons on a later sheet, a sheet-1 entry in the list, reordering sheets, an all-sheets DXF, and a different title block on later sheets. Also `pdfTextMode` (`text` default vs `outlines`) selects between selectable Type 1 Helvetica PDF text (which prints unsupported glyphs as `?`) and outline strokes. ## Issues **Drawing issues** lists what the sheet is missing or gets wrong: a feature with no dimension, a dimension that was lost after a model change, a feature a section would show better. Each issue can carry a **Fix**. **Fix all issues** applies them all, and **Issue count** shows how many are left. `DATUM_LOST` reports a datum with no current anchor in a visible view. `DATUM_TWICE` reports a repeated datum letter. `FRAME_LOST` reports a frame whose dimension is lost or missing, and `DATUM_UNDEFINED` reports a frame that names a datum with no datum feature or point target set. `FRAME_RULE` reports a frame that breaks a rule above, or (a warning) one the drawing standard no longer has. `FRAME_VIEW_MISSING` reports a standalone frame whose view is missing; its saved position is kept. `TEXT_OVER_LINES` reports annotation text, such as a dimension's, a table's or a standalone frame's, that lies over drawing lines. `DATUM_TARGET_UNVERIFIED` reports a point target that needs its endpoint selected again. `UNIT_PRECISION` (a warning, no fix) reports a tolerance or frame value too fine to print in the drawing's unit even at the most decimals. `DATUM_UNDEFINED` has no automatic fix: define the datum or edit the frame. ## Tables and balloons The sheet can carry the tables that the part's features need: - **BOM table**, with **Balloons** linking each line to its parts; - **Weld list table** and **Weld symbols** for weldments; - **Cut list table** for frames; - **Bend table** for sheet metal; - **Gland table**, **Spring data table** and **Element list table** for those features. A table column's `unit` is a header label, not a conversion: supply numbers in the unit you name. Numeric cells use up to two decimal places by default, dropping trailing zeros. `digits` accepts an integer from 0 to 6 and requests that many decimal places; very large numbers can still use exponent notation. A `null` cell shows an em dash. Table positions use sheet mm with Y increasing downward; `corner` selects which table corner sits on `at`. These positions do not use model coordinates or the model's scale. ## Export - **Export SVG** and **Export PDF** write the sheet as shown. With several sheets (Drawing sets above) the PDF has every sheet; the SVG and the DXF are of the sheet shown. - **Export DXF** writes it as AutoCAD 2000 or R12, chosen in **DXF version**. R12 converts unsupported curve forms to polylines with a chord tolerance of 0.001 mm on the sheet. This is a drawing-export setting, not a model or manufacturing tolerance. If PDF export warns that some characters became `?`, review the notes and title block before sending the file. The warning appears after the PDF download; it does not cancel it. Use **Export SVG** to keep those characters. Check **Drawing issues** as well as the exported sheet. The issue list reports unresolved references separately from the marks drawn on the sheet; an exported file alone does not establish that every annotation is resolved. ### Drawing files from code Use the `StudioPart` facade to set up a drawing and get its files. This example makes a pin with an 8 mm diameter and a 30 mm length: ```ts import { part } from '@barocss/cad-model/api'; const pin = part('pin') .cylinder({ r: 4, h: 30 }) .material('steel') .process('cnc-turning') .drawingSettings({ title: 'pin', sheet: 'A4' }) .autoDimension(); const drawing = pin.drawing(); console.log(drawing.issues, drawing.pdfMissing); // drawing.svg and drawing.dxf are text; drawing.pdf is a Uint8Array. ``` `drawingSettings` and `autoDimension` return a new part. The default `autoDimension()` can choose the front view and change the sheet, scale and view layout to fit the dimensions. To keep the current sheet, scale and views, call `autoDimension({ layout: false })`. It adds dimensions to the current layout. Both options keep manually placed dimensions. Automatic component dimensioning is refused for assembly drawing scope with `DRAWING_SCOPE_AUTO`. `pin.drawing()` is synchronous and returns the same fields as `drawingOf(doc)` from `@barocss/cad-model/api/outputs`: | Field | Result | |---|---| | `sheet` | The drawing report's sheet data | | `issues` | Issue records with `code`, `severity`, `message` and an optional `fix` | | `svg` | SVG file text | | `dxf` | AutoCAD 2000 (`AC1015`) DXF file text | | `pdf` | PDF file bytes as `Uint8Array` | | `pdfMissing` | Characters the PDF font cannot show; these print as `?` | The function does not download files or change the document. Check `issues` and `pdfMissing` before writing these files. It has no DXF-version argument; the Studio's R12 choice is separate. Drawing-input refusals throw `BarocssError`, preserving a reported bracketed code or using `DRAWING` when none is present. An issue in a returned report does not by itself mean the export was refused. --- # BOM and quotes ## The bill of materials ![The bill of materials for a shaft and its key: the part made, the key bought](/shots/studio/bom/bom.jpg) **BOM** in the top bar opens the bill of materials of the part or the assembly. - **Lines.** Each line has an **Item**, a **Qty**, the **Row** it came from and its **Source**. - The placed parts' lines come first, then the bought elements: fasteners, bearings, O-rings, rings and the like. - Bought elements are merged over copies by kind, size and row, so four M6 screws are one line of 4. - A placed fastener is a bought line of its own. - **Bought or made.** Every element line can be marked bought or made. Made elements are listed under **MADE ELEMENTS**. The choice is one undoable change. - **Estimates.** A line with no row behind it says **estimate**, so you know which numbers are not yet from your shop data. - **Separate pieces.** A body made of separate pieces that only touch along an edge or a point shows its count under **Lumps**. - **Totals.** The totals line counts the parts and bought elements and adds up the parts' mass. - **Purchase list.** **Export purchase list** downloads the bought lines as CSV. Tick **With made parts** to add the made parts. Placed parts with the same shape and material share a line; **Qty** counts their occurrences, not their faces or display triangles. The BOM lists the current document's placed parts. Do not treat that list as a recursively expanded purchase list for every child of a nested assembly. The default purchase CSV also includes library catalogue parts. **With made parts** adds made part lines and the made element list; it does not change their bought/made settings. CSV item numbers retain their BOM line numbers, so the filtered purchase list can have gaps. It is a quantity and sourcing list, not a price calculation. ## Masses Each part's mass is its volume times its material's density. The kernel integrates the volume exactly when it can. When it has to work from the display mesh, for example on some freeform bodies, the body's properties say **From the mesh** with the volume's error bound. The BOM's and the quote's masses then carry that bound and are marked as estimates. An element line's mass is already included in its part's mass. Do not add every displayed line mass together to recalculate the total. An unknown mesh mass bound remains unknown, rather than zero. If weld-bead accounting is incomplete, the reported mass is a subtotal of valid bodies; it is not a complete welded-part total. ## Quote package **Quote package**, in the library panel, downloads one zip for a supplier: - the part as STEP; - its manufacturability report; - the request: material, finish, pull direction and quantity. It contains no price. What is still open, such as a missing row or an unknown rule, is said in the request rather than left out. This package is for an injection-moulding request. Read `manifest.json`: `open` lists missing inputs, failed or unknown checks and a STEP export failure, and `complete` is true only when that list is empty. A ZIP can therefore be written while the request is incomplete, and can omit `part.step` if STEP export fails. A complete package is still a request for a supplier's quote, not manufacturing approval. Right after an edit, while the part's masses are still being worked out, it isn't written yet: export again in a moment. --- # Manufacturing A part is checked against the process you choose. Rules use the model's geometry and measurements; some printing checks also use its mesh. A check says what it cannot judge instead of passing it. ## Choosing the process Open **Library** and set **Process**: - injection moulding; - 3D printing: FDM, resin (SLA), powder-bed sintering (SLS), multi-jet fusion (MJF); - CNC milling and CNC turning; - die casting and sand casting. With no process chosen, the rules are unknown. Printing also takes a **Printer**, from generic FDM, SLA, SLS and MJF build volumes. Moulding and casting take a **Pull direction**, and moulding takes a **Mould finish**, which sets the least draft. Choose a material as well: machining uses its family to select wall limits, and missing material leaves those rules unknown. For printing, choose the build direction and printer before judging orientation and bed fit. The report names missing inputs; a generic printer profile is not a measurement of your machine. ## The manufacturability report Ask the agent to check the part. Its manufacturability query gives the report for the chosen process, for example "check this for milling". The report gives each rule `pass`, `warn`, `fail`, `unknown` or `n/a`, with the faces or features it is about: `pass` means that rule meets its stated limit. `warn` marks an unmet recommendation; `fail` marks an unmet feasible limit. `unknown` means required information or a measurement is missing. `n/a` means the rule does not apply. Read the rule's value, limit, source and reason before deciding what to change. | Process | What it checks | |---|---| | CNC milling | Material, wall, size; holes (depth, size, threads deeper than 3 × d warned); pockets' inside corners against the tool radius; which faces each of the six directions reaches, and the setups; stock from your stock rows | | CNC turning | Every surface turned; a milled feature on a turned part warned for live tools | | Injection moulding | Draft on every side face, from the exact surface; undercuts and the side actions that free them; ribs and walls; sharp inside corners; the parting line, with the mould's two halves and shut-offs | | Die and sand casting | Wall, draft, tolerance and section changes against your casting rules; hot spots for the gate you choose; for sand casting, the pattern's shrinkage scale and machining allowances | | 3D printing | On the printer you chose: fit on the bed, overhangs, walls, holes (horizontal ones too), gaps, bosses, tips, warping, enclosed cavities, and pieces that only touch | Casting needs your casting rules (see [Shop rows](/studio/rows)). Without them, every rule that reads a limit or an allowance is unknown, and a sand pattern is refused. ## Previews in the viewport ![The CNC preview at the end of a pocket's program, NOT FOR PRODUCTION at its top](/shots/studio/manufacturing/cnc-preview.jpg) The dock's **Preview & analysis** section shows one preview at a time: **CNC**, **Print**, **Clearance** or **Analysis**. See [Display, sections and analysis](/studio/display#preview-analysis). - **Analysis** colours the model with a map: wall thickness, draft or 3-axis access, with a legend. The maps draw only with WebGPU. ![The wall-thickness map on a moulded plate, with its legend (WebGPU)](/shots/studio/manufacturing/thickness-map.jpg) - **CNC** steps through the milling program's moves for a pocket from its stock: - **Setup**; - a **Progress** slider with **End**; - **Grid**, the pitch it removes material on; - **Set tool**, the tool's shape and size. It opens with `NOT FOR PRODUCTION` and shows material removal and overcut. It is a display estimate, with no G-code, feeds, speeds or collision check. - **Print** slices the part into its layers: - **Direction**; - **Set height** for the layer height; - a **Layer** slider; - **Printed up to layer**; - **Supports**. The settings are saved with the document. ![Print layers on the same plate: the layers drawn, with the Print layers panel](/shots/studio/manufacturing/print-layers.jpg) - **Clearance** and the 3D annotations are in the same section; see [Display, sections and analysis](/studio/display). ## Preparing a print **Hollow for printing** shells a part to a wall thickness with a drain into each cavity. **Fill with a lattice** fills the cavity with a gyroid lattice as a separate mesh body. **Split to fit the bed** cuts a part too big for the printer into pieces joined by dowels or plugs. **Export 3MF** writes the bodies, materials, colours and print orientation for a slicer. Writing a 3MF file does not run or pass the manufacturability report. Check the report separately before sending the file to the slicer; exported bodies and orientation do not certify the print settings or machine program. ## CNC skipped operations and tool refusal diagnostics In the CAM preview, any machining operation that cannot reach a pocket, exceeds flute length, or violates tool clearance is surfaced explicitly with its skipped reason rather than silently omitted from the toolpath. Stock and overcut overlays render with depth-bias separation so coplanar inspection faces stay crisp while orbiting. ## Quote package **Quote package** in the library panel downloads the part as STEP, its manufacturability report and the request (material, finish, pull and quantity) in one zip. See [BOM and quotes](/studio/bom). This package is for injection moulding. It can contain open items, including missing request inputs, failed or unknown rules, or a failed STEP export. Read the package's `open` list and `complete` flag; a downloaded zip alone does not mean the request is complete. How these checks are computed, step by step: [Machining, printing and moulding checks](/how/manufacturing-previews). --- # Shop rows ## Why sizes come from your files BaroCSS has no standards built in: no thread table, no fastener catalogue, no bearing list, no casting allowances. Sizes like these depend on the edition of a standard and on what your supplier stocks. A design built on numbers nobody supplied can't be trusted. So these sizes come from **rows**: JSON files that you supply, each value naming where it came from, or saying it is an estimate. - **The person loads them.** Rows are loaded only from a file a person supplies, in the studio or attached in the chat. The agent can suggest a file, but rows it wrote itself are refused with `[ROWS_NOT_FROM_PERSON]`. - **A receipt is kept.** Every loaded row keeps a receipt naming its file. - **Placed parts inherit them.** A placed part uses the rows of the document it is placed in. - **Rows in use stay.** A row something uses stays loaded. A frame section row, when edited, moves every frame built on it. - Removing a ring, O-ring, bearing, connector, drive or mount row that a feature uses is refused with `[ROW_IN_USE]`, for example `[ROW_IN_USE] ring row R1 is used by a retaining ring: remove the ring first`. - Removing a row that isn't loaded is refused with `[ROW_UNKNOWN]`. ## Row kinds | Kind | What it gives | Used by | |---|---|---| | `fastener-sizes` | Metric thread sizes: pitch, head and nut sizes, washers, the lengths offered, clearance holes and the tap drill | Tapped holes, **Fastener**, thread callouts, hole position tolerances, machining holes | | `fasteners` | Bought screws, bolts, nuts and washers as your supplier lists them | The BOM's bought lines | | `casting-rules` | Die and sand casting limits by alloy (least wall and draft, tolerance, section change) and sand casting's pattern allowances | The casting report and the sand pattern | | `sections` | Frame sections by their dimensions | **Frame**, **Structural member** | | `frame-stock` | Stock lengths for frame members | The cut list's nesting | | `stock` | Stock blocks for machining | The CNC report's stock choice | | `fits` | Fit tables: tolerance classes and their limits | **Fit class**, **Fit pair**, fit callouts on drawings | | `bearings` | Bearings: bore, outside diameter, width, shoulder limits | **Bearing** and its housing | | `orings` | O-rings | **O-ring gland** | | `rings` | Retaining rings | **Retaining ring** | | `drives` | Belts, chains and their wheels | **Pulley**, **Sprocket**, **Belt or chain** | | `connectors` | Connector openings | **Connector opening** | | `bend` | A sheet-metal bend table | A sheet part's bends | | `mounts` | How motors, servos and bearing units fix to a face: bolt pattern, pilot, shaft and its height | **Mount** | ## Loading rows in the studio ![The library with the sample fastener sizes loaded](/shots/guide/getting-started/library-rows.jpg) **Library** lists each kind with what is loaded, for example **Fastener sizes** with the sizes it holds. Load your own file there. Two kinds ship with samples you can load in one click: **Load sample fastener sizes** and **Load sample casting rules**. Mount rows can't be loaded in the Library yet: attach them in the chat. The samples are in `@barocss/cad-model` at `samples/rows/`: - `fastener-sizes.json`: metric coarse M3 to M12, with the fields not cross-checked listed in `unchecked`; - `casting-rules.json`: die and sand casting rules, each with the page it was read from. - `mounts.json`: mounts. - NSK's UCP204 pillow block and UCFL204 flange unit, from the maker's product pages. - NEMA 17 and NEMA 23 stepper flanges, as estimates with every field `unchecked`: their makers' dimension drawings are PDFs that haven't been read yet. - There's no servo row, since no maker's dimensioned mounting drawing was found to cite. They are examples taken from the sources each row names, not a standard. Check them against your supplier before you use a part for manufacture. ## Loading rows in the chat Attach the file to your message and ask the agent to load it. The agent's `load_rows` action takes the kind and the file from your conversation. ## Without rows A command that needs a row it doesn't have is refused with the row it is missing: - `[FASTENER_SIZE_ROW] no row for M6 — load your fastener sizes …`, for a tapped hole, a fastener or fitting a fastener to a hole; - `[CASTING_RULE_ROW]` in a casting report, where every rule that reads a limit or an allowance is `unknown` and a sand pattern is refused. A reading that only shows something carries on, and says what it lacks: no thread is drawn, no tap drill is given, and the position tolerance is an estimate. --- # Inspect a model and make an image ## Goal Inspect the model with display modes, sections and previews. Choose a live raster image or a frozen path-traced still when you need a picture. Keep the editable model and any report separately from that picture. ## Before you start - Have a part or assembly open in the viewport. - Decide whether you need an inspection view, an analysis preview or an image file. - Use WebGPU for Render, analysis maps and path tracing. - Keep a saved model copy if the result must remain editable. On WebGL2, unavailable maps are disabled with a reason. The Render panel explains that rendering needs WebGPU. ## Inspect the live model 1. Open Display and choose CAD display mode. Use shaded surfaces, visible edges, hidden lines, wireframe or X-ray as needed. 2. In an assembly, use Isolate selection to fade the other parts. Use Restore view to bring them back. 3. Turn on Section view to inspect the inside. Choose the section mode, then adjust a plane offset or its handle. The section changes the view; it does not cut the model geometry. 4. Use Preview & analysis for one preview at a time. Select CNC, Print, Clearance or Analysis for the task. Read a map's legend and any unavailable-feature message. 5. Return the preview switch to None when you no longer need it. ![Existing Display example: a section plane reveals a box and its hole](/shots/studio/display/section.jpg) This image is reused from the Display guide. It shows a section view, not a new analysis result. ## Choose the image workflow 1. Open Render and set the appearance, lights, background and camera. These settings change the picture, not the model geometry. 2. For the current live view, select Raster as Render method. Pause playback and choose the view, then use Export image to download a PNG. Export image does not pause the timeline for you. 3. For a frozen still, select Path tracing and then Start. Wait for at least one sample before using Export image. Stop ends sampling; Denoise still controls noise reduction for preview and export. 4. After camera or scene edits, stop sampling and select Start again. The new session uses those edits; the previous still does not update with them. ## Check the results - Confirm which display mode, section and preview are active. - Check that a map is available on the current renderer. - Confirm Render method before downloading an image. - With Raster, inspect the live view that you chose. - With Path tracing, inspect the sample count and the frozen still. - Keep the model revision and animation time separately if you need that context. The frozen still includes surfaces, materials, tone mapping and colour grading. Bloom, depth of field, outlines, overlays and shadow catchers stay in the live view. Do not expect the frozen still to reproduce those live effects. ## Keep these limits in view A section view is not a manufacturing cut in the saved geometry. A CNC preview is a display estimate marked NOT FOR PRODUCTION. It has no G-code, feeds, speeds or collision check. An image does not keep feature history or establish manufacturing or physical validation. Focus and blur are display effects, not physical camera calibration. The PNG has no document revision or animation time written by this export path. ## Continue with the detailed guides - [Display modes and sections](/studio/display) - [Preview and analysis choices](/studio/display#preview-analysis) - [Live rendering and raster export](/studio/rendering#exporting-an-image) - [Frozen path-traced stills](/studio/rendering#path-tracing) - [Focus and blur](/studio/rendering#focus-and-blur) - [Manufacturing preview limits](/studio/manufacturing#previews-in-the-viewport) - [Save and export model files](/studio/files) --- # Display, sections and analysis Everything on this page changes how the model is shown, never the model itself. Its controls are: - **Display**, the popover on the view bar; - the view bar's other buttons; - the dock's **Preview & analysis** section. ## Display modes ![The Display popover: the CAD display mode and Isolate selection](/shots/studio/display/display-popover.png) **CAD display mode** sets how bodies are drawn: | Mode | What you see | |---|---| | Shaded with edges | Shaded surfaces with their edges and curved-face silhouettes | | Hidden lines removed | Only the visible edges, as on a drawing | | Hidden lines dashed | Visible edges, and hidden ones dashed | | Wireframe | Every edge, seen through | | X-ray | See-through surfaces, so you can see inside an assembly | In an assembly, **Isolate selection** fades everything but the picked parts. **Restore view** brings the rest back. You can also set per-body opacity, mark pass-through ghost parts so pointer picks reach geometry behind them, isolate context around a target component, and peek/restore hidden or ghosted occurrence bodies directly under the cursor. Other view settings: - **Ortho** switches between perspective and orthographic projection. - **Toggle light or dark theme** switches the colour scheme. - **Ambient occlusion** shades the corners. - **Selection filter** chooses what a click picks: anything, or only faces, edges or whole bodies. - **Snap** sets the step that sketch points, placing and moves land on: 1, 0.5, 0.1, 5 or 10 mm, or off. ## Sections ![A box with a hole cut open by one section plane, its cut faces hatched, the Section bar below](/shots/studio/display/section.jpg) **Section view** cuts the part open to see inside. The model isn't changed. - **Section mode** is **Plane**, one plane along X, Y or Z, or from a flat face you click; **Box**, six planes with a handle on each face; **Planes**, two or three planes; or **Cut-out**, a corner taken out. - **Add a section plane** adds one. Each plane's offset can be typed, or dragged by its handle. - The kept region is where every plane's kept side meets. With two or three planes it can be a cut-out instead: the corner where their cut-away sides meet is removed. - **Reset the section box** puts the box a tenth in from each face of the part. - Cut faces are capped. **Hatch the cut** draws hatch lines on them, each part's at its own angle. - **Sketch the section** copies the visible cut outlines onto a single plane. **Section outlines** defaults to **All**. For a cut through one solid with one outer loop and up to two holes bounded by lines or circular arcs, choose **Outer only** to copy its perimeter or **Inner only** to copy its hole boundaries. The copied hole boundaries become independent closed contours that you can extrude. If the cut has no holes, **Inner only** keeps the section open. Review the sketch and choose **Finish sketch** to add it to the part. ## Preview & analysis The dock's **Preview & analysis** section shows one preview on the model at a time. Its switch is **None**, **CNC**, **Print**, **Clearance** or **Analysis**: - **The switch turns the preview on.** Only the chosen preview's settings show under it. - **None** shows a one-line hint. ![The Preview & analysis section with Analysis chosen: its Surface and Map choices](/shots/studio/display/preview-analysis.png) The previews are: - **CNC** and **Print**: see [Manufacturing](/studio/manufacturing). - **Clearance**: see [Assemblies](/studio/assemblies). - **Analysis**: below. ### Analysis ![Zebra stripes on a filleted box](/shots/studio/display/zebra.jpg) - **Surface:** **Zebra** stripes or a **Curvature** map, for judging how smoothly faces meet. **Overhang** appears for a part with a printing process. - **Map:** a coloured map with a legend that reads the value under the pointer. - The maps are **Thickness**, **Draft**, **Access**, **Parting** and **Halves**. - **Draft**, **Parting** and **Halves** appear for a part with a pull direction. - The maps draw only with WebGPU. On WebGL2 they are disabled, with the reason. - **The view bar.** **Analyse** and **Maps** step through the same choices. - **Turning it off.** With no surface analysis and no map, the Analysis preview turns off. | Map | Colours | |---|---| | Thickness | Wall thickness: thin red, nominal green, thick orange, past the thick-section limit purple | | Draft | Under the least draft red, positive green, negative blue, isoclines white | | Access | The share a 3-axis mill doesn't reach, in red | | Parting, Halves | The mould's parting line, then its two halves spread apart | ### 3D annotations **3D annotations**, a toggle at the right of the section's header, shows the drawing's dimensions and notes on the model, over any preview but the print and CNC previews. Clicking one picks what it dimensions. They show only in the Model workspace, and not while an edit is under way, such as a sketch or a running command. ### Persistent named inspection views Named inspection views (including saved camera framing, display mode, named section views, and WebGPU surface analysis modes such as Zebra stripes, Draft angle, and Curvature) persist directly inside the `.bcad` document across Save and fresh Open. Restoring a saved inspection view returns to the exact inspection state without modifying part geometry. Surface shaders and analysis maps are decoupled so you can inspect Zebra/Curvature shading independently of thickness or draft overlays. ## Frame cost For diagnosing slow scenes, the viewer can count each body's draw work per display mode: draw calls, triangles, lines and render passes. This isn't shown in the interface yet. Counts aren't comparable between WebGPU and WebGL2, because the two draw curved-face silhouettes differently. --- # Rendering The **Render** workspace sets how the part looks in a picture: its appearances, the lights, the background and the camera. It can also add props and animate the part. - **The model doesn't change.** The settings are saved in the document, but they aren't part of its revision. - **WebGPU only.** It draws with the studio's WebGPU viewer. On WebGL2 the panel says rendering needs WebGPU, and the view stays the modelling look. Click **Render** in the top bar to open it. The **Render** panel, in the dock, has four tabs: **Appearance**, **Lights**, **Scene** and **Source**. ![The Render workspace: the part in a brass appearance, the Render panel in the dock and the timeline under the viewport](/shots/studio/rendering/appearance.jpg) ## Path tracing Use **Render method** to select **Raster** or **Path tracing**. Path tracing requires WebGPU and creates a frozen still. 1. Select **Start**. The panel shows **Preparing still…**, then the sample count. 2. Select **Stop** to stop sampling. To use camera or scene edits, select **Start** again after sampling stops. 3. Use **Denoise still** to switch noise reduction on or off for the preview and export. 4. After at least one sample, select **Export image** to download the frozen still as a PNG. 5. Session render shots are stored in the Render Shots strip, where a wipe-slider Render Compare overlay lets you compare any two renders side-by-side in place. Camera and scene edits continue in the live view. They do not update the current still; **Start** creates a new session. The still includes surfaces, materials, tone mapping and colour grading. Bloom, depth of field, outlines, overlays and shadow catchers stay in the live view. For the GPU API and its limits, see [Progressive still images](/packages/gpu/#progressive-still-images). ## Appearance An appearance applies to the selected bodies. With none selected, it applies to every body without its own. - **Preset:** a ready look such as **Aluminium**, **Steel** or **Brass**, or **Custom**. - **Colour**, **Metallic**, **Roughness** and **Opacity**. - **Two-sided**, for open or thin shells seen from inside. - **Texture:** an image multiplied into the colour. - **Repeat every** sets its size in mm. - **Cut out below** leaves out what is under an alpha value, for holes, leaves or grilles. - **Finish:** the marks a process leaves on the surface: **Cast**, **Sand-cast**, **Machined**, **Turned**, **Brushed**, **Knurled** or **Bead-blasted**. - **Marks** sets their size and **Depth** how strong they are. - **Along** sets their direction, X, Y or Z, for the finishes that have one. - **Clear coat**, a lacquer over the colour, and **Oil film**, an oil's tint on the reflections, from 0 to 1. - **Shader:** one of the materials written on the **Source** tab. - **Use the default appearance** removes a body's own. An appearance is a look, not a material: a body's mass comes from its material, set in the modelling workspace. ## Lights, environment and tone mapping - **Lights.** **Add sun**, **Add point** and **Add spot** add lights. - A sun has **Azimuth** and **Elevation**. - A point or spot light has a position, and a **Range** over which it fades. A spot also has a **Cone**. - Light positions, **Range** and **Shadow radius** use CAD mm: 1 mm is passed to the GPU scene as 1 world unit. Point and spot **Intensity** is scaled for the scene size, so its value is not the raw GPU intensity. - Every light has **Intensity**, **Colour** and **Shadow**. Use **Shadow** to turn its shadow on or off. - A point or spot light also has **Shadow radius**, in mm. Enter `0` for the default edge or a larger value for a softer shadow. Turning **Shadow** off keeps the saved radius. Entering a radius does not turn **Shadow** on. An unset radius shows **Default (0 mm)**. Clearing the input shows an error and does not save `0`; press **Esc** to restore the saved value. - Shadows use the first four sun lights, the first four spot lights, and at most one of the first eight point lights. Count the order separately for each kind. To move a point shadow, turn the current point's **Shadow** off, then turn it on for another point in that group. **Intensity** `0` does not free that shadow slot. See [GPU light and shadow limits](/packages/gpu/#light-and-shadow-limits). - If shadow validation rejects a radius or a second point shadow in that group, the panel shows an error and keeps the accepted light settings. - **Shadows.** A sun shadow uses a fixed light size of about 3°: sharp at the foot of what casts it and wider and lighter farther off. Contact shadows darken the creases and the places where parts meet, which the shadow map is too coarse to show. The sun size and contact shadows have no separate controls; the modelling look is unchanged. These controls describe live raster shadows. An existing frozen still does not change. Use **Start** to create a new session; see [Path tracing](#path-tracing). - **Scene.** - The background's **Top** and **Bottom** colours, and the **Ambient** light. - **Studio** lights the part: **Sky and ground**, **Softboxes** or **Cyclorama**. **Environment** takes an image instead, an equirectangular one with its top row overhead. - **Environment strength**, for a studio or an image. - **Occlusion**, **Ground**, **Grid** and **Edges**. - **Post.** - **Exposure**. - **Tone map**: **Filmic (ACES)**, **Soft highlights (AgX)** or **None**. - **Grade**: **Neutral**, **Warm studio** or **Cool daylight**, with **Contrast**, **Saturation** and **Vignette**. - **Bloom** spreads light from bright areas past their edges, as a glow. The slider controls its strength; 0 turns it off. The glow is added before tone mapping, so bright reflections can bloom while the surface stays unchanged. ![The Lights tab](/shots/studio/rendering/lights.png) ![A post on a plate in the Render workspace: its shadow dark at the foot and softer and wider farther off, and the crease where it meets the plate darkened](/shots/studio/rendering/shadows.jpg) ![The Scene tab: the background, the ambient light, the Softboxes studio, its strength and the view toggles; under Post, exposure, tone map and grade](/shots/studio/rendering/scene.png) ## Camera - **Save this view** keeps the camera with the document, and **Go to saved view** returns to it. - **Field of view** sets the lens. ### Focus and blur Under **Camera**, **Focus distance** sets a positive distance along the camera's view axis, in mm. **Blur radius** sets the maximum blur in CSS pixels, from 0 to 24. A value of 0 keeps the focus setting but turns the effect off. Changing these settings changes the displayed picture, not the model geometry. Choose **Pick focus on part**, then click a surface to set its focus distance. A background click cancels the pick. Choose **Cancel focus pick** to cancel it explicitly. Focus picking requires WebGPU. On WebGL2, the focus and blur settings remain saved, while the panel explains that the effect needs WebGPU. The saved Model field is `render.environment.post.depthOfField: { focus, blur }`. It requires a finite positive `focus` and a finite `blur`; the reader clamps blur to the 0–24 range. This is a display effect, not a physical camera calibration or a change to measurements. ![View-axis focus depth is 80 mm while eye-to-point distance is 100 mm; blur is a separate CSS-pixel value](/diagrams/focus-distance.svg) [Open the focus diagram at full size](/diagrams/focus-distance.svg). ## Props and materials The **Source** tab holds two texts, both in the language of [@barocss/gpu](/packages/gpu/): - **PROPS · CSS SCENE**: objects placed round the part, such as a plinth. - **Unit** scales them. - **Apply props** shows an edited source, and **Example** fills in a sample one. - A source with an error is reported, and the last good one stays. - **MATERIALS · @SHADER**: `@shader` materials, each a colour expression with its uniforms. **Add material** starts one. ![The Source tab: the props and the materials](/shots/studio/rendering/source.png) ## Timeline and turntable The timeline animates the bodies: - **Time** scrubs and plays; **Duration** sets the length. - **Turntable** turns the camera round the part. - For a selected body, **Set key** keeps its offset at the current time. A key can be jumped to or removed. Time and duration use seconds; body offsets use mm. Positions interpolate linearly between keys and stay at the first or last offset outside their time range. Turntable changes the camera view. These are authored display motions, not gravity or contact solver results. Their playback does not establish physical behaviour; see [Experiment evidence](/reference/verification#planned-experiment-evidence). ![The timeline: play, the time and its length, and Turntable](/shots/studio/rendering/timeline.png) ## Exporting an image With **Raster** selected, **Export image** uses the live viewport. The workflow below describes that raster export. With **Path tracing** selected, the same button downloads the current frozen still; see [Path tracing](#path-tracing). **Export image**, the camera button on the Render panel, downloads the view as a PNG. It needs WebGPU. The PNG records the displayed view, including its appearance and camera. Keep the editable `.bcad` document and any analysis results separately: an image does not carry the model history or establish manufacturing or physical validation. See [Files and exports](/studio/files). Pause playback and choose the view before exporting a still. **Export image** does not pause the timeline for you or write a document revision or animation time into PNG metadata. Keep that context separately if you need it. Turntable camera orbits are evaluated deterministically from timeline time across both continuous playback and direct scrubbing, so seeking back to a timestamp reproduces the exact same framing. The PNG export has no explicit preparation-cancel or stale-design check like the STL export. ### Pixel data, PNG and the download The GPU viewer's `capture()` draws a frame and returns `{ width, height, data }`. `data` is a new `Uint8Array` of RGBA bytes, with rows from top to bottom. It is not PNG file data. Width and height use the canvas's backing pixels, which can differ from its CSS size; neither is a model distance in mm. | Step | Result | Who writes the file? | |---|---|---| | GPU `capture()` | Raw RGBA pixels, `width × height × 4` bytes | No file is written | | Studio PNG conversion | `Blob` with type `image/png` | No file is written | | Studio **Export image** | Downloads `.png` | The app requests the browser download | For example, a 640 × 480 backing canvas returns 1,228,800 raw RGBA bytes. This is a size calculation, not a measured capture; PNG compression gives a separate file size. If the viewport has no capture support, it returns `null` and the app shows **Could not export an image**. A rejected GPU readback or PNG conversion is a separate error, not a `null` image or a successful empty file. Code that calls `capture()` must handle a rejected promise; the Studio path does not turn every such error into that same message. The raw capture reply has no frame ID, timeline time or document revision field. ![Raw GPU pixels are encoded as a PNG Blob before the Studio requests a file download](/diagrams/capture-png-flow.svg) [Open the capture flow at full size](/diagrams/capture-png-flow.svg). --- # Save a model and share its outputs ## Goal Keep an editable model and prepare the files that another application needs. Use project versions to keep past document states. Keep export source records beside the files they describe. ## Before you start - Decide where to keep the editable `.bcad` document. - Check the file formats accepted by the receiving application. - Keep the original exchange file before importing or repairing it. - Check the units of mesh files before using their dimensions. A saved model, an exchange export, a source record and a project version serve different purposes. Do not use one as a substitute for all the others. ## Save or open the model 1. Use Save to keep the model as `.bcad` with its editable history. Without a project, Save downloads the file. With a project open, Save writes into that project. 2. Use Open to read a supported model or exchange file. STEP opens as imported geometry, not the source system's feature history. STL and OBJ open as mesh bodies after you choose Mesh units. 3. Review any mesh repair before applying it. Save the imported result as `.bcad` to keep edits made in Studio. This does not recover the original application's feature history. ## Prepare an exchange export 1. Choose the format for the recipient: STEP, IGES, STL or 3MF. Use the format guide to check what each file retains. 2. For STEP with mesh bodies, review the representation dialog. Confirm that the recipient can read AP242 tessellated faces when selected. 3. For STL, wait for evaluation and correct evaluation errors first. Choose a quality, read the export message and keep the `.source.json` sidecar. Use Automatic for mesh bodies; explicit quality is refused for those bodies. 4. Confirm the STL scale in the receiving application. Its coordinates follow millimetres, but the STL file stores no unit. 5. After a document change, export again for that document revision. Keep each source record beside the exported files it names. ## Keep and compare project versions 1. Open Project & versions and choose a project location. Open folder uses a disk folder in supported browsers. Keep in this browser uses that browser's storage only. 2. Use Make version to save the document and keep that state. Use Compare to inspect changes from a version to the working document. 3. Use Restore to bring a version back as the working document. A later Make version adds a new version; it does not delete the earlier ones. ![Existing Projects example: a saved version compared with the working document](/shots/studio/projects/compare.jpg) This image is reused from the Projects guide. It illustrates version comparison, not a new check of file compatibility. ## Check the results - Keep the editable `.bcad` file as well as the exchange output. - Read export warnings and check the format and scale in the receiving application. - Keep STL source sidecars beside the STL files. - Check whether Save downloaded a file or wrote into the open project. - Use the project version list to find the state that you intended to keep. ## Keep these limits in view A source record identifies the input revision and its canonical-content SHA-256. It is not a checksum of the exported file's bytes. An exchange file does not replace the saved document's history, mates and settings. Browser recovery is temporary local storage, not a substitute for saving. If a project file changed elsewhere, Save refuses to overwrite it. Open it again, or save under another name. A downloaded file alone does not establish manufacturing approval. ## Continue with the detailed guides - [Model files and supported imports](/studio/files) - [STEP mesh representation](/studio/files#choose-how-step-writes-mesh-bodies) - [STL preparation and quality](/studio/files#choose-an-stl-quality) - [Source revisions and records](/guide/concepts#revisions-and-sources) - [Project locations and versions](/studio/projects) - [Drawing files](/studio/drawings#export) - [PNG images and frozen stills](/studio/rendering#exporting-an-image) --- # Files and exports ## The .bcad document **Save** writes the part as a `.bcad` file. It holds the model's history, so it reopens editable. A document with no mesh blob references is written as plain JSON. This includes older documents with mesh arrays stored inline. When a document references mesh blobs, Save writes a binary container, `BCADPACK`, with the document and the referenced arrays. Each blob is named by its SHA-256, and the name is checked when the file is read. Both kinds open. The file reader reads schemas 3 and 4 after checking the file. When **Open** fills missing fields, **Opened an older model** lists the changes. The file stays unchanged until you save. An older or newer schema or unknown feature is refused. This does not guarantee compatibility between all unreleased versions. See [Document schema](/reference/document#schema-version). Keep a `.bcad` copy for later edits. Use an export for the receiving CAD system or slicer; it does not replace the saved document's feature history, mates and settings. With a project open, **Save** writes into the project's folder instead of downloading, and you can keep versions of the part. See [Projects and versions](/studio/projects). ## Opening files **Open** reads: | File | Opens as | |---|---| | `.bcad`, `.json` | The part, with its history | | `.step`, `.stp` | The exact solids, one body for each solid. The toast says the file's length unit; a file that declares none is read as millimetres. | | `.stl`, `.obj` | A mesh body. You first choose the file's unit in **Mesh units**. | | `.igs`, `.iges`, `.barocad` | Curves and surfaces you can edit directly | | `.dwg` | Refused: **DWG files are not read** | A file that can't be read leaves your part unchanged. A file whose extension Open doesn't read, such as another program's `.cad`, is refused as **Can't open** with its name, and the toast lists what Open reads. A file with no extension is tried as a model. STEP checks declared SI length prefixes before opening solids or meshes. An unsupported prefix, such as NANO, is refused with `NOT_READ`; it is not treated as an undeclared millimetre file. A supported declaration elsewhere in the file does not hide that refusal. The accepted part and its edits remain unchanged. Supported unit scaling and the millimetre fallback for files with no declared length unit retain their existing behavior. A STEP file that holds only meshes (AP242 tessellated, from scans or other systems) is read like an STL. A mesh that isn't closed and clean goes through the **mesh repair** dialog before it opens: - it lists what is wrong with the mesh; - the repair steps are **Fill holes**, **Orient**, **Drop degenerate triangles**, **Drop fins** and **Drop tiny pieces**, all on to start, each of which you can turn off; - **Check the repair** runs it and reports the triangles and area it adds and what is still open; - **Apply the repair** keeps it as a step on the mesh, which the badge in the **Browser** lets you change later. Keep the original exchange file before importing or repairing it. STEP opens as imported geometry, not the source system's feature history. Saving the imported result as `.bcad` keeps the edits made here; it does not recover that earlier history. A mesh import also requires the correct unit before its dimensions can be used. ![The mesh repair dialog for a cup with an open top: one hole, the repair steps and the checked repair's numbers](/shots/studio/files/mesh-repair.png) **Insert part** places another `.bcad` part in this one as an instance; see [Assemblies](/studio/assemblies). **Templates** starts a part from **Empty part**, **Plate with a hole** or a template you saved. Your templates are kept in this browser. ## Unsaved work While a part is unsaved, a recovery copy is written in this browser a moment after each change. After a reload or a crash, **Unsaved work** offers it back: **Restore** or **Discard**. The copy is cleared when you save or replace the part. It is kept only in this browser, so it is no substitute for saving. In a project, the work since the last save is kept in the project instead. - **Mesh data first.** A part's mesh data is stored before the copy that names it. So a copy is offered only when its meshes were kept too. If they are gone by the time you restore, for example because the browser's data was cleared, **Could not restore** asks you to open the mesh file again. - **When no copy can be kept,** the studio says so once: - **No recovery copy:** the browser doesn't keep one, in private browsing or with full storage. - **Crash recovery is off for this document:** the part is too large for the browser's storage. In both cases, save to keep your work. ## Exports | Export | What it writes | |---|---| | **Export STEP** | Exact solids and mesh bodies in the selected STEP representation | | **Export IGES** | Visible curves and untrimmed surfaces; a visible trimmed surface refuses the whole export | | **Export STL** | Triangles in millimetres, one file per body (or named-face ASCII STL for multi-material/region workflows), with no exact curves | | **Export 3MF** | For a slicer: component-aware 3MF with bodies, materials, colours, print orientation, Print Face (`Ctrl+B`) bed alignment, and Send to Slicer handoff | Hidden trimmed surfaces do not block IGES export of the other visible geometry. Use **Untrim** only when you intend to remove a surface's trims. ### Prepare a STEP export **Export STEP** prepares the current evaluated design and opens one panel in the right dock. Check its schema, millimetre units and applicable loss report. This profile does not transfer native editing history, assembly hierarchy and shared definitions, user body labels, colours, semantic PMI or named datum systems. The file/product name and generated face names are separate from user body labels. Names inside this STEP profile use printable ASCII. Other characters in the STEP header file name and product name become underscores, and the panel reports that loss. The download name shown in the panel is separate and remains as entered. Only the panel's **Export** action writes the file. **Cancel**, **Close** or Escape discards the preparation. An edit, Open or New also clears it; prepare again for the current design. When visible root or placed mesh bodies are present, the same panel has a **Mesh bodies** selector. | Choose | What it writes | |---|---| | **Auto** | Closed mesh bodies with up to 5,000 triangles per body use planar faces. Larger ones use AP242 tessellated faces. | | **Tessellated** | Mesh bodies use AP242 triangulated faces. Check that the receiving app supports this representation. | | **Planar faces** | Closed mesh bodies use triangles as planar B-rep faces, merged where flat. More than 250,000 triangles in one body is refused. | Open mesh sheets always use AP242, including when you select **Planar faces**. A body with both exact and mesh faces can use only AP242; selecting planar faces is refused. Its exact faces are sampled at 64 segments per quarter. Planar files can be large. Older CAD, CAM and slicer apps may not read AP242 tessellated faces. See [STEP mesh options and format limits](/packages/cad/formats#step) before choosing a representation for another app. ### Choose an STL quality 1. Wait for the current design to finish evaluating. Fix any evaluation error before exporting. 2. Choose **Export STL**. **Quality** starts at **Automatic** each time the dialog opens. 3. Use the table below to choose a quality, then choose **Export**. Choose **Cancel** to stop preparation. 4. Read the export message. If it names bodies written from the on-screen mesh, review those files before use. Keep the downloaded `.source.json` beside the STL files. | Situation | Choose or do this | |---|---| | You do not need a specific sampling setting | Use **Automatic**. It leaves the quality option unset. | | You need a specific setting for B-rep bodies | Use **Draft 8**, **Standard 16** or **Fine 32**. These set `segmentsPerQuarter` to 8, 16 or 32. They are dimensionless sampling settings, not millimetre error tolerances or guaranteed geometric error bounds. | | The output includes a mesh body | Use **Automatic**. An explicit quality is refused. | | Pieces touch only at an edge or point | Use **Automatic**. It splits the display mesh into one STL per piece. | | The document has visible placed instances | Open the part's own document before using an explicit quality. | | Automatic reports use of the on-screen mesh | The kernel returned no STL bytes (`null`), so the display mesh supplied the bytes. This fallback does not mean the kernel export succeeded. | | Explicit quality cannot produce bytes | No STL or source sidecar is downloaded. Read the message; use **Automatic** only if its display-mesh fallback is acceptable. | | Export reports an error | Read and correct the reported problem, then export again. A worker error stops both Automatic and explicit export; it does not select the fallback. | | The design changes during preparation | Wait for the current design to evaluate, then open **Export STL** again. The stale request downloads nothing. | All STL bytes and the source sidecar are prepared before downloads start. **Cancel** during preparation discards the pending export without downloading either. Changing quality does not change the on-screen mesh or save a quality setting in the document. STL coordinates follow the millimetre convention, but the file stores no unit. Confirm the scale in the receiving app before using the mesh. ![STL export flow: quality selection, preparation, current-design check and download](/diagrams/stl-export-flow.svg) If dimensions read from an image or drawing remain unconfirmed, STEP and STL still export. The message identifies the export as a draft and lists the open dimensions. For 3MF, pieces that touch only at an edge or point remain separate objects to avoid welding them in a reader. **Sources.** Each export names the document revision it was made from: - STEP writes it in its `FILE_DESCRIPTION`; - 3MF writes it as `barocss:SourceRevision` metadata; - a drawing writes it as an **SRC** line in the title block. STL and USD get a `.source.json` record beside them, and the URDF, MJCF and SDF zips hold a `robot.source.json`. See [Revisions and sources](/guide/concepts#revisions-and-sources). Keep source records beside the files they name when you send or archive an export. A source record identifies the input document revision and its canonical-content SHA-256; it is not a checksum of the exported file's bytes. After a document change, export again to produce files and source information for that revision. From the **Drawing** tab, **Export SVG**, **Export PDF** and **Export DXF** write the sheet, with DXF as 2000 or R12; see [Drawings](/studio/drawings). **Quote package** writes STEP, the manufacturability report and the request in one zip; see [BOM and quotes](/studio/bom). ## Robot files The **Joints** card exports the robot; see [Robots](/studio/robots). | Export | File | |---|---| | **Export URDF** | A zip of `robot.urdf`, its meshes and `robot.source.json` | | **Export MJCF** | A zip of `robot.xml`, its meshes and `robot.source.json` | | **Export SDF** | A zip of `robot.sdf`, its meshes and `robot.source.json` | | **Export USD** | A `.usda` file, and its `.source.json` beside it | --- # Projects, collaboration, and release packs A project stores your parts, immutable version snapshots, branches, and merge history. BaroCSS CAD supports local folders, browser OPFS storage with crash-safe write-ahead logging (WAL), and optional **Cloud** project sync (`ProjectStore`), plus one-click **Release Evidence Pack** export. ## Opening a project Open the **Versions** tab in the left panel (or **Project & versions** from the top bar): - **Open folder…** picks a folder on your disk, in browsers that have a folder picker (Chrome, Edge). The browser asks for access. After a reload, **Reopen** *name* brings the last folder back; the browser may ask again. - **Keep in this browser** creates a project in browser storage backed by the OPFS Command WAL (`commandWal.ts`), an append-only journal that protects edits across unexpected tab closes or reloads without touching external servers. - **Cloud ProjectStore (`kind: 'cloud'`):** Connects Studio to a REST `ProjectStore` endpoint (`cloudStore.ts`) with optimistic ETag concurrency (`If-Match` / `If-None-Match` refusing stale overwrites as `STORAGE_CHANGED`), shareable links with explicit `view` / `comment` / `edit` access scopes, 3-way branch sync, and shared `teamLibraries`. - **Close** closes the project. Its files stay where they are. ## Working in a project - **Save** writes *name*`.bcad` into the project instead of downloading it. Its tip says where. - The card lists the project's documents, and **Open** opens one. - **Work since the last save.** It's kept in the project a moment after each change, in place of the browser's recovery copy. When you open the document again, work that differs from the saved file is offered back: **Restore** or **Discard**. A checkpoint identical to the saved file is not offered. - **A file changed elsewhere.** When Save detects a different file version, it refuses the write as *file* **changed elsewhere**. Open it again, or save under another name. - **A new document.** **New part**, opening a file, a template or a sample starts a document that isn't the project's yet. The card's versions clear, and Save writes it as a new file in the project; a name already taken is refused. A save already in progress can finish writing its original file. Newer edits keep their unsaved state and recovery copy. After **New part** or closing the project, the older save does not attach its file to the current document or restore the closed project. Within one open project session, overlapping writes to the same file wait their turn. Each checks its expected file version after the previous write finishes, and keeps ownership until its result is read. A stale request leaves the first successful bytes intact. Different file paths can progress independently. Coordination across separate project sessions, browser tabs or external programs remains outside this qualified overlap protection. ## What the folder holds | Path | What it is | |---|---| | *name*`.bcad` | Each document, exactly as Save writes it. It opens anywhere on its own | | `.barocss/versions/`*name*`.bcad.json` | Its versions and branches | | `.barocss/snapshots/`*key*`.bcad` | Each version's document, written once and never changed | | `.barocss/autosave/`*name*`.bcad` | The work since the last save | The folder can be copied or synced: a version's files never change once they're written. ## Versions ![The project card with two versions, and the first compared with the working document: the second box listed as added, and drawn in green in the viewport](/shots/studio/projects/compare.jpg) - **Make version**, with an optional name, saves the document and keeps this state as a version. - **The list.** It shows the current branch's versions, newest first, with **latest** marking the newest. - **Restore** brings a version back as the working document. Nothing is deleted: making a version of it adds a new one on top. - **Compare** shows what changed from that version to the working document: - as a list: features added, removed, edited (with the values that changed) or moved; parameters; configurations; mates; placed parts; and other settings by name; - in the viewport: the material added, in green, and removed, in red, with their volumes. Where that can't be worked out, as for mesh bodies, the changed faces are tinted instead. **Hide** stops comparing. ## Branches and merging - **Branch**, with a name, makes a branch from the latest version, and the **Branch** list switches between branches. Switching opens that branch's latest version, and is refused while there are changes not made into a version. - **Merge into** *current* brings another branch's work in: - when the current branch has nothing of its own since they parted, it simply moves to the other's latest version; - otherwise a merge version is made, "merged from *branch*". - **What merges on its own.** Features, parameters, mates and placed parts changed on one side only. - **Conflicts.** The same thing changed differently on both sides, or a feature one branch deleted while the other built on it. Each conflict shows both sides, with the value when it is short, such as `main (3)` and `thick (5)`. Choose one side for each, or for a deleted feature keep it or drop what uses it, then **Merge with these answers**. ![A merge with one conflict: the parameter T is 3 on main and 5 on the branch thick, each side offered](/shots/studio/projects/conflict.png) - **3D merge conflict viewer:** When two branches diverge on geometry or parameters, Studio renders both candidate states directly in the 3D viewport (`mergeConflictPreview.ts`) with color-coded delta highlights so you can visually verify `ours` vs. `theirs` before clicking **Merge with these answers**. ## Release Evidence Pack (1-click manufacturing bundle) From the consolidated **Export** menu, generate a cryptographically verifiable **Release Evidence Pack** (`.zip`, `releaseEvidenceBundle.ts`) pinned to the active revision: | Archive path | Contents | | --- | --- | | `source/.bcad` | Exact editable parametric CAD source container | | `cad/.step` | Verified STEP AP214/AP242 solid geometry | | `drawing/.svg` | 1:1 mm orthographic 2D engineering drawing (SVG) | | `drawing/.pdf` | Vector 2D engineering drawing sheet (PDF) | | `bom/-bom.csv` | Complete Bill of Materials (bought + made) | | `evidence/approval-evidence.json` | Hard specs, DFM report, and TaskRun approval evidence | | `release-certificate.json` | Deterministic SHA-256 signed manifest (`barocss-release-certificate` v1) | Share the resulting bundle with [BaroCSS Review](/studio/review) or manufacturing partners to verify artifact digests and requirements end-to-end. ## Placed parts linked to project files - **Insert**, beside a document in the card's list, places that document in the one you have open. The placed part's panel then says `From ./`*file*: it is linked to that file. - **Newer files.** When the assembly is opened from the project, or on **Check** beside "*N* placed parts linked to project files", each linked file is read. If one was saved with changes since, a toast says **Newer files for** *N* placed parts, and the part's panel shows **Revision waiting**: accept the new revision, which every copy of the part takes where it stands, or keep the one it has. Nothing changes until you accept. - For a missing file, Studio shows "Not in the project any more: …". - **It still opens anywhere.** The assembly keeps its own copy of each placed part, so its `.bcad` opens on its own. ## The agent's versions The agent keeps, compares and merges versions too, through actions on its `history` tool. They work on the open project's log, the same one the card shows. With no project open, or a document not in the project yet, the log is kept for the session. | Action | What it does | |---|---| | `history.version` | `name?`, `note?`: keeps the part as a version on the current branch. Refused when nothing changed since the branch's last version, or the name is taken | | `history.versions` | `branch?`: the branches, the current one, and a branch's versions, newest first | | `history.restore_version` | `id`: the part back as that version kept it (an id or a name) | | `history.compare` | `from?`, `to?`: what changed, as the card's list gives it. Each is a version, `latest` or `current`; by default from `latest` to `current` | | `history.branch` | `name`, `from?`: a branch made at a version, by default the current branch's last. It isn't switched to | | `history.switch` | `branch`, `discard?`: the branch's last version becomes the part. Refused while there are changes not made into a version, unless `discard: true` drops them | | `history.merge` | `from`, `resolve?`: another branch's work brought in, as **Merge into** does. The part must be its branch's last version first | - **Merge conflicts.** They come back as data, and nothing is merged. Each has its code, where it is, and both sides: a short value whole, a long one as its kind and length. The agent merges again with `resolve`, `"ours"` (the current branch) or `"theirs"` for each. - **Who made it.** A version the agent makes is recorded in the folder's log as made by `agent`. - **What a turn carries.** A chat turn takes the whole list of versions and branches, but only the documents its actions need: each branch's latest version, and the version each other branch shares with the current one. A version the agent asks for whose document didn't come is refused with `VERSION_NOT_LOADED`, and that document comes with the next turn. - **When the turn comes back.** Its versions are added to the project, and the ones you made meanwhile are kept. If you and the agent both moved a branch, yours stays the branch's latest and a message says so; the agent's versions stay in the list. - **Edits made during the turn.** A restore, a switch or a merge brings back a whole earlier state, so it isn't replayed onto a part you edited while the agent worked. It waits in a proposal instead, as [other colliding changes](/agent/proposals#when-the-part-changed-meanwhile) do. ## Refusals A project refuses rather than guess, each refusal with its code: - versions, branches and merges: `VERSION_…`, `BRANCH_…` and `MERGE_…`, with `VERSION_NOT_LOADED` for a version whose document didn't come with the agent's turn; - conflicts: `FEATURE_EDITED_BOTH`, `FEATURE_DELETED_EDITED`, `MERGE_DANGLING`, `ID_CLASH` and `ITEM_DELETED_EDITED`; - storage: `STORAGE_PATH`, `STORAGE_CHANGED` (the file changed elsewhere), `STORAGE_DENIED`, `STORAGE_MISSING` and `STORAGE_UNAVAILABLE`. See [Refusal codes](/reference/refusals). ## Not yet - Renaming a document doesn't update the links to it. - Sharing, comments and several people editing one project. --- # Viewer review files `@barocss/viewer` is currently used from source. `@barocss/viewer` can capture and restore a review of a loaded CAD scene: its camera, visible geometry and selected geometry. The host app supplies file Save/Open. Opening a review does not load CAD geometry or modify the CAD model. ![Viewer review flow: load the matching CAD scene, save review JSON, validate it and restore the view](/diagrams/viewer-review-flow.svg) ## Capture and apply | API | Result | |---|---| | `viewer.captureReviewState()` | A detached, JSON-safe `ViewerReviewStateV1` snapshot | | `viewer.applyReviewState(input: unknown)` | Validates and applies the review; returns `void` or throws | Serialize the captured object with `JSON.stringify`. Later, parse the host's file text and pass the resulting `unknown` value to `applyReviewState`. Changing a captured snapshot does not change the Viewer. Do not save the whole `getState()` object as a review file. The example loads the CAD document before exposing review Save/Open functions. The caller supplies original CAD document JSON and 1..4 existing body IDs. The declared authored XYZ basis must match the Viewer's right-handed Y-up millimetre basis; the option is an assertion, not a coordinate conversion. `createViewer` requires `background`: three finite RGB components, each from 0 to 1. ```ts import { createViewer } from '@barocss/viewer'; import { parseBaroCadDocument } from '@barocss/cad-interop/document'; async function createReviewHost( canvas: HTMLCanvasElement, cadDocumentText: string, bodyIds: string[], ) { const viewer = await createViewer(canvas, { mmToSceneUnit: 0.15, background: [0.025, 0.04, 0.065], }); try { viewer.loadDocument(parseBaroCadDocument(cadDocumentText), { native: { sourceVersion: 0, countU: 8, countV: 8, unitsPerMillimeter: 1, curveDisplay: { version: 1, chordToleranceMM: 0.02, maxSegments: 512, maxDepth: 16, }, }, basis: 'authored-xyz-matches-rhyup', bodyIds, }); } catch (error) { viewer.dispose(); throw error; } return { viewer, saveReview(): string { return JSON.stringify(viewer.captureReviewState(), null, 2); }, openReview(text: string): void { const input: unknown = JSON.parse(text); viewer.applyReviewState(input); }, }; } ``` The host writes the returned text to a file and supplies file text to `openReview`. It handles JSON parsing, read/write errors and file-size limits. It also disposes the Viewer when finished. Loading and applying can throw; show the error and keep the review file for correction rather than treating a failed Open as a new accepted view. ## Pointer and keyboard controls Call `viewer.attachPointerControls(options)` or `viewer.attachKeyboardControls(options)` on the existing Viewer. Each accepts an optional plain options object with only `onError?: (error: unknown) => void`. The methods return a `ViewerPointerControls` or `ViewerKeyboardControls` handle, respectively. Keep each handle and call its `dispose()` to remove the listeners it installed. See [Host lifetime](#host-lifetime) for the cleanup order. | Adapter | Input | Action | |---|---|---| | Pointer | Primary-button drag | Orbit the camera | | Pointer | Shift + primary-button drag | Pan the camera | | Pointer | Wheel | Zoom | | Keyboard | Unmodified F | Fit the currently visible displayed geometry | | Keyboard | Escape | Clear the current Surface or Curve selection | Keyboard controls listen only on the Viewer canvas. Give the canvas `tabIndex=0` and let the host or user focus it. The adapter does not set focus. It ignores modified, repeated and composing keys. Pointer controls capture one primary pointer and use canvas CSS pixels. The host owns the canvas's `touch-action` CSS and click-to-select behavior. After a successful drag moves more than 3 CSS pixels from its start, releasing the pointer suppresses the next click. A click without such a drag still reaches the host's selection handler. The pointer adapter does not select geometry or change native measurements or display poses. Unsupported options are refused when attaching a control. Event-handling failures go to the optional `onError` callback. A failed keyboard action does not prevent the browser's default action. ## Host lifetime The host owns the Viewer and any pointer or keyboard control handles it attaches. Before removing the canvas or replacing its Viewer, stop the host's callbacks, dispose each control handle, then call `viewer.dispose()`. Disposing the Viewer does not remove the listeners installed by those separate control handles. Scene replacement, `viewer.clear()` and Viewer disposal release the Geometry owned by the SDK drawing, including its vertex/index buffers. Camera changes keep ownership bounded to the current drawing. If you use the GPU Core directly with shared Geometry, each caller still owns that Geometry: removing one Mesh leaves it available to other Meshes and later reuse; dispose it when that sharing ends. Both control-handle disposal and `viewer.dispose()` can be called again without repeating their cleanup. After Viewer disposal, `getState().status` is `disposed`; `captureReviewState()` and `applyReviewState()` refuse that instance. Create and load a new Viewer before offering review Save/Open again. A host can keep this cleanup callback with its canvas owner: ```ts import type { Viewer, ViewerPointerControls, ViewerKeyboardControls } from '@barocss/viewer'; export function reviewCleanup( viewer: Viewer, pointer: ViewerPointerControls, keyboard?: ViewerKeyboardControls, ): () => void { return () => { pointer.dispose(); keyboard?.dispose(); viewer.dispose(); }; } ``` ## What the file binds to The format is `schema: 'barocss-viewer-review'`, `version: 1`. Its fields are `scene`, `camera`, `visibleGeometry` and `selectedGeometry`. The scene pins come from the accepted loaded scene: - document or assembly kind, ID and revision; - the exact `mmToSceneUnit` scale; - the loaded body or instance inventory, including original document/asset revision references, in its original order. Load that same revision and subset before applying the file. A different scene, revision, member order, subset or scale is refused. Do not reorder or edit `scene.members` to make another scene match. The CAD producer must advance revisions when CAD data or assembly placements change. Pins identify declared revisions; they do not authenticate source contents or provide file integrity. The file contains no geometry, preview packets, CAD source, motion, materials, measurements or simulation layers. Save those inputs separately when the host needs them. Applying the review restores only camera, visibility and selection; it does not restore those other values. ## Supported scenes and visibility Review files support revisioned primitive CAD document and assembly scenes with the existing 1..4 loaded-object limit. All loaded objects may be hidden: `visibleGeometry` can be empty, with `selectedGeometry: null`. Otherwise, the selection must name visible geometry. Visibility references must be unique members of the loaded inventory. Existing material and layer restrictions can also refuse visibility or selection changes. Empty or disposed Viewers, native-source-only and model-set-only loads, Shell, mixed-depth and qualified Face scenes are outside this review profile. A review file is not a general serialization of every Viewer mode. ## Refusal and recovery `applyReviewState` checks the complete candidate before presentation. Unsupported fields, stale pins, invalid camera data, unknown or duplicate geometry and hidden selections are refused. Invalid input leaves the accepted state and drawing unchanged. The input must contain plain data; accessors and unsupported object shapes are not accepted as file fields. For an admitted candidate, the Viewer draws before committing the new CPU camera, visibility and selection. If presentation throws, it keeps the accepted CPU state and attempts to redraw the prior state. If recovery also fails, an `AggregateError` reports both errors. This recovery attempt cannot guarantee pixels after a device failure. Successful apply does not mutate the caller's object, CAD data or hierarchy. The repository's `examples/viewer-review` shows host controls for saving JSON and opening a real file. Its 32 KiB file-read limit belongs to that example host, not to the SDK review schema. --- # Designing with the AI Copilot BaroCSS CAD's AI Copilot works directly on the live `.bcad` document using the exact same parametric modeling, drawing, DFM, and inspection commands you use in Studio. Every geometry edit is validated by the B-Rep kernel — never approximated meshes. ## Three AI runtime modes (Provider-Agnostic) Switch runtimes directly from the Chat header without restarting Studio: 1. **Browser AI Runner (BYOK).** Connect directly from the browser using your own Anthropic, OpenAI, or Gemini API key. Runs the full tool loop client-side with automatic multi-angle visual self-verification. 2. **Local CLI bridge.** Connect Studio to your signed-in local CLI session without exposing credentials to the browser. 3. **External coding agents (MCP).** Connect Claude Code or other MCP-compatible agents directly to `.bcad` files — see [Headless CLI & MCP Server](/agent/cli) for 1-command setup. ## ⌘K 3D Spatial Pin & Floating Proposal Bar You do not need to type coordinates or feature IDs in a sidebar chat: 1. Select any face, edge, or body in the 3D viewport and press ⌘K (`Ctrl+K`). 2. The **3D Spatial Pin** inline prompt anchors directly to the picked geometry, automatically attaching its persistent face/edge identity, surrounding model context, and a live viewport capture. 3. Describe the edit (for example, `"add 2 mm fillets around this pocket"` or `"mount four M5 holes 8 mm from the corners"`). 4. Review structural edits right on the canvas in the **Floating Proposal Review Bar** with **Preview**, **Accept**, and **Reject**. Need multiple design directions at once? Open the [Generative Variant Explorer](/agent/variants) to evaluate parallel candidates with live parameter sliders. ## What the agent can do - **Model & edit parametrically:** Run any Studio command, author parametric features, place assembly parts and mates, edit 2D drawings, and manipulate SubD cages. - **Inspect exact geometry & visuals:** Query feature trees, persistent face/edge references, exact distances, mass properties, interference, wall thickness, draft angles, DFM reports, and multi-angle renders. - **Maintain the design brief:** Track user-stated vs. agent-assumed parameters and run hard/soft requirement checks automatically. User-stated values are never silently overwritten. - **Work from images & drawings:** Attach up to four PNG, JPEG, WebP, or GIF files per turn to trace profiles into solids or create confirmable draft features. - **Load verified Shop Rows:** Attach a JSON rows file and ask the agent to load it (see [Shop rows](/studio/rows)). ## Guardrails & autonomy (L1–L4) - **People own shop standards:** The agent cannot fabricate or load its own fastener/casting tables (`[ROWS_NOT_FROM_PERSON]`). - **Explicit approval for high-impact edits:** At default autonomy (`L2`), single-feature parameter tweaks and initial empty-part builds apply directly (with instant **Undo**). Structural edits, assemblies, mates, drawings, robot settings, and locked parts always wait in a reviewable proposal. See [Proposals and autonomy](/agent/proposals). - **Concurrent editing:** Keep modeling while a turn runs — non-colliding changes merge automatically, while colliding edits surface cleanly as proposals. ## Example turn flow These captures show the deterministic proposal lifecycle exercised against the real tool layer: 1. *"A 60 × 40 plate, 8 thick."* On an empty part at `L2`, the initial build applies directly with an **Applied by the agent** toast and one-click **Undo**. ![The first build applied directly, with the Applied by the agent toast](/shots/agent/turn-applied.jpg) 2. *"Make it 10 thick, with an 8 mm hole in the middle."* Because this combines a dimension change with a new structural feature, `L2` refuses direct mutation and returns **P1** for visual preview and approval. ![The chat column showing thinking, tool calls, the refused direct batch, and proposal P1](/shots/agent/proposals/refused-then-proposed.png) Continue to [Generative Variant Explorer & Visual Self-Verification](/agent/variants), [Tools](/agent/tools), [MCP and CLI](/agent/cli), or [AI-Ready Docs (`/llms.txt`)](/agent/ai-ready). --- # Generative Variant Explorer and Visual Self-Verification BaroCSS CAD combines parallel background evaluation with closed-loop visual inspection so AI-assisted edits stay fast, comparable, and geometrically sound. ## Generative Variant Explorer Instead of committing to a single AI guess, the **Generative Variant Explorer** evaluates multiple parametric and topological candidates in parallel without blocking your viewport: - **Parallel comparison cards:** View 3D previews of candidate designs side by side while continuing to orbit or inspect. - **Live parameter sliders:** Scrub exposed dimensions across variants and watch exact volume, mass, and bounding boxes update in real time. - **Requirement & DFM scoring:** Compare each candidate against active design brief constraints before promoting one to the active document. - **Non-destructive promotion:** Accepting a variant writes a single undoable step into the feature history. ## Visual self-verification and 1-click repair ### Multi-angle visual inspection loop In the Browser AI Runner, the agent does not stop after making a modeling edit: 1. After authoring or modifying geometry, the agent captures multi-angle visual views of the evaluated 3D solid. 2. The multimodal model inspects those views alongside exact mass properties, bounds, interference, and requirement checks to catch misplaced holes, inverted extrusions, or unintended intersections before presenting a proposal. ### Design Health & 3D error callout When a parametric edit invalidates a downstream feature (for example, an oversized fillet radius or a missing face reference): - The **Design Health** indicator in the top bar highlights the exact failure count and diagnostic category. - Clicking an issue focuses a **3D error callout** directly on the affected face or edge in the viewport. - Choose **1-click repair** to apply a deterministic fix (such as clamping a radius to geometric bounds) or send the structured diagnostic straight to the AI Copilot for a guided proposal. See [AI Copilot & Spatial Pin](/agent/), [Proposals and autonomy](/agent/proposals), and [Refusal Codes](/reference/refusals). --- # Tools (v2 actions) The agent works through one tool contract, `barocss-cad-tools-v2`. The chat, [`cad-mcp`](/agent/cli) and [`cad-cli`](/agent/cli) all serve this list and nothing else. It has 13 tools: - `model` - `features` - `query` - `history` - `requirements` - `proposals` - `assembly` - `library` - `print` - `drawing` - `subd` - `image` - `describe` ## How a call looks A call names a tool, and its arguments carry an `action`: ```json { "name": "query", "arguments": { "action": "measure", "a": "n1.top" } } ``` That is `query.measure`. - **One action.** A tool with a single action takes it without saying so: `model` with `{ "source": … }` runs a script. - **The handlers.** Each action stands for one of the tool layer's handlers. The call goes through that handler's own gates and gives its results and refusals. - **Naming faces and edges.** Faces and edges are named as the studio names them: `n1.top`, or an edge as two faces, `n1.side0|n1.side1`. Selectors work too: `{"feature": 1, "role": "top"}`, `{"normal": [0, 0, 1], "pick": "max"}`. ## `describe` The list a model reads each turn stays short, and `describe` gives the detail on request: | Ask | Returns | |---|---| | `{}` | Every tool's actions | | `{"tool"}` | That tool's actions | | `{"tool", "action"}` | The action's full description and arguments | | `{"command"}` | A command's selection and values | | `{"feature"}` | A feature kind's node JSON | New commands and feature kinds need no change to the list. The `features` tool names them, and `describe` gives their detail. For example, the agent mounts a motor with `features.command` and the command `mount`, on a picked face, after loading the person's mount rows with `features.load_rows` and the kind `mounts`. A mount adds features, so at L1 and L2 it is proposed. See [Part features](/studio/features#machine-elements). ## Results and refusals - **Data back.** A call returns JSON. A read gives what it read; a change says what it changed. - **Refusals.** A refused call leaves the part exactly as it was and says why, often with a code the agent can act on. For example, `needs_proposal` at L2, or `needs_approval` for a change to the assembly, mates, the drawing, the robot or a locked part. - **A command's refusal.** When the build behind `features.command` refuses, the call returns that refusal as its error, as `