Skip to content

Architecture

Components

Piper is a flat layout of peer subdirectories with a strict layering rule. Each component owns one concern and the dependency graph is acyclic.

core/        (piper)         domain layer: graph data, registry, V2 (de)serializer,
                             command stack, diagnostics, theme parsing.
                             Depends on: stdlib + nlohmann_json. No GUI deps.

canvas/      (piper::canvas) reusable ImGui node-editor framework.
                             Depends on: imgui only. Domain-agnostic.
                             MUST NOT link piper_core.

app/         (piper-editor)  GUI application. Depends on:
                             piper_core + piper_canvas + ImGui + GLFW
                             + portable-file-dialogs.

migrate/     (piper-migrate) V1 -> V2 CLI. Depends on:
                             piper_core + argparse + nlohmann_json.

py_bindings/ (piper python)  nanobind module. Depends on: piper_core only.
                             No GUI, no ImGui.

The CMake top level enforces this: only app/ declares ImGui or GLFW dependencies, only app/ and examples/canvas_demo/ link piper_canvas, and py_bindings/ and migrate/ cannot reach into GUI dependencies even by accident.

Pull-then-push rendering

The canvas framework reads graph state and emits intent events; the host application owns mutation. This decouples the framework from any specific domain model.

   ┌────────┐ user input ┌─────────┐ events  ┌─────────────────┐
   │ window │───────────>│ canvas  │────────>│ host (app)      │
   │ GLFW   │            │ Editor  │         │ MainWindow      │
   └────────┘<───────────│         │<────────│ + CommandStack  │
              draw cmds  └─────────┘  spans  │ + piper::Graph  │
                                             └─────────────────┘

