-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathViaPossibilitiesSolver2.ts
More file actions
463 lines (418 loc) · 16.4 KB
/
ViaPossibilitiesSolver2.ts
File metadata and controls
463 lines (418 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
import {
Bounds,
Point,
Point3,
clamp,
distance,
getSegmentIntersection,
midpoint,
pointToSegmentDistance,
segmentToSegmentMinDistance,
} from "@tscircuit/math-utils"
import { GraphicsObject } from "graphics-debug"
import { NodeWithPortPoints } from "lib/types/high-density-types"
import { cloneAndShuffleArray } from "lib/utils/cloneAndShuffleArray"
import { generateColorMapFromNodeWithPortPoints } from "lib/utils/generateColorMapFromNodeWithPortPoints"
import { getBoundsFromNodeWithPortPoints } from "lib/utils/getBoundsFromNodeWithPortPoints"
import { PortPairMap, getPortPairMap } from "lib/utils/getPortPairs"
import { BaseSolver } from "../BaseSolver"
import { safeTransparentize } from "../colors"
export type ConnectionName = string
export interface Segment {
start: Point3
end: Point3
connectionName: string
}
export interface ViaPossibilities2HyperParameters {
SHUFFLE_SEED?: number
MAX_VIA_COUNT?: number
} /**
This solver uses an intersection-based approach. Here's how it works:
0. Prepare placeholderPaths
- Placeholder paths go from (start, end) if the z is the same
- For placeholder paths, if the Z is different between the start and the end, then we create two segments, (start, mid) with start.z and (mid,end) with end.z. This means the placeholder path has four points, the second and third point are both a the mid XY but have a different z
1. We cycle through each port pair, we start by setting currentHead = start for the first pair
2. We have a currentHead, currentPath and currentConnectionName
STEP LOOP:
3. We always try to move the currentHead to the end. We try to create a line from currentHead to the end
4. If the currentHead does any of the following:
- Intersects a previously created path
- Intersects a placeholder path
- (check last) is not on the same z as the end
Then we must insert a via (2 points with a z change). Insert this via at the midpoint of currentHead and the intersection point (or the end if the "is not same z as end" condition applies)
In the next iteration of the step function we'll go back to step 3
5. After the currentPath reaches the end for the connection, we delete the placeholder path and select the next currentHead by popping the unprocessedConnections, reset currentPath and set currentConnectionName
6. When there are no more unprocessed connections, we set this.solved = true
*/
export class ViaPossibilitiesSolver2 extends BaseSolver {
override getSolverName(): string {
return "ViaPossibilitiesSolver2"
}
bounds: Bounds
maxViaCount: number
portPairMap: PortPairMap
colorMap: Record<string, string>
nodeWidth: number
availableZ: number[]
hyperParameters: ViaPossibilities2HyperParameters
VIA_INTERSECTION_BUFFER_DISTANCE = 0.05
PLACEHOLDER_WALL_BUFFER_DISTANCE = 0.1
NEW_HEAD_WALL_BUFFER_DISTANCE = 0.05
viaDiameter: number
unprocessedConnections: ConnectionName[]
completedPaths: Map<ConnectionName, Point3[]> = new Map()
placeholderPaths: Map<ConnectionName, Point3[]> = new Map()
currentHead: Point3
currentConnectionName: ConnectionName
currentPath: Point3[]
currentViaCount: number
constructor({
nodeWithPortPoints,
colorMap,
hyperParameters,
viaDiameter,
}: {
nodeWithPortPoints: NodeWithPortPoints
colorMap?: Record<string, string>
hyperParameters?: ViaPossibilities2HyperParameters
viaDiameter?: number
}) {
super()
this.MAX_ITERATIONS = 100e3
this.colorMap =
colorMap ?? generateColorMapFromNodeWithPortPoints(nodeWithPortPoints)
this.maxViaCount = hyperParameters?.MAX_VIA_COUNT ?? 5
this.bounds = getBoundsFromNodeWithPortPoints(nodeWithPortPoints)
this.nodeWidth = this.bounds.maxX - this.bounds.minX
this.portPairMap = getPortPairMap(nodeWithPortPoints)
this.stats.solutionsFound = 0
this.availableZ = nodeWithPortPoints.availableZ ?? [0, 1]
this.hyperParameters = hyperParameters ?? {
SHUFFLE_SEED: 0,
}
this.viaDiameter = viaDiameter ?? 0.3
this.unprocessedConnections = Array.from(this.portPairMap.keys()).sort()
if (hyperParameters?.SHUFFLE_SEED) {
this.unprocessedConnections = cloneAndShuffleArray(
this.unprocessedConnections,
hyperParameters.SHUFFLE_SEED,
)
}
// Generate placeholder paths
for (const [connectionName, { start, end }] of this.portPairMap.entries()) {
if (start.z === end.z) {
const isVertical = Math.abs(start.x - end.x) < 1e-9 // Use tolerance for float comparison
const isHorizontal = Math.abs(start.y - end.y) < 1e-9
if (isVertical || isHorizontal) {
this.placeholderPaths.set(connectionName, [
start,
this._padByPlaceholderWallBuffer(start),
this._padByPlaceholderWallBuffer(end),
end,
])
} else {
// Diagonal line on the same Z plane
this.placeholderPaths.set(connectionName, [start, end])
}
} else {
// Create a path with a Z change at the midpoint for different Z levels
const midX = (start.x + end.x) / 2
const midY = (start.y + end.y) / 2
// Use the (potentially offset) midpoint XY for the Z change points
const midStart: Point3 = this._padByPlaceholderWallBuffer({
x: midX,
y: midY,
z: start.z,
})
const midEnd: Point3 = this._padByPlaceholderWallBuffer({
x: midX,
y: midY,
z: end.z,
})
this.placeholderPaths.set(connectionName, [
start,
this._padByPlaceholderWallBuffer(start),
midStart,
midEnd,
this._padByPlaceholderWallBuffer(end),
end,
])
}
}
this.currentConnectionName = this.unprocessedConnections.pop()!
const start = this.portPairMap.get(this.currentConnectionName)!.start
this.currentHead = this._padByNewHeadWallBuffer(start)
this.currentPath = [start, this.currentHead]
this.currentViaCount = 0
this.placeholderPaths.delete(this.currentConnectionName) // Delete placeholder when we start processing
}
_padByNewHeadWallBuffer(point: Point3) {
return {
x: clamp(
point.x,
this.bounds.minX + this.NEW_HEAD_WALL_BUFFER_DISTANCE,
this.bounds.maxX - this.NEW_HEAD_WALL_BUFFER_DISTANCE,
),
y: clamp(
point.y,
this.bounds.minY + this.NEW_HEAD_WALL_BUFFER_DISTANCE,
this.bounds.maxY - this.NEW_HEAD_WALL_BUFFER_DISTANCE,
),
z: point.z,
}
}
_padByPlaceholderWallBuffer(point: Point3) {
return {
x: clamp(
point.x,
this.bounds.minX + this.PLACEHOLDER_WALL_BUFFER_DISTANCE,
this.bounds.maxX - this.PLACEHOLDER_WALL_BUFFER_DISTANCE,
),
y: clamp(
point.y,
this.bounds.minY + this.PLACEHOLDER_WALL_BUFFER_DISTANCE,
this.bounds.maxY - this.PLACEHOLDER_WALL_BUFFER_DISTANCE,
),
z: point.z,
}
}
_step() {
if (this.solved) return
const targetEnd = this.portPairMap.get(this.currentConnectionName)!.end
const proposedSegment: [Point3, Point3] = [this.currentHead, targetEnd]
let closestIntersection: any = null
let intersectedSegmentZ: number | null = null
const checkIntersectionsWithPathMap = (
pathMap: Map<ConnectionName, Point3[]>,
) => {
for (const path of pathMap.values()) {
for (let i = 0; i < path.length - 1; i++) {
const segment: [Point3, Point3] = [path[i], path[i + 1]]
// Skip checking intersection if segment is just a via (z change)
if (segment[0].x === segment[1].x && segment[0].y === segment[1].y) {
continue
}
// Only check intersections on the same Z plane as the proposed move start
// Or if the proposed move itself involves a Z change (handled later)
if (segment[0].z !== this.currentHead.z) {
continue
}
const intersection = getSegmentIntersection(
proposedSegment[0],
proposedSegment[1],
segment[0],
segment[1],
)
if (intersection) {
// Ignore intersection if it's exactly at the start point (currentHead)
const distToIntersection = distance(this.currentHead, intersection)
if (distToIntersection < 1e-6) continue // Tolerance for floating point
if (
!closestIntersection ||
distToIntersection < closestIntersection.dist
) {
closestIntersection = {
point: intersection,
dist: distToIntersection,
}
intersectedSegmentZ = segment[0].z // Z level of the segment we hit
}
}
}
}
}
// Check intersections against completed and placeholder paths
checkIntersectionsWithPathMap(this.completedPaths)
checkIntersectionsWithPathMap(this.placeholderPaths)
const needsZChange = this.currentHead.z !== targetEnd.z
if (closestIntersection || needsZChange) {
this.currentViaCount++
// Check if adding this via would exceed the limit
if (this.currentViaCount >= this.maxViaCount) {
this.failed = true
this.error = `Exceeded max via count of ${this.maxViaCount}`
return
}
}
if (closestIntersection) {
// --- Intersection Found ---
let viaXY: Point
const distToIntersection = closestIntersection.dist
if (distToIntersection <= this.VIA_INTERSECTION_BUFFER_DISTANCE + 1e-6) {
// If intersection is too close, place via at midpoint
viaXY = midpoint(this.currentHead, closestIntersection.point)
} else {
// Otherwise, place via VIA_INTERSECTION_BUFFER_DISTANCE before the intersection point
const intersectionPoint = closestIntersection.point
const vectorX = intersectionPoint.x - this.currentHead.x
const vectorY = intersectionPoint.y - this.currentHead.y
// Calculate the point VIA_INTERSECTION_BUFFER_DISTANCE away from the intersection towards the current head
const ratio =
(distToIntersection - this.VIA_INTERSECTION_BUFFER_DISTANCE) /
distToIntersection
viaXY = {
x: this.currentHead.x + vectorX * ratio,
y: this.currentHead.y + vectorY * ratio,
}
}
// Determine the Z level to switch to (the one NOT occupied by the intersected segment)
const nextZ = this.availableZ.find((z) => z !== intersectedSegmentZ)!
if (nextZ === undefined) {
this.error = "Could not determine next Z level for via placement!"
this.failed = true // Mark as failed if Z logic breaks
return
}
const viaPoint1: Point3 = { ...viaXY, z: this.currentHead.z }
const viaPoint2: Point3 = { ...viaXY, z: nextZ }
this.currentPath.push(viaPoint1, viaPoint2)
this.currentHead = viaPoint2
} else if (needsZChange) {
// --- No Intersection, but Z Mismatch ---
let viaXY: Point
const distToTarget = distance(this.currentHead, targetEnd)
if (distToTarget < this.VIA_INTERSECTION_BUFFER_DISTANCE) {
// If target is too close, place via at midpoint
viaXY = midpoint(this.currentHead, targetEnd)
} else {
// Otherwise, place via VIA_INTERSECTION_BUFFER_DISTANCE before the target end point
const vectorX = targetEnd.x - this.currentHead.x
const vectorY = targetEnd.y - this.currentHead.y
// Calculate the point VIA_INTERSECTION_BUFFER_DISTANCE away from the target towards the current head
const ratio =
(distToTarget - this.VIA_INTERSECTION_BUFFER_DISTANCE) / distToTarget
viaXY = {
x: this.currentHead.x + vectorX * ratio,
y: this.currentHead.y + vectorY * ratio,
}
}
const nextZ = targetEnd.z // Target the destination Z
const viaPoint1: Point3 = { ...viaXY, z: this.currentHead.z }
const viaPoint2: Point3 = { ...viaXY, z: nextZ }
this.currentPath.push(viaPoint1, viaPoint2)
this.currentHead = viaPoint2
} else {
// --- No Intersection, Z Matches: Path Clear ---
this.currentPath.push(targetEnd)
this.completedPaths.set(this.currentConnectionName, this.currentPath)
if (this.unprocessedConnections.length === 0) {
// All connections processed
this.solved = true
this.stats.solutionsFound = 1 // Mark as solved
} else {
// Start next connection
this.currentConnectionName = this.unprocessedConnections.pop()!
const { start } = this.portPairMap.get(this.currentConnectionName)!
this.currentHead = this._padByNewHeadWallBuffer(start)
this.currentPath = [start, this.currentHead]
this.currentViaCount = 0
this.placeholderPaths.delete(this.currentConnectionName) // Remove placeholder
}
}
}
visualize(): GraphicsObject {
const graphics: GraphicsObject = {
points: [],
lines: [],
circles: [],
rects: [],
title: "Via Possibilities Solver State",
coordinateSystem: "cartesian",
}
// Generate a simple color map
const colorMap = this.colorMap
// 1. Draw Node Bounds
graphics.lines!.push({
points: [
{ x: this.bounds.minX, y: this.bounds.minY },
{ x: this.bounds.maxX, y: this.bounds.minY },
{ x: this.bounds.maxX, y: this.bounds.maxY },
{ x: this.bounds.minX, y: this.bounds.maxY },
{ x: this.bounds.minX, y: this.bounds.minY },
],
strokeColor: "gray",
strokeWidth: 0.01,
})
// Draw Start/End points from portPairMap
for (const [connectionName, { start, end }] of this.portPairMap.entries()) {
const color = this.colorMap[connectionName] ?? "black"
graphics.points!.push({
x: start.x,
y: start.y,
color: color,
label: `Port: ${connectionName} Start (z${start.z})`,
})
graphics.points!.push({
x: end.x,
y: end.y,
color: color,
label: `Port: ${connectionName} End (z${end.z})`,
})
}
const drawPath = (
pathMap: Map<ConnectionName, Point3[]>,
labelPrefix: string,
) => {
for (const [connectionName, path] of pathMap.entries()) {
const color = colorMap[connectionName] ?? "black"
for (let i = 0; i < path.length - 1; i++) {
const p1 = path[i]
const p2 = path[i + 1]
if (p1.x === p2.x && p1.y === p2.y && p1.z !== p2.z) {
// Draw Via for Z change
graphics.circles!.push({
center: { x: p1.x, y: p1.y },
radius: this.viaDiameter / 2,
fill: safeTransparentize(color, 0.5),
label: `${labelPrefix}: ${connectionName} Via (z${p1.z}->z${p2.z})`,
})
} else {
// Draw Line Segment
graphics.lines!.push({
points: [p1, p2],
strokeColor: safeTransparentize(color, 0.5),
strokeDash: p1.z === 0 ? undefined : [0.1, 0.1],
strokeWidth: 0.1,
label: `${labelPrefix}: ${connectionName} (z${p1.z})`,
})
}
}
}
}
// 2. Draw Placeholder Paths
drawPath(this.placeholderPaths, "Placeholder")
// 3. Draw Completed Paths
drawPath(this.completedPaths, "Completed")
// 4. Draw Current Path (if any)
if (this.currentPath && this.currentPath.length > 0) {
const color = colorMap[this.currentConnectionName] ?? "orange" // Use a distinct color
for (let i = 0; i < this.currentPath.length - 1; i++) {
const p1 = this.currentPath[i]
const p2 = this.currentPath[i + 1]
if (p1.x === p2.x && p1.y === p2.y && p1.z !== p2.z) {
graphics.circles!.push({
center: { x: p1.x, y: p1.y },
radius: this.viaDiameter / 2,
fill: safeTransparentize(color, 0.5),
label: `Current: ${this.currentConnectionName} Via (z${p1.z}->z${p2.z})`,
})
} else {
graphics.lines!.push({
points: [p1, p2],
strokeColor: safeTransparentize(color, 0.5),
strokeWidth: 0.15, // Thicker
strokeDash: "2,2", // Dashed
label: `Current: ${this.currentConnectionName} (z${p1.z})`,
})
}
}
// Highlight current head
graphics.points!.push({
x: this.currentHead.x,
y: this.currentHead.y,
color: "green",
label: `Current Head: ${this.currentConnectionName} (z${this.currentHead.z})`,
})
}
return graphics
}
}