Object API
Quick jump: Start with CAD Model API · Interactive 3D API Results · CAD Kernel Part · Studio / Model Part · Parameters & Configs · Assemblies · Manufacturing · Scenes · 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:
import { part, assembly, Location, param, BarocssError } from '@barocss/cad-model/api';// 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 bodyThe 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:
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()andmeshes()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.
- The two parts and the assembly have
- 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 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
volumein mm³,massin g,centroidin mm andinertiain g·mm² about the centre of mass. A numericdensityis in g/cm³. Density must be positive and finite; both facades refuse other numeric densities withBarocssError, codeDENSITY, fromfacade. Native producers also report optionalmethodprovenance:closed-form,planar-exact,quadratureortessellated.planar-exactdescribes the represented planar or facet boundary; it does not recover a smooth source from a mesh.quadraturedescribes numerical integration over the represented surfaces. These method names are not accuracy certificates. Legacy or custom Model bodies without producer metadata omitmethod; the facade does not infer it from the body's family or a missing estimate. A reported tessellated result can includevolumeBasis: { method: 'tessellated', bound }. Despite its existing field name,boundis an estimate of volume error in mm³, derived from the mesh refinement change, rather than a certified error bound.nullmeans 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, andsubtract, whose command isdifference. - 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'srun_commanddoes. - The same selectors.
edges()andfaces(), 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'.
- the facade's own codes cover only how it was called, with
- 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
.docequals the hand-written document, and its results equal the core's on that document, byte for byte. cad-model's.docalso 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.
Box from [0, 0, 0] to [80, 40, 10] mm. Density 2.7 g/cm³.
Drag to rotate · focus the view and use arrow keys.
| Returned value | Result |
|---|---|
| Volume (mm³) | 32,000 |
| Mass (g) | 86.4 |
| Centroid [X, Y, Z] (mm) | [40, 20, 5] |
Inertia about the centre of mass (g·mm²)
[12,240, 0, 0]
[0, 46,800, 0]
[0, 0, 57,600]Density: 2.7 g/cm³. Labels round the saved values to three decimal places.
Executed public API code
import { part } from '@barocss/cad/api';
const result = part('bracket')
.box({ w: 80, d: 40, h: 10 });
const mass = result.mass({ density: 2.7 });
const meshes = result.meshes();Source bundle provenance
{
"format": "api-result-scenes-v1",
"provenance": {
"sourceCommit": "8cddcd05fd3a388472d5a01b4a43e09cdf8a50aa",
"cadPackagePath": "packages/barocss-cad",
"cadTreeSHA1": "61e967638890baeaab74c8b3940f7c8a50333d11",
"sourceVerification": "Pinned Git tree equals the current CAD tree; tracked CAD files are unchanged and CAD src has no untracked files.",
"producerFiles": [
{
"path": "apps/library-docs/scripts/api-result-scenes.mjs",
"sha256": "7785e6c6f38b29c37e6dc5389d70fc84684fe0c9c600f7d5366e5565baf758d8"
},
{
"path": "apps/library-docs/scripts/api-result-scenes-source.mjs",
"sha256": "161963682a15d0108ccbe8a8f5fe949ab8e37127f3a5e0e38008dce69e37b77a"
}
],
"publicAPI": "@barocss/cad/api",
"sample": {
"path": "apps/library-docs/samples/cad-api.test.mjs",
"lines": [
16,
24
],
"sourceCommit": "8cddcd05fd3a388472d5a01b4a43e09cdf8a50aa"
},
"frame": "Z-up",
"units": {
"positions": "mm",
"volume": "mm³",
"mass": "g",
"centroid": "mm",
"inertia": "g·mm² about the centre of mass",
"density": "g/cm³"
},
"density": 2.7,
"display": {
"source": "Public Part.meshes() Float32 tessellation",
"packing": "Public positions, normals and indices are copied without re-tessellation or rounding; display line segment pairs are grouped in arrays of six numbers.",
"boundary": "Display triangles approximate native surfaces. They do not establish a geometric tolerance guarantee. Mass values come from Part.mass(), not from display triangles."
},
"analyticChecks": {
"absoluteVolumeToleranceMM3": 0.000001,
"boxVolumeMM3": 32000,
"holeVolumeMM3": 31497.345175425635,
"roundedVolumeMM3": 31463.008881569225,
"roundedCornerRemovalMM3": 34.336293856408275,
"selectedVerticalCornerNames": [
"extrude1.side0|extrude1.side1",
"extrude1.side0|extrude1.side3",
"extrude1.side1|extrude1.side2",
"extrude1.side2|extrude1.side3"
],
"boundary": "Fixed-example arithmetic checks only; not a tessellation or geometric tolerance guarantee."
}
}
}01 · Box
Create the box with box({ w: 80, d: 40, h: 10 }).

