C++ API#

A C++ backend includes one header, <paperboat/sdk.hpp>, which brings everything below into namespace paperboat (paperboat::Block, paperboat::define_block, paperboat::main…). Headers it doesn’t include may change. Link paperboat::core.

The SDK#

A backend builds against the engine in one of two ways:

  • From a checkout: add_subdirectory(<paperboat>/engine paperboat EXCLUDE_FROM_ALL).

  • From an installed package: find_package(Paperboat 0.1 CONFIG REQUIRED). The SDK is the lib/, include/ and lib/cmake/Paperboat parts of the .tar.gz and the .zip. Its libraries are Release builds (shared on Linux and macOS, static on Windows), so nothing is rebuilt and nothing is downloaded at configure time. Toolkits installed with paperboat toolkit install come with it as paperboat::toolkit_<name>.

Either way the targets are paperboat::core (links paperboat::toolkit) and paperboat::warnings (the engine’s warning flags). The version check is SameMinorVersion: a backend that asks for 0.1 needs a 0.1.x SDK. On Windows the SDK uses the static runtime (/MT); its config sets CMAKE_MSVC_RUNTIME_LIBRARY to match unless you set it.

Optional toolkits (control, opencv, optimization) stay source-only: paperboat toolkit install <name> --repo <url> (or --path <dir>) compiles one into the engine, so it needs a checkout. The SDK holds the built-in packages only. The manifest’s repo is a suggested source, not an automatic download.

API Quick Reference#

Category

Symbol

Description

Definitions

PortDef

Input/output port configuration (id, type, vector units).

VectorComponent

Named component channel within an ordered vector port.

ParamDef

Parameter or property definition (number, key, enum, file).

BlockDef

Complete declarative block definition (type, ports, params, kind).

ObjectDef

Station object template definition, properties, and link slots.

Values & Context

Values

Map of string keys to typed values (numbers, vectors, tables, handles).

get_or()

Safe parameter or signal extraction helper with fallback default.

Context

Execution context providing clock time t, step dt, and log().

Block Subclasses

Block

Base computational block owning state and implementing step().

Generator

Signal generator computing \(f(t)\) from time and parameters.

Step

Procedural step block implementing enter() and tick().

Timed

Timed step block executing for a fixed duration.

Expression

Fast mathematical expression evaluator over named variables.

Station & Geometry

StationObject

Equipment object providing read(), step(), and entities().

Entity

Geometry entity rendered in 3D/2D on the Station page.

scene::box(), scene::sphere(), scene::line(), scene::image(), scene::rect(), scene::circle(), scene::rod(), scene::spring()

3D and 2D visual geometry entity construction helpers.

Solvers & Physics

Model

Continuous ODE physics model with state derivatives.

solve::Solver

Abstract numerical differential equation solver interface.

solve::step()

Advance state vector across one time step using an ODE solver (e.g. RK4).

Domain & Server

DomainState

Domain-wide shared state updated after topological passes.

Registry

Repository of block and station object definitions.

define_block()

Factory helper binding C++ Block classes to catalog definitions.

define_object()

Factory helper binding C++ StationObject classes.

load_descriptor_file()

Reads and validates descriptor.toml against the registry.

main()

Standard CLI entrypoint launching backend server processes.

serve()

High-performance WebSocket and HTTP server loop.

Schedulers

Executor

Abstract graph execution engine runner.

Run

Active run execution lifecycle and telemetry emitter.

Definitions#

What the UI shows and descriptors refer to. All fields have defaults, so designated initializers may leave any out.

struct PortDef#

A block’s input or output.

std::string id#
std::string type = "signal"#