Each frame:

  1. Pull: the host's adapter (PiperCanvasGraph) translates its piper::Graph mirror into canvas::Node / canvas::Link spans the framework draws.
  2. Render: canvas::Editor::draw() produces ImGui draw commands for the current viewport; widgets win clicks before InvisibleButtons collect drags (PR 2.10's render-then-input pattern).
  3. Events: the host calls Editor::consume_events() and turns each event into a piper::Command pushed onto the document's CommandStack. The next frame's pull reflects the change.

The framework holds zero domain state. The adapter is the only piece that knows about both worlds.

CommandStack and undo

All graph mutations -- whether triggered by the canvas, the inspector, the stages panel, the profiles panel, the right-click menu, or paste -- flow through CommandStack::push(cmd, graph). Each command captures enough state to apply and revert deterministically.

Drag interactions and paste fan out into multiple primitive commands; they coalesce into one undo entry by wrapping the dispatch in open_group() / close_group(). Save clears the document's dirty flag.

Multi-document host

MainWindow owns vector<unique_ptr<Document>>. Each Document carries its own Graph, CommandStack, canvas::Editor, PiperCanvasGraph adapter, selection, current stage, active profile profile, and load/lint diagnostics. A tab bar across the top selects the active document; only the active document's editor draws each frame.

Shared state lives on MainWindow: the Theme (including the mode colors, Theme::mode_colors), the NodeRegistry, and the cross-tab clipboard. Document addresses are stable (held via unique_ptr) so the editor's references into per-doc fields stay valid across tab insert/erase.

Save semantics preserve multi-pipeline files: hitting Ctrl+S on one tab gathers every other tab whose loaded_path matches and writes them as one bundle. This means a file that came in as a multi- pipeline bundle stays multi-pipeline after a single-tab edit.

File format

V2 wraps any number of pipelines in a top-level pipelines[] array. The full schema lives in v2_format.md. type_system.md covers the type-tag conventions and the bundled palette.

Validation boundary

V2 is the designer. It owns structural validity:

  • Pin type compatibility on link creation (string-tag equality, plus same-node and already-connected guards).
  • Visual highlight of incompatible pins during drag.
  • Re-check link types on graph load (catches drift when a node type's attribute changed since the graph was saved).
  • Schema validity on save / load.

It does not own semantic validity. The engine consuming V2 JSON owns:

  • Within-stage execution order (topological sort).
  • Cycle detection / causality / fixed-point convergence.
  • Stage-dependent pin direction resolution (the "bus" pattern).
  • Numerical type promotion (e.g. int -> float).
  • Sample-rate / unit consistency.

V2 does not enforce engine-level rules -- doing so would reject valid graphs. The engine does not enforce structural rules -- doing so would duplicate the editor.

Engine execution model

Engine::play() runs each stage once per tick, in the order they appear in graph.stages(). Within a stage, the engine builds a Kahn topological sort over the links between same-stage nodes (engine.cc, "Per-stage topo sort"). Producer steps always run before same-stage consumers, so a consumer reads the current tick's value. A cycle inside one stage is a build error (CycleDetected).

Across stages, what a consumer sees depends on tick order:

  • Producer's stage runs first: the consumer reads the producer's current-tick output.
  • Producer's stage runs after: the consumer reads the producer's previous-tick output. This single-tick break is how the engine resolves feedback loops -- a cycle that would be illegal inside one stage becomes a legal recurrence once it crosses a stage boundary. The motor command (control) / measured (feedback) Bus pattern in motor_control_dual_jacobian.piper is the canonical case.

Open-loop DAGs do not need multiple stages. The bundled filter_demo.piper would produce identical samples if its generate / control / feedback stages were collapsed into one. Add a stage when:

  • A loop closes back on itself and you need a 1-tick break to cut the cycle.
  • A subgraph should run at a different cadence than the rest (a host can call tick(stage) selectively instead of play()).
  • You want the editor to visually separate phases of the pipeline.

External I/O

Host-facing I/O is part of the attribute contract, not a node-type convention. A node type declares attributes with role ExternalInput / ExternalOutput; each attribute's value is the external name set by the user in the pipeline. The step backs each one with a field it owns, mirroring declare_output:

Role Step declaration (in declare_io) Host access
Input declare_input<T>(name) --
Output declare_output<T>(name, slot) --
ExternalInput declare_external_input<T>(name, slot) T* Engine::input<T>(external_name)
ExternalOutput declare_external_output<T>(name, slot) T const* Engine::output<T>(external_name)

Engine::build() loops over every external attribute of every node and indexes the step's slot under the attribute's value. The host pointer is the step's field, so there is no copy and no lookup on the hot path: resolve once after build(), then read/write through the pointer. The pointer is invalidated by the next build(); a lookup at the wrong T returns nullptr (checked with std::any, not with type-name strings).

Build errors (BuildDiagnostic::Kind::ExternalIoConflict):

  • the step did not declare an external attribute with the matching declare_external_* call, declared it as a regular pin, or declared an external slot the node has no matching attribute for;
  • the attribute's data_type differs from the T the step declared (declare_external_input<float> under a "double" attribute);
  • an external name used twice in the same direction (inputs and outputs are separate namespaces).

External names are optional: an unnamed external input or output builds fine and is simply not exported (an unnamed input keeps its default value, like an unwired pin). The editor lints it as a warning.

External attributes are never linked and never scheduled: they ignore stages and play no part in the per-stage topo sort. The builtin external_input<T> / external_output<T> nodes are thin adapters built on the same contract -- external_input<T> backs both its value external input and its out pin with one field.

Profiles and modes

  • A mode is the state of one node (one step): "disable" or one of the node's modes.
  • A profile belongs to the pipeline: a name plus the mode of each node, Profile{ name, per_node[NodeId] = mode }.

A pipeline always has at least one profile, and its default profile is one of them: a new Graph starts with one profile, default, the default profile cannot be removed, and the default can only be set to an existing profile. Graph::add_node() gives the new node its first mode in every profile.

Every node has an editable mode list, Node::modes; "disable" is always available on top of it. A new node starts with its type's modes (NodeType::modes, e.g. a drive's position, speed, torque), or enable when the type declares none. The user may add, rename and remove modes on any node; the type's own modes stay, and a node keeps at least one mode. Renaming a mode also renames it in the member overloads and in every profile.

Any member has a default value (Attribute::value) and optional per-mode overloads (Attribute::mode_overloads). A mode without an overload uses the default. A constant with an overload per mode is a mode-keyed value bank.

piper::modes_of() lists the modes of a node; its first entry is the default assigned when a node or, in the editor, a profile is created (fill_missing_modes()). piper::check_profile_modes() reports a node without an entry as MissingMode and an entry outside its modes as UnknownMode; the editor shows these with its lints. Removing a node also removes its profile entries.

The host switches the whole pipeline with Engine::set_profile("name"), which returns EngineError::UnknownProfile and keeps the current profile for a name the graph does not have. Graph edits that can fail return a std::error_code (GraphError) naming the reason. build() applies the graph's default profile and fails with InvalidProfile when the default profile is missing or a node has no mode in some profile, so a built engine always runs in a real profile with a mode for every step.

A step declares its pins in declare_io() and reads its members in on_mode_change(HashedString new_mode), where member() returns the new mode's value. The engine calls it on each node whose mode changes (never for "disable"); build() calls it once per mode of the node to validate every value, and reports a failure as ModeChangeFailed. Step::supported_modes() lists the node's modes. Only build() (for the default profile) and set_profile() change modes; tick() and play() never do. An exception from on_mode_change() in set_profile() propagates and stops the engine until the next build(). A step instance shared by several engines (a factory returning the same instance) keeps the values of the last engine that switched its mode.

A node type cannot declare "disable", an empty name or the same mode twice (NodeRegistry::add() refuses it); the loader drops such entries from a node's mode list with a SchemaError.

The engine reserves exactly one mode, "disable" -- nodes whose mode is "disable" in the active profile are skipped at tick time (their compute() is not called and their outputs hold their last-written value, zero on a fresh build). Every other mode is opaque to the engine, which does not check declarations; the step reads it via Step::current_mode() and decides what to do. So a step that exposes several "computational slots" can dispatch on its mode inside compute() -- e.g. publish a different stored value, run a different update rule, route a different input downstream -- without the engine knowing anything about the slot semantics.

Step::current_mode() returns this step's mode; a step typically uses it. Step::current_profile() returns the active pipeline profile (handy when several nodes need to coordinate on a single broadcast value). Both return a HashedString -- a {name, id} struct where id is the FNV-1a hash pre-computed once on set_profile(). Comparison with a string literal folds the literal hash at -O1+, so the hot path is a single uint64 compare with no string work:

void compute(HashedString) override
{
    if (current_mode() == "loose")
    {
        ...
    }
}

Stage names use the same HashedString type: compute() receives the current stage as one.

Extending Piper

  • Adding a node type: declare it in core/src/builtin_nodes.cc (or a downstream registry). Walkthrough: Adding a node type.
  • Adding a command: subclass piper::Command, implement apply and revert, expose a constructor. The pattern is consistent across the existing commands in core/include/piper/commands.h.
  • Adding a diagnostic: extend DiagnosticKind in core/include/piper/diagnostic.h; the loader and the editor's Problems panel pick it up automatically.
  • Replacing the canvas framework: canvas/ is reusable -- swap the adapter and the host can keep its Graph model unchanged.