Returned volume: 32,000 mm³. Mass: 86.4 g at 2.7 g/cm³.
02 · Through hole
From the box, select the +Z face and make a diameter 8 mm through hole at face coordinates (20, 20).

Returned volume: 31,497.345 mm³. Mass: 85.043 g at 2.7 g/cm³.
03 · Rounded vertical edges
From the holed part, select its four vertical edges and apply a 2 mm fillet radius.

Returned volume: 31,463.009 mm³. Mass: 84.95 g at 2.7 g/cm³.
CAD kernel part
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:
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 bodyThe 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.
// 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 bytepart(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
rotateverb. 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
atorpivot. A mirror plane off the origin is written as the studio writes it: a move, the mirror, and a move back.
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 bodyFillet 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.
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), andPlane.of({ origin, normal, xAxis }), which refuses vectors that aren't unit length and square to each other. - Locations.
Location.of({ position, rotation })andLocation.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.
// 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()andmass()acting on that body..docdoesn'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, andmeshes()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.
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:
x = 0 x = 4 x = 10
|-----------|--------------------|
4 mm 6 mm
split1/0 split1/1import { 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.
// 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.
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,sourceis the source document revision string. It does not identify a native or mesh representation.omittedcontains 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 withUNAVAILABLE; 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 }.linesare the display edges as segment pairs: the edges a selector offers, with seams and smooth joins left out.
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 pointsSelectors
- Edges:
along(axis),straight(),curved(),on(face),where(test),sortBy(axis),first(n),last(n),count,list()andnames(). - Faces:
facing('+z'),planar()andcurved(), the same filters and sorts, andedges(). - 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.
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 edgesCAD model part
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.
- 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.
- the box's values (
// 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 };- The agent's commands.
run_command, the features tool'scommand, with the faces and edges by persistent name. Written this way, each name has to be read from the result before it.
// 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 } },
];- 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_commanddoes.
// 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.
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 asal6061, or{ density }..material(id)sets the chosen body's material, or every body's, as the agent'sset_materialwrites it..mass()with no argument then weighs the body in it, and.meshes()carries the id for a scene to look up.
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 upText 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.
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 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.
// 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 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 |
// 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, sofasteneris refused until fastener sizes are loaded. The same file always loads the same bytes. The sample uses the rows cad-model ships undersamples/rows/.
// 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 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.
// 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 separatewithParameters(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:wanddwhilexandyare 0, andh;cylinder:x,yandh(notr: the studio's editor edits the diameter);extrude:h;hole:xandy(notd: the hole is stored by its radius);fillet:radius;chamfer:distance;shell:t;linearPattern:spacing;split:at;- in the CAD model part also
revolve'sdeg,linearPattern'scountandscale'sfactor, 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 aLocationtake numbers only.
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.
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 andsuppressed(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 withUNAVAILABLE.
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.
// 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? })isadd_part, with the part's document as it is;place(name, { at?, grounded? })isplace_part;addMate(kind, a, b, { distance?, angle?, flip? })isadd_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 })andvariants({ name: values | null }, active?)areset_inputsandset_variants. Bindings name parts and mates by id:parts()lists the parts' ids, and mates arem1,m2… in order;frames({ name: { link, at?, kind? } | null })isset_frames. The link is a part by name, andatis 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, aspositionandrotation;meshes():base/<body>and<part>/<body>, 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 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_LOADEDas 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, Manufacturing and BOM and quotes for the inputs these outputs need.
Errors
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_UNBINDABLEandFEATURE_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_UNKNOWNandCONFIGURATION_UNKNOWN; - the assembly:
NAME_TAKENandPART_UNKNOWN.
- the part:
- 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 indetails.friendly. A fillet too large for its walls is refused asRADIUS_EXCEEDS_FACEby both parts.
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
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:
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<key>/lines, thin and dark by default (LINE_MATERIAL)..material(id, look)registers a Material under an id: a part's material id, such asal6061, 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.
.datais the plain description, withframe: 'z-up'. Material ids stay ids in it, and the looks are undermaterials.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.
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_INVALIDandCAMERA_INVALID, in gpu's ownBarocssErrorof the same shape: gpu imports neither cad package.
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.