logigate/app/lib/logic/fit.ts

209 lines
8.2 KiB
TypeScript

// Where selected parts fit: runs of free pins on other parts that the whole
// selection can be wired to in one go (shown as green boxes to pick from),
// and the pins a part being dragged lands on (connected when it is dropped).
import { byPosition, type Link } from './bulk'
import { pinKindOf, shapeOf, type DefLookup, type Pt, type Shape } from './geometry'
import { SOURCE_KINDS } from './ops'
import type { CircuitNode, ComponentDef, PinRef } from './types'
export interface FitPin {
key: string
label: string
/** Place on the canvas, in grid units. */
x: number
y: number
}
export interface FitSpot {
/** The part whose pins the selection fits onto. */
part: string
/** Which of its pins: its outputs (they feed the selected parts) or its inputs (the selected parts feed them). */
side: 'in' | 'out'
/** Free pins next to each other on one edge, top to bottom. */
pins: FitPin[]
/** The selected parts' pins, top to bottom: one per pin of a fit. */
mine: PinRef[]
/** Middle of the selected parts' pins. */
from: Pt
/** Distance from there to the middle of the run. */
dist: number
}
type ShapeOf = (n: CircuitNode) => Shape
function wiredPins(def: ComponentDef) {
return {
in: new Set(def.wires.map(w => `${w.to.node}:${w.to.pin}`)),
out: new Set(def.wires.map(w => `${w.from.node}:${w.from.pin}`)),
}
}
/**
* The pin a fit wires on a selected part: its one free input (a lamp, an
* output pin, a gate with one input left), or the one unwired output of a
* switch, button, clock or gate. Null when it has none, or several.
*/
function plugPin(n: CircuitNode, dir: 'in' | 'out', shape: Shape, wired: ReturnType<typeof wiredPins>): string | null {
if (dir === 'in') {
if (['note', 'panel', 'outpanel', 'bundle', 'split', 'hex'].includes(n.kind)) return null
const free = shape.inputs.filter(p => !p.bus && !wired.in.has(`${n.id}:${p.key}`))
return free.length === 1 ? free[0]!.key : null
}
if (!SOURCE_KINDS.includes(n.kind) && n.kind !== 'nand' && n.kind !== 'chip' && n.kind !== 'ref') return null
const outs = shape.outputs.filter(p => !p.bus)
return outs.length === 1 && !wired.out.has(`${n.id}:${outs[0]!.key}`) ? outs[0]!.key : null
}
/** Whether the selected parts could be wired as a group at all: each has one free input, or each one unwired output. */
export function canFit(def: ComponentDef, get: DefLookup, selected: string[]): boolean {
const ids = new Set(selected)
const sel = def.nodes.filter(n => ids.has(n.id))
const wired = wiredPins(def)
return sel.length > 1 && (['in', 'out'] as const).some(dir => sel.every(n => plugPin(n, dir, shapeOf(n, get), wired)))
}
/**
* Places the selected parts fit as a group: on another part, a run of free
* pins on one edge at least as long as the selection, that their one free
* input each (or one unwired output each) can be wired to in order. The
* nearest `limit` runs, nearest first; none for fewer than two parts.
*/
export function fitSpots(def: ComponentDef, get: DefLookup, selected: string[], limit = 6, shapeFn?: ShapeOf): FitSpot[] {
const shape = shapeFn ?? ((n: CircuitNode) => shapeOf(n, get))
const ids = new Set(selected)
const sel = def.nodes.filter(n => ids.has(n.id)).sort(byPosition)
if (sel.length < 2) return []
const wired = wiredPins(def)
const spots: FitSpot[] = []
for (const side of ['out', 'in'] as const) {
const mineDir = side === 'out' ? 'in' : 'out'
const plugs = sel.map(n => plugPin(n, mineDir, shape(n), wired))
if (plugs.some(p => !p)) continue
const mine = sel.map((n, i) => ({ node: n.id, pin: plugs[i]! }))
const at = sel.map((n, i) => {
const s = shape(n)
const p = (mineDir === 'in' ? s.inputs : s.outputs).find(x => x.key === plugs[i])!
return [n.x + p.dx, n.y + p.dy] as Pt
})
const cx = at.reduce((s, p) => s + p[0], 0) / at.length
const cy = at.reduce((s, p) => s + p[1], 0) / at.length
const k = sel.length
for (const n of def.nodes) {
if (ids.has(n.id) || n.kind === 'note') continue
const s = shape(n)
const pins = (side === 'out' ? s.outputs : s.inputs).filter(p => !p.bus).sort((a, b) => a.dy - b.dy)
let run: FitPin[] = []
const flush = () => {
if (run.length >= k) {
const mx = run[0]!.x
const my = (run[0]!.y + run[run.length - 1]!.y) / 2
spots.push({ part: n.id, side, pins: run, mine, from: [cx, cy], dist: Math.hypot(mx - cx, my - cy) })
}
run = []
}
for (const p of pins) {
const free = !(side === 'out' ? wired.out : wired.in).has(`${n.id}:${p.key}`)
const x = n.x + p.dx
if (!free || (run.length && run[0]!.x !== x)) flush()
if (free) run.push({ key: p.key, label: p.label, x, y: n.y + p.dy })
}
flush()
}
}
return spots.sort((a, b) => a.dist - b.dist).slice(0, limit)
}
/** The fit of a spot whose middle is nearest to row `y`: index of its first pin. */
export function fitStart(spot: FitSpot, y: number): number {
const k = spot.mine.length
let best = 0
let bestD = Infinity
for (let s = 0; s + k <= spot.pins.length; s++) {
const d = Math.abs((spot.pins[s]!.y + spot.pins[s + k - 1]!.y) / 2 - y)
if (d < bestD) {
bestD = d
best = s
}
}
return best
}
/** The wires a fit makes: the selected parts, top to bottom, to the spot's pins from `start` on. */
export function fitLinks(spot: FitSpot, start: number): Link[] {
return spot.mine.map((m, i) => {
const theirs = { node: spot.part, pin: spot.pins[start + i]!.key }
return spot.side === 'out' ? { from: theirs, to: m } : { from: m, to: theirs }
})
}
export interface DropPin {
node: string
pin: string
dir: 'in' | 'out'
/** What it plugs into: '' a wire, 'bus' a cable, 'c:<id>' a connector port. */
bus: string
/** Wired already: an input can't take a second wire. */
wired: boolean
x: number
y: number
}
/** Every pin of the given parts, where it is now. */
export function dropPins(def: ComponentDef, nodes: CircuitNode[], shape: ShapeOf): DropPin[] {
const wired = wiredPins(def)
const out: DropPin[] = []
for (const n of nodes) {
const s = shape(n)
for (const p of s.inputs) out.push({ node: n.id, pin: p.key, dir: 'in', bus: pinKindOf(p), wired: wired.in.has(`${n.id}:${p.key}`), x: n.x + p.dx, y: n.y + p.dy })
for (const p of s.outputs) out.push({ node: n.id, pin: p.key, dir: 'out', bus: pinKindOf(p), wired: wired.out.has(`${n.id}:${p.key}`), x: n.x + p.dx, y: n.y + p.dy })
}
return out
}
/** A free pin of a moved part meeting a pin it can join: an output and an input that has no wire yet. */
const fits = (m: DropPin, s: DropPin) => m.dir !== s.dir && m.bus === s.bus && !m.wired && !(s.dir === 'in' && s.wired)
/**
* Parts being dragged onto other parts' pins: where a free pin of theirs
* lands on a pin it can join, or (`reach` 1) within a square of one.
* Returns the step that puts the nearest pair exactly on top of each other,
* and every wire that makes; null when nothing is in reach.
*/
export function dropLinks(moving: DropPin[], still: DropPin[], reach: 0 | 1 = 1): { shift: Pt; links: Link[] } | null {
const at = new Map<string, DropPin[]>()
for (const p of still) {
const key = `${p.x},${p.y}`
const list = at.get(key)
if (list) list.push(p)
else at.set(key, [p])
}
let best: { d: number; shift: Pt } | null = null
for (const m of moving) {
for (let dx = -reach; dx <= reach; dx++) {
for (let dy = -reach; dy <= reach; dy++) {
for (const s of at.get(`${m.x + dx},${m.y + dy}`) ?? []) {
const d = Math.hypot(dx, dy)
if (fits(m, s) && (!best || d < best.d)) best = { d, shift: [dx, dy] }
}
}
}
}
if (!best) return null
const [sx, sy] = best.shift
const links: Link[] = []
const taken = new Set<string>()
for (const m of moving) {
for (const s of at.get(`${m.x + sx},${m.y + sy}`) ?? []) {
const into = m.dir === 'in' ? m : s
const key = `${into.node}:${into.pin}`
if (!fits(m, s) || taken.has(key)) continue
taken.add(key)
const from = m.dir === 'out' ? m : s
links.push({ from: { node: from.node, pin: from.pin }, to: { node: into.node, pin: into.pin } })
break
}
}
return { shift: best.shift, links }
}