"signal" (a value), "step" (control, in a Step flow) or a shape: "image", "points", "vector"… A wire joins ports of one type. Lists (#24): "numbers" is a list of numbers (any length; it joins "vector" ports, a vector being a list of fixed length) and "points" a list of points (a Table, one row per point). Make them with numbers_port() and points_port(); see the list package. A matrix is a rectangular Table (rows of columns) on an ordinary "signal" port with the matrix flag set; make one with matrix_port().

std::string unit#

A shared unit, or the fallback unit for vector components without their own.

std::optional<std::size_t> dimension#

A vector’s fixed length. Absent: dynamic length; component metadata also fixes it. On a "points" port, the coordinates of each point (the list’s own length is never declared).

std::vector<VectorComponent> components#

Optional ordered component labels and units. Names are descriptive; dimensions and units, not labels, decide whether two vector ports fit.

bool broadcast = false#

Set on the signal ports of an elementwise block (see with_broadcast()): the port also joins a vector port. The engine sets it; a block author never does.

struct VectorComponent#
std::string id#

The component’s label, in vector order.

std::string unit#

Its optional unit.

PortDef vector_port(std::string id)#
PortDef vector_port(std::string id, std::size_t dimension)#
PortDef vector_port(std::string id, std::vector<VectorComponent> components)#

Make a "vector" port. For example, vector_port("state", {{"x", "m"}, {"angle", "rad"}}) puts a mixed-unit state on one wire while retaining the names and units of its components.

PortDef numbers_port(std::string id, std::string unit = {})#
PortDef points_port(std::string id, std::vector<VectorComponent> coordinates = {})#
PortDef matrix_port(std::string id)#

Make a list port (#24): "numbers", a list of numbers in one unit, or "points", a list of points; points_port("profile", {{"x", "m"}, {"z", "m"}}) fixes each point’s coordinates and their units. A block gives a list of numbers as a Vector and a list of points as a Table. matrix_port("a") carries a rectangular Table; the math package’s matrix blocks check its shape.

struct ParamDef#

A setting on a block (or a property of a station object), edited in the UI.

std::string id#
double default_value = 0.0#
std::string type = "number"#

Number types (to the block as Values): "number", "boolean" (a checkbox; 1 or 0). Text types (through Config): "text", "matrix" (MATLAB-style matrix rows, "1 2; 3 4"), "key" (a KeyboardEvent.code, picked by pressing it), "file" (a path, relative to the descriptor’s folder), "enum" (one of options, a dropdown; the block also gets its index in Values), "variable" (the name of a project variable, a picker; for Context::set_variable()).

std::vector<std::string> options#

An enum’s choices.

std::string default_text#

The default of a text param.

bool is_number() const#
enum class Kind#
enumerator Source#

Pushes into the domain.

enumerator Probe#

Reads it.

enumerator Function#

Computes.

enumerator Monitor#

Shows a value on the Dashboard as an instrument.

struct BlockDef#
std::string type#

Unique within a catalog ("pid", "pid-theta").

std::vector<std::string> flows#

The flow types it works in (signal, step, state, model): the palette offers it on those sheets only, and a run refuses it on another (#9). Empty: every type.

std::string label#
Kind kind = Kind::Function#
std::vector<PortDef> inputs#
std::vector<PortDef> outputs#
std::vector<ParamDef> params#
std::string instrument#

A monitor’s instrument: "graph", "display" or "image".

std::string description#

One line in plain words: what the block does. Shown on its card in the block browser. Optional; the built-in templates have one, and a descriptor may set description.

View view#

How the UI draws the block: a hint, so a block without it is the normal card. compact draws a small plate with a glyph (a few characters drawn as text; a curve is an icon) and a caption with the name and value (an expression of the params, "{k}"); icon (an opaque nlohmann::json object, null when absent) supplies a token-quantised vector icon ({w, h, g, ports}) rendered on the plate without raw colours or SVG path strings. Every key is optional: a definition inherits its parent’s view and overrides single keys (View::overridden_by()). The built-in simple maths and logic templates have one; a descriptor may set view.

bool feedthrough = true#

false for a block whose outputs this step don’t depend on its inputs this step (an integrator, a delay). Its Block gives outputs() during the pass and takes its inputs in step() after it, so a feedback loop may pass through it. A loop with no such block is an algebraic loop: the run solves it each pass (see Block::outputs_for()), or fails naming a block in it.

std::vector<Form> forms#

A magic block’s forms. Its inputs and outputs are the first form’s; its enum param form picks one (see magic_def()).

std::string ports_from#

The id of a text param that decides the inputs: one per sign character in it ("+-+": a, b, c; see parse_signs()), of the first input’s type. Empty: the inputs are the definition’s. Sum’s signs. A wire to an input that no longer exists is dropped.

std::string inputs_from#

The id of a text param whose expression’s free names are the inputs: one per identifier in it (other than pi, e and built-in functions, in order of first appearance; see with_inputs()), of the first input’s type. Empty: the inputs are the definition’s. f(t)’s f. A wire to an input that is removed or renamed is dropped.

std::string outputs_from#

The id of a text param of names ("x v theta", see parse_names()) that are the outputs, ids in that order. The first vector input gets one component per name, and a units param ("m m/s rad") gives each a unit by position. Demux’s names. ports_from = "names" does the same for the inputs (Mux), giving the first vector output the components.

bool elementwise = false#

The block works on one number at a time and the engine lifts it to vectors (#164). Its signal ports also take a vector wire. With only numbers in, nothing changes. With any vector in, all vectors must be one length N (else the run fails naming the block and port), numbers broadcast to every element, and the block runs as N instances, lanes, each fed its element and keeping its own state (one integral per element); its outputs are vectors of N, labelled like the vector that came in. A param change reaches every lane. N is found from the wires when the graph is compiled, so a block without feedthrough in a loop knows it before its first step; if the length is known only at run time (a vector port with no dimension) such a block fails at compile, and any other takes N from its first step. The built-in pointwise math blocks, f(t) and the generators, Integrator, Lag and PID are elementwise; Delay is not (it moves whole values). A block that needs the whole vector (a norm, a dot product) declares vector_port() ports instead.

std::optional<bool> cacheable#

Whether a run that evaluates once may reuse this block’s outputs from an earlier run (see RunCache) instead of calling it, when nothing it depends on changed: its type, params, text, the values on its wires and the variables it read through Context::variable(). true: it is a pure function of those (no clock, keys, domain state, randomness, files other than its file params, or side effects): the text, conversion, logic, If and Variable blocks. false: it is always called (Random Number, Key, Now). Unset: as its instance says, Block::stateless() (Constant, Gain, Sum, Mux… are reused). Runs on a clock and Step flows never reuse outputs.

struct Form#

One form of a magic block: the ports it has in that form, such as "signal" (values in and out) or "step" (a step on a Step flow’s path).

std::string name#
std::vector<PortDef> inputs#
std::vector<PortDef> outputs#
std::vector<int> parse_signs(std::string_view text)#

The signs in text, one per input: + is 1, - (or −) is -1; anything else is skipped. At most 26; none at all reads as "++".

std::vector<std::string> parse_names(std::string_view text, const std::vector<std::string> &reserved = {})#

The names in text, split on spaces and commas: what a names param makes ports of. Throws std::invalid_argument on none, a name used twice, one that isn’t an identifier, one in reserved (the block’s other ports) or more than 64; in a run the block fails.

BlockDef with_broadcast(const BlockDef &def)#

def with broadcast set on its signal ports if it is elementwise (what the catalog sends), else def.

BlockDef with_signs(const BlockDef &def, std::string_view text)#

The definition with the inputs its ports_from param (text) gives: ids a, b, c… of the first input’s type. def itself if it has no ports_from.

BlockDef with_inputs(const BlockDef &def, std::string_view text)#

The definition with the inputs its inputs_from expression param (text) gives: one per free name in text, in order of first appearance, of the first input’s type. def itself if it has no inputs_from. A wire to a removed or renamed input is dropped.

BlockDef in_form(const BlockDef &def, std::string_view form)#

The definition in form form: that form’s ports. def itself if it has no forms, or no form of that name.

struct ObjectDef#

A station object type.

std::string type#
std::string label#
std::string role = "body"#

"body" or "joint".

std::vector<ParamDef> props#

Its properties, edited on the Station page only.

std::vector<std::string> links#

Slots naming other station objects ({"a", "b"}).

std::optional<BlockDef> block#

The linked block it spawns on the Flow page (same id as the object), if any.

Values#

struct Value : std::variant<double, Vector, Table, std::string, Handle>#

What a wire carries: a number, a vector of numbers, a table (rows, such as points as [x, z]), text, or a handle. Any arithmetic type converts to double.

using Vector = std::vector<double>#

Ordered numeric data. The port’s type ("vector"), optional dimension and component metadata describe its wire contract.

using List = Vector#

Compatibility name for Vector.

using Table = std::vector<std::vector<double>>#
using Values = std::map<std::string, Value>#

Port or param id → value (with a transparent comparator).

using Config = std::map<std::string, std::string>#

Text settings: a template’s config, and every text param by id.

struct Handle#

Data the engine passes along without knowing what it is (an image, a mesh). Shared and immutable, so one output can feed many inputs.

std::string kind#

Agreed between packages; matches the ports’ type ("image").

std::shared_ptr<const void> data#
template<class T>
Handle make_handle(std::string kind, T value)#
double get_or(const Values &values, std::string_view id, double fallback = 0.0)#

The number at id, or fallback when absent or not a number (an unconnected input reads as 0).

template<class T>
const T *get_if(const Values &values, std::string_view id)#

The vector/list, table or text at id, or null.

const Vector *get_vector(const Values &values, std::string_view id)#

The numeric vector at id, or null. A Python block reads the same value as a list.

Vector as_vector(const Values &values, std::string_view id)#

The numbers at id as a vector: a vector as it is, a number as one element, otherwise (absent, text…) empty. For a block with a vector_port() input that should also take a plain number.

template<class T>
const T *get_handle(const Values &values, std::string_view id, std::string_view kind)#

The object behind a handle of kind at id, or null.

std::string get_text(const Values &values, std::string_view id, std::string fallback = {})#

What runs#

struct Context#

What a block sees on each call.

double t = 0.0#

The run clock, s (0 in a run that evaluates once).

double dt = 0.0#

The clock step, s.

const KeySet *keys_down = nullptr#

Keys held down in the UI (KeyboardEvent.code values).

DomainState *state = nullptr#

The domain’s shared state for this run, if it has one.

std::string_view node#

The id of the block (or station object) being called.

const Values *variables = nullptr#

The run’s variables by name: a number, a boolean as 1 or 0, text for the rest. A variable marked tunable may change between steps (#75); any other is constant for the run.

const Value *variable(std::string_view name) const#

A variable’s value now, or null if there is none of that name. The run records the read (variable_read_fn), so a run-once’s cache knows which variables a block’s result depends on.

bool set_variable(std::string_view name, const Value &value) const#

Set the tunable variable name (#166), as an autotuner or a calibration does: a number for a number or boolean variable, text for an enum, text or file one. It takes effect at the end of the pass, so every block in a pass sees the same variables; formulas over it and params bound to it follow (a block that takes no live change is told once in the Console), and the UI keeps the value in the project. Returns false, with a warning in the Console, if the variable is unknown, not tunable, a formula, of another type, or the value is outside its min / max.

void log(std::string_view text, std::string_view level = "info") const#

Write a line to the Console (info, warn, error), tagged with node.

void progress(double fraction) const#

How far a long step has got, 0 to 1 (a filter over a big image, a solve): the UI shows it on the block. Optional; call it as often as is useful, the run sends at most ~20 a second.

void metric(std::string_view series, double y, std::string_view unit = {}) const#
void metric(std::string_view series, double x, double y, std::string_view unit = {}) const#

A point of a series that isn’t on the run clock (#17): a solver’s residual against its iteration, a sweep’s cost against its case. The run sends a metric event. Without x the point is the series’ next index (0, 1, 2…); unit is y’s. A NaN or infinite point is dropped.

void monitor_state(MonitorState now, double value, std::string_view port = {}) const#

What a monitor says about its input now (MonitorState::Ok, Warn or Trip; a Lamp) and the value that put it there. Call it every step: the run sends monitor.state only when it changes (per port, for a monitor of several inputs), and every monitor starts a run at Ok.

void frame(const Frame &picture) const#

A live picture (#17): Frame holds an optional view ([xmin, ymin, xmax, ymax], y up), shapes (FrameShape: t line, poly, circle or text; points p; r; s; token stroke and fill) and an optional field (FrameField: w × h values v row by row from the top, NaN for no value, min / max). The run sends at most ~20 a second per block and always the latest at the end of a block in a run-once and of the run; one it can’t send (an unknown token, a point that isn’t finite, more than 65536 cells or 2000 shapes) warns once in the Console and is dropped.

tk::Frame f{.view = std::array<double, 4>{-1.2, -1.2, 1.2, 1.2}};
f.shapes.push_back({.t = "line", .p = {{0, 0}, {std::sin(a), -std::cos(a)}}});
f.shapes.push_back({.t = "circle", .p = {{std::sin(a), -std::cos(a)}}, .r = 0.08, .fill = "signal"});
ctx.frame(f);
class Block#

One instance of a block in a running graph. It owns its state; two instances never share anything.

virtual Values step(const Context &ctx, const Values &in) = 0#

Outputs from inputs. An unconnected input is absent from in. Throw to fail the run; the error names this block. For a block without feedthrough it is called after the pass, to take the step’s inputs; others read outputs().

virtual Values outputs() const#

A block without feedthrough (BlockDef::feedthrough false): what it outputs now, from its state alone. Unused for other blocks.

virtual std::vector<Entity> entities() const#

What it draws on the Station after a step (a result to show). Default: nothing.

virtual bool set_param(std::string_view id, double value)#

The number param id changed during the run (#75): a tunable variable it is bound to has a new value. Take it and return true. The default returns false: the block reads its params only when made. Keep your state: a PID takes new gains and carries on with its integral.

virtual bool stateless() const#

True for a block whose outputs depend on its inputs and the clock alone. When set_param returns false the run then makes it again with the new params. A block that is neither takes the change with the next run (the Console says so, once). Unless its BlockDef::cacheable says otherwise, a run-once may reuse a stateless block’s outputs from an earlier run. In an algebraic loop the run calls a stateless block’s step many times per pass to solve it.

virtual bool feedthrough() const#

false for an instance whose outputs this step don’t depend on its inputs this step though its BlockDef::feedthrough is true (a strictly proper transfer function). The run then reads outputs() during the pass and calls step after it, so a feedback loop through it is not an algebraic loop. Asked once, when the graph is made.

virtual std::optional<Values> outputs_for(const Context &ctx, const Values &in) const#

What step would return for in now, without changing the block’s state (Simulink’s output function, apart from its update). A block with state and feedthrough implements it to sit in an algebraic loop: the run calls it while it solves the loop, then step once with the solution. The default returns none, and such a block in an algebraic loop fails the run.

class Step#

One instance of a block on a Step flow’s path (a block with step ports).

virtual void enter(const Context &ctx, const Values &in)#

A path arrived.

virtual std::string tick(const Context &ctx, const Values &in) = 0#

Each clock step while the path is here: the step output to leave by, or "" to stay (a wait, a move). A hat (step outputs, no step input) is ticked while idle and starts a path when it names an output.

virtual bool may_start() const#

For a hat: whether it may still start a path.

virtual bool ends_run() const#

True for a block that ends the whole run when a path arrives (Stop).

virtual Values outputs() const#

Its signal outputs (a progress), read after each clock step; signal blocks see them in the next pass, so a wire from a step’s output back into it is not a cycle.

class StationObject#

One station object in a run: owns its state and properties.

virtual Values read() const = 0#

The linked block’s outputs, from the current state.

virtual void step(const Context &ctx, const Values &in) = 0#

Advance one clock step under the linked block’s inputs.

virtual std::vector<Entity> entities(const std::string &id, double z) const = 0#

Its shapes, ids prefixed with id + "/", at depth z.

virtual void link(std::string_view slot, StationObject &other)#

Another object fills one of its link slots; called once, after every object of the station is made.

class DomainState#

What a domain’s blocks share during a run (a game, a document, a physical system). The engine makes one per run (Backend::state), hands it to blocks in Context::state, steps it after each clocked pass and draws it.

virtual std::vector<Entity> entities() const#

Every entity it draws (for scene).

virtual std::vector<Entity> patch() const#

The entities that change (for scene.patch). Default: all.

virtual std::optional<std::string> step(const Context &ctx)#

Advance after a clocked pass. A message ends the run.

virtual std::optional<std::string> summary() const#

Logged when a run ends.

struct Entity#

One shape on the scene.

std::string id#
std::string shape = "box"#

"box", "sphere" (size[0] = radius), "cylinder" (size[0] = radius, size[1] = length along y), "line" (pos → to) or "image".

std::array<double, 3> pos#
std::array<double, 3> size#
std::array<double, 3> rot#

Radians, applied in x, y, z order.

std::string color = "#888888"#
std::array<double, 3> scale#
std::array<double, 3> to#

A line’s end.

std::string src#

An image’s picture: a URL or a data: URL.

Kinds of block#

Base classes in <paperboat/toolkit/bases.hpp>: derive and implement only what is particular. Python has the same (paperboat.Generator, paperboat.Timed).

class Generator : public Block#

A signal f(t). t is the input t when wired (a step’s progress), else the run clock; it outputs value(t).

explicit Generator(std::string output = "y")#
virtual double value(double t) const = 0#
BlockDef generator_def(std::string type, std::string label, std::vector<ParamDef> params = {}, std::string output = "y")#
class Timed : public Step#

A step that does its work over seconds. Each clock step the work moves to the curve input’s value (clamped to 0–1; the first frame stays at 0) or, unwired, to the share of seconds gone; the last frame goes to 1 and leaves by next. A steady 0.5 jumps to half at once, holds, and ends at 1. Outputs progress (the share of time gone), to feed a curve.

explicit Timed(double seconds)#
virtual void begin(const Context &ctx, const Values &in)#

A path arrived.

virtual void advance(const Context &ctx, double from, double to) = 0#

Move the work from progress from to to.

BlockDef timed_def(std::string type, std::string label, std::vector<ParamDef> params = {}, Kind kind = Kind::Function)#

Ports in, curve → next, progress; adds seconds (1) if params lacks it.

BlockDef magic_def(std::string type, std::string label, std::vector<Form> forms, std::vector<ParamDef> params = {})#

A magic block: one block type that changes its ports with its form param, an enum of the forms’ names (the first is the default) added in front of params. Its template sets both make (for a form of signal ports) and make_step (for a form with step ports); the engine makes the one the node’s form needs. The base logic blocks are built this way:

Template t;
t.name = "base/if";
t.def = magic_def("if", "If", {
    {.name = "signal", .inputs = {{"cond"}, {"a"}, {"b"}}, .outputs = {{"y"}}},
    {.name = "step", .inputs = {{"in", "step"}, {"cond"}},
     .outputs = {{"yes", "step"}, {"no", "step"}}},
});
t.make = [](const Values&, const Config&) { return std::make_unique<Choose>(); };
t.make_step = [](const Values& p, const Config&) { return std::make_unique<Branch>(p); };
registry.add(std::move(t));
class Expression#

An expression over named numbers, compiled once (<paperboat/toolkit/expression.hpp>).

Expression(std::string_view text, std::vector<std::string> variables)#

Throws ExpressionError saying where (at 5: unknown function "sinn").

double operator()(std::span<const double> values) const#

Values in variables order.

Domain tools#

What domain code writes with, so it gives its equations and its look, never the stepping or the entity fields (paperboat/toolkit/solve.hpp, model.hpp, scene.hpp, all through sdk.hpp).

Solvers#

using solve::State = std::vector<double>#

A state of any size, known at run time.

using solve::Deriv = std::function<State(double t, const State &x)>#

dx/dt at (t, x); for discrete, the next state.

struct solve::Options#

The error control of rk45, cvode and ida: rtol (1e-6), atol (1e-9) per component, min_step (0: automatic; it gives up below it), max_step (0: the clock step) and max_steps (100000) sub-steps in one clock step before it gives up. The fixed-step solvers (rk4, rk2, euler) take sub_steps (1) steps of dt / sub_steps per clock step.

struct solve::Defaults#

The run’s solver: name ("rk4") and options, from graph.run’s settings (the Run menu’s solver and Solver settings) over the backend’s (backend.toml [run]). A run sets them on its own thread before it makes its blocks and objects.

void solve::set_defaults(Defaults defaults)#
const solve::Defaults &solve::defaults()#
class solve::Solver#
virtual void step(State &x, double t, double dt, const Deriv &f) = 0#

Advance x from t to t + dt. Throws std::runtime_error when f returns a state of another size, or rk45, cvode or ida can’t meet its tolerances in max_steps sub-steps (an exception f throws comes through as it was).

void restart()#

Forget what it carries between clock steps (rk45’s step size, cvode’s and ida’s history): call it after the equations change (a parameter tuned, a switch). cvode and ida also start afresh on their own when a step doesn’t begin where the last one ended, from the state it left (a bounce, a reset, a new run).

template<std::size_t N>
void step(std::array<double, N> &x, double t, double dt, const std::function<std::array<double, N>(double, const std::array<double, N>&)> &f)#

Advance a fixed-size state vector without heap allocations.

std::unique_ptr<solve::Solver> solve::make(std::string_view name = "auto")#
std::unique_ptr<solve::Solver> solve::make(std::string_view name, Options options)#

A solver by name, with the run’s options unless given. auto (or "") is the run’s solver (solve::Defaults); rk4 (classic Runge–Kutta, the default), rk45 (Dormand–Prince, MATLAB’s ode45: adaptive, it sub-steps inside the clock step to meet its tolerance, so signals still arrive on the clock), rk2 (Heun), euler, discrete (a difference equation x[k+1] = f(t, x[k])), and the implicit cvode and ida for stiff systems. Throws std::invalid_argument naming them, or for an option out of range.

cvode is SUNDIALS CVODE (variable-order BDF, Newton iterations on a dense Jacobian it estimates by difference quotients); ida is SUNDIALS IDA, the same family of methods on the residual x' - f(t, x) = 0 (the form a DAE solver takes; x'(t0) = f(t0, x0) makes it consistent from the start). Both choose their own step and order inside the clock step, stop exactly at its end (a stop time: the inputs change there), and keep their history for the next one, so keep one solver between steps (a Model does) rather than solve::step()’s fresh one each time. They take rtol, atol, min_step, max_step and max_steps (internal steps per clock step). They are there when the engine is built with SUNDIALS (CMake option PAPERBOAT_WITH_SUNDIALS, on by default); solve::names() lists them then.

void solve::step(std::string_view solver, State &x, double t, double dt, const Deriv &f, Options options)#

One step with a fresh solver of that name.

Without options: the run’s.

template<std::size_t N>
void solve::step(std::string_view solver, std::array<double, N> &x, double t, double dt, const std::function<std::array<double, N>(double, const std::array<double, N>&)> &f, Options options)#

Fixed-size state overload for stepping with a fresh solver of that name.

const std::vector<std::string> &solve::names()#

The solvers, the default first: rk4, rk45, rk2, euler, discrete, then cvode and ida when the engine has SUNDIALS.

ParamDef solve::param(std::string fallback = "auto")#

An enum param or prop solver: auto (the run’s, set in the Run menu) or one of solve::names(), so the user may pick one for this block or object only.

paperboat::solve::State x = {1.0, 0.0};
auto rk45 = paperboat::solve::make("rk45", {.rtol = 1e-8});
rk45->step(x, ctx.t, ctx.dt, [&](double, const paperboat::solve::State& s) {
  return paperboat::solve::State{s[1], -k / m * s[0]};
});

Model#

class Model : public StationObject#

A station object that is a system of differential equations. It gives its initial state and derivatives(); the solver advances it each clock step, with the linked block’s inputs held through the step. It still implements read() and entities().

explicit Model(solve::State initial, std::string_view solver = "auto")#
Model(solve::State initial, std::string_view solver, solve::Options options)#

auto: the run’s solver and options.

void set_solver(std::string_view solver)#
void set_solver(std::string_view solver, solve::Options options)#

Configure or switch the numerical solver for the model.

void restart()#

Start the solver afresh (solve::Solver::restart()): call it after the equations change (a parameter tuned, a switch).

virtual solve::State derivatives(double t, const solve::State &x, const Values &in) const = 0#
const solve::State &x() const#

The state now.

protected solve::State &state()#

For a model that changes its own state between steps (a bounce, a reset).

struct Mass final : paperboat::Model {
  explicit Mass(const paperboat::Values& p)
      : Model({paperboat::get_or(p, "x0"), 0.0}, paperboat::get_text(p, "solver", "auto")),
        k(paperboat::get_or(p, "k")) {}
  paperboat::solve::State derivatives(double, const paperboat::solve::State& x,
                                      const paperboat::Values& in) const override {
    return {x[1], paperboat::get_or(in, "force") - k * x[0]};
  }
  paperboat::Values read() const override { return {{"x", x()[0]}, {"v", x()[1]}}; }
  std::vector<paperboat::Entity> entities(const std::string& id, double z) const override {
    return {paperboat::scene::rect(id + "/mass", x()[0], 0, 0.4, 0.4, "#2f5d62", 0, z)};
  }
  double k;
};

Scene builders#

Each returns an Entity. Points are scene::Vec (std::array<double, 3>), y up; the 2D helpers lie in the x–y plane at depth z, which the 2D view shows.

Entity scene::box(std::string id, Vec pos, Vec size, std::string color = "#888888", Vec rot = {})#

Centred at pos, turned by rot (radians, about x, then y, then z).

Entity scene::sphere(std::string id, Vec pos, double radius, std::string color = "#888888")#
Entity scene::line(std::string id, Vec from, Vec to, std::string color = "#888888")#
Entity scene::image(std::string id, Vec pos, double width, double height, std::string src)#
Entity scene::rect(std::string id, double x, double y, double width, double height, std::string color = "#888888", double angle = 0, double z = 0)#
Entity scene::circle(std::string id, double x, double y, double radius, std::string color = "#888888", double z = 0)#
Entity scene::rod(std::string id, Vec a, Vec b, double thickness, std::string color = "#888888")#

A bar from a to b: a link, a pole, a strut.

std::vector<Entity> scene::spring(const std::string &id, Vec a, Vec b, int coils = 8, double width = 0.2, const std::string &color = "#888888")#

A zigzag of lines (ids id/0, id/1…), the same number at any length, so a patch moves them all.

Registering#

struct Template#

A reusable block: a definition and a factory. Named "<package>/<block>".

std::string name#
BlockDef def#
Config config#
std::function<std::unique_ptr<Block>(const Values&, const Config&)> make#

Set for a signal block…

std::function<std::unique_ptr<Step>(const Values&, const Config&)> make_step#

…or for a block on a Step flow’s path.

bool extendable = false#

A parent for TOML definitions: a use of it may add params and set any config.

bool abstract = false#

Only a parent: import leaves it out.

std::function<void(const BlockDef&, const Config&)> check#

Validates a definition at load; throws with what’s wrong.

struct StationTemplate#

A reusable station object type: name, def (an ObjectDef) and make(props).

template<class B>
Template define_block(const std::string &package, BlockDef def, Config config = {})#

A template for B (derived from Block or Step), constructed from (params, config), (params) or nothing. Named package + "/" + def.type.

registry.add(paperboat::define_block<Count>("parts", {
    .type = "count", .label = "Count parts",
    .inputs = {{"mask", "image"}, {"photo", "image"}},
    .outputs = {{"total"}, {"marked", "image"}},
    .params = {{"min_area", 150.0}}}));
template<class O>
StationTemplate define_object(const std::string &package, ObjectDef def)#

A station template for O (derived from StationObject), constructed from (props) or nothing.

class Registry#

Templates and station templates by name.

void add(Template t)#

Throws std::invalid_argument on a duplicate name.

void add(StationTemplate t)#
void add_connector(std::string package, std::string name, nlohmann::json def)#

Registers a Modelica connector definition (such as "RealInput" or "Pin") under package so descriptors importing package (or whose domain is package) carry it in catalog.connectors.

const Template *find(std::string_view name) const#
std::vector<std::string> packages() const#
const Registry &builtins()#

Every built-in template (packages base, signal, math, dashboard, step). Copy it and add the domain’s own; optional external toolkits such as control (paperboat-toolkit-control), opencv (paperboat-toolkit-opencv) and optimization (paperboat-toolkit-optimization) register with paperboat::toolkit::control::register_control, paperboat::toolkit::opencv::register_opencv and paperboat::toolkit::optimization::register_optimization.

Toolkit plugins#

With the engine built as shared libraries (-DPAPERBOAT_SHARED_LIBS=ON), a toolkit can also be a plugin that a host loads at runtime, so installing it needs no engine rebuild (pb#352). A plugin is a shared library named libpaperboat_plugin_<name> with one line of C++:

#include <paperboat/toolkit/plugin.hpp>
PAPERBOAT_TOOLKIT_PLUGIN(paperboat::toolkit::opencv::register_opencv)

The engine build makes one for every toolkit under engine/toolkit/<name>. A host calls paperboat::toolkit::load_plugins(registry) after builtins(); the CLI and the workbench do. It searches $PAPERBOAT_TOOLKIT_PATH, $PAPERBOAT_HOME/toolkits, the running binary’s build tree and an installed lib/paperboat/plugins, skips a package the registry already has, and refuses a plugin built for another paperboat version or C++ standard library (PAPERBOAT_PLUGIN_ABI) with a message instead of loading it.

Loading#

struct Catalog#

A descriptor loaded against a registry: the app’s blocks and station objects, its top-level connectors table (passed unchanged into catalog), its starters (graph, station, as protocol JSON text) and its Station view (station_view, station_page, station_visible). Its entries point into the registry, which must outlive it.

Catalog load_descriptor_file(const std::filesystem::path &path, const Registry &registry = builtins())#

Throws DescriptorError with where the mistake is.

Catalog load_descriptor(std::string_view toml_text, const Registry &registry = builtins())#
void define_blocks(Registry &registry, const std::string &package, std::string_view toml_text)#

Blocks defined in TOML on parents in registry, added as "<package>/<type>": how a package ships blocks that are only a definition.

std::string descriptor_domain(std::string_view toml_text)#

The domain name, before loading (a host that registers the domain’s templates needs the package name first).

Serving#

struct RunSettings#
enum class Mode#
enumerator Clock#

Step everything on a clock (a Signal flow; a Step flow always does).

enumerator Once#

Evaluate a Signal flow once (a build, a query, an image pipeline).

Mode mode = Mode::Clock#
double dt = 0.01#
double duration = 10.0#

Run length (a Step flow: its limit), s.

int emit_every = 4#

Send signals and scene patches every N steps.

bool real_time = true#

Pace at wall-clock speed (--run and tests turn it off).

double speed = 1.0#

Times real time when paced; 0: as fast as it can. The UI may change it per run, with duration and dt (graph.run’s settings), and during one (run.speed): pacing then goes on from where the run is, at the new speed.

RunSettings with_overrides(RunSettings base, const json &settings)#

base with a graph.run’s settings on top (any but mode). Throws std::invalid_argument for a value out of range; a run with one fails before it starts.

struct Backend#

What a backend is made of.

std::string engine#

Its name in hello.

const toolkit::Catalog *catalog#
std::function<std::unique_ptr<toolkit::DomainState>()> state#

A fresh domain state per run (and one for the opening scene); empty if none.

json view#

The scene’s camera hint, e.g. {"mode": "2d", "center": [0, 0], "height": 6}.

RunSettings run#
std::function<std::unique_ptr<Executor>(const Graph&, const RunSettings&)> executor#

Optional: a run style of the backend’s own for this graph (return nullptr to leave it to default_executor()). Most backends leave it empty.

int main(const Backend &backend, int argc, char **argv, int default_port)#

What a backend’s main() returns: --port N serves the protocol (and a web station) there until the process ends; --run runs the starter once, headless, and prints every message as a JSON line (exit 0 when done, 1 when failed).

int serve(const Backend &backend, int port)#
std::string run_starter(const Backend &backend, std::ostream &out)#
class Server#

The server, started and stopped by its owner (a host with its own main loop, such as the Python bindings): start() returns "" when listening, else why not; stop().

std::string run(const std::string &id, const json &graph, const json &station, const Backend &backend, const Emit &emit, const KeysNow &keys, const std::stop_token &stop)#

One run, without sockets: every event goes to emit. Returns "done", "failed" or "cancelled". For tests (with real_time = false). Its last parameters (optional) are the run settings’ overrides, the variables, where it looks for tuned variables, where it finds a new speed (SpeedNow, run.speed, read between frames), and a RunCache: a run that evaluates once reuses the outputs of blocks nothing changed for since an earlier run with the same cache.

class RunCache#

<paperboat/core/cache.hpp>. What runs that evaluate once keep between runs: each block’s last good result by node id, with what it was computed from (its type, ports, params, text, lanes, the run’s dt and solver, its file params’ files; the values on its wires; the variables it read). A later run reuses it only when all of these are the same, comparing values exactly (numbers bit for bit, a handle by the object it holds). Comparing values rather than the graph upstream invalidates exactly what a change reaches: a station object changed reaches only the blocks its linked block feeds, and an upstream change that gives the same values stops there. Only blocks that may be reused (BlockDef::cacheable) are kept; a block that set a variable, or was still being computed when the run was cancelled, is not. A session keeps one per connection. Thread-safe.

std::size_t size() const#
bool contains(std::string_view node) const#
void clear()#

Run styles#

<paperboat/core/executor.hpp>. A backend needn’t know about these: the core picks the executor for each graph (default_executor()). They are for a backend whose runs fit none of the three, such as an event-driven one or an external solver. Its executor drives the same Run, so blocks, monitors, the station and the UI work as always.

class Executor#
virtual std::string execute(Run &run) = 0#

Runs run to its end. Returns "done", or "cancelled" once run.cancelled() said so. Throws to fail the run (a GraphError names the block at fault).

std::unique_ptr<Executor> clock_executor()#

A Signal flow on a clock: every block once per dt, for duration.

std::unique_ptr<Executor> once_executor()#

A Signal flow evaluated once.

std::unique_ptr<Executor> step_executor()#

A Step flow: hats start paths, each path is at one block.

std::unique_ptr<Executor> default_executor(const Graph &graph, const RunSettings &settings)#

Steps if the graph has step blocks or stories, else once or clock by settings.mode.

class Run#

A run in progress, as an executor sees it: the graph made, the station, the domain state and the outputs so far.

void at_time(double t)#

Sets the run clock and reads the keys held in the UI now.

json pass()#

Every signal block once, in order. Returns the monitors’ samples, for frame.

json evaluate(const std::string &id)#

One block of a run that evaluates once: its outputs from the run’s RunCache when nothing it depends on changed (node.state cached, with no running before it; the logs, metrics, monitor states and last frame it sent are sent again), else called (running, then done) and, if it may be reused, kept for the next run. Returns its samples. What the once executor calls for each block in order, after it has reported every block queued.

std::optional<std::string> advance()#

Station objects, then the domain state, move on. A message if the domain ends the run.

void frame(const json &samples, std::optional<double> progress)#

Sends samples, the scene’s changes and the run’s progress; waits to keep real time, at the speed the UI asked for last (run.speed): a custom executor that calls it gets speed changes during a run for free.

bool cancelled()#
void log(std::string_view level, std::string_view text)#
void node_state(std::string_view node, std::string_view state)#
const RunSettings &settings() const#

A minimal executor:

class TenPasses final : public paperboat::Executor {
 public:
  std::string execute(paperboat::Run& run) override {
    for (int k = 0; k < 10; ++k) {
      if (run.cancelled()) return "cancelled";
      run.at_time(k * 0.5);
      run.frame(run.pass(), k / 9.0);
    }
    return "done";
  }
};