simple-circuit-engine 0.0.1 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md ADDED
@@ -0,0 +1,151 @@
1
+ # simple-circuit-engine
2
+
3
+ Educational electronic / computer circuit Build & Simulation engine with THREE.js 3D visualization.
4
+
5
+ - **Install**: `npm install simple-circuit-engine three lil-gui`
6
+ - **Imports**: `simple-circuit-engine/core` (model/simulation) | `simple-circuit-engine/scene` (Three.js visuals)
7
+ - **TypeScript**: Full type support, strict mode compatible
8
+
9
+ ## Quick Start
10
+
11
+ ```typescript
12
+ import { WebGLRenderer } from 'three';
13
+ import {
14
+ Circuit,
15
+ BehaviorRegistry,
16
+ registerBasicComponentsBehaviors,
17
+ } from 'simple-circuit-engine/core';
18
+ import {
19
+ CircuitEngine,
20
+ engineOptions,
21
+ FactoryRegistry,
22
+ DefaultVisualFactory,
23
+ registerBasicComponentsFactories,
24
+ } from 'simple-circuit-engine/scene';
25
+
26
+ // Create component factory registry and behavior registry with basic components
27
+ const componentsFactoryRegistry = registerBasicComponentsFactories(
28
+ new FactoryRegistry(new DefaultVisualFactory())
29
+ );
30
+ const behaviorRegistry = registerBasicComponentsBehaviors(new BehaviorRegistry());
31
+
32
+ // Instanciate and Initialize CircuitEngine (it creates and uses a new Circuit by default)
33
+ const engine = new CircuitEngine(componentsFactoryRegistry, behaviorRegistry);
34
+ const container = document.getElementById('canvas-container')!;
35
+ engine.initialize(container, engineOptions());
36
+
37
+ // Rendering
38
+ const renderer = new WebGLRenderer();
39
+ const width = window.innerWidth,
40
+ height = window.innerHeight;
41
+ renderer.setSize(container.clientWidth, container.clientHeight);
42
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
43
+ // Append renderer to DOM
44
+ container.appendChild(renderer.domElement);
45
+ // Animation loop to animate the circuit scene in the canvas container
46
+ function animate() {
47
+ requestAnimationFrame(animate);
48
+ engine.getControls().update();
49
+ renderer.render(engine.getScene(), engine.getCamera());
50
+ }
51
+ animate();
52
+ ```
53
+
54
+ ## Core Module (`simple-circuit-engine/core`)
55
+
56
+ ### Domain Model
57
+
58
+ - `Circuit` - Central container: components, enodes, wires
59
+ - `Component` - Electrical component (battery, switch, LED, etc.)
60
+ - `ENode` - Connection point (Component Pin or BranchingPoint)
61
+ - `Wire` - Connection between two ENodes
62
+ - `Position` - 2D grid coordinates
63
+ - `Rotation` - Discrete rotation enum
64
+
65
+ ### Simulation
66
+
67
+ - `CircuitRunner` - Tick-based simulation orchestrator
68
+ - `SimulationState` - Circuit state at a given tick
69
+ - `BehaviorRegistry` - Maps ComponentType → behavior logic
70
+ - `registerBasicComponentsBehaviors()` - Registers built-in behaviors
71
+
72
+ ### Types
73
+
74
+ - `ComponentType` - Enum: Battery, Switch, Transistor, etc.
75
+ - `UUID` - String type alias for identifiers
76
+
77
+ ## Scene Module (`simple-circuit-engine/scene`)
78
+
79
+ ### Main Classes
80
+
81
+ - `CircuitEngine` - Unified facade with edit/simulation mode switching
82
+ - `CircuitController` - Edit mode: component placement, wiring, selection
83
+ - `CircuitRunnerController` - Simulation mode: animation, interaction
84
+
85
+ ### Visual Factories
86
+
87
+ - `FactoryRegistry` - Maps ComponentType → visual factory
88
+ - `DefaultVisualFactory` - Fallback factory for unknown types
89
+ - `registerBasicComponentsFactories()` - Registers built-in factories
90
+
91
+ ### Tools (Edit Mode)
92
+
93
+ - `BuildTool` - Primary editing tool
94
+ - `AddComponentTool` - Component placement
95
+ - `MultiSelectTool` - Rectangle selection + bulk ops
96
+
97
+ ### Managers
98
+
99
+ - `HoverManager` - Raycasting hover detection
100
+ - `SelectionManager` - Tracks selected elements
101
+ - `WireVisualManager` - Wire Line2 visuals
102
+
103
+ ## Common Patterns
104
+
105
+ ### Initialize Engine
106
+
107
+ ```typescript
108
+ const engine = new CircuitEngine(factoryRegistry, behaviorRegistry);
109
+ engine.initialize(container, engineOptions());
110
+ engine.setCircuit(new Circuit());
111
+
112
+ // Add Component Programmatically
113
+ const battery = circuit.addComponent(ComponentType.Battery, new Position(0, 0));
114
+ const led = circuit.addComponent(ComponentType.SmallLED, new Position(2, 0));
115
+
116
+ // Connect Components
117
+ const wire = circuit.addWire(battery.pins[0], led.pins[1]);
118
+
119
+ // Switch Modes
120
+ engine.setMode('simulation'); // Start simulation
121
+ engine.setMode('edit'); // Back to editing
122
+
123
+ // Listen to Events
124
+ engine.on('componentAdded', (component) => { ... });
125
+ engine.on('simulationTick', (state) => { ... });
126
+ ```
127
+
128
+ ## Non-Goals / Limitations
129
+
130
+ ### Non-Goals
131
+
132
+ - **NOT realistic physics**: This is a discrete graph model, not SPICE
133
+ - **NOT for production circuits**: Educational purposes only
134
+ - **Circuit states are boolean**: Tension/current are on/off, not continuous values
135
+ - **No analog simulation**: No voltage drops, current limiting, etc.
136
+
137
+
138
+ ### Do NOT
139
+
140
+ - Attempt to add analog physics simulation
141
+ - Expect continuous voltage/current values
142
+ - Use for real circuit design validation
143
+
144
+ ## Required Peer Dependencies
145
+
146
+ ```json
147
+ {
148
+ "three": "^0.181.0",
149
+ "lil-gui": "^0.21.0"
150
+ }
151
+ ```
package/CLAUDE.md ADDED
@@ -0,0 +1,140 @@
1
+ # simple-circuit-engine Development Guidelines
2
+
3
+ Provide a simple and easy-to-use electronic circuit simulation library for educational purposes.
4
+ It allows users to create, edit and simulate electronic circuits in a web environment.
5
+ The library should be easily importable and usable in client applications and follow open-source typeScript libraries good practices.
6
+
7
+ Last updated: 2026-01-18
8
+
9
+ ## Active Technologies
10
+
11
+ - TypeScript 5.9+ (strict mode), targeting ES2022
12
+ - Three.js 0.181+ (scene, camera, controls, 3D objects, Line2)
13
+ - lil-gui as helper for small interactive modal forms
14
+ - in-memory circuit model, optional loading/saving from/to a JSON file
15
+
16
+ ## Project Structure
17
+
18
+ Simple Circuit Engine follows a **Model-Controller** architecture with clear separation between:
19
+
20
+ - **Core module** (`src/core/`): Pure TypeScript domain **Model** and simulation engine (no dependencies)
21
+ - **Scene module** (`src/scene/`): Three.js visualization layer with editing **Controllers** and tools
22
+
23
+ ### Core Module (`src/core/`)
24
+
25
+ The core module is **dependency-free** and contains all domain logic:
26
+
27
+ ```
28
+ src/core/
29
+ +-- Circuit.ts # Central model: manages the three elements of the circuit : components, enodes, and wires
30
+ +-- Component.ts # Electrical component (battery, switch, LED, etc.)
31
+ +-- ENode.ts # Electrical node (Pin or BranchingPoint)
32
+ +-- Wire.ts # Connection between two enodes
33
+ +-- Position.ts # 2D grid position
34
+ +-- Rotation.ts # Discrete rotation
35
+ +-- types/
36
+ | +-- ComponentType.ts # Component type enum and metadata
37
+ | +-- ENodeSourceType.ts # Voltage/Current source types
38
+ | +-- ENodeType.ts # Pin vs BranchingPoint
39
+ | +-- Identifier.ts # UUID type alias
40
+ +-- simulation/
41
+ | +-- CircuitRunner.ts # Tick-based simulation orchestrator
42
+ | +-- DirtyTracker.ts # Utility used by CircuitRunner to keep tracks of simulation changed components (optimization)
43
+ | +-- EventQueue.ts # Used by CircuitRunner to queue simulation delayed transitions events
44
+ | +-- SimulationState.ts # Data Class representing the simulation state of entire circuit at a given time
45
+ | +-- StateManager.ts # Utility used by CircuitRunner to manage SimulationState updates
46
+ | +-- states/
47
+ | +-- ComponentState.ts # Abstract class for component state
48
+ | +-- ... # Components states
49
+ | +-- behaviors/
50
+ | +-- BehaviorRegistry.ts # Maps component types to behaviors
51
+ | +-- ComponentBehavior.ts # Interface for component logic
52
+ | +-- SwitchBehavior.ts # Switch toggle logic
53
+ | +-- ... # Other components behaviors
54
+ | +-- types/ # Various enums, data classes ...
55
+ +-- setup.ts # Helper to register behaviors
56
+ +-- index.ts # Public API exports
57
+ ```
58
+
59
+ ### Scene Module (`src/scene/`)
60
+
61
+ The scene module handles Three.js visualization and user interaction:
62
+
63
+ ```
64
+ src/scene/
65
+ +-- CircuitEngine.ts # Unified facade with mode switching
66
+ +-- static/
67
+ | +-- CircuitController.ts # Edit mode controller
68
+ | +-- CircuitWriter.ts # Writes scene changes to core model
69
+ | +-- SelectionManager.ts # Tracks selected elements
70
+ | +-- tools/
71
+ | +-- BuildTool.ts # Unified edit tool (state machine)
72
+ | +-- MultiSelectTool.ts # Rectangle selection + bulk operations
73
+ | +-- AddComponentTool.ts # Component placement tool
74
+ +-- simulation/
75
+ | +-- CircuitRunnerController.ts # Simulation mode controller
76
+ +-- shared/
77
+ | +-- AbstractCircuitController.ts # Base controller class
78
+ | +-- EventEmitter.ts # Type-safe event system
79
+ | +-- HoverManager.ts # Raycasting hover detection
80
+ | +-- WireVisualManager.ts # Wire Line2 visuals
81
+ | +-- BranchingPointVisualFactory.ts # BP visuals
82
+ | +-- components/
83
+ | | +-- ComponentVisualFactory.ts # Interface + base class
84
+ | | +-- FactoryRegistry.ts # Maps types to factories
85
+ | | +-- ... # Components factories
86
+ | +-- types.ts # Shared type definitions
87
+ | +-- utils/ # Geometry, camera, lighting utilities
88
+ +-- setup.ts # Helper to register factories
89
+ +-- index.ts # Public API exports
90
+ ```
91
+
92
+ ## Testing strategy
93
+
94
+ Unit tests are divided between core `tests/core` and scene `tests/scene`.
95
+ Coverage goals are :
96
+
97
+ - 80% on `core`: this module is the foundation of the model and simulation logic, hence it must be thoroughly tested
98
+ - 60% on `scene`: coverage goal deliberately less strict to allow for more visualization tinkering
99
+
100
+ ## Commands
101
+
102
+ npm test && npm run lint
103
+
104
+ ## Code Style
105
+
106
+ TypeScript (strict mode), targeting ES2022: Follow standard conventions
107
+ When possible level of nested conditional structures should be minimized by using guard clauses and early returns. Examples below:
108
+
109
+ ```typescript
110
+ /**
111
+ * GOOD practice for minimizing nested conditionals
112
+ * DO that because clearer, reduced learning/debugging overhead
113
+ * @param input
114
+ */
115
+ function goodExample(input: number | null): string {
116
+ if (input === null) {
117
+ // early return in this case
118
+ return 'No input provided';
119
+ }
120
+ // process securized input
121
+ // Main logic (possibly big) continues here without additional nesting
122
+ let output = input * 2;
123
+
124
+ return `Output is ${output}`;
125
+ }
126
+ /**
127
+ * BAD practice that increases nested conditionals
128
+ * DON'T do that because less clear, increased learning/debugging overhead
129
+ * @param input
130
+ */
131
+ function badExample(input: number | null): string {
132
+ if (input !== null) {
133
+ // Main logic (possibly big) embedded under an if :
134
+ let output = input * 2;
135
+ return `Output is ${output}`;
136
+ } else {
137
+ return 'No input provided';
138
+ }
139
+ }
140
+ ```
package/README.md CHANGED
@@ -1,6 +1,87 @@
1
1
  # Simple Circuit Engine
