Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

The CadKit kernel is a boundary-representation (B-rep) CAD kernel written in Rust. It compiles to a small WebAssembly module that runs in a browser worker or in Node, and the same code also runs as a native service. You give it a part, a JSON document that lists the features that build a model, and it rebuilds that part into a solid body with faces, edges, a display mesh and measurements.

This book describes four things:

  • The part format. What a .ckpart document contains, how features refer to the faces and edges that earlier features made, how sketches are solved, and what each feature does.
  • The protocol. How a host talks to the kernel: the messages it accepts, the binary reply envelope, and every field of a regeneration result.
  • The kernel itself. The crates, the B-rep model, the geometry and operations behind each feature, tessellation, and how regeneration is cached.
  • Validation. How the kernel decides that a body is sound: the topology and geometry checks, the tessellation checks, tolerances, healing, and how feature errors are reported so that a failing edit can be understood.

Import and export (STEP, SketchUp, SolidWorks, ACIS SAT, text) and the way the kernel is tested are covered in the last parts, and the book ends with a crate map and a glossary.

What the kernel does

A part is a list of features applied in order. A sketch feature holds 2D geometry and constraints; a solid feature such as extrude or revolve turns a sketch into material; edit features such as fillet, shell or draft change the body that exists so far. Regenerating a part runs the list from the top (or up to a chosen feature) and returns the body that results, together with a status for every feature.

{
  "format": "ck-part",
  "version": 1,
  "features": [
    { "type": "sketch",  "id": "F1", "plane": { "kind": "std", "id": "top" },
      "points": [ { "id": "p1", "x": 0, "y": 0 }, { "id": "p2", "x": 40, "y": 0 },
                  { "id": "p3", "x": 40, "y": 20 }, { "id": "p4", "x": 0, "y": 20 } ],
      "entities": [ { "type": "line", "id": "e1", "p1": "p1", "p2": "p2" },
                    { "type": "line", "id": "e2", "p1": "p2", "p2": "p3" },
                    { "type": "line", "id": "e3", "p1": "p3", "p2": "p4" },
                    { "type": "line", "id": "e4", "p1": "p4", "p2": "p1" } ],
      "constraints": [] },
    { "type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 10 }
  ]
}

That is a complete part: a 40 by 20 rectangle extruded 10 units. A first part runs it and reads the result.

The kernel covers sketches with a constraint solver; extrude, revolve, sweep and loft; fillets, chamfers, shells, drafts, holes and threads; patterns, mirrors and transforms; surfacing features; and assemblies with mates. It reads and writes STEP and reads SketchUp, SolidWorks and ACIS SAT files.

Design points worth knowing

  • Everything is data. A part is plain JSON and a reply is JSON plus binary buffers. A regeneration depends only on the part, the options sent with the request, and any fonts loaded into the session; an optional regeneration cache is keyed by that content.
  • Deterministic. The same part regenerated on the same build gives the same result, which is what lets the kernel cache and compare results.
  • Errors belong to features. A feature that fails does not abort the part: the kernel reports an error for that feature and goes on with the rest of the list, so one regeneration can return several errors. See feature errors and diagnostics.
  • Names are stable. Faces and edges carry names derived from the feature that made them, so a fillet or a sketch placed on a face still finds that face after an upstream edit. See identifiers and references.

How to read this book

If you are building a host application, start with Getting started and then read the protocol. If you are writing or generating parts, read the part format and keep the feature index open. If a body fails a check or a feature reports an error, go to validation.

Code samples in the book were run against a build of the kernel; the numbers shown are what that build returned. The runner used for the examples is book/tools/run.mjs in the repository.

Licence

The kernel is released under either the MIT or the Apache-2.0 licence, at your option. Third-party material that ships with the repository, and its licences, are listed in THIRD_PARTY.md.

Build the kernel

This chapter shows how to build the kernel as a WebAssembly module, how to build the native HTTP service that serves the same protocol, and which Cargo profiles and features exist.

Requirements

  • A Rust toolchain with the wasm32-unknown-unknown target (rustup target add wasm32-unknown-unknown). The repository does not pin a toolchain version; it uses the 2021 edition.
  • Node.js, to run the tools, the TypeScript packages and the examples in this book. The examples in this book were run with Node 22.
  • Optional: wasm-opt from binaryen, for a size and speed pass over the finished module.

The workspace is the crates/* directory. It has no third-party Rust dependencies: Cargo.lock lists only the workspace crates (the JSON parser and writer is the workspace crate ck-json), so a build needs no network access.

Build the wasm module

cargo build -p ck-wasm --target wasm32-unknown-unknown --release

The module is written to

target/wasm32-unknown-unknown/release/ck_wasm.wasm

It is about 8 MB. The module exports memory and five functions and imports three functions from the module env; Call it from Node lists them and gives a complete host.

Profiles

The workspace Cargo.toml defines three profiles that matter here.

ProfileUsed forSettings
releasethe shipped wasmopt-level = 3, lto = true, codegen-units = 1, panic = "abort"
fastiteration and the test runsinherits release, but lto = false, codegen-units = 16, incremental builds, panic = "unwind"
servicethe native serviceinherits release, but panic = "unwind"

codegen-units = 1 gives the same results as more units (the optimiser does not reassociate floating point) and a smaller module. A fast build is much quicker to produce; its output is at target/wasm32-unknown-unknown/fast/ck_wasm.wasm:

cargo build -p ck-wasm --target wasm32-unknown-unknown --profile fast

With panic = "abort" a kernel panic ends the call with a wasm trap. The host reports the panic text through the ck_panic import first and then has to create a fresh instance, because the old one is unusable (Call it from Node shows this).

Features

FeatureCrateEffect
skpck-wasmLinks the SketchUp reader (ck-skp) and enables the importSkp request. On by default: it adds about 320 KB (4.6 %) to the module; --no-default-features drops it. Without it, importSkp answers an error that begins TODO(rebuild).
sanity-shadowck-wasm, ck-opsRuns the exact tier of the boolean sanity check even where the cheap tier already passed, and asserts that both agree. A checking mode for development, not for the shipped module.
cargo build -p ck-wasm --target wasm32-unknown-unknown --release

SketchUp describes the import.

Build identity

ck_commit() returns a fixed build string compiled into the module. The source revision is reported differently: when the environment variable CK_BUILD_REV is set at compile time, the ping reply carries it as result.build.

CK_BUILD_REV=$(git rev-parse --short=12 HEAD) \
  cargo build -p ck-wasm --target wasm32-unknown-unknown --release

Without the variable the ping result is just {"pong":true}.

Optional size pass

tools/build_wasm.sh runs the release build and then wasm-opt -O3:

tools/build_wasm.sh                 # writes target/wasm32-unknown-unknown/release/ck_wasm.opt.wasm
tools/build_wasm.sh out/kernel.wasm # choose the output path

wasm-opt is taken from $WASM_OPT, else from PATH. If it is not found, the script prints a warning and copies the plain cargo output to the output path, so later steps keep working. The pass enables only the wasm features that rustc emits for this target (bulk memory, sign extension, non-trapping float-to-int, mutable globals, multivalue, reference types). The repository documents that the pass does not change floating point results. There is no separate strip step: the workspace does not set strip, and wasm-opt removes unused code.

Build the native service

ck-native is an HTTP service on 127.0.0.1 that runs the same dispatcher (ck_server::handle) as the wasm module, one worker thread per session.

cargo build --profile service -p ck-native
target/service/ck-native --port 7461

Use the service profile. The release profile aborts on a panic, which would end every session; the service profile unwinds, so the service can answer 500 and close only the session that panicked. cargo build -p ck-native (debug) also works but is slow.

ck-native links ck-wasm without features, so a native service built this way has no importSkp. The service takes no third-party dependencies; its flags, token handling, pairing and HTTP shape are described in The native service, and the transport is summarised in Call it from Node.

Numbers from the native build can differ from the wasm build in the last digits of some floating point values, because the native build uses the system maths library and the wasm build uses the one compiled into the module. The repository’s comparison script reports the 280 protocol cases it runs as identical once ms and at are normalised, with the binary mesh buffers compared separately, and the two large documents it regenerates as equivalent to a relative difference of at most 1e-6.

Tests and the regression run

cargo test --workspace            # unit and integration tests; runs from a bare checkout

The corpus and check scripts in tools/ (tools/*_check.mjs, tools/*_corpus.mjs, tools/*_sweep.mjs) take --wasm <path> to choose the module and run it under Node. Some need extra sample inputs; each script’s header says what it reads. tools/gate.mjs is different: it compares the built module with a second kernel module that is placed next to the checkout as kernel.wasm and is not distributed with the repository, so it cannot be run from a bare checkout. The book’s examples need only the built module and Node. Testing describes what the test and regression runs cover.

Environment variables named CK_* select inputs for the tools; CK_WASM is the path of the module that the TypeScript packages and tests load.

See also

Call it from Node

This chapter loads the wasm module from Node, sends messages through its five exports and decodes the replies. The host at the end is small enough to copy; the same few steps are what the packaged clients do.

The module’s interface

The module exports its memory and five functions, and imports three functions from the module env.

ExportSignatureUse
memoryWebAssembly.Memorylinear memory; requests and replies are exchanged in it
ck_alloc(n)(i32) -> i32reserve n bytes for a request body and return their address
ck_request(ptr, len)(i32, i32) -> i32run the message of len bytes at ptr; return the length of the reply in bytes
ck_reply()() -> i32address of the reply of the last ck_request
ck_commit(), ck_commit_len()() -> i32address and length of the module’s build string
Import (module env)SignatureUse
ck_now() -> f64monotonic milliseconds, for example performance.now(). Used for the ms field of replies and for timing budgets.
ck_unix_ms() -> f64wall-clock milliseconds, for example Date.now(). Used for time stamps in exported files.
ck_panic(ptr, len) -> ()receives the panic text in memory just before the module traps

The sequence for one call is always the same:

  1. Encode the request {"id": n, "msg": {...}} as UTF-8.
  2. ptr = ck_alloc(bytes.length) and copy the bytes to memory at ptr. Ownership of the block passes to ck_request; the host never frees it.
  3. total = ck_request(ptr, bytes.length).
  4. at = ck_reply() and copy total bytes from at. The reply is overwritten by the next request.

Two details matter in JavaScript. Memory can grow during any call, which detaches the old memory.buffer, so read memory.buffer again after every call into the module. And the reply must be copied out before the next request.

The module has one global state per instance, and a call runs to completion on the calling thread. Calls on one instance are therefore strictly sequential; for parallel work create several instances (see Overview).

If the kernel panics, the module is built with panic = "abort": ck_panic is called with the text, then the call traps (a WebAssembly.RuntimeError). The instance cannot be used afterwards. A host carries on by creating a new instance from the same compiled module; all tags and caches of the old instance are gone.

A complete host

kernel.mjs:

// kernel.mjs: a minimal host for the wasm kernel.
import { readFileSync } from 'node:fs';

const ARRAYS = { f32: Float32Array, f64: Float64Array, u32: Uint32Array, i32: Int32Array, u8: Uint8Array };

export class Kernel {
  #module;
  #x;                // the instance's exports
  #panic = null;     // text of the last panic, set through the ck_panic import
  #nextId = 1;

  constructor(wasmPath) {
    this.#module = new WebAssembly.Module(readFileSync(wasmPath));
    this.#boot();
  }

  #boot() {
    const env = {
      ck_now: () => performance.now(),   // ms, fractional; used for the "ms" field of replies
      ck_unix_ms: () => Date.now(),      // wall clock, used for time stamps in exported files
      ck_panic: (ptr, len) => {          // called with the panic text just before the module traps
        this.#panic = new TextDecoder().decode(new Uint8Array(this.#x.memory.buffer, ptr, len));
      },
    };
    this.#x = new WebAssembly.Instance(this.#module, { env }).exports;
  }

  /** The build string of the module (ck_commit / ck_commit_len). */
  get commit() {
    const { memory, ck_commit, ck_commit_len } = this.#x;
    return new TextDecoder().decode(new Uint8Array(memory.buffer, ck_commit(), ck_commit_len()));
  }

  /** Send one message. Returns the parsed reply: { ok, result | error, ms }. Throws if the module traps. */
  send(msg) {
    const body = new TextEncoder().encode(JSON.stringify({ id: this.#nextId++, msg }));
    let reply;
    try {
      const x = this.#x;
      const ptr = x.ck_alloc(body.length);                          // room for the request; ck_request frees it
      new Uint8Array(x.memory.buffer, ptr, body.length).set(body);  // read memory.buffer after ck_alloc: memory may have grown
      const total = x.ck_request(ptr, body.length);                 // run the message; returns the reply length
      const at = x.ck_reply();                                      // where the reply is
      reply = new Uint8Array(x.memory.buffer.slice(at, at + total)); // copy it out: the next request overwrites it
    } catch (e) {
      const why = e.message + (this.#panic ? ` (panic: ${this.#panic})` : '');
      this.#panic = null;
      this.#boot();                                                 // the instance is unusable after a trap: start a new one
      throw new Error('kernel trap: ' + why);
    }
    return decodeReply(reply);
  }
}

/** [u32 LE json length][json][pad to 8][buffers...] -> object, with every {$buf} replaced by a typed array. */
export function decodeReply(bytes) {
  const jsonLength = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0, true);
  const json = JSON.parse(new TextDecoder().decode(bytes.subarray(4, 4 + jsonLength)));
  const base = (4 + jsonLength + 7) & ~7;                           // the binary area starts at the next multiple of 8
  const resolve = (v) => {
    if (Array.isArray(v)) return v.map(resolve);
    if (v === null || typeof v !== 'object') return v;
    if ('$buf' in v) {
      const Array_ = ARRAYS[v.type];
      const start = base + v.offset;                                // offset is relative to the binary area
      return new Array_(bytes.slice(start, start + v.len * Array_.BYTES_PER_ELEMENT).buffer);
    }
    return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, resolve(x)]));
  };
  return resolve(json);
}

The binary-area layout and the $buf views are specified in Replies and buffers. book/tools/run.mjs in the repository is the same host reduced to a command-line runner: it runs one message or an array of messages on one instance and prints the replies (node book/tools/run.mjs <wasm> <messages.json> [--full]). Its ck_now returns 0, so every ms it prints is 0; the other examples in this book use it for that reason, and the ms values in them are placeholders.

Using it

main.mjs regenerates a 40 x 20 x 5 plate and reads two results:

import { Kernel } from './kernel.mjs';

const k = new Kernel(process.argv[2] ?? 'target/wasm32-unknown-unknown/release/ck_wasm.wasm');
console.log(k.send({ type: 'ping' }));

// a 40 x 20 x 5 plate: one sketch, one extrude
const rect = (id, w, h) => ({
  type: 'sketch', id, plane: { kind: 'std', id: 'front' },
  points: [{ id: 'a', x: 0, y: 0 }, { id: 'b', x: w, y: 0 }, { id: 'c', x: w, y: h }, { id: 'd', x: 0, y: h }],
  entities: [['e1', 'a', 'b'], ['e2', 'b', 'c'], ['e3', 'c', 'd'], ['e4', 'd', 'a']]
    .map(([id, p1, p2]) => ({ id, type: 'line', p1, p2 })),
  constraints: [],
});
const part = {
  format: 'ck-part', version: 1, name: 'Plate',
  features: [rect('F1', 40, 20), { type: 'extrude', id: 'F2', op: 'add', sketch: 'F1', end: 'blind', depth: 5 }],
};

const r = k.send({ type: 'regen', tag: 'main', part });
const { body } = r.result;
console.log('ok', r.ok, 'errors', r.result.errors.length, 'faces', body.faces.length, 'edges', body.edges.length);
console.log('box', JSON.stringify(body.box));
console.log('mesh', body.mesh.positions.constructor.name, body.mesh.positions.length / 9, 'triangles');
console.log(k.send({ type: 'massProps', tag: 'main' }).result.volume);
console.log(k.send({ type: 'nope' }));

Run with node main.mjs, this prints (the ms values and the build string depend on the machine and the build):

{ ok: true, result: { pong: true, build: '8302a07430fb' }, ms: 0.57 }
ok true errors 0 faces 6 edges 12
box {"min":[0,0,0],"max":[40,20,5]}
mesh Float32Array 12 triangles
4000.0000000000027
{ ok: false, error: 'unknown request nope', ms: 0.01 }

The volume is 40 x 20 x 5 = 4000 up to rounding. A request the kernel refuses is not an exception: it is a normal reply with ok: false and an error string (Errors). Only a trap throws.

Alternatives to a hand-written host

The TypeScript package packages/kernel-client wraps the same steps in three transports with one shape: request(msg) returns a promise of { ok: true, result }, { ok: false, error } (the kernel refused the message) or { ok: false, trap } (the module crashed or the transport failed). Replies come back already decoded, with typed arrays in place of $buf views.

TransportEntry pointWhere the kernel runs
Node workercreateWorkerKernel(wasmPath) in worker.tsa worker_threads worker that owns one WasmHost (wasm-host.ts); the main thread stays free during long regens. wasmPath defaults to $CK_WASM, else the release build in target/.
Browser workercreateBrowserKernel(wasmUrl) in browser.tsa module worker that fetches and compiles the module, then hosts it with the same WasmHost. Large arrays are transferred, not copied.
Native serviceNativeKernel.connect({ url, token }) in native.tsthe ck-native process, over HTTP on the loopback interface

WasmHost is the class that does what Kernel above does: it reboots the instance after a trap and returns a trap as a result of the form { ok: false, trap }. Both worker transports exchange {kind: 'init' | 'call' | 'done' | 'ready' | 'fail', ...} messages with it.

The native service speaks the same protocol over HTTP. A client opens a session with POST /session, which answers {"session": "<id>"}, then posts each request body, exactly the text a wasm host would pass to ck_request, to POST /session/<id>/rpc and gets the reply bytes back unchanged (application/octet-stream, the same framing as ck_reply). Every call except GET /ping and the pairing call carries Authorization: Bearer <token>. A message the kernel refuses is still HTTP 200 with an error reply; a kernel panic (in a service built with the service profile) is HTTP 500 and closes that session. Each session has its own kernel state, like one wasm instance per worker. NativeKernel also checks GET /version against the protocol number it was built for (KERNEL_PROTOCOL, currently 1) before it opens a session. The full description is The native service; Build the kernel shows how to build the service.

See also

A first part

This chapter builds a 100 x 60 x 10 mm plate, regenerates it, adds a hole, validates the result and reads its mass properties. Every reply shown was produced by the kernel through book/tools/run.mjs; long replies are trimmed with .... Lengths are millimetres.

To follow along, save each message list in a file (here first.json) and run

node book/tools/run.mjs target/wasm32-unknown-unknown/release/ck_wasm.wasm first.json

The runner sends the messages in order to one kernel instance, so a later message can refer to the tag of an earlier regen.

The plate

A part is a JSON document: a format name, a version, and a list of features. Each feature has a type and an id; later features refer to earlier ones by id. The plate needs two features: a sketch with four lines, and an extrude that gives the sketch a thickness.

{
  "format": "ck-part", "version": 1, "name": "Plate",
  "features": [
    { "type": "sketch", "id": "F1", "plane": { "kind": "std", "id": "front" },
      "points": [ { "id": "p1", "x": 0, "y": 0 },   { "id": "p2", "x": 100, "y": 0 },
                  { "id": "p3", "x": 100, "y": 60 }, { "id": "p4", "x": 0, "y": 60 } ],
      "entities": [ { "id": "e1", "type": "line", "p1": "p1", "p2": "p2" },
                    { "id": "e2", "type": "line", "p1": "p2", "p2": "p3" },
                    { "id": "e3", "type": "line", "p1": "p3", "p2": "p4" },
                    { "id": "e4", "type": "line", "p1": "p4", "p2": "p1" } ],
      "constraints": [] },
    { "type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 10 }
  ]
}

The sketch lies on the standard plane front, whose normal is +Z. Its points are given by coordinates in the plane; its entities connect points by id. The extrude adds material ("op": "add") from that sketch for a blind depth of 10 along the sketch normal. The part format chapters describe every field.

To regenerate it, send a regen message. tag names the state the kernel keeps for this document; every later query names the same tag.

{ "type": "regen", "tag": "plate", "part": { "format": "ck-part", "...": "the document above" } }

The reply, trimmed:

{
  "ok": true,
  "result": {
    "errors": [],
    "components": [], "planes": [], "markers": [],
    "sketches": [ [ "F1", { "frame": { "o": [0,0,0], "x": [1,0,0], "y": [0,1,0], "z": [0,0,1] },
                            "profiles": { "regions": [ { "outer": [ ... 4 lines ... ], "holes": [] } ], "open": false },
                            "sketch": { ... the sketch as the kernel read it ... } } ] ],
    "sketches3": [], "curves": [],
    "body": {
      "box": { "min": [0, 0, 0], "max": [100, 60, 10] },
      "faces": [
        { "id": "F2.C0", "kind": "plane", "planar": true, "meta": { "feature": "F2" }, "normal": [0, 0, -1] },
        { "id": "F2.C1", "kind": "plane", "planar": true, "meta": { "feature": "F2" }, "normal": [0, 0, 1] },
        { "id": "F2.S.e1", "kind": "plane", "planar": true, "meta": { "feature": "F2", "entity": "e1" }, "normal": [0, -1, 0] },
        ...
      ],
      "edges": [ { "pts": [[0,0,0],[0,0,10]], "faces": ["F2.S.e1","F2.S.e4"], "key": "F2.S.e1|F2.S.e4#0", "mid": [0,0,5], "line": true }, ... ],
      "silhouette": "<buffer f32 x0>",
      "mesh": { "positions": "<buffer f32 x108>", "normals": "<buffer f32 x108>", "mids": "<buffer f32 x108>", "triFace": "<buffer i32 x12>" }
    },
    "surfaces": []
  },
  "ms": 0
}

(The runner prints each binary buffer as a <buffer type xN> summary; a real client gets typed arrays, see Replies and buffers.) What the reply says:

  • errors is empty: both features ran.
  • body is the solid: its bounding box is the 100 x 60 x 10 box, and it has six faces and twelve edges.
  • The face ids show where each face came from. F2.C0 and F2.C1 are the two caps of feature F2 (bottom, normal -Z; top, normal +Z). F2.S.e1 to F2.S.e4 are the side faces made from the sketch entities e1 to e4. These names are stable: they are what later features and queries use to refer to a face (Persistent names).
  • The mesh has 12 triangles (triFace has 12 entries; positions holds 9 numbers per triangle).

Adding a hole

A hole is two more features: a sketch that holds the hole centre, placed on the top face of the plate, and a hole feature that cuts into the face from that sketch. The sketch plane is given as a face id, so the sketch sits on F2.C1 and its coordinates are measured in that face’s plane.

{ "type": "sketch", "id": "F3", "name": "Hole centre", "plane": { "kind": "face", "id": "F2.C1" },
  "points": [ { "id": "c", "x": 20, "y": 30 } ],
  "entities": [ { "id": "e1", "type": "point", "p": "c" } ],
  "constraints": [] },
{ "type": "hole", "id": "F4", "name": "Hole", "sketch": "F3",
  "kind": "simple", "diameter": 8, "end": "through" }

Append both to the features list of the plate and regenerate under the same tag. Each regen replaces the state of its tag, and the kernel reuses the work of the earlier features that did not change.

{ "type": "regen", "tag": "plate", "part": { ... the four features ... } }

In the reply, errors is still [], and the body now has seven faces and fourteen edges: one new cylindrical face, and the two circles where it meets the caps.

"faces": [ ..., 
  { "id": "F2.C1", "kind": "plane", "planar": true, "meta": { "feature": "F2" }, "normal": [0, 0, 1] },
  { "id": "F4.S.h1", "kind": "cylinder", "planar": false, "meta": { "feature": "F4", "entity": "h1" } } ],
"edges": [ ...,
  { "pts": [ ... 23 points ... ], "faces": ["F2.C0", "F4.S.h1"], "key": "F2.C0|F4.S.h1#12", "mid": [22.9, 27.3, 0],
    "circle": { "c": [20, 30, 0], "n": [0, 0, -1], "r": 4 } },
  ... ]

The cylinder F4.S.h1 is named for the feature F4 that made it. Its edges carry circle with the centre, the normal and the radius of 4 mm (the diameter was 8). The pts of an edge are a polyline of the curve for drawing.

To see how the regen was split into steps, add "debug": true to the message: the reply then also has a trace with one entry per feature and per stage (F2 extrude → 6 faces, F4 hole → 7 faces, boolean Subtract (6 × 3 faces) → 7 faces, tessellate 7 faces → 104 triangles). See Protocol overview.

Validate

{ "type": "validate", "tag": "plate" }
{ "ok": true, "result": { "ok": true, "issues": [], "toleranceUsed": 0 }, "ms": 0 }

The outer ok says the request ran; result.ok says the body passed all checks. An invalid body would list issues, each with a code, the entity it concerns and a detail. The validate request describes the checks.

Mass properties

{ "type": "massProps", "tag": "plate" }
{
  "ok": true,
  "result": {
    "volume": 59497.34517542564,
    "area": 15350.796447372313,
    "com": [50.25345071604068, 30, 4.999999999999997],
    "principal": [18493800.59049692, 50037589.30162367, 67539767.47253016],
    "axes": [ [1, 1.4e-17, 8.3e-19], [-1.4e-17, 1, 2.9e-22], [-8.3e-19, -2.9e-22, 1] ]
  },
  "ms": 0
}

These agree with a hand calculation. The volume is the plate minus the hole, 100 x 60 x 10 - pi x 4^2 x 10 = 59497.345 mm^3. The surface area is the plate’s 15 200 mm^2 minus the two removed discs, plus the hole wall: 15200 - 2 x pi x 16 + 2 x pi x 4 x 10 = 15350.80 mm^2. The centre of mass is at mid-thickness (z = 5) and has moved a little in x, away from the hole at x = 20. principal holds the principal moments of inertia of the solid, taken at unit density and about the centre of mass (volume plays the role of mass), and axes the three matching unit directions.

For a mass, give the density of each separate body (here one) per cubic millimetre. Aluminium at 2.7 g/cm^3 is 0.0027 g/mm^3:

{ "type": "massProps", "tag": "plate", "densities": [0.0027] }

This adds bodies: [ { "volume": 59497.3, "area": 15350.8, "com": [...], "mass": 160.64 } ] and a byMass object with the mass (160.64 g) and the principal moments for that density.

Change it and regenerate

Edit the document and send it again. Making the plate 12 thick (the depth of F2) gives a new volume of 100 x 60 x 12 - pi x 4^2 x 12 = 71396.81 mm^3; the kernel answers

{ "volume": 71396.81421051078, "area": 16041.06192982975, "com": [50.25345071604068, 30, 6], ... }

and the face ids are unchanged, so a feature that referred to F2.C1 or F4.S.h1 still works.

When a feature cannot be built, the regen still succeeds as a request: the error is reported per feature and the rest of the document runs on what exists. Setting the hole diameter to 0:

"errors": [
  [ "F4", { "code": "holeInvalid",
            "params": { "hint": "the hole diameter must be greater than zero (a standard `size`, or a positive `diameter`)" } } ]
]

The body is then the plate without a hole: six faces, the state from before F4. Each entry of errors is [feature id, { code, params }], and params.hint says what to change. Errors lists the codes.

To stop early, pass "opts": { "upTo": 2 } to regenerate only the first two features; with the four-feature document that gives the plate without the hole (six faces, as above).

See also

Overview of the part format

A part is one JSON document, normally stored as a .ckpart file. It holds an ordered list of features; the kernel runs them from first to last (a regeneration, or “regen”) and builds the sketches, planes, curves and bodies they describe. This chapter covers the document as a whole: the top-level fields, feature ids, suppression, rollback, units, coordinate frames and what is checked when a document is read.

The shortest valid part

A part needs a format and a features array. Nothing else is required.

{"format": "ck-part", "features": []}
{"format": "ck-part", "version": 1, "features": []}

Run result: no errors; no solid body. An empty features list is a valid part.

Top-level fields

FieldTypeDefaultMeaning
formatstringrequiredMust be "ck-part". Documents saved by earlier versions are read too (see versions).
versionnumber1Version of the document format. A value above the kernel’s own (1) is still read and the regen reply says so (see versions). A missing or non-numeric value counts as 1.
namestring""Display name. The kernel does not use it.
featuresarrayrequiredThe regen program, in order. See below.
variablesarray of {name, expr}noneGlobal variables usable in expressions. See variables and expressions.
seqnumber0Counter used by editors to mint feature ids ("F" + seq). The kernel reads it and never uses it.
rollbacknumber or nullnullRegenerate only the first N features. See rollback.
materialstring""Material name. The kernel does not use it for geometry or mass properties.
countersobject of numbers{}Per-command-name counters that editors use to number feature names ({"sketch": 4, "extrude": 2}). Not used by the kernel.
blobsobject of stringsnoneData that features refer to by key, such as the STEP text of an importStep feature. The key is the SHA-256 of the text, in lower-case hex.
kindstring"""assembly" marks an assembly document. The regen does not branch on it: an assembly is a part whose features are insertPart and mate (see parts and assemblies).

Any other top-level field (a thumbnail, editor settings, fields written by a newer version) is not read and is left untouched. The kernel never rejects a document for having extra fields.

A complete small part, with the editor fields filled in:

{
  "format": "ck-part", "version": 1, "name": "Plate", "seq": 3, "rollback": null, "material": "steel",
  "counters": {"sketch": 1, "extrude": 1},
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 40, "y": 0},
        {"id": "c", "x": 40, "y": 20},
        {"id": "d", "x": 0, "y": 20}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 10}
  ]
}

Run result: no errors; 6 faces, volume 8000 mm³. The faces are F2.C0, F2.C1, F2.S.e1, F2.S.e2, F2.S.e3, F2.S.e4.

Run this way, a 40 x 20 x 10 mm plate has six faces. The names are explained in identifiers and references. The other chapters of this part reuse this plate as a base and show only the features they append to it.

Features

Every entry of features is an object with a common envelope and type-specific fields.

FieldTypeDefaultMeaning
typestring""The feature type, for example "sketch" or "extrude". Features lists every type.
idstring""The feature id (see below).
numnumber0Display ordinal among features of the same kind. Not used by the kernel.
namestring""Display name. Not used by the kernel.
suppressedbooleanfalseWhen true the feature is skipped.

All other fields belong to the feature type. A field the kernel does not know is kept and ignored.

Feature ids and seq

An id is a string. Editors write F1, F2, … and keep seq one above the highest number used, so the next feature gets "F" + seq. Plane features may carry other ids; the kernel accepts any string.

Ids are the names that other features and the regen reply use:

  • a feature refers to an earlier feature by id ("sketch": "F1", "seeds": ["F4"], {"kind": "feature", "id": "P1"});
  • the faces a feature creates start with its id (F2.C1), see identifiers and references;
  • the regen reply lists errors, warnings, sketches and planes keyed by feature id.

The kernel does not check that ids are unique. Results keyed by id overwrite each other, so two features with one id make a document that is hard to read back. A feature without an id is keyed by the empty string.

Features are run in list order and can refer only to features before them. A reference to a later feature behaves like a reference to a missing one (for example missingSketch).

Errors do not stop the regen

A feature that fails reports its error under its id, contributes nothing, and leaves the body as it was. The features after it still run.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 40, "y": 0},
        {"id": "c", "x": 40, "y": 20},
        {"id": "d", "x": 0, "y": 20}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 10},
    {
      "type": "sketch", "id": "F3", "plane": {"kind": "face", "id": "F2.C1"},
      "points": [{"id": "c", "x": 20, "y": 10}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 4}], "constraints": []
    },
    {"type": "extrude", "id": "F4", "op": "cut", "sketch": "F3", "end": "blind", "depth": "=oops"},
    {"type": "extrude", "id": "F5", "op": "cut", "sketch": "F3", "end": "blind", "depth": 3}
  ]
}

Run result: errors F4: badExpression; 8 faces, volume 7849.2036 mm³.

Here F4 fails and F5 still cuts the pocket from the body that F2 left. A feature that depends on the output of a failed feature fails too (a missing sketch, a face that does not exist).

Suppression

"suppressed": true removes a feature from the run: it produces no output and no error. The value is read as a truth value: true, a non-zero number or a non-empty string all suppress. Here the extrude is added after the rectangle sketch F1 of the plate and suppressed:

{
  "type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 10,
  "suppressed": true
}

Run result: no errors; no solid body. The sketch is regenerated (1 sketch in the reply); the suppressed extrude adds nothing.

Features after a suppressed one that need its output fail as if it did not exist. Suppressing a sketch makes the features that use it report missingSketch.

Visibility flags

visible (on sketches, planes and helices) and userHidden (on planes) are display flags for editors. The kernel regenerates the feature in the same way whatever their value: a sketch with "visible": false still feeds its extrude, and a plane with "visible": false still appears in the planes list of the reply.

Rollback and upTo

Two settings limit the number of features that run:

  • rollback in the document: a number N runs the first N features (rollback: 1 runs only the first). It is how an editor shows the model at an earlier step.
  • opts.upTo in the regen request: the same limit for one request, without changing the document. See regeneration.

When both are present the smaller one wins. A value that is not a number is ignored ("rollback": "1" and "upTo": "1" do nothing); a negative rollback runs no features. Suppressed features inside the range count towards N. An inserted part ignores its own rollback (see parts and assemblies). Setting "rollback": 1 on the plate above gives this document:

{
  "format": "ck-part", "version": 1, "rollback": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 40, "y": 0},
        {"id": "c", "x": 40, "y": 20},
        {"id": "d", "x": 0, "y": 20}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 10}
  ]
}

Run result: no errors; no solid body. Only F1 runs (1 sketch in the reply).

Units

Lengths are in millimetres and angles are in degrees, in every field and in every reply. Numbers in expressions may carry a unit suffix that converts to these units (2 cm, 1 in); see variables and expressions.

Coordinate frames

The world frame is right-handed. The three standard sketch planes are frames with an origin o and axes x, y, z (the plane normal):

Planexyz (normal)
front(1, 0, 0)(0, 1, 0)(0, 0, 1)
top(1, 0, 0)(0, 0, -1)(0, 1, 0)
right(0, 0, -1)(0, 1, 0)(1, 0, 0)

All three pass through the world origin. A sketch point (u, v) on a plane with frame (o, x, y) is the world point o + u x + v y. Reference planes and planar faces provide further frames; see planes and sketches.

What is checked when a document is read

The kernel is lenient on purpose. Reading a document fails in exactly one way, with the text invalid part: Format. It happens when:

  • the document is not a JSON object;
  • format is missing, or is not "ck-part" (or one of the earlier names, see versions);
  • features is missing or is not an array.

Over the wire the reply is {"ok": false, "error": "invalid part: Format"} (see errors).

Everything else is accepted and handled while the features run, one feature at a time:

SituationResult
A feature is not an object, or has no typeunknownFeature with type: "", keyed by "".
A feature has a type the kernel does not knowunknownFeature with the type in params.type.
A field is missing or has the wrong JSON typeThe default is used (see the field tables). Features then report their own errors, for example missingSketch.
A numeric field holds a string"=expr" is an expression, a plain numeric string is that number, any other string is 0. See variables and expressions.
A boolean field holds a number, string, array or objectTruth value: true, non-zero numbers, non-empty strings, arrays and objects are true. "false" is a non-empty string and so true.
A sketch entity has an unknown typeThe entity is dropped without an error.
variables is not an array, or seq, name, material, counters have the wrong typeThe field is ignored.

The per-feature error codes are listed with each feature in the chapters that follow, and all of them are collected in feature errors and diagnostics.

See also

Identifiers and references

Features refer to each other, to sketch entities and to the faces and edges of the body by name. This chapter defines the identifiers, the grammar of face names, how edges are picked, and what keeps a name stable.

Kinds of identifier

IdentifierScopeExampleWhere it is used
Feature idthe partF4, P1sketch, seeds, path, {"kind": "feature", "id": ...} and as the first part of face names.
Sketch point idone sketcha, p3, Oentities, constraints, {"kind": "sketchPoint", ...}.
Sketch entity idone sketche1, axconstraints, axis of a revolve, regions, in face names.
Constraint idone sketchk1Solver status (conflicts, redundant).
Face namethe bodyF2.C1, F2.S.e3~2@F5.1Anywhere a face is referenced.
Edge keythe bodyF2.C1|F2.S.e1#0In replies and queries. Edges are referenced by their two faces.
Body namethe bodyCaseThe body field and {"body": ...} selectors.

Ids are free-form strings; editors use F<n> for features, e<n> for sketch entities and p<n> for points. The kernel only requires that a reference finds an entity with the same text.

A sketch entity id appears in the names of the faces made from it, so renaming an entity renames those faces.

Reference objects

A reference to a geometric object is a string or an object with a kind:

FormMeaningUsed by
"F3"A feature id, or a sketch entity id when the field takes one (a revolve axis).sketch, seeds, surfaces
{"kind": "std", "id": "front"}A standard plane.planes, mirrors, drafts
{"kind": "face", "id": "F2.C1"}A face of the body.sketch planes, plane bases, endRef, neutral
{"kind": "feature", "id": "P1"}The plane or axis made by a feature.planes, patterns
{"kind": "curve", "id": "F11"}A curve feature (a helix or a curve made by projectCurve).sweep path, curve lists
{"kind": "axis", "axis": "x"}A world axis through the origin.patterns, plane axes, insertPart
{"faces": ["F2.C1", "F2.S.e1"], "at": [20, 0, 10]}An edge: see below.fillet, chamfer, lip, fill, extend, pipeCut

The kernel keeps any other {kind} object unchanged; a feature that cannot use it reports missingReference. The kinds that only planes and curve lists take (sketchPoint, vertex, sketchCurve, sketchLine, edge) are in planes.

Face names

A face name has the grammar

name     := feature '.' role [ '~' k ] { '@' instance }
role     := 'C' digits            a cap
          | 'S.' entity           a side face from a sketch entity
          | 'B' digits            a blend (fillet or chamfer) face
          | other                 a tag written by the feature (h1, T0, P, F, W0, ...)
instance := feature '.' digits
  • feature is the id of the feature that made the face.
  • ~k numbers the pieces when one logical face was split, counted from 1. A sketch with several closed regions numbers them: each region has its own caps (F2.C0~1, F2.C0~2) and a side face is numbered when its entity is shared by or split between regions. A shell makes outer and inner copies of each wall (F2.C0~1 is the outer floor and F2.C0~2 the inner one for the plate below).
  • @F5.1 marks a copy. A pattern, mirror, moveBody with copy or an inserted part adds the id of the feature and the number of the instance. Copies of copies chain: F8.S.h1@F9.1@F1.1.

Names made by each feature

FeatureFaces
extrudeC0 (the cap whose outward normal is against the sketch normal), C1 (outward normal along the sketch normal), S.<entity> for every profile entity. With thin: S.<entity>.W0, .W1 (the two walls), .E0, .E1 (end caps of an open chain), .W0r, .W0m, .W0b (corner pieces).
revolveS.<entity>; C0 at the start angle (in the sketch plane) and C1 at the end for a partial turn; no caps for a full turn.
sphereS.e1.
sweepS.<profile entity> (split ~k along the path pieces), C0 and C1.
loftS.<entity> named by the entities of the first section, C0 and C1; no cap at a point end.
holeS.h1 (wall), S.h2 (bottom), S.h3, S.h4 and S.K0 for the stepped and cone kinds; ~k per hole when a sketch has several points.
fillet, chamferB0, B1, … one per blended edge, V0… for the sphere patch at a vertex where three edges meet.
ribC0, C1, S.<entity>r.
lipC1 (top of a lip) or C0 (floor of a groove) and S.<rim neighbour face>l.
thread (modeled)T0 … T5, the faces of the groove tool.
thickenW0, W1, … walls; the sheet faces keep their name with ~1 and ~2.
surfaceExtrude, surfaceRevolveS.<entity>.
surfacePlanarP.
fillF.
knit, trimSurface, deleteFaceThe faces of the input surfaces keep their names.
pressPullThe moved end keeps the name of the face; new walls are <id>.S.<tag> from the names of the faces across the edges; the old cap is consumed.
draft, moveFace, scale, moveBody without copy, combineAll names are unchanged. A boolean that splits a face adds ~k.
lpattern, cpattern, mirror, moveBody with copyThe copies of the seed faces, with @<feature>.<k> (k from 1; the seed is not renamed).
insertPartEvery face of the part, with @<insert id>.1.

The chapters on solids, edits, patterns, surfaces and assemblies give the details with each feature.

{"type": "shell", "id": "F3", "faces": ["F2.C1"], "thickness": 2}

Run result: no errors; 11 faces, volume 3392 mm³. The faces are F2.C0~1, F2.S.e1~1, F2.S.e2~2, F2.S.e3~2, F2.S.e4~1, F2.C1, F2.C0~2, F2.S.e1~2, F2.S.e2~1, F2.S.e3~1, F2.S.e4~2.

[
  {
    "type": "sketch", "id": "F3", "plane": {"kind": "face", "id": "F2.C1"},
    "points": [{"id": "c", "x": 8, "y": 10}],
    "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 3}], "constraints": []
  },
  {"type": "extrude", "id": "F4", "op": "cut", "sketch": "F3", "end": "blind", "depth": 4},
  {
    "type": "lpattern", "id": "F5", "seeds": ["F4"], "dir": {"kind": "axis", "axis": "x"}, "spacing": 12,
    "count": 3
  }
]

Run result: no errors; 12 faces, volume 7660.708 mm³. The pocket faces are F4.C0, F4.S.e1, F4.C0@F5.1, F4.S.e1@F5.1, F4.C0@F5.2, F4.S.e1@F5.2.

Edges

Edges have no names of their own. An edge is the meeting of two faces, so a reference to an edge is the pair of face names plus a point on the edge:

{"faces": ["F2.C1", "F2.S.e1"], "at": [20, 0, 10]}

The kernel takes the edge shared by the two faces that is nearest to at. When only one edge joins the faces at makes no difference; it is a tie-breaker for faces that meet in several edges (a cylinder and its cap, split faces), and it keeps a reference unambiguous after upstream edits move the edge.

In replies an edge is identified by a key A|B#n: the two face names in byte order, and a counter n that tells apart edges between the same pair of faces. body.edges[].key carries it.

Stability of names

A name is derived from how the geometry was made, never from a position or an index into the mesh. Editing the numbers of an earlier feature (a depth, a radius, a sketch dimension) keeps names that still exist, so later features follow. Names change when topology changes:

  • adding or removing a closed region in a sketch changes the ~k numbering of the faces of the features built from it;
  • deleting or reordering a feature leaves references to it pointing at faces that no longer exist: the feature that uses them reports missingReference, or in the worst case points at a different face with the same name. The refDiff request reports such changes (see queries);
  • a face split by a later feature is named with ~k pieces; moveFace, draft and lip accept the name without ~k and take every piece, other features need the exact name.

An edge pick never moves to another feature’s faces or to another body. It needs both face names (or their ~k family) to exist; if either is gone the feature reports missingEdge, however close the at point is to some other edge. The only fallback is for a pair whose ~k numbers shifted: the edge between faces of the same two features that passes through at (within 1e-6 relative). A suppressed maker therefore makes its dependants report missingEdge and nothing else is rounded; unsuppressing it restores the pick. Renaming a sketch entity renames its faces, so picks that used the old id are lost, not re-pointed. The error names the face that is gone and lists the faces the feature has now (gone, candidates), or, when both faces exist, the faces the first one meets (neighbours), so the pick can be repaired in one step.

Prefer caps (C0, C1) and sketch-entity sides (S.<entity>) over positions, and let the resolve query turn a description into names (see queries).

{"type": "moveFace", "id": "F3", "faces": ["F9.C1"], "distance": 1}

Run result: errors F3: missingReference {"ref":"F9.C1"}; 6 faces, volume 8000 mm³.

Body names

A feature that makes a separate body can name it: "op": "newBody", "body": "Case". The name is stored on the body (a lump) and follows it through later features. {"body": "Case"} then selects it in moveBody, combine, deleteBody and scale. See patterns and transforms and edge and face edits.

See also

Variables and expressions

Numeric fields in a part can hold an expression instead of a number, and a part can define global variables for expressions to use. This chapter gives the grammar, the units, the functions, the rules for variables and the result of each kind of mistake.

Where expressions are accepted

  • Every numeric feature field that the field tables in this part list as “number or expression”: depths, radii, angles, offsets, distances, counts, vector components such as translate.
  • The expr field of a dimensional sketch constraint; the kernel then recomputes the constraint’s value (see sketches).
  • The expr of a global variable.

Sketch point coordinates and circle radii are plain numbers. A string there is converted when it is a plain number ("3" becomes 3) and anything else, including "=2+3", becomes 0. To drive a coordinate from a variable, add a constraint with an expr.

Field values

A numeric field is read as follows:

JSON valueResult
numberthat number
string starting with = (leading spaces allowed)the value of the expression; a syntax error, an unknown name or a non-finite result is badExpression
any other stringthe string read as a plain number after trimming spaces; 0 if it is not one
missing, null, boolean, array, objectthe default of the field
Field valueValue
77
"7"7
" 7 "7
"2*3"0
"abc"0
"1in"0
true0
null0

(Run as a translation distance; the default of that field is 0.)

A field holding "=expr" fails its feature with badExpression when the expression is bad; the feature’s other checks come after it.

Grammar

expr   := term (('+' | '-') term)*
term   := power (('*' | '/') power)*
power  := unary ('^' power)?                 right associative
unary  := '(' expr ')' | '-' power | '+' power
        | name                               variable, or pi
        | function '(' expr ')'
        | function2 '(' expr (',' expr)* ')'   the functions of the second table below
        | number [unit]
number := digits ['.' [digits]] | '.' digits, with an optional exponent (e5, E-3)
unit   := mm | cm | m | in | deg | °         case-insensitive
  • A leading = is optional inside variable definitions and constraint exprs and is removed. Spaces are allowed between tokens.
  • , is read as the decimal separator, so 1,5 is 1.5, except directly inside the parentheses of a call to one of the functions of the second table, where it separates the arguments: max(1,5) is 5 and max(1.5, 2) is 2.
  • Variable names are case sensitive. pi and the function names are case-insensitive.
  • ^ binds tighter than unary minus, so -2^2 is -4 and 2^3^2 is 512.
  • Functions are sqrt, sin, cos, tan and abs, with one argument in parentheses. Trigonometric functions take degrees.
  • More functions, written in lower case and always followed by (:
FunctionArgumentsValue
min, maxone or morethe smallest, the largest
pow(a, b)2a to the power b
mod(a, b)2the remainder of a / b, with the sign of a
hypot(a, b)2sqrt(a^2 + b^2)
atan2(y, x)2the angle of the point (x, y), in degrees
asin, acos, atan1an angle in degrees
round1the nearest whole number, halves away from zero
floor, ceil, trunc1rounded down, up, towards zero
exp, ln, log101e to the power, natural and decimal logarithm
sinh, cosh, tanh1hyperbolic functions of a plain number (not degrees)
asinh, acosh, atanh1their inverses, plain numbers (not degrees); acosh needs 1 or more, atanh needs a number between -1 and 1 (both ends excluded)

A wrong number of arguments, an argument or a result that is not finite (ln(0), asin(2), mod(1, 0), acosh(0.5), atanh(1), sinh(1000)), or a name in capitals (MAX(1, 2)) is a syntax error. These names are not reserved: a variable may still be called max or round, and max * 2 is that variable times 2; only a name followed by ( is the function.

  • Units scale a number to millimetres or degrees: cm is 10, m is 1000, in is 25.4, mm, deg and ° are 1. A unit directly after a name or a parenthesis is a syntax error.
  • A result that is not finite (1/0, 1e400) is a syntax error.

Values of expressions as the kernel evaluates them (rounded to nine decimals; the variable w is 30 here):

ExpressionValue
=2^38
=2^3^2512
=-2^2-4
=10/42.5
=(1+2)*39
=2*3+410
=1e110
=.50.5
=1,51.5
=3 mm3
=2 cm20
=1 in25.4
=3 m3000
=sqrt(16)4
=SQRT(16)4
=abs(-4)4
=max(3, 1, 2)3
=mod(-7, 4)-3
=round(-2.5)-3
=atan2(1, 1)45
=hypot(3, 4)5
=ln(0)badExpression
=sin(30)0.5
=cos(60)*105
=tan(45)1
=pi3.141592654
=PI*26.283185307
=--33
=1/0badExpression
=abcbadExpression
=7)badExpression
=sqrt 4badExpression
=3 mxbadExpression
=WbadExpression

Global variables

variables is a list of definitions in the document:

FieldTypeMeaning
namestringLetters, digits and _, not starting with a digit. Case sensitive.
exprstring or numberThe value, an expression. A number is accepted and read as its text.

Variables can use each other in any order. The kernel repeatedly resolves every variable whose expression mentions no variable that is still unresolved. A variable that cannot be resolved does not stop the document:

ProblemEffect
Invalid name, a name equal to pi, a function name or a unit (mm, cm, m, in, deg) in any letter case, or a name already definedThe definition is dropped. For a repeated name the first definition is kept.
expr does not evaluateThe variable is left undefined.
A cycle (a = b + 1, b = a + 1)The variables in the cycle are left undefined.

The problems are not reported on their own. A field that uses an undefined variable fails with badExpression, because the name is then unknown.

{
  "format": "ck-part", "version": 1,
  "variables": [{"name": "t", "expr": "4"}, {"name": "d", "expr": "=t*2"}],
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [{"id": "c", "x": 0, "y": 0}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 10}], "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": "=d"}
  ]
}

Run result: no errors; 3 faces, volume 2513.2741 mm³. The extrude depth is 8, so the cylinder top is at z = 8.

{
  "format": "ck-part", "version": 1,
  "variables": [{"name": "a", "expr": "b+1"}, {"name": "b", "expr": "a+1"}],
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [{"id": "c", "x": 0, "y": 0}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 10}], "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": "=a"}
  ]
}

Run result: errors F2: badExpression; no solid body.

See also

Planes

Sketches are drawn on planes. This chapter covers the three standard planes, the planes that follow a face or a reference, the plane feature with all of its modes, and the axis feature that planes and other features use as a line.

Plane references

A plane is given as a reference object wherever a feature needs one: the plane of a sketch, the base of a plane feature, the neutral of a draft, the plane of a mirror.

ReferenceMeaning
{"kind": "std", "id": "front"}A standard plane: front, top or right.
{"kind": "feature", "id": "P1"}The plane made by an earlier plane feature.
{"kind": "face", "id": "F2.C1"}A planar face of the body made so far.

Any other reference, a face that is not planar, and a feature that is not a plane resolve to nothing: a sketch then reports missingReference.

The frames of the standard planes are in the overview. front is the XY plane with normal +Z, top is the XZ plane with normal +Y and right is the ZY plane with normal +X.

Frame of a face

The frame of a planar face is computed from its plane alone:

  • z is the outward normal of the face;
  • o is the point of the face plane closest to the world origin (the origin projected onto the plane);
  • x is the world Y axis crossed with z and normalised; when z is within about 8 degrees of the Y axis (|z.y| > 0.99), x is the world X axis instead;
  • y is z × x.

For the right face F2.S.e2 of the plate this gives o = (40, 0, 0), x = (0, 0, -1), y = (0, 1, 0), z = (1, 0, 0), the frame of the standard right plane moved to the face. A sketch on a face starts at the projected world origin, not at the face centre.

The plane feature

A plane feature creates a reference plane. Its frame appears in the planes list of the regen reply, keyed by the feature id, and other features refer to it as {"kind": "feature", "id": "P1"}.

FieldTypeDefaultMeaning
modestring"offset"How the plane is made. See the table below; an unknown mode behaves as offset.
baseplane referencenoneThe plane the mode starts from (offset, angle, perpendicular, mid, parallel, tangent).
offsetnumber or expression0Distance along the plane normal (offset, curve).
flipbooleanfalseTurns the plane around: x and z are negated (for normal the z and y axes). In angle mode it negates the angle.
axisaxis referencenoneThe line the plane turns about or contains (angle, perpendicular, linePoint, tangent).
anglenumber or expression0Degrees, for angle.
base2plane referencenoneThe second plane of mid.
pointslist of point referencesnonePoints for threePoints, linePoint, parallel, normalCurve, tangent.
curveslist of curve referencesnoneCurves for curve and normalCurve.
pathsketch idnoneThe path of normal.
atEndbooleanfalsenormal, normalCurve: use the end of the path instead of its start.
face, tangentTo, second, atsee tangentThe tangent mode.
origin, xDir, yDir[x, y, z]noneThe frame mode.
visible, userHiddenbooleantrue, falseDisplay flags, ignored by the kernel.

The frame of every mode is right-handed with z the plane normal. The origin o is given per mode below.

Modes

modePlaneOrigin and axes
offsetParallel to base, moved along its normal by offset.The base frame with o = base.o + z * offset. With flip the base x and z are negated before the offset is applied, so the plane faces the other way and the offset follows.
anglebase turned about axis by angle degrees, right-handed about the axis direction.The plane contains the axis line; o is the origin of the axis. When the axis lies in the base plane it becomes the new x.
perpendicularContains axis and is perpendicular to base.x is the axis direction, y the base normal made perpendicular to it.
midHalfway between base and base2.For parallel planes the base frame moved halfway. Otherwise the bisector plane through the line where they meet.
threePointsThrough three points.o is the first point, x points towards the second, z is x crossed with the direction to the third.
linePointThrough a line (axis) and a point (points[0]).o is the foot of the point on the line, x the line direction.
parallelParallel to base, through a point (points[0]).The base frame moved along its normal to the point.
normalPerpendicular to the sketch path at its start (or end with atEnd).z is the path direction there. The path is an open chain of lines and arcs in a sketch, or a sketch3d holding one spline.
normalCurvePerpendicular to the first of curves at points[0] (the nearest point on the curve) or at the start (end with atEnd).z is the curve tangent.
curveThe plane of the planar curves, moved along its normal by offset.o is the length-weighted centre of the curves.
tangentTangent to a sphere or cylinder face. tangentTo selects what fixes it: "point" (default, points[0] or at), "plane" (parallel to base) or "line" (through axis); second takes the other of the two solutions.z is the normal of the tangent plane.
frameGiven outright by origin, xDir and yDir.x is kept, y is made square to it, z = x × y.

Reference kinds used by the modes:

ForReference
a point{"kind": "sketchPoint", "sketch": "F1", "point": "a"}, {"kind": "vertex", "faces": ["F2.C1", "F2.S.e1", "F2.S.e2"], "at": [40, 0, 10]} (the vertex shared by the faces, nearest to at)
a curve{"kind": "sketchCurve", "sketch": "F1", "entity": "e1"} (a line, arc or circle), {"kind": "curve", "id": "F5"} (an earlier curve feature), {"kind": "edge", "faces": [..], "at": [..]} (a body edge)
an axis{"kind": "axis", "axis": "x"} (a world axis through the origin), {"kind": "feature", "id": "A1"} (an axis feature), {"kind": "edge", "faces": [..], "at": [..]} (a straight edge), {"kind": "sketchLine", "sketch": "F1", "entity": "e1"}

Errors

CodeWhen
missingReferenceA needed field is missing or does not resolve: no base (or base not a plane), no axis for angle/perpendicular/linePoint, fewer than three points for threePoints, a curve or face that cannot be found.
planeLineNormalperpendicular: the axis is parallel to the normal of base.
planePointsInLinethreePoints (collinear points) and frame (parallel xDir and yDir).
planePointOnLinelinePoint: the point is on the line.
planesParallelaxis made of two planes that are parallel.
missingPathnormal without a path, or a path that has no segments.
sweepPathInvalidnormal: the sketch is not a single open chain.
curvesNotPlanarcurve: the curves do not lie in one plane (params.dev is the deviation).
curvesStraightcurve: the curves are collinear, so the plane is not defined.
planeNotTangenttangent: the face is not a sphere or cylinder, or the requested tangent plane does not exist.
badExpressionA numeric field holds a bad expression.

A failed plane feature adds no frame to the reply, so the sketches that use it report missingReference too.

Examples

Offset planes. The top plane offset by 10 lies at y = 10; flip on a right plane negates its normal before the offset, so the second plane is at x = -10:

{
  "format": "ck-part", "version": 1,
  "features": [
    {"type": "plane", "id": "P1", "mode": "offset", "base": {"kind": "std", "id": "top"}, "offset": 10},
    {
      "type": "plane", "id": "P2", "mode": "offset", "base": {"kind": "std", "id": "right"},
      "offset": 10, "flip": true
    }
  ]
}

Run result: no errors; no solid body. P1: o [0,10,0], x [1,0,0], y [0,0,-1], z [0,1,0]. P2: o [-10,0,0], x [0,0,1], y [0,1,0], z [-1,0,0].

A sketch on a plane feature, then extruded. The sketch origin is the plane origin:

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "plane", "id": "P1", "mode": "offset", "base": {"kind": "std", "id": "front"},
      "offset": 12
    },
    {
      "type": "sketch", "id": "F2", "plane": {"kind": "feature", "id": "P1"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 10, "y": 0},
        {"id": "c", "x": 10, "y": 10},
        {"id": "d", "x": 0, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "extrude", "id": "F3", "op": "add", "sketch": "F2", "end": "blind", "depth": 3}
  ]
}

Run result: no errors; 6 faces, volume 300 mm³. The sketch frame is o [0,0,12], x [1,0,0], y [0,1,0], z [0,0,1]. The body spans z from 12 to 15.

Planes from a face of the plate (appended to the features of the plate in the overview). The offset is measured along the outward normal of the face:

[
  {"type": "plane", "id": "P1", "mode": "offset", "base": {"kind": "face", "id": "F2.C1"}, "offset": 5},
  {
    "type": "plane", "id": "P2", "mode": "offset", "base": {"kind": "face", "id": "F2.S.e2"},
    "offset": 0
  }
]

Run result: no errors; 6 faces, volume 8000 mm³. P1: o [0,0,15], x [1,0,0], y [0,1,0], z [0,0,1]. P2: o [40,0,0], x [0,0,-1], y [0,1,0], z [1,0,0].

A plane turned about a world axis, and a plane perpendicular to the front plane through the same axis:

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "plane", "id": "P1", "mode": "angle", "base": {"kind": "std", "id": "front"},
      "axis": {"kind": "axis", "axis": "x"}, "angle": 30
    }
  ]
}

Run result: no errors; no solid body. P1: o [0,0,0], x [1,0,0], y [0,0.866025404,0.5], z [0,-0.5,0.866025404].

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "plane", "id": "P1", "mode": "perpendicular", "base": {"kind": "std", "id": "front"},
      "axis": {"kind": "axis", "axis": "x"}
    }
  ]
}

Run result: no errors; no solid body. P1: o [0,0,0], x [1,0,0], y [0,0,1], z [0,-1,0].

The axis of a perpendicular plane cannot be parallel to the base normal:

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "plane", "id": "P1", "mode": "perpendicular", "base": {"kind": "std", "id": "front"},
      "axis": {"kind": "axis", "axis": "z"}
    }
  ]
}

Run result: errors P1: planeLineNormal; no solid body.

A plane through three sketch points, and a plane from a line and a point:

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 10, "y": 0},
        {"id": "c", "x": 0, "y": 10}
      ],
      "entities": [], "constraints": []
    },
    {
      "type": "plane", "id": "P1", "mode": "threePoints",
      "points": [
        {"kind": "sketchPoint", "sketch": "F1", "point": "a"},
        {"kind": "sketchPoint", "sketch": "F1", "point": "b"},
        {"kind": "sketchPoint", "sketch": "F1", "point": "c"}
      ]
    }
  ]
}

Run result: no errors; no solid body. P1: o [0,0,0], x [1,0,0], y [0,1,0], z [0,0,1].

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [{"id": "a", "x": 5, "y": 8}], "entities": [], "constraints": []
    },
    {
      "type": "plane", "id": "P1", "mode": "linePoint", "axis": {"kind": "axis", "axis": "x"},
      "points": [{"kind": "sketchPoint", "sketch": "F1", "point": "a"}]
    }
  ]
}

Run result: no errors; no solid body. P1: o [5,0,0], x [1,0,0], y [0,1,0], z [0,0,1].

A plane normal to the end of a sketch path:

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [{"id": "a", "x": 0, "y": 0}, {"id": "b", "x": 0, "y": 30}],
      "entities": [{"type": "line", "id": "e1", "p1": "a", "p2": "b"}], "constraints": []
    },
    {"type": "plane", "id": "P1", "mode": "normal", "path": "F1", "atEnd": true}
  ]
}

Run result: no errors; no solid body. P1: o [0,30,0], x [0,0,1], y [1,0,0], z [0,1,0].

The axis feature

An axis feature defines a line that other features can use as a pattern direction, a plane axis or a revolve axis reference through {"kind": "feature", "id": "A1"}. Its refs list holds either one reference or two planes.

refsLine
one world axis, straight edge or sketch linethat line
one {"kind": "face", "id": ...} naming a cylindrical facethe axis of the cylinder; faceNotCylindrical if the face is another surface
two planes (standard, feature or face)the line where they meet, planesParallel if they are parallel
anything elsemissingReference

An axis produces no entry in the reply; it is used by the features after it.

{
  "format": "ck-part", "version": 1,
  "features": [
    {"type": "axis", "id": "A1", "refs": [{"kind": "axis", "axis": "y"}]},
    {
      "type": "plane", "id": "P1", "mode": "angle", "base": {"kind": "std", "id": "front"},
      "axis": {"kind": "feature", "id": "A1"}, "angle": 45
    }
  ]
}

Run result: no errors; no solid body. P1: o [0,0,0], x [0,1,0], y [-0.707106781,0,0.707106781], z [0.707106781,0,0.707106781].

{
  "format": "ck-part", "version": 1,
  "features": [
    {"type": "plane", "id": "Q1", "mode": "offset", "base": {"kind": "std", "id": "front"}, "offset": 5},
    {
      "type": "axis", "id": "A1",
      "refs": [{"kind": "std", "id": "top"}, {"kind": "feature", "id": "Q1"}]
    },
    {
      "type": "plane", "id": "P1", "mode": "angle", "base": {"kind": "std", "id": "front"},
      "axis": {"kind": "feature", "id": "A1"}, "angle": 90
    }
  ]
}

Run result: no errors; no solid body. P1: o [0,0,5], x [1,0,0], y [0,0,1], z [0,-1,0]. Q1: o [0,0,5], x [1,0,0], y [0,1,0], z [0,0,1].

See also

Sketches

A sketch is a feature that holds 2D geometry on a plane: points, curves built on those points, and constraints between them. Solid features take their profiles from sketches. This chapter covers the fields of a sketch, the curve types, the constraint types, how closed profiles are found and what a regen returns. The solver behind the constraints has its own chapter, the sketch solver.

Fields of a sketch

FieldTypeDefaultMeaning
typestringrequired"sketch".
idstringFeature id, see identifiers.
planeplane referencerequired{"kind": "std" | "feature" | "face", "id": ...}, see planes. A missing or unresolved plane is missingReference.
pointsarray[]The points of the sketch.
entitiesarray[]The curves, built on points.
constraintsarray[]The constraints.
seqnumber0Counter an editor uses to mint ids inside the sketch. Not used by the kernel.
visiblebooleantrueDisplay flag. Not used by the kernel.
namestring""Display name.

A point (u, v) of a sketch is the world point o + u x + v y of the frame of its plane. The reply returns that frame for every sketch, so a client does not have to compute it.

Points

FieldTypeDefaultMeaning
idstring""Point id. Unique in the sketch; a repeated id resolves to the last point with it.
x, ynumber0Coordinates in the plane, mm. A numeric string is converted; anything else is 0. Expressions are not evaluated here.
fixedbooleanfalseThe solver does not move this point.

Editors create every sketch with a fixed point O at the origin so constraints can refer to it. The kernel does not require it.

Entities

Curves refer to points by id. Every entity has an id and a type; a construction flag (true) keeps a curve out of profiles and out of sweeps and lofts: it is helper geometry such as an axis line.

typeFieldsGeometry
linep1, p2The segment between two points.
circlec, rCentre point c, radius r (number). "ext": true or "from": true marks a circle whose radius is driven by something else: the solver does not treat r as unknown.
arcc, p1, p2Counter-clockwise from p1 to p2 around c. The radius is the distance from c to p1; the solver keeps p2 on the same circle. Swapping p1 and p2 gives the complementary arc.
ellipsec, p, rCentre c; p is a point on the major axis, so the major semi-axis is the distance c-p; r is the minor semi-axis.
pointpA marker for a point. Used as hole centres and as a point section of a loft.
splinepts, closedA cubic curve interpolating the points pts in order. closed joins the last point to the first.
cvsplinepts, degree, knots, closedA B-spline whose control points are pts. degree defaults to 1 when absent and is at least 1. knots is optional.
textstring, height, at or p, font, …Lettering whose outlines become closed profiles. See text and fonts.

An entity with a missing or unknown type is dropped when the sketch is read, without an error. Missing string fields (p1, c, …) read as "", which names no point.

Constraints

A constraint has an id, a type, refs (ids of points or entities) and, for dimensions, a numeric value. The constraints are used by the solver (see the sketch solver); the table lists what each type says.

typerefsMeaning
coincidentpoint, pointThe points are equal. Circle, arc and ellipse ids stand for their centres, a point entity for its point.
concentricpoint-like, point-likeSame as coincident, used for centres.
pointOnLinepoint, lineThe point lies on the infinite line through the segment.
pointOnCirclepoint, circle/arc/ellipseThe point lies at the radius from the centre.
midpointpoint, lineThe point is the middle of the segment.
horizontalline, or point, pointThe two ends have equal y.
verticalline, or point, pointThe two ends have equal x.
parallel, perpendicularline, lineDirections are parallel / at 90 degrees.
collinearline, lineBoth lines lie on one line.
equalline, line or circle/arc, circle/arcEqual length, or equal radius.
tangentline/arc/circle, arc/circleTangent. At a shared end point (at names it, or it is found) the curves meet tangentially; otherwise they touch: a line at distance r, two circles at distance r1 + r2 ("internal": true: the absolute difference of the radii).
fixpointThe point is at value: [x, y]. pierce is the same.
symmetricpoint, point, lineThe points are mirror images about the line.
distancepoint, pointDistance between the points equals value.
hdist, vdistpoint, pointAbsolute difference of x (y) equals value.
pldistpoint, lineDistance from the point to the line equals value.
radius, diametercircle/arc/ellipseThe radius (twice the radius) equals value.
raddiffcircle/arc, circle/arcsign * (r2 - r1) equals value; sign is 1 or -1.
angleline, lineThe angle from the first to the second direction equals value degrees; s1 and s2 (1 or -1) flip the direction of each line.
g1, g2, g3cvspline, curveContinuity of an open control-point spline with another curve at the end at (a control point id).
onCurvepoint, curveThe point lies at the parameter fraction value (0 to 1) of the curve.
tensioncvsplineTension at the end at with strength value.

Other fields of a constraint:

FieldMeaning
valueThe number the dimension is driven to. [x, y] for fix. A numeric string is converted.
exprA variable expression that drives value, such as "=w/2". See variables and expressions.
offsetWhere an editor draws the dimension. Kept, not used.
suppressedtrue makes the solver ignore the constraint everywhere, while the document keeps it.
at, internal, s1, s2, signOptions of tangent, angle, raddiff and the spline constraints, as above.

A constraint that names a missing point or entity, or has too few refs or an unknown type, is kept in the document but makes the equation system impossible to build; the sketch is then left as it is, without an error.

What the kernel does with a sketch

The coordinates in the document are authoritative. A regen does not re-solve the constraints of a sketch just because they exist: the points are used as they are written. The solver runs in two cases:

  • a constraint has an expr and its value differs from the stored value: the kernel evaluates the expression, writes the new value and re-solves the sketch from the stored coordinates;
  • the request has opts.solveSketches (see the sketch solver).

In both cases the reply returns the solved sketch. If the solve fails the points stay as sent and no error is raised.

{
  "format": "ck-part", "version": 1, "variables": [{"name": "w", "expr": "50"}],
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "O", "x": 0, "y": 0, "fixed": true},
        {"id": "b", "x": 30, "y": 0},
        {"id": "c", "x": 30, "y": 15},
        {"id": "d", "x": 0, "y": 15}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "O", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "O"}
      ],
      "constraints": [
        {"id": "k1", "type": "horizontal", "refs": ["e1"]},
        {"id": "k2", "type": "vertical", "refs": ["e2"]},
        {"id": "k3", "type": "horizontal", "refs": ["e3"]},
        {"id": "k4", "type": "vertical", "refs": ["e4"]},
        {"id": "k5", "type": "distance", "refs": ["O", "b"], "value": 30, "expr": "=w"},
        {"id": "k6", "type": "distance", "refs": ["b", "c"], "value": 15}
      ]
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 5}
  ]
}

Run result: no errors; 6 faces, volume 3750 mm³. The reply echoes the sketch with the solved points: b is at (50, 0) instead of (30, 0), and k5 carries value: 50. The plate is 50 mm long.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "O", "x": 0, "y": 0, "fixed": true},
        {"id": "b", "x": 30, "y": 1},
        {"id": "c", "x": 30, "y": 15},
        {"id": "d", "x": 0, "y": 15}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "O", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "O"}
      ],
      "constraints": [{"id": "k1", "type": "horizontal", "refs": ["e1"]}]
    }
  ]
}

Run result: no errors; no solid body. The point b comes back unchanged at (30, 1): the constraint is not applied because no expr changed.

An editor therefore writes solved coordinates; a program that edits a dimension by changing a variable gets them solved.

Regen errors of a sketch feature: missingReference (the plane), badExpression (a constraint expr that does not evaluate), and the lettering errors textEmpty, textNothingToDraw, textFontNotLoaded, textFontMismatch, textBadHeight, textBadArc, textBadPath, textBadValue (see text and fonts).

Profiles

Solid and surface features take their profiles from the profiles the kernel finds in a sketch. The rules:

  • All curves that are not construction curves are intersected with each other and split at the crossings. Pieces that dangle (that do not belong to a closed loop) are dropped, so a line that crosses a rectangle divides it in two and its overhanging ends vanish.
  • Exact duplicates of a piece are dropped. Collinear overlaps are not split.
  • Every bounded face of the resulting planar arrangement is a region. A loop inside a region is a hole of it; a loop inside a hole is an island and a region of its own (concentric circles give a ring and a disc).
  • A circle or ellipse is one closed loop, a closed spline one loop. A sketch with no closed loop but at least one curve is open; most solid features then report noClosedProfile.
  • Regions are listed in order of their first curve; each outer loop runs counter-clockwise and holes clockwise.

The reply gives each sketch as [id, {frame, profiles, sketch}], with profiles = {regions: [{outer: [...], holes: [[...]]}], open: bool}. A segment is {kind: "line" | "arc" | "spline", tag: <entity id>, a: [x, y], b: [x, y]}; circles and ellipses are arcs from angle 0 to 2 pi.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 40, "y": 0},
        {"id": "c", "x": 40, "y": 20},
        {"id": "d", "x": 0, "y": 20},
        {"id": "h", "x": 20, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"},
        {"type": "circle", "id": "e5", "c": "h", "r": 4}
      ],
      "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 4}
  ]
}

Run result: no errors; 7 faces, volume 2998.9381 mm³. profiles in the reply: 1 region with 1 hole, open is false. The faces are F2.C0, F2.C1, F2.S.e1, F2.S.e2, F2.S.e3, F2.S.e4, F2.S.e5.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 40, "y": 0},
        {"id": "c", "x": 40, "y": 20},
        {"id": "d", "x": 0, "y": 20},
        {"id": "x", "x": 20, "y": -5},
        {"id": "y", "x": 20, "y": 25}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"},
        {"type": "line", "id": "e5", "p1": "x", "p2": "y"}
      ],
      "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 2}
  ]
}

Run result: no errors; 12 faces, volume 1600 mm³. The line crosses the rectangle, so the profile has 2 regions; the part of the line outside the rectangle is dropped. The faces are F2.C0~1, F2.C1~1, F2.S.e1~1, F2.S.e5~1, F2.S.e3~1, F2.S.e4, F2.C0~2, F2.C1~2, F2.S.e1~2, F2.S.e2, F2.S.e3~2, F2.S.e5~2.

An extrude, revolve or loft uses all regions unless regions selects some; see solids from sketches.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 20, "y": 0},
        {"id": "c", "x": 20, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"}
      ],
      "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 4}
  ]
}

Run result: errors F2: noClosedProfile; no solid body.

Curves: the arc runs counter-clockwise from p1 to p2.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "c", "x": 0, "y": 0},
        {"id": "a", "x": 10, "y": 0},
        {"id": "b", "x": 0, "y": 10}
      ],
      "entities": [
        {"type": "arc", "id": "e1", "c": "c", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 2}
  ]
}

Run result: no errors; 4 faces, volume 57.0796 mm³. The cross-section is the segment between the chord and the quarter arc, area 28.5398 mm².

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "c", "x": 0, "y": 0},
        {"id": "a", "x": 10, "y": 0},
        {"id": "b", "x": 0, "y": 10}
      ],
      "entities": [
        {"type": "arc", "id": "e1", "c": "c", "p1": "b", "p2": "a"},
        {"type": "line", "id": "e2", "p1": "a", "p2": "b"}
      ],
      "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 2}
  ]
}

Run result: no errors; 4 faces, volume 571.2389 mm³. With the arc end points swapped the arc runs the long way round: area 285.6194 mm².

The echoed sketch

The sketch object in the reply is the input after normalisation. Key order and unknown keys are kept. Missing points, entities and constraints arrays are appended; a point gets id, x and y defaults and its x and y are converted to numbers; a non-object point becomes {"id": "", "x": 0, "y": 0}; entities of an unknown type are dropped; a numeric-string constraint value becomes a number. The solved coordinates replace the stored ones.

3D sketches

A sketch3d feature holds points with x, y, z, lines, arcs, splines and control-point splines in space, and its own constraints. It is used as a sweep path and as a path for normal planes. Its fields and reply are described in surfaces and curves.

See also

The sketch solver

The sketch solver moves the points of a sketch until its constraints hold. This chapter describes when the kernel runs it, how it is built, how it reports whether a sketch is fully defined, over-constrained or in conflict, and the read-only queries that expose more of its state.

When it runs

A regen does not solve a sketch on its own: the stored coordinates are used as written (see sketches). The solver runs in two cases:

  1. A dimensional constraint has an expr whose value differs from its stored value by more than 1e-12. The kernel evaluates the expression, writes the new value and solves the sketch starting from the stored coordinates. If the solve does not converge the coordinates are left as they were and no error is raised.
  2. The regen request has opts.solveSketches: true. Every sketch is solved with all its constraints, and a sketch that already satisfies them is not solved again. This is the mode for an editor that drags a point: a constraint fix with value: [x, y] acts as a temporary pin. The solved coordinates are used for the reply and for the features that follow.

The queries sketchFreedoms and sketchAnalyze below only analyse the sketch as stored; they move nothing.

The equation system

  • Unknowns are the x and y of every point that is not fixed, then the radius r of every circle that is not marked ext/from and of every ellipse, in document order.
  • Equations are one per arc (the radii c-p1 and c-p2 must agree), then the residuals of each constraint in document order. A constraint with suppressed: true contributes none. A constraint contributes one equation (a distance, an angle, a radius), two (coincident points, a fixed point, a collinear pair, symmetry) or several (spline constraints).
  • A constraint that names something that does not exist, or has the wrong refs, makes the whole system impossible to build. The sketch is then left unsolved without an error.

The solve

The solver is a damped Gauss-Newton iteration on the minimum-norm step:

  • the Jacobian is taken by central differences with step 1e-7 * (1 + |x|);
  • each iteration solves (J W J^T + lambda I) y = -f for the step dx = W J^T y, with lambda = 1e-10 * max diagonal + 1e-14; W is an optional per-unknown weight that makes chosen unknowns resist moving (an editor uses it for the point being dragged);
  • the step is halved up to 12 times until the sum of squared residuals decreases;
  • at most 60 iterations; it stops when the largest residual is at most 1e-9, and counts as solved when it is at most 1e-7.

Because the step is the smallest that fixes the residuals, an under-constrained sketch moves as little as it can: points stay near where they were drawn.

Status: fully defined, under, over

With opts.sketchStatus: true (implied by solveSketches) every entry of sketches in the reply gains a status:

FieldMeaning
dofDegrees of freedom: the number of unknowns minus the rank of the Jacobian. A free point counts 2, a free circle 3.
fullyDefinedstate is "full" and solved is true.
state"over" if some constraint is implied by earlier ones, otherwise "full" when dof is 0, otherwise "under".
solvedThe stored coordinates satisfy every constraint (largest residual at most 1e-7), or a solve from them converges.
conflictsIds of constraints that cannot hold together with the ones before them.
redundantIds of constraints that are implied by the ones before them.
residualThe largest absolute residual at the coordinates in the reply; -1 if it is not finite or the system cannot be built.
suppressedIds of constraints flagged suppressed, in document order. Present only when there are any.

How blame is assigned: the rows of the Jacobian are taken in solver order and orthogonalised one after the other against the rows already accepted. A row is independent when the part of it outside the span of the earlier rows is more than 1e-6 of its own norm. A dependent row belongs to a constraint that is either redundant (its residual at the solution is 1e-6 or less, so it holds anyway) or a conflict (it does not hold). The later constraint in document order is always the one blamed, and a constraint is never in both lists. Suppressing the constraint that is blamed removes the conflict.

A draft whose coordinates do not satisfy its constraints reports solved: true with a positive residual when a solve from them converges, and solved: false when the constraints cannot be met.

A fully defined sketch from the previous chapter (regen with opts.sketchStatus: true):

{
  "format": "ck-part", "version": 1, "variables": [{"name": "w", "expr": "30"}],
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "O", "x": 0, "y": 0, "fixed": true},
        {"id": "b", "x": 30, "y": 0},
        {"id": "c", "x": 30, "y": 15},
        {"id": "d", "x": 0, "y": 15}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "O", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "O"}
      ],
      "constraints": [
        {"id": "k1", "type": "horizontal", "refs": ["e1"]},
        {"id": "k2", "type": "vertical", "refs": ["e2"]},
        {"id": "k3", "type": "horizontal", "refs": ["e3"]},
        {"id": "k4", "type": "vertical", "refs": ["e4"]},
        {"id": "k5", "type": "distance", "refs": ["O", "b"], "value": 30, "expr": "=w"},
        {"id": "k6", "type": "distance", "refs": ["b", "c"], "value": 15}
      ]
    }
  ]
}

Run result: no errors; no solid body. status of the sketch: {"dof":0,"fullyDefined":true,"conflicts":[],"redundant":[],"solved":true,"state":"full","residual":0}.

Two distances between the same points, one asking for 30 mm and one for 40 mm (regen with opts.sketchStatus: true):

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "O", "x": 0, "y": 0, "fixed": true},
        {"id": "b", "x": 30, "y": 0},
        {"id": "c", "x": 30, "y": 15},
        {"id": "d", "x": 0, "y": 15}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "O", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "O"}
      ],
      "constraints": [
        {"id": "k1", "type": "distance", "refs": ["O", "b"], "value": 30},
        {"id": "k2", "type": "distance", "refs": ["O", "b"], "value": 40}
      ]
    }
  ]
}

Run result: no errors; no solid body. status of the sketch: {"dof":5,"fullyDefined":false,"conflicts":["k2"],"redundant":[],"solved":false,"state":"over","residual":10}.

The second constraint is blamed. The sketch stays as it was sent and the regen has no error: conflicting constraints never raise a feature error.

Live solve

Starting from a sketch whose point b is 1 mm off the horizontal line that k1 demands, solveSketches moves it onto the line (and then fits the distance of k5). Regen with opts.solveSketches: true of:

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "O", "x": 0, "y": 0, "fixed": true},
        {"id": "b", "x": 30, "y": 1},
        {"id": "c", "x": 30, "y": 15},
        {"id": "d", "x": 0, "y": 15}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "O", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "O"}
      ],
      "constraints": [
        {"id": "k1", "type": "horizontal", "refs": ["e1"]},
        {"id": "k5", "type": "distance", "refs": ["O", "b"], "value": 30}
      ]
    }
  ]
}

Run result: no errors; no solid body. b becomes (30, 0) in the reply and status is {"dof":4,"fullyDefined":false,"conflicts":[],"redundant":[],"solved":true,"state":"under","residual":6.306066779870889e-12}.

Without the option, the same sketch comes back unchanged.

Queries

Both queries work on the tag of a previous regen (tag), or on a part passed in part, and reply null when there is no body and no part.

sketchFreedoms

What can still move in a sketch: the null space of the Jacobian at the stored coordinates, per point, radius and entity. dof is the same number as in status.

{"type": "sketchFreedoms", "featureId": "F1", "tag": "t"}

Reply:

{
  "dof": 1, "solved": true,
  "points": [
    {"id": "O", "free": 0},
    {"id": "b", "free": 0},
    {"id": "c", "free": 1, "dir": [0, 1]},
    {"id": "d", "free": 1, "dir": [0, 1]}
  ],
  "radii": [],
  "entities": [
    {"id": "e1", "kind": "line", "free": 0},
    {"id": "e2", "kind": "line", "free": 1},
    {"id": "e3", "kind": "line", "free": 2},
    {"id": "e4", "kind": "line", "free": 1}
  ]
}

For a point, free is 0 for a fixed or fully determined point, 1 when it can move along the single direction dir (a unit vector in sketch coordinates, with the larger component positive), and 2 when it can move anywhere. For an entity free is the sum over its points plus 1 for a free radius. A rectangle with its height missing leaves the top corners free in y only.

sketchAnalyze

A structural analysis of one sketch, for diagnosing profiles that do not close. The options tolerance (near-coincident distance, default 0.01 mm) and tiny (tiny segment length, default 0.001 mm) tune it; a value of 0 or less switches the check off.

{"type": "sketchAnalyze", "featureId": "F1"}

Reply:

{
  "tolerance": 0.01, "tiny": 0.001,
  "findings": [
    {
      "kind": "openEnd", "entities": ["e1"], "points": ["e", "a"], "at": [0, 0.02], "gap": 0.02,
      "nearest": "e4"
    },
    {
      "kind": "openEnd", "entities": ["e4"], "points": ["a", "e"], "at": [0, 0], "gap": 0.02,
      "nearest": "e1"
    }
  ],
  "chains": [{"entities": ["e1", "e2", "e3", "e4"], "closed": false, "construction": false}],
  "profile": {
    "closedChains": 0,
    "reason": {
      "kind": "openEnd", "entities": ["e4"], "points": ["a", "e"], "at": [0, 0], "gap": 0.02,
      "nearest": "e1"
    }
  }
}

Finding kinds: openEnd (an end touches nothing; gap is the distance to the nearest other open end and nearest its entity), nearCoincident (two points closer than tolerance with no coincident constraint between them), duplicate, overlap (collinear lines whose interiors intersect), zeroLength, tinySegment, branch (more than two ends at a point), isolatedPoint and selfIntersection. chains lists the connected pieces and whether each is closed. profile.closedChains counts the closed chains a profile can be built from; when it is 0, profile.reason names the biggest openEnd gap, {"kind": "empty"} for a sketch with no curves, or {"kind": "constructionOnly"}.

Limits

  • The spline constraints g1, g2, g3, onCurve and tension work on open control-point splines only.
  • Text entities are fixed geometry; only their anchor point can be constrained.
  • The solver reports no feature error for any outcome. A client that needs to know must ask for the status.
  • The analysis is numerical: the rank test uses a relative threshold, so a nearly singular sketch can be reported as redundant or as under-defined by a small margin.

See also

Features

A part is a list of features, run in order. This chapter lists every feature type the kernel knows, with the chapter that documents it, and then describes what the features have in common: shared fields, boolean tolerance, time budgets and the way errors and warnings are reported.

Index of feature types

The kernel knows 68 type names. Five of them (box, frame, knurlBand, repairPart and importBody) are not described in this index. A name that is not in this list is unknownFeature. Types marked “not built” are accepted as names but have no implementation: they fail with the error code TODO(rebuild): <type> needs ck-ops.

TypeWhat it doesChapter
sketch2D points, curves and constraints on a plane.sketches
sketch3dPoints, curves and constraints in space.surfaces and curves
planeA reference plane (offset, angle, three points, …).planes
axisA reference line from an edge, a sketch line, a cylinder or two planes.planes
extrudeSweeps sketch regions along the normal, with end conditions, taper, twist and thin walls.solids
revolveRevolves sketch regions about a sketch line.solids
sphereA ball by centre and radius.solids
sweepMoves a profile along a path (sketch, helix or curve).solids
loftJoins two or more sections, with point ends, guides and a centre line.solids
ribA thin wall from an open sketch chain to the body.solids
helixA helix curve for sweeps.solids
holeCuts simple, counterbored or countersunk holes at sketch points.edits
filletRounds edges (constant, variable, full round).edits
chamferBevels edges or a vertex.edits
draftTilts faces about a neutral plane.edits
shellHollows the body, opening chosen faces.edits
threadCosmetic or modeled thread on a cylindrical face.edits
lipA raised band or a groove along rim edges.edits
moveFacePushes or pulls faces; neighbours follow.edits
pressPullContinues a flat face straight out of or into the solid, with a draft or scale taper.edits
splitCuts a body at a plane (or by tool bodies) into two named bodies.edits
lipJointA split with a centred tongue on one half and a clearance groove on the other.edits
deleteBodyRemoves or keeps whole bodies.edits
lpatternCopies features along one to three directions (any vector, edge or axis), by spacing, extent or up to an object.patterns
cpatternCopies features, or components, around an axis.patterns
mirrorReflects features or the whole body about a plane.patterns
moveBodyMoves, rotates or copies bodies.patterns
scaleScales bodies uniformly or per axis.patterns
combineBoolean between whole bodies (also written bodyBoolean).patterns
bodyBooleanAnother name for combine.patterns
sheetRules, baseFlange, contourFlange, edgeFlange, hem, fold, unfold, refold, sheetConvert, sheetCut, sheetCornerSheet metal: the stock rule, plates, bends, the flat pattern and its export.sheet metal
surfacePlanarA flat sheet from a sketch profile.surfaces
surfaceExtrudeA sheet swept from a profile.surfaces
surfaceRevolveA sheet revolved about an axis.surfaces
knitJoins sheets into a sheet or a solid.surfaces
trimSurfaceTrims sheets with a sheet or plane.surfaces
fillPatches a hole bounded by edges.surfaces
thickenGives a sheet thickness.surfaces
extendExtends a sheet past its boundary edges.surfaces
deleteFaceRemoves faces from a solid or sheet.surfaces
freeformRe-fits faces as B-spline surfaces and edits control points.surfaces
pipeCutRolls a ball along edges and cuts away what it touches.surfaces
projectCurveProjects a sketch onto faces as a B-spline curve.surfaces
editCurveRebuilds curves as a B-spline and edits its control points.surfaces
insertPartInserts another part as a component.assemblies
importStepHolds a STEP body and brings its solids into the history.assemblies
mateConstrains two components.assemblies
spatternPattern driven by a sketch. Not built.patterns
curvepatternPattern along a path: start point, flip, fixed or tangent orientation.patterns
fillpatternPattern that fills a face. Not built.patterns
surfaceOffsetOffsets a sheet. Not built.surfaces
cutWithSurfaceCuts the body with a sheet. Not built.surfaces
domeDomes a face. Not built.surfaces
splitLineSplits faces along a curve. Not built.surfaces

Reading a feature chapter

Each feature has the same parts: a field table (name, type, default, meaning), the names of the faces it creates (see identifiers and references), the error codes it raises and a run example. In the field tables:

  • “number or expression” is a numeric field as described in variables and expressions;
  • a default of “required” means that leaving the field out makes the feature fail with the error named in the text (usually missingSketch or missingReference);
  • a feature id field (sketch, seeds) names an earlier feature;
  • examples that append to a base part say so. They were run through the kernel; the line “Run result” under each states what the kernel returned.

Fields every feature reads

FieldApplies toMeaning
suppressedallSkips the feature, see the overview.
tolerancefeatures that combine a tool with the body (extrude, revolve, sweep, loft, hole, thread, patterns, combine)The fuzzy value of the boolean, in mm (number or expression, default 0).
autoFuzzythe sametrue retries a failed or implausible boolean with a growing fuzzy value.
originallA free label for where the feature came from (for example script#3 for a feature created by a script). The kernel does not read it and does not warn about it.
op, bodyextrude, revolve, sweep, loft, sphereOperation and body name, see solids.

Fuzzy booleans

With tolerance above 0, any planar, cylindrical or spherical face of the tool that lies within tolerance of an equal-kind face of the body is moved exactly onto it before the boolean, so nearly coincident faces are treated as coincident. Geometry closer than tolerance is merged, so a sliver thinner than that is removed and a gap thinner than that is closed. A snap that fails, makes the tool invalid or changes its volume by more than 4 x tolerance x area is discarded and the exact boolean runs. Useful values are 1e-6 to 1e-3 mm.

With autoFuzzy: true, a boolean that fails (booleanFailed), comes out implausible (the volume check) or comes out with more validity issues than its operands is retried with the fuzzy values 1e-7, 1e-5 and 1e-3 (those above tolerance); the first retry that is plausible and valid wins. If none is, the first error stands. A feature whose result depended on the fuzzy value carries the warning booleanFuzzy {tolerance}.

Errors and warnings

A feature reports an error as ["<feature id>", {"code": "...", "params": {...}}] in the errors list of the reply, sorted by id. A feature that fails contributes nothing and leaves the body as it was. Warnings have the same shape in warnings; the feature still ran. The codes that many features share:

CodeMeaning
unknownFeatureThe type is not in the index above (params.type).
missingSketchA sketch-driven feature names no regenerated sketch.
missingReferenceA reference (face, plane, feature, axis) does not resolve. Some carry params that name the reference.
badExpressionA numeric field holds an expression that does not evaluate.
invalidValueA value is out of range (a radius of 0, a bad op). params often hold detail and hint.
noClosedProfileThe sketch has no closed region.
nothingToCutThe feature needs a body and there is none.
cutNoEffectA cut removed nothing.
booleanFailed, booleanVolumeMismatchThe boolean with the body failed or gave an impossible volume. booleanFailed may carry faces, issue, at and a hint.
featureBudgetExceeded, regenBudgetExceededA time limit ran out (below).

A field that the feature type does not read is reported as the warning unknownField (for sketch, extrude, revolve, fillet, chamfer and hole); see misspelled fields.

The codes of each feature are in its own chapter; feature errors and diagnostics collects them.

Time budgets

When the host provides a clock, one feature may run for opts.featureTimeMs milliseconds (default 120000; 0 or less means unlimited) and the whole regen for opts.regenTimeMs (default unlimited). A feature that runs out fails with featureBudgetExceeded; once the regen limit has passed, the features not yet run fail with regenBudgetExceeded. The error carries budgetMs, elapsedMs and a hint, and cause when another error was a consequence of the limit.

See also

Solids from sketches

These features build a new solid from sketch profiles or from nothing, and combine it with the body made so far: extrude, revolve, sphere, sweep, loft, rib and helix (a curve that sweep can follow). The sketch feature itself is in sketches and hole, which cuts holes at sketch points, is in edge and face edits.

Operations and the body

The features that build a tool solid take an op that says how the tool meets the body:

opEffect
add (default)The tool is united with the body. The first add on an empty body becomes the body.
cutThe tool is subtracted. A cut with no body is nothingToCut. A cut that removes nothing is cutNoEffect and leaves the body unchanged.
newBody (read aliases new, separate)The tool becomes a separate body in the same part, not united with what it touches.

Any other value reads as add. newBody is accepted by extrude, revolve, sweep, loft and sphere; any other feature that is given newBody fails with invalidValue. A body name on one of these features, with op: "newBody", names the new body (bodyNameConflict if the name is taken; invalidValue if body is given without newBody or is not a non-empty string). See patterns and transforms for selecting bodies by name.

Every feature of this chapter that combines with the body also reads the fuzzy-boolean fields tolerance and autoFuzzy; they are described in features. A boolean that cannot be completed is booleanFailed, and a result whose volume is impossible for its operands is booleanVolumeMismatch; in both cases the body is left as it was.

extrude

Sweeps the profile of a sketch along its normal.

FieldTypeDefaultMeaning
sketchfeature idrequiredThe sketch. A missing or unknown sketch is missingSketch.
opstring"add"See above.
endstring"blind"The end condition (table below).
depthnumber or expression0Length in mm. Zero or negative is clamped to 1e-6 (a sliver, not a usable solid), and a blind or mid extrude says so with the warning extrudeZeroDepth {depth, built, hint}; give a non-zero depth, or drop the feature.
flipbooleanfalseExtrude against the sketch normal.
draftnumber or expressionnoneTaper angle in degrees; the profile shrinks towards the end. draftOut reverses it.
draftOutbooleanfalseTaper outwards.
twistnumber or expression0Degrees of rotation over the whole depth, counter-clockwise about the sketch normal. Not combinable with draft or upToNext (draftUnsupported).
twistCentre[x, y]sketch originThe axis of the twist, in sketch coordinates.
regionslist of entity idsall regionsSelects which closed regions are swept (see below).
thinobjectnoneSweeps a wall around the profile curves instead of the filled regions (see below).
endRefsee belownoneThe target of upToFace, offsetFromFace and upToPoint.
offsetnumber or expression0offsetFromFace: distance from the face along its outward normal.
strictEndbooleanfalseReport an unreachable end condition as an error instead of falling back.
bodystringnoneName of the new body (with op: "newBody").
targetselection or listnoneThe bodies an add or cut acts on, as {"body":"A"} or {"face":"F2.C1"} (a list acts on each). Without it a cut reaches every body it meets. A name that does not exist is refused with the names that do; a cut that reaches none of the named bodies is cutNoEffect; with op: "newBody" it is invalidValue. extrude, revolve, loft, sweep and hole take it.

End conditions:

endExtent
blinddepth along the normal (or against it with flip).
middepth in total, centred on the sketch plane.
throughThrough the whole body: from the sketch plane for a length computed from the body’s extent. On an empty body 1000 mm.
throughBothThrough the whole body on both sides. On an empty body 1000 mm each way.
upToNextTo the next face of the body: the tool is a through tool trimmed by the body. With no body: nothingToCut. No face to stop at: upToNextNone; an add that never meets the body: upToNextOpen.
upToFaceTo a planar face named by endRef.
offsetFromFaceTo the plane of a face moved by offset along the face’s outward normal (negative moves into the material).
upToPointTo the plane through a point, parallel to the sketch plane.
any otherunknownEnd with params.end holding the value.

The direction of a cut is reversed first: a cut goes against the sketch normal unless flip is set, so a sketch on the top face cuts into the material. A cut that runs the wrong way removes nothing and reports cutNoEffect.

The face names are C0 for the cap whose outward normal opposes the sketch normal and C1 for the other, and S.<entity> for the wall made from each profile entity. A profile with several regions numbers them ~1, ~2. After a cut, the faces left in the body are the tool’s: the floor of a blind pocket cut from a top face is C0.

Appended to the plate of the overview (a sketch on its top face, then the cut):

[
  {
    "type": "sketch", "id": "F3", "plane": {"kind": "face", "id": "F2.C1"},
    "points": [{"id": "c", "x": 20, "y": 10}],
    "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 4}], "constraints": []
  },
  {"type": "extrude", "id": "F4", "op": "cut", "sketch": "F3", "end": "blind", "depth": 4}
]

Run result: no errors; 8 faces, volume 7798.9381 mm³. The pocket faces are F4.C0, F4.S.e1.

flip, mid and through, applied to the plate rectangle (the sketch lies in z = 0 with normal +z):

Feature fieldsz range of the plate
"end": "blind", "depth": 100 to 10
"end": "blind", "depth": 10, "flip": true-10 to 0
"end": "mid", "depth": 10-5 to 5
"end": "through"0 to 1000
"end": "throughBoth"-1000 to 1000
"end": "blind", "depth": 00 to 0.000001

Taper and twist

draft tapers the walls inwards by the given angle; draftOut: true tapers outwards. A taper that closes the profile before the depth is reached is draftTooLarge. For a profile made of one circle (a cone) the error carries maxHeight, the depth at which the taper closes to a point, and a successful drafted extrude of such a profile adds limits: [["F2", {"maxHeight": h}]] to the regen reply so an editor can limit its depth field. A depth equal to maxHeight builds a cone with one apex and no top cap. A drafted extrude with end mid or throughBoth is not built: it fails with the code notImplemented (what: mid-plane drafted extrude (boolean unite)).

Added after the rectangle sketch F1 of the plate (without its extrude):

{"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 10, "draft": 5}

Run result: no errors; 6 faces, volume 7485.2737 mm³. The 40 x 20 face at the sketch plane shrinks towards the top; box [0,0,0] to [40,20,10].

twist turns the profile as it extrudes. The side faces are screw surfaces (exact cylinders for circles about the axis, fitted B-splines otherwise); the volume stays area times depth.

Likewise:

{"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 10, "twist": 45}

Run result: no errors; 6 faces, volume 8000 mm³. The twisted prism keeps the volume of the straight one (40 x 20 x 10 = 8000).

End references

endRef names the target of upToFace and offsetFromFace (a face) and upToPoint (a point).

EndForms of endRef
upToFace, offsetFromFace{"kind": "face", "id": "F4.C0", "at": [x, y, z]} or the bare face id "F4.C0". at is a point on the face: it lets the kernel find the face again if its name has changed (warning endRefRelinked).
upToPoint[x, y, z], {"kind": "point", "at": [x, y, z]} or {"kind": "vertex", "faces": ["F2.C1", "F2.S.e4", "F2.S.e1"], "at": [x, y, z]} (the vertex shared by the faces, nearest to at).

The target face must be planar. A plane slanted against the sketch is supported: the tool is trimmed by a boolean and the new end face takes the name of the cap it replaces. Non-planar targets are upToFaceUnsupported. A missing or unresolved endRef is missingReference with params.field: "endRef".

When the end cannot be reached (upToFaceBehind: the face is not ahead of the whole profile; upToFaceOutside: the face does not cover the profile; upToFaceUnsupported; upToPointBehind), the feature does not fail. It runs as a blind extrude of depth and the reply carries a warning endConditionFallback {end, reason, fallback: "blind", depth}. With "strictEnd": true the reason becomes the error instead. A missing endRef is never downgraded.

Two discs of radius 20, one on the front plane (z 0 to 10) and one above it on a plane at z = 30 (z 30 to 35). F5 is a small circle on the top face of the lower disc; the rod will start there and end at the underside of the upper disc:

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [{"id": "c", "x": 0, "y": 0}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 20}], "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 10},
    {
      "type": "plane", "id": "P1", "mode": "offset", "base": {"kind": "std", "id": "front"},
      "offset": 30
    },
    {
      "type": "sketch", "id": "F3", "plane": {"kind": "feature", "id": "P1"},
      "points": [{"id": "c", "x": 0, "y": 0}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 20}], "constraints": []
    },
    {"type": "extrude", "id": "F4", "op": "add", "sketch": "F3", "end": "blind", "depth": 5},
    {
      "type": "sketch", "id": "F5", "plane": {"kind": "face", "id": "F2.C1"},
      "points": [{"id": "c", "x": 0, "y": 0}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 4}], "constraints": []
    }
  ]
}

Appended to that document:

{
  "type": "extrude", "id": "F6", "op": "add", "sketch": "F5", "end": "upToFace",
  "endRef": {"kind": "face", "id": "F4.C0"}
}

Run result: no errors; 7 faces, volume 19854.8656 mm³. The rod runs from z = 10 to the underside of the upper disc at z = 30 and joins the two discs: pi 20² 15 + pi 4² 20 = 19854.8656.

With a target that is behind the sketch (the bottom face of the lower disc), the extrude falls back to its depth:

{
  "type": "extrude", "id": "F6", "op": "add", "sketch": "F5", "end": "upToFace", "endRef": "F2.C0",
  "depth": 3
}

Run result: no errors; warnings F6: endConditionFallback {"end":"upToFace","reason":"upToFaceBehind","fallback":"blind","depth":3}; 8 faces, volume 19000.3524 mm³. The rod is a blind extrude of 3 mm.

Selecting regions

By default all closed regions of the sketch are swept. regions is a list of sketch entity ids; a region is selected when any listed id is a segment of its outer boundary. A selected region keeps its holes; an id that bounds a hole (a circle inside a rectangle) selects that hole as a disc. Names are numbered as if the selection were the whole sketch. Errors: extrudeRegionUnknown {ids} (ids that are not entities of the sketch), extrudeRegionNone {regions} (an empty list, or ids that bound no region), invalidValue {field: "regions"} (not a list of strings). revolve takes the same field.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 40, "y": 0},
        {"id": "c", "x": 40, "y": 20},
        {"id": "d", "x": 0, "y": 20},
        {"id": "h", "x": 60, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"},
        {"type": "circle", "id": "e5", "c": "h", "r": 6}
      ],
      "constraints": []
    },
    {
      "type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 4,
      "regions": ["e5"]
    }
  ]
}

Run result: no errors; 3 faces, volume 452.3893 mm³. Only the disc is built: F2.C0, F2.C1, F2.S.e5.

Thin walls

thin sweeps a wall around the curves of the profile. An open chain gives a wall in one step; a closed loop gives a hollow wall.

FieldTypeDefaultMeaning
thicknessnumber or expression1Wall thickness; must be above 0.
sidestring"inside"inside, outside, both or mid (centred). Closed loops are oriented counter-clockwise; for an open chain inside is the left of the direction that turns counter-clockwise.
thickness2number or expressionthicknessThickness on the second side, for both. Zero or more.
endsstring"flat"flat or round (half-disc caps on an open chain).
cornerStylestring"mitre"mitre (also spelt miter) or round.
enabledbooleantruefalse keeps the settings but switches the wall off. A null or false thin is off too.

Offsets are exact for lines, arcs and circles and fitted (within 1e-5) for ellipses and splines. Errors: thinTooThick {limit, minRadius, maxThickness, thickness, face} when the offset passes a centre of curvature or a short segment is eaten; invalidValue {field} with thin.thickness, thin.side, thin.ends or thin.cornerStyle. thin also works on revolve. It is not available on sweep, loft or hole.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 20, "y": 0},
        {"id": "c", "x": 20, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"}
      ],
      "constraints": []
    },
    {
      "type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 4,
      "thin": {"thickness": 2, "side": "mid"}
    }
  ]
}

Run result: no errors; 8 faces, volume 240 mm³. The 2 mm wall along the L-shaped chain has the faces F2.C0, F2.C1, F2.S.e1.W1, F2.S.e2.W1, F2.S.e2.E1, F2.S.e2.W0, F2.S.e1.W0, F2.S.e1.E0.

Separate bodies

A second block next to the plate, as its own body (appended to the plate):

[
  {
    "type": "sketch", "id": "F3", "plane": {"kind": "std", "id": "front"},
    "points": [
      {"id": "a", "x": 60, "y": 0},
      {"id": "b", "x": 80, "y": 0},
      {"id": "c", "x": 80, "y": 20},
      {"id": "d", "x": 60, "y": 20}
    ],
    "entities": [
      {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
      {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
      {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
      {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
    ],
    "constraints": []
  },
  {
    "type": "extrude", "id": "F4", "op": "newBody", "body": "Block", "sketch": "F3", "end": "blind",
    "depth": 5
  }
]

Run result: no errors; 12 faces, volume 10000 mm³. The block is a second body next to the plate: 8000 + 2000 = 10000.

Errors of extrude

CodeWhen
missingSketchsketch names no regenerated sketch.
badExpressionA numeric field holds a bad expression.
invalidValueA sketch point is not finite (params.point, detail, hint); bad regions, thin or body values.
noClosedProfileThe sketch has no closed region (an open chain, no curves, construction only).
unknownEndend is not one of the names above.
missingReferenceAn end condition needs a reference that is missing or does not resolve.
nothingToCutA cut, or upToNext, with no body.
cutNoEffectA cut removed nothing.
upToNextNone, upToNextOpenupToNext found no face to stop at.
upToFaceBehind, upToFaceOutside, upToFaceUnsupported, upToPointBehindWith strictEnd; otherwise warnings (see above).
extrudeRegionUnknown, extrudeRegionNoneBad regions.
thinTooThickThe wall is too thick for the profile.
draftTooLarge, draftUnsupportedA taper that closes, or twist with draft.
booleanFailed, booleanVolumeMismatchThe boolean with the body failed.

revolve

Sweeps the profile about an axis.

FieldTypeDefaultMeaning
sketchfeature idrequiredThe profile sketch.
axisstring or objectrequiredA line entity of the profile’s own sketch, by id (it may be a construction line), or a line of another sketch as {"sketch": "<sketch id>", "id": "<line id>"} (entity ids restart in each sketch, so the owner is named). Its direction is from p1 to p2. Any other form, an unknown sketch or an unknown line is missingAxis.
opstring"add"See above.
anglenumber or expression360Degrees; positive turns right-handed about the axis direction, negative the other way; 360 or more is a full turn. Zero is invalidValue.
endstringOnly mid is read: the sweep is centred on the sketch plane.
flipbooleanfalseReverses the direction of the sweep.
regions, thin, bodyAs for extrude.

A profile must lie on one side of the axis: a region that crosses it is profileCrossesAxis. A revolve cut does not reverse its direction (unlike an extrude cut).

Faces: S.<entity> for each profile entity; C0 (at the start, in the sketch plane) and C1 (at the end) for a partial turn. A full turn has no caps.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "o", "x": 0, "y": 0},
        {"id": "p", "x": 0, "y": 20},
        {"id": "a", "x": 5, "y": 0},
        {"id": "b", "x": 15, "y": 0},
        {"id": "c", "x": 15, "y": 20},
        {"id": "d", "x": 5, "y": 20}
      ],
      "entities": [
        {"type": "line", "id": "ax", "p1": "o", "p2": "p", "construction": true},
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    }
  ]
}

The profile above is a rectangle from x = 5 to 15 and y = 0 to 20 and a construction line ax on the Y axis. Appended:

{"type": "revolve", "id": "F2", "op": "add", "sketch": "F1", "axis": "ax", "end": "blind", "angle": 360}

Run result: no errors; 4 faces, volume 12566.3706 mm³. A tube with outer radius 15 and inner radius 5 and height 20: volume pi (15² - 5²) 20 = 12566.3706. Faces F2.S.e1, F2.S.e2, F2.S.e3, F2.S.e4; no caps for a full turn.

{"type": "revolve", "id": "F2", "op": "add", "sketch": "F1", "axis": "ax", "angle": 90}

Run result: no errors; 6 faces, volume 3141.5927 mm³. A quarter of the tube, with faces F2.C0, F2.C1, F2.S.e1, F2.S.e2, F2.S.e3, F2.S.e4.

The axis can be drawn in a different sketch. With the construction line ax moved into its own sketch F0 (the same plane, a line from (0, 0) to (0, 20)) and left out of F1:

{"type": "revolve", "id": "F2", "op": "add", "sketch": "F1", "axis": {"sketch": "F0", "id": "ax"}, "angle": 360}

Run result: no errors; 4 faces, volume 12566.3706 mm³, the same tube as with the axis inside F1. The axis line is read at its solved position in F0 and placed by F0’s plane. surfaceRevolve takes the same forms.

Moving the profile points a and d to x = -5 puts the profile on both sides of the axis:

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "o", "x": 0, "y": 0},
        {"id": "p", "x": 0, "y": 20},
        {"id": "a", "x": -5, "y": 0},
        {"id": "b", "x": 15, "y": 0},
        {"id": "c", "x": 15, "y": 20},
        {"id": "d", "x": -5, "y": 20}
      ],
      "entities": [
        {"type": "line", "id": "ax", "p1": "o", "p2": "p", "construction": true},
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "revolve", "id": "F2", "op": "add", "sketch": "F1", "axis": "ax", "angle": 360}
  ]
}

Run result: errors F2: profileCrossesAxis; no solid body.

Errors: missingSketch, missingAxis, profileCrossesAxis, noClosedProfile, invalidValue (angle 0), nothingToCut, badExpression, and the boolean errors of extrude.

sphere

A ball. It needs no sketch.

FieldTypeDefaultMeaning
center[x, y, z][0, 0, 0]The centre, each component a number or expression.
radiusnumber or expression0Must be above 0, otherwise invalidValue with a detail.
opstring"add"add, cut or newBody.
bodystringnoneName of the body, with newBody.

The poles lie along +Y. The single face is S.e1.

{
  "format": "ck-part", "version": 1,
  "features": [{"type": "sphere", "id": "F1", "op": "add", "center": [0, 0, 0], "radius": 10}]
}

Run result: no errors; 1 face, volume 4188.7902 mm³. One spherical face, F1.S.e1; the volume is 4/3 pi 10³ = 4188.7902.

sweep

Moves the profile along a path.

FieldTypeDefaultMeaning
sketchfeature idrequiredThe profile. It must lie on a plane perpendicular to the path at its start: sweepProfileNotNormal otherwise.
pathreferencerequired{"kind": "sketch", "id": "F1"} for an open chain of lines and arcs in a sketch (or a sketch3d that holds one spline), or {"kind": "curve", "id": "F5"} for a helix or another curve feature. A missing or unusable path is missingPath.
opstring"add"See above. A sweep cut is not reversed.
targetselection or listnoneThe bodies a sweep add or cut acts on; see target under extrude.
twistnumber or expression0Degrees of rotation of the profile along the path.
guideslist of curve referencesnoneGuide curves ({"kind": ...} with sketchCurve, edge or curve) that the profile follows.
guideModestring"scale"scale, turn or stretch.
surfacebooleanfalseA sheet sweep. Not built: the error code is notImplemented (what: surface sweep (open profile -> sheet body)).
bodystringnoneName of the new body.

The path is walked from its free end. Consecutive path pieces must be joined end to end; corners between two lines are mitred. A corner between a line and an arc, or two arcs, that is not tangent is not built (notImplemented, what: mitre joint other than line-line (turn < 166 deg)); make the arc tangent.

Faces: C0 and C1 for the profile ends and S.<profile entity> for the surface swept by each profile entity. A side face is split ~1, ~2, … along the pieces of the path.

A circle swept along a path made of a line, an arc and a line (a handle). The document is complete:

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "name": "Handle path", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "p1", "x": 0, "y": 0},
        {"id": "p2", "x": 0, "y": 14},
        {"id": "p3", "x": 30, "y": 14},
        {"id": "p4", "x": 30, "y": 0},
        {"id": "p5", "x": 15, "y": 14}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "p1", "p2": "p2"},
        {"type": "arc", "id": "e2", "c": "p5", "p1": "p3", "p2": "p2"},
        {"type": "line", "id": "e3", "p1": "p3", "p2": "p4"}
      ],
      "constraints": []
    },
    {
      "type": "sketch", "id": "F2", "plane": {"kind": "std", "id": "top"},
      "points": [{"id": "c", "x": 0, "y": 0}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 3.5}], "constraints": []
    },
    {"type": "sweep", "id": "F3", "op": "add", "sketch": "F2", "path": {"kind": "sketch", "id": "F1"}}
  ]
}

Run result: no errors; 5 faces, volume 2891.1061 mm³. The caps are F3.C0 and F3.C1; the three path pieces (line, arc, line) give three side faces named after the profile circle e1: F3.S.e1~1, F3.S.e1~2, F3.S.e1~3.

A helix as a path (a coil of wire):

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "H1", "plane": {"kind": "std", "id": "top"},
      "points": [{"id": "c", "x": 0, "y": 0}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 10}], "constraints": []
    },
    {"type": "helix", "id": "F1", "sketch": "H1", "pitch": 4, "revolutions": 5},
    {
      "type": "sketch", "id": "F2", "plane": {"kind": "std", "id": "front"},
      "points": [{"id": "c", "x": 10, "y": 0}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 1.5}], "constraints": []
    },
    {"type": "sweep", "id": "F3", "op": "add", "sketch": "F2", "path": {"kind": "curve", "id": "F1"}}
  ]
}

Run result: no errors; 4 faces, volume 2220.661 mm³.

Errors: missingSketch, missingPath, sweepPathInvalid (the path sketch is not one open chain), sweepProfileNotNormal, noClosedProfile, nothingToCut, sweepFailed, sweepGuideMissing, sweepGuidesTwist (twist with guides), sweepGuideShort, sweepGuideStretchTwo and the other guide codes, booleanFailed.

loft

Joins two or more sections.

FieldTypeDefaultMeaning
sketcheslist of feature idsrequiredThe sections, in order. Fewer than two is loftProfiles.
opstring"add"Ignored for surface: true.
surfacebooleanfalseBuild a sheet (placed in surfaces, not in body). Sections may then be open chains.
guideslistnoneGuide curves: {"sketch": "G1", "influence": "next"} or a bare sketch id. Only sketch guides with influence next are supported.
centreLine{"sketch": id}noneA planar open chain the sections follow.
startNormal, endNormalnumber or truenoneTension of the normal at the ends (true is 1).
startTangent, endTangent, startContinuity, endContinuitynoneTangency to the faces next to the loft ends. Not available: any value other than false or null fails with loftTangentEdges.
connectorslistnonePositions of the start points to match, as fractions or null.
apexTangentnumber1For a point end: 0 to 2, how wide the taper is at the apex.
bodystringnoneName of the new body.

Each section must be one closed region (loftProfile for several, noClosedProfile for none). Sections whose regions have inner loops make a hollow loft: the outline loft minus the loft of the holes (matched across sections by nearest centroid); the numbers of holes must agree, otherwise loftProfile. The first or last section may be a sketch holding exactly one point entity: the loft ends in a point and has no cap there.

The face names come from the entities of the first section: S.<entity>, C0 and C1 (no cap at a point end).

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": -10, "y": -10},
        {"id": "b", "x": 10, "y": -10},
        {"id": "c", "x": 10, "y": 10},
        {"id": "d", "x": -10, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {
      "type": "plane", "id": "P1", "mode": "offset", "base": {"kind": "std", "id": "front"},
      "offset": 30
    },
    {
      "type": "sketch", "id": "S2", "plane": {"kind": "feature", "id": "P1"},
      "points": [
        {"id": "a", "x": -5, "y": -5},
        {"id": "b", "x": 5, "y": -5},
        {"id": "c", "x": 5, "y": 5},
        {"id": "d", "x": -5, "y": 5}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "loft", "id": "F5", "op": "add", "sketches": ["S1", "S2"]}
  ]
}

Run result: no errors; 6 faces, volume 7000 mm³. A frustum: (400 + 100 + sqrt(400 x 100)) x 30 / 3 = 7000. Faces F5.S.e1, F5.S.e2, F5.S.e3, F5.S.e4, F5.C0, F5.C1.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": -10, "y": -10},
        {"id": "b", "x": 10, "y": -10},
        {"id": "c", "x": 10, "y": 10},
        {"id": "d", "x": -10, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {
      "type": "plane", "id": "P1", "mode": "offset", "base": {"kind": "std", "id": "front"},
      "offset": 30
    },
    {
      "type": "sketch", "id": "S2", "plane": {"kind": "feature", "id": "P1"},
      "points": [{"id": "p", "x": 0, "y": 0}], "entities": [{"type": "point", "id": "e1", "p": "p"}],
      "constraints": []
    },
    {"type": "loft", "id": "F5", "op": "add", "sketches": ["S1", "S2"]}
  ]
}

Run result: no errors; 5 faces, volume 4000 mm³. A pyramid: 400 x 30 / 3 = 4000. It has no cap at the apex: F5.S.e1, F5.S.e2, F5.S.e3, F5.S.e4, F5.C0.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": -10, "y": -10},
        {"id": "b", "x": 10, "y": -10},
        {"id": "c", "x": 10, "y": 10},
        {"id": "d", "x": -10, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {
      "type": "plane", "id": "P1", "mode": "offset", "base": {"kind": "std", "id": "front"},
      "offset": 30
    },
    {
      "type": "sketch", "id": "S2", "plane": {"kind": "feature", "id": "P1"},
      "points": [
        {"id": "a", "x": -5, "y": -5},
        {"id": "b", "x": 5, "y": -5},
        {"id": "c", "x": 5, "y": 5},
        {"id": "d", "x": -5, "y": 5}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "loft", "id": "F5", "surface": true, "sketches": ["S1", "S2"]}
  ]
}

Run result: no errors; no solid body. The loft is a sheet: surfaces holds F5 with the faces F5.S.e1, F5.S.e2, F5.S.e3, F5.S.e4.

Errors: missingSketch, loftProfiles (fewer than two sections, or all in one plane), loftProfile (with detail and hint), loftProfileOpen (mixed open and closed sections), loftProfileNotPlanar, loftFailed, loftInvalidResult, loftProfileSelfIntersect, loftSectionTooSmall, loftGuideInvalid, loftCentreLineInvalid (and ...Kink, ...Reach, ...Tight, ...Apex, ...Guides), loftTangentEdges (any tangency field set; tangency on loft ends is always refused), nothingToCut, booleanFailed. Loft errors carry detail and, when there is one, a hint.

rib

A thin wall from an open sketch chain to the body.

FieldTypeDefaultMeaning
sketchfeature idrequiredA sketch with an open chain and no closed region.
thicknessnumber or expression2Total thickness, centred on the sketch plane. Must be above 0.
flipbooleanfalseWhich side of the chain is tried first. A successful result does not depend on it.
sideboth | right | leftbothWhere the thickness goes across the sketch plane. both centres it on the plane (C0 at -thickness/2, C1 at +thickness/2); right puts all of it on the side the sketch normal points to (C0 on the plane, C1 at +thickness); left puts it against the normal (C0 at -thickness, C1 on the plane).
draftnumber or expression0Taper of the two side faces in degrees, from 0 to 45. The wall is thickness thick at the free edge and wider by 2 * tan(draft) per unit of distance toward the body, so the rib can be released from a mould. It needs a sketch that is one straight line (draftUnsupported otherwise). With side right or left both faces still tilt away from the plane.
filletnumber or expression0Radius of a round on the two edges of the free face (the kernel fillet of those edges, after the rib is united). Must be above 0 and below half the thickness. The round ends on the faces the rib meets. The blend faces are named like any fillet (B<k>).
targetbody selection or listall bodiesThe body or bodies the rib extends to, as for extrude: {"body": "Name"}, a face name, or a list of them. The other bodies are not touched. With a list, a body the rib misses is skipped; ribNoContact only when it touches none. An unknown name is missingReference with the bodies the part has.

The wall fills the space between the chain and the body, extended past the ends of the chain until it meets the body, and is united with the body. The extension stops at the outer wall of the body: a piece of the extended wall that lies in a void of the body, such as the bore of a boss the line runs through, is not part of the rib, only the pieces that border the chain itself are kept. So a rib made before or after the bore cut gives the same body. Faces: C0 and C1 (the two sides), S.<entity>r for the free edge along the chain. Errors: nothingToCut (no body), missingSketch, invalidValue (thickness, or side, draft or fillet out of range, with detail and hint), draftUnsupported (draft on a chain that is not one straight line), ribNeedsOpenSketch (the sketch has a closed region or no chain), ribNoContact (nothing encloses the rib), a fillet refusal (blendFailed and friends) when the round does not fit.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 40, "y": 0},
        {"id": "c", "x": 40, "y": 20},
        {"id": "d", "x": 0, "y": 20}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 10},
    {"type": "shell", "id": "F3", "faces": ["F2.C1"], "thickness": 2}
  ]
}

Appended to the shelled box above (the plate with its top face removed and 2 mm walls):

[
  {"type": "plane", "id": "P1", "mode": "offset", "base": {"kind": "std", "id": "top"}, "offset": 10},
  {
    "type": "sketch", "id": "F4", "plane": {"kind": "feature", "id": "P1"},
    "points": [{"id": "a", "x": 5, "y": -5}, {"id": "b", "x": 35, "y": -5}],
    "entities": [{"type": "line", "id": "e1", "p1": "a", "p2": "b"}], "constraints": []
  },
  {"type": "rib", "id": "F5", "sketch": "F4", "thickness": 2}
]

Run result: no errors; 15 faces, volume 3608 mm³. The rib adds 216 mm³ to the shelled box (3392). Its faces: F5.C0, F5.C1, F5.S.e1r.

helix

A helix curve, for use as a sweep path or as a reference for planes and projections. It adds no body.

FieldTypeDefaultMeaning
sketchfeature idrequiredA sketch whose first circle gives the radius and the centre. No circle is helixNeedsCircle.
definedBystring"pitchRevs"Which two of the three sizes are used: pitchRevs (pitch, revolutions), heightRevs (height, revolutions) or heightPitch (height, pitch). Any other value reads as pitchRevs.
pitchnumber or expression1Rise per turn, mm.
revolutionsnumber or expression10Number of turns.
heightnumber or expression10Total rise, mm.
startAnglenumber or expression0Degrees from the sketch x axis at which the helix starts.
leftHandbooleanfalseTurn the other way.
reversebooleanfalseRise against the sketch normal.

A helix makes a curve and no faces. The axis is the normal of the sketch plane through the circle’s centre. A pitch, number of turns or radius that is not above 0 is invalidValue. The reply lists the curve in curves as [id, {pts, axis: false, t0: 0, t1: angle, helix: {o, a, x, y, k, r, angle}}]: o is the centre, a the axis, x the start direction, y the direction the helix turns towards, k = pitch / (2 pi), r the radius and angle the total turn in radians.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "H1", "plane": {"kind": "std", "id": "top"},
      "points": [{"id": "c", "x": 0, "y": 0}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 10}], "constraints": []
    },
    {
      "type": "helix", "id": "F1", "sketch": "H1", "definedBy": "pitchRevs", "pitch": 4,
      "revolutions": 5
    }
  ]
}

Run result: no errors; no solid body. curves holds F1 with 161 points; helix is {“o”:[0,0,0],“a”:[0,1,0],“k”:0.6366,“r”:10,“angle”:31.4159}: axis +Y (the normal of the top plane), 20 mm tall.

hole

hole cuts holes at the point entities of a sketch. It is documented with the other edits that remove material from the body, in edge and face edits.

See also

Edge and face edits

These features change the body that earlier features made: they round or bevel edges (fillet, chamfer), tilt faces (draft), hollow the body (shell), cut holes and threads (hole, thread), add or cut a band along a rim (lip), push faces (moveFace) and remove whole bodies (deleteBody). They refer to faces by name and to edges by the two faces that meet there (see identifiers and references). The examples append a feature to the plate of the overview (40 x 20 x 10 mm, faces F2.C0, F2.C1, F2.S.e1 … F2.S.e4).

A failed edit leaves the body as it was before the feature.

fillet

Rounds edges with a circular arc.

FieldTypeDefaultMeaning
radiusnumber or expression0Radius in mm. It must be above 0 (invalidValue).
edgeslist of edge picksrequired{"faces": [a, b], "at": [x, y, z]}; optional radius or radii per pick. No edges, or an edge that cannot be found, is missingEdge.
profilestring"circular"circular, conic (rho between 0 and 1, default 0.5; filletRho otherwise), chord (the radius is the chord width) or curvature (shape between 0.1 and 1, default 0.5; filletShape otherwise).
propagatebooleanfalseGrow the selection along edges that continue the picked ones tangentially (the outline of a rounded rectangle from one pick).
filletTypestringomittedLeave it out for a constant radius. "variable" (see below) and "fullRound" are the only accepted values; any other string, including "circular", is unsupported.
radii[near, far]nonevariable: the radius at the end of each picked edge nearer the pick point, and at the other end. Both at least 0, not both 0.
side1, center, side2face namesnonefullRound: the three faces the ball rolls between.

A pick may carry its own radius (that edge is rounded with it; the feature’s radius is the default) or, for a variable fillet, its own radii. Edges that meet at a vertex with different radii end in a mitre and the feature carries a cornerNotTangent {deviation} warning with the largest normal jump in degrees. Edges that meet at a vertex of a variable fillet must have the same radius there (variableRadiusMismatch).

Faces: B0, B1, … one per rounded edge in the order of the picks; V0, … for the spherical patch where three rounded edges meet at a convex corner.

{
  "type": "fillet", "id": "F3", "radius": 2,
  "edges": [{"faces": ["F2.C1", "F2.S.e1"], "at": [20, 0, 10]}]
}

Run result: no errors; 7 faces, volume 7965.6637 mm³. The new face is F3.B0. The removed material is 40 x (4 - pi 2²) / 4 = 34.3363 mm³.

A pick may set its own radius:

{
  "type": "fillet", "id": "F3", "radius": 2,
  "edges": [
    {"faces": ["F2.C1", "F2.S.e1"], "at": [20, 0, 10], "radius": 1},
    {"faces": ["F2.C1", "F2.S.e3"], "at": [20, 20, 10]}
  ]
}

Run result: no errors; 8 faces, volume 7957.0796 mm³. Faces F3.B0, F3.B1: the first edge has radius 1 and the second the default 2.

A variable radius, 1 mm at the end of the edge nearer the pick and 3 mm at the other:

{
  "type": "fillet", "id": "F3", "filletType": "variable", "radii": [1, 3],
  "edges": [{"faces": ["F2.C1", "F2.S.e1"], "at": [20, 0, 10]}]
}

Run result: no errors; 7 faces, volume 7962.8023 mm³.

propagate follows tangent edges; here the second pick is the next edge of the outline:

{
  "type": "fillet", "id": "F3", "radius": 2, "propagate": true,
  "edges": [
    {"faces": ["F2.C1", "F2.S.e1"], "at": [20, 0, 10]},
    {"faces": ["F2.C1", "F2.S.e2"], "at": [40, 10, 10]}
  ]
}

Run result: no errors; 8 faces, volume 7949.2625 mm³. Faces F3.B0, F3.B1.

fullRound rolls a ball between two side faces and a centre face; the centre face vanishes:

{
  "type": "fillet", "id": "F3", "filletType": "fullRound", "side1": "F2.S.e1", "center": "F2.C1",
  "side2": "F2.S.e3"
}

Run result: no errors; 4 faces, volume 6283.1853 mm³. The 10 mm high plate becomes a half cylinder of radius 10: pi 10² / 2 x 40 = 6283.1853. The top face is gone and one round face F3.B0 remains.

A radius the faces cannot take:

{
  "type": "fillet", "id": "F3", "radius": 15,
  "edges": [{"faces": ["F2.C1", "F2.S.e1"], "at": [20, 0, 10]}]
}

Run result: errors F3: blendOverflow {"detail":"F3.B0: spring leaves its face away from its edges"}; 6 faces, volume 8000 mm³.

Errors: invalidValue (radius not above 0, bad radii), missingEdge, blendOverflow {detail} (the round leaves its faces), blendTooLarge, blendFailed {detail}, blendUnsupported, unsupported {what}, filletRho, filletShape, variableRadiusMismatch, fullRoundUnsupported, missingReference (a face of fullRound), badExpression. Warnings: cornerNotTangent, filletRadiusApproximated (a variable end radius of 0 is built with a small positive radius; params.used says which).

chamfer

Bevels edges.

FieldTypeDefaultMeaning
chamferTypestring"equal"equal, distances (alias distanceDistance), angle (alias angleDistance), vertex. Any other value is unsupported {what: "chamfer <type>"}.
distancenumber or expression0The leg length. Must be above 0.
distance2number or expressiondistancedistances: the leg on the second face.
anglenumber or expressionnoneangle: degrees between the chamfer and the first face.
faceface namefirst face of each pickThe face on which distance is measured. Every pick must border it.
flipbooleanfalseSwaps the two legs.
propagatebooleanfalseAs for fillet.
edgeslist of edge picksrequiredFor vertex: one pick {"faces": [f1, f2, f3], "at": [..]} naming the three faces of the corner.
distance3number or expressiondistancevertex: the third leg (distance2 is the second).

A chamfer has constant legs along its edge: there is no variable chamfer (setbacks that differ at the two ends of an edge). A variable fillet has radii. The order of the edges list does not change the result.

For distances and angle, distance is measured on the first face of the pick (the first entry of faces) unless face names it. Picks of one feature must agree on which face comes first (mixed orders are unsupported); naming face makes a ring of edges agree.

Faces: B0, B1, … per chamfered edge.

{
  "type": "chamfer", "id": "F3", "chamferType": "equal", "distance": 2,
  "edges": [{"faces": ["F2.C1", "F2.S.e1"], "at": [20, 0, 10]}]
}

Run result: no errors; 7 faces, volume 7920 mm³. Removed: 40 x 2 x 2 / 2 = 80 mm³. New face F3.B0.

Two distances; distance is on the first face of the pick:

{
  "type": "chamfer", "id": "F3", "chamferType": "distances", "distance": 2, "distance2": 3,
  "edges": [{"faces": ["F2.C1", "F2.S.e1"], "at": [20, 0, 10]}]
}

Run result: no errors; 7 faces, volume 7880 mm³. Removed: 40 x 2 x 3 / 2 = 120 mm³; 2 mm on F2.C1 (the first face of the pick) and 3 mm on F2.S.e1.

A distance and an angle:

{
  "type": "chamfer", "id": "F3", "chamferType": "angle", "distance": 2, "angle": 30,
  "edges": [{"faces": ["F2.C1", "F2.S.e1"], "at": [20, 0, 10]}]
}

Run result: no errors; 7 faces, volume 7953.812 mm³.

A vertex chamfer cuts off a corner:

{
  "type": "chamfer", "id": "F3", "chamferType": "vertex", "distance": 2,
  "edges": [{"faces": ["F2.C1", "F2.S.e1", "F2.S.e4"], "at": [0, 0, 10]}]
}

Run result: no errors; 7 faces, volume 7998.6667 mm³.

Errors: invalidValue (distance not above 0), missingEdge, unsupported, chamferVertexEdges (the corner does not have three edges), blendTooLarge, blendOverflow, blendFailed, blendUnsupported.

draft

Tilts faces about a neutral plane.

FieldTypeDefaultMeaning
neutralplane referencerequiredThe plane that stays put: a standard plane, a plane feature or a planar face. Its normal is the pull direction (reversed by flip). A face neutral pulls into its material.
faceslist of face namesrequiredThe faces to tilt. A name without ~k selects every piece. Faces that continue a drafted face tangentially are drafted with it.
anglenumber or expression0Degrees.
flipbooleanfalseReverses the pull direction.

Face names do not change. An angle of 0 (also the default when angle is missing) is invalidValue. Errors: nothingToCut (no body), missingReference (neutral or faces), noFaces, draftParallelFace, draftAxisNotParallel, draftUnsupported, draftTangentFaces, draftTooLarge {detail} (an edge turns over; for tapers that close to a point maxHeight), draftFailed, invalidValue.

{
  "type": "draft", "id": "F3", "neutral": {"kind": "std", "id": "front"}, "faces": ["F2.S.e1"],
  "angle": 5
}

Run result: no errors; 6 faces, volume 7825.0227 mm³. The face F2.S.e1 keeps its name and leans by 5 degrees; the volume drops by 174.9773 mm³.

With a face as neutral plane, the four sides tilt towards the bottom:

{
  "type": "draft", "id": "F3", "neutral": {"kind": "face", "id": "F2.C0"},
  "faces": ["F2.S.e1", "F2.S.e2", "F2.S.e3", "F2.S.e4"], "angle": 5
}

Run result: no errors; 6 faces, volume 7485.2737 mm³.

An angle that turns an edge over:

{
  "type": "draft", "id": "F3", "neutral": {"kind": "std", "id": "front"}, "faces": ["F2.S.e1"],
  "angle": 80
}

Run result: errors F3: draftTooLarge {"detail":"edge between F2.S.e2 and F2.C1 turns over"}; 6 faces, volume 8000 mm³.

shell

Hollows the body to a wall thickness, removing the listed faces.

FieldTypeDefaultMeaning
faceslist of face namesrequiredThe faces to open. An empty list closes the cavity. A name that does not exist is missingReference.
thicknessnumber or expression0Wall thickness; must be above 0.
outwardbooleanfalseGrow the wall outwards instead of inwards.

Every wall face is doubled: the outer face and the face of the cavity share a name and are told apart as ~1 and ~2 (see identifiers and references). A body with several bodies in it shells only the body that holds the opened faces.

{"type": "shell", "id": "F3", "faces": ["F2.C1"], "thickness": 2}

Run result: no errors; 11 faces, volume 3392 mm³. Volume 40 x 20 x 10 - 36 x 16 x 8 = 3392. Faces F2.C0~1, F2.S.e1~1, F2.S.e2~2, F2.S.e3~2, F2.S.e4~1, F2.C1, F2.C0~2, F2.S.e1~2, F2.S.e2~1, F2.S.e3~1, F2.S.e4~2.

{"type": "shell", "id": "F3", "faces": ["F2.C1"], "thickness": 2, "outward": true}

Run result: no errors; 11 faces, volume 4672 mm³. The walls grow outwards: box [-2,-2,-2] to [42,22,10].

Errors carry numbers when the limit is known: shellTooThick {detail, limit, minRadius, maxThickness, face} where limit is "curvature" (the offset passes a centre of curvature) or "thin" (two sheets closer than twice the thickness) and maxThickness a thickness that works. Others: nothingToCut, invalidValue, missingReference, shellUnsupported, shellFailed, offsetUnsupported and offsetTooLarge (both with detail).

{"type": "shell", "id": "F3", "faces": ["F2.C1"], "thickness": 12}

Run result: errors F3: shellTooThick {"detail":"an edge reverses","limit":"thin","minRadius":19.5,"maxThickness":9.26}; 6 faces, volume 8000 mm³.

hole

Cuts holes at the point entities of a sketch, into the face the sketch lies on.

FieldTypeDefaultMeaning
sketchfeature idrequiredA sketch with point entities. The holes go against the sketch normal (into the material of a sketch on a face). A sketch with no points is holeNoPoints.
standardstringRead and ignored: the only table is ISO.
sizestringnoneM2, M2.5, M3, M4, M5, M6, M8, M10, M12, M16, M20 or M24.
fitstring"normal"normal, tap (simple holes only), close or loose.
kindstring"simple"simple, cbore (counterbore), countersink (alias csk) or csink (the older spelling: a plain hole unless cskDiameter is given).
diameternumber or expressionnoneA plain diameter instead of size/fit for a simple hole; also for the other kinds when the table does not apply (see below).
endstring"blind"blind uses depth; any other value is through the whole body.
depthnumber or expression0Depth of a blind hole. A blind hole needs a depth above 0: with depth missing or 0 the cut has no volume and the feature fails with booleanFailed (params.issue: "openEdge", params.faces the face the sketch lies on), a misleading code for a missing depth.
tipbooleanfalseA blind hole ends in a 118 degree drill-point cone.
flipbooleanfalseCut along the sketch normal instead of against it.
targetselection or listnoneDrill only the named bodies ({"body":"A"}); see target in solids. Without it the holes cut every body they meet.
cboreDiameter, cboreDepthnumber or expressiontableCounterbore size. Each is independent.
cskDiameter, cskAnglenumber or expressiontable, 90Countersink head diameter and included angle in degrees.

Many points. One hole feature takes any number of points; the cost grows about in step with the number of holes. Each hole is a separate tool solid; a hole is united with another only when the two overlap or touch, and all the tools are then cut from the body in one step. (Earlier builds folded every hole into one growing union, which made the time grow with the square of the number of points: 10 x 10 holes took 7.6 s, 20 x 20 about 131 s and 30 x 30 about 748 s.) On the build machine a 30 x 30 grid of through holes in one feature (900 holes, 906 faces) now takes about 3.3 s, 20 x 20 about 1.2 s and 10 x 10 under 0.1 s. The faces, their names and the volume are the same as before. Above a few hundred points the default feature time limit (when a clock is present) can still trip on a slow machine; split the points over several hole features or raise the limit.

The hole diameter by size and fit, and the head sizes (mm):

SizetapclosenormallooseCounterbore diameterCounterbore depthCountersink head
M21.62.22.42.64.32.34.4
M2.52.052.72.93.15.02.85.5
M32.53.23.43.66.53.46.5
M43.34.34.54.88.04.48.6
M54.25.35.55.810.05.410.4
M65.06.46.67.011.06.412.4
M86.88.49.010.015.08.616.4
M108.510.511.012.018.010.620.4
M1210.213.013.514.520.012.624.4
M1614.017.017.518.526.016.632.4
M2017.521.022.024.033.020.640.4
M2421.025.026.028.040.024.848.4

For counterbore and countersink holes the tap fit reads as normal. A countersink cone starts with the head diameter at the top face and tapers to the hole diameter; its depth is (head - d) / 2 / tan(angle / 2).

A diameter also serves a counterbore or countersink when no table size applies, but then the step or cone must be given (cboreDiameter and cboreDepth, or cskDiameter). If one is missing the hole is drilled as a simple hole of diameter and the reply carries a warning holeDowngraded {requested, built: "simple", missing, detail, hint}.

Faces made by one hole (the top disc lies in the existing face and has no name), with ~k appended per point when the sketch has several:

KindFaces
simpleh1 wall, h2 bottom (the cone with tip).
cboreh1 counterbore wall, h2 step floor, h3 hole wall, h4 bottom.
countersinkK0 cone, h1 wall, h2 bottom.

A through hole has no bottom face. All faces are written <feature>.S.<tag>, for example F4.S.h1.

[
  {
    "type": "sketch", "id": "F3", "plane": {"kind": "face", "id": "F2.C1"},
    "points": [{"id": "p1", "x": 10, "y": 10}], "entities": [{"type": "point", "id": "e1", "p": "p1"}],
    "constraints": []
  },
  {
    "type": "hole", "id": "F4", "sketch": "F3", "standard": "iso", "size": "M6", "fit": "normal",
    "kind": "simple", "end": "blind", "depth": 6
  }
]

Run result: no errors; 8 faces, volume 7794.7283 mm³. Diameter 6.6, depth 6: 205.2717 mm³ removed = pi 3.3² 6. Faces F4.S.h2, F4.S.h1.

Counterbore:

[
  {
    "type": "sketch", "id": "F3", "plane": {"kind": "face", "id": "F2.C1"},
    "points": [{"id": "p1", "x": 10, "y": 10}], "entities": [{"type": "point", "id": "e1", "p": "p1"}],
    "constraints": []
  },
  {
    "type": "hole", "id": "F4", "sketch": "F3", "standard": "iso", "size": "M5", "fit": "normal",
    "kind": "cbore", "end": "blind", "depth": 8
  }
]

Run result: no errors; 10 faces, volume 7514.1134 mm³. Faces F4.S.h4, F4.S.h3, F4.S.h2, F4.S.h1.

Countersink, through:

[
  {
    "type": "sketch", "id": "F3", "plane": {"kind": "face", "id": "F2.C1"},
    "points": [{"id": "p1", "x": 10, "y": 10}], "entities": [{"type": "point", "id": "e1", "p": "p1"}],
    "constraints": []
  },
  {
    "type": "hole", "id": "F4", "sketch": "F3", "standard": "iso", "size": "M5", "fit": "normal",
    "kind": "countersink", "end": "through"
  }
]

Run result: no errors; 8 faces, volume 7695.159 mm³. Faces F4.S.K0, F4.S.h1.

Two holes from one sketch:

[
  {
    "type": "sketch", "id": "F3", "plane": {"kind": "face", "id": "F2.C1"},
    "points": [{"id": "p1", "x": 10, "y": 10}, {"id": "p2", "x": 30, "y": 10}],
    "entities": [{"type": "point", "id": "e1", "p": "p1"}, {"type": "point", "id": "e2", "p": "p2"}],
    "constraints": []
  },
  {
    "type": "hole", "id": "F4", "sketch": "F3", "standard": "iso", "size": "M6", "fit": "tap",
    "kind": "simple", "end": "blind", "depth": 6
  }
]

Run result: no errors; 10 faces, volume 7764.3806 mm³. Faces F4.S.h2~1, F4.S.h1~1, F4.S.h2~2, F4.S.h1~2.

A plain diameter without the step dimensions downgrades a counterbore:

[
  {
    "type": "sketch", "id": "F3", "plane": {"kind": "face", "id": "F2.C1"},
    "points": [{"id": "p1", "x": 10, "y": 10}], "entities": [{"type": "point", "id": "e1", "p": "p1"}],
    "constraints": []
  },
  {
    "type": "hole", "id": "F4", "sketch": "F3", "kind": "cbore", "diameter": 7.5, "end": "blind",
    "depth": 6
  }
]

Run result: no errors; warnings F4: holeDowngraded {"requested":"counterbore","built":"simple","missing":["cboreDiameter","cboreDepth"],"detail":"the counterbore has no cboreDiameter or cboreDepth to build it from, so a plain hole of the given diameter was drilled","hint; 8 faces, volume 7734.9281 mm³.

An unknown size:

[
  {
    "type": "sketch", "id": "F3", "plane": {"kind": "face", "id": "F2.C1"},
    "points": [{"id": "p1", "x": 10, "y": 10}], "entities": [{"type": "point", "id": "e1", "p": "p1"}],
    "constraints": []
  },
  {
    "type": "hole", "id": "F4", "sketch": "F3", "standard": "iso", "size": "M7", "end": "blind",
    "depth": 6
  }
]

Run result: errors F4: holeInvalid {"detail":"the simple hole has no size for the standard table","hint":"give a standard size (e.g. M6), or a plain diameter"}; 6 faces, volume 8000 mm³.

Errors: missingSketch, holeNoPoints, holeInvalid {detail, hint} (no size and no diameter, an unknown size, a diameter of 0 or less), holeCboreInvalid {hint, ...} (counterbore diameter not larger than the hole, depth 0 or less, or not shallower than the hole), holeCskDiameter {hint, ...} (head diameter not larger than the hole, angle outside 0 to 180, cone deeper than the hole), nothingToCut, cutNoEffect (the hole misses the body or points away from it), badExpression.

thread

Puts a thread on a cylindrical face: the wall of a hole or a shaft. By default it is cosmetic (data for drawings and checks); with modeled it cuts a helical groove.

FieldTypeDefaultMeaning
faceface namerequiredA cylindrical face, for example F4.S.h1. A missing face is missingReference; a face that is not a cylinder is threadFaceNotCylinder.
standardstringrequiredmetric, metric-fine, UNC, UNF, BSP, BSPT, NPT, Tr or Acme (aliases such as ISO, G are accepted).
sizestringrequiredA designation from the table of the standard, for example M6, 1/4-20, G1/4, R1/4. The threadData request lists them.
classstring6H, 6g, 2B, 2A, …Tolerance class. Recorded; it does not change the geometry.
lengthnumber, expression or "full""full"Thread length in mm, clamped to the face. Zero or less is invalidValue.
handstring"right"right or left.
startstringthe open endtop or bottom: the end of the face with the higher or lower coordinate along its axis.
modeledbooleanfalseCut the real groove.
clearancenumber or expression0Printed-fit clearance in mm, signed, at most 1 in size (more is invalidValue). Positive is looser, negative tighter. It changes the modeled groove only: an internal thread’s groove reaches clearance further out, an external thread’s goes clearance deeper (the thread’s diameters move by twice that). A groove is never wider than 0.9 of the pitch, so an external thread wants the shaft drawn near the loosened major (nominal major minus twice the clearance); a shaft left at the nominal major is threadModelFallback. The threads entry carries clearance when it is not zero.

Internal or external is read from the face (concave is internal). A cosmetic thread changes nothing in the body; the reply gains a threads list sorted by feature id, one entry per thread with id, face, standard, size, class, pitch, major, minor, pitchDiameter, angle, length, hand, internal, modeled, tapered, diameter (of the face), and start and dir (a point on the axis and the unit direction into the face).

A modeled thread cuts a trapezoidal groove (flank angle 60 for ISO and UN, 55 for BSP, 30 for Tr, 29 for Acme) with flat crests and roots. The groove faces are T0 to T5 (T0 the inner or outer surface, T1 and T3 the flanks, T2 root or bottom, T4 and T5 the end caps); those that lie in the void do not remain in the body. A thread that cannot be modeled stays cosmetic and the feature carries threadModelFallback {reason, hint}: tapered threads (BSPT, NPT), a groove of more than 60 turns, a length shorter than one turn, a bore or shaft that does not match the thread, or a failed boolean.

An internal thread wants the face diameter within 3 percent of the tap drill, an external one within 3 percent of the major diameter; otherwise the feature carries a warning threadDiameterMismatch {expected, actual, size, standard, internal, nearest, hint}. BSP is the parallel pipe thread G (ISO 228, G1/16 to G4); BSPT is the tapered pipe thread of ISO 7 (sizes R1/16 to R4, and Rp1/4 or Rc1/4 find the same size). Both use the 55 degree form; a tapered size has a 1:16 taper on the diameter but is recorded as cosmetic data (tapered: true) and the real taper is not cut. Patterns and mirrors carry the threads of their seeds onto the copies (see patterns and transforms).

[
  {
    "type": "sketch", "id": "F3", "plane": {"kind": "face", "id": "F2.C1"},
    "points": [{"id": "p1", "x": 10, "y": 10}], "entities": [{"type": "point", "id": "e1", "p": "p1"}],
    "constraints": []
  },
  {
    "type": "hole", "id": "F4", "sketch": "F3", "standard": "iso", "size": "M6", "fit": "tap",
    "kind": "simple", "end": "through"
  },
  {"type": "thread", "id": "F5", "face": "F4.S.h1", "standard": "metric", "size": "M6"}
]

Run result: no errors; 7 faces, volume 7803.6505 mm³. The threads list of the reply: [{"id":"F5","face":"F4.S.h1","standard":"metric","size":"M6","class":"6H","pitch":1,"major":6,"minor":4.917468,"pitchDiameter":5.350481,"angle":60,"length":10,"hand":"right","internal":true,"modeled":false,"tapered":false,"diameter":5,"start":[10,10,10],"dir":[0,0,-1]}].

[
  {
    "type": "sketch", "id": "F3", "plane": {"kind": "face", "id": "F2.C1"},
    "points": [{"id": "p1", "x": 10, "y": 10}], "entities": [{"type": "point", "id": "e1", "p": "p1"}],
    "constraints": []
  },
  {
    "type": "hole", "id": "F4", "sketch": "F3", "standard": "iso", "size": "M6", "fit": "tap",
    "kind": "simple", "end": "through"
  },
  {"type": "thread", "id": "F5", "face": "F4.S.h1", "standard": "metric", "size": "M6", "modeled": true}
]

Run result: no errors; 10 faces, volume 7768.6672 mm³. Groove faces: F5.T0, F5.T1, F5.T2.

An unknown size lists the nearest ones:

[
  {
    "type": "sketch", "id": "F3", "plane": {"kind": "face", "id": "F2.C1"},
    "points": [{"id": "p1", "x": 10, "y": 10}], "entities": [{"type": "point", "id": "e1", "p": "p1"}],
    "constraints": []
  },
  {
    "type": "hole", "id": "F4", "sketch": "F3", "standard": "iso", "size": "M6", "fit": "tap",
    "kind": "simple", "end": "through"
  },
  {"type": "thread", "id": "F5", "face": "F4.S.h1", "standard": "metric", "size": "M99"}
]

Run result: errors F5: threadSizeUnknown {"standard":"metric","size":"M99","suggestions":["M39","M1","M2","M3","M4"],"hint":"\"M99\" is not a metric size; closest: M39, M1, M2, M3, M4 (request threadData for the list)"}; 7 faces, volume 7803.6505 mm³.

A thread on a hole of the wrong size is built but flagged:

[
  {
    "type": "sketch", "id": "F3", "plane": {"kind": "face", "id": "F2.C1"},
    "points": [{"id": "p1", "x": 10, "y": 10}], "entities": [{"type": "point", "id": "e1", "p": "p1"}],
    "constraints": []
  },
  {
    "type": "hole", "id": "F4", "sketch": "F3", "standard": "iso", "size": "M6", "fit": "tap",
    "kind": "simple", "end": "through"
  },
  {"type": "thread", "id": "F5", "face": "F4.S.h1", "standard": "metric", "size": "M8"}
]

Run result: no errors; warnings F5: threadDiameterMismatch {"expected":6.8,"actual":5,"size":"M8","standard":"metric","internal":true,"nearest":"M6","hint":"hole is 5, M8 tap drill is 6.8: drill the hole to 6.8, or choose M6 (tap drill 5)"}; 7 faces, volume 7803.6505 mm³.

Errors: threadSizeUnknown {standard, size, suggestions, hint}, threadFaceNotCylinder {face, surface, hint}, missingReference, invalidValue {field}.

lip

Adds a raised band (a lip) along rim edges, or cuts a groove into the rim face.

FieldTypeDefaultMeaning
kindstring"lip"lip raises the band out of the rim face; groove cuts it into the rim face.
faceslist of face namesrequiredThe rim face. A name without ~k selects every piece.
edgeslist of edge picksrequiredThe rim edges to follow: {"faces": [rim face, neighbour face], "at": [..]}.
widthnumber or expression1Width of the band, measured inwards from the path. Must be above 0.
heightnumber or expression1Height out of (lip) or depth into (groove) the rim face. Must be above 0.
insetnumber or expression0Distance from the path to the band, measured inwards. With 0 the band touches the path and merges with the wall; above 0 the band stands clear of the outer wall (a centred tongue in a wall) and needs a closed loop of rim edges.
clearancenumber or expression0Groove only: the groove is wider by clearance on each side (its inset shrinks by it, its width grows by twice it) and deeper by clearance, so a lip and a groove given the same inset, width and height fit with this gap. With inset above 0 it may not exceed inset (invalidValue {field: "clearance"}); with inset 0 the band is wider by clearance on its free side only.

The rim face must be planar. Faces: C1 (the top of a lip) or C0 (the floor of a groove), and S.<neighbour face>l for the inner wall of the band along each edge. The outer side of the band merges with the existing wall.

On the plate shelled with 2 mm walls (the faces of the shell keep the names F2.S.e1~1 for the outer walls):

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 40, "y": 0},
        {"id": "c", "x": 40, "y": 20},
        {"id": "d", "x": 0, "y": 20}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 10},
    {"type": "shell", "id": "F3", "faces": ["F2.C1"], "thickness": 2}
  ]
}

Four rim picks, appended to the shelled document above:

{
  "type": "lip", "id": "F4", "kind": "lip", "faces": ["F2.C1"],
  "edges": [
    {"faces": ["F2.C1", "F2.S.e1~1"], "at": [20, 0, 10]},
    {"faces": ["F2.C1", "F2.S.e2~2"], "at": [40, 10, 10]},
    {"faces": ["F2.C1", "F2.S.e3~2"], "at": [20, 20, 10]},
    {"faces": ["F2.C1", "F2.S.e4~1"], "at": [0, 10, 10]}
  ],
  "width": 1, "height": 1.5
}

Run result: no errors; 16 faces, volume 3566 mm³. Volume 3566 (3392 + the 1 mm wide, 1.5 mm high band). Faces F4.C1, F4.S.F2.S.e4l, F4.S.F2.S.e3l, F4.S.F2.S.e2l, F4.S.F2.S.e1l.

{
  "type": "lip", "id": "F4", "kind": "groove", "faces": ["F2.C1"],
  "edges": [
    {"faces": ["F2.C1", "F2.S.e1~1"], "at": [20, 0, 10]},
    {"faces": ["F2.C1", "F2.S.e2~2"], "at": [40, 10, 10]},
    {"faces": ["F2.C1", "F2.S.e3~2"], "at": [20, 20, 10]},
    {"faces": ["F2.C1", "F2.S.e4~1"], "at": [0, 10, 10]}
  ],
  "width": 1, "height": 1.5
}

Run result: no errors; 16 faces, volume 3218 mm³. Volume 3218. Faces F4.C0, F4.S.F2.S.e4l, F4.S.F2.S.e3l, F4.S.F2.S.e2l, F4.S.F2.S.e1l.

Errors: nothingToCut (no body), lipFace (no rim face), invalidValue (width, height, inset or clearance), missingReference (an edge pick), booleanFailed. A rim that is not planar, or several rim faces in different planes, is not built: the code is TODO(rebuild): lip on a curved / several rim faces needs ck-ops; so is an inset along edges that do not close into a loop.

A tongue 0.5 mm in from the outer wall of the 2 mm wall, with "inset": 0.5 on the lip above (1 mm wide, 1.5 mm high), adds 168 mm³ (1.5 times the area between the outlines offset by 0.5 and by 1.5). The matching groove, "kind": "groove" with the same width, height and inset and "clearance": 0.2, removes 266.56 mm³ (a band 0.2 mm wider on each side and 0.2 mm deeper: 1.7 times the area between the outlines offset by 0.3 and by 1.7). For both halves of a case in one step see lipJoint.

split

Cuts a body by a plane into two bodies. It is a combine of op split with a half-space tool the kernel builds for you.

FieldTypeDefaultMeaning
planeplane referencerequired{"kind":"std","id":"front"}, a reference plane {"kind":"feature","id":..} or a planar face {"kind":"face","id":..}.
offsetnumber or expression0Moves the plane along its normal.
flipbooleanfalseReverses the normal (the offset then also runs the other way).
target{"body": name} or namethe only bodyThe body to cut. Needed when the part has several bodies (invalidValue {field: "target"}).
names[below, above]noneNames of the two halves: “below” is the half the plane normal points away from. Without names the part keeps the target’s name (if it has one) on the lower half and the upper half gets <name> 2. Equal or blank names are invalidValue; a name another body already has is bodyNameConflict.
keepstringbothbelow or above drops the other half.

The cut face of each half is a planar face of the split feature; every other face keeps its name (a face the plane crosses gets ~k on both halves). Errors: nothingToCut, invalidValue {field, detail}, missingReference (the plane), cutNoEffect (the plane misses the body or lies on a face of it), bodyNameConflict, booleanFailed.

On the plate shelled open at the top with 2 mm walls (the document of lip, without the lip):

{"type": "split", "id": "F4", "plane": {"kind": "std", "id": "front"}, "offset": 5, "names": ["Base", "Lid"]}

Two bodies: Lid, the 5 mm high ring of the walls (1120 mm³), and Base, the floor and lower walls (2272 mm³); together 3392 mm³, the volume of the shelled plate.

lipJoint

A split that also gives the two halves a tongue and a groove along the walls: one half carries a centred tongue, the other a groove wider and deeper by a clearance, so the halves fit with that gap all round.

FieldTypeDefaultMeaning
plane, offset, flip, target, namesAs for split.
heightnumber or expressionrequiredHow far the tongue stands out of its half, mm. The groove is height + clearance deep.
widthnumber or expressionnoneTongue width, mm.
widthRationumber or expression0.5Tongue width as a fraction of the wall thickness, used when width is absent (0 to 1, exclusive).
insetnumber or expressioncentredDistance from the outer wall to the tongue, mm. By default the tongue is centred in the wall: (wall - width) / 2.
clearancenumber or expression0.2The groove is wider by clearance on each side and deeper by clearance.
tonguestringbelowbelow or above: the half that carries the tongue.

The wall thickness is measured on the cut face as the narrowest distance from its outer boundary to its inner boundary. A cut face with no inner boundary (a solid body) has no wall: give width and inset in mm. The tongue and the groove follow the outer boundary of the cut face and are made with lip (inset and clearance), so a curved or several-plane rim is refused in the same way. Errors: those of split, invalidValue {field, detail} when height, width, widthRatio, inset, clearance or tongue is wrong or inset + width + clearance is more than the wall, and a lip error with step: "tongue" or "groove".

On the same plate:

{"type": "lipJoint", "id": "F4", "plane": {"kind": "std", "id": "front"}, "offset": 5,
 "height": 1.5, "width": 1, "clearance": 0.2, "names": ["Base", "Lid"]}

Two bodies, both valid. The tongue (inset 0.5 mm, 1 mm wide, 1.5 mm high) adds 168 mm³ to Base (2440 mm³); the groove (0.3 to 1.7 mm from the outer wall, 1.7 mm deep) removes 266.56 mm³ from Lid (853.44 mm³). The total is 3392 + 168 - 266.56 = 3293.44 mm³, and the two bodies do not overlap: the void left around the tongue, 98.56 mm³, is the clearance.

moveFace

Pushes or pulls faces; their neighbours follow.

FieldTypeDefaultMeaning
faceslist of face namesrequiredFaces of the solid. A name without ~k selects every piece. An empty list is noFaces.
modestring"offset"offset: each face moves along its outward normal by distance (positive adds material: a pushed plane grows the part, a cylinder gets a larger radius, a hole wall shrinks the hole). translate: each planar face moves by the component of translate along its outward normal.
distancenumber or expression0Offset distance. 0 is a no-op.
translate[x, y, z]noneTranslation for translate mode.
flipbooleanfalseNegates distance.

Planes, cylinders, cones, spheres, tori and extruded walls are supported in offset mode; translate is for planar faces. The unselected neighbours keep their surfaces and are extended or trimmed to meet the moved faces. Faces keep their names, so later references still resolve. Fillets that are tangent to a pushed plane travel with it.

{"type": "moveFace", "id": "F3", "faces": ["F2.C1"], "mode": "offset", "distance": 2.5}

Run result: no errors; 6 faces, volume 10000 mm³. The plate is now 12.5 mm high; the face names are unchanged: F2.C0, F2.C1, F2.S.e1, F2.S.e2, F2.S.e3, F2.S.e4.

{"type": "moveFace", "id": "F3", "faces": ["F2.S.e2"], "mode": "translate", "translate": [3, 0, 0]}

Run result: no errors; 6 faces, volume 8600 mm³. The right side moves out by 3: box [0,0,0] to [43,20,10].

Errors: nothingToCut, noFaces, missingReference {ref}, invalidValue {detail} (bad mode, translate missing, non-finite), moveFaceUnsupported {detail} (a free-form face, a curved face in translate mode, a face of a surface body) and moveFaceFailed {detail} (an edge collapses or reverses, the result is not valid, the volume goes the wrong way). Not supported: translating a cylinder sideways (moving a hole), and moving a face past other geometry is not checked against unrelated parts of the body.

{"type": "moveFace", "id": "F3", "faces": ["F2.C1"], "distance": -12}

Run result: errors F3: moveFaceFailed {"detail":"an edge reverses"}; 6 faces, volume 8000 mm³.

pressPull

Continues a flat face straight out of the solid (joined) or into it (cut), as if the face were extruded, with the new walls optionally leaning (a draft) or the whole outline growing or shrinking (a scale). Where moveFace slides the face and lets its neighbours follow, pressPull adds or removes a piece of its own.

FieldTypeDefaultMeaning
faceslist of face namesrequiredFlat faces of the solid. A name without ~k selects every piece. Each face continues on its own, in the order given. An empty list is noFaces.
continuestring"straight"straight: the face is carried along its outward normal, unturned. along (the end follows a bend in the walls) is not built yet and is refused.
distancenumber or expressionrequiredRun length in mm, not 0. Positive runs out of the material and the piece is joined; negative runs into it and the piece is cut.
taperobject{"type":"none"}none; draft with angle in degrees (-85 to 85); scale with endScale above 0.

draft: each new wall leans from its edge on the face by t * tan(angle) at run length t, positive outward, so the outline grows and holes shrink (the reverse sign of extrude draft, which tapers inward). It is built as extrude builds a draft and has the same limits and corner behaviour. scale: the outline, holes included, scales about the area centre of the face, linearly with the run length, to endScale at the end (1.1 is 110 %); walls on lines are planes, walls on circles about the centre are cones.

Names: the moved end keeps the persistent name of the face, so sketches and features that referred to the face find it at its new place. The cap on the old face is consumed. New walls are named as the extrusion of the face names them, <id>.S.<tag>, with the tag made from the name of the face across each edge (F2.S.e1 gives F2_S_e1). A straight run on walls it continues merges into them (no new faces); a taper gives new walls.

{"type": "pressPull", "id": "F3", "faces": ["F2.C1"], "continue": "straight", "distance": 10, "taper": {"type": "scale", "endScale": 1.1}}

Run result on a 5 mm radius, 30 mm long rod: no errors; faces F2.C0, F2.C1, F2.S.c1, F3.S.F2_S_c1; volume 2356.19 + 10 * pi / 3 * (25 + 27.5 + 30.25) = 3222.74 mm³ (a frustum from radius 5 to 5.5 on the end).

Errors (the model is unchanged on any): nothingToCut, noFaces, missingReference {ref}, invalidValue {field, detail, hint} (distance 0 or not finite, endScale not above 0 or below 1e-6, angle outside -85..85 or missing, unknown taper.type, continue other than straight), pressPullUnsupported {detail} (a face that is not flat, a face of a surface body), draftTooLarge (a draft that closes the face before the end of the run: maxHeight for a round face, else maxSize in degrees), and moveFaceFailed {detail} with maxSize (distance, the sign kept) where a shorter run builds: a cut through the body, a join into other material, a result that is not valid or splits the body.

faceRun

{"type": "faceRun", "tag": "t", "faces": ["F2.C1"]} answers, per face, what the Press Pull panel needs: found, flat, centre (the area centre), normal (outward), reach (mm, how far the outline reaches from the centre at its farthest point), area, and endOf: {feature, kind, input} when the face is the moving end of an extrude (depth), revolve (angle) or sweep (path), else null, so the panel can open that feature instead of adding a press pull. The readout for a scale is atan(reach * (endScale - 1) / distance). A face that is not flat answers flat: false and its surface. No body: null.

deleteBody

Removes whole bodies.

FieldTypeDefaultMeaning
bodieslist of selectorsrequired{"body": "Block"} (every body with that name), {"face": "F4.C1"} (the body that holds the face) or {"surface": "F7"} (a surface body made by feature F7). An empty list is noBodies.
modestring"delete"delete removes the selected bodies; keep removes all the others.

Errors: noBodies, missingReference (a selector matches nothing; a {body} selector adds params.name and params.nearest, up to three existing names).

The plate with a second body Block made with newBody; the two examples below are appended to this document:

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 40, "y": 0},
        {"id": "c", "x": 40, "y": 20},
        {"id": "d", "x": 0, "y": 20}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 10},
    {
      "type": "sketch", "id": "F3", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 60, "y": 0},
        {"id": "b", "x": 80, "y": 0},
        {"id": "c", "x": 80, "y": 20},
        {"id": "d", "x": 60, "y": 20}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {
      "type": "extrude", "id": "F4", "op": "newBody", "body": "Block", "sketch": "F3", "end": "blind",
      "depth": 5
    }
  ]
}
{"type": "deleteBody", "id": "F5", "mode": "delete", "bodies": [{"body": "Block"}]}

Run result: no errors; 6 faces, volume 8000 mm³. Only the plate is left.

{"type": "deleteBody", "id": "F5", "mode": "keep", "bodies": [{"face": "F4.C1"}]}

Run result: no errors; 6 faces, volume 2000 mm³. Only the block is left: box [60,0,0] to [80,20,5].

See also

Patterns and transforms

These features copy, reflect, move and scale what earlier features made: lpattern, cpattern, curvepattern, mirror, moveBody, scale, and combine, which applies a boolean between whole bodies. The examples use a 60 x 20 x 10 mm bar with a pocket of radius 3 at x = 10 (feature F4) or the plate of the overview.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 60, "y": 0},
        {"id": "c", "x": 60, "y": 20},
        {"id": "d", "x": 0, "y": 20}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 10},
    {
      "type": "sketch", "id": "F3", "plane": {"kind": "face", "id": "F2.C1"},
      "points": [{"id": "c", "x": 10, "y": 10}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 3}], "constraints": []
    },
    {"type": "extrude", "id": "F4", "op": "cut", "sketch": "F3", "end": "blind", "depth": 4}
  ]
}

Seeds and copies

lpattern, cpattern and mirror copy features, not faces. A seed is the id of an earlier feature that made a tool solid: an extrude, revolve, sphere, sweep, loft or hole, or an earlier pattern. The copies of the tool are combined with the body in the same way as the seed was: copies of a cut are cut, copies of a boss are added. A copy that falls outside the body does nothing and is not an error, but the pattern says so with a warning (see Pattern warnings). A seed that is not a tool-making feature, or does not exist, is missingReference; an empty seeds list is noSeeds.

The faces of a copy carry the id of the pattern and the number of the copy: F4.C0@F5.1, F4.S.e1@F5.2. The copies are numbered from 1; the seed itself keeps its name. A pattern of a pattern chains the suffixes. A pattern’s tool is its seeds together with all of their copies, so a pattern whose seeds is another pattern copies the whole result of the first one, the first seed included: a row of 5 holes (F4, then F5 with count 5) used as the seed of a second pattern along the other axis gives 5 x 5 = 25 holes, with "seeds": ["F5"] alone. (Builds before this change dropped the first seed from the copy rows and gave 21; listing both ids, ["F4", "F5"], was the way round it, and still gives the same result.)

Threads on the seed’s faces are copied to the copies too: see edge and face edits. All three pattern features take carryThreads (default true) to switch this off; a thread feature id can also be listed in seeds to copy that thread alone.

lpattern

Copies the seeds along a direction.

FieldTypeDefaultMeaning
seedslist of feature idsrequiredSee above.
dir{"kind": "axis", "axis": "x"}requiredThe direction the copies run along. A world axis (x, y or z); {"kind": "vector", "dir": [x, y, z]} (any direction, oblique too; the length does not matter); {"kind": "axis", "point": [x, y, z], "dir": [x, y, z]} (only the direction is read); a straight edge {"kind": "edge", "faces": [f1, f2], "at": [x, y, z]} (it runs from the edge’s start to its end); the axis of a cylindrical face {"kind": "face", "id": ...}; an axis feature {"kind": "feature", "id": ...} or a sketch line {"kind": "sketchLine", "sketch": ..., "entity": ...}. A direction that does not resolve (a zero vector, a flat face, a curved edge) is missingReference. The same forms work for dir2 and dir3; reverse flips the way.
spacingnumber or expression0Distance between copies, mm.
countnumber or expression0Number of instances, including the seed. A value of 1 or less makes no copies and is not an error; a fractional count is rounded; more than 10000 is invalidValue.
reversebooleanfalseCopy towards the negative direction. Not read with distanceType: "toObject".
distanceType"spacing", "extent" or "toObject""spacing"How the copies are spread, see below. Any other word is invalidValue with field: "distanceType".
extentnumber or expressionnoneWith "extent": distance from the seed to the last copy, mm. It must be above 0 (invalidValue with field: "extent").
toreference or pointnoneWith "toObject": what the last copy reaches. See below. Missing or not found: missingReference with field: "to".
toOffsetnumber or expression0With "toObject": moves the end the way the copies go, mm; negative stops short.
dir2, count2, spacing2, reverse2, distanceType2, extent2, to2, toOffset2as abovenoneA second direction: the same fields for it. Without dir2 there is no second direction; count2 defaults to 1. A dir2 along dir is invalidValue with field: "dir2".

Copy k (from 1) is the seed moved by k * spacing along dir. With a second direction, the grid cell (i, j) (i along dir, j along dir2) is copy j * count + i, the seed being (0, 0), so the copies along the first direction keep their numbers from a one-direction pattern. More than 10000 instances in all is invalidValue.

Distance types, per direction:

  • "spacing": spacing is the distance between neighbours, as above.
  • "extent": extent is the distance from the seed to the last copy, and the spacing is extent / (count - 1). A new count keeps the extent.
  • "toObject": the copy furthest along the direction reaches to, measured from the middle of what is patterned (the centre of the box of the seeds’ tool solids). to is a plane ({"kind": "std", "id": "right"}, a plane feature {"kind": "feature", "id": "F9"}) or a flat face ({"kind": "face", "id": "F2.S.e2"}, with an optional at point that finds the face again if its name changed): the end is where the line from the middle along the direction meets it. Or a point: [x, y, z], {"kind": "point", "at": [x, y, z]} or a body vertex {"kind": "vertex", "faces": [..], "at": [..]}: the end is its distance along the direction. The object gives the side, so the copies go the other way when it lies behind the middle, and reverse is not read. The pattern follows the object when it moves. Refusals: a plane or face that runs along the direction is patternToObjectParallel; an object at the middle, or an offset that brings the end back to or behind it, is patternToObjectAtSeed (with distance); a curved face is patternToObjectUnsupported.
{
  "type": "lpattern", "id": "F5", "seeds": ["F4"], "dir": {"kind": "axis", "axis": "x"}, "count": 3,
  "distanceType": "toObject", "to": {"kind": "face", "id": "F2.S.e2"}, "toOffset": -10
}

The pocket at x = 10 is copied towards the bar’s end face at x = 60, ending 10 short of it: pockets at 10, 30 and 50.

{
  "type": "lpattern", "id": "F5", "seeds": ["F4"], "dir": {"kind": "axis", "axis": "x"}, "spacing": 15,
  "count": 3
}

Run result: no errors; 12 faces, volume 11660.708 mm³. Three pockets in a row: 10, 25 and 40 mm from the left edge. The pocket faces are F4.C0, F4.S.e1, F4.C0@F5.1, F4.S.e1@F5.1, F4.C0@F5.2, F4.S.e1@F5.2.

{
  "type": "lpattern", "id": "F5", "seeds": ["F4"], "dir": {"kind": "axis", "axis": "x"}, "spacing": 15,
  "count": 3, "reverse": true
}

Run result: no errors; 8 faces, volume 11886.9027 mm³. The copies go to negative x, outside the bar: no copy touches the body. This is not an error; the warning patternCopiesNoEffect with copies: [1, 2] says so.

{
  "type": "lpattern", "id": "F5", "seeds": ["F9"], "dir": {"kind": "axis", "axis": "x"}, "spacing": 15,
  "count": 3
}

Run result: errors F5: missingReference; 8 faces, volume 11886.9027 mm³.

Large patterns

The only fixed limit is count: more than 10000 instances in one pattern is invalidValue. Time is the limit that matters, and it depends on how the grid is made. Measured on a 3 mm pitch grid of through holes (radius 1) in a 2 mm plate, one regen on a built wasm in Node on a laptop; the times include building the mesh for the reply, and the volume of every run matches the analytic value to 1e-9. No clock was installed, so no budget could trigger; with a clock the default featureTimeMs of 120 s applies (see robustness).

GridHoleslpattern of lpatternOne sketch of circles, one extrude cutOne sketch of points, one hole
10 x 101000.5 s0.3 sunder 0.1 s
20 x 204001.0 snot measured1.2 s
30 x 309002.1 s2.4 s3.3 s
50 x 5025009.5 s14.5 sabout 18 s

The cost of a hole feature with many points grows about in step with the number of points: only the holes whose boxes meet are united, and all the tools are cut from the body in one step (earlier builds folded every hole into one growing union, which grew with the square of the count: 7.6 s for 10 x 10, 131 s for 20 x 20 and 748 s for 30 x 30). The hole column is a native build run beside other tests (the 10 x 10, 20 x 20 and 30 x 30 values from the fix that removed the quadratic growth, the 50 x 50 value from tests/hole_many_points.rs, which also checks 2506 faces and the analytic volume); a 50 x 50 grid of lpattern of lpattern takes about 20 s in the same native run. The numbers depend on the machine; the tests bound them loosely (180 s). With a clock installed the default featureTimeMs of 120 s applies, so a slow machine can still trip it on the largest grids: split the points over several features or raise the limit.

A two-dimensional grid is one pattern with dir2, or two patterns, the second seeded with the first ("seeds": ["F5"]: a pattern’s tool holds its seeds and all their copies, see above).

cpattern

Copies the seeds around an axis.

FieldTypeDefaultMeaning
seedslist of feature idsrequiredSee above. For assemblies the list may be empty and bodies used, see parts and assemblies.
axis{"kind": "axis", "axis": "z"}requiredThe axis the copies turn about. A world axis through the origin (x, y or z); {"kind": "axis", "point": [x, y, z], "dir": [x, y, z]} for any line (a point on it, defaulting to the origin, and its direction, oblique too; the length of dir does not matter, and its sign sets the sense of the turn); a straight edge {"kind": "edge", "faces": [f1, f2], "at": [x, y, z]}; the axis of a cylindrical face {"kind": "face", "id": ...}; an axis feature {"kind": "feature", "id": ...} or a sketch line. A bolt circle round (40, 50) is {"kind": "axis", "point": [40, 50, 0], "dir": [0, 0, 1]}. A reference that does not resolve (a zero dir, a flat face, a curved edge) is missingReference.
countnumber or expression0Number of instances including the seed.
anglenumber or expression360Degrees. With equal it is the total angle; otherwise the step.
equalbooleantruetrue: copies are spread evenly: the step is angle / count for a full turn (360) and angle / (count - 1) otherwise, so the last copy lies at angle. false: angle is the step between neighbours.
reversebooleanfalseTurn the other way.

The base is a disc of radius 30 and depth 10 with one through hole of radius 3 at x = 20 (F4):

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [{"id": "c", "x": 0, "y": 0}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 30}], "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 10},
    {
      "type": "sketch", "id": "F3", "plane": {"kind": "face", "id": "F2.C1"},
      "points": [{"id": "c", "x": 20, "y": 0}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 3}], "constraints": []
    },
    {"type": "extrude", "id": "F4", "op": "cut", "sketch": "F3", "end": "blind", "depth": 10}
  ]
}

Appended to it:

{
  "type": "cpattern", "id": "F5", "seeds": ["F4"], "axis": {"kind": "axis", "axis": "z"}, "count": 4,
  "angle": 360
}

Run result: no errors; 7 faces, volume 27143.3605 mm³. Four holes 90 degrees apart (the seed and three copies): volume pi 30² 10 - 4 pi 3² 10 = 27143.3605.

Appended to the same disc document:

{
  "type": "cpattern", "id": "F5", "seeds": ["F4"], "axis": {"kind": "axis", "axis": "z"}, "count": 3,
  "angle": 30, "equal": false
}

Run result: no errors; 6 faces, volume 27426.1039 mm³. With equal: false the angle is the step: copies at 30 and 60 degrees.

mirror

Reflects seeds, or the whole body, about a plane.

FieldTypeDefaultMeaning
seedslist of feature idsrequired unless bodyThe features to reflect. Each copy is instance 1 of the mirror (F4.C0@F5.1); a mirrored cap keeps its cap number.
planeplane referencerequiredA standard plane, a plane feature or a planar face. A missing plane is missingReference.
bodybooleanfalseReflect the whole body made so far and unite it with the body (seeds are then ignored). The copy’s faces get @<mirror id>.1. A copy clear of the body is added as a separate body without a boolean.
replacebooleanfalseWith body: the image takes the place of the body instead of being united with it. On a sheet metal part (the last feature was a sheet feature) the part stays a sheet: the reflected panel tree, with the same flat pattern and bend table, for any plane including a flat face of the sheet. Without replace, a sheet is joined to its image only when the plane runs along a bend-free straight edge of the base plate, square to it (one sheet that unfolds as a whole); any other plane is refused with sheetMetalUnsupported {detail, hint} and the part is unchanged.
[
  {"type": "plane", "id": "P1", "mode": "offset", "base": {"kind": "std", "id": "right"}, "offset": 30},
  {"type": "mirror", "id": "F5", "seeds": ["F4"], "plane": {"kind": "feature", "id": "P1"}}
]

Run result: no errors; 10 faces, volume 11773.8053 mm³. The pocket at x = 10 is mirrored about the plane x = 30 to x = 50: volume 11773.8053. The copy’s faces are F4.C0@F5.1, F4.S.e1@F5.1.

{"type": "mirror", "id": "F5", "body": true, "seeds": [], "plane": {"kind": "std", "id": "right"}}

Run result: no errors; 10 faces, volume 23773.8053 mm³. The whole body is reflected about x = 0 and united with itself: box [-60,0,0] to [60,20,10]; volume 23773.8053 = 2 x 11886.9027.

moveBody

Moves, rotates or copies whole bodies.

FieldTypeDefaultMeaning
bodieslist of selectorsall bodiesWhich bodies. target is accepted for bodies, and body when it is an object or array (or a string while copy is not true).
translate[x, y, z]noneTranslation; components may be expressions.
rotateobjectnone{"axis": [x, y, z], "origin": [x, y, z], "angle": degrees}. axis can also be "x", "y", "z" or {"kind": "axis", "axis": "x"}; origin defaults to the world origin.
copybooleanfalseKeep the source body and add a moved copy; its face names get @<id>.1.
bodystringnoneWith copy: true: the name of the copies (bodyNameConflict if taken).
mirrorplane referencenoneWith copy: true: the copy is the mirror image about this plane (solid bodies only).

Body selectors: {"body": "Block"} (every body with that name), {"face": "F2.C1"} or the bare face name (the body that holds the face), {"feature": "F4"} or a bare id without a dot (every body holding a face made by that feature, including copies), {"surface": "F7"} (a surface body), {"lump": 2} (by index). A selector that finds nothing is missingReference (with name and nearest for {body}).

The rotation is applied first, then the translation. Without copy the bodies move in place and all names stay; moved bodies are not united with what they touch, so the result may hold overlapping bodies (use combine afterwards). No motion at all is a no-op. The older keys dx, dy, dz with axis and angle still read.

Errors: nothingToCut (no body), missingReference, invalidValue {detail} (a vector without three components, a non-finite number, a zero rotation axis), bodyNameConflict.

{
  "type": "moveBody", "id": "F5", "translate": [100, 0, 0],
  "rotate": {"axis": [0, 0, 1], "origin": [0, 0, 0], "angle": 90}
}

Run result: no errors; 8 faces, volume 11886.9027 mm³. Rotated 90 degrees about z first, then moved 100 in x: box [80,0,0] to [100,60,10]. The names are unchanged.

{"type": "moveBody", "id": "F5", "copy": true, "body": "Copy", "translate": [0, 30, 0]}

Run result: no errors; 16 faces, volume 23773.8053 mm³. The copy sits 30 mm further in y and its faces carry @F5.1: F2.C0@F5.1, F2.S.e1@F5.1, F2.S.e2@F5.1, …

scale

Scales bodies about a point, uniformly or per axis.

FieldTypeDefaultMeaning
factornumber, expression or [sx, sy, sz]requiredThe factors along the world axes. factors is a synonym. Each must be finite and above 0.
at[x, y, z]noneThe fixed point (origin is a synonym).
aboutstring"centroid"Without at: "origin" or "centroid" (the centre of mass of the selection).
bodieslist of selectorsall bodiesAs for moveBody (body and target are read too).

The bodies change in place and every face keeps its name. The result is exact for planes, for cylinders and cones stretched along their axis, for B-spline faces and for spheres and tori under a uniform factor. What cannot be kept exact is refused with invalidValue {detail, hint} and the body is left as it was: round faces stretched across their axis, a sphere or torus under a non-uniform factor, and revolution, extrusion, screw and offset surfaces. A factor of 0 or less is refused with invalidValue {detail: "a scale factor must be above zero"}; for a negative factor the hint suggests mirror, but the same hint is also given for 0, where it does not apply.

On the plate of the overview:

{"type": "scale", "id": "F5", "factor": [1, 2, 0.5], "about": "origin"}

Run result: no errors; 6 faces, volume 8000 mm³. box [0,0,0] to [40,40,5]; volume 8000 = 8000 x 1 x 2 x 0.5.

A bar with a round pocket cannot be stretched across the pocket axis:

{"type": "scale", "id": "F5", "factor": [1, 2, 0.5], "about": "origin"}

Run result: errors F5: invalidValue {"detail":"a round face (cylinder or cone) would be stretched across its axis","hint":"scale it by one factor on all three axes, or only along the axis of the round faces (a cylinder stretched along its own axis stays exact)"}; 8 faces, volume 11886.9027 mm³.

{"type": "scale", "id": "F5", "factor": -1}

Run result: errors F5: invalidValue {"detail":"a scale factor must be above zero","hint":"a negative factor would mirror the body: use mirror"}; 6 faces, volume 8000 mm³.

combine

A boolean between whole bodies of one part. bodyBoolean is accepted as a second name for the feature type.

FieldTypeDefaultMeaning
opstringrequiredunion (add, join), cut (subtract), intersect (common) or split. Anything else is invalidValue.
targetselectorrequiredExactly one body (a is a synonym): {"face": ..}, {"lump": n} or {"body": name}. Several bodies with the name are ambiguousBody.
toolslist of selectorsrequiredOne or more bodies (tool or b). A tool may not be the target.
keepToolsbooleanfalseKeep the tool bodies; otherwise they are consumed.
bodystringthe target’s nameName of the result body.
tolerance, autoFuzzySee features.

union joins the target with each tool in turn, cut subtracts them, intersect keeps what lies inside all, split cuts the target into the part outside all tools and the part inside them (two bodies). Faces keep their names; a face divided by the operation gets ~k. The bodies that take no part come first, then the result.

Errors: nothingToCut (no body), missingReference, ambiguousBody, invalidValue {detail}, bodyNameConflict, booleanFailed, booleanVolumeMismatch, cutNoEffect (a cut or split changed nothing), combineEmpty (an intersect of bodies that do not overlap).

A disc and a second body Tool made with newBody, overlapping it:

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [{"id": "c", "x": 0, "y": 0}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 20}], "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 10},
    {
      "type": "sketch", "id": "F3", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 10, "y": 10},
        {"id": "b", "x": 30, "y": 10},
        {"id": "c", "x": 30, "y": 30},
        {"id": "d", "x": 10, "y": 30}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {
      "type": "extrude", "id": "F4", "op": "newBody", "body": "Tool", "sketch": "F3", "end": "blind",
      "depth": 10
    }
  ]
}
{"type": "combine", "id": "F5", "op": "cut", "target": {"face": "F2.C1"}, "tools": [{"body": "Tool"}]}

Run result: no errors; 5 faces, volume 12251.2239 mm³. The tool is subtracted from the disc and consumed; volume 12251.2239.

{
  "type": "combine", "id": "F5", "op": "intersect", "target": {"face": "F2.C1"},
  "tools": [{"body": "Tool"}]
}

Run result: no errors; 5 faces, volume 315.1467 mm³. Only the overlap of disc and tool is left.

curvepattern

Copies the seeds along a path.

FieldTypeDefaultMeaning
seedslist of feature idsrequiredAs for lpattern.
path{"kind": "sketch", "id": ..} or {"kind": "curve", "id": ..}requiredAs a sweep’s path: an open chain of lines and arcs of a sketch, a sketch3d spline, a helix or another curve feature. Missing or not found: missingPath (checked first). A closed chain is pathInvalid.
countnumber or expression0Instances including the seed, as for lpattern.
spacingnumber or expression0Distance along the path between copies, mm; must be above 0 (invalidValue with field: "spacing").
distanceType"spacing" or "extent""spacing""extent": extent is the distance along the path from the seed to the last copy.
extentnumber or expressionnoneSee distanceType.
startnumber or expression0Where the seed sits along the path, mm. Outside 0 to the path’s length: patternStartOutside.
startFractionnumber or expressionnoneThe same as a fraction of the path’s length, 0 to 1; it keeps its place when the path changes length. Read instead of start when given.
flipbooleanfalseRun the path from its other end.
orientation"fixed" or "tangent""fixed""fixed": the copies are moved, not turned. "tangent": they are carried with a rotation-minimising frame along the path: round an arc they turn about its axis, at a corner between two pieces by the least turn between their directions, and along a helix or spline by small turns between sampled directions.

The older format’s names are read too: reverse for flip, align: true for "orientation": "tangent", equal: true (with no distanceType) for copies spread over the rest of the path, and a bare string path for a sketch id.

The path runs from its end nearest the middle of the seeds (flip: from the other end). Copy k is the seed moved from the path point start to the path point start + k * spacing, turned with the path when orientation is "tangent". The seed need not sit on the path: a seed 10 mm inside an arc stays 10 mm inside it with "tangent". A last copy past the end of the path is patternBeyondPath, with lastAt, length and maxSpacing, the largest spacing that fits.

{
  "type": "curvepattern", "id": "C9", "seeds": ["H5"], "path": {"kind": "sketch", "id": "S8"}, "count": 3,
  "distanceType": "extent", "extent": 125.66370614359172, "orientation": "tangent"
}

With S8 an arc of radius 40 about (50, 50) from (50, 10) anticlockwise to (50, 90), and the hole H5 at (50, 20): copies at (80, 50) and (50, 80). With "orientation": "fixed" they are at (90, 60) and (50, 100).

Pattern warnings

After lpattern, cpattern and curvepattern have combined their copies, the result’s face names tell which copies left a mark (a copy’s faces carry @<pattern>.<k>, see above). Three warnings come from that, without any extra boolean in the common case:

WarningParamsWhen
patternCopiesNoEffectcopies (copy numbers), of (the number of copies), hintCopies that changed nothing: a cut that misses the body, a boss inside the material. A cut copy that left no face but whose box meets the body is checked with an exact intersection (it may have cut away a whole lump).
patternCopiesApartcopies, hintBoss copies that touch nothing: each stands as a body of its own.
patternCopiesOverlaphint, and minSpacing for a one-direction lpatternCopies that overlap each other or the seed: the union of seed and copies has less volume than one seed per instance. minSpacing is the width of what is patterned along the direction, the least spacing that keeps copies apart. Copies that only touch are not reported.

Not built

The feature types fillpattern and spattern are accepted as names (they are not unknownFeature) but are not implemented: they fail with the error code TODO(rebuild): <type> needs ck-ops, except that spattern without a sketch that names a regenerated sketch reports missingSketch first.

See also

Surfaces and curves

Besides solids, a part can hold sheets (surface bodies) and curves. This chapter covers the features that make sheets (surfacePlanar, surfaceExtrude, surfaceRevolve), combine and change them (knit, trimSurface, fill, thicken, extend, deleteFace, freeform, pipeCut), the features that make curves (projectCurve, editCurve; helix is in solids from sketches) and 3D sketches (sketch3d). A loft with "surface": true also makes a sheet.

Sheets in the reply

A sheet is a body whose faces are open. The regen reply keeps sheets apart from the solid: body holds the solid, and surfaces is a list of [feature id, body] pairs, one per sheet. A feature that consumes sheets removes them from the list. A sheet that turns out to be a closed shell becomes the solid body (knit with solid: true, fill with merge: true that closes a shell).

Face references work across the solid and all sheets: a name such as F2.S.e1 is looked up in whichever body holds it. A feature that takes a sheet accepts the id of the feature that made it, or the name of any of its faces.

surfacePlanar

A flat sheet bounded by a sketch profile.

FieldTypeDefaultMeaning
sketchfeature idrequiredThe sketch. missingSketch if it is not found.

The sheet has one face, P, with the normal of the sketch plane and the edges of the profile.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 20, "y": 0},
        {"id": "c", "x": 20, "y": 10},
        {"id": "d", "x": 0, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "surfacePlanar", "id": "F2", "sketch": "S1"}
  ]
}

Run result: no errors; no solid body. Surfaces: F2: F2.P.

surfaceExtrude

A sheet swept from a profile, without caps.

FieldTypeDefaultMeaning
sketchfeature idrequiredClosed regions or open chains. An open chain is closed by a chord for the sweep and the chord’s face is dropped. A missing sketch is noClosedProfile.
depthnumber or expression10Length in mm.
endstring"blind"mid centres the sheet on the sketch plane; any other value is blind.
flipbooleanfalseSweep against the sketch normal.

Faces: S.<entity>, one per profile entity. Errors: noClosedProfile, badExpression.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 20, "y": 0},
        {"id": "c", "x": 20, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"}
      ],
      "constraints": []
    },
    {"type": "surfaceExtrude", "id": "F2", "sketch": "S1", "end": "blind", "depth": 5}
  ]
}

Run result: no errors; no solid body. The reply has no body; surfaces holds F2: F2.S.e1, F2.S.e2. F2 spans [0,0,0] to [20,10,5].

surfaceRevolve

A sheet revolved about an axis.

FieldTypeDefaultMeaning
sketchfeature idrequiredThe profile (regions or open chains).
axisstring or objectrequiredA line entity of the sketch by id, or {"sketch", "id"} for a line of another sketch, as for revolve.
anglenumber or expression360Degrees.
end, flipAs for revolve.

Faces: S.<entity>. Errors: missingSketch, missingAxis, profileCrossesAxis, noClosedProfile, invalidValue.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "o", "x": 0, "y": 0},
        {"id": "p", "x": 0, "y": 20},
        {"id": "a", "x": 10, "y": 0},
        {"id": "b", "x": 10, "y": 20}
      ],
      "entities": [
        {"type": "line", "id": "ax", "p1": "o", "p2": "p", "construction": true},
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"}
      ],
      "constraints": []
    },
    {"type": "surfaceRevolve", "id": "F2", "sketch": "S1", "axis": "ax", "angle": 360}
  ]
}

Run result: no errors; no solid body. A cylindrical sheet: F2: F2.S.e1.

knit

Joins sheets along their shared edges.

FieldTypeDefaultMeaning
surfaceslist of idsrequiredSheets to join (feature ids or face names). Entries that do not resolve are skipped; if none does the feature is missingReference.
solidbooleanfalseRequire a closed shell and make a solid of it.

The inputs are consumed. Without solid the result is one sheet registered under the id of the knit; with solid it becomes the solid body (united with an existing body). The faces keep their names. Errors: missingReference, knitNotClosed {open, points} (with solid, the shell has open open edges; points lists their midpoints), knitNearMiss.

Three sheets that make a box:

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 20, "y": 0},
        {"id": "c", "x": 20, "y": 10},
        {"id": "d", "x": 0, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "surfaceExtrude", "id": "F2", "sketch": "S1", "end": "blind", "depth": 5},
    {"type": "surfacePlanar", "id": "F3", "sketch": "S1"},
    {"type": "plane", "id": "P1", "mode": "offset", "base": {"kind": "std", "id": "front"}, "offset": 5},
    {
      "type": "sketch", "id": "S2", "plane": {"kind": "feature", "id": "P1"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 20, "y": 0},
        {"id": "c", "x": 20, "y": 10},
        {"id": "d", "x": 0, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "surfacePlanar", "id": "F5", "sketch": "S2"}
  ]
}

Run result: no errors; no solid body. Surfaces: F2: F2.S.e1, F2.S.e2, F2.S.e3, F2.S.e4; F3: F3.P; F5: F5.P.

{"type": "knit", "id": "F6", "surfaces": ["F2", "F3", "F5"], "solid": true}

Run result: no errors; 6 faces, volume 1000 mm³. The three sheets are consumed and the closed shell becomes the solid body, keeping the face names: F2.S.e1, F2.S.e2, F2.S.e3, F2.S.e4, F3.P, F5.P.

Leaving out the top leaves four open edges:

{"type": "knit", "id": "F6", "surfaces": ["F2", "F3"], "solid": true}

Run result: errors F6: knitNotClosed {"open":4,"points":[[10,0,5],[20,5,5],[10,10,5],[0,5,5]]}; no solid body.

fill

Patches a hole bounded by a chain of edges.

FieldTypeDefaultMeaning
edgeslist of edge picksrequired{"faces": [face], "at": [x, y, z]}: with one face, the open boundary edge of that face nearest at; with two faces, the edge they share. All edges must be in one body and form a closed chain.
mergebooleanfalseAdd the patch to the body it borders. A result that closes a shell becomes the solid body. Without it the patch is a sheet of its own.
continuitystring"G0"G0, G1, G2 or G3. On a planar boundary the patch is a plane whatever the value.
fairingstring"meowNURBS"meowNURBS, plate, curvature or variation.
guideStrengthnumber0.5Strength of the fairing guide.

The patch is one face, F. Errors: missingReference, fillNotClosed {detail} (the chain is open), fillInvalid (the edges do not form one chain), fillFailed {detail}.

An open box (walls and floor knitted into a sheet F4), then the four rim edges filled:

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 20, "y": 0},
        {"id": "c", "x": 20, "y": 10},
        {"id": "d", "x": 0, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "surfaceExtrude", "id": "F2", "sketch": "S1", "end": "blind", "depth": 5},
    {"type": "surfacePlanar", "id": "F3", "sketch": "S1"},
    {"type": "knit", "id": "F4", "surfaces": ["F2", "F3"]}
  ]
}

Run result: no errors; no solid body. One open shell F4 (the walls and the floor). F4: F2.S.e1, F2.S.e2, F2.S.e3, F2.S.e4, F3.P.

{
  "type": "fill", "id": "F5",
  "edges": [
    {"faces": ["F2.S.e1"], "at": [10, 0, 5]},
    {"faces": ["F2.S.e2"], "at": [20, 5, 5]},
    {"faces": ["F2.S.e3"], "at": [10, 10, 5]},
    {"faces": ["F2.S.e4"], "at": [0, 5, 5]}
  ],
  "merge": true, "continuity": "G0"
}

Run result: no errors; 6 faces, volume 1000 mm³. The patch F5.F closes the shell, so the result is a solid of volume 1000: F2.S.e1, F2.S.e2, F2.S.e3, F2.S.e4, F3.P, F5.F.

{
  "type": "fill", "id": "F5",
  "edges": [
    {"faces": ["F2.S.e1"], "at": [10, 0, 5]},
    {"faces": ["F2.S.e2"], "at": [20, 5, 5]},
    {"faces": ["F2.S.e3"], "at": [10, 10, 5]},
    {"faces": ["F2.S.e4"], "at": [0, 5, 5]}
  ],
  "merge": false
}

Run result: no errors; no solid body. Without merge the patch is a sheet of its own: F4: F2.S.e1, F2.S.e2, F2.S.e3, F2.S.e4, F3.P; F5: F5.F.

trimSurface

Cuts sheets with another sheet or a plane, keeping one side.

FieldTypeDefaultMeaning
surfaceidThe sheet to trim (feature id or face name).
surfaceslist of idsSeveral sheets; used instead of surface when present.
toolSurfaceidA sheet that cuts.
planeplane referenceA plane that cuts, used when there is no toolSurface.
flipbooleanfalseKeep the other side. The kept side is the one the tool normal points to.
mutualbooleanfalseReturn the tool, uncut, in the same result.
deleteToolbooleanfalseRemove the tool sheet. An absent field keeps the tool; only an explicit true removes it.

The result is one sheet registered under the id of the trim; the kept piece keeps the face names. The trim is built for planar sheets cut by a plane or by another planar sheet. A target that is curved, or a tool that does not cross the target, is not trimmed. Errors: missingReference, trimNoIntersection {detail}, trimNothingLeft, trimPieceLoop.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "plane", "id": "P1", "mode": "offset", "base": {"kind": "std", "id": "right"},
      "offset": 10
    },
    {
      "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 20, "y": 0},
        {"id": "c", "x": 20, "y": 10},
        {"id": "d", "x": 0, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "surfacePlanar", "id": "F3", "sketch": "S1"},
    {"type": "trimSurface", "id": "F4", "surface": "F3", "plane": {"kind": "feature", "id": "P1"}}
  ]
}

Run result: no errors; no solid body. The tool plane is x = 10 and the sheet keeps the side its normal points to: F4 spans [10,0,0] to [20,10,0].

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "plane", "id": "P1", "mode": "offset", "base": {"kind": "std", "id": "right"},
      "offset": 10
    },
    {
      "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 20, "y": 0},
        {"id": "c", "x": 20, "y": 10},
        {"id": "d", "x": 0, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "surfacePlanar", "id": "F3", "sketch": "S1"},
    {
      "type": "trimSurface", "id": "F4", "surface": "F3", "plane": {"kind": "feature", "id": "P1"},
      "flip": true
    }
  ]
}

Run result: no errors; no solid body. F4 spans [0,0,0] to [10,10,0].

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "plane", "id": "P1", "mode": "offset", "base": {"kind": "std", "id": "right"},
      "offset": 30
    },
    {
      "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 20, "y": 0},
        {"id": "c", "x": 20, "y": 10},
        {"id": "d", "x": 0, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "surfacePlanar", "id": "F3", "sketch": "S1"},
    {"type": "trimSurface", "id": "F4", "surface": "F3", "plane": {"kind": "feature", "id": "P1"}}
  ]
}

Run result: errors F4: trimNoIntersection {"detail":"the tool does not cut the surface"}; no solid body.

thicken

Gives a sheet thickness, making a solid.

FieldTypeDefaultMeaning
surfaceidrequiredThe sheet. missingReference if it is not found.
thicknessnumber or expression2Thickness in mm.
sidestring"front"front (along the face normal), back or both (half each way).
thicknessAtobjectnoneA taper instead of thickness: {"along": [x, y, z], "stops": [[s, t], ...]} with two to six stops, s ascending and each t above 0. The thickness at a point is interpolated along the direction along.

The sheet is consumed and the solid is united with the body. Faces: W0, W1, … for the walls along the sheet’s boundary; the sheet’s own faces keep their name with ~1 (the side that was thickened) and ~2 (the offset side). Errors: missingReference, thickenFailed, thickenTooThick, thickenReach, offsetTooLarge {limit, ...}, invalidValue {detail, hint} (bad thicknessAt). Offsets of curved sheets that would pass a centre of curvature carry the minRadius and maxThickness fields of shellTooThick.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 20, "y": 0},
        {"id": "c", "x": 20, "y": 10},
        {"id": "d", "x": 0, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "surfacePlanar", "id": "F2", "sketch": "S1"},
    {"type": "thicken", "id": "F3", "surface": "F2", "thickness": 2, "side": "front"}
  ]
}

Run result: no errors; 6 faces, volume 400 mm³. The sheet is consumed; the slab has the faces F2.P~1, F2.P~2, F3.W0, F3.W1, F3.W2, F3.W3 and volume 400.

extend

Extends a sheet past one or more boundary edges.

FieldTypeDefaultMeaning
edgeslist of edge picksrequiredBoundary edges of a sheet ({"faces": [face], "at": [..]}). An edge of a solid is missingReference.
distancenumber or expression5How far to extend.
endstring"distance"distance, or surface with target: {"id": ...} to extend up to another sheet.
shapestring"same"Only same (continue the surface) is built; other values fail with TODO(rebuild): extend shape other than same needs ck-ops.

The faces keep their names. Errors: missingReference, extendNotBoundary, extendNoTarget, extendPointBehind, extendFolds, extendUnsupported.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 20, "y": 0},
        {"id": "c", "x": 20, "y": 10},
        {"id": "d", "x": 0, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "surfacePlanar", "id": "F2", "sketch": "S1"},
    {"type": "extend", "id": "F3", "edges": [{"faces": ["F2.P"], "at": [10, 0, 0]}], "distance": 3}
  ]
}

Run result: no errors; no solid body. The sheet grows 3 mm at its bottom edge: F3 spans [0,-3,0] to [20,10,0].

deleteFace

Removes faces from a solid or sheet. A solid that loses a face becomes a sheet.

FieldTypeDefaultMeaning
faceslist of face namesrequiredFaces to remove. An empty or unresolved list is missingReference.
modestring"delete"Any other value fails with TODO(rebuild): deleteFace fill/heal needs ck-ops.

The remaining faces keep their names.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
      "points": [
        {"id": "a", "x": 0, "y": 0},
        {"id": "b", "x": 20, "y": 0},
        {"id": "c", "x": 20, "y": 10},
        {"id": "d", "x": 0, "y": 10}
      ],
      "entities": [
        {"type": "line", "id": "e1", "p1": "a", "p2": "b"},
        {"type": "line", "id": "e2", "p1": "b", "p2": "c"},
        {"type": "line", "id": "e3", "p1": "c", "p2": "d"},
        {"type": "line", "id": "e4", "p1": "d", "p2": "a"}
      ],
      "constraints": []
    },
    {"type": "surfaceExtrude", "id": "F2", "sketch": "S1", "end": "blind", "depth": 5},
    {"type": "deleteFace", "id": "F3", "faces": ["F2.S.e1"]}
  ]
}

Run result: no errors; no solid body. F3: F2.S.e2, F2.S.e3, F2.S.e4.

freeform

Re-fits faces as B-spline surfaces and applies control-point edits.

FieldTypeDefaultMeaning
faceslist of face namesrequiredThe faces to rebuild.
degreeU, degreeVnumber3Degrees of the new surface.
spansU, spansVnumber2Spans in each direction (at most 50: rebuildTooFine).
editslist of objectsnoneControl-point edits; they work on exactly one face (freeformOneFace).

The faces keep their names. The reply gains a marker for the feature with the control net of each face. Closed (periodic) faces such as a full cylinder wall are refused with rebuildPeriodicFace. The edits are not described further here.

pipeCut

Rolls a ball along picked edges, or around the rim of picked faces, and cuts away everything it touches. The body becomes a sheet.

FieldTypeDefaultMeaning
radiusnumber or expression0Ball radius; must be above 0 (invalidValue).
edgeslist of edge picksnoneEdges to follow.
faceslist of face namesnoneFaces whose rim edges are followed.

The picks may sit in the solid or in a sheet; the result replaces that body and is registered under the feature id; the faces that remain keep their names. Errors: invalidValue, missingReference, alignPipeCutOneBody (picks in more than one body), pipeCutRadius {detail, max}, pipeCutNothingLeft, pipeCutFailed.

Appended to the plate of the overview:

{
  "type": "pipeCut", "id": "F3", "radius": 1,
  "edges": [{"faces": ["F2.C1", "F2.S.e1"], "at": [20, 0, 10]}]
}

Run result: no errors; no solid body. The solid is replaced by a surface body registered under F3 (6 faces).

projectCurve

Projects a sketch, or a planar curve, perpendicular to its plane onto faces and fits one B-spline through the result.

FieldTypeDefaultMeaning
sketchfeature idThe sketch to project (its non-construction curves).
curvefeature idA curve feature (editCurve, projectCurve) to project instead. It wins when both are given.
faceslist of face namesall facesFaces of the solid or of sheets that receive the curve. Empty or missing means every face.
degreenumber3B-spline degree, 2 to 9.
tolerancenumber0.001Largest distance of the fit from the projected data (mm), above 0. More control points (up to 400) are used until it is met.
directionstring"both"both, forward (along the sketch normal) or reverse.

Every sample of the curve is cast along the normal against the chosen faces and all crossings inside the trimmed faces are kept. The pieces must form one connected chain; several chains are projectCurveSeveral {count, points}. It makes a curve and no faces: the faces it is projected on are not split. The result appears in curves as [id, {pts, axis: false, t0: 0, t1: 1}] and in markers as {degree, count, deviation, length, pieces, corners, closed}.

Errors, in the order they are checked: projectCurveNoFaces (no solid and no sheet), projectCurveNoInput (neither sketch nor curve, or a sketch with nothing to project), missingReference (an unresolved curve or face), projectCurvePlane (a curve that is not planar), missingSketch, editCurveDegree {min, max}, invalidValue (tolerance or direction), badExpression, projectCurveMisses, projectCurveSeveral, projectCurveFailed.

A circle on a plane 20 mm above the plate (F3), projected onto the top face only. Appended to the plate of the overview:

[
  {"type": "plane", "id": "P1", "mode": "offset", "base": {"kind": "std", "id": "front"}, "offset": 20},
  {
    "type": "sketch", "id": "F3", "plane": {"kind": "feature", "id": "P1"},
    "points": [{"id": "c", "x": 20, "y": 10}],
    "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 6}], "constraints": []
  },
  {"type": "projectCurve", "id": "F4", "sketch": "F3", "faces": ["F2.C1"]}
]

Run result: no errors; 6 faces, volume 8000 mm³. curves holds F4 (121 points) and markers the fit: degree 3, 15 control points, deviation 0.000705, closed true.

Without faces the circle also hits the bottom face, which makes two separate chains (same document, faces left out):

[
  {"type": "plane", "id": "P1", "mode": "offset", "base": {"kind": "std", "id": "front"}, "offset": 20},
  {
    "type": "sketch", "id": "F3", "plane": {"kind": "feature", "id": "P1"},
    "points": [{"id": "c", "x": 20, "y": 10}],
    "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 6}], "constraints": []
  },
  {"type": "projectCurve", "id": "F4", "sketch": "F3"}
]

Run result: errors F4: projectCurveSeveral {"count":2,"points":[]}; 6 faces, volume 8000 mm³.

editCurve

Rebuilds picked curves as one B-spline and lets a client reshape it by its control points.

FieldTypeDefaultMeaning
curveslist of curve referencesrequired{"kind": "curve", "id": ...} (an earlier curve feature), {"kind": "sketchCurve", "sketch": ..., "entity": ...} or {"kind": "edge", "faces": [..], "at": [..]}.
methodstringcount (a fixed number of control points) or tolerance.
degreenumber5B-spline degree.
countnumberControl points, for method: "count".
tolerancenumber0.01For method: "tolerance".
keepEndsbooleantrueKeep the end points.
keepTangents, keepCornersbooleanfalseKeep end tangents / corners.
entries, planar, planeControl-point edits and planar constraint.

It makes a curve and no faces. The result is a curve in curves and a marker with the control net, weights, knots and the deviation. Errors: editCurveNoInput, editCurveInputMissing {curve}, editCurveDegree, editCurveNotChain, editCurveNotSmooth, editCurveTooFewPoints, editCurveTooManyPoints, editCurveWeight, editCurveNoPlane.

Appended to the document of the projection above:

{
  "type": "editCurve", "id": "F5", "curves": [{"kind": "curve", "id": "F4"}], "method": "count",
  "count": 8, "degree": 3
}

Run result: no errors; 6 faces, volume 8000 mm³. Marker of F5: degree 3, 8 control points, deviation 0.033297.

3D sketches

A sketch3d feature holds points with three coordinates, curves in space and constraints. It is not on a plane, so it has no plane field and no profiles; it serves as a path (sweep, normal planes) and as a place to draw curves.

FieldTypeMeaning
pointsarray{"id", "x", "y", "z", "fixed"}. Missing coordinates read as 0.
entitiesarrayline (p1, p2), arc (c, p1, p2), spline (pts, closed), cvspline (pts, degree, knots, closed), point (p) and ref (a curve of another sketch with its own B-spline definition). Circles and ellipses are not part of 3D sketches and are dropped.
constraintsarraySame shape as the 2D constraints, with fix taking [x, y, z].

3D constraint types: coincident, alongX, alongY, alongZ, parallel, perpendicular, equal, collinear, pointOnLine, midpoint, corner, fix, onPlane, tangent, g1, g2, g3, onCurve, tension, distance, radius and angle. alongX makes a line (or two points) parallel to the X axis, and likewise for Y and Z; the others follow the 2D constraints of the same name. As in 2D, a constraint with an expr is re-solved when its value changes and the solved sketch is returned; otherwise the points are used as written.

The reply lists each 3D sketch in sketches3 as [id, {sketch}], normalised like a 2D sketch (missing arrays added, coordinates converted).

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch3d", "id": "F1",
      "points": [
        {"id": "a", "x": 0, "y": 0, "z": 0, "fixed": true},
        {"id": "b", "x": 10, "y": 1, "z": 1}
      ],
      "entities": [{"type": "line", "id": "e1", "p1": "a", "p2": "b"}],
      "constraints": [
        {"id": "k1", "type": "distance", "refs": ["a", "b"], "value": 10, "expr": "=12"},
        {"id": "k2", "type": "alongX", "refs": ["e1"]}
      ]
    }
  ]
}

Run result: no errors; no solid body. sketches3 holds the solved sketch: b moved from (10, 1, 1) to (12, 0, 0).

As a sweep path, a sketch may hold exactly one open spline (plus points and lines that give its end tangents through tangent constraints). The profile is carried along by a rotation-minimising frame. The profile must be normal to the spline’s start direction, which a tangent line can fix:

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch3d", "id": "F1",
      "points": [
        {"id": "a", "x": 0, "y": 0, "z": 0},
        {"id": "b", "x": 0, "y": 10, "z": 3},
        {"id": "c", "x": 0, "y": 20, "z": 8},
        {"id": "d", "x": 0, "y": 30, "z": 20},
        {"id": "t", "x": 0, "y": -5, "z": 0}
      ],
      "entities": [
        {"type": "spline", "id": "e1", "pts": ["a", "b", "c", "d"]},
        {"type": "line", "id": "e2", "p1": "a", "p2": "t"}
      ],
      "constraints": [{"id": "k1", "type": "tangent", "refs": ["e1", "e2"]}]
    },
    {
      "type": "sketch", "id": "F2", "plane": {"kind": "std", "id": "top"},
      "points": [{"id": "c", "x": 0, "y": 0}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 2}], "constraints": []
    },
    {"type": "sweep", "id": "F3", "op": "add", "sketch": "F2", "path": {"kind": "sketch", "id": "F1"}}
  ]
}

Run result: no errors; 4 faces, volume 470.6909 mm³. The tangent line fixes the start direction of the spline (along -y from t to a), which is normal to the top plane where the profile lies. Faces F3.S.e1~2, F3.S.e1~1, F3.C0, F3.C1.

Not built

The feature types surfaceOffset, cutWithSurface, dome and splitLine are accepted as names (they are not unknownFeature) but are not implemented: they fail with the error code TODO(rebuild): <type> needs ck-ops.

See also

Parts and assemblies

An assembly is a part whose features insert other parts as components and constrain them with mates. This chapter covers insertPart, the placement of a component, the mate constraints and their kinds, the degrees-of-freedom report, and how a component pattern copies components.

An assembly document is an ordinary part; the top-level field "kind": "assembly" marks it for editors but the kernel does not need it.

insertPart

Puts a copy of another part in the assembly.

FieldTypeDefaultMeaning
partpart documentrequiredThe part, embedded in full: a document with format, features and the other top-level fields. If it is missing or cannot be read (it fails the format check) the feature is insertPartMissing.
place{o, x, y, z}noneThe placement frame: four vectors of three plain numbers. The component’s world origin maps to o and its axes to x, y, z.
dx, dy, dznumber0A translation, used when there is no place. Plain numbers; expressions are not evaluated here.
axis{"kind": "axis", "axis": "x"}noneRotation axis for the angle form: a world axis through the origin.
anglenumber or expression0Degrees about axis. The rotation is applied first, then the translation dx, dy, dz.
fixedbooleanfalseA fixed component never moves: its degrees of freedom are 0, and mates move the other component.
sourcestringnoneA label for where the part came from. Read and kept, not used by the kernel.

The embedded part is regenerated on its own, with its own rollback ignored, and its body becomes the component. Two inserts of the same part document regenerate it once. Components are appended to the body as separate bodies; they are never united, so components may overlap.

Every face of a component is renamed with the id of the insert feature: E1.C0 in the part becomes E1.C0@F1.1 for the insert F1. Names the part already had after @ stay in front (F8.S.h1@F9.1@F1.1). These are the names mates and later features use.

The regen reply lists the components in components, sorted by id: {id, dof, place}, where dof is 6 for a free component and 0 for a fixed one (mates lower it) and place is the frame the component now has.

{
  "format": "ck-part", "version": 1, "kind": "assembly",
  "features": [
    {
      "type": "insertPart", "id": "F1",
      "part": {
        "format": "ck-part", "version": 1,
        "features": [
          {
            "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
            "points": [{"id": "c", "x": 0, "y": 0}],
            "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 5}], "constraints": []
          },
          {"type": "extrude", "id": "E1", "op": "add", "sketch": "S1", "end": "blind", "depth": 20}
        ]
      },
      "fixed": true
    },
    {
      "type": "insertPart", "id": "F2",
      "part": {
        "format": "ck-part", "version": 1,
        "features": [
          {
            "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
            "points": [{"id": "c", "x": 0, "y": 0}],
            "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 5}], "constraints": []
          },
          {"type": "extrude", "id": "E1", "op": "add", "sketch": "S1", "end": "blind", "depth": 20}
        ]
      },
      "dx": 50, "dy": 0, "dz": 0, "axis": {"kind": "axis", "axis": "y"}, "angle": 90
    }
  ]
}

Run result: no errors; 6 faces, volume 3141.5927 mm³. Components in the reply: F1 dof 0, origin [0,0,0]; F2 dof 6, origin [50,0,0]. The faces of the body are E1.C0@F1.1, E1.C1@F1.1, E1.S.e1@F1.1, E1.C0@F2.1, E1.C1@F2.1, E1.S.e1@F2.1. The volume is the sum of the two pins (3141.5927); nothing is united.

A placement frame instead of dx, dy, dz:

{
  "format": "ck-part", "version": 1, "kind": "assembly",
  "features": [
    {
      "type": "insertPart", "id": "F1",
      "part": {
        "format": "ck-part", "version": 1,
        "features": [
          {
            "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
            "points": [{"id": "c", "x": 0, "y": 0}],
            "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 5}], "constraints": []
          },
          {"type": "extrude", "id": "E1", "op": "add", "sketch": "S1", "end": "blind", "depth": 20}
        ]
      },
      "place": {"o": [0, 0, 50], "x": [1, 0, 0], "y": [0, 1, 0], "z": [0, 0, 1]}
    }
  ]
}

Run result: no errors; 3 faces, volume 1570.7963 mm³. Component: F1 dof 6, origin [0,0,50].

Errors and edge cases:

SituationResult
No part, or an unreadable oneinsertPartMissing.
The part reports errors when regeneratedinsertPartErrors with params.detail set to "<feature id>: <code>" of the first error (by feature id). The part is not inserted.
The part has no features, or builds no solid bodyNo error and no component.
{"format": "ck-part", "version": 1, "features": [{"type": "insertPart", "id": "F1"}]}

Run result: errors F1: insertPartMissing; no solid body.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "insertPart", "id": "F1",
      "part": {
        "format": "ck-part", "version": 1,
        "features": [
          {"type": "extrude", "id": "E1", "op": "add", "sketch": "S9", "end": "blind", "depth": 5}
        ]
      }
    }
  ]
}

Run result: errors F1: insertPartErrors {"detail":"E1: missingSketch"}; no solid body.

mate

A mate constrains two components by one face on each. The mate moves the component of a onto the component of b; when that component is fixed, the other one moves instead. Mates are solved in order and each later mate keeps the earlier ones satisfied where it can. The solution is iterative (a damped Gauss-Newton on the placement of the moving component), so positions are accurate to about 1e-9 rather than exact.

FieldTypeDefaultMeaning
kindstring"coincident"See the table of kinds.
aface namerequiredA face of the moving component, in its component name (E1.C0@F2.1).
bface namerequiredA face of the other component.
distancenumber or expression0Offset for distance, the stop offset of hinge.
flipbooleanfalseReverses the contact side or the direction, depending on the kind.
a2, b2face namesnoneSecond faces (width, hinge stop, slot wall).
cface namenoneThe mirror face of symmetric.
anglenumber or expressionkind dependentDegrees: the angle of an angle mate, or the drive of gear, rackPinion and screw.
ratio, pitch, radiusnumber or expression1, 1, noneGear ratio, screw pitch (length per turn), pinion pitch radius.
min, max, oflimits: the range, and of: "distance" (default) or "angle".
dir[x, y, z]noneTravel direction of a planar rack.

Kinds. “Leaves” is the freedom a free component keeps when mated once to a fixed one (an observed value for the examples run; a second mate removes more):

kindFacesConstraintLeaves
coincidentplane, planeNormals opposed (or aligned with flip), the planes touch.3
distanceplane, planeAs coincident, at distance.3
parallelplane or axis pairsDirections parallel.4
concentriccylinder, cylinderAxes on one line.2
angleplane, cylinder or coneThe angle between the two directions equals angle.5
perpendicularplane or axis pairsDirections at 90 degrees.5
tangentcylinder or sphere against plane; cylinder or sphere pairsContact. flip takes the other side of a plane, or internal contact between round faces.4 for a cylinder on a plane
lockany face of eachThe relative pose at the time of the mate is kept.0
symmetricplane/plane, cylinder/cylinder, sphere/sphere, and ca is the mirror image of b about c (the component of c is treated as fixed).3 for a plane pair
widtha, a2 parallel planes of a tab; b, b2 of a slotThe tab centred in the slot.3
hingecylinders or cones; optional a2, b2 stop planesConcentric axes, and the stop faces in contact at distance.1 turn (2 without the stop)
slota a pin (cylinder); b (and b2) planar slot wallsPin parallel to the walls and centred between them.4
screwcylinders (screw, nut)Concentric, advance = pitch x turns; with angle the nut is placed that far along the thread.1; 0 with angle
gearcylindersThe follower turns by -angle / ratio about its axis for a drive angle of a, measured from the pose at the time of the mate.one coupling
rackPinionpinion cylinder, rack cylinder or plane with dirRack travel = radius x pinion angle.one coupling
limitstwo planes, or two directions with of: "angle"The measured value is clamped into [min, max]; inside the range the mate removes no freedom.6 inside the range

Couplings (gear, rackPinion, screw) are measured from the placements the components have when the mate is made (after earlier mates were solved), so a later mate that moves the driver drags the follower. The follower is the component of b; if that one is fixed, gear and screw swap the roles, and rackPinion is refused with mateFixed. Not supported (mateGeometry): symmetric with c on a moving component, tangent with a cylinder in a and a sphere in b, a rack that is neither a cylinder nor a plane with dir. An unknown kind is mateGeometry.

A cap against a cap. F2 slides on the cap of F1 (it keeps three freedoms: two translations along the plane and one rotation about the normal):

{
  "format": "ck-part", "version": 1, "kind": "assembly",
  "features": [
    {
      "type": "insertPart", "id": "F1",
      "part": {
        "format": "ck-part", "version": 1,
        "features": [
          {
            "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
            "points": [{"id": "c", "x": 0, "y": 0}],
            "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 5}], "constraints": []
          },
          {"type": "extrude", "id": "E1", "op": "add", "sketch": "S1", "end": "blind", "depth": 20}
        ]
      },
      "fixed": true
    },
    {
      "type": "insertPart", "id": "F2",
      "part": {
        "format": "ck-part", "version": 1,
        "features": [
          {
            "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
            "points": [{"id": "c", "x": 0, "y": 0}],
            "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 5}], "constraints": []
          },
          {"type": "extrude", "id": "E1", "op": "add", "sketch": "S1", "end": "blind", "depth": 20}
        ]
      },
      "dx": 100
    },
    {"type": "mate", "id": "F3", "kind": "coincident", "a": "E1.C0@F2.1", "b": "E1.C1@F1.1"}
  ]
}

Run result: no errors; 6 faces, volume 3141.5927 mm³. The cap of F2 lies on the cap of F1: F1 dof 0, origin [0,0,0]; F2 dof 3, origin [100,0,19.999999998] (z = 20). It can still slide in x and y and turn about z, so it keeps 3 of its 6 freedoms. The position is converged to about 1e-9, not exact.

Axis on axis, leaving a slide and a turn along the axis:

{
  "format": "ck-part", "version": 1, "kind": "assembly",
  "features": [
    {
      "type": "insertPart", "id": "F1",
      "part": {
        "format": "ck-part", "version": 1,
        "features": [
          {
            "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
            "points": [{"id": "c", "x": 0, "y": 0}],
            "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 5}], "constraints": []
          },
          {"type": "extrude", "id": "E1", "op": "add", "sketch": "S1", "end": "blind", "depth": 20}
        ]
      },
      "fixed": true
    },
    {
      "type": "insertPart", "id": "F2",
      "part": {
        "format": "ck-part", "version": 1,
        "features": [
          {
            "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
            "points": [{"id": "c", "x": 0, "y": 0}],
            "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 5}], "constraints": []
          },
          {"type": "extrude", "id": "E1", "op": "add", "sketch": "S1", "end": "blind", "depth": 20}
        ]
      },
      "dx": 100
    },
    {"type": "mate", "id": "F3", "kind": "concentric", "a": "E1.S.e1@F2.1", "b": "E1.S.e1@F1.1"}
  ]
}

Run result: no errors; 6 faces, volume 3141.5927 mm³. The axis of F2 is on the axis of F1: F1 dof 0, origin [0,0,0]; F2 dof 2, origin [0,0,0].

A hinge with a stop face leaves one turn:

{
  "format": "ck-part", "version": 1, "kind": "assembly",
  "features": [
    {
      "type": "insertPart", "id": "F1",
      "part": {
        "format": "ck-part", "version": 1,
        "features": [
          {
            "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
            "points": [{"id": "c", "x": 0, "y": 0}],
            "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 5}], "constraints": []
          },
          {"type": "extrude", "id": "E1", "op": "add", "sketch": "S1", "end": "blind", "depth": 20}
        ]
      },
      "fixed": true
    },
    {
      "type": "insertPart", "id": "F2",
      "part": {
        "format": "ck-part", "version": 1,
        "features": [
          {
            "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
            "points": [{"id": "c", "x": 0, "y": 0}],
            "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 5}], "constraints": []
          },
          {"type": "extrude", "id": "E1", "op": "add", "sketch": "S1", "end": "blind", "depth": 20}
        ]
      },
      "dx": 100
    },
    {
      "type": "mate", "id": "F3", "kind": "hinge", "a": "E1.S.e1@F2.1", "b": "E1.S.e1@F1.1",
      "a2": "E1.C0@F2.1", "b2": "E1.C1@F1.1"
    }
  ]
}

Run result: no errors; 6 faces, volume 3141.5927 mm³. F2 sits on top of F1 on the same axis and can only turn: the assembly object says {“total”:1,“translational”:0,“rotational”:1}.

Errors

CodeWhen
missingReferenceA face name does not exist (or b is empty).
mateSameBodyBoth faces belong to one component.
mateFixedBoth components are fixed (and for rackPinion a fixed rack).
mateGeometry {detail}The kind cannot use the geometry of these faces, or the kind is unknown.
mateConflictThe solver cannot satisfy this mate together with the earlier ones.
nothingToCutThe document has no body yet.

A rejected mate leaves every component where the earlier mates put it, and the other mates still run.

{
  "format": "ck-part", "version": 1, "kind": "assembly",
  "features": [
    {
      "type": "insertPart", "id": "F1",
      "part": {
        "format": "ck-part", "version": 1,
        "features": [
          {
            "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
            "points": [{"id": "c", "x": 0, "y": 0}],
            "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 5}], "constraints": []
          },
          {"type": "extrude", "id": "E1", "op": "add", "sketch": "S1", "end": "blind", "depth": 20}
        ]
      },
      "fixed": true
    },
    {
      "type": "insertPart", "id": "F2",
      "part": {
        "format": "ck-part", "version": 1,
        "features": [
          {
            "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
            "points": [{"id": "c", "x": 0, "y": 0}],
            "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 5}], "constraints": []
          },
          {"type": "extrude", "id": "E1", "op": "add", "sketch": "S1", "end": "blind", "depth": 20}
        ]
      },
      "fixed": true, "dx": 100
    },
    {"type": "mate", "id": "F3", "kind": "coincident", "a": "E1.C0@F2.1", "b": "E1.C1@F1.1"}
  ]
}

Run result: errors F3: mateFixed; 6 faces, volume 3141.5927 mm³.

{
  "format": "ck-part", "version": 1, "kind": "assembly",
  "features": [
    {
      "type": "insertPart", "id": "F1",
      "part": {
        "format": "ck-part", "version": 1,
        "features": [
          {
            "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
            "points": [{"id": "c", "x": 0, "y": 0}],
            "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 5}], "constraints": []
          },
          {"type": "extrude", "id": "E1", "op": "add", "sketch": "S1", "end": "blind", "depth": 20}
        ]
      },
      "fixed": true
    },
    {
      "type": "insertPart", "id": "F2",
      "part": {
        "format": "ck-part", "version": 1,
        "features": [
          {
            "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
            "points": [{"id": "c", "x": 0, "y": 0}],
            "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 5}], "constraints": []
          },
          {"type": "extrude", "id": "E1", "op": "add", "sketch": "S1", "end": "blind", "depth": 20}
        ]
      },
      "dx": 100
    },
    {
      "type": "mate", "id": "F3", "kind": "distance", "a": "E1.C0@F2.1", "b": "E1.C1@F1.1",
      "distance": 5
    },
    {
      "type": "mate", "id": "F4", "kind": "distance", "a": "E1.C0@F2.1", "b": "E1.C1@F1.1",
      "distance": 9
    }
  ]
}

Run result: errors F4: mateConflict; 6 faces, volume 3141.5927 mm³. The second mate is rejected and F2 stays where the first put it (z = 25): F1 dof 0, origin [0,0,0]; F2 dof 3, origin [100,0,24.999999998].

The degrees-of-freedom report

When the document uses a mate kind beyond coincident, concentric, distance and parallel, or the regen request has opts.dofReport: true, the reply carries an assembly object next to components. This is the report of the hinge example above:

{"assembly": {
  "dof": {"total": 1, "translational": 0, "rotational": 1},
  "components": [{"id": "F1", "fixed": true, "dof": 0, "translational": 0, "rotational": 0},
                 {"id": "F2", "fixed": false, "dof": 1, "translational": 0, "rotational": 1}],
  "overConstrained": false,
  "redundant": [],
  "conflicts": []
}}
  • dof.total is the dimension of the motion space of all floating components left by all mates together. rotational is the rank of the rotation part, translational the rest. Each component’s own numbers are the motions it can still make; fixed components report 0.
  • redundant lists mates that add no constraint (their rows depend on the earlier mates). They are harmless and make overConstrained true.
  • conflicts lists each rejected mate as {"mate": id, "with": [earlier mates on the same components]}, with the matching mateConflict error.
  • The rank comes from a numeric Jacobian of the mate residuals at the solved pose, so a nearly singular pose can be misreported. With more than 30 floating components the null-space part is skipped and the object carries "truncated": true.

The same number appears as components[].dof once an added kind is present.

Component patterns

A cpattern with an empty seeds list and bodies set copies whole components around an axis (see patterns and transforms). bodies is a list of {"face": "<component face>"}: every component that owns one of the faces is copied.

FieldMeaning
bodies[{"face": "E1.C0@F1.1"}]: a face of each component to copy.
axis, count, angle, equal, reverseAs for a circular pattern.

The copies are new bodies named with the pattern id after the component suffix (E1.C0@F1.1@F2.1); they are not listed in components.

{
  "format": "ck-part", "version": 1, "kind": "assembly",
  "features": [
    {
      "type": "insertPart", "id": "F1",
      "part": {
        "format": "ck-part", "version": 1,
        "features": [
          {
            "type": "sketch", "id": "S1", "plane": {"kind": "std", "id": "front"},
            "points": [{"id": "c", "x": 0, "y": 0}],
            "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 5}], "constraints": []
          },
          {"type": "extrude", "id": "E1", "op": "add", "sketch": "S1", "end": "blind", "depth": 20}
        ]
      },
      "dx": 30
    },
    {
      "type": "cpattern", "id": "F2", "seeds": [], "bodies": [{"face": "E1.C0@F1.1"}],
      "axis": {"kind": "axis", "axis": "z"}, "count": 3, "angle": 360
    }
  ]
}

Run result: no errors; 9 faces, volume 4712.389 mm³. Three pins around the z axis. The copies are named E1.C0@F1.1@F2.1, E1.C1@F1.1@F2.1, … and are not listed in components (1 component).

importStep

Holds a body that came from a STEP file, so that sketches, cuts and fillets later in the history can work on it. The STEP text is kept inside the part, so the part does not depend on a file next to it.

FieldTypeDefaultMeaning
blobstringnoneKey of an entry in the part’s top-level blobs table. The entry is the STEP text and the key is the SHA-256 of that text in lower-case hex (of its UTF-8 bytes).
stepstringnoneThe STEP text written in the feature itself. Meant for small files; use blob for anything large. blob wins when both are given.
bodystringnoneName for the body. When the file holds several solids they are named <body>, <body> 2, <body> 3, in file order.
{
  "format": "ck-part", "version": 1,
  "blobs": {"9f2c...e1": "ISO-10303-21;\nHEADER;\n..."},
  "features": [{"type": "importStep", "id": "F1", "blob": "9f2c...e1", "body": "Case"}]
}

How it behaves:

  • The kernel reads the file with its STEP reader. Lengths are converted to millimetres using the units the file declares (millimetre, centimetre, metre, inch and so on).
  • Every solid in the file becomes its own body. Following the rule for new bodies, the solids are added beside any bodies that already exist and are not joined to them.
  • Faces are named <feature id>.I<solid>F<n>, for example F1.I1F7. The solid number and the face number follow the order in the file, so the names are the same on every run and after the part is saved and opened again. Later features refer to these faces like any other face (see identifiers and references).
  • The key is checked against the text every time the feature runs. Because the regeneration cache only sees the key and not the text, a large file adds a few bytes to a cache key, and the same file used by two features is stored once.
  • Keep the blobs entry as long as a feature uses it. Editors should remove entries that no feature names.

Errors and edge cases:

SituationResult
No blob and no stepimportStepInvalid with params.detail.
The key is missing from blobs, or does not match the textimportStepInvalid with params.detail.
The text is not a STEP file, is cut short or uses something the reader cannot buildimportStepInvalid; params.detail is the reader’s message, params.reason its code and params.entity the STEP entity number when it names one.
The file holds no solidimportStepInvalid.
A body name already used by another bodybodyNameConflict.

See also

Sheet metal

A part can be built as a sheet metal part: a base plate of constant thickness with bent flanges, hems and folds, from which the kernel also derives the flat pattern and a bend table. These features are in the list of known type names (see Features). This chapter is a summary; docs/sheet-metal.md in the repository has every rule, the probes the numbers were checked against and the limits of each stage.

All lengths are in millimetres and angles in degrees. A number may be an expression string ("=Thickness*4"; inside sheetRules, Thickness is the rule’s thickness) or a string with a unit ("2 mm", "90 deg").

The features

TypeWhat it does
sheetRulesThe stock: name, thickness, kFactor, bendRadius, reliefWidth, reliefDepth, cornerRelief, cornerReliefShape (notch, round, rectangular or tear), hemGap, gap, active. Only name is required; the rest default from the thickness (2.5 when none is given). A rule with an existing name replaces it.
baseFlangeThe first plate: sketch (one closed region, holes allowed), rule (a name; default the active rule), flip. The region is extruded by the thickness. One per part, as the first body feature.
contourFlangeThe base from an open chain of sketch lines: sketch, curves (default every line), distance, rule, flip, reverse.
edgeFlangeA bent flange on edges of the plate: edges, height (required), angle (default 90), radius, heightFrom (outer, inner, tangent), position (inside, outside, middle), flip, then (chained bends, at most 16), and for a partial width start, length or from and to, relief, or a shaped leg with profile and holes.
hemA 180 degree bend that lays a leg back against the sheet: edges, length, gap, flip.
foldA bend across the sheet along a line: points or line ({sketch, curve}), angle, radius, position (centerline, start, end, mould), fixed, flip.
unfold, refoldMake the body the flat sheet, and fold it again from the same bend rows.
sheetConvertReads a bent plate of constant thickness as a sheet: thickness, rule. The result is refused if its volume differs from the body’s by more than 1 percent.
sheetCutCuts the closed regions of a sketch out of the sheet through the flat pattern: sketch, regions.
sheetCornerRounds or chamfers corners of free walls: corners, mode (round or chamfer), radius, distance.

An edge in edges is picked by a point on it ([x, y, z] or {"at": [x, y, z]}, the nearest outline edge wins), by {"edge": n} (index into the outline) or by role ("P0.side.e2"). A point on the face the base ended on bends the flange towards that side. The legs and setbacks follow the bend arithmetic: the bend allowance is BA = (r + k t) a, with a in radians.

{"type": "sheetRules", "id": "R1", "name": "Steel2", "thickness": 2, "kFactor": 0.44, "bendRadius": 2}
{"type": "baseFlange", "id": "B1", "sketch": "S1", "rule": "Steel2"}
{"type": "edgeFlange", "id": "E1", "edges": [[50, 0, 2], [50, 60, 2]], "height": 20, "angle": 90}

For a 100 x 60 plate of thickness 2 with k-factor 0.44 and bend radius 2, with two 20 mm flanges on the 100 mm edges, the flat size is 100 x 93.04778684 mm.

The result

The regen reply gains sheetMetal, one entry per sheet feature, sorted by id. Each has the rule, a flatPattern and roles (stable names for the panels, bends and walls, such as P0.front and B1.back, usable as references). The flat pattern holds flatSize (width, length, thickness), the outline loops (the outer loop, then the holes), bends (for each: bend, feature, direction up or down, angleDeg, includedAngleDeg, radius, allowance, length, start, end), bendZones and unfolded.

Two stateless requests turn a flat pattern into files: sheetDxf (the flat pattern as DXF, version R2000 or R12, with bend lines, optional notes and layer options) and sheetBendTable (the bend table as CSV or JSON). Both take the flatPattern object of a sheetMetal entry.

Errors and warnings

nothingToCut (no sheet yet), missingSketch, noClosedProfile, invalidValue (with field, detail and hint), flangeHeightTooLow (with minHeight) and sheetMetalUnsupported (with detail and hint: what the feature does not build, and what to reorder). A plain extrude cut of a folded sheet is tried as a sheetCut first; when that is refused it runs as an ordinary cut and the feature carries the warning sheetCutFallback, because the part is then no longer an unfoldable sheet.

Mirror

mirror with body: true of a part that is a live sheet keeps it a sheet: with "replace": true the image takes the place of the sheet, otherwise the image is joined to it, which gives one sheet only when the plane is square to the base plate and runs along one straight, bend-free edge. Any other plane is refused with sheetMetalUnsupported.

Not built

Flanges on a curved edge, louvres, forming tools, a jog and a mitre flange are not built. A sheetCut of a non-rectangular region across a bend is a staircase of wedges in the solid (the flat pattern is exact). sheetConvert takes bent plates with straight cylindrical bends only. Arcs in a contour chain and more than one chain are not built.

Versions and earlier files

A part records the version of the format it was written for. This chapter covers the format string and the version field, what the kernel does with a file that is newer or older than it expects, and how unknown fields, values and feature types are treated so that documents survive across versions.

The format string and the version

Every document the kernel writes or documents carries

{"format": "ck-part", "version": 1, "features": []}
  • format is the string ck-part. It is the only value of format that new documents use, and a document without a readable format is refused with invalid part: Format (see the overview).
  • version is a number. The version this kernel knows and writes is 1. It is not checked against anything when the document is read.

The TypeScript package part-model declares the same two constants (format: 'ck-part', version: 1) and emptyPart() builds a document with them.

Files saved by earlier versions

Files saved by earlier versions are still read: the older spellings of the format name are accepted and the document is read as ck-part. Writers should write ck-part; the kernel never writes an older name. The rest of the document is read by the same rules whatever the format name was, so an older file needs no conversion step.

A file newer than the kernel

A document whose version is higher than the kernel’s is still read and regenerated. The reply then says so, in one additive field of result next to errors and body:

{"result": {"errors": [], "partVersionNewer": {"file": 2, "kernel": 1}}}

file is the document’s version, kernel the one this build knows. The field is absent for every document the kernel knows (version 1, 0, or no version), so replies for those documents are unchanged.

The kernel does not refuse a newer file, because most newer files only add things that an older reader can skip. It cannot tell which, so a client that sees partVersionNewer should treat a feature that fails with unknownFeature as the likely cause of any problem, and should be careful about saving the document back.

A missing version, a version that is not a number ("3" counts as missing) and a number of 1 or less give no warning.

{
  "format": "ck-part", "version": 1,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [{"id": "c", "x": 0, "y": 0}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 10}], "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 5}
  ]
}

Run result: no errors; 3 faces, volume 1570.7963 mm³. The reply has no partVersionNewer (absent).

{
  "format": "ck-part", "version": 2,
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [{"id": "c", "x": 0, "y": 0}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 10}], "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 5}
  ]
}

Run result: no errors; 3 faces, volume 1570.7963 mm³. The reply’s result carries "partVersionNewer": {"file":2,"kernel":1}; the body is the same as for version 1.

Forward compatibility

A reader has to cope with fields and values that a newer writer may add. The kernel’s rules:

What is newWhat the kernel does
An unknown top-level fieldKept untouched, never read.
An unknown field on a featureKept in the feature, ignored. For a sketch the reply echoes it back (key order and unknown keys are preserved).
An unknown feature typeThat feature fails with unknownFeature {type}. The other features run.
An unknown sketch entity typeThe entity is dropped.
An unknown sketch constraint typeThe constraint is kept; the solver cannot build its system and leaves the sketch as written.
An unknown value in an enumerated fieldDepends on the field (below).

Unknown values of enumerated fields:

FieldUnknown value gives
op (extrude, revolve, sweep, loft, sphere)add.
plane modeoffset.
hole kind, fitsimple, normal.
helix definedBypitchRevs.
thicken sidefront.
extrude endError unknownEnd.
chamfer chamferType, fillet filletTypeError unsupported {what}.
mate kindError mateGeometry.
combine op, extrude thin.sideError invalidValue.

A part that mixes known and unknown content therefore regenerates as far as it can: here a document from a newer writer with an unknown feature type, unknown fields and a thumbnail:

{
  "format": "ck-part", "version": 3, "futureField": [1, 2], "thumbnail": "data:image/png;base64,AAAA",
  "features": [
    {
      "type": "sketch", "id": "F1", "plane": {"kind": "std", "id": "front"},
      "points": [{"id": "c", "x": 0, "y": 0}],
      "entities": [{"type": "circle", "id": "e1", "c": "c", "r": 10}], "constraints": []
    },
    {"type": "extrude", "id": "F2", "op": "add", "sketch": "F1", "end": "blind", "depth": 5},
    {"type": "hoverTool", "id": "F3", "strength": 3},
    {
      "type": "extrude", "id": "F4", "op": "add", "sketch": "F1", "end": "blind", "depth": 5,
      "futureOption": {"nested": true}
    }
  ]
}

Run result: errors F3: unknownFeature {"type":"hoverTool"}; 3 faces, volume 1570.7963 mm³. The unknown type fails alone; the unknown fields are ignored.

What a writer should do

  • Write "format": "ck-part" and the version of the format being written.
  • Keep every field it does not understand when it reads and writes a document back, at the top level and inside features. The kernel does the same when it echoes a sketch.
  • Not rely on the kernel to refuse a newer document: check partVersionNewer in the regen reply.

See also

Protocol overview

The kernel is driven by messages: one JSON request in, one framed reply out. This chapter describes the request shape, the state the kernel keeps between messages, the options that apply to every message, and lists all 57 request types. The reply framing is in Replies and buffers, the main request in Regeneration, the others in Queries, the failure model in Errors, and the HTTP service that serves the same messages in The native service.

Request shape

A request body is a UTF-8 JSON document with two keys:

{ "id": 7, "msg": { "type": "regen", "tag": "main", "part": { "...": "..." }, "opts": { "upTo": 3 } } }
KeyMeaning
idA number chosen by the host to match replies to requests. The kernel ignores it and does not echo it: the reply to a call is the return value of that call.
msgThe message: an object. The first msg key in the document is the one used.
msg.typeThe request type, a non-empty string. The 57 types are listed below.
msg.tagWhich kernel state the message uses (see Tags and sessions). A string; anything else, or no tag, means "main".
msg.debugThe boolean true adds timing information to the reply (Debug). Any other value is ignored.

Other keys of the envelope are ignored. The remaining keys of msg depend on the type.

A body that is not JSON, a document without an object msg, a msg with no type, and an unknown type are answered with an error reply, not with a trap:

Bodyerror
not valid JSONbad request: the body must be JSON {id, msg}
msg missing, or not an objectbad request: msg must be an object
msg.type missing, empty or not a stringmessage without a type
unknown type, for example nopeunknown request nope

Tags and sessions

A session is one kernel instance: one instantiation of the wasm module, or one session of the native service. A session owns its state, and sessions do not share anything.

Inside a session the state is kept per tag. A tag is a name for one regenerated document. regen computes a document and stores the result under its tag: the body (the B-rep), the solved sketches and the assembly state. Later requests that name the same tag read that state without running the part again. For example, massProps with "tag": "plate" measures the body that the last regen with "tag": "plate" produced. Typical clients use fixed tags for fixed purposes (main for the document on screen, preview for an edit being tried) and different tags for different documents.

What the rules are:

  • A regen replaces the state of its tag. It does not touch other tags. If the part produces no body (it has no features, or only sketches), the tag is stored with no body.
  • A regen whose part is not a part document (format is not "ck-part", or features is not an array) fails with invalid part: Format and keeps the previous state of the tag. A regen in which individual features fail is not a failed request: it succeeds, reports the failures in errors and stores what was built (Regeneration).
  • A request that needs state, for a tag that has never been stored, fails with noState: nothing regenerated yet. Clients that restore their state after a kernel restart can key on the prefix noState.
  • A request that needs a body, for a tag that has state but no body, does not fail: it answers an empty value of its own shape, in most cases null (Queries gives the answer of each type).
  • importStep, importSat, importSldprt and importSkp store a body under their tag when the import succeeds, and leave the tag alone when it fails. recognize with opts.apply stores a rebuilt body under <tag>.rebuilt.
  • State lives as long as the session. The warm caches that make a repeated regen fast (the regen cache, the display-mesh caches) live with the session too; a capped amount of memory, 256 MiB by default for the regen cache, can be changed with opts.cacheCap (Regeneration). A new instance starts empty.

Some requests take everything they need in the message and use no tag: ping, matchEdges, sketchOffset, refDiff, profiles, threadData, textMetrics, textOutline, the font requests, and checkProfile, sketchAnalyze and sketchFreedoms when called with a part. They can be sent before any regen.

opts.upTo

regen takes an options object. The one that matters for every client is upTo:

{ "type": "regen", "tag": "preview", "part": { "...": "..." }, "opts": { "upTo": 2 } }

With opts.upTo = n (a number, 0 or more) only the first n features of the part are regenerated, as if the others were not there. A negative or non-numeric value is ignored. It is the way to look at a part at an earlier step (a history slider, “roll back to here”) and to find the feature that broke a part. The part’s own rollback field acts the same way, and the smaller of the two wins. Features marked suppressed are skipped. matchEdges takes upTo at the top level of the message. The other options of regen are described in Regeneration.

Debug: timing trace

"debug": true in msg makes the kernel record a trace of its steps:

{ "id": 1, "msg": { "type": "regen", "tag": "plate", "part": { "...": "..." }, "debug": true } }

The reply gets two more keys after ms: buffers, with the number and total size in bytes of the binary buffers of this reply (successful replies only), and trace, a list of steps in the order they started:

"buffers": { "count": 5, "bytes": 11648 },
"trace": [
  { "at": 0.02,  "ms": 0.88,  "depth": 0, "label": "regenerate 4 features", "level": "span" },
  { "at": 0.03,  "ms": 0.02,  "depth": 1, "label": "F1 sketch", "level": "span" },
  { "at": 0.05,  "ms": 0.04,  "depth": 1, "label": "F2 extrude → 6 faces", "level": "span" },
  { "at": 0.09,  "ms": 0.80,  "depth": 1, "label": "F4 hole → 7 faces", "level": "span" },
  { "at": 0.88,  "ms": 0.01,  "depth": 2, "label": "boolean Subtract (6 × 3 faces) → 7 faces", "level": "span" },
  ...
  { "at": 0.92,  "ms": 1.37,  "depth": 0, "label": "snapshot for the view (display meshes, edges)", "level": "span" },
  { "at": 0.92,  "ms": 1.22,  "depth": 1, "label": "tessellate 7 faces → 104 triangles", "level": "span" }
]

Each entry is one span: at is the start in milliseconds since the request began, ms the duration, depth the nesting, and label what ran. A feature’s label ends with → n faces when it succeeded, or with : <code> when it failed; the stages of a boolean (locate, imprint, apply, classify, assemble, simplify, check) are listed under it. A request with debug never uses the regen cache or the view cache, so the trace shows real work. (The values above are from one real run on a 4-feature plate and rounded.) Error replies carry trace too, without buffers.

Time: ms and the host clock

Every reply has ms, the time the call took, measured with the host’s ck_now import and rounded to whole nanoseconds. A host whose ck_now returns a constant sees ms: 0 (the runner used in this book does). ck_now also drives two time budgets of regen, opts.featureTimeMs and opts.regenTimeMs, and the timeMs budget of the measurement requests; without a real clock they never expire.

Concurrency model

  • A call is synchronous and runs to completion before it returns. One instance runs one request at a time; a host that has several requests to make queues them. Because every call may take seconds on a large part, hosts run the instance in a worker (a Node worker thread, a browser worker) so that their own thread stays free.
  • There is no way to cancel a call in flight. A client that wants to abandon a request discards the reply (the native client’s cancel() drops requests that are still queued, not the running one) or, in the extreme, throws the instance away.
  • Parallelism is by instances: two instances share nothing and can run at the same time on two threads. The native service does this, one worker thread per session, with a configurable limit on sessions. Inside a call the kernel is single threaded.
  • A panic is contained by the instance boundary. The wasm module is built to abort on panic, so the call traps, and the host starts a new instance (Call it from Node); the native service, when built with the service profile (panic = "unwind"), catches the panic and ends only that session with HTTP status 500.

Compatibility

Replies grow additively: new keys appear, existing keys keep their meaning. Optional blocks (warnings, threads, limits, assembly, cacheStats, partVersionNewer in the regen result) are present only when they have content. A client should ignore keys it does not know. The wire protocol has one version number (KERNEL_PROTOCOL, currently 1 in the TypeScript client; the native service reports its own in GET /version), which changes only for an incompatible change of a message or of the framing. A part document with a version higher than the kernel knows still regenerates, and the result says so (partVersionNewer).

Request types

There are 57 request types. “Tag” says what the request needs: tag means a regenerated tag (tag, default main) and answers noState without one; body means it also needs a body in that state; none means it uses no state; part means it regenerates a part given in the message and stores nothing; sets tag means it stores state under the tag.

Document and session

TypeTagPurpose
pingnoneLiveness check. Returns {"pong": true} and, if the module was built with CK_BUILD_REV, the source revision as build.
regensets tagRegenerate a part document: run its features and store the body. Returns errors, sketches, planes, the body with its display mesh, and more.
stepbodyExport the tag’s body as a STEP file (the reply is the file text as a JSON string).
validatebodyRun the solid validator on the body, plus a mesh watertightness check.
healbodyRepair the body in place, or report what would be repaired (dryRun).

Import

TypeTagPurpose
importStepsets tagRead the solids of a STEP file (text) into a body.
importSatsets tagRead an ACIS SAT file (text) into a body.
importSldprtsets tagRead a SolidWorks part file (base64) into a body.
importSkpsets tagRead a SketchUp file (base64) into a surface body of planar faces. Needs a module built with the skp feature.
recognizebodyRecognise the features of an imported solid and propose a feature tree.

Geometry queries

TypeTagPurpose
measurebodyFacts about faces and edges; for two references also their distance, angle and offsets.
massPropsbodyVolume, area, centre of mass and principal moments; per body and with densities.
interferencebodyOverlap volume of every pair of separate bodies in the state.
inspectbodyDiagnostics for a selected sketch (regions, areas).
continuitybodyG0 to G3 continuity along edges.
curvatureAtbodyPrincipal curvatures of faces at the points nearest to given points.
curvatureMapbodyA false-colour curvature mesh for every face.
combbodyCurvature combs of edges and faces.
drawingbody2D views of the body: projected edges, hidden lines, sections with hatching.
refCurvebodyAn edge or a sketch curve as an exact NURBS curve.
convertbodyProject edges, faces or sketch curves into a sketch frame as new sketch entities.
dragbodyMove one assembly component so that a grabbed point follows a target, honouring its mates.

Selection and naming

TypeTagPurpose
matchEdgespartEdges similar, parallel or tangent to seed edges, for edge picking.
resolvebodyTurn descriptions of faces and edges (“the top face”, “the hole barrel”) into persistent names.
describebodyFacts and a one-line text for named faces and edges.
faceRunbodyArea centre, outward normal, reach and the feature end of flat faces (the Press Pull panel).
refDiffpartCompare two versions of a part and report references that now point at a different entity.
checkbodyCheck expectations (volume, counts, size, …) against the body.

Verification and measurement

TypeTagPurpose
sectionbodyExact cross-section loops of the body at a plane.
sectionsbodyA stack of sections along an axis and the volume integrated from them.
probebodyInside/outside and signed distance of points; hit lists of rays.
distancebodyMinimum distance of two entities.
maxDistancebodyOne-sided Hausdorff distance between two entities or bodies.
thicknessbodyMinimum wall thickness and the thinnest places.
thicknessAtbodyWall thickness at a point or over a face.
closestPointbodyThe nearest body, face, edge or vertex for many points.
anglesbodyDihedral angles of edges and faces, and draft angles.
clearancebodyFace pairs closer than a given distance.
symmetrybodyMirror-symmetry planes and the deviation of the mirrored body.
extremabodyLowest and highest point of the body along a direction.
bodyBooleanbodyPreview a boolean between the separate bodies of the state; nothing is stored.

Design rules

TypeTagPurpose
profilesnoneList the built-in design-rule profiles and the rule catalogue.
checkProfilebody or partRun a design-rule profile (3D printing, CNC, injection moulding or inline) on a body.
dfmMinWallbodyThinnest wall against a minimum.
dfmMinInternalRadiusbodySmallest concave corner radius against a cutter radius.
dfmPocketRatiobodyDepth to width ratio of closed pockets against a limit.
dfmOverhangbodyOverhanging faces against a build direction.
dfmConstantSectionbodyWhether the body is a constant extrusion along an axis.

Sketches

TypeTagPurpose
sketchOffsetnoneOffset sketch entities by a distance and return the resulting chains.
sketchAnalyzebody or partStructural findings of one sketch: open ends, duplicates, overlaps, and why there is no closed profile.
sketchFreedomsbody or partDegrees of freedom of one sketch, per point, radius and entity.

Text and data

TypeTagPurpose
textMetricsnoneAdvance width and ink box of a string.
textOutlinenoneThe outline loops of a text entity as polylines.
loadFontnoneRegister a TrueType/OpenType font for the session (session state, not tag state).
unloadFontnoneRemove a loaded font.
listFontsnoneList the built-in and loaded fonts.
subsetFontnoneA font file with only the glyphs of a string.
threadDatanoneThe thread standards and size tables.

See also

Replies and buffers

Every call returns one byte string: a length-prefixed JSON document, followed by an optional binary area that holds bulk arrays such as the display mesh. This chapter specifies the layout, the buffer references in the JSON, and how to decode them.

The frame

offset 0        4                      4+L        B = (4+L+7) & ~7
        +-------+----------------------+----------+---------------------------+
        | L     | JSON text, L bytes   | padding  | binary area               |
        | u32le | UTF-8                | spaces   | buffer 0, buffer 1, ...   |
        +-------+----------------------+----------+---------------------------+
  • L, the first four bytes, is the byte length of the JSON text, as an unsigned 32-bit integer in little-endian order.
  • The JSON text follows, UTF-8 encoded, without a terminator.
  • Padding follows, up to the next multiple of 8 counted from the start of the frame. The padding bytes are ASCII spaces (0x20), so the padded text is still valid JSON. If 4 + L is already a multiple of 8, there is no padding.
  • The binary area starts at B = (4 + L + 7) & ~7. Buffers are packed one after another in the order they were created; nothing follows the last one.
  • The value that ck_request returns is the length of the whole frame, binary area included. A frame without buffers is just the padded JSON.

A ping reply is the smallest example. For the body {"id":1,"msg":{"type":"ping"}} and a module built without a revision, the JSON is {"ok":true,"result":{"pong":true},"ms":0} (41 bytes), padded with 3 spaces to a frame of 48 bytes. From a real run of a module that reports its revision, the frame has 72 bytes: 40 00 00 00 (L = 64), the 64 bytes of JSON, and 4 spaces.

The JSON envelope

The JSON is always an object with one of two shapes:

{ "ok": true,  "result": <value>, "ms": 0.58 }
{ "ok": false, "error": "unknown request nope", "ms": 0.01 }
KeyMeaning
oktrue when the request ran and produced a result.
resultThe result; its shape depends on the request type. Present when ok is true. It can be any JSON value: an object, an array, a string (step), or null (for example a query on a tag that has no body).
errorA message string. Present when ok is false. There is no structured error object at this level; see Errors.
msThe time the call took in milliseconds, measured with the host’s ck_now. 0 when the host clock is constant.
buffers, traceOnly with "debug": true in the request (Protocol overview). buffers is { "count": n, "bytes": b } for the binary area (ok replies only).

An error reply has no binary area. An ok: true reply says only that the request ran: an operation that fails in a way the request models (a feature that cannot be built, a validator that finds issues, an import that cannot parse its file) reports that inside result.

Numbers are standard JSON numbers written in the shortest form that reads back to the same 64-bit float: 100, 0.5, 59497.34517542564, 1.4332395860321886e-17. A number that is not finite (NaN, infinity) cannot be written and is written as null; the continuity report, for example, uses null for values it could not compute. Object keys keep a fixed order, which is the order the tables in this book use.

Buffer references

A bulk array is not in the JSON. In its place the JSON has a reference object with exactly these four keys, in this order:

{ "$buf": 0, "type": "f32", "len": 936, "offset": 0 }
KeyMeaning
$bufThe index of the buffer in creation order, starting at 0. The index is not the order of appearance in the JSON: in a regen result, body.silhouette is buffer 4 but comes before body.mesh.
typeThe element type: f32, f64, u32, i32 or u8.
lenThe number of elements (not bytes).
offsetThe byte offset of the first element, counted from the start of the binary area B, not from the start of the frame.

Element types:

typeElementBytes
f32IEEE 754 single4
f64IEEE 754 double8
u32unsigned 32-bit integer4
i32signed 32-bit integer4
u8unsigned byte1

All multi-byte elements are little-endian (the native order of WebAssembly). Before a buffer is appended, the area is padded with zero bytes to a multiple of the element size, so that every buffer starts at an offset that suits its element type; offset is always a multiple of the element size. Because B is a multiple of 8, a typed-array view of the frame’s own memory is aligned whenever the frame itself starts at an aligned address. The reference decoder below copies each buffer instead, which makes alignment of the source irrelevant.

A zero-length buffer is legal: { "$buf": 4, "type": "f32", "len": 0, "offset": 11648 } is an empty array placed at the end of the area (the silhouette of a body without curved faces).

Which results carry buffers

ResultBuffers, in creation order
regen and the import requests: bodymesh.positions (f32), mesh.normals (f32), mesh.mids (f32), mesh.triFace (i32), silhouette (f32)
the same, for each entry of surfacesthe same five, following those of body
curvatureMap: bodies[0].meshpositions (f32), normals (f32), k (f32), triFace (i32)

No other request returns buffers. The arrays are:

ArrayLengthContent
mesh.positions9 per triangleThe display mesh as unwelded triangles: three vertices of x, y, z. Vertices are not shared between triangles.
mesh.normals9 per triangleThe exact outward surface normal at each vertex (for a plane, its normal).
mesh.mids9 per triangleFor the triangle’s edges v0-v1, v1-v2, v2-v0, the correction n(mid) - (n_a + n_b) / 2 between the true normal at the edge midpoint and the mean of the normals at its ends. A shader adds a multiple of these to the interpolated normal to round the shading of coarse curved faces. All zero on planes.
mesh.triFace1 per triangleThe index of the triangle’s face in body.faces.
silhouette12 per recordCandidate silhouette edges: a (x, y, z), b (x, y, z), nA (x, y, z), nB (x, y, z). A record exists for each mesh edge shared by two triangles of the same face whose dihedral angle is strictly convex; nA and nB are the facet normals of the two triangles (the earlier and the later triangle). They are the data a renderer needs to draw the silhouette lines of curved faces. Planar faces and concave hole walls have none.
k (curvature map)6 per triangleThe principal curvatures k1 and k2 at each of the three vertices.

body.box is the bounds of the f32 mesh positions together with the edge polylines.

Decoding

  1. Read L from the first 4 bytes, little-endian.
  2. Decode bytes 4 .. 4+L as UTF-8 and parse them as JSON.
  3. Compute B = (4 + L + 7) & ~7.
  4. Walk the parsed value. Replace every object that has a $buf key by the typed array of the right type over bytes B + offset .. B + offset + len * size.

In JavaScript (the same function as in Call it from Node):

const ARRAYS = { f32: Float32Array, f64: Float64Array, u32: Uint32Array, i32: Int32Array, u8: Uint8Array };

function decodeReply(bytes) {                       // bytes: a Uint8Array holding the whole frame
  const L = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0, true);
  const json = JSON.parse(new TextDecoder().decode(bytes.subarray(4, 4 + L)));
  const B = (4 + L + 7) & ~7;
  const walk = (v) => {
    if (Array.isArray(v)) return v.map(walk);
    if (v === null || typeof v !== 'object') return v;
    if ('$buf' in v) {
      const A = ARRAYS[v.type], start = B + v.offset;
      return new A(bytes.slice(start, start + v.len * A.BYTES_PER_ELEMENT).buffer);
    }
    return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x)]));
  };
  return walk(json);
}

bytes.slice copies; a faster host that wants views must make sure the offsets it uses are aligned for the element type.

A real frame

A regen of the 100 x 60 x 10 plate with a hole (seven faces, 104 triangles) returns a frame of 17304 bytes. The JSON is L = 5652 bytes, so B = 5656 (the 4-byte prefix and the JSON already end on a multiple of 8, so no padding is added) and the binary area is 11648 bytes. The references in body are:

"silhouette": { "$buf": 4, "type": "f32", "len": 0,   "offset": 11648 },
"mesh": {
  "positions": { "$buf": 0, "type": "f32", "len": 936, "offset": 0 },
  "normals":   { "$buf": 1, "type": "f32", "len": 936, "offset": 3744 },
  "mids":      { "$buf": 2, "type": "f32", "len": 936, "offset": 7488 },
  "triFace":   { "$buf": 3, "type": "i32", "len": 104, "offset": 11232 }
}

936 floats are 104 triangles times 9 numbers; each f32 buffer is 3744 bytes, triFace is 416 bytes, and 3744 + 3744 + 3744 + 416 = 11648. The cylinder of the hole is curved but its walls are concave, so the silhouette is empty.

book/tools/run.mjs prints each buffer as <buffer type xN> unless it is given --full.

See also

Regeneration

regen runs a part document and returns everything a client needs to show it: the errors of the features, the solved sketches, the planes and curves, and the body with its faces, edges and display mesh. It also stores the body under a tag for the queries that follow. This chapter is the reference for the request and for every field of its result.

Request

{ "type": "regen", "tag": "main", "part": { "format": "ck-part", "version": 1, "features": [ ... ] }, "opts": { "upTo": 3 } }
FieldTypeDefaultMeaning
typestring"regen"
tagstring"main"The name under which the result is stored (Tags and sessions).
partobjectrequiredThe part document. It must be an object with format equal to "ck-part" (only ck-part is written; format strings used by earlier versions are accepted and normalised to it, see Versions and earlier files) and features an array. Anything else is the request error invalid part: Format, and the tag keeps its previous state. version, name and the other fields are not checked here.
optsobject{}Options, below. Unknown keys are ignored.
debugbooleanfalseAdds buffers and a trace to the reply (Protocol overview).

Options

OptionTypeDefaultMeaning
upTonumber >= 0allRegenerate only the first n features. Negative or non-numeric values are ignored. The part’s rollback field limits the run in the same way; the smaller of the two applies.
sketchStatusbooleanfalseAdd a solver status block to every entry of sketches.
solveSketchesbooleanfalseSolve every sketch from its stored coordinates with all its constraints, and use the solved coordinates, in the reply and for the features built from them. Implies sketchStatus.
featureTimeMsnumber120000Time budget of one feature, in milliseconds on the host clock. 0 or less means unlimited. A feature that exceeds it fails with featureBudgetExceeded. See the caching limitation below.
regenTimeMsnumberunlimitedTime budget of the whole regen. When it is used up, the feature that is running fails and later features are not started: each fails with regenBudgetExceeded.
autoHealbooleanfalseAfter each feature, if the body has validation issues, try to repair a copy and keep the repair when it has fewer issues.
healTolnumber1e-5The tolerance used by autoHeal, in mm.
cacheCapnumber >= 0256 MiBSize cap in bytes of the regen cache; the display caches are scaled with it.
noCachebooleanfalseDo not read or write the caches for this call.
cacheStatsbooleanfalseAdd a cacheStats object to the result.
noViewbooleanfalseSkip the display step: the reply has body: null and surfaces: [], while the tag still stores the body for later queries. For a client that already holds the view of this document and only needs the errors and the state.
dofReportbooleanfalseAlways add the assembly block, even when no mate needs it.

The budgets need a real clock from the host (ck_now); with a constant clock they never expire. A few more boolean options are test switches for the intersection code and are not part of the interface.

What a regen does

The features run in document order. For each feature the kernel evaluates the numbers (expressions and variables, =expr fields), checks the references, builds the geometry and combines it with the body so far. Features that are suppressed are skipped. A feature that fails contributes nothing: the body stays as it was before the feature, and the failure is recorded in errors under the feature’s id. The run continues, so a failure often produces a chain of follow-on failures: a feature that refers to a sketch or a face that the failed feature should have made fails with missingSketch or missingReference. The first entry in feature order is usually the one to fix. For example, pointing the extrude of a plate at a sketch that does not exist gives the errors F2: missingSketch, F3: missingReference (the next sketch is on a face of the missing body) and F4: missingSketch, and body is null.

Results are cached per feature prefix: when a document is sent again with only later features changed, the unchanged leading features are not run again, and a document that is identical to a cached one is answered from the cache. cacheStats shows this. Failures caused by a time budget (featureBudgetExceeded, regenBudgetExceeded) are not stored, so a later regen of the same document runs again. (Earlier builds replayed them; noCache was the workaround.)

Sending the same 4-feature plate twice with cacheStats gives reusedFeatures: 0, ranFeatures: 4, viewHit: false the first time and reusedFeatures: 4, ranFeatures: 0, fullHit: true, viewHit: true the second.

Result

The result is an object. The first nine keys are always present, in this order:

{
  "errors": [], "components": [], "planes": [], "markers": [],
  "sketches": [], "sketches3": [], "curves": [], "body": null, "surfaces": []
}

That is the whole result for a part with no features. Optional keys follow when they have content: threads, limits, assembly, warnings, then cacheStats and partVersionNewer.

KeyTypeContent
errorsarrayFailed features: [featureId, { code, params }]. See Errors.
componentsarrayOne entry per inserted part: { id, dof, place }.
planesarrayThe reference planes: [featureId, frame].
markersarrayPer-feature drawing aids: [featureId, object].
sketchesarrayThe solved sketches: [featureId, { frame, profiles, sketch, status? }].
sketches3arrayThe 3D sketches: [featureId, { sketch }].
curvesarrayCurves made by features: [featureId, { pts, axis, t0, t1, ... }].
bodyobject or nullThe solid, or null when the document makes none.
surfacesarraySheet bodies: [featureId, body].
threadsarrayThread features: one object each. Only when there are some.
limitsarray[featureId, { maxHeight }]. Only when there are some.
assemblyobjectDegrees-of-freedom report. Only for added mate kinds, or with dofReport.
warningsarrayNon-fatal notes, same shape as errors. Only when there are some.
cacheStatsobjectOnly with opts.cacheStats.
partVersionNewerobject{ file, kernel }, only when the document’s version is higher than the kernel’s.

The arrays that are keyed by a feature id (errors, planes, sketches, sketches3, components, threads, limits, warnings) are sorted by the id as a string, so F10 comes before F2. An id appears once: a later entry for the same feature replaces an earlier one. curves and markers keep the order in which the features ran.

errors and warnings

Each entry is a two-element array: the id of the feature (an empty string if the feature has no id) and an object with the error code and a params object.

"errors": [ [ "F4", { "code": "holeInvalid", "params": { "hint": "the hole diameter must be greater than zero (a standard `size`, or a positive `diameter`)" } } ] ]

params carries the facts of the failure and, for most failures, a hint that says what to change. warnings has the same shape and means that the feature ran but something was approximated or ignored; for example a thread whose size does not fit the hole:

"warnings": [ [ "F5", { "code": "threadDiameterMismatch", "params": {
    "expected": 6.8, "actual": 8, "size": "M8", "standard": "metric", "internal": true, "nearest": "M10",
    "hint": "hole is 8, M8 tap drill is 6.8: drill the hole to 6.8, or choose M10 (tap drill 8.5)" } } ] ]

Errors lists all codes. With autoHeal a repaired feature adds a healed entry (with fixed, codes and remaining) to errors; it marks a repair, not a failure.

sketches

One entry per sketch feature that ran, in the form [ "F1", { frame, profiles, sketch, status? } ].

FieldMeaning
frameThe sketch plane as { o, x, y, z }: origin and the unit x, y and normal axes, in world coordinates.
profilesThe closed regions the sketch contains, and whether it also has open chains (below).
sketchThe sketch as the kernel used it: the feature object with normalised fields. With solveSketches (or when an expr changed a constraint value) the point coordinates are the solved ones.
statusOnly with sketchStatus or solveSketches (below).

profiles is { "regions": [ { "outer": [segment, ...], "holes": [[segment, ...], ...] } ], "open": false }. The regions are the closed areas that the sketch curves enclose, so curves that cross split an area into several regions; each region has one outer loop and the loops of the holes inside it. Construction geometry is left out. A segment is { "kind", "tag", "a", "b" }: kind is line, arc (arcs, circles and ellipses) or spline; tag is the id of the sketch entity it came from; a and b are the start and end points in sketch coordinates (equal for a full circle, up to rounding). open is true when the sketch has curves but no closed region at all. Extrudes and the other profile consumers build from these regions.

status is { dof, fullyDefined, conflicts, redundant, solved, state, residual }:

FieldMeaning
dofUnknowns minus the rank of the constraint system: the number of motions still free. A point that is not fixed has two unknowns; a circle or ellipse has one more for its radius.
fullyDefinedtrue when state is "full" and the sketch is solved.
conflictsIds of constraints that cannot hold together with the earlier ones.
redundantIds of constraints that are implied by the earlier ones.
solvedThe stored coordinates satisfy every constraint (largest residual at most 1e-7), or a solve from them converges.
state"under" (free motions left), "full" (none) or "over" (some equation depends on the earlier ones).
residualThe largest constraint residual at the coordinates in the reply.

By default the kernel does not move the points of a sketch: the coordinates in the document are used as stored, and the constraints are for the editor. Sending a rectangle with horizontal, vertical and distance constraints whose coordinates are slightly off (corners at (98, 3), (97, 58) and (2, 61), sides constrained to 100 and 60) gives a body with the box [0, 0, 0] to [98, 61, 10]. The same document with "solveSketches": true gives the corners at (100, 0), (100, 60) and (0, 60) to within 1e-10, the box [0, 0, 0] to [100, 60, 10], and status { "dof": 0, "fullyDefined": true, "conflicts": [], "redundant": [], "solved": true, "state": "full", "residual": 1.99e-11 }. The sketch solver describes the solver.

planes, curves, markers, sketches3

  • planes: [ "F3", { "o": [0,0,25], "x": [1,0,0], "y": [0,1,0], "z": [0,0,1] } ] for each plane feature that resolved. Standard planes (front, top, …) and the plane of a sketch are not listed. The entry is there even when the plane feature is hidden.
  • curves: curves made by helix, projectCurve and editCurve features: [ id, { pts, axis, t0, t1 } ]. pts is a polyline of points [x, y, z], axis is false, and t0, t1 the parameter range. A helix adds helix: { o, a, x, y, k, r, angle } (origin, axis, start direction, perpendicular direction, rise per radian k, radius r and the total angle) and has t1 equal to the total angle in radians. A helix with pitch 2, 5 revolutions and radius 5 gives t1 = 31.4159... (10 pi), k = 0.3183... (pitch over 2 pi) and r = 5.
  • markers: extra data about a feature for display. A loft adds { loops, starts, guided, tension }: for each profile 16 samples per piece as { p: [x, y, z], f: fraction }, the matched start point of each profile, whether guides were used, and the tension markers. A projectCurve adds { degree, count, deviation, length, pieces, corners, closed } for the fitted curve.
  • sketches3: [ "F1", { "sketch": { ... } } ] echoes each sketch3d feature as the kernel read it.

components, assembly

Each insertPart feature adds a component to the document. components has { "id": "F6", "dof": 0, "place": { o, x, y, z } } for each, sorted by id: the id of the inserting feature, its remaining degrees of freedom (0 when fully mated or fixed), and the current placement as a frame. assembly, present when the document has mates of the extended kinds or with dofReport, has the totals:

"assembly": {
  "dof": { "total": 2, "translational": 1, "rotational": 1 },
  "components": [ { "id": "F1", "fixed": true, "dof": 0, "translational": 0, "rotational": 0 }, ... ],
  "overConstrained": true, "redundant": ["F4"],
  "conflicts": [ { "mate": "F5", "with": ["F3", "F4"] } ]
}

A mate that the solver rejects is dropped (the components return to the pose before it) and reported as the error mateConflict on the mate and in conflicts. With more than 30 floating components the null-space part of the report is skipped and truncated: true is added. Parts and assemblies describes mates; drag (Queries) moves a component with its mates satisfied.

threads, limits

threads has one object per thread feature, with the facts the feature resolved: for the M8 thread above on the 8 mm hole { "id": "F5", "face": "F4.S.h1", "standard": "metric", "size": "M8", "class": "6H", "pitch": 1.25, "major": 8, "minor": 6.646835, "pitchDiameter": 7.188101, "angle": 60, "length": 10, "hand": "right", "internal": true, "modeled": false, "tapered": false, "diameter": 8, "start": [20, 30, 10], "dir": [0, 0, -1] }. A thread is cosmetic unless modeled is true.

limits records size limits of a feature: [ "F9", { "maxHeight": 56.71 } ], for an extrude of a single circle (radius 10) with a draft of 10 degrees, is the extrude depth at which the tapered sides would meet in a point. A depth of 80 for the same extrude fails with draftTooLarge (params.maxHeight is again 56.71).

body

body is the solid, or null when the document produced none (no features, only sketches, or every feature that makes material failed). It has these keys, in order:

"body": {
  "box": { "min": [0, 0, 0], "max": [100, 60, 10] },
  "faces": [ ... ],
  "edges": [ ... ],
  "silhouette": { "$buf": 4, "type": "f32", "len": 0, "offset": 11648 },
  "mesh": { "positions": { "$buf": 0, ... }, "normals": { "$buf": 1, ... }, "mids": { "$buf": 2, ... }, "triFace": { "$buf": 3, ... } }
}

box is the axis-aligned bounds of the geometry, widened to include the display mesh. silhouette and mesh are buffer references (Replies and buffers); the arrays are described there.

faces

One entry per face, in the body’s face order. The index of a face in this array is the value stored in mesh.triFace for its triangles.

FieldTypeMeaning
idstringThe persistent name of the face (Persistent names): <feature>.<role>. The role is C<k> for the caps of an extrude, revolve or loft, S.<entity> for the side face made from a sketch entity, B<k> for a blend, or a feature-specific name (a hole’s faces are S.h0 to S.h4). A face split by a later feature gets ~<k> for the region, and a face made inside an inserted part gets an @<feature>.<n> suffix.
kindstringThe surface type: plane, cylinder, cone, sphere, torus, revolution, extrusion, spline or offset.
planarbooleantrue when the face is geometrically flat (within 1e-9), whatever its kind. A free-form (spline) face is never reported planar.
metaobjectfeature: the id of the feature that made the face. entity: for side faces, the sketch entity (with an instance suffix). On the faces of a sheet body in surfaces, surface: true.
normal[x, y, z]The outward unit normal; only on planar faces.
lumpnumberThe index of the separate body (lump) the face belongs to; only when the body has more than one lump.

The faces of the plate with a hole:

{ "id": "F2.C1",    "kind": "plane",    "planar": true,  "meta": { "feature": "F2" }, "normal": [0, 0, 1] },
{ "id": "F4.S.h1",  "kind": "cylinder", "planar": false, "meta": { "feature": "F4", "entity": "h1" } }

The reply carries no geometry for curved faces beyond the mesh; ask measure, describe or inspect for the radius, axis and area (Queries).

edges

One entry per edge of the body as a client would draw it. A closed curve that the kernel stores in several pieces (a circle split at a seam) is reported once, and edges that exist only to close periodic faces are not listed.

FieldTypeMeaning
ptsarray of [x, y, z]A polyline of the edge, for drawing. A line has its two end points; curved edges are sampled finely enough to draw.
facesarray of stringsThe faces on the two sides of the edge, sorted. An edge of an open sheet has one entry.
keystringA key of the form <face>|<face>#<n>: the two face ids and the number of the edge in the body’s edge order, for example F2.C1|F2.S.e1#2. The number depends on the order of the edges, so it can change when other edges appear or disappear; the face part stays. describe and resolve take keys.
mid[x, y, z]The point half-way along the edge by length.
linetruePresent on straight edges.
circle{ c, n, r }Present on edges that lie on a circle or circular arc: centre, unit normal and radius.

An edge that is neither straight nor circular has neither line nor circle. A client refers to an edge by { "faces": [a, b], "at": [x, y, z] }: the two face ids and a point near it, which picks one when two faces share several edges.

{ "pts": [[0,0,0],[100,0,0]], "faces": ["F2.C0","F2.S.e1"], "key": "F2.C0|F2.S.e1#0", "mid": [50,0,0], "line": true }

surfaces

Features that make sheets instead of solids (surfaceExtrude and the other surface features, a loft with surface: true) put them in surfaces as [ featureId, body ], where body has the same keys as above (box, faces, edges, silhouette, mesh) and every face has meta.surface: true. Their buffers follow those of body in the binary area. A surfaceExtrude of a 20 x 20 square, depth 15, gives one entry with four faces.

Limits and known gaps

  • Time: a regen runs on one thread to completion; there is no cancel. Use featureTimeMs and regenTimeMs to bound it, and upTo to find the slow feature. The default per-feature budget is two minutes.
  • Feature types that the kernel names but does not build yet fail with a code that starts TODO(rebuild): dome, splitLine, spattern (missingSketch without a sketch, otherwise TODO(rebuild)), fillpattern, surfaceOffset and cutWithSurface (each a run on a plate, with an empty feature). The code refuses some options of implemented features the same way: a drafted mid-plane extrude that needs a union, a lip on curved or several rim faces, an extend with a shape other than same, a deleteFace with fill or heal, a surface sweep of an open profile, and the mirror of an offset surface. Known limits collects the current gaps.
  • inspect of a face, edge, curve or plane on a regenerated body is not implemented; see Queries.
  • body.faces carries no areas or radii, body.edges no lengths: use measure, describe or massProps.

See also

Queries

This chapter documents every request type other than regen: its parameters, its result, and what it answers when there is nothing to answer. The examples were run on three small documents and trimmed with ...:

  • plate: the 100 x 60 x 10 plate with an 8 mm through hole at (20, 30) from A first part, regenerated under the tag q. Its faces are F2.C0 (bottom), F2.C1 (top), F2.S.e1 to F2.S.e4 (the sides) and F4.S.h1 (the hole wall).
  • two bodies: two 20 x 20 x 10 blocks made with "op": "newBody" and named A and B through the body field, with B shifted by (10, 10) so that they overlap. The document is:
{"format":"ck-part","version":1,"name":"Two","features":[{"type":"sketch","id":"F1","plane":{"kind":"std","id":"front"},"points":[{"id":"a","x":0,"y":0},{"id":"b","x":20,"y":0},{"id":"c","x":20,"y":20},{"id":"d","x":0,"y":20}],"entities":[{"id":"e1","type":"line","p1":"a","p2":"b"},{"id":"e2","type":"line","p1":"b","p2":"c"},{"id":"e3","type":"line","p1":"c","p2":"d"},{"id":"e4","type":"line","p1":"d","p2":"a"}],"constraints":[]},{"type":"extrude","id":"F2","op":"newBody","body":"A","sketch":"F1","end":"blind","depth":10},{"type":"sketch","id":"F3","plane":{"kind":"std","id":"front"},"points":[{"id":"a","x":10,"y":10},{"id":"b","x":30,"y":10},{"id":"c","x":30,"y":30},{"id":"d","x":10,"y":30}],"entities":[{"id":"e1","type":"line","p1":"a","p2":"b"},{"id":"e2","type":"line","p1":"b","p2":"c"},{"id":"e3","type":"line","p1":"c","p2":"d"},{"id":"e4","type":"line","p1":"d","p2":"a"}],"constraints":[]},{"type":"extrude","id":"F4","op":"newBody","body":"B","sketch":"F3","end":"blind","depth":10}]}
  • rounded plate: the plate without the hole and with feature F3, a fillet of radius 5 on the edge between F2.C1 and F2.S.e1, whose face is F3.B0.

Unless an entry says otherwise, a request takes the optional string tag (default main). The behaviour that all body queries share:

  • a tag that was never regenerated answers the error noState: nothing regenerated yet;
  • a tag whose last regen made no body answers an empty value of the request’s own shape, named under “No body” in each entry (null for most);
  • bad arguments answer an error reply whose message names the request (probe: at most 2000 points per request).

Lengths are in millimetres and angles in degrees, except where an entry says radians. In the measurement requests an entity is written as described under Entities.

Document

ping

{"type":"ping"} answers {"pong":true}, plus "build":"<revision>" if the module was built with CK_BUILD_REV. It takes no tag and touches no state.

step

Exports the tag’s body as a STEP file (STEP).

ParameterTypeDefaultMeaning
namestring"part"The product name written into the file.

The result is the file’s text as one JSON string ("ISO-10303-21;\nHEADER;..."; 6.9 KB for the plate with a hole). Separate lumps that were built as voids are split into solids first. No body: null.

validate

Runs the independent solid validator, and a watertightness check of the display mesh (The validate request).

ParameterTypeDefaultMeaning
tolnumber1e-6Geometric tolerance in mm.
healTolerancenumberthe validator’s capThe largest edge or vertex tolerance a body may carry before it counts as an issue.
meshbooleantruefalse skips the mesh check.
opts.validateTimeMsnumber60000Time budget in ms (0: unlimited). When it runs out the remaining checks are not run and the reply carries validateBudgetExceeded.
opts.quickbooleanfalseTopology and bounding checks only (no volume checks, no mesh checks).
{ "type": "validate", "tag": "q" }
{ "ok": true, "issues": [], "toleranceUsed": 0 }
Result keyMeaning
oktrue when issues is empty.
issues[{ code, entity, detail }]: the check that failed, the entity it concerns (F2.S.e1, edge#4, lump#0) and a sentence.
toleranceUsedThe largest edge or vertex tolerance in the body (0 for an exact body).
stats{ totalMs, shell, loops, edges, solids, tessellation, ... }: time in ms of the request and of each check that ran.
validateBudgetExceededOnly when the time budget ran out: { budgetMs, elapsedMs, checksNotRun, checksPartial, detail }. ok is then false; issues holds what the checks that ran found.
quick, checksSkippedOnly with opts.quick: true and the checks left out.
meshNotesStrings "<face>: <note>", when the tessellator noted a problem on a face. Only when there are some.
infoFor a body with overlapping lumps: { code: "bodiesOverlap", severity: "info", a, b, aName?, bName?, volume } for each overlapping pair. Overlap is legal and is never an issue.
notesA note when the body carries tolerances above zero.

On the two overlapping blocks: {"ok":true,"issues":[],"toleranceUsed":0,"info":[{"code":"bodiesOverlap","severity":"info","a":"F2.C0","b":"F4.C0","aName":"A","bName":"B","volume":1000}]}. No body: null.

heal

Repairs the body in place: merges near-coincident vertices, sews free edges, makes face orientations consistent and so on (Healing).

ParameterTypeDefaultMeaning
tolnumber1e-5Healing tolerance in mm.
healobject or "off"Options: tol, sew, fixSmall, fixOrientation, tolerant, cap.
healTolerancenumberCap on edge and vertex tolerances.
dryRunbooleanfalseReport what would be repaired without changing the stored body.
damagestringSelf-test: break a copy of the body in the named way first (detach, shells, flip, invert, reverseCoedge, shuffle, tiny) and report whether healing restored it. The stored body is never changed.
{ "type": "heal", "tag": "q", "damage": "flip", "dryRun": true }
{ "fixed": [ { "code": "FACE_FLIPPED", "entity": "F2.S.e1", "detail": "face orientation made consistent with its neighbours" } ],
  "remaining": [],
  "volume": { "before": 59497.34517542564, "after": 59497.34517542564 },
  "damage": { "kind": "flip", "applied": true, "clean": true } }

fixed and remaining are lists of { code, entity, detail }. A healthy body without damage answers empty lists. damage.applied is false when the body has nothing of that kind to break, or is not healthy to begin with; clean is true when the repaired copy validates and has the volume of the body before the damage. No body: null.

Mass and interference

massProps

ParameterTypeDefaultMeaning
bodiesbooleanfalseAdd a per-lump list bodies.
densitiesarray of numbersOne density per lump (mass per mm^3). Implies bodies: true, adds mass to each entry and a byMass object. A wrong length is an error naming the lump count.
{ "type": "massProps", "tag": "q" }
{ "volume": 59497.34517542564, "area": 15350.796447372313, "com": [50.25345071604068, 30, 4.999999999999997],
  "principal": [18493800.59049692, 50037589.30162367, 67539767.47253016],
  "axes": [ [1, 1.4e-17, 8.3e-19], [-1.4e-17, 1, 2.9e-22], [-8.3e-19, -2.9e-22, 1] ] }
KeyMeaning
volume, areaTotal volume and surface area.
comCentre of mass at unit density.
principalThe principal moments of inertia about the centre of mass, ascending, at unit density (volume stands for mass).
axesThe three unit principal directions, matching principal. For a body with equal moments (a cylinder, a sphere) the directions are arbitrary.
bodiesWith bodies or densities: [{ volume, area, com, name?, mass? }] per lump. name is the body name if the lump has one.
byMassWith densities: { mass, com, principal, axes } for the density-weighted whole.

With two overlapping blocks and "bodies": true, bodies is [ { "volume": 4000, "area": 1600, "com": [10,10,5], "name": "A" }, { ..., "name": "B" } ] while volume is 8000: overlap is counted twice, since the lumps are separate bodies. With "densities": [0.0027] on the plate, the entry gets "mass": 160.64 and byMass.mass is 160.64. No body: null. A body whose lumps are all sheets (open edges, no enclosed volume, for example a surface import) answers volume: 0, its area, com as the area centroid and kind: "surface"; principal, axes, firstMoment, inertia and inertiaOrigin are then weighted by area (surface density 1), and mass is 0. Earlier replies had null for com and principal here; a caller that reads only volume or area sees no change.

interference

Pairs of lumps of the same state that overlap. No parameters.

{ "bodies": 2, "pairs": [ { "a": "F2.C0", "b": "F4.C0", "aName": "A", "bName": "B",
                            "volume": 1000, "com": [15, 15, 5], "box": { "min": [10,10,0], "max": [20,20,10] } } ] }

bodies is the lump count. Each pair names one face of each lump (a, b), the lump names if they have any, and the common part: its volume, centre of mass and bounding box. A pair whose boolean fails has error instead. For the plate, {"bodies":1,"pairs":[]}. No body: null.

bodyBoolean

Previews the combine feature on the state’s separate bodies and stores nothing.

ParameterTypeMeaning
opstringunion (add, join), cut (subtract), intersect (common) or split.
targetselectorExactly one lump: a face id (the lump holding it), { "face": id }, { "lump": n } or { "body": name }.
toolsarray of selectorsOne or more lumps; none may be the target.
keepToolsbooleanKeep the tool lumps next to the result.
tolerance, autoFuzzynumber, booleanThe fuzzy-boolean controls that the features which combine bodies also take: a tolerance in mm for nearly coincident faces, and a retry at looser tolerances.
{ "type": "bodyBoolean", "tag": "t", "op": "intersect", "target": { "body": "A" }, "tools": [ { "body": "B" } ] }
{ "ok": true, "lumps": 1, "volume": 1000, "area": 600, "faces": ["F2.C0","F2.C1","F2.S.e2","F2.S.e3","F4.S.e1","F4.S.e4"] }

The union of the same two blocks answers "volume": 7000 (4000 + 4000 - 1000). A failure is a normal result, not an error reply: { "ok": false, "error": { "code": "invalidValue", "params": { "detail": "a tool is the target lump" } } }. (This error is an object of the feature-error form, unlike the string of an error reply; see Errors.) No body: null.

Selection and references

measure

Facts about faces and edges and, for exactly two references, the relation between them.

ParameterTypeMeaning
refsarrayOne or more references: { "kind": "face", "id": "F2.C1" } or { "kind": "edge", "faces": ["F2.C1","F2.S.e1"], "at": [50,0,10] }.

The result is { "items": [...] } with one item per reference, plus the pair keys when there are exactly two references. If any reference does not resolve, the result is null. Items:

ItemKeys
plane facekind: "face", surface: "plane", area, normal (outward)
cylinder facesurface: "cylinder", area, radius, center, axis
cone facesurface: "cone", area, center, axis
sphere facesurface: "sphere", area, radius, center
other facessurface, area
edgekind: "edge", length; a line adds direction; a circle radius, center, axis; then wedge: the angle in radians between the outward normals of the two faces, for edges with two faces

Pair keys: distance and points (the closest point on each reference), angle in radians between the normals or directions (a plane against a line gives the complement), normalDistance for parallel planes, and centerDistance for cylinders, cones, spheres and circles. Distances are found by sampling and refinement, to the accuracy of the refinement; the distance request is the exact one.

{ "type": "measure", "tag": "q", "refs": [ { "kind": "face", "id": "F2.C0" }, { "kind": "face", "id": "F2.C1" } ] }
{ "items": [ { "kind": "face", "surface": "plane", "area": 5949.73, "normal": [0,0,-1] },
             { "kind": "face", "surface": "plane", "area": 5949.73, "normal": [0,0,1] } ],
  "distance": 10, "points": [[0,0,0],[0,0,10]], "angle": 0, "normalDistance": 10 }

For the hole wall and a side face: items[0] is { "surface": "cylinder", "area": 251.33, "radius": 4, "center": [20,30,10], "axis": [0,0,-1] }, and the pair has "distance": 16 with points [16,30,10] and [0,30,10]. A single edge: { "items": [ { "kind": "edge", "length": 100, "direction": [1,0,0], "wedge": 1.5707963267948966 } ] }. No body: null.

faceRun

Facts of flat faces for the Press Pull panel (see pressPull).

ParameterTypeMeaning
facesarrayFace names.

The result is { "items": [...] }, one per name: face, found; for a flat face flat: true, centre (area centre, holes taken out), normal (outward), reach (mm, the distance from the centre to the farthest point of the outer outline), area, and endOf ({ "feature", "kind", "input" } when the face is the moving end of an extrude (depth), revolve (angle) or sweep (path), else null). A face that is not flat has flat: false and surface. No body: null.

{ "type": "faceRun", "tag": "q", "faces": ["F2.C1"] }
{ "items": [ { "face": "F2.C1", "found": true, "flat": true, "centre": [0,30,0], "normal": [0,1,0], "reach": 5, "area": 78.54,
               "endOf": { "feature": "F2", "kind": "extrude", "input": "depth" } } ] }

describe

Facts and a one-line description for named faces and edges.

ParameterTypeMeaning
namesarrayEach: a face id, an edge key (F2.C0|F2.S.e1#0), { "kind": "face", "id": ... } or an edge reference { "faces": [a, b], "at": [x, y, z] }.

The result is { "items": [...] }. An item for a face that exists has name, a ref that can be stored in a feature ({ kind: "face", id } or an edge reference), kind, surface or curve, area or length, centroid or mid, feature, role (cap, side, blend, other), the direction facts that apply (normal, axis, dir, radius), concave and hole for cylinders, adjacent faces, outermost (the sides of the body’s box that a planar face lies on), text, and found: true. A name that no longer exists answers found: false, an error, and nearest candidates:

{ "name": "F9.X", "found": false, "error": "face id not found", "nearest": ["F2.C0","F2.C1","F2.S.e1"] }

and for the hole wall: "text": "hole barrel (concave) cylinder face F4.S.h1: radius 4, axis -z, area 251.3274, centre (20, 30, 5); side face of sketch entity h1 in F4; adjacent to F2.C0, F2.C1". No body: null.

resolve

Turns descriptions of faces and edges into persistent names, with a report of how unambiguous the description was.

ParameterTypeMeaning
descriptions (or description)array of objectsEach has kind (face or edge) and any of the filters below; all given filters must hold.

Filters: surface (plane cylinder cone sphere torus spline revolution extrusion offset, string or list) and normal, axis, radius, area, role, entity, concave, hole for faces; curve (line circle other), dir, length, between for edges; and for both feature, name (exact, or a prefix ending *), touches, body, extreme with along, and near with within. Directions are "x", "+z", "-y" or [x, y, z] and match to about 0.08 degrees. Number values are 5 (relative 1e-6), { "value", "tol" } or { "min", "max" }. Filters apply in a fixed order (feature, name, touches, radius, shape fields, extreme, near), so extreme chooses among the faces already filtered.

Each description answers { description, status, ambiguous, count, matches, narrowing }. status is unique, ambiguous (more than one match, all of them listed), none or invalid (an unknown field or bad value, with error). narrowing lists how many candidates remained after each filter; hint and resolvedBy ("near") appear when they apply. Each match is a describe item.

{ "type": "resolve", "tag": "q", "descriptions": [ { "kind": "face", "surface": "plane", "normal": "+z", "extreme": "max" } ] }
{ "results": [ { "description": { ... }, "status": "unique", "ambiguous": false, "count": 1,
                 "matches": [ { "name": "F2.C1", "ref": { "kind": "face", "id": "F2.C1" }, "surface": "plane", "area": 5949.73,
                                "centroid": [50.25, 30, 10], "role": "cap", "normal": "+z", ... } ],
                 "narrowing": [ { "filter": "surface", "remaining": 6 }, { "filter": "normal", "remaining": 1 },
                                { "filter": "extreme", "remaining": 1 } ] } ] }

No body: null.

check

Checks expectations about the body, for tests and for clients that verify a result.

ParameterTypeMeaning
expectarray or object[{ kind, equals | min | max, tol?, relTol?, id? }], or the shorthand { "volume": 1000, "faces": 7, "edges": { "min": 10 } }.
tolnumberTolerance of the valid check (default 1e-6).

Kinds: volume, area (default relative tolerance 1e-4); mass (volume times density); bbox (any of min, max, size as [x, y, z], absolute tol); com (at, tol); the counts faces, edges, vertices, solids; holes (concave cylindrical faces bounded by full circles); innerLoops; and valid (validator issue count must be 0).

{ "type": "check", "tag": "q", "expect": [ { "kind": "volume", "equals": 59497.345 }, { "kind": "faces", "equals": 7 }, { "kind": "holes", "equals": 1 } ] }
{ "ok": true, "passed": 3, "failed": 0,
  "results": [ { "index": 0, "kind": "volume", "pass": true, "measured": 59497.345175426,
                 "expected": { "equals": 59497.345, "tol": 5.9497345 }, "detail": "volume 59497.3452 vs [59491.3953, 59503.2947]" }, ... ],
  "measured": { "volume": 59497.345175426, "area": 15350.796447372, "com": [50.253450716, 30, 5],
                "bbox": { "min": [0,0,0], "max": [100,60,10], "size": [100,60,10] },
                "faces": 7, "edges": 14, "vertices": 11, "solids": 1, "holes": 1, "innerLoops": 2 } }

An expectation that cannot be used (unknown kind, missing value) fails with an explanatory detail. No body: null.

refDiff

Compares two versions of a document and reports references that now point at a different entity. It regenerates both documents privately (through the regen cache) and stores nothing.

ParameterTypeMeaning
baseobjectThe document before the edit.
partobjectThe document after the edit. Both must be part documents (invalid part: Format otherwise).
repairbooleanDefault false. true adds repaired (the part with every unambiguous suggestion applied) and repairs.

Result: { ok, checked, warnings, features, errors }. checked is the number of references present in both. Each warning is { code, feature, ref, reason, before, after }, with code referenceChanged (it resolves, to something that no longer matches in surface type, direction, neighbour kinds, size ratio between 0.25 and 4, or position) or referenceLost. features is { removed, added, reordered } (feature ids). errors lists regen failures of either document as [featureId, code] pairs (the code is a plain string here). Ordinary parameter edits do not warn.

base is the plate of A first part without the hole and with the fillet { "type": "fillet", "id": "F3", "radius": 5, "edges": [ { "faces": ["F2.C1", "F2.S.e1"], "at": [50, 0, 10] } ] } as third feature. part is the same document with the points of sketch F1 reordered to p1 (100, 60), p2 (0, 60), p3 (0, 0), p4 (100, 0), the entities unchanged, so that e1 is now the opposite side of the plate:

{ "ok": false, "checked": 1,
  "warnings": [ { "code": "referenceChanged", "feature": "F3",
                  "ref": { "faces": ["F2.C1","F2.S.e1"], "at": [50,0,10] },
                  "reason": "position (50, 0, 10) -> (50, 60, 10)",
                  "before": "line edge F2.C1|F2.S.e1#5: length 100, direction +x, midpoint (50, 0, 10); between F2.C1 and F2.S.e1",
                  "after":  "line edge F2.C1|F2.S.e1#5: length 100, direction -x, midpoint (50, 60, 10); between F2.C1 and F2.S.e1" } ],
  "features": { "removed": [], "added": [], "reordered": false }, "errors": [] }

A referenceLost warning also carries candidates and, when exactly one of them fits, suggest. The candidates are the faces ({ "id", "text" }) or, for an edge pick, the edges ({ "faces": [a, b], "text" }) of the body at that feature that the old entity could be: the kernel keeps those whose kind, direction, neighbour kinds, size and position still match the old one under the rules above, closest first, at most five. suggest is present only when exactly one entity fits, so a repair is never a choice between two; with two or more the client or the agent picks from candidates. With "repair": true the reply adds repaired, the part with each suggestion applied (a face id replaced in that feature, an edge pick given the new face pair with its at kept), and repairs, [{ feature, from, to }]. Nothing else in the document is touched. A reference that does not resolve in part and has no suggestion stays as it is and keeps failing with missingReference or missingEdge, whose own params list what the body has now.

A client calls it with the document before an edit when it applies an edit, a deletion or a move. References inside sketches and inside nested inserted parts are not compared, and a feature whose id changes looks like a removal plus an addition.

matchEdges

Finds edges that are like seed edges, for “select similar” commands. It regenerates the part given in the message, so it needs no tag.

ParameterTypeDefaultMeaning
partobjectrequiredThe document.
upTonumberallRegenerate only this many features.
modestringsimilarsimilar: same curve type, length and dihedral angle (convex and concave edges differ). parallel: lines parallel to a line seed, circles with a parallel axis to a circle seed. tangent: the chain of edges that continue the seed tangentially (angle under 1e-3 rad) through shared vertices. An unknown mode acts as similar.
seedsarrayEdges as { "faces": [a, b], "at": [x, y, z] }.
excludearrayEdges to leave out of the answer.
noCachebooleanfalseDo not use the regen cache.

The result is an array of { faces, at } edge references: the union over the seeds, without the seeds or the excluded edges, without duplicates. For the plate with a hole, parallel from the front top edge gives the three other edges parallel to it that lie in the top and bottom faces: [ { "faces": ["F2.C0","F2.S.e1"], "at": [50,0,0] }, { "faces": ["F2.C0","F2.S.e3"], "at": [50,60,0] }, { "faces": ["F2.C1","F2.S.e3"], "at": [50,60,10] } ]. An empty part gives [].

recognize

Recognises the features of a body that was imported (a solid with no history) and proposes a feature tree that rebuilds it (Feature recognition).

ParameterTypeDefaultMeaning
applybooleanfalseAlso store the rebuilt body under the tag <tag>.rebuilt so that it can be compared (distance with tagB). May be given at the top level or in opts.

Result keys: features (a feature list in part-document form that rebuilds the body), report (the recognition strategy, the features and what could not be explained), verify (the comparison of the rebuilt body with the input body, or null), errors (strings from the rebuild), unexplainedArea, unexplainedAreaFraction, applied. For the plate with a hole the answer is the plate sketch and extrude, a hole feature, and strategy: "prism". No body: null.

fitQuadrics

Refits the facet fans of an imported mesh body (rings and arcs of planar strips) as cylinders and cones and, when the result validates and keeps the volume, replaces the tag’s body (Cylinders and cones from facets).

ParameterTypeDefaultMeaning
opts.tolnumber0.5 % of the diagonalLargest facet-to-surface deviation (chord sag), mm.
opts.fitTolnumbertol / 10Largest corner-to-surface deviation, mm.
opts.maxStepDeg, opts.minStrips, opts.smoothDegnumber30, 3, 20Largest angle between rails, fewest strips, crease below which coaxial groups are a curved profile.
opts.cones, opts.mergebooleantrueRecognise cones; merge coplanar faces first.
opts.volumeTolnumber0.05Keep the fit only if the relative volume change is smaller.
opts.dryRunbooleanfalseReport without changing the body.

Result keys: applied, reason (nothing, invalid, volumeChanged, dryRun), faces, volume, issues, groups, declined. No body: null.

Geometry

inspect

Diagnostics for one selected thing.

ParameterTypeMeaning
refobject{ "kind": "sketch", "id": "F1" }.

Only kind: "sketch" is implemented, and it needs a body in the state. The result is { type: "sketch", frame, regions, areas, open, texts? }: the sketch plane, the number of closed regions, the area of each (outer minus holes) and the open flag; texts lists text entities with their ink boxes. For the plate sketch: { "type": "sketch", "frame": { ... }, "regions": 1, "areas": [6000.000000000001], "open": false }.

All other cases are errors: no ref or no string kind is cannot inspect nothing; an unknown kind (body, FACE) is cannot inspect <kind>; a sketch id that does not exist, or a state with no body, is sketch not found; on a state without a body face, edge, curve, plane give <kind> not found, vertex gives vertex without a point (no at) or no vertex, and feature answers { "type": "feature" }. With a body, the kinds face, edge, curve, plane, vertex and feature are accepted but not implemented: they answer an error that begins notImplemented: inspect <kind>. Use describe, measure and resolve for faces and edges.

continuity

G0 to G3 continuity along edges (Geometry).

ParameterTypeDefaultMeaning
refsarrayWhich edges: { "kind": "face", "id" } (all edges of the face) or { "kind": "edge", "faces": [a, b], "at": [x, y, z] }.
wholebooleanfalseWith no refs, judge every edge of the body that is smooth enough to judge (corners and open edges are left out).
requiredstring"G2"The level the edges must meet: G0, G1, G2 or G3 (any case). Anything else means G2.
tolobject{ gap: 0.01, angle: 0.1, curvature: 0.05, rate: 0.1 }Tolerances: gap in mm, angle in degrees, curvature and rate as fractions. Each key overrides its default when it is a number.

Each edge is sampled 49 times along its length. At every sample the two faces are compared: the gap between them (G0), the angle between the normals (G1), the relative difference of the normal curvatures (G2) and of their rates (G3). The result is { required, tol, edges }, and each edge is

KeyMeaning
key, faces, sidesThe edge key, its two faces sorted, and the same two faces in the order used for the comparison.
kind"judged" (the faces meet smoothly enough to compare), "corner" (every sample is at least 100 tolerances off tangent) or "open" (the edge does not have exactly two faces).
status"ok", "warn" or "fail" for a judged edge, else null.
lengthEdge length.
maxThe largest [gap, angle, curvature, rate] found, null for levels that were not evaluated.
worstThe worst sample, with the level it concerns; null unless judged.
samplesAll samples: { t, s, at, normal, gap, angle, curvature: [kA, kB], g2, rate, g3, fails, status }; fails is the first level that failed ("G1") or null.

On the rounded plate, the edge between the cap F2.C1 and the fillet F3.B0 meets G1 (angle 0, gap 3.5e-9) and its curvature jumps from 0 to the fillet’s 0.2: with "required": "G1" it is "kind": "judged", "status": "ok"; with the default G2 it is reported as failing at G2. The edge of the plain plate between F2.C1 and F2.S.e1 is "kind": "corner", "status": null with angle: 90 in every sample. With no body: { required, tol, edges: [] }.

curvatureAt

Principal curvatures of a face at the point of its surface closest to a probe point.

ParameterTypeMeaning
pointsarray[{ "face": id, "p": [x, y, z] }].

The result is an array, one entry per point. An entry is { p, n, k1, k2, d1, d2, gaussian, mean }: the projected point on the (untrimmed) surface, the outward normal, the principal curvatures k1 >= k2 (positive where the surface bends away from the normal) with their directions d1, d2, and the Gaussian and mean curvature; singular: true is added at a singular point of the surface, such as the pole of a sphere. An unknown face, or an entry without face and p, is { "error": "notFound" }. On the fillet of radius 5: { "p": [50,1,8], "n": [0,-0.8,0.6], "k1": 0.2, "k2": 0, "d1": [0,-0.6,-0.8], "d2": [1,0,0], "gaussian": 0, "mean": 0.1 }. On the planar top: all curvatures 0. If points is not an array the result is []. No body: one { "error": "notFound" } per element.

curvatureMap

A mesh of every face with per-vertex principal curvatures, for a false-colour display. No parameters.

{ "bodies": [ { "id": null, "faces": ["F2.S.e1", ..., "F4.S.h1"],
                "mesh": { "positions": <f32 buffer>, "normals": <f32 buffer>, "k": <f32 buffer>, "triFace": <i32 buffer> } } ],
  "failed": [] }

faces are the face ids; triFace indexes into that list. positions and normals have 9 numbers per triangle, k has 6 (k1, k2 at each vertex), and the four buffers follow each other in the binary area (Replies and buffers). Planar faces use the display triangulation and curved faces are subdivided; curvature values are exact. failed lists faces that could not be meshed. No body: { "bodies": [], "failed": [] }.

comb

Curvature combs of curves and faces.

ParameterTypeDefaultMeaning
refsarray{ "kind": "edge", "faces", "at" } or { "kind": "face", "id" }.
densitynumber50Samples per curve, clamped to 10 to 300.
linesnumber5Number of comb lines across a face, clamped to 1 to 30.
dirstring"uv"For faces, the parameter directions to comb: "u", "v" or "uv".

The result has one entry per ref: { "curves": [ { p, k, dir? } ] } or { "error": "notFound" } (a reference that does not resolve, or kind: "curve") or { "error": "notCurve" } (any other kind). p is a flat array of sample points [x0, y0, z0, x1, ...] and k a flat array of the curvature vectors at those points (the comb’s teeth: the direction toward the centre of curvature, with the curvature as length); dir ("u" or "v") is added for face curves. For the fillet face with density: 10, lines: 2 each comb curve has 11 points, and the curvature vector has length 0.2 (1/5). Without a body: notFound for face, edge and curve refs, notCurve for the others.

drawing

2D views of the body: projected visible and hidden edges, optional section cuts with hatching.

ParameterTypeDefaultMeaning
viewsarray[]Each view: { "name": "front" } with a name from front back left right top bottom iso, or { "x": [..], "y": [..] }, the view’s right and up directions as 3-vectors (the view direction is their cross product). A section: "section": { "point": [x, y, z], "hatch": 3 } cuts the body by the plane through point perpendicular to the view direction and draws the cut face hatched with the given line spacing (default 3).
hiddenbooleantrueInclude hidden lines. With a body, an absent value means true. With no body, only a hidden sent as true (or a non-zero number) gives {}; absent or false gives null.

A view that has neither a known name nor both x and y fails the whole request with drawing: a view needs a name (front, back, left, right, top, bottom, iso) or x and y. The result is { "views": [view, ...] } in request order. A view is { min, max, lines, edges, axes }:

KeyMeaning
min, maxThe 2D bounds of the view.
linesThe drawn pieces: { k, v, p, e? }: k the kind (e edge, o outline of a curved face, t tangent edge, h hatch), v whether the piece is visible, p a flat polyline [u0, v0, u1, v1, ...], e the index into edges when the piece belongs to an edge.
edgesThe model edges in the view: { faces, at, line | circle, mid, ends } with the face pair and a point at on the edge in 3D (the same reference measure takes), line the 2D segment or circle { c, r }, the 2D midpoint and end points; outline: true for silhouette edges.
axesAxis lines of cylindrical features as 2D segments [[u0, v0], [u1, v1]].

The standard views are fixed frames, given as the view’s right, up and normal directions (x, y, z of the view):

Viewrightupnormal
front+X+Y+Z
back-X+Y-Z
right-Z+Y+X
left+Z+Y-X
top+X-Z+Y
bottom+X+Z-Y
iso(0.7071, 0, -0.7071)the normal crossed with right(0.5774, 0.5774, 0.5774)

The plate is extruded along Z, so its top view looks along the Y axis: the plate seen from the side. That view of the plate with a hole has min [0, -10], max [100, 0], 6 line pieces, 17 edges and one entry in axes, [[[20, -10], [20, 0]]], the axis line of the hole. A section view through (20, 30, 5) adds edges between F4.S.h1 and the cut face SEC.C1, and hatch lines (k: "h"). A section whose plane misses the body gives { "error": "cutNoEffect" } for that view. If views is missing or not an array: { "views": [] }. With no body: null, unless hidden is sent as true, which gives {}.

refCurve

An edge, or a curve of a sketch, as an exact NURBS curve.

ParameterTypeMeaning
refobject{ "kind": "edge", "faces": [a, b], "at": [x, y, z] } or { "kind": "sketchCurve", "sketch": id, "entity": id }.

Result: { curve, start, end, closed } where curve is { P, p, knots, w? }: the control points, degree, knot vector and, for rational curves, the weights. Or { "error": "missingReference" }. A straight edge of the plate gives degree 1; the circle of the hole gives a rational degree-2 curve with 9 control points and weights 1, 0.7071, ..., closed: true. Without a body: { "error": "missingReference" }.

{ "type": "refCurve", "tag": "q", "ref": { "kind": "edge", "faces": ["F2.C1","F2.S.e1"], "at": [50,0,10] } }
{ "curve": { "P": [[0,0,10],[100,0,10]], "p": 1, "knots": [0,0,100,100] }, "start": [0,0,10], "end": [100,0,10], "closed": false }

convert

Projects edges, faces or sketch curves into a sketch frame as new fixed sketch entities.

ParameterTypeMeaning
sketchobjectThe sketch to add to (points, entities, optional seq).
frameobjectThe sketch plane { o, x, y, z }, each a 3-vector. Anything else is the error bad sketch frame.
refobjectAn edge reference, a face reference, or { "kind": "sketchCurve", ... } for a curve of a sketch in the state.

Result: { sketch, ids, skipped }: the sketch with the added points (marked fixed) and entities, the ids of the new entities, and the count of projected pieces dropped as degenerate. A line becomes a line; a circle parallel to the plane a circle or arc; a circle seen edge-on a line; a circle seen at an angle an ellipse; anything else a spline through 129 samples. Each entity carries from: { kind: "edge", faces, at, shape }. null when the reference does not resolve, and for a state with no body.

{ "sketch": { "id": "S", "points": [ { "id": "p1", "x": 0, "y": 0, "fixed": true }, { "id": "p2", "x": 100, "y": 0, "fixed": true } ],
              "entities": [ { "id": "e3", "type": "line", "p1": "p1", "p2": "p2",
                              "from": { "kind": "edge", "faces": ["F2.C1","F2.S.e1"], "at": [50,0,10], "shape": "line" } } ],
              "constraints": [], "seq": 4 },
  "ids": ["e3"], "skipped": 0 }

sketchOffset

Offsets sketch entities and returns the resulting chains. It needs no tag.

ParameterTypeMeaning
sketchobjectThe sketch (with points and entities).
idsarray of stringsThe entities to offset.
distancenumberThe offset; a missing or non-numeric value is the error sketchOffset without a distance.

The result is { "chains": [chain, ...] }; a chain is a list of segments { kind, a, b, ... } in sketch coordinates. A sketch with no entities gives { "chains": [] }. A segment is { kind: "line", a, b }, { kind: "arc", c, r, a, b, ccw } or { kind: "circle", c, r, a, b, ccw }. A positive distance moves a counter-clockwise outline inwards and a negative one outwards. An offset that cannot be made, because it would shrink an arc or circle to nothing, answers { "error": "offsetTooLarge" } as the result (a circle of radius 4 offset by 10). Offsetting the plate outline by -5:

{ "chains": [ [ { "kind": "line", "a": [-5,-5], "b": [105,-5] }, { "kind": "line", "a": [105,-5], "b": [105,65] },
                { "kind": "line", "a": [105,65], "b": [-5,65] }, { "kind": "line", "a": [-5,65], "b": [-5,-5] } ] ] }

The same outline offset by 40 gives the inner rectangle from (40, 40) to (60, 20), and a circle of radius 4 offset by 1 gives a circle of radius 3.

drag

Moves one component of an assembly so that a grabbed point follows the cursor, honouring the mates of the component.

ParameterTypeMeaning
facestringA face of the component to move.
point[x, y, z]The grabbed point.
target[x, y, z]Where it should go.

Result: { insert, delta, place, moves }: the id of the moved insertPart, the rigid motion as a frame, the new placement, and moves, a list [{ id, delta, place }] (only the dragged component moves; others keep their mates unsatisfied). A component without mates translates by target - point; with mates it reaches the closest point of its mate manifold (a point on the circle for a concentric mate, an in-plane slide for a coincident mate). Errors in the result: missingReference (unknown face, or no body), dragNoComponent (a face that belongs to no component), dragFixed (the component is fixed). Missing or non-numeric face, point or target is the error reply drag: face, point and target are required.

Two 20 x 20 x 10 blocks inserted by insertPart, F1 fixed and F2 free at x = 40, then a drag of the top face of F2 by (5, 0, 0):

{ "type": "drag", "tag": "asm", "face": "F2.C1@F2.1", "point": [50,10,10], "target": [55,10,10] }
{ "insert": "F2", "delta": { "o": [5,0,0], "x": [1,0,0], "y": [0,1,0], "z": [0,0,1] },
  "place": { "o": [45,0,0], "x": [1,0,0], "y": [0,1,0], "z": [0,0,1] },
  "moves": [ { "id": "F2", "delta": { ... }, "place": { ... } } ] }

The regen of this assembly with "opts": { "dofReport": true } reports components [ { "id": "F1", "dof": 0, ... }, { "id": "F2", "dof": 6, ... } ] and assembly.dof { "total": 6, "translational": 3, "rotational": 3 }. Faces of an inserted part are named <face>@<insert id>.<n>. On the plate (no components) drag answers { "error": "dragNoComponent" }.

Verification and measurement

These requests are read-only and never change the body. The entity forms, the options and the common elapsedMs / truncated fields are described first.

Entities

Where a request takes an entity (a, b, of, ids):

  • a face id as in describe (a duplicated id selects every face with it);
  • an edge key (F2.C0\|F2.S.e1#0) or e<n>;
  • a vertex V<n>;
  • a point [x, y, z];
  • lump:<n> (the faces of one lump), or "body" (everything);
  • an array of any of these, or an object { face | edge | vertex | lump | point | faces | edges }.

Replies name the face, edge or vertex a point lies on as { kind, id }.

Budget: elapsedMs and truncated

The measurement requests (distance to extrema) carry elapsedMs, the wall time inside the request, and truncated. They stop their loops after opts.timeMs (default 8000 ms) and answer with what they have; truncated: true then means the result is partial: a lower bound for a maximum, or an incomplete list. Options may sit in opts or at the top level of the request. The clock is the host’s; with a constant clock elapsedMs is 0 and nothing is cut off.

section

The exact cross-section of the body at a plane.

ParameterTypeMeaning
planeobject{ "origin": [x, y, z], "normal": [x, y, z] }; the normal is normalised and must not be zero.

Result: { loops, frame, area, meshArea, bbox2d }. frame is the plane’s frame (z the unit normal, x the world Z crossed with the normal, or world X when the normal is within 2.5 degrees of Z); loop coordinates are in it. loops are { kind: "outer" \| "inner", closed, area, edges, pts }; outer loops run counter-clockwise around material (positive area), inner loops clockwise around holes. area of the result is the sum (outer minus inner), meshArea the same from the display mesh, bbox2d is [minx, miny, maxx, maxy]. Edge records are { type: "line", from, to, face }, { type: "arc", centre, radius, start, end, startAngle, sweep, ccw, face } or { type: "polyline", pts, face }, with face the persistent face id. A plane that misses the body gives loops: [], area: 0. When the cut leaves chains that do not close (for instance where a face failed to mesh), the result adds openChains (a count) and openEnds, a list of { start, end, startFace, endFace } with 3D end points and the faces they lie on. If gaps in a chain were bridged to close it, bridgedGaps lists them as { from, to, length, face }; both keys are absent when nothing was open or bridged. Cutting the plate at y = 30, through the centre of the hole, leaves two pieces of the 10 mm thick plate: 76 mm wide (area 760) and 16 mm wide (area 160), so area is 920:

{ "loops": [ { "kind": "outer", "closed": true, "area": 760, "edges": [ { "face": "F2.C0", "type": "line", "from": [-100,0], "to": [-24,0] }, ... ], "pts": [[-100,0],[-24,0],[-24,10],[-100,10]] },
             { "kind": "outer", "closed": true, "area": 160, ... } ],
  "frame": { "o": [0,30,0], "x": [-1,0,0], "y": [0,0,1], "z": [0,1,0] }, "area": 920, "meshArea": 920.455, "bbox2d": [-100,0,0,10] }

How exact: the display mesh is cut by the plane, the cut is chained into loops, every vertex is moved onto the exact surfaces that meet there, and curved stretches are subdivided until the sagitta is under 2e-5 of the body diagonal. Planar faces give exact lines; a run on one circle (a cylinder or cone cut perpendicular to its axis, any sphere cut) becomes an exact arc; everything else is a polyline on the exact surface. A plane exactly through a planar face counts on-plane vertices as on the positive side. No body: null.

sections

A stack of parallel sections and the volume integrated from them.

ParameterTypeDefaultMeaning
axisstring or arrayrequired"x", "y", "z" or [nx, ny, nz] (not zero); sections are perpendicular to it.
nnumber21Number of cell centres between the mesh extent of the body along the axis.
positionsarray of numbersExplicit positions (signed distances along the unit axis), 1 to 1000; used instead of n.
exactbooleantruefalse skips the massProps cross-check, which takes seconds on large bodies.

Result: { axis, range, rule, positions, areas, loops, volume, exactVolume, volumeError }. rule is midpoint (cell centres) or trapezoid (explicit positions, covering only the span between the first and last); areas and loops (count per position) are per section; volume is the integral; exactVolume and volumeError (relative difference) come from massProps. For the plate with "axis": "z", "n": 3: positions [1.667, 5, 8.333], each areas entry 5949.73, loops [2, 2, 2], volume 59497.3453 against exactVolume 59497.3452 (volumeError 2e-9). The rule’s error is about 1e-3 at n = 41 for smooth profiles; a profile with steps needs far more sections, while each section area stays exact. No body: null.

probe

Inside/outside classification of points and the hits of rays.

ParameterTypeMeaning
pointsarray[[x, y, z], ...], at most 2000.
raysarray[{ "origin": [..], "dir": [..] }, ...], at most 2000; dir is normalised and must not be zero.

At least one of the two is required. The result has points and rays for what was requested. A point answers { inside: true \| false \| "boundary", distance, face, nearest } where distance is the signed distance to the nearest face (negative inside), face its id and nearest the foot point. A ray answers { hits: [{ t, point, face, entering, tangent? }] } sorted by t (distance along the unit direction); entering is true when the ray goes from outside to inside; a hit on a shared edge is reported once; a ray lying in a face skips that face; tangent: true marks grazing hits.

{ "type": "probe", "tag": "q", "points": [[50,30,5],[20,30,5]], "rays": [ { "origin": [-10,30,5], "dir": [1,0,0] } ] }
{ "points": [ { "inside": true,  "distance": -5, "face": "F2.C0",   "nearest": [50,30,0] },
              { "inside": false, "distance": 4,  "face": "F4.S.h1", "nearest": [24,30,5] } ],
  "rays": [ { "hits": [ { "t": 10,  "point": [0,30,5],   "face": "F2.S.e4", "entering": true },
                        { "t": 26,  "point": [16,30,5],  "face": "F4.S.h1", "entering": false },
                        { "t": 34,  "point": [24,30,5],  "face": "F4.S.h1", "entering": true },
                        { "t": 110, "point": [100,30,5], "face": "F2.S.e2", "entering": false } ] } ] }

The second point is in the hole, so it is outside the material, 4 mm from the hole wall. No body: null.

distance

Minimum distance between two entities.

ParameterTypeMeaning
a, bentitiesThe two entities.
tagBstringTake b from the body of another tag (a rebuilt part against its source).
opts.samplesnumberGrid size per face for the multi-start search (default 7).

Result: { distance, pointA, pointB, a, b, intersects, direction, aLabel, bLabel, elapsedMs, truncated }. a and b name what each point lies on. When the entities touch, intersects is true, distance 0 and intersection is { "kind": "point" \| "curve" \| "area" }; across two tags, one solid inside the other is kind: "containment" with boundaryDistance. The method is exact projection of points onto faces and edges, the closed form for two segments, and otherwise a multi-start alternating projection (best four starts, up to 400 iterations, stop at a relative gain under 1e-15), so for doubly curved pairs far from every start the minimum can be missed (raise opts.samples).

{ "type": "distance", "tag": "q", "a": { "face": "F4.S.h1" }, "b": { "face": "F2.S.e4" } }
{ "distance": 16, "pointA": [16,30,9.2857], "pointB": [0,30,9.2857], "a": { "kind": "face", "id": "F4.S.h1" }, "b": { "kind": "face", "id": "F2.S.e4" },
  "intersects": false, "direction": [-1,0,0], "aLabel": null, "bLabel": null, "elapsedMs": 1, "truncated": false }

The two overlapping blocks (a: "lump:0", b: "lump:1") give distance: 0, intersects: true, intersection: { "kind": "curve" }. The point on a face is any point of the minimum set: a whole line of the cylinder is equally near. No body: null.

maxDistance

The one-sided Hausdorff distance: the largest distance from the surface of a (default the body) to b (default the body).

ParameterTypeMeaning
a, bentitiesDefault: the whole body.
tagBstringb from another tag.
opts.samplesnumberSample points over the body (default 3000).
opts.bothbooleanAlso measure b to a.

Result: { maxDistance, location, nearest, errorBound, upperBound, rms, samples, coverage, face, elapsedMs, truncated }. The distance function is 1-Lipschitz, so the true maximum lies in [maxDistance, maxDistance + errorBound] where errorBound is the covering radius of the sample grid; coverage is the share of sample points measured. With both: true the reply is { hausdorff, errorBound, aToB, bToA }. A body against itself gives 3.6e-15. No body: null.

thickness

Wall thickness of a solid, by rays from surface samples along the inward normal to the first exit.

ParameterTypeDefaultMeaning
opts.samplesnumber2500About this many samples over all faces.
opts.topnumber10How many thin places to list.
opts.radiusnumberthe larger of 2 x min and 2 % of the diagonalMinimum distance between listed places.
opts.belownumberDrop places thicker than this.
opts.methodstring"ray""sphere" refines the thinnest places with the largest inscribed ball (thickness = 2 r; slower).
opts.sphereSamplesnumber200How many places the sphere method refines.

Result: { method, samples, noExit, minThickness, location, meanThickness, clusterRadius, thin }. location and the entries of thin are { thickness, point, farPoint, face, farFace, direction }, thinnest first. noExit counts samples whose ray found no exit. For the plate with 300 samples: minThickness: 10, between F2.C0 and F2.C1. The value is a sampled minimum: a feature thinner than the sample spacing can be missed, and ray overestimates in wedges and corners. No body: null.

thicknessAt

Wall thickness at one place.

ParameterTypeMeaning
point[x, y, z]The surface point nearest to this point is used.
facestringOr: the minimum, maximum and mean over this face.
opts.samplesnumberSamples on the face.

With point: { distanceToSurface, result: { thickness, point, farPoint, face, farFace, direction }, elapsedMs, truncated }. With face: { min: {...}, max, mean, samples, ... }. Neither is thicknessAt: point [x, y, z] or face id is required. No body: null.

closestPoint

The nearest part of the body to each of many points.

ParameterTypeDefaultMeaning
pointsarrayrequiredUp to 2000 points.
onstring"body""body", "face", "edge" or "vertex".
idsarrayallRestrict face / edge / vertex to these.
knumber1Return the k nearest entities per point as a list.

With on: "body" each result is { signedDistance, inside, nearest: { distance, point, entity, face, uv } } (negative inside, like probe). With the other values the result is the nearest entity of that kind with uv (face) or curve parameter t (edge). For the point (50, 30, 20) above the plate, signedDistance is 10 with entity { kind: "face", id: "F2.C1" }; with on: "face", k: 2 the list adds F2.C0 at distance 20. No body: null.

angles

Dihedral angles of edges and faces, and draft angles.

ParameterTypeMeaning
edges"all" or array of keysPer two-faced edge: { edge, faces, angle, normalAngle, type, min, max, at }. angle is the interior angle through the material (a box edge is 90, a re-entrant edge of an L is 270); type is convex, concave or smooth (normals within 0.5 degrees); min and max are over five points along the edge.
faces[a, b]The angle between two faces: with a shared edge the dihedral angle (sharedEdge, at), else the angle between the normals at their nearest points (angle, normalAngle, distance, parallel).
draft{ pull, faces?, min? }The draft angle of each face (or the listed faces) against the pull direction: asin(n . pull) in degrees over a 5 x 5 grid, as { face, draft, min, max, class }; class is vertical (under 0.01 in magnitude), undercut (negative), parting (over 89.99) or ok. With min, walls below that draft are listed in violations.

At least one of the three is required. For the plate, the straight edges are convex at 90; draft against +Z shows the four sides vertical, F2.C0 an undercut at -90 and F2.C1 the parting face at 90. No body: null.

clearance

Face pairs closer than a minimum distance.

ParameterTypeDefaultMeaning
minnumberrequiredThe distance under which pairs are reported.
a, bentitiesall facesRestrict the pairs to these sets.
opts.includestring"both""gap", "wall" or "both".
opts.limitnumber200Maximum pairs listed.
opts.maxPairsnumber4000Candidate pairs examined, closest boxes first.

Result: { min, count, pairsTested, listedAll, pairs, elapsedMs, truncated } with pairs sorted by distance: { a, b, distance, kind, pointA, pointB }, where kind says what lies between the faces: gap (air), wall (material, for example a hole to the edge of the part, the figure thickness reports) or contact. Pairs of faces that share a vertex are skipped (they touch by construction), so the two faces of a tight V groove are not reported. For the plate with min: 30: the caps at 10 (wall), the hole wall to the left side at 16, and to the front and back sides at 26. No body: null.

symmetry

Mirror symmetry planes and the deviation of the mirrored body.

ParameterTypeMeaning
planesarray[{ origin, normal }]; default: the coordinate axes and the principal axes through the centre of mass.
opts.samplesnumberSample points on the surface (default 600).
opts.tolnumberDeviation under which a plane counts as symmetric (default 1e-4 of the diagonal).
opts.fullbooleanMeasure every sample even after a plane already failed.

Result: { tol, samples, symmetric, best, planes }. Each plane record is { origin, normal, basis, maxDeviation, rmsDeviation, symmetric, exact, worstPoint }: the surface is sampled, mirrored and measured against the body. symmetric lists the planes within tol, best the least deviating, planes all, sorted. A plane has exact: false when it was abandoned early and its maxDeviation is a lower bound. For the plate with a hole the planes normal to Z and Y through the centre of mass are symmetric (deviations 5e-15); the X plane is not. The X plane is listed twice in planes, once through the centre of mass (basis: “axis x through the centre of mass”) and once through the bounding-box centre (“axis x through the bbox centre”), so the example returns four records. No body: null.

extrema

The lowest and highest point of the body along a direction.

ParameterTypeMeaning
dir[x, y, z]Any length; not zero.
ofentityMeasure this instead of the whole body.
opts.samplesnumberGrid size per face (default 16, at most 64).

Result: { direction, min, max, extent, method, exact, samples, ofLabel, elapsedMs, truncated }, where min and max are { value, point, entity, at }: the value dir . p, one point where it is attained, what that point lies on, and everything that attains it (at most 20: faces whose interior reaches it, else edges, else vertices). method: "vertices", exact: true means every face searched is planar and every edge straight, and the values are exact. Otherwise "sampled+refined": curved faces and edges are searched on a grid and refined to about 1e-9 of the cell size; an extreme of a free-form face narrower than the grid spacing can be missed. For the plate along Z: min.value 0 on F2.C0 (and all its edges and vertices), max.value 10 on F2.C1, extent 10. No body: null.

Design rules and manufacturing

profiles

Lists the built-in design-rule profiles and the rule catalogue. No parameters and no tag.

{ "profiles": [ { "id": "fdm-print", "name": "FDM 3D printing", "description": "...", "rules": [
      { "id": "openShell", "title": "Watertight", "description": "...", "severity": "error", "params": [] }, ... ] },
    { "id": "cnc-3axis", ... }, { "id": "injection", ... } ],
  "rules": [ ... ] }

Each rule has id, title, description, severity (error, warn or info) and params: { name, type, default, value, unit, min?, max?, description } where type is number or vec3, value is what the profile uses and default what the rule uses on its own. The three profiles are fdm-print (rules openShell, bodyCount, minWall, overhang, bridge, minFeature, plateContact), cnc-3axis (openShell, minInternalRadius, minWall, undercut) and injection (openShell, draft, uniformWall, minWall).

checkProfile

Runs a profile on a body.

ParameterTypeDefaultMeaning
profilestring or objectrequiredA built-in id, or an inline { id?, name?, rules: [{ id, params?, severity? }] }. Rules not listed do not run; omitted params keep the rule defaults. Unknown profile, rule or parameter, a wrong type or an out-of-range value are errors that list the valid choices.
tagstringmainThe body to check.
partobjectInstead of the tag: regenerate this document privately (through the regen cache; no tag is created) and check it. A part that makes no body answers { profile, noBody: true, errors }.
opts.samplesnumber3000Surface samples for the sampled rules.
opts.maxIssuesnumber100Cap per rule; the rest is counted in summary.truncated.

Result: { profile, ok, issues, summary }. profile is the effective profile with its parameters. ok is true when there is no error-severity issue. Each issue is { rule, severity, message, faces, edges, value, limit, unit, at? }: an actionable sentence with the numbers, the faces and edges by persistent name, the measured value and the limit, and a point to focus on. summary is { errors, warnings, infos, total, rules: [{ rule, severity, issues, passed }], truncated, skippedFaces, samples }. The rules are a first slice and not a certification: some are exact (hole diameters, concave radii, watertightness), some use the display mesh (overhang, bridge, draft), some sample rays (wall thickness) and can miss features thinner than the sample spacing. Sheet-metal rules, user rules and build orientation are not covered. With neither a body nor a part: null.

dfmMinWall, dfmMinInternalRadius, dfmPocketRatio, dfmOverhang, dfmConstantSection

One design-for-manufacture rule each, with the limit as a required argument. They answer with the measured value, where it is (face names, an edge key where an edge is the thing, and a point) and which rule was broken. Replies are deterministic and numbers are rounded to 1e-6.

RequestParametersQuestion
dfmMinWallthreshold (> 0); opts.samplesIs the thinnest wall at least threshold? (the thickness ray method; default 6000 samples)
dfmMinInternalRadiustoolRadius; direction (default [0,0,1], the tool axis)Are all concave corners parallel to the tool axis (within 5 degrees) at least as round as the cutter?
dfmPocketRatiomaxRatioIs depth over width of every closed pocket (planar floor, every boundary edge concave) within the limit?
dfmOverhangdirection (build direction, up), angle (0 to 90, from vertical), minAreaWhich downward faces are steeper than angle from vertical (0 wall, 90 flat ceiling)? Faces on the build plate are ignored.
dfmConstantSectionaxisIs the body a constant extrusion along axis, else where does the section first change?

Common result keys: rule ({ id, <limit>, unit, description }), supported (true), pass, violations (each repeating the rule id, the measured value and the limit). Specific keys: dfmMinWall has threshold, minimum ({ thickness, faces, point, farPoint } or null), samples, truncated; dfmMinInternalRadius has toolRadius, direction, minimum, corners (all, ascending radius, at most 200; kind is fillet or sharp); dfmPocketRatio has maximum and pockets ({ floor, walls, faces, depth, width, ratio, limit, fails, point }, deepest first); dfmOverhang has faces ({ face, overhangAngle, overhangArea, faceArea, supportVolume, point }), overhangArea, supportVolume (a rough estimate); dfmConstantSection has start, end, length, constant and either station ({ position, offset, faces, point, sectionAreaBefore, sectionAreaAfter }) or, when constant, sectionArea and loops.

A body that a rule cannot judge is not guessed at. The reply is { "rule": { "id": ... }, "supported": false, "pass": null, "refusal": { "code", "reason", "faces"? } } with code emptyBody (no faces; all rules), nonAnalyticFaces (a face is B-spline, screw or offset, or an extrusion or revolution of a spline profile: lofts, free-form and most imported bodies; for dfmMinInternalRadius, dfmPocketRatio, dfmConstantSection) or tessellationFailed (some faces did not mesh; for dfmOverhang, dfmConstantSection). Bad arguments are error replies prefixed with the request name (dfmMinWall: threshold must be a positive number). No body: null.

On the plate with a hole: dfmMinWall with threshold: 12 fails with minimum.thickness 10 between F2.C0 and F2.C1; dfmMinInternalRadius with toolRadius: 3 passes with corners: [] (a drilled hole is not a corner); dfmPocketRatio with maxRatio: 4 passes with pockets: []; dfmOverhang upward with 45 degrees passes; dfmConstantSection along Z answers constant: true, sectionArea 5949.734518 and loops 2.

Sketches

sketchAnalyze

Structural analysis of one sketch: exact, structured feedback instead of a bare noClosedProfile.

ParameterTypeDefaultMeaning
featureIdstringrequiredThe id of the sketch feature.
tolerancenumber0.01Near-coincident distance in mm; <= 0 disables.
tinynumber0.001Tiny-segment length in mm; <= 0 disables.
tag or partThe sketch comes from the tag’s regenerated state, or from a private regen of part (the way to analyse a document that made no body, for example one failing noClosedProfile).

Result: { tolerance, tiny, findings, chains, profile }. A finding has a kind, the entities and points it names, and at in sketch coordinates:

kindfires whenextra
openEndan entity end touches nothinggap to the nearest other open end, nearest entity
nearCoincidenttwo points closer than tolerance with no coincident constraintdistance
duplicatetwo entities of the same kind on the same points
overlaptwo collinear lines whose interiors overlap
zeroLengtha curve of length or radius 0 or less
tinySegmentlength under tinylength
branchmore than two entity ends at one pointdegree
isolatedPointa point no entity uses
selfIntersectiontwo entities cross inside their interiors

chains are the connected sets of entities, each { entities, closed, construction }. profile.closedChains counts closed non-construction chains; when it is 0, profile.reason says why: the biggest openEnd finding, { "kind": "empty" } or { "kind": "constructionOnly" }. For the plate sketch: { "tolerance": 0.01, "tiny": 0.001, "findings": [], "chains": [ { "entities": ["e1","e2","e3","e4"], "closed": true, "construction": false } ], "profile": { "closedChains": 1 } }. Errors: sketchAnalyze: featureId must be a string, sketchAnalyze: sketch F9 not found. With neither a body nor a part: null.

sketchFreedoms

What the solver can still move in one sketch.

ParameterTypeMeaning
featureIdstringThe sketch feature id.
tag or partAs for sketchAnalyze.

Result: { dof, solved, points, radii, entities }. dof is the same number as the regen status.dof. points has every point with free: 0 (fixed or determined), 1 (moves along exactly dir, a unit sketch direction) or 2 (any direction). radii lists circles, ellipses and arcs with whether the radius is free. entities lists each entity with the sum of its points’ free plus 1 for a free radius. For the unconstrained plate sketch: dof: 8, every point free: 2, every line free: 4. Errors carry the sketchFreedoms: prefix with the same texts as sketchAnalyze; null without a body or part.

Import

The four import requests read a file into a body and store it under the tag, with the same rules: a failure leaves the tag’s previous state alone, and the reply has the shape of a regen result (errors, components, …, body, surfaces) plus an import object. The imported body has its own face names (I1.F1 and so on for STEP, skp.F<n> for SketchUp) and can be used with every body query.

importStep

ParameterTypeDefaultMeaning
datastringrequiredThe STEP file text. Missing: the error reply importStep: data must be a STEP file as a string.
namestring"part"Name of the import.
heal"off" or objectonHealing options as in heal; healTolerance also works.

The result’s import is { solids, faces, unitScale, warnings, heal: { fixed, remaining, toleranceUsed } }. A file that cannot be read answers body: null and an errors entry ["import", { "code": "parse", "params": { "message": "not a STEP file (missing ISO-10303-21 header)" } }]. Round trip of the plate with a hole through step and importStep: import { "solids": 1, "faces": 7, "unitScale": 1, "warnings": [], "heal": { "fixed": 0, "remaining": 0, "toleranceUsed": 0 } }, volume 59497.345175425646. See STEP.

importSat

data is the SAT file text (required: importSat: data (the SAT file text) is required); name is optional. A failure answers body: null and errors in the same pair shape as the other importers: [ ["import", { "code": "sat.parse", "params": { "message": "bad SAT header (version)", "entity": null, "kind": "", "line": 1 } }] ]. See ACIS SAT.

importSldprt

data is the base64 of a .SLDPRT file (required: importSldprt: data (the .SLDPRT file as base64) is required); name is optional. The result’s import describes the body read (solids, faces, container, schema, …) and the file’s metadata: features (the feature tree with ids, types and dimension values), configurations, material, customProperties, configurationProperties, units, versions, thumbnail (base64 PNG or null), faceAttributes (colour and building feature of each face, by face id) and bodyAttributes. User names and paths recorded in the file are not returned. A failed import still carries the metadata in import when the file’s container opens. A file that is not a SolidWorks part answers errors [ ["import", { "code": "container.format", "params": { "message": "neither an OLE2 compound file nor a SolidWorks block container" } }] ]. See SolidWorks.

importSkp

data is the base64 of a .skp file (required: importSkp: data (the .skp file as base64) is required); name is optional. opts takes hidden (boolean), maxFaces (number) and up ("z" default, "y" or "yFlip": how the file’s axes map onto the kernel’s; another value is an error reply). The result is a surface body: one planar face per SketchUp face (holes kept), vertices welded, and import.faceMaterials listing the colour index of each skp.F<n> face. A file that is not a SketchUp file answers errors [ ["import", { "code": "container.magic", "params": { "message": "not a SketchUp file (bad header magic)", "offset": 0 } }] ]. In a module built without the skp feature the request answers an error reply that begins notImplemented: importSkp. See SketchUp.

Text, fonts and tables

These requests use no tag. Two fonts (gauge, engrave) are compiled in; further fonts are registered for the session. Fonts are session state, shared by all tags, and are part of the regen cache key by hash. See Text and fonts.

textMetrics

ParameterTypeDefaultMeaning
stringstringrequiredThe text.
fontstringgaugeA font name.
heightnumberrequiredCap height in mm; a non-positive value is textBadHeight: text height must be a positive number.
spacingnumberLetter spacing.

Result: { advance, bbox, width, capHeight, chars, advances, warnings }: the advance width, the ink box [minx, miny, maxx, maxy], its width, the number of characters and the advance of each. For “Hello” at height 5: advance 12.129, width 11.386, chars 5.

textOutline

Takes the fields of a sketch text entity (string, font, height, at, anchor, angle, spacing, mirror, arc) and returns the outline: { regions, bbox, area, warnings }, where regions is a list of { outer: [[x, y], ...], holes: [[[x, y], ...]] } polylines in sketch coordinates. “Hi” at height 5 gives 3 regions (H, the stem of the i and its dot), bbox [0, 0, 4.157, 5.121] and area 10.696.

loadFont, unloadFont, listFonts, subsetFont

RequestParametersResult
loadFontname, data (base64 TTF or OTF), replace?{ name, hash, builtin, family, bytes, glyphs, chars, unitsPerEm, capHeight, outlines, supported, coverage, warnings, alreadyLoaded, replaced }. Loading the same name and file again answers the same record with alreadyLoaded: true. Errors: fontBadData, fontBadName, fontReserved, fontNameConflict (same name, other file, no replace), fontTooLarge, fontTooMany.
unloadFontname{ name, unloaded }; unloaded is false for a name that was not loaded.
listFontsnone{ fonts: [...] }, the built-in fonts first; each entry has the loadFont fields.
subsetFontname, text{ name, hash, bytes, glyphs, data, warnings }, with data the base64 of a font file holding only the glyphs of text. An unknown font is the error reply textFontNotLoaded: font "x" is not loaded; load it with {type:"loadFont", ...}.

Subsetting gauge to “Hi” gives a 756-byte font with 3 glyphs; loading that as mini answers { "name": "mini", "builtin": false, "bytes": 756, "glyphs": 3, "chars": 2, "unitsPerEm": 1000, "capHeight": 700, "outlines": "glyf", "supported": ["Basic Latin"], "coverage": [ { "block": "Basic Latin", "mapped": 2, "of": 95 } ], "warnings": [], "alreadyLoaded": false, "replaced": false, ... }. A sketch text entity that names a font that is not loaded fails its sketch with textFontNotLoaded.

threadData

The thread tables, for dropdowns and for scripts.

ParameterTypeMeaning
standardstringA standard id: metric (coarse), metric-fine, UNC, UNF, BSP, NPT, Tr, Acme; aliases (ISO, G, bspp) and any case work.
sizestringA size designation (M6, 1/4-20, G1/4).

Without standard: { units: "mm", standards: [ { id, description, count, sizes: [...] } ] }. With it: { standard, units, sizes: [...] } with every number for each size. With both: the one entry. A size record is { size, standard, major, pitch, tpi, minorInternal, minorExternal, pitchDiameter, angle, tapDrill, tapDrillName?, classInternal, classExternal, tapered }:

{ "type": "threadData", "standard": "metric", "size": "M6" }
{ "standard": "metric", "units": "mm", "sizes": [ { "size": "M6", "standard": "metric", "major": 6, "pitch": 1, "tpi": 25.4,
    "minorInternal": 4.9175, "minorExternal": 4.7731, "pitchDiameter": 5.3505, "angle": 60, "tapDrill": 5,
    "classInternal": "6H", "classExternal": "6g", "tapered": false } ] }

major is the nominal diameter (for NPT the pipe outside diameter); minorInternal is the crest of an internal thread and minorExternal the root of an external thread; tapDrill is the bore an internal thread is cut into. An unknown standard or size is an error reply that lists the known choices (unknown thread standard zzz (known: metric, metric-fine, UNC, UNF, BSP, NPT, Tr, Acme)). A standard or size that is not a string is threadData: <key> must be a string.

See also

Errors

The kernel reports problems at four levels: the call itself can fail (a trap), the request can be refused (an error reply), the request can run and report a failure in its result, and a regen can run and report failures per feature. This chapter describes each level, how hints are attached, and lists the codes that the kernel can emit.

The levels

LevelWhere it showsExample
TrapThe call to ck_request throws a WebAssembly.RuntimeError; ck_panic got the text first. The instance is unusable; the host starts a new one (Call it from Node). The native service, when built with the service profile, answers HTTP 500 and closes the session (a release build aborts the process instead).an internal panic
Error reply{"ok": false, "error": "<message>", "ms": ...}. error is always a string.noState: nothing regenerated yet
Failure in the resultok is true; the result says the operation failed.{"error": "notFound"}, an issues list, an import with body: null
Feature errorok is true; the regen result has errors (and warnings) with one entry per failed feature.["F4", {"code": "holeInvalid", ...}]

The first rule of thumb: ok: false means the request was not carried out and nothing changed. A regen with failed features is not a failed request: ok is true, the tag is replaced with the partial result, and the failures are data.

Error replies

The message is free text, but the part before the first colon is stable and names the request or the code, so clients can match on the prefix.

Envelope and state

MessageCause
bad request: the body must be JSON {id, msg}The body is not valid JSON.
bad request: msg must be an objectThere is no msg key, or it is not an object (a top-level array or string gives the same).
message without a typemsg.type is missing, empty or not a string.
unknown request <type>No such request type; the type is echoed as sent.
noState: nothing regenerated yetA request that needs a tag was sent for a tag that has no state. Clients match on the prefix noState.
invalid part: Formatregen, matchEdges, refDiff or checkProfile/sketchAnalyze/sketchFreedoms with a part that is not a part document (not an object, wrong format, or features not an array). The tag keeps its state.

Arguments of single requests

Message (prefix)RequestCause
drag: face, point and target are requireddragface is not a string, or point / target is not a triple of numbers.
bad sketch frameconvertframe is not an object with numeric triples o, x, y, z.
sketchOffset without a distancesketchOffsetdistance is missing or not a number.
drawing: a view needs a name (front, back, left, right, top, bottom, iso) or x and ydrawingA view has neither a known name nor both x and y.
massProps: densities has N entries but the body has M lump(s) (expected M)massPropsdensities does not have one entry per lump.
importStep: data must be a STEP file as a string, importSat: data (the SAT file text) is required, importSldprt: data (the .SLDPRT file as base64) is required, importSkp: data (the .skp file as base64) is requiredimportsdata is missing.
importSkp: opts.up must be "z", "y" or "yFlip", got ...importSkpUnknown opts.up.
cannot inspect nothing, cannot inspect <kind>, <kind> not found, vertex without a point, no vertexinspectSee Queries.
<request>: ...measurement and analysis requestsA bad or missing argument, named after the request: angles: edges ('all' | [keys]), faces [a, b] or draft {pull} is required, closestPoint: at most 2000 points per request, closestPoint: on must be 'body', 'face', 'edge' or 'vertex', extrema: dir must not be zero, probe: at most 2000 points per request (and rays), probe: points [[x, y, z], ...] or rays [{origin, dir}, ...] is required, probe: ray.dir must not be zero, section: plane.normal must not be zero, sections: axis must be 'x', 'y', 'z' or [nx, ny, nz], sections: between 1 and 1000 positions, symmetry: plane.normal must not be zero, thickness: the body has no faces, thicknessAt: point [x, y, z] or face id is required, clearance: more than 4000 faces, maxDistance: nothing to sample. Entity arguments that cannot be read give unknown entity ..., no lump N (the body has M) or expected a face / edge / vertex id, a point, a lump or ....
dfmMinWall: threshold must be a positive number (and the like)dfm*The required limit is missing or out of range; the message starts with the request name.
checkProfile ..., profile needs ..., rule <id>: ...checkProfileUnknown profile, rule or parameter, a wrong type or a value out of range; the message lists the valid choices.
sketchAnalyze: featureId must be a string, sketchAnalyze: sketch F9 not found (and sketchFreedoms: ...)sketch analysisMissing or unknown featureId.
textBadHeight: ..., textEmpty, textFontNotLoaded: font "x" is not loaded; ..., fontBadData: ..., fontBadName, fontReserved, fontNameConflict, fontTooLarge, fontTooMany, fontSubsetFailed: ...text and font requests<code>: <message>; see Text and fonts.
unknown thread standard zzz (known: metric, ...), threadData: <key> must be a stringthreadDataUnknown standard or size, or a non-string argument.
TODO(rebuild): <what> needs the geometry engine (no hook installed)inspect (with a body, for kinds other than sketch), importSkp in a module built without the skp featureThe request type exists but this case is not implemented. The wording is misleading: no hook is missing.

Failures in a result

These are answered with ok: true.

ResultRequestCause
nullmost body queriesThe tag has state but no body.
{ "error": "missingReference" }drag, refCurveThe reference does not resolve, or there is no body.
{ "error": "dragNoComponent" }, { "error": "dragFixed" }dragThe face belongs to no inserted part; the part is fixed.
{ "error": "notFound" }, { "error": "notCurve" }curvatureAt, combUnknown face or edge; a reference that is not a curve.
{ "error": "cutNoEffect" }drawing (per view)The section plane misses the body.
{ "error": "offsetTooLarge" }sketchOffsetAn arc or circle would shrink to nothing.
{ "ok": false, "error": { "code", "params" } }bodyBooleanThe boolean cannot be done; the object has the form of a feature error.
{ "supported": false, "pass": null, "refusal": { "code", "reason" } }dfm*The body is not one the rule can judge: emptyBody, nonAnalyticFaces, tessellationFailed.
body: null and an errors entryimportsThe file could not be read. The entry is ["import", { "code", "params" }] for every importer (codes such as parse, container.magic, container.format, sat.parse). See Import and export.
issues listvalidate, heal, checkProfileFindings about a body; see Topology and geometry checks.
errors listrefDiffRegen failures of either document as [featureId, code], with the code as a plain string.

Feature errors in regen

Each failed feature has one entry in errors: [featureId, { "code": "<code>", "params": { ... } }]. If a feature has no id, the id is the empty string. An id appears once; a later entry for the same feature replaces an earlier one. A failed feature changes nothing: the body is as it was before the feature, and later features run on it.

params is an object that depends on the code. These conventions apply to many codes:

  • hint: one sentence on what to change. Present on the codes whose cause the kernel can name (holeInvalid, booleanFailed, invalidValue for a scale factor, threadSizeUnknown, the loft codes, …). Show it first when reporting the failure.
  • detail: a sentence naming the faces or edges involved, often with numbers: F3.B0: spring leaves its face away from its edges.
  • field: for invalidValue and missingReference, which field of the feature is wrong (thin.thickness, regions, endRef).
  • Numbers that say how far off the request was: max (largest blend radius that fits), limit, minRadius, maxThickness, maxHeight, budgetMs, elapsedMs.
  • maxSize: { "param", "value", "unit" } on a refusal because a size is too large: param is the feature field (a dotted path for a nested one, thin.thickness), value the largest value of it that builds (the sign of the request kept, so a face pushed in by -12 gets -9.96), unit mm or deg. The hint says the same in words. Given only for a value the kernel built with its own checks (or the exact bound of a closed-form check), so a client can set the field to it without parsing text; when no such value is found it is absent. Given today by shell (thickness), moveFace (distance), draft (angle), a drafted extrude (draft), a thin wall (thin.thickness), hole (cboreDepth, cskDiameter) and knurlBand (depth); not yet by fillet and chamfer.
  • name and nearest: for a body or face name that does not resolve, with up to three existing names that are close.
  • ref, candidates, hint: for a face id that no face carries (missingReference from shell, thread, combine, deleteFace, moveBody, pipeCut, fullRound, the surface features and projectCurve). candidates lists up to six live face ids, those of the same feature first and the closest name first, or the three closest names of the whole model when the feature has no face left; hint says which of the two it is. A repair is a one-field edit: replace ref by one of candidates.
  • faces, gone, candidates, neighbours, hint: for missingEdge on an edge pick {faces, at} that no edge joins any more. gone lists the names no face carries (with candidates as above); when both faces exist, neighbours lists the faces the first one now meets.

Because a failure removes a feature’s output, the next features that depend on it fail too. The errors are in feature id order as strings, but the cause is the first failing feature in document order.

Time budgets

featureBudgetExceeded and regenBudgetExceeded report that a time limit stopped the work. When the limit of a feature (opts.featureTimeMs, default two minutes) has run out, a feature that failed at that moment reports featureBudgetExceeded instead of its own code, unless its own code already ends in BudgetExceeded (a boolean stopped by the limit keeps booleanBudgetExceeded); its result is not applied. When the limit of the whole document (opts.regenTimeMs) has run out, the running feature and every later one report regenBudgetExceeded; the later ones are not run. The params are budgetMs, elapsedMs, hint and, if the feature had failed for another reason, cause (that code). A feature limit that has already passed when a feature starts (a few microseconds, for instance) is reported as regenBudgetExceeded with the feature limit’s hint. Budgets need a host clock (Protocol overview).

Budget failures are not cached. A failure caused by a time budget is not stored in the regen cache, so a later regen of the same part runs again with its own budget. Builds before this change replayed the stored error (and body: null) on the same instance; opts.noCache: true was the workaround.

Codes of the driver and of references

CodeCause
unknownFeatureThe feature’s type is not a known type. params.type is the type as given (empty if missing).
missingReferenceA reference does not resolve: a face, edge, plane, axis or body name that does not exist, a required reference field that is absent, or a feature that needs a body when there is none. Often has field, face, ref or name and nearest.
missingSketchThe feature’s sketch is absent or names no sketch that was regenerated before it (also when that sketch failed).
badExpressionA numeric field or constraint value is an expression that does not evaluate: syntax error, unknown name or function, or a variable that is itself invalid or part of a cycle.
invalidValueA value is out of range or the wrong shape: a radius, count, angle, factor or distance that must be positive, an unknown option value, a mix of options that does not work together. params has detail, field or hint.
noClosedProfileThe sketch has no closed profile to build from. sketchAnalyze says why.
nothingToCutThe feature modifies a body (cut, shell, rib, draft, mate, …) but the document has no body yet.
noBodiesdeleteBody with no body in the document.
noFacesmoveFace, pressPull, or draft with a valid neutral plane, was given an empty faces list.
noSeedsA pattern or mirror has an empty seeds list or nothing to copy.
unsupportedAn option of a fillet or chamfer that the kernel does not build. params.what names it (chamfer <type>, fillet profile <name>, fillet <filletType>). Any filletType is refused this way, including "circular": filletType: "circular" gives unsupported { what: "fillet circular" } although circular is also the name of the default profile. Leave filletType out, or use "fullRound".
TODO(rebuild): <what> needs ck-opsThe feature type is accepted but not implemented (see Regeneration), or the particular option is refused. The code is this whole sentence.
healedNot an error. With autoHeal, the feature’s body had validation issues and was repaired; params has fixed, codes and remaining. It is listed in errors.

The variable table of the part (variables) is resolved before the features run. A variable with an invalid name, one that depends on a cycle, and one whose expression does not evaluate are all left unset in the reply, so no code of their own is reported; the features that use them fail with badExpression.

Reference planes and axes

CodeCause
planeLineNormalThe perpendicular plane mode: the axis line is parallel to the base plane’s normal.
planePointsInLineThree points (or the two directions of a frame) lie on one line, so they define no plane.
planePointOnLineThe linePoint mode: the point lies on the line.
planesParallelTwo planes are parallel where their intersection line (an axis, an angle plane) is needed.
planeNotTangentThe tangent mode: the face cannot be tangent to the given plane or line (for example a cylinder axis not parallel to the plane).
missingPathThe plane mode normal or normalCurve, or a sweep: the path is not given or does not name a usable open sketch.
curvesNotPlanarThe curve plane mode: the curves do not lie in one plane. params.dev is the deviation.
curvesStraightThe curves are straight, so they give no unique plane.
faceNotCylindricalThe axis feature was given a face that is not a cylinder.

Extrude, revolve and profiles

CodeCause
extrudeRegionNoneregions matched no closed region of the sketch (an empty list, or ids that are no region’s outer boundary). It never falls back to “all regions”. params.regions lists them.
extrudeRegionUnknownregions names ids that are no entity of the sketch. params.ids.
unknownEndThe end condition is not a known one. params.end.
upToFaceBehind, upToPointBehindThe end face (or the plane through the end point) is not ahead of the whole profile in the extrusion direction, or is parallel to it.
upToFaceOutsideupToFace: the face does not cover the whole profile along the direction. params.face.
upToFaceUnsupportedThe end face is not planar. params.face.
endClipFailedThe boolean that trims a slanted end failed. By default it appears only as the reason of an endConditionFallback warning; with strictEnd: true it is the error. params.detail.
upToNextNoneupToNext cut: no face to stop at.
upToNextOpenupToNext add: the tool never meets the body.
missingAxisA revolve has no axis, or its axis does not resolve to a line of the sketch.
profileCrossesAxisA revolve profile straddles the axis. params.detail.
thinTooThickA thin-wall extrude or revolve: the thickness is too large for the profile (a corner or curvature limit). params: limit (curvature or corner), minRadius, maxThickness, thickness, face.
offsetFitFailedThe offset curve of a thin-wall profile could not be fitted within tolerance.
zeroDepthAn extrusion or twisted extrusion with no depth (below 1e-9). The extrude feature itself replaces a depth of zero or less by 1e-6, so this code shows only on paths that do not; the extrude feature raises the warning extrudeZeroDepth instead (see Warnings).
emptyProfile, openProfileThe profile has no region or is not closed.
extrudeDirectionInPlaneThe extrusion direction lies in the sketch plane.
zeroAngle, revolveAxisNotInPlane, revolveDegenerateA revolve with a zero angle, an axis that is not in the sketch plane, or a profile that is degenerate about the axis.
draftTooLargeA drafted extrude: the taper closes to a point, or an edge turns over. params.detail; for an extrude of one circle params.maxHeight is the greatest depth that works.
draftUnsupportedA twisted extrude combined with a draft or upToNext; a drafted rib whose sketch is not one straight line; a draft feature whose direction is skewed against the neutral plane or whose neutral plane cuts through the profile; or a face that is not a plane, a cylinder or a cylindrical cone (params.detail names the face and its surface kind).
twistUnsupportedA twisted extrusion whose direction is not the sketch normal.

Two warnings of the end conditions are in Warnings: endConditionFallback (an unreachable end reference ran as a blind extrude of depth, unless the feature sets strictEnd: true, which makes the four unreachable codes above errors) and endRefRelinked.

Booleans and bodies

CodeCause
booleanFailedThe result of a boolean could not be assembled into a valid solid. params.hint suggests moving the tool by about 0.01, uniting touching bodies first, or giving the feature a fuzzy tolerance / autoFuzzy: true. When the cause is known: hostFace, toolFace, gap (two nearly coincident free-form walls); or faces, issue (openEdge, nonManifoldEdge, badPairing) and at (the faces and a point at the first bad edge).
booleanTangentThe result has an odd Euler characteristic: the operands touch tangentially. params: euler, hint.
booleanBudgetExceededThe boolean stopped retrying because it had already run long. params: budgetMs, elapsedMs, hint.
booleanVolumeMismatchThe boolean produced a valid body whose volume or box is impossible for the operands (material dropped or added); the body is left as before. params: what (volume or box), expected_min, expected_max, got and hint.
cutNoEffectA cut that removes nothing (a tool that misses the body). The body is unchanged. It is reported in errors.
combineEmptycombine intersect of lumps that do not overlap.
bodyNameConflictA body name that a live body already has. params: name, features (the feature that made that body and the one that asked for the name).
ambiguousBodycombine.target names several bodies. params: name, candidates ({ lump, face }).

Holes and threads

CodeCause
holeNoPointsThe hole’s sketch has no point entities.
holeInvalidNo usable hole size: an unknown size, a non-simple hole without a size, or a diameter that is zero or negative. detail and hint say which.
holeCboreInvalidThe counterbore diameter is not larger than the hole, or its depth is not positive or too deep. params: cboreDiameter, cboreDepth, holeDiameter, hint.
holeCskDiameterThe countersink head diameter is not larger than the hole, or the cone angle is outside 0 to 180 degrees.
threadSizeUnknownThe thread standard or size is not in the tables. params: standard, size, suggestions (the nearest sizes, or the known standards), hint.
threadFaceNotCylinderThe thread face is not cylindrical. params: face, surface, hint.

Patterns, moves and pipes

CodeCause
moveFaceFailedA face move or offset produced no valid body. params.detail; for a curvature or thin-gap limit also limit, minRadius, maxThickness, face.
moveFaceUnsupportedA face move of a surface or option the kernel does not offset.
pressPullUnsupportedA pressPull of a face that is not flat, or of a face of a surface body. params.detail. A run that cannot be built is moveFaceFailed (with maxSize for the distance), a draft that closes the face is draftTooLarge.
alignPipeCutOneBodypipeCut edges that belong to different bodies.
pipeCutFailedThe pipe cannot be built: an edge without length, or an edge type that is not supported. params.detail.
pipeCutNothingLeftThe pipe removes every face.
pipeCutRadiusThe pipe radius is larger than the bend radius of an edge, so the tube folds over itself. params.max is the largest radius that does not.

Assemblies and mates

CodeCause
insertPartMissinginsertPart without a valid part document.
insertPartErrorsThe inserted part has errors. params.detail is <feature>: <code> of the first one.
mateConflictThe solver rejected the mate; it is dropped and the components return to the pose before it. params.mates lists the mate and its neighbours.
mateGeometryThe faces or edges of the mate have no geometry the mate kind can use.
mateSameBodyBoth sides of the mate belong to the same component.
mateFixedBoth components are fixed, or the mate needs a floating component (for rackPinion the rack).

Ribs and lips

CodeCause
ribNeedsOpenSketchThe rib’s sketch is not one open chain.
ribNoContactThe rib’s profile does not touch the body.
lipFacelip was given no faces, or none of them exist.

Blends: fillet, chamfer

CodeCause
missingEdgeA fillet or chamfer pick {faces, at} does not resolve to an edge.
blendFailedThe blend could not be built. params.detail.
blendOverflowThe blend leaves its faces: the radius is too large for the faces it rolls on. params.detail; max is the largest radius that fits, when it can be computed.
blendG2TooLargeMaxThe same for a curvature-continuous fillet. params: max, shape.
blendSizeNo blend fits between the two faces.
variableRadiusMismatchA variable-radius fillet gives two different radii at one shared vertex. detail names both radii and the vertex.
blendCornerThe corner patch of a vertex with several blended edges cannot be built (the edges are not perpendicular). params.hint: fillet concave and convex edges in separate features.
blendNonManifoldA free-form blend met an edge that does not have exactly two faces.
blendTolerantEdgeAn edge of imported geometry carries a tolerance, so there is no exact intersection to roll along. params.detail names the edge and the tolerance.
blendTooLargeA vertex chamfer distance reaches the far end of an edge, or the contact line of an interpolated blend falls outside its face.
blendUnsupportedA blend on an edge type or configuration that is not built (a vertex chamfer on curved edges).
chamferVertexEdgesA vertex chamfer needs a vertex of exactly three edges.
filletRhoA conic fillet rho outside 0 to 1.
filletShapeA curvature-continuous fillet shape outside the allowed range.
fullRoundUnsupportedA full-round fillet with the same face twice, or a centre face that is not adjacent to both sides.

Shell, offset and draft

CodeCause
shellTooThickThe wall is too thick: an offset passes the centre of curvature of a face (limit: "curvature"), or two faces are closer than twice the wall (limit: "thin"). params: detail, limit, minRadius, maxThickness (a safe thickness), face.
shellFailedThe shell could not be built; curvature was not the limit, or the boolean failed.
shellUnsupportedAn opened face of a shell is not planar.
offsetUnsupportedA shell of a surface or edge type that the offset cannot rebuild. params.detail, and a hint when the cause is a fillet on a drafted edge (shell before the fillet, or remove the draft). A face move reports the same cause as moveFaceUnsupported.
offsetTooLargeA shell offset reaches the centre of curvature of a face. Carries the same limit params as shellTooThick. (sketchOffset uses the same name for an arc or circle that would vanish, in its result.)
offsetDegenerateAn offset met an edge that reverses (detail: “an edge reverses”). The offset code is offsetDegenerate; a shell reports it as shellTooThick, and a face move reports a failed offset as moveFaceFailed with this text in detail.
draftParallelFaceA draft of a face parallel to the neutral plane.
draftTangentFacesTwo faces of the draft are tangent to each other.
draftAxisNotParallelA cylinder or cone face whose axis is not parallel to the pull direction.
draftFailedThe draft could not be built; no interior point on a face.

Loft, sweep and helix

CodeCause
loftProfilesFewer than two usable profiles.
loftProfileA loft section sketch does not give exactly one profile: it has several closed profiles, or (for a surface loft) is not one open chain.
loftProfileOpenA solid-loft section is not closed.
loftProfileNotPlanarA section is not planar.
loftProfileSelfIntersectA section’s outline crosses itself. detail, hint.
loftSectionTooSmallThe same, with a section small against the loft length.
loftInvalidResultThe solid built from the sections failed validation under every matching strategy. detail, hint.
loftFailedThe loft could not be built (for example guide curves with a point section, an unsupported guide influence). detail, hint.
loftTangentEdgesAny truthy startTangent, endTangent, startContinuity or endContinuity on a loft. The check runs before the loft is built and always fails: tangency to adjacent faces is not available. Remove the fields.
loftGuideInvalidA guide cannot be used: it is not a curve or has no length, two guides touch a profile at the same point, or the guides cannot be matched to the sections. detail says which.
loftGuideMissA guide misses one of the profiles (detail: “the guide misses profile N”).
loftGuideOrderA guide meets the profiles out of order, or the guides meet the profiles in different orders.
loftCentreLineInvalidThe centre line is not a single open chain of supported curves in a sketch.
loftCentreLineKinkThe centre line has a corner; its pieces must run on tangentially.
loftCentreLineTightThe centre line bends too tightly for the sections.
loftCentreLineReachThe centre line does not reach a profile.
loftCentreLineApexA curved centre line with a point (apex) end.
loftCentreLineGuidesA curved centre line together with guide curves.
sweepPathInvalidThe path sketch is not one connected open chain of supported curves.
sweepProfileNotNormalThe profile plane is not nearly perpendicular (within 15 degrees) to the path at its start.

| sweepFailed | A guided sweep whose profile is not valid. | | sweepGuidesCount | More than two guides. | | sweepGuideStretchTwo | Stretch mode needs exactly two guides. | | sweepGuideNotTouching | A guide does not touch the profile. | | sweepGuideNotAlong | A guide does not advance along the path direction at all, so the section planes never meet it. | | sweepGuideShort | A guide advances along the path but ends before a section plane reaches it. | | sweepGuidesSamePoint | Two guides meet the profile at the same point, or coincide at a section. | | sweepGuideDegenerate | A guide is not a curve or has no length. | | sweepGuideOnPath | A guide lies on the path itself at a section, so it gives nothing to scale or turn by. | | sweepGuideMissing | A guide reference does not resolve to a curve. | | sweepGuidesTwist | Guides together with a twist. | | helixNeedsCircle | The helix sketch has no circle to take the radius from. |

Curves

CodeCause
editCurveNoInputeditCurve with no curves.
editCurveInputMissingA curve of the list does not exist. params.curve.
editCurveDegreeThe degree is outside 2 to 9. params: min, max.
editCurveFitFailedNo curve could be fitted.
editCurveNotChainThe curves do not form one chain.
editCurveNotSmoothThe chain has corners and corners were not kept. params.angle.
editCurveTooFewPoints, editCurveTooManyPointsThe control point count is below its minimum or above the limit.
editCurveWeightA weight is not positive. params.entry.
editCurveNoPlaneThe planar option without a plane.
projectCurveNoFacesprojectCurve with no body or sheet to project onto.
projectCurveNoInputNo curve or sketch given, or fewer than two points.
projectCurvePlaneThe input curve does not define a projection plane.
projectCurveMissesThe projection hits no face.
projectCurveSeveralThe projection gives several separate chains; params: count, points.
projectCurveFailedThe projected curve could not be fitted. params.detail.

Surfaces

CodeCause
knitNotClosedknit with solid requested, but the sheets do not close; params lists the open points.
knitNearMissknit: two edges that should be joined diverge by more than 100 tolerances at their midpoints (detail: “edges diverge: …”).
fillInvalidThe edges of a fill do not form one chain, or the patch is not a valid face.
fillNotClosedThe chain of a fill is open.
fillFailedThe patch of a fill is not a valid face (a parameter area of zero). detail.
extendNotBoundaryextend of an edge that is not an open boundary edge.
extendNoTargetThe extension never reaches its target.
extendPointBehindThe extension target lies behind the edge.
extendFoldsThe extension would fold.
extendUnsupportedThe sheet or edge is not one the extension handles: a boundary shared with other faces (only single-face sheets are extended), or an edge that is not a straight line of a planar sheet.
freeformOneFaceA freeform edit with control point edits on more than one face.
freeformEntryInvalidAn edit entry is invalid. params.entry (1-based).
freeformEntryPlaneAn edit entry has no usable plane. params.entry.
freeformCrossesThe edited surface would cross other faces.
freeformNotSymmetricA symmetric edit whose control net is not symmetric.
rebuildPeriodicFacefreeform rebuild of a periodic face.
rebuildTooFineThe rebuild asks for more than 50 spans.
rebuildFailedThe rebuild could not fit a surface.
thickenFailedThe thickened body is not closed.
thickenReachThe thickening offset cannot reach across an edge.
thickenTooThickAn edge vanishes at this thickness.
trimNoIntersectionThe tool does not cut the surface.
trimPieceLoopThe kept piece of a face could not be closed into a loop. The trim is not applied.
trimNothingLeftNothing remains on the chosen side.

Warnings

warnings has the same shape as errors and means the feature ran. A client shows them as notes.

CodeCause
booleanFuzzyThe result depends on a fuzzy tolerance. params.tolerance is the value that decided it.
endConditionFallbackAn unreachable end reference ran as a blind extrude. params: end, reason, fallback, depth, and the params of the reason.
extrudeZeroDepthA blind or mid extrude has a depth of zero or less, or none (also when an expression evaluates to 0). It was built as a sliver of 1e-6 mm, as the reference does, which is not a usable solid and can make a later union fail with booleanFailed / openEdge. params: depth, built, hint.
sheetCutFallbackA plain extrude cut of a folded sheet was tried as a sheet cut, which refused, so it ran as an ordinary cut of the solid; the part is no longer an unfoldable sheet (no flat pattern, no bend table). params: detail, hint, reason (the code of the sheet-cut refusal), reasonDetail (its detail, when it has one).
endRefRelinkedThe end face id no longer exists; the face was found again. params: from, to.
holeDowngradedA counterbore or countersink was drilled as a simple hole because its step or cone dimension is missing. params: requested, built, missing, detail, hint.
threadDiameterMismatchThe hole or shaft diameter does not suit the thread. params: expected, actual, size, standard, internal, nearest, hint.
threadModelFallbackA modelled thread could not be built and stays cosmetic. params: reason, hint.
threadNotCarriedA pattern or mirror copy could not carry a thread over. params: thread, face, reason, hint.
cornerNotTangentBlended edges meet at a corner that is not tangent. params.deviation in degrees.
filletRadiusApproximatedA fillet used an approximated radius.
unknownFieldA feature carries a field its type does not read, usually a misspelling. params: fields (the names, in document order), suggest (only for names close to a known field: {"depht": "depth"}), detail, hint. See misspelled fields.
textTooSmall, textMissingGlyph, textTruncated, textOverlappingContours, textOverlap, textSpacingAdjustedText sketch notes; see Text and fonts. params: entity, detail.

Text and font codes

Sketch features with text can fail with textEmpty (empty string), textNothingToDraw (only blanks or unknown letters), textFontNotLoaded, textFontMismatch (fontHash does not match the loaded file), textBadHeight (not a number in 0 to 1e5), textBadArc (radius not positive), textBadPath (the path of a text on a path is not a curve of the sketch or has no length) and textBadValue (a position, angle or spacing is not finite, or spacing is outside 0 to 20). Loading a font can warn with fontKerningIgnored, fontLigaturesIgnored, fontVariableDefaultOnly, fontCollectionFirstFace, fontCffApproximated, fontNoCapHeight, fontOverlappingContours, fontEmbeddingRestricted, fontNoSubsetting and fontNoLatin. Text and fonts gives the causes.

Notes on specific codes

  • An insertPart whose nested part is empty or has no solid body is not an error: it adds no component.
  • The badName and cyclicVariables codes are produced inside the variable resolver but are not put in the reply (see above).
  • healed is listed under errors although it marks a successful repair.
  • refDiff reports regen failures as [featureId, code] with a string code, not the { code, params } object.
  • An import of a SAT file reports its failure as an object in errors, not the pair form.

See also

The native service

ck-native is an optional local HTTP service that runs the same request dispatch as the wasm module, outside the browser. This chapter covers what it is for, how to start it, its HTTP interface, authentication, limits, and how the TypeScript client uses it.

What it is for

The service wraps ck_server::handle, the function behind the wasm entry point. A request body is the same {"id":..,"msg":{..}} text that you pass to the module, and the reply is the same framed reply (see replies and buffers). Nothing in the protocol changes; only the host does.

Reasons to use it:

  • Heavy parts regenerate natively, without the wasm linear-memory ceiling and without the wasm runtime’s overhead.
  • Each session runs on its own operating-system thread with a 256 MiB stack by default, so deep recursion that would be tight in a worker has room.
  • A session keeps its kernel state between requests, exactly like one wasm instance: a regen followed by a query on the same tag works.

What it is not:

  • It is not a remote or multi-user server. It binds to 127.0.0.1 only, speaks plain HTTP, and is meant for the person logged in to the machine.
  • It is not a different kernel. There is no separate native protocol; the message types, errors and results are those of the wasm module.
  • It is not required. Everything works with the wasm module alone; the client falls back to it (see the TypeScript client).

Build and start

The crate is crates/ck-native and produces a binary named ck-native. Build it with the service profile, which has the optimisations of release but unwinds on panic instead of aborting:

cargo build --profile service -p ck-native
./target/service/ck-native

On start it prints three lines to standard error: the version and address, the token file path, and the allowed origins. The default address is http://127.0.0.1:7461.

FlagDefaultMeaning
--port N7461TCP port on 127.0.0.1, 0 to 65535. 0 lets the system pick one; the chosen port is printed. A larger number is refused.
--config-dir DIRsee belowDirectory for the token, paired clients and pairing code.
--allow-origin URLnoneAdd an allowed browser origin. Repeatable.
--site-origin URLnoneSynonym for --allow-origin.
--max-body-mib N64Largest request body, in MiB.
--max-reply-mib N1024Largest reply body, in MiB.
--max-sessions N8Sessions that may exist at once.
--idle-secs N600A session idle this long is removed.
--stack-mib N256Stack size of each session’s worker thread.
--quietoffDo not log requests.
--print-tokenoffPrint the shared token and exit.
--pairoffWrite a one-time pairing code, print it and exit.
-h, --helpPrint usage.

Two subcommands work on the config directory and exit: ck-native clients lists paired clients (id, label, origin, creation time), and ck-native revoke <id> removes one. An unknown flag prints the usage and exits with status 2.

The config directory is, in order: CK_NATIVE_CONFIG_DIR, $XDG_CONFIG_HOME/ck-native, $HOME/.config/ck-native. The listener always uses 127.0.0.1; there is no flag to change the address.

The origin http://localhost:5173 is always allowed. --allow-origin adds to it (a trailing slash is ignored; comparison is case-insensitive).

HTTP interface

Every response carries Content-Length, Cache-Control: no-store and X-Content-Type-Options: nosniff. Connections are HTTP/1.1 keep-alive. Request bodies must have a Content-Length; Transfer-Encoding (chunked) is refused. Any query string is ignored.

Errors are JSON of the form {"error":"message"}.

Method and pathAuthRequestSuccess reply
GET /pingnonenone{"service":"ck-native","protocol":1}
POST /pairone-time code{"code","origin","label"}{"token","id","origin","label"}
GET /versiontokennoneJSON, see below
POST /sessiontokenempty body{"session":"<id>"}
POST /session/<id>/rpctokena protocol messagethe framed reply, application/octet-stream
DELETE /session/<id>tokennone{"closed":true}
OPTIONS (any path)noneCORS preflight204 with CORS headers

A known path with the wrong method answers 405; an unknown path answers 404. Both require valid authentication first, except for the two unauthenticated routes.

Version and handshake

GET /ping returns exactly the service name and the protocol number, with no token. It reveals nothing else; it exists so a client can discover a running service.

GET /version requires a token and returns:

{"kernel":"0.1.0","protocol":1,"git":"<12-hex>","build":"<wasm commit string>","cores":8,"sessions":0,"maxSessions":8}
FieldMeaning
kernelThe crate version of ck-native.
protocolThe protocol number of the HTTP shape and message framing (currently 1).
gitShort hash of the checkout the service was built from, or unknown.
buildThe build identifier compiled into the kernel (the same string a wasm build from that source reports).
coresAvailable parallelism.
sessions, maxSessionsCurrent and maximum number of sessions.

A client checks compatibility by comparing protocol with the number it was built for. A different number means the HTTP shape or framing differs and the service must not be used. A client may additionally compare build with the build of its own wasm module, to refuse a service built from different source.

Sessions and rpc

POST /session creates a session (a worker thread with its own kernel state) and returns a random 16-hex-digit id. At the session limit it answers 429.

POST /session/<id>/rpc takes the message text as the body and returns the frame. The Content-Type of the request is not checked. A message that the kernel rejects is still a 200 with "ok":false inside the frame, as with the wasm module (see errors). Status codes other than 200 mean the transport or service failed, not the kernel request.

Requests on one session run one after another on that session’s thread; different sessions run in parallel. An unknown or expired id answers 404.

DELETE /session/<id> removes the session and ends its worker. Unknown id: 404.

A session whose last request finished more than the idle time ago (default 600 s) is removed by a background reaper; a session with a request in progress is not. The next request for it answers 404.

Authentication

Two kinds of bearer token are accepted, sent as Authorization: Bearer <token>:

  • The shared token. On first start the service creates <config-dir>/token, a random 256-bit value as 64 hex digits, with file mode 600 in a directory of mode 700 (Unix). The file is reused afterwards if it holds at least 32 characters. ck-native --print-token prints it. It is not bound to an origin.
  • A paired token, issued by POST /pair. It is bound to the origin it was paired with.

Tokens are compared in constant time; a paired token is compared by its SHA-256 only, and the service stores only the hash.

Pairing

Pairing lets a web page obtain its own token without the user copying the shared one.

  1. The user runs ck-native --pair. It writes pairing.json in the config dir and prints pairing code: <8 hex digits>. The code is valid for 2 minutes and single use.
  2. The page sends POST /pair with {"code":"..","origin":"..","label":".."}. The origin must be an allowed origin, and if the request has an Origin header it must equal the body’s origin. The label is truncated to 64 characters.
  3. On success the service returns a new token (64 hex digits), a client id (8 hex digits), and the origin and label, and records the client in clients.json (hash only, mode 600).

Failures: 401 with no pairing code, wrong pairing code or pairing code expired; 403 for an origin that is not allowed or does not match the page; 400 for a malformed body; 413 for a body over 4096 bytes; 501 if the service has no config dir. A wrong guess does not consume the real code, but after 5 wrong guesses the pending code is cancelled (too many wrong pairing codes; the code was cancelled) and ck-native --pair must be run again. Concurrent attempts on one code: exactly one succeeds (tested with eight at once).

A paired token works only from its origin: a request that carries a different Origin answers 403 (token not valid for this origin), and one without an Origin header (a non-browser client) is accepted. ck-native revoke <id> takes effect on a running service at its next request, because the service reloads clients.json when the file changes.

Origin and host checks

The Host and Origin checks run before any route, including the unauthenticated GET /ping and POST /pair, and a rejection closes the connection.

ConditionStatus
Host is not exactly 127.0.0.1:<port> or localhost:<port> (port is the one the service listens on; missing Host included)403 bad Host
Origin present and not on the allow-list (null included)403 Origin not allowed
OPTIONS without an Origin403

After these checks, every route except GET /ping and POST /pair (and an allowed OPTIONS preflight) needs a valid bearer token; without one the answer is 401 missing or wrong token.

A request with no Origin header is accepted, since non-browser clients do not send one. For an allowed origin the reply carries Access-Control-Allow-Origin (the origin itself) and Vary: Origin. A preflight (OPTIONS, 204, no token needed) adds Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS, Access-Control-Allow-Headers: authorization, content-type, Access-Control-Allow-Private-Network: true and Access-Control-Max-Age: 600. Rejected origins receive no CORS headers.

The Host check means a name that resolves to the loopback address, such as a DNS-rebinding hostname, is refused; so is [::1] and 127.0.0.1 without the port.

Limits, timeouts, concurrency and panics

LimitValueResult
Request headers32 KiB in total, 100 headers431 / 400
Request body--max-body-mib, default 64 MiB413, decided from Content-Length before the body is read; connection closed
Missing or invalid Content-Length411 / 400
Chunked request body501
Reply body--max-reply-mib, default 1 GiB413; checked after the kernel has run, and the session stays usable
Sessions--max-sessions, default 8429 on create
Connections64 at oncean extra connection gets 503 with Retry-After: 1
Socket read timeout300 s per readthe connection ends

There is no server-side time limit on a kernel request; any budgets inside the kernel are not covered here. The client enforces its own timeout (below).

Each connection has its own thread, and each session its own worker thread; the kernel keeps state per thread, so sessions share nothing.

A panic inside the kernel is caught with catch_unwind on the worker. This works only in a binary built with the service profile; the release profile aborts on panic, which would end the whole process. The worker then ends, because its state may be inconsistent, and the request answers 500 with {"error":"kernel panic; the session was closed"}. The session is removed, so later requests for it answer 404. The panic hook logs only the source location, never document text. Other sessions are not affected. No test covers the panic path.

The request log (standard error unless --quiet) records method, path, status, size and time, and never a body, token or pairing code; a test checks this.

Body framing

The request body is the message text, UTF-8 JSON, identical to the input of the wasm module. The success reply body is the binary frame described in replies and buffers: a little-endian u32 JSON length, the JSON, padding to a multiple of 8, then the binary area. The tests decode it the same way for both transports and require the HTTP reply to equal a direct call of the dispatch (apart from the ms timing field).

The TypeScript client

packages/kernel-client/src/native.ts implements the transport.

  • probeService({url, token, expect}) calls GET /version with a 5 s timeout. It never throws; it returns {ok: true, version} or a failure of kind unreachable, unauthorized (401 or 403), invalid (not a kernel service) or mismatch. A mismatch is a different protocol, or, when expect.build is given, a build/git that is not the same commit. A bare 127.0.0.1:7461 is read as http://.
  • NativeKernel.connect(options) probes first and throws NativeConnectError on failure; the session opens lazily on the first request.
  • request(msg) sends messages one at a time in call order and returns the same reply shape as the wasm transport. A transport failure is {ok: false, trap}, a refusal is {ok: false, error}. A 5xx is reported as kernel crashed; a 4xx other than 401, 403 or 404 is a refusal of that request and the session continues.
  • A failure that makes the session unusable (service gone, token refused, session expired by 404, timeout, unreadable reply) is reported once through onFailure. The application then switches to the built-in wasm kernel. The client never continues a session on another kernel by itself.
  • Defaults: request timeout 5 minutes, and a ping message every 30 s while idle so the service does not expire the session. After a stale idle connection fails, the client re-sends once if GET /version still answers.
  • cancel() aborts what is in flight and drops queued requests; close() also sends DELETE /session/<id>.
  • Requests use Authorization headers only, never a URL parameter; they omit cookies and send a local-network hint when a page on a public address calls the loopback address.

The client does not call /ping or /pair; both are for other tools. Choosing when to use the service is left to the application.

Security notes

  • Keep the config directory private. Anyone who can read token can run kernel requests; the service has no other protection against local users.
  • The service listens on loopback only and speaks unencrypted HTTP. Do not forward its port to other machines.
  • The Host and Origin checks and the token together are what stop other web pages from using the service. Add an origin only for a site you trust.
  • Prefer a paired token for a web page: it is bound to that origin and can be revoked without changing the shared token.
  • The pairing code is 8 hex digits valid for 2 minutes. The service applies no limit on wrong guesses (a wrong guess leaves the code valid), so run --pair only when you are about to pair.
  • The service creates its random values from /dev/urandom; it reads /dev/urandom, so the service targets Unix-like systems.
  • The HTTP routes take only protocol messages, and no message type touches host files: the request dispatcher and the kernel crates do not use the filesystem (only the service itself reads and writes its token and pairing files).

See also

Architecture

This chapter describes how the kernel is divided into crates, how they depend on each other, and the rules the whole code base follows for numerics, errors, panics and threads.

Layers

The kernel is a Cargo workspace (crates/*). Dependencies only point downwards in the table below, and no crate depends on a crate in a higher layer.

layercrateswhat they hold
0ck-core, ck-json, ck-textMath and utilities (ck-core), the JSON reader and writer (ck-json), outline fonts and lettering (ck-text). None has dependencies.
1ck-geomCurves, surfaces and NURBS. Representation only: no topology. Depends on ck-core.
2ck-topoThe B-rep data model, primitive construction (extrude, revolve), local edits, orientation, mass properties and point classification. Depends on ck-core, ck-geom, ck-json.
3ck-tess, ck-checkThe tessellator and the independent solid validator. Both read a body and never change it.
4ck-ops, ck-heal, ck-io, ck-skp, ck-sldprtModelling operations (booleans, blends, loft, sweep, offset, shell, draft, surfacing, measurement), repair, STEP and ACIS SAT, and the SketchUp and SolidWorks readers.
5ck-model, ck-recogThe document model and the regeneration program (ck-model), and feature recognition for imported solids (ck-recog).
6ck-server, ck-wasm, ck-nativeRequest dispatch and replies (ck-server), the WebAssembly entry points (ck-wasm), the local HTTP service (ck-native).

Some details that the table hides:

  • ck-ops depends on ck-tess and ck-check: the section and probe requests cut the display mesh, and a few operations validate their own result.
  • ck-heal depends on ck-check. A repair pass is driven by the findings of the validator, so it only touches what the validator reported.
  • ck-server depends only on ck-json. It knows the envelope, the request table and the session state, and gets geometry through hooks that ck-wasm installs (ck_wasm::engine::install). Without the hooks a request that needs a body answers with an error.
  • ck-wasm is the only crate that sees everything. It contains the glue that needs several crates at once: the regeneration hook, the regeneration cache, the view cache, the validate and heal requests, and the queries that read the snapshot of the last regeneration.

The crates map one to one to the chapters of this part: the B-rep model is ck-topo, geometry is ck-geom, operations is ck-ops, tessellation is ck-tess, regeneration is ck-model and the cache in ck-wasm. Validation is ck-check and ck-heal; see the validation overview.

What ck-core provides

modulecontents
linalgVec2, Vec3, Mat3, Mat4, Quat, Plane and Frame (origin and three axes), the tolerance constants.
xformXform, a rigid or affine map p -> r*p + t. a * b applies b first.
quadReal roots of quadratics, cubics and quartics, polished by Newton steps against the given coefficients. Used by closed-form intersections.
kdtreeA 3D tree for nearest, k-nearest, radius and weld queries. Ties are broken by lower index so results are deterministic.
budgetWall-clock work budgets (see below).
memoContent-keyed memo tables for pure geometric functions (see below).
fxhashA small multiply-rotate hasher for integer-keyed maps.
traceThe debug trace that a request with "debug": true returns.

The shared tolerance constants in linalg are EPS_LINEAR = 1e-6, EPS_POINT = 1e-9, EPS_PARAM = 1e-12, EPS_MACHINE = 1e-15 and EPS_COARSE = 1e-3. Most operations use the first as their working tolerance; see tolerances.

The code path of one request

host -> ck_request -> ck_server::handle   envelope, dispatch on msg.type
                          |
                          +-> hooks (ck-wasm engine)
                                |-> regen: ck-model::regen -> features -> ck-ops / ck-topo
                                |         -> ck-tess (display mesh) -> reply JSON + buffers
                                '-> queries: read the snapshot of the tag
                                          (ck-topo mass, ck-ops measure, ck-check, ck-heal, ...)

A request carries a tag. The result of a regen is kept under that tag as a snapshot (the body, the sketches and the assembly state), and later queries on the same tag read it. The wire format is described in the protocol part.

Numerics and determinism

The kernel computes in IEEE-754 double precision (f64) throughout. Results are meant to be reproducible: the same document gives the same bytes on every run of one build. The following rules support that; the one place where platforms can differ is noted below.

  • No float reassociation. The release profile uses one codegen unit and no fast-math. The compiler may not reorder floating-point sums, so a build’s results do not depend on inlining decisions.
  • Same sin and cos in the angle-critical code. The system math library differs between platforms in the last bit. ck_topo::trig is a port of the standard msun kernels, and revolve, draft and mate rotations call it instead of f64::sin and f64::cos, so a native build produces the same bits as the WebAssembly build for those. Other code calls the standard functions, which are the same on WebAssembly and may differ in the last bit on a native platform.
  • Guarded normalisation. Vec3::normalize returns the zero vector, not NaN, when the length is not above 1e-300 or not finite. try_normalize returns None in that case. Callers that need to detect degenerate input use the second form.
  • Stable ordering. Where a result is a list, it has a defined order: intersection results are sorted by the parameter on the first curve, the BVH pair traversal has a fixed order, and the tree queries break ties by index. Hash maps from fxhash are used only where iteration order is never observed.
  • Caches do not change results. The content-keyed memo tables (ck_core::memo) are keyed by the exact bits of their inputs, so a hit returns the value the computation would have produced. The regeneration cache and the face-mesh cache are exact in the same sense; see regeneration.
  • Local origin for far parts. A boolean whose operands are far from the origin compared with their size (centre farther than 1e4 diagonals) is computed in coordinates centred on the operands and moved back, because absolute tolerances such as 1e-6 are below the resolution of f64 squared distances near 1e6 mm.

Floating-point tolerances are model-space distances in millimetres, not relative numbers, except where the text says “bounding-box relative”; see tolerances.

Platform constraints

The kernel is compiled to wasm32-unknown-unknown and also runs natively (tests, command-line tools, the local service). It is not no_std: it uses std collections, strings and thread_local!. It does restrict itself to what a sandbox can offer:

  • No file, network or process access in the kernel crates. Time is the only host service: the host passes ck_now and ck_unix_ms, and the work budgets and the request timer use those injected functions. The exceptions are debug switches (environment variables such as CK_OFFSET_DEBUG and stopwatch code behind them) that print diagnostics on native builds; they have no effect in the WebAssembly module.
  • No unsafe code in ck-core, ck-geom, ck-topo, ck-ops, ck-tess, ck-check, ck-heal or ck-model. The only unsafe in the kernel proper is the optional logging import of the trace feature in ck-tess, which is off in normal builds. The WebAssembly entry points in ck-wasm use unsafe for the pointer interface, and ck-skp and ck-sldprt forbid it.
  • No random numbers and no threads inside the kernel.
  • JSON is handled by ck-json, which keeps object keys in insertion order and prints floats in the shortest form that round-trips.

The WebAssembly module exports five functions (ck_alloc, ck_request, ck_reply, ck_commit, ck_commit_len) and imports three (ck_panic, ck_now, ck_unix_ms); see calling it from Node.

Panics and traps

The release profile is built with panic = "abort". A Rust panic in the WebAssembly module is therefore a trap (unreachable) that cannot be caught at the request boundary. What happens instead:

  1. A panic hook installed on first use calls the host’s ck_panic(ptr, len) with the panic message.
  2. The module traps. The host sees a WebAssembly.RuntimeError, treats the instance as lost, and creates a new instance. All tags and caches of the old instance are gone.

Because a trap gives no structured feedback, the code base follows a rule instead of a safety net: no unwrap(), expect(), unchecked index or map lookup on data that comes from a document or from geometry. Failures are returned as errors with a code and, where possible, a hint. Every loop whose length depends on geometry has a bound or polls the work budget. The crash-fuzz run in the repository (5000 generated documents on a release build) ended with no traps, but its baseline still lists three open hangs (slow near-degenerate cases, which end in a structured result or a budget error when run alone but exceed the harness timeout under load); see robustness under edits.

The native service is built with a separate service profile that keeps unwinding. Each session runs on its own worker thread; a panic is caught with catch_unwind, the session ends with the error kernel panic, and the log records only the source location, not document text.

Work budgets

ck_core::budget implements two nested wall-clock limits that long loops poll:

limitrequest optiondefault
one featureopts.featureTimeMs120000 ms (0 = unlimited)
the whole regenerationopts.regenTimeMsnone

The limits are active only where the host installed a clock. The WebAssembly build wires the host’s ck_now, so a host must return real time from it: under the book’s own runner ck_now returns 0, so the budgets never fire there. A loop that finds its limit passed stops and returns its own ...BudgetExceeded code; the regeneration driver turns any failure that happened while a limit was running out into featureBudgetExceeded or regenBudgetExceeded, with the elapsed and permitted milliseconds and the code the feature would have reported in cause. See feature errors.

Threads

One kernel instance is single-threaded. The kernel keeps its state (the session tags, caches, memo tables, the budget clock) in thread_local! variables, 51 of them in the kernel crates, so two instances never share anything and a host gets parallelism by running several instances.

  • In the browser or Node, one WebAssembly instance per worker is the unit.
  • In the native service one worker thread serves one session. The thread gets a large stack (256 MiB by default, Config::stack) because some recursive algorithms are deep on large bodies.
  • Two process-wide atomic flags in ck-ops::intersect::ss switch intersection seeding variants, and a set of counters in intersect::patch exists for profiling. They are written at the start of a regeneration; they are the only shared mutable state in the kernel crates.

Multi-threaded geometry inside one request is not implemented (see known limits).

See also

The B-rep model

This chapter describes the boundary-representation data model in ck-topo: the entities, their conventions, how bodies are built and edited, and how volume and mass properties are computed from them.

Entities

A Body is a set of arenas, one Vec per entity kind. Entities refer to each other by typed 32-bit indices (VertexId, EdgeId, CoedgeId, LoopId, FaceId, ShellId, LumpId).

Body
 '- Lump          one solid (or one connected sheet group); has an optional body name
     '- Shell     a closed boundary: the outer skin, or an internal void
         '- Face  a trimmed piece of a surface, with a persistent name
             '- Loop     a closed boundary of the face; the first one is the outer loop
                 '- Coedge   one use of an edge by a face, with a direction and a pcurve
                     '- Edge     a curve segment shared by (normally) two coedges
                         '- Vertex   a point
entityfields that matter
Vertexp (the position) and tol.
Edgecurve (a 3D curve of ck-geom), the trim range t0 < t1 on that curve, v0 and v1 (the vertices at t0 and t1), the list of coedges, and tol.
CoedgeThe edge, rev (it traverses the edge backwards), the loop it belongs to and an optional pcurve.
LoopThe face and the ordered coedges.
Facesurface, sense, the loops, the shell, the persistent name, and absorbed (see below).
ShellThe faces and the lump.
LumpThe shells and an optional body name.

tol on vertices and edges is the tolerance in millimetres (0 means exact). Modelling operations create only exact entities; the repair pass sets tolerances on imported geometry. See tolerances.

Conventions

These hold for every body the kernel builds, and the validator and the repair pass rely on them.

  • Face sense. A face carries a surface and a boolean sense. The outward normal is the natural surface normal Su x Sv when sense is true and its negation otherwise.
  • Loop orientation. Every loop runs counter-clockwise about the face’s outward normal, so the material is on the left when walking along a coedge. The first loop of a face is the outer loop; the others are holes.
  • Coedge direction. A manifold edge has two coedges, and they run in opposite directions: one has rev = true, the other false. Two coedges of one edge with the same rev are the defect SHELL_ORIENTATION.
  • Pcurves. A coedge may carry a 2D curve in the surface’s (u, v) space. It is parameterised by the edge parameter, so pcurve.eval(t) is the (u, v) of edge.curve.eval(t) on this face. Every face the kernel builds carries exact pcurves. Where a pcurve is missing, mass properties and the validator project the 3D curve onto the surface instead.
  • Seams and poles. A periodic face (a full cylinder, cone, sphere or torus) is closed in u or v by a seam edge: an edge whose two coedges both belong to the same face. Where a revolve passes through its axis, the vertex is a pole with no rail edge. Seams stay inside the model because mass integration, meshing and booleans need uv-closed loops, but they are not exported: the edges list of a reply never contains a seam, and an arc that a seam splits is reported as one edge.
  • Arenas never shrink. Deleting an entity flags it alive = false. Indices stay valid, and the order of the live entities is the order they were created. This is what fixes the numbering of edges in the reply (#N in an edge key).

Shells, lumps and voids

A lump is one solid. A lump has one outer shell and any number of void shells (the cavity of a hollow part). A boolean that splits a part in two gives two lumps. Lumps of one body can overlap (see newBody in the features chapter); such lumps are legal, and validate only reports the overlap as information.

rebuild_lumps groups faces into edge-connected components and assigns them to lumps. A component whose signed volume is positive opens a lump; a negative component (inside-out, hence a void) attaches to the lump that contains it. A shell whose faces are not edge-connected is split into one shell per component. A sheet (a surface body made by surfaceExtrude, fill and similar features) is a body of open shells. The regeneration program keeps sheets apart from the solid body, and the reply lists them under surfaces.

Face names

Every face has a FaceName. The name is what documents refer to, and it is built from how the face was made, not from its position in a list:

<feature>.<role>[~<region>][@<instance>...]
    role     S.<sketch entity>    side face swept from a sketch entity
             C<k>                 end cap (C0 = start, C1 = end)
             B<k>                 blend face (fillet, chamfer)
             anything else        written as is (V0 vertex blend, W0 thicken wall, F patch ...)
    ~k       k-th piece when a face was split in several (1-based)
    @F5.2    copy 2 made by pattern F5; chained for nested instances

FaceName::parse is the inverse of FaceName::id. A face that merges into another during a union keeps its name in Face::absorbed of the surviving face, and Body::find_face looks there when an exact match fails. Persistent names explains how this keeps later features working.

An edge in a reply is named by the two faces it separates, sorted bytewise, plus its index in the exported edge list: F2.C1|F2.S.e1#2. The index changes when the topology changes, so documents refer to an edge by {faces, at} (two face names and a point) instead.

Building bodies

All construction ends in a Body with consistent loops and pcurves.

  • Extrude and revolve (ck_topo::make). A Profile is a frame plus regions; a region is an outer loop and hole loops of ProfileSeg (line, arc or circle pieces with their sketch entity tag). extrude takes ExtrudeOpts (the start and end offsets along the sketch normal, a direction override, and a draft angle) and revolve takes an axis and two angles. Each region becomes its own lump. The creation order is fixed: per region the caps C0, C1, then the side faces in loop order; per loop first the rails, then for each segment its C0 edge and its C1 edge.
  • Operations in ck-ops produce a new body from existing ones. Booleans assemble their result from fragments of the operands’ faces; blends and offsets rebuild a body from changed surfaces. See operations.
  • Appending. Body::append copies another body’s arenas into this one and returns the new lumps. Documents use it for newBody and for pattern instances, which are then renamed with push_instance.
  • Transforms. Body::transform applies a rigid transform to every surface, curve and vertex.

Editing a body

ck_topo::edit offers local edits that keep the data structure consistent:

functioneffect
split_edge(e, t)Splits an edge at a parameter. Every coedge of the edge gets a partner in its loop. Returns the new vertex and edge.
split_face(f, va, vb, ...)Splits a face with a new edge between two vertices of one of its loops. The other part becomes a new face.
delete_face(f)Removes a face and leaves its edges open (free edges).
merge_faces, merge_coplanarMerge adjacent planar faces with the same plane and normal into the face with the lower id.
gcFlags edges without live coedges, and vertices without live edges, as dead.

ck_topo::orient fixes orientation: flip_face, reverse_loop, fix_planar_loops, orient_shell and orient_body (make faces agree with their neighbours and the solid outward), and loop_uv_area, which gives the signed area of a loop in uv space.

Queries on a body

  • Classification. region::classify(body, point, tol) returns Inside, Outside or On. Near the boundary (closer than 1 percent of the box diagonal) the side is read from the nearest feature: a face interior by its outward normal, an edge by the sum of its faces’ normals, a vertex by the angle-weighted sum. Farther away the generalised winding number, evaluated with the exact face integrator, decides. Neither method needs a ray-surface intersection, and both are insensitive to seams and poles.
  • Counts. check::euler gives V - E + F - (L - F). For a closed orientable shell this is 2(1 - genus): 2 for a block, 0 for a block with a through hole.
  • Boxes. Body::bbox samples every edge (65 points) and is memoised by content.

The validator is a separate crate; see topology and geometry checks. ck_topo::check is the smaller, internal predecessor used inside operations (open and non-manifold edges, broken loops, pcurve deviation).

Mass properties

ck_topo::mass computes volume, area, centre of mass and inertia from the faces, with no mesh involved. The divergence theorem turns the volume into a surface integral of p . n / 3 over the faces. Each face integral over the trimmed parameter domain is turned into a boundary integral by Green’s theorem and evaluated along the coedge pcurves. Both integrals use composite 8-point Gauss-Legendre quadrature, with adaptive panels where the integrand is rough. For analytic faces with exact pcurves this reaches machine precision.

solidvolume relative errorarea relative error
sphere, radius 104e-162e-16
cylinder, radius 50, height 1003e-163e-16
torus, R = 10, r = 38e-160

(Measured through the massProps request on solids built with the kernel; the reference values are the closed forms.)

Moments are accumulated per lump about a reference point and then combined. The inertia tensor about the centroid goes through a cyclic Jacobi eigen-solver; the principal moments come out ascending and axes[i] is the unit eigenvector of principal[i]. The eigenvectors have no sign convention, and for repeated moments (a cylinder, a sphere) the axes are an arbitrary basis of the eigenspace. The massProps reply shape and its limits are described in mass properties and interference.

See also

Geometry

ck-geom holds the curves and surfaces that bodies are made of. It is representation only: it evaluates, differentiates, converts and fits geometry, and knows nothing about topology. This chapter lists the types, their parameterisations, the NURBS machinery, fitting, projection, and the intersection routines in ck-ops that the booleans rely on.

Curves

Curve (3D) has six variants:

variantdefinitionparameter
Lineo + t d, d a unit vectorarc length
Circlec + r (cos t x + sin t y), normal = frame.zangle, period 2 pi
Ellipsec + a cos t x + b sin t yangle, period 2 pi
Conicfocus form p / (1 + e cos t) about frame.o: circle, parabola, hyperbola branchpolar angle
Sinusoido + t x + a sin(w t + phase) y in a frame planet along x
BSplineB-spline or NURBS curveknot parameter

Curve2 is the 2D counterpart used for sketches and for pcurves: Line, Circle, Ellipse and BSpline.

Every curve offers eval, derivatives up to second order, tangent, closest_param and closest_point, length_between, segment (a trimmed copy), reversed, transform, sample and kind. kind() returns the string used on the wire: line, circle, ellipse, conic, sinusoid or spline. A circle reports circle and its centre, normal and radius in the edge record of a reply.

Surfaces

Surface has ten variants. The analytic parameterisations follow ISO 10303-42, so STEP export can write them one to one.

varianteval(u, v)domainperiods
Planeo + u x + v yunboundednone
Cylinder { r }o + r (cos u x + sin u y) + v zu in [0, 2 pi), v unboundedu
Cone { r, semi_angle }o + (r + v tan a)(cos u x + sin u y) + v z, r = radius at v = 0as the cylinderu
Sphere { r }o + r cos v (cos u x + sin u y) + r sin v zv in [-pi/2, pi/2]u
Torus { major, minor }o + (R + r cos v)(cos u x + sin u y) + r sin v zboth [0, 2 pi)u and v
Revolution { profile, axis_o, axis }the profile curve rotated about an axisu angle, v along the profileu
Extrusion { profile, dir }the profile curve translated along dir (its length is kept)u along the profile, v unboundedthe profile’s
BSplinetensor-product B-spline or NURBSthe knot rangesnone
Screwa profile carried by a rotation plus an axial advance (helical sweep)bounded in bothnone
Offset { base, dist }base + dist N, the base surface moved along its normalthe base’sthe base’s

kind() returns plane, cylinder, cone, sphere, torus, revolution, extrusion, spline or offset. A Screw patch reports spline. These are the values of faces[].kind in a regeneration reply.

Offset surfaces are exact, not fitted: the second derivatives come from differentiating the unit normal of the base, using the base’s third partial derivatives (exact for analytic surfaces and for B-splines). An offset cylinder of radius 10 moved by 2 has principal curvatures 1/12 and 0, as it should.

Every surface offers eval, first and second derivatives (derivs1, derivs2), normal, closest_point and closest_param, distance, domain, periods, is_pole and is_planar. Variants of the closest point exist for a warm start from a hint (closest_point_near) and for a bounded search (closest_point_within), which is how a marching intersection and a loop of projections stay cheap.

B-splines and NURBS

BSplineCurve<P> (P is Vec2 or Vec3) and BSplineSurface store the degree, the knot vector, the control points and optional weights (None means non-rational). Knot vectors are full: a clamped curve has ctrl.len() + degree + 1 knots with end multiplicity degree + 1. A surface keeps its control net as ctrl[i * nv + j] with u as the slow index.

The routines follow The NURBS Book (Piegl and Tiller): span search, basis functions and their derivatives, knot insertion, refinement, splitting at a parameter, degree elevation, knot removal within a tolerance, Bezier decomposition, iso-curves of a surface and surface transposition. Rational evaluation works in homogeneous coordinates, including the derivatives. At a knot value the span search walks back over repeated end knots, so clamped ends evaluate to the end point.

Closest-point queries on a curve seed from samples and polish with Newton steps, skipping spans whose speed bound proves they cannot contain a nearer point. Surfaces seed from a parameter grid and polish with a two-variable Newton iteration; a B-spline surface keeps a cached preparation per surface (closest_prep) for loops of queries.

Conversions

convert turns analytic geometry into NURBS exactly. A circle or ellipse arc becomes a rational quadratic with quarter-turn spans and weights 1 and sqrt(2)/2; lines become degree 1; analytic surfaces become rational patches (surface_to_nurbs). A revolution or extrusion of a spline profile becomes a surface by convert::revolve and convert::extrude. The refCurve request returns this form for an edge. For the hole edge of a plate it is a degree 2 curve with nine control points and weights [1, 0.7071, 1, 0.7071, 1, 0.7071, 1, 0.7071, 1], closed.

Fitting

fit builds B-splines through data, following the same book:

functionwhat it does
interpolate(points, degree, param)Global interpolation with averaged knots. Param is Uniform, ChordLength or Centripetal.
interpolate_cubic_tangentsCubic interpolation with prescribed end tangents.
approximate(points, degree, n_ctrl, param)Least-squares fit with a fixed control point count and fixed end points.
approximate_tol(points, degree, tol, param)Raises the control point count until the maximum deviation is within the tolerance.
max_deviationDistance of the data to the curve.
interpolate_surface, grid_surfaceTensor-product interpolation through a grid of points.

The interpolation solves a banded system row by row, so thousands of samples cost memory proportional to the point count, not its square. Two fits (interpolate_cubic_tangents and approximate_with) still build dense matrices and are not used on long inputs.

Fitting is where tolerances enter geometry: intersection curves, pcurves of non-analytic pairs, offsets of free-form faces and lofts through sections are all fitted splines, with deviations of the order 1e-5 (see tolerances).

Curves on surfaces

A coedge’s pcurve (see the B-rep model) is a Curve2 in the face’s uv space. pcurve::exact_pcurve gives an exact one, parameterised like the 3D curve, for the analytic pairs:

  • a line or a circle or ellipse on a plane;
  • an axial line on a cylinder or cone (constant u);
  • a circle about the axis on a cylinder, cone, sphere or torus (constant v).

For every other pair, pcurve_of projects samples of the 3D curve onto the surface and fits a cubic through the uv points; pcurve_of_dense doubles the sample count (up to 1024) until the pcurve reproduces the 3D curve to a requested relative deviation. project_points unwraps periodic parameters so the uv sequence is continuous across a seam, including for B-spline surfaces that close on themselves (closed_periods).

CurveOnSurface composes a pcurve and a surface into a 3D curve S(uv(t)) with derivatives, which the validator uses to measure how far an edge lies from its faces.

Differential analysis

analysis provides curvature and torsion of space curves from their derivatives, the Frenet frame, a rotation-minimising frame along a polyline, and the fundamental forms, normal curvature and principal curvatures of a surface. curvatureAt returns them for a point of a face. On the fillet of a 2 mm round the principal curvatures are k1 = 0.5 and k2 = 0, the Gaussian curvature 0 and the mean curvature 0.25. The sign convention is positive where the surface bends away from the outward normal.

Intersection support

Booleans, blends and sections need intersections. They live in ck-ops::intersect and share one convention: a curve is given with a parameter range, a periodic curve may use a range outside [0, 2 pi) (an edge range such as [4, 4 + 2 pi]) and results are mapped into that range, and tol is a model distance. The default is 1e-6. Results are sorted by the parameter on the first curve.

pairmethod
curve and curve (cc)Closed forms for line and line, line and circle, circle and circle (coplanar or skew). Otherwise polyline seeding followed by a two-variable Newton iteration. Coincident stretches are reported as overlaps (parameter intervals on both curves), not as point lists.
curve and surface (cs)Closed forms for a line against a plane, cylinder, cone, sphere (quadratic) and torus (quartic); a circle against a plane. Otherwise seeds from the distance function and a three-variable Newton iteration. A curve that lies in the surface is reported as an interval.
surface and surface (ss)Analytic carriers where they exist (below), otherwise marching.

For two surfaces the analytic cases are: plane and plane (line, or coincident); plane and cylinder (zero to two axial lines, a circle, an ellipse); plane and sphere (circle); plane and cone (circle, ellipse, two generators through the apex); plane and torus (latitude circles, or the two meridian circles); two cylinders with parallel axes (lines) or the same axis; coaxial cylinder, cone and sphere pairs and two spheres (circles, by intersecting the meridians). Parabolas and hyperbolas from a plane and a cone fall through to marching.

Marching seeds the intersection from a grid of patches. Each surface is cut into 10 by 10 parameter cells with padded boxes, only overlapping cell pairs are searched, and a Newton corrector refines the seeds. A predictor-corrector march with adaptive steps then follows each curve, and a cubic B-spline is fitted through the traced points, refined until the deviation is within tol / 100. Marched curves meet their neighbours only to about 1e-6 to 1e-5, which is why the boolean retries at looser welding tolerances; see operations.

Real roots of low-degree polynomials come from ck_core::quad, which uses a cancellation-free quadratic formula, trigonometric and Cardano solutions for cubics, Ferrari’s method for quartics, and Newton polishing against the given coefficients.

Projection of curves onto faces

The projectCurve feature projects a sketch or a planar curve orthogonally onto faces and returns one B-spline that lies on them. It is used for groove paths and guide curves. It is built from these steps:

  1. Every sample of the source (800 to 1040 per entity) is cast along the projection direction against all selected faces, and every crossing inside a trimmed face is kept, so the near and far sheets of a cylinder or sphere are both hit.
  2. Consecutive hits on one face form a run. The ends of a run are bisected to the exact face boundary or silhouette, and runs are resampled evenly.
  3. Runs whose ends are closer than 1e-3 (a fixed distance, independent of the requested tolerance) join into one chain. If the hits do not form one connected chain, the feature fails with projectCurveSeveral and lists the open ends.
  4. The chain is fitted as one B-spline, degree 3 by default (2 to 9 allowed), with a knot of multiplicity degree at every corner where the tangent turns by more than 1 degree. Control points are added, at most 400, until the deviation is within tolerance (default 0.001 mm). The fit is rechecked densely and tightened up to three times. The marker returned with the curve states the achieved deviation.

The check order and all error codes are in the feature’s reference (projectCurveNoInput, projectCurveNoFaces, projectCurveMisses, projectCurveSeveral, projectCurvePlane, projectCurveFailed; see surfaces and curves). A ray that only grazes a surface is not a hit, and tolerances below the sampling resolution of the data (about 3e-5 for a long spline) are reported with the deviation actually reached.

See also

Operations

ck-ops is the feature engine: booleans, blends, loft, sweep, offset, shell, draft, helix, pipe cut and the surfacing operations. This chapter describes how each works, what tolerance it uses and how it fails. The fields of the corresponding features are in the format part; here the focus is the geometry.

Common behaviour

  • Inputs and outputs. An operation takes resolved inputs (bodies, face and edge handles, numbers) and returns a new Body or an error with a code and an optional detail. The feature layer in ck-model resolves references, evaluates expressions, calls the operation and turns an error into the entry ["F3", {"code": ..., "params": {...}}] of the reply’s errors.
  • A failed feature changes nothing. The body is left as it was before the feature, and the following features still run on it. A later feature that depended on the failed one reports its own error, for example missingEdge. See feature errors.
  • Working tolerance. The feature layer passes TOL = 1e-6 mm to operations (ck_model::features::TOL). It is the welding distance of the boolean, the tolerance of intersections, and the model tolerance handed to the validator. Operations that fit splines use their own looser internal tolerances (see below).
  • Exact first. Whenever the geometry allows, results are built from exact analytic surfaces: a fillet along a line between two planes is a cylinder, a chamfer is a plane, a cut through a block with a cylinder gives an exact cylinder face. Free-form results (lofts, sweeps along splines, offsets of free-form faces) are NURBS.
  • Self-check. An operation does not report success on a body it can see is broken. A boolean checks the topology of its result (open edges, non-manifold edges, broken loops) and its volume against the operands; a loft, a shell and a move-face validate their result with the full validator.
  • Names. Every operation names the faces it creates; see persistent names.

Booleans

ck_ops::boolean::boolean(a, b, op, tol) with op one of Union, Cut (a - b) and Intersect. The pipeline has five stages:

  1. Imprint. Every face of a is intersected with every face of b (candidate pairs come from a bounding-volume hierarchy). The intersection curves are trimmed to both faces. A welded vertex pool (tolerance tol) is shared by both bodies, the existing edges are split at every pool point on them, and coincident pieces are merged into one edge. Coincident face pairs imprint each other’s boundaries instead of an intersection curve.
  2. Fragments. In each imprinted face a loop walk finds the cells: at each vertex the next half-edge is the first one clockwise about the outward normal, so every cycle has its face on the left. Cycles with positive area are outer loops; negative ones are holes and go to the smallest outer loop that contains them.
  3. Classification. Each fragment is classified against the other solid as inside, outside, on-with-same-normal or on-with-opposite-normal. A point on a face is detected first by an explicit point-on-face test; other points use the winding number of ck_topo::region.
  4. Selection. The operation decides which fragments to keep, to flip (the faces of the tool in a cut) and to merge (coincident same-facing fragments, such as the caps of two flush blocks).
  5. Assembly. A new body is built with exact pcurves, lumps are formed, and faces keep their names; the result’s face order is fixed (faces of a untouched, a modified, b untouched, b modified, then merged faces).

Tool faces keep the tool feature’s ids: cutting a hole with feature F4 leaves a face F4.S.e1 on the plate. A face split into several pieces gets ~1, ~2 … numbered by the lexicographic order of the fragment centroids.

Tolerance ladder

Marched intersection curves meet their neighbours only to about 1e-6 to 1e-5, so an arrangement can fail to close at the base tolerance. The boolean therefore escalates:

  1. The plain attempt at tol. If an operand has B-spline or offset faces and tol is the default, the ladder starts at 10 tol and falls back to tol only if the whole raised ladder fails.
  2. On booleanFailed, retries at 10 tol and 100 tol.
  3. If every attempt failed, robust mode: the same attempts at 10 tol, tol and 100 tol with three sliver-tolerant steps switched on (splitting two cut curves where they cross, merging edge pieces within 100 tol that join the same vertices, and classifying a fragment sampled within a sliver’s width of the other solid by a vote of several rays). Robust mode only ever turns a failure into a result. It stops early, with booleanBudgetExceeded, if the earlier attempts already used 12 seconds.

A result that assembled into a closed manifold is then checked against the operands (the sanity check):

operationvolume bound
unionmax(va, vb) <= vr <= va + vb
cutva - vb <= vr <= va
intersect0 <= vr <= min(va, vb)

The overlap that the result implies must also fit in the overlap of the operands’ boxes, and a union’s box must contain both operand boxes. A result outside the bounds is valid but wrong (a region of an operand was dropped); the ladder tries looser tolerances and a split-only pass, and if nothing plausible comes out the feature fails with booleanVolumeMismatch and the body stays as before.

Fuzzy booleans

Features that run a boolean accept tolerance (the fuzzy value, mm) and autoFuzzy. With a fuzzy value, every planar, cylindrical or spherical face of the tool that lies within the value of an equal-kind face of the host (same normal, axis or centre) is first moved onto that face exactly, so the boolean sees coincident faces and merges them. The result differs from the exact boolean of the unsnapped inputs by at most the fuzzy value, and a snap that fails or changes the tool’s volume by more than the value times its area is discarded. With autoFuzzy, a boolean that fails, comes out implausible or comes out less valid than its operands is retried at 1e-7, 1e-5 and 1e-3 (values above the explicit one), and the first plausible, valid result wins. The value used is reported as the warning booleanFuzzy.

Special cases handled

  • Operands far from the origin are shifted to a local origin and moved back.
  • Contact along an edge. Two parts that touch only along an edge leave an edge shared by four faces. The edge is split into two coincident edges, one per material wedge, and the parts become separate lumps.
  • A cut that misses is the error cutNoEffect; the body is unchanged. A tool that sits entirely in a cavity of the body is a valid no-op and gives no error.
  • A lone sphere with a pole on the other solid’s surface needs a special path, because the intersection circle passes through the poles and the uv polygon cannot hold a pole as a point.

Failure

codemeaning and parameters
booleanFailedThe result did not close. When the cause is diagnosed the error carries faces (the faces around the open edges), issue and at (a point), or hostFace, toolFace and gap when two nearly coincident free-form walls are the cause. Always with a hint.
booleanTangentAn exact tangency whose result has an odd Euler characteristic. Carries euler and a hint.
booleanVolumeMismatchThe result closed but is outside the sanity bounds. Carries what (volume or box), expected_min, expected_max, got.
booleanBudgetExceededThe time budget ran out.
cutNoEffectA cut or intersection changed nothing. Reported in errors; the body is unchanged.

The usual remedies are in the hints: move the tool by a small amount (0.01 mm), unite bodies that touch first, make near-coincident faces exactly coincident, or give the feature a fuzzy tolerance between 1e-5 and 1e-3.

Blends: fillets and chamfers

A blend is built as a boolean with a tool, not by editing faces in place. For each edge, a tool solid (the corner prism between the two faces, with the rolling-ball profile as one face) is made and then cut from the body for a convex edge or united for a concave edge. The tool’s profile face becomes the blend face B<k> of the feature. Straight edges between planes give a cylinder (fillet) or a plane (chamfer); circular edges between coaxial planes, cylinders and cones use a revolved profile; free-form edges (B-spline or revolution faces, spline intersection curves) are handled by a rolling-ball construction that fits a spline tool (blend::freeform).

feature optionsresult
fillet radiusCircular profile, constant radius. A pick may carry its own radius; unequal radii at a vertex give a mitre and the warning cornerNotTangent with the largest normal jump (deviation, degrees).
filletType: "variable" with radii: [near, far]The radius changes along each picked edge. An end radius of 0 is built with the smallest positive end radius that works (warning filletRadiusApproximated).
filletType: "fullRound" with side1, center, side2A ball tangent to three planar faces; the center face vanishes.
profile: "conic" (rho in (0, 1)), "chord", "curvature" (shape in [0.1, 1])Other section shapes.
chamfer chamferType: "equal"Equal distance.
"distances" (distance, distance2) and "angle" (distance, angle)Two distances or a distance and an angle, measured from the first face (named by face, or the first of each pick’s faces); flip swaps the legs.
"vertex"Cuts off the corner nearest at where three edges meet.
propagate: trueThe selection grows along edges that continue tangentially.

Corners are the hard part. Three convex edges with one radius meeting at a vertex get the rolling ball’s sphere patch V<k>. A vertex with two convex edges and one concave edge is built in two stages (the concave edge first, then the two rim edges and the arc as one tangent chain, a torus patch). Four edges that flip between convex and concave at a vertex (a block overhanging a wall) get a B-spline corner patch P0. Reflex corners of two convex edges are cut at the bisector plane through the vertex.

Verified results (a 40 x 20 x 10 block, the edge between F2.C1 and F2.S.e1):

featurevolumeclosed form
fillet, radius 27965.66378000 - (1 - pi/4) 4 * 40 = 7965.6637
chamfer, equal 279208000 - 2 * 40 = 7920
chamfer, distances 2 and 378808000 - 3 * 40 = 7880
chamfer, distance 2, angle 307953.818000 - 0.5 * 2 * (2 tan 30) * 40

All results validated clean.

Blend failures

codemeaning
invalidValueRadius or distance not positive.
missingEdgeAn edge pick ({faces, at}) matches no edge. A pick takes the edge between the two named faces nearest to at.
blendOverflowThe blend runs off its faces. detail names the blend (F3.B0: spring leaves its face away from its edges). For curved ends, max gives the largest radius that fits, and curvedEnd says which end. A radius of 30 on a 10 mm block edge gives this error.
blendTooLargeA distance exceeds the edge or face (vertex chamfers, variable radii).
blendSizeNo blend fits between the faces.
blendCornerA corner patch cannot be built (for example convex and concave edges that are not perpendicular); the hint says to blend them in separate features.
blendNonManifold, blendFailed, blendUnsupportedThe tool could not be applied, or the case is outside what the builders cover (with a detail where known).
blendTolerantEdgeAn imported edge carries a tolerance; the blend needs an exact edge.
variableRadiusMismatchEdges that meet at a vertex have different radii there.
filletRho, filletShapeProfile parameter outside its range.

Loft

loft makes a solid or, with surface, a sheet through two or more closed profiles (open chains for a sheet).

  • Stations. The profiles are brought to a common number of pieces: the longest piece of a profile with fewer pieces is bisected at its parameter midpoint until the counts agree (a lone circle becomes two half circles). A profile that runs the other way round than its predecessor is reversed, and each profile’s start is rotated to the cyclic shift that minimises the summed squared distance between the start points of consecutive stations.
  • Rails. The edge through matching points of the stations is a straight line for two profiles and a natural cubic spline through them for more, parameterised by cumulative chord length between the station centroids.
  • Faces. Profile pieces become rational B-splines (arcs as quarter-turn quadratics). Side faces interpolate the homogeneous control points of the stations, so the profiles are exact iso-curves. Two parallel flat squares give planes; a square to a circle gives four spline faces. Names: S.<entity> per piece of the first profile (cut pieces ~k), C0 at the first profile, C1 at the last.
  • Guides are curves that touch every profile. They cut the profile pieces at the contact, and a face that has a guide as a rail becomes a Gordon surface (rails and station curves blended, minus their tensor product), which contains the guide and the stations exactly. influence other than next is refused.
  • A centre line makes the sections between the profiles follow a planar spine. A moving frame carries each profile’s local coordinates along the spine and the coordinates are interpolated by a natural cubic spline. The end profiles stay pinned exactly, and a straight spine changes nothing.

A 20 x 20 square lofted to a 10 x 10 square 30 mm away has volume 7000, the frustum formula (A1 + A2 + sqrt(A1 A2)) h / 3. The result of a loft is validated; if the default matching gives an invalid body, other matchings are tried. Codes: loftProfiles (fewer than two), loftProfileOpen, loftProfileNotPlanar, loftProfileSelfIntersect, loftSectionTooSmall, loftGuideInvalid, loftGuideMiss, loftGuideOrder, loftCentreLineReach, loftCentreLineTight, loftCentreLineKink, loftCentreLineApex, loftCentreLineGuides, loftFailed and loftInvalidResult.

Sweep

sweep moves a planar profile along a path of lines, arcs, helices and splines.

  • A path that is one rigid motion is built exactly. All lines in one direction is a translation (built like an extrude), an arc about an axis is a rotation (built like a revolve), and a helix is a screw motion with B-spline side faces.
  • A path of several pieces (lines and arcs) is swept piece by piece and the pieces are united with mitre joints. Tangent joints need no mitre; a corner between two lines is mitred when it turns by less than 166 degrees. A 6 mm circle swept along a 20 mm line and a perpendicular 20 mm line gives a volume of 1130.9734, equal to 2e-9 relative to a straight tube of length 40. Helices and splines inside a multi-piece path are refused (sweepPathInvalid).
  • A single spline path (a sketch3d spline: a natural cubic through the points, parameterised by chord length) carries the section by rotation-minimising frames (the double-reflection method), which do not roll with the torsion as Frenet frames would. Rows are placed at least 2 per cubic piece and in proportion to how much the tangent turns, and the side faces interpolate the rows.
  • twist rotates the profile about the path as it travels. It is supported along a straight path only. On a multi-piece path the feature fails with an error whose code is the text TODO(rebuild): twisted sweep along a multi-piece path; codes that start with TODO(rebuild) mark cases that are not implemented yet and are not stable names. A 6 x 6 square swept 20 mm with a 90 degree twist keeps its area at every station: the volume is 720.
  • The end of the path nearest to the profile starts the sweep, and the path direction is otherwise irrelevant.
  • Guides (one or two) make the section follow guide curves, with modes scale (the default: scale and turn), turn and stretch (two guides).

The path tangent at the start must be perpendicular to the profile plane to within 5e-5 (sweepProfileNotNormal). Other codes: sweepPathInvalid, sweepGuidesCount, sweepGuideStretchTwo, sweepGuideNotTouching, sweepGuideNotAlong, sweepGuideShort, sweepGuidesSamePoint, sweepGuideDegenerate, sweepGuideOnPath, sweepGuidesTwist and sweepFailed.

Offset and shell

offset moves every face of a closed body along its outward normal by its own signed distance. Vertices are re-solved as the point at the right distance from all incident offset surfaces, and edge curves follow their vertices (lines keep their direction, circles stay coaxial). Free-form faces are re-fitted to B-splines (internal fit tolerances: 1e-5 for surfaces, 3e-3 for edge curves). Codes: offsetTooLarge (the offset passes a centre of curvature, an edge shrinks to nothing or reverses), offsetUnsupported, offsetDegenerate, offsetFitFailed.

shell is body - cavity: the cavity is the body offset inward by the wall thickness on every kept face, and outward by a quarter of the wall on each opened face so that the cavity runs out through it. The opened face survives as a rim ring under its own name; every other face is split by the boolean into an outer and an inner wall, named ~1 and ~2 by centroid order. With outward: true the wall grows outside instead. For a 40 x 20 x 10 block shelled with thickness 2 through the top face, the volume is 3392 (= 8000 - 36 * 16 * 8) and the body validates clean. Shelling a free-form face is supported for lofted hulls; the margin by which an opened free-form face’s offset is continued is capped at 12 wall thicknesses and reduced if the continuation folds.

shellTooThick reports the cause in detail and gives maxThickness and minRadius. maxThickness is a safe estimate, not the exact limit: for the 40 x 20 x 10 block the true limit is 10, and the replies gave 8.9 to 9.35.

Draft

draft rotates planar faces about a hinge (the intersection with the neutral plane) and turns cylinders into cones. The face normals are exact; edges and vertices are re-derived by intersecting the new surfaces. Draft 5 degrees on the four sides of the block about its bottom face gives volume 7485.27, matching 8000 - 3000 tan(5) + (1000/3) tan^2(5) with the tangent of the draft. Codes: draftParallelFace (a face parallel to the neutral plane), draftAxisNotParallel, draftTangentFaces, draftTooLarge (an edge turns over; detail names it), draftUnsupported, draftFailed. Extrusion with a draft is a separate path in ck-topo.

Helix

helix produces a curve, not a body: p(t) = o + r (x cos t + y sin t) + a (pitch / 2 pi) t for t in [0, 2 pi * revolutions], on the circle of its sketch, with leftHand and reverse options. definedBy is pitchRevs, heightRevs or heightPitch. The curve is sampled with max(2, ceil(32 * revolutions)) segments. The helix serves as a sweep path and as a thread axis.

Pipe cut

pipeCut removes everything of the body’s faces that a ball of radius r rolled along the selected edges touches. The result is a surface body (a sheet): the pipe surface itself is not part of it, and fill can close the gap. The cutters (a cylinder or torus sector per edge, a ball per end vertex) only split faces in the boolean’s imprint stage; a fragment is kept when the distance from an interior sample point to the nearest selected edge is at least r. Codes: pipeCutRadius (with max, 0.999 of a circle edge’s radius), pipeCutFailed, pipeCutNothingLeft.

Surfacing

Surface bodies are open shells kept apart from the solid. The operations are:

operationwhat it doescodes
knitSews faces from several bodies into one by merging coincident edges (tolerance 1e-6). solid: true requires a closed result.knitNotClosed, knitNearMiss
trimSurfaceCuts surfaces with a tool plane and keeps one side; mutual keeps the tool uncut. All-planar inputs take an exact path (a half-plane clip in uv); anything else goes through surface-surface intersection.trimNoIntersection, trimNothingLeft
extendExtends a sheet across an open boundary edge by a distance or to a target surface.extendNotBoundary, extendNoTarget, extendPointBehind, extendUnsupported, extendFolds
fillPatches a boundary chain plus its closing chord. A planar boundary gives the exact plane. For a non-planar boundary the patch is a ruled surface between the chain and the chord: the fairing modes (meowNURBS, plate, curvature, variation) and the continuity options (G0 to G3) are accepted, but they do not yet shape a non-planar patch (a known gap).fillNotClosed, fillInvalid, fillFailed
thickenTurns a sheet into a solid wall (front, back or both), mitring corners. Creased free-form sheets are offset face by face with mitred corner points.thickenReach (offsets do not meet at a corner), thickenTooThick, thickenFailed
rebuild (freeform)Re-fits a face onto a degree and span net, keeping its edges.rebuildPeriodicFace, rebuildTooFine, rebuildFailed

Verified: a 20 + 10 mm open chain extruded 10 mm and thickened with thickness 2 on both gives a volume of 600, which is the sheet area 300 times 2, with walls F3.W0 to F3.W5.

Measurement and analysis

measure, interference, section, probe, distance, thickness and the related queries are operations in ck-ops too (measure.rs, interference.rs, section.rs, analysis.rs, dfm.rs). They are described, with accuracy, in mass properties and interference.

Tolerances at a glance

wherevalue
Model tolerance passed to operations, boolean welding distance, intersection tolerance1e-6 mm
Boolean retry ladder10x, 100x the welding distance; robust mode adds the base again
Fuzzy boolean values tried by autoFuzzy1e-7, 1e-5, 1e-3 mm
Marched intersection fitdeviation within tol / 100
Free-form offset fit: surfaces; edge curves1e-5; 3e-3
Sweep profile-normal check5e-5

See tolerances for how these relate to the validator’s.

See also

Tessellation

ck-tess turns the faces of a body into the triangle mesh that a viewer draws, and produces the edge polylines and silhouette data that go with it. This chapter describes how faces are meshed, what the mesh contains, what controls its density, and where it can fail. The checks that use the mesh as a witness are in tessellation checks.

What the mesh is for

The mesh is a display mesh. It approximates the exact B-rep to a chord height; it is not used for volume, area or any measurement that has an exact answer (those come from massProps and the other analysis requests). For a sphere of radius 10 the mesh volume is 0.097 percent below the exact one, for a cylinder of radius 50 and height 100 it is 0.18 percent below, and for a torus with R = 10 and r = 3 it is 0.34 percent below. The sign depends on the surface: polygons inscribed in convex surfaces fall short and those in concave surfaces overshoot, so a body with both can go either way (a block with a radius 4 through hole meshes 0.04 percent above its exact volume when the block is cut with a circle extrude: 7500.31 against 7497.35).

A regen reply carries the mesh of the solid body and one mesh for each surface body. Tessellation also runs inside validate (to check that the mesh is watertight), curvatureMap, comb, section, sections and a few analysis queries.

Tolerance

Two numbers control the density. Both are fixed by the body; no request option changes them.

quantityvalue
chord heightmax(1e-3, 4e-4 * diagonal) mm, where diagonal is the length of the body’s bounding-box diagonal; rounded down to four significant figures
angle0.3 rad between consecutive samples on a curve and between the normals at the two ends of a refined edge

An empty bounding box, or a NaN diagonal, gives the minimum, 1e-3. The rounding down makes the tolerance stay the same when an unrelated edit moves the box in the last digits, so unchanged faces keep their mesh bit for bit and the face cache can find them.

Because the chord height scales with the body, the number of segments on a circle depends on the circle’s radius relative to the body, with the angle limit as a ceiling. A circle of radius r is cut into steps of min(2 acos(1 - chord / r), 0.3) radians, which is at least 21 segments for a full circle. A cylinder of radius 50 and height 100 meshes to 61 segments around (the extra one comes from the periodic cut), and a radius 1, height 2 cylinder meshes to the same 61 because chord and radius scale together.

The pipeline

  1. Edge sampling. Every edge is sampled once, and its samples are used by both faces that share it. This is what makes the mesh watertight without any welding step: the boundary vertices of neighbouring faces are bit-identical. A line has its two ends. A circle uses the step above. An ellipse uses a step derived from its two semi-axes. A spline gets each knot span cut into max(2, degree + 1) pieces, refined adaptively, and then thinned to what the tolerance needs.
  2. Refinement along edges. For each coedge the parameter list is refined in the face’s uv space: bisect while the pcurve midpoint is farther than a scaled tolerance from the uv chord (at most 12 levels). Then, for each coedge, bisect while the angle between the face normals at the two ends exceeds 0.3 rad (at most 8 levels).
  3. Periodic cut. A periodic face (a cylinder wall, a sphere, a torus) is cut open along a line in uv at the middle of the largest gap between the boundary samples. The cut adds one sample to every edge that crosses it. The face is meshed in the strip between the cut and one period later. Faces with no trimming loops (a full sphere or torus) get the whole domain as a rectangle with pole lines.
  4. Triangulation. The boundary samples, mapped through the pcurves into a metric-scaled uv frame, are triangulated by a constrained Delaunay triangulation (CDT). The triangles that lie inside the boundary, found by crossing parity, are kept. A planar cap with N boundary points becomes N - 2 triangles, and a cylinder wall with N segments becomes 2N triangles, because no interior points are needed.
  5. Interior refinement. For curved faces, triangles are refined by inserting the uv centroid of every triangle whose surface point at the centroid, or at the middle of one of its edges, is farther than the chord height from the flat triangle. Passes repeat until nothing is inserted, at most 64 passes and a budget of points per face. Two guards keep a face with an unreachable trim from spending the whole budget: a boundary vertex more than 100 chord heights off its analytic surface is judged by the surface point rather than by its own position (spline faces already did this at a quarter of the chord height), and after 14 passes refinement stops when the set of triangles still to be split is no smaller than it was six passes earlier. A healthy face is resolved in about ten passes and its set shrinks well before that; these guards matter only for the invalid bodies that a failed edit can leave behind. Large B-spline faces are first seeded with a uv lattice sized to the number of knot spans so that long thin faces converge quickly, and a surface-aware choice of diagonals avoids fans on long strips.
  6. Output. Triangles are written counter-clockwise about the face’s outward normal (flipped for sense = false). Points within 1e-4 of an already emitted point, and within 1e-3 in uv, share a vertex, so that two points an f32 cannot tell apart do not produce a zero-area triangle.

The constrained Delaunay triangulation

cdt.rs is a standard implementation: a super-triangle encloses the points, points are inserted by splitting a triangle or an edge and restoring the Delaunay property with Lawson flips, and constrained segments are inserted by flipping the edges they cross (Sloan’s method) and are never flipped afterwards. All orientation and in-circle decisions use adaptive exact predicates, so the result is a consistent triangulation even for nearly degenerate input. A segment that cannot be inserted is counted and reported as a note on the face.

What the mesh contains

The reply buffers for a body (see replies and buffers) are:

buffertypesizecontent
positionsf329 per triangleThree vertices of each triangle. The mesh is unwelded: vertices are not shared between triangles.
normalsf329 per triangleThe exact outward surface normal at each vertex (the face normal for planes).
midsf329 per triangleFor each triangle edge (v0v1, v1v2, v2v0), the correction n(mid) - (n_a + n_b) / 2, where n(mid) is the unit surface normal at the uv midpoint of the edge. A shader adds it to the interpolated normal to shade a curved surface smoothly with coarse triangles. Zero on planes.
triFacei321 per triangleIndex of the face in body.faces.
silhouettef3212 per candidate edge[a, b, nA, nB] for each mesh edge shared by two triangles of the same face whose dihedral angle is strictly convex. With the two facet normals a viewer can decide, for its current view direction, whether the edge is a silhouette. Concave and flat edges are excluded, so a cylindrical hole has none.

The body’s box is the bounds of the f32 positions. Edge pts in the edges list are the same samples the faces used.

A box gives 12 triangles, a 40 x 20 x 10 plate with a radius 4 hole gives 152 (the two caps 38 each, the hole wall 68), a block with one radius 2 fillet gives 36, and a sphere of radius 10 gives 17776.

Welding

The reply mesh has no shared vertices, so a consumer that needs connectivity welds it. Because edge samples are shared, welding by quantised position works: the weld in the validator quantises positions to max(1e-5 * largest absolute coordinate, 1e-4) and finds no open edge on a closed body. Welding with a coarser grid than the chord height can merge vertices that belong to different parts of a thin feature, so keep the quantum well below the smallest feature. See tessellation checks for the exact rule.

Cache

tessellate_memo caches the mesh of each face under a key made from the exact bits of everything that influences it: the surface and sense, every live coedge’s edge curve, pcurve, parameter range and final edge samples, the seam flag, the end vertices, the periodic cut and the tolerance. A hit is bit-identical to meshing again. Adding a hole to a plate re-meshes only the faces whose geometry or samples changed. The cache holds up to 128 MB by default (opts.cacheCap scales it); see regeneration and caching.

  • curvatureMap returns a triangle soup with per-vertex principal curvatures k1 and k2 for a false-colour overlay. It reuses the display mesh and subdivides curved faces 4 x 4 in uv, with exact curvature at every vertex.
  • comb returns sample points and curvature vectors along edges, and along iso-parameter lines of faces.

Known failure modes

A face that cannot be triangulated is left out of the mesh and listed in the mesh’s failed indices, with a reason. The reasons are loop winds a period (a boundary loop goes around a periodic direction without closing), face has fewer than 3 boundary points, and face produced no triangles. validate reports such a face as TESSELLATION_OPEN and adds the reason.

A face can also mesh but be suspect. The mesh then carries a note for the face: the boundary graph has an unclosed loop (a vertex of odd degree), or some trim segments could not be restored by the triangulation. validate returns these notes as meshNotes.

Behaviours to expect:

  • Near-degenerate bodies are expensive. A disc of height 5e-4 and radius 3 meshes to tens of thousands of triangles, and revolved and mirrored near-degenerate bodies are the main source of validator findings in the crash-fuzz runs.
  • The mesh is coarse for curved faces at the default tolerance. In the repository’s tessellation sweep, volume from the mesh was more than 0.1 percent away from the exact volume for every cylinder and torus and about half of the cones (up to 0.8 percent for a torus), while boxes, spheres and two-station lofts stayed within it. Treat the mesh as a picture.
  • Trim curves that touch. A crescent-shaped cap, or a face whose trim curves cross by a few 1e-6, is the typical case where the triangulation has trouble. Several such cases (a bore wall cut by a branch hole, a torus band spanning a full period, a sphere zone whose circle junction lies on the cut line) are fixed and kept as regression tests; the rules above handle them, but new combinations can still fail.
  • Tolerance is not user-controlled. There is no per-request chord height; a client that needs exact numbers should use the exact queries, not the mesh.
  • The display mesh is not the measurement. Section areas, mass, distances and clearances are computed on the exact surfaces; the section request cuts the mesh and then snaps the cut points onto the exact surfaces, and clearance seeds from the mesh and refines on the surfaces.

See also

Regeneration and caching

Regeneration rebuilds a part from its feature list: it runs the features in order, collects errors, and produces the body and the data a viewer needs. This chapter covers the driver in ck-model, the options that shorten a run, how errors behave, and the cache in ck-wasm that makes an edit near the end of a long part fast. The request and reply format is in regeneration (protocol).

The driver

ck_model::regen::regen_from walks the part’s features array in order. For each feature that is not suppressed:

  1. It opens a work-budget scope for the feature (opts.featureTimeMs, default 120000 ms) and checks that the whole-document budget has not run out.
  2. It runs the feature. Sketches are solved and their profiles found; reference planes and axes are evaluated; every other feature is passed to the geometry executor (ck_model::features::Brep), which resolves the feature’s references against the current body, evaluates its expressions with the part’s variables, and calls ck-topo or ck-ops.
  3. On success the feature’s result replaces the current body (or is added to the sketch, plane and curve tables). On failure an error entry is recorded and the body stays as it was.

Features are independent records: there is no dependency graph. A feature depends on earlier ones only through the names it uses (sketch, face names, edge picks, feature ids) and through the body that earlier features left.

The result has these top-level keys, in this order: errors, components, planes, markers, sketches, sketches3, curves, body, surfaces, and, when non-empty, threads, limits, assembly and warnings. The maps keyed by feature id (errors, components, planes, sketches, sketches3, threads, limits, warnings) are sorted by the id as a string, so F10 comes before F3, and a second entry for the same id replaces the first.

Which features run

mechanismeffect
opts.upTo = nRun only features[..n]. A non-number or a negative value is ignored.
part.rollback = nThe same, stored in the document (the rollback bar). When both are given the smaller wins.
suppressed: true on a featureThe feature is skipped as if it were not there. It still takes part in the cache key.
opts.featureTimeMs, opts.regenTimeMsWork budgets; 0 means unlimited. A feature that runs out is featureBudgetExceeded; the whole document running out gives regenBudgetExceeded for the feature in progress and every later one. (A host clock that advances by more than featureTimeMs between reads makes every feature, sketches included, fail with regenBudgetExceeded and the feature-budget hint; see errors.)
opts.sketchStatus, opts.solveSketchesAdd a solver status to each sketch, or re-solve every sketch from its coordinates.
opts.autoHeal, opts.healTolAfter each feature that leaves validator issues, try a repair pass and keep the repaired body only if it has fewer issues; the feature gets a healed entry. That entry is written to errors, not warnings; when the feature already has an entry, that entry is kept and no healed entry is added (the repair still applies). Default tolerance 1e-5.

Measured with a box, a fillet that fails (F3) and a chamfer that picks the fillet’s face (F4):

runerrorsfaces
all featuresF3 blendOverflow, F4 missingEdge7 (F5 still adds a face)
upTo: 2none6
upTo: 3F3 blendOverflow6
rollback: 2none6

Errors

An error entry is ["F3", {"code": "blendOverflow", "params": {...}}]: the feature id, a code, and parameters such as detail, hint, max or faces. The codes are described in feature errors.

  • A failing feature produces no output. Its result is not applied, and the body is as it was before the feature.
  • The run continues. The following features execute against the unchanged body. A feature that depended on the failed one then fails for its own reason, typically missingReference, missingEdge or missingSketch. The reply does not link the two errors; there is no blockedBy field. The way to find the root cause is to read the errors in the order of the features (not the order in the reply, which is sorted by the id string) and to take the first one in feature order.
  • Failures that never reach the geometry. unknownFeature (the type is not one the kernel knows, with params.type), missingSketch (the sketch id is not an earlier sketch), insertPartMissing, badExpression, and invalidValue.
  • A time budget turns whatever failure happened while the limit was running out into the budget error, with the code the feature would have reported in params.cause.

The debug: true flag on a regeneration request adds a trace array of spans with the feature labels, for example F3 fillet: blendOverflow {...} with its nested F3: Fillet(30.0, Circular) of 1 edge, and one span for each stage of a boolean.

The regeneration cache

Without a cache, every edit would rebuild the part from the first feature. The kernel instead keeps the states of earlier runs and resumes from the longest prefix that is still valid.

What is stored

After a feature (every feature in a short run, every stride-th in a long one) the cache stores the complete state a continuation needs: the body with its face names, the tools of earlier body-making features (needed by mirror and patterns), the assembly state, the helices, the surface bodies, the regeneration result so far (errors, planes, markers, sketches with their solved coordinates, curves) and the axis table. States share what a feature did not change: a sketch or plane feature does not copy the body, and a new snapshot reuses the previous one when the piece is equal. Entries for failed features are stored like the rest, so a replay reports the same errors.

The key

The key of the state after feature i is a chain of SHA-256 hashes:

key[0]   = SHA256( cache format number, kernel crate version,
                   sketchStatus, solveSketches, autoHeal + healTol,
                   the document fields format, version, kind, material, variables )
key[i+1] = SHA256( key[i] || the JSON text of feature i without its cosmetic keys )

So the key depends on the whole prefix of the document up to that feature, on the options that change results, and on the kernel version. It does not depend on the tag (a preview regeneration reuses the states that main built), on name, seq, counters or rollback of the part, or on upTo; those only change how long the run is. Fonts used by text entities are part of the key by content hash.

Five keys of a feature are cosmetic and left out of the hash: group, name, autoName, visible and userHidden. Renaming a feature, moving it into a folder or hiding a plane keeps every key. Any other change of a feature, including keys the kernel does not know, changes its key and the keys of every later feature, deliberately: an unknown key stays in the hash because the cache cannot know it is harmless. suppressed is not cosmetic.

Lookup, resume and reuse

A regeneration computes the chain of keys for the features it is going to run, finds the longest prefix with a stored state, restores that state, and runs the remaining features, storing new entries as it goes. A full hit runs no feature; the reply is rebuilt from the restored state. Measured through the cacheStats option on a box with a fillet:

stepreusedFeaturesranFeaturesfullHit
first run of the 3 features, after the box was seen before21false
same document again30true
fillet radius 2 changed to 321false
fillet renamed30true
same edit with noCache: true03false

An edit to feature k re-runs features k and after, because a later feature may use a body that now differs. The cache cannot reuse a later feature even when its inputs happen to be identical. In particular an edit that leaves the body identical (changing a UI-only field that is not in the cosmetic list) still invalidates every later key.

Checkpoints and limits

Storing a state after every feature of a long run would copy the result and the body each time, which is quadratic in the number of features. A run of more than 256 features therefore stores every stride-th state, where stride = ceil(n / 256) and n is the number of features the run executes, plus always the last one. Positions are absolute ((i + 1) % stride == 0), so a later run of the same document stores at the same places, and an edit resumes from the nearest checkpoint before it.

The cache is bounded by an LRU over the estimated bytes of the unique pieces it holds (Body::est_bytes plus estimates for results and tools); a piece shared by several entries counts once. The default cap is 256 MiB of estimate; with the display caches the linear memory can reach roughly 300 MB in the worst case. Evicting an entry only drops that prefix, since every entry is self-contained.

Time-limit failures are not cached

A failure caused by a time budget (featureBudgetExceeded, regenBudgetExceeded) depends on the machine and the moment, not on the document, so it is not stored: once a budget error is in the result, the run stores no further states. A later regeneration of the same document runs again, with whatever budget it carries. (Builds before this change replayed the stored error; opts.noCache: true did not remove it.) The options featureTimeMs and regenTimeMs are not part of the cache key.

Options

option (in opts)effect
noCache: trueBypass lookup and storage. The cache is untouched.
cacheCap: <bytes>Set the cap of this kernel instance (persists). 0 turns the cache off for that request (nothing is stored or replayed). The display caches scale with it.
cacheStats: trueAppend a cacheStats object to the result: enabled, reusedFeatures, ranFeatures, fullHit, entries, bytes, cap, lookups, hits, stored, evicted, viewHit, and the face-mesh counters tessFaceLookups, tessFaceHits, tessEntries, tessBytes, viewEntries, viewBytes.
noView: trueSkip the display snapshot: body and surfaces stay empty. For a client that already holds the view of this document and only needs the kernel’s state and the errors.

Requests with debug: true bypass the cache because they want the real per-feature spans. A nested insertPart runs its own regeneration directly and does not use the cache; the assembly state memoises nested parts.

Display caches

The wire body (face and edge JSON, display meshes) is cached too, because for a large part it costs as much as the features. The view snapshot is keyed by the final chain key, so an identical document, or one reverted to (undo, a slider moved back), replays the stored JSON and re-attaches the buffers; the default cap is 96 MB. The face meshes are cached per face by exact inputs (see tessellation); the default cap is 128 MB. Both are bypassed by noCache. A cosmetic edit gives a full hit and a view hit, and the reply is byte for byte the one a cold run would give.

Queries that use the cache

refDiff {base, part} regenerates two documents privately to find references that now point somewhere else (see persistent names). It finds the longest prefix the two documents share, takes the cached state just before the first changed feature and rebuilds only the rest of each. matchEdges {part} continues from the longest cached prefix of its part. Neither stores anything.

Why the replies are identical

A snapshot is the state after the feature, a restore re-creates exactly that state, and every later feature is a pure function of the state, the feature JSON and the variables. Thread-local geometry memos are keyed by content and persist across regenerations; the repository’s check runs noCache regenerations in a used instance against the replies of a fresh instance to guard against them.

Cost

The repository’s measurements were made on a 44-feature part with a 23 MB reply that is not published, so they cannot be reproduced from this book: about two minutes cold, under a second after removing or restoring the last feature, and tens of seconds after editing a feature in the middle. The 0.85 s or so of a full hit is tessellation and serialisation of the final body. What an edit costs is the features after the changed one plus that reply. Hashing and snapshots cost well under 5 percent of a cold run.

See also

Persistent names

A part refers to faces and edges of earlier features: “fillet these edges”, “sketch on this face”. The kernel names faces by how they were made, so a reference keeps meaning the same thing when a dimension upstream changes. This chapter describes the naming scheme, how references resolve, what keeps names stable, and where they break.

Face names

A face name has the form

<feature>.<role>[~<k>][@<instance>...]
partmeaning
<feature>The id of the feature that made the face: F2.
S.<entity>A side face swept from the sketch entity <entity> of the feature’s sketch: F2.S.e1. Extrude, revolve, sweep and loft all name side faces this way. Faces from a hole feature use h<n> for the hole’s entity: F4.S.h1.
C0, C1The end caps. C0 is the low end (an extrude: the minimum along the sketch normal, also when flipped; a revolve: the start angle) and C1 the high end. A full 360 degree revolve has no caps.
B<k>The k-th blend face (fillet or chamfer) of the feature, counted from 0: F3.B0.
V<k>, P<k>, W<k>, FA sphere corner patch of a fillet, a free-form corner patch, a thicken wall, a fill patch.
~<k>The k-th piece (1-based) of a face that was split into several.
@<feature>.<n>Copy n made by a pattern feature (the seed has no suffix); chained for nested copies and for parts inserted into assemblies: F8.S.h1@F9.1@F1.1.

Examples from runs of the kernel:

operationnames produced
extrude of a rectangle F1 by feature F2F2.C0, F2.C1, F2.S.e1 to F2.S.e4
cut by a circle extrude F4 through the blockthe block’s faces keep their names; the new wall is F4.S.e1 (a tool face keeps the tool feature’s id, with the sense flipped)
fillet F3 on one edgeF3.B0; the faces next to it keep their names
three fillets meeting at a convex cornerF3.B0, F3.B1, F3.B2 and the sphere patch F3.V0
a cut that splits a block in twoeach face that is cut in two becomes F2.C0~1 and F2.C0~2, and so on, and the body has two lumps
shell of a block through its top facethe opened top keeps F2.C1; every other face is split into its outer and inner wall, named ~1 and ~2 by centroid order, for example F2.S.e1~1 and F2.S.e1~2 (which number is the outer wall depends on the face)
pattern F5 with count 3 of a hole made by F4F4.S.e1 (seed), F4.S.e1@F5.1, F4.S.e1@F5.2
thicken F3 of a sheetthe layers keep the sheet’s names with ~k, and the walls are F3.W0, F3.W1, …

Several rules fix the suffix numbers and the order of faces so that they do not depend on rounding: a face split into several pieces is numbered by the lexicographic order of the pieces’ centroids, a closed spline that is cut at half its length gets its pieces numbered by the rank of their control-net box centres, and a face absorbed into another one by a union keeps its old name as an alias (below).

Edge names

An edge is named by the two faces it separates, in bytewise order, followed by its index in the exported edge list of the body:

F2.C1|F2.S.e1#2

The #2 is not persistent. It is the position of the edge in the edge list and changes whenever the topology of the body changes. A document therefore never stores an edge key. Features that need an edge, such as fillet, chamfer and pipe cut, store an edge reference:

{ "faces": ["F2.C1", "F2.S.e1"], "at": [20, 0, 10] }

The kernel takes the edge between the two named faces that lies nearest to the point at. The point is a tie-breaker between edges that are otherwise the same (two faces can meet along more than one edge), not the primary key. A reference whose face names are right survives a change of dimensions even when at is no longer exactly on the edge.

How a reference resolves

  1. Face names. Body::find_face looks for a live face whose name equals the string. If there is none, it looks for a face whose absorbed list contains the name. When two coplanar faces merge in a union, the surviving face keeps its own name and records the other’s name in absorbed, so a later feature that still refers to the old name finds the merged face. A test: after uniting a block with another block flush against it, a fillet on the edge between F4.C1 and F4.S.e3 still works, although F4.C1 has merged into F2.C1.
  2. Edge references. The two names are resolved as above, the edges whose faces are that pair are collected, and the one nearest at wins.
  3. No match. A face name that does not resolve fails the feature with missingReference, and an edge reference with missingEdge. describe gives a more helpful answer to a name that no longer exists: found: false, an error, and the three nearest names ranked by similarity (for F2.S.e9, it offers F2.S.e1 first).

Stability across edits

Names come from the construction, not from positions, so changing a number does not change a name. In the following run the same part was regenerated with three different block sizes and fillet radii (40 x 20 x 10 with r = 2, 60 x 35 x 15 with r = 4, and 10 x 10 x 30 with r = 1); the face lists were identical: F2.C0 F2.S.e3 F2.C1 F2.S.e1 F2.S.e4 F2.S.e2 F3.B0.

The repository measures this as a gate: edits of upstream dimensions across 37 test cases leave 214 of 216 edits with every reference still resolving to the same kind of geometry, and none resolving to a wrong entity. The two losses are edits that change the topology.

What breaks a name

  • Deleting or reordering an upstream feature can re-point a name without any error: the name still resolves, but to a different face than the author meant. This is the known weak point of the scheme, and the reason refDiff exists (below).
  • Edits that change the topology: a dimension that makes a face vanish, split in two, or merge with its neighbour. A ~k piece number is the order of the pieces’ centroids, so it can swap when the pieces move past each other; a shelled body’s ~1 and ~2 can change meaning after an edit that changes which wall is the outer one.
  • Split faces have no successor tracking. If F2.C1 is split into F2.C1~1 and F2.C1~2 by a later edit, a reference to F2.C1 stops resolving; nothing says which piece is meant.
  • Sketch entity ids. A side-face name embeds the id of the sketch entity (e1), so a sketch whose entity ids change renames its faces.

Comparison with a lineage-based proposal

A design proposal for another CAD project (read for ideas only, nothing taken from its code) lists failure classes of persistent naming and three rules: when a name is lost, fall back by lineage (among the faces the same feature made, scored by role and origin) and never by geometry alone; a suppressed maker is a reference that is waiting, not a lost one; a reference is never re-pointed to another body. Our rules against each, with the tests that pin them (crates/ck-model/tests/blend_naming.rs):

Failure classWhat we doTest
A blend edge pick falls back to a point on another bodyAn edge reference needs both face names (or their ~k family) to resolve. If either is gone the feature reports missingEdge, however close at is to another body’s edge. With valid names the names win over a stray point.names_beat_the_picked_point_on_another_body, lost_names_do_not_fall_back_to_a_point_on_another_body, half_lost_names_do_not_fall_back_to_a_point_on_another_body
The maker of a referenced face is suppressedThe dependants report an error (missingEdge for an edge pick, missingReference for a face pick). Nothing is re-pointed, a look-alike body is never rounded, and unsuppressing restores the exact result.suppressed_maker_is_not_repointed_and_recovers, suppressed_maker_with_a_lookalike_body_never_rounds_it, face_pick_of_a_suppressed_maker_is_not_repointed
A reference crosses to another bodyNever: a name belongs to one feature and one body, and the only position fallback (below) is limited to faces of the same two features.the three tests of the first row
A number edit upstream, or an unrelated cutThe pick keeps resolving: names come from the construction.upstream_number_edit_keeps_the_pick, upstream_cut_elsewhere_keeps_the_pick
A renamed sketch entity or a replaced maker idThe name changes with the entity or the feature id, so the pick is lost and reported, not re-pointed.renamed_entity_loses_the_pick_instead_of_repointing, replaced_maker_id_loses_the_pick
A face split by a later featureA reference to the unsplit name stops resolving; there is no successor tracking (see above). The one fallback is for edge picks: faces of the same two features whose ~k numbers shifted, the edge passing through at.not a failing case, documented under “What breaks a name”

Where our rule differs:

  • A suppressed maker is an error on the dependant, not a “waiting” state. The part regenerates with that error and recovers when the maker is back; the error names the face that is gone.
  • Our fallback when a name is lost is position-based but narrow (same two features, the edge through at within 1e-6 relative); there is no lineage score among the faces of a feature.
  • A split pick takes the piece nearest the point, not every piece.
  • Names are text, not structured records, so role and origin are parsed from the string.

Not covered by tests here: lineage scoring (we have none), stability of piece ordinals across kernels, and the two naming.stable edits of the gate that lose their references (both change the topology).

Finding out when references change

Two requests help an editor keep references valid.

refDiff {base, part} regenerates the previous document and the edited document privately, records which entity every face name and {faces, at} reference resolves to at the feature that uses it, and compares them. The comparison is by surface kind, direction, the kinds of the neighbouring faces, size (ratio between 0.25 and 4) and position, so an ordinary dimension change that keeps the topology does not warn. The reply is {ok, checked, warnings, features, errors}; a warning has code referenceChanged (the name now points at a different entity) or referenceLost (it no longer resolves), the feature that uses it, the ref, a reason, and before and after descriptions. features lists the ids removed and added and whether the order changed. References stored inside sketches or inside a nested part are not walked, and feature ids must be stable across the edit: an id that is re-minted looks like a removal plus an addition.

describe {names} returns the facts of a name (surface kind, size, direction, centroid, the feature and role, the adjacent faces and a one-line text), so an author can check that a reference means what they think. resolve {descriptions} goes the other way: given a description such as {kind: "face", surface: "plane", normal: "+z", extreme: "max"} it returns the matching names, each with a ready-to-store name and ref. If more than one entity matches, the status is ambiguous and every candidate is listed; the kernel never picks silently. For the full grammar see queries.

See also

Validation overview

This chapter explains what “valid” means for a body in this kernel, the layers that check it, and how to use them together. The other chapters of this part cover each layer in detail.

What valid means

A body is valid when the validator (ck-check) reports no issue for it. That is a specific claim, built from these tests:

  • Closed, oriented skin. Every edge is used by exactly two faces, and the two uses run in opposite directions. No edge is free, none is shared by three faces, none is unused.
  • Connected shells. The faces of a shell are reachable from each other through shared edges, and the Euler characteristic V - E + F - (L - F) of each connected piece is even and at most 2.
  • Positive solids. Each lump has a positive signed volume (its normals point outward) and exactly one outer shell. Voids are inner shells.
  • Closed loops. The coedges of every loop join head to tail, and the loops of a planar face do not cross themselves or each other.
  • Consistent geometry. Each vertex lies on the end of its edge’s curve, each edge lies on the faces that use it, and no edge is shorter than the tolerance. “Lies on” means within a tolerance that scales with position; see tolerances.
  • A watertight display mesh (in the validate request): every face has triangles, the mesh covers each analytic face’s area, and no mesh edge is used by only one triangle.

It does not say that two non-adjacent faces do not intersect, that a free-form surface is well behaved, or that the model has the dimensions you meant. The full list of what is and is not checked is in topology and geometry checks.

The layers

layerwhen it runswhat it tells youchapter
Construction checksInside the operations, on every regeneration.A boolean checks the topology of its result and its volume against the operands. A loft, a shell and a move-face validate the body they built. A failure becomes a feature error and the body stays as it was.operations
Feature errors and warningsIn every regen reply: errors and warnings.Which feature could not be built and why, with codes, parameters and hints.diagnostics
The validate requestOn demand, on the body of a tag.The independent B-rep checks, then the mesh check. ok and a list of {code, entity, detail}.validate, checks
Tessellation checksPart of validate (mesh: false skips them).That the display mesh has no holes, which is a witness for the closed shell.tessellation checks
ExpectationsOn demand: check {expect}.That measured values (volume, counts, bounding box, validity) match what you intended.analysis
HealingOn import (importStep), on demand (heal), or per feature (opts.autoHeal).Repairs what the validator reported, within a tolerance, and reports every repair.healing

The layers are independent. Construction checks catch an operation that cannot produce a sound body. Feature errors say which input was wrong. validate re-examines the final body with code that shares nothing with the operations except the data structure, so a defect that an operation missed is still found. Expectations check the model against intent, which no structural check can do.

How to use them together

A client that builds or edits a part, and an agent in particular, can follow this loop.

  1. Regenerate. Send regen and read errors. If it is not empty, fix the first feature in document order and regenerate; later errors are often consequences. See feature errors.
  2. Validate. Send validate for the same tag. An empty issues list means the body is a valid closed solid. If there are issues, the entity field points to faces, and the face name tells the feature that made it (F4.S.e1 came from F4).
  3. Separate mesh from B-rep. If the only issue is TESSELLATION_OPEN, repeat with mesh: false. Clean means the B-rep is sound and one face did not mesh; see tessellation checks.
  4. Check intent. Send check with the expectations you care about: valid, volume, faces, holes, bbox. Measure further with measure, section and probe where the numbers matter.
  5. Repair imports. For a body that came from a file, validate first. If it fails, heal (a dry run first, if you want to see the repairs), then validate again. Imported geometry that is a few thousandths of a millimetre off its faces is accepted by recording a tolerance on the edge, not by moving it.

A sequence on a 40 x 20 x 10 block with a hole:

regen            -> errors: []
validate         -> ok: true, issues: [], toleranceUsed: 0
check valid, volume equals 7497.35 (relTol 1e-6), holes equals 1   -> 3 passed

and on a block imported without its top face (heal: "off"):

validate         -> ok: false, SHELL_OPEN x4, EULER
heal (dry run)   -> fixed: [], remaining: the same 5 findings   (nothing to sew the free edges to)

Which tolerance applies

Modelling uses absolute tolerances of 1e-6 mm. validate uses the same default and scales it with position, so a body built here passes with a wide margin. The display mesh and its checks use tolerances relative to the size of the body. Edges and vertices of imported bodies can carry a tolerance of their own, up to a cap of 0.05 mm. Tolerances has the numbers.

Guarantees and their limits

  • Bodies the kernel builds are meant to be valid in the sense above. In the repository’s crash-fuzz run of 5000 random documents there were no traps and 24 invalid results (0.5 percent), on near-degenerate mirrored or revolved bodies.
  • Valid does not mean accurate: a mesh is a display approximation, and an imported body may carry tolerances.
  • Because a failed feature leaves the body unchanged, a body with errors in errors can still validate clean. A clean validate is no evidence that every feature ran.

See also

Topology and geometry checks

This chapter lists every issue code that the validator in ck-check can report: what it tests, the thresholds, what usually causes it and what to do. For how the checks are called and what the reply looks like, see the validate request.

How an issue is reported

An issue has three fields.

fieldcontent
codeA stable machine identifier, upper case with underscores.
entityWhat the issue is about. Faces use their persistent name (F2.C1). Edges are written edge#N[faceA|faceB] with the names of the faces that use the edge. Shells, lumps and components are shell#N, lump#N and component#N.
detailA sentence with the numbers.

The N in edge#N is the position of the edge in the body’s internal edge list. It need not equal the #N at the end of an edge key in a reply, because seam edges are internal and are not numbered there; use the face names to find the edge. Faces of imported bodies are named I1.F1, I1.F2 and so on.

The validator runs four groups of checks in this order: shell and edge use, loops, edges and vertices, solids. A body is valid when no check reports anything. tol is the model tolerance of the request (default 1e-6 mm) and cap the largest edge or vertex tolerance accepted (default 0.05 mm).

Shell and edge use

These tests establish that the faces form closed, consistently oriented skins.

codeentitymeaningtypical causefix
EDGE_UNUSEDedgeThe edge is used by no face.A face was deleted and the edge was left behind by a repair or an import.Healing flags edges without any face use as dead when it sews; otherwise remove the edge’s source.
SHELL_OPENedgeThe edge is used by only one face (a free or boundary edge). Detail: free (boundary) edge: used by 1 face.A missing face, a gap between two faces, edges of two faces that nearly coincide but were never joined (an import), a failed boolean. The solid is not closed.Heal with sewing (heal); for imports raise the sewing tolerance; add the missing face; in a modelling sequence, find the feature before the first issue and change the operands so the boolean can close.
SHELL_ORIENTATIONedgeThe two faces that use the edge run along it in the same direction.A face with a flipped sense, a loop with the wrong direction.Heal (fixOrientation) makes face senses consistent; a flipped face is FACE_FLIPPED in the report.
SHELL_NONMANIFOLDedgeThe edge is used by three or more faces. Detail: edge used by N faces.Two solids touching along an edge that were not split into two edges; a face glued onto an existing edge.Separate the touching parts into two lumps, or avoid exact contact along a line. Booleans split such contact edges themselves.
SHELL_EMPTYshellA shell with no live faces.A repair or edit removed every face of the shell.Heal drops empty shells (SHELL_REMOVED).
SHELL_DISCONNECTEDfaceThe faces of one shell are not all connected through shared edges. The entity is the first unreachable face; detail k of n faces reachable from the first face.Two solids or a solid and a void put in one shell by an import or an edit. The builders split such components into their own shells.Heal does not repair this code on its own: SHELL_SPLIT runs only after a sewing step that joined edges. The STEP importer separates components into lumps itself.
EULERcomponentFor an edge-connected component of the body, V - E + F - (L - F) is odd or greater than 2. The detail prints V, E, F and L.A component with free edges (the count of an open shell is odd, for example 1 for a box without one face), or an inconsistent loop structure.Fix the open edges first; the EULER issue then disappears. Genus is allowed: 2 for a block, 0 for one through-hole, -2 for two.

The Euler count is made per edge-connected component of the whole body, across shells, because a surface patch (from fill or knit) can sit in its own shell next to the shell it caps.

Loops

These checks look at the closed boundaries of faces.

codeentitymeaningtypical causefix
FACE_NO_LOOPfaceA planar face with no boundary loop. (A closed analytic face, a full sphere or torus, may have none and is accepted.)A repair or edit removed the boundary.Remove the face or rebuild it from its edges.
LOOP_EMPTYfaceA loop with no edges.As above.As above.
LOOP_OPENfaceThe end vertex of a coedge is not the start vertex of the next one, and their positions are farther apart than max(tol, vertex tolerances). Detail: coedge i end != coedge j start.A gap in an imported boundary, edges stored in the wrong order, a vertex that was moved.Heal merges near-miss vertices (within the healing tolerance) and re-chains the loop (VERTEX_MERGED, LOOP_CHAINED).
LOOP_SELF_INTERSECTfaceTwo non-adjacent edges of one loop of a planar face cross.A bow-tie profile, a bad trim.Redraw the profile or the trim. Not repaired.
LOOP_CROSSfaceAn outer loop and a hole of a planar face cross transversally.A hole that pokes out of its face.Move the hole inside or let the boolean cut through. Not repaired.

The crossing test works on the uv polylines of the loops. For faces with curved edges each coedge is subdivided (at least 2 and at most 12 levels) until the chord sag is below 1e-5 of the face size, and the crossing tolerance follows that sag, so thin annuli and near-concentric loops are not flagged. Touching at a shared vertex or running back over a bridge is not a crossing. Only planar faces are tested; loops of curved faces are not checked for self-intersection.

Edges and vertices

These checks compare the curves with the vertices and with the surfaces. The distance scale is scale = 1 + |position of the edge's start|.

codeentitymeaning and thresholdtypical causefix
EDGE_RANGEedget0 >= t1: an empty or reversed parameter range on the curve.A corrupt edit.Rebuild the edge.
VERTEX_OFF_CURVEedgeThe vertex is farther from the end of the edge’s curve than max(10 * tol * scale, edge tolerance, vertex tolerance). Detail: start vertex 1.000e-3 off curve.Imported geometry whose vertex positions disagree with the fitted curves; a vertex moved without its edges.Heal with tolerant: true records the deviation as a tolerance on the vertex or edge (up to cap); or move the vertex onto the curve.
EDGE_DEGENERATEedgeThe edge is shorter than tol (length of the curve over its range).A zero-length edge from a sketch with coincident points, a sliver left by a boolean.Heal removes degenerate edges whose ends were merged (EDGE_REMOVED). In modelling, avoid features smaller than the tolerance.
EDGE_OFF_SURFACEfaceThe edge curve does not lie on the face: at 9 points per coedge the distance between the surface at the pcurve’s uv and the edge curve exceeds max(10 * tol * scale, 1e-6 * scale, edge tolerance). The detail names the edge and whether the test used the pcurve or a projection (when the coedge has no pcurve).Exporters that fit B-spline faces a few 1e-3 away from the analytic surfaces they meet; a face moved without its edges.Heal with tolerant: true (cap 0.05 mm); for bodies built here this signals a defect to report.
EDGE_TOLERANCE_EXCEEDEDedgeThe edge’s own tolerance is above cap (default 0.05 mm).A toleranced edge from a repair with a larger cap than the validation cap.Raise healTolerance on the request, or repair the geometry instead of tolerating it.
VERTEX_TOLERANCE_EXCEEDEDedgeA vertex tolerance of the edge’s ends is above cap.As above.As above.

Solids

codeentitymeaningtypical causefix
VOLUME_NONPOSITIVElumpThe lump’s signed volume is zero, negative or not a number: the solid is inside out or degenerate. Detail: signed volume ... (inside-out or degenerate).All faces flipped; a degenerate solid made of slivers.Heal makes the lump outward (SOLID_FLIPPED). A degenerate solid must be rebuilt.
SOLID_MULTIPLE_OUTERSlumpOne lump holds more than one outer shell: closed components with positive volume beyond the first. Negative closed components are its internal voids and are fine.Two solids left in one lump.No request repairs this code and heal does not touch it; the STEP importer separates components into lumps itself, so it does not arise there.

A body can hold several lumps (a disjoint union, a cut that splits a part, a multi-solid import). Each lump is judged on its own and the entity names the lump, so breaking one solid does not hide the state of the others. Lumps that overlap each other are legal; the request reports that as information, not as an issue.

Display mesh

codeentitymeaning
TESSELLATION_OPENface, or several faces joined by |The display mesh has a hole although the B-rep is closed. Added by the validate request, not by the B-rep checks. See tessellation checks.

What the validator does not check

  • Intersection of faces that are not neighbours. Two walls that pass through each other, a body that crosses itself, or two lumps of one body that overlap are not reported as issues.
  • Whether a hole loop lies inside its outer loop on a curved face, or whether loops of curved faces cross.
  • Surface-level defects: a surface that folds over itself, a NURBS patch with a degenerate corner, a normal that flips inside the face.
  • Continuity between faces (tangency, curvature); see the continuity request.
  • That pcurves exist. A coedge without a pcurve is projected, and only its deviation is judged.

Reproduced and unit-tested codes

The following reproduce through the request interface: SHELL_OPEN and EULER (a block exported to STEP with one face removed, then imported without healing), SHELL_ORIENTATION (one face of that block flipped), VERTEX_OFF_CURVE (the coordinates of a VERTEX_POINT of the exported block moved by 1e-3), EDGE_OFF_SURFACE (the origin of an edge’s LINE moved by 1e-3), and VERTEX_TOLERANCE_EXCEEDED and EDGE_TOLERANCE_EXCEEDED (the tolerances that healing recorded for those two cases, 1.05e-3, checked against a cap of 1e-4); see the validate request. The other codes are covered by the unit tests of ck-check (a hole crossing its outer loop, a bow-tie polygon, two outer shells in one lump, a flipped solid, a shell with unreachable faces). They did not arise in the attempts made for this book through the request interface, because the STEP importer and the modelling operations repair or reject those defects before the validator runs (for example, a STEP file with all faces reversed, or with two solids in one shell, imports as a valid body).

See also

The validate request

validate runs the independent solid validator on the body of a tag and returns the issues it finds. This chapter gives the parameters, the reply, and examples including a deliberately broken body.

Request

{ "type": "validate", "tag": "main", "tol": 1e-6 }
fieldtypedefaultmeaning
tagstring"main"The state to validate: the body left by the last regen, importStep, importSat, importSldprt or importSkp on that tag.
tolnumber1e-6Model tolerance in mm. It scales the vertex, edge and loop tests; see tolerances.
healTolerancenumber0.05The cap on the tolerance recorded on an edge or vertex. A larger tolerance is an error (EDGE_TOLERANCE_EXCEEDED, VERTEX_TOLERANCE_EXCEEDED).
meshbooleantrueTessellate the body and check that the display mesh is watertight (TESSELLATION_OPEN). false skips the tessellation, which makes the request much cheaper on a large body.
opts.validateTimeMsnumber60000Wall-clock budget of the whole request in ms; 0 is unlimited. When it runs out the remaining checks are not run and the reply says which (see the time budget). Only enforced where the host provides a clock (the wasm module always does).
opts.quickbooleanfalseRun only the topology and bounding checks: the shell and edge-use checks, loop closure, and edge and vertex deviation. Leaves out the planar loop crossing test, the solid (volume) checks, the display mesh and its area witness, and the overlap scan of multi-lump bodies. See the quick mode.

The validator does not change the body.

Reply

{
  "ok": true,
  "issues": [],
  "toleranceUsed": 0
}
fieldmeaning
oktrue when issues is empty.
issuesAn array of {code, entity, detail}; see topology and geometry checks for every code.
toleranceUsedThe largest edge or vertex tolerance in the body, in mm. 0 when every entity is exact.
notesPresent when toleranceUsed is above 0: one sentence naming the largest tolerance and the cap.
statsAlways present: {totalMs, <check>: ms, ...}, the wall-clock time of the request and of each check that ran, in ms. The check names are shell, loops, edges, solids, tessellation, meshAreaWitness, meshOpenEdges and, for a body with several lumps, overlap. All 0 when the host has no clock.
validateBudgetExceededPresent when the time budget ran out; see below.
quick, checksSkippedPresent when opts.quick was set: true, and the names of the checks that were left out.
meshNotesPresent when the tessellator marked a face as suspect: strings <face>: <note>. Not issues; see tessellation checks.
infoPresent when the body has more than one lump and some of them overlap: one record per pair, {code: "bodiesOverlap", severity: "info", a, b, volume} with the names of the lumps when they have one. Overlap is legal (newBody, moveBody), so it is information, not an issue.

The request answers null as its result when the tag exists but holds no body (a document of only sketches, or one whose solid features all failed), and {"ok": false, "error": "noState: nothing regenerated yet"} when the tag has no state at all.

A solid body in the state is what is validated. Surface bodies (sheets from surfaceExtrude, fill, and similar) are kept apart from it, so a document whose features produce only sheets answers null. Features that turn sheets into solids (thicken, knit with solid) put the solid into the state.

What the request runs

In this order: the shell and edge checks, the loop checks, the edge and vertex checks, the solid checks (all from ck-check, with the tolerance and the cap above), then, unless mesh is false, the display mesh is built and its watertightness checked. The mesh check is an independent witness for the claim that the B-rep is a valid closed shell: a boolean can produce a body whose B-rep checks pass while one face lost its trims and meshes to nothing.

The time budget

The cost of validate grows with the number of faces, edges and loops, and the mesh checks (re-tessellation, and an exact area integral for every analytic face) cost as much as meshing the whole body. A request that would run for minutes is cut off instead: the budget opts.validateTimeMs (default 60 s) is checked between the checks and inside their long loops (each face, each edge, each loop segment, each face of the area witness). When it runs out, the checks that have not started are not run, and the reply is the honest partial result: the issues found so far, ok: false (a run that was cut short is not a clean bill of health), and

"validateBudgetExceeded": {
  "budgetMs": 60000, "elapsedMs": 60112,
  "checksNotRun": ["solids", "tessellation", "meshAreaWitness", "meshOpenEdges"],
  "checksPartial": ["loops"],
  "detail": "validate used up its time budget (opts.validateTimeMs); ..."
}

checksNotRun names the checks that never started; checksPartial the ones that were running and stopped early (their findings up to that point are in issues). Two stretches cannot be interrupted: the tessellation itself (it is one call; the budget is judged when it returns, and the mesh checks after it are then not run) and the volume integrals of the solids check. Raise validateTimeMs, set it to 0, or use the quick mode to get a full answer on a very large body.

The check order is shell, loops, edges, solids, then the mesh checks, then overlap; the cheap topology checks therefore always run first. The stats object of every reply shows where the time went.

The quick mode

opts.quick: true answers a sanity question about a big part without the expensive checks. It runs shell (every edge used by two faces with opposite directions, connectivity, Euler-Poincare), loops (closed loops; the planar crossing test loopCrossings is left out) and edges (vertex on curve, edge on surface, tolerances, degenerate edges). It leaves out loopCrossings, solids (positive volume, one outer shell per solid), tessellation, meshAreaWitness, meshOpenEdges and overlap; the reply names them in checksSkipped. A body that passes the quick mode can still fail the full request (an inside-out body, a face that meshes to nothing).

Growth with the size of the part

tools/validate_scale_check.mjs times validate on generated parts. Wall-clock seconds for the whole request (mesh on) on the build machine, no time budget:

facesplate with holesplate with joined padsdisjoint boxes (one lump each)
5002.10.100.08
1,0005.50.160.12
2,00010.50.330.23
4,00014.00.750.47

Growth is now close to linear in the number of faces. Two stretches used to grow with a power above 1 and were rebuilt on an index: the crossing test of the loops of a planar face (every pair of loop segments was compared; a plate with 500 holes spent 34 of 36 s there; the growth is quadratic, which puts a plate with 4,000 holes at roughly half an hour) and the overlap scan of a body with many lumps (a single-lump copy of the body was built, with a full clean-up pass per deleted face, for every lump; 333 lumps took 2 minutes and the growth is cubic, which puts 667 lumps at roughly a quarter of an hour). What remains is the display mesh: on a plate with thousands of holes the tessellation and the area witness are about three quarters of the time. Use stats to see where a given part spends its time, opts.quick for a cheap sanity check, and opts.validateTimeMs to bound the request.

Examples

A valid body

A 40 x 20 x 10 block with a radius 4 hole through it:

{ "type": "validate", "tag": "t" }
{ "ok": true, "issues": [], "toleranceUsed": 0 }

Every body the kernel builds from correct input should answer like this. The crash-fuzz runs generate random documents and count the bodies that do not; of 5000 documents, 24 produced an invalid result (TESSELLATION_OPEN, VOLUME_NONPOSITIVE or EDGE_OFF_SURFACE, mostly on near-degenerate mirrored or revolved bodies), and none produced a trap.

A broken body

Export the block to STEP with the step request, delete the last face from the CLOSED_SHELL list in the text, and import it without healing:

{ "type": "importStep", "tag": "bad", "heal": "off", "data": "<STEP text with 5 of 6 faces>" }

Then:

{ "type": "validate", "tag": "bad" }
{
  "ok": false,
  "issues": [
    { "code": "SHELL_OPEN", "entity": "edge#0[I1.F1]", "detail": "free (boundary) edge: used by 1 face" },
    { "code": "SHELL_OPEN", "entity": "edge#7[I1.F2]", "detail": "free (boundary) edge: used by 1 face" },
    { "code": "SHELL_OPEN", "entity": "edge#9[I1.F3]", "detail": "free (boundary) edge: used by 1 face" },
    { "code": "SHELL_OPEN", "entity": "edge#11[I1.F5]", "detail": "free (boundary) edge: used by 1 face" },
    { "code": "EULER", "entity": "component#0", "detail": "V-E+F-(L-F) = 1 (V=8 E=12 F=5 L=5)" }
  ],
  "toleranceUsed": 0
}

The four edges that bordered the missing face are free; the Euler count of five faces is odd. The heal request cannot repair this: it has nothing to sew the free edges to, and answers with the same five issues in remaining.

The same block with one face’s orientation flag flipped gives four SHELL_ORIENTATION issues, one for each edge of that face (two face uses run the same direction).

The effect of tol

Sketch the block on the front plane (the rectangle from (0, 0) to (40, 20), extruded 10), export it with step, add 1e-3 to the x coordinate of the CARTESIAN_POINT of one VERTEX_POINT (entity #22 in this export, the vertex at (0, 20, 0)), and import it with heal: "off". The entity numbers belong to this particular export; the effect is that one vertex lies 1e-3 mm from the ends of the curves that meet there. Which issues appear depends on tol:

requestresult
tol 1e-6 (default)two VERTEX_OFF_CURVE issues, start vertex 1.000e-3 off curve (on edge#0[I1.F1|I1.F6] and edge#11[I1.F5|I1.F6])
tol 1e-2ok: true

Moving each of the 8 vertex points by 1e-3 along each of the three axes (24 cases) gave VERTEX_OFF_CURVE and nothing else, and every case was repaired by heal.

Displacing a curve instead of a vertex gives edge-to-face deviations. Adding 1e-3 to x of the origin point of the LINE of edge 0 (entity #26) moves that straight edge off its two faces while its vertices stay put. The default tolerance then reports VERTEX_OFF_CURVE twice (the vertices are no longer on the displaced line) and EDGE_OFF_SURFACE on face I1.F6 (edge#0[I1.F1|I1.F6] pcurve deviates 1.000e-3); tol 1e-2 gives ok: true.

The comparison is against 10 * tol * (1 + |p|) with p the start of the edge’s curve: for an edge that starts about 20 mm from the origin the limit is about 2e-4 at the default tolerance and about 2 at 1e-2. Raising tol hides a defect rather than fixing it: after a validation at a loose tolerance the body is not exact to the tolerance of the operations that follow.

Tolerances and the cap

After heal with tolerant geometry the body from the vertex case carries a vertex tolerance of 1.05e-3 (VERTEX_TOLERANCE in the repair report), and the displaced-line case carries an edge tolerance of 1.05e-3 (EDGE_TOLERANCE). Both validate clean at the default cap:

{ "ok": true, "issues": [], "toleranceUsed": 0.00105,
  "notes": ["body carries edge/vertex tolerances up to 1.050e-3 mm (cap 5.000e-2)"] }

With a smaller cap (healTolerance: 1e-4) the vertex case reports one VERTEX_TOLERANCE_EXCEEDED per edge that ends in the vertex (three issues):

{ "ok": false,
  "issues": [ { "code": "VERTEX_TOLERANCE_EXCEEDED", "entity": "edge#0[I1.F1|I1.F6]",
                "detail": "vertex tolerance 1.050e-3 exceeds the cap 1.000e-4" },
              { "code": "VERTEX_TOLERANCE_EXCEEDED", "entity": "edge#1[I1.F1|I1.F5]",
                "detail": "vertex tolerance 1.050e-3 exceeds the cap 1.000e-4" },
              { "code": "VERTEX_TOLERANCE_EXCEEDED", "entity": "edge#11[I1.F5|I1.F6]",
                "detail": "vertex tolerance 1.050e-3 exceeds the cap 1.000e-4" } ],
  "toleranceUsed": 0.00105,
  "notes": ["body carries edge/vertex tolerances up to 1.050e-3 mm (cap 1.000e-4)"] }

and the displaced-line case reports a single EDGE_TOLERANCE_EXCEEDED on edge#0[I1.F1|I1.F6] (edge tolerance 1.050e-3 exceeds the cap 1.000e-4).

Overlapping lumps

A block and a second block added with op: "newBody" that overlaps it by 10 x 10 x 10 is valid, with the overlap as information:

{ "ok": true, "issues": [], "toleranceUsed": 0,
  "info": [ { "code": "bodiesOverlap", "severity": "info", "a": "F2.C0", "b": "F4.C0",
              "bName": "tool", "volume": 1000.0 } ] }

Using validate in a loop

A client that builds or edits a part usually calls regen, reads errors, and then validate with the default tolerance. If errors is empty and issues is not, the issues point at the body itself (the entity field gives the faces). The overview describes how to combine the layers. The check request with the expectation {"kind": "valid"} runs the same validator and counts the issues, so it can be combined with other expectations (volume, face count) in one call.

See also

Tessellation checks

The TESSELLATION_OPEN check compares the display mesh of a body with the B-rep it came from. This chapter explains what it measures, the exact thresholds, and why it can report a hole on a body whose B-rep checks pass (and, less often, stay silent on a mesh with a hole).

Why there is a mesh check

The B-rep checks of topology and geometry checks look at the data structure. A boolean can still assemble a body that passes them while one face lost its trim loops and has no triangles; on screen the face is a see-through patch. The mesh is the cheapest independent witness of the claim “this is a closed shell”. The check lives in ck_check::tessellation and works on plain arrays (the mesh positions and the face index of every triangle), so ck-check does not depend on the tessellator. The validate request tessellates the body and passes the arrays in; mesh: false skips it. regen does not report it (the only other caller of the mesh test is a regression test in ck-ops).

What an open mesh edge is

The mesh is unwelded: three vertices per triangle. The check welds it first, then looks at the edges of the triangles.

  1. Weld. Positions are put on a grid of cell size q and two vertices are the same if their distance is at most q, where

    q = max(1e-5 * hi, 1e-4)        hi = the largest absolute coordinate in the mesh
    
  2. Count uses. For each pair of welded vertices (a mesh edge), count the triangles that use it. Edges whose two ends welded into one vertex are ignored. An edge used by exactly one triangle is open. In a watertight closed mesh every edge is used by two triangles. An open edge belongs to the face of its triangle.

Counted this way, a block with one face removed has 4 open edges, and a block has none.

What the check forgives

Two faces that share an edge both use the edge’s samples, so ordinarily no seam appears. A crack still can come from two sources: a trim curve that ends at a cusp, and an edge that two faces sampled differently. A tolerance crack separates that hairline from a hole:

crack = max(2e-3 * hi, 0.01)

An open edge is dropped from the count when either of these holds:

  • Both ends near another face’s open edge. Both end points lie within crack of an open edge that belongs to a different face. Two faces that sample their shared edge with different points (a T-junction) leave pairs of such edges.
  • Covered. Nine samples along the edge all lie within crack of a triangle of another face. The neighbour covers the edge to within the chord deviation.

The remaining open edges are reported as one issue:

{ "code": "TESSELLATION_OPEN",
  "entity": "F2.C1|F2.S.e1",
  "detail": "12 mesh edges are used by a single triangle (the display mesh has holes)" }

The entity lists up to six faces with open edges, in face order, joined by |.

The other two reports

The same code is used for two more findings, reported per face.

  • No triangles. A face of the body that has no triangle in the mesh. The detail says whether the tessellator failed and why: face has no mesh triangles (tessellation failed: face produced no triangles). The reasons are loop winds a period, face has fewer than 3 boundary points and face produced no triangles; if the face is simply absent from the mesh the text ends in (no triangles).
  • Area mismatch. For a plane, cylinder, cone, sphere or torus face, the mesh area is compared with the exact area (an exact integral). The face is reported when the mesh area is below 90 percent or above 110 percent of the exact area and the difference also exceeds 5e-4 * hi * hi. The second condition keeps slivers and specks, whose inscribed polygon cannot be seen to differ, out of the report. The detail reads the mesh covers 62% of the face area (a of b). This catches a face meshed only partly, for example a cylinder wall triangulated around its cut-outs but not along its length, which shows no open edge of its own. Free-form faces are not tested, because their exact area costs more than meshing the whole body.

Numbers for a small part

For a 40 x 20 x 10 mm block, hi is 40, so the weld distance is q = 4e-4, the crack tolerance is 0.08, and the area floor is 5e-4 * 40 * 40 = 0.8 mm squared. A part that sits far from the origin has a large hi, so all three thresholds grow with its distance from the origin: a 10 mm part at x = 1000 has q = 0.01 and crack = 2.

Why it can fire on a valid B-rep

The check fires on the mesh, so any cause that damages the mesh and not the B-rep shows up. In order of how often they occur:

  1. The tessellator gave up on a face. Trim loops that touch or cross by a few 1e-6, a loop that winds around a periodic direction, a face whose boundary graph has an odd-degree vertex, trim segments the triangulation could not restore. validate returns the tessellator’s notes for faces that meshed but are suspect, as meshNotes.
  2. A face meshed only partly. The area check.
  3. Edges sampled differently by their two faces. A hairline wider than crack. Edges are sampled once and shared by their faces, so this is rare.
  4. A thin or tiny feature. Features smaller than the weld distance q collapse; a near-degenerate body (a disc 5e-4 mm high) meshes to tens of thousands of slivers.

The crash-fuzz runs found TESSELLATION_OPEN together with VOLUME_NONPOSITIVE and EDGE_OFF_SURFACE on mirrored and revolved near-degenerate bodies.

To separate a mesh problem from a B-rep problem, run validate with mesh: false. If that is clean and the default is not, the B-rep is probably fine and the tessellator could not mesh a face. Then:

  • read meshNotes and the detail of the issue to find the face;
  • check the face with describe and the surrounding features for a trim that nearly coincides with another edge;
  • change the feature that produced the face by a small amount (a tenth of a millimetre) and compare;
  • if it is a real case, keep the document: tessellation failures of valid bodies are bugs and the document is the regression case.

Limits of the check

  • A hole bounded by several faces can be forgiven. The first forgiveness rule looks only at the end points of an open edge. When a face is missing from the mesh and the faces around it each contribute one open edge, every open edge ends at the corner where its neighbour’s open edge ends, so all of them are dropped. A block exported without its top face has 4 open mesh edges by the strict count and the validator reports only SHELL_OPEN and EULER, no TESSELLATION_OPEN. A face with no triangles is still caught by the first report above, and a body with free edges is caught by the B-rep checks, so the rule only matters when both are clean.
  • Free-form faces are not area-checked. A B-spline face with a part of its mesh missing is found only through its open edges.
  • Two overlapping lumps are not a mesh hole. The check does not look at intersections.
  • The mesh is a display mesh. Passing says the mesh has no visible holes, not that it is accurate; see tessellation for the chord tolerance and its volume error.

See also

Tolerances

This chapter explains which tolerances the kernel uses, what each one means, which operations use which default, how a tolerance gets from a request to the code, and what the tolerance fields on edges and vertices do. All lengths are in millimetres.

Two kinds of tolerance

  • Absolute tolerances are model distances. Two points closer than 1e-6 mm are the same point; an edge may lie 1e-6 * (1 + |p|) * 10 from its face. They apply to geometry, whatever its size.
  • Bounding-box-relative tolerances scale with the size of the body. They belong to display and verification, not to geometry: the tessellation chord height, the thresholds of the mesh check, and the sag of a section.

Mixing the two is deliberate. Modelling must not depend on how big a part is, so its tolerances are absolute. A picture of a 1 m part and a 10 mm part should look alike, so tessellation is relative.

Where each tolerance comes from

quantityvaluewhere it is used
Model tolerance TOL1e-6Passed by the feature layer to every operation in ck-ops: the welding distance of the boolean, the tolerance of the intersections, knit, thicken, trim, extend, fill, pipe cut, and the tolerance of the validator in a few self-checks.
Shared constants in ck-coreEPS_LINEAR 1e-6, EPS_POINT 1e-9, EPS_PARAM 1e-12, EPS_MACHINE 1e-15, EPS_COARSE 1e-3Zero tests and coincidence tests inside geometry code.
Boolean welding retries10 x and 100 x TOLWhen a boolean does not close. Free-form operands start at 10 x. Robust mode repeats 10 x, 1 x, 100 x.
Fuzzy valuefeature field tolerance, mm; autoFuzzy tries 1e-7, 1e-5, 1e-3Snaps nearly coincident planes, cylinders and spheres of a tool onto the host before a boolean.
IntersectionTOL 1e-6; marched curves fitted to tol / 100ck-ops::intersect.
Extrude depth floor1e-6A depth of zero or less is raised to it.
Sweep profile-normal check5e-5 on abs(t . n) - 1sweepProfileNotNormal.
Loftvalidator at 1e-6Whether the default matching of stations gives a valid body; if not, other matchings are tried.
Free-form offset fit1e-5 surfaces, 3e-3 edge curvesShell and offset of free-form faces.
Free-form blend fitabout 1.2e-5Rolling-ball fillets of free-form edges.
projectCurvefield tolerance, default 0.001; chain join 1e-3The fit of the projected curve, and the distance within which runs are joined.
editCurvefield tolerance, default 0.01Fit of an edited curve.
Point classificationwithin 1 percent of the box diagonal of the boundary: nearest-feature test; farther: winding numberck_topo::region::classify.
Operands far from the origincentre farther than 1e4 diagonalsBoolean works in local coordinates.
Tessellationchord max(1e-3, 4e-4 * diagonal), angle 0.3 radSee tessellation.
Sectionsag 2e-5 * diagonalsection: curved segments are bisected until the chord sag is below it.
check expectationsrelative 1e-4 for volume and area; 1e-4 of the diagonal for boxescheck, unless tol, relTol is given.
Validator tol1e-6 (request field tol)validate; see below.
Heal tol1e-4 on import, 1e-5 for the heal requestRepair distance; detection runs at min(tol, 1e-6).
Tolerance cap0.05 mm (request healTolerance)Largest tolerance that may sit on an edge or vertex.

How a tolerance is chosen and passed

  1. Modelling. ck_model::features::TOL is the single value handed to the operations. A feature does not choose its own, with these exceptions: the fuzzy tolerance field of any feature that runs a boolean, the tolerance fields of projectCurve and editCurve (fit tolerances), and operations that need a looser internal value (offset fits, blend fits). A fuzzy tolerance must be positive and finite, otherwise it is treated as 0 (exact).
  2. Booleans. Called with TOL, then retried with the ladder in operations. The tolerance that finally decided a boolean is reported as the warning booleanFuzzy.
  3. Validation. validate takes tol from the request, default 1e-6, and passes it into every test of the validator. The same number is also the one used by the repair pass to detect what to repair.
  4. Tessellation. Computed from the body by body_tol; not set by the request.
  5. Cache. Results do not depend on a tolerance that is not in the document, so none is part of the regeneration cache key except autoHeal and healTol.

The validator’s formulas

With scale = 1 + |p|, where p is the start of the edge’s curve:

testpasses when
vertex on its edge’s curve enddistance <= max(10 * tol * scale, edge.tol, vertex.tol)
edge on its face (9 samples per coedge)deviation <= max(10 * tol * scale, 1e-6 * scale, edge.tol)
loop closure (end of a coedge to start of the next)same vertex, or distance <= max(tol, both vertex tolerances)
edge not degeneratelength >= tol
edge or vertex tolerance<= cap

The factor 10 and the scale make the test insensitive to rounding in coordinates far from the origin. The test is therefore looser than the working tolerance of the operations by at least a factor of 10, and more for parts far from the origin, which is why a freshly built body passes with room to spare.

Tolerance fields on edges and vertices

Every Edge and every Vertex has a tol (default 0, meaning exact).

  • Edge tol is the largest distance the edge’s curve may lie from the faces that use it. Imported B-spline faces often sit a few 1e-3 mm away from the analytic faces they meet, and no single curve lies on both.
  • Vertex tol is the largest distance the vertex may lie from the end of each incident edge curve.
  • Only repair sets them. Modelling operations create exact entities. split_edge copies the tolerance to both halves and Body::append clones it.
  • The validator honours them: a deviation up to max(model tolerance, the entity's own tolerance) passes; a tolerance above the cap is an error.
  • Results. The validate reply has toleranceUsed (the largest value in the body) and, when it is not 0, a notes sentence.
  • Not propagated. Booleans and blends build new, exact edges; the result is exact where it is new. fillet and chamfer refuse an edge that carries a tolerance with blendTolerantEdge. Mass properties, tessellation (edges are shared polylines, so there are no cracks) and STEP export ignore the tolerance.

The heal request sets edge and vertex tolerances when asked (tolerant: true): per edge, the largest distance of its curve to its faces (the validator’s 9 sample points, 8 intervals, then 33 where those fail), multiplied by 1.05, when it is above the strict tolerance and within the cap. A deviation above the cap is reported, not repaired. See healing.

Choosing a tolerance in practice

  • Leave tol at the default for bodies the kernel built. A finding at 1e-6 on such a body is a defect, not a rounding problem.
  • For imported bodies, validate at the default first, then decide: heal with tolerant: true (the tolerance is recorded and stays on the body), or validate with a larger tol for a one-off judgement. The first is preferable because later operations see the tolerance.
  • For a boolean that fails on nearly coincident faces, use the feature’s fuzzy tolerance (between 1e-5 and 1e-3) or autoFuzzy, not a larger welding tolerance; raising the welding tolerance for the whole arrangement makes every decision in it fuzzy.
  • Do not try to control the display mesh through tolerances; see tessellation.

See also

Healing

ck-heal repairs the defects that the validator finds in a body: gaps, free edges, misordered or reversed loops, flipped faces, inside-out solids, and geometry that is a little off its faces. It is meant for imported bodies and for bodies that a failed edit left damaged. This chapter lists what it detects and repairs, how to call it, and what it does not do.

Principles

  • Driven by the validator. Healing first runs the validator at a strict tolerance (min(tol, 1e-6)) and only touches what it reports. A valid body is returned unchanged: healing is a fixed point on valid bodies, and a test in the repository checks that no fix is recorded and that the volume agrees to 1e-12.
  • Repair within tol. Detection is strict; repair may move things by up to the healing tolerance tol.
  • Every repair is reported as {code, entity, detail}, and the findings that are left as remaining.
  • Geometry stays. Healing changes topology (vertices merged, edges sewn, loops re-chained, faces flipped) and records tolerances. It does not move or refit curves and surfaces to a compromise position.

The passes

The passes run in this order, and the sequence repeats up to four times while it keeps changing something.

passtriggered bywhat it doesreport codes
Near-miss verticesSHELL_OPEN, LOOP_OPEN, EDGE_DEGENERATE, EDGE_UNUSEDMerges vertices closer than tol that bound an unpaired or tiny edge, or lie on both sides of a loop gap. Only these candidates are considered, so healthy vertices are never touched.VERTEX_MERGED
Degenerate edges and facesEDGE_DEGENERATEDrops edges shorter than tol whose ends were merged from every loop, and deletes faces left without a loop (never the last face of a shell).EDGE_REMOVED, FACE_REMOVED
LoopsLOOP_OPENRe-chains the coedges of a loop head to tail by a bounded depth-first search (up to 8 solutions), flipping coedges that run against the chain, and splits a loop that closes early into several.LOOP_CHAINED, LOOP_UNFIXED
SewingSHELL_OPEN, EDGE_UNUSED, SHELL_EMPTYPairs free edges that join the same two vertices and coincide: 5 sample points of the two curves within 5 * tol, in the same or the opposite direction. The two become one edge with two coedges. Then shells and lumps of the joined faces are merged, shells that fell apart are split, empty shells dropped.EDGE_SEWN, SHELL_MERGED, LUMP_MERGED, SHELL_SPLIT, SHELL_REMOVED
OrientationSHELL_ORIENTATION, VOLUME_NONPOSITIVEReverses loops against their face sense, flips faces that disagree with their neighbours, and turns an inside-out solid outward.LOOP_REVERSED, COEDGE_FLIPPED, FACE_FLIPPED, SOLID_FLIPPED
Tolerant geometrytolerant: true, after the structural passesGives an edge whose curve lies farther from its faces than the strict tolerance a tolerance equal to the measured deviation times 1.05 (9 sample points first, 8 intervals, then 33 where those fail), provided that is within the cap. Gives vertices farther than that from their edge ends the same treatment.EDGE_TOLERANCE, VERTEX_TOLERANCE

The pass switches are sew (near-miss vertices, loop gaps and sewing), fixSmall (degenerate edges and slivers), fixOrientation, and tolerant.

Calling it

The heal request

{ "type": "heal", "tag": "main", "tol": 1e-5,
  "heal": { "sew": true, "fixSmall": true, "fixOrientation": true, "tolerant": true, "cap": 0.05 },
  "dryRun": false }
fielddefaultmeaning
tag"main"The state to repair.
tol1e-5Healing tolerance, mm. A value in heal.tol is used when tol is not given.
healall passes onAn object with the switches above and tol, cap. "off" or false runs the structural passes only, without the tolerant pass.
healTolerance0.05The cap on a tolerance that may be recorded (the same as heal.cap).
dryRunfalseReport what would be repaired and leave the body alone.
damagenoneA self-test: break a copy of the body in a named way, repair that copy, and report whether the repair restored it. The body in the state is not changed.

Reply:

{ "fixed": [ { "code": "VERTEX_TOLERANCE", "entity": "vertex#0", "detail": "vertex tolerance set to 1.050e-3" } ],
  "remaining": [],
  "volume": { "before": 8000.0, "after": 8000.0 } }

fixed and remaining are described above; remaining has the shape of validate issues. volume is the volume before and after, a quick check that nothing moved. Unless dryRun or damage is given, the repaired body replaces the state of the tag.

Healing on import

importStep heals by default with tol 1e-4. (The SAT, SolidWorks and SketchUp import requests do not run the repair pass; call heal on their tag afterwards if the body needs it.) heal: "off" disables it; heal: {tol, sew, fixSmall, fixOrientation, tolerant, cap} tunes it, and healTolerance sets the cap. The reply has import.heal with the number of repairs, the number of findings left, and the largest tolerance used:

{ "solids": 1, "faces": 6, "heal": { "fixed": 1, "remaining": 0, "toleranceUsed": 0.00105 } }

Healing during regeneration

opts.autoHeal: true (with opts.healTol, default 1e-5) tries a repair pass after every feature that leaves validator issues. The healed body is kept only if it has fewer issues than before, and the feature gets a healed entry with the number of fixes, the codes and the number left. The entry is written to errors (not warnings); a feature that already has an entry keeps it.

The Rust API

ck_heal::heal(&mut body, tol) -> HealReport and heal_with(&mut body, &HealOpts); HealOpts { tol, sew, fix_small, fix_orientation, tolerant, cap } (the constructor HealOpts::new leaves tolerant off, the request turns it on).

Examples

The damage self-test breaks a block in seven ways and repairs the copy (tolerance 1e-5). All seven are restored, with the volume unchanged (the tiny case moves it by 1.3e-6):

damagewhat it doesrepairs reported
detachUn-sews one face, shifting it by 2e-6.4 x VERTEX_MERGED, 4 x EDGE_SEWN
shellsDetaches half of a shell into a new lump.8 x VERTEX_MERGED, 8 x EDGE_SEWN, SHELL_MERGED, LUMP_MERGED
flipFlips one face.FACE_FLIPPED
invertFlips every face.SOLID_FLIPPED
reverseCoedgeReverses one coedge.LOOP_CHAINED
shuffleSwaps two coedges of a loop.LOOP_CHAINED
tinySplits an edge 1e-9 of its length from its start.VERTEX_MERGED, EDGE_REMOVED

The 40 x 20 x 10 block sketched on the front plane (entity numbers as in the validate request), exported, imported with heal: "off", with 1e-3 added to x of one VERTEX_POINT’s coordinates (the vertex then lies 1e-3 from the curves that end there):

requestresult
default (tolerant on)fixed: VERTEX_TOLERANCE 1.05e-3; remaining: none
heal: {"tolerant": false} or heal: "off"nothing fixed; remaining: the two VERTEX_OFF_CURVE findings
heal: {"cap": 1e-4}nothing fixed; the deviation is above the cap, so the findings remain

If instead the origin of the LINE of one edge is displaced by 1e-3 (the curve moves, the vertices do not), the default repair records EDGE_TOLERANCE 1.05e-3, and tolerant: false leaves two VERTEX_OFF_CURVE and one EDGE_OFF_SURFACE. In a scan that moved every CARTESIAN_POINT of the export by 1e-3 along each axis, 27 of 81 cases stayed valid (points whose move is invisible, such as an axis origin), 24 gave only VERTEX_OFF_CURVE, 6 only EDGE_OFF_SURFACE, and 24 both; every failing case was repaired by tolerant healing within the default cap. A displacement of 1e-2 gives a tolerance of 1.05e-2, within the cap of 0.05.

Limits

  • Missing material. A face that is absent cannot be invented. A block with one face removed has four free edges and nothing to sew them to; heal leaves all five findings (SHELL_OPEN x 4 and EULER) in remaining.
  • Gaps larger than tol. Vertices are merged and edges sewn only within tol (and curves must agree within 5 * tol). Larger gaps are reported.
  • Deviations above the cap. An edge or vertex that is farther off than cap is not given a tolerance. Raise the cap, or repair the source.
  • Not repaired. SHELL_NONMANIFOLD, EULER on its own, LOOP_SELF_INTERSECT, LOOP_CROSS, FACE_NO_LOOP, EDGE_RANGE and SOLID_MULTIPLE_OUTERS have no repair pass, and neither has SHELL_DISCONNECTED on its own: a body whose only finding is that code is never touched (the SHELL_SPLIT fix runs only after a sewing step that joined edges). (The STEP importer separates multiple outer shells into lumps itself.)
  • Tolerant edges are not free. Booleans and blends build new exact edges and do not propagate tolerances, and fillet and chamfer refuse a toleranced edge with blendTolerantEdge. To model on an imported part, heal it, then use features that do not need those edges, or rebuild the region.
  • Order of results. The fixes of a pass follow the order of the entities in the body, so the report is deterministic for a given body.

See also

Feature errors and diagnostics

When a feature cannot be built, the regeneration reply says which one and why. This chapter explains how errors are produced, how to read the errors array, how to tell a root cause from a consequence, and what the main codes mean and what to try.

Where errors come from

Three layers produce them.

  1. The regeneration driver (ck-model::regen) checks what is true of every feature before any geometry runs: the type is known (unknownFeature), a sketch that a feature names exists and was regenerated before it (missingSketch), a nested part is present (insertPartMissing), and the time budget has not run out (featureBudgetExceeded, regenBudgetExceeded).
  2. The feature layer (ck-model::features) reads the feature’s fields, evaluates expressions, and resolves references. It produces the codes about input: badExpression, invalidValue, missingReference, missingEdge, noClosedProfile, nothingToCut, and the per-feature codes (holeInvalid, ribNoContact, …). It also maps the failures of operations into errors, adding a hint where it knows a remedy.
  3. The operations (ck-ops) return a code and a detail when the geometry cannot be built (blendOverflow, shellTooThick, booleanFailed, loftFailed, …). The feature layer copies them into the error’s parameters.

A failure never leaves a half-built body: the operations either return a new body or an error, and the body of the state stays as it was. See regeneration.

The shape of an error

["F3", { "code": "blendOverflow",
         "params": { "detail": "F3.B0: spring leaves its face away from its edges" } }]
partmeaning
"F3"The feature id. The empty string when a failure belongs to no feature.
codeA short camelCase identifier; the part to switch on.
paramsAnything else that helps: detail (a sentence about what failed, often naming faces), hint (what to change), and code-specific numbers (max, limit, maxThickness, faces, at, gap, budgetMs, elapsedMs, cause, …). The object is empty when the code says it all.

The code notImplemented marks a feature or option that is not built yet (for example a twisted sweep along a multi-piece path, or the dome feature). Its what parameter names the feature or option. The code is stable; the set of cases that return it shrinks as they are built.

A second array, warnings, has the same shape. A warning does not stop the feature: the body is built and the warning says that something was approximated or chosen. Warnings appear in the reply only when there is at least one.

Misspelled fields

A field that a feature does not read is ignored, so a misspelling leaves the default in force: "depht": 10 on an extrude builds the 1e-6 slab of depth: 0, with no error. For the feature types in the table below, the driver compares the feature’s fields with the names the type reads and adds an unknownField warning per feature that has others.

["F2", { "code": "unknownField",
         "params": { "detail": "extrude has no field `depht`; it is ignored",
                     "fields": ["depht"],
                     "suggest": { "depht": "depth" },
                     "hint": "`depht` -> `depth`" } }]

The warning above is what the kernel returned for an extrude of a 10 x 10 square sketch that says "depht": 10 and no depth.

  • It is a warning, never an error: the feature runs exactly as it would without the extra field, and the rest of the reply is unchanged. A part with no unknown fields has no warnings entry for this.
  • fields lists the unknown names in document order. suggest has an entry only for names within two edits of a known field (a swapped pair of letters counts as one edit; so does a difference of case).
  • Always accepted, for every feature: id, type, num, name, suppressed, the editor fields group, autoName, visible, userHidden and after, and the boolean fields tolerance and autoFuzzy. A sketch also carries the editor fields seq, prop and gear. Keys inside a field’s value (the members of thin, endRef or an edge pick) are not checked.
  • A suppressed feature is not checked. A feature type that is not in the table is not checked; the table starts with the most used types and grows with the format.
TypeFields it reads
sketchplane, points, entities, constraints
extrudesketch, op, end, depth, flip, draft, draftOut, twist, twistCentre, regions, thin, endRef, offset, strictEnd, body
revolvesketch, op, axis, angle, end, flip, regions, thin, body
filletradius, edges, profile, propagate, filletType, radii, rho, rhos, shape, side1, center, side2
chamferchamferType, distance, distance2, distance3, angle, face, flip, propagate, edges
holesketch, standard, size, fit, kind, diameter, end, depth, tip, flip, cboreDiameter, cboreDepth, cskDiameter, cskAngle

The list lives in one table in ck-model (features/known_fields.rs); a test checks that no part of the test corpus produces the warning.

Reading the errors array

  • Sorting. Errors are sorted by the feature id compared as a string, so F10 comes before F3. There is one entry per feature; a second error for the same feature replaces the first. To read them in the order the features ran, sort by the feature’s position in the document.
  • Features are independent. After a failure the run goes on with the unchanged body. The reply has no link between an error and the feature that caused it, and no blockedBy field.
  • Root cause and consequences. Take the errors in feature order. The first one is a root cause. A later error is probably a consequence if it has one of the codes missingReference, missingEdge, missingSketch, nothingToCut or noBodies, and the thing it cannot find is made by an earlier failed feature. Errors of another kind (a different feature failing for its own geometric reason) are independent roots. Fix the first root and regenerate; the consequences usually disappear.
  • A failed feature that nothing depends on is not a consequence of anything and does not hide later features. In the run below F5 is built although F3 and F4 failed.

A run on a 40 x 20 x 10 block:

[
  { "type": "fillet",  "id": "F3", "radius": 30, "edges": [ { "faces": ["F2.C1", "F2.S.e1"], "at": [20, 0, 10] } ] },
  { "type": "chamfer", "id": "F4", "chamferType": "equal", "distance": 1,
    "edges": [ { "faces": ["F3.B0", "F2.C1"], "at": [20, 2, 10] } ] },
  { "type": "chamfer", "id": "F5", "chamferType": "equal", "distance": 1,
    "edges": [ { "faces": ["F2.C1", "F2.S.e3"], "at": [20, 20, 10] } ] }
]
{ "errors": [
    ["F3", { "code": "blendOverflow", "params": { "detail": "F3.B0: spring leaves its face away from its edges" } }],
    ["F4", { "code": "missingEdge", "params": {} }]
  ] }

F3 is the root: a radius of 30 does not fit a 10 mm edge, so no face F3.B0 exists. F4 refers to F3.B0 and fails with missingEdge: a consequence. F5 is independent and builds (the body has 7 faces). With F3 suppressed, F4 still fails.

The debug trace

A request with "debug": true returns a trace array of spans: one per feature with the result, nested spans inside (one per stage of a boolean, one per blend), and for failures a span that names the code:

[
  { "at": 0, "ms": 0, "depth": 1, "label": "F3 fillet: blendOverflow {\"detail\":\"F3.B0: spring leaves its face away from its edges\"}", "level": "span" },
  { "at": 0, "ms": 0, "depth": 2, "label": "F3: Fillet(30.0, Circular) of 1 edge", "level": "span" },
  { "at": 0, "ms": 0, "depth": 2, "label": "F3 failed: blendOverflow {\"detail\":\"F3.B0: spring leaves its face away from its edges\"}", "level": "span" }
]

(at and ms are 0 here because the host in this run supplied no clock; a real host gives milliseconds.)

Successful features read F2 extrude → 6 faces. The trace is the quickest way to see where time went and which stage failed. Requests with debug bypass the regeneration cache.

Hints and repair advice

The feature layer attaches a hint to codes where the remedy is known. Examples (the text is part of the reply):

codehint, shortened
booleanFailedThe operands’ intersection could not be closed; usually tangent faces, coincident faces or a sliver thinner than 1e-3 mm. Move the tool by 0.01, unite bodies that touch first, split the tool, or give the feature a fuzzy tolerance (1e-5 to 1e-3) or autoFuzzy.
booleanVolumeMismatchThe result is valid but its volume is impossible for these operands; a circle or edge of the tool lies exactly on the other solid’s wall. Nudge the tool by 0.01, change the feature order, or split the tool.
holeInvalidgive a standard size (e.g. M6), or a plain diameter
invalidValue with newBody on a feature that does not support itnewBody is accepted by extrude, revolve, loft and sweep; build the solid with one of them (op newBody), then use combine, moveBody or a pattern
featureBudgetExceededReduce the amount of geometry the feature works on (pattern count, number of edges), split it, or raise featureTimeMs.

The verify function of the agent driver package (packages/driver) wraps regen, validate and check in one call, and turns each error and issue into a {feature, code, hint} record with advice for about thirty codes. It is a client-side layer; the kernel itself returns the codes and parameters described here.

The main codes

Input and references

codemeaningtry
unknownFeature (type)The feature type is not one the kernel knows.Check the spelling against the feature list.
missingSketchsketch names no earlier sketch.Point it at an existing sketch that comes before the feature.
missingReferenceA face, plane, body or feature that the field names does not resolve.Use the names in the latest body.faces; see persistent names. describe suggests the nearest names.
missingEdgeAn edge pick {faces, at} finds no edge between the two faces, or the selection is empty.Check both face names exist and share an edge.
missingAxisA revolve names no axis line.Give the id of a line entity of the sketch.
badExpressionAn expression in a field cannot be evaluated: unknown variable, syntax error, cyclic variables.Check variables and the field.
invalidValueA number is outside its range (radius or thickness not positive, unknown option), or an option the feature does not support. detail and hint explain.Fix the value.
noClosedProfileThe sketch has no closed region to extrude or fill.Close the profile; check for gaps between entities.
nothingToCutThe feature needs a body and none exists yet.Put a body-making feature before it.
noBodies, noFaces, noSeedsA delete, move or pattern has nothing to act on.Check the selection.
unsupported (what)A variant of a feature the kernel does not implement.Use another variant.

Booleans

codemeaningtry
cutNoEffectA cut or intersection changed nothing: the tool misses the body, or only touches it.Flip the direction (flip), move the sketch so it overlaps the body, or use throughBoth.
booleanFailedThe result did not close. Parameters may carry faces, issue, at, or hostFace, toolFace, gap.See the hint above.
booleanTangent (euler)An exact tangency leaves an odd Euler characteristic.Move one operand or widen the model tolerance.
booleanVolumeMismatchSee the hint above.
booleanBudgetExceededA failing boolean had already run long (12 s) when the retries would start.As for booleanFailed.
booleanFuzzy (warning, tolerance)The fuzzy value that decided the boolean.Information.

Solids from sketches

codemeaning
extrudeRegionNone, extrudeRegionUnknownThe regions selection of an extrude or revolve matches no closed region (an empty list never falls back to “all regions”), or names ids that are no entity of the sketch.
unknownEndThe end is not a known end condition.
upToFaceBehind, upToFaceOutside, upToFaceUnsupported, upToPointBehind, endClipFailedAn up-to-face or up-to-point end cannot be reached or is not planar. The extrude falls back to a blind depth and warns with endConditionFallback; endRefRelinked warns that the face named by the end reference no longer existed and was found again by its ~k family or its at anchor (from, to).
upToNextNone, upToNextOpenUp-to-next finds no face to stop at, or an up-to-next add whose tool never meets the body.
loftProfiles, loftProfileOpen, loftProfileNotPlanar, loftGuideMiss, loftCentreLineReach, loftFailed, …See operations for the list. Fewer than two sketches is loftProfiles.
sweepProfileNotNormal, sweepPathInvalid, sweepGuide..., sweepFailedThe profile plane must be perpendicular to the path at its start. See operations.
holeInvalid (detail, hint), holeNoPoints, holeCskDiameter, holeCboreInvalidA hole has no valid size, no centres (the sketch must hold point entities), or an impossible counterbore. holeDowngraded (warning) says a counterbore was drilled as a simple hole.
ribNeedsOpenSketch, ribNoContact, lipFaceRib and lip preconditions.

Edits

codemeaningtry
blendOverflow (detail, sometimes max)The blend runs off its faces. max is the largest radius that fits where known.Reduce the radius or distance.
blendTooLarge, blendSize, blendCorner, blendNonManifold, blendFailed, blendUnsupported, blendTolerantEdgeSee operations.Blend the edges in separate features, or reorder.
cornerNotTangent (warning, deviation)Edges of unequal radius meet at a vertex and the blend faces are not tangent there; deviation is the largest normal jump in degrees.Use equal radii if tangency matters.
filletRadiusApproximated (warning)A variable fillet with an end radius of 0 was built with the smallest positive end radius that works.Give a positive end radius.
shellTooThick (detail, limit, minRadius, maxThickness)The wall is too thick for the body. maxThickness is a safe thickness, not the exact limit.Use at most maxThickness.
shellUnsupported, shellFailed, offsetTooLarge, offsetUnsupported, offsetDegenerate, offsetFitFailedShell and offset limits.Reduce thickness; open another face.
draftParallelFace, draftAxisNotParallel, draftTangentFaces, draftTooLarge, draftUnsupported, draftFailedDraft preconditions; draftTooLarge names the edge that turns over.Reduce the angle; pick another neutral plane.
moveFaceFailed, moveFaceUnsupported, pressPullUnsupportedA move-face could not keep the neighbours consistent. maxThickness may give a limit.Move less, or include tangent neighbours.
pipeCutRadius (max), pipeCutFailed, pipeCutNothingLeftSee operations.Reduce the radius.

Surfaces and curves

knitNotClosed, knitNearMiss; fillNotClosed, fillInvalid, fillFailed; trimNoIntersection, trimNothingLeft, trimPieceLoop; extendNotBoundary, extendNoTarget, extendPointBehind, extendUnsupported, extendFolds; thickenReach, thickenTooThick, thickenFailed; rebuildPeriodicFace, rebuildTooFine, rebuildFailed; projectCurveNoInput, projectCurveNoFaces, projectCurveMisses, projectCurveSeveral, projectCurvePlane, projectCurveFailed; editCurveNoInput, editCurveDegree. Their meanings are in operations and geometry.

Assemblies and bodies

insertPartMissing, insertPartErrors (the nested part had errors), mateConflict, mateGeometry, mateSameBody, mateFixed, bodyNameConflict (name, features), ambiguousBody (name, candidates), combineEmpty (detail), threadSizeUnknown, threadFaceNotCylinder, with the warnings threadDiameterMismatch, threadModelFallback, threadNotCarried.

Budgets and repair

Budgets only fire when the host supplies a real clock through ck_now. A host whose ck_now returns a constant, such as the runner used for this book (it returns 0), never sees these errors.

codemeaning
featureBudgetExceededThe feature used more than opts.featureTimeMs (default 120000 ms). Its result is not applied. It is not stored in the regeneration cache, so a later regen of the same document runs again. Parameters: budgetMs, elapsedMs, hint, and cause (the code the feature would have reported).
regenBudgetExceededThe document used more than opts.regenTimeMs. This feature and every later one did not run. It also appears, with the feature-budget hint, on every feature (sketches included) when the host clock advances by more than featureTimeMs between reads; see errors. The same cache limitation applies.
healed (in errors)opts.autoHeal repaired the body after the feature: fixed, codes, remaining. Although it is informational it is stored in errors; it is not added when the feature already has an entry of its own.
partVersionNewerNot a feature error: a top-level key of the reply that says the document was written by a newer kernel (file, kernel).

What to do, in order

  1. Read errors in feature order. Fix the first root cause.
  2. If the code is a boolean or blend failure, read detail and hint, and change the geometry a little (a tenth of a millimetre) before reaching for tolerances.
  3. If errors is empty, run validate. Issues there point at the body, not at a feature; the face names in entity tell which feature made the face (F4.S.e1 was made by F4).
  4. If the body is imported, heal it.

See also

Mass properties and interference

This chapter describes the read-only requests that measure a body: mass properties, measure, interference, sections and probes, and the distance, thickness and clearance family. For each it says what is computed, how, and how accurate the answer is, with values checked against closed forms. All of them read the body of a tag and never change it.

Common behaviour

  • Every request takes tag (default main) and answers null when the tag holds no solid body, and {"ok": false, "error": "noState: ..."} when the tag has no state.
  • Lengths are in millimetres, volumes in cubic millimetres, areas in square millimetres.
  • The requests from distance onwards stop their loops after opts.timeMs (default 8000 ms) and answer with what they have. Their replies carry elapsedMs and truncated; truncated: true means the result is partial, for example a lower bound of a maximum.
  • Replies name faces by their persistent name, so an answer can be used as a reference in a later feature.

The examples use a 40 x 20 x 10 block (feature F2, an extrude of the rectangle F1) with a radius 4 hole through its middle, made by a circle sketch F3 at (20, 10) extruded as a cut F4 with end: "throughBoth". The hole wall is then F4.S.e1. A hole made with the hole feature instead names its wall F4.S.h1 (see persistent names); the numbers below are the same.

Mass properties

{ "type": "massProps", "tag": "main", "bodies": true, "densities": [0.0078] }
fieldmeaning
bodiestrue adds bodies[], one entry per lump: volume, area, com, and name when the lump has one.
densitiesOne density per lump (0.0078 g/mm3 for steel). Implies bodies: true. A length that is not the number of lumps is an error that names the expected count.

Reply:

fieldmeaning
volume, areaTotal volume and surface area.
comCentre of mass of the volume (density 1).
principalThe three principal moments of inertia about the centre of mass, ascending, for density 1.
axesThe unit eigenvectors of principal: axes[i] belongs to principal[i].
bodies[]Per-lump volume, area, com, and mass = volume * density when densities was given.
byMassWith densities: mass, com, principal and axes of the whole body weighted by the densities.

For the block with the hole the reply is (rounded):

{ "volume": 7497.3452, "area": 2950.7964, "com": [20, 10, 5],
  "principal": [327133.92, 1127133.92, 1329312.09],
  "axes": [[1, 0, 0], [0, 1, 0], [0, 0, 1]] }

With densities: [0.0078] the lump also has mass: 58.4793 (7497.3452 x 0.0078).

How it is computed

Volume, area, centroid and inertia come from the faces by the divergence theorem, with no mesh. Each face integral over the trimmed parameter domain becomes a boundary integral by Green’s theorem along the coedge pcurves, and both integrals use composite 8-point Gauss-Legendre quadrature. The principal moments come from a Jacobi eigen-solver for the symmetric inertia tensor. See the B-rep model.

Accuracy

Analytic faces with exact pcurves reach machine precision. Results through the request against closed forms:

solidvolume relative errorarea relative error
block 40 x 20 x 107e-16 (8000.0000000000055)3e-16
block with radius 4 hole1e-15 (7497.34517542564 against 7497.345175425633)5e-16
sphere, radius 104e-162e-16
cylinder, radius 50, height 1003e-163e-16
torus, R = 10, r = 38e-160

The principal moments of the plain block are V (b^2 + c^2) / 12 for each axis: 333333.33, 1133333.33 and 1333333.33. In the repository’s mass-property sweep (box, cylinder, cone, sphere, torus, tube, two-station loft, revolve, line, arc and L sweeps), volume, area, centre and inertia agree with an independent mass-property integrator to about 1e-14 or better. The one exception in that sweep is the three-section loft through circles: the integrator is exact for the surface the kernel builds, but that surface differs from the thru-sections surface of the independent system, and the two disagree by up to 6.7 percent in volume and 10 percent in inertia. That is a difference in the shape, not in the integration; see known limits.

Free-form faces (B-spline, swept, lofted) are integrated by the same quadrature on their spans. The quadrature error is small compared with the fit error of the surface itself, so for a free-form body the accuracy of the answer is the accuracy of the surface, not of the integral.

Limits

  • Overlapping lumps count twice. Two lumps that overlap (a newBody over a block) are summed: lumps of 8000 and 2000 mm3 that overlap by 1000 mm3 give 10000. Use interference to find overlaps and combine to unite them.
  • Repeated principal moments. For a body with a repeated moment (a cylinder, a sphere, a cube) the axes are an arbitrary orthonormal basis of the eigenspace, with no sign convention. The moments are exact; the directions carry no meaning.
  • Sheets have no volume. Sheet bodies are kept apart from the solid state, and the request answers for the solid only.

measure

{ "type": "measure", "refs": [ {"kind": "face", "id": "F2.S.e1"}, {"kind": "face", "id": "F4.S.e1"} ] }

A reference is a face {kind: "face", id} or an edge {kind: "edge", faces: [a, b], at}. The reply has items with the facts of each reference and, for exactly two references, the minimum distance and the points:

  • a face item: kind, surface, area; for a plane the outward normal, for a cylinder radius, center and axis, for a cone center and axis, for a sphere radius and center;
  • an edge item: kind, length; for a line direction; for a circle radius, center and axis; and wedge, the angle between the outward normals of the two faces at the edge midpoint;
  • for a pair: distance and points, and where they apply angle, normalDistance and centerDistance.

The block’s side face and the hole wall are 6 mm apart, with points [[20, 0, 0], [20, 6, 0]]. The area of the hole wall is 251.3274, which is 2 pi * 4 * 10. The pair distance samples both references, projects every sample onto the other and refines the best three by alternating projection, so two references that touch pick one of their zero-distance points. The center of a cylinder is the origin of the surface’s frame, not necessarily a point inside the face: its position along the axis depends on how the face was built: (20, 10, -78.7) for the circle-cut wall above in one run, (20, 10, 10) with axis (0, 0, -1) for a wall made by the hole feature.

interference

interference reports overlap between the lumps of a body: {bodies, pairs}, where each pair is {a, b, volume, com, box} (and aName, bName when the lumps are named) describing the volume common to two lumps, computed as a boolean of the pair.

For the 40 x 20 x 10 block and a second block from x 30 to 50 and y 5 to 15, added with newBody:

{ "bodies": 2,
  "pairs": [ { "a": "F2.C0", "b": "F4.C0", "bName": "tool", "volume": 1000,
               "com": [35, 10, 5], "box": { "min": [30, 5, 0], "max": [40, 15, 10] } } ] }

The volume 1000 is the 10 x 10 x 10 overlap. Lumps that only touch give no pair. A pair whose boolean fails reports an error instead. A union merges overlapping solids, so a body gets overlapping lumps only from newBody and moveBody. validate reports the overlap as information.

section and sections

{ "type": "section", "plane": { "origin": [0, 10, 0], "normal": [0, 1, 0] } }

The reply gives loops, each {kind: "outer" | "inner", closed, area, edges, pts}, the plane frame (z is the normalised normal, x is the world Z crossed with the normal, or world X when the normal is within 2.5 degrees of Z), the signed total area (outer minus inner), bbox2d, and meshArea, the area of the same cut computed from the display polygons (320.041 for the section at y = 10 below, against the exact area 320). area is the number to use; meshArea is a check on the cut. Coordinates are in the plane frame. Loops run counter-clockwise around material. A plane that misses the body gives no loops and area 0.

The edges of a loop are exact where the geometry allows: line for planar faces; arc with centre, radius, startAngle and a signed sweep for runs of one curved face that lie on a circle (a cylinder, cone or torus cut perpendicular to its axis, any sphere cut); otherwise a polyline whose vertices are on the exact surface and whose sagitta is below 2e-5 of the body diagonal.

How it works: the display mesh of each face is cut by the plane, the segments are chained into loops, each loop vertex is snapped onto the exact surfaces that meet there by Newton iteration, and curved segments are bisected until the sagitta is small enough. Tangent slivers with an area below 1e-9 of the squared diagonal are dropped. If a face failed to mesh, the loops are incomplete: openChains appears and those pieces are omitted.

For the block with the hole, the section at y = 10 (through the hole’s axis) has area 320 (40 * 10 - 8 * 10) in two loops of 160. The section at z = 5 has an outer loop of area 800 and an inner loop that is an exact arc of radius 4 with area 50.2655 (pi * 4^2).

sections takes axis (x, y, z or a vector) and n (default 21) or explicit positions, and returns areas and the number of loops at each position, with volume integrated from the areas (midpoint rule for cell centres, trapezoid rule for explicit positions), exactVolume from the mass properties and the relative volumeError; exact: false skips the mass-property computation. For the block with the hole and 5 sections along z, every section has area 749.7345, and the integrated volume 7497.34519 differs from the exact 7497.34518 by 2e-9. For smooth profiles the rule’s error is about 1e-3 at 41 sections; a profile with steps needs more, while the section areas themselves stay exact.

probe

{ "type": "probe", "points": [[20, 10, 5], [1, 1, 5]], "rays": [ { "origin": [-5, 10, 5], "dir": [1, 0, 0] } ] }

At most 2000 points and 2000 rays per request. For each point: inside (true, false or "boundary"), the signed distance to the nearest face (negative inside, 0 on the boundary), the face and the foot point nearest. For each ray: hits, sorted by t (the direction is normalised, so t is a distance), each {t, point, face, entering}, with tangent: true on a grazing hit.

On the block with the hole:

queryanswer
point (20, 10, 5) (in the hole)inside: false, distance: 4, face F4.S.e1, nearest (24, 10, 5)
point (1, 1, 5)inside: true, distance: -1, face F2.S.e1
point (24, 10, 5) (on the hole wall)inside: "boundary", distance: 0
point (50, 50, 50)distance: 50.9902, which is sqrt(10^2 + 30^2 + 40^2)
ray from (-5, 10, 5) along +xhits at t = 5 (enters, F2.S.e4), 21 (exits, hole wall), 29 (enters, hole wall), 45 (exits, F2.S.e2)

Containment uses a parity test of up to seven fixed-direction rays, falling back to the nearest face when every ray is ambiguous.

Distance, thickness and the measurement set

These requests live in ck-ops::analysis. Entities (a, b, ids) are a face id, an edge key, a vertex V<n>, a point [x, y, z], lump:<n> or "body", or an array of those.

requestwhat it computesaccuracy
distance {a, b}The minimum distance of two entities, with the two points, what they lie on, and intersects: true with the extent when they touch. tagB takes b from another tag.Exact point-to-surface projections, a closed form for two segments, and a multi-start alternating projection otherwise. Against an independent routine on exported STEP, 80 face pairs of analytic parts agree to 4e-15 and 60 pairs on B-spline parts to 2.6e-8. A minimum in the interior of two doubly curved faces and far from every grid sample can be missed; raise opts.samples.
maxDistance {a, b}The one-sided Hausdorff distance: the maximum over a of the distance to b. Reply: maxDistance, location, errorBound, upperBound, rms, coverage.The distance function is 1-Lipschitz, so the true maximum lies in [maxDistance, maxDistance + errorBound].
thicknessWall thickness: from samples on every face, a ray along the inward normal to its first exit. thin lists the thinnest places, clustered. method: "sphere" refines the thinnest with an inscribed ball.A sampled minimum; a feature thinner than the sample spacing can be missed (raise opts.samples). The ray method overestimates in wedges and at corners.
thicknessAt {point} or {face}Thickness at one place, or min, max and mean over a face.As above.
closestPoint {points, on, ids, k}The nearest point of the body (or of faces, edges or vertices) to each point, what it lies on, and the signed distance. At most 2000 points.Exact projection.
anglesPer two-faced edge the interior dihedral angle through the material (90 for a block edge, 270 for a re-entrant edge), the type convex, concave or smooth, and min and max along the edge. Also the angle between two faces, and draft angles against a pull direction.Exact for planar faces; sampled at five points otherwise.
clearance {min}Face pairs closer than min, classed gap, wall or contact.Seeds from the display mesh and refines on the surfaces; a face whose mesh failed can hide a pair. Pairs that share a vertex are skipped.
symmetryCandidate mirror planes, each with the maximum and rms deviation of the mirrored surface. The same plane can be listed twice when a coordinate axis and a principal axis coincide (reported for some bodies; the block with the hole lists three distinct planes).Sampled; a plane reports exact: true when every sample was measured.
extrema {dir}The lowest and highest point of the body along a direction.Exact (method: "vertices") when every face is planar and every edge straight; otherwise sampled and refined to about 1e-9.

angles

angles needs at least one of these parameters; a bare request answers angles: edges ('all' | [keys]), faces [a, b] or draft {pull} is required.

parametermeaning
edges"all" or a list of edge keys such as "F2.C1|F2.S.e1#2".
faces[a, b]: the angle between two faces.
draft{pull, faces?, min?}: draft angle of each face (or of faces) against the pull direction; with min, walls under that angle are listed in violations.
reply fieldcontent
edges[]edge, faces, angle (interior dihedral through the material, degrees), normalAngle, type (convex, concave, smooth), min, max, at. For the edge above: angle 90, convex, at [20, 0, 10].
betweenFor two faces with a shared edge: angle, normalAngle, type, sharedEdge, at (90 for F2.S.e1 and F2.S.e2). Without a shared edge: normalAngle, angle, distance, pointA, pointB, parallel (the side F2.S.e1 and the hole wall: normalAngle 180, distance 6, parallel: true).
draft[]face, draft (degrees, asin(n . pull)), min, max, class (vertical below 0.01, undercut, parting above 89.99, ok). With pull (0, 0, 1) the block’s sides are vertical, F2.C0 is undercut at -90 and F2.C1 parting at 90.
elapsedMs, truncatedAs for every request of this group.

closestPoint

parametermeaning
pointsRequired: [[x, y, z], ...], at most 2000. Without it the answer is closestPoint: points [[x, y, z], ...] is required.
on"body" (default), "face", "edge" or "vertex".
idsRestrict face, edge or vertex queries to these entities.
kWith k > 1, return the k nearest entities per point (one list per point).

The reply is {on, results, elapsedMs, truncated}. For on: "body" each result has signedDistance (negative inside), inside, and nearest: {distance, point, entity: {kind, id}, face, uv}; for the point (30, 10, 5) it is -5 with the nearest point (30, 10, 0) on F2.C0. For on: "face", "edge" or "vertex" each result is {distance, point, entity} plus uv for a face or the curve parameter t for an edge (for (30, 10, 5) and on: "edge": distance 7.8102 to the edge F2.C0|F4.S.e1#12 at (24, 10, 0)).

Verified on the block with the hole:

  • distance between the side F2.S.e1 and the hole wall F4.S.e1: 6, with points (20, 0, z) and (20, 6, z).
  • thickness: minThickness 6 (the wall between the hole and the side) and meanThickness 18.69, from 2485 samples.
  • clearance with min: 7: two pairs at distance 6, both of kind wall (the hole wall against F2.S.e1 and against F2.S.e3).
  • maxDistance from the hole wall to the plane x = 40: maxDistance 23.9997, errorBound 1.04, upperBound 25.04. The true maximum is 24; it lies inside the bound, and the lower end is within 3e-4 of it.
  • symmetry: the three coordinate planes through the centre of mass are symmetric, with a maximum deviation near 3e-15.
  • extrema along x: 0 to 40, extent 40.

check: expectations

check {expect} measures the body and compares it with expected values in one call. The kinds are volume, area, mass (with density), bbox, com, the counts faces, edges, vertices, solids, holes and innerLoops, and valid (the validator reports no issue). An expectation is {kind, equals | min | max, tol?, relTol?}, and the reply is {ok, passed, failed, results, measured}. For the block with the hole, volume equals 7497.35 relTol 1e-6 passes (the window is plus or minus 0.0075), holes equals 1 passes, and faces equals 8 fails with faces 7 vs [8, 8]. The default tolerance for volume and area is 1e-4 relative.

See also

STEP

The kernel writes a body as an ISO 10303-21 file (AP214, AUTOMOTIVE_DESIGN) with the step request and reads B-rep solids from STEP files with the importStep request. Both live in crates/ck-io (step/write.rs, step/read.rs, step/parse.rs).

Export: the step request

{"type":"step","tag":"main","name":"plate"}
FieldTypeDefaultMeaning
tagstring"main"State to export. A tag that has never been regenerated or imported answers the error noState: nothing regenerated yet
namestring"part"Part name written into FILE_NAME, PRODUCT, the solid and the shape representation

The reply carries the whole file as one JSON string, with no binary buffers:

{"ok":true,"result":"ISO-10303-21;\nHEADER;\n...END-ISO-10303-21;\n","ms":0}

result is null when the tag holds no body. This happens for an empty part and for a part that only builds surfaces (checked: a sketch with a surfaceExtrude answers null).

The examples in this chapter use a 40 x 20 x 8 mm plate with a 10 mm through hole, built from this part:

{"format":"ck-part","version":1,"name":"plate","features":[
 {"type":"sketch","id":"F1","plane":{"kind":"std","id":"front"},
  "points":[{"id":"a","x":0,"y":0},{"id":"b","x":40,"y":0},{"id":"c","x":40,"y":20},{"id":"d","x":0,"y":20}],
  "entities":[{"id":"e1","type":"line","p1":"a","p2":"b"},{"id":"e2","type":"line","p1":"b","p2":"c"},
              {"id":"e3","type":"line","p1":"c","p2":"d"},{"id":"e4","type":"line","p1":"d","p2":"a"}],
  "constraints":[]},
 {"type":"extrude","id":"F2","op":"add","sketch":"F1","end":"blind","depth":8},
 {"type":"plane","id":"F3","mode":"offset","base":{"kind":"std","id":"front"},"offset":8},
 {"type":"sketch","id":"F4","plane":{"kind":"feature","id":"F3"},
  "points":[{"id":"p1","x":20,"y":10}],"entities":[{"type":"point","id":"e1","p":"p1"}],"constraints":[]},
 {"type":"hole","id":"F5","sketch":"F4","kind":"simple","diameter":10,"end":"through"}]}

With "name":"plate" in the step request, the export is 189 lines and ends with #178=MANIFOLD_SOLID_BREP, #179=ADVANCED_BREP_SHAPE_REPRESENTATION and #180=SHAPE_DEFINITION_REPRESENTATION. If the hole is instead a circle in the first sketch (a point o at (20, 10) and a circle of radius 5 centred on o, no hole feature), the file is 187 lines and the same three entities are #176, #177 and #178. The header and the first entities:

ISO-10303-21;
HEADER;
FILE_DESCRIPTION(('CadKit model'),'2;1');
FILE_NAME('plate.step','2026-01-01T00:00:00',(''),(''),'CadKit','CadKit','');
FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));
ENDSEC;
DATA;
#1=APPLICATION_CONTEXT('core data for automotive mechanical design processes');
...
#10=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));
#11=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.));
...
#178=MANIFOLD_SOLID_BREP('plate',#177);
#179=ADVANCED_BREP_SHAPE_REPRESENTATION('plate',(#178,#18),#14);
#180=SHAPE_DEFINITION_REPRESENTATION(#9,#179);
ENDSEC;
END-ISO-10303-21;

The time stamp in FILE_NAME is the host clock (ck_unix_ms) in UTC. A host that returns a fixed clock gets a reproducible file.

What is written

  • One product. Entities #1 to #14 are the application context, the product definition and the geometric context. Lengths are millimetres, angles radians, with a distance uncertainty of 1.E-06. Entities #15 to #18 are the world placement.
  • Faces in shell order. For each face the writer emits the surface, then per boundary the edges (vertices, curve, EDGE_CURVE, ORIENTED_EDGE), the EDGE_LOOP, the bound, and finally the ADVANCED_FACE. A CLOSED_SHELL follows each shell and then every solid.
  • Surfaces: PLANE, CYLINDRICAL_SURFACE, CONICAL_SURFACE, SPHERICAL_SURFACE, TOROIDAL_SURFACE, SURFACE_OF_LINEAR_EXTRUSION, SURFACE_OF_REVOLUTION, OFFSET_SURFACE, and B-spline surfaces (B_SPLINE_SURFACE_WITH_KNOTS, or the rational complex entity when the weights differ from 1).
  • Curves: LINE, CIRCLE, ELLIPSE, B-spline curves (rational as a complex entity). Conic curves are written as ELLIPSE, PARABOLA or HYPERBOLA (not exercised in the checks for this chapter); sinusoids as B-splines.
  • Seams are not written. A periodic face (cylinder, cone, torus, sphere) is bounded the way STEP usually bounds it: by bare circles. A full sphere or torus with no boundary is split into two faces on one shared surface.
  • Planar faces get a FACE_OUTER_BOUND (the loop of largest area); every other bound is a FACE_BOUND.
  • Voids. A lump with cavities becomes BREP_WITH_VOIDS; each void is a CLOSED_SHELL wrapped in ORIENTED_CLOSED_SHELL.
  • Several lumps give several MANIFOLD_SOLID_BREP entities in one ADVANCED_BREP_SHAPE_REPRESENTATION. A two-block part exported as 2 solids (checked).
  • Numbers. Reals print in the shortest form that reads back exactly, always with a decimal point (0., 25., 1.E-7); scientific notation is used below 1e-6 and from 1e15. Strings escape ' and \, drop control characters and write non-ASCII characters as \X2\hhhh\X0\.

The writer has a code path for open shells (SHELL_BASED_SURFACE_MODEL in a MANIFOLD_SURFACE_SHAPE_REPRESENTATION). It is marked as unverified in the source and was not exercised here.

Not written

Colours and styles, layers, per-face or per-body names, assemblies and placements, product structure beyond a single part, and product and manufacturing information. A part with several named bodies exports them as anonymous solids that share the part name.

Import: the importStep request

{"type":"importStep","tag":"imp","name":"plate","data":"ISO-10303-21;\n..."}
FieldTypeDefaultMeaning
tagstring"main"State that receives the body
namestring"part"Accepted, not used in the reply
datastringrequiredThe STEP file text. A missing or non-string value is a request error (importStep: data must be a STEP file as a string)
heal"off", false or objectonHealing options, below
healTolerancenumber0.05Cap on the tolerance healing may give an edge or vertex, in mm

The reply has the shape of a regen result: body (faces, edges, mesh buffers), errors, and an import summary. Importing the plate above back gives:

{"errors":[], ...,
 "import":{"solids":1,"faces":7,"unitScale":1,"warnings":[],
           "heal":{"fixed":0,"remaining":0,"toleranceUsed":0}}}
import fieldMeaning
solidsNumber of MANIFOLD_SOLID_BREP and BREP_WITH_VOIDS entities read (one lump each)
facesFaces of the resulting body
unitScaleMillimetres per file length unit that was applied
warningsNon-fatal problems, each ["import", {code, params:{message, entity?}}]
healPresent unless healing is off: fixed repairs made, remaining validator findings left, toleranceUsed largest edge or vertex tolerance in the body

The tag’s state becomes the imported body, so massProps, validate, heal, recognize, drawing and step work on it. Re-importing the exported plate gives a volume of 5771.681 mm3, the same as the source (checked), and validate reports no issues. A failed import leaves the tag’s previous state untouched (checked: the volume of the earlier import was still answered after a failed one).

Face names and multi-solid files

Imported faces are named I<k>.F<n>: k is the 1-based index of the solid in entity-id order and n counts faces over the whole file. The plate imports as I1.F1 to I1.F7; the cylinder face of the hole is I1.F7. Names are stable for a given file, but a STEP file carries no history, so they say nothing about how the part was made. For a rebuilt feature tree see feature recognition.

All solids of a file are read into one body with one lump each. Two disjoint blocks exported by the kernel import as solids: 2, 13 faces and the same combined volume and mass properties (checked).

Units

The reader takes the length and plane-angle units named by the GLOBAL_UNIT_ASSIGNED_CONTEXT of the geometric representation context. If there is none it uses the first LENGTH_UNIT and PLANE_ANGLE_UNIT in the file. SI units with any prefix, and CONVERSION_BASED_UNIT (inch, degree and so on), are converted to millimetres and radians. A file whose context declares inches, with the plate’s numbers, imports as a 1016 x 508 x 203.2 mm body and reports unitScale: 25.4 (checked).

Entities read

GroupEntities
Solids and shellsMANIFOLD_SOLID_BREP, BREP_WITH_VOIDS (with ORIENTED_CLOSED_SHELL), CLOSED_SHELL
Faces and loopsADVANCED_FACE, FACE_SURFACE, FACE_BOUND, FACE_OUTER_BOUND, EDGE_LOOP, ORIENTED_EDGE (also nested), EDGE_CURVE, VERTEX_POINT
SurfacesPLANE, CYLINDRICAL_SURFACE, CONICAL_SURFACE, SPHERICAL_SURFACE, TOROIDAL_SURFACE (negative radii accepted), SURFACE_OF_REVOLUTION, SURFACE_OF_LINEAR_EXTRUSION, OFFSET_SURFACE, RECTANGULAR_TRIMMED_SURFACE (basis surface), B-spline surfaces (simple, complex, rational, Bezier and quasi-uniform forms)
CurvesLINE, CIRCLE, ELLIPSE, PARABOLA, HYPERBOLA, B-spline curves (same forms), TRIMMED_CURVE (the bounds come from the edge vertices), SURFACE_CURVE, SEAM_CURVE, INTERSECTION_CURVE, BOUNDED_SURFACE_CURVE (the 3D curve is used)

The parser is a full Part 21 value-tree parser: nested lists, typed parameters, complex (multi-part) entities and comments.

Topology completion

STEP describes periodic faces differently from the kernel. The importer therefore completes the topology:

  • a cylinder bounded by two bare circles gets a seam edge, and a circle is split at the seam position when the two circles’ vertices are not aligned;
  • cone and sphere faces with a single boundary get their pole structure;
  • a full sphere or torus that the file splits into two faces is merged back into one;
  • degenerate edges (poles, apexes) are dropped;
  • closed B-spline profiles that wind over several laps are unrolled.

A boundary that is a VERTEX_LOOP is ignored with a skipped warning (vertex loop ignored), as is a loop with no non-degenerate edge.

Tolerances and healing

Exporters often write intersection edges as fitted splines that sit a few thousandths of a millimetre off the faces they bound. After reading, the importer moves an edge that is off both of its faces by more than rounding but less than a file-sized amount onto the faces’ intersection, and reports a skipped warning for an edge it cannot move.

Healing then runs by default with a model tolerance of 1e-4 mm. It merges near vertices, closes gaps, sews free edges, removes degenerate edges and sliver faces, makes loop and shell orientation consistent, and gives remaining small deviations an edge or vertex tolerance up to the cap (0.05 mm unless healTolerance or heal.cap says otherwise). A valid body is not touched. Options:

{"type":"importStep","tag":"imp","data":"...","heal":{"tol":1e-3,"sew":true,"fixSmall":true,"fixOrientation":true,"tolerant":true,"cap":0.05}}

"heal":"off" (or false) skips the pass and omits import.heal from the reply. See healing and tolerances.

Errors

A failed import answers body: null and one entry in errors:

CodeMeaningExample (run)
parseThe text is not a Part 21 filenot a STEP file (missing ISO-10303-21 header); expected '(' after keyword at line 77
noSolidThe file parses but holds no solidno MANIFOLD_SOLID_BREP / BREP_WITH_VOIDS in the file
unsupportedAn entity the reader does not handle, with its idreplacing the first PLANE of the plate by SWEPT_DISC_SURFACE gives {"code":"unsupported","params":{"message":"SWEPT_DISC_SURFACE is not supported","entity":22}} (entity 21 for the circle-in-sketch variant)
badEntityA supported entity with missing or invalid arguments
topologyThe faces cannot be assembled into a closed shell

The reader does not panic on malformed or truncated input; this is covered by a truncation test.

Limits

  • No assemblies: placements and SHAPE_REPRESENTATION_RELATIONSHIP are not read. Every solid in the file is imported at its own coordinates.
  • Shell-based surface models and open shells are not imported as solids; a file with no solid answers noSolid.
  • POLY_LOOP bounds, composite curves and faces whose boundary winds twice around a periodic surface are not supported.
  • Colours, names, layers and product information are ignored.
  • Open items: torus-fillet shell orientation and sphere pole boundaries in some files. In four samples of 200 STEP files each from a public research set (seeds 1234, 4242, 5678, 9001), 185 to 188 files per sample import and validate; the rest import but fail validate, mostly with TESSELLATION_OPEN and EDGE_OFF_SURFACE (see corpora and sweeps).
  • Known exporter limit: an arc split at a seam vertex but used by a planar face on only one half is written as a closed circle, and the import of that file is then wrong. The cases are flangeHalf@9 to flangeHalf@11 and flangeNut@12 in tools/brep_cases.mjs.

See also

SketchUp

The importSkp request reads a SketchUp .skp file into a body made of planar faces. The reader is the crate crates/ck-skp; it uses no SketchUp library. It reimplements published reverse-engineering work on the file formats (attribution in crates/ck-skp/NOTICE and THIRD_PARTY.md).

Request

{"type":"importSkp","tag":"s","name":"model","data":"<base64 of the .skp file>",
 "opts":{"hidden":false,"maxFaces":50000,"up":"z"}}
FieldTypeDefaultMeaning
tagstring"main"State that receives the body
namestring"model"Echoed as import.name
datastringrequiredBase64 of the file. URL-safe letters, whitespace and a data:...;base64, prefix are accepted. A missing data or a character outside base64 is a request error
opts.hiddenboolfalseInclude hidden faces, instances and tags
opts.maxFacesnumber50000Refuse models with more faces (limit.faces). Values below 1 are ignored
opts.up"z", "y", "yFlip""z"Rotate the whole model, below. Any other value is a request error

The request is available when the kernel is built with the skp feature of ck-wasm (it adds about 4.6 percent to the module). Without the feature importSkp answers the usual “not implemented” error. The module used for the examples in this book has the feature.

The reply has the shape of a regen result: body, errors, and an import summary. A refused file answers body: null with one error ["import", {code, params:{message, offset?}}] and leaves the tag’s state alone.

What is read

SketchUp has two file containers, and the reader detects which one it has:

Containerimport.containerVersionsLayout
Classic"classic"3 to 2020An MFC CArchive object stream
Modern"modern"2021 and laterA ZIP archive holding model.dat (a tag-length-value tree) and material images

The sample files in crates/ck-skp/tests/fixtures cover these versions. The fixtures for classic 3.0, 6.0, 7.0 and 14.0 (legacy_v3_synthetic, legacy_v6_synthetic, legacy_v7_synthetic, legacy_v2014_synthetic) are synthetic files written to the old layout, not exports from SketchUp, so support for those versions is checked against hand-made files; classic 17 and 20 and modern 25 are checked against files from the application. import.version is the version string stored in the file.

From the file the reader takes vertices, edges, faces with holes and texture coordinates, component definitions and their instances with transforms, groups, tags (layers) and hidden state, and materials (colour, opacity, double-sidedness, texture bytes). Nested instances are flattened (nesting is capped at 32 levels) and the result is baked into world space.

What the body is

A SketchUp model is a surface model, not a solid. The body therefore has:

  • one planar face per SketchUp face, with its holes as inner loops;
  • vertices welded within 1e-4 mm and edges shared between neighbouring faces;
  • millimetres: SketchUp stores inches, and the importer multiplies by 25.4 (import.unitScale);
  • faces named skp.F0, skp.F1, and so on, in creation order;
  • one lump, with one shell per connected piece (import.lumps counts pieces).

The body is closed only where the model is. import.openEdges counts edges used by one face, import.nonManifoldEdges those used by more than two. A closed cube from the sample files has openEdges: 0; a model made of loose faces has many.

Materials do not live in the body. import.materials lists {color:[r,g,b], opacity, doubleSided, textured} and import.faceMaterials[n] is the material index of face skp.F<n>. Texture image bytes are read by the library but not sent over the protocol.

Not imported: scenes (pages) and cameras, dimensions, text, section planes, construction lines and points, loose edges and curves (no wire output), analytic arcs (faces are polygons), attribute dictionaries and dynamic-component properties, and styles other than face colours. Overlapping holes in one face are bridged as given.

Reply fields

FieldMeaning
format, name"skp" and the request name
container, versionContainer kind and the version string in the file
unitsThe model unit in the file ("Millimeter" for a modern file); null for classic files, which carry no unit
unitScaleAlways 25.4 (inches to millimetres)
up, upMatrixThe orientation option and its 3 x 3 matrix, row major
faces, lumpsFace and connected-piece counts
openEdges, nonManifoldEdgesBoundary and non-manifold edge counts
skippedFaces, hiddenSkippedFaces that could not be built, and hidden items left out
definitions, instancesComponent definitions and baked instances
materials, faceMaterialsAs above
bboxMm[xmin, ymin, zmin, xmax, ymax, zmax] of the finished body
warningsStrings, code: message

Orientation

SketchUp is Z up. The default keeps the file’s axes. opts.up rotates the finished model (after units and instances are resolved):

upMaps (x, y, z) toMeaning
"z"(x, y, z)As stored
"y"(x, z, -y)Rotate -90 degrees about X: SketchUp Z becomes Y
"yFlip"(-x, -z, -y)"y" and then 180 degrees about Z

Both rotations have determinant 1, so winding, face order, names, areas and counts do not change.

Examples

A single face with holes (holes.skp, a classic 17 file), with opts.up set to "y":

{"format":"skp","container":"classic","version":"{17.0.1}","units":null,"unitScale":25.4,
 "up":"y","upMatrix":[1,0,0,0,0,1,0,-1,0],"faces":1,"lumps":1,"openEdges":8,
 "materials":[{"color":[255,84,84],"opacity":1,"doubleSided":true,"textured":false}],
 "faceMaterials":[0],"bboxMm":[0,0,-2540,5080,0,0],"warnings":[]}

With up: "z" the box is [0,0,0,5080,2540,0]. The body has one planar face skp.F0, area 11 870 944 mm2 and volume 0 (it is a sheet).

A modern file with two closed pieces (SU_File.skp): 32 faces, 2 lumps, openEdges: 0, validate reports no issues, and massProps with bodies: true gives volumes of 1.0e9 mm3 (a 1 m cube) and 1.6145e9 mm3.

A classic furniture model (chair_and_table.skp): 128 faces, 28 lumps, 9 definitions, 15 instances, 6 materials, 128 open edges.

Failures, all from real runs:

InputError
Base64 of the text AAAAcontainer.magic: not a SketchUp file (bad header magic), offset 0
A file with only edges (blank_v17.skp)body.empty: the model has no visible faces to import ...
chair_and_table.skp with maxFaces: 50limit.faces: 128 faces exceed the import limit of 50; ...

Error codes

Codes are grouped by stage. offset is a byte offset when the reader can give one.

PrefixRaised when
container.*Bad magic, unknown container, no ZIP directory, no model.dat
zip.*, inflate.*Damaged ZIP structure, CRC or size mismatch, corrupt DEFLATE data
tlv.*, legacy.*Truncated or inconsistent model data in the modern or classic container
limit.*A safety limit was exceeded: file size (512 MB), inflated size and compression ratio, node count (40 million) and depth (64), archive objects (40 million) and depth, instances (2 million), triangles (30 million), faces (maxFaces)
body.*The scene produced no face (body.empty)

The reader never panics on malformed input. Every read is bounds checked, and the crate carries a seeded mutation fuzzer that flips, truncates and splices the sample files.

Limits

  • The result is a surface body: volume is 0 unless the model is closed, and it does not behave like a solid in booleans.
  • Models above 50 000 faces are refused unless maxFaces is raised; per-face work makes large imports slow (the largest sample, 39 352 faces, takes about 1.1 s in the checks).
  • Curves are polygons: circles and arcs arrive as many short planar facets.
  • Three of the 17 sample files (no faces, or everything hidden) are refused with body.empty; this is the expected answer for models without faces.

See also

SolidWorks

The importSldprt request reads a SolidWorks part file (.SLDPRT) and builds a body directly from the geometry stored in it. There is no STEP file in between. The reader is the crate crates/ck-sldprt, which uses no SolidWorks or Parasolid library; it decodes the file’s container and the Parasolid transmit data inside it.

Request

{"type":"importSldprt","tag":"s","name":"part","data":"<base64 of the .SLDPRT file>"}
FieldTypeDefaultMeaning
tagstring"main"State that receives the body
namestring"part"Echoed as import.name
datastringrequiredBase64 of the file (URL-safe letters, whitespace and a data:...;base64, prefix are accepted)

The reply has the shape of a regen result with body, errors and an import summary. A failed import answers body: null with errors: [["import", {code, params:{message}}]] and leaves the tag’s state unchanged. On success the tag holds the body, so massProps, validate, heal, recognize, drawing and step work on it.

Pipeline

StageModuleWhat it does
Containercontainer.rs, inflate.rsOpens the file and extracts named streams, with an own bounded DEFLATE decoder and CRC-32
Transmitxt.rsReads the Parasolid neutral binary transmit (schema SCH_13006 plus the embedded schema edits)
Intermediate formir.rsBodies, regions, shells, faces, loops, fins, edges, vertices, and their surfaces and curves, in metres; face colours and feature tags, body density
Kernel bodybuild.rsConverts to millimetres and builds the body: solid regions only, edge ranges from the vertices, fin senses to coedge directions, seams on periodic faces, loop ordering, shell orientation
Metadatameta.rsFeature list, configurations, material, properties, units, versions and preview from the plain streams

Containers

Kindimport.containerFilesDetection
OLE2 compound file"ole2"SolidWorks 2014 and earlierFirst 8 bytes D0 CF 11 E0 A1 B1 1A E1; streams hold zlib frames
Block container"modern"SolidWorks 2015 and laterA block marker 14 00 06 00 08 00; every block carries a name, sizes, a CRC-32 and raw DEFLATE data. A block is accepted only if its data inflate to the declared size and the CRC matches

Any other file is container.format. The geometry sits in Parasolid transmits inside the streams, wrapped in GUIDs. The reader takes the live partition (Contents/Config-0-Partition). If it holds no solid, as in parts whose geometry is an imported body, the solid bodies of the free-standing part transmits are used instead (and a note says so).

Reply fields

Real output for a 10 mm cube saved by SolidWorks 2011 (OLE2 container), with the face list shortened to two of its six entries:

{"format":"sldprt","name":"part","solids":1,"faces":6,
 "unitScale":1000,"container":"ole2","schema":"SCH_2201236_20000_13006",
 "stream":"Contents/Config-0-Partition","nodes":165,
 "approximations":[],"notes":[],"swMassProps":null,
 "features":[{"id":2,"name":"Front Plane","type":"Plane","dimensions":[]},
             {"id":3,"name":"Top Plane","type":"Plane","dimensions":[]},
             {"id":4,"name":"Right Plane","type":"Plane","dimensions":[]},
             {"id":5,"name":"Origin","type":"Origin","dimensions":[]},
             {"id":18,"name":"Sketch1","type":"Sketch","dimensions":[]},
             {"id":24,"name":"Boss-Extrude1","type":"Boss-Extrude",
              "dimensions":[{"name":"D1","text":"10","value":10}]}],
 "configurations":[{"name":"Default","material":null}],
 "material":null,"customProperties":[],"configurationProperties":[],"units":null,
 "versions":{"solidworks":4700,"solidworksRelease":2011,"parasolid":"22.01","parasolidModeller":2201236},
 "thumbnail":{"mime":"image/png","width":640,"height":480,"base64":"iVBORw0KGgo..."},
 "omittedForPrivacy":0,
 "faceAttributes":[{"face":"sldprt.F1","xtFace":1,"colour":[0.792,0.820,0.933],
                    "featureId":24,"feature":"Boss-Extrude1","kind":40,"local":1},
                   {"face":"sldprt.F85","xtFace":85,"colour":[0.792,0.820,0.933],
                    "featureId":24,"feature":"Boss-Extrude1","kind":74,"local":4}],
 "bodyAttributes":[{"xtBody":2,"density":1000,"lastFeatureId":24}]}
FieldMeaning
solids, facesSolid bodies and faces built
unitScaleMillimetres per file unit; Parasolid stores metres, so 1000
container"ole2" or "modern"
schemaParasolid schema name of the transmit that was read
streamThe stream the body came from
nodesParasolid node count
approximationsCarriers that were fitted, each {what, maxErrorMm}, below
notesFree-text notes (for example that the live partition was empty)
swMassPropsMass properties SolidWorks stored in the file (property SW-MassProp-Config-0, either container, when present): volumeMm3, areaMm2, massKg, comMm. An independent check of the body; null in the bundled samples
features, configurations, material, customProperties, configurationProperties, units, versions, thumbnail, omittedForPrivacyThe file’s metadata, below
faceAttributes, bodyAttributesColour and feature of each face, attributes of each body, below

Every metadata key is always present: a stream the file does not have gives null or [], never an error.

Metadata

Besides the body, a part file holds its feature tree, properties and a preview. They are read from plain streams, with no decoding of SolidWorks’ own object archive:

FieldStreamContent
featuresswXmlContents/KeyWords (XML; zlib-wrapped in OLE2)The feature tree in id order: {id, name, type, dimensions:[{name, text, value}]}. id is SolidWorks’ feature id, the one the faces carry. type is the feature type (Boss-Extrude, Extrusion, Fillet, HoleWizard, Revolve, Sketch, Plane, …). text is the dimension as SolidWorks displays it, in the document’s display units (10, R1, 360°, Ø20); value is its number. The fixed folders of every tree (annotations, lights, bodies, equations, notes, material, favourites, history, user folders) are left out
configurationsKeyWords{name, material} per configuration; material is null when none is assigned
materialswXmlContents/MATERIALTREE (UTF-16 XML), else KeyWords{name, densityKgM3}: the material’s name without its library prefix, and its mass density in kg/m^3 (null when only the name is known)
customProperties, configurationPropertiesdocProps/custom.xml and docProps/Config-0-Properties.xml (modern); the user-defined sections of DocumentSummaryInformation and Config-0-Properties (OLE2 property sets){name, value} of the user-defined file properties and of the first configuration’s. SolidWorks’ own SW-* file properties are not listed
unitsdocProps/ISolidWorksInformation.xml (modern) or the ISolidWorksInformation property set{system, length, angle, lengthDecimals}: MMGS, CGS, MKS, IPS or custom; mm, cm, m, in, ft, …; deg or rad. null when the file does not record them (the SolidWorks 2011 samples)
versions_MO_VERSION_<n> streams; the transmit’s schema namesolidworks: the file’s version number (4700, 9000, 10000, 11000, 15000 in the samples); solidworksRelease: its year (2007 + n / 1000: 2011, 2016, 2017, 2018, 2022); parasolid: the modeller version of the transmit read (22.01 to 33.01) and parasolidModeller its number
thumbnailPreviewPNG{mime, width, height, base64}, the 640 by 480 preview SolidWorks saved, with any text chunks removed; null when the file has none

Face colour and feature

Every face of the Parasolid body carries attributes SolidWorks wrote: its colour and the id of the feature that built it. The kernel body has no per-face colour, so both are reported in faceAttributes, one entry per face built, keyed by the face’s id in body.faces:

FieldMeaning
faceThe face id (sldprt.F<n>)
xtFaceThe Parasolid face node id n
colourRGB in 0..1 (attribute SDL/TYSA_COLOUR), null if the face has none
featureId, featureThe feature that built the face (attribute FACE_ID_2001) and its name from features
kind, localTwo more fields of FACE_ID_2001. Their meaning is inferred from sample files, not documented: kind 40 is an end cap, 74 a side face of an extrusion or revolution, 72 a fillet face; local numbers the faces a feature made

In the 41 sample parts every face carries both attributes, and every feature id is in the feature list. The 10 mm cube with a 5 mm hole tags its six box faces with Boss-Extrude1 and the hole’s cylinder with Cut-Extrude1.

bodyAttributes lists each solid body read: {xtBody, density, lastFeatureId}. lastFeatureId is the last feature that changed the body. density is the value stored on the body (attribute SDL/TYSA_DENSITY); its unit is not established (the 2011 samples store 1000 and the later ones 1.0, whatever the material), so use material.densityKgM3 for mass.

Privacy

The same files record Windows user names (last saved by, author) and absolute paths (the folder the part was saved in, the save history). The reader does not read those fields or streams (SW-Folder Name, SW-Last Saved By, SW-Author, the swXmlContents/Features path list, _MO_VERSION_<n>/Biography and History, ModelHeader). Every string it does return is checked: a value that looks like an absolute path (a drive letter, a UNC prefix, a home directory) or that contains a user name the file records is left out, and omittedForPrivacy counts what was left out. The preview PNG is passed on without its text chunks. Tests check this on the fixtures (the user names and folders they record are read from the raw streams and must not appear in the reply) and on synthetic files with a user name and paths in their custom properties.

A file without a body

When the body cannot be imported (errors is set, body is null), the reply still carries import with format, name, swMassProps and the metadata keys above, as long as the container opens. The feature list and thumbnail of a part the kernel cannot build are still available.

Examples

The four sample parts in crates/ck-sldprt/tests/fixtures, imported and checked in this chapter:

FileContainerFacesVolume (mm3)Area (mm2)validate
10 mm cube, SolidWorks 2011ole261000.000600.000clean
10 mm cube with a 5 mm hole, SolidWorks 2022modern7803.650717.810clean
10 mm cube, SolidWorks 2022modern61000.000600.000clean
Cone, radius 5, height 10, SolidWorks 2022modern2261.799254.160clean

The cone’s volume is the closed form pi r^2 h / 3 = 261.799. A file that is not a SolidWorks file answers container.format: neither an OLE2 compound file nor a SolidWorks block container.

Geometry mapping

ParasolidKernelNotes
Plane, cylinder, cone, sphere, torusThe same analytic surfacesExact
B-surfaceB-spline surfaceExact; rational weights are divided out
Swept, spun, offset surfacesExtrusion, revolution, offset surfacesExact
Rolling-ball blend surfaceB-spline surfaceApproximated (spine sections, circular cross-sections, cubic interpolation); the deviation is reported
Line, circle, ellipse, B-curveThe same curvesExact
Trimmed curveBasis curve restricted to the range
Intersection curve, surface-parameter curveB-spline curveApproximated; the deviation is reported
Void regionSkippedOnly solid regions are read; a second shell in a solid region is a cavity

Parasolid has no seams. The builder adds them: a seam line on cylinders and cones, a meridian on tori and sphere bands, an apex or pole edge on caps, and the standard loops on full spheres and tori. Planar faces order their loops by signed area, curved ones by extent, and each shell is oriented by its signed volume.

Each approximated carrier is listed in import.approximations with its maximum deviation. An approximation that deviates by more than 0.05 mm makes the import fail with geometry.invalid.

Errors

Codes are stable strings:

PrefixRaised when
container.*format (neither container), cfb (damaged OLE2 structure), empty, no_parasolid
inflate.*Corrupt DEFLATE or zlib data
limit.*A safety limit: file 256 MiB, 256 MiB per stream, 768 MiB inflated in total, compression ratio above 2000, 4096 streams, 4 million Parasolid nodes, 50 000 faces
xt.*The transmit is empty, has a bad header, schema, stream or topology
topology.*, geometry.*The faces cannot be assembled, or a surface is outside what can be built
unsupported.*body (the file holds only sheet or wire bodies), geometry (for example a self-intersecting torus)

The reader does not panic on malformed input. A test feeds truncated, bit-flipped, zeroed and garbage-padded copies of every fixture and requires an error or a body.

Results on a larger sample set

tools/sldprt_check.mjs was run over 41 public sample parts (cubes, cones, spheres, tori, lofts, blends, and the NIST test parts). Only the four fixtures above are in the repository, so the figures below (39 of 41 imported, and the rest) cannot be re-run from the repository. 39 of 41 imported. 33 passed the kernel validator. Of the 37 parts that had a reference volume (computed from a STEP export of the same part), 32 matched to the tolerance (1e-4, or 1e-3 for spline-heavy parts). Parts that failed:

  • a part with a self-intersecting (lemon-shaped) torus: unsupported.geometry;
  • a part with a B-surface whose vertices fall outside the NURBS domain: geometry.invalid (a vertex 2.5 mm off its spline surface);
  • parts that imported but failed the strict edge-to-surface check (EDGE_OFF_SURFACE), all on approximated blend or intersection carriers whose deviations are at most 1e-3 mm, although volume and area match the stored SolidWorks values to 1e-3 or better.

Limits

  • Only the active configuration’s body is read. importSldprt returns the feature tree as a list (names, types, ids and dimension values, see Metadata); equations and annotations are not read, and other configurations are listed by name only. The editable history comes from the separate sldprtHistory request, which rebuilds sketches, extrudes and cuts, fillets, chamfers, holes, shells, patterns, mirrors, revolves and simple lofts where it can. A feature it cannot read back, or a rebuild that does not verify against the file’s solid, ends the history there and the rest of the part is the file’s exact solid; a part it cannot rebuild at all stays the plain imported solid.
  • Only the (partition) transmit is applied. The (deltas) transmit that follows it is read but not applied: it holds the partition’s undo history, ending at the mark the partition already sits at, so the partition is the finished part. On several sample parts SolidWorks’ stored volume matches the state one change back (the last cut feature is missing from it), up to 0.4 percent away from the imported solid; the import follows the feature tree, not the stored mass.
  • Sheet and wire bodies are not imported. A file with only such bodies answers unsupported.body.
  • Sheet-metal parts import as the folded solid; the flat pattern and bend table are not read.
  • Not supported: self-intersecting tori, B-surfaces with periodic or extended domains whose vertices fall outside the NURBS domain, variable-radius and cliff-edge blends, foreign geometry and mesh bodies.
  • The oldest sample is SolidWorks 2011 and the newest SolidWorks 2022. Newer files are untested; the container and schema layers do not depend on the version.
  • Speed: the reader takes 5 to 700 ms per part. The importSldprt reply also tessellates the body, which dominates on parts with hundreds of faces.

Feature history: sldprtHistory

{"type":"sldprtHistory","name":"part","data":"<base64 of the .SLDPRT file>"}

Rebuilds the feature history of the part (sketches, extrudes, fillets, chamfers, holes, shells …; the crate crates/ck-swedit, see docs/sldprt-editable.md) as a part document. Read only: no tag, no state. The reply is {ok, complete, part, outcome} when the history is editable: part is a ck-part document that regenerates to the body importSldprt reads, complete is true when every feature is ours (false: the document ends in an importBody feature that stands for the rest of the file and holds the file in blobs), outcome lists every step and its check. A file that does not rebuild is not an error: the reply is {ok:false, reason, detail, outcome} with reason import (the file cannot be read), noHistory (nothing could be read back) or notEditable, and the caller keeps importSldprt. A missing data is an error reply.

Keeping the built body: built and builtExport

An importBody feature builds its body from the file held in the part’s blobs; on a spline-rich part that takes minutes. The result can be kept with the document so that the next open does not build it:

{"type":"builtExport","feature":"F9"}

answers {ok, entries:[{feature, key, source, data, rejected?}]}: the results of importBody features built from their file (source: "built") or read from the document ("saved") since the process started, newest last (at most four; feature narrows to one). Store data (base64 text; it may be compressed for storage) in the part’s top-level built table under key:

{"format":"ck-part","version":1,"blobs":{"<blob key>":"<base64 file>"},"built":{"<key>":"<base64 result>"},"features":[...]}

The entry is a cache and never an input. The feature computes the key itself (from the file’s blob key, its own id, the kernel version and the format version), and reads the entry only when the key, a checksum and the structure of the stored body all hold; with no entry, a damaged one or one from another kernel version it builds from the file as before and the part comes out the same. The restored body is identical to the built one (same faces and names, same volume, same validity). rejected says why an entry under the right key was not used. See docs/regen-cache.md, “Saved bodies”.

See also

ACIS SAT

The importSat request reads the text form of an ACIS file (.sat) and builds a B-rep with exact analytic and NURBS geometry. The importer is in crates/ck-io/src/sat. There is no SAT export.

Request

{"type":"importSat","tag":"s","name":"box.sat","data":"700 0 1 0\n@12 ck-test-gen ... "}
FieldTypeDefaultMeaning
tagstring"main"State that receives the body
namestring"part"Echoed as import.name
datastringrequiredThe SAT file as text. A missing data is a request error (importSat: data (the SAT file text) is required)

The reply is a regen-shaped result with body, errors and an import summary. On failure body is null and the tag keeps its previous state. On success massProps, validate, heal, recognize, drawing and step work on the tag.

Real output for the bundled box fixture (a 10 x 20 x 30 box):

{"format":"sat","name":"box.sat","units":1,"sheet":false,"faces":6,
 "version":700,"records":85,"bodies":1,"lumps":1,"shells":1,"skipped":{}}

massProps gives a volume of 6000 mm3 and an area of 2200 mm2, and validate is clean.

import fieldMeaning
unitsMillimetres per file unit; the geometry is already scaled
sheettrue when every face is double sided, an open sheet body rather than a solid
facesFaces of the body
versionThe ACIS version number from the header (700 is ACIS 7.0)
recordsNumber of records read
bodies, lumps, shellsCounts from the file; several bodies are merged into one kernel body, one lump each
skippedRecord types that were read past but not used, with counts (for example attributes and pcurves); sorted by name

Supported records

GroupSupported
Surfacesplane-surface; cone-surface (a cylinder when the sine is 0, otherwise a cone; circular sections only); sphere-surface; torus-surface (major radius larger than the absolute minor radius); spline-surface with an exact nubs or nurbs net
Curvesstraight-curve; ellipse-curve (a circle when the ratio is 1); intcurve-curve with an exact nubs or nurbs block
Topologybody, lump, shell, face, loop, coedge, edge, vertex, and the tolerant variants tedge, tcoedge, tvertex
SensesFace sense, coedge sense and edge sense (resolved geometrically against the vertices), single and double sided faces
TransformsBody transforms with rotation, uniform scale and translation

Dialects handled (the dialect tests also read real exported files, which are not in the repository and cannot be re-run from it; the bundled fixtures are ACIS 7.0 text): CR, CRLF and LF line endings, -N record index prefixes, the extra id integer of ACIS 20 and later (dropped at parse time), { ref N } shared spline definitions, control nets stored u-fastest (a net long in v is transposed), and many bodies per file.

ACIS cylinders and cones come without a seam; the importer inserts one when two boundary loops wrap the axis. Sphere faces cut by circles around the pole axis get a meridian seam to an implicit pole.

Errors

A failed import returns one error, in the same ["import", {code, params}] pair shape as the other import requests:

["import", {"code":"sat.parse","params":{"message":"bad SAT header (version)","entity":null,"kind":"","line":1}}]

The fields below are in params, except code.

FieldMeaning
codeOne of sat.parse, sat.empty, sat.topology, sat.unsupported, sat.geometry, sat.orientation
entityThe record ordinal as $N, or null
kindThe record’s type (cone-surface, …), empty if unknown
line1-based line in the file (0 when unknown)
messageWhat is wrong

Examples from real runs: the text hello gives sat.parse with bad SAT header (version); an empty string gives sat.parse with empty file; a header with a bad unit line gives bad SAT header (units) on line 3. A file with no faces is sat.empty. The importer never panics on malformed input.

Not supported

Each of these gives a structured error naming the record:

  • non-exact splines (approximated intcurve and spline-surface forms) and periodic splines;
  • elliptical cones;
  • torus faces whose loops wrap an axis;
  • reflecting or shearing body transforms (only rotation, uniform scale and translation);
  • sphere bands whose loops share no azimuth vertex;
  • mixed single and double sided faces in one body.

A further limit: the bundled sphere and torus files (one face, no edges) import with volume 0 and VOLUME_NONPOSITIVE.

Attributes, pcurves and any other unread record are skipped and counted in import.skipped.

Test fixtures

crates/ck-io/tests/fixtures/sat holds seven small files. Five have closed-form volumes in expected.json, checked to 1e-6 relative:

FileVolume (mm3)
box.sat6000
box_spline.sat6000
cylinder_hole.sat5277.876
plate_fillet.sat3922.743
frustum.sat593.761

The other two, sphere.sat and torus.sat, hold a single face with no edges. They import (1 face, faces: 1), but the body has volume 0 and validate reports VOLUME_NONPOSITIVE; the test expects exactly that, so a closed sphere or torus written in this form is not a usable solid after import. Larger real files are not in the repository (licence and size); the test that reads them looks in a directory named by the environment and skips when it is absent.

See also

Feature recognition

An imported solid is a plain B-rep with no history. The recognize request rebuilds an editable feature list for it: it finds holes, a prismatic or revolved base and the blends on it, emits ordinary features, rebuilds them, and compares the result numerically with the imported body. The code is the crate crates/ck-recog. It is deterministic and uses no learned model.

Request

{"type":"recognize","tag":"imp","opts":{"apply":true}}
FieldTypeDefaultMeaning
tagstring"main"State holding the body to analyse (usually an import)
opts.apply or applyboolfalseStore the rebuilt body under the tag <tag>.rebuilt

A tag with no state answers the usual noState error. A tag with state but no body answers null.

Reply

result holds:

FieldMeaning
featuresThe recognised feature list, in the same JSON as a part’s features (plane, sketch, extrude, revolve, hole, fillet, chamfer, lpattern, cpattern). Feature ids restart at F1
report.strategy"prism", "revolve" or "none"
report.noteWhy nothing was found, or null
report.featuresOne entry per recognised feature: id, type, kind, confidence, the imported faces it explains and its params
report.unexplainedFaces no feature explains: face, surface kind, area
report.faces, report.explainedFractionFace count and the fraction of faces explained
verifyThe numeric check, below. null when nothing was rebuilt
errorsRegeneration errors of the rebuilt feature list (strings)
unexplainedArea, unexplainedAreaFractionArea of the unexplained faces, absolute and relative to the whole body
appliedtrue when apply was set and a body was rebuilt

verify has volume (rebuilt), volumeOriginal, symDiffVolume (the volume of the symmetric difference, computed with the kernel’s own booleans), relativeError, areaRelativeError, bboxDeviation, exact (relative error below 1e-6) and close (below 1e-3).

Example

The plate of the STEP chapter (40 x 20 x 8 mm, sketched on the front plane, 10 mm through hole made by a hole feature) with one more feature, a 2 mm fillet on the 40 mm edge between the top cap and the side at y = 0:

{"type":"fillet","id":"F6","radius":2,
 "edges":[{"faces":["F2.C1","F2.S.e1"],"at":[20,0,8]}]}

The part is built, exported with step, imported with importStep and then recognised. The part has volume 5737.345 mm3 (the volume depends on the edge: a fillet on a shorter edge removes less material). The report (trimmed):

{"strategy":"prism",
 "features":[
  {"id":"F2","type":"extrude","kind":"base","confidence":0.95,
   "faces":["I1.F1","I1.F2","I1.F4","I1.F5","I1.F6","I1.F7"],
   "params":{"axis":"y","depth":20,"level":0,"profileLoops":1}},
  {"id":"F5","type":"hole","kind":"simple","confidence":0.9,"faces":["I1.F3"],
   "params":{"diameter":10,"through":true,"depth":null,"count":1,"pattern":"none","axis":"z"}},
  {"id":"F6","type":"fillet","kind":"fillet","confidence":0.85,"faces":["I1.F8"],"params":{"radius":2}}],
 "unexplained":[],"faces":8,"explainedFraction":1}

and verify:

{"volume":5737.345,"volumeOriginal":5737.345,"symDiffVolume":0,
 "relativeError":0,"areaRelativeError":0,"bboxDeviation":0,"exact":true,"close":true}

The recognised feature list is a sketch, an extrude, a construction plane, a sketch with the hole centre, the hole feature and a fillet whose edge is named by the base extrude’s persistent face names. With apply: true the rebuilt body is in the tag imp.rebuilt and has the same volume.

Two SolidWorks sample parts, imported with importSldprt and recognised:

PartStrategyFeaturesverify
Cone, radius 5, height 10revolvesketch, revolveexact, relative error 2e-16
Cube with a 5 mm holeprismsketch, extrude, plane, sketch, holeexact

A body the analysis cannot explain is reported as such. A whole sphere imported from STEP gives strategy: "none", no features, verify: null, and the single face I1.F1 (kind sphere, area 1256.6) in unexplained; unexplainedAreaFraction is 1.

How it works

  1. Classify faces as plane, cylinder, cone, sphere, torus or other, with their outward sense.
  2. Holes. Concave cylinders are grown into coaxial groups: concave cylinders and cones, plus planar floors and steps that meet a group member at a concave edge and have only coaxial circular edges. The circles where the group meets planes normal to the axis give the entry and exit, so the hole is through or blind, and the stage sequence (countersink cone, counterbore cylinder, bore, drill-point cone) gives its kind and sizes. A simple hole becomes a hole feature; a counterbore adds an extrude cut and a countersink a revolve cut. Identical holes become one multi-point hole, or a seed plus a linear pattern (along a world axis) or circular pattern (about a world axis through the origin).
  3. Prismatic base, tried on each of the three principal axes. Wall faces (planes parallel to the axis, cylinders with the axis parallel) form closed cycles through their vertical edges. The largest cycle is the outer profile, the others are windows. Planar caps sit at the two extremes. A constant-radius cylinder or torus tangent to a cap and a wall, or an equal-distance chamfer plane or cone, becomes a fillet or chamfer named through the base extrude’s face names. Sphere patches between blends of the same radius are folded in. Pockets, bosses and islands come from the height intervals of the wall cycles; each cycle becomes an add or cut extrude.
  4. Revolve. If a prism cannot explain the faces, a revolve is tried: every face must be a plane normal to the axis or a quadric about it. The generatrices are chained through their circular edges into a closed half profile.
  5. Verify. Up to four candidate recognitions are rebuilt in preference order. The first exact one with no unexplained faces wins; otherwise the one with the smallest volume error is reported.

Limits

Recognition covers what a few common construction patterns produce. It is not a general reverse modeller.

  • Not recognised: obliquely oriented bases or holes (the principal axes only), holes whose mouth lies on a curved wall (radial bores), B-spline or extruded-spline walls, lofts and sweeps, shells, variable and asymmetric blends, mirrored halves, whole-body spheres and tori, and bodies with cross-bores.
  • Walls that are not all parallel to one principal axis (tapered walls, ribs, slanted faces) make the wall-cycle walk fail.
  • Parts that need a revolve plus a prismatic cut are not handled.
  • Layered rebuilds can be close but not exact (1e-3 to 3e-3) when a blend edge is named across several extrudes.
  • Free-form parts and gear bodies are slow, because the verification booleans and the area integration of spline faces dominate (seconds).
  • The recognised tree reproduces the shape, not the intent: sketches are in principal planes, ids are renumbered, and dimensions are what the geometry gives.

Corpus runner: tools/recog_check.mjs regenerates each sample part, exports it as STEP, re-imports it, recognises it, and classifies the rebuild as exact, close, partial or failed. The sample parts it reads are not in the repository. On the prismatic subset (parts built only from sketch, extrude, revolve, plane, hole, fillet, chamfer and pattern features) 27 of 66 parts are exact or close; tools/recog_baseline.json stores that count and the check exits non-zero if it drops.

See also

Cylinders and cones from facets

A mesh import (SketchUp, or any polygon soup written as a B-rep) turns a cylinder into a ring of flat strips and a cone into a ring of flat trapezoids or triangles. Such a body measures and exports, but a hole cannot be drilled to its axis, a circular edge cannot be filleted and a STEP file carries hundreds of planes. The fitQuadrics request recognises these fans and replaces each by one analytic face. The code is crates/ck-ops/src/fit_quadrics.rs; it is deterministic and works on the topology and the corner positions only.

Request

{"type":"fitQuadrics","tag":"imp","opts":{"tol":0.2}}
FieldTypeDefaultMeaning
tagstring"main"State holding the body (usually an import)
opts.tolnumber0.5 % of the bounding-box diagonal (mm)The most a facet may differ from the fitted surface: the chord sag of the strips. A cylinder of radius R in N sides sags by R(1 - cos(pi/N))
opts.fitTolnumbertol / 10The most a facet corner may lie off the fitted surface (the fit residual)
opts.maxStepDegnumber30Largest angle between neighbouring rails. A square or hexagonal prism is a prism, not a cylinder; a 12-sided one is the coarsest that is fitted
opts.minStripsnumber3Fewest strips of a group
opts.smoothDegnumber20Coaxial groups meeting at a smaller crease are a curved profile (see below) and are all left alone
opts.conesbooltrueRecognise cones
opts.mergebooltrueFirst merge coplanar neighbours, so triangulated strips become quads (bodies up to 3000 faces; larger ones are reported with mergeSkipped and should be merged by the importer)
opts.volumeTolnumber0.05The fit is kept only if the volume changes by less than this fraction
opts.dryRunboolfalseReport, keep nothing

A tag with no state answers the usual noState error. A tag with state but no body answers null.

What is recognised

A group is a ring or an arc of planar strips (one outer loop each) joined along rails, the edges two strips share. The rails of a cylinder are parallel; those of a cone pass through one apex. The rails’ cross-section must lie on a circle within fitTol, in equal angular steps of at most maxStepDeg, and the chord sag must not exceed tol. An arc may end at a flat face: a shaft with a flat keeps its flat and the rest becomes a cylinder face.

Every other edge of a strip is an end chord at constant height. It becomes a circle, so the face across it has to hold that circle: a plane normal to the axis, or a strip of another accepted group on the same circle. Consecutive arcs on a circle between the same two faces are joined into one edge, a whole circle where they close. A hole in a block comes out as a concave cylinder and two circle edges.

Left alone, with a reason in declined: residual, sag, mixedSense, obliqueEnd (the end is an oblique cut: its edge would be an ellipse), endNotPlane, endMismatch, endNotManifold, coneAxis, and smoothProfile. The last is what keeps a faceted sphere, torus or ogive intact: its bands are cones, each of them valid on its own, but they meet at creases of a few degrees, so they are the tessellation of a curved profile and replacing them by cones would change the shape. A random triangle mesh has no rails and is untouched.

Reply

FieldMeaning
appliedtrue when the tag’s body was replaced
reasonWhy not: nothing (no group found), invalid (the result validates worse than the input), volumeChanged, dryRun
tol, fitTolThe tolerances used
facesbefore and after face counts
volumebefore, after and relative change. For a regular N-gon prism the change is the sag of the inscription: 1.15 % for 24 sides, 0.29 % for 48, 0.07 % for 96
issuesvalidate issue counts before and after
mergedCoplanar merges done first
groupsOne per accepted group: kind (cylinder or cone), face (the id of the new face, the first strip’s), strips, full, axis, origin, radius or halfAngle, maxResidual, sag
declined{ face, strips, reason }

The new face keeps the first strip’s name; the other strips’ names are kept in the face’s absorbed list, so references to them still resolve.

Limits

Caps that cut the axis obliquely, strips with holes in them, strips with extra vertices on their rails, spheres, tori and free-form surfaces are not recognised. A crease below smoothDeg also hides a real cone that is nearly tangent to a cylinder. The kit does not call this request yet.

Text and fonts

A text entity in a sketch turns a string into closed loops that extrudes, thin walls and region selection use like any other sketch loop. Engraved or embossed lettering (dial numerals, nameplates, part numbers) is built this way. The layout code is the crate crates/ck-text; the entity and its profile regions are in crates/ck-model/src/sketch/text.rs.

The text entity

{"type":"text","id":"t1","string":"RPM x100","font":"gauge","height":8,
 "at":[30,10],"anchor":["center","middle"],"angle":0,"spacing":1}
FieldTypeDefaultMeaning
stringstring""The text, at most 500 characters (more gives the warning textTruncated). A newline is not a line break: use one entity per line
fontstring"gauge"A built-in font (gauge, engrave; aliases sans, serif, default) or the name of a font loaded with loadFont
fontHashstringnoneA prefix of the SHA-256 of the font file the document was made with. A different file under that name gives textFontMismatch
heightnumber5Cap height (the height of H) in sketch units. Must be in (0, 1e5)
at[x, y][0, 0]Anchor position
pstringnoneA sketch point id; overrides at, so the position can be constrained or dragged. The text itself takes no constraints
anchor[h, v] or a string such as "center middle"["left","baseline"]h is left, center or right of the ink box; v is baseline, middle (height / 2) or top (height)
anglenumber0Degrees, counter-clockwise about the anchor
spacingnumber1Letter pitch factor, in (0, 20)
mirrorboolfalseMirror about the vertical line through the anchor
polylineboolfalseLines within a chord tolerance (0.005 x height) instead of B-spline edges
kernboolfalseApply the font’s pair kerning (kern table and GPOS kern)
ligaboolfalseApply the font’s standard ligatures (GSUB liga)
mergeboolfalseUnion glyphs whose contours cross themselves (overlapping strokes) before layout
runSpansnumber4Longest run of curve spans in one B-spline edge, clamped to 1 to 16
arcobjectnoneLay the letters along a circle, below
pathstringnoneLay the letters along another entity of the sketch (a line, arc, circle, ellipse or spline, construction or not), below
pathOffsetnumber0Slide along the path (mm, may be negative), added to the default place of the anchor
pathFlipboolfalseTravel the path the other way
constructionboolfalseWhen true the entity is ignored: no layout and no profile

arc fields: centre ([x, y]) or c (a sketch point id), radius (of the anchor line), angleCentre (degrees counter-clockwise from +x, default 90) and side: outside (default; letter tops point away from the centre and the text reads clockwise) or inside (tops point at the centre). Every letter keeps its shape and is rotated as a whole, tangent to the circle.

Path layout: put a construction line or curve where the text should run and name it in path. Each letter is rotated as a whole to the tangent of the path at its middle, with its baseline on the path and its top on the left of the direction of travel. A centre anchor centres the text on the path (a left anchor starts at its start, a right anchor ends at its end); pathOffset slides it along the path, pathFlip reverses the direction. Past the end the letters continue straight. The text follows the path when it moves. A path that is not a curve of the sketch or has no length is textBadPath. Wins over arc when both are given.

Using it

The text is flat on the sketch plane. Put it in a sketch of its own on a plane (standard, offset, or a plane on a planar face), then use an extrude with op: "cut" to engrave or op: "add" to emboss. Text reads correctly when the plane is viewed from its normal side. Its loops are not intersected with the other curves of the same sketch, so lettering drawn inside a rectangle of the same sketch does not become a hole in it. Keep lettering in its own sketch.

A complete check: a 60 x 20 x 3 mm plate, text RPM x100 of cap height 8 centred at (30, 10) in a sketch on an offset plane at the top face, cut 0.5 mm deep.

[
 {"type":"plane","id":"P1","mode":"offset","base":{"kind":"std","id":"front"},"offset":3},
 {"type":"sketch","id":"F3","plane":{"kind":"feature","id":"P1"},"points":[],
  "entities":[{"id":"t1","type":"text","string":"RPM x100","font":"gauge","height":8,
               "at":[30,10],"anchor":["center","middle"]}],"constraints":[]},
 {"type":"extrude","id":"F4","op":"cut","sketch":"F3","end":"blind","depth":0.5}
]

These are the last three entries of the part’s features, after the plate’s own sketch and extrude (a 60 x 20 rectangle extruded 3 mm on the front plane).

Real results: the plate volume falls from 3600 to 3540.149 mm3, which is 59.85 mm3, the glyph area (119.70 mm2, from inspect) times the depth 0.5. The body has 134 faces, errors is empty, and validate with mesh: true reports no issues. inspect on the sketch lists the entity:

{"id":"t1","string":"RPM x100","font":"gauge","fontHash":"a416bff2...","height":8,"ok":true,
 "bbox":[12.37,5.89,47.63,14.11],"area":119.70,"glyphs":8}

Requests

textMetrics and textOutline are stateless. The font requests below act on the font table of the kernel instance.

textMetrics {string, font?, height, spacing?, kern?, liga?} measures a string without a sketch. For RPM x100 at height 5 with gauge it returns:

{"advance":22.8,"bbox":[0.443,-0.071,22.486,5.071],"width":22.043,"capHeight":5,"chars":8,
 "advances":[3.236,3.221,3.786,1.429,2.843,1.9,3.193,3.193],"warnings":[]}

advance is the pen advance of the whole string, bbox the ink box relative to the pen start on the baseline, width its width and advances the per-letter pen advances. An empty string is the error textEmpty: the text string is empty.

textOutline takes the entity fields and returns {regions, bbox, area, warnings}. Each region is {outer:[[x,y],..], holes:[[[x,y],..],..]}, polylines (8 points per curved span) of the loops exactly as the sketch lays them out; area is the filled area. The string Ab in engrave at height 5 gives 2 regions, each with 1 hole, area 13.15, bbox width 8.48. edges: true adds the exact line and B-spline control points of each loop.

Errors and warnings

Errors make the sketch fail (a feature error with a detail message):

CodeWhen
textEmptyThe string is empty
textNothingToDrawOnly blanks or unknown letters
textFontNotLoadedThe font is not built in and not loaded. The message names the font and says how to load one. There is no substitution
textFontMismatchfontHash does not match the loaded file
textBadHeightHeight not a number in (0, 1e5)
textBadArcArc radius not positive
textBadPathpath is not a line, arc, circle, ellipse or spline of the sketch, or has no length
textBadValueA position, angle or spacing is not finite, or spacing is outside (0, 20)

Warnings leave the sketch valid and appear in the regen result’s warnings:

CodeWhen
textTooSmallCap height below 0.8 mm (checked: cap height 0.5 is below 0.8: ...)
textMissingGlyphThe font has no glyph for some characters; they are skipped and listed
textTruncatedMore than 500 characters
textOverlappingContoursA loaded font’s glyph has contours that cross themselves. Set merge: true to union them; otherwise validation can fail with LOOP_SELF_INTERSECT
textOverlapNeighbouring letters still overlap after the spacing adjustment, so booleans cannot merge them
textSpacingAdjustedLetters would have touched or overlapped (closer than max(1.2 percent of the height, 0.03)), so later letters were moved apart: on a line in steps of 1 percent of the height, on an arc by widening the pitch in 4 percent steps, at most 60 percent

Fonts

The kernel carries two subset fonts compiled into the binary (about 108 KB of wasm). No font is read from the machine, so the same entity gives the same geometry everywhere.

NameFaceLicenceCovers
gaugeBarlow Condensed MediumSIL OFL 1.1Basic Latin, Latin-1, bullet, minus, dashes and typographic quotes
engravePT Serif RegularSIL OFL 1.1The same set

Characters outside that set (CJK, Cyrillic, Greek) give textMissingGlyph unless a font that has them is loaded. The font reader is part of the crate: TrueType glyf (with composites), OpenType CFF Type 2 charstrings, cmap formats 4 and 12, name, OS/2, hmtx, kern, GPOS kern and GSUB liga. No external crate is used.

Loading a font

loadFont {name, data, replace?} registers a TTF or OTF for the kernel instance (the font table is process-wide, as regen has no other handle on a request: one WebAssembly instance has one table, and sessions of the native service in one process share it). data is base64; a data:...;base64, prefix is accepted. The reply for a Latin serif test font:

{"name":"plate-serif","hash":"ce049812...","builtin":false,"bytes":5712,"glyphs":33,"chars":26,
 "unitsPerEm":1000,"capHeight":700,"outlines":"glyf",
 "supported":["Basic Latin","Latin-1 Supplement"],
 "coverage":[{"block":"Basic Latin","mapped":24,"of":95},{"block":"Latin-1 Supplement","mapped":2,"of":96}],
 "warnings":[{"code":"fontKerningIgnored","detail":"..."},{"code":"fontLigaturesIgnored","detail":"..."}],
 "alreadyLoaded":false,"replaced":false}

Rules:

  • Fonts are keyed by name and by the SHA-256 of the file. Loading the same file again under the same name is a no-op (alreadyLoaded: true, checked). The same name with a different file is fontNameConflict unless replace: true. One file under two names is two fonts.
  • The built-in names cannot be loaded over: fontReserved: "gauge" is a built-in font name; choose another name for the loaded font (checked).
  • A name is 1 to 64 characters without control characters or surrounding blanks (fontBadName). At most 64 fonts and 24 MB per file (fontTooMany, fontTooLarge).
  • A file that is not a usable font is fontBadData: not a TrueType / OpenType font (unknown file signature) (checked). WOFF and WOFF2 are refused (give the TTF or OTF), as are CFF2, truncated files and files without a Unicode cmap of format 4 or 12.
  • The regen cache key of a feature includes the hash of every font its text names, so replacing, unloading or loading a font invalidates exactly the features that use it.

Load warnings (the font still loads): fontKerningIgnored, fontLigaturesIgnored (kerning and ligatures apply only when the entity opts in), fontVariableDefaultOnly (variable fonts give the default instance), fontCollectionFirstFace (TTC and OTC use the first face), fontCffApproximated (cubic CFF curves become quadratic B-splines within 0.05 percent of the em), fontNoCapHeight, fontOverlappingContours, fontEmbeddingRestricted and fontNoSubsetting (the OS/2 licence flags), and fontNoLatin.

unloadFont {name} answers {name, unloaded} (false when nothing was loaded; built-in names are refused). listFonts {} answers {fonts:[...]} with the built-in fonts first, then the loaded ones in load order. subsetFont {name, text} answers {name, hash, bytes, glyphs, data, warnings}: a plain TrueType font (base64 in data) holding only the glyphs of text plus .notdef and H. Subsetting ABC from the test font gave 4 glyphs and 3168 bytes with a textMissingGlyph warning for C, which the font lacks. The subset loads with loadFont and gives the same outlines; a document can carry a subset and pin it with fontHash.

From outlines to loops

  • A TrueType contour is quadratic. Consecutive off-curve points make one quadratic B-spline of degree 2 with clamped knots, exact and not flattened. Runs are cut every runSpans spans, so a letter is a few edges and the walls of an extrusion are B-spline surfaces, not hundreds of facets.
  • A curved span that deviates from its chord by less than 0.3 percent of the cap height becomes a line. Rounded stroke corners of a few percent of the cap height (single-span curves between two lines) are made sharp, because a face 0.1 mm wide cannot be engraved and only hurts the booleans.
  • Loops are grouped per letter by nesting depth: even depth is an outer boundary, odd depth a hole. O 0 8 6 9 A B D P Q R & @ % give faces with holes; i j : ; give separate regions. Outer loops run counter-clockwise, holes clockwise.
  • Side faces of an extrusion are named <feature>.S.<id>#n like those of any sketch entity.

Limits

  • Text is planar. It lives on a sketch plane, so there is no wrapping or projection onto a curved face. For a curved part, place a plane tangent to the face and accept that the cut or boss is flat.
  • A single line per entity, left to right. No right-to-left or complex scripts, no contextual alternates, no bold or italic synthesis (load the bold file instead).
  • Kerning and ligatures are off unless the entity sets kern or liga. Subsets drop the layout tables, so a subset kerns and ligates as a no-op.
  • Connected script faces overlap by design. Overlapping letters are not merged; the spacing adjustment pushes them apart or reports textOverlap, and a 35-character string can take 0.5 to 2 s. Use them for short names.
  • Glyphs whose boundary only touches itself at a point fall back to the unmerged loops with a warning.
  • Letters of different entities that overlap are neither merged nor checked.
  • A rare display-mesh crack (about 1 case in 1500 random strings) reports TESSELLATION_OPEN from validate with mesh: true between two neighbouring walls, although the B-rep is valid and the volume is right.
  • Below 0.8 mm cap height the strokes are too thin to engrave or print.

Checks

cargo test -p ck-text covers glyph area, nesting, orientation, anchors, arcs, metrics, font loading with twelve fixture fonts, and 900 damaged font files. The corpus runner node tools/text_corpus.mjs builds 126 cases through the wasm (engraving and embossing, every glyph with holes, rotation, mirror, several planes, dial numerals, arc text, text past a plate edge, error and warning cases, opt-in kerning, ligatures and merge, loaded fonts). Each case checks that there is no error and no booleanFailed, that validate with mesh: true is clean, and that the volume change equals the glyph area times the depth to within 1 percent. In this chapter’s run all 126 passed in 53 s.

See also

Drawings

The drawing request projects a body into 2D views: visible and hidden lines, curve outlines, centre lines and, optionally, a hatched section. The reply is geometry only, in view coordinates; layout on a sheet, dimensions and annotations are left to the client. The projection code is in crates/ck-ops/src/drawing, the request check in crates/ck-server/src/drawing.rs.

Request

{"type":"drawing","tag":"main","hidden":true,
 "views":[{"name":"front"},
          {"name":"top"},
          {"x":[1,0,0],"y":[0,0,1]},
          {"name":"front","section":{"point":[0,0,4],"hatch":3}}]}
FieldTypeDefaultMeaning
tagstring"main"State to project. A tag with no state answers noState: nothing regenerated yet, even if views is malformed
viewsarray[]The views to produce. A missing or non-array value answers {"views":[]}
hiddenbooltrueInclude hidden lines (v: false). With false only visible pieces are returned

Each view is an object with either a name or both x and y:

View fieldMeaning
nameOne of front, back, left, right, top, bottom, iso
x, yArrays of three numbers: the view’s horizontal and vertical axes in world coordinates. The viewing direction is x cross y, normalised
sectionOptional {point:[x,y,z], hatch?}. The body is cut by the plane through point normal to the viewing direction; the half on the viewer’s side is kept and the cut face is hatched with 45 degree lines hatch units apart (default 3)

If any view lacks a valid name and lacks both x and y, the whole request fails with drawing: a view needs a name (front, back, left, right, top, bottom, iso) or x and y (checked). The part’s world axes are Y up; the named views are:

NameView x (right)View y (up)Looks along
front+X+Y-Z (viewer at +Z)
back-X+Y+Z
right-Z+Y-X (viewer at +X)
left+Z+Y+X
top+X-Z-Y (viewer at +Y)
bottom+X+Z+Y
iso(0.707, 0, -0.707)derivedfrom (1, 1, 1)

A part sketched on the front plane and extruded with a positive depth therefore appears in the front view as the sketch, and in the top view as a strip below the X axis.

Reply

{"ok":true,"result":{"views":[ {view}, ... ]},"ms":0}

Each view is:

FieldMeaning
min, max[u, v] bounds of all emitted line points
linesThe drawn pieces, below
edgesOne entry per model edge seen in the view, plus one per outline
axesCentre lines of cylinders, each [[u0,v0],[u1,v1]]

A piece in lines:

FieldMeaning
k"e" edge, "t" tangent edge (the two faces meet with parallel normals, as at a fillet boundary), "o" outline (the silhouette of a curved face), "h" section hatch
vtrue if visible, false if hidden
pFlat polyline [u0, v0, u1, v1, ...] in view units (the model’s millimetres)
eIndex into this view’s edges array. Hatch pieces have no e

An entry in edges:

FieldMeaning
facesSorted ids of the faces meeting at the edge
atThe edge midpoint in world coordinates
lineTwo projected points, for straight edges
circle{c:[u,v], r} for a circle seen face-on
mid, endsThe projected midpoint and end points
outlinetrue for a silhouette entry
roundtrue for a full circle seen edge-on that spans the view’s full width

Curved pieces are polylines, so a circle arrives as a sequence of points.

Examples

The plate of the STEP chapter: 40 x 20 x 8 mm, sketched on the front plane, with a 10 mm through hole at (20, 10) made by a hole feature. The part:

{"format":"ck-part","version":1,"name":"plate","features":[
 {"type":"sketch","id":"F1","plane":{"kind":"std","id":"front"},
  "points":[{"id":"a","x":0,"y":0},{"id":"b","x":40,"y":0},{"id":"c","x":40,"y":20},{"id":"d","x":0,"y":20}],
  "entities":[{"id":"e1","type":"line","p1":"a","p2":"b"},{"id":"e2","type":"line","p1":"b","p2":"c"},
              {"id":"e3","type":"line","p1":"c","p2":"d"},{"id":"e4","type":"line","p1":"d","p2":"a"}],
  "constraints":[]},
 {"type":"extrude","id":"F2","op":"add","sketch":"F1","end":"blind","depth":8},
 {"type":"plane","id":"F3","mode":"offset","base":{"kind":"std","id":"front"},"offset":8},
 {"type":"sketch","id":"F4","plane":{"kind":"feature","id":"F3"},
  "points":[{"id":"p1","x":20,"y":10}],"entities":[{"type":"point","id":"e1","p":"p1"}],"constraints":[]},
 {"type":"hole","id":"F5","sketch":"F4","kind":"simple","diameter":10,"end":"through"}]}

Results of a fresh run:

ViewminmaxPiecesEdgesedges with circle
front[0, 0][40, 20]7153
top[0, -8][40, 0]6170
iso[-5.66, -19.60][28.28, 16.33]17170

In the front view the four outer edges are straight pieces, for example {"k":"e","v":true,"p":[0,20,40,20],"e":9}. The hole rims are three visible polylines: a closed one of 39 points starting at (25, 10) (the rim point on the +u side of the centre (20, 10)), and two partial arcs of 15 and 25 points that end at (16.36, 13.42). Three entries of edges carry "circle":{"c":[20,10],"r":5}. In the top view the hole appears as two hidden outline pieces, with e indices 15 and 16:

[{"k":"o","v":false,"p":[15,-8,15,0],"e":15},{"k":"o","v":false,"p":[25,-8,25,0],"e":16}]

and axes is [[[20,-8],[20,0]]]. With "hidden":false the top view keeps its 4 visible pieces and drops the 2 hidden ones.

A section of the front view through [0, 0, 4] (half way up the plate’s thickness, which runs along Z) returns 25 pieces: edge pieces plus 18 hatch pieces of the form {"k":"h","v":true,"p":[38.18,0,40,1.82]}. The cut face is named SEC.C1 in the faces of 6 edge entries. With hatch: 6 the hatch count drops to 9. A section plane that misses the body gives that view only {"error":"cutNoEffect"} (checked with a point at z = 40).

A sphere made by the part {"format":"ck-part","version":1,"features":[{"type":"sphere","id":"F1","op":"add","center":[0,0,0],"radius":10}]} gives, in the front view, a single outline piece k: "o" of 127 points, min [-9.997, -10], max [10, 10] and no edges.

Empty state

A tag whose state has no body (an empty part) answers null, or {} when hidden is truthy. Clients should check for a body first.

Limits

  • No dimensions, tolerances, notes, title blocks or sheet layout. Thread callouts and cosmetic thread symbols are not drawn.
  • Curved faces are drawn as polylines; there is no exact arc or spline output.
  • Silhouettes of smooth faces other than cylinders come from the display mesh (marching the zero set of the surface normal against the view direction), so they are accurate to the mesh tolerance rather than exact. The emission order of curved pieces and the round flag are conventions, not guaranteed stable.
  • Duplicate coincident pieces are not merged for curved edges (front and back rims in the example above).
  • Hidden-line removal uses the tessellated body as occluder, so complete hidden-line handling for curved occluders is not exact.
  • A section keeps one half and cuts with a single plane; offset or stepped section lines are not supported.

See also

Testing

The kernel is tested at four levels: Rust unit tests inside each crate, Rust integration tests that drive whole requests, Node scripts that run the built WebAssembly module against corpora and sweeps, and a regression gate that compares a scoreboard of metrics with a committed baseline. This chapter describes the first, second and fourth; the corpora are in corpora and sweeps.

Rust tests per crate

Every crate is tested on its own. A text search finds about 1,200 #[test] functions in the workspace (approximate, counted by grep); about 30 more are #[ignore]d probes, described below.

CrateWhere the tests areWhat they cover
ck-core, ck-geomsrc/ modulesLinear algebra, quadrature, k-d tree, budget clock; curves, surfaces, NURBS evaluation, fitting, conversions
ck-toposrc/ modulesExtrusion and revolution builders, orientation, mass properties, region classification, edits, naming
ck-checksrc/tests.rsA good box validates clean; the same box damaged (open shell, flipped face, …) must report the expected code
ck-healsrc/tests.rs, tests/integration.rsDamage a valid body (damage.rs has the kinds), heal it, require validate clean and the volume unchanged
ck-tesssrc/, tests/Constrained Delaunay triangulation, per-face meshing, poles and domes
ck-opssrc/ (about 190 tests) and tests/Booleans (grid fuzz of 600 sequences, spheres, tangent and toleranced operands), blends, lofts, sweeps, shell, surfacing, surface-surface intersection
ck-modelsrc/ and 72 files in tests/Feature behaviour by family: blends, booleans, sweeps, lofts, shell and thicken, patterns, threads, text, mates, projection; regression files for named bugs; the robustness suite (below)
ck-iotests/STEP writer entities, STEP round trip, hand-written import fixtures, NIST-derived cases, ACIS SAT fixtures and dialects, multi-solid files
ck-skp, ck-sldprttests/Sample files from each container version, bodies against known mass properties, a mutation fuzzer that must never panic
ck-textsrc/tests.rs, src/font_tests.rsGlyph area, nesting, orientation, anchors, arcs, metrics; twelve fixture fonts; 900 damaged font files
ck-recogtests/Recognition of kernel-built parts and rebuild accuracy
ck-server, ck-wasmsrc/, tests/The request envelope; full requests through the dispatch table: STEP, SAT, SketchUp imports, healing, regen cache, loft families, section and measure queries, part versions
ck-nativetests/service.rsThe local HTTP service: replies equal direct calls, sessions do not share state, authentication and origin checks, size limits, keep-alive, idle expiry, pairing

To run one crate:

cargo test -p ck-io
cargo test -p ck-model --test blend_overhang           # one test file
cargo test -p ck-io --test dump write_ours -- --ignored  # one ignored probe

Heavy crates are faster with the fast profile, which keeps release optimisation but turns link-time optimisation off and uses 16 code-generation units:

cargo test --profile fast -p ck-model

Ignored tests are developer probes or documented open items. Probes read an environment variable (STEP, CK_PART, PART, CASE) naming the input to inspect, and print timings or dumps. Open items carry their reason in the attribute, so cargo test -- --ignored lists them:

  • a blade-to-hub ring blend whose ball-centre solve diverges at a shallow dihedral;
  • three near-tangent rail spacings of a marine-fuse case that leave an open edge;
  • the sphere patch of a concave fillet corner, whose seam is sampled finer than its neighbour (30 T-junctions among 462 mesh edges);
  • adjacent conic or curvature fillets at a corner of two spline sections (blendFailed);
  • the torus eye of one imported part, dropped from the display mesh.

Invariants the tests check

The same few properties recur across the suites. A result is accepted only if:

  1. It validates. validate (the independent checker in ck-check) reports no issue, which covers closed manifold shells, Euler characteristic, loop closure and orientation, edge and vertex agreement with their faces, positive volume, and with mesh: true a watertight display mesh. See topology and geometry checks.
  2. It has the right numbers. Volume, area and centre of mass equal a closed-form value (a prism, a revolved profile, a sphere) or a value computed another way, typically to 1e-6 relative. For free-form shapes, a numerical integral or a section-area integral is used.
  3. It survives a round trip. STEP export followed by import keeps volume and area (1e-6), the face and edge counts, and a clean validate.
  4. It is deterministic. A warm regeneration that reuses the cache is byte-identical to a cold one; repeated runs give the same bytes. The sine and cosine used by the kernel are ported (ck_topo::trig) because the platform math library can differ by one unit in the last place from the WebAssembly build.
  5. It never traps and never hangs. Every error path must return a structured code. crates/ck-model/tests/robust_*.rs run documents on a worker thread with a time limit and fail on a panic, a hang, or an error with an empty code; the cases in tools/cases/crash/ are replayed there.
  6. Untrusted input is refused, not crashed on. Importers get truncation, bit-flip and splice fuzzing.

Native and WebAssembly

The shipped kernel is the crate ck-wasm compiled to wasm32-unknown-unknown. Its exports are ck_alloc, ck_request, ck_reply, ck_commit and ck_commit_len; the host provides ck_now, ck_unix_ms and ck_panic. The same engine can run natively: tests call ck_wasm::engine::install() and then ck_server::handle(bytes), the same entry point the exports use. So the Rust suites exercise the production request path without a browser.

Differences to keep in mind:

  • Panics. The release profile sets panic = "abort", so a panic in the module is a WebAssembly trap that cannot be caught. Test targets use panic = "unwind". The service profile (release optimisation with unwinding) is for the native HTTP service, which catches a panic and ends only that session.
  • Clocks. Time budgets (featureTimeMs, regenTimeMs) are active only where the host supplies a clock. Native tests without a clock are never cut short, which keeps unit tests deterministic; robust_budget.rs drives the budget with a counter clock.
  • Floating point. Release builds use one code-generation unit, which gave the same results as more units and a smaller module.
  • Speed. Native runs are roughly two to three times faster than the module in the same machine.

The Node scripts in tools/ always run the built module through a small host (tools/kernel.mjs) that instantiates it, supplies the clock imports, and re-instantiates it after a trap. Build the module with cargo build -p ck-wasm --target wasm32-unknown-unknown --release (or tools/build_wasm.sh, which also runs wasm-opt when available), then pass it with --wasm; most scripts default to the release path.

The TypeScript packages (packages/part-model, builder, kernel-client, driver, session and render) have their own tests: npm test in packages/ builds all of them and runs node --test over every compiled *.test.js file under dist/*/src/. One test walks every part under tools/cases and the BenchCAD parts and checks that each rebuilds through the builder to the same document and regenerates to the same result.

What runs from a bare checkout

Some checks compare the kernel live against a second kernel build, called here the comparison build: parts of tools/gate.mjs, and tools/edit_robustness_check.mjs. The comparison build is a separate kernel.wasm that must be placed next to the checkout (the scripts look for ../../kernel.wasm relative to tools/; edit_robustness_check.mjs also takes --orig path). It is not distributed with the repository. The gate runs without it in standalone mode (below); everything else here runs from a bare checkout plus a built module:

Needs only the repository and a built moduleNeeds the comparison build
cargo test for every cratetools/gate.mjs without --standalone (it opens the comparison build before running any metric)
text_corpus, boolean_corpus, blend_corpusThe gate metrics wire, regen.*, mass.*, vol.* and step (replies, volumes and STEP text compared with the comparison build’s)
lint_protocol, section_check, thread_checkThe gate metric edit.robust and tools/edit_robustness_check.mjs
skp_check, sldprt_check, regen_cache_check
tools/gate.mjs --standalone: the metrics that judge the module alone (valid.*, build.*, the closed-form mass-property metrics, import.*, heal.repair, naming.stable, iface.*, bench.*)
The sweeps and crash_fuzz, run with --wasm <module> --check <baseline> against their committed baselines

Scripts that load a module take --wasm; several default to a path outside the checkout, so pass it explicitly (for example --wasm target/wasm32-unknown-unknown/release/ck_wasm.wasm).

The regression gate

tools/gate.mjs runs the built module and the comparison build side by side over a fixed set of cases, computes a scoreboard of counts (items that pass out of items tried), compares it with the committed tools/scoreboard.json, prints each metric with its change, and exits with status 1 if a hard metric went down. With a comparison build next to the checkout it runs every metric; the numbers below are from that run. Without one (or with --standalone) it prints standalone: no comparison build and runs only the metrics that judge the module alone, which it compares with its own baseline, tools/scoreboard.standalone.json (--update writes that file in this mode). In standalone mode valid.* counts the parts that build and build.* counts how many do; the metrics that compare with the comparison build (wire, regen.*, mass.*, vol.*, step) and edit.robust are not run, so a standalone pass does not replace the full gate for a change to geometry or output formats.

node tools/gate.mjs [--quiet] [--standalone] [--wasm path/to/ck_wasm.wasm]   # all metrics need the comparison build, except with --standalone
node tools/gate.mjs --update      # rewrite the baseline, in the commit that improves a metric

Some metrics compare the two builds’ replies (wire, regen.*, mass.*, vol.*, step) and the quick edit check (edit.robust); they are not listed here. The metrics that judge the kernel on its own, against closed-form values, round trips or ground-truth files, are:

MetricKindCommitted countWhat it counts
analytic-reference metrichard59 / 59Volume, area, centre and bounding box against closed-form values derived from the feature parameters (1e-6)
valid.brephard280 / 319No feature error, positive volume, every edge bounds two faces, validate clean
heal.repairhard1740 / 1745Damaged copies of the valid bodies (seven damage kinds) healed back to validate clean with the volume within 1e-6
import.roundtriphard258 / 259STEP export then importStep: volume and area 1e-6, same face and edge counts, clean validate
import.heal.noophard258 / 258Healing an already valid import changes nothing
import.sathard5 / 5The five closed-form SAT fixtures import clean with the expected volume
bench.benchcad, .stepsoft49 / 50, 45 / 50The BenchCAD parts against their ground truth, and the ground-truth STEP files through importStep
bench.brepjs.stepsoft23 / 25The brepjs reference STEP files through importStep
naming.stablesoft214 / 216References to earlier faces still resolve to the same geometry after an upstream dimension edit
iface.*soft58 / 58 eachAgent-query self-consistency (describe, resolve, check, refDiff) on every fourth part

These too are computed inside gate.mjs and run in standalone mode; their scripts (tools/bench/run.mjs, tools/naming_stability.mjs, tools/agent_iface.mjs) can be run alone. Hard metrics fail the gate when they fall. Soft metrics print WARN(soft). A metric not in the baseline prints (new).

Results of the checks run for this book

These runs used the module built from this repository and the commands shown:

CommandResult
node tools/text_corpus.mjs --quiet126 / 126 cases ok (53 s)
node tools/boolean_corpus.mjs --quiet145 / 147 ok, 2 booleanFailed
node tools/blend_corpus.mjs142 / 150 ok, 0 failed, 6 known, 2 without a reference volume
node tools/lint_protocol.mjs120,635 requests over 57 request types, 0 violations
node tools/edit_robustness_check.mjs --quick (needs the comparison build)12 parts, 24 edits, 22 comparable, 0 failures
node tools/section_check.mjs --quick, node tools/thread_check.mjsboth ok
node tools/regen_cache_check.mjs2,827 checks ok (9.5 min)
node tools/feature_sweep.mjs --samples 15 --seed 7 --wasm <module> --check tools/feature_sweep_baseline.json0 regressions (120 ok)
node tools/skp_check.mjs17 sample files: 14 imported, 3 refused with body.empty, 0 traps

See also

Corpora and sweeps

Beyond the unit tests, the kernel is measured against sets of parts with known answers. A corpus is a fixed list of cases, each with an expected result. A sweep generates seeded random cases from templates and compares each with an independently computed value. This chapter lists them, says what each measures and how to read the output, and gives the committed results. All scripts are in tools/ and run on Node against the built module (see testing).

Reading a result

Most scripts print one line per case and a summary of classes. The class names are shared:

ClassMeaning
okNo feature error, validate clean where checked, and the number agrees with the reference within the tolerance of that script
okNoEffect, okEmptyThe operands do not overlap, so a cut changed nothing or an intersection was empty; correct, not a failure
wrongVolume, wrongAreaThe kernel built something valid-looking whose volume or area is off the reference
invalidThe result has validate issues (EDGE_OFF_SURFACE, TESSELLATION_OPEN, …)
booleanFailed, blendFailed, blendOverflow, shellFailed, …A structured feature error; see errors
refusedAn expected refusal (for example a shell wall thicker than the part allows)
kernel-null, trap, hangNo reply, a WebAssembly trap, or a timeout
ref-failsThe reference computation could not build the case; the case says nothing about the kernel
knownA failure with a documented cause, which does not fail the run

Sweeps and fuzzers take --samples N --seed S, write detail with --json out.json, store a class-only baseline with --update-baseline file and compare with --check file. A check exits non-zero only when a case that passed in the baseline now fails; new passes are printed but are not errors. A baseline stores case ids and classes, plus the module hash, seed and sample count.

Reference values

  • Closed forms derived from the parameters: prisms, revolved profiles, spheres, tori, grids of unit cells.
  • An independent geometry library, called through Python bindings, for volume, area, centre of mass and inertia of the same shape built with the same parameters. The scripts tools/*_ref.py are needed only to refresh or extend a baseline; running a baseline --check needs only Node.
  • Ground truth shipped with a dataset (BenchCAD, brepjs examples): volume, area, centre of mass, bounding box and a STEP file per part.

Corpora

CorpusScriptCasesWhat it measures
Generated partstools/brep_cases.mjs (feeds the gate)319Small documents across the feature families (extrudes with each end condition, revolves, holes, patterns, blends, lofts, sweeps) and prefixes of the larger sample parts; 59 have closed-form volume, area, centre and box
Protocol casestools/cases.mjs (feeds the gate)133 cases, 280 request bodiesEnvelope handling, malformed bodies and each request type
Boolean coincidencetools/boolean_corpus.mjs147Extrude and revolve add and cut, moveBody and the body-level combine with coincident, tangent, near-coincident, contained, coaxial and sliver geometry. Each has an analytic volume and, where defined, a lump count. --fuzz N runs random add and cut sequences on an integer grid whose exact volume is a count of unit cells. --tol and --auto try the fuzzy tolerance
Blendstools/blend_corpus.mjs150Fillets and chamfers (constant and variable radius, unequal radii, corners, rounded outlines, overhang corners) against reference volumes in tools/blend_reference.json. Bands: 1e-5 for planar bodies, 1e-4 for curved ones, wider for variable and unequal radii at corners
Letteringtools/text_corpus.mjs126Engraving and embossing, every glyph with holes, planes, arcs, fonts; the volume change must equal the glyph area times the depth to 1 percent. --fuzz N --seed S runs random strings
OpenCASCADE test scriptstools/occt_corpus.mjs1664Primitives, booleans, blends and drafts translated from the OpenCASCADE test suite, compared with its own checkprops values
BenchCAD-derived partstools/bench/run.mjs50Parts translated by hand from a public benchmark: regenerate, compare volume and area (1e-3), centre and box, validate, and import the dataset’s STEP
brepjs-derived partstools/bench/run.mjs --set brepjs25Mechanical examples translated by hand; the reference STEP files go through importStep
Crash casestools/cases/crash/24Minimal documents that once trapped or hung; replayed by robust_cases.rs
STEP importstools/step_nist_check.mjs, tools/import_sample_check.mjs, tools/heal_check.mjsvariesNIST test-case STEP files with reference volumes, and samples of 200 files from a public research set
SketchUp, SolidWorkstools/skp_check.mjs, tools/sldprt_check.mjs17 and 4Sample files per container version: imported, faces, volume, validity, time
Recognitiontools/recog_check.mjsvariesRegenerate, export, re-import and recognise sample parts

Boolean coincidence corpus

Run in this chapter: 145 of 147 cases ok. The two failures are booleanFailed on near-coincident cylinders 1e-3 apart: two stacked cylinders of radius 5 and 5.001, and a plug of radius 5.001 fused into a hole of radius 5. The rim circles are too far apart to weld, so the intersection curves cannot close. With --tol 1e-3 or --auto all 147 pass, because the tool wall is first snapped onto the host wall and the case becomes the exactly coincident one. The grid fuzz (--fuzz 300 --seed 7: four boxes per sequence on a 5-unit grid) passes 299 of 300.

Blend corpus

Run in this chapter: 142 of 150 ok, 0 failed, 6 known, 2 without a reference volume (the external builder fails on them). A pick is a point on an edge; both the kernel and the reference take the edge of the base body nearest to it. The base bodies are built by the kernel and written with step, so both start from the same geometry. The known cases and the open items (three-edge corners with unequal radii, which are valid but not tangent-continuous and carry a cornerNotTangent warning, and some sector fillets) are in the corpus notes.

OpenCASCADE test scripts

tools/occt_corpus.mjs translates test scripts from the OpenCASCADE repository into feature trees. The test data files of that suite are distributed separately and are not used; the data-driven cases are counted as needs-data and left out. OpenCASCADE source and test data are not part of this repository (OpenCASCADE is LGPL-2.1 with an exception). The runner reads a checkout fetched by tools/occt_fetch.sh; the committed tools/occt_picks.json holds derived edge midpoints and directions only. Edge and face picks are matched by position, not by index.

Committed baseline of the 1664 selected cases (tools/occt_baseline.json): 1570 ok, 29 invalid, 19 booleanFailed, 17 wrongArea, 8 unsupported (shapes the translator cannot express), 7 blendUnsupported, 6 booleanVolumeMismatch, 3 blendFailed, and five single cases: combineEmpty, missingEdge, draftUnsupported, invalidValue and missingReference. The failures cluster in sphere against box corners, perpendicular cylinder intersections, cone and cylinder seams, and fillets on partial cylinder and cone sectors.

Sets that ship and their licences

SetSourceLicenceIn the repository
BenchCAD-derived partsBenchCAD/BenchCAD, configuration code_genCC-BY-4.0; attribute the BenchCAD authorsGround-truth STEP files and our own translations of 50 parts (no source code copied)
brepjs-derived partsThe mechanical examples of the brepjs playgroundApache-2.0; attribute the brepjs projectOur translations of 25 examples (parameters paraphrased) and ground truth from running the examples
NIST PMI test filesNIST MBE PMI validation projectUS Government work, public domainOne file (nist_ftc_11.step) and computed reference volumes of the others
OpenCASCADE testsOpenCASCADE TechnologyLGPL-2.1 with exceptionNothing vendored; derived pick coordinates only
Public research sets of STEP filesPublished by CAD vendors and universitiesNon-commercial research termsNothing: fixed sample ids and class-only baselines only

THIRD_PARTY.md has the exact entries. Research-only data must not be redistributed or used as a release gate for a product, which is why the repository keeps sample ids and baselines, not files.

Sweeps

Each sweep is seeded, generates cases from templates, runs them through the module, and compares with an independently computed value. The results below are the committed class-only baselines (seed 7 unless noted); they are snapshots of one build, so re-run --check for the current state.

SweepScriptCasesMeasuresCommitted result
Fillet and chamfertools/fillet_sweep.mjs640 (16 templates x 40)Volume of box, cylinder, tube, boss, hole-rim, variable-radius and rounded-outline fillets and the three chamfer forms575 ok, 32 blendOverflow, 28 wrongVolume, 3 blendFailed, 2 kernel-null. Seed 11: 591 ok, 30 wrongVolume, 16 blendOverflow, 3 kernel-null
Shell and thickentools/shell_sweep.mjs480Inward and outward shells of boxes, tubes, cones and an L body; thicken of planar, cylindrical and conical sheets324 ok, 97 wrongVolume, 42 refused, 15 shellFailed, 2 draftTooLarge
Booleantools/boolean_sweep.mjs320Primitive pairs (box, cylinder, cone, sphere, torus) with overlap, coincident, tangent, contained, sliver, angled and chain relations146 ok, 80 okNoEffect, 65 okEmpty, 22 wrongVolume, 5 invalid, 2 booleanFailed. The 175 cases that are neither okNoEffect nor okEmpty contain all 29 failures
Loft, revolve, sweeptools/shape_sweep.mjs240Volume of two- and three-section lofts, point-ended lofts, revolves, line, arc and mitred sweeps223 ok, 16 wrongVolume, 1 ref-fails
Mass propertiestools/massprops_sweep.mjs240Volume, area, centre of mass and inertia tensor, 1e-6 relative220 ok, 20 wrongVolume. All 20 are three-section circle lofts, which differ from a thru-sections reference surface by up to 6.7 percent in volume, 3.7 percent in area, 1.6 percent in centre of mass and 10 percent in inertia. Every other template agrees to 2e-14 or better
STEP round triptools/step_roundtrip_sweep.mjs120Export, read by the reference library and re-import: volume and area to 1e-6, a validity check on its body, validate on ours100 ok, 20 ocp-wrongArea (lofts: the reference library’s area of the written file is 5e-4 to 8e-4 low; our re-import reproduces both numbers exactly)
Tessellationtools/tess_sweep.mjs180Volume and area of the display mesh against massProps; fails above 0.1 percent96 ok, 84 meshVolume; the worst are torus (0.8 percent) and cylinder (0.4 percent), caused by chord height at the default tolerance. Mesh area stays under 0.1 percent everywhere
Holes, patterns, mirror, drafttools/feature_sweep.mjs120Through, blind, counterbore and countersink holes; linear and circular patterns; mirror; draft120 ok
Crash fuzztools/crash_fuzz.mjs5000Schema-valid random documents of 2 to 8 features with degenerate parameters; see robustness668 ok, 4290 structured errors, 24 invalid results, 13 surface-only and 2 degenerate documents, 0 traps, and 3 hangs (an open defect)
Research STEP samplestools/import_sample_check.mjs200 per sampleimportStep and validate on files kept outside the repositorySeed 1234: 185 ok, 15 invalid (TESSELLATION_OPEN 13, EDGE_OFF_SURFACE 7, LOOP_SELF_INTERSECT 1, EULER 1; some files carry two codes). Other seeds: 4242 gives 188 ok, 5678 gives 185, 9001 gives 187. One file is a known slow import (over 90 s)

How to read these:

  • A wrongVolume group is not random: each sweep’s notes name the template and parameter range (for example outward shells with the top removed, or three-section lofts). Use the failing parameter range to decide whether a case is in a known gap before suspecting a regression.
  • blendOverflow in the fillet sweep starts when the radius approaches half the shortest side of a box, or half the height of a cylinder; the reference library succeeds on those, so they are genuine large-radius gaps.
  • refused in the shell sweep is the expected shellTooThick answer for walls that cannot fit.
  • The tessellation sweep measures the display mesh, not the exact B-rep; exact volumes come from massProps.
  • The shell sweep is run one template at a time (--only box_top); a single process that walks every template can stop responding.

One-command run

tools/verify_wasm.sh <module> [--quick|--accept] runs the sweeps and corpora above against one module and prints a single page of counts per class, new passes and regressions with case ids. Each template runs in its own process with a hard timeout, so a hang is reported as ERROR: <template>: hang and does not block the run. The exit status is non-zero only on a regression, meaning a case that passed in its baseline and now fails. --quick uses one seed and four templates per sweep and takes under two minutes. --accept does a full run and rewrites every baseline.

See also

Robustness under edits

A kernel driven by a person nudging one number, or by a program editing a part in a loop, must not turn a model that builds into a broken one, must not crash, and must not hang. This chapter describes the rules the code follows and the checks that enforce them: structured errors and work budgets, the crash fuzzer, the single-parameter edit check, and the determinism and concurrency checks.

The rule: errors are values

A failed request must return a precise error and leave the kernel usable. The release module is built with panic = "abort", so a Rust panic is a WebAssembly trap with no way to catch it at the request boundary. There is no generic safety net; the defence is this rule:

  • No unwrap(), expect(), slice index or map lookup by key on data that comes from a document or from geometry (a topology lookup, a curve fit, an intersection result, a parsed parameter). Use get, first or ok_or_else and return an error.
  • The error has a code, a message saying what failed and, where possible, a hint on what to change (shellUnsupported, blendOverflow, booleanFailed with its parameters).
  • If a missing key means a logic bug, fix the logic and add a test. If the input is genuinely unsupported, return a structured refusal.
  • Every loop whose trip count depends on geometry has a bound or a progress check. A loop that can run long polls the work budget.
  • A hang is a result or a structured error. Slow is allowed; unbounded is not.

Work budgets

Wall-clock limits are active only where the host installs a clock (ck-wasm takes it from ck_now; native tests without a clock are never cut short). They are options on the regen request:

OptionDefaultMeaning
opts.featureTimeMs120000Time allowed for one feature; 0 means unlimited
opts.regenTimeMsnoneTime allowed for the whole document; 0 or absent means unlimited

The feature default is large so that a result does not depend on machine load: a pattern that takes 5 s on a quiet machine took over 30 s on a busy one and failed with a budget error. Choose regenTimeMs larger than featureTimeMs. The budget is polled in every boolean attempt and its retry ladder, the face-pair imprint loop and the pattern instance loop.

CodeWhenParameters
featureBudgetExceededA feature ran past featureTimeMs; its result is not appliedbudgetMs, elapsedMs, hint, cause (the code the feature would have reported)
regenBudgetExceededThe document ran past regenTimeMs; this and the following features did not runthe same
booleanBudgetExceededA boolean was stopped by a limit, or a failing boolean that had already run 12 s did not start its three robust retriesbudgetMs, elapsedMs, hint

A feature that fails while a limit is running out reports the limit, whatever its own code was. Slow cases still exist, for example a linear pattern with count 100 of a revolve followed by a fillet, which takes 5 to 30 s on a quiet machine; it ends in a result or featureBudgetExceeded, never a trap. The cost is the boolean with a 100-instance tool, a matter of speed rather than a missing bound.

The crash fuzzer

tools/crash_fuzz.mjs generates seeded, schema-valid documents of 2 to 8 features with degenerate parameters and runs each in its own worker, so a trap or timeout kills only that case. It then shrinks every distinct trap or hang to a small document.

node tools/crash_fuzz.mjs --cases 5000 --seed 7 --budget-ms 400 --timeout 6000 --json out.json
node tools/crash_fuzz.mjs --cases 200 --seed 7 --no-shrink --json out.json
node tools/crash_fuzz.mjs --cases 5000 --seed 7 --check tools/crash_fuzz_baseline.json

Classes:

ClassMeaningAcceptable
okA valid resultyes
structured-errorA useful error replyyes
trapWebAssembly unreachable or panicno
hangPer-case timeoutno; 3 remain open (below)
invalid-resultAn ok reply whose validate has issuestracked
wrong-answerA positive-volume or area invariant brokenno
surface-only, degenerateDocuments with no solid, or with noise-sized bodiesyes

The committed baseline of 5000 cases (seed 7, --budget-ms 400) is 668 ok, 4290 structured errors, 3 hangs, 24 invalid results, 13 surface-only and 2 degenerate documents, and no traps. The 3 recorded hangs (case_34, case_644, case_2668) were slow cases rather than infinite loops, and the class is a wall-clock limit (6 s per case, with 8 workers sharing the machine), so its count depends on how busy the machine is. The cause of the worst one was found and fixed: a chamfer that left a trim far off its cone made the mesher split triangles that could never come within the tolerance until its whole budget (about 25,000 points) was spent, and validate then spent a second on the exact area of the same face. Alone, that case went from 1.1 s to 50 ms for regeneration with the display mesh and from 2.3 s to 0.15 s for validate. Two guards in the refinement (see tessellation) cover the same failure on other surfaces. On the same machine and settings a run of the build before the change showed 56 cases past the limit and runs after it showed between 4 and 10, a different few each time. The baseline file is not re-recorded from such runs; a few cases (for example case_4259, a hundred copies of one degenerate face) are still slow.

To add a case: find it with the fuzzer, save the minimal document (minimal[].features of the output) as tools/cases/crash/<id>.json with {"id","was","key","features"} and no private data, run it natively with cargo test --profile fast -p ck-model --test robust_cases, add an assertion for the intended outcome in a robust_<area>.rs test (a valid result or a specific error code, not only “does not panic”), and refresh the baseline with --update-baseline. --check exits non-zero when a case that was ok or a structured error is now a trap, hang or invalid result. The Rust side is crates/ck-model/tests/robust_*.rs: the shared runner executes a regen on a worker thread with a time limit, and robust_cases.rs replays every file in tools/cases/crash/.

The protocol itself is fuzzed by tools/lint_protocol.mjs: it sends every request type (taken from the dispatch table) with a minimal valid body, malformed envelopes and field fuzz (wrong types, huge numbers, empty arrays and objects), and requires a well-formed reply for each. In this chapter’s run: 120,635 requests over 57 types, 0 violations.

Edit robustness

tools/edit_robustness_check.mjs applies single-parameter edits and applies the same edit to the kernel and to the comparison build, a second kernel build supplied separately and not distributed with the repository (placed at ../../kernel.wasm relative to tools/, or given with --orig). It cannot be run from a bare checkout. For each edit:

  • Parts: tools/cases/*.ckpart and the 50 BenchCAD parts.
  • Edits: for a spread of features per part (default 5), the first numeric leaf (preferring depth, offset, angle, radius, distance, count, height, width, thickness) multiplied by 0.8, 1.25 and 1.5. Edits that make the input nonsense (an arc whose endpoints stop being equidistant from its centre, crossing sketch lines) are skipped.
  • A case counts when the comparison build regenerates the edited part with no feature error. The kernel fails the case when it then has a feature error, a trap, a hang, or a volume more than --vol-tol (default 1e-3 relative) from the comparison build’s. A part whose unedited volume already differs between the two builds is judged on errors only.
  • Each part runs in a worker process (--jobs, --timeout). tools/edit_robustness_known.json lists understood failures, each with its evidence; anything else fails the run.

--quick (12 small parts, 2 features, factor 1.25, about 7 s) is the gate metric edit.robust. In a run with the comparison build: 24 edits, 2 skipped because the comparison build itself errors, 22 comparable, 0 failures. These counts reproduce only with the comparison build.

The full run after the fixes, with the comparison build: 741 cases, 116 skipped, 625 comparable, 5 failures, all in the known list. Before the fixes it was 39 failures in 636. The fixed causes, each with a regression test in crates/ck-model/tests, show what edits tend to break:

  1. Shell cavities that overshoot an opened face by a whole wall: free-form walls continue past their domain with a second-order polynomial, so neighbours drift apart with the square of the overshoot. The cavity now overshoots by a quarter of the wall.
  2. A boolean on a revolved sphere whose seam-only loop is the whole parameter domain.
  3. Fillet and chamfer picks by face names that shift when ~k numbering of a shell’s inner and outer faces changes after an edit: fall back to the same face families and keep all picks on one connected rim.
  4. Zero-length closed edge remnants of a conic cut at its seam.

Open items from the same notes: a circular pattern of lofted blades fails with booleanFailed for some angles (two blades 170 degrees apart, four at 100, five and eight equal blades over 360), and one twisted-drill partial revolve cut differs by 0.23 percent with no ground truth.

Determinism

The kernel is deterministic for a given input and module: the same document gives the same bytes. Checks:

  • tools/regen_cache_check.mjs verifies that a warm regeneration (a cache hit on a document prefix) is byte-identical to a cold regeneration of the same document in a fresh instance. It covers every case part and BenchCAD part: a repeated identical request (full hit), a changed first, middle and last feature, removing the last feature, remove then re-add (undo), swapping two adjacent features, renames, a tiny cache cap (eviction must not change results), changed options, and opts.noCache. In this chapter’s run: 2,827 checks ok in 9.5 minutes. --slow adds the 140 s cold comparisons of the largest sample.
  • The sine and cosine used in geometry are ported (ck_topo::trig) so native and WebAssembly builds agree to the last bit where the platform math library would differ by one unit in the last place.
  • The fonts used for lettering are compiled in; no system data is read.
  • The STEP writer’s only host-dependent value is the time stamp in the file header, taken from the host clock.

Parallelism

The kernel itself is single-threaded in WebAssembly. State is kept in thread-locals, one set per kernel instance:

  • In a browser or worker, one module instance is one session.
  • The native service (ck-native) runs one worker thread per session, each with its own kernel state (regen cache, tags, reply buffer) and a 256 MiB stack, because regen recurses deeply. Its test checks that sessions do not share state and that a reply equals the direct call.
  • The fuzzer, sweeps and edit check use worker processes or threads, one kernel instance each.

Multithreaded booleans are an open item (a trial with native threads gave a 1.38 times speed-up), listed in known limits. The font table for lettering is a process-wide registry (a mutex-guarded static), so it is per instance in a WebAssembly module but shared by all sessions of one native service process.

See also

Known limits

This chapter lists what the kernel does not do or does not do reliably, ordered by how soon a user is likely to meet it. Each item says what happens and where the evidence is: a sweep result, an #[ignore]d test with its reason, or a run made for this book. Counts from sweeps are snapshots of a past build (see corpora and sweeps); re-run the sweep for the current state.

1. Things met in the first hour

Unknown fields are ignored. Part parsing is deliberately lenient. A misspelled field is skipped, and the feature runs with its default. Checked:

{"type":"extrude","id":"F2","op":"add","sketch":"F1","end":"blind","depht":8}

regenerates with no error and no warning, and the plate is 0.000001 mm thick (the default depth). A field with an unknown name (bogusField) is also accepted silently. The only structural errors are a part that is not an object, a wrong format, and features that is not an array; an unknown feature type is a per-feature error (unknownFeature, checked). Reporting ignored fields as errors or warnings is not implemented. Until then, compare the result with check or massProps instead of trusting an empty errors list.

A valid-looking reply can be wrong. The sweeps find wrongVolume, replies without an error whose volume differs from an independent computation. They occur in random overlapping curved primitives, outward shells and three-section lofts (details below). A volume sanity check exists for booleans (booleanVolumeMismatch) but does not catch everything. Call validate and compare massProps with what you expect.

Large blends are refused. A fillet radius that approaches half the shortest side of a box, or half the height of a cylinder, answers blendOverflow, although the geometry is valid and an independent geometry library builds it. In the fillet sweep this was 32 of 640 cases, starting at radii of about 6 mm on the sweep’s random sizes. Checked: a 9 mm fillet on the top long edge of the 8 mm-thick 40 x 20 x 8 plate answers blendOverflow (“spring leaves its face away from its edges”).

Blends at corners are limited. Variable-radius blends (var_box in the sweep: 9 of 40 ok, 28 wrongVolume, 3 blendFailed) are the weakest group. Unequal radii at a vertex where three edges meet end in a mitre, not a patch: valid, but not tangent-continuous, and flagged with a cornerNotTangent warning. A three-edge corner with radii 10, 5 and 5 (one case in the test-script corpus), face-face fillets, adjacent conic or curvature-continuous fillets (the ignored test conic_ring), and fillets of a ring at a blade root (the ignored test closed_blunt_root_ring_fillets_cleanly) answer blendFailed or blendUnsupported. Partial cylinder and cone sectors with fillets are blendUnsupported in the test-script corpus.

A fillet of a rounded-rectangle loop can stop responding. In the fillet sweep, 2 of 40 rrect_loop cases (3 with a second seed) returned no reply at all (kernel-null) for a top-loop fillet with propagate. A time budget may not stop such a request; run untrusted documents under a host-side timeout as well. See robustness.

2. Shells, offsets and thickness

CaseResult (shell sweep, 40 cases per template)
Inward shell of a box, one or two faces removedWorks; thick walls refused with shellTooThick (expected)
Outward shell with the top removedAll 40 wrongVolume (an extra roof slab remains)
Shell of a drafted cylinder (cone)38 wrongVolume, 2 draftTooLarge
Closed shell of a two-box L19 wrongVolume, 21 refused
Tube with the top removed15 shellFailed
Thicken of planar, cylindrical and conical sheetsWorks

Walls made of general B-spline surfaces are offset by fitting a grid and report a sampled radius; extruded spline walls are exact. Shell and thicken of a hull with a point-ended loft work only when the cavity can be cut off short of the apex; a plain cone loft and walls thicker than the keel radius are refused with a hint.

3. Booleans on curved shapes

Coincident, tangent, contained and sliver relations between boxes, cylinders and spheres are handled (145 of 147 cases in the coincidence corpus without any tolerance; the two failures are near-coincident cylinders 1e-3 apart, and with a tolerance of 1e-3 or autoFuzzy all 147 pass). Random overlaps of curved primitives are the weak spot. In the boolean sweep, 29 of the 175 cases that were not an expected no-effect or empty result (320 minus 80 okNoEffect and 65 okEmpty) failed (22 wrongVolume, 5 invalid, 2 booleanFailed):

  • anything with a torus (10 cases, relative error 1.7e-3 to 0.95);
  • cone against cone and cone against cylinder;
  • sphere against torus or cone;
  • chains of three bodies with a cone, torus or sphere.

In the test-script corpus, the clusters are a sphere against a box corner, perpendicular cylinders intersected, cone and cylinder near a seam, and staged blends followed by a union (86 failures among 1664 cases). Tool bodies with 100 instances (a long pattern) make a boolean take 5 to 30 s.

4. Lofts, sweeps and free-form surfaces

  • Three-section circle lofts differ from a smooth thru-sections surface: relative volume error 3e-3 to 0.15 in the shape sweep (16 of 30); in the mass-property sweep all 20 three-section lofts differ from the thru-sections reference, by up to 6.7 percent in volume, 3.7 percent in area, 1.6 percent in centre of mass and 10 percent in inertia. The mass-property reply is exact for the shape the kernel builds; the shape itself is a different surface from the reference. Two-section lofts, rotated rectangles and point-ended lofts agree.
  • No closed loft, no sweep normal control; multi-section sweeps are partial; mitre joints that involve arcs, twist and multi-region profiles on multi-piece paths are not built.
  • Surface-surface intersection on arbitrary NURBS is the weak spot of the free-form side. There are no network or constrained plate surfaces, and no mesh-to-B-rep conversion or sewing from meshes.
  • Booleans on free-form walls: spline pockets, bosses and rings work on spline walls; other tilted plane or extrusion sections still march and can be slow.
  • Thread features: pipe-thread tapers, threads on conical faces and rounded roots are not modelled.

5. Import

See the import chapters for details; the main points:

FormatMain limits
STEPNo assemblies, placements, colours or names. Shell-based surface models and open shells are not imported. In four samples of 200 published files, 185 to 188 per sample imported valid and the rest were invalid (mostly TESSELLATION_OPEN and EDGE_OFF_SURFACE). Torus-fillet shell orientation and sphere pole boundaries are open
SolidWorksGeometry of the active configuration only; the feature tree is read as a list, and sldprtHistory rebuilds it as editable features where it can (a part it cannot rebuild completely keeps the file’s exact solid for the rest); the (deltas) transmit is not applied; sheet and wire bodies refused (unsupported.body); self-intersecting tori and some B-surface domains unsupported; blends and intersection curves are fitted (reported, refused above 0.05 mm) and some then fail the strict validate edge check
SketchUpA surface body of planar faces; no curves, dimensions, scenes or text; refused above 50 000 faces unless maxFaces is raised
ACIS SATExact splines only; no periodic splines, elliptical cones or reflecting transforms; no export. The bundled sphere and torus files (one face, no edges) import with volume 0 and VOLUME_NONPOSITIVE
Other formatsNo STL, DXF, DWG, IGES or glTF import or export (listed as planned)

Feature recognition rebuilds a feature tree for simple prismatic and revolved parts: 27 of 66 prismatic sample parts were exact or close. Curved-wall holes, lofts, shells and variable blends are not recognised.

6. Output

  • Drawings (drawings): geometry only, as polylines; no dimensions, annotations or sheet layout; hidden-line handling of curved occluders is approximate, and thread symbols are not drawn.
  • STEP export writes one product with geometry only: no colours, names, layers or assemblies.
  • Display mesh: the default tolerance is max(1e-3, 4e-4 x bounding-box diagonal) mm. In the tessellation sweep 84 of 180 cases had a mesh volume more than 0.1 percent off the exact one, at worst 0.8 percent for a torus and 0.4 percent for a cylinder. Exact quantities come from massProps. A rare crack (TESSELLATION_OPEN) remains for one text case in about 1500 and for some imported parts; one imported part (eyebolt) loses its torus eye from the mesh (an ignored test).
  • Text (text and fonts) is planar and single-line; no wrapping onto curved faces, no complex scripts.

7. Features not built

Not implemented: sheet metal flanges on a curved edge, louvres, forming tools, a jog and a mitre flange (the rest of sheet metal is built: see sheet metal); mate kinds profileCenter, path, linearCoupler, cam and universalJoint; hinge angle limits; upToFace for revolve and sweep, offsetFromFace on curved faces and upToBody; thin on sweep and loft and variable wall thickness on a thin extrude; moving a hole sideways with moveFace; a true n-ary union (booleans are sequential).

Six feature types are accepted as names (they are not unknownFeature) but are not built. dome, splitLine, fillpattern, surfaceOffset and cutWithSurface always fail with TODO(rebuild): <type> needs ck-ops (checked: each as an empty feature after the plate of the STEP chapter), and spattern does the same once it has a sketch (without one it answers missingSketch). Some options of built features are refused with the same prefix: a drafted mid or throughBoth extrude, a lip on curved or several rim faces, an extend with a shape other than same, and a surface sweep of an open profile. See regeneration and patterns and transforms.

8. Speed and concurrency

  • The kernel is single-threaded. A trial with native threads gave 1.38 times; multithreaded booleans are open.
  • Free-form parts (springs, propellers, shell-like lofts) and long patterns take seconds to tens of seconds in WebAssembly. The default per-feature budget is 120 s.
  • Native runs are about two to three times faster than the module.
  • Feature recognition of gear bodies takes 2 to 10 s.

9. Ignored tests

cargo test -- --ignored lists the documented open items (the others are developer probes that need an environment variable):

TestReason in the attribute
closed_blunt_root_ring_fillets_cleanly (ck-model)The ring path runs but the ball-centre solve diverges at the blade root
marine_fuse_open_edge_spacings_build (ck-model)Three near-tangent rail spacings still leave an open edge
the_concave_corner_patch_tessellates_watertight (ck-model)The sphere patch seam is sampled finer than the cylinder’s end arc: 30 of 462 mesh edges are T-junctions (chord sag below 0.04 mm at r = 2)
conic_ring (ck-ops)Adjacent conic or curvature fillets at a corner of two spline sections answer blendFailed
eyebolt_torus_fragments_tessellate (ck-io)The torus eye of this imported part is dropped from the display mesh

10. Common refusal codes

These codes mean the request was understood and refused; the kernel state is unchanged.

CodeTypical cause
unknownFeatureA feature type the kernel does not have
blendOverflow, blendTooLargeBlend radius or distance too large for the faces
blendUnsupported, blendFailedA blend configuration not built, or whose construction failed
booleanFailed, booleanVolumeMismatchThe boolean could not assemble a result, or the result’s volume failed the sanity check
shellTooThick, shellFailed, shellUnsupportedWall thickness, construction or surface type
draftUnsupported, draftTooLargeDraft of a face type or angle that is not supported
thickenFailed, thickenReachThicken could not close the offset sheet
loft*, sweep*Section, guide or path problems (profile open, guide misses, path invalid)
cutNoEffectA cut changed nothing
featureBudgetExceeded, regenBudgetExceeded, booleanBudgetExceededA time budget ran out

The full list with parameters is in errors and feature errors and diagnostics.

See also

Crate map

The kernel is a Cargo workspace of 17 crates under crates/. This table is read from each crate’s Cargo.toml and lib.rs. Dependencies are the [dependencies] of the manifest (dev-dependencies are noted separately).

Table

CrateRoleMain modulesDepends on
ck-coreMath and utilities shared by everythinglinalg (vectors, matrices, frames), xform, quad (root finding), kdtree, fxhash, memo, budget (work budgets), tracenone
ck-geomCurves and surfaces, analytic and NURBS; representation only, no topologycurve, curve2 (sketch and parameter space), pcurve, surface, nurbs (basis, B-spline curves and surfaces, rational), fit, analysis (curvature, derivatives), convertck-core
ck-jsonZero-dependency JSON value, parser and writer; keeps key order; shortest round-trip floatsone filenone
ck-topoThe B-rep: arena-based body of lumps, shells, faces, loops, coedges, edges and vertices; builders, mass properties, region classification, editsbody, make (extrude, revolve), mass, orient, region, edit, check (structural check), facekey, trig (ported sine and cosine)ck-core, ck-geom, ck-json
ck-checkThe independent solid validator behind validate: topology, geometry and display-mesh checks with stable issue codesshell, wire, edge, solid, tessellationck-geom, ck-topo, ck-core
ck-healHealing: vertex merging, sewing, small-feature removal, orientation, tolerant edges; also damages bodies for testingvertex, sew, small, wire, orient, tolerance, damageck-geom, ck-topo, ck-check (dev: ck-model, ck-json, ck-core)
ck-tessTessellation of bodies into the display mesh (positions, normals, triangle-to-face map, silhouettes)cdt (constrained Delaunay), curvature (tolerances), face, mesh, comb, curvmap. Feature traceck-core, ck-geom, ck-topo (dev: ck-json)
ck-opsModelling operations: the geometric work behind the featuresboolean, blend (fillet, chamfer, g2), loft, sweep, helix, offset, shell, draft, pipecut, surfacing (fill, knit, trim, extend, fair, thicken), intersect (curve and surface intersections), bvh, analysis (the distance, thickness, section, probe and related requests), section, measure, interference, drawing, dfm, profile (design rules), agent (queries). Feature sanity-shadowck-core, ck-geom, ck-topo, ck-json, ck-tess, ck-check
ck-textLettering: built-in fonts, TrueType and OpenType outline reader, layout into closed loopsttf, fonts (registry), sha256; layout in libnone
ck-modelThe document model and feature program: parts, expressions, references, sketches and solver, features, regeneration driverexpr, refs, planes, sketch (solver, profiles, offset, spline, text), sketch3, features (one module per family), threads, regenck-core, ck-geom, ck-json, ck-topo, ck-ops, ck-check, ck-text (dev: ck-io, ck-tess)
ck-ioSTEP export and import, ACIS SAT importstep (write, read, parse), sat (parse, build)ck-core, ck-geom, ck-topo (dev: ck-json, ck-check, ck-tess)
ck-skpSketchUp reader, both containers; bakes to meshes or to a planar-face bodyvff (modern), legacy, legacy_ar (classic), zip, inflate, tlv, xml, model, scene, tri, body, export, errorck-geom, ck-topo (dev: ck-check, ck-tess)
ck-sldprtSolidWorks part reader, to a bodycontainer, inflate, xt (Parasolid transmit), ir, build, errorck-geom, ck-topo (dev: ck-check, ck-tess)
ck-recogFeature recognition of imported bodiesholes, prism, revolve, emit, rebuild, request, modelck-core, ck-geom, ck-json, ck-topo, ck-model, ck-ops (dev: ck-io)
ck-serverRequest envelope, dispatch table, reply framing, tag-keyed session state, hooks for the geometry layerssession, reply, query, geometry (mass, interference, import and step requests), model, agent, drawing, comb, curvature, trace, clock, viewck-json
ck-wasmThe WebAssembly module: the five-function ABI and the engine that wires every request to the geometry cratesengine, regen_cache, view_cache, drag, profile_q, refdiff, sketch_q, host. Features skp, sanity-shadow. Crate types cdylib and rlibck-json, ck-server, ck-model, ck-core, ck-geom, ck-topo, ck-check, ck-heal, ck-ops, ck-io, ck-sldprt, ck-tess, ck-recog, ck-text; optional ck-skp
ck-nativeA local HTTP service around the same dispatch, one worker thread per session; a library and the ck-native binarystore (token and pairing records), mainck-server, ck-wasm, ck-ops, ck-core, ck-json, ck-text

Layers

From the bottom up:

  1. Foundations: ck-core, ck-json, ck-text.
  2. Geometry and topology: ck-geom, then ck-topo.
  3. Analysis and meshing: ck-check (validation), ck-tess (display mesh), ck-heal.
  4. Operations: ck-ops.
  5. Document model: ck-model (features, regeneration), ck-recog.
  6. Interchange: ck-io, ck-skp, ck-sldprt. They build bodies and depend only on geometry and topology.
  7. Protocol and hosts: ck-server (dispatch; it depends only on ck-json and receives geometry behaviour through hooks), ck-wasm (installs the hooks and exports the ABI), ck-native (HTTP).

ck-wasm is the only crate that sees every other one; it is where a request type such as importStep or step is tied to ck-io and ck-heal. A native test calls ck_wasm::engine::install() and then ck_server::handle, which is the path the module exports use. See architecture.

Build profiles

Defined in the workspace Cargo.toml:

ProfileSettingsUse
releaseoptimisation 3, link-time optimisation, panic = "abort", one code-generation unitThe shipped WebAssembly module
servicerelease with panic = "unwind"ck-native, which must survive a panic in one session
fastrelease without link-time optimisation, 16 code-generation units, incremental, panic = "unwind"Quick native test runs

See also

Glossary

Terms used across this book, in alphabetical order. Where a term has a field or code in the kernel, it is given in code font.

ABI The binary interface of the WebAssembly module: five exports (ck_alloc, ck_request, ck_reply, ck_commit, ck_commit_len) and three imports (ck_now, ck_unix_ms, ck_panic). One request in, one reply out.

Arena How ck-topo stores a body: one vector per entity kind, with typed ids and an alive flag. Entities are never removed from the vector; an edit marks them dead. Export order is creation order.

Assembly A part that places other parts (insertPart instances) and relates them with mates. See parts and assemblies.

B-spline A piecewise polynomial curve or surface defined by control points, a degree and a knot vector. With weights it is rational (NURBS). The kernel uses them for free-form geometry and as the exact form of text outlines.

Blend A fillet or chamfer: a surface that replaces a sharp edge. Blend faces are named B<k> (and V<k> for a corner patch).

Body The B-rep result of regeneration: the topology (lumps, shells, faces, loops, coedges, edges, vertices) and the geometry attached to it. A part builds one body, which may hold several lumps.

Boolean Union (add), cut or intersect of two bodies. The implementation imprints the operands onto each other, classifies the pieces as inside, outside or on the other body, and reassembles the kept pieces.

Budget A wall-clock limit on work (featureTimeMs, regenTimeMs). Active only where the host provides a clock. See robustness.

Cache (regen cache) Stored intermediate states of a regeneration, keyed by a hash chain over the document prefix, so that an edit near the end of the feature list re-runs only the features after it. See regeneration and caching.

CDT Constrained Delaunay triangulation. The tessellator triangulates each face in its parameter space with the trimming loops as constraints, using exact predicates.

Chamfer A blend that replaces an edge by a flat or conical bevel.

Classification Deciding whether a point or face piece is inside, outside or on a solid. Uses a nearest-feature pseudo-normal test close to the boundary and a winding number farther out.

Coedge One use of an edge by a loop. An edge shared by two faces has two coedges. rev says whether the coedge runs against the edge’s direction. A seam edge has both coedges on the same face.

Constraint A relation in a sketch (coincident, horizontal, distance, radius, tangent, …) that the sketch solver satisfies by moving points. See the sketch solver.

Degrees of freedom (DOF) The number of independent motions left in a sketch or an assembly after constraints and mates.

Edge A bounded piece of a curve, between two vertices, with a parameter range [t0, t1] on its curve and an optional tolerance. It is used by the coedges of two faces in a closed manifold body.

Expression A string such as "d/2" or "=2*w" in a field that takes a number. Evaluated against the part’s variables. See variables and expressions.

Face A bounded region of a surface. It has a surface, a sense (whether its outward normal agrees with the surface’s natural normal) and one or more loops. The first loop is the outer boundary. Faces have persistent names such as F2.S.e1.

Feature One entry of a part’s features list: a sketch, an extrude, a fillet, a hole, a pattern, a plane, and so on. Features run in order; each has an id such as F4.

Fuzzy tolerance The tolerance and autoFuzzy options of a boolean-producing feature, which snap nearly coincident faces onto each other before intersecting.

Healing Repairing a body so it validates: merging near vertices, sewing gaps, removing degenerate edges and sliver faces, fixing orientation, and giving small deviations an edge tolerance. See healing.

Imprint The step of a boolean that cuts each operand’s faces along its intersection curves with the other.

Knot vector The non-decreasing parameter values that define a B-spline’s basis. Multiplicities control continuity.

Loop A closed chain of coedges bounding part of a face. On a face the outer loop runs counter-clockwise about the outward normal and holes run clockwise.

Lump A connected solid piece of a body, with one outer shell and zero or more void shells. A body with two separate blocks has two lumps.

Mass properties Volume, area, centre of mass and the inertia tensor (reported as principal moments and axes), computed by exact integration over faces (massProps).

Mate A relation between two parts of an assembly (coincident, angle, hinge, gear, …) that fixes some of their relative degrees of freedom.

Mesh The display triangulation of a body: positions, normals and a triangle-to-face index, sent as binary buffers in the reply. Distinct from the exact B-rep.

NURBS Non-uniform rational B-spline: a B-spline with weights, able to represent conics exactly.

Part A document (.ckpart) with a format, a version and a list of features. Regenerating it yields a body.

Pcurve A curve in the (u, v) parameter space of a surface, giving an edge’s path on a face. Faces on periodic surfaces rely on pcurves for mass properties and meshing.

Persistent name A face or edge identifier that survives edits because it is derived from the feature that made it, for example F2.C0 (cap), F2.S.e1 (side of sketch entity e1), F3.B0 (blend). Later features refer to geometry through these names. See persistent names.

Pole The point where a sphere, cone or revolve closes on its axis. A face at a pole has no rail edge there.

Profile The closed loops of a sketch used by a feature, grouped into regions (an outer loop with its holes).

Regen Regeneration: running a part’s features in order to build the body. The regen request. Also the name of the stage in a reply.

Region A face of a sketch’s planar arrangement: an outer boundary with its holes. Extrudes act on regions.

Rollback part.rollback = n regenerates only the first n features, as the rollback bar of a feature tree does. opts.upTo does the same for one request; the smaller wins.

Seam The edge where a periodic surface (cylinder, cone, sphere, torus) joins itself. The kernel keeps seams internally and omits them from exported edge lists and STEP files.

Sense A boolean orientation flag: of a face against its surface, of a coedge against its edge, of a loop about the outward normal.

Sheet (surface body) A body of faces that is not a closed solid, produced by surface features or by importing a surface model.

Shell A connected set of faces. A closed shell bounds a volume. A lump has an outer shell and void shells for cavities.

Sketch A set of points, entities (lines, arcs, circles, splines, text) and constraints on a plane. The source of profiles.

SSI Surface-surface intersection: computing the curves where two surfaces meet, by marching, with analytic cases handled exactly. The weak spot is general NURBS.

Surface The geometry of a face. Ten kinds: plane, cylinder, cone, sphere, torus, extrusion, revolution, offset, B-spline and screw (the screw surface of twisted extrudes and helical sweeps reports as spline on the wire). See geometry.

Tag The name of a state held by the kernel instance. regen, imports and queries take a tag (default "main"); a query on a tag that has no state answers noState.

Tessellation Turning exact faces into triangles, to a chord-height and angle tolerance. The default chord tolerance is max(1e-3, 4e-4 x bounding-box diagonal) mm.

Tolerance A distance below which two things are treated as equal. The model tolerance is used by validation and healing; an edge or vertex can carry its own tolerance (set by healing) for geometry that is only approximately consistent, such as imported files. A tolerance above the cap (0.05 mm by default) is an error.

Transmit The Parasolid data stream stored inside a SolidWorks file.

Valid (validation) A body is valid when validate reports no issue: closed manifold shells, consistent orientation, edges on their faces, loops closed, positive volume. See validation.

Variable A named value in a part that expressions can use.

Vertex A point where edges meet, with an optional tolerance.

Void A cavity inside a lump: an inner shell whose faces point into the cavity. Written as BREP_WITH_VOIDS in STEP.

Welding Merging points that are closer than a tolerance into one vertex, so that neighbouring faces share edges. Used when importing meshes and surface models (1e-4 mm for SketchUp) and by healing.

Wire (protocol) The JSON request and reply format and its binary buffers, as opposed to the B-rep. “Wire” ids are the face ids and edge keys that appear in replies.

See also