logigate/app/lib/logic/latch.ts

179 lines
7.6 KiB
TypeScript
Raw Permalink Normal View History

// Latching: a part set right against another so that every pin it shares
// with it touches that part's pin, like a display on a CPU's outputs or a
// switch on a component's input. A latched part moves with the part it is
// latched to; dragging it away (or "Unlatch") lets go and its wires show
// again. Parts whose shared pins touch latch by themselves. Cable ends plug
// in the same way (cables.ts); docked panels follow their own rule (panels.ts).
import { shapeOf, type DefLookup, type PinInfo, type Shape } from './geometry'
import type { CircuitNode, ComponentDef, Project } from './types'
import { lookup } from './ops'
/** Parts that never latch: cable ends plug instead, notes are not wired. */
const SKIP = new Set(['bundle', 'split', 'note'])
const canLatch = (n: CircuitNode) => !SKIP.has(n.kind) && !n.attach
interface Pair {
/** The guest's pin, relative to the guest. */
g: PinInfo
/** The host's pin, on the canvas. */
hx: number
hy: number
}
/**
* The pins a guest shares with a host, as pairs, all on one side: the
* guest's inputs fed by the host's outputs (it sits on the host's right),
* or its outputs feeding the host's inputs (on its left). Null when its
* wires to the host run both ways, or a pin is used twice.
*/
function pairsOf(def: ComponentDef, guest: CircuitNode, host: CircuitNode, gs: Shape, hs: Shape): { right: boolean; list: Pair[] } | null {
const right: Pair[] = []
const left: Pair[] = []
for (const w of def.wires) {
const fed = w.from.node === host.id && w.to.node === guest.id
const feeds = w.from.node === guest.id && w.to.node === host.id
if (!fed && !feeds) continue
const g = (fed ? gs.inputs : gs.outputs).find(p => p.key === (fed ? w.to.pin : w.from.pin))
const h = (fed ? hs.outputs : hs.inputs).find(p => p.key === (fed ? w.from.pin : w.to.pin))
if (!g || !h || g.bus || h.bus) return null
// Pins facing the usual way only: an output's wire leaves right, an input's arrives from the left.
const gFace = g.face ?? (fed ? -1 : 1)
const hFace = h.face ?? (fed ? 1 : -1)
if (gFace !== (fed ? -1 : 1) || hFace !== (fed ? 1 : -1)) return null
;(fed ? right : left).push({ g, hx: host.x + h.dx, hy: host.y + h.dy })
}
if (right.length && left.length) return null
const list = right.length ? right : left
if (!list.length || new Set(list.map(p => p.g.key)).size !== list.length) return null
return { right: right.length > 0, list }
}
/**
* Where a guest sits latched to a host: every pin it shares with the host on
* that pin, all moved by the same step. It has to fit exactly: no other pin
* of either part may land on a pin of the other without a wire between them.
*/
export function latchLayout(def: ComponentDef, guest: CircuitNode, host: CircuitNode, get: DefLookup): { x: number; y: number; right: boolean } | null {
if (guest.id === host.id || !canLatch(guest) || SKIP.has(host.kind)) return null
const gs = shapeOf(guest, get)
const hs = shapeOf(host, get)
const pairs = pairsOf(def, guest, host, gs, hs)
if (!pairs) return null
const first = pairs.list[0]!
const sx = first.hx - (guest.x + first.g.dx)
const sy = first.hy - (guest.y + first.g.dy)
if (pairs.list.some(p => p.hx - (guest.x + p.g.dx) !== sx || p.hy - (guest.y + p.g.dy) !== sy)) return null
const x = guest.x + sx
const y = guest.y + sy
// Facing pins that would touch without a wire between them would look connected.
const mine = pairs.right ? gs.inputs : gs.outputs
const theirs = pairs.right ? hs.outputs : hs.inputs
const wired = new Set(pairs.list.map(p => `${p.g.key}@${p.hx},${p.hy}`))
for (const g of mine) {
const gx = x + g.dx
const gy = y + g.dy
const h = theirs.find(t => host.x + t.dx === gx && host.y + t.dy === gy)
if (h && !wired.has(`${g.key}@${gx},${gy}`)) return null
}
return { x, y, right: pairs.right }
}
/** The part a part can latch onto: one it is wired to whose pins it fits exactly (most shared pins first). */
export function latchTarget(def: ComponentDef, guest: CircuitNode, get: DefLookup): CircuitNode | undefined {
if (!canLatch(guest)) return
const ids = new Set<string>()
for (const w of def.wires) {
if (w.from.node === guest.id) ids.add(w.to.node)
if (w.to.node === guest.id) ids.add(w.from.node)
}
ids.delete(guest.id)
let best: CircuitNode | undefined
let most = 0
for (const id of ids) {
const host = def.nodes.find(n => n.id === id)
if (!host || !latchLayout(def, guest, host, get) || hostChain(def, host).has(guest.id)) continue
const n = def.wires.filter(w => (w.from.node === id && w.to.node === guest.id) || (w.from.node === guest.id && w.to.node === id)).length
if (n > most) {
best = host
most = n
}
}
return best
}
/** The parts a part is latched to, directly or through others. */
function hostChain(def: ComponentDef, n: CircuitNode): Set<string> {
const out = new Set<string>()
let at: CircuitNode | undefined = n
while (at?.latch && !out.has(at.latch)) {
out.add(at.latch)
at = def.nodes.find(x => x.id === at!.latch)
}
return out
}
/** Latches a part onto a host: it moves onto the host's pins and its wires to it lose their bends. False when it doesn't fit. */
export function latchInto(def: ComponentDef, guest: CircuitNode, hostId: string, get: DefLookup): boolean {
const host = def.nodes.find(n => n.id === hostId)
const lay = host && !hostChain(def, host).has(guest.id) ? latchLayout(def, guest, host, get) : null
if (!host || !lay) {
delete guest.latch
return false
}
guest.latch = host.id
guest.x = lay.x
guest.y = lay.y
for (const w of def.wires) if ((w.from.node === host.id && w.to.node === guest.id) || (w.from.node === guest.id && w.to.node === host.id)) delete w.pts
return true
}
const area = (s: Shape) => s.body.w * s.body.h
/**
* The part a part's shared pins already all touch, so it counts as latched.
* Of two parts that touch, the smaller one latches onto the larger; as large
* as each other, the one that is fed latches onto the one feeding it.
*/
function touchingHost(def: ComponentDef, guest: CircuitNode, get: DefLookup): string | null {
const host = latchTarget(def, guest, get)
const lay = host && latchLayout(def, guest, host, get)
if (!host || !lay || lay.x !== guest.x || lay.y !== guest.y) return null
const a = area(shapeOf(guest, get))
const b = area(shapeOf(host, get))
if (a > b || (a === b && !lay.right)) return null
return host.id
}
/** Keeps every latched part on its host's pins; parts that newly touch latch, ones that no longer fit let go. */
export function syncLatches(project: Project) {
const get = lookup(project)
for (const def of project.components) {
if (def.nodes.length < 2) continue
for (const n of def.nodes) {
if (!canLatch(n)) {
delete n.latch
continue
}
const id = n.latch ?? touchingHost(def, n, get)
if (id) latchInto(def, n, id, get)
}
}
}
/** Parts latched onto any of `ids`. */
export function latchedTo(def: ComponentDef, ids: Set<string>): CircuitNode[] {
return def.nodes.filter(n => n.latch && ids.has(n.latch))
}
/** Where a latched part touches its host, relative to the part: the column of its pins and their top and bottom rows. */
export function latchSeam(def: ComponentDef, guest: CircuitNode, get: DefLookup): { x: number; y0: number; y1: number } | null {
const host = guest.latch ? def.nodes.find(n => n.id === guest.latch) : undefined
if (!host) return null
const pairs = pairsOf(def, guest, host, shapeOf(guest, get), shapeOf(host, get))
if (!pairs) return null
const ys = pairs.list.map(p => p.g.dy)
return { x: pairs.list[0]!.g.dx, y0: Math.min(...ys), y1: Math.max(...ys) }
}