2
2
 
3
- A simple electronic circuit edition and simulation engine written in typescript.
4
- Core module provides circuit data structure and simulation algorithms and scene module provides Three.js circuit scene creation and controls.
3
+ [![NPM Package][npm]][npm-url]
5
4
 
6
- TODO : complete the README.md
5
+ ## TypeScript Educational Electronic circuit library
6
+
7
+ The aim of the project is to provide a simple and easy to use electronic circuit simulation engine for educational purposes.
8
+ It allows users to create, edit and simulate electronic circuits in a web environment using [three.js](https://threejs.org/) for 3D rendering.
9
+
10
+ ![cover](docs/project-cover.png)
11
+
12
+ Visit the [Demo page](https://demo.beyondtheswitch.net/) to see the library in action.
13
+
14
+ ### Use Cases
15
+
16
+ The goal of this project is to vulgarize the bridge between **electronics**, the physical world and **informatic**, the abstract world that runs upon the former.
17
+ The electrical model is deliberately simplified to the bare minimum needed to vulgarize circuits automation:
18
+
19
+ - Electric states in nodes / wires are just two booleans : if there is tension or not and if there is current or not.
20
+ - Components react to changes of inputs discretely with transitional state lasting N ticks (step) before their outputs change.
21
+ - Changes in components states affect conductivity (let pass or not) between their pins.
22
+ - Changes in electrical states throughout the circuit are then propagated using BFS (Breadth First Search) graph algorithm.
23
+
24
+ There are some technicalities about initial simulation state computation (to prevent illegal initial states in feedback loop circuits) but that's pretty much all the simulation model does.
25
+ It's not a realistic physical model but a **discrete graph model** and for the current scope of this project that's enough.
26
+
27
+ However if you're searching for an open-source real electrical simulation model, you might want to check:
28
+
29
+ - [circuitjs](https://github.com/sharpie7/circuitjs1) for a web implementation
30
+ - The very complete [ngspice](https://ngspice.sourceforge.io/) (desktop) which is [SPICE](https://en.wikipedia.org/wiki/SPICE) compatible.
31
+
32
+ ### Usage
33
+
34
+ In addition to `simple-circuit-engine` you must import the `three` and `lil-gui` libraries in your project to use Simple Circuit Engine.
35
+ This code set up the main CircuitEngine instance in edit mode on a new Circuit, handles THREE.js objects creation and rendering/animation in the canva-container HTML element.
36
+
37
+ ```javascript
38
+ import { WebGLRenderer } from 'three';
39
+ import { Circuit, BehaviorRegistry, registerBasicComponentsBehaviors } from 'simple-circuit-engine/core';
40
+ import { CircuitEngine, engineOptions, FactoryRegistry, DefaultVisualFactory, registerBasicComponentsFactories } from 'simple-circuit-engine/scene';
41
+
42
+ // Create component factory registry with all basic visual factories (for scene objects creation - rendering
43
+ const componentsFactoryRegistry = registerBasicComponentsFactories(new FactoryRegistry(new DefaultVisualFactory()));
44
+ // Create behavior registry with all basic component behaviors (for simulation)
45
+ const behaviorRegistry = registerBasicComponentsBehaviors(new BehaviorRegistry());
46
+
47
+ // Initialize CircuitEngine
48
+ // It creates THREE.js scene, camera, controls, lights, etc
49
+ // and the interactive controllers (edit and simulation) of simple-circuit-engine
50
+ const container = document.getElementById('canva-container')!;
51
+ const engine = new CircuitEngine(componentsFactoryRegistry, behaviorRegistry);
52
+ engine.initialize(container, engineOptions());
53
+ // set engine circuit to a new empty circuit (which it does by default)
54
+ engine.setCircuit(new Circuit());
55
+
56
+ // Create and setup WebGL renderer
57
+ const renderer = new WebGLRenderer({ antialias: true, alpha: false });
58
+ renderer.setClearColor(0x1a1a2e);
59
+ const width = window.innerWidth, height = window.innerHeight;
60
+ renderer.setSize(container.clientWidth, container.clientHeight);
61
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
62
+ // Append renderer to DOM
63
+ container.appendChild(renderer.domElement);
64
+
65
+ // Animation loop to animate the circuit scene in the canvas container
66
+ function animate() {
67
+ requestAnimationFrame(animate);
68
+ engine.getControls().update();
69
+ renderer.render(engine.getScene(), engine.getCamera());
70
+ }
71
+ animate();
72
+ ```
73
+
74
+ If this goes well, you should see a 10\*10 3D grid with some lights and camera mapControls in the canvas container.
75
+
76
+ ### Contributing
77
+
78
+ Feel free to open issues or submit pull requests for bug fixes, improvements, or new features.
79
+ Particularly, since this project is at early stage issues reports and discussions about desired features are very welcome!
80
+ If you're interested in contributing, please read the [CONTRIBUTING](CONTRIBUTING.md) guide for more information.
81
+
82
+ ### License
83
+
84
+ This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
85
+
86
+ [npm]: https://img.shields.io/npm/v/simple-circuit-engine
87
+ [npm-url]: https://www.npmjs.com/package/simple-circuit-engine
@@ -1052,7 +1052,7 @@ const U = {
1052
1052
  /**
1053
1053
  * Default simulation speed in ticks per second
1054
1054
  */
1055
- DEFAULT_TPS: 2,
1055
+ DEFAULT_TPS: 3,
1056
1056
  /**
1057
1057
  * Default tick interval in milliseconds (1000 / DEFAULT_TPS)
1058
1058
  */
@@ -1474,4 +1474,4 @@ export {
1474
1474
  x as m,
1475
1475
  L as s
1476
1476
  };
1477
- //# sourceMappingURL=CircuitRunner-CAeE31M5.js.map
1477
+ //# sourceMappingURL=CircuitRunner-FXM_s5ll.js.map