SILICON
Loading...
Searching...
No Matches
wireManager.hpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#pragma once
19
20#include <functional>
21#include <compare>
22#include <cstdint>
23#include <memory>
24#include <map>
25#include <span>
26#include <utility>
27#include <vector>
28
29#include <boost/graph/adjacency_list.hpp>
30
31#include <QPointF>
32#include <QRectF>
33
34#include <core/wire.hpp>
35
36class QGraphicsScene;
37
38namespace SILICON::ui {
39
40class GraphicalWire;
42
44struct RoutedWire {
46 std::vector<QPointF> points;
47};
48
49/* WireManager
50 * Central orchestrator for GraphicalWires and GraphicalWireSegments.
51 *
52 * Responsibilities:
53 * - Owns all GraphicalWires.
54 * - Group segments when either endpoint touches another segment's route.
55 * - Split groups when edited geometry separates them.
56 */
57
59public:
60 enum class Change : uint8_t { None = 0, Geometry = 1, Connectivity = 2, Electrical = 4 };
61 using ChangeCallback = std::function<void(Change)>;
62 enum class VertexKind : uint8_t { FreeEndpoint, Junction, Port };
64 uint64_t componentId;
65 uint32_t portIndex;
66 bool output;
68 auto operator<=>(const PortReference&) const = default;
69 };
71 uint64_t id;
72 QPointF position;
74 std::vector<PortReference> ports;
75 };
76 struct TopologyEdge {
77 uint64_t id;
78 uint64_t segmentId;
79 uint64_t firstVertex;
80 uint64_t lastVertex;
81 std::vector<QPointF> points;
82 };
83 using TopologyVertexMap = std::map<uint64_t, TopologyVertex>;
84 using TopologyEdgeMap = std::map<uint64_t, TopologyEdge>;
86 uint64_t firstVertex = 0;
87 uint64_t lastVertex = 0;
88 std::vector<std::pair<uint64_t, QPointF>> junctions;
89 std::vector<uint64_t> edgeIds;
90 };
91 struct PortAnchor {
92 uint64_t componentId;
93 uint32_t portIndex;
94 bool output;
95 QPointF position;
96 };
97 using PortAnchorProvider = std::function<std::vector<PortAnchor>()>;
100 uint64_t segmentId;
102 };
103
105 [[nodiscard]] const TopologyVertexMap& topologyVertices() const { return vertices; }
107 [[nodiscard]] const TopologyEdgeMap& topologyEdges() const { return edges; }
109 [[nodiscard]] const SegmentTopology& topologyFor(uint64_t segmentId) const;
112 { portAnchors = std::move(anchors); }
113
114 void refreshPortAnchors();
116 void rebuildFromGeometry();
118 class Edit {
119 public:
127 ~Edit() noexcept;
129 Edit(const Edit&) = delete;
131 Edit& operator=(const Edit&) = delete;
137 void commit();
139 void cancel();
140
141 private:
143 uint64_t segmentId;
144 std::vector<QPointF> originalPoints;
145 };
146
147 class Batch {
148 public:
150 explicit Batch(WireManager& manager) : manager(manager) { ++manager.batchDepth; }
152 ~Batch() noexcept { if (active) manager.discardBatch(); }
154 Batch(const Batch&) = delete;
156 Batch& operator=(const Batch&) = delete;
158 void commit()
159 {
160 if (!active)
161 return;
162 active = false;
163 try {
164 manager.finishBatch();
165 } catch (...) {
166 manager.discardBatch();
167 throw;
168 }
169 }
170 private:
172 bool active = true;
173 };
174
175 WireManager() = default;
177
178 WireManager(const WireManager&) = delete;
182
183 std::shared_ptr<GraphicalWire> createWire(unsigned int busSize = 1);
184 void removeWire(GraphicalWire* wire);
185 [[nodiscard]] const std::vector<std::shared_ptr<GraphicalWire>>& wires() const
186 {
187 return managedWires;
188 }
189
190 // Register an existing segment. A bulk load can defer geometry reconstruction.
191 void addSegment(GraphicalWireSegment* segment, bool updateTopology = true);
192
193 // Unregister a segment. If its GraphicalWire becomes empty, the wire is
194 // removed.
195 void removeSegment(GraphicalWireSegment* segment);
196 // Recalculate membership after changing a segment's route.
198
204 [[nodiscard]] bool commitSegmentTranslations(
205 std::span<const std::pair<uint64_t, QPointF>> translations);
206
207 // Recalculate the junction flags for a specific segment
209 bool includeNeighborhood = true) const;
210
211 // Recalculate all junction flags across every registered segment.
212 void calculateJunctions() const;
213
214 // Find a segment whose body or endpoint is at `scenePoint`.
215 [[nodiscard]] GraphicalWireSegment*
216 segmentAtPoint(QPointF scenePoint,
217 const GraphicalWireSegment* ignoredSegment = nullptr) const;
218
219 // Returns a set of segments near the argument (and including it) using Qt's colliding
220 // items [O(log n)]
221 static std::vector<GraphicalWireSegment*>
223
225 [[nodiscard]] const std::vector<GraphicalWireSegment*>& getSegments() const
226 {
227 return allSegments;
228 }
229
231 void clearSegments(QGraphicsScene& scene);
232
234 void replaceSegments(QGraphicsScene& scene, std::span<const RoutedWire> routedSegments);
235
236 // Check whether `segment`'s first or last endpoint lies on `other`'s body
237 // (or vice-versa). Used for T-junction and connectivity detection.
238 [[nodiscard]] static bool segmentsTouching(const GraphicalWireSegment* segment,
239 const GraphicalWireSegment* other);
240
246 {
247 onChanged = std::move(cb);
248 }
249
255 {
257 }
258
261
262 void clear();
263
264private:
265 // Parallel edges represent distinct routed pieces between the same contacts.
266 using TopologyGraph = boost::adjacency_list<boost::vecS, boost::vecS,
267 boost::undirectedS, uint64_t, uint64_t>;
268 using VertexDescriptor = boost::graph_traits<TopologyGraph>::vertex_descriptor;
270 std::map<uint64_t, VertexDescriptor> vertexDescriptors;
271
272 std::vector<std::shared_ptr<GraphicalWire>> managedWires;
273 std::vector<GraphicalWireSegment*> allSegments;
274
277 unsigned int batchDepth = 0;
278 bool rebuildPending = false;
279 mutable uint8_t pendingChanges = 0;
280 std::vector<uint64_t> pendingEdits;
283 std::map<uint64_t, SegmentTopology> segmentTopology;
284 uint64_t nextVertexId = 1;
285 uint64_t nextEdgeId = 1;
287
289 void calculateJunctionsFor(std::span<GraphicalWireSegment* const> segments) const;
291 void finishBatch();
293 void discardBatch() noexcept;
295 void notify(Change change) const;
297 GraphicalWireSegment* registeredSegment(uint64_t id) const;
299 uint64_t createVertex(QPointF position, VertexKind kind = VertexKind::FreeEndpoint);
302};
303
304} // namespace SILICON::ui
The visible, selectable polyline wire on the diagram scene.
Logical wire entity that groups segments sharing the same bus.
Represents a connection point on a component.
~Batch() noexcept
Discards an unfinished batch's pending work without restoring geometry.
Batch & operator=(const Batch &)=delete
Disables copy assignment of the batch lifecycle guard.
void commit()
Finishes the batch, rebuilding topology and notifying at the outermost level.
Batch(const Batch &)=delete
Disables copying of the batch lifecycle guard.
Batch(WireManager &manager)
Begins a batch that defers topology rebuilds and change notifications.
void cancel()
Restores the original local route if the segment is still registered.
Edit & operator=(const Edit &)=delete
Disables copy assignment of a route edit.
std::vector< QPointF > originalPoints
Edit(WireManager &manager, GraphicalWireSegment *segment)
Captures a registered segment's original local route for a preview edit.
~Edit() noexcept
Cancels an uncommitted edit and suppresses exceptions during cleanup.
Edit(const Edit &)=delete
Disables copying of an edit that owns route restoration.
void commit()
Validates the preview route and queues its topology rebuild.
void addSegment(GraphicalWireSegment *segment, bool updateTopology=true)
void calculateJunctions() const
void replaceSegments(QGraphicsScene &scene, std::span< const RoutedWire > routedSegments)
Replaces all managed graphical wire segments with routed segments.
std::map< uint64_t, TopologyEdge > TopologyEdgeMap
static bool segmentsTouching(const GraphicalWireSegment *segment, const GraphicalWireSegment *other)
GraphicalWireSegment * segmentAtPoint(QPointF scenePoint, const GraphicalWireSegment *ignoredSegment=nullptr) const
std::vector< GraphicalWireSegment * > allSegments
const TopologyEdgeMap & topologyEdges() const
Borrows the topology edge map until the topology is modified.
void finishBatch()
Finishes one batch level and flushes pending edits and changes at the outermost level.
void notifyTopologyChanged() const
Force execute the callback natively mapped to topological splits, merges, or drags.
boost::graph_traits< TopologyGraph >::vertex_descriptor VertexDescriptor
void removeSegment(GraphicalWireSegment *segment)
WireManager(WireManager &&)=delete
WireManager & operator=(WireManager &&)=delete
const TopologyVertexMap & topologyVertices() const
Borrows the topology vertex map until the topology is modified.
const std::vector< std::shared_ptr< GraphicalWire > > & wires() const
boost::adjacency_list< boost::vecS, boost::vecS, boost::undirectedS, uint64_t, uint64_t > TopologyGraph
void rebuildTopologyEdges()
Rebuilds graph edges by splitting each segment route at its electrical vertices.
std::vector< uint64_t > pendingEdits
std::vector< std::shared_ptr< GraphicalWire > > managedWires
const std::vector< GraphicalWireSegment * > & getSegments() const
static std::vector< GraphicalWireSegment * > segmentNeighbors(GraphicalWireSegment *segment)
void discardBatch() noexcept
Drops one batch level and clears pending work when no batch remains.
TopologyVertexMap vertices
std::map< uint64_t, SegmentTopology > segmentTopology
const SegmentTopology & topologyFor(uint64_t segmentId) const
Borrows segment topology until rebuilt; missing segments return an empty topology.
std::shared_ptr< GraphicalWire > createWire(unsigned int busSize=1)
GraphicalWireSegment * registeredSegment(uint64_t id) const
Returns the registered segment with the given identifier, or nullptr.
WireManager(const WireManager &)=delete
std::function< std::vector< PortAnchor >()> PortAnchorProvider
void calculateJunctionsFor(std::span< GraphicalWireSegment *const > segments) const
Updates endpoint junction flags for the supplied registered segments.
std::map< uint64_t, TopologyVertex > TopologyVertexMap
void refreshPortAnchors()
Refreshes port references after components enter or leave the scene.
void setChangedCallback(ChangeCallback cb)
Sets the callback for geometry, connectivity, and electrical changes.
std::map< uint64_t, VertexDescriptor > vertexDescriptors
void updateSegmentTopology(GraphicalWireSegment *segment)
void removeWire(GraphicalWire *wire)
void rebuildFromGeometry()
Derives electrical groups, junctions, and port vertices from segment geometry.
WireManager & operator=(const WireManager &)=delete
PortAnchorProvider portAnchors
void notify(Change change) const
Delivers change flags to the callback or accumulates them in an active batch.
uint64_t createVertex(QPointF position, VertexKind kind=VertexKind::FreeEndpoint)
Creates a topology vertex and attaches matching port anchors.
void clearSegments(QGraphicsScene &scene)
Deletes all managed graphical wire segments from scene.
void notifyElectricalChanged() const
Notifies listeners of an electrical change, deferring delivery within a batch.
std::function< void(Change)> ChangeCallback
bool commitSegmentTranslations(std::span< const std::pair< uint64_t, QPointF > > translations)
Rebuilds connectivity after segment positions have been translated.
ChangeCallback onChanged
Callback invoked when wire topology changes (splits, merges, drags).
void setPortAnchors(PortAnchorProvider anchors)
Sets the provider of current component port anchors in scene coordinates.
Scene-coordinate wire path produced by an automatic router.
std::vector< QPointF > points
auto operator<=>(const PortReference &) const =default
Compares references by component identifier, port index, and direction.
std::vector< std::pair< uint64_t, QPointF > > junctions
std::vector< PortReference > ports