{"version":3,"file":"index.mjs","names":["orthogonalSegmentsCross","PER_DIMENSION_PIPELINE","freeSegmentID","fixedSegmentID","freeWeight","fixedWeight","newRoutingVertex","VertInfClass"],"sources":["../src/utilities/option-set.ts","../src/models/Direction.ts","../src/geomtypes.ts","../src/vertex.ts","../src/graph.ts","../src/models/obstacle.ts","../src/models/annotation-group.ts","../src/models/junction.ts","../src/pipeline.ts","../src/models/endpoint.ts","../src/models/Checkpoint.ts","../src/geometry.ts","../src/data-structures/PtOrder.ts","../src/data-structures/ConnectorCrossings.ts","../src/utilities/heap.ts","../src/makepath.ts","../src/models/edge.ts","../src/utilities/sorted-array.ts","../src/utilities/assert.ts","../src/hyperedgetree.ts","../src/mtst.ts","../src/hyperedge.ts","../src/utilities/map.ts","../src/improveCrossings.ts","../src/scanline.ts","../src/hyperedgeimprover.ts","../src/pipeline/improver-steps.ts","../src/vpsc.ts","../src/utilities/nudging-shift-segment.ts","../src/utilities/pos-vert-inf.ts","../src/utilities/line-segment.ts","../src/utilities/segment-list-wrapper.ts","../src/orthogonal.ts","../src/pipeline/orthogonal-steps.ts","../src/pipeline/route-steps.ts","../src/router.ts","../src/utilities/print.ts"],"sourcesContent":["export class OptionSet {\n  readonly rawValue: number;\n  constructor(value: number | OptionSet[]) {\n    if (typeof value === 'number') {\n      this.rawValue = value;\n    } else {\n      this.rawValue = value.reduce((oldValue, newValue) => oldValue | newValue.rawValue, 0);\n    }\n  }\n\n  has(value: OptionSet) {\n    return (this.rawValue & value.rawValue) === value.rawValue;\n  }\n\n  // Returns true if any bit of `value` is set in this set.  Use `has` when\n  // you need to check that *all* bits of `value` are set.\n  intersects(value: OptionSet): boolean {\n    return (this.rawValue & value.rawValue) !== 0;\n  }\n\n  add(value: typeof this): typeof this {\n    let constructor = <typeof OptionSet>this.constructor;\n    return new constructor(this.rawValue | value.rawValue) as typeof this;\n  }\n\n  equal(other: typeof this): boolean {\n    return this.rawValue === other.rawValue;\n  }\n\n  static zero = new OptionSet(0);\n}\n","import {OptionSet} from '../utilities/option-set';\n\n// ─── Direction ───────────────────────────────────────────────────────────────\n\nexport class Direction extends OptionSet {\n  static blockStart = new Direction(1);\n  static blockEnd = new Direction(2);\n  static block = new Direction([Direction.blockStart, Direction.blockEnd]);\n\n  static inlineStart = new Direction(4);\n  static inlineEnd = new Direction(8);\n  static inline = new Direction([Direction.inlineStart, Direction.inlineEnd]);\n\n  static all = new Direction([Direction.block, Direction.inline]);\n}\n","export const XDIM = 0;\nexport const YDIM = 1;\nexport const kUnassignedVertexNumber = 8;\nexport const kShapeConnectionPin = 9;\n\n// Direction of point c relative to directed segment a→b.\n// Returns 1 (CCW), 0 (collinear), or -1 (CW).\n// maybeZero widens the zero band for near-collinear tolerance.\nexport function vecDir(a: Point, b: Point, c: Point, maybeZero = 0): number {\n  const area2 = (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y);\n  if (area2 < -maybeZero) return -1;\n  if (area2 > maybeZero) return 1;\n  return 0;\n}\n\nexport class Point {\n  x: number;\n  y: number;\n  // Geometric corner-index / midpoint label used by `midVertexNumber` in\n  // shared-path detection.  Valid values: 0..3 = rectangle corners, 4..7 =\n  // edge midpoints, kUnassignedVertexNumber = not on any shape boundary.\n  vn: number;\n\n  constructor(x = 0, y = 0) {\n    this.x = x;\n    this.y = y;\n    this.vn = kUnassignedVertexNumber;\n  }\n\n  eq(rhs: Point): boolean {\n    return this.x === rhs.x && this.y === rhs.y;\n  }\n\n  // Index by dimension: 0=x, 1=y (read).\n  at(dimension: number): number {\n    return dimension === XDIM ? this.x : this.y;\n  }\n\n  // Index by dimension: 0=x, 1=y (write).\n  setAt(dimension: number, value: number): void {\n    if (dimension === XDIM) this.x = value;\n    else this.y = value;\n  }\n}\n\nexport class Box {\n  min: Point;\n  max: Point;\n\n  constructor() {\n    this.min = new Point();\n    this.max = new Point();\n  }\n\n  length(dimension: number): number {\n    return dimension === XDIM ? this.max.x - this.min.x : this.max.y - this.min.y;\n  }\n\n  width(): number {\n    return this.max.x - this.min.x;\n  }\n\n  height(): number {\n    return this.max.y - this.min.y;\n  }\n}\n\nexport class Polygon {\n  ps: Point[];\n  // Checkpoints on the route and which segment/vertex they lie on.\n  // Encoding: 2*k → on ps[k]; 2*k+1 → on segment ps[k]→ps[k+1].\n  checkpointsOnRoute: Array<[number, Point]>;\n\n  constructor(n?: number) {\n    this.ps = n !== undefined ? Array.from({length: n}, () => new Point()) : [];\n    this.checkpointsOnRoute = [];\n  }\n\n  clone(): Polygon {\n    const copy = new Polygon();\n    copy.ps = this.ps.map(p => {\n      const np = new Point(p.x, p.y);\n      np.vn = p.vn;\n      return np;\n    });\n    copy.checkpointsOnRoute = this.checkpointsOnRoute.map(([n, p]) => {\n      const np = new Point(p.x, p.y);\n      np.vn = p.vn;\n      return [n, np] as [number, Point];\n    });\n    return copy;\n  }\n\n  clear(): void {\n    this.ps = [];\n  }\n\n  empty(): boolean {\n    return this.ps.length === 0;\n  }\n\n  size(): number {\n    return this.ps.length;\n  }\n\n  at(index: number): Point | undefined {\n    return this.ps.at(index);\n  }\n\n  *pairs(): Generator<[Point, Point]> {\n    for (let i = 0; i < this.ps.length - 1; i++) {\n      yield [this.ps[i], this.ps[i + 1]];\n    }\n  }\n\n  simplify(): Polygon {\n    const simplified = this.clone();\n    const checkpoints = simplified.checkpointsOnRoute;\n    const hasCheckpointInfo = checkpoints.length > 0;\n\n    let j = 2;\n    while (j < simplified.ps.length) {\n      if (vecDir(simplified.ps[j - 2], simplified.ps[j - 1], simplified.ps[j]) === 0) {\n        simplified.ps.splice(j - 1, 1);\n\n        if (hasCheckpointInfo) {\n          const deletedPointValue = j - 1 - 1;\n          for (const cp of checkpoints) {\n            if (cp[0] === deletedPointValue) {\n              cp[0] -= 1;\n            } else if (cp[0] > deletedPointValue) {\n              cp[0] -= 2;\n            }\n          }\n        }\n      } else {\n        j++;\n      }\n    }\n\n    return simplified;\n  }\n\n  checkpointsOnSegment(segmentLowerIndex: number, indexModifier = 0): Point[] {\n    let lower = 2 * segmentLowerIndex;\n    let upper = lower + 2;\n\n    if (indexModifier > 0) lower++;\n    else if (indexModifier < 0) upper--;\n\n    const result: Point[] = [];\n    for (const [pos, pt] of this.checkpointsOnRoute) {\n      if (pos >= lower && pos <= upper) {\n        result.push(pt);\n      }\n    }\n    return result;\n  }\n\n  offsetBoundingBox(offset: number): Box {\n    const box = new Box();\n    box.min.x = Infinity;\n    box.min.y = Infinity;\n    box.max.x = -Infinity;\n    box.max.y = -Infinity;\n\n    for (let pt of this.ps) {\n      if (pt.x < box.min.x) box.min.x = pt.x;\n      if (pt.y < box.min.y) box.min.y = pt.y;\n      if (pt.x > box.max.x) box.max.x = pt.x;\n      if (pt.y > box.max.y) box.max.y = pt.y;\n    }\n\n    box.min.x -= offset;\n    box.min.y -= offset;\n    box.max.x += offset;\n    box.max.y += offset;\n\n    return box;\n  }\n}\n\nexport class Rect extends Polygon {\n  readonly _origin: {x: number; y: number};\n  readonly _size: {width: number; height: number};\n  constructor(origin: {x: number; y: number}, size: {width: number; height: number}) {\n    super(4);\n    this._origin = origin;\n    this._size = size;\n    this.ps[0] = new Point(origin.x + size.width, origin.y);\n    this.ps[1] = new Point(origin.x + size.width, origin.y + size.height);\n    this.ps[2] = new Point(origin.x, origin.y + size.height);\n    this.ps[3] = new Point(origin.x, origin.y);\n\n    this.ps[0].vn = 0;\n    this.ps[1].vn = 1;\n    this.ps[2].vn = 2;\n    this.ps[3].vn = 3;\n  }\n\n  offsetPolygon(bufferSpace: number) {\n    return new Rect(\n      {\n        x: this._origin.x - bufferSpace,\n        y: this._origin.y - bufferSpace,\n      },\n      {\n        width: this._size.width + bufferSpace * 2,\n        height: this._size.height + bufferSpace * 2,\n      },\n    );\n  }\n}\n","import {Direction} from './models/Direction.ts';\nimport {Point} from './geomtypes.ts';\nimport type {EdgeInf} from './graph.ts';\n\n// Forward reference for ANode (defined in makepath.ts).\nexport interface ANode {}\n\n// ─── Orthogonal visibility property flags ────────────────────────────────────\n\nexport const XL_EDGE = 1;\nexport const XL_CONN = 2;\nexport const XH_EDGE = 4;\nexport const XH_CONN = 8;\nexport const YL_EDGE = 16;\nexport const YL_CONN = 32;\nexport const YH_EDGE = 64;\nexport const YH_CONN = 128;\n\n// Role-flag bag passed to `VertInf`'s constructor.\n// Omitted fields default to `false`.\nexport interface VertInfRoles {\n  isConnPoint?: boolean;\n  isOrthShapeEdge?: boolean;\n  isJunctionCentre?: boolean;\n  isConnCheckpoint?: boolean;\n  // Stage 5 of the VertID overhaul: synthetic vertex MTST creates to model\n  // the bend penalty between horizontal/vertical routing layers.\n  isDimensionChangePartner?: boolean;\n}\n\n// Monotonic counter used to stamp each `VertInf` with a unique `_seq` at\n// construction.  Drives the deterministic tie-break ordering used by MTST\n// (when two tree roots compare equal on point coordinates we still need a\n// stable winner).  Replaces the C++ `VertID::lt` ordering.\nlet _vertInfSeqCounter = 0;\n\n// ─── VertInf ──────────────────────────────────────────────────────────────────\n\nexport class VertInf {\n  // ─── Identity ──────────────────────────────────────────────────────────────\n  // `objID` is the owner's `_id` (Obstacle / ConnRef) — or 0 for synthetic\n  // vertices that aren't owned by any obstacle.  `vn` is shape-corner index\n  // (for shape vertices) or a connector-internal disambiguator (0 = src,\n  // 1 = tar, 2 + i = i-th checkpoint).  Stage 5 of the VertID overhaul\n  // hoisted these out of the now-deleted `VertID` class.\n  objID: number;\n  vn: number;\n\n  // Monotonically increasing creation sequence — guarantees a stable\n  // deterministic ordering between any two VertInfs, used by MTST and the\n  // scanline's `PosVertInf.lt` tie-break.  Replaces the C++ `VertID::lt`.\n  readonly _seq: number;\n\n  point: Point;\n\n  // ─── Role flags ────────────────────────────────────────────────────────────\n  // Named role bits, owned directly by the vertex.  Callers pass the\n  // applicable flags via the fourth constructor argument.\n  // (TS can't see that `applyRoles` populates these from inside the\n  // constructor, so the `!` definite-assignment assertions are required.)\n  isConnPoint!: boolean;\n  isOrthShapeEdge!: boolean;\n  isJunctionCentre!: boolean;\n  isConnCheckpoint!: boolean;\n  isDimensionChangePartner!: boolean;\n\n  // Doubly-linked list pointers within VertInfList.\n  lstPrev: VertInf | null;\n  lstNext: VertInf | null;\n  // Linked list pointers within a shape's own vertex ring.\n  shPrev: VertInf | null;\n  shNext: VertInf | null;\n\n  // Orthogonal visibility graph edge list.\n  orthogVisList: EdgeInf[];\n\n  // A* pathfinding.\n  pathNext: VertInf | null;\n  aStarDoneNodes: ANode[];\n  aStarPendingNodes: ANode[];\n\n  // Orthogonal partner used when building the orthogonal visibility graph.\n  orthogonalPartner: VertInf | null;\n\n  // MTST tree root — a shared mutable box so multiple vertices can track the\n  // same root through a single reference.  Replaces the C++ VertInf** hack.\n  _treeRootBox: {value: VertInf | null} | null;\n\n  // SPTF (shortest-path tree from source) root — stored separately because\n  // the C++ reuses the m_treeRoot field with an unsafe cast; we keep them\n  // distinct for clarity.\n  _sptfRoot: VertInf | null;\n\n  sptfDist: number;\n\n  visDirections: Direction;\n\n  // Flags encoding which sides of this vertex border shape edges or\n  // connection points (used by orthogonal routing).\n  orthogVisPropFlags: number;\n\n  constructor(objID: number, vn: number, point: Point, roles: VertInfRoles = {}) {\n    this.objID = objID;\n    this.vn = vn;\n    this._seq = ++_vertInfSeqCounter;\n\n    this.point = new Point(point.x, point.y);\n    this.point.vn = vn;\n\n    this.applyRoles(roles);\n\n    this.lstPrev = null;\n    this.lstNext = null;\n    this.shPrev = null;\n    this.shNext = null;\n\n    this.orthogVisList = [];\n\n    this.pathNext = null;\n    this.aStarDoneNodes = [];\n    this.aStarPendingNodes = [];\n\n    this.orthogonalPartner = null;\n    this._treeRootBox = null;\n    this._sptfRoot = null;\n    this.sptfDist = 0;\n\n    this.visDirections = Direction.zero;\n    this.orthogVisPropFlags = 0;\n  }\n\n  private applyRoles(roles: VertInfRoles): void {\n    this.isConnPoint = roles.isConnPoint ?? false;\n    this.isOrthShapeEdge = roles.isOrthShapeEdge ?? false;\n    this.isJunctionCentre = roles.isJunctionCentre ?? false;\n    this.isConnCheckpoint = roles.isConnCheckpoint ?? false;\n    this.isDimensionChangePartner = roles.isDimensionChangePartner ?? false;\n  }\n\n  // Total ordering for `SortedArray<VertInf>`: primary by point position\n  // (x then y), tiebreak by (`objID`, `vn`).  Two VertInfs at the same\n  // point with the same (`objID`, `vn`) compare equal — they're considered\n  // the same vertex for set-semantics purposes.  In our scanline-built\n  // vis-graph that pair uniquely identifies a vertex; if a caller ever\n  // wants to distinguish two distinct instances with the same (objID, vn),\n  // they should add another tiebreaker.\n  //\n  // NB: the old `VertSet` allowed multiple distinct VertInfs at the same\n  // point AND the same (objID, vn) to coexist (identity dedup, not\n  // comparator dedup).  In practice the scanline never produces such\n  // duplicates, but keeping this in mind in case a future caller relies\n  // on the wider behaviour.\n  static compare(a: VertInf, b: VertInf): number {\n    if (a.point.x !== b.point.x) {\n      return a.point.x < b.point.x ? -1 : 1;\n    }\n    if (a.point.y !== b.point.y) {\n      return a.point.y < b.point.y ? -1 : 1;\n    }\n    if (a.objID !== b.objID) {\n      return a.objID - b.objID;\n    }\n    return a.vn - b.vn;\n  }\n\n  // Removes all edges from this vertex, alerting connected connectors.\n  removeFromGraph(_isConnVert = true): void {\n    while (this.orthogVisList.length > 0) {\n      const edge = this.orthogVisList[0];\n      edge.destroy();\n    }\n  }\n\n  // Returns the direction flags of this vertex relative to other.\n  // Uses a small epsilon to avoid floating-point noise.\n  directionFrom(other: VertInf): Direction {\n    const epsilon = 0.000001;\n    let diff = new Point(this.point.x - other.point.x, this.point.y - other.point.y);\n    let directions = Direction.zero;\n\n    if (diff.y > epsilon) {\n      directions = directions.add(Direction.blockStart);\n    }\n    if (diff.y < -epsilon) {\n      directions = directions.add(Direction.blockEnd);\n    }\n    if (diff.x > epsilon) {\n      directions = directions.add(Direction.inlineEnd);\n    }\n    if (diff.x < -epsilon) {\n      directions = directions.add(Direction.inlineStart);\n    }\n    return directions;\n  }\n\n  // Disables visibility edges whose direction is not in the given set.\n  setVisibleDirections(directions: Direction): void {\n    for (const edge of this.orthogVisList) {\n      if (directions.equal(Direction.all)) {\n        edge.setDisabled(false);\n      } else {\n        const other = edge.otherVert(this);\n        const dir = other.directionFrom(this);\n        edge.setDisabled(!dir.has(directions)); // (dir & directions) === 0\n      }\n    }\n  }\n\n  // Returns the number of steps from this vertex back to start along\n  // pathNext links, or 0 if no such path exists.\n  pathLeadsBackTo(start: VertInf): number {\n    let pathlen = 1;\n    for (let i: VertInf | null = this; i !== start; i = i.pathNext) {\n      if (pathlen > 1 && i === this) return 0; // circular\n      pathlen++;\n      if (i === null) return 0; // not found\n    }\n    return pathlen;\n  }\n\n  // Returns an edge to target in the appropriate visibility list, or null.\n  hasNeighbour(target: VertInf): EdgeInf | null {\n    for (const edge of this.orthogVisList) {\n      if (edge.otherVert(this) === target) return edge;\n    }\n    return null;\n  }\n\n  // ─── MTST tree root ───────────────────────────────────────────────────────\n  // The C++ uses a malloc'd VertInf** so multiple vertices can share one root\n  // cell.  We model this as a shared { value } box.\n\n  makeTreeRootPointer(root: VertInf): {value: VertInf | null} {\n    this._treeRootBox = {value: root};\n    return this._treeRootBox;\n  }\n\n  treeRoot(): VertInf | null {\n    return this._treeRootBox ? this._treeRootBox.value : null;\n  }\n\n  treeRootPointer(): {value: VertInf | null} | null {\n    return this._treeRootBox;\n  }\n\n  setTreeRootPointer(pointer: {value: VertInf | null} | null): void {\n    this._treeRootBox = pointer;\n  }\n}\n\n// ─── VertInfList ─────────────────────────────────────────────────────────────\n// A split linked list that keeps connector vertices before shape vertices.\n// Invariants (matching the C++ checkVertInfListConditions macro):\n//   - connector vertices occupy the head of the list\n//   - shape vertices follow immediately after\n//   - _lastConnVert->lstNext === _firstShapeVert (or null when no shapes)\n//   - _lastShapeVert->lstNext === null\n\nexport class VertInfList {\n  private _firstShapeVert: VertInf | null;\n  private _firstConnVert: VertInf | null;\n  private _lastShapeVert: VertInf | null;\n  private _lastConnVert: VertInf | null;\n\n  constructor() {\n    this._firstShapeVert = null;\n    this._firstConnVert = null;\n    this._lastShapeVert = null;\n    this._lastConnVert = null;\n  }\n\n  addVertex(vert: VertInf): void {\n    if (vert.isConnPoint) {\n      if (this._firstConnVert) {\n        vert.lstNext = this._firstConnVert;\n        this._firstConnVert.lstPrev = vert;\n        this._firstConnVert = vert;\n      } else {\n        this._firstConnVert = vert;\n        this._lastConnVert = vert;\n        vert.lstNext = this._firstShapeVert;\n      }\n    } else {\n      if (this._lastShapeVert) {\n        vert.lstPrev = this._lastShapeVert;\n        this._lastShapeVert.lstNext = vert;\n        this._lastShapeVert = vert;\n      } else {\n        this._firstShapeVert = vert;\n        this._lastShapeVert = vert;\n        if (this._lastConnVert) {\n          this._lastConnVert.lstNext = vert;\n        }\n      }\n    }\n  }\n\n  // Removes vert from the list and returns the successor.\n  removeVertex(vert: VertInf | null): VertInf | null {\n    if (vert === null) return null;\n\n    const following = vert.lstNext;\n\n    if (vert.isConnPoint) {\n      if (vert === this._firstConnVert) {\n        if (vert === this._lastConnVert) {\n          this._firstConnVert = null;\n          this._lastConnVert = null;\n        } else {\n          this._firstConnVert = this._firstConnVert!.lstNext;\n          if (this._firstConnVert) {\n            this._firstConnVert.lstPrev = null;\n          }\n        }\n      } else if (vert === this._lastConnVert) {\n        this._lastConnVert = this._lastConnVert!.lstPrev;\n        this._lastConnVert!.lstNext = this._firstShapeVert;\n      } else {\n        vert.lstNext!.lstPrev = vert.lstPrev;\n        vert.lstPrev!.lstNext = vert.lstNext;\n      }\n    } else {\n      if (vert === this._lastShapeVert) {\n        this._lastShapeVert = this._lastShapeVert!.lstPrev;\n\n        if (vert === this._firstShapeVert) {\n          this._firstShapeVert = null;\n          if (this._lastConnVert) {\n            this._lastConnVert.lstNext = null;\n          }\n        }\n\n        if (this._lastShapeVert) {\n          this._lastShapeVert.lstNext = null;\n        }\n      } else if (vert === this._firstShapeVert) {\n        this._firstShapeVert = this._firstShapeVert!.lstNext;\n\n        if (this._lastConnVert) {\n          this._lastConnVert.lstNext = this._firstShapeVert;\n        }\n\n        if (this._firstShapeVert) {\n          this._firstShapeVert.lstPrev = null;\n        }\n      } else {\n        vert.lstNext!.lstPrev = vert.lstPrev;\n        vert.lstPrev!.lstNext = vert.lstNext;\n      }\n    }\n\n    vert.lstPrev = null;\n    vert.lstNext = null;\n\n    return following;\n  }\n\n  shapesBegin(): VertInf | null {\n    return this._firstShapeVert;\n  }\n\n  // Returns the first connector vertex, falling back to the first shape\n  // vertex when there are no connectors.\n  connsBegin(): VertInf | null {\n    return this._firstConnVert ?? this._firstShapeVert;\n  }\n\n  // Sentinel: iteration ends when lstNext returns null.\n  end(): null {\n    return null;\n  }\n\n  // ─── Iteration ────────────────────────────────────────────────────────────\n  // The list is two singly-linked segments joined at the seam between\n  // `_lastConnVert` and `_firstShapeVert`, so a single walk from\n  // `connsBegin()` to `null` naturally covers every vertex.  These iterator\n  // helpers replace the C++-style `for (k = …Begin(); k !== end; k = k!.lstNext)`\n  // dance at the half-dozen call sites that need them.\n\n  // Yields every vertex (connector vertices first, then shape vertices),\n  // in linked-list order.  Use a plain `for (const v of vertices) { ... }`.\n  *[Symbol.iterator](): IterableIterator<VertInf> {\n    for (let curr = this._firstConnVert ?? this._firstShapeVert; curr !== null; curr = curr.lstNext) {\n      yield curr;\n    }\n  }\n\n  // Yields only the connector vertices (the \"conn\" segment of the list).\n  // Stops at the seam where shape vertices begin.\n  *conns(): IterableIterator<VertInf> {\n    for (let curr = this._firstConnVert; curr !== null && curr !== this._firstShapeVert; curr = curr.lstNext) {\n      yield curr;\n    }\n  }\n\n  // Yields only the shape vertices.\n  *shapes(): IterableIterator<VertInf> {\n    for (let curr = this._firstShapeVert; curr !== null; curr = curr.lstNext) {\n      yield curr;\n    }\n  }\n}\n","import {vecDir, Point} from './geomtypes';\nimport type {Router} from './router';\nimport {VertInf} from './vertex';\n\n// ─── Internal helpers ─────────────────────────────────────────────────────────\n\nfunction removeFromArray<T>(arr: T[], item: T): void {\n  const idx = arr.indexOf(item);\n  if (idx !== -1) {\n    arr.splice(idx, 1);\n  }\n}\n\n// Returns a turn-order value for point c given the last segment was a→b:\n//   0  directly backwards\n//   1  left-hand 90° turn\n//   2  right-hand 90° turn\n//   3  straight ahead\n//   4  not orthogonally positioned\nfunction orthogTurnOrder(a: Point, b: Point, c: Point): number {\n  if ((c.x !== b.x && c.y !== b.y) || (a.x !== b.x && a.y !== b.y)) {\n    return 4;\n  }\n\n  const dir = vecDir(a, b, c);\n  if (dir > 0) return 1; // CCW = left\n  if (dir < 0) return 2; // CW  = right\n\n  // Collinear — check if behind or ahead.\n  if (b.x === c.x) {\n    if ((a.y < b.y && c.y < b.y) || (a.y > b.y && c.y > b.y)) return 0;\n  } else {\n    if ((a.x < b.x && c.x < b.x) || (a.x > b.x && c.x > b.x)) return 0;\n  }\n  return 3;\n}\n\n// ─── EdgeInf ─────────────────────────────────────────────────────────────────\n\nexport class EdgeInf {\n  // Intrusive linked-list pointers for EdgeList.\n  lstPrev: EdgeInf | null;\n  lstNext: EdgeInf | null;\n\n  private router: Router;\n  private _added: boolean;\n  private _isHyperedgeSegment: boolean;\n  private _disabled: boolean;\n  private _vert1: VertInf;\n  private _vert2: VertInf;\n\n  private _dist: number;\n  private _mtstDist: number;\n  // Additional cost MTST should charge for using this edge, on top of\n  // `_dist`.  Populated by the rerouter's `computeCrossingCosts` pass when\n  // `router.params.crossingPenalty > 0` — set to `crossingPenalty × (number\n  // of existing connector segments this edge would cross)`.  Default 0 means\n  // \"no penalty\" so the field is harmless when crossing-aware MTST isn't in\n  // play.  See Stage 2 of the crossing-aware-MTST plan.\n  private _crossingCost: number;\n\n  constructor(v1: VertInf, v2: VertInf, router: Router) {\n    this.lstPrev = null;\n    this.lstNext = null;\n\n    this.router = router;\n    this._added = false;\n    this._isHyperedgeSegment = false;\n    this._disabled = false;\n    this._vert1 = v1;\n    this._vert2 = v2;\n    this._dist = -1;\n    this._mtstDist = 0;\n    this._crossingCost = 0;\n  }\n\n  // ─── Public accessors ─────────────────────────────────────────────────────\n\n  getDist(): number {\n    return this._dist;\n  }\n\n  isOrthogonal(): boolean {\n    return this._vert1.point.x === this._vert2.point.x || this._vert1.point.y === this._vert2.point.y;\n  }\n\n  // Returns true when this edge connects a junction centre vertex to a\n  // connector endpoint vertex — a zero-length dummy edge used when a\n  // connector is anchored at a junction.\n  isDummyConnection(): boolean {\n    return (\n      (this._vert1.isJunctionCentre && this._vert2.isConnPoint) ||\n      (this._vert2.isJunctionCentre && this._vert1.isConnPoint)\n    );\n  }\n\n  isDisabled(): boolean {\n    return this._disabled;\n  }\n\n  setDisabled(disabled: boolean): void {\n    this._disabled = disabled;\n  }\n\n  isHyperedgeSegment(): boolean {\n    return this._isHyperedgeSegment;\n  }\n\n  setHyperedgeSegment(hyperedge: boolean): void {\n    this._isHyperedgeSegment = hyperedge;\n  }\n\n  mtstDist(): number {\n    return this._mtstDist;\n  }\n\n  setMtstDist(joinCost: number): void {\n    this._mtstDist = joinCost;\n  }\n\n  // ─── Crossing cost (used by MTST) ─────────────────────────────────────────\n  // See `_crossingCost` field comment.  Populated by the hyperedge rerouter\n  // before MTST runs; read by MTST's edge expansion.  Default is 0.\n\n  crossingCost(): number {\n    return this._crossingCost;\n  }\n\n  /** @internal */\n  setCrossingCost(cost: number): void {\n    this._crossingCost = cost;\n  }\n\n  otherVert(vert: VertInf): VertInf {\n    return vert === this._vert1 ? this._vert2 : this._vert1;\n  }\n\n  // ─── First / second endpoint accessors (used by mtst) ─────────────────────\n  // Mirror C++ public `m_vert1` / `m_vert2`.  The fields remain private to\n  // preserve invariant control inside EdgeInf; outside callers use these.\n  vert1(): VertInf {\n    return this._vert1;\n  }\n\n  vert2(): VertInf {\n    return this._vert2;\n  }\n\n  // ─── Visibility state ─────────────────────────────────────────────────────\n\n  // Sets the visibility distance and activates this edge if it isn't already.\n  setDist(dist: number): void {\n    if (!this._added) {\n      this.makeActive();\n    }\n    this._dist = dist;\n  }\n\n  // ─── Activation / deactivation ────────────────────────────────────────────\n\n  // Adds this edge to the router's orthogonal visibility graph and both\n  // vertices' edge lists.\n  private makeActive(): void {\n    this.router.visOrthogGraph.addEdge(this);\n    this._vert1.orthogVisList.unshift(this);\n    this._vert2.orthogVisList.unshift(this);\n    this._added = true;\n  }\n\n  // Removes this edge from the orthogonal visibility graph and both vertices'\n  // edge lists.\n  private makeInactive(): void {\n    this.router.visOrthogGraph.removeEdge(this);\n    removeFromArray(this._vert1.orthogVisList, this);\n    removeFromArray(this._vert2.orthogVisList, this);\n    this._added = false;\n  }\n\n  destroy() {\n    if (this._added) {\n      this.makeInactive();\n    }\n  }\n\n  // ─── Rotation ordering ────────────────────────────────────────────────────\n\n  // Returns true if this edge should sort before rhs in a rotation sweep\n  // starting from lastV.  Both edges must share a common vertex.\n  rotationLessThan(lastV: VertInf | null, rhs: EdgeInf): boolean {\n    if (this._vert1 === rhs._vert1 && this._vert2 === rhs._vert2) return false;\n\n    let commonV: VertInf | null = null;\n    let lhsV: VertInf | null = null;\n    let rhsV: VertInf | null = null;\n\n    if (this._vert1 === rhs._vert1) {\n      commonV = this._vert1;\n      lhsV = this._vert2;\n      rhsV = rhs._vert2;\n    } else if (this._vert1 === rhs._vert2) {\n      commonV = this._vert1;\n      lhsV = this._vert2;\n      rhsV = rhs._vert1;\n    } else if (this._vert2 === rhs._vert1) {\n      commonV = this._vert2;\n      lhsV = this._vert1;\n      rhsV = rhs._vert2;\n    } else if (this._vert2 === rhs._vert2) {\n      commonV = this._vert2;\n      lhsV = this._vert1;\n      rhsV = rhs._vert1;\n    }\n\n    const commonPt = commonV!.point;\n    const lastPt = lastV ? lastV.point : new Point(commonPt.x - 10, commonPt.y);\n\n    const lhsVal = orthogTurnOrder(lastPt, commonPt, lhsV!.point);\n    const rhsVal = orthogTurnOrder(lastPt, commonPt, rhsV!.point);\n\n    return lhsVal < rhsVal;\n  }\n}\n\n// ─── EdgeList ─────────────────────────────────────────────────────────────────\n// Intrusive doubly-linked list of EdgeInf nodes via lstPrev/lstNext.\n\nexport class EdgeList {\n  private _firstEdge: EdgeInf | null;\n  private _lastEdge: EdgeInf | null;\n  private _count: number;\n\n  constructor() {\n    this._firstEdge = null;\n    this._lastEdge = null;\n    this._count = 0;\n  }\n\n  size(): number {\n    return this._count;\n  }\n\n  begin(): EdgeInf | null {\n    return this._firstEdge;\n  }\n\n  // Appends edge to the tail of the list.\n  addEdge(edge: EdgeInf): void {\n    if (!this._firstEdge) {\n      this._firstEdge = edge;\n      this._lastEdge = edge;\n      edge.lstPrev = null;\n      edge.lstNext = null;\n    } else {\n      this._lastEdge!.lstNext = edge;\n      edge.lstPrev = this._lastEdge;\n      this._lastEdge = edge;\n      edge.lstNext = null;\n    }\n    this._count++;\n  }\n\n  // Removes edge from any position in the list.\n  removeEdge(edge: EdgeInf): void {\n    if (edge.lstPrev) edge.lstPrev.lstNext = edge.lstNext;\n    if (edge.lstNext) edge.lstNext.lstPrev = edge.lstPrev;\n\n    if (edge === this._lastEdge) {\n      this._lastEdge = edge.lstPrev;\n      if (edge === this._firstEdge) this._firstEdge = null;\n    } else if (edge === this._firstEdge) {\n      this._firstEdge = edge.lstNext;\n    }\n\n    edge.lstPrev = null;\n    edge.lstNext = null;\n    this._count--;\n  }\n\n  // Destroys all edges (equivalent to deleting each, which calls makeInactive).\n  // Relies on `values()` snapshotting `lstNext` before each yield so that\n  // `edge.destroy()` (which splices the edge out) doesn't disturb the walk.\n  clear(): void {\n    for (const edge of this.values()) {\n      edge.destroy();\n    }\n    this._firstEdge = null;\n    this._lastEdge = null;\n    this._count = 0;\n  }\n\n  // Iterates the list from `_firstEdge` to the tail.  Safe against\n  // mid-iteration removal of the *current* edge (we snapshot `lstNext`\n  // before yielding), but not against arbitrary structural mutation —\n  // callers that splice while iterating should snapshot via\n  // `Array.from(list.values())` first.\n  *values(): IterableIterator<EdgeInf> {\n    let edge = this._firstEdge;\n    while (edge !== null) {\n      const next = edge.lstNext;\n      yield edge;\n      edge = next;\n    }\n  }\n\n  [Symbol.iterator](): IterableIterator<EdgeInf> {\n    return this.values();\n  }\n}\n","import type {Box, Rect} from '../geomtypes.ts';\nimport type {Router} from '../router.ts';\n\n// ─── Obstacle ─────────────────────────────────────────────────────────────────\n\n// A rectangular routing obstacle (shape) or the small backing rectangle of a\n// fixed `Junction`.\n//\n// Pure geometry: the orthogonal visibility graph is built from each obstacle's\n// `routingBox()` by the scanline (which synthesises its own graph vertices), so\n// an obstacle no longer carries a ring of `VertInf` corner nodes.\n\nexport class Obstacle {\n  readonly router: Router;\n  readonly polygon: Rect;\n\n  constructor(router: Router, poly: Rect) {\n    this.router = router;\n    this.polygon = poly;\n  }\n\n  // ─── Public API ─────────────────────────────────────────────────────────────\n\n  // Returns the expanded bounding box used for routing around this obstacle.\n  routingBox(): Box {\n    const bufferSpace = this.router.params.shapeBufferDistance;\n    return this.polygon.offsetBoundingBox(bufferSpace);\n  }\n\n  // Returns the expanded routing polygon (Minkowski sum with a square buffer).\n  routingPolygon(bufferSpace: number): Rect {\n    return this.polygon.offsetPolygon(bufferSpace);\n  }\n}\n","import {Point, type Box, type Rect} from '../geomtypes.ts';\nimport type {Router} from '../router.ts';\n\n// ─── AnnotationGroup ──────────────────────────────────────────────────────────\n\n// A rectangular region that visually groups shapes.  Unlike an `Obstacle`, a\n// group is *soft*: connectors may cross its boundary, but every crossing costs\n// `groupCrossingPenalty`.  An edge whose endpoint lies inside the group has to\n// cross that boundary at least once anyway, so the penalty only steers the\n// avoidable crossings — routes that would cut through a group they don't\n// belong to, or leave and re-enter one they do.\n//\n// Membership is purely geometric: a point is \"inside\" when it lies in the\n// strict interior of `polygon`.  The boundary itself counts as outside, so an\n// edge attached to the group's border is outside it, and nested groups compose\n// without bookkeeping.\nexport class AnnotationGroup {\n  readonly router: Router;\n  readonly polygon: Rect;\n\n  constructor(router: Router, poly: Rect) {\n    this.router = router;\n    this.polygon = poly;\n  }\n\n  // The group's own (unbuffered) bounds — the boundary crossings are counted\n  // against.\n  bounds(): Box {\n    return this.polygon.offsetBoundingBox(0);\n  }\n\n  // Distance from the boundary at which the visibility graph places routing\n  // tracks, both just outside and just inside the group.  Falls back to the\n  // shape buffer so group-hugging routes sit as far off the border as\n  // shape-hugging routes sit off shapes.\n  bufferDistance(): number {\n    return this.router.params.groupBufferDistance ?? this.router.params.shapeBufferDistance;\n  }\n\n  // Corner points of the outer (and, when there's room, inner) track ring.\n  // The vis-graph sweep turns each point into a scanline in both dimensions,\n  // so these four-or-eight points yield the lines routes use to skirt the\n  // group from outside or to run along its inside edge.\n  trackPoints(): Point[] {\n    const b = this.bounds();\n    const d = this.bufferDistance();\n    const rings = [d];\n    if (d > 0 && b.max.x - b.min.x > 2 * d && b.max.y - b.min.y > 2 * d) {\n      rings.push(-d);\n    }\n    const points: Point[] = [];\n    for (const r of rings) {\n      points.push(\n        new Point(b.min.x - r, b.min.y - r),\n        new Point(b.max.x + r, b.min.y - r),\n        new Point(b.min.x - r, b.max.y + r),\n        new Point(b.max.x + r, b.max.y + r),\n      );\n    }\n    return points;\n  }\n\n  contains(p: Point): boolean {\n    const b = this.bounds();\n    return p.x > b.min.x && p.x < b.max.x && p.y > b.min.y && p.y < b.max.y;\n  }\n\n  // Number of times the axis-aligned step a→b crosses this group's boundary\n  // (0, 1 or 2).  Crossing is a change between strict-interior and\n  // not-interior, so summing over a route's steps counts its boundary\n  // crossings exactly.\n  crossings(a: Point, b: Point): number {\n    const inA = this.contains(a);\n    const inB = this.contains(b);\n    if (inA !== inB) return 1;\n    if (inA) return 0;\n\n    // Both ends outside: the step crosses twice iff it passes through the\n    // interior.\n    const box = this.bounds();\n    if (a.y === b.y) {\n      if (!(a.y > box.min.y && a.y < box.max.y)) return 0;\n      const lo = Math.min(a.x, b.x);\n      const hi = Math.max(a.x, b.x);\n      return lo < box.max.x && hi > box.min.x ? 2 : 0;\n    }\n    if (a.x === b.x) {\n      if (!(a.x > box.min.x && a.x < box.max.x)) return 0;\n      const lo = Math.min(a.y, b.y);\n      const hi = Math.max(a.y, b.y);\n      return lo < box.max.y && hi > box.min.y ? 2 : 0;\n    }\n    // Orthogonal routing never produces diagonal steps.\n    return 0;\n  }\n\n  // Length of the axis-aligned step a→b that lies in this group's strict\n  // interior.  A step along the boundary itself contributes nothing.\n  interiorLength(a: Point, b: Point): number {\n    const box = this.bounds();\n    if (a.y === b.y) {\n      if (!(a.y > box.min.y && a.y < box.max.y)) return 0;\n      return Math.max(0, Math.min(Math.max(a.x, b.x), box.max.x) - Math.max(Math.min(a.x, b.x), box.min.x));\n    }\n    if (a.x === b.x) {\n      if (!(a.x > box.min.x && a.x < box.max.x)) return 0;\n      return Math.max(0, Math.min(Math.max(a.y, b.y), box.max.y) - Math.max(Math.min(a.y, b.y), box.min.y));\n    }\n    return 0;\n  }\n}\n\n// Total group-crossing cost of the step a→b.\nexport function groupCrossingCost(router: Router, a: Point, b: Point): number {\n  const penalty = router.params.groupCrossingPenalty;\n  if (penalty <= 0 || router.groups.length === 0) return 0;\n  let count = 0;\n  for (const group of router.groups) {\n    count += group.crossings(a, b);\n  }\n  return count * penalty;\n}\n\n// Extra cost of the step a→b for the distance it travels inside groups.\n// Every candidate route into a group pays its crossing equally, so without\n// this an edge is indifferent to where it enters — and the shortest route\n// often enters early and threads between the group's members.  Charging\n// interior distance makes it stay outside and enter near its endpoint.\nexport function groupInteriorCost(router: Router, a: Point, b: Point): number {\n  const factor = router.params.groupInteriorCost;\n  if (factor <= 0 || router.groups.length === 0) return 0;\n  let length = 0;\n  for (const group of router.groups) {\n    length += group.interiorLength(a, b);\n  }\n  return length * factor;\n}\n","import {Point, kShapeConnectionPin, Rect} from '../geomtypes';\nimport {Direction} from './Direction';\nimport {Obstacle} from './obstacle';\nimport {VertInf} from '../vertex';\n\nimport type {Edge} from './edge';\nimport type {Router} from '../router';\n\n// ─── Junction ────────────────────────────────────────────────────────────────\n\n// A junction between edges.\n//\n// Pure model — the constructor allocates internal state (centre vertex,\n// backing obstacle for fixed junctions) but performs **no** router-side\n// registration.  Callers must explicitly hand the junction to the router\n// via `router.addJunction(j)` / `router.deleteJunction(j)`.\n//\n// When `fixed === true` the junction owns a small backing `Obstacle`\n// (rectangle around `position`).  The router activates / deactivates that\n// obstacle alongside the junction itself; outside of `add/deleteJunction`\n// it should be treated as opaque internal state.\nexport class Junction<UserData = unknown> {\n  readonly router: Router;\n  readonly centreVertex: VertInf;\n  readonly attachedEdges: Set<Edge> = new Set();\n  userData: UserData | null = null;\n\n  readonly positionFixed: boolean;\n  /** @internal */ _obstacle: Obstacle | null = null;\n\n  private _position: Point;\n\n  constructor(router: Router, position: Point, fixed: boolean = false, userData: UserData | null = null) {\n    this.router = router;\n    this._position = new Point(position.x, position.y);\n    this.positionFixed = fixed;\n    this.userData = userData;\n\n    this.centreVertex = new VertInf(router._assignObjectId(), kShapeConnectionPin, position, {\n      isConnPoint: true,\n      isJunctionCentre: true,\n    });\n    this.centreVertex.visDirections = Direction.all;\n\n    if (fixed) {\n      this._obstacle = new Obstacle(this.router, Junction.makeRectangle(this.router, this._position));\n    }\n  }\n\n  // ─── Public API ─────────────────────────────────────────────────────────────\n\n  // Returns the position of this junction.\n  position(): Point {\n    return this._position;\n  }\n\n  // Mutates the in-memory junction position.  HyperedgeImprover calls this\n  // to commit the result of its junction-shifting passes before\n  // ImproveOrthogonalRoutes runs — without it, the orthogonal nudger reads\n  // the stale MTST-time `_position` and fails to treat the new location as\n  // a pinned anchor for junction-attached segments.\n  //\n  // Also drags the centre vertex to the new position.  If the junction is\n  // position-fixed (and therefore owns a backing obstacle), the obstacle is\n  // re-created at the new position so its routing rectangle stays in sync.\n  _setPosition(position: Point): void {\n    this._position = new Point(position.x, position.y);\n    this.centreVertex.point = new Point(position.x, position.y);\n    this.centreVertex.point.vn = kShapeConnectionPin;\n    if (this._obstacle !== null) {\n      const wasRegistered = this.router.obstacles.includes(this._obstacle);\n      if (wasRegistered) this.router.deleteObstacle(this._obstacle);\n      this._obstacle = new Obstacle(this.router, Junction.makeRectangle(this.router, this._position));\n      if (wasRegistered) this.router.addObstacle(this._obstacle);\n    }\n  }\n\n  // ─── Internal helpers ──────────────────────────────────────────────────────\n\n  // Constructs the small routing rectangle used when the junction owns a\n  // backing obstacle.  Sides are `idealNudgingDistance` (capped at 1.0)\n  // wide, centred on `position`.  Static so tests can call it without\n  // instantiating a Junction.\n  static makeRectangle(router: Router, position: Point): Rect {\n    const nudgeDist = Math.min(1.0, router.params.idealNudgingDistance);\n    const low = new Point(position.x - nudgeDist, position.y - nudgeDist);\n    return new Rect({x: low.x, y: low.y}, {width: nudgeDist * 2, height: nudgeDist * 2});\n  }\n}\n","// ─── Pipeline / Step ─────────────────────────────────────────────────────────\n//\n// Lightweight orchestration scaffolding shared by `Router.route()` and\n// `HyperedgeImprover.execute()`.  A pipeline is a fixed, ordered sequence of\n// `Step`s that mutate a shared context object — typically the router plus\n// per-run scratch state.\n//\n// Each step has:\n//   • `name`         — short label used for telemetry / log lines.\n//   • `shouldRun(ctx)` — predicate gating execution; defaults to `true`.\n//   • `execute(ctx)` — the work.\n//\n// Steps don't return data — anything later steps need is written onto the\n// context object.  Looping or parameterised work (e.g. the improver's 4-pass\n// dimension cycle) is expressed by a single step that wraps its own inner\n// `Pipeline`.\n\nexport abstract class Step<Context> {\n  abstract readonly name: string;\n\n  shouldRun(_context: Context): boolean {\n    return true;\n  }\n\n  abstract execute(context: Context): void;\n}\n\nexport class Pipeline<Context> {\n  constructor(readonly steps: ReadonlyArray<Step<Context>>) {}\n\n  run(context: Context): void {\n    for (const step of this.steps) {\n      if (!step.shouldRun(context)) continue;\n      step.execute(context);\n    }\n  }\n}\n","import {Point} from '../geomtypes.ts';\nimport {Direction} from './Direction.ts';\n\n// ─── Endpoint ────────────────────────────────────────────────────────────────\n\n// Free-point endpoint for a connector — a position plus its allowed entry /\n// exit directions.  Junction-anchored endpoints are passed to `Edge`\n// directly as `Junction` instances; the Edge constructor's `instanceof`\n// dispatch picks the right storage.\n//\n// This is purely an argument-shape now — `Edge` never stores an Endpoint\n// internally (it extracts the fields).  No back-pointer to the owning Edge,\n// no connect/disconnect lifecycle: that bookkeeping moved to `Junction`'s\n// `attachedEdges` registry.\nexport class Endpoint {\n  position: Point;\n  directions: Direction;\n\n  constructor(position: Point, directions: Direction = Direction.all) {\n    this.position = position;\n    this.directions = directions;\n  }\n}\n","import {Direction} from './Direction';\nimport type {Point} from '../geomtypes';\n\n// ─── Checkpoint ──────────────────────────────────────────────────────────────\n// A point that a connector route must visit, with optional arrival/departure\n// direction constraints.\n\nexport class Checkpoint {\n  point: Point;\n  arrivalDirections: Direction;\n  departureDirections: Direction;\n\n  constructor(point: Point, arrivalDirections = Direction.all, departureDirections = Direction.all) {\n    this.point = point;\n    this.arrivalDirections = arrivalDirections;\n    this.departureDirections = departureDirections;\n  }\n}\n","import {vecDir, Point, type Polygon} from './geomtypes';\n\n// ─── Intersection result codes ────────────────────────────────────────────────\n\nexport const DONT_INTERSECT = 0;\nexport const DO_INTERSECT = 1;\nexport const PARALLEL = 3;\n\n// ─── Pure geometry utilities ──────────────────────────────────────────────────\n\n// Returns the Manhattan distance between points a and b.\nexport function manhattanDist(a: Point, b: Point): number {\n  return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);\n}\n\nexport function inBetween(a: Point, b: Point, c: Point): boolean {\n  const epsilon = Number.EPSILON;\n  if (Math.abs(a.x - b.x) > epsilon) {\n    // Not vertical — compare x.\n    return (a.x < c.x && c.x < b.x) || (b.x < c.x && c.x < a.x);\n  } else {\n    return (a.y < c.y && c.y < b.y) || (b.y < c.y && c.y < a.y);\n  }\n}\n\n// ─── Collinearity / between-ness ─────────────────────────────────────────────\n\n// Returns true iff c lies on the closed segment ab (inclusive of endpoints).\nexport function pointOnLine(a: Point, b: Point, c: Point, tolerance = 0): boolean {\n  if (a.x === b.x) {\n    return a.x === c.x && ((a.y < c.y && c.y < b.y) || (b.y < c.y && c.y < a.y));\n  }\n  if (a.y === b.y) {\n    return a.y === c.y && ((a.x < c.x && c.x < b.x) || (b.x < c.x && c.x < a.x));\n  }\n  return vecDir(a, b, c, tolerance) === 0 && inBetween(a, b, c);\n}\n\n// ─── Intersection tests ───────────────────────────────────────────────────────\n\n// Returns true if segment cd properly intersects segment ab (blocking\n// visibility).  Endpoint-touching cases are excluded.\nexport function segmentIntersect(a: Point, b: Point, c: Point, d: Point): boolean {\n  const ab_c = vecDir(a, b, c);\n  if (ab_c === 0) return false;\n\n  const ab_d = vecDir(a, b, d);\n  if (ab_d === 0) return false;\n\n  const cd_a = vecDir(c, d, a);\n  const cd_b = vecDir(c, d, b);\n\n  return ab_c * ab_d < 0 && cd_a * cd_b < 0;\n}\n\n// Returns true if segment e1–e2 intersects shape boundary segment s1–s2,\n// blocking visibility.  seenIntersectionAtEndpoint is a shared mutable box:\n// endpoint touches are allowed once, then block on the second occurrence.\nexport function segmentShapeIntersect(\n  e1: Point,\n  e2: Point,\n  s1: Point,\n  s2: Point,\n  seenIntersectionAtEndpoint: {value: boolean},\n): boolean {\n  if (segmentIntersect(e1, e2, s1, s2)) {\n    return true;\n  }\n\n  const e1TouchesS = s2.eq(e1) || pointOnLine(s1, s2, e1);\n  const e2TouchesS = s2.eq(e2) || pointOnLine(s1, s2, e2);\n\n  if ((e1TouchesS && vecDir(s1, s2, e2) !== 0) || (e2TouchesS && vecDir(s1, s2, e1) !== 0)) {\n    if (seenIntersectionAtEndpoint.value) {\n      return true;\n    }\n    seenIntersectionAtEndpoint.value = true;\n  }\n  return false;\n}\n\n// ─── Point-in-polygon ─────────────────────────────────────────────────────────\n\n// Fast convex-polygon test.  Returns true iff q is inside (or on the border\n// when countBorder is true) the convex polygon poly.\nexport function inPoly(poly: Polygon, q: Point, countBorder = true): boolean {\n  const n = poly.size();\n  const P = poly.ps;\n  let onBorder = false;\n  for (let i = 0; i < n; i++) {\n    const prev = (i + n - 1) % n;\n    const dir = vecDir(P[prev], P[i], q);\n    if (dir === -1) {\n      return false; // outside\n    }\n    onBorder = onBorder || dir === 0;\n  }\n  if (!countBorder && onBorder) {\n    return false;\n  }\n\n  return true;\n}\n\n// ─── Region / visibility helpers ─────────────────────────────────────────────\n\n// Returns the side (+1 anticlockwise / -1 clockwise) of corner c1–c2–c3\n// that point p lies on.\nexport function cornerSide(c1: Point, c2: Point, c3: Point, p: Point): number {\n  const s123 = vecDir(c1, c2, c3);\n  const s12p = vecDir(c1, c2, p);\n  const s23p = vecDir(c2, c3, p);\n\n  if (s123 === 1) {\n    return s12p >= 0 && s23p >= 0 ? 1 : -1;\n  }\n  if (s123 === -1) {\n    return s12p <= 0 && s23p <= 0 ? -1 : 1;\n  }\n  // c1–c2–c3 collinear: use vecDir from c1–c2.\n  return s12p;\n}\n\n// ─── Intersection-point solvers ───────────────────────────────────────────────\n\nexport interface IntersectResult {\n  code: typeof DONT_INTERSECT | typeof DO_INTERSECT | typeof PARALLEL;\n  x: number;\n  y: number;\n}\n\n// Segment-intersection with intersection-point output.\n// Based on Franklin Antonio, Graphics Gems III.\nexport function segmentIntersectPoint(a1: Point, a2: Point, b1: Point, b2: Point): IntersectResult {\n  const Ax = a2.x - a1.x;\n  const Bx = b1.x - b2.x;\n\n  // X bounding-box test.\n  let x1lo: number, x1hi: number;\n  if (Ax < 0) {\n    x1lo = a2.x;\n    x1hi = a1.x;\n  } else {\n    x1hi = a2.x;\n    x1lo = a1.x;\n  }\n\n  if (Bx > 0) {\n    if (x1hi < b2.x || b1.x < x1lo) return {code: DONT_INTERSECT, x: 0, y: 0};\n  } else {\n    if (x1hi < b1.x || b2.x < x1lo) return {code: DONT_INTERSECT, x: 0, y: 0};\n  }\n\n  const Ay = a2.y - a1.y;\n  const By = b1.y - b2.y;\n\n  // Y bounding-box test.\n  let y1lo: number, y1hi: number;\n  if (Ay < 0) {\n    y1lo = a2.y;\n    y1hi = a1.y;\n  } else {\n    y1hi = a2.y;\n    y1lo = a1.y;\n  }\n\n  if (By > 0) {\n    if (y1hi < b2.y || b1.y < y1lo) return {code: DONT_INTERSECT, x: 0, y: 0};\n  } else {\n    if (y1hi < b1.y || b2.y < y1lo) return {code: DONT_INTERSECT, x: 0, y: 0};\n  }\n\n  const Cx = a1.x - b1.x;\n  const Cy = a1.y - b1.y;\n  const d = By * Cx - Bx * Cy; // alpha numerator\n  const f = Ay * Bx - Ax * By; // common denominator\n\n  // Alpha tests.\n  if (f > 0) {\n    if (d < 0 || d > f) return {code: DONT_INTERSECT, x: 0, y: 0};\n  } else {\n    if (d > 0 || d < f) return {code: DONT_INTERSECT, x: 0, y: 0};\n  }\n\n  const e = Ax * Cy - Ay * Cx; // beta numerator\n\n  // Beta tests.\n  if (f > 0) {\n    if (e < 0 || e > f) return {code: DONT_INTERSECT, x: 0, y: 0};\n  } else {\n    if (e > 0 || e < f) return {code: DONT_INTERSECT, x: 0, y: 0};\n  }\n\n  if (f === 0) return {code: PARALLEL, x: 0, y: 0};\n\n  const x = a1.x + (d * Ax) / f;\n  const y = a1.y + (d * Ay) / f;\n  return {code: DO_INTERSECT, x, y};\n}\n","import type {Edge} from '../models/edge';\nimport type {Point} from '../geomtypes';\n\nexport type PtConnPtrPair = [Point, Edge];\nexport type PointRepVector = PtConnPtrPair[];\n\n// Point → PtOrder map keyed by coordinates, mirroring the C++\n// `std::map<Point, PtOrder>`.  Order info is built from cloned routes and\n// looked up with the nudging segments' points, so keys must compare by value\n// rather than by `Point` identity.\nexport class PtOrderMap {\n  private map = new Map<string, PtOrder>();\n\n  private static key(p: Point): string {\n    return `${p.x},${p.y}`;\n  }\n\n  get(p: Point): PtOrder | undefined {\n    return this.map.get(PtOrderMap.key(p));\n  }\n\n  getOrCreate(p: Point): PtOrder {\n    const key = PtOrderMap.key(p);\n    let order = this.map.get(key);\n    if (!order) {\n      order = new PtOrder();\n      this.map.set(key, order);\n    }\n    return order;\n  }\n}\n\nexport class PtOrder {\n  private sorted: [boolean, boolean] = [false, false];\n  private nodes: [PointRepVector, PointRepVector] = [[], []];\n  private links: [Array<[number, number]>, Array<[number, number]>] = [[], []];\n  private sortedConnVector: [PointRepVector, PointRepVector] = [[], []];\n\n  addPoints(dim: number, arg1: PtConnPtrPair, arg2: PtConnPtrPair): void {\n    this.insertPoint(dim, arg1);\n    this.insertPoint(dim, arg2);\n  }\n\n  addOrderedPoints(dim: number, inner: PtConnPtrPair, outer: PtConnPtrPair, swapped: boolean): void {\n    const actualInner = swapped ? outer : inner;\n    const actualOuter = swapped ? inner : outer;\n\n    const innerIndex = this.insertPoint(dim, actualInner);\n    const outerIndex = this.insertPoint(dim, actualOuter);\n\n    // Edge: outerIndex -> innerIndex (outer comes first in sorted order).\n    this.links[dim].push([outerIndex, innerIndex]);\n  }\n\n  positionFor(dim: number, conn: Edge): number {\n    if (!this.sorted[dim]) {\n      this.sort(dim);\n    }\n    const sv = this.sortedConnVector[dim];\n    for (let i = 0; i < sv.length; ++i) {\n      if (sv[i][1] === conn) {\n        return i;\n      }\n    }\n    return -1;\n  }\n\n  sortedPoints(dim: number): PointRepVector {\n    if (!this.sorted[dim]) {\n      this.sort(dim);\n    }\n    return this.sortedConnVector[dim];\n  }\n\n  private insertPoint(dim: number, point: PtConnPtrPair): number {\n    // Is this connector's bendpoint already inserted?\n    const n = this.nodes[dim];\n    for (let i = 0; i < n.length; ++i) {\n      if (n[i][1] === point[1]) {\n        return i;\n      }\n    }\n    // Not found — insert.\n    n.push(point);\n    return n.length - 1;\n  }\n\n  private sort(dim: number): void {\n    // Topological sort of the points using the edge/dependency info.\n    this.sorted[dim] = true;\n\n    const n = this.nodes[dim].length;\n    if (n === 0) {\n      this.sortedConnVector[dim] = [];\n      return;\n    }\n\n    // Build adjacency matrix.\n    const adjacencyMatrix: boolean[][] = Array.from({length: n}, () => new Array<boolean>(n).fill(false));\n    for (const [from, to] of this.links[dim]) {\n      adjacencyMatrix[from][to] = true;\n    }\n\n    // Build incoming-degree counts.\n    const incomingDegree: number[] = new Array<number>(n).fill(0);\n    for (let i = 0; i < n; ++i) {\n      for (let j = 0; j < n; ++j) {\n        if (adjacencyMatrix[j][i]) {\n          incomingDegree[i]++;\n        }\n      }\n    }\n\n    // Seed queue with nodes that have no incoming edges.\n    const queue: number[] = [];\n    for (let i = 0; i < n; ++i) {\n      if (incomingDegree[i] === 0) {\n        queue.push(i);\n      }\n    }\n\n    const result: PointRepVector = [];\n    while (queue.length > 0) {\n      const k = queue.shift()!;\n      result.push(this.nodes[dim][k]);\n\n      for (let i = 0; i < n; ++i) {\n        if (adjacencyMatrix[k][i]) {\n          adjacencyMatrix[k][i] = false;\n          incomingDegree[i]--;\n          if (incomingDegree[i] === 0) {\n            queue.push(i);\n          }\n        }\n      }\n    }\n\n    this.sortedConnVector[dim] = result;\n  }\n}\n","import {\n  Edge,\n  CROSSING_NONE,\n  splitBranchingSegments,\n  CROSSING_SHARES_PATH,\n  CROSSING_SHARES_FIXED_SEGMENT,\n  posInlineWithConnEndSegs,\n  CROSSING_SHARES_PATH_AT_END,\n  pathLengthFromIndices,\n  segDir,\n  CROSSING_TOUCHES,\n} from '../models/edge';\nimport {PtOrderMap} from './PtOrder';\nimport {cornerSide, segmentIntersectPoint, DO_INTERSECT} from '../geometry';\nimport {Polygon, Point, vecDir} from '../geomtypes';\n\nexport class ConnectorCrossings {\n  poly: Polygon;\n  polyIsConn: boolean;\n  conn: Polygon;\n  checkForBranchingSegments: boolean;\n  polyConnRef: Edge | null;\n  connConnRef: Edge | null;\n\n  crossingCount: number;\n  crossingFlags: number;\n  crossingPoints: Set<Point> | null;\n  pointOrders: PtOrderMap | null;\n  sharedPaths: Point[][] | null;\n\n  firstSharedPathAtEndLength: number;\n  secondSharedPathAtEndLength: number;\n\n  constructor(\n    poly: Polygon,\n    polyIsConn: boolean,\n    conn: Polygon,\n    polyConnRef: Edge | null = null,\n    connConnRef: Edge | null = null,\n  ) {\n    this.poly = poly;\n    this.polyIsConn = polyIsConn;\n    this.conn = conn;\n    this.checkForBranchingSegments = false;\n    this.polyConnRef = polyConnRef;\n    this.connConnRef = connConnRef;\n    this.crossingCount = 0;\n    this.crossingFlags = CROSSING_NONE;\n    this.crossingPoints = null;\n    this.pointOrders = null;\n    this.sharedPaths = null;\n    this.firstSharedPathAtEndLength = Number.MAX_VALUE;\n    this.secondSharedPathAtEndLength = Number.MAX_VALUE;\n  }\n\n  clear(): void {\n    this.crossingCount = 0;\n    this.crossingFlags = CROSSING_NONE;\n    this.firstSharedPathAtEndLength = Number.MAX_VALUE;\n    this.secondSharedPathAtEndLength = Number.MAX_VALUE;\n  }\n\n  // Works out if the segment conn[cIndex-1]--conn[cIndex] really crosses poly.\n  // This does not count non-crossing shared paths as crossings.\n  // poly can be either a connector (polyIsConn = true) or a cluster\n  // boundary (polyIsConn = false).\n  countForSegment(cIndex: number, finalSegment: boolean): void {\n    this.clear();\n\n    // All connectors are orthogonal in this port — true iff the ConnRef\n    // exists.  Kept as locals so the downstream checks read clearly.\n    const polyIsOrthogonal = this.polyConnRef !== null;\n    const connIsOrthogonal = this.connConnRef !== null;\n\n    // We need to split apart connectors at potential crossing points if\n    // either has a fixed route or it is a polyline connector.\n    if (this.checkForBranchingSegments || !polyIsOrthogonal || !connIsOrthogonal) {\n      const epsilon = Number.EPSILON;\n      const conn_pn = this.conn.size();\n      const tolerance = !this.polyIsConn ? epsilon : 0.0;\n      splitBranchingSegments(this.poly, this.polyIsConn, this.conn, tolerance);\n      // cIndex is going to be the last, so take into account added points.\n      cIndex += this.conn.size() - conn_pn;\n    }\n\n    const poly_size = this.poly.size();\n\n    // c_path and p_path are index arrays into conn.ps and poly.ps.\n    const max_path_size = Math.min(poly_size, this.conn.size());\n    const c_path: number[] = new Array(max_path_size);\n    const p_path: number[] = new Array(max_path_size);\n    let size = 0;\n\n    const a1 = this.conn.ps[cIndex - 1];\n    const a2 = this.conn.ps[cIndex];\n\n    for (let j = this.polyIsConn ? 1 : 0; j < poly_size; ++j) {\n      const b1_idx = (j - 1 + poly_size) % poly_size;\n      const b2_idx = j;\n      const b1 = this.poly.ps[b1_idx];\n      const b2 = this.poly.ps[b2_idx];\n\n      size = 0;\n\n      let converging = false;\n\n      const a1_eq_b1 = a1.eq(b1);\n      const a2_eq_b1 = a2.eq(b1);\n      const a2_eq_b2 = a2.eq(b2);\n      const a1_eq_b2 = a1.eq(b2);\n\n      if ((a1_eq_b1 && a2_eq_b2) || (a2_eq_b1 && a1_eq_b2)) {\n        if (finalSegment) {\n          converging = true;\n        } else {\n          // Route along same segment: no penalty. We detect crossovers when\n          // we see the segments diverge.\n          continue;\n        }\n      } else if (a2_eq_b1 || a2_eq_b2 || a1_eq_b2) {\n        // Each crossing that is at a vertex in the visibility graph gets\n        // noticed four times. We ignore three of these cases.\n        continue;\n      }\n\n      if (a1_eq_b1 || converging) {\n        if (!converging) {\n          if (this.polyIsConn && j === 1) {\n            // Can't be the end of a shared path or crossing path since the\n            // common point is the first point of the connector path.\n            continue;\n          }\n\n          const b0_idx = (j - 2 + poly_size) % poly_size;\n          const b0 = this.poly.ps[b0_idx];\n          if (a2.eq(b0)) {\n            // a2 is not a split, continue.\n            continue;\n          }\n        }\n\n        let shared_path = false;\n        let p_dir_back = false;\n        let p_dir = 0;\n        let trace_c = 0;\n        let trace_p = 0;\n\n        if (converging) {\n          p_dir_back = a2_eq_b2;\n          p_dir = p_dir_back ? -1 : 1;\n          trace_c = cIndex;\n          trace_p = j;\n          if (!p_dir_back) {\n            if (finalSegment) {\n              trace_p--;\n            } else {\n              trace_c--;\n            }\n          }\n          shared_path = true;\n        } else if (cIndex >= 2) {\n          const b0_idx = (j - 2 + poly_size) % poly_size;\n          const b0 = this.poly.ps[b0_idx];\n          const a0 = this.conn.ps[cIndex - 2];\n\n          if (a0.eq(b2) || a0.eq(b0)) {\n            p_dir_back = a0.eq(b0);\n            p_dir = p_dir_back ? -1 : 1;\n            trace_c = cIndex;\n            trace_p = p_dir_back ? j : j - 2;\n            shared_path = true;\n          }\n        }\n\n        if (shared_path) {\n          this.crossingFlags |= CROSSING_SHARES_PATH;\n\n          // Build the shared path, including the diverging points at each end.\n          while (trace_c >= 0 && (!this.polyIsConn || (trace_p >= 0 && trace_p < poly_size))) {\n            const index_p = ((trace_p % poly_size) + poly_size) % poly_size;\n            const index_c = trace_c;\n            c_path[size] = index_c;\n            p_path[size] = index_p;\n            ++size;\n            if (size > 1 && !this.conn.ps[index_c].eq(this.poly.ps[index_p])) {\n              // Points don't match, so break out of loop.\n              break;\n            }\n            trace_c--;\n            trace_p += p_dir;\n          }\n\n          const front_same = this.conn.ps[c_path[0]].eq(this.poly.ps[p_path[0]]);\n          const back_same = this.conn.ps[c_path[size - 1]].eq(this.poly.ps[p_path[size - 1]]);\n\n          // Determine if the shared path originates at a junction.\n          let terminatesAtJunction = false;\n          if (this.polyConnRef && this.connConnRef && (front_same || back_same)) {\n            const connJunction = front_same ? this.connConnRef.dstJunction : this.connConnRef.srcJunction;\n            let use_first = back_same;\n            if (p_dir_back) {\n              use_first = !use_first;\n            }\n            const polyJunction = use_first ? this.polyConnRef.dstJunction : this.polyConnRef.srcJunction;\n\n            terminatesAtJunction = !!(connJunction && connJunction === polyJunction);\n          }\n\n          if (this.sharedPaths) {\n            const start = front_same ? 0 : 1;\n            const limit = size - (back_same ? 0 : 1);\n            const sPath: Point[] = [];\n            for (let pi = start; pi < limit; ++pi) {\n              sPath.push(this.conn.ps[c_path[pi]]);\n            }\n            this.sharedPaths.push(sPath);\n          }\n\n          // Check to see if these share a fixed segment.\n          if (polyIsOrthogonal && connIsOrthogonal) {\n            const startPt = front_same ? 0 : 1;\n            const endPt = size - (back_same ? 1 : 2);\n            for (let dim = 0; dim < 2; ++dim) {\n              if (this.conn.ps[c_path[startPt]].at(dim) === this.conn.ps[c_path[endPt]].at(dim)) {\n                const pos = this.conn.ps[c_path[startPt]].at(dim);\n                if (\n                  (pos === this.poly.ps[0].at(dim) || pos === this.poly.ps[poly_size - 1].at(dim)) &&\n                  (pos === this.conn.ps[0].at(dim) || pos === this.conn.ps[cIndex].at(dim)) &&\n                  !terminatesAtJunction\n                ) {\n                  this.crossingFlags |= CROSSING_SHARES_FIXED_SEGMENT;\n                }\n              }\n            }\n\n            if (!front_same && !back_same) {\n              for (let dim = 0; dim < 2; ++dim) {\n                const end = size - 1;\n                const altDim = (dim + 1) % 2;\n                if (this.conn.ps[c_path[1]].at(altDim) === this.conn.ps[c_path[end - 1]].at(altDim)) {\n                  const posBeg = this.conn.ps[c_path[1]].at(dim);\n                  const posEnd = this.conn.ps[c_path[end - 1]].at(dim);\n                  if (\n                    posBeg === this.conn.ps[c_path[0]].at(dim) &&\n                    posBeg === this.poly.ps[p_path[0]].at(dim) &&\n                    posEnd === this.conn.ps[c_path[end]].at(dim) &&\n                    posEnd === this.poly.ps[p_path[end]].at(dim)\n                  ) {\n                    if (\n                      posInlineWithConnEndSegs(posBeg, dim, this.conn, this.poly) &&\n                      posInlineWithConnEndSegs(posEnd, dim, this.conn, this.poly)\n                    ) {\n                      this.crossingFlags |= CROSSING_SHARES_FIXED_SEGMENT;\n                    }\n                  }\n                }\n              }\n            }\n          }\n\n          // Determine corner sides at start/end of shared path.\n          let startCornerSide = 1;\n          let endCornerSide = 1;\n\n          if (!front_same) {\n            startCornerSide = cornerSide(\n              this.conn.ps[c_path[0]],\n              this.conn.ps[c_path[1]],\n              this.conn.ps[c_path[2]],\n              this.poly.ps[p_path[0]],\n            );\n          }\n          if (!back_same) {\n            endCornerSide = cornerSide(\n              this.conn.ps[c_path[size - 3]],\n              this.conn.ps[c_path[size - 2]],\n              this.conn.ps[c_path[size - 1]],\n              this.poly.ps[p_path[size - 1]],\n            );\n          } else {\n            endCornerSide = startCornerSide;\n          }\n          if (front_same) {\n            startCornerSide = endCornerSide;\n          }\n\n          if (endCornerSide !== startCornerSide) {\n            this.crossingCount += 1;\n            if (this.crossingPoints) {\n              this.crossingPoints.add(this.conn.ps[c_path[1]]);\n            }\n          }\n\n          if (front_same || back_same) {\n            this.crossingFlags |= CROSSING_SHARES_PATH_AT_END;\n\n            const straightModifier = 200;\n            this.firstSharedPathAtEndLength = this.secondSharedPathAtEndLength = pathLengthFromIndices(\n              this.conn,\n              this.poly,\n              c_path,\n              p_path,\n              size,\n            );\n\n            if (back_same && size > 2) {\n              if (vecDir(this.poly.ps[p_path[0]], this.poly.ps[p_path[1]], this.poly.ps[p_path[2]]) === 0) {\n                this.firstSharedPathAtEndLength -= straightModifier;\n              }\n              if (vecDir(this.conn.ps[c_path[0]], this.conn.ps[c_path[1]], this.conn.ps[c_path[2]]) === 0) {\n                this.secondSharedPathAtEndLength -= straightModifier;\n              }\n            } else if (front_same && size > 2) {\n              if (\n                vecDir(\n                  this.poly.ps[p_path[size - 3]],\n                  this.poly.ps[p_path[size - 2]],\n                  this.poly.ps[p_path[size - 1]],\n                ) === 0\n              ) {\n                this.firstSharedPathAtEndLength -= straightModifier;\n              }\n              if (\n                vecDir(\n                  this.conn.ps[c_path[size - 3]],\n                  this.conn.ps[c_path[size - 2]],\n                  this.conn.ps[c_path[size - 1]],\n                ) === 0\n              ) {\n                this.secondSharedPathAtEndLength -= straightModifier;\n              }\n            }\n          } else if (polyIsOrthogonal && connIsOrthogonal) {\n            const cStartDir = vecDir(this.conn.ps[c_path[0]], this.conn.ps[c_path[1]], this.conn.ps[c_path[2]]);\n            const pStartDir = vecDir(this.poly.ps[p_path[0]], this.poly.ps[p_path[1]], this.poly.ps[p_path[2]]);\n            if (cStartDir !== 0 && cStartDir === -pStartDir) {\n              startCornerSide = -cStartDir;\n            } else {\n              const cEndDir = vecDir(\n                this.conn.ps[c_path[size - 3]],\n                this.conn.ps[c_path[size - 2]],\n                this.conn.ps[c_path[size - 1]],\n              );\n              const pEndDir = vecDir(\n                this.poly.ps[p_path[size - 3]],\n                this.poly.ps[p_path[size - 2]],\n                this.poly.ps[p_path[size - 1]],\n              );\n              if (cEndDir !== 0 && cEndDir === -pEndDir) {\n                startCornerSide = -cEndDir;\n              }\n            }\n          }\n\n          if (this.pointOrders) {\n            let reversed = false;\n            const startPt = front_same ? 0 : 1;\n\n            if (startCornerSide > 0) {\n              reversed = !reversed;\n            }\n\n            let prevDir = 0;\n            const adj_size = size - (back_same ? 0 : 1);\n            for (let pi = startPt; pi < adj_size; ++pi) {\n              const an = this.conn.ps[c_path[pi]];\n              const bn = this.poly.ps[p_path[pi]];\n\n              if (pi > startPt) {\n                const ap = this.conn.ps[c_path[pi - 1]];\n                const bp = this.poly.ps[p_path[pi - 1]];\n\n                const thisDir = segDir(ap, an);\n                if (prevDir === 0) {\n                  if (thisDir > 0) {\n                    reversed = !reversed;\n                  }\n                } else if (thisDir !== prevDir) {\n                  reversed = !reversed;\n                }\n\n                const orientation = ap.x === an.x ? 0 : 1;\n\n                // Get or create PtOrder for an.\n                const ptOrderAn = this.pointOrders.getOrCreate(an);\n                ptOrderAn.addOrderedPoints(orientation, [bn, this.polyConnRef!], [an, this.connConnRef!], reversed);\n\n                const ptOrderAp = this.pointOrders.getOrCreate(ap);\n                ptOrderAp.addOrderedPoints(orientation, [bp, this.polyConnRef!], [ap, this.connConnRef!], reversed);\n\n                prevDir = thisDir;\n              }\n            }\n          }\n\n          this.crossingFlags |= CROSSING_TOUCHES;\n        } else if (cIndex >= 2) {\n          // The connectors cross or touch at this point.\n          const b0_idx = (j - 2 + poly_size) % poly_size;\n          const b0 = this.poly.ps[b0_idx];\n          const a0 = this.conn.ps[cIndex - 2];\n\n          const side1 = cornerSide(a0, a1, a2, b0);\n          const side2 = cornerSide(a0, a1, a2, b2);\n          if (side1 !== side2) {\n            this.crossingCount += 1;\n            if (this.crossingPoints) {\n              this.crossingPoints.add(a1);\n            }\n          }\n\n          this.crossingFlags |= CROSSING_TOUCHES;\n\n          if (this.pointOrders) {\n            if (polyIsOrthogonal && connIsOrthogonal) {\n              const reversedX = a0.x < a1.x || a2.x < a1.x;\n              const reversedY = a0.y < a1.y || a2.y < a1.y;\n              const ptOrderB1 = this.pointOrders.getOrCreate(b1);\n              ptOrderB1.addOrderedPoints(0, [b1, this.polyConnRef!], [a1, this.connConnRef!], !reversedX);\n              ptOrderB1.addOrderedPoints(1, [b1, this.polyConnRef!], [a1, this.connConnRef!], !reversedY);\n            }\n          }\n        }\n      } else {\n        // No endpoint is shared between these two line segments,\n        // so just calculate normal segment intersection.\n        if (polyIsOrthogonal && connIsOrthogonal) {\n          // All crossings in orthogonal connectors will be at a vertex in\n          // the visibility graph, so we need not bother doing normal line\n          // intersection.\n          continue;\n        }\n\n        const result = segmentIntersectPoint(a1, a2, b1, b2);\n\n        if (result.code === DO_INTERSECT) {\n          const cPt = new Point(result.x, result.y);\n          if (!this.polyIsConn && (a1.eq(cPt) || a2.eq(cPt) || b1.eq(cPt) || b2.eq(cPt))) {\n            continue;\n          }\n          this.crossingCount += 1;\n          if (this.crossingPoints) {\n            this.crossingPoints.add(cPt);\n          }\n        }\n      }\n    }\n  }\n}\n","export class BinaryHeap<T> {\n  content: T[] = [];\n  private less: (a: T, b: T) => boolean;\n\n  // `less(a, b) === true` means `a` outranks `b` (closer to the top).\n  constructor(less: (a: T, b: T) => boolean) {\n    this.less = less;\n  }\n\n  get length() {\n    return this.content.length;\n  }\n\n  front(): T | undefined {\n    return this.content.at(0);\n  }\n\n  push(v: T): void {\n    this.content.push(v);\n    this.bubbleUp(this.content.length - 1);\n  }\n\n  pop(): T {\n    const top = this.content[0];\n    const last = this.content.pop()!;\n    if (this.content.length > 0) {\n      this.content[0] = last;\n      this.bubbleDown(0);\n    }\n    return top;\n  }\n\n  rebuild() {\n    for (let i = (this.content.length >> 1) - 1; i >= 0; i--) {\n      this.bubbleDown(i);\n    }\n  }\n\n  // Replace the underlying array (and re-heapify).\n  replaceWith(items: T[]): void {\n    this.content = items.slice();\n    this.rebuild();\n  }\n\n  contains(v: T): boolean {\n    return this.content.includes(v);\n  }\n\n  private bubbleUp(i: number): void {\n    while (i > 0) {\n      const parent = (i - 1) >> 1;\n      if (this.less(this.content[i], this.content[parent])) {\n        [this.content[i], this.content[parent]] = [this.content[parent], this.content[i]];\n        i = parent;\n      } else break;\n    }\n  }\n\n  private bubbleDown(i: number): void {\n    const n = this.content.length;\n    while (true) {\n      const l = i * 2 + 1;\n      const r = i * 2 + 2;\n      let best = i;\n      if (l < n && this.less(this.content[l], this.content[best])) {\n        best = l;\n      }\n      if (r < n && this.less(this.content[r], this.content[best])) {\n        best = r;\n      }\n      if (best === i) {\n        break;\n      }\n      [this.content[i], this.content[best]] = [this.content[best], this.content[i]];\n      i = best;\n    }\n  }\n}\n","// A* path search.\n//\n// Ports input/makepath.cpp.  The exported entry point is `AStarPath.search()`,\n// which performs an A* search through the router's visibility graph from\n// `src` to `tar`, populating each VertInf's `pathNext` pointer to reconstruct\n// the shortest path.\n\nimport {Point, vecDir, XDIM, YDIM} from './geomtypes';\nimport {VertInf} from './vertex';\nimport {manhattanDist} from './geometry';\nimport {CROSSING_SHARES_PATH, CROSSING_SHARES_FIXED_SEGMENT, CROSSING_SHARES_PATH_AT_END, Edge} from './models/edge';\nimport {ConnectorCrossings} from './data-structures/ConnectorCrossings';\nimport {Polygon} from './geomtypes';\nimport {BinaryHeap} from './utilities/heap';\nimport {Junction} from './models/junction';\nimport {Direction} from './models/Direction';\nimport {groupCrossingCost, groupInteriorCost} from './models/annotation-group';\n\n// ─── ConnRefLike for makepath ─────────────────────────────────────────────────\n// Structural interface for the connector — we don't import `ConnRef` directly\n// to avoid a tight coupling (the AStar code lives outside ConnRef but still\n// needs to introspect a few of its fields).\n\n// ─── ANode ────────────────────────────────────────────────────────────────────\n\n// Search node used in PENDING / Done lists.  Stored by pointer in C++; here\n// we just allocate plain instances.  Each VertInf maintains intrusive lists\n// (`aStarPendingNodes` / `aStarDoneNodes`) — see vertex.ts.\nexport class ANode {\n  inf: VertInf;\n  g: number; // Gone (cost so far)\n  h: number; // Heuristic (estimated remaining)\n  f: number; // f = g + h\n  prevNode: ANode | null;\n  timeStamp: number;\n\n  constructor(inf: VertInf, time = 0) {\n    this.inf = inf;\n    this.g = 0;\n    this.h = 0;\n    this.f = 0;\n    this.prevNode = null;\n    this.timeStamp = time;\n  }\n}\n\n// ─── Cardinal-direction helpers ───────────────────────────────────────────────\n//\n// makepath represents A* travel directions as a `Direction` (`OptionSet`) over\n// the four cardinal directions:\n//\n//   N ↔ Direction.blockStart   (up / -y)\n//   S ↔ Direction.blockEnd     (down / +y)\n//   E ↔ Direction.inlineEnd    (right / +x)\n//   W ↔ Direction.inlineStart  (left / -x)\n//\n// Note the rawValue bit layout differs from the legacy `CostDirectionN/E/S/W`\n// integer constants (N|S share bits 0–1; W|E share bits 2–3 instead of being\n// interleaved).  Combinations like \"north-east\" are expressed as\n// `DirN.add(DirE)`; tests against single cardinals use `.has(...)`, against\n// composite directions `.equal(...)`, and \"any overlap\" checks `.intersects()`.\nexport const DirN = Direction.blockStart;\nexport const DirS = Direction.blockEnd;\nexport const DirE = Direction.inlineEnd;\nexport const DirW = Direction.inlineStart;\nexport const DirAll = Direction.all;\n\nconst RIGHT_OF: Map<number, Direction> = new Map([\n  [DirN.rawValue, DirE],\n  [DirE.rawValue, DirS],\n  [DirS.rawValue, DirW],\n  [DirW.rawValue, DirN],\n]);\nconst LEFT_OF: Map<number, Direction> = new Map([\n  [DirN.rawValue, DirW],\n  [DirE.rawValue, DirN],\n  [DirS.rawValue, DirE],\n  [DirW.rawValue, DirS],\n]);\nconst REVERSE_OF: Map<number, Direction> = new Map([\n  [DirN.rawValue, DirS],\n  [DirE.rawValue, DirW],\n  [DirS.rawValue, DirN],\n  [DirW.rawValue, DirE],\n]);\n\nexport function orthogonalDirectionsCount(directions: Direction): number {\n  let count = 0;\n  if (directions.has(DirN)) count++;\n  if (directions.has(DirE)) count++;\n  if (directions.has(DirS)) count++;\n  if (directions.has(DirW)) count++;\n  return count;\n}\n\n// Returns the direction of b from a as a `Direction` (possibly a combination\n// of one vertical and one horizontal cardinal).  Empty when a === b.\nexport function orthogonalDirection(a: Point, b: Point): Direction {\n  let result = new Direction(0);\n  if (b.y > a.y) {\n    result = result.add(DirS);\n  } else if (b.y < a.y) {\n    result = result.add(DirN);\n  }\n\n  if (b.x > a.x) {\n    result = result.add(DirE);\n  } else if (b.x < a.x) {\n    result = result.add(DirW);\n  }\n  return result;\n}\n\nexport function dirRight(direction: Direction): Direction {\n  const r = RIGHT_OF.get(direction.rawValue);\n  if (!r) throw new Error('dirRight: invalid direction');\n  return r;\n}\n\nexport function dirLeft(direction: Direction): Direction {\n  const r = LEFT_OF.get(direction.rawValue);\n  if (!r) throw new Error('dirLeft: invalid direction');\n  return r;\n}\n\nexport function dirReverse(direction: Direction): Direction {\n  const r = REVERSE_OF.get(direction.rawValue);\n  if (!r) throw new Error('dirReverse: invalid direction');\n  return r;\n}\n\n// ─── bends() ──────────────────────────────────────────────────────────────────\n\n// Given Point curr with direction currDir, returns the minimum number of bends\n// to reach `dest` with the entry direction `destDir`.  Used for estimating the\n// bend penalty heuristic in orthogonal routing.\nexport function bends(curr: Point, currDir: Direction, dest: Point, destDir: Direction): number {\n  if (currDir.rawValue === 0) {\n    throw new Error('bends: currDir must be non-zero');\n  }\n  const currToDestDir = orthogonalDirection(curr, dest);\n  const reverseDestDir = dirReverse(destDir);\n  const currDirPerpendicularToDestDir = currDir.equal(dirLeft(destDir)) || currDir.equal(dirRight(destDir));\n\n  if (currDir.equal(destDir) && currToDestDir.equal(currDir)) return 0;\n\n  if (currDirPerpendicularToDestDir && currToDestDir.equal(destDir.add(currDir))) {\n    return 1;\n  }\n  if (currDirPerpendicularToDestDir && currToDestDir.equal(currDir)) return 1;\n  if (currDirPerpendicularToDestDir && currToDestDir.equal(destDir)) return 1;\n\n  if (currDir.equal(destDir) && !currToDestDir.equal(currDir) && !currToDestDir.intersects(reverseDestDir)) {\n    return 2;\n  }\n  if (currDir.equal(reverseDestDir) && !currToDestDir.equal(destDir) && !currToDestDir.equal(currDir)) {\n    return 2;\n  }\n  if (currDirPerpendicularToDestDir && !currToDestDir.equal(destDir.add(currDir)) && !currToDestDir.equal(currDir)) {\n    return 3;\n  }\n  if (currDir.equal(reverseDestDir) && (currToDestDir.equal(destDir) || currToDestDir.equal(currDir))) {\n    return 4;\n  }\n  if (currDir.equal(destDir) && currToDestDir.intersects(reverseDestDir)) {\n    return 4;\n  }\n\n  // Should not be reached.\n  return 0;\n}\n\n// ─── Angle helpers (for cost()) ───────────────────────────────────────────────\n\nfunction dot(l: Point, r: Point): number {\n  return l.x * r.x + l.y * r.y;\n}\n\nfunction crossLength(l: Point, r: Point): number {\n  return l.x * r.y - l.y * r.x;\n}\n\n// Returns the angle between line segments p1-p2 and p2-p3, in radians.\nexport function angleBetween(p1: Point, p2: Point, p3: Point): number {\n  if ((p1.x === p2.x && p1.y === p2.y) || (p2.x === p3.x && p2.y === p3.y)) {\n    return Math.PI;\n  }\n  const v1 = new Point(p1.x - p2.x, p1.y - p2.y);\n  const v2 = new Point(p3.x - p2.x, p3.y - p2.y);\n  return Math.abs(Math.atan2(crossLength(v1, v2), dot(v1, v2)));\n}\n\n// ─── constructPolygonPath ─────────────────────────────────────────────────────\n\n// Builds a temporary Polygon from the chain of ANode prevNodes plus the\n// pending step (inf2 → inf3).  Used for cluster-crossing and crossing-penalty\n// checks inside cost().  Collinear points are eliminated.\nexport function constructPolygonPath(connRoute: Polygon, inf2: VertInf, inf3: VertInf, inf1Node: ANode | null): void {\n  let routeSize = 2;\n  for (let curr = inf1Node; curr !== null; curr = curr.prevNode) {\n    routeSize += 1;\n  }\n  connRoute.ps = new Array(routeSize);\n  const arraySize = routeSize;\n  connRoute.ps[routeSize - 1] = inf3.point;\n  connRoute.ps[routeSize - 2] = inf2.point;\n  routeSize -= 3;\n  for (let curr = inf1Node; curr !== null; curr = curr.prevNode) {\n    const isJunctionCentre = curr.inf.isJunctionCentre;\n\n    if (curr === inf1Node || vecDir(curr.inf.point, connRoute.ps[routeSize + 1], connRoute.ps[routeSize + 2]) !== 0) {\n      // Earlier than the last segment and not collinear — keep it.\n      connRoute.ps[routeSize] = curr.inf.point;\n      routeSize -= 1;\n    } else {\n      // Collinear with the last segment — collapse it.\n      connRoute.ps[routeSize + 1] = curr.inf.point;\n    }\n\n    if (isJunctionCentre) {\n      // Stop at the junction — its centre vertex is the route's terminus.\n      break;\n    }\n  }\n\n  // Trim any unused front.\n  const diff = routeSize + 1;\n  if (diff > 0) {\n    for (let i = diff; i < arraySize; ++i) {\n      connRoute.ps[i - diff] = connRoute.ps[i];\n    }\n    connRoute.ps.length = arraySize - diff;\n  }\n}\n\n// Crossing test for two orthogonal segments — returns true when the segments\n// are perpendicular and meet inside one or both of them.\n//\n//   • `strict: true`   — meeting point must lie in the strict interior of\n//     BOTH segments (no endpoint touches).  Used to patch a gap in\n//     `ConnectorCrossings.countForSegment`'s orthogonal/orthogonal fast path\n//     for T-junction-style crossings.  Mirrors the helper of the same name\n//     in `improveCrossings.ts`.\n//   • `strict: false`  — T-junction-permissive: the meeting point must be in\n//     the strict interior of AT LEAST ONE segment (the other may touch at an\n//     endpoint).  A pure shared-corner touch (both endpoints meeting) is\n//     still rejected.  Used by the atCostTarget short-circuit in `cost()`\n//     where the new step endpoint frequently coincides with a vis-graph\n//     corner sitting on another connector's interior — strict alone would\n//     miss the visible crossing.\nfunction orthogonalSegmentsCross(a1: Point, a2: Point, b1: Point, b2: Point, strict: boolean): boolean {\n  const aVertical = a1.x === a2.x;\n  const bVertical = b1.x === b2.x;\n  if (aVertical === bVertical) return false;\n  const v1 = aVertical ? a1 : b1;\n  const v2 = aVertical ? a2 : b2;\n  const h1 = aVertical ? b1 : a1;\n  const h2 = aVertical ? b2 : a2;\n  const vX = v1.x;\n  const hY = h1.y;\n  const vyMin = Math.min(v1.y, v2.y);\n  const vyMax = Math.max(v1.y, v2.y);\n  const hxMin = Math.min(h1.x, h2.x);\n  const hxMax = Math.max(h1.x, h2.x);\n  const vxStrictInH = vX > hxMin && vX < hxMax;\n  const hyStrictInV = hY > vyMin && hY < vyMax;\n  if (strict) {\n    return vxStrictInH && hyStrictInV;\n  }\n  const vxOnH = vX >= hxMin && vX <= hxMax;\n  const hyOnV = hY >= vyMin && hY <= vyMax;\n  return (vxStrictInH && hyOnV) || (vxOnH && hyStrictInV);\n}\n\n// ─── cost() ──────────────────────────────────────────────────────────────────\n\n// Segment penalty for the turn at p2 on the path p1 → p2 → p3: none when\n// going straight, one for a bend, two for doubling back.  Orthogonal routing\n// has no per-angle penalty (no acute bends), so this is the only bend cost.\nfunction bendPenalty(router: Edge['router'], p1: Point, p2: Point, p3: Point): number {\n  const segmentPenalty = router.params.segmentPenalty;\n  if (segmentPenalty <= 0) return 0;\n  const rad = Math.PI - angleBetween(p1, p2, p3);\n  if (rad === Math.PI) {\n    // Doubling back.\n    return 2 * segmentPenalty;\n  }\n  return rad > 0 ? segmentPenalty : 0;\n}\n\n// Compute the cost of stepping from inf2 to inf3 (a segment of length `dist`,\n// preceded by inf1Node's vertex, if any).  Applies angle, segment, and\n// reverse-direction penalties up front, then optionally adds cluster-crossing\n// and connector-crossing penalties.\nexport function cost(lineRef: Edge, dist: number, inf2: VertInf, inf3: VertInf, inf1Node: ANode | null): number {\n  const inf1 = inf1Node ? inf1Node.inf : null;\n  let result = dist;\n  const connRoute = new Polygon();\n  let routeBuilt = false;\n\n  let router = lineRef.router;\n  if (inf1 !== null) {\n    // Not the first segment — there's a bend between this segment and the\n    // previous one.\n    result += bendPenalty(router, inf1.point, inf2.point, inf3.point);\n  }\n\n  // Reverse-direction penalty.\n  const reversePenalty = router.params.reverseDirectionPenalty;\n  if (reversePenalty) {\n    const srcVert = lineRef.src();\n    const dstVert = lineRef.dst();\n    const xDir = Math.sign(dstVert.point.x - srcVert.point.x);\n    const yDir = Math.sign(dstVert.point.y - srcVert.point.y);\n\n    let doesReverse = false;\n    if (xDir !== 0 && -xDir === Math.sign(inf3.point.x - inf2.point.x)) {\n      doesReverse = true;\n    }\n    if (yDir !== 0 && -yDir === Math.sign(inf3.point.y - inf2.point.y)) {\n      doesReverse = true;\n    }\n    if (doesReverse) {\n      result += reversePenalty;\n    }\n  }\n\n  // Annotation-group crossings are part of the base cost (unlike connector\n  // crossings, they don't depend on other routes), so they apply in every\n  // pass.\n  result += groupCrossingCost(router, inf2.point, inf3.point);\n  result += groupInteriorCost(router, inf2.point, inf3.point);\n\n  if (!router.isInCrossingPenaltyReroutingStage()) {\n    // Crossing-penalty pass only runs in the rerouting stage.\n    return result;\n  }\n\n  const crossing_penalty = router.params.crossingPenalty;\n\n  const shared_path_penalty = router.params.fixedSharedPathPenalty;\n  if (shared_path_penalty > 0 || crossing_penalty > 0) {\n    if (!routeBuilt) {\n      constructPolygonPath(connRoute, inf2, inf3, inf1Node);\n      routeBuilt = true;\n    }\n    for (const connRef of router.connRefs) {\n      if (connRef === lineRef) continue;\n      const route2 = connRef.displayRoute();\n      const dynamic_route2 = new Polygon();\n      dynamic_route2.ps = route2.ps.slice();\n      const dynamic_conn_route = new Polygon();\n      dynamic_conn_route.ps = connRoute.ps.slice();\n      const dstVert = lineRef.dst();\n      const finalSegment = inf3.point.eq(dstVert.point);\n      const cross = new ConnectorCrossings(dynamic_route2, true, dynamic_conn_route, connRef, lineRef);\n      cross.checkForBranchingSegments = true;\n      cross.countForSegment(connRoute.size() - 1, finalSegment);\n\n      if (\n        cross.crossingFlags & CROSSING_SHARES_PATH &&\n        cross.crossingFlags & CROSSING_SHARES_FIXED_SEGMENT &&\n        (router.options.penaliseOrthogonalSharedPathsAtConnEnds || !(cross.crossingFlags & CROSSING_SHARES_PATH_AT_END))\n      ) {\n        result += shared_path_penalty;\n      }\n      let crossingCount = cross.crossingCount;\n      if (crossing_penalty > 0) {\n        // `ConnectorCrossings` has an orthogonal/orthogonal fast path that\n        // skips strict-interior segment intersection on the assumption that\n        // any real crossing surfaces as a shared vis-graph vertex.  That\n        // breaks down for T-junctions where one route's interior point lies\n        // on another route's segment but neither route has the intersection\n        // as an actual endpoint — and worse, `constructPolygonPath` above\n        // collapses collinear points in the partial route, hiding the\n        // mid-route vis-graph vertex from `countForSegment`'s\n        // shared-endpoint logic.  So an A* step from (1056,332) east toward\n        // (1480,332) shows up as the simplified 2-point segment\n        // (1056,332)→(1480,332), which has no shared endpoint with a user\n        // vertical at x=1400 spanning y∈[288,352] — `crossingCount` stays 0\n        // even though the route would visibly cross at (1400,332).\n        //\n        // Patch the gap with a direct strict-interior scan over the new\n        // segment vs every segment of `route2`.  Use `max` (not `+=`) so we\n        // don't double-count crossings that `ConnectorCrossings` did\n        // notice via the shared-endpoint path.\n        const ps = connRoute.ps;\n        const a1 = ps[ps.length - 2];\n        const a2 = ps[ps.length - 1];\n        let strictCount = 0;\n        for (let pi = 1; pi < route2.ps.length; pi++) {\n          if (orthogonalSegmentsCross(a1, a2, route2.ps[pi - 1], route2.ps[pi], true)) {\n            strictCount++;\n          }\n        }\n        if (strictCount > crossingCount) crossingCount = strictCount;\n      }\n      result += crossingCount * crossing_penalty;\n    }\n  }\n\n  return result;\n}\n\n// ─── estimatedCost (heuristic) ────────────────────────────────────────────────\n\n// Heuristic for A*: for polyline routing it's the straight-line distance to\n// the closest cost target; for orthogonal routing it's manhattan distance\n// plus an extra cost for unavoidable bends.\nexport function estimatedCostSpecific(\n  lineRef: Edge,\n  last: Point | null,\n  curr: Point,\n  costTar: VertInf,\n  costTarDirs: Direction,\n): number {\n  const costTarPoint = costTar.point;\n  const router = lineRef.router;\n  const dist = manhattanDist(curr, costTarPoint);\n\n  let bendCount = 0;\n  const xmove = costTarPoint.x - curr.x;\n  const ymove = costTarPoint.y - curr.y;\n  if (last === null) {\n    // Initial point: penalise if not inline with the target.\n    if (xmove !== 0 && ymove !== 0) {\n      bendCount += 1;\n    }\n  } else if (dist > 0) {\n    const currDir = orthogonalDirection(last, curr);\n    if (currDir.rawValue > 0 && orthogonalDirectionsCount(currDir) === 1) {\n      bendCount = 10;\n      if (costTarDirs.has(DirN)) {\n        bendCount = Math.min(bendCount, bends(curr, currDir, costTarPoint, DirN));\n      }\n      if (costTarDirs.has(DirE)) {\n        bendCount = Math.min(bendCount, bends(curr, currDir, costTarPoint, DirE));\n      }\n      if (costTarDirs.has(DirS)) {\n        bendCount = Math.min(bendCount, bends(curr, currDir, costTarPoint, DirS));\n      }\n      if (costTarDirs.has(DirW)) {\n        bendCount = Math.min(bendCount, bends(curr, currDir, costTarPoint, DirW));\n      }\n    }\n  }\n  const penalty = bendCount * router.params.segmentPenalty;\n  return dist + penalty;\n}\n\n// ─── ANodeCmp (heap ordering) ─────────────────────────────────────────────────\n\n// Returns true if `a` has *higher* priority than `b`, i.e., should pop sooner\n// from the heap.  Lower f-value first; ties broken by higher timestamp (so\n// \"forward\" exploration wins over left/right turns at equal cost).\nexport function aNodeBetter(a: ANode, b: ANode): boolean {\n  if (Math.abs(a.f - b.f) > 1e-7) {\n    return a.f < b.f;\n  }\n  if (a.timeStamp !== b.timeStamp) {\n    return a.timeStamp > b.timeStamp;\n  }\n  return false;\n}\n\n// ─── AStarPath ────────────────────────────────────────────────────────────────\n\n// Returns true if `point[dim]` is collinear (along the named axis) with at\n// least one of `points`.\nexport function pointAlignedWithOneOf(point: Point, points: Point[], dim: number): boolean {\n  for (const p of points) {\n    if (point.at(dim) === p.at(dim)) {\n      return true;\n    }\n  }\n  return false;\n}\n\nexport class AStarPath {\n  // For orthogonal heuristic computation.\n  private m_cost_targets: VertInf[] = [];\n  private m_cost_targets_directions: Direction[] = [];\n  private m_cost_targets_displacements: number[] = [];\n\n  // Search entry point.  Updates `tar.pathNext` chain in place; on failure,\n  // `tar.pathNext` is left null.\n  search(lineRef: Edge, src: VertInf, tar: VertInf, start: VertInf = src): void {\n    const router = lineRef.router;\n\n    // ─── Cost targets ──────────────────────────────────────────────────\n    this.m_cost_targets = [];\n    this.m_cost_targets_directions = [];\n    this.m_cost_targets_displacements = [];\n\n    if (tar.isConnPoint && !tar.isConnCheckpoint) {\n      const dist = manhattanDist(start.point, tar.point);\n      for (const edge of tar.orthogVisList) {\n        const other = edge.otherVert(tar);\n        if (other.isJunctionCentre && !tar.isJunctionCentre) {\n          // Junction centre vertex — descend one more level.  Pre-refactor\n          // this fired for the zero-length dummy edge bridging a connector\n          // endpoint into its own junction; now that junction-anchored\n          // endpoints ARE the centre vertex, `tar` being a centre means any\n          // centre neighbour belongs to a *different* junction — descending\n          // through it would register that junction's surroundings as cost\n          // targets (wrong heuristic, and the free final-hop discount would\n          // let routes pass through foreign junctions).  Only descend when\n          // `tar` is an ordinary endpoint whose neighbour is a centre.\n          const replacementTar = other;\n          for (const edge2 of replacementTar.orthogVisList) {\n            const other2 = edge2.otherVert(replacementTar);\n            if (other2 === tar || other2.point.eq(tar.point)) continue;\n            this.determineEndPointLocation(dist, start, replacementTar, other2, 2);\n          }\n          continue;\n        }\n        this.determineEndPointLocation(dist, start, tar, other, 1);\n      }\n    }\n\n    if (this.m_cost_targets.length === 0) {\n      this.m_cost_targets.push(tar);\n      this.m_cost_targets_directions.push(DirAll);\n      this.m_cost_targets_displacements.push(0);\n    }\n\n    // We may turn aside only when in line with an endpoint or alongside a\n    // shape.\n    const endPoints: Point[] = [];\n    let destination = lineRef.destination;\n    if (destination instanceof Junction) {\n      endPoints.push(destination.position());\n    }\n\n    endPoints.push(tar.point);\n\n    // Group tracks are the only lines that let a route skirt a group, but\n    // they carry no shape-edge flags — so treat them like endpoint lines.\n    for (const group of router.groups) {\n      endPoints.push(...group.trackPoints());\n    }\n\n    // ─── Initial PENDING ───────────────────────────────────────────────\n    const PENDING = new BinaryHeap<ANode>(aNodeBetter);\n\n    // ANodeHeap();\n    let exploredCount = 0;\n    let bestNode: ANode | null = null;\n    let timestamp = 1;\n\n    if (start.pathNext) {\n      // Checkpoint routing: pre-seed Done with the existing previous\n      // segment so we prefer a collinear continuation.\n      const dummy = new ANode(start.pathNext, timestamp++);\n      dummy.inf.aStarDoneNodes.push(dummy);\n      bestNode = dummy;\n      exploredCount++;\n    }\n\n    const node = new ANode(src, timestamp++);\n    node.g = 0;\n    node.h = this.estimatedCost(lineRef, null, node.inf.point);\n    node.f = node.g + node.h;\n    node.prevNode = bestNode;\n    src.aStarPendingNodes.push(node);\n    PENDING.push(node);\n\n    tar.pathNext = null;\n\n    // ─── Main A* loop ──────────────────────────────────────────────────\n    while (PENDING.length !== 0) {\n      bestNode = PENDING.pop();\n      const bestNodeInf = bestNode.inf;\n\n      // Remove this node from the vertex's pending list.\n      const pIdx = bestNodeInf.aStarPendingNodes.indexOf(bestNode);\n      if (pIdx !== -1) bestNodeInf.aStarPendingNodes.splice(pIdx, 1);\n\n      bestNodeInf.aStarDoneNodes.push(bestNode);\n      exploredCount++;\n\n      const prevInf = bestNode.prevNode ? bestNode.prevNode.inf : null;\n\n      if (bestNodeInf === tar) {\n        // Reached the target — link pathNext.\n        for (let curr: ANode | null = bestNode; curr && curr.prevNode; curr = curr.prevNode) {\n          curr.inf.pathNext = curr.prevNode.inf;\n        }\n        break;\n      }\n\n      // Expand neighbours.  Sort the candidate edges by rotation away from\n      // the incoming segment.\n      //\n      // A junction-anchored start has no incoming segment.  Pre-refactor the\n      // search began at a dummy vertex coincident with the junction centre,\n      // so when the centre was expanded the \"incoming\" segment was the\n      // zero-length dummy→centre hop — which degenerates the rotation\n      // comparison (every candidate ties) and leaves the list order as-is.\n      // With the dummy gone, `prevInf` is null here and rotationLessThan\n      // would fall back to pretending the route arrived from the west,\n      // re-sorting the candidates and flipping tie-break exploration order.\n      // Pass the centre itself as the pivot to reproduce the degenerate\n      // zero-length-incoming behaviour.\n      const rotationPivot = prevInf ?? (bestNodeInf.isJunctionCentre ? bestNodeInf : null);\n      const visList = bestNodeInf.orthogVisList;\n      visList.sort((u, v) => {\n        if (u.isOrthogonal() && v.isOrthogonal()) {\n          return u.rotationLessThan(rotationPivot, v) ? -1 : 1;\n        }\n        // Fall back to a stable ordering for non-orthogonal edges (we use\n        // object identity, akin to the C++ pointer comparison).\n        return 0;\n      });\n\n      for (const edge of visList) {\n        if (edge.isDisabled()) continue;\n\n        const otherInf = edge.otherVert(bestNodeInf);\n        const node = new ANode(otherInf, timestamp++);\n        node.prevNode = bestNode;\n        const localPrevInf = bestNode.prevNode ? bestNode.prevNode.inf : null;\n\n        // Don't revisit the segment we just arrived along.\n        if (localPrevInf && localPrevInf === node.inf) continue;\n\n        if (node.inf.isJunctionCentre && !node.inf.isConnCheckpoint) {\n          // Junction centre vertices belong to a specific junction; the\n          // only ones this conn is allowed to land on are its own\n          // endpoint anchors (`lineRef.src()` / `lineRef.dst()`, which\n          // for a junction-anchored endpoint ARE the junction's centre\n          // vertex post the dummy-pin refactor).  Other junctions' centres\n          // are off-limits — routing through them would tangle two\n          // hyperedges.\n          if (node.inf !== lineRef.src() && node.inf !== lineRef.dst()) {\n            continue;\n          }\n        } else if (node.inf.isConnPoint) {\n          // Don't traverse other connector endpoints.\n          if (node.inf !== tar) continue;\n        }\n\n        if (!edge.isDummyConnection()) {\n          // Only turn when in line with an endpoint or beside a shape\n          // boundary.\n          const bestPt = bestNodeInf.point;\n          const nextPt = node.inf.point;\n          const notInlineX = !!localPrevInf && localPrevInf.point.x !== bestPt.x;\n          const notInlineY = !!localPrevInf && localPrevInf.point.y !== bestPt.y;\n\n          if (bestPt.x === nextPt.x && notInlineX && !notInlineY && bestPt.at(YDIM) !== src.point.at(YDIM)) {\n            if (nextPt.y < bestPt.y) {\n              if (\n                !((bestNodeInf.orthogVisPropFlags & 16) /* YL_EDGE */) &&\n                !pointAlignedWithOneOf(bestPt, endPoints, XDIM)\n              ) {\n                continue;\n              }\n            } else if (nextPt.y > bestPt.y) {\n              if (\n                !((bestNodeInf.orthogVisPropFlags & 64) /* YH_EDGE */) &&\n                !pointAlignedWithOneOf(bestPt, endPoints, XDIM)\n              ) {\n                continue;\n              }\n            }\n          }\n          if (bestPt.y === nextPt.y && notInlineY && !notInlineX && bestPt.at(XDIM) !== src.point.at(XDIM)) {\n            if (nextPt.x < bestPt.x) {\n              if (\n                !((bestNodeInf.orthogVisPropFlags & 1) /* XL_EDGE */) &&\n                !pointAlignedWithOneOf(bestPt, endPoints, YDIM)\n              ) {\n                continue;\n              }\n            } else if (nextPt.x > bestPt.x) {\n              if (\n                !((bestNodeInf.orthogVisPropFlags & 4) /* XH_EDGE */) &&\n                !pointAlignedWithOneOf(bestPt, endPoints, YDIM)\n              ) {\n                continue;\n              }\n            }\n          }\n        }\n\n        const edgeDist = edge.getDist() + edge.crossingCost();\n        if (edge.getDist() === 0) continue;\n\n        // Detect whether bestNode is itself one of the orthogonal cost\n        // targets — in which case the next step to tar/pin has zero cost.\n        let atCostTarget = false;\n        for (const t of this.m_cost_targets) {\n          if (bestNode.inf === t) {\n            atCostTarget = true;\n            break;\n          }\n        }\n\n        if (atCostTarget && (node.inf.isJunctionCentre || node.inf === tar)) {\n          // The \"step from a cost target to its junction centre / target is\n          // free\" optimisation: the displacement was rolled into the\n          // heuristic when m_cost_targets was built, and the C++ comment\n          // says this point sits \"on the side of an obstacle that connects\n          // to the target or a connection pin\" — so the actual edge cost\n          // is implicitly accounted for.\n          //\n          // BUT the cost-target list is populated by walking the dst's\n          // orthogVisList and then descending one more level through any\n          // junction centre.  In this port the junction centre has\n          // `Direction.all` visibility, so its neighbours include far-away\n          // lattice vertices, not just nearby obstacle corners.  When A*\n          // expands one of those lattice neighbours into the centre, the\n          // edge can be a long horizontal that geometrically crosses\n          // another connector — but the short-circuit skips `cost()`, so\n          // no crossing penalty is applied and A* picks a route that\n          // visibly crosses through user verticals (see sludeg-1 / cross-\n          // error-1 with `regenerateStaticBuiltGraph` after the improver).\n          //\n          // Patch: still scan the step segment against every other\n          // connector route for strict-interior or T-junction crossings,\n          // and bill the penalty.  Use the wider `orthogonalSegmentsCross`\n          // (T-junction-permissive) here because the segment endpoints\n          // often coincide with user-route endpoints exactly in\n          // junction-anchored routing, and the strict-only check would\n          // miss those.  Touching at a shared corner (both endpoints) is\n          // still not counted.\n          let crossingPenaltyAdd = 0;\n          if (router.params.crossingPenalty > 0) {\n            const a1 = bestNodeInf.point;\n            const a2 = node.inf.point;\n            let strictCount = 0;\n            for (const connRef of router.connRefs) {\n              if (connRef === lineRef) continue;\n              const route2 = connRef.displayRoute();\n              for (let pi = 1; pi < route2.ps.length; pi++) {\n                if (orthogonalSegmentsCross(a1, a2, route2.ps[pi - 1], route2.ps[pi], false)) {\n                  strictCount++;\n                }\n              }\n            }\n            crossingPenaltyAdd = strictCount * router.params.crossingPenalty;\n          }\n          // The short-circuit skips `cost()`, so bill the group crossings\n          // of this final hop here too — it's often the step that enters\n          // the target's group.\n          crossingPenaltyAdd += groupCrossingCost(router, bestNodeInf.point, node.inf.point);\n          crossingPenaltyAdd += groupInteriorCost(router, bestNodeInf.point, node.inf.point);\n          // Bill the turn onto this final hop too.  Otherwise a route that\n          // runs straight into the target ties with one that pulls up beside\n          // it and turns in, and A*'s expansion order picks between them —\n          // which any change to the step costs (e.g. a group's interior\n          // cost) can flip.\n          if (bestNode.prevNode) {\n            crossingPenaltyAdd += bendPenalty(router, bestNode.prevNode.inf.point, bestNodeInf.point, node.inf.point);\n          }\n          node.g = bestNode.g + crossingPenaltyAdd;\n          node.h = 0;\n        } else {\n          if (node.inf === tar) {\n            node.h = 0;\n          } else {\n            node.h = this.estimatedCost(lineRef, bestNodeInf.point, node.inf.point);\n          }\n          node.g = bestNode.g + cost(lineRef, edgeDist, bestNodeInf, node.inf, bestNode.prevNode);\n        }\n        node.f = node.g + node.h;\n\n        // Deduplicate against PENDING.\n        let bNodeFound = false;\n        for (const ati of node.inf.aStarPendingNodes as ANode[]) {\n          if (\n            node.inf === ati.inf &&\n            (node.prevNode === ati.prevNode ||\n              (node.prevNode && ati.prevNode && node.prevNode.inf === ati.prevNode.inf))\n          ) {\n            if (node.g < ati.g) {\n              // Update in place; rebuild heap since f changed.\n              ati.g = node.g;\n              ati.h = node.h;\n              ati.f = node.f;\n              ati.prevNode = node.prevNode;\n              ati.timeStamp = node.timeStamp;\n              PENDING.rebuild();\n            }\n            bNodeFound = true;\n            break;\n          }\n        }\n        if (!bNodeFound) {\n          // Then check Done.\n          for (const ati of node.inf.aStarDoneNodes as ANode[]) {\n            if (\n              node.inf === ati.inf &&\n              ati.prevNode &&\n              (node.prevNode === ati.prevNode || (node.prevNode && node.prevNode.inf === ati.prevNode.inf))\n            ) {\n              bNodeFound = true;\n              break;\n            }\n          }\n        }\n\n        if (!bNodeFound) {\n          node.inf.aStarPendingNodes.push(node);\n          PENDING.push(node);\n        }\n      }\n    }\n\n    // Cleanup all the per-vertex node lists.\n    for (const k of router.vertices) {\n      k.aStarDoneNodes.length = 0;\n      k.aStarPendingNodes.length = 0;\n    }\n  }\n\n  // Helper: record one possible target point for orthogonal cost\n  // estimation (called from the orthogonal-endpoint setup).\n  private determineEndPointLocation(\n    _dist: number,\n    _start: VertInf,\n    target: VertInf,\n    other: VertInf,\n    _level: number,\n  ): void {\n    const thisDirs = orthogonalDirection(other.point, target.point);\n    if (orthogonalDirectionsCount(thisDirs) === 0) return;\n    const displacement = manhattanDist(other.point, target.point);\n    this.m_cost_targets.push(other);\n    this.m_cost_targets_directions.push(thisDirs);\n    this.m_cost_targets_displacements.push(displacement);\n  }\n\n  // Heuristic from `curr` (with optional preceding point `last`) to whichever\n  // cost target is cheapest.  Polyline routing uses euclidean distance;\n  // orthogonal routing uses manhattan + bend penalty.\n  private estimatedCost(lineRef: Edge, last: Point | null, curr: Point): number {\n    if (this.m_cost_targets.length === 0) return 0;\n    let estimate = Infinity;\n    for (let i = 0; i < this.m_cost_targets.length; i++) {\n      let iEstimate = estimatedCostSpecific(\n        lineRef,\n        last,\n        curr,\n        this.m_cost_targets[i],\n        this.m_cost_targets_directions[i],\n      );\n      iEstimate += this.m_cost_targets_displacements[i];\n      if (iEstimate < estimate) estimate = iEstimate;\n    }\n    return estimate;\n  }\n}\n","import {kUnassignedVertexNumber, Point, Polygon} from '../geomtypes';\nimport {Endpoint} from './endpoint';\nimport {Direction} from './Direction';\nimport {Checkpoint} from './Checkpoint';\nimport {VertInf} from '../vertex';\nimport {manhattanDist, pointOnLine} from '../geometry';\nimport {AStarPath} from '../makepath';\nimport {Junction} from './junction';\n\nimport type {Router} from '../router';\n\n// Internal per-end storage.  An Edge endpoint is *either* a free-floating\n// point with an entry/exit direction *or* a Junction reference — never\n// both.  External callers pass `Endpoint` for the point case and `Junction`\n// directly for the junction case (the Edge constructor / `updateEndPoint`\n// dispatch via `instanceof`).\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n// Builds a fresh route Point at the vertex's position, carrying its\n// geometric corner-index / midpoint label in `pt.vn`.  The label drives\n// `midVertexNumber` in the nudging code: 0..3 = rectangle corners,\n// 4..7 = edge midpoints, kUnassignedVertexNumber = not on any shape edge.\n// Connector endpoints / checkpoints aren't on a shape boundary, so the\n// Point keeps its default vn (kUnassignedVertexNumber) and `midVertexNumber`\n// short-circuits cleanly.\nfunction stampRoutePoint(v: VertInf): Point {\n  const pt = new Point(v.point.x, v.point.y);\n  if (!v.isConnPoint) {\n    pt.vn = v.vn;\n  }\n  return pt;\n}\n\n// ─── ConnRef class ────────────────────────────────────────────────────────────\n\n// @brief   The ConnRef class represents a connector object.\n//\n// Connectors are a (possible multi-segment) line between two points.\n// They are routed intelligently so as not to overlap any of the shape\n// objects in the Router scene.\nexport class Edge<UserData = unknown> {\n  readonly router: Router;\n  readonly userData: UserData | null;\n  _id: number;\n  private _needsRerouteFlag: boolean;\n  private _hateCrossings: boolean;\n  _route: Polygon;\n\n  private _srcVert: VertInf;\n  private _dstVert: VertInf;\n  private _src: Junction | Endpoint;\n  private _dst: Junction | Endpoint;\n\n  private _checkpoints: Checkpoint[];\n  private _checkpointVertices: VertInf[];\n\n  // ─── Accessors ────────────────────────────────────────────────────────────\n\n  // The junction this edge's source endpoint is anchored to, or null when\n  // the source is a free-floating point.  Replaces the older\n  // `srcConnEnd?.junction()` indirection.\n  get srcJunction(): Junction | null {\n    return this._src instanceof Junction ? this._src : null;\n  }\n\n  get dstJunction(): Junction | null {\n    return this._dst instanceof Junction ? this._dst : null;\n  }\n\n  get source() {\n    return this._src;\n  }\n\n  get destination() {\n    return this._dst;\n  }\n\n  // ─── Constructors ─────────────────────────────────────────────────────────\n  constructor(router: Router, src: Endpoint | Junction, dst: Endpoint | Junction, userData: UserData | null = null) {\n    this.router = router;\n    this.userData = userData;\n    this._needsRerouteFlag = true;\n    this._hateCrossings = false;\n    this._checkpoints = [];\n    this._checkpointVertices = [];\n    this._route = new Polygon();\n\n    this._id = router._assignObjectId();\n\n    let {terminal: source, vertext: sourceVertext} = this.updateEndPoint('src', src);\n    let {terminal: destination, vertext: destinationVertext} = this.updateEndPoint('tar', dst);\n\n    this._src = source;\n    this._srcVert = sourceVertext;\n    this._dst = destination;\n    this._dstVert = destinationVertext;\n  }\n\n  // ─── Public API ───────────────────────────────────────────────────────────\n\n  reverseRoute() {\n    this.displayRoute().ps.reverse();\n  }\n\n  // @brief   Returns the connector's route.\n  //\n  // This used to lazily simplify a raw `_route` into a cached `_displayRoute`.\n  // The route is now kept simplified in place (see `generatePath`), so there's\n  // a single route polygon and nothing to cache — callers get it directly and\n  // may mutate it (e.g. `reverseRoute`, the nudging passes).\n  displayRoute(): Polygon {\n    return this._route;\n  }\n\n  endpointAnchors(): [Junction | null, Junction | null] {\n    let source = this.source;\n    let destination = this.destination;\n    return [source instanceof Junction ? source : null, destination instanceof Junction ? destination : null];\n  }\n\n  // @brief  Allows the user to specify a set of checkpoints that this\n  //         connector will route via.\n  setRoutingCheckpoints(checkpoints: Checkpoint[]): void {\n    this._checkpoints = checkpoints;\n\n    // Clear previous checkpoint vertices.\n    for (const vert of this._checkpointVertices) {\n      vert.removeFromGraph(true);\n      this.router.vertices.removeVertex(vert);\n    }\n    this._checkpointVertices = [];\n\n    for (let [index, checkpoint] of this._checkpoints.entries()) {\n      const vertex = new VertInf(this._id, 2 + index, checkpoint.point, {\n        isConnPoint: true,\n        isConnCheckpoint: true,\n      });\n      this.router.vertices.addVertex(vertex);\n      vertex.visDirections = Direction.all;\n      this._checkpointVertices.push(vertex);\n    }\n  }\n\n  // @brief   Returns the current set of routing checkpoints for this connector.\n  routingCheckpoints(): Checkpoint[] {\n    return this._checkpoints;\n  }\n\n  // @brief  Sets the hat-crossings flag.\n  setHateCrossings(val: boolean): void {\n    this._hateCrossings = val;\n  }\n\n  // @brief  Returns the hat-crossings flag.\n  doesHateCrossings(): boolean {\n    return this._hateCrossings;\n  }\n\n  // @brief  Sets the route directly (internal use).\n  set_route(route: Polygon): void {\n    this._route.ps = route.ps.slice();\n  }\n\n  // @brief  Drops the route so this connector's path is no longer visible to\n  //         other connectors' crossing-penalty calculations.  Used by\n  //         improveCrossings between marking the path invalid and re-running A*.\n  /** @internal */\n  freeRoutes(): void {\n    this._route.clear();\n  }\n\n  // @brief  Generates the path for this connector.\n  generatePath(): boolean {\n    if (!this._needsRerouteFlag) {\n      return false;\n    }\n\n    this._needsRerouteFlag = false;\n\n    const path: Point[] = [];\n    const vertices: VertInf[] = [];\n    if (this._checkpoints.length === 0) {\n      this.generateStandardPath(path, vertices);\n    } else {\n      this.generateCheckpointsPath(path, vertices);\n    }\n\n    // Keep the route simplified in place: callers read it directly via\n    // `displayRoute()`, which no longer simplifies on demand.\n    this._route.clear();\n    this._route.ps = path;\n    this._route = this._route.simplify();\n\n    return true;\n  }\n\n  // ─── Internal methods ─────────────────────────────────────────────────────\n\n  /** @internal */\n  src(): VertInf {\n    return this._srcVert;\n  }\n\n  /** @internal */\n  dst(): VertInf {\n    return this._dstVert;\n  }\n\n  /** @internal */\n  makePathInvalid(): void {\n    this._needsRerouteFlag = true;\n  }\n\n  /** @internal */\n  private updateEndPoint(type: 'src' | 'tar', end: Endpoint | Junction) {\n    // vn = 0 (src) / 1 (tar) keeps endpoint identities unique within the\n    // connector so checkpoint vertices (vn = 2 + i) don't collide.\n    const vn = type === 'src' ? 0 : 1;\n\n    if (end instanceof Junction) {\n      end.attachedEdges.add(this);\n      return {\n        terminal: end,\n        vertext: end.centreVertex,\n      };\n    } else {\n      // No reusable vert (either first call or transitioning from a\n      // junction-anchored slot, where `oldVert` aliased the junction's\n      // centre and must NOT be torn down — the junction still owns it).\n      let endpointVert = new VertInf(this._id, vn, end.position, {\n        isConnPoint: true,\n      });\n      this.router.vertices.addVertex(endpointVert);\n\n      endpointVert.visDirections = end.directions;\n      // Strip any per-conn edges; they'll be regenerated when the static\n      // graph is rebuilt.\n      endpointVert.removeFromGraph(true);\n\n      return {\n        terminal: end,\n        vertext: endpointVert,\n      };\n    }\n  }\n\n  /** @internal */\n  generateStandardPath(path: Point[], vertices: VertInf[]): void {\n    const src = this._srcVert;\n    const tar = this._dstVert;\n\n    new AStarPath().search(this, src, tar);\n    let pathlen = tar.pathLeadsBackTo(src);\n\n    if (pathlen < 2) {\n      // No valid path — degrade to a direct line so callers can continue.\n      this._needsRerouteFlag = true;\n      pathlen = 2;\n      tar.pathNext = src;\n    }\n\n    path.length = pathlen;\n    vertices.length = pathlen;\n    let j = pathlen - 1;\n    for (let i: VertInf | null = tar; i && i !== src; i = i.pathNext) {\n      path[j] = stampRoutePoint(i);\n      vertices[j] = i;\n      j--;\n    }\n    path[0] = stampRoutePoint(src);\n    vertices[0] = src;\n  }\n\n  /** @internal */\n  generateCheckpointsPath(path: Point[], vertices: VertInf[]): void {\n    const src = this._srcVert;\n    const dst = this._dstVert;\n\n    // Build [src, ...checkpoint verts, dst]\n    const checkpoints: VertInf[] = [src, ...this._checkpointVertices, dst];\n\n    path.length = 0;\n    vertices.length = 0;\n    path.push(src.point);\n    vertices.push(src);\n\n    let lastSuccessfulIndex = 0;\n    for (let i = 1; i < checkpoints.length; i++) {\n      const start = checkpoints[lastSuccessfulIndex];\n      const end = checkpoints[i];\n\n      // Apply checkpoint visibility-direction restrictions.\n      if (lastSuccessfulIndex > 0) {\n        const srcCP = this._checkpoints[lastSuccessfulIndex - 1];\n        if (!srcCP.departureDirections.equal(Direction.all)) {\n          start.setVisibleDirections(srcCP.departureDirections);\n        }\n      }\n      if (i + 1 < checkpoints.length) {\n        const dstCP = this._checkpoints[i - 1];\n        if (!dstCP.arrivalDirections.equal(Direction.all)) {\n          end.setVisibleDirections(dstCP.arrivalDirections);\n        }\n      }\n\n      new AStarPath().search(this, start, end);\n\n      // Restore full visibility for these vertices.\n      if (lastSuccessfulIndex > 0) {\n        start.setVisibleDirections(Direction.all);\n      }\n      if (i + 1 < checkpoints.length) {\n        end.setVisibleDirections(Direction.all);\n      }\n\n      const pathlen = end.pathLeadsBackTo(start);\n      if (pathlen >= 2) {\n        const prevPathSize = path.length;\n        path.length = prevPathSize + (pathlen - 1);\n        vertices.length = prevPathSize + (pathlen - 1);\n        let vertInf: VertInf | null = end;\n        for (let index = path.length - 1; index >= prevPathSize && vertInf; index--) {\n          path[index] = stampRoutePoint(vertInf);\n          vertices[index] = vertInf;\n          vertInf = vertInf.pathNext;\n        }\n        lastSuccessfulIndex = i;\n      } else if (i + 1 === checkpoints.length) {\n        // Last segment failed — bail with a direct dst point.\n        this._needsRerouteFlag = true;\n        path.push(dst.point);\n        vertices.push(dst);\n      }\n      // Else: skip this checkpoint and try the next.\n    }\n  }\n}\n\n// ─── midVertexNumber (module-private) ────────────────────────────────────────\n\n// Returns the vn for a point that lies between two shape corners p0 and p1.\nfunction midVertexNumber(p0: Point, p1: Point, c: Point): number {\n  if (c.vn !== kUnassignedVertexNumber) {\n    // The split point is a shape corner, so doesn't need its vertex number\n    // adjusting.\n    return c.vn;\n  }\n  if (p0.vn >= 4 && p0.vn < kUnassignedVertexNumber) {\n    return p0.vn;\n  }\n  if (p1.vn >= 4 && p1.vn < kUnassignedVertexNumber) {\n    return p1.vn;\n  }\n  if (p0.vn < 4 && p1.vn < 4) {\n    if (p0.vn !== p1.vn) {\n      return p0.vn;\n    }\n    // Splitting between two ordinary shape corners.\n    let vn_mid = Math.min(p0.vn, p1.vn);\n    if (Math.max(p0.vn, p1.vn) === 3 && vn_mid === 0) {\n      vn_mid = 3; // Next vn is effectively 4.\n    }\n    return vn_mid + 4;\n  }\n\n  if (p0.vn !== kUnassignedVertexNumber) {\n    if (p0.x === p1.x) {\n      if (p0.vn === 2 || p0.vn === 3) {\n        return 6;\n      }\n      return 4;\n    } else {\n      if (p0.vn === 0 || p0.vn === 3) {\n        return 7;\n      }\n      return 5;\n    }\n  } else if (p1.vn !== kUnassignedVertexNumber) {\n    if (p0.x === p1.x) {\n      if (p1.vn === 2 || p1.vn === 3) {\n        return 6;\n      }\n      return 4;\n    } else {\n      if (p1.vn === 0 || p1.vn === 3) {\n        return 7;\n      }\n      return 5;\n    }\n  }\n\n  // Shouldn't both be new (kUnassignedVertexNumber) points.\n  return kUnassignedVertexNumber;\n}\n\n// ─── splitBranchingSegments ───────────────────────────────────────────────────\n\n// @brief  Break up overlapping parallel segments that are not the same edge\n//         in the visibility graph, i.e., where one segment is a subsegment\n//         of another.\nexport function splitBranchingSegments(poly: Polygon, polyIsConn: boolean, conn: Polygon, tolerance = 0): void {\n  // Loop over conn segments (skipping first point).\n  let i = 1;\n  while (i < conn.ps.length) {\n    const c0 = conn.ps[i - 1];\n    // `c1` is the current end of the conn segment under examination.  When\n    // we splice a poly point into conn (branches C and D below), the new\n    // point becomes the new c1 — we update the local so the next iteration\n    // checks the shorter sub-segment, not the original.  Without the update,\n    // `pointOnLine(c0, c1, p0)` keeps returning true with the same `c1` and\n    // the same `p0`, splicing the same point indefinitely.\n    let c1 = conn.ps[i];\n\n    let j = polyIsConn ? 1 : 0;\n    while (j < poly.ps.length) {\n      const poly_size = poly.ps.length;\n      const p0 = j === 0 ? poly.ps[poly_size - 1] : poly.ps[j - 1];\n      const p1 = poly.ps[j];\n\n      // Check the first point of the first segment (c0 = conn.ps[i-1]).\n      if (i === 1 && pointOnLine(p0, p1, c0, tolerance)) {\n        c0.vn = midVertexNumber(p0, p1, c0);\n        poly.ps.splice(j, 0, c0);\n        if (j > 0) {\n          j--;\n        }\n        continue;\n      }\n      // And the second point of every conn segment (c1 = conn.ps[i]).\n      if (pointOnLine(p0, p1, c1, tolerance)) {\n        c1.vn = midVertexNumber(p0, p1, c1);\n        poly.ps.splice(j, 0, c1);\n        if (j > 0) {\n          j--;\n        }\n        continue;\n      }\n\n      // Check the first point of the first poly segment (p0 = poly.ps[j-1]).\n      if (polyIsConn && j === 1 && pointOnLine(c0, c1, p0, tolerance)) {\n        p0.vn = midVertexNumber(c0, c1, p0);\n        conn.ps.splice(i, 0, p0);\n        // Shrink the segment under examination to c0..p0 so we don't\n        // re-trigger the same pointOnLine on the next iteration.\n        c1 = p0;\n        continue;\n      }\n      // And the second point of every poly segment (p1 = poly.ps[j]).\n      if (pointOnLine(c0, c1, p1, tolerance)) {\n        p1.vn = midVertexNumber(c0, c1, p1);\n        conn.ps.splice(i, 0, p1);\n        // Same as branch above — the segment is now c0..p1.\n        c1 = p1;\n      }\n\n      j++;\n    }\n    i++;\n  }\n}\n\n// ─── segDir (module-private) ──────────────────────────────────────────────────\n\nexport function segDir(p1: Point, p2: Point): number {\n  let result = 1;\n  if (p1.x === p2.x) {\n    if (p2.y > p1.y) {\n      result = -1;\n    }\n  } else if (p1.y === p2.y) {\n    if (p2.x < p1.x) {\n      result = -1;\n    }\n  }\n  return result;\n}\n\n// ─── posInlineWithConnEndSegs (module-private) ────────────────────────────────\n\nexport function posInlineWithConnEndSegs(pos: number, dim: number, poly: Polygon, conn: Polygon): boolean {\n  const pLast = poly.size() - 1;\n  const cLast = conn.size() - 1;\n  if (\n    // Is inline with the beginning of the \"poly\" line\n    ((pos === poly.ps[0].at(dim) && pos === poly.ps[1].at(dim)) ||\n      // Is inline with the end of the \"poly\" line\n      (pos === poly.ps[pLast].at(dim) && pos === poly.ps[pLast - 1].at(dim))) &&\n    // Is inline with the beginning of the \"conn\" line\n    ((pos === conn.ps[0].at(dim) && pos === conn.ps[1].at(dim)) ||\n      // Is inline with the end of the \"conn\" line\n      (pos === conn.ps[cLast].at(dim) && pos === conn.ps[cLast - 1].at(dim)))\n  ) {\n    return true;\n  }\n  return false;\n}\n\n// ─── Constants ───────────────────────────────────────────────────────────────\n\nexport const CROSSING_NONE = 0;\nexport const CROSSING_TOUCHES = 1;\nexport const CROSSING_SHARES_PATH = 2;\nexport const CROSSING_SHARES_PATH_AT_END = 4;\nexport const CROSSING_SHARES_FIXED_SEGMENT = 8;\n\n// ─── pathLengthFromIndices (module-private) ──────────────────────────────────\n\n// Computes the *shared* length of two shared paths.\n// Uses index arrays into conn.ps and poly.ps.\nexport function pathLengthFromIndices(\n  conn: Polygon,\n  poly: Polygon,\n  c_path: number[],\n  p_path: number[],\n  size: number,\n): number {\n  let length = 0;\n\n  for (let ind = 1; ind < size; ++ind) {\n    if (conn.ps[c_path[ind - 1]].eq(poly.ps[p_path[ind - 1]]) && conn.ps[c_path[ind]].eq(poly.ps[p_path[ind]])) {\n      // This segment is shared by both paths.\n      // Use Manhattan distance since this is for orthogonal paths.\n      length += manhattanDist(conn.ps[c_path[ind - 1]], conn.ps[c_path[ind]]);\n    }\n  }\n\n  return length;\n}\n","// A sorted array with set-like dedup, ordered by an injected comparator.\n//\n// Backed by a plain `T[]` kept in sorted order; `lowerBound` is binary\n// search (O(log n)) and insert/erase splice (O(n)).  The router's inputs\n// are small enough (low hundreds of items at most) that splicing wins\n// against the bookkeeping of a balanced tree.\n//\n// Set semantics: an `insert` whose item compares equal (`cmp(...) === 0`)\n// to one already in the array is a silent no-op.  Equality is exactly what\n// the comparator returns 0 for — callers that want to allow distinct items\n// at the same primary key should encode a stable tiebreaker (e.g. `objID`,\n// `vn`, insertion-order id) into their comparator so two truly distinct\n// items never compare equal.\n//\n// Most callers can pass `T.compare` directly (a static comparator method on\n// the value type — see `Node.compare`, `VertInf.compare`,\n// `PosVertInf.compare`).  Callers parameterised on something else\n// (e.g. axis dimension) pass a closure — see `HyperedgeTreeNode.compareInDim`.\n\nexport class SortedArray<T> {\n  private items: T[];\n  private cmp: (a: T, b: T) => number;\n\n  constructor(cmp: (a: T, b: T) => number) {\n    this.cmp = cmp;\n    this.items = [];\n  }\n\n  size(): number {\n    return this.items.length;\n  }\n\n  isEmpty(): boolean {\n    return this.items.length === 0;\n  }\n\n  // Direct (mutable!) reference to the underlying array.  Callers must not\n  // mutate the order, but read-only iteration and index reads are fine.\n  // Used in hot loops where allocating a copy is wasteful.\n  values(): T[] {\n    return this.items;\n  }\n\n  // Defensive copy — handy for tests and one-off serialisation.\n  toArray(): T[] {\n    return this.items.slice();\n  }\n\n  // Smallest / largest by comparator.  Returns `undefined` if empty.\n  first(): T | undefined {\n    return this.items[0];\n  }\n\n  last(): T | undefined {\n    return this.items[this.items.length - 1];\n  }\n\n  // Inserts `item` in sorted position.  Returns `true` if inserted, `false`\n  // if an item already present compared equal (no-op).\n  insert(item: T): boolean {\n    const idx = this.lowerBound(item);\n    if (idx < this.items.length && this.cmp(this.items[idx], item) === 0) {\n      return false;\n    }\n    this.items.splice(idx, 0, item);\n    return true;\n  }\n\n  insertAll(other: Iterable<T>): void {\n    for (const item of other) this.insert(item);\n  }\n\n  // Removes `item` (compared by `cmp(...) === 0`).  Returns `true` if it\n  // was present.\n  erase(item: T): boolean {\n    const idx = this.indexOf(item);\n    if (idx === -1) return false;\n    this.items.splice(idx, 1);\n    return true;\n  }\n\n  // Drops the first `count` items (in sorted order).  No-op for `count <= 0`.\n  eraseFront(count: number): void {\n    if (count > 0) this.items.splice(0, count);\n  }\n\n  clear(): void {\n    this.items = [];\n  }\n\n  // Returns the index of `item` (by `cmp === 0`) or -1.\n  indexOf(item: T): number {\n    const idx = this.lowerBound(item);\n    if (idx < this.items.length && this.cmp(this.items[idx], item) === 0) {\n      return idx;\n    }\n    return -1;\n  }\n\n  has(item: T): boolean {\n    return this.indexOf(item) !== -1;\n  }\n\n  // First index where `items[i] >= item` (by comparator).  Equals\n  // `this.items.length` when `item` is strictly greater than every entry.\n  lowerBound(item: T): number {\n    let lo = 0;\n    let hi = this.items.length;\n    while (lo < hi) {\n      const mid = (lo + hi) >> 1;\n      if (this.cmp(this.items[mid], item) < 0) lo = mid + 1;\n      else hi = mid;\n    }\n    return lo;\n  }\n\n  // The item sorted just before `item`, or `null` if `item` is the first\n  // (or not present and would sort to position 0).\n  prev(item: T): T | null {\n    const idx = this.lowerBound(item);\n    return idx > 0 ? this.items[idx - 1] : null;\n  }\n\n  // The item sorted just after `item`, or `null`.  Returns `null` if `item`\n  // is not present.\n  next(item: T): T | null {\n    const idx = this.lowerBound(item);\n    if (idx >= this.items.length || this.cmp(this.items[idx], item) !== 0) {\n      return null;\n    }\n    return idx + 1 < this.items.length ? this.items[idx + 1] : null;\n  }\n\n  *[Symbol.iterator](): IterableIterator<T> {\n    for (const item of this.items) yield item;\n  }\n}\n","export function assert(desc: string, condition: unknown): asserts condition {\n  if (!condition) {\n    throw new Error(desc);\n  }\n}\n","// Hyperedge represented as a tree of nodes and edges.\n//\n// Ports input/hyperedgetree.cpp and input/hyperedgetree.h.  The C++ uses a\n// tree of `HyperedgeTreeNode` records linked together by `HyperedgeTreeEdge`\n// records.  Hyperedge improvement transformations (shifting segments,\n// removing redundant junctions, rewriting connector endpoints) are applied\n// over this tree representation since it is far easier to manipulate than\n// a list of polylines.\n//\n// Each node carries a Point, an optional JunctionRef (when the node is a\n// junction between multiple segments), and a few flags used during route\n// reconstruction.  Each edge tracks the ConnRef the segment will become and\n// whether the original connector route was fixed by the caller.\n//\n// Deviations from C++:\n//   - Raw pointers become TS class instances; GC reclaims dropped subtrees.\n//   - `std::list<HyperedgeTreeEdge *>` is a plain array; insertion order is\n//     preserved by `push` / `splice`.\n//   - Debug helpers (`outputEdgesExcept`, `outputNodesExcept`, `validateHyperedge`,\n//     `setDebuggingOutput`) are dropped — they emit SVG/stderr only.\n//   - `friend`-style access is modelled via `/** @internal */` comments rather\n//     than visibility hacks.\n//   - C++ output parameters (e.g. `JunctionRefList&`) are expressed by passing\n//     in arrays the caller owns, matching the C++ usage exactly.\n//\n// Several structural interfaces are exported so callers can plug in their own\n// ConnRef / JunctionRef / Router types without an actual `import` cycle.\n\nimport {Edge} from './models/edge';\nimport {Endpoint} from './models/endpoint';\nimport {Point} from './geomtypes';\nimport {Junction} from './models/junction';\nimport {SortedArray} from './utilities/sorted-array';\n\nimport type {Router} from './router';\nimport type {VertInf} from './vertex';\nimport {assert} from './utilities/assert';\n\n// ─── Structural interfaces ───────────────────────────────────────────────────\n// We keep these as structural interfaces so hyperedgetree.ts can live\n// dependency-free of connector.ts / junction.ts / router.ts.  The concrete\n// classes (ConnRef, JunctionRef, Router) all satisfy these by default.\n\n// ─── Type aliases ────────────────────────────────────────────────────────────\n\n// Map from a junction to the tree node that represents it.\nexport type JunctionHyperedgeTreeNodeMap = Map<Junction, HyperedgeTreeNode>;\n\n// Map from a VertInf to the tree node it became.\nexport type VertexNodeMap = Map<VertInf, HyperedgeTreeNode>;\n\n// ─── HyperedgeTreeNode ───────────────────────────────────────────────────────\n\n// @brief   A node in the hyperedge tree.\n//\n// Carries a position, optional junction, optional VertInf marker (used to\n// identify terminals), and the list of edges incident on this node.\nexport class HyperedgeTreeNode {\n  edges: HyperedgeTreeEdge[];\n  junction: Junction | null;\n  point: Point;\n  // VertInf representing the original endpoint of a connector that landed\n  // at this node.  Used by buildHyperedgeTreeToRoot to remember terminals.\n  finalVertex: VertInf | null;\n  // True if this terminal node is the source of its connector (vs target).\n  isConnectorSource: boolean;\n  // Used during recursive traversals to detect cycles.\n  visited: boolean;\n\n  shiftSegmentNodeSet: SortedArray<HyperedgeTreeNode> | null = null;\n\n  constructor() {\n    this.edges = [];\n    this.junction = null;\n    this.point = new Point(0, 0);\n    this.finalVertex = null;\n    this.isConnectorSource = false;\n    this.visited = false;\n  }\n\n  // Returns a `(lhs, rhs) => number` comparator that orders\n  // `HyperedgeTreeNode`s along `dimension` (0 = X, 1 = Y).  Primary by the\n  // point's coordinate on that axis, tiebreak by a deterministic\n  // insertion-order id stamped lazily via a private WeakMap.  Pass the\n  // returned function to `new SortedArray<HyperedgeTreeNode>(...)`.\n  // The closure is created per dimension because the dim is the only\n  // parameter — there's no single `T.compare` that handles all axes.\n  static compareInDim(dimension: number): (a: HyperedgeTreeNode, b: HyperedgeTreeNode) => number {\n    return (a, b) => {\n      const av = a.point.at(dimension);\n      const bv = b.point.at(dimension);\n      if (av !== bv) return av < bv ? -1 : 1;\n      return _nodeOrder(a) - _nodeOrder(b);\n    };\n  }\n\n  //! Traverses the tree and removes from `treeRoots` any junctions other\n  //! than the first one we reach (the root).  Returns true when a cycle is\n  //! detected during traversal.\n  removeOtherJunctionsFrom(ignored: HyperedgeTreeEdge | null, treeRoots: Set<Junction>): boolean {\n    if (this.visited) {\n      // Already visited - cycle.\n      return true;\n    }\n    let containsCycle = false;\n    if (this.junction && ignored !== null) {\n      // Remove junctions other than the first (when ignored === null).\n      treeRoots.delete(this.junction);\n    }\n    this.visited = true;\n    for (const curr of this.edges) {\n      if (curr !== ignored) {\n        if (curr.removeOtherJunctionsFrom(this, treeRoots)) {\n          containsCycle = true;\n        }\n      }\n    }\n    return containsCycle;\n  }\n\n  // Traverses the tree and writes each branch's path back to its connector's\n  // display route.  `pass === 0` clears each connector's route; `pass === 1`\n  // actually writes the points.\n  writeEdgesToConns(ignored: HyperedgeTreeEdge | null, pass: number) {\n    for (const curr of this.edges) {\n      if (curr !== ignored) {\n        curr.writeEdgesToConns(this, pass);\n      }\n    }\n  }\n\n  // Traverses the tree from a junction outwards, creating one fresh connector\n  // per branch.  A branch runs from the junction it starts at to the next\n  // terminal or junction, threading through any number of bend nodes; every\n  // tree edge along the branch shares that single connector.\n  //\n  // `branchJunction` is the junction the branch we're currently on is rooted\n  // at.  It is `null` only on the very first call, where `this` must itself be\n  // a junction (the tree root) — a junction node re-roots every branch leaving\n  // it at itself.\n  //\n  // `sourceTerminals` holds the terminal vertices that were the *source* end\n  // of a deleted connector.  A branch ending at one of them is oriented\n  // terminal→junction so the new connector keeps the original src→dst\n  // direction (everything else is junction→terminal).\n  addConns(\n    ignored: HyperedgeTreeEdge | null,\n    router: Router,\n    branchJunction: Junction | null,\n    sourceTerminals: Set<VertInf>,\n  ): void {\n    const rootedAt = this.junction ?? branchJunction;\n    if (rootedAt === null) {\n      throw new Error('HyperedgeTreeNode.addConns: no junction to root the branch at');\n    }\n\n    for (const curr of this.edges) {\n      if (curr !== ignored) {\n        curr.addConns(this, router, rootedAt, sourceTerminals);\n      }\n    }\n  }\n\n  // Returns true if this node cannot be moved during hyperedge improvement.\n  // Conditions:\n  //   - It has only one edge (a terminal).\n  //   - Its junction has a fixed position.\n  //   - It hosts a junction (Steiner or otherwise).  `HyperedgeImprover.execute()`\n  //     runs `moveJunctionsAlongCommonEdges` BEFORE each `nudgeHyperedgeSegments`\n  //     cycle; the slide step has already placed every junction at its locally\n  //     optimal point along its shared sub-paths.  Letting `nudgeHyperedgeSegments`\n  //     drag the junction-bearing segment to a different position would just undo\n  //     that work — and in practice (see sludeg-1) snap a Steiner sitting on a\n  //     y=100 spine \"down\" onto y=332 because of a balance count that doesn't\n  //     understand the spine has no orthogonal alternative once it leaves y=100.\n  //     `nudgeHyperedgeSegments` is supposed to balance free terminal segments\n  //     against each other; junction segments are not free.\n  isImmovable(): boolean {\n    if (this.edges.length === 1 || this.junction !== null) {\n      return true;\n    }\n    return false;\n  }\n\n  // Removes a specific edge from this node's edge list (all occurrences).\n  disconnectEdge(edge: HyperedgeTreeEdge): void {\n    for (let i = this.edges.length - 1; i >= 0; i--) {\n      if (this.edges[i] === edge) {\n        this.edges.splice(i, 1);\n      }\n    }\n  }\n\n  // Moves every edge attached to `oldNode` to be attached to this node\n  // instead.  Used when collapsing two coincident nodes into one.\n  spliceEdgesFrom(oldNode: HyperedgeTreeNode): void {\n    if (oldNode === this) {\n      throw new Error('HyperedgeTreeNode.spliceEdgesFrom: cannot splice from self');\n    }\n    while (oldNode.edges.length > 0) {\n      // replaceNode mutates oldNode.edges, so we always look at index 0.\n      oldNode.edges[0].replaceNode(oldNode, this);\n    }\n  }\n}\n\n// ─── Per-node insertion-order tiebreaker ─────────────────────────────────────\n// Used by `HyperedgeTreeNode.compareInDim` to give two nodes at the same\n// dim-axis position a deterministic order (C++ falls back on pointer order\n// for the same effect).  Declared after the class so the WeakMap value-type\n// reference resolves cleanly.  Module-private.\nlet _hyperedgeNodeCounter = 0;\nconst _nodeIds = new WeakMap<HyperedgeTreeNode, number>();\n\nfunction _nodeOrder(node: HyperedgeTreeNode): number {\n  let id = _nodeIds.get(node);\n  if (id === undefined) {\n    id = ++_hyperedgeNodeCounter;\n    _nodeIds.set(node, id);\n  }\n  return id;\n}\n\n// ─── HyperedgeTreeEdge ───────────────────────────────────────────────────────\n\n// @brief   An edge in the hyperedge tree.  Connects exactly two nodes\n//          and tracks the connector this segment will become.\nexport class HyperedgeTreeEdge {\n  // Pair of endpoint nodes; conventionally `first` is the \"from\" side\n  // when traversing.  Either can be null briefly during disconnect.\n  ends: [HyperedgeTreeNode | null, HyperedgeTreeNode | null];\n  conn: Edge | null;\n\n  constructor(node1: HyperedgeTreeNode, node2: HyperedgeTreeNode, conn: Edge | null) {\n    this.ends = [node1, node2];\n    this.conn = conn;\n    node1.edges.push(this);\n    node2.edges.push(this);\n  }\n\n  // Returns the node at the other end from `from`.\n  followFrom(from: HyperedgeTreeNode): HyperedgeTreeNode {\n    if (this.ends[0] === from) {\n      return this.ends[1]!;\n    }\n    return this.ends[0]!;\n  }\n\n  // True when both endpoints share the same position.\n  zeroLength(): boolean {\n    return this.ends[0]!.point.eq(this.ends[1]!.point);\n  }\n\n  // True when both endpoints have the same coordinate along `dimension`\n  // (i.e. the edge is axis-aligned in that dimension).\n  hasOrientation(dimension: number): boolean {\n    return this.ends[0]!.point.at(dimension) === this.ends[1]!.point.at(dimension);\n  }\n\n  // Replaces `oldNode` with `newNode` on whichever side it appears.\n  // `oldNode` is detached and `newNode` gains the edge in its list.\n  replaceNode(oldNode: HyperedgeTreeNode, newNode: HyperedgeTreeNode): void {\n    if (this.ends[0] === oldNode) {\n      oldNode.disconnectEdge(this);\n      newNode.edges.push(this);\n      this.ends[0] = newNode;\n    } else if (this.ends[1] === oldNode) {\n      oldNode.disconnectEdge(this);\n      newNode.edges.push(this);\n      this.ends[1] = newNode;\n    }\n  }\n\n  // Traverses outward from `ignored`, writing the segment between this\n  // edge's two endpoints into the appropriate connector's display route.\n  //\n  // `pass === 0` clears each connector's route; `pass === 1` writes points.\n  // `setRouteOps` provides connector-side primitives.\n  writeEdgesToConns(ignored: HyperedgeTreeNode, pass: number) {\n    if (this.ends[0] === null || this.ends[1] === null) {\n      throw new Error('HyperedgeTreeEdge.writeEdgesToConns: edge has null endpoint');\n    }\n    assert('HyperedgeTreeEdge.writeEdgesToConns has edge', this.conn);\n    const prevNode = ignored === this.ends[0] ? this.ends[0] : this.ends[1];\n    const nextNode = ignored === this.ends[0] ? this.ends[1] : this.ends[0];\n\n    if (pass === 0) {\n      this.conn.freeRoutes();\n    } else if (pass === 1) {\n      if (this.conn.displayRoute().size() === 0) {\n        this.conn.displayRoute().ps.push(new Point(prevNode.point.x, prevNode.point.y));\n      }\n      this.conn.displayRoute().ps.push(new Point(nextNode.point.x, nextNode.point.y));\n\n      const nextEdgeCount = nextNode.edges.length;\n      if (nextEdgeCount !== 2) {\n        // Done writing this connector.\n        let shouldReverse = false;\n        if (nextEdgeCount === 1) {\n          // Terminal.\n          if (nextNode.isConnectorSource) {\n            shouldReverse = true;\n          }\n        } else {\n          // nextEdgeCount > 2 — between two junctions.\n          let destination = this.conn.destination;\n          let correctEnd = destination instanceof Junction ? destination : null;\n          if (nextNode.junction !== correctEnd) {\n            shouldReverse = true;\n          }\n        }\n        if (shouldReverse) {\n          this.conn.reverseRoute();\n        }\n      }\n    }\n\n    nextNode.writeEdgesToConns(this, pass);\n  }\n\n  // Traverses outward (away from `ignored`) to the end of the branch and wires\n  // up the single connector this branch becomes, storing it on this edge.  The\n  // connector runs from `branchJunction` (where the branch started) to\n  // whichever terminal or junction the branch reaches; bend nodes in between\n  // share the same connector.\n  addConns(ignored: HyperedgeTreeNode, router: Router, branchJunction: Junction, sourceTerminals: Set<VertInf>): void {\n    const farNode = this.ends[0] !== ignored ? this.ends[0] : this.ends[1];\n    if (farNode === null) {\n      throw new Error('HyperedgeTreeEdge.addConns: edge has a null endpoint');\n    }\n\n    if (farNode.finalVertex) {\n      // Branch ends at a terminal: a free point at the terminal, carrying its\n      // visibility directions (defaulting to Direction.all would let A*\n      // approach from any side).\n      const terminal = new Endpoint(\n        new Point(farNode.finalVertex.point.x, farNode.finalVertex.point.y),\n        farNode.finalVertex.visDirections,\n      );\n      // Preserve the original connector direction.  If this terminal was a\n      // source, the new connector runs terminal→junction; otherwise the tree's\n      // outward direction (junction→terminal) already matches.  Orienting the\n      // Edge is all that's needed: the refinement A* pass regenerates the\n      // route points from the connector's src→dst, so the polyline follows\n      // suit without touching `isConnectorSource` here.\n      if (sourceTerminals.has(farNode.finalVertex)) {\n        this.conn = new Edge(router, terminal, branchJunction);\n      } else {\n        this.conn = new Edge(router, branchJunction, terminal);\n      }\n      router.addConnector(this.conn);\n      // (A terminal has no onward edges, so the recursion below is a no-op.)\n      farNode.addConns(this, router, branchJunction, sourceTerminals);\n    } else if (farNode.junction) {\n      // Branch ends at the next junction: connect the two junctions directly,\n      // then descend into that junction's own outgoing branches.  Creating\n      // this connector before recursing matches the order connectors are\n      // produced in (junction-first, outwards).\n      this.conn = new Edge(router, branchJunction, farNode.junction);\n      router.addConnector(this.conn);\n      farNode.addConns(this, router, branchJunction, sourceTerminals);\n    } else {\n      const onward = farNode.edges.find(edge => edge !== this);\n      if (onward) {\n        // Bend node: build out the rest of the branch first, then continue on\n        // the connector its onward edge ends up carrying.\n        farNode.addConns(this, router, branchJunction, sourceTerminals);\n        this.conn = onward.conn;\n      } else {\n        // Leaf with no recorded terminal vertex — a degenerate spanning tree\n        // (e.g. free terminals with no real structure) can produce one.  Still\n        // emit a connector, anchored to a free point at the leaf.\n        this.conn = new Edge(router, branchJunction, new Endpoint(new Point(farNode.point.x, farNode.point.y)));\n        router.addConnector(this.conn);\n      }\n    }\n  }\n\n  // Splits this edge by inserting a fresh node at `point`.  The existing\n  // edge stays attached to `source` on one side and to the new node on\n  // the other; a fresh edge connects the new node to the original target.\n  //\n  // Returns the newly created node so callers can position more edges off\n  // it (the C++ creates the new HyperedgeTreeEdge purely for its side\n  // effect — the constructor wires itself into both endpoint lists).\n  splitFromNodeAtPoint(source: HyperedgeTreeNode, point: Point): HyperedgeTreeNode {\n    // Make `source` the first of the two nodes.\n    if (this.ends[1] === source) {\n      const tmp = this.ends[0];\n      this.ends[0] = this.ends[1];\n      this.ends[1] = tmp;\n    }\n    if (this.ends[0] !== source) {\n      throw new Error('HyperedgeTreeEdge.splitFromNodeAtPoint: source is not an endpoint');\n    }\n\n    const target = this.ends[1]!;\n\n    // Create the new node at the split point.\n    const split = new HyperedgeTreeNode();\n    split.point = new Point(point.x, point.y);\n\n    // New edge between split and the original target.\n    new HyperedgeTreeEdge(split, target, this.conn);\n\n    // Detach the current edge from target and reattach it to split.\n    target.disconnectEdge(this);\n    this.ends[1] = split;\n    split.edges.push(this);\n\n    return split;\n  }\n\n  // Detaches this edge from both endpoints and clears its `ends` array.\n  disconnectEdge(): void {\n    if (this.ends[0] === null || this.ends[1] === null) {\n      throw new Error('HyperedgeTreeEdge.disconnectEdge: edge already disconnected');\n    }\n    this.ends[0].disconnectEdge(this);\n    this.ends[1].disconnectEdge(this);\n    this.ends[0] = null;\n    this.ends[1] = null;\n  }\n\n  //! Traverses the tree and removes from `treeRoots` any junctions on\n  //! the other side of this edge.  Returns true on cycle detection.\n  removeOtherJunctionsFrom(ignored: HyperedgeTreeNode | null, treeRoots: Set<Junction>): boolean {\n    let containsCycle = false;\n    if (this.ends[0] && this.ends[0] !== ignored) {\n      if (this.ends[0].removeOtherJunctionsFrom(this, treeRoots)) {\n        containsCycle = true;\n      }\n    }\n    if (this.ends[1] && this.ends[1] !== ignored) {\n      if (this.ends[1].removeOtherJunctionsFrom(this, treeRoots)) {\n        containsCycle = true;\n      }\n    }\n    return containsCycle;\n  }\n}\n","// Minimum Terminal Spanning Tree construction for hyperedge routing. - EBOARST paper\nimport {Point} from './geomtypes';\nimport {VertInf} from './vertex';\nimport {EdgeInf} from './graph';\nimport {\n  HyperedgeTreeEdge,\n  HyperedgeTreeNode,\n  type JunctionHyperedgeTreeNodeMap,\n  type VertexNodeMap,\n} from './hyperedgetree';\nimport type {Router} from './router';\nimport {Junction} from './models/junction';\nimport {groupCrossingCost, groupInteriorCost} from './models/annotation-group';\nimport {BinaryHeap} from './utilities/heap';\n\n// ─── Type aliases ────────────────────────────────────────────────────────────\n\nexport type VertexSet = Set<VertInf>;\nexport type VertexSetList = VertexSet[];\nexport type VertexPair = [VertInf, VertInf];\n\n// (Edge, partner) pair used by the orthogonal-edge traversal in heuristic 2.\ntype LayeredOrthogonalEdge = [EdgeInf, VertInf];\ntype LayeredOrthogonalEdgeList = LayeredOrthogonalEdge[];\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n// Hyperedge tree's tree-root pointer is a shared { value: VertInf | null }\n// box.  This is the TS analogue of `VertInf **` from C++.\ntype RootPointer = {value: VertInf | null};\n\n// ─── Binary heap for vertex / edge priority queues ───────────────────────────\n\n// Heap comparators (C++ priority queues are max-heaps; \"lower\" cost wins by\n// reversing the comparison, matching `a > b` returns from `HeapCmpVertInf`).\nfunction vertHeapLess(a: VertInf, b: VertInf): boolean {\n  return a.sptfDist < b.sptfDist;\n}\n\nfunction edgeHeapLess(a: EdgeInf, b: EdgeInf): boolean {\n  return a.mtstDist() < b.mtstDist();\n}\n\n// ─── MinimumTerminalSpanningTree ─────────────────────────────────────────────\n\n// @brief   Builds a minimum terminal spanning tree for a set of terminal\n//          vertices.\nexport class MinimumTerminalSpanningTree {\n  private router: Router;\n  private terminals: VertexSet;\n  private origTerminals: VertexSet;\n  private hyperedgeTreeJunctions: JunctionHyperedgeTreeNodeMap | null;\n\n  private nodes: VertexNodeMap;\n  private m_rootJunction: HyperedgeTreeNode | null;\n  private bendPenalty = 2000;\n  private extraVertices: VertInf[];\n\n  // Heaps used by extended Dijkstra (vHeap) and extended Kruskal (beHeap).\n  private vHeap: BinaryHeap<VertInf>;\n  private beHeap: BinaryHeap<EdgeInf>;\n\n  constructor(\n    router: Router,\n    terminals: VertexSet,\n    hyperedgeTreeJunctions: JunctionHyperedgeTreeNodeMap | null = null,\n  ) {\n    this.router = router;\n    this.terminals = new Set(terminals);\n    this.origTerminals = new Set();\n    this.hyperedgeTreeJunctions = hyperedgeTreeJunctions;\n\n    this.nodes = new Map();\n    this.m_rootJunction = null;\n    this.extraVertices = [];\n\n    this.vHeap = new BinaryHeap(vertHeapLess);\n    this.beHeap = new BinaryHeap(edgeHeapLess);\n  }\n\n  // Returns the root junction node of the constructed tree (null until\n  // construct{Sequential,Interleaved}() runs).\n  rootJunction(): HyperedgeTreeNode | null {\n    return this.m_rootJunction;\n  }\n\n  // ─── HyperedgeTreeNode bookkeeping ─────────────────────────────────────────\n\n  // Returns the HyperedgeTreeNode for a given vertex, creating it if needed.\n  // When two vertices end up at the same node, that node becomes a junction.\n  // Also wires a fresh HyperedgeTreeEdge to `prevNode` if supplied.\n  private addNode(vertex: VertInf, prevNode: HyperedgeTreeNode | null): HyperedgeTreeNode {\n    let node: HyperedgeTreeNode;\n    const existing = this.nodes.get(vertex);\n    if (!existing) {\n      const newNode = new HyperedgeTreeNode();\n      newNode.point = new Point(vertex.point.x, vertex.point.y);\n      this.nodes.set(vertex, newNode);\n      node = newNode;\n    } else {\n      const junctionNode = existing;\n      if (junctionNode.junction === null) {\n        // Promote this node into a junction.\n        let junction = new Junction(this.router, new Point(vertex.point.x, vertex.point.y));\n        this.router.addJunction(junction);\n        junctionNode.junction = junction;\n\n        if (this.m_rootJunction === null) {\n          // Remember the first junction node, used to traverse the tree\n          // when adding connectors and ConnEnds later.\n          this.m_rootJunction = junctionNode;\n        }\n      }\n      node = junctionNode;\n    }\n\n    if (prevNode) {\n      // Wire prevNode → node.  HyperedgeTreeEdge's constructor self-attaches.\n      new HyperedgeTreeEdge(prevNode, node, null);\n    }\n\n    return node;\n  }\n\n  // Walks backwards along pathNext links, materialising HyperedgeTreeNodes\n  // and edges as it goes.  Stops when it reaches a junction or terminal.\n  private buildHyperedgeTreeToRoot(\n    currVert: VertInf | null,\n    prevNode: HyperedgeTreeNode | null,\n    prevVert: VertInf,\n    markEdges = false,\n  ): void {\n    if (prevNode && prevNode.junction) {\n      // Reached a junction; stop.\n      return;\n    }\n    // If currVert is null on entry (terminal had no pathNext), the loop\n    // simply doesn't run — mirroring the C++ COLA_ASSERT-less release path.\n\n    while (currVert) {\n      const currentNode = this.addNode(currVert, prevNode);\n\n      if (markEdges) {\n        let edge = prevVert.hasNeighbour(currVert);\n        if (edge === null && currVert.isDimensionChangePartner) {\n          const modCurr = currVert.isDimensionChangePartner ? (currVert.orthogonalPartner ?? currVert) : currVert;\n          const modPrev = prevVert.isDimensionChangePartner ? (prevVert.orthogonalPartner ?? prevVert) : prevVert;\n          edge = modPrev.hasNeighbour(modCurr);\n        }\n        if (edge) {\n          edge.setHyperedgeSegment(true);\n        }\n      }\n\n      if (currentNode.junction) {\n        // Reached a junction; stop.\n        break;\n      }\n\n      if (currVert.pathNext === null) {\n        // Hyperedge terminal — record the vertex so we can later wire a\n        // proper ConnEnd for the connector.\n        currentNode.finalVertex = currVert;\n      }\n\n      prevNode = currentNode;\n      prevVert = currVert;\n      currVert = currVert.pathNext;\n    }\n  }\n\n  // Resets sptfDist and treeRootPointer for every vertex on the pathNext\n  // chain starting at `currVert`.  Returns the old tree-root pointer for\n  // the first vertex that already had sptfDist === 0.\n  private resetDistsForPath(currVert: VertInf, newRootVertPtr: RootPointer): RootPointer | null {\n    if (!currVert) {\n      throw new Error('resetDistsForPath: currVert must not be null');\n    }\n\n    let cv: VertInf | null = currVert;\n    while (cv) {\n      if (cv.sptfDist === 0) {\n        const oldTreeRootPtr = cv.treeRootPointer();\n        this.rewriteRestOfHyperedge(cv, newRootVertPtr);\n        return oldTreeRootPtr;\n      }\n      cv.sptfDist = 0;\n      cv.setTreeRootPointer(newRootVertPtr);\n      this.terminals.add(cv);\n      cv = cv.pathNext;\n    }\n    throw new Error('resetDistsForPath: walked off the end');\n  }\n\n  // Recursively marks the rest of an existing hyperedge with the new root\n  // pointer so all vertices on a freshly-committed branch share one root.\n  private rewriteRestOfHyperedge(vert: VertInf, newTreeRootPtr: RootPointer): void {\n    vert.setTreeRootPointer(newTreeRootPtr);\n\n    const edgeList = this.getOrthogonalEdgesFromVertex(vert, null);\n    for (const [, v] of edgeList) {\n      if (v.treeRootPointer() === newTreeRootPtr) continue;\n      if (v.sptfDist === 0) {\n        this.rewriteRestOfHyperedge(v, newTreeRootPtr);\n      }\n    }\n  }\n\n  // Annotation-group cost of `e`, in MTST's units.  MTST prices a bend at\n  // `bendPenalty` where A* prices it at `segmentPenalty`, and skirting a group\n  // takes a few extra bends — so an unscaled `groupCrossingPenalty` would let\n  // MTST cut through groups that A* routes around.  Scaling makes a crossing\n  // worth the same number of bends to both.  The interior cost trades against\n  // length, which both price alike, so it stays unscaled.  Not stamped onto\n  // `crossingCost()`, which A* reads too.\n  private groupCost(e: EdgeInf): number {\n    const a = e.vert1().point;\n    const b = e.vert2().point;\n    const crossing = groupCrossingCost(this.router, a, b);\n    const scaled = crossing === 0 ? 0 : (crossing * this.bendPenalty) / Math.max(this.router.params.segmentPenalty, 1);\n    return scaled + groupInteriorCost(this.router, a, b);\n  }\n\n  // ─── Orthogonal partner & edge enumeration ─────────────────────────────────\n\n  // Creates (if necessary) and returns the dummy orthogonal partner for a\n  // given vertex.  The partner sits at the same point but is on a different\n  // \"layer\" — turning between the two layers costs `penalty` (default\n  // bendPenalty).  This models the rectilinear bend cost.\n  private orthogonalPartner(vert: VertInf, penalty = 0): VertInf {\n    if (penalty === 0) penalty = this.bendPenalty;\n    if (vert.orthogonalPartner === null) {\n      // Synthetic partner; objID=0 / vn=0 is the conventional \"no owner\"\n      // identity.  The `isDimensionChangePartner` flag is what downstream\n      // checks (was `id.eq(dimensionChangeVertexID)` in the pre-Stage-5\n      // code).  Not added to the router's vertex list — this is a transient\n      // bookkeeping vertex used only inside the MTST construction.\n      const partner = new VertInf(0, 0, vert.point, {\n        isDimensionChangePartner: true,\n      });\n      vert.orthogonalPartner = partner;\n      partner.orthogonalPartner = vert;\n      this.extraVertices.push(partner);\n      const extraEdge = new EdgeInf(partner, vert, this.router);\n      extraEdge.setDist(penalty);\n    }\n    return vert.orthogonalPartner;\n  }\n\n  // Removes bridging edges from `beHeap` whose endpoints no longer connect\n  // distinct trees or whose roots have been pruned.\n  private removeInvalidBridgingEdges(): void {\n    const valid: EdgeInf[] = [];\n    for (const e of this.beHeap.content) {\n      const ends = this.realVerticesCountingPartners(e);\n      const r1 = ends[0].treeRoot();\n      const r2 = ends[1].treeRoot();\n      const ok = r1 !== r2 && r1 !== null && r2 !== null && this.origTerminals.has(r1) && this.origTerminals.has(r2);\n      if (ok) valid.push(e);\n    }\n    this.beHeap.replaceWith(valid);\n  }\n\n  // Returns every orthogonal edge incident on `vert`, paired with the\n  // \"partner\" vertex on the other side (which may be `vert`'s real\n  // neighbour or its orthogonal partner depending on layer).  Pre-computes\n  // the orthogonal partner if not present.\n  private getOrthogonalEdgesFromVertex(vert: VertInf, prev: VertInf | null): LayeredOrthogonalEdgeList {\n    const edgeList: LayeredOrthogonalEdgeList = [];\n    if (!vert) throw new Error('getOrthogonalEdgesFromVertex: vert required');\n\n    const penalty = prev === null ? 0.1 : 0;\n    this.orthogonalPartner(vert, penalty);\n\n    const isRealVert = !vert.isDimensionChangePartner;\n    const realVert = isRealVert ? vert : this.orthogonalPartner(vert);\n\n    for (const edge of realVert.orthogVisList) {\n      const other = edge.otherVert(realVert);\n\n      if (other === this.orthogonalPartner(realVert)) {\n        const partner = isRealVert ? other : this.orthogonalPartner(other);\n        if (partner !== prev) {\n          edgeList.push([edge, partner]);\n        }\n        continue;\n      }\n\n      const partner = isRealVert ? other : this.orthogonalPartner(other);\n\n      if (other.point.y === realVert.point.y) {\n        if (isRealVert && prev !== partner) {\n          edgeList.push([edge, partner]);\n        }\n      } else if (other.point.x === realVert.point.x) {\n        if (!isRealVert && prev !== partner) {\n          edgeList.push([edge, partner]);\n        }\n      } else {\n        // Non-orthogonal edge — keep but record.\n        edgeList.push([edge, other]);\n      }\n    }\n\n    return edgeList;\n  }\n\n  constructInterleaved(): void {\n    this.origTerminals = new Set(this.terminals);\n\n    // Initialisation: clear every vertex's distance and partner.  The\n    // iterator walks conn vertices first then shape vertices in linked-list\n    // order — same coverage as the old `connsBegin()`…`end()` loop, since\n    // the list's two segments are spliced together at the seam.\n    for (const k of this.router.vertices) {\n      k.sptfDist = Number.MAX_VALUE;\n      k.pathNext = null;\n      k.setTreeRootPointer(null);\n      k.orthogonalPartner = null;\n    }\n    for (const t of this.terminals) {\n      t.sptfDist = 0;\n      t.makeTreeRootPointer(t);\n      this.vHeap.content.push(t); // Verify...\n    }\n    // Reset hyperedge-segment flags on every orthogonal edge.\n    for (const t of this.router.visOrthogGraph) {\n      t.setHyperedgeSegment(false);\n    }\n\n    this.vHeap.rebuild();\n\n    // Main loop — interleaves forest growth with bridging-edge commits.\n    while (this.vHeap.length !== 0) {\n      const u = this.vHeap.front()!;\n\n      if (u.treeRoot() === null) {\n        throw new Error('constructInterleaved: orphaned vertex on heap');\n      }\n      if (u.pathNext === null && u.sptfDist !== 0) {\n        throw new Error('constructInterleaved: non-terminal without pathNext');\n      }\n\n      let firstBeHeap = this.beHeap.front();\n      if (firstBeHeap && u.sptfDist >= 0.5 * firstBeHeap.mtstDist()) {\n        // Commit to the cheapest bridging edge.\n        const e = this.beHeap.pop();\n        this.commitToBridgingEdge(e);\n\n        if (this.origTerminals.size === 1) {\n          break;\n        }\n\n        this.removeInvalidBridgingEdges();\n        // Don't pop u — re-loop.\n        continue;\n      }\n\n      this.vHeap.pop();\n\n      const edgeList = this.getOrthogonalEdgesFromVertex(u, u.pathNext);\n      for (const [e, v] of edgeList) {\n        // Crossing penalty is added on top of Euclidean distance — see\n        // `computeCrossingCosts` in hyperedge.ts.  Zero-cost by default,\n        // so this is a no-op unless `router.params.crossingPenalty > 0`.\n        const edgeDist = e.getDist() + e.crossingCost() + this.groupCost(e);\n\n        // Skip intra-tree edges.\n        if (u.treeRoot() === v.treeRoot()) {\n          continue;\n        }\n\n        if (v.treeRoot() === null) {\n          // Unexplored vertex — attach to u's tree.\n          const newCost = u.sptfDist + edgeDist;\n          v.sptfDist = newCost;\n          v.pathNext = u;\n          v.setTreeRootPointer(u.treeRootPointer());\n          this.vHeap.content.push(v); // Verify!!\n          this.vHeap.rebuild();\n        } else {\n          // Bridging candidate.  Mirror the per-edge cost composition used\n          // in `constructSequential`'s bridging branch.\n          const cost = v.sptfDist + u.sptfDist + e.getDist() + e.crossingCost() + this.groupCost(e);\n          const found = this.beHeap.contains(e);\n          if (!found) {\n            e.setMtstDist(cost);\n            this.beHeap.push(e);\n          } else if (cost < e.mtstDist()) {\n            e.setMtstDist(cost);\n            this.beHeap.rebuild();\n          }\n        }\n      }\n    }\n\n    // Detach dummy vertices.\n    for (const v of this.extraVertices) {\n      v.removeFromGraph(false);\n    }\n    this.extraVertices.length = 0;\n  }\n\n  // Returns the real vertices of a bridging edge, swapping in orthogonal\n  // partners when needed to make orientation comparisons meaningful.\n  private realVerticesCountingPartners(edge: EdgeInf): VertexPair {\n    const v1 = edge.vert1();\n    const v2 = edge.vert2();\n    let r1 = v1;\n    let r2 = v2;\n\n    if (\n      !v1.isDimensionChangePartner &&\n      !v2.isDimensionChangePartner &&\n      !v1.point.eq(v2.point) &&\n      v1.point.x === v2.point.x\n    ) {\n      if (v1.orthogonalPartner) r1 = v1.orthogonalPartner;\n      if (v2.orthogonalPartner) r2 = v2.orthogonalPartner;\n    }\n    return [r1, r2];\n  }\n\n  // Commits to a particular bridging edge — merges the two terminal trees,\n  // materialises the path on the HyperedgeTree, and rewrites root pointers\n  // so all vertices on the committed branch share a single tree root.\n  private commitToBridgingEdge(e: EdgeInf): void {\n    const ends = this.realVerticesCountingPartners(e);\n    const r1 = ends[0].treeRoot()!;\n    const r2 = ends[1].treeRoot()!;\n    // Stable tie-break by VertInf creation order — TS has no inherent\n    // pointer ordering, and we need the choice to be deterministic.\n    const r1Less = r1._seq < r2._seq;\n    const newRoot = r1Less ? r1 : r2;\n    const oldRoot = r1Less ? r2 : r1;\n\n    let node1: HyperedgeTreeNode | null = null;\n    let node2: HyperedgeTreeNode | null = null;\n    const vert1 = ends[0];\n    const vert2 = ends[1];\n    if (this.hyperedgeTreeJunctions) {\n      node1 = this.addNode(vert1, null);\n      node2 = this.addNode(vert2, node1);\n      e.setHyperedgeSegment(true);\n    }\n\n    this.buildHyperedgeTreeToRoot(vert1.pathNext, node1, vert1, true);\n    this.buildHyperedgeTreeToRoot(vert2.pathNext, node2, vert2, true);\n\n    // Re-root every vertex on the committed path to a fresh shared box.\n    const oldTreeRootPtr1 = vert1.treeRootPointer();\n    const oldTreeRootPtr2 = vert2.treeRootPointer();\n    this.origTerminals.delete(oldRoot);\n    const newTreeRootPtr = vert1.makeTreeRootPointer(newRoot);\n    vert2.setTreeRootPointer(newTreeRootPtr);\n\n    if (newRoot === null) {\n      throw new Error('commitToBridgingEdge: newRoot must not be null');\n    }\n    this.resetDistsForPath(vert1, newTreeRootPtr);\n    this.resetDistsForPath(vert2, newTreeRootPtr);\n\n    if (!oldTreeRootPtr1 || !oldTreeRootPtr2) {\n      throw new Error('commitToBridgingEdge: oldTreeRootPtrs must be set');\n    }\n\n    oldTreeRootPtr1.value = null;\n    oldTreeRootPtr2.value = null;\n\n    if (this.origTerminals.size === 1) return;\n\n    // Drop orphaned vertices from the vertex heap.\n    const next: VertInf[] = [];\n    for (const v of this.vHeap.content) {\n      if (v.treeRoot() !== null) {\n        next.push(v);\n      }\n    }\n    // Reset all (current) terminals back to the heap with sptfDist === 0.\n    for (const t of this.terminals) {\n      if (t.sptfDist !== 0) {\n        throw new Error('commitToBridgingEdge: terminal sptfDist not 0');\n      }\n      next.push(t);\n    }\n    this.vHeap.replaceWith(next);\n  }\n}\n","import {kUnassignedVertexNumber, Point, type Polygon} from './geomtypes';\nimport {Endpoint} from './models/endpoint';\nimport {VertInf} from './vertex';\nimport {Edge} from './models/edge';\nimport {Junction} from './models/junction';\nimport type {JunctionHyperedgeTreeNodeMap} from './hyperedgetree';\nimport {MinimumTerminalSpanningTree} from './mtst';\nimport type {Router} from './router';\n\nexport type Hyperedge = {type: 'terminals'; connEnds: (Endpoint | Junction)[]} | {type: 'invalid'};\n\n// ─── Internal helpers ────────────────────────────────────────────────────────\n\n// Equivalent of C++ `ConnEnd::getHyperedgeVertex(router)`.  Returns the\n// `VertInf` that represents this endpoint inside the visibility graph — either\n// an existing pin vertex or a freshly created one.  When a new vertex is\n// created, `addedVertex` is true so the caller can clean it up later.\n//\n// The C++ version also calls `vertexVisibility(vertex, null, true, true)` when\n// poly-line routing is enabled; we skip that — this port is orthogonal-only.\nfunction getHyperedgeVertex(end: Endpoint | Junction, router: Router): {addedVertex: boolean; vertex: VertInf} {\n  if (end instanceof Junction) {\n    return {addedVertex: false, vertex: end.centreVertex};\n  }\n\n  // Free-floating endpoint.  If some existing connector already has an\n  // endpoint vertex at this exact position+direction, reuse it — that vertex\n  // is already in the orthogonal visibility graph (built at the top of\n  // `route()`), so MTST can expand from it without forcing a graph rebuild.\n  // Synthesising a fresh duplicate vertex would land in `router.vertices`\n  // mid-`route()`, miss the graph, and leave MTST with an empty visList.\n  for (const curr of router.vertices) {\n    if (curr.isConnPoint && curr.point.eq(end.position) && curr.visDirections.equal(end.directions)) {\n      return {addedVertex: false, vertex: curr};\n    }\n  }\n\n  // No existing vertex matched — synthesise a fresh one.  This vertex won't\n  // have visibility edges (the static graph is already built), so the caller\n  // is responsible for regenerating the graph before MTST runs.\n  const vertex = new VertInf(0, kUnassignedVertexNumber, end.position, {\n    isConnPoint: true,\n  });\n  router.vertices.addVertex(vertex);\n  vertex.visDirections = end.directions;\n  return {addedVertex: true, vertex};\n}\n\n// ─── Crossing-cost precompute (Stage 3 of crossing-aware MTST) ───────────────\n//\n// Before MTST runs we walk the orthogonal visibility graph and, for each edge,\n// count how many existing connector route segments it would cross.  Each\n// crossing contributes `router.params.crossingPenalty` to that edge's\n// `crossingCost`, which MTST then adds to the edge's distance during\n// expansion (Stage 4).  Connectors that are about to be torn down by the\n// rerouter are skipped — penalising them would just punish MTST for going\n// near routes that won't exist by the time the new tree lands.\n//\n// Crossing rule: two orthogonal segments \"cross\" iff one is horizontal, the\n// other is vertical, and at least ONE of them meets the other at a point\n// strictly interior to itself.  This captures three cases:\n//\n//   1. Strict crossing — both interior (the X passes through both segments).\n//   2. T-junction — one segment's endpoint touches the other's interior.\n//      This case matters because the orthogonal sweepline splits vis-graph\n//      edges at intersection points, so a single \"real\" crossing routinely\n//      shows up as two vis-graph edges meeting at a shared T-junction\n//      vertex.  Without counting T-junctions, MTST would see no penalty\n//      even though going through the vertex traverses the other route.\n//   3. Shared-endpoint corner — explicitly excluded (both clauses fail).\n//\n// Note: this rule will count a \"real\" crossing twice when the vis graph has\n// split the offending edge at the intersection vertex (once per half of the\n// split).  That's a 2× over-penalty per crossing, which is still\n// behaviourally correct — MTST avoids the path either way.\n\n// Returns true iff axis-aligned orthogonal segments a1-a2 and b1-b2 meet at\n// a point that's interior to at least one of them and non-endpoint of the\n// other.  Caller guarantees both segments are axis-aligned (the orthogonal\n// vis graph and orthogonal-only route output satisfy this).  Parallel\n// segments never cross under this rule.\nfunction orthogonalSegmentsCross(a1: Point, a2: Point, b1: Point, b2: Point): boolean {\n  const aHorizontal = a1.y === a2.y;\n  const bHorizontal = b1.y === b2.y;\n  if (aHorizontal === bHorizontal) return false; // parallel\n  // Normalise so `h*` is horizontal, `v*` is vertical.\n  const h1 = aHorizontal ? a1 : b1;\n  const h2 = aHorizontal ? a2 : b2;\n  const v1 = aHorizontal ? b1 : a1;\n  const v2 = aHorizontal ? b2 : a2;\n  const hY = h1.y;\n  const vX = v1.x;\n  const hxMin = Math.min(h1.x, h2.x);\n  const hxMax = Math.max(h1.x, h2.x);\n  const vyMin = Math.min(v1.y, v2.y);\n  const vyMax = Math.max(v1.y, v2.y);\n\n  const vxStrictInH = vX > hxMin && vX < hxMax;\n  const vxOnH = vX >= hxMin && vX <= hxMax;\n  const hyStrictInV = hY > vyMin && hY < vyMax;\n  const hyOnV = hY >= vyMin && hY <= vyMax;\n\n  // At least one side must be a strict interior (else it's a corner touch).\n  return (vxStrictInH && hyOnV) || (vxOnH && hyStrictInV);\n}\n\n// Counts how many segments of `route` cross the orthogonal segment a-b.\nfunction countCrossingsWithRoute(a: Point, b: Point, route: Polygon): number {\n  let count = 0;\n  const ps = route.ps;\n  for (let i = 0; i + 1 < ps.length; i++) {\n    if (orthogonalSegmentsCross(a, b, ps[i], ps[i + 1])) count++;\n  }\n  return count;\n}\n\n// Walks `router.visOrthogGraph` and stamps each edge with its crossing cost\n// against the current `displayRoute()` of every non-skipped connector.\n// Called once per hyperedge by `performRerouting` before MTST runs.\nexport function computeCrossingCosts(router: Router, skipConnectors: Set<Edge>): void {\n  const penalty = router.params.crossingPenalty;\n\n  // Always zero out — stale costs from a previous hyperedge (or a previous\n  // `route()` call) would otherwise leak through.\n  for (const edge of router.visOrthogGraph) {\n    edge.setCrossingCost(0);\n  }\n\n  if (penalty <= 0) {\n    return;\n  }\n\n  for (const edge of router.visOrthogGraph) {\n    const a = edge.vert1().point;\n    const b = edge.vert2().point;\n    let crossings = 0;\n    for (const conn of router.connRefs) {\n      if (skipConnectors.has(conn)) continue;\n      crossings += countCrossingsWithRoute(a, b, conn.displayRoute());\n    }\n    if (crossings > 0) {\n      edge.setCrossingCost(penalty * crossings);\n    }\n  }\n}\n\ntype HyperedgeEntry = {\n  hyperedge: Hyperedge;\n  deletedEdges: Set<Edge>;\n  terminalVertices: Set<VertInf>;\n};\n\nexport class HyperedgeRerouter {\n  router: Router;\n  hyperedges: HyperedgeEntry[];\n  addedVertices: VertInf[] = [];\n  // Registered hyperedges.  Each one is either a list of endpoint ConnEnds or\n  // a root junction (with the other vector entry empty).\n  // private m_terminals_vector: ConnEnd[][] = [];\n  // private m_root_junction_vector: (JunctionRef | null)[] = [];\n\n  // Populated by performRerouting().  Indexed by registration order.\n\n  constructor(router: Router, hyperedges: Hyperedge[]) {\n    this.hyperedges = hyperedges.map(hyperedge => {\n      return {\n        hyperedge,\n        deletedEdges: new Set(),\n        terminalVertices: new Set(),\n      };\n    });\n    this.router = router;\n  }\n\n  // @brief   The number of hyperedges that have been registered.\n  count(): number {\n    return this.hyperedges.length;\n  }\n\n  // ─── Internal: invoked from Router ────────────────────────────────────────\n  calcHyperedgeConnectors(): {edges: Set<Edge>; addedVertices: VertInf[]} {\n    let allRegistered = new Set<Edge>();\n    this.addedVertices = [];\n\n    for (let {hyperedge, terminalVertices, deletedEdges} of this.hyperedges.values()) {\n      if (hyperedge.type === 'terminals') {\n        for (let connEnd of hyperedge.connEnds) {\n          const {addedVertex, vertex} = getHyperedgeVertex(connEnd, this.router);\n          terminalVertices.add(vertex);\n          if (addedVertex) {\n            this.addedVertices.push(vertex);\n          }\n        }\n        // Any existing connector whose *both* endpoints sit at registered\n        // terminal positions+directions is implicitly part of the user's\n        // intended hyperedge — the rerouter will spit out a fresh tree\n        // spanning these terminals, so leaving the old connectors alive\n        // would leave two parallel routings on the diagram.  Mark them for\n        // deletion and tell the connector loop in `Router.route()` to skip\n        // them (via `allRegistered`).\n        //\n        // The \"both endpoints\" rule is conservative: a connector that only\n        // shares one endpoint with the hyperedge is still doing its own\n        // independent job and shouldn't be deleted.\n        this.findExistingConnectorsForTerminals(deletedEdges, hyperedge.connEnds, allRegistered);\n      }\n    }\n    return {edges: allRegistered, addedVertices: this.addedVertices};\n  }\n\n  /** @internal */\n  // Walks `router.connRefs` and marks for deletion any connector whose\n  // src AND dst both match a registered terminal (by position + direction).\n  // See the `terminals` branch in `calcHyperedgeConnectors` for the\n  // rationale.\n  private findExistingConnectorsForTerminals(\n    deletedEdges: Set<Edge>,\n    connEnds: (Endpoint | Junction)[],\n    allRegistered: Set<Edge>,\n  ): void {\n    // Match against the connector's *stored* endpoint (`source` /\n    // `destination`), NOT its runtime endpoint vertex.  The vertex's\n    // `visDirections` is widened by the static-graph build\n    // (`fixConnectionPointVisibilityOnOutsideOfVisibilityGraph` opens up the\n    // visibility of endpoints sitting on the boundary of the vis graph), so\n    // comparing the registered terminal's direction against\n    // `vert.visDirections` gives false negatives.  The stored Endpoint keeps\n    // the originally-requested position + direction.\n    const matchesAnyTerminal = (end: Endpoint | Junction): boolean => {\n      for (const ce of connEnds) {\n        if (ce instanceof Junction) {\n          if (end === ce) return true;\n        } else if (!(end instanceof Junction) && end.position.eq(ce.position) && end.directions.equal(ce.directions)) {\n          return true;\n        }\n      }\n      return false;\n    };\n\n    for (const edge of this.router.connRefs) {\n      if (allRegistered.has(edge)) {\n        continue;\n      }\n      if (matchesAnyTerminal(edge.source) && matchesAnyTerminal(edge.destination)) {\n        deletedEdges.add(edge);\n        allRegistered.add(edge);\n      }\n    }\n  }\n\n  /** @internal */\n  // Perform the actual rerouting.  Called from `Router.route()` before\n  // individual connector routing.  Builds an MTST per registered hyperedge,\n  // writes the tree back to fresh ConnRef objects, then deletes the old\n  // junctions and connectors.\n  performRerouting(): void {\n    for (let {terminalVertices, deletedEdges} of this.hyperedges) {\n      if (terminalVertices.size === 0) {\n        continue; // Invalid hyperedge.\n      }\n\n      // Stamp `crossingCost` onto every vis-graph edge before MTST runs,\n      // weighting against the current routes of every connector that ISN'T\n      // about to be deleted by this hyperedge.  No-op when crossingPenalty\n      // is 0.\n      computeCrossingCosts(this.router, deletedEdges);\n\n      // Build the MTST and grab its hyperedge tree root.\n      const hyperedgeTreeJunctions: JunctionHyperedgeTreeNodeMap = new Map();\n      const mtst = new MinimumTerminalSpanningTree(this.router, terminalVertices, hyperedgeTreeJunctions);\n      mtst.constructInterleaved();\n      const treeRoot = mtst.rootJunction();\n      if (treeRoot === null) {\n        // No junction was created — can't form a hyperedge.  Skip.\n        continue;\n      }\n\n      // Which terminals were the *source* end of a deleted connector?  The new\n      // connectors must keep the original src→dst direction, so a branch\n      // ending at one of these is oriented terminal→junction rather than the\n      // tree's default junction→terminal.\n      const sourceTerminals = new Set<VertInf>();\n      for (const conn of deletedEdges) {\n        const src = conn.source;\n        const srcPos = src instanceof Junction ? src.position() : src.position;\n        for (const terminal of terminalVertices) {\n          if (terminal.point.eq(srcPos)) {\n            sourceTerminals.add(terminal);\n          }\n        }\n      }\n\n      // Walk the tree, creating a fresh ConnRef for each branch (junction to\n      // terminal or junction to junction).\n      treeRoot.addConns(null, this.router, null, sourceTerminals);\n\n      // Two-pass write of segments → connector routes.\n      const setRouteOps = makeSetRouteOps();\n      for (let pass = 0; pass < 2; pass++) {\n        treeRoot.writeEdgesToConns(null, pass, setRouteOps);\n      }\n\n      // Delete the old objects.\n      for (const conn of deletedEdges) {\n        this.router.deleteConnector(conn);\n      }\n    }\n\n    // Clear the registration so subsequent route() calls don't re-process.\n    this.hyperedges = [];\n\n    // Free temporary endpoint vertices.\n    for (const vertex of this.addedVertices) {\n      vertex.removeFromGraph();\n      this.router.vertices.removeVertex(vertex);\n    }\n    this.addedVertices = [];\n  }\n}\n\n// ─── Tree-traversal glue (matches hyperedgeimprover.ts pattern) ─────────────\n\n// Builds the setRouteOps record that `HyperedgeTreeEdge.writeEdgesToConns`\n// expects.  Same shape as in hyperedgeimprover.ts.\nfunction makeSetRouteOps(): {\n  clearDisplayRoute: (conn: Edge) => void;\n  pushPoint: (conn: Edge, point: Point) => void;\n  routeIsEmpty: (conn: Edge) => boolean;\n  destinationJunction: (conn: Edge) => Junction | null;\n} {\n  return {\n    clearDisplayRoute(edge) {\n      // Empty the route so `routeIsEmpty()` reports true and `pushPoint`\n      // starts a fresh polyline for this connector.\n      edge.freeRoutes();\n    },\n    pushPoint(edge, point) {\n      edge.displayRoute().ps.push(new Point(point.x, point.y));\n    },\n    routeIsEmpty(edge) {\n      return edge.displayRoute().ps.length === 0;\n    },\n    destinationJunction(edge) {\n      let destination = edge.destination;\n      return destination instanceof Junction ? destination : null;\n    },\n  };\n}\n","export function getOrInsertComputed<Key, Value>(map: Map<Key, Value>, key: Key, computed: (key: Key) => Value): Value {\n  if (map.has(key)) {\n    return map.get(key) as Value;\n  }\n  let computedEntry = computed(key);\n  map.set(key, computedEntry);\n  return computedEntry;\n}\n","// Port of `Router::improveCrossings()` (libavoid router.cpp:1409).\n//\n// Post-routing pass that walks every pair of connectors, finds those whose\n// orthogonal routes cross (or share a fixed segment) and re-runs A* on a\n// minimal subset to remove the crossings.  Re-routing happens with\n// `router.isInCrossingPenaltyReroutingStage() === true` so makepath's\n// `cost()` adds the per-step crossing / shared-path penalties — A* will\n// therefore route around the existing fixed routes instead of through them.\n//\n// Differences from the C++ original:\n//   - Exclusive-pin propagation is dropped (the port has no\n//     ShapeConnectionPin machinery).\n//   - The `performContinuationCheck` / `m_abort_transaction` cancellation\n//     hooks are dropped — the port has no transaction layer.\n//   - PolyLine length uses manhattan distance unconditionally (the port is\n//     orthogonal-only; there's no `routingType()`).\n//\n// Algorithm:\n//   1. Walk every (i,j) pair of non-empty routes.  For each pair, use\n//      `ConnectorCrossings` to detect crossings and fixed shared paths.\n//      Record matching pairs in `CrossingConnectorsInfo`, which groups\n//      transitively-interacting connectors together.\n//   2. For each group, greedily pick the connector with the most crossings\n//      (cheap-cost as tiebreak) and add it to the rerouting set.  Repeat\n//      until no connector in the group has any remaining crossings.\n//   3. Sort each rerouting set by ascending cheap-cost, then for two passes:\n//      pass 0 invalidates the path + clears routes (so they don't pollute\n//      other connectors' penalty calculations), pass 1 calls generatePath.\n\nimport {Point, Polygon} from './geomtypes';\nimport {manhattanDist} from './geometry';\nimport {CROSSING_SHARES_PATH, CROSSING_SHARES_PATH_AT_END, CROSSING_SHARES_FIXED_SEGMENT} from './models/edge';\nimport {ConnectorCrossings} from './data-structures/ConnectorCrossings';\n\nimport type {Edge} from './models/edge';\nimport type {Router} from './router';\nimport {getOrInsertComputed} from './utilities/map';\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n// Cheap proxy for connector cost used to pick which connector to reroute when\n// two connectors have the same crossing count and to order the rerouting\n// sequence within a group.  Mirrors C++ `cheapEstimatedCost`: manhattan length\n// minus the segment count so straight routes (which \"look correct\") are\n// preferred over wiggly ones.\nfunction cheapEstimatedCost(edge: Edge): number {\n  const route = edge.displayRoute();\n  let length = route.pairs().reduce((length, [prev, next]) => (length += manhattanDist(prev, next)), 0);\n  return length - (route.size() + 1);\n}\n\n// One entry in a rerouting set: the connector and the crossing count it had\n// when it was selected.  `cost === 0` is used for connectors pulled in by\n// exclusive-pin propagation in C++ — kept here for parity even though we\n// don't propagate that way.\ntype ConnCostRef = {cost: number; conn: Edge};\n\n// Strict-interior crossing test for two orthogonal segments.  Returns true\n// when the segments are perpendicular and intersect in *both* segments'\n// strict interiors (endpoints touching is not a crossing — those are\n// T-junctions that the shared-path branch handles).\n//\n// We need this because `ConnectorCrossings.countForSegment` skips the\n// generic segment-intersection check for the orthogonal/orthogonal case on\n// the assumption that \"all crossings will be at a vis-graph vertex\" — a\n// valid invariant at A* time but broken post-nudge, where the improver\n// moves segments without splitting them at new intersection points.\nfunction orthogonalSegmentsCrossStrict(a1: Point, a2: Point, b1: Point, b2: Point): boolean {\n  const aVertical = a1.x === a2.x;\n  const bVertical = b1.x === b2.x;\n  if (aVertical === bVertical) {\n    // Parallel (both vertical or both horizontal) — no point crossing.\n    return false;\n  }\n  const v1 = aVertical ? a1 : b1;\n  const v2 = aVertical ? a2 : b2;\n  const h1 = aVertical ? b1 : a1;\n  const h2 = aVertical ? b2 : a2;\n\n  const vX = v1.x;\n  const hY = h1.y;\n  const vyMin = Math.min(v1.y, v2.y);\n  const vyMax = Math.max(v1.y, v2.y);\n  const hxMin = Math.min(h1.x, h2.x);\n  const hxMax = Math.max(h1.x, h2.x);\n\n  // Strict interior on both axes.  Endpoints touching => not a crossing.\n  return vX > hxMin && vX < hxMax && hY > vyMin && hY < vyMax;\n}\n\n// Returns true if the two routes cross or share a fixed segment that\n// should be penalised.  Combines `ConnectorCrossings` (for shared-path\n// detection, which doesn't have a brute-force alternative) with a direct\n// O(n*m) orthogonal-segment scan (for strict crossings, which\n// `ConnectorCrossings` skips post-nudge — see `orthogonalSegmentsCrossStrict`).\nfunction pairCrosses(\n  routeI: Polygon,\n  routeJ: Polygon,\n  connI: Edge,\n  connJ: Edge,\n  crossingPenalty: number,\n  sharedPathPenalty: number,\n  penaliseOrthogonalSharedPathsAtConnEnds: boolean,\n): boolean {\n  // Shared-path detection via ConnectorCrossings.  Only worth running when\n  // a shared-path penalty is configured; otherwise the orthogonal scan\n  // below handles all the cases we care about.\n  if (sharedPathPenalty > 0) {\n    const cross = new ConnectorCrossings(routeI, true, routeJ, connI, connJ);\n    for (let jInd = 1; jInd < routeJ.size(); jInd++) {\n      const finalSegment = jInd + 1 === routeJ.size();\n      cross.countForSegment(jInd, finalSegment);\n\n      const isFixedSharedPath =\n        cross.crossingFlags & CROSSING_SHARES_PATH &&\n        cross.crossingFlags & CROSSING_SHARES_FIXED_SEGMENT &&\n        (penaliseOrthogonalSharedPathsAtConnEnds || !(cross.crossingFlags & CROSSING_SHARES_PATH_AT_END));\n      if (isFixedSharedPath) return true;\n    }\n  }\n\n  // Strict orthogonal crossings.  O(n*m) over segment pairs, fine for the\n  // route lengths we deal with here.\n  if (crossingPenalty > 0) {\n    for (let [a1, a2] of routeI.pairs()) {\n      for (let [b1, b2] of routeJ.pairs()) {\n        if (orthogonalSegmentsCrossStrict(a1, a2, b1, b2)) {\n          return true;\n        }\n      }\n    }\n  }\n\n  return false;\n}\n\n// ─── CrossingConnectorsInfo ──────────────────────────────────────────────────\n//\n// Maintains a set of disjoint groups of crossing-interacting connectors.\n// Adding (a, b) merges any existing groups containing a or b.\n\nfunction createSet(): Set<Edge> {\n  return new Set();\n}\n\ntype CrossingGroup = Map<Edge, Set<Edge>>;\n\nclass CrossingConnectorsInfo {\n  private groups: CrossingGroup[] = [];\n\n  addCrossing(c1: Edge, c2: Edge): void {\n    const group = this.groupForCrossingConns(c1, c2);\n    getOrInsertComputed(group, c1, createSet).add(c2);\n    getOrInsertComputed(group, c2, createSet).add(c1);\n  }\n\n  // True if the pair is already known to cross — saves redundant\n  // ConnectorCrossings walks in the outer pair loop.\n  connsKnownToCross(c1: Edge, c2: Edge): boolean {\n    const g1 = this.groupForConn(c1);\n    const g2 = this.groupForConn(c2);\n    if (g1 === g2 && g1 !== null) {\n      const set = g1.get(c1);\n      return !!set && set.has(c2);\n    }\n    return false;\n  }\n\n  // Build the list of rerouting sets, one per group.  Greedy peel:\n  // repeatedly remove the connector with the most crossings (cheap-cost as\n  // tiebreak) until no crossings remain in the group.\n  crossingSetsListToRemoveCrossingsFromGroups(): ConnCostRef[][] {\n    const result: ConnCostRef[][] = [];\n    for (const group of this.groups) {\n      const crossingSet: ConnCostRef[] = [];\n      let next: ConnCostRef | null;\n      while ((next = this.removeConnectorWithMostCrossings(group)) !== null) {\n        crossingSet.push(next);\n      }\n      // (C++ would also add other connectors attached to the same exclusive\n      // pins here — dropped, see file header.)\n      if (crossingSet.length > 0) {\n        result.push(crossingSet);\n      }\n    }\n    return result;\n  }\n\n  // ─── private ────────────────────────────────────────────────────────────\n\n  private groupForConn(conn: Edge): CrossingGroup | null {\n    for (const g of this.groups) {\n      if (g.has(conn)) return g;\n    }\n    return null;\n  }\n\n  private groupForCrossingConns(c1: Edge, c2: Edge): CrossingGroup {\n    const g1 = this.groupForConn(c1);\n    const g2 = this.groupForConn(c2);\n    if (g1 === null && g2 === null) {\n      const g: CrossingGroup = new Map();\n      this.groups.push(g);\n      return g;\n    }\n    if (g1 !== null && g2 === null) return g1;\n    if (g1 === null && g2 !== null) return g2;\n    if (g1 !== g2) {\n      // Merge g2 into g1.\n      for (const [k, v] of g2!) {\n        if (!g1!.has(k)) g1!.set(k, new Set());\n        for (const x of v) g1!.get(k)!.add(x);\n      }\n      this.groups.splice(this.groups.indexOf(g2!), 1);\n      return g1!;\n    }\n    return g1!;\n  }\n\n  // Pick (and remove) the connector with the most outstanding crossings in\n  // the group.  Returns null when no connector in the group has any\n  // crossings left (i.e. the group is fully peeled).\n  private removeConnectorWithMostCrossings(group: CrossingGroup): ConnCostRef | null {\n    let candidate: Edge | null = null;\n    let candidateCount = 0;\n    let candidateCost = 0;\n    for (const [conn, peers] of group) {\n      const crossings = peers.size;\n      if (crossings === 0) continue;\n      const cost = cheapEstimatedCost(conn);\n      if (crossings > candidateCount || (crossings === candidateCount && cost > candidateCost)) {\n        candidate = conn;\n        candidateCount = crossings;\n        candidateCost = cost;\n      }\n    }\n    if (candidate === null) return null;\n\n    // Remove `candidate` from every peer's crossing set, then clear its own.\n    const peerSet = group.get(candidate)!;\n    for (const peer of peerSet) {\n      group.get(peer)?.delete(candidate);\n    }\n    peerSet.clear();\n    return {cost: candidateCount, conn: candidate};\n  }\n}\n\n// ─── improveCrossings ────────────────────────────────────────────────────────\n\n// Returns true when at least one connector was rerouted.\nexport function improveCrossings(router: Router): boolean {\n  const crossingPenalty = router.params.crossingPenalty;\n  const sharedPathPenalty = router.params.fixedSharedPathPenalty;\n  if (crossingPenalty === 0 && sharedPathPenalty === 0) {\n    // No penalties configured; rerouting would have nothing to optimise for.\n    return false;\n  }\n\n  const penaliseEnds = router.options.penaliseOrthogonalSharedPathsAtConnEnds;\n\n  const info = new CrossingConnectorsInfo();\n  let rerouted = false;\n\n  // ─── Phase 1: detect crossings ─────────────────────────────────────────\n  router._setInCrossingPenaltyReroutingStage(true);\n  try {\n    const conns = router.connRefs.slice();\n    for (let i = 0; i < conns.length; i++) {\n      const ci = conns[i];\n      const ri = ci.displayRoute();\n      if (ri.size() === 0) {\n        // Rerouted hyperedges have empty raw routes; we can't reason about\n        // them here — skip.\n        continue;\n      }\n      for (let j = i + 1; j < conns.length; j++) {\n        const cj = conns[j];\n        if (info.connsKnownToCross(ci, cj)) continue;\n        const rj = cj.displayRoute();\n        if (rj.size() === 0) continue;\n        if (pairCrosses(ri, rj, ci, cj, crossingPenalty, sharedPathPenalty, penaliseEnds)) {\n          info.addCrossing(ci, cj);\n        }\n      }\n    }\n\n    // ─── Phase 2: peel the crossing-causing connectors out of each group ──\n    const crossingSets = info.crossingSetsListToRemoveCrossingsFromGroups();\n\n    // ─── Phase 3: reroute, group by group ─────────────────────────────────\n    for (const set of crossingSets) {\n      // Sort ascending by the crossing count we recorded when peeling.  C++\n      // sorts by `first` (= count) — the connector with the fewest crossings\n      // reroutes first, on the theory that it's easiest to redirect and the\n      // remaining (more-tangled) connectors then have a cleaner field.\n      const ordered = set.slice().sort((a, b) => a.cost - b.cost);\n\n      // Pass 0: invalidate + free routes so the connectors-being-rerouted\n      // don't appear in each other's crossing penalties during pass 1.\n      for (const {conn} of ordered) {\n        conn.makePathInvalid();\n        conn.freeRoutes();\n      }\n      // Pass 1: rerun A*.  `isInCrossingPenaltyReroutingStage()` is true so\n      // makepath's `cost()` adds per-segment crossing/shared-path penalties.\n      for (const {conn} of ordered) {\n        conn.generatePath();\n        rerouted = true;\n      }\n    }\n  } finally {\n    router._setInCrossingPenaltyReroutingStage(false);\n  }\n  return rerouted;\n}\n","// Scanline sweep for orthogonal-routing channel building.\n//\n// Ports input/scanline.cpp.  Three exports drive the algorithm:\n//   - buildOrthogonalChannelInfo: orthogonal nudging's space-determination\n//   - buildConnectorRouteCheckpointCache: marks segments touched by\n//     routing checkpoints\n//   - clearConnectorRouteCheckpointCache: clears those caches\n//\n// The scanline maintains a sorted set of Node objects (by `pos`, with\n// insertion-order tiebreak).  Each insertion records firstAbove/firstBelow\n// neighbour pointers so the Node can later inspect its environment without\n// re-querying the set.  ShiftSegments and Obstacles meet through the same\n// Node abstraction.\n//\n// The ShiftSegment interface is left abstract; concrete subclasses come from\n// orthogonal.ts (not yet ported).\n\nimport {type Point, XDIM, YDIM} from './geomtypes';\nimport {type VertInf} from './vertex';\nimport {pointOnLine} from './geometry';\nimport type {Router} from './router';\nimport type {Obstacle} from './models/obstacle';\nimport {SortedArray} from './utilities/sorted-array';\n\n// ─── Constants ────────────────────────────────────────────────────────────────\n\nexport const CHANNEL_MAX = 1e8;\n\n// ─── ShiftSegment ─────────────────────────────────────────────────────────────\n\n// Abstract interface for a shiftable segment in the orthogonal nudger.\n// Concrete implementations (NudgingShiftSegment, etc.) live in orthogonal.ts.\n//\n// `dimension` is the axis the segment is shifted *along* (perpendicular to\n// the segment direction).  `lowPoint`/`highPoint` return endpoints; the order\n// follows lower → higher in `1 - dimension` (the segment's own axis).\nexport interface ShiftSegment {\n  dimension: number;\n  minSpaceLimit: number;\n  maxSpaceLimit: number;\n\n  lowPoint(): Point;\n  highPoint(): Point;\n  overlapsWith(rhs: ShiftSegment, dim: number): boolean;\n  immovable(): boolean;\n}\n\n// ─── Node ─────────────────────────────────────────────────────────────────────\n//\n// A Node represents one of three kinds of scanline element:\n//   - An obstacle (`v` set) — the centre of a shape/junction's range\n//   - A connector endpoint (`c` set) — a single point\n//   - A shift segment (`ss` set) — a candidate shiftable segment\n//\n// `min[dim]`/`max[dim]` is the extent of this Node in dimension `dim`.  The\n// scanline sorts Nodes by `pos`; tiebreaking is by insertion order so behaviour\n// stays deterministic.\n\nlet _nodeCounter = 0;\n\nexport class Node {\n  v: Obstacle | null;\n  c: VertInf | null;\n  ss: ShiftSegment | null;\n  pos: number;\n  min: [number, number];\n  max: [number, number];\n  firstAbove: Node | null;\n  firstBelow: Node | null;\n  // Insertion-order id used as a deterministic tiebreaker.  Replaces the C++\n  // pointer comparison in CmpNodePos.\n  readonly id: number;\n\n  // ─── Factories (one per kind) ─────────────────────────────────────────────\n\n  static forObstacle(v: Obstacle, pos: number): Node {\n    const node = new Node(pos);\n    node.v = v;\n    const bb = v.routingBox();\n    node.min[XDIM] = bb.min.x;\n    node.min[YDIM] = bb.min.y;\n    node.max[XDIM] = bb.max.x;\n    node.max[YDIM] = bb.max.y;\n    return node;\n  }\n\n  static forVertex(c: VertInf, pos: number): Node {\n    const node = new Node(pos);\n    node.c = c;\n    node.min[XDIM] = node.max[XDIM] = c.point.x;\n    node.min[YDIM] = node.max[YDIM] = c.point.y;\n    return node;\n  }\n\n  // A bare point with no vertex or obstacle behind it.  Used for the extra\n  // scanlines `generateStaticOrthogonalVisGraph` adds between facing\n  // connector endpoints.\n  static forPoint(point: Point, pos: number): Node {\n    const node = new Node(pos);\n    node.min[XDIM] = node.max[XDIM] = point.x;\n    node.min[YDIM] = node.max[YDIM] = point.y;\n    return node;\n  }\n\n  static forShiftSegment(ss: ShiftSegment, pos: number): Node {\n    const node = new Node(pos);\n    node.ss = ss;\n    // min/max never read for shift-segment nodes.\n    return node;\n  }\n\n  private constructor(pos: number) {\n    this.v = null;\n    this.c = null;\n    this.ss = null;\n    this.pos = pos;\n    this.min = [0, 0];\n    this.max = [0, 0];\n    this.firstAbove = null;\n    this.firstBelow = null;\n    this.id = ++_nodeCounter;\n  }\n\n  // Total ordering used by every scanline `SortedArray<Node>`: primary by\n  // `pos`, tiebreak by insertion-order `id` (the C++ source falls back on\n  // pointer order here; we use the monotonic id assigned at construction\n  // for the same deterministic effect).\n  static compare(a: Node, b: Node): number {\n    if (a.pos !== b.pos) return a.pos < b.pos ? -1 : 1;\n    return a.id - b.id;\n  }\n\n  // ─── Queries ──────────────────────────────────────────────────────────────\n\n  // Returns the position of the first shape edge above (in scanline order)\n  // that has not just been opened or closed at this position.  Returns\n  // -Number.MAX_VALUE if no such edge exists.\n  firstObstacleAbove(dim: number): number {\n    let curr = this.firstAbove;\n    while (curr && (curr.ss !== null || curr.max[dim] > this.pos)) {\n      curr = curr.firstAbove;\n    }\n    return curr ? curr.max[dim] : -Number.MAX_VALUE;\n  }\n\n  // Same as firstObstacleAbove but in the \"below\" direction.\n  firstObstacleBelow(dim: number): number {\n    let curr = this.firstBelow;\n    while (curr && (curr.ss !== null || curr.min[dim] < this.pos)) {\n      curr = curr.firstBelow;\n    }\n    return curr ? curr.min[dim] : Number.MAX_VALUE;\n  }\n\n  // Walk above and mark every connector segment whose space is bounded by\n  // this obstacle's near edge.\n  markShiftSegmentsAbove(dim: number): void {\n    let curr = this.firstAbove;\n    while (curr && (curr.ss !== null || curr.pos > this.min[dim])) {\n      if (curr.ss !== null && curr.pos <= this.min[dim]) {\n        curr.ss.maxSpaceLimit = Math.min(this.min[dim], curr.ss.maxSpaceLimit);\n      }\n      curr = curr.firstAbove;\n    }\n  }\n\n  // Same but in the \"below\" direction.\n  markShiftSegmentsBelow(dim: number): void {\n    let curr = this.firstBelow;\n    while (curr && (curr.ss !== null || curr.pos < this.max[dim])) {\n      if (curr.ss !== null && curr.pos >= this.max[dim]) {\n        curr.ss.minSpaceLimit = Math.max(this.max[dim], curr.ss.minSpaceLimit);\n      }\n      curr = curr.firstBelow;\n    }\n  }\n\n  // Used by orthogonal nudging: enumerate first/last shape limits above and\n  // below for the line at `linePos` (the perpendicular axis).\n  findFirstPointAboveAndBelow(\n    dim: number,\n    linePos: number,\n  ): {\n    firstAbove: number;\n    firstBelow: number;\n    lastAbove: number;\n    lastBelow: number;\n  } {\n    let firstAbove = -Number.MAX_VALUE;\n    let firstBelow = Number.MAX_VALUE;\n    // Start from the obstacle's own edges; we relax these as we walk.\n    let lastAbove = this.max[dim];\n    let lastBelow = this.min[dim];\n\n    const altDim = 1 - dim;\n\n    for (let direction = 0; direction < 2; direction++) {\n      let curr = direction === 0 ? this.firstAbove : this.firstBelow;\n      while (curr) {\n        // True if both events share their begin or end position along altDim.\n        // Such pairs do not block visibility.\n        const eventsAtSamePos =\n          (linePos === this.max[altDim] && linePos === curr.max[altDim]) ||\n          (linePos === this.min[altDim] && linePos === curr.min[altDim]);\n\n        if (curr.max[dim] <= this.min[dim]) {\n          // curr is entirely to the \"above\" side of `this`; its right edge\n          // bounds firstAbove from above.\n          firstAbove = Math.max(curr.max[dim], firstAbove);\n        } else if (curr.min[dim] >= this.max[dim]) {\n          // curr is entirely \"below\"; its left edge bounds firstBelow.\n          firstBelow = Math.min(curr.min[dim], firstBelow);\n        } else if (!eventsAtSamePos) {\n          // Overlap: shrink lastAbove/lastBelow accordingly.\n          lastAbove = Math.min(curr.min[dim], lastAbove);\n          lastBelow = Math.max(curr.max[dim], lastBelow);\n        }\n        curr = direction === 0 ? curr.firstAbove : curr.firstBelow;\n      }\n    }\n\n    return {firstAbove, firstBelow, lastAbove, lastBelow};\n  }\n\n  // Walk above looking for the closest obstacle whose edge is not in line\n  // with this Node's `altDim` edge (i.e. visibility along edges is allowed).\n  firstPointAbove(dim: number): number {\n    const altDim = 1 - dim;\n    let result = -Number.MAX_VALUE;\n    for (let curr = this.firstAbove; curr; curr = curr.firstAbove) {\n      const inLineWithEdge = this.min[altDim] === curr.min[altDim] || this.min[altDim] === curr.max[altDim];\n      if (!inLineWithEdge && curr.max[dim] <= this.pos) {\n        result = Math.max(curr.max[dim], result);\n      }\n    }\n    return result;\n  }\n\n  // Same, but looking below.\n  firstPointBelow(dim: number): number {\n    const altDim = 1 - dim;\n    let result = Number.MAX_VALUE;\n    for (let curr = this.firstBelow; curr; curr = curr.firstBelow) {\n      const inLineWithEdge = this.min[altDim] === curr.min[altDim] || this.min[altDim] === curr.max[altDim];\n      if (!inLineWithEdge && curr.min[dim] >= this.pos) {\n        result = Math.min(curr.min[dim], result);\n      }\n    }\n    return result;\n  }\n\n  // True if this point's `pos` falls strictly inside any neighbour shape's\n  // extent in `dimension`.\n  isInsideShape(dimension: number): boolean {\n    for (let curr = this.firstBelow; curr; curr = curr.firstBelow) {\n      if (curr.min[dimension] < this.pos && this.pos < curr.max[dimension]) {\n        return true;\n      }\n    }\n    for (let curr = this.firstAbove; curr; curr = curr.firstAbove) {\n      if (curr.min[dimension] < this.pos && this.pos < curr.max[dimension]) {\n        return true;\n      }\n    }\n    return false;\n  }\n}\n\n// ─── EventType / Event ────────────────────────────────────────────────────────\n\n// Note: Open must come first.  The integer ordering determines tie-breaking\n// when multiple events share the same scanline position — Opens fire before\n// Closes at the same line.\nexport const EventType = {\n  Open: 1,\n  SegOpen: 2,\n  ConnPoint: 3,\n  SegClose: 4,\n  Close: 5,\n} as const;\nexport type EventTypeKind = (typeof EventType)[keyof typeof EventType];\n\nlet _eventCounter = 0;\n\nexport class Event {\n  type: EventTypeKind;\n  v: Node;\n  pos: number;\n  readonly id: number;\n\n  constructor(type: EventTypeKind, v: Node, pos: number) {\n    this.type = type;\n    this.v = v;\n    this.pos = pos;\n    this.id = ++_eventCounter;\n  }\n}\n\n// ─── Comparators ──────────────────────────────────────────────────────────────\n\n// compareEvents: sort key for the event queue.  Primary by `pos`, then by\n// `type` (Opens before Closes), then by insertion order.\nexport function compareEvents(a: Event, b: Event): number {\n  if (a.pos !== b.pos) return a.pos < b.pos ? -1 : 1;\n  if (a.type !== b.type) return a.type - b.type;\n  return a.id - b.id;\n}\n\n// ─── processShiftEvent ────────────────────────────────────────────────────────\n\n// Processes a single sweep event in one of four passes:\n//   pass 1: SegClose / Close — record limits while neighbours are still here\n//   pass 2: SegClose / Close — remove from scanline\n//   pass 3: Open / SegOpen   — insert into scanline & link neighbours\n//   pass 4: Open / SegOpen   — record limits with neighbours now in place\nfunction processShiftEvent(scanline: SortedArray<Node>, e: Event, dim: number, pass: number): void {\n  const v = e.v;\n\n  if (pass === 3 && (e.type === EventType.Open || e.type === EventType.SegOpen)) {\n    scanline.insert(v);\n\n    // Wire up the neighbours by querying the set.\n    const above = scanline.prev(v);\n    if (above) {\n      v.firstAbove = above;\n      above.firstBelow = v;\n    }\n    const below = scanline.next(v);\n    if (below) {\n      v.firstBelow = below;\n      below.firstAbove = v;\n    }\n  }\n\n  if (\n    (pass === 4 && (e.type === EventType.Open || e.type === EventType.SegOpen)) ||\n    (pass === 1 && (e.type === EventType.SegClose || e.type === EventType.Close))\n  ) {\n    if (v.ss !== null) {\n      // As far as we can see in both directions.\n      const minLimit = v.firstObstacleAbove(dim);\n      const maxLimit = v.firstObstacleBelow(dim);\n      v.ss.minSpaceLimit = Math.max(minLimit, v.ss.minSpaceLimit);\n      v.ss.maxSpaceLimit = Math.min(maxLimit, v.ss.maxSpaceLimit);\n    } else {\n      v.markShiftSegmentsAbove(dim);\n      v.markShiftSegmentsBelow(dim);\n    }\n  }\n\n  if (pass === 2 && (e.type === EventType.SegClose || e.type === EventType.Close)) {\n    // Unlink the doubly-linked neighbour pointers and remove from the set.\n    const l = v.firstAbove;\n    const r = v.firstBelow;\n    if (l !== null) l.firstBelow = v.firstBelow;\n    if (r !== null) r.firstAbove = v.firstAbove;\n\n    const removed = scanline.erase(v);\n    if (!removed) {\n      throw new Error('processShiftEvent: failed to erase Node from scanline');\n    }\n  }\n}\n\n// ─── buildOrthogonalChannelInfo ───────────────────────────────────────────────\n\n// @brief   Determines the spatial limits for each shift segment in the given\n//          dimension.  Mirrors the C++ `buildOrthogonalChannelInfo`.\n//\n// For each event scan line we run four passes:\n//   1) Close handlers (limits from current neighbours)\n//   2) Remove closing events from the scanline\n//   3) Add opening events to the scanline\n//   4) Open handlers (limits from new neighbours)\nexport function buildOrthogonalChannelInfo(router: Router, dim: number, segmentList: ShiftSegment[]): void {\n  if (segmentList.length === 0) return;\n\n  const altDim = 1 - dim;\n  const events: Event[] = [];\n\n  // `router.m_obstacles` only contains shape obstacles and the obstacles\n  // that fixed junctions own; free junctions deliberately stay out of the\n  // list (they're not routing barriers).  See `Junction.setPositionFixed`.\n  for (const obstacle of router.obstacles) {\n    const bb = obstacle.routingBox();\n    const minPt = bb.min;\n    const maxPt = bb.max;\n    const mid = minPt.at(dim) + (maxPt.at(dim) - minPt.at(dim)) / 2;\n    const node = Node.forObstacle(obstacle, mid);\n    events.push(new Event(EventType.Open, node, minPt.at(altDim)));\n    events.push(new Event(EventType.Close, node, maxPt.at(altDim)));\n  }\n\n  for (const ss of segmentList) {\n    const lowPt = ss.lowPoint();\n    const highPt = ss.highPoint();\n    // Sanity: segment is along `altDim` at fixed `dim`.\n    if (lowPt.at(dim) !== highPt.at(dim)) {\n      throw new Error('ShiftSegment endpoints disagree on `dim`');\n    }\n    if (lowPt.at(altDim) >= highPt.at(altDim)) {\n      throw new Error('ShiftSegment endpoints out of order in `altDim`');\n    }\n    const node = Node.forShiftSegment(ss, lowPt.at(dim));\n    events.push(new Event(EventType.SegOpen, node, lowPt.at(altDim)));\n    events.push(new Event(EventType.SegClose, node, highPt.at(altDim)));\n  }\n\n  events.sort(compareEvents);\n\n  // Sweep:\n  //   - Pass 1 is interleaved as we walk through events for the current line.\n  //   - Passes 2..4 are batched once we reach the next line position.\n  const scanline = new SortedArray<Node>(Node.compare);\n  const total = events.length;\n  let thisPos = total > 0 ? events[0].pos : 0;\n  let posStart = 0;\n  let i = 0;\n  for (; i <= total; i++) {\n    if (i === total || events[i].pos !== thisPos) {\n      const posFinish = i;\n      for (let pass = 2; pass <= 4; pass++) {\n        for (let j = posStart; j < posFinish; j++) {\n          processShiftEvent(scanline, events[j], dim, pass);\n        }\n      }\n      if (i === total) break;\n      thisPos = events[i].pos;\n      posStart = i;\n    }\n    processShiftEvent(scanline, events[i], dim, 1);\n  }\n\n  if (scanline.size() !== 0) {\n    throw new Error('buildOrthogonalChannelInfo: scanline non-empty after sweep');\n  }\n\n  limitChannelsByGroups(router, dim, segmentList);\n}\n\n// Annotation groups don't block the sweep above, so a segment's channel can\n// run straight across a group boundary — and nudging would then slide a\n// route that A* kept outside a group into it (or one inside out of it).\n// Clamp each segment's channel to the side of every group boundary it is\n// already on, keeping the group's buffer where there's room.  A segment never\n// gets a limit past its current position, so the channel stays valid even\n// when the route sits closer to the boundary than the buffer.\nfunction limitChannelsByGroups(router: Router, dim: number, segmentList: ShiftSegment[]): void {\n  if (router.groups.length === 0) return;\n  const altDim = 1 - dim;\n  for (const ss of segmentList) {\n    const pos = ss.lowPoint().at(dim);\n    const spanLo = ss.lowPoint().at(altDim);\n    const spanHi = ss.highPoint().at(altDim);\n    for (const group of router.groups) {\n      const b = group.bounds();\n      // Only boundaries the segment runs alongside constrain it.\n      if (!(spanLo < b.max.at(altDim) && spanHi > b.min.at(altDim))) continue;\n      const d = group.bufferDistance();\n      const lo = b.min.at(dim);\n      const hi = b.max.at(dim);\n      if (pos > lo && pos < hi) {\n        ss.minSpaceLimit = Math.max(ss.minSpaceLimit, Math.min(pos, lo + d));\n        ss.maxSpaceLimit = Math.min(ss.maxSpaceLimit, Math.max(pos, hi - d));\n      } else if (pos <= lo) {\n        ss.maxSpaceLimit = Math.min(ss.maxSpaceLimit, Math.max(pos, lo - d));\n      } else {\n        ss.minSpaceLimit = Math.max(ss.minSpaceLimit, Math.min(pos, hi + d));\n      }\n    }\n  }\n}\n\n// ─── Connector route checkpoint cache ─────────────────────────────────────────\n\n// @brief   For each orthogonal connector, mark every (segment, point) pair\n//          where a routing checkpoint lies on the route.  Each match is\n//          appended to displayRoute.checkpointsOnRoute as [segmentIndex, pt].\n//\n// The `segmentIndex` is `ind * 2` for a checkpoint that lands on a bendpoint\n// and `(ind * 2) - 1` for one that lies along a segment.\nexport function buildConnectorRouteCheckpointCache(router: Router): void {\n  for (const conn of router.connRefs) {\n    const displayRoute = conn.displayRoute();\n    const checkpoints = conn.routingCheckpoints();\n    displayRoute.checkpointsOnRoute = [];\n    for (let ind = 0; ind < displayRoute.size(); ind++) {\n      if (ind > 0) {\n        for (const cp of checkpoints) {\n          if (pointOnLine(displayRoute.ps[ind - 1], displayRoute.ps[ind], cp.point)) {\n            displayRoute.checkpointsOnRoute.push([ind * 2 - 1, cp.point]);\n          }\n        }\n      }\n      for (const cp of checkpoints) {\n        if (displayRoute.ps[ind].eq(cp.point)) {\n          displayRoute.checkpointsOnRoute.push([ind * 2, cp.point]);\n        }\n      }\n    }\n  }\n}\n\n// @brief   Clear the per-route checkpoint cache built by\n//          buildConnectorRouteCheckpointCache.\nexport function clearConnectorRouteCheckpointCache(router: Router): void {\n  for (const conn of router.connRefs) {\n    conn.displayRoute().checkpointsOnRoute = [];\n  }\n}\n","import {Point} from './geomtypes';\nimport {type ShiftSegment, CHANNEL_MAX} from './scanline';\nimport {HyperedgeTreeNode} from './hyperedgetree';\nimport {Junction} from './models/junction';\nimport {Router} from './router';\nimport {SortedArray} from './utilities/sorted-array';\n\n// ─── HyperedgeShiftSegment ───────────────────────────────────────────────────\n\n//! @brief   The ShiftSegment subclass used by hyperedge improvement.\n//!\n//! Unlike NudgingShiftSegment (orthogonal.ts), which operates over indexes\n//! into a connector's display route, HyperedgeShiftSegment operates over\n//! HyperedgeTreeNodes — mutating their `point` directly when adjustPosition()\n//! moves the segment.\n//!\n//! `nodes` is a `SortedArray<HyperedgeTreeNode>` ordered along the\n//! segment's own axis (`(dimension + 1) % 2`).  The segment can be shifted\n//! along `dimension`.\nexport class HyperedgeShiftSegment implements ShiftSegment {\n  // ShiftSegment interface fields.\n  dimension: number;\n  minSpaceLimit: number;\n  maxSpaceLimit: number;\n\n  /** @internal */ nodes: SortedArray<HyperedgeTreeNode>;\n  /** @internal */ isImmovable: boolean;\n  private _balanceCount: number;\n  private _balanceCountSet: boolean;\n  private _nextPosLower: number;\n  private _nextPosUpper: number;\n  private _atLimit: boolean;\n\n  constructor(n1: HyperedgeTreeNode, n2: HyperedgeTreeNode, dim: number, immovable: boolean) {\n    this.dimension = dim;\n    // The nodes set is ordered along the segment's own axis — the alt dim.\n    this.nodes = new SortedArray<HyperedgeTreeNode>(HyperedgeTreeNode.compareInDim((dim + 1) % 2));\n    this.isImmovable = immovable;\n    this._balanceCount = 0;\n    this._balanceCountSet = false;\n    this._nextPosLower = 0;\n    this._nextPosUpper = 0;\n    this._atLimit = false;\n\n    this.nodes.insert(n1);\n    this.nodes.insert(n2);\n    n1.shiftSegmentNodeSet = this.nodes;\n    n2.shiftSegmentNodeSet = this.nodes;\n\n    this.minSpaceLimit = -CHANNEL_MAX;\n    this.maxSpaceLimit = CHANNEL_MAX;\n  }\n\n  //! Disconnects this segment's nodes from `shiftSegmentNodeSet`.  C++ does\n  //! this in the destructor; we call it explicitly when discarding a segment.\n  /** @internal */\n  cleanup(): void {\n    for (const node of this.nodes.values()) {\n      if (node.shiftSegmentNodeSet === this.nodes) {\n        node.shiftSegmentNodeSet = null;\n      }\n    }\n  }\n\n  lowPoint(): Point {\n    // The constructor inserts n1 and n2, so `nodes` is never empty during\n    // the segment's lifetime — assert that here and let the caller fail\n    // loudly if the invariant is ever violated.\n    const first = this.nodes.first();\n    if (!first) throw new Error('HyperedgeShiftSegment.lowPoint on empty set');\n    return first.point;\n  }\n\n  highPoint(): Point {\n    const last = this.nodes.last();\n    if (!last) throw new Error('HyperedgeShiftSegment.highPoint on empty set');\n    return last.point;\n  }\n\n  //! Counts the number of incident segments diverging on each side.  Sets\n  //! the cached balance count: negative if more diverge to the lower side,\n  //! positive if more to the upper side, zero if balanced.\n  //!\n  //! Also remembers the closest \"interesting\" position on each side (the\n  //! position of the nearest diverging-on-that-side segment) so\n  //! adjustPosition() can snap to it.\n  setBalanceCount(): void {\n    const altDim = (this.dimension + 1) % 2;\n    this._nextPosLower = this.minSpaceLimit;\n    this._nextPosUpper = this.maxSpaceLimit;\n    this._balanceCount = 0;\n    if (this.isImmovable) {\n      this._balanceCountSet = true;\n      return;\n    }\n    for (const curr of this.nodes.values()) {\n      const currPoint = curr.point;\n      for (const currEdge of curr.edges) {\n        const node = currEdge.followFrom(curr);\n        const otherPoint = node.point;\n        if (currPoint.at(altDim) === otherPoint.at(altDim)) {\n          if (otherPoint.at(this.dimension) < currPoint.at(this.dimension)) {\n            this._nextPosLower = Math.max(this._nextPosLower, otherPoint.at(this.dimension));\n            this._balanceCount--;\n          } else if (otherPoint.at(this.dimension) > currPoint.at(this.dimension)) {\n            this._nextPosUpper = Math.min(this._nextPosUpper, otherPoint.at(this.dimension));\n            this._balanceCount++;\n          }\n        }\n      }\n    }\n    this._balanceCountSet = true;\n  }\n\n  balanceCount(): number {\n    if (!this._balanceCountSet) {\n      throw new Error('hyperedgeimprover: balanceCount read before setBalanceCount');\n    }\n    return this._balanceCount;\n  }\n\n  //! Move every node in this segment to the next interesting position on the\n  //! side where more siblings diverge.  Also pulls in any zero-length nodes\n  //! that collapsed into this segment as a result of the shift.\n  adjustPosition(): void {\n    if (!this._balanceCountSet) {\n      throw new Error('hyperedgeimprover: adjustPosition called before setBalanceCount');\n    }\n    if (this._balanceCount === 0) {\n      throw new Error('hyperedgeimprover: adjustPosition called with zero balance');\n    }\n\n    const newPos = this._balanceCount < 0 ? this._nextPosLower : this._nextPosUpper;\n    const limit = this._balanceCount < 0 ? this.minSpaceLimit : this.maxSpaceLimit;\n\n    if (this.lowPoint().at(this.dimension) === newPos) {\n      // We aren't actually moving — mark as at-limit.  Matches the C++\n      // behaviour where this is a workaround for incorrectly marked limits\n      // (e.g. a junction positioned inside a shape).\n      this._atLimit = true;\n    }\n\n    for (const curr of this.nodes.values()) {\n      const pt = curr.point;\n      // We don't have an in-place setter on Point in the geomtypes module —\n      // mutate the x/y fields directly.  The C++ version uses operator[] on\n      // Point too, which is also an in-place mutation.\n      if (this.dimension === 0) pt.x = newPos;\n      else pt.y = newPos;\n    }\n\n    if (newPos === limit) {\n      this._atLimit = true;\n    }\n\n    // Pull in any nodes from collapsed zero-length edges, in case they are\n    // not part of any segment that will later be merged.\n    // Snapshot the current node list first — we mutate `nodes` inside.\n    const snapshot = Array.from(this.nodes.values());\n    for (const curr of snapshot) {\n      const currPoint = curr.point;\n      for (const currEdge of curr.edges) {\n        const node = currEdge.followFrom(curr);\n        if (currPoint.eq(node.point)) {\n          this.nodes.insert(node);\n          node.shiftSegmentNodeSet = this.nodes;\n        }\n      }\n    }\n  }\n\n  //! Overlap check used by buildOrthogonalChannelInfo and merging.  Two\n  //! segments overlap iff their projection onto the alt-dim axis intersects\n  //! AND their channel-limit ranges intersect.\n  overlapsWith(rhs: ShiftSegment, dim: number): boolean {\n    const altDim = (dim + 1) % 2;\n    const lowPt = this.lowPoint();\n    const highPt = this.highPoint();\n    const rhsLowPt = rhs.lowPoint();\n    const rhsHighPt = rhs.highPoint();\n    if (lowPt.at(altDim) <= rhsHighPt.at(altDim) && rhsLowPt.at(altDim) <= highPt.at(altDim)) {\n      if (this.minSpaceLimit <= rhs.maxSpaceLimit && rhs.minSpaceLimit <= this.maxSpaceLimit) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  immovable(): boolean {\n    return this.isImmovable;\n  }\n\n  //! \"Settled\" segments don't get re-considered by the nudging loop.\n  settled(): boolean {\n    return this.isImmovable || this._atLimit || this.balanceCount() === 0;\n  }\n\n  //! If `other` is collinear with `this` and their alt-dim ranges overlap,\n  //! absorb `other`'s nodes into this segment and return true.  Resets the\n  //! balance count either way.\n  /** @internal */\n  mergesWith(other: HyperedgeShiftSegment): boolean {\n    const altDim = (this.dimension + 1) % 2;\n    const lowPt = this.lowPoint();\n    const highPt = this.highPoint();\n    const otherLowPt = other.lowPoint();\n    const otherHighPt = other.highPoint();\n    if (\n      lowPt.at(this.dimension) === otherLowPt.at(this.dimension) &&\n      lowPt.at(altDim) <= otherHighPt.at(altDim) &&\n      otherLowPt.at(altDim) <= highPt.at(altDim)\n    ) {\n      this.isImmovable = this.isImmovable || other.isImmovable;\n      // C++: m_at_limit |= m_at_limit; — a no-op, faithfully preserved as\n      // a no-op here.\n      this.minSpaceLimit = Math.max(this.minSpaceLimit, other.minSpaceLimit);\n      this.maxSpaceLimit = Math.min(this.maxSpaceLimit, other.maxSpaceLimit);\n      this.nodes.insertAll(other.nodes.values());\n      other.nodes.clear();\n      for (const curr of this.nodes.values()) {\n        curr.shiftSegmentNodeSet = this.nodes;\n      }\n      this.setBalanceCount();\n      return true;\n    }\n    this.setBalanceCount();\n    return false;\n  }\n}\n\n// ─── HyperedgeImprover ───────────────────────────────────────────────────────\n\n//! @brief   Per-run state for the hyperedge-improvement pipeline.\n//!\n//! Just a typed bag of mutable fields — `m_hyperedge_tree_junctions` /\n//! `m_hyperedge_tree_roots` / `m_root_shift_segments` /\n//! `m_all_shift_segments` — that the pipeline steps in\n//! `src/pipeline/improver-steps.ts` read and write.  No `execute()`; the\n//! caller (`HyperedgeImproverStep` in `route-steps.ts`) allocates the\n//! improver, wraps it in an `ImproverContext`, and runs `IMPROVER_PIPELINE`\n//! directly.\nexport class HyperedgeImprover {\n  router: Router;\n  m_hyperedge_tree_junctions: Map<Junction, HyperedgeTreeNode>;\n  m_hyperedge_tree_roots: Set<Junction>;\n  m_root_shift_segments: Map<Junction, HyperedgeShiftSegment[]>;\n  /** @internal */ m_all_shift_segments: HyperedgeShiftSegment[];\n\n  constructor(router: Router) {\n    this.router = router;\n    this.m_hyperedge_tree_junctions = new Map();\n    this.m_hyperedge_tree_roots = new Set();\n    this.m_root_shift_segments = new Map();\n    this.m_all_shift_segments = [];\n  }\n}\n","// ─── HyperedgeImprover pipeline steps ────────────────────────────────────────\n//\n// The four-stage hyperedge-improvement algorithm decomposed into named steps.\n// Each step owns the body of one phase of the improver; the recursion helpers\n// (tree walks, segment merging, etc.) live as module-private free functions\n// at the bottom of this file.\n//\n// The improver instance still holds the per-run state\n// (`m_hyperedge_tree_junctions`, `m_hyperedge_tree_roots`,\n// `m_root_shift_segments`, `m_all_shift_segments`) — steps reach into those\n// fields via `ctx.improver`.  The improver is essentially a typed bag of\n// mutable state once the pipeline takes over.\n\nimport {Step, Pipeline} from '../pipeline';\nimport {Point} from '../geomtypes';\nimport {type ShiftSegment, CHANNEL_MAX, buildOrthogonalChannelInfo} from '../scanline';\nimport {HyperedgeTreeNode, HyperedgeTreeEdge} from '../hyperedgetree';\nimport {pointOnLine} from '../geometry';\nimport {Junction} from '../models/junction';\nimport {Edge} from '../models/edge';\nimport {getOrInsertComputed} from '../utilities/map';\nimport {HyperedgeImprover, HyperedgeShiftSegment} from '../hyperedgeimprover';\n\nfunction createHyperedgeTreeNode(junction: Junction): HyperedgeTreeNode {\n  const node = new HyperedgeTreeNode();\n  node.junction = junction;\n  node.point = junction.position();\n  return node;\n}\n\nexport class ImproverContext {\n  // Set by `NudgePassesStep` before each invocation of the inner pipeline.\n  // The inner steps read it instead of being parameterised individually.\n  dimension = 0;\n\n  constructor(readonly improver: HyperedgeImprover) {}\n}\n\n// ─── Outer-pipeline steps ─────────────────────────────────────────────────────\n\n// Build a HyperedgeTreeNode/HyperedgeTreeEdge representation of every\n// hyperedge by walking `router.connRefs` and threading nodes through the\n// junctions each connector anchors against.\nclass BuildHyperedgeTreesStep extends Step<ImproverContext> {\n  readonly name = 'Build hyperedge trees';\n\n  execute(ctx: ImproverContext): void {\n    const improver = ctx.improver;\n    for (const connRef of improver.router.connRefs) {\n      let [jFront, jBack] = connRef.endpointAnchors();\n      if (!jFront && !jBack) {\n        continue;\n      }\n\n      let nodeFront = jFront\n        ? getOrInsertComputed(improver.m_hyperedge_tree_junctions, jFront, createHyperedgeTreeNode)\n        : new HyperedgeTreeNode();\n\n      let nodeBack = jBack\n        ? getOrInsertComputed(improver.m_hyperedge_tree_junctions, jBack, createHyperedgeTreeNode)\n        : new HyperedgeTreeNode();\n\n      const route = connRef.displayRoute();\n      let prev: HyperedgeTreeNode | null = null;\n      for (let i = 1; i < route.size(); i++) {\n        let node: HyperedgeTreeNode;\n        if (i + 1 === route.size()) {\n          node = nodeBack;\n        } else {\n          node = new HyperedgeTreeNode();\n        }\n        node.point = new Point(route.ps[i].x, route.ps[i].y);\n        if (i === 1) {\n          prev = nodeFront;\n          nodeFront.point = new Point(route.ps[0].x, route.ps[0].y);\n          nodeFront.isConnectorSource = true;\n        }\n        new HyperedgeTreeEdge(prev!, node, connRef);\n        prev = node;\n      }\n    }\n  }\n}\n\n// Walk every junction-bearing node and collect roots; then strip any\n// hyperedge whose root forms a cycle through other junctions.\nclass ComputeRootsAndStripCyclesStep extends Step<ImproverContext> {\n  readonly name = 'Compute roots & strip cyclic hyperedges';\n\n  execute(ctx: ImproverContext): void {\n    const improver = ctx.improver;\n    for (const [, node] of improver.m_hyperedge_tree_junctions) {\n      if (node.junction) {\n        improver.m_hyperedge_tree_roots.add(node.junction);\n      }\n    }\n\n    const cyclicRoots: Junction[] = [];\n    for (const junction of improver.m_hyperedge_tree_roots) {\n      const node = improver.m_hyperedge_tree_junctions.get(junction)!;\n      const containsCycle = node.removeOtherJunctionsFrom(null, improver.m_hyperedge_tree_roots);\n      if (containsCycle && node.junction) {\n        cyclicRoots.push(node.junction);\n      }\n    }\n    for (const junction of cyclicRoots) {\n      improver.m_hyperedge_tree_roots.delete(junction);\n    }\n  }\n}\n\n// For each hyperedge root, traverse and elide zero-length edges.  Used both\n// as an outer-pipeline cleanup step and inside the per-dimension inner\n// pipeline.\nclass RemoveZeroLengthEdgesStep extends Step<ImproverContext> {\n  readonly name = 'Remove zero-length edges';\n\n  execute(ctx: ImproverContext): void {\n    const improver = ctx.improver;\n    for (const junction of improver.m_hyperedge_tree_roots) {\n      const node = improver.m_hyperedge_tree_junctions.get(junction)!;\n      removeZeroLengthEdgesFromNode(node, null);\n    }\n  }\n}\n\n// For every junction in the tree, try shifting it along any shared sub-paths.\n// Repeats until each junction can no longer move.\nclass MoveJunctionsAlongCommonEdgesStep extends Step<ImproverContext> {\n  readonly name = 'Move junctions along common edges';\n\n  execute(ctx: ImproverContext): void {\n    const improver = ctx.improver;\n    // Snapshot keys; we may add to the map during iteration when major\n    // changes are allowed.\n    const keys = Array.from(improver.m_hyperedge_tree_junctions.keys());\n    let i = 0;\n    while (i < keys.length) {\n      const junction = keys[i];\n      let node = improver.m_hyperedge_tree_junctions.get(junction);\n      if (!node) {\n        // Junction was deleted by an earlier merge.\n        i++;\n        continue;\n      }\n\n      let nodeMapHasChanged = false;\n      let moved: HyperedgeTreeNode | null = node;\n      while (moved !== null) {\n        const result = moveJunctionAlongCommonEdge(node!);\n        moved = result.newNode;\n        if (result.nodeMapHasChanged) nodeMapHasChanged = true;\n        if (moved !== null) {\n          improver.m_hyperedge_tree_junctions.set(junction, moved);\n          node = moved;\n        }\n      }\n\n      if (nodeMapHasChanged) {\n        // Restart iteration: a new junction was added that may be earlier\n        // in the (re-sampled) map order.\n        i = 0;\n        // Re-snapshot keys to pick up new junctions.\n        const fresh = Array.from(improver.m_hyperedge_tree_junctions.keys());\n        keys.length = 0;\n        for (const k of fresh) keys.push(k);\n      } else {\n        i++;\n      }\n    }\n  }\n}\n\n// Commit each touched junction's improved position back to the model.\n// `_setPosition` drags the centre vertex with it; the router rebuilds the\n// visgraph afterwards (see HyperedgeImproverStep in route-steps.ts).\nclass CommitJunctionPositionsStep extends Step<ImproverContext> {\n  readonly name = 'Commit junction positions';\n\n  execute(ctx: ImproverContext): void {\n    for (const [junction, node] of ctx.improver.m_hyperedge_tree_junctions) {\n      junction._setPosition(node.point);\n    }\n  }\n}\n\n// Push the improved tree back into each connector's route in two passes\n// (pass 0 clears, pass 1 writes).\nclass WriteHyperedgeRoutesBackStep extends Step<ImproverContext> {\n  readonly name = 'Write hyperedge routes back to connectors';\n\n  execute(ctx: ImproverContext): void {\n    const improver = ctx.improver;\n    const setRouteOps = {\n      clearDisplayRoute: (conn: Edge) => {\n        // Empty the route so `routeIsEmpty()` reports true and the writer\n        // starts a fresh polyline (pushing `prev` then each `next`) rather\n        // than appending to the pre-improver A* route.\n        conn.freeRoutes();\n      },\n      pushPoint: (conn: Edge, point: Point) => {\n        conn.displayRoute().ps.push(new Point(point.x, point.y));\n      },\n      routeIsEmpty: (conn: Edge): boolean => {\n        return conn.displayRoute().size() === 0;\n      },\n      destinationJunction: (edge: Edge): Junction | null => {\n        let destination = edge.destination;\n        return destination instanceof Junction ? destination : null;\n      },\n    };\n\n    for (let pass = 0; pass < 2; pass++) {\n      for (const junction of improver.m_hyperedge_tree_roots) {\n        const node = improver.m_hyperedge_tree_junctions.get(junction);\n        if (!node) continue;\n        node.writeEdgesToConns(null, pass, setRouteOps);\n      }\n    }\n  }\n}\n\n// ─── Inner per-dimension pipeline steps ──────────────────────────────────────\n\n// Build `HyperedgeShiftSegment`s for one dimension by traversing every\n// hyperedge tree and merging collinear segments as we go.\nclass BuildHyperedgeSegmentsStep extends Step<ImproverContext> {\n  readonly name = 'Build hyperedge shift segments';\n\n  execute(ctx: ImproverContext): void {\n    const improver = ctx.improver;\n    const dim = ctx.dimension;\n    for (const junction of improver.m_hyperedge_tree_roots) {\n      const segments: HyperedgeShiftSegment[] = [];\n      improver.m_root_shift_segments.set(junction, segments);\n\n      const node = improver.m_hyperedge_tree_junctions.get(junction)!;\n      createShiftSegmentsForDimensionExcludingFromNode(node, dim, null, segments);\n\n      mergeOverlappingSegments(segments);\n\n      for (const s of segments) improver.m_all_shift_segments.push(s);\n    }\n  }\n}\n\n// Compute channel limits for the per-dimension shift segments.  Delegates to\n// scanline.ts.\nclass BuildOrthogonalChannelInfoStep extends Step<ImproverContext> {\n  readonly name = 'Build orthogonal channel info';\n\n  execute(ctx: ImproverContext): void {\n    buildOrthogonalChannelInfo(ctx.improver.router, ctx.dimension, ctx.improver.m_all_shift_segments);\n  }\n}\n\n// Run VPSC-free nudging on this dimension's shift segments.  The algorithm\n// is greedy: walk segments, snap unsettled ones to their next ideal position,\n// merge overlapping ones, and repeat until every segment is settled.\nclass NudgeHyperedgeSegmentsStep extends Step<ImproverContext> {\n  readonly name = 'Nudge hyperedge segments';\n\n  execute(ctx: ImproverContext): void {\n    const improver = ctx.improver;\n    for (const junction of improver.m_hyperedge_tree_roots) {\n      const segmentList = improver.m_root_shift_segments.get(junction);\n      if (!segmentList) continue;\n\n      // Compute initial balance for every segment.\n      for (const segment of segmentList) {\n        segment.setBalanceCount();\n      }\n\n      let change = false;\n      let i = 0;\n      while (i < segmentList.length) {\n        const segment = segmentList[i];\n        if (!segment.settled()) {\n          segment.adjustPosition();\n          mergeOverlappingSegments(segmentList);\n          change = true;\n        }\n        if (change) {\n          change = false;\n          i = 0;\n        } else {\n          i++;\n        }\n      }\n    }\n  }\n}\n\n// Lift junction-bearing segments off the shape of a terminal they hug.\n//\n// MTST is free to put a junction on the first vertex out of a terminal —\n// the shape-buffer line in front of it — leaving a stub only\n// `shapeBufferDistance` long and the rest of the tree running parallel to\n// that shape's side, so the branch never visibly leaves the shape.  Junction\n// segments are immovable to `NudgeHyperedgeSegmentsStep` (see\n// `HyperedgeTreeNode.isImmovable`), so move them here instead: away from the\n// stub, to the middle of the space between the terminal's buffer line and the\n// next thing on the other side (channel limit or diverging branch).\n//\n// Deliberately narrow: the stub must hang off the junction itself, the\n// segment must be pinned only by free junctions (not a terminal or a fixed\n// junction), and at least as many branches must leave on the far side as on\n// the stub side — so the lift never makes the tree longer.\nclass LiftJunctionStubsStep extends Step<ImproverContext> {\n  readonly name = 'Lift junction stubs off terminal shapes';\n\n  execute(ctx: ImproverContext): void {\n    const buffer = ctx.improver.router.params.shapeBufferDistance;\n    if (buffer <= 0) return;\n    for (const segment of ctx.improver.m_all_shift_segments) {\n      liftJunctionStub(segment, ctx.dimension, buffer);\n    }\n  }\n}\n\nfunction liftJunctionStub(segment: HyperedgeShiftSegment, dim: number, buffer: number): void {\n  const altDim = (dim + 1) % 2;\n  const nodes = segment.nodes.values();\n  if (!nodes.some(n => n.junction !== null)) return;\n  if (nodes.some(n => n.edges.length === 1 || (n.junction !== null && n.junction.positionFixed))) return;\n\n  const pos = segment.lowPoint().at(dim);\n  let stubSide = 0;\n  // Branches leaving the segment on each side, and the nearest one's\n  // position (starting from the channel limits).\n  let lowerCount = 0;\n  let upperCount = 0;\n  let nearestLower = segment.minSpaceLimit;\n  let nearestUpper = segment.maxSpaceLimit;\n  for (const node of nodes) {\n    for (const edge of node.edges) {\n      const other = edge.followFrom(node);\n      if (other.point.at(altDim) !== node.point.at(altDim)) continue;\n      const delta = other.point.at(dim) - pos;\n      if (delta === 0) continue;\n      if (delta < 0) lowerCount++;\n      else upperCount++;\n      if (node.junction !== null && other.edges.length === 1 && Math.abs(delta) <= buffer) {\n        const side = Math.sign(delta);\n        if (stubSide !== 0 && stubSide !== side) return; // Stubs both ways.\n        stubSide = side;\n      } else if (delta < 0) {\n        nearestLower = Math.max(nearestLower, other.point.at(dim));\n      } else {\n        nearestUpper = Math.min(nearestUpper, other.point.at(dim));\n      }\n    }\n  }\n  if (stubSide === 0) return;\n  const [awayCount, stubSideCount] = stubSide > 0 ? [lowerCount, upperCount] : [upperCount, lowerCount];\n  if (awayCount < stubSideCount) return;\n\n  // Move into the open space on the side away from the stub.\n  const bound = stubSide > 0 ? nearestLower : nearestUpper;\n  if (Math.abs(bound) >= CHANNEL_MAX) return;\n  const target = (bound + pos) / 2;\n  if (target === pos) return;\n  for (const node of nodes) {\n    if (dim === 0) node.point.x = target;\n    else node.point.y = target;\n  }\n}\n\n// Tear down the per-pass shift-segment state — called at the end of each\n// nudging pass before the next one rebuilds.\nclass CleanupShiftSegmentsStep extends Step<ImproverContext> {\n  readonly name = 'Cleanup shift segments';\n\n  execute(ctx: ImproverContext): void {\n    const improver = ctx.improver;\n    for (const junction of improver.m_hyperedge_tree_roots) {\n      const segs = improver.m_root_shift_segments.get(junction);\n      if (segs) {\n        for (const segment of segs) {\n          segment.cleanup();\n        }\n      }\n    }\n    improver.m_root_shift_segments = new Map();\n    improver.m_all_shift_segments = [];\n  }\n}\n\n// Inner pipeline run once per pass (alternating X and Y).  The `dimension`\n// field on the shared context is set by the wrapping `NudgePassesStep` before\n// each invocation.\nconst PER_DIMENSION_PIPELINE = new Pipeline<ImproverContext>([\n  new BuildHyperedgeSegmentsStep(),\n  new BuildOrthogonalChannelInfoStep(),\n  new NudgeHyperedgeSegmentsStep(),\n  new LiftJunctionStubsStep(),\n  new RemoveZeroLengthEdgesStep(),\n  new MoveJunctionsAlongCommonEdgesStep(),\n  new CleanupShiftSegmentsStep(),\n]);\n\nclass NudgePassesStep extends Step<ImproverContext> {\n  readonly name = 'Nudge segments (4 passes, alternating X/Y)';\n\n  execute(ctx: ImproverContext): void {\n    // Four nudging passes — alternating X (dim=0) and Y (dim=1).  The inner\n    // pipeline reads `ctx.dimension`.\n    for (let count = 0; count < 4; count++) {\n      ctx.dimension = count % 2;\n      PER_DIMENSION_PIPELINE.run(ctx);\n    }\n  }\n}\n\n// ─── Outer pipeline ──────────────────────────────────────────────────────────\n\nexport const IMPROVER_PIPELINE = new Pipeline<ImproverContext>([\n  new BuildHyperedgeTreesStep(),\n  new ComputeRootsAndStripCyclesStep(),\n  new RemoveZeroLengthEdgesStep(),\n  new MoveJunctionsAlongCommonEdgesStep(),\n  new NudgePassesStep(),\n  new CommitJunctionPositionsStep(),\n  new WriteHyperedgeRoutesBackStep(),\n]);\n\n// ─── Module-private recursion helpers ─────────────────────────────────────────\n//\n// These are stateless walks over `HyperedgeTreeNode` / `HyperedgeTreeEdge`.\n// They don't need access to improver state — every relevant pointer is\n// reachable from the input node.\n\n// Traverse downwards from a node, deleting zero-length edges\n//   - If one end carries a junction and the other doesn't, the junction end\n//     is the merge target.\n//   - If both ends carry no junction, either end is fine.\n//   - If both ends carry a junction, we leave them\nfunction removeZeroLengthEdgesFromNode(self: HyperedgeTreeNode, ignored: HyperedgeTreeEdge | null): void {\n  // Snapshot the edge list — we may splice while iterating.\n  const edgeSnapshot = self.edges.slice();\n  for (const edge of edgeSnapshot) {\n    if (edge === ignored) continue;\n    // Edge may have already been removed by an earlier iteration; skip.\n    if (!self.edges.includes(edge)) continue;\n\n    if (edge.zeroLength()) {\n      const other = edge.followFrom(self);\n      let target: HyperedgeTreeNode | null = null;\n      let source: HyperedgeTreeNode | null = null;\n      if (other.junction && !self.junction) {\n        target = other;\n        source = self;\n      } else if (!other.junction && self.junction) {\n        target = self;\n        source = other;\n      } else if (!other.junction && !self.junction) {\n        target = self;\n        source = other;\n      }\n\n      if (target && source) {\n        edge.disconnectEdge();\n        target.spliceEdgesFrom(source);\n        // Restart from the merged target.\n        removeZeroLengthEdgesFromNode(target, ignored);\n        return;\n      }\n    }\n\n    // Recurse through the surviving edge.\n    removeZeroLengthEdgesFromEdge(edge, self);\n  }\n}\n\n// Traverse from an edge through to its other endpoint.\nfunction removeZeroLengthEdgesFromEdge(self: HyperedgeTreeEdge, ignored: HyperedgeTreeNode | null): void {\n  if (self.ends[0] && self.ends[0] !== ignored) {\n    removeZeroLengthEdgesFromNode(self.ends[0], self);\n  }\n  if (self.ends[1] && self.ends[1] !== ignored) {\n    removeZeroLengthEdgesFromNode(self.ends[1], self);\n  }\n}\n\n// Try to shift the junction at `self` along any sub-paths shared with another\n// connector at the same junction.  Returns `{ newNode, nodeMapHasChanged }`\n// describing the result — `newNode` is the node the junction now lives on\n// (or null when no move was possible).\nfunction moveJunctionAlongCommonEdge(self: HyperedgeTreeNode): {\n  newNode: HyperedgeTreeNode | null;\n  nodeMapHasChanged: boolean;\n} {\n  if (!self.junction) {\n    throw new Error('hyperedgeimprover: moveJunctionAlongCommonEdge on non-junction node');\n  }\n\n  let newSelf: HyperedgeTreeNode | null = null;\n  let nodeMapHasChanged = false;\n\n  // Snapshot — splitFromNodeAtPoint mutates edge lists.\n  const edgesSnapshot = self.edges.slice();\n  for (const currEdge of edgesSnapshot) {\n    // The edge may have been removed by a previous loop iteration.\n    if (!self.edges.includes(currEdge)) continue;\n    const currNode = currEdge.followFrom(self);\n    const commonEdges: HyperedgeTreeEdge[] = [];\n    const otherEdges: HyperedgeTreeEdge[] = [];\n\n    if (currNode.junction) {\n      continue; // Don't shift onto other junctions.\n    }\n\n    commonEdges.push(currEdge);\n\n    for (const otherEdge of self.edges) {\n      if (otherEdge === currEdge) {\n        continue;\n      }\n\n      const otherNode = otherEdge.followFrom(self);\n      if (otherNode.point.eq(currNode.point)) {\n        // Common edge at same point — but not a common junction.\n        if (otherNode.junction) {\n          otherEdges.push(otherEdge);\n        } else {\n          commonEdges.push(otherEdge);\n        }\n      } else if (pointOnLine(self.point, otherNode.point, currNode.point)) {\n        // Collinear: split the longer edge at currNode's point.\n        otherEdge.splitFromNodeAtPoint(self, currNode.point);\n        commonEdges.push(otherEdge);\n      } else {\n        otherEdges.push(otherEdge);\n      }\n    }\n\n    // A position-fixed junction stays put unless we're allowed major changes.\n    const selfFixed = self.junction.positionFixed;\n\n    if (commonEdges.length > 1 && otherEdges.length <= 1 && !selfFixed) {\n      // Move junction onto the target node (commonEdges[0]'s far end);\n      // splice the other common-edge nodes onto it; delete the rest.\n      const targetNode = commonEdges[0].followFrom(self);\n      for (let k = 1; k < commonEdges.length; k++) {\n        const thisNode = commonEdges[k].followFrom(self);\n        commonEdges[k].disconnectEdge();\n        targetNode.spliceEdgesFrom(thisNode);\n      }\n      targetNode.junction = self.junction;\n      self.junction = null;\n\n      if (otherEdges.length === 0) {\n        // Nothing else attached — remove `self` and the connecting edge.\n        commonEdges[0].disconnectEdge();\n      } else {\n        // The first common edge inherits the connector of the surviving\n        // other edge (so writeEdgesToConns can label it correctly).\n        commonEdges[0].conn = otherEdges[0].conn;\n      }\n      newSelf = targetNode;\n      break;\n    }\n  }\n\n  return {newNode: newSelf, nodeMapHasChanged};\n}\n\n// Helper for `BuildHyperedgeSegmentsStep`: traverse from a tree node, ignoring\n// one specific edge (used by the recursion to avoid backtracking).\nfunction createShiftSegmentsForDimensionExcludingFromNode(\n  node: HyperedgeTreeNode,\n  dim: number,\n  ignore: HyperedgeTreeEdge | null,\n  segments: ShiftSegment[],\n): void {\n  for (const edge of node.edges) {\n    if (edge !== ignore) {\n      createShiftSegmentsForDimensionExcludingFromEdge(edge, dim, node, segments);\n    }\n  }\n}\n\n// Helper for `BuildHyperedgeSegmentsStep`: traverse from a tree edge, ignoring\n// one specific endpoint node.\nfunction createShiftSegmentsForDimensionExcludingFromEdge(\n  edge: HyperedgeTreeEdge,\n  dim: number,\n  ignore: HyperedgeTreeNode | null,\n  segments: ShiftSegment[],\n): void {\n  if (edge.hasOrientation(dim) && !edge.zeroLength()) {\n    const e0 = edge.ends[0]!;\n    const e1 = edge.ends[1]!;\n    const immovable = e0.isImmovable() || e1.isImmovable();\n    const newSegment = new HyperedgeShiftSegment(e0, e1, dim, immovable);\n    segments.push(newSegment);\n  }\n\n  if (edge.ends[0] && edge.ends[0] !== ignore) {\n    createShiftSegmentsForDimensionExcludingFromNode(edge.ends[0], dim, edge, segments);\n  }\n  if (edge.ends[1] && edge.ends[1] !== ignore) {\n    createShiftSegmentsForDimensionExcludingFromNode(edge.ends[1], dim, edge, segments);\n  }\n}\n\n// Try to merge each segment in `segments` with every other; merged segments\n// are removed.  Mirrors the C++ O(n^2) walk — fine because the per-hyperedge\n// segment count is small.\nfunction mergeOverlappingSegments(segments: HyperedgeShiftSegment[]): void {\n  for (let i = 0; i < segments.length; i++) {\n    const edge1 = segments[i];\n    let j = 0;\n    while (j < segments.length) {\n      if (j === i) {\n        j++;\n        continue;\n      }\n      const edge2 = segments[j];\n      if (edge1.mergesWith(edge2)) {\n        // Detach the absorbed segment from its (now-empty) node set, then\n        // splice it out.  Adjust `i` so the outer-loop index stays valid.\n        edge2.cleanup();\n        segments.splice(j, 1);\n        if (j < i) i--;\n      } else {\n        j++;\n      }\n    }\n  }\n}\n","import {BinaryHeap} from './utilities/heap';\n\nconst ZERO_UPPERBOUND = -1e-10;\nconst LAGRANGIAN_TOLERANCE = -1e-4;\n\n// ─── Errors ──────────────────────────────────────────────────────────────────\n\n// Thrown when satisfy() cannot resolve the constraint set (e.g. an equality\n// cycle).  `path` is the active path of constraints that caused the failure.\nexport class UnsatisfiableError extends Error {\n  path: Constraint[];\n\n  constructor(path: Constraint[] = []) {\n    super('VPSC: unsatisfiable constraint system');\n    this.name = 'UnsatisfiableError';\n    this.path = path;\n  }\n}\n\n// ─── PositionStats ───────────────────────────────────────────────────────────\n\n// Sufficient statistics for the unconstrained optimum of a block.  When a\n// variable v with scale s_v, offset o_v, weight w_v, desired d_v is added,\n// the block's optimal position posn satisfies posn = (AD - AB) / A2 where\n// a_i = scale/s_v, b_i = o_v/s_v.\nclass PositionStats {\n  scale = 0;\n  AB = 0;\n  AD = 0;\n  A2 = 0;\n\n  addVariable(v: Variable): void {\n    const ai = this.scale / v.scale;\n    const bi = v.offset / v.scale;\n    const wi = v.weight;\n    this.AB += wi * ai * bi;\n    this.AD += wi * ai * v.desiredPosition;\n    this.A2 += wi * ai * ai;\n  }\n}\n\n// ─── Variable ────────────────────────────────────────────────────────────────\n\n// A variable to be positioned, with a desired position and a weight that\n// controls how strongly it resists being moved away from that position.\nexport class Variable {\n  id: number;\n  desiredPosition: number;\n  finalPosition = 0;\n  weight: number;\n  scale: number;\n  offset = 0;\n  /** @internal */ block: Block | null = null;\n  /** @internal */ visited = false;\n  fixedDesiredPosition = false;\n  /** @internal */ in: Constraint[] = [];\n  /** @internal */ out: Constraint[] = [];\n\n  constructor(id: number, desiredPos = -1.0, weight = 1.0, scale = 1.0) {\n    this.id = id;\n    this.desiredPosition = desiredPos;\n    this.weight = weight;\n    this.scale = scale;\n  }\n\n  // Derivative of the local cost wrt this variable's position.\n  dfdv(): number {\n    return 2 * this.weight * (this.position() - this.desiredPosition);\n  }\n\n  /** @internal */\n  position(): number {\n    const b = this.block!;\n    return (b.ps.scale * b.posn + this.offset) / this.scale;\n  }\n\n  /** @internal */\n  unscaledPosition(): number {\n    const b = this.block!;\n    if (b.ps.scale !== 1) throw new Error('VPSC: unscaledPosition requires block scale == 1');\n    if (this.scale !== 1) throw new Error('VPSC: unscaledPosition requires variable scale == 1');\n    return b.posn + this.offset;\n  }\n}\n\n// ─── Constraint ──────────────────────────────────────────────────────────────\n\n// A separation (or equality) constraint between two Variables of the form\n// `right.position - left.position >= gap` (or `==` when equality is true).\nexport class Constraint {\n  left: Variable;\n  right: Variable;\n  gap: number;\n  lm = 0;\n  /** @internal */ timeStamp = 0;\n  /** @internal */ active = false;\n  readonly equality: boolean;\n  unsatisfiable = false;\n  needsScaling = true;\n\n  constructor(left: Variable, right: Variable, gap: number, equality = false) {\n    this.left = left;\n    this.right = right;\n    this.gap = gap;\n    this.equality = equality;\n  }\n\n  // How much slack the constraint has, i.e. `right - left - gap`.  Negative\n  // values mean the constraint is violated.  Returns Number.MAX_VALUE when\n  // the constraint has been flagged unsatisfiable.\n  slack(): number {\n    if (this.unsatisfiable) {\n      return Number.MAX_VALUE;\n    }\n    if (this.needsScaling) {\n      return this.right.scale * this.right.position() - this.gap - this.left.scale * this.left.position();\n    }\n    if (this.left.scale !== 1 || this.right.scale !== 1) {\n      throw new Error('VPSC: unscaled slack requires scale == 1');\n    }\n    return this.right.unscaledPosition() - this.gap - this.left.unscaledPosition();\n  }\n\n  toString(): string {\n    const sign = this.gap < 0 ? `- ${-this.gap}` : `+ ${this.gap}`;\n    const rel = this.equality ? '==' : '<=';\n    return `Constraint: var(${this.left.id}) ${sign} ${rel} var(${this.right.id})`;\n  }\n\n  static compare(l: Constraint, r: Constraint): boolean {\n    const sl = l.left.block!.timeStamp > l.timeStamp || l.left.block === l.right.block ? -Number.MAX_VALUE : l.slack();\n    const sr = r.left.block!.timeStamp > r.timeStamp || r.left.block === r.right.block ? -Number.MAX_VALUE : r.slack();\n    if (sl === sr) {\n      // Deterministic tiebreak by variable ids.\n      if (l.left.id === r.left.id) {\n        return l.right.id < r.right.id;\n      }\n      return l.left.id < r.left.id;\n    }\n    return sl > sr;\n  }\n}\n\n// ─── Block ────────────────────────────────────────────────────────────────────\n\n// A connected component of variables linked by active constraints.  Inside a\n// block all variables move together; the block's `posn` is the optimum of\n// the unconstrained sub-problem for those variables.\nclass Block {\n  vars: Variable[] = [];\n  posn = 0;\n  ps = new PositionStats();\n  deleted = false;\n  timeStamp = 0;\n  in: BinaryHeap<Constraint> | null = null;\n  out: BinaryHeap<Constraint> | null = null;\n  blocks: Blocks;\n\n  constructor(blocks: Blocks, v: Variable | null = null) {\n    this.blocks = blocks;\n    if (v !== null) {\n      v.offset = 0;\n      this.addVariable(v);\n    }\n  }\n\n  /** @internal */\n  addVariable(v: Variable): void {\n    v.block = this;\n    this.vars.push(v);\n    if (this.ps.A2 === 0) this.ps.scale = v.scale;\n    this.ps.addVariable(v);\n    this.posn = (this.ps.AD - this.ps.AB) / this.ps.A2;\n    if (Number.isNaN(this.posn)) {\n      throw new Error('VPSC: Block.posn became NaN');\n    }\n  }\n\n  // Recompute posn from the current variable offsets (called after a merge\n  // or moveBlocks pass).\n  updateWeightedPosition(): void {\n    this.ps.AB = 0;\n    this.ps.AD = 0;\n    this.ps.A2 = 0;\n    for (const v of this.vars) this.ps.addVariable(v);\n    this.posn = (this.ps.AD - this.ps.AB) / this.ps.A2;\n    if (Number.isNaN(this.posn)) {\n      throw new Error('VPSC: Block.posn became NaN');\n    }\n  }\n\n  setUpInConstraints(): void {\n    this.in = this.setUpConstraintHeap(true);\n  }\n\n  setUpOutConstraints(): void {\n    this.out = this.setUpConstraintHeap(false);\n  }\n\n  private setUpConstraintHeap(isIn: boolean): BinaryHeap<Constraint> {\n    const constraintHeap = new BinaryHeap<Constraint>(Constraint.compare);\n    for (const v of this.vars) {\n      const cs = isIn ? v.in : v.out;\n      for (const c of cs) {\n        c.timeStamp = this.blocks.blockTimeCtr;\n        if ((c.left.block !== this && isIn) || (c.right.block !== this && !isIn)) {\n          constraintHeap.push(c);\n        }\n      }\n    }\n    return constraintHeap;\n  }\n\n  // Merge two blocks across constraint c (selecting which side is `this`\n  // and which is the merged-in block by size, to keep the operation\n  // amortised cheap).\n  mergeWith(b: Block, c: Constraint): Block {\n    const dist = c.right.offset - c.left.offset - c.gap;\n    const l = c.left.block!;\n    const r = c.right.block!;\n    if (l.vars.length < r.vars.length) {\n      r.mergeInto(l, c, dist);\n    } else {\n      l.mergeInto(r, c, -dist);\n    }\n    return b.deleted ? this : b;\n  }\n\n  // Merge b into this block across c.  All variables of b are shifted by\n  // `dist` so that c is satisfied as an equality.\n  /** @internal */\n  mergeInto(b: Block, c: Constraint, dist: number): void {\n    c.active = true;\n    for (const v of b.vars) {\n      v.offset += dist;\n      this.addVariable(v);\n    }\n    this.posn = (this.ps.AD - this.ps.AB) / this.ps.A2;\n    if (Number.isNaN(this.posn)) throw new Error('VPSC: Block.posn became NaN');\n    b.deleted = true;\n  }\n\n  // Move the contents of b's in-heap into this block's in-heap.\n  mergeIn(b: Block): void {\n    this.findMinInConstraint();\n    b.findMinInConstraint();\n    while (b.in!.length !== 0) {\n      this.in!.push(b.in!.pop());\n    }\n  }\n\n  mergeOut(b: Block): void {\n    this.findMinOutConstraint();\n    b.findMinOutConstraint();\n    while (b.out!.length !== 0) {\n      this.out!.push(b.out!.pop());\n    }\n  }\n\n  findMinInConstraint(): Constraint | null {\n    let v: Constraint | null = null;\n    const outOfDate: Constraint[] = [];\n    const heap = this.in!;\n    while (heap.length !== 0) {\n      v = heap.front()!;\n      const lb = v.left.block!;\n      const rb = v.right.block!;\n      if (lb === rb) {\n        heap.pop();\n      } else if (v.timeStamp < lb.timeStamp) {\n        heap.pop();\n        outOfDate.push(v);\n      } else {\n        break;\n      }\n    }\n    for (const c of outOfDate) {\n      c.timeStamp = this.blocks.blockTimeCtr;\n      heap.push(c);\n    }\n    if (heap.length === 0) {\n      return null;\n    }\n    return heap.front() || null;\n  }\n\n  findMinOutConstraint(): Constraint | null {\n    const heap = this.out!;\n    let v = heap.front()!;\n    if (!v) {\n      return null;\n    }\n    while (v.left.block === v.right.block) {\n      heap.pop();\n      if (heap.length === 0) {\n        return null;\n      }\n      v = heap.front()!;\n    }\n    return v;\n  }\n\n  deleteMinInConstraint(): void {\n    this.in!.pop();\n  }\n\n  deleteMinOutConstraint(): void {\n    this.out!.pop();\n  }\n\n  private canFollowLeft(c: Constraint, last: Variable | null): boolean {\n    return c.left.block === this && c.active && last !== c.left;\n  }\n\n  private canFollowRight(c: Constraint, last: Variable | null): boolean {\n    return c.right.block === this && c.active && last !== c.right;\n  }\n\n  // Computes df/dv at v in the active-constraint tree, treating constraint\n  // lm values as the recursive sums.  Does not back-track over u.  When\n  // `minLm` is supplied, the constraint with the smallest lm so far is\n  // tracked through the holder.\n  private compute_dfdv(v: Variable, u: Variable | null, minLm: {c: Constraint | null} | null): number {\n    let dfdv = v.dfdv();\n    for (const c of v.out) {\n      if (this.canFollowRight(c, u)) {\n        c.lm = this.compute_dfdv(c.right, v, minLm);\n        dfdv += c.lm * c.left.scale;\n        if (minLm && !c.equality && (minLm.c === null || c.lm < minLm.c.lm)) {\n          minLm.c = c;\n        }\n      }\n    }\n    for (const c of v.in) {\n      if (this.canFollowLeft(c, u)) {\n        c.lm = -this.compute_dfdv(c.left, v, minLm);\n        dfdv -= c.lm * c.right.scale;\n        if (minLm && !c.equality && (minLm.c === null || c.lm < minLm.c.lm)) {\n          minLm.c = c;\n        }\n      }\n    }\n    return dfdv / v.scale;\n  }\n\n  // Search the active-constraint tree from v outward (not back-tracking\n  // over u) for the lm-minimum constraint that lies on the path to r.  Only\n  // left-to-right traversals contribute candidates, to avoid creating new\n  // violations.  `desperation` mirrors a (currently unused) C++ flag.\n  private split_path(\n    r: Variable,\n    v: Variable,\n    u: Variable | null,\n    minLm: {c: Constraint | null},\n    desperation = false,\n  ): boolean {\n    for (const c of v.in) {\n      if (this.canFollowLeft(c, u)) {\n        if (c.left === r) {\n          if (desperation && !c.equality) minLm.c = c;\n          return true;\n        } else {\n          if (this.split_path(r, c.left, v, minLm)) {\n            if (desperation && !c.equality && (!minLm.c || c.lm < minLm.c.lm)) {\n              minLm.c = c;\n            }\n            return true;\n          }\n        }\n      }\n    }\n    for (const c of v.out) {\n      if (this.canFollowRight(c, u)) {\n        if (c.right === r) {\n          if (!c.equality) minLm.c = c;\n          return true;\n        } else {\n          if (this.split_path(r, c.right, v, minLm)) {\n            if (!c.equality && (!minLm.c || c.lm < minLm.c.lm)) {\n              minLm.c = c;\n            }\n            return true;\n          }\n        }\n      }\n    }\n    return false;\n  }\n\n  // Zero the lm value on every active constraint reachable from v (without\n  // back-tracking over u).\n  private reset_active_lm(v: Variable, u: Variable | null): void {\n    for (const c of v.out) {\n      if (this.canFollowRight(c, u)) {\n        c.lm = 0;\n        this.reset_active_lm(c.right, v);\n      }\n    }\n    for (const c of v.in) {\n      if (this.canFollowLeft(c, u)) {\n        c.lm = 0;\n        this.reset_active_lm(c.left, v);\n      }\n    }\n  }\n\n  // Find the constraint with the smallest Lagrange multiplier — the one\n  // most \"wanting\" to split.\n  findMinLM(): Constraint | null {\n    const holder: {c: Constraint | null} = {c: null};\n    this.reset_active_lm(this.vars[0], null);\n    this.compute_dfdv(this.vars[0], null, holder);\n    return holder.c;\n  }\n\n  // Like findMinLM but restricted to the active path between two specific\n  // variables.  Throws UnsatisfiableError when no such path exists.\n  findMinLMBetween(lv: Variable, rv: Variable): Constraint {\n    this.reset_active_lm(this.vars[0], null);\n    this.compute_dfdv(this.vars[0], null, null);\n    const holder: {c: Constraint | null} = {c: null};\n    this.split_path(rv, lv, null, holder);\n    if (holder.c === null) {\n      const path: Constraint[] = [];\n      this.getActivePathBetween(path, lv, rv, null);\n      throw new UnsatisfiableError(path);\n    }\n    return holder.c;\n  }\n\n  // Populates block b by traversing the active-constraint tree starting at v,\n  // not back-tracking over u.\n  private populateSplitBlock(b: Block, v: Variable, u: Variable | null): void {\n    b.addVariable(v);\n    for (const c of v.in) {\n      if (this.canFollowLeft(c, u)) {\n        this.populateSplitBlock(b, c.left, v);\n      }\n    }\n    for (const c of v.out) {\n      if (this.canFollowRight(c, u)) {\n        this.populateSplitBlock(b, c.right, v);\n      }\n    }\n  }\n\n  // Active path between u and v in the block's active-constraint tree.\n  // Result is pushed into `path` (in reverse order; matches C++).\n  getActivePathBetween(path: Constraint[], u: Variable, v: Variable, w: Variable | null): boolean {\n    if (u === v) return true;\n    for (const c of u.in) {\n      if (this.canFollowLeft(c, w)) {\n        if (this.getActivePathBetween(path, c.left, v, u)) {\n          path.push(c);\n          return true;\n        }\n      }\n    }\n    for (const c of u.out) {\n      if (this.canFollowRight(c, w)) {\n        if (this.getActivePathBetween(path, c.right, v, u)) {\n          path.push(c);\n          return true;\n        }\n      }\n    }\n    return false;\n  }\n\n  // Search the active tree from u for a directed path of `right` traversals\n  // to v.\n  isActiveDirectedPathBetween(u: Variable, v: Variable): boolean {\n    if (u === v) return true;\n    for (const c of u.out) {\n      if (this.canFollowRight(c, null)) {\n        if (this.isActiveDirectedPathBetween(c.right, v)) return true;\n      }\n    }\n    return false;\n  }\n\n  getActiveDirectedPathBetween(path: Constraint[], u: Variable, v: Variable): boolean {\n    if (u === v) return true;\n    for (const c of u.out) {\n      if (this.canFollowRight(c, null)) {\n        if (this.getActiveDirectedPathBetween(path, c.right, v)) {\n          path.push(c);\n          return true;\n        }\n      }\n    }\n    return false;\n  }\n\n  // Split this block across the violated path between vl and vr.  Sets `lb`\n  // and `rb` (returned via a 2-tuple) and marks this block as deleted.\n  splitBetween(vl: Variable, vr: Variable): {c: Constraint | null; l: Block; r: Block} {\n    const c = this.findMinLMBetween(vl, vr);\n    const {l, r} = this.split(c);\n    this.deleted = true;\n    return {c, l, r};\n  }\n\n  // Split into two new blocks across c (which becomes inactive).\n  split(c: Constraint): {l: Block; r: Block} {\n    c.active = false;\n    const l = new Block(this.blocks);\n    this.populateSplitBlock(l, c.left, c.right);\n    const r = new Block(this.blocks);\n    this.populateSplitBlock(r, c.right, c.left);\n    return {l, r};\n  }\n\n  // Sum of squared distances from desired positions, weighted.\n  cost(): number {\n    let c = 0;\n    for (const v of this.vars) {\n      const diff = v.position() - v.desiredPosition;\n      c += v.weight * diff * diff;\n    }\n    return c;\n  }\n}\n\n// ─── Blocks ───────────────────────────────────────────────────────────────────\n\n// Container for all current Blocks.  Owns the timestamp counter used by the\n// priority queues to detect out-of-date heap entries.\nexport class Blocks {\n  blockTimeCtr = 0;\n  private m_blocks: Block[] = [];\n  private vs: Variable[];\n  private nvs: number;\n\n  constructor(vs: Variable[]) {\n    this.vs = vs;\n    this.nvs = vs.length;\n    for (let i = 0; i < this.nvs; i++) {\n      this.m_blocks.push(new Block(this, vs[i]));\n    }\n  }\n\n  size(): number {\n    return this.m_blocks.length;\n  }\n\n  at(i: number): Block {\n    return this.m_blocks[i];\n  }\n\n  insert(block: Block): void {\n    this.m_blocks.push(block);\n  }\n\n  // Topological order on variables derived from the constraint DAG.\n  totalOrder(): Variable[] {\n    const order: Variable[] = [];\n    for (const v of this.vs) v.visited = false;\n    for (const v of this.vs) {\n      if (v.in.length === 0) this.dfsVisit(v, order);\n    }\n    // C++ pushes to the front of a list; we replicate that by appending and\n    // reversing at the end.\n    return order.reverse();\n  }\n\n  private dfsVisit(v: Variable, order: Variable[]): void {\n    v.visited = true;\n    for (const c of v.out) {\n      if (!c.right.visited) this.dfsVisit(c.right, order);\n    }\n    order.push(v);\n  }\n\n  // Process incoming constraints, most violated to least, merging with\n  // left-neighbour blocks until no more violated in-constraints remain.\n  mergeLeft(r: Block): void {\n    r.timeStamp = ++this.blockTimeCtr;\n    r.setUpInConstraints();\n    let c = r.findMinInConstraint();\n    while (c !== null && c.slack() < 0) {\n      r.deleteMinInConstraint();\n      let l = c.left.block!;\n      if (l.in === null) l.setUpInConstraints();\n      let dist = c.right.offset - c.left.offset - c.gap;\n      if (r.vars.length < l.vars.length) {\n        dist = -dist;\n        const tmp = l;\n        l = r;\n        r = tmp;\n      }\n      this.blockTimeCtr++;\n      r.mergeInto(l, c, dist);\n      r.mergeIn(l);\n      r.timeStamp = this.blockTimeCtr;\n      this.removeBlock(l);\n      c = r.findMinInConstraint();\n    }\n  }\n\n  mergeRight(l: Block): void {\n    l.setUpOutConstraints();\n    let c = l.findMinOutConstraint();\n    while (c !== null && c.slack() < 0) {\n      l.deleteMinOutConstraint();\n      let r = c.right.block!;\n      r.setUpOutConstraints();\n      let dist = c.left.offset + c.gap - c.right.offset;\n      if (l.vars.length > r.vars.length) {\n        dist = -dist;\n        const tmp = l;\n        l = r;\n        r = tmp;\n      }\n      l.mergeInto(r, c, dist);\n      l.mergeOut(r);\n      this.removeBlock(r);\n      c = l.findMinOutConstraint();\n    }\n  }\n\n  private removeBlock(doomed: Block): void {\n    doomed.deleted = true;\n  }\n\n  // Drop deleted blocks from the live list.\n  cleanup(): void {\n    let i = 0;\n    for (let j = 0; j < this.m_blocks.length; j++) {\n      if (this.m_blocks[j].deleted) continue;\n      if (j > i) this.m_blocks[i] = this.m_blocks[j];\n      i++;\n    }\n    this.m_blocks.length = i;\n  }\n\n  // Split block b across c, then run mergeLeft / mergeRight to consume any\n  // violations created by the split.  Returns the two surviving blocks (but\n  // note: they may have been further merged during the rebalance).\n  split(b: Block, c: Constraint): {l: Block; r: Block} {\n    const {l, r} = b.split(c);\n    this.m_blocks.push(l);\n    this.m_blocks.push(r);\n    r.posn = b.posn;\n    this.mergeLeft(l);\n    // r may have been merged in the meantime — re-fetch through the\n    // constraint's right block.\n    const rPrime = c.right.block!;\n    rPrime.updateWeightedPosition();\n    this.mergeRight(rPrime);\n    this.removeBlock(b);\n    if (Number.isNaN(l.posn)) throw new Error('VPSC: split produced NaN posn');\n    if (Number.isNaN(rPrime.posn)) throw new Error('VPSC: split produced NaN posn');\n    return {l, r: rPrime};\n  }\n\n  // Total squared cost across all blocks.\n  cost(): number {\n    let c = 0;\n    for (const b of this.m_blocks) c += b.cost();\n    return c;\n  }\n}\n\n// ─── IncSolver ────────────────────────────────────────────────────────────────\n\n// Incremental VPSC solver.  Construct with the variable and constraint\n// lists, then call `satisfy()` to find a feasible solution or `solve()` to\n// drive cost to a local minimum.\nexport class IncSolver {\n  splitCnt = 0;\n  protected bs: Blocks;\n  protected m: number;\n  protected cs: Constraint[];\n  protected n: number;\n  protected vs: Variable[];\n  protected needsScaling: boolean;\n  private inactive: Constraint[];\n\n  constructor(vs: Variable[], cs: Constraint[]) {\n    this.vs = vs;\n    this.cs = cs;\n    this.n = vs.length;\n    this.m = cs.length;\n    this.needsScaling = false;\n    for (const v of vs) {\n      v.in = [];\n      v.out = [];\n      if (v.scale !== 1) this.needsScaling = true;\n    }\n    for (const c of cs) {\n      c.left.out.push(c);\n      c.right.in.push(c);\n      c.needsScaling = this.needsScaling;\n    }\n    this.bs = new Blocks(vs);\n    this.inactive = cs.slice();\n    for (const c of this.inactive) c.active = false;\n  }\n\n  // Returns the current Blocks container (mainly for tests / debugging).\n  getBlocks(): Blocks {\n    return this.bs;\n  }\n\n  // Returns the variable list (read-only by convention).\n  getVariables(): Variable[] {\n    return this.vs;\n  }\n\n  addConstraint(c: Constraint): void {\n    this.m++;\n    c.active = false;\n    this.inactive.push(c);\n    c.left.out.push(c);\n    c.right.in.push(c);\n    c.needsScaling = this.needsScaling;\n  }\n\n  // Stores the relative positions of variables in their finalPosition field.\n  private copyResult(): void {\n    for (const v of this.vs) {\n      v.finalPosition = v.position();\n      if (Number.isNaN(v.finalPosition)) throw new Error('VPSC: variable finalPosition NaN');\n    }\n  }\n\n  // Drive cost(): satisfy() + while-cost-decreases-loop.  Returns true if\n  // any blocks remain merged at the end (the C++ contract).\n  solve(): boolean {\n    this.satisfy();\n    let lastCost = Number.MAX_VALUE;\n    let cost = this.bs.cost();\n    while (Math.abs(lastCost - cost) > 0.0001) {\n      this.satisfy();\n      lastCost = cost;\n      cost = this.bs.cost();\n    }\n    this.copyResult();\n    return this.bs.size() !== this.n;\n  }\n\n  // Incremental satisfaction:\n  //   - move blocks to new positions\n  //   - repeatedly merge across the most violated constraint until none\n  //     remain\n  // Special case: if the most violated constraint lies between two variables\n  // in the same block, split that block at its lm-minimum active constraint.\n  satisfy(): boolean {\n    this.splitBlocks();\n    let v: Constraint | null;\n    while (\n      (v = this.mostViolated(this.inactive)) !== null &&\n      (v.equality || (v.slack() < ZERO_UPPERBOUND && !v.active))\n    ) {\n      if (v.active) throw new Error('VPSC: invariant — most violated should be inactive');\n      let lb = v.left.block!;\n      let rb = v.right.block!;\n      if (lb !== rb) {\n        lb.mergeWith(rb, v);\n      } else {\n        if (lb.isActiveDirectedPathBetween(v.right, v.left)) {\n          // Cycle: relax this violated constraint.\n          v.unsatisfiable = true;\n          continue;\n        }\n        // Constraint is within the block: split first.\n        try {\n          const split = lb.splitBetween(v.left, v.right);\n          if (split.c !== null) {\n            if (split.c.active) throw new Error('VPSC: split constraint should be inactive');\n            this.inactive.push(split.c);\n            lb = split.l;\n            rb = split.r;\n          } else {\n            v.unsatisfiable = true;\n            continue;\n          }\n        } catch (e) {\n          if (e instanceof UnsatisfiableError) {\n            e.path.push(v);\n            v.unsatisfiable = true;\n            continue;\n          }\n          throw e;\n        }\n        if (v.slack() >= 0) {\n          if (v.active) throw new Error('VPSC: invariant');\n          // The split was enough to satisfy v.\n          this.inactive.push(v);\n          this.bs.insert(lb);\n          this.bs.insert(rb);\n        } else {\n          this.bs.insert(lb.mergeWith(rb, v));\n          // Original lb (now deleted) is GC-managed; no manual delete.\n        }\n      }\n    }\n    this.bs.cleanup();\n    let activeConstraints = false;\n    for (const c of this.cs) {\n      if (c.active) activeConstraints = true;\n      if (c.slack() < ZERO_UPPERBOUND) {\n        throw new Error(`VPSC: Unsatisfied constraint: ${c.toString()}`);\n      }\n    }\n    this.copyResult();\n    return activeConstraints;\n  }\n\n  moveBlocks(): void {\n    const length = this.bs.size();\n    for (let i = 0; i < length; i++) {\n      this.bs.at(i).updateWeightedPosition();\n    }\n  }\n\n  splitBlocks(): void {\n    this.moveBlocks();\n    this.splitCnt = 0;\n    const length = this.bs.size();\n    for (let i = 0; i < length; i++) {\n      const block = this.bs.at(i);\n      const v = block.findMinLM();\n      if (v !== null && v.lm < LAGRANGIAN_TOLERANCE) {\n        if (v.equality) throw new Error('VPSC: cannot split on an equality');\n        this.splitCnt++;\n        const b = v.left.block!;\n        if (v.left.block !== v.right.block) throw new Error('VPSC: split invariant');\n        const {l, r} = b.split(v);\n        l.updateWeightedPosition();\n        r.updateWeightedPosition();\n        this.bs.insert(l);\n        this.bs.insert(r);\n        b.deleted = true;\n        if (v.active) throw new Error('VPSC: split constraint should be inactive');\n        this.inactive.push(v);\n      }\n    }\n    this.bs.cleanup();\n  }\n\n  // Scan constraint list for the most violated constraint, or the first\n  // equality constraint encountered.  The chosen constraint is swapped to\n  // the end and popped, matching the C++ \"swap-and-shrink\" idiom.\n  private mostViolated(l: Constraint[]): Constraint | null {\n    let slackForMostViolated = Number.MAX_VALUE;\n    let mostViolated: Constraint | null = null;\n    let deleteIndex = l.length;\n    for (let i = 0; i < l.length; i++) {\n      const c = l[i];\n      const s = c.slack();\n      if (c.equality || s < slackForMostViolated) {\n        slackForMostViolated = s;\n        mostViolated = c;\n        deleteIndex = i;\n        if (c.equality) break;\n      }\n    }\n    if (\n      deleteIndex < l.length &&\n      mostViolated !== null &&\n      ((slackForMostViolated < ZERO_UPPERBOUND && !mostViolated.active) || mostViolated.equality)\n    ) {\n      l[deleteIndex] = l[l.length - 1];\n      l.length--;\n    }\n    return mostViolated;\n  }\n}\n","import {Variable} from '../vpsc';\nimport {Edge} from '../models/edge.ts';\nimport {CHANNEL_MAX, type ShiftSegment} from '../scanline.ts';\nimport {Point} from '../geomtypes';\nimport {CmpIndexes} from '../orthogonal';\n\n// ─── Constants ───────────────────────────────────────────────────────────────\n\n// Variable IDs used by the VPSC solver (passed as `Variable.id`).  The\n// channel-edge IDs let us recognise unsatisfied channel boundaries later.\nconst freeSegmentID = 0;\nconst fixedSegmentID = 1;\n\n// Weights for the four kinds of variable.\nconst freeWeight = 0.00001;\nconst strongWeight = 0.001;\nconst strongerWeight = 1.0;\nconst fixedWeight = 100000;\n\n// The concrete ShiftSegment implementation used during orthogonal nudging.\n//\n// Each instance represents a segment of a connector's display route that\n// may be shifted along `dimension`.  Construction takes the low and high\n// route-index of the segment endpoints; the actual coordinates are read\n// lazily from `connRef.displayRoute().ps`.\nexport class NudgingShiftSegment implements ShiftSegment {\n  connRef: Edge;\n  variable: Variable | null;\n  indexes: number[];\n  fixed: boolean;\n  finalSegment: boolean;\n  endsInShape: boolean;\n  singleConnectedSegment: boolean;\n  checkpoints: Point[];\n\n  // ShiftSegment interface fields.\n  dimension: number;\n  minSpaceLimit: number;\n  maxSpaceLimit: number;\n\n  // Private bend flags.\n  private _sBend: boolean;\n  private _zBend: boolean;\n\n  // ─── Construction ─────────────────────────────────────────────────────────\n  //\n  // Two constructor forms in the C++ source; modelled here as `makeShiftable`\n  // and `makeFixed` static factories.  The public constructor accepts the\n  // shiftable shape.\n\n  // Shiftable segment.\n  constructor(\n    conn: Edge,\n    low: number,\n    high: number,\n    isSBend: boolean,\n    isZBend: boolean,\n    dim: number,\n    minLim: number,\n    maxLim: number,\n  );\n  // Fixed segment.\n  constructor(conn: Edge, low: number, high: number, dim: number);\n  constructor(\n    conn: Edge,\n    low: number,\n    high: number,\n    isSBendOrDim: boolean | number,\n    isZBend?: boolean,\n    dim?: number,\n    minLim?: number,\n    maxLim?: number,\n  ) {\n    this.connRef = conn;\n    this.variable = null;\n    this.indexes = [low, high];\n    this.finalSegment = false;\n    this.endsInShape = false;\n    this.singleConnectedSegment = false;\n    this.checkpoints = [];\n\n    if (typeof isSBendOrDim === 'number') {\n      // Fixed-segment overload.\n      this.dimension = isSBendOrDim;\n      this.fixed = true;\n      this._sBend = false;\n      this._zBend = false;\n      // This has no space to shift.\n      const pos = this.lowPoint().at(this.dimension);\n      this.minSpaceLimit = pos;\n      this.maxSpaceLimit = pos;\n    } else {\n      // Shiftable overload.\n      this.dimension = dim!;\n      this.fixed = false;\n      this._sBend = isSBendOrDim;\n      this._zBend = isZBend!;\n      this.minSpaceLimit = minLim!;\n      this.maxSpaceLimit = maxLim!;\n    }\n  }\n\n  // ─── Endpoint accessors ───────────────────────────────────────────────────\n\n  lowPoint(): Point {\n    return this.connRef.displayRoute().ps[this.indexes[0]];\n  }\n\n  highPoint(): Point {\n    return this.connRef.displayRoute().ps[this.indexes[this.indexes.length - 1]];\n  }\n\n  // ─── Predicates ───────────────────────────────────────────────────────────\n\n  nudgeDistance(): number {\n    return this.connRef.router.params.idealNudgingDistance;\n  }\n\n  // Returns true when this segment is fixed in place by topology / direction\n  // (i.e., not an s- or z-bend the nudger is allowed to slide).\n  immovable(): boolean {\n    return !this.zigzag();\n  }\n\n  zigzag(): boolean {\n    return this._sBend || this._zBend;\n  }\n\n  get sBend(): boolean {\n    return this._sBend;\n  }\n  get zBend(): boolean {\n    return this._zBend;\n  }\n\n  // ─── Solver variable management ───────────────────────────────────────────\n\n  // Assign a VPSC Variable describing this segment's desired position and\n  // how strongly it resists moving.  The `justUnifying` flag distinguishes\n  // the unifying preprocessing pass from the main nudging pass — see\n  // ImproveOrthogonalRoutes.execute.\n  createSolverVariable(justUnifying: boolean): void {\n    const router = this.connRef.router;\n    const nudgeFinalSegments = router.options.nudgeOrthogonalSegmentsConnectedToShapes;\n\n    let varID = freeSegmentID;\n    let varPos = this.lowPoint().at(this.dimension);\n    let weight = freeWeight;\n\n    if (nudgeFinalSegments && this.finalSegment) {\n      weight = strongWeight;\n      if (this.singleConnectedSegment && !justUnifying) {\n        // Single-segment connector spanning two shapes — keep it centred.\n        weight = strongerWeight;\n      }\n    } else if (this.checkpoints.length > 0) {\n      weight = strongWeight;\n    } else if (this.zigzag()) {\n      if (!(this.minSpaceLimit > -CHANNEL_MAX)) {\n        throw new Error('orthogonal: zigzag segment without left channel');\n      }\n      if (!(this.maxSpaceLimit < CHANNEL_MAX)) {\n        throw new Error('orthogonal: zigzag segment without right channel');\n      }\n      // For zigzag bends, take the middle as ideal.\n      varPos = this.minSpaceLimit + (this.maxSpaceLimit - this.minSpaceLimit) / 2;\n    } else if (this.fixed) {\n      weight = fixedWeight;\n      varID = fixedSegmentID;\n    } else if (!this.finalSegment) {\n      // Set a higher weight for c-bends to stop them sometimes getting pushed\n      // out into channels by more-free connectors to the \"inner\" side.\n      weight = strongWeight;\n    }\n\n    this.variable = new Variable(varID, varPos, weight);\n  }\n\n  // Push the solver's chosen position back into the route.\n  updatePositionsFromSolver(_justUnifying: boolean): void {\n    if (this.fixed) return;\n    let newPos = this.variable!.finalPosition;\n\n    // The solver can sometimes cause variables to be outside their limits by a\n    // tiny amount, since all variables are held by weights.  Clamp.\n    newPos = Math.max(newPos, this.minSpaceLimit);\n    newPos = Math.min(newPos, this.maxSpaceLimit);\n\n    const route = this.connRef.displayRoute();\n    for (const index of this.indexes) {\n      route.ps[index].setAt(this.dimension, newPos);\n    }\n  }\n\n  // Returns 0 when the segment is fixed or pinned at both limits, +1 when\n  // limited only at the min side, -1 when limited only at the max side.\n  fixedOrder(): {order: number; isFixed: boolean} {\n    const nudgeDist = this.nudgeDistance();\n    const pos = this.lowPoint().at(this.dimension);\n    const minLimited = pos - this.minSpaceLimit < nudgeDist;\n    const maxLimited = this.maxSpaceLimit - pos < nudgeDist;\n\n    if (this.fixed || (minLimited && maxLimited)) {\n      return {order: 0, isFixed: true};\n    }\n    if (minLimited) return {order: 1, isFixed: false};\n    if (maxLimited) return {order: -1, isFixed: false};\n    return {order: 0, isFixed: false};\n  }\n\n  order(): number {\n    if (this._lowC()) return -1;\n    if (this._highC()) return 1;\n    return 0;\n  }\n\n  // Returns true if `rhs` shares an overlap with this segment such that the\n  // two need to be constrained against each other in the nudger.  Counts\n  // collinear-sharing-endpoint pairs as overlapping so they can be nudged\n  // apart where possible.\n  overlapsWith(rhsSuper: ShiftSegment, dim: number): boolean {\n    const rhs = rhsSuper as NudgingShiftSegment;\n    const altDim = (dim + 1) % 2;\n    const lowPt = this.lowPoint();\n    const highPt = this.highPoint();\n    const rhsLowPt = rhs.lowPoint();\n    const rhsHighPt = rhs.highPoint();\n\n    if (lowPt.at(altDim) < rhsHighPt.at(altDim) && rhsLowPt.at(altDim) < highPt.at(altDim)) {\n      // The segments overlap.\n      if (this.minSpaceLimit <= rhs.maxSpaceLimit && rhs.minSpaceLimit <= this.maxSpaceLimit) {\n        return true;\n      }\n    } else if (lowPt.at(altDim) === rhsHighPt.at(altDim) || rhsLowPt.at(altDim) === highPt.at(altDim)) {\n      const router = this.connRef.router;\n      const nudgeColinearSegments = router.options.nudgeOrthogonalTouchingColinearSegments;\n\n      if (this.minSpaceLimit <= rhs.maxSpaceLimit && rhs.minSpaceLimit <= this.maxSpaceLimit) {\n        if (router.params.fixedSharedPathPenalty > 0) {\n          return true;\n        }\n        if ((rhs._sBend && this._sBend) || (rhs._zBend && this._zBend)) {\n          return nudgeColinearSegments;\n        }\n        if (rhs.finalSegment && this.finalSegment && rhs.connRef === this.connRef) {\n          return nudgeColinearSegments;\n        }\n      }\n    }\n    return false;\n  }\n\n  // True if these two end-segments can drift together along `dimension`.\n  canAlignWith(rhs: NudgingShiftSegment, _dim: number): boolean {\n    if (this.connRef !== rhs.connRef) return false;\n    // If either has checkpoints we want to maintain the path through them.\n    if (this.checkpoints.length > 0 || rhs.checkpoints.length > 0) return false;\n    return true;\n  }\n\n  // True if these two end-segments should actively align with each other in\n  // the nudger.\n  shouldAlignWith(rhsSuper: ShiftSegment, dim: number): boolean {\n    const rhs = rhsSuper as NudgingShiftSegment;\n    if (this.connRef === rhs.connRef && this.finalSegment && rhs.finalSegment && this.overlapsWith(rhs, dim)) {\n      if ((this.endsInShape && rhs.endsInShape) || Math.abs(this.lowPoint().at(dim) - rhs.lowPoint().at(dim)) < 10) {\n        return true;\n      }\n    } else if (\n      this.connRef === rhs.connRef &&\n      // Not both final\n      !(this.finalSegment && rhs.finalSegment)\n    ) {\n      const hasCheckpoints = this.checkpoints.length > 0;\n      const rhsHasCheckpoints = rhs.checkpoints.length > 0;\n      if (hasCheckpoints !== rhsHasCheckpoints) {\n        const altDim = (dim + 1) % 2;\n        const space = Math.abs(this.lowPoint().at(dim) - rhs.lowPoint().at(dim));\n        let touchPos = 0;\n        let couldTouch = false;\n        if (this.lowPoint().at(altDim) === rhs.highPoint().at(altDim)) {\n          couldTouch = true;\n          touchPos = this.lowPoint().at(altDim);\n        } else if (this.highPoint().at(altDim) === rhs.lowPoint().at(altDim)) {\n          couldTouch = true;\n          touchPos = this.highPoint().at(altDim);\n        }\n        return (\n          couldTouch &&\n          space <= 10 &&\n          !this.hasCheckpointAtPosition(touchPos, altDim) &&\n          !rhs.hasCheckpointAtPosition(touchPos, altDim)\n        );\n      }\n    }\n    return false;\n  }\n\n  // Merge an end-segment from the same connector into this one.\n  mergeWith(rhsSuper: ShiftSegment, dim: number): void {\n    // Adjust limits.\n    this.minSpaceLimit = Math.max(this.minSpaceLimit, rhsSuper.minSpaceLimit);\n    this.maxSpaceLimit = Math.min(this.maxSpaceLimit, rhsSuper.maxSpaceLimit);\n\n    // New position is the midpoint of the two originals, clamped by the\n    // merged limits.\n    let segmentPos = this.lowPoint().at(this.dimension);\n    const segment2Pos = rhsSuper.lowPoint().at(this.dimension);\n    if (segment2Pos < segmentPos) {\n      segmentPos -= (segmentPos - segment2Pos) / 2.0;\n    } else if (segment2Pos > segmentPos) {\n      segmentPos += (segment2Pos - segmentPos) / 2.0;\n    }\n    segmentPos = Math.max(this.minSpaceLimit, segmentPos);\n    segmentPos = Math.min(this.maxSpaceLimit, segmentPos);\n\n    // Merge the index lists and sort by altDim position.\n    const rhs = rhsSuper as NudgingShiftSegment;\n    this.indexes.push(...rhs.indexes);\n    const altDim = (dim + 1) % 2;\n    const cmp = new CmpIndexes(this.connRef, altDim);\n    this.indexes.sort((a, b) => cmp.compare(a, b));\n\n    // Apply the new position to all points.\n    const route = this.connRef.displayRoute();\n    for (const index of this.indexes) {\n      route.ps[index].setAt(this.dimension, segmentPos);\n    }\n  }\n\n  hasCheckpointAtPosition(position: number, dim: number): boolean {\n    for (const cp of this.checkpoints) {\n      if (cp.at(dim) === position) return true;\n    }\n    return false;\n  }\n\n  // ─── Private c-bend detection ─────────────────────────────────────────────\n\n  private _lowC(): boolean {\n    return (\n      !this.finalSegment && !this.zigzag() && !this.fixed && this.minSpaceLimit === this.lowPoint().at(this.dimension)\n    );\n  }\n\n  private _highC(): boolean {\n    return (\n      !this.finalSegment && !this.zigzag() && !this.fixed && this.maxSpaceLimit === this.lowPoint().at(this.dimension)\n    );\n  }\n}\n","// A breakpoint along a candidate visibility segment — a position on the\n// perpendicular axis combined with the vertex (which may be a shape corner,\n// a connection point, or a dummy lattice vertex) at that position.\n\nimport {VisDirNone} from '../orthogonal';\nimport {VertInf} from '../vertex';\n\n// Two VertInfs share the same identity tag when both `objID` and `vn` match.\nfunction sameId(a: VertInf, b: VertInf): boolean {\n  return a.objID === b.objID && a.vn === b.vn;\n}\n\n// True when the vertex is a synthesised lattice vertex with no owning\n// obstacle or connector — the scanline can produce multiple of these at the\n// same point (e.g. for junctions sitting outside any shape), and the\n// ordering treats them as interchangeable.\nfunction isAnonymousDummy(v: VertInf): boolean {\n  return v.objID === 0 && v.vn === 0;\n}\n\nexport class PosVertInf {\n  pos: number;\n  vert: VertInf;\n  dirs: number;\n\n  constructor(pos: number, vert: VertInf, dirs = VisDirNone) {\n    this.pos = pos;\n    this.vert = vert;\n    this.dirs = dirs;\n  }\n\n  // Total ordering used by `SortedArray<PosVertInf>` — the union of the\n  // old `lt` (strict less-than) and `eq` predicates.  Returns 0 only for\n  // pairs that the C++ operator< treats as interchangeable; the set\n  // semantics in SortedArray dedup those.\n  //\n  // Ordering:\n  //   1. by `pos` (the perpendicular-axis coordinate).\n  //   2. if both vertices are anonymous-dummy lattice vertices (objID=0,\n  //      vn=0) at the same `pos`, they're interchangeable — return 0.\n  //   3. else by (objID, vn) for stable cross-run order.\n  //   4. else by `dirs`.\n  static compare(a: PosVertInf, b: PosVertInf): number {\n    if (a.pos !== b.pos) return a.pos < b.pos ? -1 : 1;\n    if (sameId(a.vert, b.vert) && isAnonymousDummy(a.vert)) return 0;\n    if (a.vert.objID !== b.vert.objID) return a.vert.objID - b.vert.objID;\n    if (a.vert.vn !== b.vert.vn) return a.vert.vn - b.vert.vn;\n    return a.dirs - b.dirs;\n  }\n}\n","import {VertInf, XH_CONN, XH_EDGE, XL_CONN, XL_EDGE, YH_CONN, YH_EDGE, YL_CONN, YL_EDGE} from '../vertex';\nimport type {Router} from '../router';\nimport {Point, XDIM, YDIM} from '../geomtypes';\nimport {VisDirDown, VisDirNone, VisDirUp} from '../orthogonal';\nimport {EdgeInf} from '../graph';\nimport {Direction} from '../models/Direction';\nimport {PosVertInf} from './pos-vert-inf';\nimport {SortedArray} from './sorted-array';\n\n// Module-private helper: construct an anonymous routing-graph vertex\n// (objID=0, vn=0) and register it with the router's vertex list.\nfunction newRoutingVertex(router: Router, point: Point): VertInf {\n  const v = new VertInf(0, 0, point);\n  router.vertices.addVertex(v);\n  return v;\n}\n\n// Returns a bitfield describing which scanline directions are visible from v\n// in dimension `dim`.  Translates user-facing Direction visibility (left /\n// right / up / down) into scanline-orientation directions (which differ for\n// the Y axis because our Y points downward).\nexport function getPosVertInfDirections(v: VertInf, dim: number): number {\n  if (dim === XDIM) {\n    if (v.visDirections.has(Direction.inline)) {\n      return VisDirDown | VisDirUp;\n    }\n    if (v.visDirections.has(Direction.inlineStart)) return VisDirDown;\n    if (v.visDirections.has(Direction.inlineEnd)) return VisDirUp;\n  } else if (dim === YDIM) {\n    if (v.visDirections.has(Direction.block)) {\n      return VisDirDown | VisDirUp;\n    }\n    // Ours Y points downwards: user \"down\" visibility means scanline\n    // visibility to higher positions, and vice versa.\n    if (v.visDirections.has(Direction.blockEnd)) {\n      return VisDirUp;\n    }\n    if (v.visDirections.has(Direction.blockStart)) {\n      return VisDirDown;\n    }\n  }\n  return VisDirNone;\n}\n\n// A candidate horizontal/vertical visibility segment produced during sweep.\n// Stores its extent along the segment axis (`begin`..`finish`) and its\n// perpendicular position (`pos`), plus a sorted set of vertices that lie on\n// it (`vertInfs`) and intersection break-points discovered during the cross\n// sweep (`breakPoints`).\nexport class LineSegment {\n  begin: number;\n  finish: number;\n  pos: number;\n  shapeSide: boolean;\n  vertInfs: SortedArray<VertInf>;\n  breakPoints: SortedArray<PosVertInf>;\n\n  // Two construction shapes (segment with explicit begin..finish, and point\n  // segment with begin==finish).  We model them as a single signature.\n\n  constructor(b: number, f: number, p: number, ss?: boolean, bvi?: VertInf | null, fvi?: VertInf | null);\n  constructor(bf: number, p: number, bfvi?: VertInf | null);\n  constructor(\n    b: number,\n    fOrP: number,\n    pOrBfvi?: number | VertInf | null,\n    ss?: boolean,\n    bvi?: VertInf | null,\n    fvi?: VertInf | null,\n  ) {\n    this.vertInfs = new SortedArray<VertInf>(VertInf.compare);\n    this.breakPoints = new SortedArray<PosVertInf>(PosVertInf.compare);\n\n    if (typeof pOrBfvi === 'number') {\n      // Three-number form.\n      this.begin = b;\n      this.finish = fOrP;\n      this.pos = pOrBfvi;\n      this.shapeSide = ss ?? false;\n      if (this.begin >= this.finish) {\n        throw new Error('orthogonal: LineSegment requires begin < finish');\n      }\n      if (bvi) this.vertInfs.insert(bvi);\n      if (fvi) this.vertInfs.insert(fvi);\n    } else {\n      // Two-number form (point segment).\n      this.begin = b;\n      this.finish = b;\n      this.pos = fOrP;\n      this.shapeSide = false;\n      if (pOrBfvi) this.vertInfs.insert(pOrBfvi);\n    }\n  }\n\n  // Sort key: by begin, pos, finish.\n  static compare(lhs: LineSegment, rhs: LineSegment): number {\n    if (lhs.begin !== rhs.begin) return lhs.begin < rhs.begin ? -1 : 1;\n    if (lhs.pos !== rhs.pos) return lhs.pos < rhs.pos ? -1 : 1;\n    if (lhs.finish !== rhs.finish) return lhs.finish < rhs.finish ? -1 : 1;\n    return 0;\n  }\n\n  overlaps(rhs: LineSegment): boolean {\n    if (this.begin === rhs.begin && this.pos === rhs.pos && this.finish === rhs.finish) {\n      return true;\n    }\n    if (this.pos === rhs.pos) {\n      if (\n        (this.begin >= rhs.begin && this.begin <= rhs.finish) ||\n        (rhs.begin >= this.begin && rhs.begin <= this.finish)\n      ) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  mergeVertInfs(segment: LineSegment): void {\n    this.begin = Math.min(this.begin, segment.begin);\n    this.finish = Math.max(this.finish, segment.finish);\n    this.vertInfs.insertAll(segment.vertInfs.values());\n  }\n\n  private beginVertInf(): VertInf | null {\n    const inf = this.vertInfs.first();\n    if (!inf) return null;\n    if (\n      (inf.point.y === this.begin && inf.point.x === this.pos) ||\n      (inf.point.x === this.begin && inf.point.y === this.pos)\n    ) {\n      return inf;\n    }\n    return null;\n  }\n\n  private finishVertInf(): VertInf | null {\n    const inf = this.vertInfs.last();\n    if (!inf) return null;\n    if (\n      (inf.point.y === this.finish && inf.point.x === this.pos) ||\n      (inf.point.x === this.finish && inf.point.y === this.pos)\n    ) {\n      return inf;\n    }\n    return null;\n  }\n\n  private commitPositionX(router: Router, posX: number): VertInf {\n    for (const v of this.vertInfs.values()) {\n      if (v.point.x === posX) return v;\n    }\n    const found = newRoutingVertex(router, new Point(posX, this.pos));\n    this.vertInfs.insert(found);\n    return found;\n  }\n\n  // For horizontal lines: commit the begin endpoint vertex if none assigned.\n  private horiCommitBegin(router: Router, vert: VertInf | null = null): void {\n    if (vert) this.vertInfs.insert(vert);\n    const first = this.vertInfs.first();\n    if (!first || first.point.x !== this.begin) {\n      if (this.begin !== -Number.MAX_VALUE) {\n        this.vertInfs.insert(newRoutingVertex(router, new Point(this.begin, this.pos)));\n      }\n    }\n  }\n\n  private horiCommitFinish(router: Router, vert: VertInf | null = null): void {\n    if (vert) this.vertInfs.insert(vert);\n    const last = this.vertInfs.last();\n    if (!last || last.point.x !== this.finish) {\n      if (this.finish !== Number.MAX_VALUE) {\n        this.vertInfs.insert(newRoutingVertex(router, new Point(this.finish, this.pos)));\n      }\n    }\n  }\n\n  // Walk the vertices of this line up to `finishPos`, registering each as a\n  // breakpoint.  Returns the index of the first intersection point at\n  // `finishPos` (or vertInfs.size() if none).\n  private addSegmentsUpTo(finishPos: number): number {\n    let firstIntersection = this.vertInfs.size();\n    const verts = this.vertInfs.values();\n    for (let i = 0; i < verts.length; i++) {\n      const v = verts[i];\n      if (v.point.x > finishPos) break;\n      this.breakPoints.insert(new PosVertInf(v.point.x, v, getPosVertInfDirections(v, XDIM)));\n      if (firstIntersection === this.vertInfs.size() && v.point.x === finishPos) {\n        firstIntersection = i;\n      }\n    }\n    return firstIntersection;\n  }\n\n  addEdgeHorizontal(router: Router): void {\n    this.horiCommitBegin(router);\n    this.horiCommitFinish(router);\n    this.addSegmentsUpTo(this.finish);\n  }\n\n  // Walk through breakPoints, setting the orthog-vis property flags for each\n  // vertex according to whether it has seen a conn-point or shape-edge so far\n  // in either direction.\n  private setLongRangeVisibilityFlags(dim: number): void {\n    const pts = this.breakPoints.values();\n\n    // Forward pass.\n    let seenConnPt = false;\n    let seenShapeEdge = false;\n    for (const nvert of pts) {\n      let mask = 0;\n      if (dim === XDIM) {\n        if (seenConnPt) mask |= XL_CONN;\n        if (seenShapeEdge) mask |= XL_EDGE;\n      } else {\n        if (seenConnPt) mask |= YL_CONN;\n        if (seenShapeEdge) mask |= YL_EDGE;\n      }\n      nvert.vert.orthogVisPropFlags |= mask;\n      if (nvert.vert.isConnPoint) seenConnPt = true;\n      if (nvert.vert.isOrthShapeEdge) seenShapeEdge = true;\n    }\n\n    // Reverse pass.\n    seenConnPt = false;\n    seenShapeEdge = false;\n    for (let i = pts.length - 1; i >= 0; i--) {\n      const rvert = pts[i];\n      let mask = 0;\n      if (dim === XDIM) {\n        if (seenConnPt) mask |= XH_CONN;\n        if (seenShapeEdge) mask |= XH_EDGE;\n      } else {\n        if (seenConnPt) mask |= YH_CONN;\n        if (seenShapeEdge) mask |= YH_EDGE;\n      }\n      rvert.vert.orthogVisPropFlags |= mask;\n      if (rvert.vert.isConnPoint) seenConnPt = true;\n      if (rvert.vert.isOrthShapeEdge) seenShapeEdge = true;\n    }\n  }\n\n  // Add visibility edges for this segment up until an intersection with\n  // `vertLine`.  After return, this segment has been advanced past the\n  // intersection so subsequent calls deal with the remainder.  Returns the\n  // intersection-point vertices.\n  addEdgeHorizontalTillIntersection(router: Router, vertLine: LineSegment): VertInf[] {\n    const intersectionSet: VertInf[] = [];\n\n    this.horiCommitBegin(router);\n\n    // Does a vertex already exist for this point?\n    this.commitPositionX(router, vertLine.pos);\n\n    // Generate segments and find the first index at the intersection position.\n    const restBegin = this.addSegmentsUpTo(vertLine.pos);\n\n    // Capture all intersection points at vertLine.pos.\n    const verts = this.vertInfs.values();\n    let restEnd = restBegin;\n    while (restEnd < verts.length && verts[restEnd].point.x === vertLine.pos) {\n      intersectionSet.push(verts[restEnd]);\n      restEnd++;\n    }\n\n    // Adjust segment to remove processed portion.\n    this.begin = vertLine.pos;\n    this.vertInfs.eraseFront(restBegin);\n\n    return intersectionSet;\n  }\n\n  insertBreakpointsBegin(router: Router, vertLine: LineSegment): void {\n    let vert: VertInf | null = null;\n    if (this.pos === vertLine.begin && vertLine.beginVertInf()) {\n      vert = vertLine.beginVertInf();\n    } else if (this.pos === vertLine.finish && vertLine.finishVertInf()) {\n      vert = vertLine.finishVertInf();\n    }\n    this.horiCommitBegin(router, vert);\n    for (const v of this.vertInfs.values()) {\n      if (v.point.x === this.begin) {\n        vertLine.breakPoints.insert(new PosVertInf(this.pos, v, getPosVertInfDirections(v, YDIM)));\n      }\n    }\n  }\n\n  insertBreakpointsFinish(router: Router, vertLine: LineSegment): void {\n    let vert: VertInf | null = null;\n    if (this.pos === vertLine.begin && vertLine.beginVertInf()) {\n      vert = vertLine.beginVertInf();\n    } else if (this.pos === vertLine.finish && vertLine.finishVertInf()) {\n      vert = vertLine.finishVertInf();\n    }\n    this.horiCommitFinish(router, vert);\n    for (const v of this.vertInfs.values()) {\n      if (v.point.x === this.finish) {\n        vertLine.breakPoints.insert(new PosVertInf(this.pos, v, getPosVertInfDirections(v, YDIM)));\n      }\n    }\n  }\n\n  generateVisibilityEdgesFromBreakpointSet(router: Router, dim: number): void {\n    const firstBP = this.breakPoints.first();\n    if (firstBP === undefined || firstBP.pos > this.begin) {\n      // Add a begin point if there was not already an intersection at that\n      // point.  Skip if the line goes to -infinity — nothing to connect to.\n      if (this.begin === -Number.MAX_VALUE) {\n        if (firstBP === undefined) {\n          throw new Error('orthogonal: breakPoints empty at -∞ begin');\n        }\n        this.begin = firstBP.pos;\n      } else {\n        const point = new Point(this.pos, this.pos);\n        point.setAt(dim, this.begin);\n        const vert = newRoutingVertex(router, point);\n        this.breakPoints.insert(new PosVertInf(this.begin, vert));\n      }\n    }\n    const lastBP = this.breakPoints.last();\n    if (lastBP === undefined || lastBP.pos < this.finish) {\n      if (this.finish === Number.MAX_VALUE) {\n        if (lastBP === undefined) {\n          throw new Error('orthogonal: breakPoints empty at +∞ finish');\n        }\n        this.finish = lastBP.pos;\n      } else {\n        const point = new Point(this.pos, this.pos);\n        point.setAt(dim, this.finish);\n        const vert = newRoutingVertex(router, point);\n        this.breakPoints.insert(new PosVertInf(this.finish, vert));\n      }\n    }\n\n    // Set flags for orthogonal routing optimisation.\n    this.setLongRangeVisibilityFlags(dim);\n\n    const pts = this.breakPoints.values();\n    let vert = 0;\n    let last = 0;\n    while (vert < pts.length) {\n      const firstPrev = last;\n      while (pts[last].vert.point.at(dim) !== pts[vert].vert.point.at(dim)) {\n        // Pair of two endpoints both inside a shape.\n        if (pts[vert].vert.isConnPoint && pts[last].vert.isConnPoint) {\n          // Give vert visibility back to the first non-connector vertex.\n          let side = last;\n          while (pts[side].vert.isConnPoint) {\n            if (side === 0) break;\n            side--;\n          }\n          const canSeeDown = (pts[vert].dirs & VisDirDown) !== 0;\n          if (canSeeDown && !pts[side].vert.isConnPoint) {\n            const edge = new EdgeInf(pts[side].vert, pts[vert].vert, router);\n            edge.setDist(pts[vert].vert.point.at(dim) - pts[side].vert.point.at(dim));\n          }\n\n          // Give last visibility forward.\n          let side2 = vert;\n          while (side2 < pts.length && pts[side2].vert.isConnPoint) {\n            side2++;\n          }\n          const canSeeUp = (pts[last].dirs & VisDirUp) !== 0;\n          if (canSeeUp && side2 < pts.length) {\n            const edge = new EdgeInf(pts[last].vert, pts[side2].vert, router);\n            edge.setDist(pts[side2].vert.point.at(dim) - pts[last].vert.point.at(dim));\n          }\n        }\n\n        // The normal case.\n        let generateEdge = true;\n        if (pts[last].vert.isConnPoint && !(pts[last].dirs & VisDirUp)) {\n          generateEdge = false;\n        } else if (pts[vert].vert.isConnPoint && !(pts[vert].dirs & VisDirDown)) {\n          generateEdge = false;\n        }\n        if (generateEdge) {\n          const edge = new EdgeInf(pts[last].vert, pts[vert].vert, router);\n          edge.setDist(pts[vert].vert.point.at(dim) - pts[last].vert.point.at(dim));\n        }\n        last++;\n      }\n\n      vert++;\n\n      if (vert < pts.length && pts[last].vert.point.at(dim) === pts[vert].vert.point.at(dim)) {\n        // Still looking at same pair, just reset prev pointer.\n        last = firstPrev;\n      }\n      // else: vert has moved to a new position; last is in the right place.\n    }\n  }\n}\n","import {LineSegment} from './line-segment';\n\n// A list of LineSegments with overlap-merging insertion.  The list keeps the\n// invariant that no two segments overlap; on insertion a new segment that\n// overlaps existing ones is merged into the first overlap, and subsequent\n// overlapping segments are merged into the first and removed.\nexport class SegmentListWrapper {\n  /** @internal */ _list: LineSegment[] = [];\n\n  insert(segment: LineSegment): LineSegment {\n    let foundIdx = -1;\n    let i = 0;\n    while (i < this._list.length) {\n      const curr = this._list[i];\n      if (curr.overlaps(segment)) {\n        if (foundIdx !== -1) {\n          // Already found one; merge that one into curr, remove the previous.\n          curr.mergeVertInfs(this._list[foundIdx]);\n          this._list.splice(foundIdx, 1);\n          if (foundIdx < i) i--;\n          foundIdx = i;\n        } else {\n          // First overlap — merge new segment into curr.\n          curr.mergeVertInfs(segment);\n          foundIdx = i;\n        }\n      }\n      i++;\n    }\n\n    if (foundIdx === -1) {\n      this._list.push(segment);\n      return this._list[this._list.length - 1];\n    }\n    return this._list[foundIdx];\n  }\n\n  list(): LineSegment[] {\n    return this._list;\n  }\n\n  sort(): void {\n    this._list.sort(LineSegment.compare);\n  }\n\n  clear(): void {\n    this._list.length = 0;\n  }\n}\n","// Orthogonal routing — static visibility graph build and post-route nudging.\n//\n// Ports input/orthogonal.cpp and input/orthogonal.h.  The two public entry\n// points are:\n//\n//   - generateStaticOrthogonalVisGraph(router): runs two sweepline passes (one\n//     per dimension) over every obstacle corner, junction corner, and\n//     connector endpoint, producing the lattice of horizontal/vertical\n//     visibility edges that orthogonal A* searches over.  Each edge stores\n//     XL_EDGE / XH_EDGE / YL_EDGE / YH_EDGE flags so makepath can know which\n//     edges hug shape boundaries.\n//\n//   - improveOrthogonalRoutes(router): runs the post-route nudging pipeline.\n//     Walks every orthogonal connector, builds NudgingShiftSegments, runs an\n//     optional \"unifying\" VPSC preprocessing pass to centre free segments in\n//     overlapping channels, then per-dimension nudges the segments via VPSC\n//     with PotentialSegmentConstraints.\n//\n// Deviations from the C++ source:\n//   - C++ raw pointers become TypeScript class instances; rely on GC.\n//   - C++ output reference params (`Variable*&`, `LineSegment*&`) return\n//     `{ ... }` records or are written via mutable fields on returned objects.\n//   - `std::set<T, Cmp>` with custom comparators are modelled as sorted arrays\n//     with binary insertion (see SortedSet helper) or sort-on-finalise.\n//   - DBL_MAX  → Number.MAX_VALUE / -Number.MAX_VALUE.\n//   - All NUDGE_DEBUG / DEBUG_JUST_UNIFY / LIBVPSC_LOGGING /\n//     MAJOR_HYPEREDGE_IMPROVEMENT_DEBUG blocks are dropped.\n//   - operator<< printers, fprintf and SVG output are dropped.\n//   - DebugHandler / debug callbacks and setDebuggingOutput are dropped.\n//   - performContinuationCheck / TransactionPhase reporting is dropped\n//     (transactions are not modelled in this port).\n//   - improveOrthogonalTopology is dropped — the libtopology hook is not\n//     ported.\n//   - COLA_ASSERT becomes explicit invariant checks via Error throws for the\n//     ones that matter and is dropped for pure-debug assertions.\n\nimport {Point, XDIM, YDIM, type Box, Polygon} from './geomtypes';\nimport {VertInf as VertInfClass, type VertInfRoles} from './vertex';\n\nimport {Direction} from './models/Direction';\nimport {type Edge, CROSSING_SHARES_PATH_AT_END, splitBranchingSegments} from './models/edge';\nimport {ConnectorCrossings} from './data-structures/ConnectorCrossings';\nimport {type ShiftSegment, CHANNEL_MAX, Node, Event, EventType, compareEvents} from './scanline';\nimport {SortedArray} from './utilities/sorted-array';\nimport {Variable, Constraint, IncSolver} from './vpsc';\nimport {Router} from './router';\nimport {NudgingShiftSegment} from './utilities/nudging-shift-segment';\nimport {getPosVertInfDirections, LineSegment} from './utilities/line-segment';\nimport {PosVertInf} from './utilities/pos-vert-inf';\nimport {SegmentListWrapper} from './utilities/segment-list-wrapper';\nimport type {PtOrderMap} from './data-structures/PtOrder';\n\n// Module-private helper: construct a routing-graph vertex (with no owning\n// obstacle: objID=0, vn=0) and register it with the router's vertex list.\nfunction newRoutingVertex(router: Router, point: Point, roles: VertInfRoles = {}): VertInfClass {\n  const v = new VertInfClass(0, 0, point, roles);\n  router.vertices.addVertex(v);\n  return v;\n}\n\n// Convenience wrapper for the dominant case in this file: a synthesised\n// shape-edge breakpoint discovered by the scanline.\nfunction newShapeEdgeVertex(router: Router, point: Point): VertInfClass {\n  return newRoutingVertex(router, point, {isOrthShapeEdge: true});\n}\n\n// ─── Constants ───────────────────────────────────────────────────────────────\n\n// Variable IDs used by the VPSC solver (passed as `Variable.id`).  The\n// channel-edge IDs let us recognise unsatisfied channel boundaries later.\nconst freeSegmentID = 0;\nconst fixedSegmentID = 1;\nconst channelLeftID = 2;\nconst channelRightID = 3;\n\n// Weights for the four kinds of variable.\nconst freeWeight = 0.00001;\nconst strongWeight = 0.001;\nconst strongerWeight = 1.0;\nconst fixedWeight = 100000;\n\n// ─── UnsignedPair ─────────────────────────────────────────────────────────────\n\n// A pair of unsigned values that can be compared and used as keys.  The\n// smaller index is stored first so {a,b} and {b,a} compare equal.\nexport class UnsignedPair {\n  readonly _index1: number;\n  readonly _index2: number;\n\n  constructor(ind1: number, ind2: number) {\n    if (ind1 === ind2) {\n      throw new Error('orthogonal: UnsignedPair indices must differ');\n    }\n    this._index1 = ind1 < ind2 ? ind1 : ind2;\n    this._index2 = ind1 > ind2 ? ind1 : ind2;\n  }\n\n  // Strict less-than ordering, primary by _index1, then _index2.\n  lt(rhs: UnsignedPair): boolean {\n    if (this._index1 !== rhs._index1) return this._index1 < rhs._index1;\n    return this._index2 < rhs._index2;\n  }\n\n  eq(rhs: UnsignedPair): boolean {\n    return this._index1 === rhs._index1 && this._index2 === rhs._index2;\n  }\n\n  // String key for use with Set / Map.\n  key(): string {\n    return `${this._index1}:${this._index2}`;\n  }\n}\n\n// A set-of-pairs backed by a string-keyed Set, preserving the C++ semantics.\nexport class UnsignedPairSet {\n  private _items = new Set<string>();\n\n  insert(p: UnsignedPair): void {\n    this._items.add(p.key());\n  }\n\n  has(p: UnsignedPair): boolean {\n    return this._items.has(p.key());\n  }\n\n  clear(): void {\n    this._items.clear();\n  }\n\n  size(): number {\n    return this._items.size;\n  }\n}\n\n// ─── CmpIndexes ───────────────────────────────────────────────────────────────\n\n// Comparator used when merging NudgingShiftSegments — sorts route indexes by\n// point position in `dimension`.\nexport class CmpIndexes {\n  connRef: Edge;\n  dimension: number;\n\n  constructor(connRef: Edge, dimension: number) {\n    this.connRef = connRef;\n    this.dimension = dimension;\n  }\n\n  // Returns negative if lhs < rhs, positive if lhs > rhs, 0 if equal.  Suits\n  // Array.prototype.sort callbacks.\n  compare(lhs: number, rhs: number): number {\n    const a = this.connRef.displayRoute().ps[lhs].at(this.dimension);\n    const b = this.connRef.displayRoute().ps[rhs].at(this.dimension);\n    return a < b ? -1 : a > b ? 1 : 0;\n  }\n}\n\n// ─── ScanVisDir / PosVertInf ──────────────────────────────────────────────────\nexport const VisDirNone = 0;\nexport const VisDirUp = 1; // higher position values\nexport const VisDirDown = 2; // lower position values\n\n// ─── intersectSegments ────────────────────────────────────────────────────────\n\n// Given a router and a list of possible horizontal segments, plus a possible\n// vertical visibility segment, compute and add edges to the orthogonal\n// visibility graph for all visibility edges.\n//\n// Modifies `segments` in place — segments whose finish position is behind\n// the vertical line are committed and removed.\nexport function intersectSegments(router: Router, segments: LineSegment[], vertLine: LineSegment): void {\n  if (segments.length === 0) {\n    // C++ asserts; we tolerate empty since callers may legitimately pass empty.\n    vertLine.generateVisibilityEdgesFromBreakpointSet(router, YDIM);\n    return;\n  }\n\n  let i = 0;\n  while (i < segments.length) {\n    const horiLine = segments[i];\n    const inVertSegRegion = vertLine.begin <= horiLine.pos && vertLine.finish >= horiLine.pos;\n\n    if (vertLine.pos < horiLine.begin) {\n      // Yet to reach this segment in the sweep, ignore.\n      i++;\n      continue;\n    } else if (vertLine.pos === horiLine.begin) {\n      if (inVertSegRegion) {\n        horiLine.insertBreakpointsBegin(router, vertLine);\n      }\n    } else if (vertLine.pos === horiLine.finish) {\n      if (inVertSegRegion) {\n        horiLine.addEdgeHorizontal(router);\n        horiLine.insertBreakpointsFinish(router, vertLine);\n        horiLine.generateVisibilityEdgesFromBreakpointSet(router, XDIM);\n        segments.splice(i, 1);\n        continue;\n      }\n    } else if (vertLine.pos > horiLine.finish) {\n      horiLine.addEdgeHorizontal(router);\n      horiLine.generateVisibilityEdgesFromBreakpointSet(router, XDIM);\n      segments.splice(i, 1);\n      continue;\n    } else {\n      // vertLine.pos strictly between horiLine.begin and horiLine.finish.\n      if (inVertSegRegion) {\n        const intersectionVerts = horiLine.addEdgeHorizontalTillIntersection(router, vertLine);\n        for (const v of intersectionVerts) {\n          vertLine.breakPoints.insert(new PosVertInf(horiLine.pos, v, getPosVertInfDirections(v, YDIM)));\n        }\n      }\n    }\n    i++;\n  }\n\n  vertLine.generateVisibilityEdgesFromBreakpointSet(router, YDIM);\n}\n\n// ─── Sweep event processing ───────────────────────────────────────────────────\n\n// Pass-1: insert into scanline & link neighbours.\n// Pass-2: process the event.\n// Pass-3: remove from scanline.\n\nfunction processEventVert(\n  router: Router,\n  scanline: SortedArray<Node>,\n  segments: SegmentListWrapper,\n  e: Event,\n  pass: number,\n): void {\n  const v = e.v;\n\n  if ((pass === 1 && e.type === EventType.Open) || (pass === 2 && e.type === EventType.ConnPoint)) {\n    scanline.insert(v);\n    const above = scanline.prev(v);\n    if (above) {\n      v.firstAbove = above;\n      above.firstBelow = v;\n    }\n    const below = scanline.next(v);\n    if (below) {\n      v.firstBelow = below;\n      below.firstAbove = v;\n    }\n  }\n\n  if (pass === 2) {\n    if (e.type === EventType.Open || e.type === EventType.Close) {\n      // Only difference between Open and Close: which side of the shape we\n      // emit segments on.\n      const lineY = e.type === EventType.Open ? v.min[YDIM] : v.max[YDIM];\n\n      const minShape = v.min[XDIM];\n      const maxShape = v.max[XDIM];\n      const limits = v.findFirstPointAboveAndBelow(XDIM, lineY);\n      const minLimit = limits.firstAbove;\n      const maxLimit = limits.firstBelow;\n      const minLimitMax = limits.lastAbove;\n      const maxLimitMin = limits.lastBelow;\n\n      if (minLimitMax >= maxLimitMin) {\n        // Shape corners (these are real shape-edge vertices).\n        const vI1 = newShapeEdgeVertex(router, new Point(minShape, lineY));\n        const vI2 = newShapeEdgeVertex(router, new Point(maxShape, lineY));\n\n        // No overlapping shapes, full visibility.\n        if (minLimit < minShape) {\n          segments.insert(new LineSegment(minLimit, minShape, lineY, true, null, vI1));\n        }\n        segments.insert(new LineSegment(minShape, maxShape, lineY, true, vI1, vI2));\n        if (maxShape < maxLimit) {\n          segments.insert(new LineSegment(maxShape, maxLimit, lineY, true, vI2, null));\n        }\n      } else {\n        // Overlapping shapes along this shape edge.\n        if (minLimitMax > minLimit && minLimitMax >= minShape) {\n          const line = segments.insert(new LineSegment(minLimit, minLimitMax, lineY, true));\n          const vI1 = newShapeEdgeVertex(router, new Point(minShape, lineY));\n          line.vertInfs.insert(vI1);\n        }\n        if (maxLimitMin < maxLimit && maxLimitMin <= maxShape) {\n          const line = segments.insert(new LineSegment(maxLimitMin, maxLimit, lineY, true));\n          const vI2 = newShapeEdgeVertex(router, new Point(maxShape, lineY));\n          line.vertInfs.insert(vI2);\n        }\n      }\n    } else if (e.type === EventType.ConnPoint && e.v.c === null) {\n      // Midline between facing endpoints — a bare horizontal line.\n      if (!v.isInsideShape(XDIM)) {\n        segments.insert(new LineSegment(v.firstPointAbove(XDIM), v.firstPointBelow(XDIM), e.pos));\n      }\n    } else if (e.type === EventType.ConnPoint) {\n      const centreVert = e.v.c!;\n      const cp = centreVert.point;\n      const minLimit = v.firstPointAbove(XDIM);\n      const maxLimit = v.firstPointBelow(XDIM);\n      const inShape = v.isInsideShape(XDIM);\n\n      let line1: LineSegment | null = null;\n      let line2: LineSegment | null = null;\n      if (centreVert.visDirections.has(Direction.inlineStart) && minLimit < cp.x) {\n        line1 = segments.insert(new LineSegment(minLimit, cp.x, e.pos, true, null, centreVert));\n      }\n      if (centreVert.visDirections.has(Direction.inlineEnd) && cp.x < maxLimit) {\n        line2 = segments.insert(new LineSegment(cp.x, maxLimit, e.pos, true, centreVert, null));\n        // If there was a line1, it was just merged with this one — invalidate.\n        line1 = null;\n      }\n      if (!line1 && !line2) {\n        // Point segment for the centre point.\n        segments.insert(new LineSegment(cp.x, e.pos, centreVert));\n      }\n\n      if (!inShape) {\n        // Add a dummy lattice vertex at the centre too.\n        if (line1 || line2) {\n          const cent = newRoutingVertex(router, cp);\n          if (line1) line1.vertInfs.insert(cent);\n          if (line2) line2.vertInfs.insert(cent);\n        }\n      }\n    }\n  }\n\n  if ((pass === 3 && e.type === EventType.Close) || (pass === 2 && e.type === EventType.ConnPoint)) {\n    const l = v.firstAbove;\n    const r = v.firstBelow;\n    if (l !== null) l.firstBelow = v.firstBelow;\n    if (r !== null) r.firstAbove = v.firstAbove;\n    if (!scanline.erase(v)) {\n      throw new Error('orthogonal: failed to erase Node from scanline');\n    }\n  }\n}\n\nfunction processEventHori(\n  router: Router,\n  scanline: SortedArray<Node>,\n  segments: SegmentListWrapper,\n  e: Event,\n  pass: number,\n): void {\n  const v = e.v;\n\n  if ((pass === 1 && e.type === EventType.Open) || (pass === 2 && e.type === EventType.ConnPoint)) {\n    scanline.insert(v);\n    const above = scanline.prev(v);\n    if (above) {\n      v.firstAbove = above;\n      above.firstBelow = v;\n    }\n    const below = scanline.next(v);\n    if (below) {\n      v.firstBelow = below;\n      below.firstAbove = v;\n    }\n  }\n\n  if (pass === 2) {\n    if (e.type === EventType.Open || e.type === EventType.Close) {\n      const lineX = e.type === EventType.Open ? v.min[XDIM] : v.max[XDIM];\n      const minShape = v.min[YDIM];\n      const maxShape = v.max[YDIM];\n      const limits = v.findFirstPointAboveAndBelow(YDIM, lineX);\n      const minLimit = limits.firstAbove;\n      const maxLimit = limits.firstBelow;\n      const minLimitMax = limits.lastAbove;\n      const maxLimitMin = limits.lastBelow;\n\n      if (minLimitMax >= maxLimitMin) {\n        const line = segments.insert(new LineSegment(minLimit, maxLimit, lineX));\n        const vI1 = newShapeEdgeVertex(router, new Point(lineX, minShape));\n        const vI2 = newShapeEdgeVertex(router, new Point(lineX, maxShape));\n        line.vertInfs.insert(vI1);\n        line.vertInfs.insert(vI2);\n      } else {\n        if (minLimitMax > minLimit && minLimitMax >= minShape) {\n          const line = segments.insert(new LineSegment(minLimit, minLimitMax, lineX));\n          const vI1 = newShapeEdgeVertex(router, new Point(lineX, minShape));\n          line.vertInfs.insert(vI1);\n        }\n        if (maxLimitMin < maxLimit && maxLimitMin <= maxShape) {\n          const line = segments.insert(new LineSegment(maxLimitMin, maxLimit, lineX));\n          const vI2 = newShapeEdgeVertex(router, new Point(lineX, maxShape));\n          line.vertInfs.insert(vI2);\n        }\n      }\n    } else if (e.type === EventType.ConnPoint && e.v.c === null) {\n      // Midline between facing endpoints — a bare vertical line.\n      if (!v.isInsideShape(YDIM)) {\n        segments.insert(new LineSegment(v.firstPointAbove(YDIM), v.firstPointBelow(YDIM), e.pos));\n      }\n    } else if (e.type === EventType.ConnPoint) {\n      const centreVert = e.v.c!;\n      const cp = centreVert.point;\n      const minLimit = v.firstPointAbove(YDIM);\n      const maxLimit = v.firstPointBelow(YDIM);\n      if (centreVert.visDirections.has(Direction.blockStart) && minLimit < cp.y) {\n        segments.insert(new LineSegment(minLimit, cp.y, e.pos));\n      }\n      if (centreVert.visDirections.has(Direction.blockEnd) && cp.y < maxLimit) {\n        segments.insert(new LineSegment(cp.y, maxLimit, e.pos));\n      }\n    }\n  }\n\n  if ((pass === 3 && e.type === EventType.Close) || (pass === 2 && e.type === EventType.ConnPoint)) {\n    const l = v.firstAbove;\n    const r = v.firstBelow;\n    if (l !== null) l.firstBelow = v.firstBelow;\n    if (r !== null) r.firstAbove = v.firstAbove;\n    if (!scanline.erase(v)) {\n      throw new Error('orthogonal: failed to erase Node from scanline');\n    }\n  }\n}\n\n// ─── fixConnectionPointVisibilityOnOutsideOfVisibilityGraph ───────────────────\n\n// Pins or connector endpoints sitting on the leading/trailing edge of the\n// visibility graph may only have visibility in the outward direction (away\n// from the graph).  Add the supplied visibility flags so they can still be\n// reached.\nfunction fixConnectionPointVisibilityOnOutsideOfVisibilityGraph(events: Event[], addedVisibility: Direction): void {\n  const totalEvents = events.length;\n  if (totalEvents === 0) return;\n\n  const firstPos = events[0].pos;\n  let index = 0;\n  while (index < totalEvents) {\n    if (events[index].pos > firstPos) break;\n    if (events[index].v.c) {\n      events[index].v.c!.visDirections = events[index].v.c!.visDirections.add(addedVisibility);\n    }\n    index++;\n  }\n  const lastPos = events[totalEvents - 1].pos;\n  for (let k = 0; k < totalEvents; k++) {\n    const revIndex = totalEvents - 1 - k;\n    if (events[revIndex].pos < lastPos) break;\n    if (events[revIndex].v.c) {\n      events[revIndex].v.c!.visDirections = events[revIndex].v.c!.visDirections.add(addedVisibility);\n    }\n  }\n}\n\n// ─── facingEndpointMidpoints ──────────────────────────────────────────────────\n\n// A connector whose endpoints face each other in `dim` (source pointing\n// towards the target, target open towards the source) but sit at different\n// positions in the other dimension wants a Z-shaped route: out, one crossing\n// segment, in.  The crossing segment has to lie strictly between the two\n// endpoints, and when neither endpoint can turn towards the other there is\n// usually no scanline there — A* then detours past the nearest shape edges\n// and doubles back (see zig-zag-1.svg).  Returns, for each such connector, a\n// point halfway between its endpoints in `dim`, on the source's line in the\n// other dimension; the sweep turns each into a scanline across `dim`.\n//\n// Directions are read before either sweep runs, since\n// `fixConnectionPointVisibilityOnOutsideOfVisibilityGraph` widens them.\nfunction facingEndpointMidpoints(router: Router, dim: number): Point[] {\n  const altDim = 1 - dim;\n  const towardsLow = [Direction.inlineStart, Direction.blockStart];\n  const towardsHigh = [Direction.inlineEnd, Direction.blockEnd];\n\n  const midpoints: Point[] = [];\n  for (const conn of router.connRefs) {\n    const src = conn.src();\n    const dst = conn.dst();\n    if (!src.isConnPoint || !dst.isConnPoint) continue;\n    if (src.point.at(dim) === dst.point.at(dim) || src.point.at(altDim) === dst.point.at(altDim)) continue;\n\n    const [lo, hi] = src.point.at(dim) < dst.point.at(dim) ? [src, dst] : [dst, src];\n    if (!lo.visDirections.has(towardsHigh[dim]) || !hi.visDirections.has(towardsLow[dim])) continue;\n\n    // If either endpoint can turn towards the other, an L-shaped route\n    // through its own scanline already exists.\n    const loBelow = lo.point.at(altDim) < hi.point.at(altDim);\n    if (lo.visDirections.has(loBelow ? towardsHigh[altDim] : towardsLow[altDim])) continue;\n    if (hi.visDirections.has(loBelow ? towardsLow[altDim] : towardsHigh[altDim])) continue;\n\n    const mid = (lo.point.at(dim) + hi.point.at(dim)) / 2;\n    midpoints.push(dim === XDIM ? new Point(mid, src.point.y) : new Point(src.point.x, mid));\n  }\n  return midpoints;\n}\n\n// ─── generateStaticOrthogonalVisGraph ─────────────────────────────────────────\n\n// @brief  Build the static orthogonal visibility graph for the router.\n//\n// Runs two sweepline passes (one per dimension) over every obstacle corner,\n// junction corner (when fixed), and connector endpoint, populating\n// `router.visOrthogGraph` with the lattice of horizontal/vertical visibility\n// edges and tagging every vertex with XL_*/XH_*/YL_*/YH_* property flags.\nexport function generateStaticOrthogonalVisGraph(router: Router): void {\n  const horiMidpoints = facingEndpointMidpoints(router, YDIM);\n  const vertMidpoints = facingEndpointMidpoints(router, XDIM);\n\n  // Annotation groups aren't obstacles — they don't block visibility — but\n  // routes need tracks along their boundaries to skirt them (outer ring) or\n  // to run along their inside edge (inner ring).  Each track point becomes a\n  // scanline in both dimensions, just like the facing-endpoint midpoints.\n  for (const group of router.groups) {\n    const points = group.trackPoints();\n    horiMidpoints.push(...points);\n    vertMidpoints.push(...points);\n  }\n\n  // ── Vertical sweep (events sorted by Y; produces horizontal segments) ──\n\n  let events: Event[] = [];\n  // `router.m_obstacles` only holds shape obstacles and the backing\n  // obstacles that fixed junctions register on the side; free junctions\n  // are deliberately absent (they're not routing barriers).  See\n  // `Junction.setPositionFixed`.\n  for (const obstacle of router.obstacles) {\n    const bbox = obstacle.routingBox();\n    const midX = bbox.min.x + (bbox.max.x - bbox.min.x) / 2;\n    const node = Node.forObstacle(obstacle, midX);\n    events.push(new Event(EventType.Open, node, bbox.min.y));\n    events.push(new Event(EventType.Close, node, bbox.max.y));\n  }\n\n  // Connector endpoints.\n  for (const curr of router.vertices.conns()) {\n    if (curr.visDirections.equal(Direction.zero)) {\n      // Connector endpoint attached to a shape's connection pin — no\n      // visibility needed.\n      continue;\n    }\n    const point = curr.point;\n    const node = Node.forVertex(curr, point.x);\n    events.push(new Event(EventType.ConnPoint, node, point.y));\n  }\n  for (const point of horiMidpoints) {\n    events.push(new Event(EventType.ConnPoint, Node.forPoint(point, point.x), point.y));\n  }\n\n  events.sort(compareEvents);\n\n  fixConnectionPointVisibilityOnOutsideOfVisibilityGraph(events, Direction.inline);\n\n  // Process the vertical sweep — adds candidate horizontal edges.\n  const segments = new SegmentListWrapper();\n  const scanline = new SortedArray<Node>(Node.compare);\n  {\n    const totalEvents = events.length;\n    let thisPos = totalEvents > 0 ? events[0].pos : 0;\n    let posStartIndex = 0;\n    for (let i = 0; i <= totalEvents; i++) {\n      if (i === totalEvents || events[i].pos !== thisPos) {\n        const posFinishIndex = i;\n        for (let pass = 2; pass <= 3; pass++) {\n          for (let j = posStartIndex; j < posFinishIndex; j++) {\n            processEventVert(router, scanline, segments, events[j], pass);\n          }\n        }\n        if (i === totalEvents) break;\n        thisPos = events[i].pos;\n        posStartIndex = i;\n      }\n      processEventVert(router, scanline, segments, events[i], 1);\n    }\n  }\n  if (scanline.size() !== 0) {\n    throw new Error('orthogonal: scanline non-empty after vertical sweep');\n  }\n\n  // Sort the segment list before the horizontal sweep so intersection\n  // testing is deterministic.\n  segments.sort();\n\n  // ── Horizontal sweep (events sorted by X; produces vertical segments) ──\n\n  events = [];\n  for (const obstacle of router.obstacles) {\n    const bbox: Box = obstacle.routingBox();\n    const midY = bbox.min.y + (bbox.max.y - bbox.min.y) / 2;\n    const node = Node.forObstacle(obstacle, midY);\n    events.push(new Event(EventType.Open, node, bbox.min.x));\n    events.push(new Event(EventType.Close, node, bbox.max.x));\n  }\n  for (const curr of router.vertices.conns()) {\n    if (curr.visDirections.equal(Direction.zero)) {\n      continue;\n    }\n    const point = curr.point;\n    const node = Node.forVertex(curr, point.y);\n    events.push(new Event(EventType.ConnPoint, node, point.x));\n  }\n  for (const point of vertMidpoints) {\n    events.push(new Event(EventType.ConnPoint, Node.forPoint(point, point.y), point.x));\n  }\n  events.sort(compareEvents);\n\n  fixConnectionPointVisibilityOnOutsideOfVisibilityGraph(events, Direction.block);\n\n  // Horizontal sweep — vertical edges.\n  {\n    const vertSegments = new SegmentListWrapper();\n    const totalEvents = events.length;\n    let thisPos = totalEvents > 0 ? events[0].pos : 0;\n    let posStartIndex = 0;\n    for (let i = 0; i <= totalEvents; i++) {\n      if (i === totalEvents || events[i].pos !== thisPos) {\n        const posFinishIndex = i;\n        for (let pass = 2; pass <= 3; pass++) {\n          for (let j = posStartIndex; j < posFinishIndex; j++) {\n            processEventHori(router, scanline, vertSegments, events[j], pass);\n          }\n        }\n\n        // Process the merged line segments — for each vertical segment, run\n        // intersect against the horizontal-segment set produced by the\n        // vertical sweep.\n        vertSegments.sort();\n        for (const curr of vertSegments.list()) {\n          intersectSegments(router, segments.list(), curr);\n        }\n        vertSegments.clear();\n\n        if (i === totalEvents) break;\n        thisPos = events[i].pos;\n        posStartIndex = i;\n      }\n      processEventHori(router, scanline, vertSegments, events[i], 1);\n    }\n  }\n  if (scanline.size() !== 0) {\n    throw new Error('orthogonal: scanline non-empty after horizontal sweep');\n  }\n\n  // Commit any horizontal segments still in the list (they extend past the\n  // final vertical sweep position we considered).\n  for (const horiLine of segments.list()) {\n    horiLine.addEdgeHorizontal(router);\n    horiLine.generateVisibilityEdgesFromBreakpointSet(router, XDIM);\n  }\n  segments.clear();\n}\n\n// ─── insideRectBounds ─────────────────────────────────────────────────────────\n\ntype RectBounds = [Point, Point];\n\nfunction insideRectBounds(point: Point, rectBounds: RectBounds): boolean {\n  // Invalid sentinel: zero/zero bounds.\n  if (rectBounds[0].x === 0 && rectBounds[0].y === 0 && rectBounds[1].x === 0 && rectBounds[1].y === 0) {\n    return false;\n  }\n  for (let i = 0; i < 2; i++) {\n    if (point.at(i) < rectBounds[0].at(i)) return false;\n    if (point.at(i) > rectBounds[1].at(i)) return false;\n  }\n  return true;\n}\n\n// ─── buildOrthogonalNudgingSegments ───────────────────────────────────────────\n\n// Walks each orthogonal connector and produces a NudgingShiftSegment for every\n// segment in `dim`.  Segments at route endpoints are made fixed (or shiftable\n// with constrained limits if `nudgeOrthogonalSegmentsConnectedToShapes` is\n// enabled).\nexport function buildOrthogonalNudgingSegments(router: Router, dim: number, segmentList: NudgingShiftSegment[]): void {\n  if (router.params.segmentPenalty === 0) {\n    // The nudging code assumes routes are pretty optimal.  Only true with a\n    // segment penalty.\n    return;\n  }\n  const nudgeFinalSegments = router.options.nudgeOrthogonalSegmentsConnectedToShapes;\n  // Cache routing limits so we don't rebuild them per-segment.  Shapes\n  // contribute their (zero-buffer) bounding boxes; every junction —\n  // whether fixed or free — contributes a degenerate point-rect at its\n  // current position so junction-attached segments pin to that exact\n  // location during nudging.  (Fixed junctions also live in\n  // `m_obstacles` via the obstacle they own, which means they're\n  // technically counted twice here, but a degenerate point-rect is\n  // strictly tighter than the surrounding small obstacle bbox so the\n  // duplicate is harmless.)\n  let shapeLimits: RectBounds[] = [];\n  if (nudgeFinalSegments) {\n    const zeroBufferDist = 0.0;\n    for (const o of router.obstacles) {\n      const bBox = o.polygon.offsetBoundingBox(zeroBufferDist);\n      shapeLimits.push([new Point(bBox.min.x, bBox.min.y), new Point(bBox.max.x, bBox.max.y)]);\n    }\n    for (const j of router.junctions) {\n      const pos = j.position();\n      shapeLimits.push([new Point(pos.x, pos.y), new Point(pos.x, pos.y)]);\n    }\n  }\n\n  const altDim = (dim + 1) % 2;\n\n  for (const conn of router.connRefs) {\n    const displayRoute = conn.displayRoute();\n\n    for (let i = 1; i < displayRoute.size(); i++) {\n      if (displayRoute.ps[i - 1].at(dim) !== displayRoute.ps[i].at(dim)) continue;\n\n      // Segment in our dimension.\n      let indexLow = i - 1;\n      let indexHigh = i;\n      if (displayRoute.ps[i - 1].at(altDim) === displayRoute.ps[i].at(altDim)) {\n        // Zero-length, skip.\n        continue;\n      }\n      if (displayRoute.ps[i - 1].at(altDim) > displayRoute.ps[i].at(altDim)) {\n        indexLow = i;\n        indexHigh = i - 1;\n      }\n\n      const checkpoints = displayRoute.checkpointsOnSegment(i - 1);\n      const prevCheckpoints = displayRoute.checkpointsOnSegment(i - 2, -1);\n      const nextCheckpoints = displayRoute.checkpointsOnSegment(i, +1);\n\n      const hasCheckpoints = checkpoints.length > 0;\n      if (hasCheckpoints && !nudgeFinalSegments) {\n        segmentList.push(new NudgingShiftSegment(conn, indexLow, indexHigh, dim));\n        continue;\n      }\n\n      const thisPos = displayRoute.ps[i].at(dim);\n\n      if (i === 1 || i + 1 === displayRoute.size()) {\n        // First or last segment.\n        if (nudgeFinalSegments) {\n          let minLim = -CHANNEL_MAX;\n          let maxLim = CHANNEL_MAX;\n          let endsInShapes = 0;\n          for (let k = 0; k < shapeLimits.length; k++) {\n            const shapeMin = shapeLimits[k][0].at(dim);\n            const shapeMax = shapeLimits[k][1].at(dim);\n            if (insideRectBounds(displayRoute.ps[i - 1], shapeLimits[k])) {\n              minLim = Math.max(minLim, shapeMin);\n              maxLim = Math.min(maxLim, shapeMax);\n              endsInShapes |= 0x01;\n            }\n            if (insideRectBounds(displayRoute.ps[i], shapeLimits[k])) {\n              minLim = Math.max(minLim, shapeMin);\n              maxLim = Math.min(maxLim, shapeMax);\n              endsInShapes |= 0x10;\n            }\n          }\n          if (endsInShapes === 0) {\n            const pos = displayRoute.ps[i - 1].at(dim);\n            const freeConnBuffer = 15;\n            minLim = Math.max(minLim, pos - freeConnBuffer);\n            maxLim = Math.min(maxLim, pos + freeConnBuffer);\n          }\n          if (minLim === maxLim) {\n            segmentList.push(new NudgingShiftSegment(conn, indexLow, indexHigh, dim));\n          } else {\n            const seg = new NudgingShiftSegment(conn, indexLow, indexHigh, false, false, dim, minLim, maxLim);\n            seg.finalSegment = true;\n            seg.endsInShape = endsInShapes > 0;\n            if (displayRoute.size() === 2 && endsInShapes === 0x11) {\n              seg.singleConnectedSegment = true;\n            }\n            segmentList.push(seg);\n          }\n        } else {\n          segmentList.push(new NudgingShiftSegment(conn, indexLow, indexHigh, dim));\n        }\n        continue;\n      }\n\n      // Inner segment with shifting headroom.\n      let minLim = -CHANNEL_MAX;\n      let maxLim = CHANNEL_MAX;\n\n      for (const cp of nextCheckpoints) {\n        if (cp.at(dim) < thisPos) minLim = Math.max(minLim, cp.at(dim));\n        else if (cp.at(dim) > thisPos) maxLim = Math.min(maxLim, cp.at(dim));\n      }\n      for (const cp of prevCheckpoints) {\n        if (cp.at(dim) < thisPos) minLim = Math.max(minLim, cp.at(dim));\n        else if (cp.at(dim) > thisPos) maxLim = Math.min(maxLim, cp.at(dim));\n      }\n\n      let isSBend = false;\n      let isZBend = false;\n\n      if (checkpoints.length === 0) {\n        const prevPos = displayRoute.ps[i - 2].at(dim);\n        const nextPos = displayRoute.ps[i + 1].at(dim);\n        if ((prevPos < thisPos && nextPos > thisPos) || (prevPos > thisPos && nextPos < thisPos)) {\n          if (prevPos < thisPos && nextPos > thisPos) {\n            minLim = Math.max(minLim, prevPos);\n            maxLim = Math.min(maxLim, nextPos);\n            isZBend = true;\n          } else {\n            minLim = Math.max(minLim, nextPos);\n            maxLim = Math.min(maxLim, prevPos);\n            isSBend = true;\n          }\n        }\n      }\n\n      const nss = new NudgingShiftSegment(conn, indexLow, indexHigh, isSBend, isZBend, dim, minLim, maxLim);\n      nss.checkpoints = checkpoints.slice();\n      segmentList.push(nss);\n    }\n  }\n}\n\n// ─── CmpLineOrder ─────────────────────────────────────────────────────────────\n\n// Comparator for the line-order sort used during nudging.  Orders segments\n// that share a position by their PtOrder map ranking, falling back to\n// fixedOrder / c-bend order for fixed and c-bend segments.\nexport class CmpLineOrder {\n  orders: PtOrderMap;\n  dimension: number;\n\n  constructor(orders: PtOrderMap, dimension: number) {\n    this.orders = orders;\n    this.dimension = dimension;\n  }\n\n  // Returns `{ lessThan, comparable }`.  `comparable` is false when the two\n  // segments can't be ordered against each other.\n  compare(lhsSuper: ShiftSegment, rhsSuper: ShiftSegment): {lessThan: boolean; comparable: boolean} {\n    const lhs = lhsSuper as NudgingShiftSegment;\n    const rhs = rhsSuper as NudgingShiftSegment;\n    let comparable = true;\n    const lhsLow = lhs.lowPoint();\n    const rhsLow = rhs.lowPoint();\n    const altDim = (this.dimension + 1) % 2;\n\n    if (lhsLow.at(this.dimension) !== rhsLow.at(this.dimension)) {\n      return {\n        lessThan: lhsLow.at(this.dimension) < rhsLow.at(this.dimension),\n        comparable,\n      };\n    }\n\n    const lhsFixed = lhs.fixedOrder();\n    const rhsFixed = rhs.fixedOrder();\n    const oneIsFixed = lhsFixed.isFixed || rhsFixed.isFixed;\n    if (oneIsFixed && lhsFixed.order !== rhsFixed.order) {\n      return {lessThan: lhsFixed.order < rhsFixed.order, comparable};\n    }\n\n    const lhsOrder = lhs.order();\n    const rhsOrder = rhs.order();\n    if (lhsOrder !== rhsOrder) {\n      return {lessThan: lhsOrder < rhsOrder, comparable};\n    }\n\n    // Index into the PtOrder map using the original (un-shifted) point of the\n    // one whose altDim is greater.\n    const unchanged = lhsLow.at(altDim) > rhsLow.at(altDim) ? lhsLow : rhsLow;\n    const lowOrder = this.orders.get(unchanged);\n    if (!lowOrder) {\n      // No order recorded for this point — fall back to altDim comparison.\n      comparable = false;\n      return {lessThan: lhsLow.at(altDim) < rhsLow.at(altDim), comparable};\n    }\n    const lhsPos = lowOrder.positionFor(this.dimension, lhs.connRef);\n    const rhsPos = lowOrder.positionFor(this.dimension, rhs.connRef);\n    if (lhsPos === -1 || rhsPos === -1) {\n      comparable = false;\n      return {lessThan: lhsLow.at(altDim) < rhsLow.at(altDim), comparable};\n    }\n    return {lessThan: lhsPos < rhsPos, comparable};\n  }\n}\n\n// ─── linesort ─────────────────────────────────────────────────────────────────\n\n// Insertion-sort variant that tolerates partially-ordered comparisons.\n// Mirrors the C++ algorithm: segments that aren't comparable to anything in\n// the result list are deferred and retried later.\nfunction linesort(\n  nudgeFinalSegments: boolean,\n  origList: NudgingShiftSegment[],\n  comparison: CmpLineOrder,\n): NudgingShiftSegment[] {\n  // Merge end-segments of the same connector that should align.\n  if (nudgeFinalSegments) {\n    for (let i = 0; i < origList.length; i++) {\n      for (let j = i + 1; j < origList.length; ) {\n        const currSeg = origList[i];\n        const otherSeg = origList[j];\n        if (currSeg.shouldAlignWith(otherSeg, comparison.dimension)) {\n          currSeg.mergeWith(otherSeg, comparison.dimension);\n          origList.splice(j, 1);\n        } else {\n          j++;\n        }\n      }\n    }\n  }\n\n  const resultList: NudgingShiftSegment[] = [];\n  let origListSize = origList.length;\n  let deferredN = 0;\n\n  while (origList.length > 0) {\n    const segment = origList.shift()!;\n\n    // Find the insertion point.\n    let allComparable = true;\n    let insertIdx = resultList.length;\n    for (let k = 0; k < resultList.length; k++) {\n      const cmp = comparison.compare(segment, resultList[k]);\n      allComparable = allComparable && cmp.comparable;\n      if (cmp.comparable && cmp.lessThan) {\n        insertIdx = k;\n        break;\n      }\n    }\n\n    if (resultList.length === 0 || allComparable || deferredN >= origListSize) {\n      resultList.splice(insertIdx, 0, segment);\n      deferredN = 0;\n      origListSize = origList.length;\n    } else {\n      origList.push(segment);\n      deferredN++;\n    }\n  }\n\n  return resultList;\n}\n\n// ─── PotentialSegmentConstraint ───────────────────────────────────────────────\n\n// A pair of variable indices marking a candidate \"potential\" equality\n// constraint between two free segments.  Used in the unifying pass to\n// greedily glue free segments to the same position.\nexport class PotentialSegmentConstraint {\n  index1: number;\n  index2: number;\n  vs: Variable[];\n\n  constructor(index1: number, index2: number, vs: Variable[]) {\n    this.index1 = index1;\n    this.index2 = index2;\n    this.vs = vs;\n  }\n\n  sepDistance(): number {\n    if (!this.stillValid()) return 0;\n    return Math.abs(this.vs[this.index1].finalPosition - this.vs[this.index2].finalPosition);\n  }\n\n  stillValid(): boolean {\n    return this.index1 !== this.index2;\n  }\n\n  rewriteIndex(oldIndex: number, newIndex: number): void {\n    if (this.index1 === oldIndex) this.index1 = newIndex;\n    if (this.index2 === oldIndex) this.index2 = newIndex;\n  }\n\n  // Comparator for sorting (smallest separation distance first).\n  static compare(a: PotentialSegmentConstraint, b: PotentialSegmentConstraint): number {\n    const da = a.sepDistance();\n    const db = b.sepDistance();\n    return da < db ? -1 : da > db ? 1 : 0;\n  }\n}\n\n// ─── ImproveOrthogonalRoutes ──────────────────────────────────────────────────\n\n// Detects crossings between every pair of orthogonal connectors and populates\n// `pointOrders` and (optionally) `sharedPathConnectors`.  Called by the\n// orthogonal-nudging pipeline before each main-pass dimension run; see\n// `src/pipeline/orthogonal-steps.ts`.\nexport function buildOrthogonalNudgingOrderInfo(\n  router: Router,\n  pointOrders: PtOrderMap,\n  sharedPathConnectors: UnsignedPairSet,\n): void {\n  // Pre-pass: simplify routes (matches the C++ flow — every order build is\n  // preceded by a fresh simplify).\n  for (const conn of router.connRefs) {\n    conn.set_route(conn.displayRoute().simplify());\n  }\n\n  // The C++ source tallies a `crossingsN` counter for debug printing; we\n  // drop it but still need to walk every connector pair for the side\n  // effects on `pointOrders` and the shared-path set.\n  const buildSharedPathInfo = !router.options.nudgeSharedPathsWithCommonEndPoint && sharedPathConnectors.size() === 0;\n\n  const connRefs = router.connRefs.slice();\n  // Clone the routes — splitBranchingSegments mutates the polygons, but the\n  // C++ `connRoutes[ind] = connRefs[ind]->displayRoute()` makes a copy via\n  // Polygon copy-assignment, so we do the same here.\n  const connRoutes: Polygon[] = connRefs.map(c => c.displayRoute().clone());\n\n  // Segment splitting.\n  for (let i1 = 0; i1 < connRefs.length; i1++) {\n    for (let i2 = 0; i2 < connRefs.length; i2++) {\n      if (i1 === i2) continue;\n      const route = connRoutes[i1];\n      const route2 = connRoutes[i2];\n      splitBranchingSegments(route2, true, route);\n    }\n  }\n\n  // Crossing detection.\n  for (let i1 = 0; i1 < connRefs.length; i1++) {\n    const conn = connRefs[i1];\n    for (let i2 = i1 + 1; i2 < connRefs.length; i2++) {\n      const conn2 = connRefs[i2];\n      const route = connRoutes[i1];\n      const route2 = connRoutes[i2];\n      let crossingFlags = 0;\n      const cross = new ConnectorCrossings(route2, true, route, conn2, conn);\n      cross.pointOrders = pointOrders;\n      for (let i = 1; i < route.size(); i++) {\n        const finalSegment = i + 1 === route.size();\n        cross.countForSegment(i, finalSegment);\n        crossingFlags |= cross.crossingFlags;\n      }\n      if (buildSharedPathInfo && crossingFlags & CROSSING_SHARES_PATH_AT_END) {\n        sharedPathConnectors.insert(new UnsignedPair(conn._id, conn2._id));\n      }\n    }\n  }\n}\n\n// Main nudging pass for one dimension.  Walks `segmentList` to greedily\n// build \"regions\" of overlapping segments, runs VPSC on each, and commits\n// the solver result back to the constituent segments.\nexport function nudgeOrthogonalRoutes(\n  router: Router,\n  segmentList: NudgingShiftSegment[],\n  pointOrders: PtOrderMap,\n  sharedPathConnectors: UnsignedPairSet,\n  dimension: number,\n  justUnifying: boolean,\n): void {\n  const nudgeFinalSegments = router.options.nudgeOrthogonalSegmentsConnectedToShapes;\n  const nudgeSharedPathsWithCommonEnd = router.options.nudgeSharedPathsWithCommonEndPoint;\n  const baseSepDist = router.params.idealNudgingDistance;\n  if (baseSepDist < 0) {\n    throw new Error('orthogonal: baseSepDist must be >= 0');\n  }\n  const reductionSteps = 10.0;\n\n  while (segmentList.length > 0) {\n    const currentSegment = segmentList[0];\n    const currentRegion: NudgingShiftSegment[] = [currentSegment];\n    segmentList.splice(0, 1);\n\n    // Greedy region expansion — find every segment overlapping anyone\n    // already in the region, restart from the beginning each time.\n    let kIndex = 0;\n    while (kIndex < segmentList.length) {\n      let overlaps = false;\n      for (const inRegion of currentRegion) {\n        if (segmentList[kIndex].overlapsWith(inRegion, dimension)) {\n          overlaps = true;\n          break;\n        }\n      }\n      if (overlaps) {\n        currentRegion.push(segmentList[kIndex]);\n        segmentList.splice(kIndex, 1);\n        kIndex = 0;\n      } else {\n        kIndex++;\n      }\n    }\n\n    let sortedRegion = currentRegion;\n    if (!justUnifying) {\n      const cmp = new CmpLineOrder(pointOrders, dimension);\n      sortedRegion = linesort(nudgeFinalSegments, currentRegion.slice(), cmp);\n    }\n\n    if (sortedRegion.length === 1) {\n      if (sortedRegion[0].immovable() || justUnifying) {\n        continue;\n      }\n    }\n\n    // Build VPSC variables/constraints.\n    const freeIndexes: number[] = [];\n    const vs: Variable[] = [];\n    const cs: Constraint[] = [];\n    const gapcs: Constraint[] = [];\n    const prevVars: NudgingShiftSegment[] = [];\n    let sepDist = baseSepDist;\n\n    for (const currSegment of sortedRegion) {\n      currSegment.createSolverVariable(justUnifying);\n      vs.push(currSegment.variable!);\n      const index = vs.length - 1;\n\n      if (justUnifying) {\n        if (currSegment.variable!.weight === freeWeight) {\n          freeIndexes.push(index);\n        }\n        prevVars.push(currSegment);\n        continue;\n      }\n\n      // Channel boundary left.\n      if (!currSegment.fixed) {\n        if (currSegment.minSpaceLimit > -CHANNEL_MAX) {\n          vs.push(new Variable(channelLeftID, currSegment.minSpaceLimit, fixedWeight));\n          cs.push(new Constraint(vs[vs.length - 1], vs[index], 0.0));\n        }\n      }\n\n      // Constrain against previously-seen segments.\n      for (const prevSeg of prevVars) {\n        const prevVar = prevSeg.variable!;\n        if (currSegment.overlapsWith(prevSeg, dimension) && !(currSegment.fixed && prevSeg.fixed)) {\n          let thisSepDist = sepDist;\n          let equality = false;\n          if (currSegment.shouldAlignWith(prevSeg, dimension)) {\n            thisSepDist = 0;\n            equality = true;\n          } else if (currSegment.canAlignWith(prevSeg, dimension)) {\n            thisSepDist = 0;\n          } else if (\n            !nudgeSharedPathsWithCommonEnd &&\n            sharedPathConnectors.has(new UnsignedPair(currSegment.connRef._id, prevSeg.connRef._id))\n          ) {\n            thisSepDist = 0;\n            equality = true;\n          }\n          const constraint = new Constraint(prevVar, vs[index], thisSepDist, equality);\n          cs.push(constraint);\n          if (thisSepDist) gapcs.push(constraint);\n        }\n      }\n\n      // Channel boundary right.\n      if (!currSegment.fixed) {\n        if (currSegment.maxSpaceLimit < CHANNEL_MAX) {\n          vs.push(new Variable(channelRightID, currSegment.maxSpaceLimit, fixedWeight));\n          cs.push(new Constraint(vs[index], vs[vs.length - 1], 0.0));\n        }\n      }\n\n      prevVars.push(currSegment);\n    }\n\n    // Potential constraints between free indexes (unifying pass only).\n    const potentialConstraints: PotentialSegmentConstraint[] = [];\n    if (justUnifying) {\n      for (let p = 0; p < freeIndexes.length; p++) {\n        for (let q = p + 1; q < freeIndexes.length; q++) {\n          potentialConstraints.push(new PotentialSegmentConstraint(freeIndexes[p], freeIndexes[q], vs));\n        }\n      }\n    }\n\n    // Solve repeatedly, either greedy-add (unifying) or reduce-separation\n    // (nudging) until the constraint set is satisfied.\n    let justAddedConstraint = false;\n    let satisfied = false;\n\n    type UnsatRange = [number, number];\n    let unsatisfiedRanges: UnsatRange[] = [];\n\n    // Defensive iteration cap — should never trigger but prevents pathological\n    // input from infinite-looping.\n    let iter = 0;\n    const ITER_CAP = 200;\n\n    do {\n      iter++;\n      if (iter > ITER_CAP) break;\n\n      try {\n        const f = new IncSolver(vs, cs);\n        f.solve();\n      } catch {\n        // VPSC unsatisfiable — bail out of this region.\n        break;\n      }\n\n      unsatisfiedRanges = [];\n      satisfied = true;\n      for (let i = 0; i < vs.length; i++) {\n        if (vs[i].id === freeSegmentID) continue;\n        if (Math.abs(vs[i].finalPosition - vs[i].desiredPosition) <= 0.0001) continue;\n        satisfied = false;\n        if (vs[i].id === channelLeftID) {\n          if (\n            unsatisfiedRanges.length === 0 ||\n            unsatisfiedRanges[unsatisfiedRanges.length - 1][0] !== unsatisfiedRanges[unsatisfiedRanges.length - 1][1]\n          ) {\n            unsatisfiedRanges.push([i, i + 1]);\n          }\n        } else if (vs[i].id === channelRightID) {\n          if (unsatisfiedRanges.length === 0) {\n            if (i === 0 || vs[i - 1].id !== channelLeftID) {\n              throw new Error('orthogonal: channelRight without channelLeft');\n            }\n            unsatisfiedRanges.push([i - 1, i]);\n          } else {\n            unsatisfiedRanges[unsatisfiedRanges.length - 1][1] = i;\n          }\n        } else if (vs[i].id === fixedSegmentID) {\n          if (unsatisfiedRanges.length === 0) {\n            unsatisfiedRanges.push([i, i]);\n          } else {\n            unsatisfiedRanges[unsatisfiedRanges.length - 1][1] = i;\n          }\n        }\n      }\n\n      if (justUnifying) {\n        if (justAddedConstraint) {\n          if (potentialConstraints.length === 0) {\n            throw new Error('orthogonal: lost potentialConstraints front');\n          }\n          if (!satisfied) {\n            // Roll back the just-added constraint.\n            potentialConstraints.shift();\n            cs.pop();\n          } else {\n            const pc = potentialConstraints[0]!;\n            for (const it of potentialConstraints) {\n              it.rewriteIndex(pc.index1, pc.index2);\n            }\n            potentialConstraints.shift();\n          }\n        }\n        potentialConstraints.sort(PotentialSegmentConstraint.compare);\n        justAddedConstraint = false;\n        while (potentialConstraints.length > 0 && !potentialConstraints[0].stillValid()) {\n          potentialConstraints.shift();\n        }\n        if (potentialConstraints.length > 0) {\n          const pc = potentialConstraints[0];\n          if (pc.index1 === pc.index2) {\n            throw new Error('orthogonal: pc invariant');\n          }\n          cs.push(new Constraint(vs[pc.index1], vs[pc.index2], 0, true));\n          satisfied = false;\n          justAddedConstraint = true;\n        }\n      } else if (!satisfied) {\n        if (unsatisfiedRanges.length === 0) {\n          // Shouldn't happen; bail to avoid loop.\n          break;\n        }\n        sepDist -= baseSepDist / reductionSteps;\n        let withinUnsatisfied = false;\n        let rangeIdx = 0;\n        for (const constraint of cs) {\n          if (rangeIdx >= unsatisfiedRanges.length) break;\n          const range = unsatisfiedRanges[rangeIdx];\n          if (constraint.left === vs[range[0]]) withinUnsatisfied = true;\n          if (withinUnsatisfied && constraint.gap > 0) {\n            constraint.gap = sepDist;\n          }\n          if (constraint.right === vs[range[1]]) {\n            withinUnsatisfied = false;\n            rangeIdx++;\n          }\n        }\n      }\n    } while (!satisfied && sepDist > 0.0001);\n\n    if (satisfied) {\n      for (const seg of sortedRegion) {\n        seg.updatePositionsFromSolver(justUnifying);\n      }\n    }\n  }\n}\n\n// ─── Internal testing exports ─────────────────────────────────────────────────\n\nexport const _testing = {\n  UnsignedPair,\n  UnsignedPairSet,\n  CmpIndexes,\n  LineSegment,\n  CmpLineOrder,\n  PotentialSegmentConstraint,\n  SegmentListWrapper,\n  PosVertInf,\n  intersectSegments,\n  insideRectBounds,\n  linesort,\n  freeSegmentID,\n  fixedSegmentID,\n  channelLeftID,\n  channelRightID,\n  freeWeight,\n  strongWeight,\n  fixedWeight,\n  VisDirNone,\n  VisDirUp,\n  VisDirDown,\n};\n","// ─── Orthogonal-routing improvement pipeline steps ──────────────────────────\n//\n// Decomposes `ImproveOrthogonalRoutes.execute()` (formerly a single class\n// method, ~300 lines including helpers) into named steps over a shared\n// `OrthogonalContext`.  The outer pipeline owns the top-level sequence; an\n// inner per-dimension pipeline (driven by `UnifyingPreprocessingStep` and\n// `MainNudgingStep`) owns the alternating-axis loops.\n//\n// State flow:\n//   • `pointOrders` — populated by `buildOrthogonalNudgingOrderInfo` before\n//     each main-pass dimension run; consumed by `nudgeOrthogonalRoutes` via\n//     `CmpLineOrder`.\n//   • `sharedPathConnectors` — populated once per execute() across both\n//     dimensions (size() > 0 short-circuits subsequent rebuilds).\n//   • `segmentList` — rebuilt fresh for every dimension pass; consumed by\n//     channel-info computation and nudging.\n\nimport {Step, Pipeline} from '../pipeline';\nimport {\n  UnsignedPairSet,\n  buildOrthogonalNudgingSegments,\n  buildOrthogonalNudgingOrderInfo,\n  nudgeOrthogonalRoutes,\n} from '../orthogonal';\nimport {\n  buildOrthogonalChannelInfo,\n  buildConnectorRouteCheckpointCache,\n  clearConnectorRouteCheckpointCache,\n} from '../scanline';\nimport type {Router} from '../router';\nimport type {NudgingShiftSegment} from '../utilities/nudging-shift-segment';\nimport {PtOrderMap} from '../data-structures/PtOrder';\n\nexport class OrthogonalContext {\n  // Cross-dimension state — accumulated by `buildOrthogonalNudgingOrderInfo`\n  // and read by the nudger.  Reset between unifying and main phases.\n  pointOrders: PtOrderMap = new PtOrderMap();\n  sharedPathConnectors: UnsignedPairSet = new UnsignedPairSet();\n\n  // Per-pass state — rebuilt by `BuildNudgingSegmentsStep` before each\n  // dimension's channel-info computation and nudge run.\n  segmentList: NudgingShiftSegment[] = [];\n\n  // Set by the wrapping outer step (UnifyingPreprocessing or MainNudging)\n  // before invoking the inner per-dimension pipeline.\n  dimension = 0;\n  justUnifying = false;\n\n  constructor(readonly router: Router) {}\n}\n\n// ─── Outer-pipeline steps ─────────────────────────────────────────────────────\n\n// Reset the shared-path connector set and simplify every connector's display\n// route in place.  Both are pre-conditions of the algorithm — the C++ source\n// starts with the exact same two operations.\nclass ClearAndSimplifyStep extends Step<OrthogonalContext> {\n  readonly name = 'Clear state & simplify routes';\n\n  execute(ctx: OrthogonalContext): void {\n    ctx.sharedPathConnectors.clear();\n    for (const conn of ctx.router.connRefs) {\n      conn.set_route(conn.displayRoute().simplify());\n    }\n  }\n}\n\n// Build the connector-route checkpoint cache so segment-checkpoint lookups\n// stay valid across the in-place mutations the nudger performs.\nclass BuildCheckpointCacheStep extends Step<OrthogonalContext> {\n  readonly name = 'Build connector-route checkpoint cache';\n\n  execute(ctx: OrthogonalContext): void {\n    buildConnectorRouteCheckpointCache(ctx.router);\n  }\n}\n\n// Unifying preprocessing — greedy free-segment co-position.  Two dimension\n// passes (X, Y) running the inner per-dimension pipeline with\n// `justUnifying = true`.  Skipped when the option is off or fixed-shared-path\n// penalty is non-zero (the C++ logic).\nclass UnifyingPreprocessingStep extends Step<OrthogonalContext> {\n  readonly name = 'Unifying preprocessing (2 passes)';\n\n  shouldRun(ctx: OrthogonalContext): boolean {\n    return ctx.router.options.performUnifyingNudgingPreprocessingStep && ctx.router.params.fixedSharedPathPenalty === 0;\n  }\n\n  execute(ctx: OrthogonalContext): void {\n    ctx.justUnifying = true;\n    for (let dim = 0; dim < 2; dim++) {\n      ctx.dimension = dim;\n      PER_DIMENSION_PIPELINE.run(ctx);\n    }\n  }\n}\n\n// Main nudging passes — two dimension iterations (X, Y).  Each starts by\n// rebuilding `pointOrders` (with a fresh map every iteration), then runs the\n// same inner pipeline used by the unifying step — only `justUnifying` flips.\nclass MainNudgingStep extends Step<OrthogonalContext> {\n  readonly name = 'Main nudging (2 passes, alternating X/Y)';\n\n  execute(ctx: OrthogonalContext): void {\n    ctx.justUnifying = false;\n    for (let dim = 0; dim < 2; dim++) {\n      ctx.dimension = dim;\n      ctx.pointOrders = new PtOrderMap();\n      buildOrthogonalNudgingOrderInfo(ctx.router, ctx.pointOrders, ctx.sharedPathConnectors);\n      PER_DIMENSION_PIPELINE.run(ctx);\n    }\n  }\n}\n\n// Re-simplify every connector route after the nudger has done its work.\nclass FinalSimplifyStep extends Step<OrthogonalContext> {\n  readonly name = 'Simplify routes (post-nudge)';\n\n  execute(ctx: OrthogonalContext): void {\n    for (const conn of ctx.router.connRefs) {\n      conn.set_route(conn.displayRoute().simplify());\n    }\n  }\n}\n\n// Drop the checkpoint cache built earlier — it has no purpose outside this\n// pipeline and would otherwise leak connector references.\nclass ClearCheckpointCacheStep extends Step<OrthogonalContext> {\n  readonly name = 'Clear connector-route checkpoint cache';\n\n  execute(ctx: OrthogonalContext): void {\n    clearConnectorRouteCheckpointCache(ctx.router);\n  }\n}\n\n// ─── Inner per-dimension pipeline steps ──────────────────────────────────────\n\n// Rebuild `segmentList` from scratch for this dimension.  The nudger consumes\n// segments destructively (splices them out as it processes regions), so each\n// pass needs a fresh list.\nclass BuildNudgingSegmentsStep extends Step<OrthogonalContext> {\n  readonly name = 'Build nudging segments';\n\n  execute(ctx: OrthogonalContext): void {\n    ctx.segmentList = [];\n    buildOrthogonalNudgingSegments(ctx.router, ctx.dimension, ctx.segmentList);\n  }\n}\n\n// Compute channel limits for each segment via the scanline algorithm.  Sets\n// `minSpaceLimit` / `maxSpaceLimit` on every entry in `segmentList`.\nclass BuildChannelInfoStep extends Step<OrthogonalContext> {\n  readonly name = 'Build orthogonal channel info';\n\n  execute(ctx: OrthogonalContext): void {\n    buildOrthogonalChannelInfo(ctx.router, ctx.dimension, ctx.segmentList);\n  }\n}\n\n// Run the VPSC-based nudging algorithm on this dimension's segments.  The\n// substantial work — region expansion, variable/constraint construction,\n// solver loop, position commit — lives in `orthogonal.ts` as a free function\n// (its data dependencies are intimate with the orthogonal module's internal\n// types).  This step is a thin invoke + the surrounding pipeline gives it a\n// name and a slot in the flow.\nclass NudgeRoutesStep extends Step<OrthogonalContext> {\n  readonly name = 'Nudge orthogonal routes';\n\n  execute(ctx: OrthogonalContext): void {\n    nudgeOrthogonalRoutes(\n      ctx.router,\n      ctx.segmentList,\n      ctx.pointOrders,\n      ctx.sharedPathConnectors,\n      ctx.dimension,\n      ctx.justUnifying,\n    );\n  }\n}\n\n// Inner pipeline run once per axis by both `UnifyingPreprocessingStep` and\n// `MainNudgingStep`.  The wrapping step sets `ctx.dimension` and\n// `ctx.justUnifying` before each invocation.\nconst PER_DIMENSION_PIPELINE = new Pipeline<OrthogonalContext>([\n  new BuildNudgingSegmentsStep(),\n  new BuildChannelInfoStep(),\n  new NudgeRoutesStep(),\n]);\n\n// ─── Outer pipeline ──────────────────────────────────────────────────────────\n\nexport const ORTHOGONAL_PIPELINE = new Pipeline<OrthogonalContext>([\n  new ClearAndSimplifyStep(),\n  new BuildCheckpointCacheStep(),\n  new UnifyingPreprocessingStep(),\n  new MainNudgingStep(),\n  new FinalSimplifyStep(),\n  new ClearCheckpointCacheStep(),\n]);\n","// ─── Route pipeline steps ────────────────────────────────────────────────────\n//\n// The ordered list of `Step`s that make up `Router.route()`.  Each step takes\n// a `RouteContext` — the router plus the per-run scratch slots (`rerouted`,\n// `hyperedgeRerouter`, `anyChange`).\n\nimport {Step, Pipeline} from '../pipeline';\nimport {HyperedgeRerouter, computeCrossingCosts} from '../hyperedge';\nimport {improveCrossings} from '../improveCrossings';\nimport {HyperedgeImprover} from '../hyperedgeimprover';\nimport {IMPROVER_PIPELINE, ImproverContext} from './improver-steps';\nimport {ORTHOGONAL_PIPELINE, OrthogonalContext} from './orthogonal-steps';\nimport {generateStaticOrthogonalVisGraph} from '../orthogonal';\nimport type {Router} from '../router';\nimport type {Edge} from '../models/edge';\n\n// Rebuilds the static orthogonal visibility graph from scratch.  Inlined into\n// every step that needs it — the previous `Router.regenerateStaticBuiltGraph`\n// helper was a thin 2-liner and lived purely as a convenience for these\n// callers.\nfunction rebuildVisGraph(router: Router): void {\n  router.visOrthogGraph.clear();\n  generateStaticOrthogonalVisGraph(router);\n}\n\nexport class RouteContext {\n  rerouted: Set<Edge> = new Set();\n  hyperedgeRerouter: HyperedgeRerouter | null = null;\n  anyChange = false;\n\n  constructor(readonly router: Router) {}\n}\n\n// 1. Rebuild the static orthogonal visibility graph.  This is the baseline —\n//    everything downstream A*'s against the graph this step produces.\nclass RegenerateVisGraphStep extends Step<RouteContext> {\n  readonly name: string;\n\n  constructor(name = 'Regenerate visibility graph') {\n    super();\n    this.name = name;\n  }\n\n  execute(ctx: RouteContext): void {\n    rebuildVisGraph(ctx.router);\n  }\n}\n\n// 2. Set up `HyperedgeRerouter` and snapshot which connectors it will tear\n//    down / replace.  Skipped when no hyperedges are queued.  If MTST\n//    injected new terminal vertices, rebuild the visgraph so they show up.\nclass PrepareHyperedgeReroutingStep extends Step<RouteContext> {\n  readonly name = 'Prepare hyperedge rerouting';\n\n  shouldRun(ctx: RouteContext): boolean {\n    return ctx.router.hyperedgesForRerouting.length > 0;\n  }\n\n  execute(ctx: RouteContext): void {\n    ctx.hyperedgeRerouter = new HyperedgeRerouter(ctx.router, ctx.router.hyperedgesForRerouting);\n    let {edges, addedVertices} = ctx.hyperedgeRerouter.calcHyperedgeConnectors();\n    ctx.rerouted = edges;\n    if (addedVertices.length > 0) {\n      rebuildVisGraph(ctx.router);\n    }\n  }\n}\n\n// 3. Route every non-hyperedge connector before MTST runs.  Their\n//    `displayRoute()`s become inputs to the hyperedge rerouter so MTST can\n//    weight crossings against them (Stage 2+).  Connectors the rerouter is\n//    going to delete are skipped.\n//\n//    `computeCrossingCosts` first stamps crossing costs onto vis-graph edges\n//    so this A* pass is also crossing-aware against any routes already in\n//    `displayRoute()` from a prior `route()` call.  On a fresh router this is\n//    a no-op (all routes are empty).\nclass InitialAStarPassStep extends Step<RouteContext> {\n  readonly name = 'Initial A* pass';\n\n  execute(ctx: RouteContext): void {\n    computeCrossingCosts(ctx.router, ctx.rerouted);\n    const snapshot = ctx.router.connRefs.slice();\n    for (const conn of snapshot) {\n      if (ctx.rerouted.has(conn)) continue;\n      if (conn.generatePath()) ctx.anyChange = true;\n    }\n  }\n}\n\n// 4. Run the hyperedge rerouter (MTST + new ConnRefs at the Steiner points),\n//    then rebuild the visgraph and re-stamp crossing costs so the refinement\n//    A* pass below sees the new junctions / vertices and can avoid crossing\n//    the user routes from step 3.  Skipped when no hyperedge rerouter was\n//    prepared.\nclass HyperedgeReroutingStep extends Step<RouteContext> {\n  readonly name = 'Hyperedge rerouting';\n\n  shouldRun(ctx: RouteContext): boolean {\n    return ctx.hyperedgeRerouter !== null;\n  }\n\n  execute(ctx: RouteContext): void {\n    ctx.hyperedgeRerouter!.performRerouting();\n    // performRerouting() creates fresh JunctionRefs (at the Steiner points\n    // chosen by MTST) and fresh ConnRefs — their centre vertices and\n    // endpoint vertices land in `router.vertices`, but the orthogonal vis\n    // graph was built before any of that existed.  Rebuild so the\n    // refinement A* pass can see them.\n    rebuildVisGraph(ctx.router);\n\n    // Re-stamp crossing costs onto the freshly-rebuilt vis-graph so the\n    // refinement A* pass can avoid crossing the already-routed user\n    // connectors (the previous stamping was wiped by the rebuild — every\n    // EdgeInf above is brand new).  Skip-set is empty because every\n    // connector still in `connRefs` is routed and its displayRoute() is\n    // something we want to avoid crossing.\n    computeCrossingCosts(ctx.router, new Set());\n\n    // Route the new ConnRefs the rerouter just created.  Their\n    // `_needsRerouteFlag` is `true` from construction; the previously-routed\n    // user connectors have `_needsRerouteFlag === false`, so `generatePath`\n    // is a no-op for them — only the new connectors get A*'d here.\n    for (const edge of Array.from(ctx.router.connRefs)) {\n      if (!ctx.rerouted.has(edge) && edge.generatePath()) {\n        ctx.anyChange = true;\n      }\n    }\n  }\n}\n\n// 5. Walk every pair of routed connectors, peel out a minimal set whose\n//    routes cross (or share fixed segments), and re-run A* on them with\n//    `isInCrossingPenaltyReroutingStage()` flipped on so makepath's per-step\n//    crossing/shared-path penalties kick in.  No-op when both crossing-style\n//    penalties are zero.\n//\n//    With `renudge`, any connector rerouted here is fresh A* output sitting on\n//    visibility-graph lines, so it can lie right on top of a connector that\n//    was already nudged.  Re-run the nudging pipeline to separate them again.\nclass ImproveCrossingsStep extends Step<RouteContext> {\n  readonly name: string;\n  readonly renudge: boolean;\n\n  constructor(name = 'Improve crossings', {renudge = false} = {}) {\n    super();\n    this.name = name;\n    this.renudge = renudge;\n  }\n\n  execute(ctx: RouteContext): void {\n    const rerouted = improveCrossings(ctx.router);\n    if (rerouted && this.renudge) {\n      ORTHOGONAL_PIPELINE.run(new OrthogonalContext(ctx.router));\n    }\n  }\n}\n\n// 6. Hyperedge-tree local-improvement pass.  Slides junctions along common\n//    edges and nudges parallel segments toward the channel midline.  May\n//    move junctions via `_setPosition`, which drags each junction's centre\n//    vertex along — the visgraph still indexes neighbours at the OLD\n//    junction position, so we rebuild after.  Skipped unless one of the\n//    `improveHyperedgeRoutes*` options is on.\nclass HyperedgeImproverStep extends Step<RouteContext> {\n  readonly name = 'Hyperedge improver';\n\n  shouldRun(ctx: RouteContext): boolean {\n    return (\n      ctx.router.options.improveHyperedgeRoutesMovingAddingAndDeletingJunctions ||\n      ctx.router.options.improveHyperedgeRoutesMovingJunctions\n    );\n  }\n\n  execute(ctx: RouteContext): void {\n    // The improver is a typed bag of per-run state (tree maps, shift-segment\n    // lists); the algorithm itself lives in `improver-steps.ts`.  Allocate\n    // an improver, wrap it in an ImproverContext, and run the inner pipeline.\n    const improver = new HyperedgeImprover(ctx.router);\n    const improverCtx = new ImproverContext(improver);\n    IMPROVER_PIPELINE.run(improverCtx);\n\n    // The improver may have moved junctions via `_setPosition`, which drags\n    // each junction's centre vertex along with it.  The visibility graph\n    // built before the improver ran still indexes the centre vertex's\n    // neighbours at the OLD junction position, though — so the orthogVisList\n    // contains edges that no longer touch the centre vertex's new position.\n    // Without a rebuild, the second `improveCrossings` pass below would A*\n    // along those stale edges and emit non-orthogonal diagonal segments\n    // (see sludeg-1.svg).  Mirrors what libavoid C++ achieves via\n    // `Router::moveJunction` → `setNewPoly` → `newBlockingShape`.\n    rebuildVisGraph(ctx.router);\n  }\n}\n\n// 7. Orthogonal nudging pass — centring and channel-share routing.  May\n//    introduce crossings (parallel segments centred onto the same midline);\n//    a final `ImproveCrossingsStep` below cleans those up.  The actual\n//    algorithm lives in `src/pipeline/orthogonal-steps.ts` as its own\n//    pipeline; this step just allocates the context and runs it.\nclass OrthogonalNudgingStep extends Step<RouteContext> {\n  readonly name = 'Nudge orthogonal segments';\n\n  execute(ctx: RouteContext): void {\n    const orthoCtx = new OrthogonalContext(ctx.router);\n    ORTHOGONAL_PIPELINE.run(orthoCtx);\n  }\n}\n\n// The route pipeline itself.  Construct once at module load — every router\n// invocation reuses the same step instances.  Steps hold no per-run state;\n// everything mutable lives on `RouteContext`.\nexport const ROUTE_PIPELINE = new Pipeline<RouteContext>([\n  new RegenerateVisGraphStep(),\n  new PrepareHyperedgeReroutingStep(),\n  new InitialAStarPassStep(),\n  new HyperedgeReroutingStep(),\n  new ImproveCrossingsStep('Improve crossings (post-MTST)'),\n  new HyperedgeImproverStep(),\n  new OrthogonalNudgingStep(),\n  new ImproveCrossingsStep('Improve crossings (post-nudge)', {renudge: true}),\n]);\n","import {VertInfList} from './vertex.ts';\nimport {EdgeList} from './graph.ts';\nimport {Obstacle} from './models/obstacle.ts';\nimport {AnnotationGroup} from './models/annotation-group.ts';\n\nimport {Junction} from './models/junction.ts';\nimport {ROUTE_PIPELINE, RouteContext} from './pipeline/route-steps.ts';\n\nimport type {Edge} from './models/edge.ts';\nimport type {Rect} from './geomtypes.ts';\nimport type {Hyperedge} from './hyperedge.ts';\n\nexport type RoutingParams = {\n  segmentPenalty: number;\n  crossingPenalty: number;\n  fixedSharedPathPenalty: number;\n  portDirectionPenalty: number;\n  shapeBufferDistance: number;\n  idealNudgingDistance: number;\n  reverseDirectionPenalty: number;\n  // Cost of each crossing of an annotation group's boundary.  Crossings an\n  // edge can't avoid (its endpoint is inside the group) are paid by every\n  // candidate route alike, so this only discourages cutting through groups.\n  groupCrossingPenalty: number;\n  // Extra cost per unit of route length inside an annotation group (on top\n  // of the length itself).  Makes edges entering a group do so near their\n  // endpoint instead of threading through it.\n  groupInteriorCost: number;\n  // Offset of the routing tracks placed just outside and just inside each\n  // annotation group.  Defaults to `shapeBufferDistance`.\n  groupBufferDistance?: number;\n};\n\nexport type RoutingOptions = {\n  nudgeOrthogonalSegmentsConnectedToShapes: boolean;\n  improveHyperedgeRoutesMovingJunctions: boolean;\n  penaliseOrthogonalSharedPathsAtConnEnds: boolean;\n  nudgeOrthogonalTouchingColinearSegments: boolean;\n  performUnifyingNudgingPreprocessingStep: boolean;\n  improveHyperedgeRoutesMovingAddingAndDeletingJunctions: boolean;\n  nudgeSharedPathsWithCommonEndPoint: boolean;\n};\n\nexport class Router<EdgeUserData = unknown, JunctionUserData = unknown> {\n  junctions = new Set<Junction>();\n  obstacles: Obstacle[];\n  groups: AnnotationGroup[] = [];\n  connRefs: Edge<EdgeUserData>[];\n  visOrthogGraph: EdgeList;\n  vertices: VertInfList;\n\n  // General routing options:\n\n  params: RoutingParams;\n  options: RoutingOptions;\n  hyperedgesForRerouting: Hyperedge[] = [];\n\n  private _nextObjectId: number;\n  private m_in_crossing_rerouting_stage: boolean;\n\n  constructor(params: Partial<RoutingParams> = {}, options: Partial<RoutingOptions> = {}) {\n    this.params = Object.assign(\n      {\n        segmentPenalty: 10,\n        idealNudgingDistance: 4,\n        crossingPenalty: 0, // Sensable default: 200,\n        fixedSharedPathPenalty: 0, // Sensable default: 110,\n        portDirectionPenalty: 0, // Sensable default: 100,\n        shapeBufferDistance: 0, // Sensable default: 50,\n        reverseDirectionPenalty: 0, // Sensable default: 50,\n        groupCrossingPenalty: 200,\n        groupInteriorCost: 1,\n      },\n      params,\n    );\n\n    this.options = Object.assign(\n      {\n        nudgeOrthogonalSegmentsConnectedToShapes: false,\n        improveHyperedgeRoutesMovingJunctions: true,\n        penaliseOrthogonalSharedPathsAtConnEnds: false,\n        nudgeOrthogonalTouchingColinearSegments: false,\n        performUnifyingNudgingPreprocessingStep: true,\n        improveHyperedgeRoutesMovingAddingAndDeletingJunctions: false,\n        nudgeSharedPathsWithCommonEndPoint: true,\n      },\n      options,\n    );\n\n    this.obstacles = [];\n    this.connRefs = [];\n    this.visOrthogGraph = new EdgeList();\n    this.vertices = new VertInfList();\n\n    this._nextObjectId = 1;\n    this.m_in_crossing_rerouting_stage = false;\n  }\n\n  // ─── Internal object-id assignment ────────────────────────────────────────\n\n  // @brief  Returns the next unused internal object id and advances the\n  //         counter.  Used by `Obstacle` and `ConnRef` to tag their owning\n  //         `VertInf.objID` and cache keys.  Not part of the public API.\n  /** @internal */\n  _assignObjectId(): number {\n    return this._nextObjectId++;\n  }\n\n  // ─── Obstacle / shape / junction registration ─────────────────────────────\n\n  // @brief  Convenience: construct an `Obstacle` for `rect` and register it\n  //         with this router in one shot.  Equivalent to\n  //         `const o = new Obstacle(router, rect); router.addObstacle(o)`.\n  createObstacle(rect: Rect) {\n    const obstacle = new Obstacle(this, rect);\n    this.addObstacle(obstacle);\n    return obstacle;\n  }\n\n  // @brief  Adds an obstacle to the router scene.  The obstacle's geometry is\n  //         consumed directly from `obstacles` when the visibility graph is\n  //         built, so there are no vertices to register here.  Idempotent —\n  //         re-adding a registered obstacle is a no-op.\n  addObstacle(obstacle: Obstacle): void {\n    if (this.obstacles.includes(obstacle)) {\n      return;\n    }\n    this.obstacles.push(obstacle);\n  }\n\n  // @brief  Removes an obstacle from the router scene.  Idempotent.\n  deleteObstacle(obstacle: Obstacle): void {\n    const idx = this.obstacles.indexOf(obstacle);\n    if (idx === -1) return;\n    this.obstacles.splice(idx, 1);\n  }\n\n  // @brief  Convenience: construct an `AnnotationGroup` for `rect` and\n  //         register it with this router.\n  createGroup(rect: Rect) {\n    const group = new AnnotationGroup(this, rect);\n    this.addGroup(group);\n    return group;\n  }\n\n  // @brief  Adds an annotation group to the router scene.  Idempotent.\n  addGroup(group: AnnotationGroup): void {\n    if (this.groups.includes(group)) return;\n    this.groups.push(group);\n  }\n\n  // @brief  Removes an annotation group from the router scene.  Idempotent.\n  deleteGroup(group: AnnotationGroup): void {\n    const idx = this.groups.indexOf(group);\n    if (idx !== -1) this.groups.splice(idx, 1);\n  }\n\n  // @brief  Adds a junction to the router scene.  Materialises the\n  //         centre vertex into the visgraph and (for fixed junctions)\n  //         registers the backing obstacle.  Idempotent.\n  addJunction(junction: Junction<JunctionUserData>): void {\n    if (this.junctions.has(junction)) {\n      return;\n    }\n    this.junctions.add(junction);\n    this.vertices.addVertex(junction.centreVertex);\n    if (junction._obstacle !== null) {\n      this.addObstacle(junction._obstacle);\n    }\n  }\n\n  // @brief  Adds a connector to the router scene.  Idempotent — re-adding\n  //         a connector that's already registered is a no-op.\n  addConnector(connector: Edge<EdgeUserData>): void {\n    if (this.connRefs.includes(connector)) return;\n    this.connRefs.unshift(connector);\n  }\n\n  // @brief  Remove a connector from the router scene.\n  deleteConnector(connector: Edge<EdgeUserData>) {\n    const idx = this.connRefs.indexOf(connector);\n    if (idx !== -1) this.connRefs.splice(idx, 1);\n  }\n\n  // ─── Flag setters / state readers ─────────────────────────────────────────\n  // @brief  Returns whether the router is currently in the crossing-penalty\n  //         rerouting stage.  Used by makepath to suppress some penalties\n  //         during the first routing pass.\n  isInCrossingPenaltyReroutingStage(): boolean {\n    return this.m_in_crossing_rerouting_stage;\n  }\n\n  // @brief  Flip the crossing-penalty rerouting stage flag.  Called by\n  //         `improveCrossings` around its rerouting passes so makepath's\n  //         `cost()` enables the per-step crossing/shared-path penalties.\n  /** @internal */\n  _setInCrossingPenaltyReroutingStage(active: boolean): void {\n    this.m_in_crossing_rerouting_stage = active;\n  }\n\n  registerHyperedgeForRerouting(hyperedge: Hyperedge) {\n    switch (hyperedge.type) {\n      case 'terminals':\n        this.hyperedgesForRerouting.push({\n          type: 'terminals',\n          connEnds: [...hyperedge.connEnds],\n        });\n        break;\n    }\n  }\n\n  // ─── route() — the routing pipeline entry point ───────────────────────────\n\n  // @brief  Run the orthogonal routing pipeline over every active connector.\n  //\n  // Replaces the C++ `processTransaction` minus the action-replay machinery.\n  // The actual sequence of steps lives in `src/pipeline/route-steps.ts` as\n  // a list of `Step<RouteContext>` instances — read that file to see what\n  // each step does.  `route()` itself only assembles the per-run context,\n  // drives the pipeline, and clears the hyperedge queue.\n  //\n  // @return  Per-run state: `anyChange` (did any connector update its\n  //          route?) and `hyperedgeRerouter` (so callers can introspect\n  //          what MTST decided).\n  route() {\n    const ctx = new RouteContext(this);\n    ROUTE_PIPELINE.run(ctx);\n\n    this.hyperedgesForRerouting = [];\n\n    return {\n      anyChange: ctx.anyChange,\n      hyperedgeRerouter: ctx.hyperedgeRerouter,\n    };\n  }\n}\n","import type {Edge} from '../models/edge';\nimport type {Endpoint} from '../models/endpoint';\nimport type {Direction} from '../models/Direction';\nimport {Junction} from '../models/junction';\nimport type {Router} from '../router';\n\nfunction printDirection(direction: Direction) {\n  return `new Direction(${direction.rawValue})`;\n}\n\nfunction variableNameForJunction(junction: Junction) {\n  let position = junction.position();\n  return `junc_${position.x}_${position.y}`;\n}\n\nfunction printEdge(edge: Edge) {\n  let source = edge.source;\n  let destination = edge.destination;\n  if (source && destination) {\n    return `new Edge(router, ${printEndPoint(source)}, ${printEndPoint(destination)})`;\n  }\n  return null;\n}\n\nfunction printEndPoint(endpoint: Endpoint | Junction) {\n  if (endpoint instanceof Junction) {\n    return variableNameForJunction(endpoint);\n  }\n  const position = endpoint.position;\n  return `new Endpoint(new Point(${position.x}, ${position.y}), ${printDirection(endpoint.directions)})`;\n}\n\nexport function print(router: Router) {\n  let statements: string[] = [];\n\n  statements.push(\n    `let router = new Router(${JSON.stringify(router.params, null, 2)}, ${JSON.stringify(router.options, null, 2)})`,\n  );\n\n  for (let junction of router.junctions) {\n    let position = junction.position();\n    const name = variableNameForJunction(junction);\n    statements.push(`let ${name} = new Junction(router, new Point(${position.x}, ${position.y}))`);\n    statements.push(`router.addJunction(${name})`);\n  }\n\n  for (let obstacle of router.obstacles) {\n    statements.push(`router.createObstacle(\n        new Rect(\n          {\n            x: ${obstacle.polygon._origin.x},\n            y: ${obstacle.polygon._origin.y},\n          },\n          {\n            width: ${obstacle.polygon._size.width},\n            height: ${obstacle.polygon._size.height},\n          },\n        )\n      )`);\n  }\n\n  for (let edge of router.connRefs.toReversed()) {\n    let output = printEdge(edge);\n    if (output) {\n      statements.push(`router.addConnector(${output})`);\n    }\n  }\n\n  for (let hyperedge of router.hyperedgesForRerouting) {\n    switch (hyperedge.type) {\n      case 'terminals':\n        statements.push(`router.registerHyperedgeForRerouting({\n          type: 'terminals',\n          connEnds: [${hyperedge.connEnds.map(endpoint => printEndPoint(endpoint))}]\n        })`);\n        break;\n      case 'junction':\n        break;\n    }\n  }\n\n  return statements.join('\\n');\n}\n"],"mappings":";AAAA,IAAa,YAAb,MAAa,UAA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