A connector types of your own: HDMI, RJ45 or any bus, with out and in ports and one cable that carries every line both ways

- A project keeps connector types: a name, a colour and lines that run
  out -> in or back. Made, edited and deleted (once unused) from the
  parts list's new Connectors group and a connector dialog.
- "<type> out" and "<type> in" ports: inside a component a pin per line
  on the inner side plus a cable pin to pass the whole cable on to a
  part inside; on the component's box one port, coloured like its type.
- One cable joins an out port to an in port of the same type; the
  compiler joins line by line, forward and back, at every depth. Ports
  of different types never join; mismatched cables are pruned.
- Pins can face the other way (the inner pins of ports); the router
  takes them out and in from the side they face.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-22 18:59:56 +02:00
parent c5b67ee7c1
commit 8de4a81678
19 changed files with 915 additions and 80 deletions

View File

@ -14,6 +14,7 @@ Nuxt 4 (client-only editor, `ssr: false`), Tailwind CSS v4, Lucide icons via `@n
- Sound (speaker in the top bar; volume and clock ticks in Settings, the gear in the top bar): clicks for placing, wiring, switches and buttons, a tick per clock cycle up to 8 Hz (off by default), and jingles for a solve, a failed check, unlocks and new records. All synthesised with Web Audio, no sound files ([app/lib/audio.ts](app/lib/audio.ts)).
- Transistors: every component shows how many it takes, counted as a CMOS NAND (4 transistors) per gate at every depth: in the palette, its settings and the circuit stats. Each challenge keeps your record, the fewest transistors of any passing solution, and says so when you beat it.
- Cables: a bundle gathers 2 to 32 wires into one cable, a split fans it out again in the same order; one bundle can feed several splits. Select the wires (a box across them, or Shift + click) and press "Bundle into cable" or Ctrl+G: the cable starts right after the sources on their middle row and ends right before the targets on theirs, so the wires keep running as they did (backwards too); an end steps aside when another part is in the way. "Place the ends yourself…" (Ctrl+Shift+G) lets you click where it starts and ends, with a preview; Esc cancels. "Unlink all" on a bundle or split removes only the wires going in or out; the cable stays. Drag the bundle and split later to move the ends. Up to 16 wires, the cable is drawn as a ribbon: each wire is its own thin line inside, in its own colour, lit while it carries a 1. The sleeve starts neutral and gets its own colour (cable or bundle/split settings). "Remove cable" turns it back into single wires. A cable end only joins another cable end, and the cable shows its width.
- Connectors (your own HDMI, RJ45, buses): in the parts list, "New connector type" makes one: a name, a colour, and lines that each run out → in or back (acknowledge, hot-plug, a receive pair). Each type gives two parts, "<type> out" and "<type> in". Inside a component, a port shows its lines as pins on its inner side (lines coming in are outputs, lines going out inputs) and has a cable pin at the top to hand the whole cable on to a part inside; on the component's box it is one port, in ports on the left, out ports on the right, drawn as a socket in the type's colour. One cable joins an out port to an in port of the same type and carries every line, forward and back; it is drawn as a sleeve in the type's colour with its name. Ports of different types never join, and a cable whose ends stop matching (a port changed type) is removed. Editing a type changes every port and cable of it; lines are matched by their place in the list. A type can only be deleted once no port uses it.
- Pixels and screens: a pixel is a one-grid square that lights at 1, in five colours. Inside a component all pixels show on its box as one screen without gaps (every column and row they sit on becomes one of the screen), so you build your own LCD; see "Screen 4×4" and "Demo: Screen".
- Input panel: one part with a column of controls; each row is a switch, button or clock. "Attach input panel" on a placed component docks one to its left with a row per free input, lined up with the pins and named after them. A docked panel moves with its component, gets a row when the component gains an input and loses it when the pin goes; inputs that are wired elsewhere, and rows you remove, are left alone. Inside a component a switch row keeps its position and a button row is 0.
- Automatic names: copies continue a series (D0 copied gives D1, D2; A gives B), and so does placing a new input or output after a numbered one. A switch, button, lamp or output pin without a name of its own (or with an automatic one) takes the name of the component pin it gets wired to, made unique (Cin, Cin2); a name typed by hand is kept. On the canvas, a switch, button, clock, lamp or output pin without a name typed by hand shows the name of the component pin it is wired to, dimmed and in italics (or its automatic name, also dimmed); the name follows the wiring as it changes.

View File

@ -4093,3 +4093,130 @@ table.board {
.fold-body {
padding: 2px 14px 14px;
}
/* ── Connector ports and their cables ───────────────────────────── */
.node .body.port {
fill: #141a22;
}
.port-head {
opacity: 0.85;
}
.port-title {
fill: #0e1116;
font-family: var(--font-mono);
font-size: 9px;
font-weight: 700;
pointer-events: none;
}
.port-line {
fill: var(--text);
}
.port-socket {
stroke: #0e1116;
stroke-width: 1.5;
pointer-events: none;
}
.wire.port-cable .cable-sleeve {
stroke: var(--w-on, #8592a3);
opacity: 0.9;
}
.wire.port-cable .cable-core {
stroke: #10151c;
}
.port-mark text {
fill: var(--text);
font-family: var(--font-mono);
font-size: 9px;
font-weight: 700;
}
/* Connectors in the parts list */
.conn-row {
display: flex;
align-items: center;
gap: 6px;
padding: 2px 8px 2px 12px;
font-size: 13px;
}
.conn-row.blocked {
opacity: 0.45;
}
.conn-swatch {
flex: 0 0 auto;
width: 10px;
height: 10px;
border-radius: 3px;
background: var(--w-on, #8592a3);
}
.conn-swatch.c-red { --w-on: #ff5c5c; }
.conn-swatch.c-orange { --w-on: #ff9f43; }
.conn-swatch.c-yellow { --w-on: #ffd93d; }
.conn-swatch.c-green { --w-on: #3ddc84; }
.conn-swatch.c-blue { --w-on: #4dabff; }
.conn-swatch.c-purple { --w-on: #b388ff; }
.conn-swatch.c-pink { --w-on: #ff7ac6; }
.port-pick {
padding: 1px 7px;
font-size: 11px;
}
.port-pick.active {
border-color: var(--accent);
color: var(--accent);
}
/* Connector type dialog */
.conn-modal {
width: min(560px, 100%);
}
.conn-lines {
display: grid;
gap: 4px;
margin-bottom: 8px;
}
.conn-lines li {
display: flex;
align-items: center;
gap: 4px;
}
.conn-lines input {
flex: 1;
min-width: 0;
}
.conn-index {
width: 20px;
text-align: right;
font-family: var(--font-mono);
font-size: 11px;
color: var(--muted);
}
.conn-dir {
min-width: 78px;
font-family: var(--font-mono);
font-size: 11px;
}
.conn-dir.back {
color: var(--lamp);
border-color: rgb(255 211 77 / 0.4);
}
.wire.port-cable:not([class*='c-']) .cable-sleeve {
stroke: #8592a3;
}

View File

@ -70,6 +70,7 @@ watch(
</div>
<EditorTruthTableDialog v-if="ed.dialog.value === 'table'" />
<EditorPublishDialog v-if="ed.dialog.value === 'publish'" />
<EditorConnectorDialog v-if="ed.dialog.value === 'connector'" />
<EditorHelp v-if="ed.showHelp.value" />
<EditorPauseMenu v-if="ed.paused.value && ed.screen.value === 'editor'" />
<EditorShareDialog v-if="ed.dialog.value === 'share'" />

View File

@ -1,7 +1,7 @@
<script setup lang="ts">
import { cableKeys, INVERTIBLE } from '~/lib/logic/compile'
import { CHECKED_INPUTS } from '~/lib/logic/check'
import { cableBits, GRID as G, pinPos, routeWire, type Pt, type Shape } from '~/lib/logic/geometry'
import { cableBits, GRID as G, pinKindOf, pinPos, routeWire, type Pt, type Shape } from '~/lib/logic/geometry'
import type { CircuitNode, PanelRow, PinRef, Wire } from '~/lib/logic/types'
import { branchCorners, branchTo, endGrip, moveCorner, moveSegment, nearEnd, routeTouchesBox, segmentAt, segmentDrag, splitDrag } from '~/lib/logic/wires'
import { circuitRoutes, findCrossings } from '~/lib/logic/routing'
@ -43,6 +43,26 @@ interface Route {
lanes?: { i: number; d: string; color?: string }[]
/** Width of the cable's sleeve in pixels. */
sleeve?: number
/** What its pins plug into: '' a wire, 'bus' a cable, 'c:<id>' a connector port. */
kind: string
/** A cable between connector ports: its type's name and colour. */
port?: { name: string; color?: string }
}
/** The middle of a route's longest straight run, where a cable's label goes. */
function midOfLongest(draw: Pt[]): Pt | undefined {
let best = 0
let at: Pt | undefined
for (let i = 0; i < draw.length - 1; i++) {
const [ax, ay] = draw[i]!
const [bx, by] = draw[i + 1]!
const len = Math.abs(bx - ax) + Math.abs(by - ay)
if (len > best) {
best = len
at = [(ax + bx) / 2, (ay + by) / 2]
}
}
return at
}
const toPath = (pts: Pt[]) => pts.map(([x, y], i) => `${i ? 'L' : 'M'}${x * G} ${y * G}`).join('')
@ -59,7 +79,16 @@ const routes = computed<Route[]>(() => {
return routed.map((r, k) => {
const wire = byId.get(r.id)!
const from = nodeMap.value.get(wire.from.node)
const route: Route = { wire, pts: r.grid, draw: r.draw, d: wirePath(r.draw, hops.get(k), style), src: r.net }
const pin = from && shapes.value.get(from.id)?.outputs.find(p => p.key === wire.from.pin)
const route: Route = { wire, pts: r.grid, draw: r.draw, d: wirePath(r.draw, hops.get(k), style), src: r.net, kind: pin ? pinKindOf(pin) : '' }
if (pin?.conn) {
// A cable between connector ports: a sleeve in its type's colour, named.
const type = ed.getDef.value.conn?.(pin.conn)
route.port = { name: type?.name ?? '?', color: type?.color }
route.d = toPath(r.draw)
route.sleeve = Math.min(8, Math.max(2, type?.lines.length ?? 2)) * LANE * G + 3
route.mark = midOfLongest(r.draw)
}
if (from?.kind === 'bundle') {
route.bits = cableBits(from)
if (route.bits <= RIBBON_MAX) {
@ -70,16 +99,7 @@ const routes = computed<Route[]>(() => {
route.sleeve = route.bits * LANE * G + 3
}
// The width mark sits on the middle of the longest straight run.
let best = 0
for (let i = 0; i < r.draw.length - 1; i++) {
const [ax, ay] = r.draw[i]!
const [bx, by] = r.draw[i + 1]!
const len = Math.abs(bx - ax) + Math.abs(by - ay)
if (len > best) {
best = len
route.mark = [(ax + bx) / 2, (ay + by) / 2]
}
}
route.mark = midOfLongest(r.draw)
}
return route
})
@ -109,6 +129,11 @@ function wireTip(r: Route): string {
const part = n.label?.trim() || (n.kind === 'chip' ? (n.chip && ed.getDef.value(n.chip)?.name) || 'Component' : n.kind.toUpperCase())
return pin ? `${part} ${pin}` : part
}
if (r.port) {
const type = r.kind.startsWith('c:') ? ed.getDef.value.conn?.(r.kind.slice(2)) : undefined
const lines = (type?.lines ?? []).map(l => (l.back ? `${l.name} (back)` : l.name)).join(', ')
return `${name(r.wire.from)} → ${name(r.wire.to)}: ${r.port.name} cable${lines ? ` with ${lines}` : ''}`
}
return `${name(r.wire.from)} → ${name(r.wire.to)}: ${srcVal(r.src)}`
}
@ -257,8 +282,8 @@ onBeforeUnmount(() => {
// ── Placing ─────────────────────────────────────────────────────────
const cursor = ref<Pt | null>(null)
function originFor(p: { kind: CircuitNode['kind']; chip?: string }, at: Pt): Pt {
const b = ed.shape({ id: 'ghost', kind: p.kind, chip: p.chip, x: 0, y: 0 }).body
function originFor(p: { kind: CircuitNode['kind']; chip?: string; conn?: string }, at: Pt): Pt {
const b = ed.shape({ id: 'ghost', kind: p.kind, chip: p.chip, conn: p.conn, x: 0, y: 0 }).body
return [Math.round(at[0] - (b.x + b.w / 2)), Math.round(at[1] - (b.y + b.h / 2))]
}
@ -272,9 +297,9 @@ const altDown = ref(false)
* at the mouse, or a square over so its free pins land on pins they can
* join, with the wires that makes.
*/
function landing(p: { kind: CircuitNode['kind']; chip?: string }, at: Pt, alt: boolean) {
function landing(p: { kind: CircuitNode['kind']; chip?: string; conn?: string }, at: Pt, alt: boolean) {
const [x, y] = originFor(p, at)
const node: CircuitNode = { id: 'ghost', kind: p.kind, chip: p.chip, x, y, label: p.kind === 'note' ? 'Note' : p.kind === 'input' ? '?' : undefined }
const node: CircuitNode = { id: 'ghost', kind: p.kind, chip: p.chip, conn: p.conn, x, y, label: p.kind === 'note' ? 'Note' : p.kind === 'input' ? '?' : undefined }
const snap = alt ? null : dropLinks(dropPins(def.value, [node], n => ed.shape(n)), allPins.value, 1)
if (snap) {
node.x += snap.shift[0]
@ -341,7 +366,7 @@ function onDrop(e: DragEvent) {
const raw = e.dataTransfer?.getData('application/x-logigate')
ed.dragPart.value = null
if (!raw) return
const p = JSON.parse(raw) as { kind: CircuitNode['kind']; chip?: string }
const p = JSON.parse(raw) as { kind: CircuitNode['kind']; chip?: string; conn?: string }
if (p.chip && !ed.canPlace(p.chip)) return ed.notify('A component cannot contain itself', 'error')
if (!ed.canPlaceKind(p.kind)) return
const { node, links } = landing(p, toWorld(e), e.altKey)
@ -433,7 +458,7 @@ function onPointerDown(e: PointerEvent) {
const end = link?.queue[link.at]
if (end) {
// Connecting: a click on a pin or a part wires the current pin there.
const target = targetAt(w, end.dir === 'out' ? 'in' : 'out', ed.isBus(end.node, end.pin, end.dir))
const target = targetAt(w, end.dir === 'out' ? 'in' : 'out', ed.pinKind(end.node, end.pin, end.dir))
if (target) return ed.linkTo(target)
const pinEl = (e.target as Element).closest('[data-pin]')
if (pinEl && link.queue.length === 1) {
@ -758,13 +783,13 @@ function nodeAt(at: Pt): CircuitNode | undefined {
* else, over a part, that part's first free pin (or its nearest one when
* all are taken). So dropping a wire anywhere on a component works.
*/
function targetAt(at: Pt, dir: 'in' | 'out', bus = false): PinRef | null {
function targetAt(at: Pt, dir: 'in' | 'out', bus = ''): PinRef | null {
let best: PinRef | null = null
let bestD = 1.1 * 1.1
for (const n of def.value.nodes) {
const s = shapes.value.get(n.id)!
for (const p of dir === 'in' ? s.inputs : s.outputs) {
if (!!p.bus !== bus) continue
if (pinKindOf(p) !== bus) continue
const dx = n.x + p.dx - at[0]
const dy = n.y + p.dy - at[1]
const dd = dx * dx + dy * dy
@ -777,7 +802,7 @@ function targetAt(at: Pt, dir: 'in' | 'out', bus = false): PinRef | null {
if (best) return best
const n = nodeAt(at)
if (!n) return null
const pins = (dir === 'in' ? shapes.value.get(n.id)!.inputs : shapes.value.get(n.id)!.outputs).filter(p => !!p.bus === bus)
const pins = (dir === 'in' ? shapes.value.get(n.id)!.inputs : shapes.value.get(n.id)!.outputs).filter(p => pinKindOf(p) === bus)
if (!pins.length) return null
const taken = linked.value[dir]
const free = pins.find(p => !taken.has(`${n.id}:${p.key}`))
@ -827,7 +852,7 @@ function onPointerUp(e: PointerEvent) {
break
}
const onWire = wireDrop(d)
const target = targetAt(d.cur, d.dir === 'out' ? 'in' : 'out', ed.isBus(d.node, d.pin, d.dir)) ?? onWire?.pin
const target = targetAt(d.cur, d.dir === 'out' ? 'in' : 'out', ed.pinKind(d.node, d.pin, d.dir)) ?? onWire?.pin
if (!target) break
if (d.replace) {
ed.rewire(d.replace, d.dir === 'out' ? here : target, d.dir === 'out' ? target : here)
@ -1044,17 +1069,20 @@ const tempWire = computed(() => {
const p = pinPos(n, shapes.value.get(n.id)!, d.pin, d.dir)
if (!p) return null
const want = d.dir === 'out' ? 'in' : 'out'
const target = targetAt(d.cur, want, ed.isBus(d.node, d.pin, d.dir))
const target = targetAt(d.cur, want, ed.pinKind(d.node, d.pin, d.dir))
let end: Pt = [Math.round(d.cur[0]), Math.round(d.cur[1])]
// The side the far end faces: a snapped pin's own, else the usual one.
let endFace: 1 | -1 = want === 'in' ? -1 : 1
if (target) {
const tn = nodeMap.value.get(target.node)!
const tp = pinPos(tn, shapes.value.get(tn.id)!, target.pin, want)!
end = [tp.x, tp.y]
endFace = tp.face
}
const pts =
d.dir === 'out'
? routeWire([p.x, p.y], end, d.branch && branchTo(d.branch, [p.x, p.y], end))
: routeWire(end, [p.x, p.y])
? routeWire([p.x, p.y], end, d.branch && branchTo(d.branch, [p.x, p.y], end), p.face, endFace)
: routeWire(end, [p.x, p.y], undefined, endFace, p.face)
return { d: toPath(pts), snapped: !!target, end }
})
@ -1066,11 +1094,11 @@ const isCable = (w: Wire) => nodeMap.value.get(w.from.node)?.kind === 'bundle'
* what that wire fed, in its place.
*/
function wireDrop(d: { node: string; pin: string; dir: 'in' | 'out'; cur: Pt; replace?: string }) {
if (targetAt(d.cur, d.dir === 'out' ? 'in' : 'out', ed.isBus(d.node, d.pin, d.dir))) return null
const bus = ed.isBus(d.node, d.pin, d.dir)
if (targetAt(d.cur, d.dir === 'out' ? 'in' : 'out', ed.pinKind(d.node, d.pin, d.dir))) return null
const bus = ed.pinKind(d.node, d.pin, d.dir)
for (let i = routes.value.length - 1; i >= 0; i--) {
const r = routes.value[i]!
if (r.wire.id === d.replace || !!r.bits !== bus) continue
if (r.wire.id === d.replace || r.kind !== bus) continue
if (d.dir === 'in' ? r.wire.to.node === d.node && r.wire.to.pin === d.pin : r.wire.from.node === d.node && r.wire.from.pin === d.pin) continue
const seg = segmentAt(r.pts, d.cur, 0.35)
if (seg < 0) continue
@ -1109,13 +1137,13 @@ const targets = computed(() => {
const d = pending.value
if (!d) return []
const want = d.dir === 'out' ? 'in' : 'out'
const bus = ed.isBus(d.node, d.pin, d.dir)
const bus = ed.pinKind(d.node, d.pin, d.dir)
const taken = linked.value[want]
const out: { x: number; y: number; free: boolean }[] = []
for (const n of def.value.nodes) {
const s = shapes.value.get(n.id)!
for (const p of want === 'in' ? s.inputs : s.outputs) {
if (!!p.bus !== bus) continue
if (pinKindOf(p) !== bus) continue
// An output can always take one more wire; an input only has room for one.
out.push({ x: n.x + p.dx, y: n.y + p.dy, free: want === 'out' || !taken.has(`${n.id}:${p.key}`) })
}
@ -1388,9 +1416,10 @@ defineExpose({ fit, zoomAt })
:key="r.wire.id"
class="wire"
:class="[
r.wire.color ? `c-${r.wire.color}` : '',
r.wire.color ? `c-${r.wire.color}` : r.port?.color ? `c-${r.port.color}` : '',
{
on: srcVal(r.src) === 1,
'port-cable': !!r.port,
selected: wireSelected.has(r.wire.id),
hover: hoverSrc === r.src,
cable: !!r.bits,
@ -1400,7 +1429,12 @@ defineExpose({ fit, zoomAt })
]"
>
<path v-if="wireSelected.has(r.wire.id)" :d="r.d" class="wire-halo" :style="r.sleeve ? { strokeWidth: `${r.sleeve + 9}px` } : undefined" />
<template v-if="r.lanes">
<template v-if="r.port">
<!-- A cable between connector ports: one sleeve, named after its type -->
<path :d="r.d" class="cable-sleeve" :style="{ strokeWidth: `${r.sleeve! + 3}px` }" />
<path :d="r.d" class="cable-core" :style="{ strokeWidth: `${r.sleeve}px` }" />
</template>
<template v-else-if="r.lanes">
<!-- Ribbon cable: a sleeve in the cable's colour, one line per wire inside -->
<path :d="r.d" class="cable-sleeve" :style="{ strokeWidth: `${r.sleeve! + 3}px` }" />
<path :d="r.d" class="cable-core" :style="{ strokeWidth: `${r.sleeve}px` }" />
@ -1433,6 +1467,9 @@ defineExpose({ fit, zoomAt })
<text x="6" :y="r.sleeve ? -r.sleeve / 2 - 4 : -6">{{ r.bits }}</text>
<text x="6" :y="r.sleeve ? r.sleeve / 2 + 11 : 14" class="cable-value">= {{ cableValue(r)?.dec }}</text>
</g>
<g v-if="r.port && r.mark" class="cable-mark port-mark" :transform="`translate(${r.mark[0] * G} ${r.mark[1] * G})`">
<text text-anchor="middle" :y="-r.sleeve! / 2 - 5">{{ r.port.name }}</text>
</g>
<title v-if="hoverWire === r.wire.id">{{ wireTip(r) }}</title>
</g>
<g v-for="(j, i) in junctions" :key="`j${i}`" class="wire" :class="[j.color ? `c-${j.color}` : '', { on: srcVal(j.src) === 1 }]">

View File

@ -0,0 +1,138 @@
<script setup lang="ts">
// Edit a connector type of your own, like HDMI or RJ45: its name, colour and
// lines. A line runs out → in (from an "out" port to an "in" port), or back.
// Every port and cable of this type follows the changes.
import { WIRE_COLORS, type ConnectorType, type WireColor } from '~/lib/logic/types'
const ed = useEditor()
const close = () => (ed.dialog.value = null)
const type = computed<ConnectorType | undefined>(() => ed.project.value.connectors?.find(c => c.id === ed.connectorFor.value))
const uses = computed(() => (type.value ? ed.connectorUses(type.value.id) : 0))
const confirmDelete = ref(false)
/** Every change is one step to undo, and reaches every port of this type. */
const save = () => ed.commit()
function setName(e: Event) {
if (!type.value) return
type.value.name = (e.target as HTMLInputElement).value.trim().slice(0, 40) || 'Connector'
save()
}
function setColor(c: WireColor | undefined) {
if (!type.value) return
if (c) type.value.color = c
else delete type.value.color
save()
}
function setLine(i: number, e: Event) {
const line = type.value?.lines[i]
if (!line) return
line.name = (e.target as HTMLInputElement).value.trim().slice(0, 24) || `L${i}`
save()
}
function flip(i: number) {
const line = type.value?.lines[i]
if (!line) return
if (line.back) delete line.back
else line.back = true
save()
}
function move(i: number, by: number) {
const lines = type.value?.lines
if (!lines || i + by < 0 || i + by >= lines.length) return
const [l] = lines.splice(i, 1)
lines.splice(i + by, 0, l!)
save()
}
function remove(i: number) {
type.value?.lines.splice(i, 1)
save()
}
function addLine() {
const lines = type.value?.lines
if (!lines || lines.length >= 64) return
// Continue a series: D0, D1 → D2.
const last = lines.at(-1)?.name ?? 'D-1'
const m = /^(.*?)(\d+)$/.exec(last)
lines.push({ name: m ? `${m[1]}${Number(m[2]) + 1}` : `L${lines.length}` })
save()
nextTick(() => document.querySelector<HTMLInputElement>('.conn-lines li:last-child input')?.select())
}
function remove_type() {
if (!type.value) return
ed.removeConnector(type.value.id)
}
const forward = computed(() => type.value?.lines.filter(l => !l.back).length ?? 0)
</script>
<template>
<div class="modal-backdrop" @click.self="close">
<div v-if="type" class="modal conn-modal" role="dialog" aria-labelledby="conn-title">
<div class="flex items-start justify-between gap-4">
<div>
<h2 id="conn-title">Connector type</h2>
<p class="hint mt-1">
A cable of this type joins an <strong>out</strong> port to an <strong>in</strong> port and carries all its lines.
{{ uses ? `Used by ${uses} port${uses === 1 ? '' : 's'}; they follow every change.` : 'Not used yet: place its ports from the Connectors list.' }}
</p>
</div>
<button class="tb-btn" title="Close" @click="close"><Icon name="lucide:x" class="size-4" /></button>
</div>
<div class="sel-row mt-4">
<label class="field grow">
<span>Name</span>
<input :value="type.name" maxlength="40" placeholder="e.g. HDMI, RJ45, Bus" @change="setName" @keydown.enter="($event.target as HTMLInputElement).blur()" />
</label>
</div>
<div class="field">
<span>Colour of its cables</span>
<div class="swatches">
<button class="swatch none" :class="{ active: !type.color }" title="Default: grey" @click="setColor(undefined)" />
<button v-for="c in WIRE_COLORS" :key="c" class="swatch" :class="[`c-${c}`, { active: type.color === c }]" :title="c" @click="setColor(c)" />
</div>
</div>
<div class="field">
<span>Lines ({{ forward }} out → in, {{ type.lines.length - forward }} back)</span>
<ul class="conn-lines">
<li v-for="(l, i) in type.lines" :key="i">
<span class="conn-index">{{ i }}</span>
<input :value="l.name" maxlength="24" @change="setLine(i, $event)" @keydown.enter="($event.target as HTMLInputElement).blur()" />
<button
class="btn-sm conn-dir"
:class="{ back: l.back }"
:title="l.back ? 'Runs back: from the in port to the out port (like an acknowledge or hot-plug line). Click to turn it around.' : 'Runs from the out port to the in port. Click to make it a line back.'"
@click="flip(i)"
>
{{ l.back ? '← back' : 'out → in' }}
</button>
<button class="icon-btn" title="Move up" :disabled="i === 0" @click="move(i, -1)"><Icon name="lucide:arrow-up" class="size-3.5" /></button>
<button class="icon-btn" title="Move down" :disabled="i === type.lines.length - 1" @click="move(i, 1)"><Icon name="lucide:arrow-down" class="size-3.5" /></button>
<button class="icon-btn danger" title="Remove this line" @click="remove(i)"><Icon name="lucide:x" class="size-3.5" /></button>
</li>
</ul>
<button class="btn-sm self-start" :disabled="type.lines.length >= 64" @click="addLine"><Icon name="lucide:plus" class="size-3.5" /> Add line</button>
<p v-if="uses" class="hint mt-2">Ports and cables match lines by their place in this list: moving a line moves what it carries.</p>
</div>
<div class="mt-4 flex items-center gap-2">
<button class="btn btn-primary" @click="close">Done</button>
<span class="grow" />
<button v-if="!confirmDelete" class="btn btn-ghost" :disabled="uses > 0" :title="uses ? 'Still used by ports' : ''" @click="confirmDelete = true">
<Icon name="lucide:trash-2" class="size-4" /> Delete type
</button>
<button v-else class="btn btn-danger" @click="remove_type">Really delete?</button>
</div>
</div>
</div>
</template>

View File

@ -23,6 +23,7 @@ const SHORTCUTS: [string, string][] = [
['Right or middle drag, Space + drag', 'Move the view'],
['Mouse wheel', 'Zoom'],
['N, I, O, L, B, C, H, T, P, X', 'Place NAND, input, output, lamp, button, clock, hex display, note, input panel, pixel'],
['Connectors (parts list)', 'Make a cable type of your own (HDMI, RJ45): its lines; place its Out and In ports; one cable joins them'],
['Select wires, Ctrl+G', 'Bundle them into one cable; an end whose wires all meet one part plugs straight into it'],
['Select a component, cable button beside its pins', 'A cable plugged onto S0–S3 (or any group); drop its free end on the next part\'s pins'],
['Drag a part from the list onto pins', 'It lands on them and connects (green rings show where); Alt just places it'],

View File

@ -152,7 +152,7 @@ const cables = computed(() => ed.cableChoices(n.value))
const invertible = computed(() => {
if (!INVERTIBLE.has(n.value.kind)) return []
const inv = new Set(n.value.invert ?? [])
return ed.shape(n.value).inputs.map((p, i) => ({ key: p.key, label: p.label || (n.value.kind === 'nand' ? 'AB'[i]! : 'In'), on: inv.has(p.key) }))
return ed.shape(n.value).inputs.filter(p => !p.bus).map((p, i) => ({ key: p.key, label: p.label || (n.value.kind === 'nand' ? 'AB'[i]! : 'In'), on: inv.has(p.key) }))
})
const inverted = computed(() => invertible.value.filter(p => p.on).length)
@ -166,6 +166,19 @@ const transistorNote = computed(() =>
: 'No logic gate inside',
)
// Connector ports: which type, and which side of the box.
const connTypes = computed(() => ed.project.value.connectors ?? [])
function setConn(id: string) {
if (!id || id === n.value.conn) return
n.value.conn = id
ed.commit()
}
function setSide(kind: 'portin' | 'portout') {
if (kind === n.value.kind) return
n.value.kind = kind
ed.commit()
}
// The "more" button opens the same list as a right click on the part.
const menu = useMenu()
const more = ref<{ x: number; y: number; entries: MenuEntry[] } | null>(null)
@ -292,6 +305,28 @@ function setRowHz(row: PanelRow, e: Event) {
@keydown.enter="($event.target as HTMLInputElement).blur()"
/>
</label>
<template v-if="n.kind === 'portin' || n.kind === 'portout'">
<div class="sel-row">
<label class="field grow" title="Changing it unplugs cables of the old type">
<span>Connector type</span>
<select :value="n.conn ?? ''" @change="setConn(($event.target as HTMLSelectElement).value)">
<option v-if="!n.conn || !connTypes.some(c => c.id === n.conn)" value="" disabled>Pick a type</option>
<option v-for="c in connTypes" :key="c.id" :value="c.id">{{ c.name }} ({{ c.lines.length }} lines)</option>
</select>
</label>
<label class="field narrow" title="In: a cable comes in here (the port sits on the left of the box). Out: a cable leaves here (on the right).">
<span>Side</span>
<select :value="n.kind" @change="setSide(($event.target as HTMLSelectElement).value as 'portin' | 'portout')">
<option value="portin">In</option>
<option value="portout">Out</option>
</select>
</label>
</div>
<button class="btn mb-2 w-full" :disabled="!n.conn" @click="ed.editConnector(n.conn!)">
<Icon name="lucide:cable" class="size-4" /> Edit the type's lines
</button>
</template>
<datalist id="signal-names">
<option v-for="name in signalNames" :key="name" :value="name" />
</datalist>

View File

@ -2,7 +2,7 @@
import { gateDrawing, sevenSegment } from '~/lib/draw'
import { LANE, nameTags, RIBBON_MAX } from '~/lib/logic/cables'
import { baseOf, gateFamily, inputCount, MAX_GATE_INPUTS } from '~/lib/logic/wide'
import { faceTransform, GRID as G, noteLines, noteScale, PANEL_CONTROL_W, shapeTransform, type Shape } from '~/lib/logic/geometry'
import { faceTransform, GRID as G, noteLines, noteScale, PANEL_CONTROL_W, portLines, shapeTransform, type Shape } from '~/lib/logic/geometry'
import type { CircuitNode } from '~/lib/logic/types'
const props = defineProps<{
@ -26,6 +26,16 @@ const style = computed(() => ed.project.value.settings.symbols)
const gate = computed(() => (props.shape.gate ? gateDrawing(props.shape, style.value) : null))
const chipDef = computed(() => (props.node.chip ? ed.getDef.value(props.node.chip) : undefined))
const b = computed(() => props.shape.body)
// Connector ports: their type, lines and colour.
const CONN_HEX: Record<string, string> = { red: '#ff5c5c', orange: '#ff9f43', yellow: '#ffd93d', green: '#3ddc84', blue: '#4dabff', purple: '#b388ff', pink: '#ff7ac6' }
const connColor = (id?: string) => {
const c = id ? ed.getDef.value.conn?.(id)?.color : undefined
return c ? CONN_HEX[c] ?? '#8592a3' : '#8592a3'
}
const connType = computed(() => (props.node.conn ? ed.getDef.value.conn?.(props.node.conn) : undefined))
const connName = computed(() => connType.value?.name ?? 'Port')
const lines = computed(() => (props.node.kind === 'portin' || props.node.kind === 'portout' ? portLines(props.node, ed.getDef.value) : []))
const rows = computed(() => props.node.rows ?? [])
// A name typed by hand shows as is. Otherwise the name of the pin the part is
// wired to, or its automatic name, shows dimmed.
@ -324,6 +334,27 @@ const title = computed(() => {
<path :d="`M${b.w * G} 0H${(b.w + 0.5) * G}`" class="stub" />
</template>
<!-- Connector port: the type on top, its lines along the inner side -->
<template v-else-if="node.kind === 'portin' || node.kind === 'portout'">
<rect :x="0" :y="b.y * G" :width="b.w * G" :height="b.h * G" rx="3" class="body port" />
<rect :x="0" :y="b.y * G" :width="b.w * G" :height="0.95 * G" rx="3" class="port-head" :style="{ fill: connColor(node.conn) }" />
<text :x="(b.w * G) / 2" :y="b.y * G + 0.68 * G" text-anchor="middle" class="port-title">
{{ connName }} {{ node.kind === 'portin' ? 'in' : 'out' }}<template v-if="node.label?.trim()"> · {{ node.label.trim() }}</template>
</text>
<text
v-for="l in lines"
:key="l.key"
:x="node.kind === 'portin' ? b.w * G - 7 : 7"
:y="(Number(l.key.slice(1)) + 1) * G + 3.5"
:text-anchor="node.kind === 'portin' ? 'end' : 'start'"
class="pin-label port-line"
>
<template v-if="node.kind === 'portin'">{{ l.name }} {{ l.enters ? '→' : '←' }}</template>
<template v-else>{{ l.enters ? '←' : '→' }} {{ l.name }}</template>
</text>
<text v-if="!lines.length" :x="(b.w * G) / 2" :y="G + 3.5" text-anchor="middle" class="pin-label">{{ node.conn && !connType ? 'type missing' : 'no lines' }}</text>
</template>
<!-- Pixel: one square of a screen -->
<template v-else-if="node.kind === 'pixel'">
<rect x="1" :y="b.y * G + 1" :width="G - 2" :height="G - 2" rx="1" class="pixel" :class="[node.color ? `px-${node.color}` : '', { on: v('a') === 1 }]" />
@ -411,11 +442,13 @@ const title = computed(() => {
<g v-for="p in shape.inputs" :key="`i-${p.key}`">
<path v-if="open?.has(p.key)" :d="`M${p.dx * G - 8} ${p.dy * G - 3.5}L${p.dx * G - 3} ${p.dy * G}L${p.dx * G - 8} ${p.dy * G + 3.5}Z`" class="open-pin" />
<circle :cx="p.dx * G" :cy="p.dy * G" r="7" class="pin-hit" :data-node="node.id" :data-pin="p.key" data-dir="in" />
<circle v-if="dot(p.key)" :cx="p.dx * G" :cy="p.dy * G" r="2.6" class="pin" :class="{ on: v(p.key) === 1 }" />
<rect v-if="p.conn" :x="p.dx * G - 4" :y="p.dy * G - 5" width="8" height="10" rx="2" class="port-socket" :style="{ fill: connColor(p.conn) }" />
<circle v-else-if="dot(p.key)" :cx="p.dx * G" :cy="p.dy * G" r="2.6" class="pin" :class="{ on: v(p.key) === 1 }" />
</g>
<g v-for="p in shape.outputs" :key="`o-${p.key}`">
<circle :cx="p.dx * G" :cy="p.dy * G" r="7" class="pin-hit" :data-node="node.id" :data-pin="p.key" data-dir="out" />
<circle v-if="dot(p.key)" :cx="p.dx * G" :cy="p.dy * G" r="2.6" class="pin" :class="{ on: v(p.key) === 1 }" />
<rect v-if="p.conn" :x="p.dx * G - 4" :y="p.dy * G - 5" width="8" height="10" rx="2" class="port-socket" :style="{ fill: connColor(p.conn) }" />
<circle v-else-if="dot(p.key)" :cx="p.dx * G" :cy="p.dy * G" r="2.6" class="pin" :class="{ on: v(p.key) === 1 }" />
</g>
</template>
</g>

View File

@ -76,14 +76,36 @@ function pick(kind: NodeKind, chip?: string) {
ed.placing.value = { kind, chip }
}
function onDragStart(e: DragEvent, kind: NodeKind, chip?: string) {
// ── Connector ports ──
const connectors = computed(() => ed.project.value.connectors ?? [])
const PORT_SIDES = [
{ kind: 'portout' as NodeKind, label: 'Out', hint: (n: string) => `${n} out: where a ${n} cable leaves this circuit. On its box it is one port on the right.` },
{ kind: 'portin' as NodeKind, label: 'In', hint: (n: string) => `${n} in: where a ${n} cable comes into this circuit. On its box it is one port on the left.` },
]
/** In a campaign, ports come with cables. */
const portsOk = computed(() => ed.canPlaceKind('portin'))
function pickPort(kind: NodeKind, conn: string) {
if (!portsOk.value) {
ed.play('error')
return ed.notify(lockedHint(kind), 'error')
}
ed.placing.value = { kind, conn }
}
function newConnector() {
if (!portsOk.value) return ed.notify(lockedHint('portin'), 'error')
ed.addConnector()
}
function onDragStart(e: DragEvent, kind: NodeKind, chip?: string, conn?: string) {
if (chip && !ed.canPlace(chip)) {
e.preventDefault()
return
}
e.dataTransfer?.setData('application/x-logigate', JSON.stringify({ kind, chip }))
e.dataTransfer?.setData('application/x-logigate', JSON.stringify({ kind, chip, conn }))
if (e.dataTransfer) e.dataTransfer.effectAllowed = 'copy'
ed.dragPart.value = { kind, chip }
ed.dragPart.value = { kind, chip, conn }
}
const solved = computed(() => new Set(ed.project.value.solved))
@ -208,6 +230,41 @@ const started = computed(() => new Map(ed.project.value.components.filter(d => d
</ul>
</template>
<!-- Connector types you made: place their ports, edit them, add new ones -->
<button class="group-head" @click="fold('connectors')">
<Icon :name="folded.has('connectors') ? 'lucide:chevron-right' : 'lucide:chevron-down'" class="size-3.5" />
<span>Connectors</span>
<span v-if="connectors.length" class="group-count">{{ connectors.length }}</span>
</button>
<ul v-if="!folded.has('connectors')" class="items">
<li v-for="c in connectors" :key="c.id" class="comp-row conn-row" :class="{ blocked: !portsOk }">
<span class="conn-swatch" :class="c.color ? `c-${c.color}` : ''" />
<span class="grow truncate" :title="`${c.lines.length} lines: ${c.lines.map(l => (l.back ? `${l.name} (back)` : l.name)).join(', ')}`">{{ c.name }}</span>
<button
v-for="side in PORT_SIDES"
:key="side.kind"
class="btn-sm port-pick"
:class="{ active: ed.placing.value?.kind === side.kind && ed.placing.value?.conn === c.id }"
:title="side.hint(c.name)"
:draggable="portsOk"
@click="pickPort(side.kind, c.id)"
@dragstart="onDragStart($event, side.kind, undefined, c.id)"
@dragend="ed.dragPart.value = null"
>
{{ side.label }}
</button>
<button class="open" title="Edit this connector type: name, colour, lines" @click="ed.editConnector(c.id)">
<Icon name="lucide:pencil" class="size-3.5" />
</button>
</li>
<li>
<button class="item" :class="{ blocked: !portsOk }" title="Make a connector type of your own, like HDMI or RJ45: a name, a colour and its lines" @click="newConnector">
<Icon name="lucide:plus" class="size-4 shrink-0 text-(--muted)" />
<span class="grow truncate">New connector type</span>
</button>
</li>
</ul>
<template v-for="g in componentGroups" :key="g.name">
<button class="group-head" @click="fold(`c:${g.name}`)">
<Icon :name="folded.has(`c:${g.name}`) ? 'lucide:chevron-right' : 'lucide:chevron-down'" class="size-3.5" />

View File

@ -24,7 +24,7 @@ import { apiId, makePuzzle, scoreSolution, weekKey, weeklyId } from '~/lib/logic
import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide'
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
import { compile, INVERTIBLE, invertedPins, rowSource } from '~/lib/logic/compile'
import { chipPins, MAX_BITS, panelOffsets, shapeOf, type Pt } from '~/lib/logic/geometry'
import { chipPins, MAX_BITS, panelOffsets, pinKindOf, shapeOf, type Pt } from '~/lib/logic/geometry'
import { adoptName, continueSeries, newPinLabel, uniqueLabel, usedLabels } from '~/lib/logic/labels'
import { attachPanel, combineIntoPanel, detachPanel, dockedPanels, mergePanels, newPanelRows, removeRow, syncPanels } from '~/lib/logic/panels'
import {
@ -71,7 +71,7 @@ import {
type AccountUser,
type ProjectMeta,
} from '~/lib/logic/storage'
import type { CircuitNode, LampColor, NodeKind, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types'
import type { CircuitNode, ConnectorType, LampColor, NodeKind, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types'
/** A challenge check plus how many transistors the solution uses. */
/** How everyone did on a puzzle, from the server. */
@ -108,6 +108,8 @@ export interface LinkEnd {
export interface Placing {
kind: NodeKind
chip?: string
/** Port: its connector type. */
conn?: string
keep?: boolean
}
@ -163,7 +165,7 @@ function create() {
const notice = ref<{ text: string; kind: 'ok' | 'error' } | null>(null)
const labelFocus = ref(0)
const showHelp = ref(false)
const dialog = ref<null | 'share' | 'account' | 'versions' | 'table' | 'publish' | 'settings' | 'search' | 'face'>(null)
const dialog = ref<null | 'connector' | 'share' | 'account' | 'versions' | 'table' | 'publish' | 'settings' | 'search' | 'face'>(null)
/** The component whose box is being drawn in the face designer. */
const faceFor = ref<string | null>(null)
function designFace(defId: string) {
@ -232,7 +234,7 @@ function create() {
}
// ── History ───────────────────────────────────────────────────────
const snap = () => JSON.stringify({ components: project.value.components, solved: project.value.solved })
const snap = () => JSON.stringify({ components: project.value.components, solved: project.value.solved, connectors: project.value.connectors })
let last = snap()
const undoStack: string[] = []
const redoStack: string[] = []
@ -272,9 +274,11 @@ function create() {
}
function restore(s: string) {
const data = JSON.parse(s) as Pick<Project, 'components' | 'solved'>
const data = JSON.parse(s) as Pick<Project, 'components' | 'solved' | 'connectors'>
project.value.components = data.components
project.value.solved = data.solved
if (data.connectors) project.value.connectors = data.connectors
else delete project.value.connectors
if (!project.value.components.some(d => d.id === project.value.openId)) project.value.openId = project.value.components[0]!.id
last = s
selection.value = selection.value.filter(id => def.value.nodes.some(n => n.id === id))
@ -463,6 +467,7 @@ function create() {
function addNode(p: Placing, x: number, y: number, links: Link[] = []): CircuitNode {
const node: CircuitNode = { id: uid('n'), kind: p.kind, x, y }
if (p.chip) node.chip = p.chip
if (p.conn) node.conn = p.conn
if (p.kind === 'input' || p.kind === 'output') {
node.label = newPinLabel(def.value, p.kind)
node.autoLabel = true
@ -509,18 +514,22 @@ function create() {
if (patch.on || patch.volume !== undefined) play('on')
}
/** True when the pin is a cable end (bundle output, split input). */
function isBus(nodeId: string, pin: string, dir: 'in' | 'out'): boolean {
/** What a pin plugs into: '' a single wire, 'bus' a cable end, 'c:<id>' a port of that connector type. Wires join pins of one kind. */
function pinKind(nodeId: string, pin: string, dir: 'in' | 'out'): string {
const n = def.value.nodes.find(x => x.id === nodeId)
if (!n) return false
if (!n) return ''
const s = shapeOf(n, getDef.value)
return !!(dir === 'in' ? s.inputs : s.outputs).find(p => p.key === pin)?.bus
const p = (dir === 'in' ? s.inputs : s.outputs).find(p => p.key === pin)
return p ? pinKindOf(p) : ''
}
/** True when the pin is a cable end or a port. */
const isBus = (nodeId: string, pin: string, dir: 'in' | 'out') => pinKind(nodeId, pin, dir) !== ''
/** Adds one wire (replacing whatever fed that input) without recording an undo step. False for a cable/wire mismatch. */
function addWire(from: PinRef, to: PinRef, pts?: Pt[]): boolean {
const d = def.value
if (isBus(from.node, from.pin, 'out') !== isBus(to.node, to.pin, 'in')) return false
if (pinKind(from.node, from.pin, 'out') !== pinKind(to.node, to.pin, 'in')) return false
const old = d.wires.find(w => w.to.node === to.node && w.to.pin === to.pin)
d.wires = d.wires.filter(w => w !== old)
const wire: (typeof d.wires)[number] = { id: uid('w'), from, to }
@ -538,10 +547,19 @@ function create() {
return true
}
/** Why two pins can't be joined, in words. */
function mismatch(from: PinRef, to: PinRef): string {
const name = (k: string) => (k.startsWith('c:') ? (getDef.value.conn?.(k.slice(2))?.name ?? 'connector') : '')
const a = name(pinKind(from.node, from.pin, 'out'))
const b = name(pinKind(to.node, to.pin, 'in'))
if (a || b) return a && b ? `A ${a} port only plugs into a ${a} port, not ${b}` : `A ${a || b} port only takes a ${a || b} cable from another ${a || b} port`
return 'A cable runs from a bundle to a split; single wires go to the bundle’s and split’s side pins'
}
function connect(from: PinRef, to: PinRef, pts?: Pt[]) {
if (!addWire(from, to, pts)) {
play('error')
return notify('A cable runs from a bundle to a split; single wires go to the bundle’s and split’s side pins', 'error')
return notify(mismatch(from, to), 'error')
}
wireSel.value = []
commit()
@ -557,9 +575,9 @@ function create() {
const old = d.wires.find(w => w.id === wireId)
if (!old) return
if (old.from.node === from.node && old.from.pin === from.pin && old.to.node === to.node && old.to.pin === to.pin) return
if (isBus(from.node, from.pin, 'out') !== isBus(to.node, to.pin, 'in')) {
if (pinKind(from.node, from.pin, 'out') !== pinKind(to.node, to.pin, 'in')) {
play('error')
return notify('A cable pin only joins another cable pin', 'error')
return notify(mismatch(from, to), 'error')
}
d.wires = d.wires.filter(w => w !== old)
addWire(from, to)
@ -1497,6 +1515,41 @@ function create() {
commit()
}
// ── Connector types ─────────────────────────────────────────────
/** The connector type open in the connector dialog. */
const connectorFor = ref<string | null>(null)
/** A new connector type with two lines, opened for editing. */
function addConnector(): ConnectorType {
const names = new Set((project.value.connectors ?? []).map(c => c.name.toLowerCase()))
let name = 'Connector'
for (let i = 2; names.has(name.toLowerCase()); i++) name = `Connector ${i}`
const c: ConnectorType = { id: uid('k'), name, lines: [{ name: 'D0' }, { name: 'D1' }] }
project.value.connectors = [...(project.value.connectors ?? []), c]
commit()
editConnector(c.id)
return c
}
function editConnector(id: string) {
connectorFor.value = id
dialog.value = 'connector'
}
/** Where a connector type is used: ports in all circuits. */
function connectorUses(id: string): number {
return project.value.components.reduce((n, d) => n + d.nodes.filter(x => x.conn === id && (x.kind === 'portin' || x.kind === 'portout')).length, 0)
}
function removeConnector(id: string) {
const uses = connectorUses(id)
if (uses) return notify(`Still used by ${uses} port${uses === 1 ? '' : 's'}: change or delete those first`, 'error')
project.value.connectors = (project.value.connectors ?? []).filter(c => c.id !== id)
if (!project.value.connectors.length) delete project.value.connectors
if (connectorFor.value === id) dialog.value = null
commit()
}
// ── Cables ────────────────────────────────────────────────────────
/** Bundling with a chosen route: the next click places the start of the cable, the one after its end. */
const cabling = ref<{ wires: string[]; start?: Pt } | null>(null)
@ -2263,6 +2316,12 @@ function create() {
openPuzzle,
publishPuzzle,
isBus,
pinKind,
connectorFor,
addConnector,
editConnector,
connectorUses,
removeConnector,
bundleSelected,
cabling,
startCable,

View File

@ -2,7 +2,7 @@
// nets. Chip boundaries and input/output pins disappear: they are aliases,
// merged with union-find. Net 0 is constant LOW, net 1 constant HIGH.
import { cableBits, chipPins, isPinRow, rowPin, type ChipPins, type DefLookup } from './geometry'
import { cableBits, chipPins, isPinRow, portLines, rowPin, type ChipPins, type DefLookup } from './geometry'
import type { CircuitNode, ComponentDef, Wire } from './types'
export const LOW = 0
@ -34,8 +34,12 @@ export interface Netlist {
errors: string[]
}
export function inputKeys(node: CircuitNode, pins?: ChipPins): string[] {
export function inputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup): string[] {
switch (node.kind) {
case 'portin':
return get ? portLines(node, get).filter(l => !l.enters).map(l => l.key) : []
case 'portout':
return ['bus', ...(get ? portLines(node, get).filter(l => !l.enters).map(l => l.key) : [])]
case 'nand':
return ['a', 'b']
case 'output':
@ -51,14 +55,21 @@ export function inputKeys(node: CircuitNode, pins?: ChipPins): string[] {
case 'bundle':
return cableKeys(node)
case 'chip':
return pins ? pins.inputs.map(p => p.key) : []
return pins ? [...pins.inputs.map(p => p.key), ...portKeys(pins, 'in')] : []
default:
return []
}
}
export function outputKeys(node: CircuitNode, pins?: ChipPins): string[] {
/** Keys of a component's connector ports on one side. */
const portKeys = (pins: ChipPins, side: 'in' | 'out') => (pins.ports ?? []).filter(p => p.side === side).map(p => p.key)
export function outputKeys(node: CircuitNode, pins?: ChipPins, get?: DefLookup): string[] {
switch (node.kind) {
case 'portin':
return ['bus', ...(get ? portLines(node, get).filter(l => l.enters).map(l => l.key) : [])]
case 'portout':
return get ? portLines(node, get).filter(l => l.enters).map(l => l.key) : []
case 'output':
case 'lamp':
return ['q']
@ -71,7 +82,7 @@ export function outputKeys(node: CircuitNode, pins?: ChipPins): string[] {
case 'ref':
return ['q']
case 'chip':
return pins ? pins.outputs.map(p => p.key) : []
return pins ? [...pins.outputs.map(p => p.key), ...portKeys(pins, 'out')] : []
case 'hex':
return ['q0', 'q1', 'q2', 'q3']
case 'panel':
@ -152,7 +163,14 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
return p
}
const expand = (def: ComponentDef, inNets: Map<string, number> | null, path: string, stack: string[]): Map<string, number> => {
// `portNets`: for each port part of this component, the nets of its lines, from the parent that placed it.
const expand = (
def: ComponentDef,
inNets: Map<string, number> | null,
path: string,
stack: string[],
portNets?: Map<string, number[]>,
): Map<string, number> => {
const result = new Map<string, number>()
if (stack.includes(def.id)) {
errors.push(`"${def.name}" contains itself`)
@ -167,10 +185,12 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
const wiresTo = new Map<string, Wire>()
for (const w of def.wires) wiresTo.set(`${w.to.node}:${w.to.pin}`, w)
const nodeById = new Map(def.nodes.map(n => [n.id, n]))
// Ends of typed cables ("node:pin"): the nets of their lines, joined line by line below.
const ends = new Map<string, number[]>()
const outNet = new Map<string, number>()
for (const n of def.nodes) {
for (const k of outputKeys(n, pinsOf(n))) outNet.set(`${n.id}:${k}`, make())
for (const k of outputKeys(n, pinsOf(n), getDef)) outNet.set(`${n.id}:${k}`, make())
}
const inNet = (nodeId: string, pin: string) => {
const w = wiresTo.get(`${nodeId}:${pin}`)
@ -272,6 +292,20 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
if (!n.inner) result.set(rowPin(n.id, r.id), net)
}
break
case 'portin':
case 'portout': {
// A connector port: its lines are the nets the parent handed in (fresh ones at the top).
const lines = portLines(n, getDef)
const nets = portNets?.get(n.id) ?? lines.map(() => make())
ends.set(`${n.id}:bus`, nets)
lines.forEach((l, i) => {
const net = nets[i]
if (net === undefined) return
if (l.enters) union(outNet.get(`${n.id}:${l.key}`)!, net)
else if (wiresTo.has(`${n.id}:${l.key}`)) union(inNet(n.id, l.key), net)
})
break
}
case 'chip': {
const child = n.chip ? getDef(n.chip) : undefined
const pins = pinsOf(n)
@ -281,13 +315,26 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
}
const childIn = new Map<string, number>()
for (const p of pins.inputs) childIn.set(p.key, pinIn(n, p.key))
const childOut = expand(child, childIn, `${path}${n.id}/`, inner)
const childPorts = new Map<string, number[]>()
for (const p of pins.ports ?? []) {
const nets = (getDef.conn?.(p.conn)?.lines ?? []).map(() => make())
childPorts.set(p.key, nets)
ends.set(`${n.id}:${p.key}`, nets)
}
const childOut = expand(child, childIn, `${path}${n.id}/`, inner, childPorts)
for (const p of pins.outputs) union(outNet.get(`${n.id}:${p.key}`)!, childOut.get(p.key) ?? LOW)
break
}
}
}
// Typed cables: line i of one end is line i of the other.
for (const w of def.wires) {
const a = ends.get(`${w.from.node}:${w.from.pin}`)
const b = ends.get(`${w.to.node}:${w.to.pin}`)
if (a && b) for (let i = 0; i < Math.min(a.length, b.length); i++) union(a[i]!, b[i]!)
}
// Lamps, displays and pixels inside placed components, at every depth: a box may show those of parts inside it.
if (stack.length >= 1) {
for (const n of def.nodes) {
@ -302,8 +349,8 @@ export function compile(getDef: DefLookup, rootId: string, opts: { trace?: boole
}
for (const n of def.nodes) {
const pins = pinsOf(n)
for (const k of inputKeys(n, pins)) record(n, k, inNet(n.id, k))
for (const k of outputKeys(n, pins)) record(n, k, outNet.get(`${n.id}:${k}`)!)
for (const k of inputKeys(n, pins, getDef)) record(n, k, inNet(n.id, k))
for (const k of outputKeys(n, pins, getDef)) record(n, k, outNet.get(`${n.id}:${k}`)!)
}
}
return result

View File

@ -3,7 +3,7 @@
// and the pins a part being dragged lands on (connected when it is dropped).
import { byPosition, type Link } from './bulk'
import { shapeOf, type DefLookup, type Pt, type Shape } from './geometry'
import { pinKindOf, shapeOf, type DefLookup, type Pt, type Shape } from './geometry'
import { SOURCE_KINDS } from './ops'
import type { CircuitNode, ComponentDef, PinRef } from './types'
@ -141,7 +141,8 @@ export interface DropPin {
node: string
pin: string
dir: 'in' | 'out'
bus: boolean
/** 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
@ -154,8 +155,8 @@ export function dropPins(def: ComponentDef, nodes: CircuitNode[], shape: ShapeOf
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: !!p.bus, 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: !!p.bus, wired: wired.out.has(`${n.id}:${p.key}`), x: n.x + p.dx, y: n.y + p.dy })
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
}

View File

@ -1,7 +1,7 @@
// Node shapes and pin positions, all in grid units relative to the node's
// (x, y). Pins always sit on whole grid points so straight wires line up.
import type { CircuitNode, ComponentDef, FaceShape, LampColor, PanelRow, SymbolKind } from './types'
import type { CircuitNode, ComponentDef, ConnectorType, FaceShape, LampColor, PanelRow, SymbolKind } from './types'
export const GRID = 16
@ -12,6 +12,10 @@ export interface PinInfo {
dy: number
/** A cable pin: only joins another cable pin. */
bus?: boolean
/** A port of a connector type: only joins a port of the same type (and is a cable pin). */
conn?: string
/** Side the wire leaves (outputs) or arrives from (inputs): 1 right, -1 left. Default: outputs right, inputs left. */
face?: 1 | -1
}
export interface Shape {
@ -61,7 +65,8 @@ export interface FaceItem {
h: number
}
export type DefLookup = (id: string) => ComponentDef | undefined
/** Finds a component by id; `conn` finds a connector type (set by `lookup(project)`). */
export type DefLookup = ((id: string) => ComponentDef | undefined) & { conn?: (id: string) => ConnectorType | undefined }
const LABEL_CHAR = 0.4 // grid units per character of a pin label
const NAME_CHAR = 0.44
@ -70,8 +75,21 @@ const FACE_CHAR = 0.34
export interface ChipPins {
inputs: { key: string; label: string }[]
outputs: { key: string; label: string }[]
/** Connector ports, top to bottom: "in" ones sit with the inputs, "out" ones with the outputs. */
ports?: PortPin[]
}
export interface PortPin {
/** The port node's id inside the component. */
key: string
label: string
conn: string
side: 'in' | 'out'
}
/** What a pin plugs into: '' a single wire, 'bus' a cable end, 'c:<id>' a port of that connector type. */
export const pinKindOf = (p: { bus?: boolean; conn?: string }) => (p.conn ? `c:${p.conn}` : p.bus ? 'bus' : '')
/** Pin key of a panel row: the same key the row has as a switch in the simulator. */
export const rowPin = (panelId: string, rowId: string) => `${panelId}:${rowId}`
@ -106,9 +124,14 @@ export function chipPins(def: ComponentDef): ChipPins {
}
}
outputs.sort((a, b) => a.y - b.y || a.x - b.x)
const ports = def.nodes
.filter(n => (n.kind === 'portin' || n.kind === 'portout') && n.conn)
.sort((a, b) => a.y - b.y || a.x - b.x)
.map(n => ({ key: n.id, label: n.label?.trim() ?? '', conn: n.conn!, side: n.kind === 'portin' ? ('in' as const) : ('out' as const) }))
return {
inputs: inputs.map((p, i) => ({ key: p.key, label: p.label || `in${i + 1}` })),
outputs: outputs.map((p, i) => ({ key: p.key, label: p.label || `out${i + 1}` })),
...(ports.length ? { ports } : {}),
}
}
@ -317,7 +340,7 @@ function gateShape(symbol: SymbolKind, inputs: { key: string; label: string }[],
* anyway, and its drawings.
*/
function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeof faceLayout>, get: DefLookup): Shape {
const auto = boxShape(def.name, pins, face)
const auto = boxShape(def.name, pins, face, get)
const d = def.design!
const top = auto.body.y
const hide = new Set(d.hide ?? [])
@ -383,7 +406,13 @@ function designedShape(def: ComponentDef, pins: ChipPins, face: ReturnType<typeo
}
}
function boxShape(name: string, pins: ChipPins, face: ReturnType<typeof faceLayout>): Shape {
function boxShape(name: string, plain: ChipPins, face: ReturnType<typeof faceLayout>, get?: DefLookup): Shape {
// Ports sit below the single pins of their side, as one cable pin each.
const port = (side: 'in' | 'out') =>
(plain.ports ?? [])
.filter(p => p.side === side)
.map(p => ({ key: p.key, label: p.label || get?.conn?.(p.conn)?.name || 'port', bus: true, conn: p.conn }))
const pins = { inputs: [...plain.inputs, ...port('in')], outputs: [...plain.outputs, ...port('out')] }
const nIn = pins.inputs.length
const nOut = pins.outputs.length
const n = Math.max(nIn, nOut, 1)
@ -548,6 +577,39 @@ export function noteScale(node: CircuitNode): number {
return node.size === 'sm' ? 0.8 : node.size === 'lg' ? 1.5 : 1
}
/**
* The lines of a port, each with whether its signal comes into the circuit
* through this port (and so is an output pin of the port part) or leaves it
* (an input pin). An in port brings the forward lines in and sends the back
* lines out; an out port the other way round.
*/
export function portLines(node: CircuitNode, get: DefLookup): { name: string; enters: boolean; key: string }[] {
const type = node.conn ? get.conn?.(node.conn) : undefined
return (type?.lines ?? []).map((l, i) => ({ name: l.name, enters: (node.kind === 'portin') !== !!l.back, key: `l${i}` }))
}
/**
* A port inside a component: on its inner side, a pin per line (outputs for
* lines coming in, inputs for lines going out) and, at the top, a cable pin
* that passes the whole cable on to a part inside with the same port. An in
* port sits on the left of a circuit and faces right; an out port the reverse.
*/
function portShape(node: CircuitNode, get: DefLookup): Shape {
const lines = portLines(node, get)
// Wide enough for the longest line name, and for the title: "<type> in · <name>".
const title = `${(node.conn && get.conn?.(node.conn)?.name) || 'Port'} out${node.label?.trim() ? ` · ${node.label.trim()}` : ''}`
const w = Math.max(4, Math.ceil(lines.reduce((m, l) => Math.max(m, l.name.length), 0) * LABEL_CHAR + 2.6), Math.ceil(title.length * 0.42 + 1.2))
const inner = node.kind === 'portin' ? w : 0
const face: 1 | -1 = node.kind === 'portin' ? 1 : -1
const bus: PinInfo = { key: 'bus', label: '', dx: inner, dy: 0, bus: true, conn: node.conn }
const pins = lines.map((l, i) => ({ key: l.key, label: l.name, dx: inner, dy: i + 1, face }))
return {
body: { x: 0, y: -0.75, w, h: lines.length + 1.5 },
inputs: node.kind === 'portin' ? pins.filter((_, i) => !lines[i]!.enters) : [bus, ...pins.filter((_, i) => !lines[i]!.enters)],
outputs: node.kind === 'portin' ? [bus, ...pins.filter((_, i) => lines[i]!.enters)] : pins.filter((_, i) => lines[i]!.enters),
}
}
export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
switch (node.kind) {
case 'nand':
@ -589,17 +651,20 @@ export function shapeOf(node: CircuitNode, getDef: DefLookup): Shape {
const pins = chipPins(def)
const face = faceLayout(def)
if (def.design) return designedShape(def, pins, face, getDef)
if (def.symbol !== 'box' && !face.items.length && pins.outputs.length === 1 && pins.inputs.length >= 1 && pins.inputs.length <= 16) {
if (def.symbol !== 'box' && !face.items.length && !pins.ports && pins.outputs.length === 1 && pins.inputs.length >= 1 && pins.inputs.length <= 16) {
return gateShape(def.symbol, pins.inputs, pins.outputs[0]!)
}
return boxShape(def.name, pins, face)
return boxShape(def.name, pins, face, getDef)
}
case 'portin':
case 'portout':
return portShape(node, getDef)
}
}
export function pinPos(node: CircuitNode, shape: Shape, key: string, dir: 'in' | 'out') {
const pin = (dir === 'in' ? shape.inputs : shape.outputs).find(p => p.key === key)
return pin ? { x: node.x + pin.dx, y: node.y + pin.dy } : undefined
return pin ? { x: node.x + pin.dx, y: node.y + pin.dy, face: pin.face ?? (dir === 'in' ? -1 : 1) } : undefined
}
export type Pt = [number, number]
@ -626,7 +691,7 @@ export function simplify(pts: Pt[]): Pt[] {
* wires get one vertical segment halfway; backward wires (feedback loops) go
* out to the right, around, and back in from the left.
*/
export function routeWire(a: Pt, b: Pt, corners?: Pt[]): Pt[] {
export function routeWire(a: Pt, b: Pt, corners?: Pt[], aFace: 1 | -1 = 1, bFace: 1 | -1 = -1): Pt[] {
const [x1, y1] = a
const [x2, y2] = b
if (corners?.length) {
@ -641,6 +706,13 @@ export function routeWire(a: Pt, b: Pt, corners?: Pt[]): Pt[] {
out.push(b)
return simplify(out)
}
// Pins that face the other way (the inner pins of ports): out the side the
// source faces, in from the side the target faces.
if (aFace === -1 && bFace === 1) return routeWire([-x1, y1], [-x2, y2]).map(([x, y]) => [-x, y] as Pt)
if (aFace === bFace) {
const x = aFace === 1 ? Math.max(x1, x2) + 1 : Math.min(x1, x2) - 1
return simplify([a, [x, y1], [x, y2], b])
}
if (y1 === y2 && x2 > x1) return [a, b]
if (x2 >= x1 + 1) {
const m = Math.round((x1 + x2) / 2)

View File

@ -18,7 +18,10 @@ function clone<T>(value: T): T {
export function lookup(project: Project): DefLookup {
const map = new Map(project.components.map(d => [d.id, d]))
return id => map.get(id)
const conns = new Map((project.connectors ?? []).map(c => [c.id, c]))
const get: DefLookup = id => map.get(id)
get.conn = id => conns.get(id)
return get
}
export function createProject(opts: { examples: boolean; name?: string; campaign?: boolean }): Project {
@ -181,10 +184,16 @@ export function pruneWires(project: Project): boolean {
for (const def of project.components) {
const ins = new Set<string>()
const outs = new Set<string>()
// What each cable pin takes: a cable end, or a port of one connector type. Ends must match.
const kinds = new Map<string, string>()
for (const n of def.nodes) {
const pins = n.kind === 'chip' && n.chip && get(n.chip) ? chipPins(get(n.chip)!) : undefined
for (const k of inputKeys(n, pins)) ins.add(`${n.id}:${k}`)
for (const k of outputKeys(n, pins)) outs.add(`${n.id}:${k}`)
for (const k of inputKeys(n, pins, get)) ins.add(`${n.id}:${k}`)
for (const k of outputKeys(n, pins, get)) outs.add(`${n.id}:${k}`)
for (const p of pins?.ports ?? []) kinds.set(`${n.id}:${p.key}`, `c:${p.conn}`)
if ((n.kind === 'portin' || n.kind === 'portout') && n.conn) kinds.set(`${n.id}:bus`, `c:${n.conn}`)
if (n.kind === 'bundle') kinds.set(`${n.id}:q`, 'bus')
if (n.kind === 'split') kinds.set(`${n.id}:a`, 'bus')
}
const taken = new Set<string>()
const kept: Wire[] = []
@ -192,6 +201,10 @@ export function pruneWires(project: Project): boolean {
const w = def.wires[i]!
const to = `${w.to.node}:${w.to.pin}`
if (!ins.has(to) || !outs.has(`${w.from.node}:${w.from.pin}`) || taken.has(to)) continue
// A port only joins a port of the same connector type.
const ka = kinds.get(`${w.from.node}:${w.from.pin}`) ?? ''
const kb = kinds.get(to) ?? ''
if ((ka.startsWith('c:') || kb.startsWith('c:')) && ka !== kb) continue
taken.add(to)
kept.push(w)
}
@ -378,7 +391,7 @@ export const SINK_KINDS: NodeKind[] = ['output', 'lamp', 'hex']
export function pinKeys(node: CircuitNode, get: DefLookup): { ins: string[]; outs: string[] } {
const def = node.kind === 'chip' && node.chip ? get(node.chip) : undefined
const pins = def ? chipPins(def) : undefined
return { ins: inputKeys(node, pins), outs: outputKeys(node, pins) }
return { ins: inputKeys(node, pins, get), outs: outputKeys(node, pins, get) }
}
/**

View File

@ -24,6 +24,8 @@ export const KIND_NAMES: Partial<Record<NodeKind, string>> = {
bundle: 'Cable bundle',
split: 'Cable split',
pixel: 'Pixel',
portin: 'Connector in',
portout: 'Connector out',
tag: 'Send signal',
ref: 'Use signal',
}
@ -59,6 +61,8 @@ export const KIND_UNLOCK: Partial<Record<NodeKind, string>> = {
pixel: 'dec2',
bundle: 'add2',
split: 'add2',
portin: 'add2',
portout: 'add2',
button: 'sr',
clock: 'dlatch',
}

View File

@ -10,6 +10,7 @@ import {
WIRE_COLORS,
type CircuitNode,
type ComponentDef,
type ConnectorType,
type FaceDesign,
type PanelRow,
type Project,
@ -24,6 +25,7 @@ function cleanNode(n: CircuitNode) {
if (n.size !== undefined && !['sm', 'md', 'lg'].includes(n.size)) delete n.size
if (n.autoLabel !== undefined && n.autoLabel !== true) delete n.autoLabel
if (n.bits !== undefined && !(Number.isInteger(n.bits) && n.bits >= 2 && n.bits <= 32)) delete n.bits
if (n.conn !== undefined && !(typeof n.conn === 'string' && n.conn.length <= 32)) delete n.conn
if (n.attach !== undefined && typeof n.attach !== 'string') delete n.attach
if (n.skip !== undefined) {
if (Array.isArray(n.skip)) n.skip = n.skip.filter(k => typeof k === 'string').slice(0, MAX_ROWS)
@ -141,6 +143,7 @@ export function toProject(data: unknown): Project {
...(bestOf(p.best) ? { best: bestOf(p.best)! } : {}),
...(p.mode === 'campaign' || p.mode === 'challenges' ? { mode: p.mode } : {}),
...(puzzlesOf(p.puzzles) ? { puzzles: puzzlesOf(p.puzzles)! } : {}),
...(connectorsOf(p.connectors) ? { connectors: connectorsOf(p.connectors)! } : {}),
}
}
@ -152,6 +155,26 @@ function bestOf(raw: unknown): Record<string, number> | null {
return Object.keys(out).length ? out : null
}
/** Connector types of a project: names, colours and lines within bounds; broken ones are dropped. */
function connectorsOf(raw: unknown): ConnectorType[] | null {
if (!Array.isArray(raw)) return null
const out: ConnectorType[] = []
for (const c of raw.slice(0, 200) as Partial<ConnectorType>[]) {
if (!c || typeof c.id !== 'string' || !c.id || c.id.length > 32 || out.some(o => o.id === c.id) || !Array.isArray(c.lines)) continue
const lines = c.lines
.slice(0, 64)
.filter(l => l && typeof l.name === 'string')
.map(l => ({ name: l.name.trim().slice(0, 24) || 'line', ...(l.back === true ? { back: true } : {}) }))
out.push({
id: c.id,
name: typeof c.name === 'string' && c.name.trim() ? c.name.trim().slice(0, 40) : 'Connector',
...(c.color && WIRE_COLORS.includes(c.color) ? { color: c.color } : {}),
lines,
})
}
return out.length ? out : null
}
/** Puzzles kept in a project; broken ones are dropped. */
function puzzlesOf(raw: unknown): PuzzleSpec[] | null {
if (!Array.isArray(raw)) return null

View File

@ -19,6 +19,9 @@ export interface RouteInput {
a: Pt
b: Pt
pts?: Pt[]
/** Side the wire leaves the source (1 right, default) and arrives at the target from (-1 left, default). */
aFace?: 1 | -1
bFace?: 1 | -1
}
export interface Box {
@ -202,7 +205,12 @@ function* candidates(a: Pt, b: Pt): Generator<Pt[]> {
}
}
/** A wire to or from a pin facing the unusual way (the inner pins of ports). */
const reversed = (w: RouteInput) => w.aFace === -1 || w.bFace === 1
function autoRoute(input: RouteInput, occ: Occupancy, bodies: BodyIndex, pins: Set<number>): Pt[] {
// Wires to the inner pins of ports keep their simple shape.
if (reversed(input)) return routeWire(input.a, input.b, undefined, input.aFace, input.bFace)
const usual = routeWire(input.a, input.b)
const base = cost(usual, input.net, occ, bodies, pins)
if (base.penalty === 0) return usual
@ -426,7 +434,7 @@ function tidyRoutes(inputs: RouteInput[], boxes: Box[], occ: Occupancy, bodies:
// sorted together, so separate bundles can't end up crossing each other.
const gaps = new Map<number, { hi: number; nets: Map<string, TidyNet & { lo: number }> }>()
for (const w of inputs) {
if (grid.has(w.id)) continue
if (grid.has(w.id) || reversed(w)) continue
const [x1, y1] = w.a
const [x2, y2] = w.b
if (x2 < x1 + 2) continue // feedback wires keep the usual router
@ -538,7 +546,7 @@ export function circuitRoutes(def: ComponentDef, shapes: Map<string, Shape>, opt
const a = pinPos(fn, shapes.get(fn.id)!, w.from.pin, 'out')
const b = pinPos(tn, shapes.get(tn.id)!, w.to.pin, 'in')
if (!a || !b) continue
inputs.push({ id: w.id, net: `${w.from.node}:${w.from.pin}`, a: [a.x, a.y], b: [b.x, b.y], pts: w.pts })
inputs.push({ id: w.id, net: `${w.from.node}:${w.from.pin}`, a: [a.x, a.y], b: [b.x, b.y], pts: w.pts, ...(a.face === -1 ? { aFace: -1 as const } : {}), ...(b.face === 1 ? { bFace: 1 as const } : {}) })
}
return routeAll(inputs, bodies, pins, opts)
}

View File

@ -18,6 +18,8 @@ export type BuiltinKind =
| 'bundle' // gathers several wires into one cable
| 'split' // fans a cable out into its wires again
| 'pixel' // one square of a screen; inside a component, pixels form a screen on its box
| 'portin' // a connector socket of your own type (HDMI, RJ45, …) where a cable comes in; one port on the component's box
| 'portout' // the same, where a cable goes out
| 'tag' // gives the signal wired into it a name (its label)
| 'ref' // carries the signal of the tag with the same name in this circuit, without a wire
@ -48,6 +50,8 @@ export interface CircuitNode {
autoLabel?: boolean
/** Number of wires in the cable of a bundle or split. */
bits?: number
/** Port: the connector type (id in the project's connectors). */
conn?: string
/** Rows of a panel, top to bottom. */
rows?: PanelRow[]
/** Panel docked to a component: the id of that chip node. Its rows follow the chip's input pins. */
@ -218,6 +222,8 @@ export interface Project {
mode?: 'campaign' | 'challenges'
/** Puzzles opened from links or the weekly puzzle; their components carry `challenge: <puzzle id>`. */
puzzles?: PuzzleSpec[]
/** Connector types made in this project (HDMI, RJ45, your own buses): their lines and colour. */
connectors?: ConnectorType[]
}
/** A puzzle someone published: what to build, without their solution. */
@ -233,3 +239,22 @@ export interface PuzzleSpec {
/** Transistors in the author's own solution. */
author?: number
}
/**
* A connector type you define, like HDMI or RJ45: a set of lines that a
* single cable carries between an "out" port and an "in" port. Most lines
* run out → in; a line marked `back` runs the other way (acknowledge,
* hot-plug detect, the receive pair of a network cable).
*/
export interface ConnectorType {
id: string
name: string
color?: WireColor
lines: ConnectorLine[]
}
export interface ConnectorLine {
name: string
/** Runs from the in port back to the out port. */
back?: boolean
}

153
tests/connectors.test.ts Normal file
View File

@ -0,0 +1,153 @@
import { describe, expect, it } from 'vitest'
import { compile } from '../app/lib/logic/compile'
import { routeWire, shapeOf } from '../app/lib/logic/geometry'
import { createProject, lookup, pruneWires } from '../app/lib/logic/ops'
import { toProject } from '../app/lib/logic/project'
import { Simulator } from '../app/lib/logic/sim'
import type { ComponentDef, Project, Wire } from '../app/lib/logic/types'
const w = (id: string, from: [string, string], to: [string, string]): Wire => ({ id, from: { node: from[0], pin: from[1] }, to: { node: to[0], pin: to[1] } })
/**
* A made-up "Mini HDMI": two data lines out → in, and a hot-plug line back.
* Source sends A and B out through its out port and reports the hot-plug
* line as HPD; Sink shows the data as X and Y and drives hot-plug from H.
*/
function project(): Project {
const p = createProject({ examples: false })
p.connectors = [{ id: 'hdmi', name: 'Mini HDMI', color: 'blue', lines: [{ name: 'D0' }, { name: 'D1' }, { name: 'HPD', back: true }] }]
const source: ComponentDef = {
id: 'source',
name: 'Source',
symbol: 'box',
nodes: [
{ id: 'a', kind: 'input', x: 0, y: 0, label: 'A' },
{ id: 'b', kind: 'input', x: 0, y: 2, label: 'B' },
{ id: 'tx', kind: 'portout', conn: 'hdmi', x: 20, y: 0, label: 'OUT' },
{ id: 'hpd', kind: 'output', x: 10, y: 8, label: 'HPD' },
],
wires: [w('w1', ['a', 'q'], ['tx', 'l0']), w('w2', ['b', 'q'], ['tx', 'l1']), w('w3', ['tx', 'l2'], ['hpd', 'a'])],
}
const sink: ComponentDef = {
id: 'sink',
name: 'Sink',
symbol: 'box',
nodes: [
{ id: 'rx', kind: 'portin', conn: 'hdmi', x: 0, y: 0, label: 'IN' },
{ id: 'x', kind: 'output', x: 20, y: 0, label: 'X' },
{ id: 'y', kind: 'output', x: 20, y: 2, label: 'Y' },
{ id: 'h', kind: 'input', x: 10, y: 8, label: 'H' },
],
wires: [w('w1', ['rx', 'l0'], ['x', 'a']), w('w2', ['rx', 'l1'], ['y', 'a']), w('w3', ['h', 'q'], ['rx', 'l2'])],
}
const root: ComponentDef = {
id: 'root',
name: 'Root',
symbol: 'box',
nodes: [
{ id: 'sa', kind: 'input', x: 0, y: 0 },
{ id: 'sb', kind: 'input', x: 0, y: 2 },
{ id: 'sh', kind: 'input', x: 0, y: 8 },
{ id: 'src', kind: 'chip', chip: 'source', x: 6, y: 0 },
{ id: 'snk', kind: 'chip', chip: 'sink', x: 30, y: 0 },
],
wires: [
w('r1', ['sa', 'q'], ['src', 'a']),
w('r2', ['sb', 'q'], ['src', 'b']),
w('r3', ['sh', 'q'], ['snk', 'h']),
w('cable', ['src', 'tx'], ['snk', 'rx']),
],
}
p.components.push(source, sink, root)
return p
}
function run(p: Project, rootId: string, on: Record<string, boolean>) {
const s = new Simulator(compile(lookup(p), rootId))
for (const [k, v] of Object.entries(on)) s.setSource(k, v)
s.run()
return s
}
describe('connector ports', () => {
it('puts each port on the component box as one cable pin of its type', () => {
const p = project()
const get = lookup(p)
const src = shapeOf({ id: 'n', kind: 'chip', chip: 'source', x: 0, y: 0 }, get)
const port = src.outputs.find(o => o.key === 'tx')!
expect(port).toMatchObject({ bus: true, conn: 'hdmi', label: 'OUT' })
expect(src.inputs.map(i => i.key)).toEqual(['a', 'b'])
const snk = shapeOf({ id: 'n', kind: 'chip', chip: 'sink', x: 0, y: 0 }, get)
expect(snk.inputs.find(i => i.key === 'rx')).toMatchObject({ bus: true, conn: 'hdmi' })
})
it('a port part has a pin per line on its inner side, facing into the circuit', () => {
const get = lookup(project())
const out = shapeOf({ id: 'n', kind: 'portout', conn: 'hdmi', x: 0, y: 0 }, get)
expect(out.inputs.map(i => i.key)).toEqual(['bus', 'l0', 'l1'])
expect(out.outputs).toMatchObject([{ key: 'l2', face: -1, dx: 0 }])
const inn = shapeOf({ id: 'n', kind: 'portin', conn: 'hdmi', x: 0, y: 0 }, get)
expect(inn.outputs.map(o => o.key)).toEqual(['bus', 'l0', 'l1'])
expect(inn.inputs).toMatchObject([{ key: 'l2', face: 1 }])
})
it('one cable carries the forward lines one way and the back line the other', () => {
const p = project()
for (const [a, b, h] of [[0, 0, 0], [1, 0, 1], [0, 1, 0], [1, 1, 1]] as const) {
const s = run(p, 'root', { sa: !!a, sb: !!b, sh: !!h })
expect([s.pin('snk', 'x'), s.pin('snk', 'y'), s.pin('src', 'hpd')]).toEqual([a, b, h])
}
})
it('passes a port straight through a component that wraps another', () => {
const p = project()
// "Box" holds a Source and offers its port as its own.
p.components.push({
id: 'box',
name: 'Box',
symbol: 'box',
nodes: [
{ id: 'i', kind: 'input', x: 0, y: 0, label: 'I' },
{ id: 'inner', kind: 'chip', chip: 'source', x: 6, y: 0 },
{ id: 'p2', kind: 'portout', conn: 'hdmi', x: 30, y: 0 },
],
wires: [w('b1', ['i', 'q'], ['inner', 'a']), w('b2', ['inner', 'tx'], ['p2', 'bus'])],
})
const root = p.components.find(d => d.id === 'root')!
root.nodes.push({ id: 'bx', kind: 'chip', chip: 'box', x: 6, y: 20 }, { id: 'snk2', kind: 'chip', chip: 'sink', x: 30, y: 20 })
root.wires.push(w('r9', ['sa', 'q'], ['bx', 'i']), w('cable2', ['bx', 'p2'], ['snk2', 'rx']))
expect(run(p, 'root', { sa: true }).pin('snk2', 'x')).toBe(1)
expect(run(p, 'root', { sa: false }).pin('snk2', 'x')).toBe(0)
})
it('drops a cable between ports of different types, keeps the rest', () => {
const p = project()
p.connectors!.push({ id: 'rj45', name: 'RJ45', lines: [{ name: 'TX' }, { name: 'RX', back: true }] })
expect(pruneWires(p)).toBe(false)
p.components.find(d => d.id === 'sink')!.nodes.find(n => n.id === 'rx')!.conn = 'rj45'
expect(pruneWires(p)).toBe(true)
expect(p.components.find(d => d.id === 'root')!.wires.some(x => x.id === 'cable')).toBe(false)
expect(p.components.find(d => d.id === 'root')!.wires).toHaveLength(3)
})
it('keeps connector types through validation and cleans bad ones', () => {
const p = project()
const data = JSON.parse(JSON.stringify(p))
data.connectors.push({ id: 'x', name: 'Bad', color: 'chartreuse', lines: [{ name: 5 }, { name: 'OK', back: 'yes' }] }, { name: 'no id' })
const back = toProject(data)
expect(back.connectors).toEqual([
{ id: 'hdmi', name: 'Mini HDMI', color: 'blue', lines: [{ name: 'D0' }, { name: 'D1' }, { name: 'HPD', back: true }] },
{ id: 'x', name: 'Bad', lines: [{ name: 'OK' }] },
])
})
it('routes wires to pins facing the other way around the right side', () => {
// Out of a normal output, into an input that faces right (a back line of an in port).
expect(routeWire([10, 0], [2, 4], undefined, 1, 1)).toEqual([[10, 0], [11, 0], [11, 4], [2, 4]])
// Out of a pin facing left, into a normal input: mirrored usual route.
const r = routeWire([20, 0], [2, 4], undefined, -1, -1)
expect(r[0]).toEqual([20, 0])
expect(r.at(-1)).toEqual([2, 4])
expect(r[1]![0]).toBeLessThan(20)
})
})