Docs / Bastion Circuit Designer manual / Architecture

Architecture

1. Executive Summary & Philosophy

Bastion Circuit Designer (BCD) is a lightweight, cross-platform Electronic Design Automation (EDA) desktop suite engineered to bridge the gap between schematic capture, interactive visual physics simulation, and modern developer tooling.

Unlike traditional enterprise EDA suites that suffer from legacy UI paradigms, and unlike purely educational browser applets that lack industrial CAD rigor, BCD unites:

  1. Schematic Rigor: Professional CAD drafting, hierarchical multi-sheet support, orthogonal routing, netlist generation, and live Bill of Materials (BOM).
  2. Visual Interactive Physics: CircuitJS-style high-contrast voltage color gradients on conductors and animated charge-carrier particles reflecting instantaneous current magnitude and direction.
  3. Modern IDE Ergonomics: VS Code / Linear dark theme aesthetic, keyboard-first command palette, native Git-friendly JSON storage, and cloud sync (Google Drive).
  4. Multimodal AI Co-Pilot: Iterative, non-destructive schematic editing through strict JSON patch diffs, cost-aware design optimization, and PDF datasheet ingestion into simulatable component definitions.

2. Technology Stack & Rationale

Layer Technology Rationale
Language & Runtime C# on .NET 10 / .NET 9 LTS High-performance JIT/AOT compilation, memory safety, zero-overhead SIMD vectorization for matrix math, cross-compilation for win-x64, linux-x64, and linux-arm64.
Desktop UI Framework Avalonia UI 11+ Hardware-accelerated Skia rendering backend, 60+ FPS high-performance canvas, native cross-platform windowing, and mature MVVM tooling (CommunityToolkit.Mvvm).
Graphics Engine SkiaSharp Direct GPU-accelerated drawing context (SKCanvas), efficient path caching, custom shader support for glowing traces, and off-screen rendering for export.
Storage & Data System.Text.Json + JSON Schema Native high-speed serialization, human-readable .eda.json project format, Git-diff friendly, and strict schema validation.
Cloud Sync Google Drive REST API v3 / OAuth2 Cross-platform loopback OAuth2 authentication, zero proprietary cloud lock-in, automated workspace sync.
Procurement API Octopart GraphQL & DigiKey API Real-time pricing tiers, distributor stock counts, lifecycle alerts (EOL/NRND), and cart export.

3. Critical Technical Guardrails

Guardrail 1: Behavioral vs. Analog Simulation (Hybrid Engine)

Full transistor-level SPICE simulation of complex integrated circuits (e.g., an ESP32 or ATmega328P with millions of transistors) is computationally prohibitive at interactive 60 FPS speeds.

Solution: Decoupled Multi-Rate Hybrid Architecture

                  ┌──────────────────────────────────────────────┐
                  │          Multi-Rate Master Clock             │
                  │   Analog: 10µs fixed / Digital: Event-driven │
                  └──────────────────────┬───────────────────────┘
                                         │
                 ┌───────────────────────┴───────────────────────┐
                 ▼                                               ▼
   ┌───────────────────────────┐                   ┌───────────────────────────┐
   │    Analog Solver (MNA)    │                   │ Behavioral / Digital Bus  │
   │  - Passives (R, L, C)     │                   │  - Microcontrollers (AVR) │
   │  - Non-linear (Diode, BJT)│◄───Boundary────►  │  - Logic (74xx, 4000)     │
   │  - Op-Amps (Linear model) │    Conditions     │  - I2C / SPI / UART buses │
   │  - Newton-Raphson loop    │                   │  - Displays (OLED, LCD)   │
   └───────────────────────────┘                   └───────────────────────────┘
  1. Analog Nodal Core (Modified Nodal Analysis - MNA):
    • Implements \([G][V] = [I]\) formulation expanded for independent voltage sources and operational amplifiers (\([M][x] = [z]\)).
    • Reactive Elements (\(L, C\)): Discretized using companion models (Trapezoidal integration for high accuracy, Backward Euler for numerical damping during sharp discontinuities).
    • Non-linear Devices (Diodes, Transistors): Solved via iterative Newton-Raphson updates using piecewise companion conductances and Norton current sources until node convergence threshold (\(\epsilon < 1\,\mu\text{V}\), \(\epsilon < 1\,\text{pA}\)) or max iterations (20) is met.
  2. Behavioral Domain (Digital & Protocols):
    • High-level ICs (e.g. HD44780 LCD, SSD1306 OLED, MPU6050) operate as discrete-event state machines.
    • Digital buses (I2C, SPI, UART) do not simulate continuous sub-nanosecond physical capacitance curves unless explicitly requested. Instead, they operate on byte/packet transactions with state transitions occurring on clock edges.
  3. Boundary Coupling:
    • Digital output pins interface with the analog solver as Thévenin equivalents: an ideal switch between \(V_{CC}\) and \(GND\) with a selectable internal output impedance (e.g. \(25\,\Omega\)).
    • Digital input pins present high impedance (\(10\,\text{M}\Omega \parallel 5\,\text{pF}\)) and read logic levels via Schmitt-trigger threshold comparators (\(V_{IL} \le 0.3 \times V_{CC}\), \(V_{IH} \ge 0.7 \times V_{CC}\)).

