SILICON
Loading...
Searching...
No Matches
interactiveWireRouter.cpp
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
19
20#include <algorithm>
21#include <array>
22#include <cmath>
23#include <map>
24#include <ranges>
25#include <set>
26#include <utility>
27
28#include <libavoid/libavoid.h>
29#include <libavoid/qtgeomtypes.h>
30
34
35namespace SILICON::ui {
36namespace {
37
38 using PointKey = std::pair<qreal, qreal>;
39 using JunctionKey = std::pair<uint64_t, PointKey>;
40
41 inline PointKey key(const QPointF point)
42 {
43 return {point.x(), point.y()};
44 }
45
46 inline QPointF point(const PointKey& value)
47 {
48 return {value.first, value.second};
49 }
50
51 inline bool onEdge(const QPointF p, const QPointF a, const QPointF b)
52 {
53 return core::pointOnOrthogonalRoute(p, std::array{a, b});
54 }
55
56 // A branch endpoint can lie inside a trunk edge. Split there so both connectors
57 // share a libavoid junction, retaining the point at the end of each adjacent piece.
58 std::vector<std::vector<QPointF>> splitAtJunctions(const std::span<const QPointF> route,
59 const std::set<PointKey>& junctions)
60 {
61 if (route.empty())
62 return {};
63
64 std::vector<std::vector<QPointF>> result;
65 std::vector<QPointF> current{route.front()};
66 std::vector<QPointF> between;
67 const auto append = [&](const QPointF p) {
68 current.push_back(p);
69 if (junctions.contains(key(p)))
70 result.push_back(std::exchange(current, {p}));
71 };
72
73 for (auto [a, b] : route | SILICON::views::adjacent<2>) {
74 between.clear();
75 for (const auto& candidate : junctions) {
76 if (const QPointF p = point(candidate); p != a && p != b && onEdge(p, a, b))
77 between.push_back(p);
78 }
79
80 // Visit junctions in route order, including edges that run left or upward.
81 std::ranges::sort(between, std::less{}, [a](const QPointF p) {
82 return std::abs(p.x() - a.x()) + std::abs(p.y() - a.y());
83 });
84
85 for (const QPointF p : between)
86 append(p);
87 append(b);
88 }
89 if (current.size() >= 2)
90 result.push_back(std::move(current));
91 return result;
92 }
93
94 bool electricallyAttached(const RoutingSegment& selected, const RoutingSegment& other,
95 const QPointF tip)
96 {
97 // Callers already check geometric contact. Use shared vertex IDs when available;
98 // snapshots without electrical metadata fall back to that geometric contact.
99 if (selected.electricalVertices.empty() || other.electricalVertices.empty())
100 return true;
101 return std::ranges::any_of(selected.electricalVertices, [&](const auto& vertex) {
102 return vertex.first && vertex.second == tip
103 && std::ranges::find(other.electricalVertices, vertex)
104 != other.electricalVertices.end();
105 });
106 }
107
108 void setFixedRoute(Avoid::ConnRef& connector, const std::span<const QPointF> points)
109 {
110 Avoid::PolyLine fixed;
111 fixed.ps.reserve(points.size());
112 for (const QPointF position : points)
113 fixed.ps.push_back(Avoid::pointFromQPointF(position));
114 connector.setFixedRoute(fixed);
115 }
116
117 Avoid::JunctionRef* fixedJunction(Avoid::Router& router, const QPointF position)
118 {
119 auto* junction = new Avoid::JunctionRef(&router, Avoid::pointFromQPointF(position));
120 junction->setPositionFixed(true);
121 return junction;
122 }
123
124 void addComponentPins(Avoid::Router& router, const RoutingComponent& component,
125 const QPointF displacement,
126 std::map<PointKey, Avoid::ConnEnd>& portEnds, unsigned int& pinId)
127 {
128 const QRectF original = component.bounds.normalized();
129 qreal left = original.left(), top = original.top();
130 qreal right = original.right(), bottom = original.bottom();
131 for (const QPointF port : component.ports) {
132 left = std::min(left, port.x());
133 top = std::min(top, port.y());
134 right = std::max(right, port.x());
135 bottom = std::max(bottom, port.y());
136 }
137
138 // Include ports outside the component's collision bounds in the pin shape.
139 const QRectF pinBounds(QPointF(left, top), QPointF(right, bottom));
140 auto* shape = new Avoid::ShapeRef(
141 &router, Avoid::rectangleFromQRectF(pinBounds.translated(displacement)));
142 for (const QPointF port : component.ports) {
143 const QPointF offset = port - pinBounds.topLeft();
144 new Avoid::ShapeConnectionPin(shape, pinId, offset.x(), offset.y(), false, 0.0,
145 Avoid::ConnDirAll);
146 // Lookup uses snapshot coordinates; the pin follows the translated shape.
147 portEnds.emplace(key(port), Avoid::ConnEnd(shape, pinId++));
148 }
149 }
150
151 std::optional<std::vector<QPointF>>
152 extractRoute(const std::span<Avoid::ConnRef* const> connectors, const qreal gridSize)
153 {
154 std::vector<QPointF> points;
155 for (auto* connector : connectors) {
156 if (!connector->hasValidRoute() || connector->hasCrossingObstacles())
157 return std::nullopt;
158
159 const auto routed = core::extractOrthogonalRoute(*connector, gridSize);
160 const auto [source, destination] = connector->endpointConnEnds();
161 // Grid snapping must preserve the exact connector endpoints.
162 if (routed.size() < 2 || routed.front() != Avoid::toQPointF(source.position())
163 || routed.back() != Avoid::toQPointF(destination.position()))
164 return std::nullopt;
165 // Adjacent pieces share one junction; append it only once.
166 points.append_range(routed | std::views::drop(points.empty() ? 0 : 1));
167 }
168
169 // LocalWireEditor::valid() checks the assembled geometry for changed routes.
170 return core::canonicalizeOrthogonalRoute(std::move(points));
171 }
172
173 bool straightSpanPresent(const std::span<const QPointF> route, QPointF a, QPointF b)
174 {
175 if (a == b)
176 return core::pointOnOrthogonalRoute(a, route);
177
178 // Check if any line segment contains both 'a' and 'b'
179 return std::ranges::any_of(route | SILICON::views::adjacent<2>, [&](const auto& seg) {
180 auto [p1, p2] = seg;
181 return onEdge(a, p1, p2) && onEdge(b, p1, p2);
182 });
183 }
184
185} // namespace
186
188 std::vector<RoutingSegment> segments,
189 const qreal gridSize)
190 : components(std::move(components)), segments(std::move(segments)), gridSize(gridSize)
191{
192}
193
195 const std::span<const ComponentRouteMove> moves) const
196{
197 if (auto local = LocalWireEditor(components, segments, gridSize).moveComponents(moves))
198 return local;
199 Request request;
200 request.moves = moves;
201 return routeWithLibavoid(request);
202}
203
205 const uint64_t segmentId, const std::size_t bendIndex, const QPointF position) const
206{
207 if (auto local = LocalWireEditor(components, segments, gridSize)
208 .moveBend(segmentId, bendIndex, position))
209 return local;
210 Request request;
211 request.handle = Handle::Bend;
212 request.segmentId = segmentId;
213 request.index = bendIndex;
214 request.value = position;
215 return routeWithLibavoid(request);
216}
217
220 const std::size_t endpointIndex,
221 const QPointF position) const
222{
223 Request request;
224 request.handle = Handle::Endpoint;
225 request.segmentId = segmentId;
226 request.index = endpointIndex;
227 request.value = position;
228 return routeWithLibavoid(request);
229}
230
233 const std::size_t edgeIndex,
234 const QPointF displacement) const
235{
236 if (auto local = LocalWireEditor(components, segments, gridSize)
237 .moveEdge(segmentId, edgeIndex, displacement))
238 return local;
239 Request request;
240 request.handle = Handle::Edge;
241 request.segmentId = segmentId;
242 request.index = edgeIndex;
243 request.value = displacement;
244 return routeWithLibavoid(request);
245}
246
249{
250 // Validate before inspecting endpoints or allocating libavoid objects.
251 // Collect endpoints per net so coincident points on different nets stay separate.
252 std::map<uint64_t, std::set<PointKey>> netJunctions;
253 for (const auto& segment : segments) {
254 if (segment.points.size() < 2 || !core::isOrthogonalRoute(segment.points))
255 return std::nullopt;
256 auto& junctions = netJunctions[segment.net];
257 junctions.insert(key(segment.points.front()));
258 junctions.insert(key(segment.points.back()));
259 }
260
261 const bool hasHandle = request.handle != Handle::None;
262 const auto selected =
263 hasHandle ? std::ranges::find(segments, request.segmentId, &RoutingSegment::id)
264 : segments.end();
265 if (hasHandle) {
266 if (selected == segments.end())
267 return std::nullopt;
268 const auto last = selected->points.size() - 1;
269 switch (request.handle) {
270 case Handle::Bend:
271 if (request.index == 0 || request.index >= last)
272 return std::nullopt;
273 break;
274 case Handle::Endpoint:
275 if (request.index != 0 && request.index != last)
276 return std::nullopt;
277 break;
278 case Handle::Edge:
279 if (request.index >= last)
280 return std::nullopt;
281 break;
282 case Handle::None: break;
283 }
284 }
285
286 QPointF edgeA, edgeB, edgeMove;
287 if (request.handle == Handle::Edge) {
288 edgeA = selected->points[request.index];
289 edgeB = selected->points[request.index + 1];
290 edgeMove = request.value;
291
292 // Edge dragging changes only the coordinate perpendicular to the edge.
293 if (edgeA.y() == edgeB.y())
294 edgeMove.setX(0);
295 else
296 edgeMove.setY(0);
297 }
298
299 auto movedBounds = request.moves | std::views::transform([](const auto& m) {
300 return std::pair{m.id, m.bounds.normalized()};
301 })
302 | std::ranges::to<std::map>();
303
304 std::set<uint64_t> unlockedNets;
305 std::set<uint64_t> unlockedSegments;
306
307 const auto touchesHandle = [&](const QPointF tip) {
308 return request.handle == Handle::Bend ? tip == selected->points[request.index]
309 : onEdge(tip, edgeA, edgeB);
310 };
311
312 // Bend and edge drags also move attached branches. Endpoint drags detach just
313 // the selected endpoint, leaving the original junction and its other wires fixed.
314 if (hasHandle) {
315 unlockedSegments.insert(selected->id);
316 if (request.handle == Handle::Bend || request.handle == Handle::Edge) {
317 for (const auto& segment : segments) {
318 if (segment.id == selected->id || segment.net != selected->net)
319 continue;
320
321 const auto attached = [&](const QPointF tip) {
322 return touchesHandle(tip) && electricallyAttached(*selected, segment, tip);
323 };
324 if (attached(segment.points.front()) || attached(segment.points.back())) {
325 unlockedSegments.insert(segment.id);
326 }
327 }
328 }
329 }
330
331 // Component moves can affect an entire attached net, including its fanout.
332 // Index original port positions once instead of scanning every port per segment.
333 std::set<PointKey> movedPorts;
334 for (const auto& component : components) {
335 if (!movedBounds.contains(component.id))
336 continue;
337 for (const QPointF port : component.ports)
338 movedPorts.insert(key(port));
339 }
340 for (const auto& segment : segments) {
341 if (movedPorts.contains(key(segment.points.front()))
342 || movedPorts.contains(key(segment.points.back())))
343 unlockedNets.insert(segment.net);
344 }
345
346 // Cache eligibility in snapshot order for obstacle checks and connector routing.
347 const auto unlocked = segments
348 | std::views::transform([&](const RoutingSegment& segment) {
349 return unlockedNets.contains(segment.net)
350 || unlockedSegments.contains(segment.id);
351 })
352 | std::ranges::to<std::vector<bool>>();
353
354 // A moved component cannot push an unrelated net out of its way.
355 for (const auto& [segment, canRoute] : std::views::zip(segments, unlocked)) {
356 if (canRoute)
357 continue;
358 for (const auto& moveBounds : movedBounds | std::views::values) {
360 std::array{moveBounds}))
361 return std::nullopt;
362 }
363 }
364
365 Avoid::Router router(Avoid::OrthogonalRouting);
367
368 std::map<PointKey, Avoid::ConnEnd> portEnds;
369 unsigned int pinId = 1;
370
371 for (const auto& component : components) {
372 QPointF displacement{};
373 if (const auto it = movedBounds.find(component.id); it != movedBounds.end())
374 displacement = it->second.topLeft() - component.bounds.normalized().topLeft();
375 addComponentPins(router, component, displacement, portEnds, pinId);
376 }
377
378 // Keep original coordinates as lookup keys even when a drag moves the junction.
379 // Component ports already have shape pins and do not need standalone junctions.
380 std::map<JunctionKey, Avoid::JunctionRef*> junctionRefs;
381 for (const auto& [net, positions] : netJunctions) {
382 for (const PointKey& position : positions) {
383 if (portEnds.contains(position))
384 continue;
385
386 QPointF destination = point(position);
387 if (request.handle == Handle::Bend && net == selected->net
388 && destination == selected->points[request.index])
389 destination = request.value;
390
391 if (request.handle == Handle::Edge && net == selected->net
392 && onEdge(destination, edgeA, edgeB) && destination != selected->points.front()
393 && destination != selected->points.back())
394 destination += edgeMove;
395
396 junctionRefs.emplace(JunctionKey{net, position},
397 fixedJunction(router, destination));
398 }
399 }
400
401 // A separate junction lets one endpoint leave a shared junction or component pin
402 // without relocating the other connectors attached to it.
403 Avoid::JunctionRef* movedEndpoint = nullptr;
404 if (request.handle == Handle::Endpoint)
405 movedEndpoint = fixedJunction(router, request.value);
406
407 auto endFor = [&](const uint64_t net, const QPointF position) {
408 if (auto port = portEnds.find(key(position)); port != portEnds.end())
409 return port->second;
410 return Avoid::ConnEnd(junctionRefs.at(JunctionKey{net, key(position)}));
411 };
412
413 // Keep connector groups in snapshot order; the router owns the connectors.
414 // Include fixed pieces so libavoid considers them when routing movable wires.
415 std::vector<std::vector<Avoid::ConnRef*>> connectorsBySegment(segments.size());
416
417 for (const auto& [segment, canRoute, connectors] :
418 std::views::zip(segments, unlocked, connectorsBySegment)) {
419 const bool isSelected = hasHandle && segment.id == request.segmentId;
420 const bool selectedEndpoint = isSelected && request.handle == Handle::Endpoint;
421 const auto pieces = splitAtJunctions(segment.points, netJunctions.at(segment.net));
422 connectors.reserve(pieces.size());
423 for (const auto& piece : pieces) {
424 const bool moveFirst = selectedEndpoint && request.index == 0
425 && piece.front() == segment.points.front();
426 const bool moveLast = selectedEndpoint && request.index + 1 == segment.points.size()
427 && piece.back() == segment.points.back();
428
429 auto* connector = new Avoid::ConnRef(
430 &router,
431 moveFirst ? Avoid::ConnEnd(movedEndpoint) : endFor(segment.net, piece.front()),
432 moveLast ? Avoid::ConnEnd(movedEndpoint) : endFor(segment.net, piece.back()));
433 connector->setRoutingType(Avoid::ConnType_Orthogonal);
434
435 const bool selectedPiece = isSelected && [&]() {
436 switch (request.handle) {
437 case Handle::Bend:
438 return core::pointOnOrthogonalRoute(selected->points[request.index], piece);
439 case Handle::Edge: return std::ranges::any_of(piece, touchesHandle);
440 case Handle::Endpoint:
441 return piece.front() == selected->points[request.index]
442 || piece.back() == selected->points[request.index];
443 case Handle::None: return false;
444 }
445 return false;
446 }();
447
448 if (!canRoute || (isSelected && !selectedPiece)) {
449 // A handle edit may affect only part of a segment split by junctions.
450 setFixedRoute(*connector, piece);
451 } else if (selectedPiece && request.handle == Handle::Bend
452 && piece.front() != segment.points[request.index]
453 && piece.back() != segment.points[request.index]) {
454 // A bend at a piece endpoint was handled by moving its junction above.
455 // An interior bend needs a checkpoint to force the route through the target.
456 connector->setRoutingCheckpoints(
457 {Avoid::Checkpoint(Avoid::pointFromQPointF(request.value))});
458 } else if (selectedPiece && request.handle == Handle::Edge) {
459 // Constrain the translated edge while leaving terminals in place; libavoid
460 // can add doglegs between those terminals and the displaced span.
461 std::vector<Avoid::Checkpoint> checkpoints;
462
463 for (auto [p1, p2] : piece | SILICON::views::adjacent<2>) {
464 if (!onEdge(p1, edgeA, edgeB) || !onEdge(p2, edgeA, edgeB))
465 continue;
466
467 for (const QPointF cp : {p1 + edgeMove, p2 + edgeMove}) {
468 if (cp != piece.front() && cp != piece.back())
469 checkpoints.emplace_back(Avoid::pointFromQPointF(cp));
470 }
471 }
472 if (!checkpoints.empty())
473 connector->setRoutingCheckpoints(checkpoints);
474 }
475 connectors.push_back(connector);
476 }
477 }
478
479 // Route all connectors together so obstacle avoidance and nudging see every wire.
480 router.processTransaction();
481 std::vector<RoutedSegment> result;
482 std::vector<RoutedSegment> changes;
483 result.reserve(segments.size());
484
485 for (const auto& [segment, canRoute, connectors] :
486 std::views::zip(segments, unlocked, connectorsBySegment)) {
487 if (!canRoute) {
488 // Preserve the original representation of wires outside the edit's scope.
489 result.push_back({segment.id, segment.points});
490 continue;
491 }
492
493 auto routePoints = extractRoute(connectors, gridSize);
494 if (!routePoints)
495 return std::nullopt;
496 if (*routePoints != segment.points)
497 changes.push_back({segment.id, *routePoints});
498 result.push_back({segment.id, std::move(*routePoints)});
499 }
500
501 // Check the requested geometry after snapping and canonicalization, which can
502 // otherwise remove a checkpoint or shorten the dragged edge.
503 if (request.handle == Handle::Bend || request.handle == Handle::Edge) {
504 const auto& routePoints = result[selected - segments.begin()].points;
505 if (request.handle == Handle::Bend) {
506 if (!core::pointOnOrthogonalRoute(request.value, routePoints))
507 return std::nullopt;
508 } else if (!straightSpanPresent(routePoints, edgeA + edgeMove, edgeB + edgeMove)) {
509 return std::nullopt;
510 }
511 }
512
513 // Validate only changed geometry against the full snapshot. Untouched segments
514 // remain available to valid() without triggering checks against each other.
515 // Use destination component geometry so vacated bounds are no longer obstacles.
516 auto movedComponents = components;
517 for (auto& component : movedComponents) {
518 if (const auto it = movedBounds.find(component.id); it != movedBounds.end()) {
519 const QPointF delta =
520 it->second.topLeft() - component.bounds.normalized().topLeft();
521 component.bounds = it->second;
522 for (auto& port : component.ports)
523 port += delta;
524 }
525 }
526 if (!LocalWireEditor(movedComponents, segments, gridSize)
527 .valid(changes, request.segmentId))
528 return std::nullopt;
529
530 return result;
531}
532
533} // namespace SILICON::ui
RoutePreview routeWithLibavoid(Request request) const
Routes a validated request with libavoid and checks the resulting geometry.
RoutePreview routeWireEdge(uint64_t segmentId, std::size_t edgeIndex, QPointF displacement) const
Moves an edge perpendicular to its original direction.
std::vector< RoutingComponent > components
std::vector< RoutingSegment > segments
RoutePreview routeWireEndpoint(uint64_t segmentId, std::size_t endpointIndex, QPointF position) const
Routes a wire with one endpoint moved to a new position.
RoutePreview routeComponents(std::span< const ComponentRouteMove > moves) const
Routes wires around moved components while preserving their connections.
InteractiveWireRouter(std::vector< RoutingComponent > components, std::vector< RoutingSegment > segments, qreal gridSize)
Owns a snapshot used as the starting geometry for every routing preview.
RoutePreview routeWireBend(uint64_t segmentId, std::size_t bendIndex, QPointF position) const
Moves an interior bend and routes electrically attached branches.
RTLIL::SigSpec port(RTLIL::Module *module, RTLIL::Cell *cell, RTLIL::IdString key, int expected)
std::vector< QPointF > canonicalizeOrthogonalRoute(std::vector< QPointF > points)
Removes consecutive duplicates and redundant collinear interior points.
bool orthogonalRouteCrossesObstacleInterior(const std::span< const QPointF > route, const std::span< const QRectF > obstacles)
void configureOrthogonalRouter(Avoid::Router &router, const qreal gridSize)
Applies SILICON's shared orthogonal-routing policy to a libavoid router.
std::vector< QPointF > extractOrthogonalRoute(Avoid::ConnRef &connector, const qreal gridSize)
Extracts, grid-snaps, and canonicalizes a libavoid display route.
bool pointOnOrthogonalRoute(const QPointF point, const std::span< const QPointF > route)
Returns whether point lies on an orthogonal polyline.
bool isOrthogonalRoute(const std::span< const QPointF > points)
Returns whether every consecutive route segment is axis-aligned.
QVariant value(const QSettings &settings, const Definition &setting)
Reads a setting value, falling back to its declared default when unset.
std::optional< std::vector< RoutedSegment > > RoutePreview
constexpr auto adjacent
std::span< const ComponentRouteMove > moves