Guardrail 2: AI Schematic Diffs (JSON Patch Engine)

When an LLM attempts to generate complete schematics from scratch, it invariably scrambles spatial coordinates, breaks wire routing topologies, introduces duplicate component IDs, and wipes user annotations.

Solution: Atomic JSON Operation Patches (patch.schema.json)

  • The AI Co-Pilot outputs an array of discrete, typed operations:
    • ADD_COMPONENT: Inserts a new component. If position is omitted or relative, the layout engine searches the Voronoi / Delaunay empty-space grid adjacent to target connection pins.
    • REMOVE_COMPONENT: Safely removes a component and cleans up hanging or orphaned net segments.
    • UPDATE_COMPONENT: Modifies electrical value (e.g. \(10\,\text{k}\Omega \to 4.7\,\text{k}\Omega\)), tolerance, or part number without touching geometry.
    • CONNECT_NET: Merges two pins into an existing or new net using the Manhattan A* orthogonal router.
    • DISCONNECT_NET: Detaches a specific pin while preserving the rest of the net.
    • ADD_PROBE: Attaches a virtual oscilloscope or voltage probe to a net.
  • Transactional Safety: Patches are pre-validated against the schematic topological model before application. If an operation violates electrical constraints (e.g. direct short circuit between two ideal voltage sources of differing potential), the patch is rejected with descriptive feedback to the AI for self-correction.
  • Undo/Redo: Every applied patch pushes an inverse operation patch onto the undo stack.

Guardrail 3: Cross-Platform In-Memory Video & GIF Recording

Bundling full FFmpeg binary executables adds 80MB–150MB of bloat, introduces platform-dependent child process management, and causes distribution headaches on macOS/Linux sandboxes.

Solution: Direct Skia Buffer Capture & In-Memory Encoding

  1. Frame Capture Pipeline:
    • At each simulation display tick (e.g. 30 FPS or 60 FPS), the off-screen Skia canvas buffer (SKBitmap / SKPixmap) is captured directly from video memory into a frame buffer ring.
  2. GIF Encoding:
    • High-efficiency in-memory palette quantizer (NeuQuant neural-network color quantizer or Octree quantizer) generates a 256-color palette per frame or globally.
    • Streamed directly to an in-memory LZW encoder, creating lightweight animated .gif files with zero external dependencies.
  3. Video Encoding:
    • Lightweight container writer for WebM (VP8/VP9) or OS-native media encoders (Microsoft Media Foundation on Windows, GStreamer / libvpx bindings on Linux), keeping the standalone executable under 35MB.

4. System Architecture & Component Decoupling

┌─────────────────────────────────────────────────────────────────────────────┐
│                             Bastion.App (UI)                                │
│  ┌───────────────────────┐ ┌───────────────────────┐ ┌───────────────────┐  │
│  │   Solution Explorer   │ │  Skia Schematic Canvas│ │ AI Co-Pilot Chat  │  │
│  │  (Sheets, Modules)    │ │ (Pan, Zoom, Overlays) │ │  (Diffs & Audio)  │  │
│  └──────────┬────────────┘ └───────────┬───────────┘ └─────────┬─────────┘  │
│             │                          │                       │            │
│             ▼                          ▼                       ▼            │
│  ┌───────────────────────────────────────────────────────────────────────┐  │
│  │                         MVVM ViewModels Layer                         │  │
│  │    (MainViewModel, CanvasViewModel, ChatViewModel, BomViewModel)      │  │
│  └───────────────────────────────────┬───────────────────────────────────┘  │
└──────────────────────────────────────┼──────────────────────────────────────┘
                                       │
┌──────────────────────────────────────┼──────────────────────────────────────┐
│                                      ▼                                      │
│                             Bastion.Core                                    │
│  ┌───────────────────┐ ┌───────────────────┐ ┌───────────────────────────┐  │
│  │  Schematic Model  │ │  Component Library│ │     JSON Patch Engine     │  │
│  │ (Components, Nets)│ │  (~100 Definitions│ │(Validation, Auto-Placement│  │
│  └──────────┬────────┘ └─────────┬─────────┘ └─────────────┬─────────────┘  │
│             │                    │                         │                │
│             ▼                    ▼                         │                │
│  ┌─────────────────────────────────────────┐               │                │
│  │        Orthogonal Wire Router           │◄──────────────┘                │
│  │    (Manhattan A*, Obstacle Grid)        │                                │
│  └──────────────────┬──────────────────────┘                                │
└─────────────────────┼───────────────────────────────────────────────────────┘
                      │
┌─────────────────────┼───────────────────────────────────────────────────────┐
│                     ▼                                                       │
│                             Bastion.Simulation                              │
│  ┌─────────────────────────────────────────┐ ┌───────────────────────────┐  │
│  │       Modified Nodal Analysis (MNA)     │ │  Behavioral Bus Engine    │  │
│  │ (Matrix Formulation, LU Decomposition)  │ │ (I2C, SPI, UART, Sensors) │  │
│  └──────────────────┬──────────────────────┘ └─────────────┬─────────────┘  │
│                     │                                      │                │
│                     ▼                                      ▼                │
│  ┌───────────────────────────────────────────────────────────────────────┐  │
│  │         Multi-Rate Simulation Loop & Particle Generator               │  │
│  │       (Voltages, Current Directions, Particle Velocities)             │  │
│  └───────────────────────────────────┬───────────────────────────────────┘  │
└──────────────────────────────────────┼──────────────────────────────────────┘
                                       │
┌──────────────────────────────────────┼──────────────────────────────────────┐
│                                      ▼                                      │
│                             External Services                               │
│  ┌───────────────────┐ ┌───────────────────┐ ┌───────────────────────────┐  │
│  │ Google Drive Sync │ │  Octopart / DigiKey│ │ Multimodal LLM (Gemini /  │  │
│  │  (OAuth2 Storage) │ │ (Live BOM Pricing)│ │ Claude / OpenAI APIs)     │  │
│  └───────────────────┘ └───────────────────┘ └───────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────────┘

5. Mathematical Simulation Engine (MNA)

5.1 Matrix Formulation

For any circuit network with \(N\) nodes (excluding reference ground node 0) and \(M\) independent voltage sources or inductors, the system is modeled as:

\(\begin{bmatrix} \mathbf{G} & \mathbf{B} \\ \mathbf{C} & \mathbf{D} \end{bmatrix} \begin{bmatrix} \mathbf{v} \\ \mathbf{j} \end{bmatrix} = \begin{bmatrix} \mathbf{i} \\ \mathbf{e} \end{bmatrix}\)

Where:

  • \(\mathbf{G} \in \mathbb{R}^{N \times N}\): Conductance matrix constructed from passive two-terminal conductances \(g = 1/R\).
  • \(\mathbf{B} \in \mathbb{R}^{N \times M}\): Connectivity matrix representing current contributions of independent voltage sources.
  • \(\mathbf{C} \in \mathbb{R}^{M \times N}\): Constraint matrix enforcing voltage differentials (\(v_+ - v_- = E\)).
  • \(\mathbf{D} \in \mathbb{R}^{M \times M}\): Dependency matrix (typically zero for ideal voltage sources, or \(-R_s\) for real sources).
  • \(\mathbf{v} \in \mathbb{R}^N\): Unknown node voltages with respect to ground.
  • \(\mathbf{j} \in \mathbb{R}^M\): Unknown branch currents flowing through voltage sources.
  • \(\mathbf{i} \in \mathbb{R}^N\): Independent current source vectors.
  • \(\mathbf{e} \in \mathbb{R}^M\): Independent voltage source values.

5.2 Dynamic Reactive Elements

  • Capacitors: Discretized using Trapezoidal Rule: \(I_{C}(t) = \frac{2C}{\Delta t} (V(t) - V(t - \Delta t)) - I_C(t - \Delta t)\) Equivalent companion conductance: \(G_{eq} = \frac{2C}{\Delta t}\); Norton equivalent current source: \(I_{eq} = G_{eq} V(t - \Delta t) + I_C(t - \Delta t)\).
  • Inductors: \(I_L(t) = I_L(t - \Delta t) + \frac{\Delta t}{2L} (V(t) + V(t - \Delta t))\) Equivalent companion conductance: \(G_{eq} = \frac{\Delta t}{2L}\); Norton equivalent current source: \(I_{eq} = I_L(t - \Delta t) + G_{eq} V(t - \Delta t)\).

5.3 Non-Linear Iteration (Newton-Raphson)

For diodes (\(I_D = I_S (e^{V_D / n V_T} - 1)\)): In iteration \(k+1\): \(G_d^{(k)} = \left.\frac{\partial I_D}{\partial V_D}\right|_{V_D^{(k)}} = \frac{I_S}{n V_T} e^{V_D^{(k)} / n V_T}\) \(I_{eq}^{(k)} = I_D(V_D^{(k)}) - G_d^{(k)} V_D^{(k)}\) The matrix updates until \(\max |V_D^{(k+1)} - V_D^{(k)}| < 10^{-6}\,\text{V}\).


6. CircuitJS-Style Visual Rendering Model

  1. Wire Voltage Color Gradients:
    • Wires are colored along their length according to electric potential:
      • \(V > 0\,\text{V}\): Bright green (#22c55e), with luminance scaling dynamically from \(0\,\text{V}\) to \(+15\,\text{V}\).
      • \(V = 0\,\text{V}\) (Ground): Cool gray (#71717a).
      • \(V < 0\,\text{V}\): Amber/red (#ef4444), scaling dynamically for negative potentials.
  2. Animated Charge-Carrier Particles:
    • Each active wire segment maintains a virtual particle chain.
    • Particle spacing: constant (e.g. 16 screen pixels).
    • Particle velocity: \(v = \text{clamp}(k \cdot I, -v_{max}, v_{max})\), where \(I\) is branch current computed by the MNA solver.
    • Particle rendering: Bright glowing dots (#e2e8f0 with a Skia SKMaskFilter.CreateBlur glow).
    • When \(I = 0\), particles remain stationary. When current flows backwards, particles advance in reverse.

7. Component Library Taxonomy (~100 Core Items)

The core library is organized into four distinct tiers:

Component Library
├── 1. Passives & Discretes (30 items)
│   ├── Resistor, Potentiometer, Trimpot, Photoresistor (LDR), Thermistor (NTC/PTC)
│   ├── Ceramic Capacitor, Electrolytic Capacitor, Tantalum Capacitor, Variable Capacitor
│   ├── Inductor, Ferrite Bead, Coupled Inductors, Transformer (1:1, Step-up, Step-down)
│   ├── Diode (1N4148), Schottky Diode (1N5819), Zener Diode (3.3V, 5.1V, 12V), LED (Red, Green, Blue, RGB)
│   ├── NPN BJT (2N3904, BC547), PNP BJT (2N3906), N-Channel MOSFET (2N7000, IRFZ44N), P-Channel MOSFET (IRF9540)
│   └── SPST Switch, SPDT Switch, Pushbutton (NO/NC), Relay (SPDT, DPDT), Fuse, Ground, DC Voltage Source, AC Source
├── 2. Logic & Analog ICs (35 items)
│   ├── Logic Gates: AND (74HC08), OR (74HC32), NOT/Inverter (74HC04), NAND (74HC00), NOR (74HC02), XOR (74HC86), XNOR
│   ├── Flip-Flops & Registers: D-Type Flip Flop (74HC74), JK Flip Flop (74HC73), 8-bit Shift Register (74HC595, 74HC165)
│   ├── Counters & Decoders: Decade Counter (CD4017), Binary Counter (74HC393), 3-to-8 Decoder (74HC138), BCD-to-7Seg (74LS47)
│   ├── Linear & Timers: NE555 Precision Timer, LM358 Dual Op-Amp, LM324 Quad Op-Amp, TL072 Low-Noise Op-Amp, LM393 Dual Comparator
│   └── Regulators & Reference: LM7805 (+5V), LM7812 (+12V), LM317 Adjustable, AMS1117-3.3, TL431 Voltage Reference
├── 3. Displays, Sensors & Actuators (20 items)
│   ├── Displays: 16x2 Character LCD (HD44780 4-bit/8-bit/I2C backpack), 0.96" I2C OLED (SSD1306 128x64), 7-Segment Single & Quad Display
│   ├── Sensors: MPU6050 (6-DOF IMU with interactive UI orientation sliders), DHT22 / DHT11 (Temp/Humidity with UI sliders)
│   ├── Navigation: NEO-6M GPS Module (streams simulated NMEA sentence sentences over serial UART)
│   ├── Inputs: Rotary Encoder with push-button, 4x4 Matrix Keypad, Analog Joystick (dual-axis potentiometers)
│   └── Actuators: DC Motor, SG90 Micro Servo (PWM angle control), Piezo Buzzer (frequency audible output)
└── 4. Microcontroller & Processing Wrappers (15 items)
    ├── ATmega328P (Arduino Uno form-factor and bare DIP-28, running simavr emulation core)
    ├── ESP32-WROOM-32 (Dual-core Xtensa simulation wrapper with stubbed WiFi/BLE registers)
    ├── ATtiny85 (Compact 8-pin microcontroller)
    ├── Raspberry Pi Pico (RP2040 Dual ARM Cortex-M0+)
    └── Milk-V Duo (CV1800B RISC-V 64-bit emulation stub)

8. Live BOM & Procurement Pipeline

  1. Automatic BOM Tally:
    • As components are placed, modified, or deleted on the schematic, the BOM aggregation engine updates in real time.
    • Aggregates by Manufacturer Part Number (MPN), package footprint (e.g. 0805, SOIC-8, DIP-14), and value.
  2. API Integrations:
    • Octopart GraphQL API:
      • Query: Part availability, authorized distributor list (Mouser, DigiKey, Farnell, Arrow), price breaks (\(1, 10, 100, 1000)\), and active lifecycle status (Active, End of Life, Not Recommended for New Designs).
    • DigiKey REST API v3:
      • Secondary lookup and direct shopping cart export.
  3. One-Click Purchasing:
    • Export structured cart payloads via Octocart API or standard DigiKey / Mouser CSV format.

9. Multimodal AI Co-Pilot & Datasheet Ingestion

  1. Prompt-to-Diff Pipeline:
    • User inputs natural language (e.g., "Wire an ESP32 to an MPU6050 on I2C and add 4.7k pull-up resistors to SDA and SCL").
    • System injects current schematic netlist summary + standard component catalog into system context.
    • LLM responds strictly with valid patch.schema.json operations.
    • BCD dry-runs the patch, identifies non-colliding coordinates, verifies net continuity, and executes the changes with animated insertion indicators.
  2. Cost-Aware Optimization Prompts:
    • User: "Redesign this circuit using cheaper, in-stock alternatives for the op-amps."
    • AI queries current live BOM pricing data, searches catalog for equivalent pin-compatible op-amps (e.g. swapping an expensive precision op-amp for an in-stock equivalent), and outputs an UPDATE_COMPONENT patch.
  3. PDF Datasheet Ingestion (.edamod):
    • User drags a PDF manufacturer datasheet (e.g. Texas Instruments, Microchip) into the AI sidebar.
    • Multi-modal model analyzes pinout diagrams, electrical specifications (\(V_{CC}\) min/max, pin functions, I2C addresses), and functional truth tables.
    • Emits a standard .edamod JSON module definition containing visual pin layout, electrical types, and behavioral emulation rules.

10. Verification & Quality Assurance Strategy

  1. Unit & Math Testing (Bastion.Tests):
    • Verification of MNA equations against analytical benchmarks (voltage dividers, bridged T-filters, Wien-bridge oscillators, 555 astable timers).
    • Newton-Raphson convergence tests with steep diode curves and switching transients.
  2. Patch & Topological Testing:
    • Fuzz testing the AI patch parser with malformed, cyclic, and short-circuit operations to verify guaranteed rollback and error reporting.
    • Manhattan orthogonal routing collision and cross-over minimization tests.
  3. Cross-Platform Verification:
    • Standalone portable binary builds on Windows x64 and Linux x64/ARM64.
    • Skia rendering performance profiling (ensuring steady \(\ge 60\) FPS with 500+ active wire particles).

Updated 2026-11-01

An unhandled error has occurred. Reload 🗙

Rejoining the server...

Rejoin failed... trying again in seconds.

Failed to rejoin.
Please retry or reload the page.

The session has been paused by the server.

Failed to resume the session.
Please retry or reload the page.